cache

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 12 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.

README

cache

cache provides typed, composable caches for Go: one generic storage contract with in-process, on-disk and remote backends, layered stores with promotion, pull-through loading with single flight and negative caching, renewable distributed fill leases, and transport-neutral invalidation between processes. It is for Go services and tools that want caching without hand-rolling stampede protection, expiry handling and cross-process invalidation for each storage technology. Cached data is assumed to be reconstructible and disposable; correctness-critical state belongs in a durable system of record.

Features

  • Typed Cache[K, V] and Store[K, V] contracts with namespaces, default and per-write TTLs, negative entries and explicit never-expiring entries (NoExpiry).
  • Batch reads, writes and invalidations (BatchCache, BatchStore), one round trip or transaction where the backend supports it.
  • LayeredStore: fastest-to-slowest layers with promotion that preserves expiration, fail-open or strict reads, and an Observer hook.
  • PullThroughCache: per-key single flight with waiter-scoped cancellation, negative caching, loader-panic recovery, and optional distributed fill leases.
  • Distributed invalidation through any InvalidationBus, with adapters for messaging and distributed-coordination.
  • Backends: bounded in-process LRU, bbolt file with ordered prefix scans, Redis, Valkey, Dragonfly, Memcached, Hazelcast and PostgreSQL.
  • cachetest: public conformance suites for your own stores and invalidation buses.

Installation

go get github.com/justusschock/cache@latest

Requires Go 1.25 or newer. The root package and every backend are one module; an application compiles only the backend packages it imports.

Quick start

This is the package Example in example_test.go:

package main

import (
	"context"
	"fmt"
	"time"

	cache "github.com/justusschock/cache"
	"github.com/justusschock/cache/backend/memory"
)

type User struct {
	ID   string
	Name string
}

func main() {
	store := memory.New[string, User]()
	defer func() { _ = store.Close() }()

	users, err := cache.New("users", 5*time.Minute, store)
	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	if err := users.Set(ctx, "user-42", User{ID: "user-42", Name: "Ada"}); err != nil {
		panic(err)
	}
	user, found, err := users.Get(ctx, "user-42")
	if err != nil {
		panic(err)
	}
	fmt.Println(found, user.Name) // true Ada
}

memory.New is bounded to 10,000 live entries and sweeps expired entries once per minute; memory.NewWithOptions sets both limits. The store uses one least-recently-used order across namespaces. Every memory store must be closed, because construction starts the sweeper goroutine.

store, err := memory.NewWithOptions[string, User](memory.Options{
	MaxEntries:      50_000,
	CleanupInterval: 15 * time.Second,
})
Entries without expiration

TTLs must be positive, with one explicit opt-in: cache.NoExpiry. Passed to New, it makes Set and SetMany write entries that never expire; passed to SetWithTTL or SetManyWithTTL, it does the same for one write. Any other zero or negative TTL is rejected with ErrInvalidTTL.

hashes, err := cache.New("file-hashes", cache.NoExpiry, store)
err = hashes.Set(ctx, "src/main.go", digest)

// Or keep a default TTL and opt out per write:
err = sessions.SetWithTTL(ctx, "pinned", session, cache.NoExpiry)

A never-expiring entry has a zero Entry.ExpiresAt (Entry.NeverExpires). Backends keep it until it is invalidated, replaced or evicted by the backend's own capacity policy: memory never sweeps it, Redis, Valkey, Dragonfly and Hazelcast write it without a native TTL, Memcached uses expiration 0, and PostgreSQL stores expires_at = 'infinity'.

Batch operations

StandardCache implements BatchCache: GetMany, SetMany, SetManyWithTTL and InvalidateMany. Results are aligned with the key slice, value slices must have the same length (ErrBatchLength otherwise), and a later duplicate key wins.

digests, found, err := hashes.GetMany(ctx, []string{"src/a.go", "src/b.go"})
err = hashes.SetMany(ctx, changedPaths, changedDigests)

When the store implements BatchStore, each call is one store call; otherwise the cache falls back to one call per key and stops at the first error. The disk store applies a batch in one bbolt transaction (atomic, one commit); the memory store under one lock; Redis, Valkey and Dragonfly in one pipeline, which is not a transaction, so a failed call can leave part of a batch applied.

Layered caches

Stores are ordered from fastest to slowest. A lower-layer hit is promoted into every faster layer that missed, without changing its expiration. Writes go to the slowest layer first.

layers, err := cache.NewLayered([]cache.Store[string, User]{local, shared})
users, err := cache.New("users", 5*time.Minute, layers)

Reads fail open by default: a failing layer is reported to the optional Observer (cache.WithLayerObserver) and lookup continues below it; cache.WithStrictLayerReads() makes the first layer error terminal. A slowest-layer write failure stops the write; faster-layer failures are joined.

Pull-through loading

NewPullThrough loads misses with one shared load per key. Each caller waits with its own context, so canceling one waiter does not cancel a load other callers need; when the last waiter leaves, the load is canceled and a later request starts afresh. Loader errors are never cached.

loaded, err := cache.NewPullThrough(
	"users",
	users,
	func(ctx context.Context, id string) (User, bool, error) {
		return database.FindUser(ctx, id)
	},
	cache.WithNegativeTTL[string](30*time.Second),
)
user, found, err := loaded.Get(ctx, "user-42")

Authoritative misses (found == false) are stored as negative entries only when the wrapped cache implements EntryCache, as StandardCache does.

For cross-process fill coordination, pass a Locker: a backend locker, or any distributed-coordination backend through NewCoordinationLocker.

locker, err := cache.NewCoordinationLocker(
	coordinationBackend,
	"worker-7",
	func(namespace, key string) (string, error) {
		encoded, err := json.Marshal([2]string{namespace, key})
		return string(encoded), err
	},
)
loaded, err := cache.NewPullThrough("users", users, loadUser,
	cache.WithLocker[string](locker, 10*time.Second))

The FillKeyFunc must be deterministic and injective over the whole (namespace, key) tuple; concatenating with a delimiter is unsafe when either part may contain it. Leases are refreshed every half TTL. Observed lease loss or a failed refresh cancels the loader, waits for it, skips the cache write if it has not started, and returns ErrFillLeaseLost; the lease is released on a non-canceled context. Loaders and caches used with leases must honour cancellation. Leases reduce duplicate fills; they do not fence writes.

Distributed invalidation

A LayeredStore built with NewLayeredWithInvalidationBus publishes a key-scoped event for Set and Invalidate and a namespace-scoped event for InvalidateAll. ListenInvalidations applies remote events by evicting only the layers above the shared layer, so duplicate and out-of-order delivery is safe. InvalidationEvent.Generation is transport metadata, not an ordering.

bus, err := cache.NewMessagingInvalidationBus[string](publisher, subscriber,
	func(namespace string) messaging.Subscription {
		return messaging.Subscription{
			Subject:     "cache.invalidations." + namespace,
			Consumer:    "worker-7",
			Semantics:   messaging.AtLeastOnce,
			MaxInFlight: 32,
		}
	})
layers, err := cache.NewLayeredWithInvalidationBus(
	[]cache.Store[string, User]{local, shared}, bus)

go func() { _ = layers.ListenInvalidations(listenCtx, "users", 1) }()

The subscription factory is also the source of the publish subject, so it must return a stable subject per namespace. Handled deliveries and deliveries for another namespace are acknowledged; handler failures are negatively acknowledged for at-least-once redelivery.

Disk prefix scans

The bbolt store hashes keys by default. disk.WithOrderedKeys stores the key codec's bytes verbatim, which keeps entries in encoded-key order and enables ScanPrefix and DeletePrefix:

store, err := disk.Open[string, string](
	filepath.Join(stateDir, "hashes.db"),
	disk.WithOrderedKeys[string, string](),
)
defer store.Close()

err = store.ScanPrefix(ctx, "file-hashes", []byte("src/"),
	func(path string, entry cache.Entry[string]) bool {
		fmt.Println(path, entry.Value)
		return true // false stops the scan
	})
removed, err := store.DeletePrefix(ctx, "file-hashes", []byte("vendor/"))

The prefix is matched against encoded key bytes: strings and []byte encode to themselves, integers to decimal text (lexicographic order), composite keys to JSON; use disk.WithKeyCodec for another ordering. ScanPrefix runs in one read transaction and its callback must not write to the same store. Without ordered keys both return disk.ErrOrderedKeysRequired. Ordered and hashed layouts are separate; always reopen a file with the same choice.

Packages

Package Purpose
github.com/justusschock/cache Contracts (Store, Cache, Locker, InvalidationBus), StandardCache, LayeredStore, PullThroughCache, codecs and adapters
backend/memory Bounded in-process LRU store, locker and invalidation bus
backend/disk Persistent bbolt store with atomic batches and prefix scans
backend/redis Redis store, locker and Pub/Sub invalidation bus
backend/valkey Valkey store, locker and Pub/Sub invalidation bus
backend/dragonfly Dragonfly store, locker and invalidation bus (Redis protocol)
backend/memcached Memcached store and locker
backend/hazelcast Hazelcast map store and topic invalidation bus
backend/postgres PostgreSQL store, row-lease locker and LISTEN/NOTIFY invalidation bus
cachetest Conformance suites for Store, BatchStore and InvalidationBus implementations

Packages under internal/ are not part of the API.

Backend Store BatchStore Locker Invalidation bus
backend/memory yes yes (one lock) yes yes (in-process)
backend/disk yes yes (one transaction) no no
backend/redis yes yes (pipelined) yes yes
backend/valkey yes yes (pipelined) yes yes
backend/dragonfly yes yes (pipelined) yes yes
backend/memcached yes no yes no
backend/hazelcast yes no no yes
backend/postgres yes no yes yes

To test your own implementation:

func TestStoreContract(t *testing.T) {
	cachetest.RunStoreContract(t, func(t *testing.T) cache.Store[string, int] {
		return mybackend.New[string, int](client)
	})
}

Design and guarantees

Concurrency. Every exported type is safe for concurrent use. Operations that block or perform I/O take a context.Context first and honour cancellation. Remote clients and pools are caller-owned: stores, lockers and buses never close them. The memory and disk stores own resources and must be closed; Close is idempotent.

Expiry. Entry.ExpiresAt is the logical expiration and is enforced on read by every store; native TTLs are used only to reclaim space. PostgreSQL uses the server clock and offers Migrate (idempotent schema creation) and DeleteExpired (physical cleanup of entries and locks). Memcached rounds TTLs up to whole seconds; leases whose expiry exceeds its signed 32-bit Unix range are rejected. Hazelcast has no Locker, because its map API cannot atomically verify a lease token and extend that value's TTL.

Errors. Sentinel errors (for example ErrInvalidTTL, ErrNilStore, ErrBatchLength, ErrLockNotAcquired, ErrLeaseLost, ErrFillLeaseLost, ErrLoaderPanic) support errors.Is; underlying errors are wrapped with %w, and operations on several layers join their errors. Nil and typed-nil dependencies are rejected at construction. The library never logs; layered fail-open errors reach the optional Observer, whose events contain no keys or values.

Keys, values and schema. The memory backend compares keys with Go ==; serialized backends compare the bytes produced by the key codec, so two pointers to equal values are distinct memory keys but the same default JSON key. Values are not copied: the memory backend returns reference-bearing values by reference, so treat cached values as immutable. The namespace, key and value types and codecs, and the entry envelope together form a shared schema; change it with a new namespace or an explicit migration. The DefaultCodec encodes strings, byte slices, booleans and numbers directly and other values as JSON; interface types need a custom codec.

Wire formats. Serialized backends write a versioned entry envelope (version 2; version 1 is still read) and a versioned invalidation message. Format changes are rolled out reader-first: every process that reads a shared namespace must understand a new version before any process writes it.

Non-goals. cache is not a correctness-critical database and offers no write-through persistence or transactions across keys, no strong coherence or exactly-once invalidation, no fenced writes after lease loss, and no connection management or provisioning.

Stability. The module is at v0.x: minor releases may break the API. Every break is listed in CHANGELOG.md and backed by an ADR.

Documentation

Contributing

Contributions are welcome through pull requests; nothing is pushed to main directly. Read AGENTS.md first: it describes the docs-first process, the API and testing rules, and the checks to run before opening a pull request.

License

Apache License 2.0. See LICENSE and NOTICE.

Documentation

Overview

Package cache provides typed, composable caches.

A StandardCache applies a namespace and a default TTL to a Store, the storage contract implemented by the backend packages under backend/ (an in-process LRU, a bbolt file, Redis, Valkey, Dragonfly, Memcached, Hazelcast and PostgreSQL). Stores compose: LayeredStore stacks stores from fastest to slowest with read promotion and optional distributed invalidation through an InvalidationBus, and PullThroughCache loads misses with per-key single flight, negative caching and optional distributed fill leases from a Locker.

Entries are typed (Entry) and carry a logical expiration; a zero expiration, requested with NoExpiry, never expires. Persistent backends serialize keys and values with a Codec; DefaultCodec covers strings, byte slices, scalars and JSON-compatible values.

Cached data is assumed to be reconstructible and disposable. Fill leases reduce duplicate work but do not fence writes, and invalidation delivery is at-least-once without ordering guarantees.

All exported types are safe for concurrent use unless their documentation says otherwise. Operations that block or perform I/O take a context.Context and honour its cancellation.

Example
package main

import (
	"context"
	"fmt"
	"time"

	cache "github.com/justusschock/cache"
	"github.com/justusschock/cache/backend/memory"
)

type User struct {
	ID   string
	Name string
}

func main() {
	store := memory.New[string, User]()
	defer func() { _ = store.Close() }()

	users, err := cache.New("users", 5*time.Minute, store)
	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	if err := users.Set(ctx, "user-42", User{ID: "user-42", Name: "Ada"}); err != nil {
		panic(err)
	}
	user, found, err := users.Get(ctx, "user-42")
	if err != nil {
		panic(err)
	}
	fmt.Println(found, user.Name)
}
Output:
true Ada

Index

Examples

Constants

NoExpiry is the explicit opt-in TTL for entries that never expire. New and SetWithTTL accept it in place of a positive duration; the resulting entries carry a zero ExpiresAt and remain until they are invalidated or evicted by the store. Every other non-positive TTL is still rejected with ErrInvalidTTL.

Variables

View Source
var (
	// ErrEmptyNamespace reports an empty cache namespace.
	ErrEmptyNamespace = errors.New("cache: namespace must not be empty")
	// ErrInvalidTTL reports a non-positive TTL other than NoExpiry, or an
	// entry that is already expired.
	ErrInvalidTTL = errors.New("cache: ttl must be positive")
	// ErrNilStore reports a nil or typed-nil store.
	ErrNilStore = errors.New("cache: store must not be nil")
)
View Source
var (
	ErrNilCoordinationBackend = errors.New("cache: coordination backend must not be nil")
	ErrEmptyCoordinationOwner = errors.New("cache: coordination owner must not be empty")
	ErrNilFillKeyFunc         = errors.New("cache: fill key function must not be nil")
	ErrNilCoordinationLease   = errors.New("cache: coordination backend returned a nil lease")
)

Errors returned by NewCoordinationLocker and CoordinationLocker.Lock.

View Source
var (
	ErrNoLayers          = errors.New("cache: at least one layer is required")
	ErrNoInvalidationBus = errors.New("cache: no invalidation bus configured")
	ErrInvalidLowerLayer = errors.New("cache: lower layer must have at least one upper layer")
)

Errors returned by layered-store constructors and ListenInvalidations.

View Source
var (
	ErrLockNotAcquired = errors.New("cache: lock not acquired")
	ErrLeaseLost       = errors.New("cache: lease is no longer owned")
	ErrFillLeaseLost   = errors.New("cache: fill lease lost")
	ErrNilLease        = errors.New("cache: locker returned a nil lease")
)

Errors reported by lockers, leases and lease-guarded fills.

View Source
var (
	ErrNilMessagingPublisher  = errors.New("cache: messaging publisher must not be nil")
	ErrNilMessagingSubscriber = errors.New("cache: messaging subscriber must not be nil")
	ErrNilSubscriptionFactory = errors.New("cache: subscription factory must not be nil")
)

Errors returned by NewMessagingInvalidationBus.

View Source
var (
	ErrNilCache    = errors.New("cache: wrapped cache must not be nil")
	ErrNilLoader   = errors.New("cache: loader must not be nil")
	ErrNilLocker   = errors.New("cache: locker must not be nil")
	ErrLoaderPanic = errors.New("cache: loader panicked")
)

Errors returned by NewPullThrough and PullThroughCache.Get.

View Source
var ErrBatchLength = errors.New("cache: batch keys and values must have equal length")

ErrBatchLength reports batch arguments whose key and value slices differ in length.

View Source
var ErrNilInvalidationHandler = errors.New("cache: invalidation handler must not be nil")

ErrNilInvalidationHandler reports a nil handler passed to InvalidationBus.Subscribe.

View Source
var ErrUntypedValue = errors.New("cache: decoding an interface value requires a custom codec")

ErrUntypedValue reports a DefaultCodec decode into an interface type, whose concrete type cannot be recovered from the encoded bytes.

Functions

This section is empty.

Types

type BatchCache

type BatchCache[K comparable, V any] interface {
	Cache[K, V]
	GetMany(context.Context, []K) ([]V, []bool, error)
	SetMany(context.Context, []K, []V) error
	SetManyWithTTL(context.Context, []K, []V, time.Duration) error
	InvalidateMany(context.Context, []K) error
}

BatchCache is an optional Cache extension for multi-key operations. Results are positionally aligned with keys, and value slices must match the key slice length.

type BatchStore

type BatchStore[K comparable, V any] interface {
	Store[K, V]
	GetMany(context.Context, string, []K) ([]Entry[V], []bool, error)
	SetMany(context.Context, string, []K, []Entry[V]) error
	InvalidateMany(context.Context, string, []K) error
}

BatchStore is an optional Store extension for multi-key operations.

GetMany returns entries and presence flags positionally aligned with keys, applying the same visibility rules as Get. SetMany writes entries[i] under keys[i], returns ErrBatchLength when the slices differ in length, and lets a later duplicate key win. InvalidateMany removes every listed key and is idempotent for missing keys. Atomicity is backend-specific: unless an implementation documents otherwise, a failed call may have applied part of the batch.

type Cache

type Cache[K comparable, V any] interface {
	Get(context.Context, K) (V, bool, error)
	Set(context.Context, K, V) error
	SetWithTTL(context.Context, K, V, time.Duration) error
	Invalidate(context.Context, K) error
	InvalidateAll(context.Context) error
}

Cache is the typed cache API exposed to callers.

type Codec

type Codec[T any] interface {
	Encode(T) ([]byte, error)
	Decode([]byte) (T, error)
}

Codec converts a typed value to and from bytes for persistent stores.

func DefaultCodec

func DefaultCodec[T any]() Codec[T]

DefaultCodec returns the automatic codec for T. Strings, byte slices, and scalar values use direct encodings; composite values use JSON. Encoded key identity is defined by the resulting bytes, so pointer keys encode their pointed-to value rather than their in-process pointer identity.

type CoordinationLocker

type CoordinationLocker[K comparable] struct {
	// contains filtered or unexported fields
}

CoordinationLocker is a Locker backed by any distributed-coordination Backend. Its leases implement ObservableLease. It is safe for concurrent use if the backend is.

func NewCoordinationLocker

func NewCoordinationLocker[K comparable](
	backend coordination.Backend,
	owner string,
	key FillKeyFunc[K],
) (*CoordinationLocker[K], error)

NewCoordinationLocker adapts backend into a Locker that acquires leases as owner under keys derived by key. It returns ErrNilCoordinationBackend, ErrEmptyCoordinationOwner or ErrNilFillKeyFunc for missing dependencies.

func (*CoordinationLocker[K]) Lock

func (l *CoordinationLocker[K]) Lock(
	ctx context.Context,
	namespace string,
	key K,
	ttl time.Duration,
) (Lease, error)

Lock acquires a lease for the fill key of (namespace, key), waiting as the backend's Acquire with Wait set does. Contention is reported as ErrLockNotAcquired and a lost or foreign lease as ErrLeaseLost, each joined with the backend error.

type Entry

type Entry[V any] struct {
	Value     V
	Found     bool
	ExpiresAt time.Time
}

Entry is the value and logical freshness metadata exchanged with stores. Found is false for an authoritative negative-cache entry. A zero ExpiresAt marks an entry that never expires; stores must neither hide it as expired nor attach a backend-native TTL to it.

func (Entry[V]) Expired

func (e Entry[V]) Expired(now time.Time) bool

Expired reports whether the entry is logically expired at now. Entries without an expiration are never expired.

func (Entry[V]) NeverExpires

func (e Entry[V]) NeverExpires() bool

NeverExpires reports whether the entry has no expiration (zero ExpiresAt).

type EntryCache

type EntryCache[K comparable, V any] interface {
	Cache[K, V]
	GetEntry(context.Context, K) (Entry[V], bool, error)
	SetEntry(context.Context, K, Entry[V]) error
}

EntryCache is an optional Cache extension that exposes stored entries, including negative entries and their expiration.

type Event

type Event struct {
	Operation string
	Namespace string
	Layer     int
	Err       error
}

Event describes a non-fatal layered-cache failure without exposing keys or values.

type FillKeyFunc

type FillKeyFunc[K comparable] func(namespace string, key K) (string, error)

FillKeyFunc derives the coordination lease key for a cache key. It must be deterministic and injective over the complete (namespace, key) tuple and stable across deployments, or different keys may share one lease.

type InvalidationBus

type InvalidationBus[K comparable] interface {
	Publish(context.Context, InvalidationEvent[K]) error
	Subscribe(context.Context, string, InvalidationHandler[K]) error
}

InvalidationBus publishes and subscribes to cache invalidation events.

type InvalidationEvent

type InvalidationEvent[K comparable] struct {
	Namespace  string
	Kind       InvalidationKind
	Key        K
	Generation uint64
}

InvalidationEvent is sent between cache workers after a mutation.

type InvalidationHandler

type InvalidationHandler[K comparable] func(context.Context, InvalidationEvent[K]) error

InvalidationHandler applies a remotely published invalidation event.

type InvalidationKind

type InvalidationKind uint8

InvalidationKind identifies the scope of an invalidation event.

const (
	// InvalidateKey invalidates one key in a namespace.
	InvalidateKey InvalidationKind = iota + 1
	// InvalidateNamespace invalidates every key in a namespace.
	InvalidateNamespace
)

type LayeredOption

type LayeredOption func(*layeredConfig)

LayeredOption configures layered-store behavior.

func WithLayerObserver

func WithLayerObserver(observer Observer) LayeredOption

WithLayerObserver reports errors skipped by fail-open reads and promotions.

func WithStrictLayerReads

func WithStrictLayerReads() LayeredOption

WithStrictLayerReads makes the first read error abort the lookup.

type LayeredStore

type LayeredStore[K comparable, V any] struct {
	// contains filtered or unexported fields
}

LayeredStore composes stores ordered from fastest to slowest.

func NewLayered

func NewLayered[K comparable, V any](layers []Store[K, V], options ...LayeredOption) (*LayeredStore[K, V], error)

NewLayered constructs a store from a fastest-to-slowest layer list.

Example
package main

import (
	"context"
	"fmt"

	cache "github.com/justusschock/cache"
	"github.com/justusschock/cache/backend/memory"
)

type User struct {
	ID   string
	Name string
}

func main() {
	fast := memory.New[string, User]()
	defer func() { _ = fast.Close() }()
	shared := memory.New[string, User]()
	defer func() { _ = shared.Close() }()

	layers, err := cache.NewLayered([]cache.Store[string, User]{fast, shared})
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	entry := cache.Entry[User]{Value: User{ID: "user-42", Name: "Ada"}, Found: true}
	if err := shared.Set(ctx, "users", "user-42", entry); err != nil {
		panic(err)
	}

	// A lower-layer hit is promoted into the faster layer.
	if _, _, err := layers.Get(ctx, "users", "user-42"); err != nil {
		panic(err)
	}
	promoted, present, err := fast.Get(ctx, "users", "user-42")
	if err != nil {
		panic(err)
	}
	fmt.Println(present, promoted.Value.Name)
}
Output:
true Ada

func NewLayeredWithInvalidationBus

func NewLayeredWithInvalidationBus[K comparable, V any](layers []Store[K, V], bus InvalidationBus[K], options ...LayeredOption) (*LayeredStore[K, V], error)

NewLayeredWithInvalidationBus constructs a layered store that publishes invalidations.

func (*LayeredStore[K, V]) Get

func (s *LayeredStore[K, V]) Get(ctx context.Context, namespace string, key K) (Entry[V], bool, error)

Get reads layers from fastest to slowest and returns the first entry found, promoting it unchanged into every faster layer that missed. A layer error is reported to the Observer and treated as a miss, unless WithStrictLayerReads is set, in which case it is returned.

func (*LayeredStore[K, V]) Invalidate

func (s *LayeredStore[K, V]) Invalidate(ctx context.Context, namespace string, key K) error

Invalidate removes key from every layer, joining the errors, and publishes a key-scoped event when an invalidation bus is configured.

func (*LayeredStore[K, V]) InvalidateAll

func (s *LayeredStore[K, V]) InvalidateAll(ctx context.Context, namespace string) error

InvalidateAll removes namespace from every layer, joining the errors, and publishes a namespace-scoped event when an invalidation bus is configured.

func (*LayeredStore[K, V]) ListenInvalidations

func (s *LayeredStore[K, V]) ListenInvalidations(ctx context.Context, namespace string, lowerLayer int) error

ListenInvalidations applies bus events to layers above lowerLayer. The lower layer itself is not touched because it is the event's source of truth.

func (*LayeredStore[K, V]) Set

func (s *LayeredStore[K, V]) Set(ctx context.Context, namespace string, key K, entry Entry[V]) error

Set writes entry to the slowest layer first and then to each faster layer. A slowest-layer failure stops the write; faster-layer failures are joined. With an invalidation bus, a key-scoped event is published afterwards.

type Lease

type Lease interface {
	Refresh(context.Context, time.Duration) error
	Release(context.Context) error
}

Lease is a renewable distributed lock held by the caller.

type Loader

type Loader[K comparable, V any] func(context.Context, K) (V, bool, error)

Loader returns a value, an authoritative found state, or an error.

type Locker

type Locker[K comparable] interface {
	Lock(context.Context, string, K, time.Duration) (Lease, error)
}

Locker coordinates cache fills for one namespaced key.

type MessagingInvalidationBus

type MessagingInvalidationBus[K comparable] struct {
	// contains filtered or unexported fields
}

MessagingInvalidationBus is an InvalidationBus over typed messaging publishers and subscribers. It is safe for concurrent use if they are.

func NewMessagingInvalidationBus

func NewMessagingInvalidationBus[K comparable](
	publisher messaging.Publisher[InvalidationEvent[K]],
	subscriber messaging.Subscriber[InvalidationEvent[K]],
	factory SubscriptionFactory,
) (*MessagingInvalidationBus[K], error)

NewMessagingInvalidationBus constructs a bus that publishes to and subscribes on the subscription that factory returns for each namespace.

func (*MessagingInvalidationBus[K]) Publish

func (b *MessagingInvalidationBus[K]) Publish(ctx context.Context, event InvalidationEvent[K]) error

Publish wraps event in an envelope addressed to the subject of its namespace's subscription and publishes it.

func (*MessagingInvalidationBus[K]) Subscribe

func (b *MessagingInvalidationBus[K]) Subscribe(
	ctx context.Context,
	namespace string,
	handler InvalidationHandler[K],
) error

Subscribe follows the messaging subscriber lifetime and normally blocks until ctx ends. Handled deliveries and deliveries for another namespace are acknowledged; handler failures are negatively acknowledged so that an at-least-once transport redelivers them.

type ObservableLease

type ObservableLease interface {
	Lease
	Done() <-chan struct{}
}

ObservableLease is a Lease that reports loss of ownership by closing the channel returned by Done.

type Observer

type Observer interface {
	Observe(context.Context, Event)
}

Observer receives fail-open and promotion errors.

type PullThroughCache

type PullThroughCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

PullThroughCache loads and stores values on cache misses.

func NewPullThrough

func NewPullThrough[K comparable, V any](namespace string, wrapped Cache[K, V], loader Loader[K, V], options ...PullThroughOption[K]) (*PullThroughCache[K, V], error)

NewPullThrough wraps a cache with automatic miss loading.

Example
package main

import (
	"context"
	"fmt"
	"time"

	cache "github.com/justusschock/cache"
	"github.com/justusschock/cache/backend/memory"
)

type User struct {
	ID   string
	Name string
}

func main() {
	store := memory.New[string, User]()
	defer func() { _ = store.Close() }()
	users, err := cache.New("users", 5*time.Minute, store)
	if err != nil {
		panic(err)
	}

	loads := 0
	loaded, err := cache.NewPullThrough(
		"users",
		users,
		func(_ context.Context, id string) (User, bool, error) {
			loads++
			if id != "user-42" {
				return User{}, false, nil // authoritative miss, cached negatively
			}
			return User{ID: id, Name: "Ada"}, true, nil
		},
		cache.WithNegativeTTL[string](30*time.Second),
	)
	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	for range 2 {
		user, found, err := loaded.Get(ctx, "user-42")
		if err != nil {
			panic(err)
		}
		fmt.Println(found, user.Name)
	}
	_, found, err := loaded.Get(ctx, "user-7")
	if err != nil {
		panic(err)
	}
	fmt.Println(found, "loads:", loads)
}
Output:
true Ada
true Ada
false loads: 2

func (*PullThroughCache[K, V]) Get

func (c *PullThroughCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)

Get returns the cached value for key, loading it on a miss. Concurrent misses for one key share a single load; each caller waits with its own ctx, and the load is canceled once every waiter has left. Authoritative misses are cached for the negative TTL when the wrapped cache is an EntryCache; loader errors are never cached.

func (*PullThroughCache[K, V]) Invalidate

func (c *PullThroughCache[K, V]) Invalidate(ctx context.Context, key K) error

Invalidate delegates to the wrapped cache.

func (*PullThroughCache[K, V]) InvalidateAll

func (c *PullThroughCache[K, V]) InvalidateAll(ctx context.Context) error

InvalidateAll delegates to the wrapped cache.

func (*PullThroughCache[K, V]) Set

func (c *PullThroughCache[K, V]) Set(ctx context.Context, key K, value V) error

Set delegates to the wrapped cache.

func (*PullThroughCache[K, V]) SetWithTTL

func (c *PullThroughCache[K, V]) SetWithTTL(ctx context.Context, key K, value V, ttl time.Duration) error

SetWithTTL delegates to the wrapped cache.

type PullThroughOption

type PullThroughOption[K comparable] func(*pullThroughConfig[K]) error

PullThroughOption configures pull-through behavior.

func WithLoadOnLockError

func WithLoadOnLockError[K comparable]() PullThroughOption[K]

WithLoadOnLockError permits loading when the distributed locker fails.

func WithLockPollInterval

func WithLockPollInterval[K comparable](interval time.Duration) PullThroughOption[K]

WithLockPollInterval controls how often a contended lock is retried.

func WithLocker

func WithLocker[K comparable](locker Locker[K], leaseTTL time.Duration) PullThroughOption[K]

WithLocker enables distributed miss coordination using renewable leases.

func WithNegativeTTL

func WithNegativeTTL[K comparable](ttl time.Duration) PullThroughOption[K]

WithNegativeTTL sets the lifetime of authoritative not-found entries.

func WithStrictPullThroughReads

func WithStrictPullThroughReads[K comparable]() PullThroughOption[K]

WithStrictPullThroughReads returns cache read errors instead of loading.

type StandardCache

type StandardCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

StandardCache applies namespace and TTL policy to a Store.

func New

func New[K comparable, V any](namespace string, defaultTTL time.Duration, store Store[K, V]) (*StandardCache[K, V], error)

New constructs a cache with a required namespace and positive default TTL. Pass NoExpiry as defaultTTL to make Set and SetMany write entries that never expire.

func (*StandardCache[K, V]) Get

func (c *StandardCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)

Get returns the value cached under key and whether it was found. Missing, expired and negative entries report found as false.

func (*StandardCache[K, V]) GetEntry

func (c *StandardCache[K, V]) GetEntry(ctx context.Context, key K) (Entry[V], bool, error)

GetEntry returns the entry stored under key, including negative entries, and whether a live entry is present. Expired entries are reported absent.

func (*StandardCache[K, V]) GetMany

func (c *StandardCache[K, V]) GetMany(ctx context.Context, keys []K) ([]V, []bool, error)

GetMany looks up keys and returns values and found flags aligned with keys. Missing, expired, and negative entries report found as false. It uses a single BatchStore call when the store supports batching and otherwise falls back to one Get per key.

Example
package main

import (
	"context"
	"fmt"

	cache "github.com/justusschock/cache"
	"github.com/justusschock/cache/backend/memory"
)

func main() {
	store := memory.New[string, int]()
	defer func() { _ = store.Close() }()

	sizes, err := cache.New("file-sizes", cache.NoExpiry, store)
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	if err := sizes.SetMany(ctx, []string{"a.txt", "b.txt"}, []int{10, 20}); err != nil {
		panic(err)
	}
	values, found, err := sizes.GetMany(ctx, []string{"b.txt", "missing.txt", "a.txt"})
	if err != nil {
		panic(err)
	}
	fmt.Println(values, found)
}
Output:
[20 0 10] [true false true]

func (*StandardCache[K, V]) Invalidate

func (c *StandardCache[K, V]) Invalidate(ctx context.Context, key K) error

Invalidate removes key. Removing a missing key is not an error.

func (*StandardCache[K, V]) InvalidateAll

func (c *StandardCache[K, V]) InvalidateAll(ctx context.Context) error

InvalidateAll removes every key in the cache's namespace.

func (*StandardCache[K, V]) InvalidateMany

func (c *StandardCache[K, V]) InvalidateMany(ctx context.Context, keys []K) error

InvalidateMany removes keys. It uses a single BatchStore call when the store supports batching and otherwise falls back to one Invalidate per key, stopping at the first error.

func (*StandardCache[K, V]) Set

func (c *StandardCache[K, V]) Set(ctx context.Context, key K, value V) error

Set stores value under key with the cache's default TTL.

func (*StandardCache[K, V]) SetEntry

func (c *StandardCache[K, V]) SetEntry(ctx context.Context, key K, entry Entry[V]) error

SetEntry stores entry as-is. It rejects entries that are already expired; a zero ExpiresAt stores an entry that never expires.

func (*StandardCache[K, V]) SetMany

func (c *StandardCache[K, V]) SetMany(ctx context.Context, keys []K, values []V) error

SetMany stores values[i] under keys[i] with the default TTL.

func (*StandardCache[K, V]) SetManyWithTTL

func (c *StandardCache[K, V]) SetManyWithTTL(ctx context.Context, keys []K, values []V, ttl time.Duration) error

SetManyWithTTL stores values[i] under keys[i] for ttl, or without expiration when ttl is NoExpiry. It uses a single BatchStore call when the store supports batching and otherwise falls back to one Set per key, stopping at the first error.

func (*StandardCache[K, V]) SetWithTTL

func (c *StandardCache[K, V]) SetWithTTL(ctx context.Context, key K, value V, ttl time.Duration) error

SetWithTTL stores value for ttl, or without expiration when ttl is NoExpiry.

type Store

type Store[K comparable, V any] interface {
	Get(context.Context, string, K) (Entry[V], bool, error)
	Set(context.Context, string, K, Entry[V]) error
	Invalidate(context.Context, string, K) error
	InvalidateAll(context.Context, string) error
}

Store persists typed entries for one or more namespaces.

type SubscriptionFactory

type SubscriptionFactory func(namespace string) messaging.Subscription

SubscriptionFactory maps a namespace to the deterministic subscription used for both publishing and subscribing. In particular, Subject must be stable.

Directories

Path Synopsis
backend
disk
Package disk provides a persistent bbolt-backed cache store.
Package disk provides a persistent bbolt-backed cache store.
dragonfly
Package dragonfly provides a Dragonfly-backed cache store through its Redis protocol.
Package dragonfly provides a Dragonfly-backed cache store through its Redis protocol.
hazelcast
Package hazelcast provides a Hazelcast IMap-backed cache store.
Package hazelcast provides a Hazelcast IMap-backed cache store.
memcached
Package memcached provides a Memcached-backed cache store.
Package memcached provides a Memcached-backed cache store.
memory
Package memory provides a race-safe in-process cache store.
Package memory provides a race-safe in-process cache store.
postgres
Package postgres provides a PostgreSQL-backed cache store.
Package postgres provides a PostgreSQL-backed cache store.
redis
Package redis provides a Redis-backed cache store.
Package redis provides a Redis-backed cache store.
valkey
Package valkey provides a Valkey-backed cache store.
Package valkey provides a Valkey-backed cache store.
Package cachetest provides conformance suites for implementations of the cache store and invalidation-bus interfaces.
Package cachetest provides conformance suites for implementations of the cache store and invalidation-bus interfaces.
internal
wire
Package wire implements the persistent entry envelope and the invalidation message format shared by the serialized backends.
Package wire implements the persistent entry envelope and the invalidation message format shared by the serialized backends.

Jump to

Keyboard shortcuts

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