cache

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 25 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cache stores JSON-encoded values with expiration times so repeated requests can read a cached result instead of repeating slow work.

A Cache wraps any Store, including MemoryStore, DatabaseStore, FailoverStore, DiscardStore, and the redis package's CacheStore. Package-level functions such as Get, Put, Remember, Flexible, and Lock operate on the default cache of the application attached to ctx, so HTTP handlers, jobs, commands, and tests use the same API:

users, err := cache.Remember(r, "users:count", 10*time.Minute, func(ctx context.Context) (int, error) {
	return db.Table("users").Count(ctx)
})

Use Named to access a specific configured store, or Memo to cache reads in memory for the duration of a single request or job attempt.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotInteger = errors.New("cache: the value isn't an integer")

ErrNotInteger is returned by Increment or Store.Increment when the existing value stored under a key cannot be parsed as a base-10 integer.

Functions

func Add

func Add(ctx context.Context, key string, value any, ttl time.Duration) (bool, error)

Add stores value under key in the application's default cache for ttl only if key does not exist, as described by Cache.Add. Add panics if ctx does not carry an application scope.

func CompareAndSwap

func CompareAndSwap(ctx context.Context, key string, old, value any, ttl time.Duration) (bool, error)

CompareAndSwap atomically replaces key with value for ttl in the application's default cache only if its current value matches old, as described by Cache.CompareAndSwap. CompareAndSwap panics if ctx does not carry an application scope.

func CreateTables

func CreateTables(ctx context.Context) error

CreateTables creates the cache and cache_locks tables used by the database cache store. Register it directly in database/migrations/migrations.go:

{Name: "0001_01_01_000001_create_cache_table", Run: cache.CreateTables}

Table names follow DB_CACHE_TABLE and DB_CACHE_LOCK_TABLE when configured, defaulting to "cache" and "cache_locks".

func Flexible

func Flexible[T any](ctx context.Context, key string, fresh, stale time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

Flexible returns key's value from the application's default cache and refreshes it in the background once older than fresh, as described by Cache.Flexible:

posts, err := cache.Flexible(r, "posts:count", 5*time.Minute, 10*time.Minute, func(ctx context.Context) (int, error) {
	return db.Table("posts").Count(ctx)
})

Flexible panics if ctx does not carry an application scope.

func Flush

func Flush(ctx context.Context) error

Flush removes every cached value from the application's default cache store, regardless of key prefix. Flush panics if ctx does not carry an application scope.

func Forget

func Forget(ctx context.Context, key string) error

Forget deletes key from the application's default cache. Forget panics if ctx does not carry an application scope.

func Get

func Get[T any](ctx context.Context, key string) (T, bool, error)

Get reads key from the application's default cache and decodes it into T, as described by Cache.Get. It returns false when the key is missing or expired:

name, ok, err := cache.Get[string](r, "user:42:name")

Get panics if ctx does not carry an application scope.

func Has

func Has(ctx context.Context, key string) (bool, error)

Has reports whether key currently exists in the application's default cache. Has panics if ctx does not carry an application scope.

func Increment

func Increment(ctx context.Context, key string, by int64) (int64, bool, error)

Increment atomically adds by to an existing integer value in the application's default cache, as described by Cache.Increment. Increment panics if ctx does not carry an application scope.

func IncrementOrAdd

func IncrementOrAdd(ctx context.Context, key string, by int64, ttl time.Duration) (int64, error)

IncrementOrAdd atomically adds by to an existing integer value in the application's default cache, or stores by for ttl if missing, as described by Cache.IncrementOrAdd:

hits, err := cache.IncrementOrAdd(r, "hits:"+r.IP(), 1, time.Minute)

IncrementOrAdd panics if ctx does not carry an application scope.

func Many

func Many[T any](ctx context.Context, keys ...string) (map[string]T, error)

Many reads multiple keys from the application's default cache and decodes each found value into T, as described by Cache.Many:

names, err := cache.Many[string](r, "user:1:name", "user:2:name")

Many panics if ctx does not carry an application scope.

func Pull

func Pull[T any](ctx context.Context, key string) (T, bool, error)

Pull reads key from the application's default cache into T and deletes it, as described by Cache.Pull. Pull panics if ctx does not carry an application scope.

func Put

func Put(ctx context.Context, key string, value any, ttl time.Duration) error

Put stores value under key in the application's default cache for ttl, as described by Cache.Put:

err := cache.Put(r, "user:42:name", "Taylor", 10*time.Minute)

Put panics if ctx does not carry an application scope.

func PutMany

func PutMany(ctx context.Context, values map[string]any, ttl time.Duration) error

PutMany stores each key-value pair in the application's default cache for ttl, as described by Cache.PutMany:

err := cache.PutMany(r, map[string]any{"user:1:name": "Taylor", "user:2:name": "Abigail"}, 10*time.Minute)

PutMany panics if ctx does not carry an application scope.

func Remember

func Remember[T any](ctx context.Context, key string, ttl time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

Remember returns key's value from the application's default cache, or calls fn and stores its result for ttl, as described by Cache.Remember:

titles, err := cache.Remember(r, "posts:titles", time.Hour, func(ctx context.Context) ([]string, error) {
	return db.Table("posts").WhereNotNull("published_at").Pluck[string](ctx, "title")
})

Remember panics if ctx does not carry an application scope.

func Touch

func Touch(ctx context.Context, key string, ttl time.Duration) (bool, error)

Touch resets key's expiration to ttl from now in the application's default cache, as described by Cache.Touch. Touch panics if ctx does not carry an application scope.

Types

type AtomicLock

type AtomicLock struct {
	// contains filtered or unexported fields
}

AtomicLock coordinates mutually exclusive access to a named resource using a Cache store. Locks on DatabaseStore and Redis stores are shared across processes, MemoryStore locks apply within a single process, and DiscardStore locks do not block callers.

func Lock

func Lock(ctx context.Context, name string, ttl time.Duration) *AtomicLock

Lock returns a named AtomicLock on the application's default cache that expires after ttl once acquired, as described by Cache.Lock:

lock := cache.Lock(r, "reports", 10*time.Second)
ok, err := lock.Acquire(r)
if err != nil {
	return web.Fail(err)
}
if ok {
	defer lock.Release(r)
	// ...
}

Lock panics if ctx does not carry an application scope or if ttl is not positive.

func RestoreLock

func RestoreLock(ctx context.Context, name, owner string) *AtomicLock

RestoreLock reconstructs a named AtomicLock held by owner on the application's default cache so another process can refresh or release it, as described by Cache.RestoreLock. RestoreLock panics if ctx does not carry an application scope.

func (*AtomicLock) Acquire

func (l *AtomicLock) Acquire(ctx context.Context) (bool, error)

Acquire attempts to take the lock immediately and reports whether it succeeded. Always pair a successful Acquire with AtomicLock.Release so the lock does not stay held until its TTL expires.

Acquire returns an error on a restored lock from Cache.RestoreLock because restored locks have no TTL.

func (*AtomicLock) Block

func (l *AtomicLock) Block(ctx context.Context, wait time.Duration) error

Block polls for the lock until it is acquired, wait elapses, or ctx is canceled. If wait elapses without acquiring the lock, Block returns a *LockTimeoutError, which maps to HTTP 423 Locked.

func (*AtomicLock) BlockRun

func (l *AtomicLock) BlockRun(ctx context.Context, wait time.Duration, fn func(ctx context.Context) error) error

BlockRun waits up to wait to acquire the lock like AtomicLock.Block, runs fn while holding it, and releases the lock when fn returns or panics:

err := cache.Lock(ctx, "billing-sync", time.Minute).BlockRun(ctx, 5*time.Second, func(ctx context.Context) error {
	return syncBilling(ctx)
})

func (*AtomicLock) ForceRelease

func (l *AtomicLock) ForceRelease(ctx context.Context) error

ForceRelease deletes the lock regardless of who holds it. Like AtomicLock.Release, it detaches from ctx cancellation.

func (*AtomicLock) IsLocked

func (l *AtomicLock) IsLocked(ctx context.Context) (bool, error)

IsLocked reports whether any owner currently holds the lock.

func (*AtomicLock) IsOwned

func (l *AtomicLock) IsOwned(ctx context.Context) (bool, error)

IsOwned reports whether this lock's owner token currently holds the lock.

func (*AtomicLock) Owner

func (l *AtomicLock) Owner() string

Owner returns the opaque token identifying this lock holder. Pass it to Cache.RestoreLock when another process needs to release or refresh the lock.

func (*AtomicLock) Refresh

func (l *AtomicLock) Refresh(ctx context.Context) (bool, error)

Refresh extends the lock's expiration to its original TTL from now while this owner holds it, returning false if another owner holds the lock. If the lock expired and nobody else claimed it, Refresh reacquires it and returns true. Check the boolean result before each protected step:

for _, month := range months {
	if ok, err := lock.Refresh(ctx); err != nil || !ok {
		return err
	}
	// Generate the month's report.
}

Refresh returns an error on a restored lock because it has no TTL; call AtomicLock.RefreshFor instead.

func (*AtomicLock) RefreshFor

func (l *AtomicLock) RefreshFor(ctx context.Context, ttl time.Duration) (bool, error)

RefreshFor extends the lock's expiration to ttl from now while this owner holds it, returning false if another owner holds the lock. Use RefreshFor to extend a restored lock:

refreshed, err := cache.RestoreLock(ctx, "processing", owner).RefreshFor(ctx, time.Minute)

RefreshFor panics if ttl is not positive.

func (*AtomicLock) Release

func (l *AtomicLock) Release(ctx context.Context) (bool, error)

Release frees the lock if this owner still holds it and reports whether it was released. Release detaches from ctx cancellation so a deferred release still runs if a client disconnects.

func (*AtomicLock) Run

func (l *AtomicLock) Run(ctx context.Context, fn func(ctx context.Context) error) (bool, error)

Run attempts to acquire the lock, executes fn if acquired, and releases the lock when fn returns or panics. It returns (false, nil) if another owner already holds the lock, (true, err) after running fn, or (false, err) if acquiring the lock fails:

ran, err := cache.Lock(ctx, "rebuild-index", time.Minute).Run(ctx, func(ctx context.Context) error {
	return rebuildIndex(ctx)
})

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache reads and writes JSON-encoded values in a Store with a key prefix so multiple applications can share one backend without collisions. All methods on Cache are safe for concurrent use.

func Memo

func Memo(ctx context.Context) *Cache

Memo returns a memoized view of the application's default Cache for the current request, job attempt, command, or test context, as described by Cache.Memo:

settings := cache.Memo(r)
theme, ok, err := settings.Get[string](r, "settings:theme")

To memoize a different store, call Cache.Memo on Named, such as cache.Named(r, "database").Memo(). Memo panics if ctx does not carry an application scope.

func Named

func Named(ctx context.Context, name string) *Cache

Named returns the configured Cache store named name, such as "database" when CACHE_STORE is "redis", or a custom store registered by a package:

reports := cache.Named(r, "database")
total, err := reports.Remember[int](r, "reports:total", time.Hour, countOrders)

Each named store initializes once on first use, and naming the default store returns the application's default Cache. Named panics if ctx does not carry an application scope, if no store with that name exists, or if the store cannot be initialized.

func New

func New(store Store, prefix string) *Cache

New creates a Cache backed by store that prepends prefix to every cache key and lock name.

func (*Cache) Add

func (c *Cache) Add(ctx context.Context, key string, value any, ttl time.Duration) (bool, error)

Add stores value under key for ttl only if key does not currently exist, and reports whether the value was stored. When concurrent callers race on the same key, only one succeeds.

func (*Cache) CompareAndSwap

func (c *Cache) CompareAndSwap(ctx context.Context, key string, old, value any, ttl time.Duration) (bool, error)

CompareAndSwap atomically stores value under key for ttl only if the current stored value matches old (compared as encoded JSON), or if old is nil and key does not exist. It reports whether the swap succeeded. When ttl is zero or negative, CompareAndSwap returns false and a nil error without writing.

func (*Cache) Flexible

func (c *Cache) Flexible[T any](ctx context.Context, key string, fresh, stale time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

Flexible implements stale-while-revalidate caching. While the cached value is younger than fresh, Flexible returns it immediately. Between fresh and stale, Flexible returns the stale value immediately and runs fn in a background goroutine to refresh it. Once stale expires, Flexible calls fn synchronously and stores the new result.

The background refresh detaches from ctx's cancellation and database transaction so it completes after the HTTP response finishes. An internal lock ensures only one caller refreshes a stale key at a time. If a refresh fails, the stale value remains cached and the error is logged.

func (*Cache) Flush

func (c *Cache) Flush(ctx context.Context) error

Flush removes every cached value in the underlying store, regardless of key prefix.

func (*Cache) Forget

func (c *Cache) Forget(ctx context.Context, key string) error

Forget deletes key from the cache.

func (*Cache) Get

func (c *Cache) Get[T any](ctx context.Context, key string) (T, bool, error)

Get reads the cached value for key and decodes it into T. If the key is missing or expired, Get returns the zero value of T, false, and a nil error. Get returns an error if the store fails or the stored JSON cannot decode into T.

func (*Cache) Has

func (c *Cache) Has(ctx context.Context, key string) (bool, error)

Has reports whether key currently exists in the cache.

func (*Cache) Increment

func (c *Cache) Increment(ctx context.Context, key string, by int64) (int64, bool, error)

Increment atomically adds by to an existing integer value without changing its expiration time, returning the new total and true. Pass a negative by to decrement. If key does not exist, Increment returns 0, false, nil. If the stored value is not an integer, Increment returns ErrNotInteger.

func (*Cache) IncrementOrAdd

func (c *Cache) IncrementOrAdd(ctx context.Context, key string, by int64, ttl time.Duration) (int64, error)

IncrementOrAdd atomically adds by to an existing integer value, or stores by for ttl if key does not exist, returning the resulting total. When ttl is zero or negative and key does not exist, IncrementOrAdd returns by without storing it.

func (*Cache) Lock

func (c *Cache) Lock(name string, ttl time.Duration) *AtomicLock

Lock creates a named AtomicLock with a random owner token that stays held for ttl once acquired. Use locks to ensure only one process runs a critical section at a time. Lock panics if ttl is not positive.

func (*Cache) Many

func (c *Cache) Many[T any](ctx context.Context, keys ...string) (map[string]T, error)

Many reads multiple keys and returns a map of the keys that exist, decoded into T. Missing or expired keys are omitted from the returned map:

names, err := c.Many[string](ctx, "user:1:name", "user:2:name")

Many returns an error if the store fails or any found value cannot decode into T.

func (*Cache) Memo

func (c *Cache) Memo() *Cache

Memo returns a view of c that memoizes reads in memory for the current unit of work (request, job attempt, command, or test context). Repeated reads of the same key return the memoized value or miss without hitting the backing store:

settings := cache.Memo(r)
theme, ok, err := settings.Get[string](r, "settings:theme") // Reads the store.
theme, ok, err = settings.Get[string](r, "settings:theme")  // Returns the memoized value.

Writes and deletes through c or any memoized view of c clear the affected memo entries, and Cache.Flush clears all memoized entries for c. Reading through a memoized cache panics if ctx does not carry an application scope.

func (*Cache) Prune

func (c *Cache) Prune(ctx context.Context) (bool, error)

Prune deletes expired values and locks immediately if the underlying store implements PruningStore, reporting whether pruning was supported. DatabaseStore also prunes automatically about once an hour, so call Prune when you want expired rows removed right away.

func (*Cache) Pull

func (c *Cache) Pull[T any](ctx context.Context, key string) (T, bool, error)

Pull reads and decodes key like Cache.Get, then removes it from the cache. If key is missing, Pull returns the zero value of T, false, and a nil error.

func (*Cache) Put

func (c *Cache) Put(ctx context.Context, key string, value any, ttl time.Duration) error

Put encodes value as JSON and stores it under key for ttl. When ttl is zero or negative, Put removes key instead.

func (*Cache) PutMany

func (c *Cache) PutMany(ctx context.Context, values map[string]any, ttl time.Duration) error

PutMany encodes and stores each key-value pair in values for ttl. When ttl is zero or negative, PutMany removes all keys in values instead.

func (*Cache) Remember

func (c *Cache) Remember[T any](ctx context.Context, key string, ttl time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

Remember returns the cached value for key, or calls fn, stores its result for ttl, and returns it. If fn returns an error, Remember returns that error without writing to the cache. A stored value that fails to decode into T is treated as a cache miss so deploying a schema change recovers automatically.

Concurrent callers that miss at the same time each run fn. Coordinate them with Cache.Lock if the work must run only once.

func (*Cache) RestoreLock

func (c *Cache) RestoreLock(name, owner string) *AtomicLock

RestoreLock reconstructs a named AtomicLock with an existing owner token from AtomicLock.Owner so a different process or job can refresh or release the lock.

func (*Cache) Store

func (c *Cache) Store() Store

Store returns the underlying Store used by c.

func (*Cache) Touch

func (c *Cache) Touch(ctx context.Context, key string, ttl time.Duration) (bool, error)

Touch resets key's expiration to ttl from now without modifying its value, and reports whether key existed. When ttl is zero or negative, Touch removes key if it exists and reports whether it was present.

type DatabaseStore

type DatabaseStore struct {
	// contains filtered or unexported fields
}

DatabaseStore stores cache entries and distributed locks in database tables shared across application servers, implementing PruningStore.

The values table expects key, value, and expiration columns; the locks table expects key, owner, and expiration columns, with expiration stored as a timestamp. The tables may live on different connections. Expiration times round up to the timestamp precision of the table's connection so entries live at least their requested TTL.

DatabaseStore prunes expired rows automatically about once an hour on writes. When called inside a transaction on the values table's connection, value writes join the transaction and roll back with it. Locks stay outside the caller's transaction, except on SQLite, so a rollback doesn't release them.

func NewDatabaseStore

func NewDatabaseStore(conn *db.DB, table string, lockConn *db.DB, lockTable string) *DatabaseStore

NewDatabaseStore creates a DatabaseStore that keeps cached values in table on conn and distributed locks in lockTable on lockConn, such as "cache" and "cache_locks". Pass the same connection twice to keep both tables together.

func (*DatabaseStore) AcquireLock

func (d *DatabaseStore) AcquireLock(ctx context.Context, name, owner string, ttl time.Duration) (bool, error)

AcquireLock inserts a lock row for owner with expiration ttl, or takes over an existing row that has expired or is already held by owner. It reports whether owner now holds the lock.

func (*DatabaseStore) CompareAndSwap

func (d *DatabaseStore) CompareAndSwap(ctx context.Context, key string, old, value []byte, ttl time.Duration) (bool, error)

CompareAndSwap atomically replaces key with value for ttl if the current unexpired row matches old, or if old is nil and no unexpired row exists. It reports whether the swap succeeded.

func (*DatabaseStore) Flush

func (d *DatabaseStore) Flush(ctx context.Context) error

Flush deletes every row from the cache values table.

func (*DatabaseStore) Forget

func (d *DatabaseStore) Forget(ctx context.Context, key string) error

Forget deletes the row for key from the cache table.

func (*DatabaseStore) Get

func (d *DatabaseStore) Get(ctx context.Context, key string) ([]byte, error)

Get returns the raw bytes stored under key, or nil if the key is missing or has expired.

func (*DatabaseStore) Increment

func (d *DatabaseStore) Increment(ctx context.Context, key string, by int64) (int64, bool, error)

Increment atomically adds by to an existing unexpired integer entry inside a row-locked transaction and returns the new total and true. If the key is missing or expired, Increment returns 0, false, nil. If the stored value is not an integer, Increment returns ErrNotInteger.

func (*DatabaseStore) LockOwner

func (d *DatabaseStore) LockOwner(ctx context.Context, name string) (string, error)

LockOwner returns the current owner of the unexpired lock for name, or an empty string if the lock is not held.

func (*DatabaseStore) Prune

func (d *DatabaseStore) Prune(ctx context.Context) error

Prune deletes all expired rows from both the cache and lock tables.

func (*DatabaseStore) Put

func (d *DatabaseStore) Put(ctx context.Context, key string, value []byte, ttl time.Duration) error

Put upserts value under key with an expiration of ttl from now.

func (*DatabaseStore) ReleaseLock

func (d *DatabaseStore) ReleaseLock(ctx context.Context, name, owner string) (bool, error)

ReleaseLock deletes the unexpired lock row for name when held by owner, or unconditionally when owner is empty. It reports whether a lock was deleted.

type DiscardStore

type DiscardStore struct{}

DiscardStore is a no-op Store that discards all writes and misses every read. Use it to disable caching; its locks never block callers.

func (DiscardStore) AcquireLock

AcquireLock always succeeds and returns true, nil.

func (DiscardStore) CompareAndSwap

func (DiscardStore) CompareAndSwap(context.Context, string, []byte, []byte, time.Duration) (bool, error)

CompareAndSwap always reports true, as if the value was stored and expired immediately.

func (DiscardStore) Flush

Flush does nothing and returns nil.

func (DiscardStore) Forget

Forget does nothing and returns nil.

func (DiscardStore) Get

Get always returns nil, nil.

func (DiscardStore) Increment

Increment always reports a miss (0, false, nil).

func (DiscardStore) LockOwner

func (DiscardStore) LockOwner(context.Context, string) (string, error)

LockOwner always returns an empty string because DiscardStore holds no locks.

func (DiscardStore) Put

Put discards the value and returns nil.

func (DiscardStore) ReleaseLock

func (DiscardStore) ReleaseLock(context.Context, string, string) (bool, error)

ReleaseLock always succeeds and returns true, nil.

type FailoverStore

type FailoverStore struct {
	// contains filtered or unexported fields
}

FailoverStore tries a list of Store backends in order so caching keeps working when a primary backend is unavailable. When a store fails, FailoverStore logs the initial failure with slog.Default, falls through to the next store, and skips the failed store for 10 seconds before retrying it. The final store is always attempted.

Distributed locks always use the first store and never fail over, because acquiring a lock in a fallback store during an outage would allow two processes to hold the same lock once the primary recovers.

func NewFailoverStore

func NewFailoverStore(stores ...Store) *FailoverStore

NewFailoverStore creates a FailoverStore that attempts stores in order, such as Redis followed by the database store. It panics if no stores are provided.

func (*FailoverStore) AcquireLock

func (f *FailoverStore) AcquireLock(ctx context.Context, name, owner string, ttl time.Duration) (bool, error)

AcquireLock acquires the named lock on the primary (first) store without failing over.

func (*FailoverStore) CompareAndSwap

func (f *FailoverStore) CompareAndSwap(ctx context.Context, key string, old, value []byte, ttl time.Duration) (bool, error)

CompareAndSwap runs Store.CompareAndSwap on the first healthy store.

func (*FailoverStore) Flush

func (f *FailoverStore) Flush(ctx context.Context) error

Flush clears all cached values from the first healthy store.

func (*FailoverStore) Forget

func (f *FailoverStore) Forget(ctx context.Context, key string) error

Forget removes key from the first healthy store.

func (*FailoverStore) Get

func (f *FailoverStore) Get(ctx context.Context, key string) ([]byte, error)

Get reads key from the first healthy store.

func (*FailoverStore) Increment

func (f *FailoverStore) Increment(ctx context.Context, key string, by int64) (int64, bool, error)

Increment runs Store.Increment on the first healthy store.

func (*FailoverStore) LockOwner

func (f *FailoverStore) LockOwner(ctx context.Context, name string) (string, error)

LockOwner returns the lock owner from the primary (first) store without failing over.

func (*FailoverStore) Prune

func (f *FailoverStore) Prune(ctx context.Context) error

Prune runs PruningStore.Prune on every member store that implements PruningStore, returning any errors joined together.

func (*FailoverStore) Put

func (f *FailoverStore) Put(ctx context.Context, key string, value []byte, ttl time.Duration) error

Put writes value under key for ttl in the first healthy store.

func (*FailoverStore) ReleaseLock

func (f *FailoverStore) ReleaseLock(ctx context.Context, name, owner string) (bool, error)

ReleaseLock releases the named lock on the primary (first) store without failing over.

type LockTimeoutError

type LockTimeoutError struct {
	// Name is the lock name that could not be acquired.
	Name string
}

LockTimeoutError is returned by AtomicLock.Block when the lock cannot be acquired before the wait duration expires. It reports HTTP status 423 Locked.

func (*LockTimeoutError) Error

func (e *LockTimeoutError) Error() string

Error returns a message naming the lock that timed out.

func (*LockTimeoutError) StatusCode

func (e *LockTimeoutError) StatusCode() int

StatusCode returns http.StatusLocked (423).

type ManyStore

type ManyStore interface {
	Store
	// GetMany returns the raw bytes for each key in the same order as keys,
	// with nil for any missing or expired key.
	GetMany(ctx context.Context, keys []string) ([][]byte, error)
	// PutMany stores every key-value pair in values for ttl.
	PutMany(ctx context.Context, values map[string][]byte, ttl time.Duration) error
}

ManyStore is an optional extension of Store for backends that can read or write multiple keys in one round trip. Cache.Many and Cache.PutMany use these batch methods when supported and fall back to per-key calls otherwise.

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

MemoryStore stores cache entries and locks in process memory for the lifetime of the process. Because entries are not shared across servers, use DatabaseStore or Redis in multi-process deployments. All methods on MemoryStore are safe for concurrent use.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates an empty MemoryStore.

func (*MemoryStore) AcquireLock

func (m *MemoryStore) AcquireLock(ctx context.Context, name, owner string, ttl time.Duration) (bool, error)

AcquireLock acquires the named lock for owner for ttl unless another owner currently holds it, or extends it if owner already holds it. It reports whether owner now holds the lock.

func (*MemoryStore) CompareAndSwap

func (m *MemoryStore) CompareAndSwap(ctx context.Context, key string, old, value []byte, ttl time.Duration) (bool, error)

CompareAndSwap atomically replaces key with value for ttl if the current unexpired bytes match old, or if old is nil and key is absent or expired. It reports whether the swap succeeded.

func (*MemoryStore) Flush

func (m *MemoryStore) Flush(context.Context) error

Flush removes all cached values from memory.

func (*MemoryStore) Forget

func (m *MemoryStore) Forget(_ context.Context, key string) error

Forget removes key from memory.

func (*MemoryStore) Get

func (m *MemoryStore) Get(ctx context.Context, key string) ([]byte, error)

Get returns the raw bytes stored under key, or nil if the key is missing or has expired.

func (*MemoryStore) Increment

func (m *MemoryStore) Increment(ctx context.Context, key string, by int64) (int64, bool, error)

Increment atomically adds by to an existing unexpired integer entry and returns the new total and true. If key is absent or expired, Increment returns 0, false, nil. If the stored value is not an integer, Increment returns ErrNotInteger.

func (*MemoryStore) LockOwner

func (m *MemoryStore) LockOwner(ctx context.Context, name string) (string, error)

LockOwner returns the current owner of the unexpired lock for name, or an empty string if the lock is not held.

func (*MemoryStore) Put

func (m *MemoryStore) Put(ctx context.Context, key string, value []byte, ttl time.Duration) error

Put stores a copy of value under key for ttl.

func (*MemoryStore) ReleaseLock

func (m *MemoryStore) ReleaseLock(ctx context.Context, name, owner string) (bool, error)

ReleaseLock deletes the unexpired lock for name if owner holds it, or unconditionally when owner is empty. It reports whether a lock was removed.

type Memos

type Memos struct {
	// contains filtered or unexported fields
}

Memos stores the values read by memoized caches created with Cache.Memo for a single unit of work, such as an HTTP request or job attempt. The framework attaches a fresh Memos to each request, job, command, and test context. The zero value of Memos is ready to use and safe for concurrent access.

type PruningStore

type PruningStore interface {
	Store
	// Prune deletes all expired cache entries and locks from the store.
	Prune(ctx context.Context) error
}

PruningStore is an optional extension of Store for backends that require explicit cleanup of expired rows, such as DatabaseStore. Cache.Prune and the cache:prune command call Prune when the store implements it.

type Store

type Store interface {
	// Get returns the raw bytes stored under key, or nil if the key does not
	// exist or has expired.
	Get(ctx context.Context, key string) ([]byte, error)
	// Put stores value under key for ttl, replacing any existing entry.
	Put(ctx context.Context, key string, value []byte, ttl time.Duration) error
	// CompareAndSwap atomically stores value under key for ttl only if the
	// current value equals old, or if old is nil and the key is absent. It
	// reports whether the swap succeeded.
	CompareAndSwap(ctx context.Context, key string, old, value []byte, ttl time.Duration) (bool, error)
	// Increment atomically adds by to an existing integer entry without
	// changing its expiration time, returning the new value and true. It
	// returns 0, false, nil if the key is absent, or [ErrNotInteger] if the
	// stored value is not an integer.
	Increment(ctx context.Context, key string, by int64) (int64, bool, error)
	// Forget deletes key from the store.
	Forget(ctx context.Context, key string) error
	// Flush removes every cached value from the store.
	Flush(ctx context.Context) error
	// AcquireLock acquires the named lock for owner for ttl unless another
	// owner currently holds it, or extends the expiration if owner already
	// holds it. It reports whether owner now holds the lock.
	AcquireLock(ctx context.Context, name, owner string, ttl time.Duration) (bool, error)
	// ReleaseLock deletes the named lock if owner holds it, or unconditionally
	// when owner is empty. It reports whether a lock was released.
	ReleaseLock(ctx context.Context, name, owner string) (bool, error)
	// LockOwner returns the current owner of the named lock, or an empty
	// string if the lock is not held.
	LockOwner(ctx context.Context, name string) (string, error)
}

Store is the low-level backend interface for storing raw cached bytes and distributed locks. Built-in implementations include MemoryStore, DatabaseStore, FailoverStore, DiscardStore, and the redis package's CacheStore. Cache layers key prefixes, JSON encoding, atomic counters, and request memoization on top of a Store.

Implementations must treat expired entries as absent: Get returns nil, and CompareAndSwap treats the key as missing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL