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

> Package cache defines what every cache store of the module promises: the keys it accepts, how it copies values, how a TTL works, how it honors a context, its lifecycle, and the errors it returns.

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

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

Package cache defines what every cache store of the module promises:
the keys it accepts, how it copies values, how a TTL works, how it
honors a context, its lifecycle, and the errors it returns.

The stores implement gas.CacheProvider and gas.Service, and each lives
in its own package:

- gas/cache/memory: a map in the process's memory, with an entry
limit and least-recently-used eviction.
- gas/cache/valkey: a Valkey server, or any server that speaks its
protocol, such as Redis.
- gas/cache/cachetest: a mock for tests.

## Usage

Each store's New returns a constructor in the shape the gas container
expects, so a store is registered as gas.CacheProvider:

```go
gas.WithSingletonService[gas.CacheProvider](memory.New())
```

A handler then reads through the cache:

```go
b, err := c.Get(ctx, "user:42")
if errors.Is(err, cache.ErrKeyNotFound) {
	b = loadUser(ctx, 42)
	err = c.Set(ctx, "user:42", b, 5*time.Minute)
}
if err != nil {
	return err
}
```

After this the cache holds `user:42` for five minutes, unless a store
evicts it first.

## Contract

Every store, and any gas.CacheProvider that wants to be one, keeps the
rules of the sections Keys and values, TTL, Context and Lifecycle. The
module's conformance tests run every store through these rules, with
identical expectations.

A method checks its arguments first, the key and then the TTL, then the
store's state, then the context, and returns the first failure.

## Keys and values

The methods read, write and remove values by key:

- Get returns the value of a key, or an error wrapping
[ErrKeyNotFound](#ErrKeyNotFound) when the store holds no live value under it.
- Exists reports whether Get would find one.
- Delete removes a key. Deleting a key the store does not hold is not
an error.

A key is any non-empty string, of any bytes; keys are compared byte for
byte. The empty key is [ErrInvalidKey](#ErrInvalidKey), from every method, as
[CheckKey](#CheckKey) reports it.

Values are bytes and are copied: Set keeps a copy of what it is given,
and Get returns a copy of what the store keeps, so the caller may change
either slice afterwards. A nil value is stored as empty, and Get returns
an empty value as an empty, non-nil slice.

## TTL

Set replaces the value of a key and its TTL. The TTL works like this:

- A TTL above zero makes the value expire once that time has passed,
rounded up to a whole millisecond, so `500µs` lives a millisecond,
as Valkey counts TTLs. [EffectiveTTL](#EffectiveTTL) computes the rounded TTL.
- A TTL of zero takes the store's DefaultTTL setting, where zero means
no expiry.
- A negative TTL is [ErrInvalidTTL](#ErrInvalidTTL), as [CheckTTL](#CheckTTL) reports it, and
stores nothing.

A TTL within a millisecond of the largest time.Duration is rounded down
to a whole millisecond instead, since rounding up would overflow.

An expired value is a miss for Get and for Exists, whether or not the
store has removed it yet.

## Context

Every method returns the context's error, wrapped, when its context has
ended before it starts. A store that does I/O honors the context during
the call too. Close is the exception: it always closes.

## Lifecycle

A store is initialized with Init and closed with Close:

- Before its first successful Init, every method but Init and Close
returns [ErrNotInitialized](#ErrNotInitialized).
- Init on an initialized store returns [ErrAlreadyInitialized](#ErrAlreadyInitialized) and
changes nothing.
- After Close, until Init succeeds again, every method but Init and
Close returns [ErrClosed](#ErrClosed).
- Close on a store that is not initialized returns nil.

Close then Init restarts the store. Close waits for the goroutines the
store started.

## Security

Cache keys often carry user identifiers or session and token hashes,
and values are application data. So the stores keep them out of what
they report:

- No error the stores make holds a key or a value.
- No error or log holds a server's address, a user name or a
password.

A store's errors name the operation instead.

## Concurrency

Every store is safe for concurrent use, as each store's package
describes. The mock is too, except for setting its fields while it is
called.

## Errors

Every error a store returns starts with its service name, such as
`gas/cache/memory`, then the operation, such as `get`, then what
failed. It wraps one of these sentinels, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrKeyNotFound](#ErrKeyNotFound): no live value under the key.
- [ErrInvalidKey](#ErrInvalidKey): the key is empty.
- [ErrInvalidTTL](#ErrInvalidTTL): the TTL is negative.
- [ErrNotInitialized](#ErrNotInitialized), [ErrAlreadyInitialized](#ErrAlreadyInitialized), [ErrClosed](#ErrClosed): as under
Lifecycle.
- [ErrNilLogger](#ErrNilLogger): a store's constructor got a nil logger.
- [ErrNilConfig](#ErrNilConfig), [ErrNoConfigProvider](#ErrNoConfigProvider), [ErrInvalidConfig](#ErrInvalidConfig): Init
could not resolve a valid configuration.

The errors of this package's checks, as returned, before a store adds
its service name and the operation:

```go
invalid key: empty
invalid TTL: negative
```


## API reference

### Variables

<a id="ErrKeyNotFound"></a><a id="ErrInvalidKey"></a><a id="ErrInvalidTTL"></a><a id="ErrNotInitialized"></a><a id="ErrAlreadyInitialized"></a><a id="ErrClosed"></a><a id="ErrNilLogger"></a><a id="ErrNilConfig"></a><a id="ErrNoConfigProvider"></a><a id="ErrInvalidConfig"></a>

```go
var (
	// ErrKeyNotFound indicates that a store holds no live value under the
	// key: it was never set, was deleted, or expired.
	ErrKeyNotFound = errors.New("key not found")
	// ErrInvalidKey indicates that a key is not one a store accepts: it
	// is empty.
	ErrInvalidKey = errors.New("invalid key")
	// ErrInvalidTTL indicates that a TTL is negative.
	ErrInvalidTTL = errors.New("invalid TTL")
	// ErrNotInitialized indicates that a method was called before the
	// store's first successful Init.
	ErrNotInitialized = errors.New("service not initialized")
	// ErrAlreadyInitialized indicates that Init was called on a store that
	// is initialized.
	ErrAlreadyInitialized = errors.New("service already initialized")
	// ErrClosed indicates that a method was called after Close, before
	// Init succeeded again, or that Close ran while the call was in
	// progress.
	ErrClosed = errors.New("service closed")
	// ErrNilLogger indicates that a store's constructor was given a nil
	// logger.
	ErrNilLogger = errors.New("logger is nil")
	// ErrNilConfig indicates that WithConfig was given a nil
	// configuration.
	ErrNilConfig = errors.New("config is nil")
	// ErrNoConfigProvider indicates that there is neither a configuration
	// given to WithConfig nor a ConfigProvider to bind one from.
	ErrNoConfigProvider = errors.New("no config provider")
	// ErrInvalidConfig indicates that the configuration failed to bind,
	// failed its validate tags, or broke one of the store's rules.
	ErrInvalidConfig = errors.New("invalid config")
)
```

The sentinel errors every store of the module shares, as described in
the package documentation. A store's errors start with its own service
name and the operation, and wrap one of these.

<a id="CheckKey"></a>

#### func CheckKey

```go
func CheckKey(key string) error
```

CheckKey returns nil for a key every store accepts, any non-empty
string, and otherwise an error wrapping ErrInvalidKey. The error never
holds the key.

<a id="CheckTTL"></a>

#### func CheckTTL

```go
func CheckTTL(ttl time.Duration) error
```

CheckTTL returns nil for a TTL every store accepts, zero or positive,
and otherwise an error wrapping ErrInvalidTTL. The error never holds the
TTL.

<a id="EffectiveTTL"></a>

#### func EffectiveTTL

```go
func EffectiveTTL(ttl, defaultTTL time.Duration) time.Duration
```

EffectiveTTL returns how long a value set with ttl lives, as described
in the package documentation: defaultTTL in place of a zero ttl, rounded
up to a whole millisecond, with 0 for no expiry. It is for a ttl that
CheckTTL accepts and a defaultTTL that is not negative.
