## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# storage/memory

> Package memory is an object store held in the process's memory, as a storage.Provider.

The Markdown of https://gasmod.dev/reference/storage/memory/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
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](#Provider) implements storage.Provider,
gas.Service and gas.ReadyReporter.

## Usage

In an app, the container builds the store from [New](#New) and calls its
Init. By hand, with a configuration given in code:

```go
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

The settings live in the `storage` section, in [Settings](#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](#MinMaxBytes) (1 MiB). Default:
[DefaultMaxBytes](#DefaultMaxBytes) (256 MiB).
- `storage.maxobjects`: the most objects the store holds, across its
buckets, at least 1. Default: [DefaultMaxObjects](#DefaultMaxObjects) (100000).

The store holds at most [MaxBuckets](#MaxBuckets) buckets (10000), which is not a
setting.

[Provider.Init](#Provider.Init) resolves the configuration each time it runs:

- Without [WithConfig](#WithConfig), it binds [DefaultConfig](#DefaultConfig) from the
gas.ConfigProvider, which checks the `validate` tags. 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](#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.

## Store

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](#ErrStorageFull) and change nothing:

- a write that would take the store past `maxobjects` objects or
`maxbytes` bytes;
- 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

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](#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.

## Reads

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

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

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](#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](#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

[Provider.CheckReady](#Provider.CheckReady) does no I/O: it fails only when the store is not
initialized or its context has ended.

## 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

The sentinel error of this package, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrStorageFull](#ErrStorageFull): a write would take the store past `maxobjects` or
`maxbytes`, 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](#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:

```go
gas/storage/memory: logger is nil
gas/storage/memory: option is nil: at position 0
gas/storage/memory: config is nil
gas/storage/memory: init: no config provider
gas/storage/memory: init: invalid config: Storage.Bucket must be a valid bucket name
gas/storage/memory: init: service already initialized
gas/storage/memory: init: context canceled
gas/storage/memory: ready: service not initialized
gas/storage/memory: put object: input is nil
gas/storage/memory: put object: service not initialized
gas/storage/memory: put object: service closed
gas/storage/memory: put object: context canceled
gas/storage/memory: put object: invalid key: empty
gas/storage/memory: put object: bucket not found
gas/storage/memory: put object: precondition failed
gas/storage/memory: put object: object not found
gas/storage/memory: put object: storage full
gas/storage/memory: copy object: source: invalid key: empty
gas/storage/memory: copy object: invalid argument: copies an object onto itself without Replace
gas/storage/memory: create bucket: storage full
gas/storage/memory: get object: object not found
gas/storage/memory: get object: object not found: bucket not found
gas/storage/memory: get object: not supported: the store keeps no versions
gas/storage/memory: get object: not supported: the store keeps no parts
gas/storage/memory: get object: range not satisfiable
gas/storage/memory: delete bucket: bucket not empty
gas/storage/memory: list objects: invalid continuation token: not one this backend issued for this listing
gas/storage/memory: close: context deadline exceeded
```


## API reference

### Constants

<a id="DefaultMaxBytes"></a><a id="MinMaxBytes"></a><a id="DefaultMaxObjects"></a><a id="MaxBuckets"></a>

```go
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
)
```

<a id="ServiceName"></a>

```go
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

<a id="ErrStorageFull"></a>

```go
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.

<a id="New"></a>

#### func New

```go
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.

<a id="Config"></a>

### type Config

```go
type Config struct {
	// Storage holds the settings.
	Storage Settings
}
```

Config holds the memory store's configuration, read from the `storage`
section.

<a id="DefaultConfig"></a>

#### func DefaultConfig

```go
func DefaultConfig() *Config
```

DefaultConfig returns the configuration a store starts from before
binding: no configured bucket, DefaultMaxBytes and DefaultMaxObjects.

<a id="Option"></a>

### type Option

```go
type Option func(*Provider)
```

Option configures a Provider. Options only record what they are given;
the constructor and Init check it.

<a id="WithConfig"></a>

#### func WithConfig

```go
func WithConfig(cfg *Config) Option
```

WithConfig 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.

<a id="Provider"></a>

### type Provider

```go
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.

<a id="Provider.CheckReady"></a>

#### func (*Provider) CheckReady

```go
func (p *Provider) CheckReady(ctx context.Context) error
```

CheckReady 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.

<a id="Provider.Close"></a>

#### func (*Provider) Close

```go
func (p *Provider) Close(ctx context.Context) error
```

Close 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.

<a id="Provider.Config"></a>

#### func (*Provider) Config

```go
func (p *Provider) Config() Config
```

Config 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.

<a id="Provider.CopyObject"></a>

#### func (*Provider) CopyObject

```go
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.

<a id="Provider.CreateBucket"></a>

#### func (*Provider) CreateBucket

```go
func (p *Provider) CreateBucket(ctx context.Context, in *storage.CreateBucketInput) error
```

CreateBucket 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.

<a id="Provider.DeleteBucket"></a>

#### func (*Provider) DeleteBucket

```go
func (p *Provider) DeleteBucket(ctx context.Context, in *storage.DeleteBucketInput) error
```

DeleteBucket deletes the bucket in.Bucket when it holds no object, as
described in the package documentation.

<a id="Provider.DeleteObject"></a>

#### func (*Provider) DeleteObject

```go
func (p *Provider) DeleteObject(ctx context.Context, in *storage.DeleteObjectInput) error
```

DeleteObject deletes the object in, as described in the package
documentation. Deleting a key that holds no object is not an error.

<a id="Provider.GetObject"></a>

#### func (*Provider) GetObject

```go
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.

<a id="Provider.HeadBucket"></a>

#### func (*Provider) HeadBucket

```go
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.

<a id="Provider.HeadObject"></a>

#### func (*Provider) HeadObject

```go
func (p *Provider) HeadObject(
	ctx context.Context,
	in *storage.HeadObjectInput,
) (*storage.ObjectInfo, error)
```

HeadObject describes the object in, as described in the package
documentation.

<a id="Provider.Init"></a>

#### func (*Provider) Init

```go
func (p *Provider) Init(ctx context.Context) error
```

Init 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.

<a id="Provider.ListBuckets"></a>

#### func (*Provider) ListBuckets

```go
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.

<a id="Provider.ListObjects"></a>

#### func (*Provider) ListObjects

```go
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.

<a id="Provider.Name"></a>

#### func (*Provider) Name

```go
func (*Provider) Name() string
```

Name returns ServiceName.

<a id="Provider.PutObject"></a>

#### func (*Provider) PutObject

```go
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.

<a id="Settings"></a>

### type Settings

```go
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.
