github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/state/bakerystorage/interface.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  // Package bakerystorage provides an implementation
     5  // of the bakery Storage interface that uses MongoDB
     6  // to store items.
     7  //
     8  // This is based on gopkg.in/macaroon-bakery.v2/bakery/mgostorage.
     9  package bakerystorage
    10  
    11  import (
    12  	"time"
    13  
    14  	"github.com/juju/errors"
    15  	"gopkg.in/macaroon-bakery.v2-unstable/bakery"
    16  	"gopkg.in/macaroon-bakery.v2-unstable/bakery/mgostorage"
    17  
    18  	"github.com/juju/juju/mongo"
    19  )
    20  
    21  // Config contains configuration for creating bakery storage with New.
    22  type Config struct {
    23  	// GetCollection returns a mongo.Collection and a function that
    24  	// will close any associated resources.
    25  	GetCollection func() (collection mongo.Collection, closer func())
    26  
    27  	// GetStorage returns a bakery.Storage and a function that will close
    28  	// any associated resources.
    29  	GetStorage func(rootKeys *mgostorage.RootKeys, coll mongo.Collection, expireAfter time.Duration) (storage bakery.Storage)
    30  }
    31  
    32  // Validate validates the configuration.
    33  func (c Config) Validate() error {
    34  	if c.GetCollection == nil {
    35  		return errors.NotValidf("nil GetCollection")
    36  	}
    37  	if c.GetStorage == nil {
    38  		return errors.NotValidf("nil GetStorage")
    39  	}
    40  	return nil
    41  }
    42  
    43  // ExpirableStorage extends bakery.Storage with the ExpireAfter method,
    44  // to expire data added at the specified time.
    45  type ExpirableStorage interface {
    46  	bakery.Storage
    47  
    48  	// ExpireAfter returns a new ExpirableStorage that will expire
    49  	// added items after the specified duration.
    50  	ExpireAfter(time.Duration) ExpirableStorage
    51  }
    52  
    53  // New returns an implementation of bakery.Storage
    54  // that stores all items in MongoDB with an expiry
    55  // time.
    56  func New(config Config) (ExpirableStorage, error) {
    57  	if err := config.Validate(); err != nil {
    58  		return nil, errors.Annotate(err, "validating config")
    59  	}
    60  	return &storage{
    61  		config:   config,
    62  		rootKeys: mgostorage.NewRootKeys(5),
    63  	}, nil
    64  }