Documentation
¶
Overview ¶
Package cache provides typed, backend-independent cache semantics.
Index ¶
- Variables
- type Backend
- type BulkResult
- type Cache
- func (c *Cache[K, V]) Add(ctx context.Context, logical K, value V) (bool, error)
- func (c *Cache[K, V]) Close() error
- func (c *Cache[K, V]) Delete(ctx context.Context, logical K) (err error)
- func (c *Cache[K, V]) DeleteMany(ctx context.Context, keys []K) ([]MutationResult[K], error)
- func (c *Cache[K, V]) Get(ctx context.Context, logical K) (result Result[V], err error)
- func (c *Cache[K, V]) GetMany(ctx context.Context, keys []K) ([]BulkResult[K, V], error)
- func (c *Cache[K, V]) GetOrLoad(ctx context.Context, logical K, loader Loader[K, V]) (Result[V], error)
- func (c *Cache[K, V]) Replace(ctx context.Context, logical K, value V) (bool, error)
- func (c *Cache[K, V]) Set(ctx context.Context, logical K, value V) error
- func (c *Cache[K, V]) SetIfOwned(ctx context.Context, logical K, value V, guard OwnershipGuard) error
- func (c *Cache[K, V]) SetMany(ctx context.Context, entries []Entry[K, V]) ([]MutationResult[K], error)
- func (c *Cache[K, V]) SetNegativeIfOwned(ctx context.Context, logical K, guard OwnershipGuard) error
- type Clock
- type Codec
- type Condition
- type Config
- type Entry
- type Error
- type ErrorKind
- type Event
- type JSONCodec
- type JitterSource
- type KeyEncoder
- type KeySpace
- type LoadPolicy
- type LoadResult
- type Loader
- type MutationResult
- type Observer
- type Operation
- type Outcome
- type OwnershipBackend
- type OwnershipGuard
- type RandomJitter
- type Record
- type Result
- type State
- type StringKeyEncoder
- type SystemClock
- type TTLPolicy
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMiss identifies an explicit cache miss where an error value is needed. ErrMiss = errors.New("cache miss") // ErrBackend identifies a storage or transport failure. ErrBackend = errors.New("cache backend error") // ErrDecode identifies malformed serialized data. ErrDecode = errors.New("cache decode error") // ErrSchemaMismatch identifies an incompatible payload version. ErrSchemaMismatch = errors.New("cache schema mismatch") // ErrInvalidKey identifies invalid key configuration or encoding. ErrInvalidKey = errors.New("invalid cache key") // ErrKeyTooLarge identifies a backend key beyond its configured bound. ErrKeyTooLarge = errors.New("cache key too large") // ErrValueTooLarge identifies a payload beyond its configured bound. ErrValueTooLarge = errors.New("cache value too large") // ErrInvalidTTL identifies an invalid or already expired deadline. ErrInvalidTTL = errors.New("invalid cache TTL") // ErrCapacity identifies a record that cannot fit a bounded backend. ErrCapacity = errors.New("cache capacity exceeded") // ErrClosed identifies use after cache or backend shutdown. ErrClosed = errors.New("cache backend closed") // ErrLoader identifies a source loader failure. ErrLoader = errors.New("cache loader error") // ErrLoaderPanic identifies a recovered loader panic. ErrLoaderPanic = errors.New("cache loader panic") // ErrRecursiveLoad identifies a loader re-entering the same cache. ErrRecursiveLoad = errors.New("recursive cache load") // ErrWaiterLimit identifies excess callers for one active key flight. ErrWaiterLimit = errors.New("cache waiter limit exceeded") // ErrInvalidPolicy identifies invalid or contradictory policy options. ErrInvalidPolicy = errors.New("invalid cache policy") // ErrBatchTooLarge identifies a bulk request beyond its configured bound. ErrBatchTooLarge = errors.New("cache batch too large") // ErrInvalidRecord identifies malformed portable backend state. ErrInvalidRecord = errors.New("invalid cache record") // ErrInvalidConfig identifies invalid constructor dependencies or limits. ErrInvalidConfig = errors.New("invalid cache configuration") // ErrOwnershipLost identifies a protected write rejected by its backend. ErrOwnershipLost = errors.New("cache ownership lost") // ErrOwnershipUnsupported identifies a backend without atomic ownership validation. ErrOwnershipUnsupported = errors.New("cache ownership validation unsupported") )
Functions ¶
This section is empty.
Types ¶
type Backend ¶
type Backend interface {
Get(context.Context, string) (Record, bool, error)
Set(context.Context, string, Record, Condition) (bool, error)
Delete(context.Context, string) (bool, error)
}
Backend is the atomic storage contract implemented by cache adapters.
type BulkResult ¶
BulkResult reports one GetMany result without flattening per-key errors.
type Cache ¶
type Cache[K, V any] struct { // contains filtered or unexported fields }
Cache provides typed cache operations over a backend.
func (*Cache[K, V]) Close ¶
Close cancels active loads, waits for their cleanup, and rejects new work.
func (*Cache[K, V]) DeleteMany ¶
func (c *Cache[K, V]) DeleteMany(ctx context.Context, keys []K) ([]MutationResult[K], error)
DeleteMany deletes keys in input order and records per-key failures.
func (*Cache[K, V]) GetMany ¶
func (c *Cache[K, V]) GetMany(ctx context.Context, keys []K) ([]BulkResult[K, V], error)
GetMany reads keys in input order and records per-key failures in the result.
func (*Cache[K, V]) GetOrLoad ¶
func (c *Cache[K, V]) GetOrLoad(ctx context.Context, logical K, loader Loader[K, V]) (Result[V], error)
GetOrLoad returns a cached value or coalesces a bounded source load.
Example ¶
package main
import (
"context"
"fmt"
"time"
cache "github.com/faustbrian/go-cache"
"github.com/faustbrian/go-cache/backend/memory"
)
func main() {
backend, _ := memory.New(memory.Config{
MaxEntries: 100,
MaxBytes: 1 << 20,
Clock: cache.SystemClock{},
})
keys, _ := cache.NewKeySpace("example", "greeting", 1, cache.StringKeyEncoder{}, 128)
store, _ := cache.New(cache.Config[string, string]{
Backend: backend,
Keys: keys,
Codec: cache.JSONCodec[string]{Version: 1},
TTL: cache.TTLPolicy{TTL: time.Minute},
Clock: cache.SystemClock{},
MaxValue: 1024,
})
defer func() { _ = store.Close() }()
result, err := store.GetOrLoad(context.Background(), "hello",
func(context.Context, string) (cache.LoadResult[string], error) {
return cache.LoadResult[string]{Value: "world", Found: true}, nil
})
fmt.Println(result.State == cache.Hit, result.Value, err)
}
Output: true world <nil>
func (*Cache[K, V]) SetIfOwned ¶
func (c *Cache[K, V]) SetIfOwned( ctx context.Context, logical K, value V, guard OwnershipGuard, ) error
SetIfOwned atomically writes a value only while guard identifies the active backend owner. Ownership loss is reported as ErrOwnershipLost.
func (*Cache[K, V]) SetMany ¶
func (c *Cache[K, V]) SetMany(ctx context.Context, entries []Entry[K, V]) ([]MutationResult[K], error)
SetMany writes entries in input order and records per-key failures.
func (*Cache[K, V]) SetNegativeIfOwned ¶
func (c *Cache[K, V]) SetNegativeIfOwned( ctx context.Context, logical K, guard OwnershipGuard, ) error
SetNegativeIfOwned atomically writes an explicit negative record only while guard identifies the active backend owner. The configured NegativeTTL must be positive. Ownership loss is reported as ErrOwnershipLost.
type Condition ¶
type Condition uint8
Condition controls the atomic precondition applied by Backend.Set.
type Config ¶
type Config[K, V any] struct { Backend Backend Keys KeySpace[K] Codec Codec[V] TTL TTLPolicy Clock Clock MaxValue int MaxBatch int Load LoadPolicy Jitter JitterSource Observer Observer }
Config contains all dependencies, limits, and policies for a Cache.
type Entry ¶
type Entry[K, V any] struct { Key K Value V }
Entry pairs a logical key with a value for SetMany.
type ErrorKind ¶
type ErrorKind uint8
ErrorKind classifies an operation failure independently of its cause.
const ( // BackendError identifies storage or transport failures. BackendError ErrorKind = iota + 1 // DecodeError identifies malformed encoded values. DecodeError // SchemaMismatchError identifies incompatible payload versions. SchemaMismatchError // InvalidKeyError identifies invalid key configuration or encoding. InvalidKeyError // LimitError identifies a configured resource-limit violation. LimitError // PolicyError identifies an invalid or contradictory policy. PolicyError // LoaderError identifies a source loader failure. LoaderError )
type JSONCodec ¶
JSONCodec stores strict JSON behind a one-byte schema version.
type JitterSource ¶
JitterSource chooses how much time to subtract from a loaded value's TTL.
type KeyEncoder ¶
KeyEncoder deterministically converts a typed logical key to bytes.
type KeySpace ¶
type KeySpace[K any] struct { // contains filtered or unexported fields }
KeySpace hashes logical keys beneath a namespace, name, and version prefix.
func NewKeySpace ¶
func NewKeySpace[K any]( namespace string, name string, version uint32, encoder KeyEncoder[K], maxKeySize int, ) (KeySpace[K], error)
NewKeySpace validates and constructs an isolated versioned key space.
type LoadPolicy ¶
type LoadPolicy struct {
MaxConcurrent int
MaxWaitersPerKey int
NegativeTTL time.Duration
StaleWhileRevalidate bool
StaleIfError bool
RefreshJitter time.Duration
}
LoadPolicy bounds loading and enables optional negative and stale behavior.
type LoadResult ¶
LoadResult is the value and existence result returned by a Loader.
type Loader ¶
type Loader[K, V any] func(context.Context, K) (LoadResult[V], error)
Loader fetches a logical key from its source of truth.
type MutationResult ¶
MutationResult reports one bulk mutation error in input order.
type Operation ¶
type Operation string
Operation names the semantic cache action associated with an event or error.
const ( // OperationGet identifies a read. OperationGet Operation = "get" // OperationSet identifies a write. OperationSet Operation = "set" // OperationDelete identifies invalidation. OperationDelete Operation = "delete" // OperationLoad identifies a source load. OperationLoad Operation = "load" // OperationEvict identifies capacity eviction. OperationEvict Operation = "evict" // OperationExpire identifies deadline expiration. OperationExpire Operation = "expire" )
type Outcome ¶
type Outcome string
Outcome is a low-cardinality semantic operation result.
const ( // OutcomeSuccess identifies a successful mutation or load. OutcomeSuccess Outcome = "success" // OutcomeHit identifies a fresh read. OutcomeHit Outcome = "hit" // OutcomeMiss identifies an absent read. OutcomeMiss Outcome = "miss" // OutcomeStale identifies a stale read. OutcomeStale Outcome = "stale" // OutcomeNegative identifies a negative-cache result. OutcomeNegative Outcome = "negative" // OutcomeRejected identifies a failed conditional mutation. OutcomeRejected Outcome = "rejected" // OutcomeError identifies an operation failure. OutcomeError Outcome = "error" // OutcomeEvicted identifies capacity eviction. OutcomeEvicted Outcome = "evicted" // OutcomeExpired identifies deadline expiration. OutcomeExpired Outcome = "expired" )
type OwnershipBackend ¶
type OwnershipBackend interface {
Backend
SetIfOwned(context.Context, string, Record, OwnershipGuard) error
}
OwnershipBackend atomically validates ownership and writes one record.
type OwnershipGuard ¶
OwnershipGuard identifies backend-authenticated ownership for one protected write. Implementations must return opaque storage coordinates, not logical keys or credentials.
type RandomJitter ¶
type RandomJitter struct{}
RandomJitter samples a non-cryptographic duration in [0, max).
type Record ¶
Record is the portable value and expiration envelope stored by a Backend.
type StringKeyEncoder ¶
type StringKeyEncoder struct{}
StringKeyEncoder encodes strings without conversion.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
backend
|
|
|
memory
Package memory provides a bounded, concurrency-safe LRU cache backend.
|
Package memory provides a bounded, concurrency-safe LRU cache backend. |
|
redis
Package redis adapts go-redis/v9 clients to the cache backend contract.
|
Package redis adapts go-redis/v9 clients to the cache backend contract. |
|
valkey
Package valkey adapts valkey-go clients to the cache backend contract.
|
Package valkey adapts valkey-go clients to the cache backend contract. |
|
Package cacheservice adapts explicit cache resources to the service lifecycle without hiding their concrete types.
|
Package cacheservice adapts explicit cache resources to the service lifecycle without hiding their concrete types. |
|
Package cachetest provides a shared backend conformance suite.
|
Package cachetest provides a shared backend conformance suite. |
|
internal
|
|
|
wire
Package wire encodes portable backend records for remote storage.
|
Package wire encodes portable backend records for remote storage. |
|
observability
|
|
|
otel
Package otel exports cache events as low-cardinality OpenTelemetry metrics.
|
Package otel exports cache events as low-cardinality OpenTelemetry metrics. |
|
slog
Package slog records redacted cache events with the standard log package.
|
Package slog records redacted cache events with the standard log package. |