Cache
Introduction
Some work is expensive: a slow query, a call to a remote API, a report that takes seconds to build. The cache package lets you do that work once and reuse the result. It gives you a small, uniform API (get, put, remember and friends) on top of a swappable storage backend, plus atomic counters, tags, and locks that let several workers agree on who does a piece of work.
pnpm add @plinthjs/cacheThe package ships two stores: an in-memory store (ArrayStore) and a file-backed store (FileStore). You can plug in your own store (for example one backed by Redis) by implementing a small interface.
Basic usage
The quickest way to get a working cache is arrayCache(), which returns a Repository over an in-memory store. A repository is the object you call in application code.
import { arrayCache } from '@plinthjs/cache'
const cache = arrayCache()
await cache.put('answer', 42, 60) // store for 60 seconds
await cache.get('answer') // => 42
await cache.has('answer') // => true
await cache.missing('answer') // => falseEvery method is asynchronous, because a store may talk to a disk or a network. get resolves to null when the key is missing or expired. A null you stored also reads back as null, but has(key) is true for it, so use has to tell a stored null from a miss.
TTLs (time to live) are always expressed in seconds. If you omit the TTL on put, the value is stored without an expiry.
Storing several values
putMany writes a record of keys with one shared TTL, and many (or its alias getMany) reads several keys at once. Missing keys come back as null.
await cache.putMany({ p: 1, q: 2 }, 60)
await cache.many(['p', 'q', 'z']) // => { p: 1, q: 2, z: null }Storing only when absent
add writes a value only if the key does not exist (or has expired). It resolves to true when it wrote the value and false when it declined. This is the atomic building block that locks are made from.
await cache.add('lock:import', 1, 30) // => true
await cache.add('lock:import', 2, 30) // => false
await cache.get('lock:import') // => 1Storing forever, forgetting, flushing
await cache.forever('settings', { theme: 'dark' }) // never expires
await cache.forget('settings') // => true when the key existed
await cache.flush() // remove everything in this storeWARNING
flush clears the whole store, not just keys your code wrote. If other code shares the store, forget individual keys or use tags instead.
Fetching and removing
pull reads a key and removes it in one step. Pass a second argument for a default when the key is missing.
await cache.put('flash', 'Saved!')
await cache.pull('flash') // => 'Saved!'
await cache.pull('flash', 'nothing') // => 'nothing'Computing values once with remember
remember is the method you will use most. It returns the cached value when there is one; otherwise it runs your callback, stores the result for the given number of seconds, and returns it. The callback may be sync or async.
let calls = 0
const first = await cache.remember('user:1', 300, async () => ++calls) // => 1
const second = await cache.remember('user:1', 300, async () => ++calls) // => 1
// calls => 1For values that should never expire on their own, use rememberForever (also available as sear):
const config = await cache.rememberForever('config', async () => loadConfig())INFO
A callback that returns null is cached like any other value: the next call is a hit and the callback does not run again. (Internally the repository stores a sentinel in place of null; reads decode it back.)
Stale-while-revalidate with flexible
flexible takes a pair of lifetimes, [fresh, stale], in seconds. While the value is younger than fresh, it is returned as is. Once it is older than fresh but younger than stale, the old value is returned immediately and a refresh is started in the background, so no caller waits for the recomputation. After stale seconds the value has expired and the next call recomputes it synchronously.
let now = 0
const cache = arrayCache({ now: () => now })
let counter = 0
const load = () => cache.flexible('report', [10, 60], async () => ++counter)
await load() // => 1 (miss, computed)
now = 5_000
await load() // => 1 (fresh)
now = 20_000
await load() // => 1 (stale: returned now, refresh starts in the background)
await load() // => 2 (the refresh finished)Only one caller refreshes at a time (the refresh takes a lock), and a refresh that throws is swallowed: the stale value was already served and the next stale read tries again.
Reading typed values
When you know what a key should hold, the typed getters check it for you and throw a TypeError instead of handing back something unexpected. Each accepts a default used when the key is missing.
await cache.put('count', '42')
await cache.integer('count') // => 42 (numeric strings are accepted)
await cache.float('count') // => 42
await cache.string('title', 'untitled') // => 'untitled'
await cache.boolean('enabled', false) // => false
await cache.array<number>('ids', []) // => []
await cache.string('missing') // throws TypeError: Cache value for key [missing] must be a string, null given.Counters
increment and decrement adjust a numeric key atomically. A missing key starts at zero. Both return the new value.
await cache.increment('hits') // => 1
await cache.increment('hits', 5) // => 6
await cache.decrement('hits', 2) // => 4Extending an expiry
touch pushes out the expiry of a live key without rewriting its value. It resolves to false when the key does not exist. Omit the seconds to make the key permanent.
await cache.put('session:abc', 'data', 10)
await cache.touch('session:abc', 100) // => true
await cache.touch('missing') // => falseTags
Tags let you invalidate a group of related keys together. Call tags() with one or more names; the returned cache reads and writes within that group.
const people = cache.tags(['people'])
const artists = cache.tags(['people', 'artists'])
await artists.put('John', 'john-record', 600)
await people.put('Anne', 'anne-record', 600)
await artists.get('John') // => 'john-record'
await cache.get('John') // => null (the untagged cache cannot see tagged keys)
await cache.tags(['people']).flush() // invalidates both entries above
await artists.get('John') // => null
await people.get('Anne') // => nullKeys written with a set of tags are visible only through the same set of tags (in the same order). Flushing any one of the tags invalidates every entry that was written under it. flush() on a tagged cache only affects that tag, never the rest of the store.
Atomic locks
A lock makes sure only one process runs a critical section at a time. Locks are built on add, so they are as atomic as the store behind them. Create one with cache.lock(name, seconds); the optional seconds is how long the lock lives before it auto-expires if the holder crashes.
const lock = cache.lock('reports', 10)
const result = await lock.get(async () => generateReport())
if (result === false) {
// someone else holds the lock
}get returns false straight away when the lock is taken. When it succeeds, it runs your callback and always releases the lock afterwards, even if the callback throws. Without a callback, get just acquires the lock and returns true.
To wait for a busy lock instead of giving up, use block. It retries until the lock is free or the given number of seconds elapses, and then throws a LockTimeoutError.
import { LockTimeoutError } from '@plinthjs/cache'
try {
await cache.lock('reports', 10).block(5, async () => generateReport())
} catch (error) {
if (error instanceof LockTimeoutError) {
// waited 5 seconds without getting the lock
}
}You can also manage a lock by hand with acquire() and release():
const lock = cache.lock('import', 30)
if (await lock.acquire()) {
try {
await runImport()
} finally {
await lock.release()
}
}By default block polls every 250 milliseconds. Pass retryAfterMs to arrayCache() (or to a Repository) to change that.
WARNING
Each lock instance has an owner token (lock.owner()). release() only releases while this instance still owns the lock and resolves true when it did; if the lock expired and another holder took it, release() does nothing, so you never free someone else's lock. forceRelease() deletes the key regardless of owner (for a stuck lock). To release from another process, create the lock with { owner: token }. The owner check and the delete are two steps, so on a shared store it narrows the race rather than eliminating it; still choose a lock lifetime longer than the work.
Choosing a store
The in-memory store
arrayCache() keeps values in the current process only. They vanish when the process exits and are not shared between workers. It is the right choice for tests and for cheap per-process memoisation.
The file store
fileCache() writes each entry to its own JSON file under a directory, so the cache survives restarts.
import { fileCache } from '@plinthjs/cache'
const cache = fileCache({ directory: 'storage/framework/cache/data' })
await cache.put('k', { a: 1 }, 30)
await cache.get('k') // => { a: 1 }Values must be JSON-serialisable.
Building a repository yourself
arrayCache and fileCache are shortcuts. You can construct a repository from any store:
import { ArrayStore, Repository } from '@plinthjs/cache'
const cache = new Repository(new ArrayStore())Using several stores with the manager
CacheManager holds named stores and hands out a Repository for each. The built-in names are array and file. The file store needs a fileDirectory option; asking for it without one throws.
import { CacheManager } from '@plinthjs/cache'
const caches = new CacheManager({
default: 'file',
fileDirectory: 'storage/framework/cache/data',
})
await caches.store().put('a', 1) // the default store
await caches.store('array').put('b', 2) // a named store
caches.getDefaultStore() // => 'file'
caches.store('nope') // throws Error: Cache store [nope] is not defined.A repository is created once per name and reused, so caches.store('array') always returns the same object.
Adding your own store
A store is any object that implements the Store interface: get, put, add, forever, forget, flush, has, increment and decrement (all async), and optionally touch. Register it by name with extend, or pass it up front through the stores option.
import { ArrayStore, CacheManager } from '@plinthjs/cache'
import type { Store } from '@plinthjs/cache'
class AuditedStore extends ArrayStore implements Store {
override async put<T>(key: string, value: T, ttlSeconds?: number): Promise<boolean> {
console.log('writing', key)
return super.put(key, value, ttlSeconds)
}
}
const caches = new CacheManager()
caches.extend('audited', () => new AuditedStore())
await caches.store('audited').put('z', 1) // logs "writing z"The factory is called lazily, the first time the store is requested. Calling extend again with the same name replaces the store and drops any repository already resolved for it.
Cache events
Pass an events object with a dispatch(event) method to the manager (or to a Repository) and it will announce what the cache does. The cache passes a single event object, so a Dispatcher can be passed directly: new CacheManager({ events: dispatcher }), then dispatcher.listen(CacheHit, ...).
| Event | When it fires |
|---|---|
CacheHit | get found a value (value is on the event) |
CacheMissed | get found nothing |
KeyWritten | a put, forever or successful add wrote a value |
KeyWriteFailed | a put or forever reported that it could not write |
KeyForgotten | forget removed an existing key |
CacheFlushed | flush cleared the store |
Each event carries storeName and key (except CacheFlushed, which has only storeName). KeyWritten and KeyWriteFailed also carry the value and the seconds TTL.
import { CacheHit, CacheManager } from '@plinthjs/cache'
const caches = new CacheManager({
events: {
dispatch(event) {
if (event instanceof CacheHit) console.log('hit', event.key)
},
},
})
await caches.store().put('a', 1)
await caches.store().get('a') // logs "hit a"Events are dispatched for repositories created by the manager, and storeName is the name you asked for. A repository you build by hand gets events only if you pass events in its options.
Testing
The cache has no separate fake: the in-memory store is the fake. Use arrayCache() in your tests and inject a clock so expiry is deterministic instead of depending on real time.
let now = 0
const cache = arrayCache({ now: () => now })
await cache.put('k', 1, 60) // expires at now + 60_000 ms
now = 60_001
await cache.get('k') // => nullFor lock timeouts, also inject sleep so waiting advances your fake clock instead of really waiting:
let now = 0
const cache = arrayCache({
now: () => now,
sleep: async (ms) => {
now += ms
},
retryAfterMs: 100,
})
await cache.lock('k', 100).acquire()
await cache.lock('k').block(1, () => 1) // throws LockTimeoutError, instantlyTo assert on what your code does to the cache, pass an events collector and inspect the events it receives, as in the previous section.