Documentation
¶
Overview ¶
Package cache provides typed cache contracts and a bounded in-memory implementation for generated Spice cache decorators.
Index ¶
- type Definition
- type Memory
- func (memory *Memory[K, V]) Delete(ctx context.Context, key K) error
- func (memory *Memory[K, V]) Get(ctx context.Context, key K) (value V, found bool, err error)
- func (memory *Memory[K, V]) PurgeExpired(ctx context.Context) (int, error)
- func (memory *Memory[K, V]) Put(ctx context.Context, key K, value V, ttl time.Duration) error
- func (memory *Memory[K, V]) Snapshot() Snapshot
- type Observation
- type Observer
- type Operation
- type Snapshot
- type Store
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Definition ¶
Definition identifies one compiler-owned cache and its module.
type Memory ¶
type Memory[K comparable, V any] struct { // contains filtered or unexported fields }
Memory is a fixed-capacity least-recently-used cache. It has no background goroutine; expiration occurs on Get or PurgeExpired.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/spice-framework/spice/cache"
)
func main() {
memory, err := cache.NewMemory[string, string](
cache.Definition{ID: "products.by-id", Module: "example.com/shop/products"},
100,
nil,
)
if err != nil {
fmt.Printf("construct: %v\n", err)
return
}
err = memory.Put(context.Background(), "sku-1", "coffee", time.Minute)
if err != nil {
fmt.Printf("put: %v\n", err)
return
}
value, found, err := memory.Get(context.Background(), "sku-1")
fmt.Printf("value=%s found=%v err=%v\n", value, found, err)
}
Output: value=coffee found=true err=<nil>
func NewMemory ¶
func NewMemory[K comparable, V any]( definition Definition, capacity int, clock func() time.Time, observers ...Observer, ) (*Memory[K, V], error)
NewMemory constructs an empty cache. A nil clock selects time.Now.
func (*Memory[K, V]) PurgeExpired ¶
PurgeExpired removes all entries expired at the caller-controlled clock.
type Observation ¶
type Observation struct {
Definition Definition
Operation Operation
Duration time.Duration
Hit bool
Evicted int
Removed int
Size int
}
Observation contains bounded cache metadata. Keys and values are intentionally excluded.
type Observer ¶
type Observer func(context.Context, Observation)
Observer receives completed cache operations on the caller's goroutine.
type Operation ¶
type Operation string
Operation identifies one observed cache action.
const ( // OperationGet identifies a lookup. OperationGet Operation = "get" // OperationPut identifies an insertion or replacement. OperationPut Operation = "put" // OperationDelete identifies explicit invalidation. OperationDelete Operation = "delete" // OperationPurge identifies explicit expired-entry removal. OperationPurge Operation = "purge" )