cachev1
import cachev1 "pocketone.dev/ext/contracts/cache/v1"
Package cachev1 is the cache/v1 contract: named buckets of bytes an app keeps for a while, so extensions and apps can remember what was expensive to compute. Who keeps them (memory and disk in this process, Redis, Memcached) is the provider's business; code that caches talks only to this contract.
A caller opens a bucket by name with the limits it wants (how many items, how much memory, how long, where to spill to disk) and then gets and sets keys in it:
b, err := cachev1.Open(app, "pages.render", cachev1.Options{MaxItems: 1000, TTL: 10 * time.Minute})
if v, ok, _ := b.Get(ctx, key); ok {
return v
}
v := render()
_ = b.Set(ctx, key, v, 0)
The promise is a cache's, not a store's: a provider may drop any entry at any time, even right after Set, and a Get may miss for any reason. It never returns a value that was deleted, cleared or replaced since, nor one past its TTL.
Source: ext/contracts/cache/v1.
Variables
var Contract = extkit.NewContract[Cache]("cache/v1", extkit.One)
Contract is cache/v1: one provider per app.
Functions
Clear
func Clear(ctx context.Context, app core.App) error
Clear empties every bucket app has, through whoever provides cache/v1; with no provider there's nothing to empty.
Load
func Load(ctx context.Context, b Bucket, key string, fn func(ctx context.Context) ([]byte, error)) ([]byte, error)
Load returns key's value from b, or on a miss computes it with fn and stores it. Callers asking for the same key of the same bucket while fn runs share that one call (a cold key under load computes once, not once per request):
- every caller is released only after the value is stored, so none of them misses again right after;
- fn's error goes to the callers waiting then and is never stored: the next caller tries again;
- each caller waits on its own ctx: one that gives up returns ctx's error and leaves fn running for the others.
fn runs with ctx's values but not its cancellation (the first caller leaving mustn't fail the rest), so it bounds its own time. A failed store still returns the value. A bucket whose type can't be a map key isn't coalesced.
ValidName
func ValidName(name string) error
ValidName checks a bucket name: 1 to 64 characters of a-z, 0-9, '.', '_' and '-', starting with a letter or digit. Prefix it with your extension's name ("pages.render") so two extensions don't share a bucket by accident.
Types
Bucket
type Bucket interface {
// Get returns key's value and true, or false on a miss. The returned slice is the caller's to keep or change.
Get(ctx context.Context, key string) ([]byte, bool, error)
// Set stores value under key, replacing what was there. ttl 0 uses the bucket's TTL; a negative ttl deletes key.
// The bucket keeps its own copy of value.
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Delete removes key. Deleting a missing key is not an error.
Delete(ctx context.Context, key string) error
// Clear removes every key of the bucket.
Clear(ctx context.Context) error
}
Bucket is one named cache: keys to byte values.
Open
func Open(app core.App, name string, opts Options) (Bucket, error)
Open returns app's bucket name from whoever provides cache/v1, or a bucket that keeps nothing when nothing does, so code that only works better with a cache declares cache/v1 in WorksWith and needs no other branch. Call it after registration (in hooks, at serve time), and keep the bucket.
Cache
type Cache interface {
// Bucket returns the bucket name, creating it with opts on first use. Later calls with the same name return the
// same bucket and ignore their opts. name must pass [ValidName]. A provider may override opts with an
// operator's settings for that bucket, and treats each field as a hint it keeps as well as its storage allows.
Bucket(name string, opts Options) (Bucket, error)
// Clear empties every bucket the app has, opened since it started or not.
Clear(ctx context.Context) error
}
Cache gives an app its buckets. Each app has its own: a bucket named "x" on one app never sees another app's "x", on a multisite host too, even when the provider keeps every app's entries in one shared store.
Decoder
type Decoder struct {
Version string
Decode func([]byte) (Item, error)
}
Decoder turns bytes back into an item: a Marshaler's bytes of the same Version, or bytes Set as a value (whose version is "").
Eviction
type Eviction string
Eviction is which entry a full bucket drops to make room.
const (
// LRU drops the least recently used entry (read or written). The default.
LRU Eviction = "lru"
// MRU drops the most recently used entry: for scans that won't come back to what they just read.
MRU Eviction = "mru"
// FIFO drops the oldest written entry; reads don't count.
FIFO Eviction = "fifo"
// LIFO drops the newest written entry; reads don't count. (Also called FILO.)
LIFO Eviction = "lifo"
)
Eviction.Valid
func (e Eviction) Valid() bool
Valid reports whether e is one of the strategies above, or "" for the provider's default.
Item
type Item interface {
// CacheSize is roughly how many bytes the item holds in memory, counted against the bucket's memory limits in
// place of a byte value's length.
CacheSize() int64
}
Item is a Go value a bucket keeps as it is: a parsed template, a compiled program, a decoded struct. Each key holds its own: a bucket never hands one key's item to another key, another bucket or another app, so the code that owns the bucket owns its items, and every Get of a key returns that key's item (not a copy).
An item that is only an Item lives in memory alone: it never goes to disk or to another server, and when memory is full it is simply dropped. To let it leave memory, make it a Marshaler.
ItemBucket
type ItemBucket interface {
Bucket
// GetItem returns key's item and true, or false on a miss. decode turns bytes into an item when the key doesn't
// hold one in memory (it was Set as bytes, or its item was moved to disk or kept across a restart).
GetItem(ctx context.Context, key string, decode Decoder) (Item, bool, error)
// SetItem stores item under key, replacing what was there; the bucket keeps item itself, not a copy. ttl is as in
// [Bucket.Set].
SetItem(ctx context.Context, key string, item Item, ttl time.Duration) error
}
ItemBucket is the optional interface of a Bucket that keeps Item values without marshaling them. Byte values and items share the bucket's keys: Get on a key holding a Marshaler returns its bytes (and misses on an item that can't marshal), and GetItem on a key holding bytes of the decoder's version returns them decoded, as that key's item from then on. Bytes of another version are a miss. An item held in memory is returned as it is, whatever the decoder's version.
Items
type Items[T Item] struct {
// contains filtered or unexported fields
}
Items is a bucket of T values: typed Get and Set over any Bucket. On an ItemBucket the values stay Go values; on a bucket of bytes each Set marshals (keeping nothing for a T that isn't a Marshaler) and each Get decodes, with the version written in front of the bytes.
NewItems
func NewItems[T Item](b Bucket, version string, decode func([]byte) (T, error)) *Items[T]
NewItems returns typed access to b's values.
OpenItems
func OpenItems[T Item](app core.App, name string, opts Options, version string, decode func([]byte) (T, error)) (*Items[T], error)
OpenItems opens bucket name as Open does, for T values that decode turns back from bytes of version (T's CacheVersion; "" for a T that isn't a Marshaler).
Items.Bucket
func (it *Items[T]) Bucket() Bucket
Bucket returns the bucket underneath.
Items.Clear
func (it *Items[T]) Clear(ctx context.Context) error
Clear removes every key of the bucket, items and byte values alike.
Items.Decoder
func (it *Items[T]) Decoder() Decoder
Decoder is the items' Decoder.
Items.Delete
func (it *Items[T]) Delete(ctx context.Context, key string) error
Delete removes key.
Items.Get
func (it *Items[T]) Get(ctx context.Context, key string) (T, bool, error)
Get returns key's value and true, or false on a miss. A key holding an item of another type is a miss.
Items.Load
func (it *Items[T]) Load(ctx context.Context, key string, fn func(ctx context.Context) (T, error)) (T, error)
Load is Load for a bucket of T values: a miss computes the value with fn once for every caller waiting on the same key, stores it, then releases them all.
Items.Set
func (it *Items[T]) Set(ctx context.Context, key string, v T, ttl time.Duration) error
Set stores v under key; ttl is as in Bucket.Set.
Marshaler
type Marshaler interface {
Item
MarshalCache() ([]byte, error)
// CacheVersion names MarshalCache's format. Change it whenever the format changes: a provider keeps it beside the
// bytes (bucket, key, version -> content), and a Decoder of another version never sees them.
CacheVersion() string
}
Marshaler is an Item that can leave memory. MarshalCache promises that its bytes, given to a Decoder of the same CacheVersion, come back as an item equivalent in every way. Only then may a provider move it to disk, keep it across restarts or send it to another server; a provider may also keep identical bytes from many keys once, there.
A provider marshals when it moves the item, which may be later than Set and on another goroutine. Changing an item after Set changes what its key holds in memory, and may or may not reach a copy already marshaled: Set it again to be sure.
None
type None struct{}
None is a bucket that keeps nothing: every Get misses.
None.Clear
func (None) Clear(context.Context) error
Clear implements Bucket.
None.Delete
func (None) Delete(context.Context, string) error
Delete implements Bucket.
None.Get
func (None) Get(context.Context, string) ([]byte, bool, error)
Get implements Bucket: always a miss.
None.Set
func (None) Set(context.Context, string, []byte, time.Duration) error
Set implements Bucket: keeps nothing.
Options
type Options struct {
// Eviction is which of the bucket's entries goes first when the bucket is full; "" is LRU.
Eviction Eviction
// MaxItems caps the bucket's entries; 0 is no cap of its own.
MaxItems int
// MaxMemory caps the bytes of the bucket's keys and of the values it holds in memory; 0 is no cap of its own.
MaxMemory int64
// TTL is how long an entry lives when Set gives no ttl; 0 is until it's evicted.
TTL time.Duration
}
Options are a bucket's limits: caps on what this app's bucket may hold, inside whatever room the provider has in all. A zero field leaves the choice to the provider (and to the operator's settings). Where entries live (memory, disk, another server) and how much room there is in all are the provider's business, not the bucket's.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.