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

# cache/memory

> Package memory is a cache held in the process's memory, as a gas.CacheProvider.

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

```go
import "github.com/gasmod/gas/cache/memory"
```

Package memory is a cache held in the process's memory, as a
gas.CacheProvider. It is local to one process and lost when the process
stops, so it suits development, tests and single-instance apps.

[Service](#Service) implements gas.Service and gas.CacheProvider, and keeps the
contract of the cache package.

## 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.Cache.MaxEntries = 10000

c, err := memory.New(memory.WithConfig(cfg))(nil, logger)
if err != nil {
	return err
}
if err := c.Init(ctx); err != nil {
	return err
}
defer c.Close(ctx)

err = c.Set(ctx, "greeting", []byte("hello"), time.Minute)
```

After this c.Get(ctx, "greeting") returns `hello` for a minute, and
c.Len() is 1.

## Configuration

The settings live in the `cache` section, in [Settings](#Settings):

- `cache.maxentries`: the most entries the store holds, 0 or more; 0
is no limit. Default: [DefaultMaxEntries](#DefaultMaxEntries), no limit.
- `cache.cleanupinterval`: how often the janitor removes expired
entries, at least [MinCleanupInterval](#MinCleanupInterval) (1s). Default:
[DefaultCleanupInterval](#DefaultCleanupInterval) (1m).
- `cache.defaultttl`: the TTL of a Set with a zero TTL, 0 or more; 0
is no expiry. Default: [DefaultTTL](#DefaultTTL), no expiry.

With the defaults the store has no limit: entries without a TTL stay
until deleted, and the store grows with the keys it is given. Set
MaxEntries, DefaultTTL, or both, for keys that come from requests.

[Service.Init](#Service.Init) resolves the configuration each time it runs, in one of
two ways:

- Without [WithConfig](#WithConfig), it binds [DefaultConfig](#DefaultConfig) from the
gas.ConfigProvider, which checks the `validate` tags. A nil
ConfigProvider is the error cache.ErrNoConfigProvider.
- With WithConfig, it takes a copy of the given Config, never changing
the caller's struct, and checks the same tags. A nil Config is the
error cache.ErrNilConfig.

A failure wraps cache.ErrInvalidConfig. The resolved configuration
belongs to the entries Init opens, so a restart with another
configuration is safe while calls run.

[Service.Config](#Service.Config) returns a copy of the configuration the last successful
Init resolved, defaults included, or the zero Config before one. A
failed Init and Close leave it as it was.

## Eviction

The store keeps its entries in order of use. Get and Set make an entry
the most recently used; Exists and Delete do not.

When MaxEntries is set and a Set adds a new key to a full store, the
store first removes one entry:

- the one that expired first, if any has expired;
- else the least recently used.

Replacing a key's value never evicts. A full store never refuses a Set.

## Expiry

A TTL is counted from the Set, on the monotonic clock, so a change of
the wall clock does not move it. Expired entries are removed in two
ways:

- Get and Exists treat an expired entry as a miss and remove it.
- The janitor, a goroutine that each Init starts, removes every
expired entry each `cleanupinterval`, holding the store's lock while
it does.

An expired entry that nothing reads is held until the next sweep, or
until eviction picks it, as under Eviction. [Service.Len](#Service.Len) counts it
until then.

## Lifecycle

A successful Init opens an empty store, starts the janitor and logs
`service initialized` at info level, with `max_entries`,
`cleanup_interval` and `default_ttl`. Init on an initialized store
returns cache.ErrAlreadyInitialized and changes nothing.

[Service.Close](#Service.Close) runs these steps, in order:

1. It drops every entry.
2. It stops the janitor, and waits for it to return.
3. It logs `service closed` at info level.

Close on a store that is not initialized returns nil and logs nothing.
Close ignores its context. Init after Close starts again with an empty
store and a configuration resolved afresh.

Outside a successful Init, every method but Init, Close, Name, Len and
Config returns an error wrapping:

- cache.ErrNotInitialized, before the first successful Init.
- cache.ErrClosed, after Close, until Init succeeds.

Len returns 0 then.

[New](#New)'s constructor fails with cache.ErrNilLogger for a nil logger. A
nil ConfigProvider is accepted, and Init then requires WithConfig.

## Context

The store does no I/O, so a call never waits: each method returns the
context's error when the context has ended before the call, and runs to
the end otherwise.

## Concurrency

A Service is safe for concurrent use. One mutex guards the entries and
the state:

- Each call holds it for the whole call, which is short and does no
I/O.
- The janitor holds it for each sweep.
- Close releases it before waiting for the janitor.

A call that runs beside Close either completes before it or returns
cache.ErrClosed.

## Errors

Every error starts with [ServiceName](#ServiceName) and the operation, and wraps a
sentinel of the cache package, as the cache package describes.

A configuration that fails its tags gets the validator's error after
`gas/cache/memory: init: invalid config: validate config: `, such as:

```go
Key: 'Config.Cache.CleanupInterval' Error:Field validation for 'CleanupInterval' failed on the 'min' tag
```

The other errors, as returned, with `get` standing for each operation
that can fail the same way:

```go
gas/cache/memory: logger is nil
gas/cache/memory: init: config is nil
gas/cache/memory: init: no config provider
gas/cache/memory: init: service already initialized
gas/cache/memory: init: context canceled
gas/cache/memory: get: invalid key: empty
gas/cache/memory: get: key not found
gas/cache/memory: get: service not initialized
gas/cache/memory: get: service closed
gas/cache/memory: get: context canceled
gas/cache/memory: set: invalid TTL: negative
```


## API reference

### Constants

<a id="DefaultMaxEntries"></a><a id="DefaultCleanupInterval"></a><a id="DefaultTTL"></a><a id="MinCleanupInterval"></a>

```go
const (
	// DefaultMaxEntries is the entry limit of DefaultConfig: none.
	DefaultMaxEntries = 0
	// DefaultCleanupInterval is the janitor's interval of DefaultConfig.
	DefaultCleanupInterval = time.Minute
	// DefaultTTL is the TTL of DefaultConfig for a Set with a zero TTL:
	// no expiry.
	DefaultTTL time.Duration = 0
	// MinCleanupInterval is the shortest CleanupInterval.
	MinCleanupInterval = time.Second
)
```

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

```go
const ServiceName = "gas/cache/memory"
```

ServiceName is the name of the memory store, returned by Service.Name
and prefixed to every error the store returns.

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

#### func New

```go
func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Service, error)
```

New returns the constructor of a Service with opts applied, in the shape
the gas container expects. The constructor returns an error wrapping
cache.ErrNilLogger for a nil logger; a nil ConfigProvider is accepted,
and Init then requires WithConfig.

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

### type Config

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

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

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

#### func DefaultConfig

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

DefaultConfig returns the configuration a store starts from before
binding: DefaultMaxEntries, DefaultCleanupInterval and DefaultTTL.

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

### type Option

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

Option configures a Service. Options only record what they are given;
Init checks 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 Init fail with
cache.ErrNilConfig.

Default: bind the `cache` section from the ConfigProvider over
DefaultConfig.

<a id="Service"></a>

### type Service

```go
type Service struct {
	// contains filtered or unexported fields
}
```

Service is a cache held in the process's memory, as described in the
package documentation. It is safe for concurrent use.

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

#### func (*Service) Close

```go
func (s *Service) Close(context.Context) error
```

Close drops every entry, stops the janitor and waits for it to return.
Every later call but Init returns an error wrapping cache.ErrClosed.
Close on a store that is not initialized returns nil and logs nothing.
It ignores its context.

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

#### func (*Service) Config

```go
func (s *Service) Config() Config
```

Config returns a copy of the configuration the last successful Init
resolved, defaults included, or the zero Config before one. A failed
Init and Close leave it as it was. Config holds no slice, map or
pointer, so the copy shares nothing with the store.

<a id="Service.Delete"></a>

#### func (*Service) Delete

```go
func (s *Service) Delete(ctx context.Context, key string) error
```

Delete removes the value of key. Deleting a key the store does not hold
is not an error.

<a id="Service.Exists"></a>

#### func (*Service) Exists

```go
func (s *Service) Exists(ctx context.Context, key string) (bool, error)
```

Exists reports whether the store holds a live value under key. It does
not make the entry the most recently used.

<a id="Service.Get"></a>

#### func (*Service) Get

```go
func (s *Service) Get(ctx context.Context, key string) ([]byte, error)
```

Get returns a copy of the value of key, or an error wrapping
cache.ErrKeyNotFound when the store holds no live value under it. A hit
makes the entry the most recently used.

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

#### func (*Service) Init

```go
func (s *Service) Init(ctx context.Context) error
```

Init resolves the configuration, opens an empty cache and starts the
janitor, as described in the package documentation. On an initialized
store it returns cache.ErrAlreadyInitialized and changes nothing.

<a id="Service.Len"></a>

#### func (*Service) Len

```go
func (s *Service) Len() int
```

Len returns the number of entries the store holds, counting those that
have expired and that neither a call nor the janitor has removed yet.
It is 0 when the store is not initialized.

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

#### func (*Service) Name

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

Name returns ServiceName.

<a id="Service.Set"></a>

#### func (*Service) Set

```go
func (s *Service) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
```

Set stores a copy of value under key, as the most recently used entry,
expiring as ttl says, as described in the package documentation. A nil
value is stored as empty. A new key on a full store evicts one entry
first.

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

### type Settings

```go
type Settings struct {
	// MaxEntries is the most entries the store holds; 0 is no limit.
	MaxEntries int `validate:"min=0"`
	// CleanupInterval is how often the janitor removes expired entries,
	// at least MinCleanupInterval.
	CleanupInterval time.Duration `validate:"min=1s"`
	// DefaultTTL is the TTL of a Set with a zero TTL; 0 is no expiry.
	DefaultTTL time.Duration `validate:"min=0"`
}
```

Settings are the memory store's settings, as described in the package
documentation.
