cache

package module
v0.3.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 14 Imported by: 0

README

cache

Backend-neutral cache abstraction for gokit.

  • Core ships the Store contract, explicit FactoryRegistry, typed JSON store, component integration, and in-memory backend.
  • External backends are opt-in adapter modules. Redis lives under cache/redis and registers only when redis.Register(registry) is called.
  • There is no package-level mutable registry and no import-time backend registration.

In-memory default

reg := cache.NewFactoryRegistry()
if err := cache.RegisterMemory(reg); err != nil {
    return err
}

store, err := cache.New(reg, cache.Config{
    Provider: cache.ProviderMemory,
}, nil, log)

Redis adapter

import cacheredis "github.com/kbukum/gokit/cache/redis"

reg := cache.NewFactoryRegistry()
if err := cacheredis.Register(reg); err != nil {
    return err
}

store, err := cache.New(reg, cache.Config{
    Provider: cache.ProviderRedis,
    Enabled:  true,
}, &cacheredis.Config{
    Enabled: true,
    Addr:    "127.0.0.1:6379",
}, log)

Documentation

Overview

Package cache provides a backend-neutral cache abstraction with explicit factory registration and an in-memory backend for the default provider name.

Index

Constants

View Source
const (
	// ProviderMemory is the lean in-process cache backend shipped by core.
	ProviderMemory = "memory"

	// ProviderRedis is registered by the opt-in cache/redis adapter module.
	ProviderRedis = "redis"

	// ProviderFile is the filesystem-backed cache shipped by core.
	ProviderFile = "fs"

	DefaultProvider = ProviderMemory
)

Variables

This section is empty.

Functions

func RegisterFile

func RegisterFile(reg *FactoryRegistry) error

RegisterFile registers the filesystem backend into an explicit registry.

func RegisterMemory

func RegisterMemory(reg *FactoryRegistry) error

RegisterMemory registers the core memory backend into an explicit registry.

Types

type BatchStore

type BatchStore interface {
	GetMany(ctx context.Context, keys []string) (map[string][]byte, error)
}

BatchStore is optionally implemented by stores that support efficient batch reads.

type CloseStore

type CloseStore interface {
	Close() error
}

CloseStore is optionally implemented by stores that hold resources.

type Component

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

Component wraps Store and implements component.Component.

func NewComponent

func NewComponent(registry *FactoryRegistry, cfg Config, providerCfg any, log *logging.Logger) *Component

NewComponent creates a cache component. The registry is explicit and must contain the selected provider.

func (*Component) Describe

func (c *Component) Describe() component.Description

func (*Component) Health

func (c *Component) Health(ctx context.Context) component.Health

func (*Component) Name

func (c *Component) Name() string

func (*Component) Start

func (c *Component) Start(_ context.Context) error

func (*Component) Stop

func (c *Component) Stop(_ context.Context) error

func (*Component) Store

func (c *Component) Store() Store

Store returns the started cache store, if any.

type Config

type Config struct {
	Name       string        `mapstructure:"name" json:"name" yaml:"name"`
	Provider   string        `mapstructure:"provider" json:"provider" yaml:"provider"`
	Enabled    bool          `mapstructure:"enabled" json:"enabled" yaml:"enabled"`
	DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl" yaml:"default_ttl"`
}

Config holds provider-agnostic cache configuration.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults fills zero-valued fields.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks provider-agnostic settings.

type ConfigTypeError

type ConfigTypeError struct {
	Provider string
	Expected string
	Actual   any
}

ConfigTypeError reports an adapter-specific config type mismatch.

func (*ConfigTypeError) Error

func (e *ConfigTypeError) Error() string

type Factory

type Factory func(cfg Config, providerCfg any, log *logging.Logger) (Store, error)

Factory creates a cache store from core and provider-specific config.

type FactoryRegistry

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

FactoryRegistry stores cache backend factories by provider name.

func NewFactoryRegistry

func NewFactoryRegistry() *FactoryRegistry

NewFactoryRegistry creates an isolated cache factory registry.

func (*FactoryRegistry) Get

func (r *FactoryRegistry) Get(name string) (Factory, bool)

Get returns a cache factory by provider name.

func (*FactoryRegistry) Register

func (r *FactoryRegistry) Register(name string, f Factory) error

Register stores a cache backend factory for a provider name.

type FileConfig

type FileConfig struct {
	// Root is the directory that holds cache entries. It is created on demand.
	Root string `mapstructure:"root" json:"root" yaml:"root"`

	// KeyPrefix namespaces keys so independent caches may share a Root without collisions.
	KeyPrefix string `mapstructure:"key_prefix" json:"key_prefix" yaml:"key_prefix"`

	// MaxEntryBytes rejects serialized entries larger than this bound. Zero selects
	// the 16 MiB default.
	MaxEntryBytes int64 `mapstructure:"max_entry_bytes" json:"max_entry_bytes" yaml:"max_entry_bytes"`

	// DefaultTTL is applied when Set is called with ttl == 0. A resulting zero
	// duration means the entry never expires.
	DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl" yaml:"default_ttl"`
}

FileConfig configures the filesystem cache backend.

type FileStore

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

FileStore is a persistent cache backed by sharded files under a confined root. Entries are addressed by a content hash of their prefixed key, so keys never map onto filesystem paths directly and directory traversal is impossible. Writes are serialized and atomic (temp file + rename); reads run concurrently.

func NewFileStore

func NewFileStore(cfg FileConfig) (*FileStore, error)

NewFileStore creates a filesystem cache rooted at cfg.Root, creating the root directory if necessary. Root must be non-empty.

func (*FileStore) CleanupExpired

func (s *FileStore) CleanupExpired(ctx context.Context, maxEntries int) (int, error)

CleanupExpired scans at most maxEntries files and deletes expired entries, returning the number removed. It is application-invoked maintenance; the store performs no automatic capacity eviction.

func (*FileStore) Delete

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

Delete removes key. A missing key is not an error.

func (*FileStore) Exists

func (s *FileStore) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether key is present and unexpired.

func (*FileStore) Get

func (s *FileStore) Get(ctx context.Context, key string) (value []byte, found bool, err error)

Get returns a cached value when present and unexpired. Expired entries are reported as a miss but left in place for CleanupExpired to reclaim.

func (*FileStore) Set

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

Set writes value for key with the given TTL. ttl == 0 adopts the store default; a resulting zero duration means the entry never expires.

type MemoryConfig

type MemoryConfig struct {
	DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl" yaml:"default_ttl"`
}

MemoryConfig configures the in-memory cache backend.

type MemoryStore

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

MemoryStore is a thread-safe in-memory cache with TTL expiration.

func NewMemoryStore

func NewMemoryStore(cfg MemoryConfig) *MemoryStore

NewMemoryStore creates an in-memory cache.

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(_ context.Context, key string) error

Delete removes a key.

func (*MemoryStore) Exists

func (s *MemoryStore) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether key is present and unexpired.

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, key string) (value []byte, found bool, err error)

Get returns a copy of the cached bytes when present and not expired.

func (*MemoryStore) GetMany

func (s *MemoryStore) GetMany(ctx context.Context, keys []string) (map[string][]byte, error)

GetMany returns present, unexpired keys.

func (*MemoryStore) Set

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

Set stores a copy of value with the given TTL. ttl=0 uses the store default; a resulting zero TTL means no expiration.

type Store

type Store 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
	Exists(ctx context.Context, key string) (bool, error)
}

Store is the backend-neutral cache contract.

func New

func New(reg *FactoryRegistry, cfg Config, providerCfg any, log *logging.Logger) (Store, error)

New creates a Store using an explicitly populated registry.

type TypedStore

type TypedStore[C any] struct {
	// contains filtered or unexported fields
}

TypedStore provides JSON-serialized typed cache operations.

func NewTypedStore

func NewTypedStore[C any](store Store, keyPrefix string) *TypedStore[C]

NewTypedStore creates a typed cache store.

func (*TypedStore[C]) Delete

func (s *TypedStore[C]) Delete(ctx context.Context, key string) error

Delete removes key.

func (*TypedStore[C]) Load

func (s *TypedStore[C]) Load(ctx context.Context, key string) (*C, error)

Load deserializes JSON from cache. It returns (nil, nil) for a miss.

func (*TypedStore[C]) Save

func (s *TypedStore[C]) Save(ctx context.Context, key string, val *C, ttl time.Duration) error

Save serializes val to JSON and stores it with ttl.

Jump to

Keyboard shortcuts

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