arc

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package arc provides a fixed-capacity Adaptive Replacement Cache with TTL, optional expiration jitter, cache-aside loading, and per-key duplicate-load suppression.

Index

Examples

Constants

View Source
const (
	// DefaultTTL is the lifetime assigned to ARC entries.
	DefaultTTL = 5 * time.Minute
	// DefaultCleanupInterval controls background removal of expired entries.
	DefaultCleanupInterval = time.Minute
	// DefaultTTLJitter spreads entry expiration over this maximum offset.
	DefaultTTLJitter = time.Minute
)

Variables

View Source
var (
	// ErrNilCache reports a method call that requires a constructed Cache.
	ErrNilCache = errors.New("arc: cache is nil")
	// ErrNilContext reports a nil context passed to New or a load operation.
	ErrNilContext = errors.New("arc: context must not be nil")
	// ErrEmptyName reports an empty cache name passed to New.
	ErrEmptyName = errors.New("arc: cache name must not be empty")
	// ErrInvalidCapacity reports a non-positive ARC capacity.
	ErrInvalidCapacity = errors.New("arc: capacity must be positive")
	// ErrNilLoader reports a nil Loader or MultiLoader.
	ErrNilLoader = errors.New("arc: loader must not be nil")
	// ErrNilOption reports a nil functional option passed to New.
	ErrNilOption = errors.New("arc: option must not be nil")
	// ErrNilMetrics reports a nil metrics implementation.
	ErrNilMetrics = errors.New("arc: metrics must not be nil")
	// ErrInvalidTTL reports a non-positive TTL passed to WithTTL.
	ErrInvalidTTL = errors.New("arc: ttl must be positive")
	// ErrInvalidCleanupInterval reports a non-positive cleanup interval.
	ErrInvalidCleanupInterval = errors.New("arc: cleanup interval must be positive")
	// ErrInvalidTTLJitter reports a non-positive maximum TTL jitter.
	ErrInvalidTTLJitter = errors.New("arc: ttl jitter must be positive")
	// ErrLoaderPanic reports a panic recovered from a user loader.
	ErrLoaderPanic = errors.New("arc: loader panicked")
)

Functions

This section is empty.

Types

type Cache

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

Cache is a fixed-capacity Adaptive Replacement Cache with optional TTL. Construct a Cache with New; the zero value is not usable for mutations or loads.

func New

func New[K comparable, V any](ctx context.Context, name string, capacity int, options ...Option) (*Cache[K, V], error)

New constructs a context-bound ARC cache. Canceling ctx stops only the cleanup worker; reads, writes, and explicit loads remain available.

func (*Cache[K, V]) Capacity

func (c *Cache[K, V]) Capacity() int

Capacity returns the maximum number of live ARC entries.

func (*Cache[K, V]) Contains

func (c *Cache[K, V]) Contains(key K) bool

Contains reports whether a fresh value exists without updating ARC state.

func (*Cache[K, V]) Delete

func (c *Cache[K, V]) Delete(key K)

Delete removes a key if present.

func (*Cache[K, V]) Done

func (c *Cache[K, V]) Done() <-chan struct{}

Done is closed after the constructor context stops the cleanup worker.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (V, bool)

Get returns a fresh value and updates ARC recency and frequency.

func (*Cache[K, V]) GetOrLoad

func (c *Cache[K, V]) GetOrLoad(ctx context.Context, key K, loader Loader[V]) (V, error)

GetOrLoad returns a cached value or coalesces one loader call for key.

Example
package main

import (
	"context"
	"fmt"

	"github.com/assurrussa/gocache/arc"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	cache, err := arc.New[string, int](ctx, "scores", 128, arc.WithoutPeriodicCleanup())
	if err != nil {
		panic(err)
	}
	value, err := cache.GetOrLoad(ctx, "alice", func(context.Context) (int, error) {
		return 42, nil
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(value)
}
Output:
42

func (*Cache[K, V]) GetOrLoadMany

func (c *Cache[K, V]) GetOrLoadMany(ctx context.Context, keys []K, loader MultiLoader[K, V]) (map[K]V, error)

GetOrLoadMany returns cached values and batch-loads unique missing keys. Overlapping single and batch calls coalesce by key. When a joined load omits a key, the loader may be called again for every still-missing key because the prior round's staged values are discarded.

func (*Cache[K, V]) Keys

func (c *Cache[K, V]) Keys() []K

Keys returns physically stored keys in unspecified order. It may briefly include expired entries until cleanup.

func (*Cache[K, V]) Len

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

Len returns the number of physically stored entries. It may briefly include expired entries until a lookup or periodic cleanup removes them.

func (*Cache[K, V]) Name

func (c *Cache[K, V]) Name() string

Name returns the configured cache name.

func (*Cache[K, V]) Peek

func (c *Cache[K, V]) Peek(key K) (V, bool)

Peek returns a fresh value without updating ARC recency or frequency.

func (*Cache[K, V]) Purge

func (c *Cache[K, V]) Purge()

Purge removes all entries.

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, value V)

Set inserts or replaces one value and resets its TTL.

func (*Cache[K, V]) Values

func (c *Cache[K, V]) Values() []V

Values returns physically stored values in unspecified order. It may briefly include expired entries until cleanup.

type Loader

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

Loader loads one value after a cache miss.

type Metrics

type Metrics interface {
	Increment(key string)
	Gauge(key string, value any)
}

Metrics receives cache counters and gauges. Implementations must be safe for concurrent use and should return promptly.

type MultiLoader

type MultiLoader[K comparable, V any] func(context.Context, []K) (map[K]V, error)

MultiLoader loads values for unique missing keys.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a Cache. Options are created by this package's With and Without functions.

func WithCleanupInterval

func WithCleanupInterval(interval time.Duration) Option

WithCleanupInterval configures periodic expired-entry cleanup.

func WithMetrics

func WithMetrics(metrics Metrics) Option

WithMetrics configures optional cache metrics.

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL configures entry lifetime.

func WithTTLJitter

func WithTTLJitter(maximum time.Duration) Option

WithTTLJitter configures the maximum random offset added to each TTL.

func WithoutExpiration

func WithoutExpiration() Option

WithoutExpiration disables TTL checks and background expiration.

func WithoutPeriodicCleanup

func WithoutPeriodicCleanup() Option

WithoutPeriodicCleanup disables timer-driven cleanup. Key lookups still reject expired entries.

func WithoutTTLJitter

func WithoutTTLJitter() Option

WithoutTTLJitter disables expiration spreading.

Jump to

Keyboard shortcuts

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