cache

package
v0.0.0-...-15f65a9 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2024 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New[T any](config Config[T]) (*cache[T], error)

func WithCache

func WithCache[T any](c Cache[T], loadFromDatabase func(ctx context.Context, identifier string) (T, bool, error)) func(ctx context.Context, identifier string) (T, bool, error)

withCache builds a pullthrough cache function to wrap a database call. Example: api, found, err := withCache(s.apiCache, s.db.FindApiByKeyAuthId)(ctx, key.KeyAuthId)

Types

type Cache

type Cache[T any] interface {
	// Get returns the value for the given key.
	// If the key is not found, found will be false.
	Get(ctx context.Context, key string) (value T, hit CacheHit)

	// Sets the value for the given key.
	Set(ctx context.Context, key string, value T)

	// Sets the given key to null, indicating that the value does not exist in the origin.
	SetNull(ctx context.Context, key string)

	// Removes the key from the cache.
	Remove(ctx context.Context, key string)

	// Dump returns a serialized representation of the cache.
	Dump(ctx context.Context) ([]byte, error)

	// Restore restores the cache from a serialized representation.
	Restore(ctx context.Context, data []byte) error

	// Clear removes all entries from the cache.
	Clear(ctx context.Context)
}

func NewNoopCache

func NewNoopCache[T any]() Cache[T]

type CacheHit

type CacheHit int
const (
	Null CacheHit = iota
	// The entry was in the cache and can be used
	Hit
	// The entry was not in the cache
	Miss
)

type Config

type Config[T any] struct {
	// How long the data is considered fresh
	// Subsequent requests in this time will try to use the cache
	Fresh time.Duration

	// Subsequent requests that are not fresh but within the stale time will return cached data but also trigger
	// fetching from the origin server
	Stale time.Duration

	// A handler that will be called to refetch data from the origin when necessary
	RefreshFromOrigin func(ctx context.Context, identifier string) (data T, ok bool)

	Logger  logging.Logger
	Metrics metrics.Metrics

	// Start evicting the least recently used entry when the cache grows to MaxSize
	MaxSize int

	Resource string
}

type Middleware

type Middleware[T any] func(Cache[T]) Cache[T]

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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