cache/v1

A place for an app and its extensions to keep what was expensive to compute: rendered pages, API answers, resized images. Code opens a bucket by name with the limits it wants and gets and sets keys in it. Who keeps the bytes (memory and disk in this process, or Redis or Memcached shared between servers) is up to the provider, so a new one replaces the old without any caller changing.

A bucket has its own caps, inside whatever room the provider has in all:

Option What it does
Eviction Which of the bucket's entries go first when it's full: lru (default), mru, fifo, lifo
MaxItems Most entries the bucket holds
MaxMemory Most bytes of keys and values the bucket holds
TTL How long an entry lives unless Set says otherwise

Where entries live (memory, disk, another server) and how much room there is in all are the provider's and the operator's business, not the bucket's.

The promise is a cache's: a provider may drop any entry at any time, and a Get may miss. It never returns a value that was deleted, cleared or replaced since, nor one past its TTL. Each app has its own buckets, on a multisite host too, even when the provider keeps every app's entries in one shared store.

An app service contract, one provider (cache.go).

Use

Open a bucket after registration (in a hook or at serve time), keep it, and use it:

b, err := cachev1.Open(app, "myext.answers", cachev1.Options{MaxItems: 1000, TTL: 10 * time.Minute})
if err != nil {
	return err
}
if v, ok, _ := b.Get(ctx, key); ok {
	return v
}
v := compute()
_ = b.Set(ctx, key, v, 0) // 0 = the bucket's TTL

Name buckets after your extension (myext.answers) so two extensions never share one. Declare cache/v1 in WorksWith: when nothing provides it, Open returns a bucket that keeps nothing, so the same code runs uncached.

When the value is expensive and many requests may ask for the same cold key at once, let cachev1.Load compute it: callers asking for the same key of the same bucket while it runs share one call, and all of them are released only after the value is stored. An error goes to the callers waiting then and is never stored; each caller waits on its own context, and the call keeps running for the others when one gives up (so bound its time yourself).

v, err := cachev1.Load(ctx, b, key, func(ctx context.Context) ([]byte, error) { return compute(ctx) })

Items has the same Load for Go values.

To empty every bucket the app has (after a change that left stale entries), call cachev1.Clear(ctx, app); the app's admins can do the same from outside its code through cache.clear/v1.

Go values

To cache a Go value (a parsed template, a compiled program) without turning it into bytes on every Set and back on every Get, make it a cachev1.Item and open the bucket with OpenItems:

type compiled struct{ /* ... */ }

func (c *compiled) CacheSize() int64              { /* roughly the bytes it holds in memory */ }
func (c *compiled) MarshalCache() ([]byte, error) { /* bytes decode turns back into an equal value */ }
func (c *compiled) CacheVersion() string          { return "compiled/2" } // change it when the bytes' format changes

items, err := cachev1.OpenItems(app, "myext.compiled", cachev1.Options{MaxMemory: 64 << 20}, "compiled/2",
	func(b []byte) (*compiled, error) { /* ... */ })
if c, ok, _ := items.Get(ctx, key); ok {
	return c
}
c := compile()
_ = items.Set(ctx, key, c, 0)

What a provider does with them:

  • Each key holds its own item. Nothing is shared between keys, buckets or apps: the code that owns the bucket owns its items, and every Get of a key returns that key's item, not a copy. CacheSize counts against the memory caps in place of a length.
  • Only a Marshaler leaves memory. CacheSize alone makes an item that lives in memory only: evicted, it's gone. MarshalCache promises bytes that decode back to an equivalent item; the provider calls it only when it moves the item (to disk, across a restart, to another server), and may keep identical bytes from many keys once, there.
  • Versions keep old bytes out. The provider keeps CacheVersion beside the bytes (bucket, key, version -> content), and a decoder of another version never sees them: a miss, so a code change that alters the format doesn't decode stale bytes.

On a provider that keeps only bytes, Items marshals on Set (with the version in front) and decodes on Get, so the code is the same either way.

Provide

Implement cachev1.Cache (Bucket, Clear) and cachev1.Bucket (Get, Set, Delete, Clear), and provide it in Register, as the default if another provider should replace yours:

cachev1.Contract.Provide(app, myCache)

Cache.Clear empties every bucket the app has, including ones it hasn't opened since it started. Provide cache.clear/v1 beside it.

To keep Go values without marshaling them, have your buckets also implement cachev1.ItemBucket (GetItem, SetItem). Items and bytes share a bucket's keys: Get of a Marshaler returns its bytes (and misses on an item that can't marshal), and GetItem of bytes of the decoder's version returns them decoded, as the key's item from then on. Never hand one key's item to another key. A bucket that only keeps bytes needs nothing more: Items marshals for it.

Keep each app's buckets apart: on a shared store (one per process, or Redis), prefix keys with extkit.AppID(app) and the bucket name. Treat Options as caps you keep as well as your storage allows (Redis has its own eviction), and say in your README which ones you honour.

Extensions

Extension
cache provides (default)
mothership requires
pages works with

License

MIT