cache

package
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: AGPL-3.0 Imports: 8 Imported by: 0

Documentation

Overview

Package cache keeps registry answers in memory for a while, so a burst of checks on the same identifier calls an upstream once (ADR 0002).

A Cache holds at most Config.MaxEntries entries and evicts the least recently used one beyond that. A value lives for Config.TTL; an error lives for the shorter Config.NegativeTTL when Config.Negative says it is a lasting answer, such as "no such company", and is never kept otherwise. Concurrent misses on one key share a single load.

Index

Constants

View Source
const (
	DefaultMaxEntries  = 10_000
	DefaultTTL         = time.Hour
	DefaultNegativeTTL = 5 * time.Minute
)

Defaults applied by New to a zero Config field. They are choices: the registries behind a cache (RDAP, SIRENE, BODACC) change a record at most daily, and an answer such as "not found" may stop being true sooner.

Variables

View Source
var ErrInvalidConfig = errors.New("invalid cache config")

ErrInvalidConfig means New was given a Config it cannot use.

Functions

This section is empty.

Types

type Cache

type Cache[V any] struct {
	// contains filtered or unexported fields
}

Cache maps string keys to values of type V. It is safe for concurrent use. A cached V is shared by every caller: V should be a value type or treated as read-only.

func New

func New[V any](cfg Config) (*Cache[V], error)

New returns an empty Cache, or ErrInvalidConfig.

func (*Cache[V]) Get

func (c *Cache[V]) Get(ctx context.Context, key string, load func(context.Context) (V, error)) (V, error)

Get returns the answer cached for key, or calls load once for all the callers that miss on key at the same time and caches its answer.

A caller whose ctx ends stops waiting and gets ctx.Err(), but the load goes on for the others with a context that is never cancelled: load must bound its own duration, as the platform HTTP client does.

func (*Cache[V]) Len

func (c *Cache[V]) Len() int

Len returns the number of entries held, expired ones included until a lookup or an eviction drops them.

type Config

type Config struct {
	// MaxEntries is the most entries the cache holds.
	MaxEntries int

	// TTL is how long a loaded value is served.
	TTL time.Duration

	// NegativeTTL is how long an error accepted by Negative is served.
	NegativeTTL time.Duration

	// Negative reports whether a load error is a lasting answer worth
	// keeping for NegativeTTL. Nil keeps no error.
	Negative func(error) bool
}

Config configures a Cache. Every zero numeric field takes its Default value; a negative one is invalid.

Jump to

Keyboard shortcuts

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