cache

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2024 License: MIT Imports: 9 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.

README

Self Adjusting Cache

This is a cache designed for use cases where you have complex, interdependent cached data that need to be efficiently recomputed when there are changes to related entries in the cache.

In the case where the value function used to populate the cache produces the same output for a given set of inputs, you can optimize the cache's performance by preempting change propagation using cutoff conditions. That is, when a cache entry's value changes, the cache uses cutoff conditions to determine if the change is "significant enough" to propagate further and trigger recomputations of dependent entries. For example, if a numeric value in the cache changes from 3.0001 to 3.0002, and the cutoff is defined to ignore small differences, then the update will not propagate to other dependent cache entries because it's considered negligible. This can help prevent unnecessary work and can lead to efficient change propagation.

To summarize, this package provides a cache implementation that offers the following:

  • Dependency Tracking: Automatically tracks dependencies between cached values and allows for dynamic updates to the relationships between cache entries.
  • Efficient Recomputation: Uses incremental computation to recompute only the necessary parts of cache when cache entries change and allows for conditional termination of propagations via cutoff conditions.

Usage

A mini-worked example:

import "github.com/selasijean/golang-self-adjusting-cache"

...
type cacheKey struct {
	t int
}

func (k cacheKey) Identifier() string {
	return strconv.Itoa(k.t)
}

func fnKey(t int) cacheKey {
	return cacheKey{t: t}
}

func (e *evaluator) identityFn(ctx context.Context, t int) (Entry[cacheKey, int], error) {
	cached, ok := e.cache.Get(fnKey(t))
	if ok {
		return cached, nil
	}

	out := NewEntry(fnKey(t), 0, nil)
	if t > 0 {
		tMinus := t-1
		r, err := e.identityFn(ctx, tMinus)
		if err != nil {
			return nil, err
		}
		out = NewEntry(fnKey(t), r.Value()+1, []cacheKey{fnKey(tMinus)})
	}

	err := e.cache.Put(ctx, out)
	if err != nil {
		return nil, err
	}
	return out, nil
}

valueFn := func(ctx context.Context, k cacheKey) (Entry[cacheKey, int], error) {
	return evaluator.identityFn(ctx, k.t) // where identity(t) = identity(t-1) + 1 where identity(0) = 0.
}

cache := cache.New(valueFn)

_, err := evaluator.identityFn(ctx, 4)
require.NoError(t, err)

cached, ok := cache.Get(fnKey(4))
require.True(t, ok)
require.Equal(t, 4, cached.Value())

// setting identityFn(0) to 1 by overriding the value in the cache.
err = cache.Put(ctx, NewEntry(0, 1, nil))
require.NoError(t, err)

// all cached values that depend on identityFn(0) should be recomputed and their values offset by 1.
for i := 1; i <= 4; i++ {
	cached, ok = cache.Get(fnKey(i))
	require.True(t, ok)
	require.Equal(t, i+1, cached.Value())
}

A note on Parallelism

Put adds to the cache serially, building the internal graph that tracks the relationships between cached values. When parallelism is enabled, it only works with Recompute because the cache at that point has sufficient information from its internal graph to infer which entries are independent from one another and hence can be recomputed in parallel.

In certain cases, Parallel mode may be slower to recompute since locks have to be acquired and shared state managed carefully. You should only reach to use Parallel mode if the computation involved in re-evaluating a cache value is large relative to that overhead of managing locks and shared state.

API compatibility guarantees

As of v1.xxx you should assume that the functions and types exported by this library will maintain forward compatibility until some future v2 necessitates changing things meaningfully, at which point we'll integrate semantic import versioning.

Documentation

Index

Constants

View Source
const (
	// DefaultMaxHeight is the default maximum length of a path in the cache's dependency graph.
	DefaultMaxHeight = 20000
)

Variables

This section is empty.

Functions

func OptMaxHeightOfDependencyGraph

func OptMaxHeightOfDependencyGraph(size int) func(*CacheOptions)

OptMaxHeightOfDependencyGraph caps the longest path within the cache's dependency graph

If not provided, the default height is 20000.

func OptPreallocateSize

func OptPreallocateSize(size int) func(*CacheOptions)

OptCachePreallocateNodesSize preallocates the size of the cache

If not provided, no size for elements will be preallocated.

func OptUseParallelism

func OptUseParallelism(numCPU *int) func(*CacheOptions)

OptUseParallelism enables parallel recomputation of cache keys. numCPU sets the parallelism factor, or said another way the number of goroutines, to use

numCPU will default to runtime.NumCPU if unset.

Types

type Cache

type Cache[K Hashable, V any] interface {
	// Clear removes all entries from the cache.
	Clear(ctx context.Context)
	// Copy creates a deep copy of the cache.
	Copy(ctx context.Context) (Cache[K, V], error)
	// Get returns the value of the given key if it is in the cache, and a boolean indicating whether the key was found.
	Get(key K) (Value[K, V], bool)
	// Keys returns all the keys in the cache.
	Keys() []K
	// Len returns the number of entries in the cache.
	Len() int64
	// Purge removes the given keys and all dependent keys from the cache.
	Purge(ctx context.Context, keys ...K)
	// Put adds the given entries to the cache.
	Put(ctx context.Context, entries ...Entry[K, V]) error
	// Recompute re-evaluates the values of the given keys using the value function provided to the cache.
	Recompute(ctx context.Context, keys ...K) error
	// Values returns all the values in the cache.
	Values() []Value[K, V]
	// WithCutoffFn sets the cutoff function for the cache.
	WithCutoffFn(fn func(ctx context.Context, key K, previous, current V) (bool, error)) Cache[K, V]
	// WithParallelism sets whether the cache should use parallelism when recomputing values.
	WithParallelism(enabled bool) Cache[K, V]
	// WithWriteBackFn sets the write back function for the cache
	//
	// The write back function is called when the value of a key is updated
	// and is useful when the value of a key is computed and then stored in an external database or service.
	WithWriteBackFn(fn func(ctx context.Context, key K, value V) error) Cache[K, V]
	// WithHashFn sets the hash function used by the cache
	WithHashFn(func(hash string) uintptr) Cache[K, V]
	// MarshalJSON will marshal the cached into a JSON-based representation.
	MarshalJSON() ([]byte, error)
	// UnmarshalJSON will unmarshal a JSON-based byte slice into a full cache datastructure.
	// For this to work, cache's types must implement the Marshal/Unmarshal interface.
	UnmarshalJSON(b []byte) error
}

func New

func New[K Hashable, V any](valueFn func(ctx context.Context, key K) (Entry[K, V], error), opts ...CacheOption) Cache[K, V]

type CacheOption

type CacheOption func(*CacheOptions)

type CacheOptions

type CacheOptions struct {
	MaxHeightOfDependencyGraph int
	PreallocateCacheSize       int
	Parallelism                int
	EnableParallelism          bool
}

CacheOptions are options for the cache.

type Entry

type Entry[K Hashable, V any] interface {
	// Dependencies returns the dependencies of the cache entry.
	Dependencies() []K
	// Key returns the key of the cache entry.
	Key() K
	// Value returns the value of the entry.
	Value() V
}

Entry is a generic interface for an entry in the cache.

func NewEntry

func NewEntry[K Hashable, V any](key K, value V, deps []K) Entry[K, V]

NewEntry creates a cache entry with the given key, value, and dependencies.

type Hashable

type Hashable interface {
	// Identifier returns a unique identifier for the key.
	Identifier() string
}

Types that can be used as keys for this cache must be comparable and have a unique identifier.

type Value

type Value[K Hashable, V any] interface {
	// TopSortOrder returns the topological sort order of the value within the cache.
	// For v1,v2 if v1.TopSortOrder() == v2.TopSortOrder() then v1 and v2 are independent of each other. If v2 depends on v1 (directly or indirectly), then v2.TopSortOrder() > v1.TopSortOrder().
	TopSortOrder() int

	Entry[K, V]
	// OnUpdate registers a callback that is called when the value is updated.
	OnUpdate(fn func(context.Context))
	// OnPurged registers a callback that is called when the value is purged from the cache.
	OnPurged(fn func(context.Context))
	// Direct dependents provides a list of keys in the cache that directly depend on the value.
	DirectDependents() []K
}

Jump to

Keyboard shortcuts

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