Documentation
¶
Overview ¶
Package cachex is a multi-layer read-through cache: a Cache reads its layers top down (memory, then Redis, then a database table, say) and asks the source only when none of them has a usable entry. Concurrent misses of a key are fetched once; writes through the Cache reach every layer in one order. See docs/design.md.
Index ¶
- Constants
- Variables
- func IsShared(ctx context.Context) bool
- func NewBatchError(errs map[string]error) error
- type Backend
- type BatchError
- type BatchSource
- type Broadcast
- type ByteBackend
- type ByteEntry
- type ByteLeaser
- type ByteLeasing
- type ByteLocalBackend
- type Cache
- func (c *Cache[T]) Close() error
- func (c *Cache[T]) Del(ctx context.Context, key string) error
- func (c *Cache[T]) DelMany(ctx context.Context, keys []string) error
- func (c *Cache[T]) Get(ctx context.Context, key string) (T, error)
- func (c *Cache[T]) GetMany(ctx context.Context, keys []string) (map[string]T, error)
- func (c *Cache[T]) Set(ctx context.Context, key string, value T) error
- func (c *Cache[T]) SetMany(ctx context.Context, values map[string]T) error
- type Codec
- type Entry
- type Layer
- type LayerOption
- type Leaser
- type Leasing
- type LocalBackend
- type Option
- func WithBroadcast(b Broadcast) Option
- func WithFetchTimeout(timeout time.Duration) Option
- func WithGetManyChunkSize(size int) Option
- func WithGetManyConcurrency(n int) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMaxAge[T any](maxAge func(T) time.Duration) Option
- func WithNow(now func() time.Time) Option
- type SingleBackend
- type SliceGetter
- type Source
- type SourceFunc
Constants ¶
const ( DefaultFetchTimeout = 60 * time.Second DefaultGetManyConcurrency = 16 )
Defaults of the Cache options.
const DefaultJitter = 0.1
DefaultJitter is the jitter of a layer that does not set one (see Jitter).
Variables ¶
var ErrNotFound = errors.New("cachex: not found")
ErrNotFound reports that a key does not exist. Sources return it from Get for a missing key; Cache.Get returns it for a key the source does not have, whether it was just asked or a cached not-found answered. Test with errors.Is.
var ErrUnsupportedKey = errors.New("cachex: unsupported key: it holds a \"}\" but no hash tag")
ErrUnsupportedKey reports a key that holds a "}" but no hash tag: a "{" followed, later, by a "}" with something between them, as Redis Cluster reads it. Such a key cannot share its Redis Cluster slot with the key of its lease, so the Cache rejects it whatever its layers, and a key that works now keeps working when a layer moves to Redis: Get, GetMany, Set and SetMany fail it, Del and DelMany do nothing (it was never stored). Test with errors.Is.
Functions ¶
func IsShared ¶
IsShared reports whether ctx belongs to a fetch shared by every request of a key rather than to one caller: it carries the caller's values but not its cancellation, and a backend must not use caller state from it, such as a database transaction.
func NewBatchError ¶
NewBatchError returns a *BatchError listing errs, or nil if errs is empty: what a backend's Many method returns after trying every key.
Types ¶
type Backend ¶
type Backend[T any] interface { Get(ctx context.Context, key string) (Entry[T], bool, error) GetMany(ctx context.Context, keys []string) (map[string]Entry[T], error) Set(ctx context.Context, key string, entry Entry[T]) error SetMany(ctx context.Context, entries map[string]Entry[T]) error Del(ctx context.Context, key string) error DelMany(ctx context.Context, keys []string) error }
Backend stores the entries of one layer. A missing key is not an error: Get reports it with false, GetMany leaves it out of the map. The Many methods are best effort: a failure of some keys is reported as a *BatchError listing them (returned as is, not wrapped); any other error means the whole call failed. A store with single-key operations only can implement SingleBackend and be wrapped with Batched.
func Batched ¶
func Batched[T any](b SingleBackend[T]) Backend[T]
Batched turns a SingleBackend into a Backend whose Many methods go key by key, best effort: the keys that fail are reported in a *BatchError. It forwards b's LocalBackend and Leasing, if b has them.
func Encoded ¶
Encoded turns a ByteBackend into a Backend that stores each entry as bytes: its times, whether it is a not-found, and its value as codec (nil: DefaultCodec) marshals it. Data that does not decode is a miss, not a failure: it was written by something else, or before the value's type changed, so Encoded logs a WARN to logger (nil: slog.Default()), deletes the key, and reports it absent. An entry already past its ExpiresAt is not written: its key is deleted instead. That is judged by the wall clock (time.Now), as backends expire entries by it, whatever clock the Cache uses. It forwards ByteLeasing (as Leasing) and ByteLocalBackend (as LocalBackend).
type BatchError ¶
BatchError lists the keys a batch operation failed for. Keys that do not exist are never in it.
func (*BatchError) Error ¶
func (e *BatchError) Error() string
type BatchSource ¶
type BatchSource[T any] interface { GetMany(ctx context.Context, keys []string) (map[string]T, error) }
BatchSource is a Source that can answer many keys in one call; GetMany uses it when the source implements it. A key the source does not have is absent from the map (not an error). A *BatchError returned as is fails only the keys it lists; any other error fails every key. An error that wraps ErrNotFound (for a key, or for the call) reads its keys as not found but caches nothing, so each read asks again: leave missing keys out instead.
type Broadcast ¶
type Broadcast interface {
// Publish sends msg to every instance listening; it may reach this one
// too.
Publish(ctx context.Context, msg []byte) error
// Listen calls deliver with each message published, one at a time, until
// ctx ends, and returns then. It calls ready each time it subscribes,
// before delivering what is published from then on: what was published
// while it was not subscribed is lost.
Listen(ctx context.Context, ready func(), deliver func(msg []byte)) error
}
Broadcast carries invalidations between the instances of a Cache: the keys each write changed, so that the other instances drop them from their local layers (see WithBroadcast). Messages are opaque to it.
type ByteBackend ¶
type ByteBackend interface {
Get(ctx context.Context, key string) ([]byte, bool, error)
GetMany(ctx context.Context, keys []string) (map[string][]byte, error)
// Set stores data until expiresAt, which Encoded passes only in the
// future; the backend may drop the key from then on.
Set(ctx context.Context, key string, data []byte, expiresAt time.Time) error
SetMany(ctx context.Context, entries map[string]ByteEntry) error
Del(ctx context.Context, key string) error
DelMany(ctx context.Context, keys []string) error
}
ByteBackend stores bytes by key, for a backend that stores entries encoded: wrap it with Encoded to get a Backend. Like Backend, a missing key is not an error (Get reports it with false, GetMany leaves it out of the map), and the Many methods are best effort: a failure of some keys is a *BatchError listing them, returned as is; any other error means the whole call failed. The single-key methods return plain errors.
type ByteLeaser ¶
type ByteLeaser interface {
Lease(ctx context.Context, keys []string, ttl time.Duration) (map[string]string, error)
PutLeased(ctx context.Context, tokens map[string]string, entries map[string]ByteEntry) error
Release(ctx context.Context, tokens map[string]string) error
}
ByteLeaser is Leaser for a ByteBackend; Encoded turns it into a Leaser. Like ByteBackend.Set, PutLeased gets only entries that expire in the future.
type ByteLeasing ¶
type ByteLeasing interface {
Leaser() ByteLeaser
}
ByteLeasing is a ByteBackend that can lease its keys; see Leasing.
type ByteLocalBackend ¶
ByteLocalBackend is LocalBackend for a ByteBackend; Encoded forwards it.
type Cache ¶
type Cache[T any] struct { // contains filtered or unexported fields }
Cache reads through its layers to its source. Build it with New.
func New ¶
New returns a Cache reading layers top down (layers[0] first) and then source. With no layers it only merges concurrent fetches of a key.
func (*Cache[T]) Close ¶
Close stops listening to the broadcast, if any, and waits for the fetches and background refreshes in progress (and their backfills) and for the invalidations of writes that gave up waiting (and their publishes), so that the backends can be closed after it, and starts no more background refreshes. It does not close the backends. The Cache still serves reads and writes, but no longer hears of other instances' writes: its local layers may serve what they overwrote until it rots.
func (*Cache[T]) Del ¶
Del drops key from every layer, bottom up, so the next read asks the source. Like Set, call it after changing the source; it records nothing about whether the key exists. Failures and waiting are as for Set.
func (*Cache[T]) DelMany ¶
DelMany is Del for many keys, with one call per layer; failures are reported as for SetMany.
func (*Cache[T]) Get ¶
Get returns key's value from the first layer with a usable entry, or else from the source; concurrent misses of a key share one fetch, whose result is backfilled into the layers above where it was found. A stale entry is returned at once and refreshed in the background. Get returns ErrNotFound for a key the source does not have.
func (*Cache[T]) GetMany ¶
GetMany returns the values of keys that exist, with the semantics of calling Get for each: the first layer is read in one call, the layers below and a BatchSource in one call per chunk (see WithGetManyChunkSize; by default one chunk), any other source key by key (see WithGetManyConcurrency), and keys being fetched by other calls are waited for, not fetched again. A key the source does not have is absent from the map. If some keys failed, the map holds every other key and the error is a *BatchError listing the failed ones.
func (*Cache[T]) Set ¶
Set writes value for key into every layer, bottom up, as if the source had just answered it. It does not write the source: change the source first, then call Set (or Del), so that a read in between cannot cache the old value after the write.
Until Set returns, a concurrent read may still see the old value; once it returns, no read gets a value fetched before it, and a fetch that started before it does not backfill over it. Writes of one key through one Cache apply one at a time, in the same order on every layer. If a layer fails, the key is dropped from that layer and every layer above it (what the layers below hold was written), and the error is returned.
Set waits while another write of a key in the same stripe is in progress; if ctx ends first it returns ctx's error, writes nothing, and drops the key from every layer once the stripe is free, since the caller may have changed the source already (with a broadcast, it publishes the key again then).
func (*Cache[T]) SetMany ¶
SetMany is Set for many keys, with one call per layer. A key that fails in a layer is dropped from that layer and those above and listed in the returned *BatchError; the other keys are written. An error that is not a *BatchError means nothing was written (ctx ended while waiting).
type Codec ¶
Codec turns values into bytes and back, for backends that store bytes.
func DefaultCodec ¶
DefaultCodec stores []byte and string values as they are, values whose T implements encoding.BinaryMarshaler (and *T BinaryUnmarshaler) as they marshal themselves, and anything else as JSON.
type Entry ¶
type Entry[T any] struct { Value T NotFound bool // the source does not have the key; Value is the zero value // CachedAt is when the source answered; an entry copied from a lower layer // keeps it. CachedAt time.Time // FreshUntil is when the entry turns stale: still served (and refreshed in // the background) until ExpiresAt, if the layer has a stale TTL. FreshUntil time.Time // ExpiresAt is when the entry is rotten: never served again. A backend may // drop it from then on. ExpiresAt time.Time }
Entry is what a layer stores for one key: a value, or a record that the source does not have the key, and when it stops being fresh and usable. The Cache computes every field and never serves an entry past ExpiresAt; a backend stores it as given and may drop it from then on (rediscachex and ottercachex expire it natively).
type Layer ¶
type Layer[T any] struct { // contains filtered or unexported fields }
Layer is one level of a Cache: a backend and how long its entries stay fresh and usable. Build it with NewLayer.
type LayerOption ¶
type LayerOption func(*layerConfig)
LayerOption configures a Layer.
func Jitter ¶
func Jitter(ratio float64) LayerOption
Jitter shortens each entry's fresh period by a random part of up to ratio (in [0, 1), default DefaultJitter), so entries written together do not all turn stale or rotten at the same moment. It never lengthens one.
func NotFoundTTL ¶
func NotFoundTTL(fresh, stale time.Duration) LayerOption
NotFoundTTL is TTL for the answer that a key does not exist. With a zero fresh (the default) the layer does not record such answers.
func TTL ¶
func TTL(fresh, stale time.Duration) LayerOption
TTL sets how long a value stays fresh and, after that, how long it is still served stale while being refreshed in the background (zero: not at all). Both count from when an entry is written into the layer (an answer of the source, a copy from a layer below, a Set); a copy is never fresher or longer lived than the entry it came from. Required, with a positive fresh; fresh plus stale is at most 100 years.
type Leaser ¶
type Leaser[T any] interface { // Lease takes a lease, for ttl, on each of keys that nobody leases, and // returns a token for each lease it took. A key leased by someone else is // left out; a key that failed, or that the backend cannot lease (one it // cannot store, say), is left out and reported in the error. Lease(ctx context.Context, keys []string, ttl time.Duration) (map[string]string, error) // PutLeased writes, for each key of tokens whose lease still holds its // token, the key's entry in entries, or deletes the key if it has none, and // ends its lease. A key whose lease has ended or holds another token is // left alone, without an error. PutLeased(ctx context.Context, tokens map[string]string, entries map[string]Entry[T]) error // Release ends, for each key of tokens, its lease if it still holds the // token, and writes nothing. Release(ctx context.Context, tokens map[string]string) error }
Leaser keeps an old answer out of a layer that several instances share. A fetch leases the keys it misses in the layer, before it reads further down; a write of a key (Set, SetMany, Del, DelMany on the backend) ends its lease; and the fetch backfills the layer only with the keys whose lease it still holds. So an answer read before another instance's write is never written over it. A Cache never waits for a lease another instance holds: it fetches the key anyway, without backfilling that layer.
Like Backend's Many methods, its methods are best effort: a *BatchError returned as is fails only the keys it lists; any other error fails every key.
type Leasing ¶
Leasing is a Backend that can lease its keys. Its Leaser returns nil when leases are off; when they are on, every write of a key ends its lease. Wrappers of a backend forward it.
type LocalBackend ¶
LocalBackend is a Backend whose entries live in this process only, such as one in memory: a write on another instance never reaches it through a shared layer. Its layers are the ones a broadcast invalidates (see WithBroadcast), and Clear drops all of their entries when a broadcast may have been missed. A backend shared by instances must not implement it.
type Option ¶
type Option func(*options)
Option configures a Cache.
func WithBroadcast ¶
WithBroadcast makes the Cache share its writes with the other instances over b: after a write, it publishes the keys it wrote, and an instance that receives them drops them from its local layers (those whose backend is a LocalBackend), through the write-order guard as a write of its own would. The shared layers were written by the writer. Each time b subscribes, the Cache clears its local layers, as a message may have been lost. A Cache with a broadcast needs a local layer. A publish that fails is tried again twice; if it still fails it is logged as an error, not returned (the layers were written), and the other instances serve what their local layers hold of those keys until it stops being fresh there.
func WithFetchTimeout ¶
WithFetchTimeout bounds, each on its own: a fetch's double check, each lower layer read together with the backfill of what it found, each source call together with the backfill of its answers, taking and releasing leases (a lease lasts two of it), the invalidation after a failed write, a broadcast's publish of each message, a received invalidation, and the clear after subscribing again. Default DefaultFetchTimeout.
func WithGetManyChunkSize ¶
WithGetManyChunkSize splits the keys one GetMany fetches (and a background refresh of many keys) into chunks of at most size keys. A chunk is claimed when it starts, read from each layer below the first in one call, and sent to the source in one call (a BatchSource) or as a Get per key; its answers are returned and backfilled as soon as they arrive. The keys of a chunk not started yet are not claimed: a Get of one of them fetches it at once instead of waiting for the GetMany, and if the GetMany's ctx ends they are not fetched at all. Smaller chunks cost more calls to the lower layers. Zero (the default) makes all the keys one chunk.
func WithGetManyConcurrency ¶
WithGetManyConcurrency sets how many source requests one GetMany has in flight at once: Get calls if the source is not a BatchSource, chunk calls otherwise. A chunk (see WithGetManyChunkSize) starts only when the source has room for its requests. Default DefaultGetManyConcurrency.
func WithLogger ¶
WithLogger sets the logger for failures that do not fail a call (a failed backfill, invalidation or background refresh) and for panics in fetches. Default slog.Default().
func WithMaxAge ¶
WithMaxAge caps how long a value from the source is kept, in every layer: maxAge is called once when the value is fetched, and the entry is never served after that much time (zero or less: the value is not cached). Use it for values that expire on their own, such as tokens. Set and SetMany call it too, for the values they write. Its argument type must be the Cache's T, or New panics.
type SingleBackend ¶
type SingleBackend[T any] interface { Get(ctx context.Context, key string) (Entry[T], bool, error) Set(ctx context.Context, key string, entry Entry[T]) error Del(ctx context.Context, key string) error }
SingleBackend is a Backend without the Many methods; see Batched.
type SliceGetter ¶
type SliceGetter[T any] interface { GetInto(ctx context.Context, keys []string, entries []Entry[T], found []bool) error }
SliceGetter is an optional Backend method for the first layer: GetInto reads keys into entries and found (both as long as keys), entries[i] and found[i] being what Get returns for keys[i], with errors as GetMany's. A GetMany of the Cache uses it instead of the backend's GetMany: that map allocates once per entry when Entry[T] is over 128 bytes (a value type of over 48 bytes, say), as Go maps hold larger values out of line. A wrapper that embeds a backend having GetInto and overrides GetMany must override GetInto too (or embed the Backend interface), or reads bypass its GetMany.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package bigcachex is an in-memory cachex backend that stores entries as bytes in a BigCache, out of reach of the garbage collector: worth it when the memory layer holds millions of values and GC shows in profiles, at the cost of decoding on every read.
|
Package bigcachex is an in-memory cachex backend that stores entries as bytes in a BigCache, out of reach of the garbage collector: worth it when the memory layer holds millions of values and GC shows in profiles, at the cost of decoding on every read. |
|
Package cachextest has helpers for testing code that uses cachex: an in-memory Backend (with leases, NewLeasingMap), an in-memory broadcast (NewBus), a manual clock, and the contract tests for Backend, ByteBackend, Leaser and Broadcast implementations (TestBackend, TestByteBackend, TestLeaser, TestBroadcast).
|
Package cachextest has helpers for testing code that uses cachex: an in-memory Backend (with leases, NewLeasingMap), an in-memory broadcast (NewBus), a manual clock, and the contract tests for Backend, ByteBackend, Leaser and Broadcast implementations (TestBackend, TestByteBackend, TestLeaser, TestBroadcast). |
|
Package gobuscachex is the cachex invalidation broadcast over go-bus (github.com/qor5/go-bus), a publish-subscribe bus on PostgreSQL, which it needs: it is for deployments on PostgreSQL that have no Redis (with MySQL, use rediscachex.NewBroadcast).
|
Package gobuscachex is the cachex invalidation broadcast over go-bus (github.com/qor5/go-bus), a publish-subscribe bus on PostgreSQL, which it needs: it is for deployments on PostgreSQL that have no Redis (with MySQL, use rediscachex.NewBroadcast). |
|
Package goquecachex runs a cache's cleanup (gormcachex's DeleteExpired) as a recurring job on go-que (github.com/qor5/go-que), on one instance at a time however many run it.
|
Package goquecachex runs a cache's cleanup (gormcachex's DeleteExpired) as a recurring job on go-que (github.com/qor5/go-que), on one instance at a time however many run it. |
|
Package gormcachex is a cachex backend on a database table through GORM: one row per key, the entry encoded in the value column.
|
Package gormcachex is a cachex backend on a database table through GORM: one row per key, the entry encoded in the value column. |
|
internal
|
|
|
flight
Package flight is a singleflight whose Claim answers at once whether the caller now leads the fetch of a key.
|
Package flight is a singleflight whose Claim answers at once whether the caller now leads the fetch of a key. |
|
stripe
Package stripe orders the writes and backfills of keys without a lock per key: keys hash into a fixed number of stripes, each with a read-write lock and two counters.
|
Package stripe orders the writes and backfills of keys without a lock per key: keys hash into a fixed number of stripes, each with a read-write lock and two counters. |
|
Package ottercachex is an in-memory cachex backend built on otter: bounded by entry count or weight, and each entry expires at its own ExpiresAt.
|
Package ottercachex is an in-memory cachex backend built on otter: bounded by entry count or weight, and each entry expires at its own ExpiresAt. |
|
Package rediscachex is a cachex backend on Redis (or Redis Cluster): each entry is one string key, expiring natively at the entry's ExpiresAt.
|
Package rediscachex is a cachex backend on Redis (or Redis Cluster): each entry is one string key, expiring natively at the entry's ExpiresAt. |