gas/storage
storage/memory
import "github.com/gasmod/gas/storage/memory"Package memory is an object store held in the process’s memory, as a storage.Provider. It keeps the contract of the storage package, and so the rules of Amazon S3, without a server or a disk.
It suits tests and local development. The store is local to one process and lost when the process stops. Provider implements storage.Provider, gas.Service and gas.ReadyReporter.
In an app, the container builds the store from New and calls its Init. By hand, with a configuration given in code:
cfg := memory.DefaultConfig()cfg.Storage.Bucket = "photos"
store, err := memory.New(memory.WithConfig(cfg))(nil, logger)if err != nil { return err}if err := store.Init(ctx); err != nil { return err}defer store.Close(ctx)
_, err = store.PutObject(ctx, &storage.PutObjectInput{ Key: "cats/tom.txt", Body: strings.NewReader("Tom"),})info, err := store.HeadObject(ctx, &storage.HeadObjectInput{Key: "cats/tom.txt"})After this the bucket photos, which Init created, holds cats/tom.txt,
and:
- info.Size is 3.
- info.ContentType is
application/octet-stream. - info.ETag is the hex MD5 of
Tom.
Configuration
Section titled “Configuration”The settings live in the storage section, in Settings:
storage.bucket: the configured bucket, which an input with a nil Bucket names, and which Init creates when it does not exist. It keeps the bucket rules of the storage package. Default: none.storage.maxbytes: the most bytes the objects of the store hold, counting each object’s key, contents, header values and metadata names and values, at least MinMaxBytes (1 MiB). Default: DefaultMaxBytes (256 MiB).storage.maxobjects: the most objects the store holds, across its buckets, at least 1. Default: DefaultMaxObjects (100000).
The store holds at most MaxBuckets buckets (10000), which is not a setting.
Provider.Init resolves the configuration each time it runs:
- Without WithConfig, it binds DefaultConfig from the
gas.ConfigProvider, which checks the
validatetags. A nil ConfigProvider is the error storage.ErrNoConfigProvider. - With WithConfig, it takes a copy of the given Config, never changing the caller’s struct, and checks the same tags.
Then bucket, when set, must be a valid bucket name. A failure wraps
storage.ErrInvalidConfig and names the setting, never its value.
Provider.Config returns a copy of the configuration the last successful Init bound, defaults included: the zero Config before the first, and the last one bound after Close. A failed Init leaves it as it was, and changing the copy changes nothing in the store. It is safe to call at any time, while Init or Close runs included.
The buckets and their objects belong to the Provider, not to one Init. Close keeps them, and Init after Close finds them as Close left them.
These fail with ErrStorageFull and change nothing:
- a write that would take the store past
maxobjectsobjects ormaxbytesbytes; - a CreateBucket past MaxBuckets;
- an Init whose configured bucket would be one past MaxBuckets.
The store keeps no versions and no parts: a Version or a PartNumber is storage.ErrNotSupported.
Writes
Section titled “Writes”PutObject reads the body whole, outside the store’s lock. It then stores the object under the lock, where it evaluates the condition and the limits.
As it reads, it reserves room for each chunk of the body under the lock.
It fails with ErrStorageFull as soon as the objects stored and the
bodies every PutObject in flight has read so far would hold more than
maxbytes bytes, so that writes in flight cannot hold more memory than
the limit between them. A write that replaces an object thus needs room
for both until it is stored.
The store keeps a copy of the body as long as the body, so it holds the bytes it counts. The ETag is the hex MD5 of the contents.
CopyObject looks up the source, then the destination’s bucket, and
stores the copy, all under the store’s lock. So it sees the source as
one write stored it, and stores the copy whole. The copy shares the
source’s contents, which no write changes, but counts toward maxbytes
and maxobjects as an object of its own. A copy past them fails with
ErrStorageFull and writes nothing.
HeadObject and GetObject of an object in a missing bucket are storage.ErrObjectNotFound and storage.ErrBucketNotFound. HeadBucket returns the name, and the region is always empty.
GetObject’s Body is also an io.Seeker over the bytes selected. It shares the stored bytes, which no write changes, so it stays readable:
- after Close;
- after the object is replaced or deleted;
- after Body is closed. Its Close does nothing.
The metadata a call returns is a copy.
Listing
Section titled “Listing”A continuation token holds its listing’s last entry sealed with a key that Init draws at random, so a token from before a restart is storage.ErrInvalidToken.
A page of ListObjects sorts the keys of the bucket that start with Prefix, so it costs as much as the bucket holds under Prefix.
Lifecycle
Section titled “Lifecycle”A successful Init logs service initialized at info level, with
bucket, whether a bucket is configured, max_bytes and
max_objects. It never logs the bucket’s name.
Provider.Close makes the store closed, waits for the calls in flight,
such as a PutObject that reads its body, and logs service closed at
info level. When its context ends first, it cancels them, logs
service closed, calls in flight canceled at warn level, and returns
an error wrapping the context’s error. Close on a store that is not
initialized, or on a nil Provider, returns nil and logs nothing.
New’s constructor fails with:
- storage.ErrNilLogger for a nil logger;
- storage.ErrNilOption for a nil option, naming its position;
- storage.ErrNilConfig for WithConfig(nil).
A nil ConfigProvider is accepted, and Init then requires WithConfig.
Readiness
Section titled “Readiness”Provider.CheckReady does no I/O: it fails only when the store is not initialized or its context has ended.
Concurrency
Section titled “Concurrency”A Provider is safe for concurrent use. Init and Close run one at a time. One mutex guards the buckets and objects. A call holds it while it works, which is short and does no I/O, and PutObject does not hold it while it reads a body.
Errors
Section titled “Errors”The sentinel error of this package, to be tested with errors.Is:
- ErrStorageFull: a write would take the store past
maxobjectsormaxbytes, or CreateBucket found MaxBuckets buckets.
The other errors wrap a sentinel of the storage package, as the storage
package describes. Every error starts with ServiceName and the
operation. A configuration that fails its tags gets the validator’s
error after gas/storage/memory: init: invalid config: validate config: .
The other errors, as returned, with put object and get object
standing for each operation that can fail the same way, copy object
included:
gas/storage/memory: logger is nilgas/storage/memory: option is nil: at position 0gas/storage/memory: config is nilgas/storage/memory: init: no config providergas/storage/memory: init: invalid config: Storage.Bucket must be a valid bucket namegas/storage/memory: init: service already initializedgas/storage/memory: init: context canceledgas/storage/memory: ready: service not initializedgas/storage/memory: put object: input is nilgas/storage/memory: put object: service not initializedgas/storage/memory: put object: service closedgas/storage/memory: put object: context canceledgas/storage/memory: put object: invalid key: emptygas/storage/memory: put object: bucket not foundgas/storage/memory: put object: precondition failedgas/storage/memory: put object: object not foundgas/storage/memory: put object: storage fullgas/storage/memory: copy object: source: invalid key: emptygas/storage/memory: copy object: invalid argument: copies an object onto itself without Replacegas/storage/memory: create bucket: storage fullgas/storage/memory: get object: object not foundgas/storage/memory: get object: object not found: bucket not foundgas/storage/memory: get object: not supported: the store keeps no versionsgas/storage/memory: get object: not supported: the store keeps no partsgas/storage/memory: get object: range not satisfiablegas/storage/memory: delete bucket: bucket not emptygas/storage/memory: list objects: invalid continuation token: not one this backend issued for this listinggas/storage/memory: close: context deadline exceededAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( // DefaultMaxBytes is the most bytes the store holds in DefaultConfig: // 256 MiB. DefaultMaxBytes = 256 << 20 // MinMaxBytes is the least the MaxBytes setting allows: 1 MiB. MinMaxBytes = 1 << 20 // DefaultMaxObjects is the most objects the store holds in // DefaultConfig. DefaultMaxObjects = 100000 // MaxBuckets is the most buckets the store holds. MaxBuckets = 10000)const ServiceName = "gas/storage/memory"ServiceName is the name of the memory store, returned by Provider.Name and prefixed to every error the store returns.
Variables
Section titled “Variables”var ErrStorageFull = errors.New("storage full")ErrStorageFull indicates that a write would take the store past MaxBytes or MaxObjects, or that CreateBucket found MaxBuckets buckets.
func New
Section titled “func New”func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Provider, error)New returns the constructor of a Provider with opts applied, in the shape the gas container expects. The constructor returns an error wrapping storage.ErrNilLogger for a nil logger, storage.ErrNilOption for a nil option, and storage.ErrNilConfig for WithConfig(nil); a nil ConfigProvider is accepted, and Init then requires WithConfig.
type Config
Section titled “type Config”type Config struct { // Storage holds the settings. Storage Settings}Config holds the memory store’s configuration, read from the storage
section.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns the configuration a store starts from before binding: no configured bucket, DefaultMaxBytes and DefaultMaxObjects.
type Option
Section titled “type Option”type Option func(*Provider)Option configures a Provider. Options only record what they are given; the constructor and Init check it.
func WithConfig
Section titled “func WithConfig”func WithConfig(cfg *Config) OptionWithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init copies *cfg each time it runs and never changes it; the copy is checked against its validate tags as a bound configuration is. A nil cfg makes the constructor fail with storage.ErrNilConfig.
Default: bind the storage section from the ConfigProvider over
DefaultConfig.
type Provider
Section titled “type Provider”type Provider struct { // contains filtered or unexported fields}Provider is an object store held in the process’s memory, as described in the package documentation. It is safe for concurrent use.
func (*Provider) CheckReady
Section titled “func (*Provider) CheckReady”func (p *Provider) CheckReady(ctx context.Context) errorCheckReady reports readiness without I/O: an error wrapping storage.ErrNotInitialized or storage.ErrClosed when the store is not initialized, the context’s error when ctx has ended, and else nil.
func (*Provider) Close
Section titled “func (*Provider) Close”func (p *Provider) Close(ctx context.Context) errorClose makes every later call but Init return an error wrapping storage.ErrClosed, and waits for every call in flight to return, as described in the package documentation. When ctx ends first, it cancels the calls in flight, which return storage.ErrClosed, and returns an error wrapping ctx’s error. The buckets and objects stay. Close on a store that is not initialized returns nil and logs nothing.
func (*Provider) Config
Section titled “func (*Provider) Config”func (p *Provider) Config() ConfigConfig returns a copy of the configuration the last successful Init bound, defaults included, as described in the package documentation: the zero Config before the first successful Init, and on a nil Provider, and the last one bound after Close. Changing it changes nothing in the store. It is safe to call at any time, while Init or Close runs included.
func (*Provider) CopyObject
Section titled “func (*Provider) CopyObject”func (p *Provider) CopyObject( ctx context.Context, in *storage.CopyObjectInput,) (*storage.CopyObjectOutput, error)CopyObject copies the object in names, as described in the package documentation: under the store’s lock, it looks up the source and the destination’s bucket, and stores the copy when the limits allow it. The copy shares the source’s contents, which no write changes, but counts toward MaxBytes as an object of its own.
func (*Provider) CreateBucket
Section titled “func (*Provider) CreateBucket”func (p *Provider) CreateBucket(ctx context.Context, in *storage.CreateBucketInput) errorCreateBucket creates the bucket in.Bucket, as described in the package documentation. Creating one that exists is not an error; creating one past MaxBuckets is an error wrapping ErrStorageFull.
func (*Provider) DeleteBucket
Section titled “func (*Provider) DeleteBucket”func (p *Provider) DeleteBucket(ctx context.Context, in *storage.DeleteBucketInput) errorDeleteBucket deletes the bucket in.Bucket when it holds no object, as described in the package documentation.
func (*Provider) DeleteObject
Section titled “func (*Provider) DeleteObject”func (p *Provider) DeleteObject(ctx context.Context, in *storage.DeleteObjectInput) errorDeleteObject deletes the object in, as described in the package documentation. Deleting a key that holds no object is not an error.
func (*Provider) GetObject
Section titled “func (*Provider) GetObject”func (p *Provider) GetObject( ctx context.Context, in *storage.GetObjectInput,) (*storage.Object, error)GetObject returns the object in, as described in the package documentation. Its Body is also an io.Seeker over the bytes selected, and stays readable after Close.
func (*Provider) HeadBucket
Section titled “func (*Provider) HeadBucket”func (p *Provider) HeadBucket( ctx context.Context, in *storage.HeadBucketInput,) (*storage.Bucket, error)HeadBucket returns the bucket in.Bucket, with its name only, or an error wrapping storage.ErrBucketNotFound.
func (*Provider) HeadObject
Section titled “func (*Provider) HeadObject”func (p *Provider) HeadObject( ctx context.Context, in *storage.HeadObjectInput,) (*storage.ObjectInfo, error)HeadObject describes the object in, as described in the package documentation.
func (*Provider) Init
Section titled “func (*Provider) Init”func (p *Provider) Init(ctx context.Context) errorInit resolves the configuration, opens the store and creates the configured bucket, as described in the package documentation. On an initialized store it returns storage.ErrAlreadyInitialized and changes nothing.
func (*Provider) ListBuckets
Section titled “func (*Provider) ListBuckets”func (p *Provider) ListBuckets( ctx context.Context, in *storage.ListBucketsInput,) (*storage.ListBucketsOutput, error)ListBuckets returns one page of the buckets, as described in the package documentation.
func (*Provider) ListObjects
Section titled “func (*Provider) ListObjects”func (p *Provider) ListObjects( ctx context.Context, in *storage.ListObjectsInput,) (*storage.ListObjectsOutput, error)ListObjects returns one page of the objects of a bucket, as described in the package documentation.
func (*Provider) Name
Section titled “func (*Provider) Name”func (*Provider) Name() stringName returns ServiceName.
func (*Provider) PutObject
Section titled “func (*Provider) PutObject”func (p *Provider) PutObject( ctx context.Context, in *storage.PutObjectInput,) (*storage.PutObjectOutput, error)PutObject stores the object in, as described in the package documentation, once its body is read whole and its condition holds.
type Settings
Section titled “type Settings”type Settings struct { // Bucket is the configured bucket, which an input with a nil Bucket // names; empty is none. Bucket string // MaxBytes is the most bytes the objects of the store hold, at least // MinMaxBytes. MaxBytes int64 `validate:"min=1048576"` // MaxObjects is the most objects the store holds, at least 1. MaxObjects int `validate:"min=1"`}Settings are the memory store’s settings, as described in the package documentation.