cache

package
v1.33.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: 10 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 is a minimal key/value cache with TTL semantics and the runtime counterpart of the `nucleus createcachetable` CLI command: an in-memory backend for single-process deployments, a SQL backend wired to the table that command creates (`nucleus_cache_entries` by default) for replicas that share a database, and a registry other backends join by import — the Redis one is pkg/cache/rediscache.

The framework builds one cache per application from the `cache` block of its configuration (Open, with cache.provider selecting the backend) and hands it to modules through nucleus.CacheFrom.

Lifecycle: experimental (see docs/reference/API_CONTRACT_INVENTORY.md). The surface may still grow (GetOrSet helpers) before it freezes. The package itself links only the standard library and the framework's catalog; a backend with a client library lives in a package of its own.

Index

Constants

View Source
const (
	ProviderMemory = "memory"
	ProviderSQL    = "sql"
)

The provider names the framework builds itself. Every other name is a registered backend: "redis" registers when github.com/jcsvwinston/nucleus/pkg/cache/rediscache is imported.

View Source
const DefaultKeyPrefix = "nucleus:cache:"

DefaultKeyPrefix is the namespace a shared backend puts every key under when Config.Prefix is empty, so a cache sharing a Redis with the session store ("nucleus:sessions:") and the job queue never reads their keys.

View Source
const DefaultTableName = "nucleus_cache_entries"

DefaultTableName is the table `nucleus createcachetable` creates when no --table override is given, and the table NewSQL uses when SQLOptions.Table is empty. The CLI and this package share the constant on purpose: the command and the runtime must not drift apart.

Variables

View Source
var (
	// ErrEmptyKey is returned when a cache operation receives an empty key.
	ErrEmptyKey = errors.New("cache: key cannot be empty")
	// ErrNonPositiveTTL is returned by Set when ttl <= 0. The backing table
	// requires an expiry for every entry; an entry that must never expire
	// does not belong in a cache.
	ErrNonPositiveTTL = errors.New("cache: ttl must be greater than zero")
)

Functions

func MustRegisterProvider added in v1.32.0

func MustRegisterProvider(name string, factory Factory)

MustRegisterProvider is RegisterProvider for an init function: it panics with RegisterProvider's error.

func RegisterProvider added in v1.32.0

func RegisterProvider(name string, factory Factory) error

RegisterProvider makes a backend selectable by name in `cache.provider`. It refuses an empty name, a nil factory, a name the framework builds itself ("memory", "sql") and a name already registered: two packages claiming the same name is a build mistake, not something to resolve at run time. A backend registers from an init function of its package, the way database/sql drivers do — MustRegisterProvider is the form for that.

func RegisteredProviders added in v1.32.0

func RegisteredProviders() []string

RegisteredProviders returns every name `cache.provider` accepts in this binary — the built-in ones and the registered ones — sorted.

Types

type Cache

type Cache interface {
	Get(ctx context.Context, key string) ([]byte, bool, error)
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
}

Cache is the minimal contract both backends implement.

Get returns (value, true, nil) for a live entry and (nil, false, nil) for a missing or expired one — an expired entry is indistinguishable from an absent one on purpose. Set stores value under key for ttl; a second Set on the same key replaces the value and its expiry. Delete removes an entry; deleting an absent key is not an error.

func Open added in v1.32.0

func Open(ctx context.Context, cfg Config) (Cache, error)

Open builds the backend Config selects.

A name this project publishes and the binary does not link — "redis" without the rediscache import — is refused with the command that adds it, never replaced by the memory backend: a cache that silently stops being shared between instances is how one instance serves what another invalidated.

type Config added in v1.32.0

type Config struct {
	// Provider selects the backend: "memory" (the default when empty),
	// "sql", or the name a backend registered with RegisterProvider
	// ("redis").
	Provider string
	// URL is the address of the store a remote backend talks to — for
	// redis, cache.redis_url (or redis_url when that is empty).
	URL string
	// Prefix namespaces every key in a shared store. Empty means
	// DefaultKeyPrefix. The memory and SQL backends do not use it: the
	// first is the process's own, the second has a table of its own.
	Prefix string
	// DB and System are the database the sql provider keeps its table in
	// and the SQL system it speaks ("sqlite", "postgresql", …, the values
	// (*db.DB).System() returns). Ignored by every other provider.
	DB     *sql.DB
	System string
	// Table is the sql provider's table; empty means DefaultTableName.
	Table string
}

Config is the `cache` block of the application's configuration, resolved: what Open builds a backend from, and what a registered provider receives.

type Factory added in v1.32.0

type Factory func(ctx context.Context, cfg Config) (Cache, error)

Factory builds a backend from the resolved configuration. A factory that opens a connection checks it before returning: Open is called at boot, and an unreachable store is a boot error, not a first-request one.

type Memory

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

Memory is an in-process Cache backend. It is safe for concurrent use and suitable for single-replica deployments; replicas do NOT share it — use the SQL backend (or an external store) when running more than one server process (see docs/guides/DEPLOYMENT_GUIDE.md, shared-state table).

Expired entries are dropped lazily: Get treats them as absent and deletes them, and every sweepEvery-th Set sweeps the whole map (amortised, so a write-heavy cache does not pay O(n) per Set). There is no background janitor goroutine, so a Memory cache needs no shutdown call. Call PruneExpired from your own maintenance schedule for tighter bounds.

func NewMemory

func NewMemory() *Memory

NewMemory creates an empty in-memory cache.

func (*Memory) Delete

func (m *Memory) Delete(_ context.Context, key string) error

Delete implements Cache.

func (*Memory) Get

func (m *Memory) Get(_ context.Context, key string) ([]byte, bool, error)

Get implements Cache.

func (*Memory) PruneExpired

func (m *Memory) PruneExpired(_ context.Context) (int, error)

PruneExpired removes every expired entry and returns how many it removed.

func (*Memory) Set

func (m *Memory) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

Set implements Cache.

type SQL

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

SQL is a Cache backed by the table `nucleus createcachetable` creates. It shares state across replicas that point at the same database, which makes it the SQL-backed option in the deployment guide's shared-state table. Expiry is enforced on read (expired rows are invisible to Get) and reclaimed by PruneExpired; expired rows that are never pruned only cost storage, never correctness.

mssql and oracle support follows the exploratory posture of those CI lanes (docs/governance/CI_MATRIX.md): the statements are exercised against sqlite/postgresql/mysql in CI, and take a transactional delete+insert path on mssql/oracle instead of a native upsert.

func NewSQL

func NewSQL(db *sql.DB, opts SQLOptions) (*SQL, error)

NewSQL builds a SQL cache over db. The table (SQLOptions.Table, default DefaultTableName) must have the schema `nucleus createcachetable` creates: cache_key, value, expires_at, created_at, updated_at. NewSQL validates its inputs but does not touch the database; a missing table surfaces as an error from the first Get/Set.

func (*SQL) Delete

func (s *SQL) Delete(ctx context.Context, key string) error

Delete implements Cache.

func (*SQL) Get

func (s *SQL) Get(ctx context.Context, key string) ([]byte, bool, error)

Get implements Cache. Expired rows are filtered server-side against the database clock, so a stale replica clock cannot resurrect an entry.

func (*SQL) PruneExpired

func (s *SQL) PruneExpired(ctx context.Context) (int, error)

PruneExpired deletes every expired row and returns how many it removed. Run it from a scheduled task or cron; Get never returns expired rows, so pruning is a storage-reclamation concern, not a correctness one.

func (*SQL) Set

func (s *SQL) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set implements Cache.

type SQLOptions

type SQLOptions struct {
	// Table is the cache table name. Empty means DefaultTableName — the
	// table `nucleus createcachetable` creates. The table must already
	// exist; run the command (or ship its DDL as a migration) first.
	Table string
	// System is the SQL system the *sql.DB speaks, using the same names
	// `(*db.DB).System()` returns: "sqlite", "postgresql", "mysql",
	// "mssql", or "oracle". It selects placeholder style, upsert form,
	// and the server-side UTC now() expression.
	System string
}

SQLOptions configures NewSQL.

Directories

Path Synopsis
Package rediscache is the Redis backend of pkg/cache: entries every instance of an application pointed at the same server shares, with the expiry kept by Redis itself.
Package rediscache is the Redis backend of pkg/cache: entries every instance of an application pointed at the same server shares, with the expiry kept by Redis itself.

Jump to

Keyboard shortcuts

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