API reference
Reference the root, Cloudflare, and React Router exports in the current @astilba/cache source snapshot.
This page documents the complete root export surface and the two public adapter subpaths in the current source snapshot. Start with the overview or local quickstart if you are learning the library; use this page when you need an exact method, option, result field, or driver contract.
Create a cache
Section titled “Create a cache”createCache(config)
Section titled “createCache(config)”Creates a Cache instance from application-supplied capabilities.
const cache = createCache({ namespace: "storefront", clock, rng, l2: store,})The raw constructor requires namespace, clock, and rng. A factory fill also requires l2; without it, the fill throws NotImplementedError. createWorkersCache() is the higher-level Workers constructor.
CacheConfig
Section titled “CacheConfig”| Field | Type | Meaning and current boundary |
|---|---|---|
namespace |
string |
Required stable boundary for canonical keys and namespace invalidation. |
clock |
Clock |
Required source of logical time. |
rng |
Rng |
Required source of randomness. |
l1 |
Store |
Optional local tier. Retains principal-derived values that cannot be written to shared storage. |
l2 |
Store |
Shared or durable tier. Currently required whenever a factory runs and can also hold replication-mirror objects for recovery. |
registry |
Registry |
Authoritative invalidation driver. Required by the purge methods. |
bus |
Bus |
Live invalidation delivery. Coordinated validation is built when Registry and L2 are also configured. Registry plus Bus without L2 throws at construction. |
cdn |
Cdn |
Declared L3 purge capability; not invoked by the current kernel. |
lock |
Lock |
Optional cross-instance fill lock. A read opts in with lock: true. |
codec |
Codec |
Value encoder and wire identity. Defaults to the built-in JSON round trip. |
defaults |
CacheDefaults |
Instance policy defaults. Several timing and unavailable-policy fields remain partial. |
telemetry |
TelemetrySink | TelemetryConfig |
Receives operational events. Hosted mode pseudonymizes string fields when a salt is present; configured delivery isolates sink failures and can call onSinkError. |
takedownSensitive |
boolean |
Selects the provisional unknown-as-error posture unless explicitly overridden. It currently continues as a miss rather than throwing. |
dev |
boolean |
Makes incompatible same-key singleflight calls fail loudly and guards request reads inside explicitly public factories. |
CacheDefaults
Section titled “CacheDefaults”| Field | Meaning and current boundary |
|---|---|
ttl |
Default freshness duration. Declared but not applied; elapsed expiry is unfinished. |
grace |
Default stale window. Declared but not applied; elapsed grace is unfinished. |
maxEntryRetention |
Maximum retention registered when a Registry is configured. It has no registration target without that driver. |
consistency |
Declared default consistency. The current read path ignores it and defaults an omitted per-call option to eventual. |
unknownPolicy |
Chooses registry-check, miss, or the provisional error posture for unknown invalidation knowledge. |
staleIfError |
Replaces the default isRetriableHttp() failure classifier. |
graceBackoff |
Declared retry backoff for grace behavior; not consumed today. |
maxSyncLag |
Base cadence for the attached replication poller. Defaults to the Workers profile’s 60 seconds when omitted. |
acceptCodecs |
Additional stored codec identities the current Codec is allowed to decode. |
heartbeatInterval |
Reader-side heartbeat interval used to derive the invalidation-silence threshold. The Workers factory defaults it to 30 seconds; the Coordinator deployment variable is configured separately. |
onUnavailable |
Declares strong-read degradation to eventual; not consumed today. |
Read or fill values
Section titled “Read or fill values”Cache methods
Section titled “Cache methods”| Method | Returns | Current behavior |
|---|---|---|
getOrSet(options) |
Promise<T> |
Returns a usable hit or runs the factory. A terminal fenced fill throws FencedError. |
getOrSetEntry(options) |
Promise<CacheEntry<T>> |
Adds skip() and returns read metadata. A terminal fenced fill becomes a miss entry. |
expire(selector) |
Promise<PurgeResult> |
Applies a soft invalidation through Registry. |
delete(selector) |
Promise<PurgeResult> |
Applies a hard invalidation through Registry. CDN modes are not wired. |
clear() |
Promise<PurgeResult> |
Bumps the local namespace version and hard-invalidates the reserved namespace tag. |
expireAll(guard) |
Promise<PurgeResult> |
Declared with an explicit origin-load acknowledgement; currently throws NotImplementedError. |
deleteAll(guard) |
Promise<PurgeResult> |
Declared with an explicit origin-load acknowledgement; currently throws NotImplementedError. |
collect() |
RenderCollector |
Creates a scope-aware L3 dependency collector. React Router binds one per request so hits and fills contribute automatically. |
explain(key) |
Promise<Explanation> |
Witnesses the default-public key in L1 then L2, its stored identity, current local verdict and reader state, and any request-scoped attribution. A missing entry is a reportable result. |
Read option types
Section titled “Read option types”GetOrSetOptions<T> and GetOrSetEntryOptions<T> extend GetOptions with their respective factory type.
GetOptions field |
Meaning and current boundary |
|---|---|
key |
Required application-facing key. Namespace, scope, and namespace version are added internally. |
tags |
Optional dependency tags. Use branded values created by the tag helpers. |
ttl |
Intended freshness duration. It participates in singleflight compatibility but elapsed time is not enforced. |
grace |
Opts a stale candidate into classified error fallback. The declared duration is not enforced. |
notFoundTtl |
Its presence allows an HttpError 404 to become a negative entry. The duration is not enforced. |
scope |
“public” or { tenant }. When omitted, visible identity derives a principal-local scope; contextless work resolves public. |
consistency |
“eventual” or “strong”. Strong live-checks a stored entry and pre-checks a miss before running its factory when coordinated invalidation is active. |
lock |
Requests a configured cross-instance Lock. Without a driver, true currently continues unlocked. |
request |
Adapter-provided RequestContext used for identity derivation and the development public-scope guard. |
factory |
Async origin loader. Its context is FactoryCtx<T> or EntryFactoryCtx<T>. |
The exported option types are GetOptions, GetOrSetOptions, and GetOrSetEntryOptions.
Factory context
Section titled “Factory context”FactoryCtx<T> member |
Meaning and current boundary |
|---|---|
signal |
A fresh AbortSignal. The kernel does not yet abort it on a cache deadline. |
graced |
Optional GracedInfo describing a stale candidate. It is not populated today. |
request |
The adapter request object. Under dev: true and explicit public scope, property reads can demote the fill to L1-only. |
fail(err?) |
Throws a factory failure without pretending it is a returned T. |
dependsOn(tag, options?) |
Adds a membership to the final stored tag set and the active render collector. { l3: false } currently throws NotImplementedError. |
setTags(tags) |
Authors a replacement for the call-level tag base. dependsOn() memberships remain unioned independently. |
setTtl(ttl) |
Declared factory-time TTL override; currently throws NotImplementedError. |
reuseGraced() |
Intended typed reuse of the graced value after provenance checks; currently throws NotImplementedError. |
The final settle-time union may contain at most 126 distinct user tags. Invalid, reserved, or excessive tags fail before storage. Calling dependsOn() or setTags() after the factory promise settles throws FactorySettledError.
EntryFactoryCtx<T> adds skip(): never. Calling it produces a skipped entry and stores nothing. The plain FactoryCtx<T> deliberately has no skip().
Related exports are FactoryCtx, EntryFactoryCtx, GracedInfo, and RequestContext.
GracedInfo exposes the candidate’s unknown-typed value, source identifier src, schema version v, and original bornMs. It is metadata for reuseGraced(), not permission to cast the unknown value to T.
CacheEntry<T>
Section titled “CacheEntry<T>”| Field | Meaning and current boundary |
|---|---|
value |
The value, or undefined for a miss, skip, or negative entry. |
skipped |
The entry factory called skip(). |
stale |
The returned value was not fresh at this read’s consistency level. |
age |
Always zero while elapsed-time accounting is unfinished. |
tier |
l1, l2, origin, or miss. The exported Tier union also declares l1.5, which is not emitted. |
servedOnError |
Present when a classified transient failure reused a revalidated stale candidate. |
durable |
On an origin result, whether shared L2 accepted the value or a newer durable entry won. Existing hit paths currently report true unconditionally. |
Invalidate values
Section titled “Invalidate values”Selector types
Section titled “Selector types”ExpireSelector accepts { tag, scope? } or { key }. DeleteSelector accepts those shapes plus an optional cdn mode.
- A tag selector affects every entry carrying that tag. The current implementation ignores its optional
scopefield. - A key selector targets the contextless public canonical key only. Use a dependency tag when tenant or principal variants may exist.
CdnModeis“enqueue” | “await” | “block”, but no mode invokes the configured CDN today.
OriginLoadGuard is the explicit { iUnderstandTheOriginLoad: true } acknowledgement required by the unimplemented expireAll() and deleteAll() methods.
PurgeResult
Section titled “PurgeResult”| Field or method | Meaning and current boundary |
|---|---|
epoch |
Registry epoch returned for the mutation. |
matchedHint |
Best-effort MatchedHint: yes, no-such-scope, or unknown. It is always unknown today. |
flushed({ timeout? }) |
Intended durable, Bus, and mirror-acceptance completion. Resolves immediately today. |
edgePurged({ timeout? }) |
Intended CDN-acceptance completion. Resolves immediately without a CDN purge today. |
See Invalidate cached data for safe mutation order and Implementation status before using completion fields operationally.
Build tags and durations
Section titled “Build tags and durations”Tag exports
Section titled “Tag exports”| Export | Purpose and current boundary |
|---|---|
Tag |
Branded string accepted by cache reads and invalidation selectors. |
TagPart |
string | number input used by tag helpers. |
compound(…parts) |
Implemented positional builder. Escapes %, :, and |
t |
Implemented tagged-template trust boundary. Validates a non-empty, non-reserved final tag against the lowercase grammar and 256 UTF-8-byte ceiling; it rejects rather than escaping interpolations. |
globalTag(name) |
Declared globally scoped tag helper; currently throws NotImplementedError. |
User tags beginning with __ are reserved and rejected with InvalidTagError at the cache boundary.
Duration exports
Section titled “Duration exports”Duration is a template-literal type such as “250ms”, “5m”, or “1.5h”. DurationUnit is “ms” | “s” | “m” | “h” | “d”; m means minutes.
duration(value, unit) is the implemented computed-value helper. It rejects non-positive or non-finite values and any multiplied millisecond result that is not a finite, positive, safe integer, throwing InvalidDurationError. Duration strings can appear in typed options, although elapsed TTL and grace behavior is unfinished.
Driver contracts
Section titled “Driver contracts”Most application developers should receive drivers from a runtime package. These exports exist for adapter authors, test harnesses, and advanced integrations.
Storage
Section titled “Storage”The core Store shape is:
interface Store { get(key: string, readKind?: ReadKind): Promise<StoreValue | undefined> set( key: string, value: string, options?: StoreWriteOptions, ): Promise<void> delete(key: string): Promise<void>}| Export | Purpose |
|---|---|
Store |
Async get(), set(), and delete() contract used by L1, L2, and mirror storage. |
ReadKind |
Optional Store read hint: “pointer”, “delta”, or “snap”. Drivers may map it to different read-cache policy. |
StoreValue |
Stored string value plus optional metadata. |
StoreMetadata |
Readonly metadata record. |
StoreWriteOptions |
Optional physical expirationTtl in seconds and metadata. |
StoreWriteError |
Structural write rejection with code throttled, too_large, or unavailable, plus retryability and optional cause. |
isStoreWriteError(value) |
Implemented shape-based type guard for StoreWriteError. |
MemoryOptions |
Optional clock, maxEntries, UTF-8 maxBytes, telemetry, and onSinkError for the local Store. |
memory(options?) |
Implemented per-instance LRU Store. It evicts to both configured bounds, rejects a single oversize value as too_large, honors Store-level expirationTtl with a Clock, and can report pressure eviction of principal-scoped entries without identifiers. |
Calling Store.set() with expirationTtl on a clockless memory Store fails loudly instead of silently ignoring residency. The Cache kernel does not currently pass value TTL through as Store residency, so this behavior matters primarily to direct Store users and replication objects.
CasOrder contains epoch and fence. CasRecord adds an optimistic-concurrency token. CasStore declares seed(key, order), load(key), and swap(key, expectedToken, next). It is an optional atomic compare-and-set capability for durable drivers; the current kernel does not consume it.
Invalidation coordination
Section titled “Invalidation coordination”| Export | Purpose |
|---|---|
Registry |
Registry identity, live checks, soft and hard mutations, and retention registration. |
RegistryAck |
Mutation acknowledgement containing the accepted epoch. |
TagChange |
One tag’s optional soft and hard watermark changes. |
BusFrame |
A contiguous fromEpoch to toEpoch range of changes. |
BusEvent |
frame, gap, reset, or hello event delivered to a subscriber. |
Bus |
Subscribes the kernel to Bus events. The kernel validates continuity. |
Subscription |
Handle with close(). |
The Registry is authoritative; the Bus is a delivery mechanism. A gap or reset suspends warm trust until recovery establishes a verified position.
The Registry contract exposes:
| Member | Meaning |
|---|---|
regId |
Stable Registry identity used to scope and verify recovery-mirror objects. |
check(tags) |
Returns live TagKnowledge for each requested tag. |
expire(tags) |
Advances soft watermarks and returns a RegistryAck. |
delete(tags) |
Advances hard watermarks and returns a RegistryAck. |
registerRetention(retentionMs) |
Registers this instance’s maximum retention. |
RegistryAck contains the accepted epoch. TagChange contains a tag plus optional softEpoch and hardEpoch. BusFrame contains fromEpoch, toEpoch, and a list of changes. BusEvent is one of:
{ kind: “frame”, frame }for a contiguous change frame;{ kind: “gap”, head }when delivery loss is known and the transport declares the minimum head the reader must reach;{ kind: “reset” }when the transport is re-established;{ kind: “hello”, head }immediately after establishment, declaring the live channel’s current head.
Other capabilities
Section titled “Other capabilities”| Export | Purpose and current boundary |
|---|---|
Clock |
now(): number, the kernel’s explicit logical-time source. |
Rng |
next(): number, the kernel’s explicit random source in [0, 1). |
Codec |
Wire identity plus synchronous encode() and decode(). |
Lock |
Acquires a LockHandle for a canonical key. |
LockHandle |
Carries a monotone fence and async release(). |
Cdn |
Accepts a set of tags and a CdnMode. Declared but not called today. |
CdnMode |
CDN acceptance request: enqueue, await, or block. |
See Driver implementations for available implementations.
Consistency and stored data
Section titled “Consistency and stored data”| Export | Meaning |
|---|---|
Consistency |
eventual or strong. |
Watermark |
Monotone softEpoch and hardEpoch for a tag. |
TagKnowledge |
Either known watermarks with a verified throughEpoch, or { known: false }. |
Validity |
Validation result: fresh, stale, dead, or unknown. |
UnknownPolicy |
registry-check, miss, or the provisional error policy. |
Scope |
Explicit public or tenant scope. An omitted scope may derive a principal-local storage class. |
Tier |
Result tier: l1, declared l1.5, l2, origin, or miss. |
Envelope<T> is the exported schema-v3 stored entry. Most applications should not construct envelopes directly.
| Field | Meaning |
|---|---|
v |
Literal schema version 3. |
key |
Canonical namespace-version, namespace, scope, and user-key string. |
val |
Stored value. |
bornEpoch |
Invalidation epoch captured at fill start. |
bornMs |
Fill-start time for TTL, grace, age, and retention arithmetic—not invalidation ordering. |
storedAt |
Observability timestamp. |
ttl, grace |
Stored timing fields. They are zero in current entries. |
tags |
Sorted, deduplicated user and reserved dependency tags. |
scope |
Resolved public, tenant, or principal storage class. |
src |
Source identifier. |
kind |
EnvelopeKind: val or negative neg. |
enc |
EnvelopeEnc: json, json+gz, or bin. |
size |
Stored payload size. |
codecId |
Wire identity checked before decoding. |
fence |
Optional Lock fencing token. |
Render collection and L3
Section titled “Render collection and L3”| Export | Purpose and current boundary |
|---|---|
RenderCollector |
Records dependency tags and makes an eligibility decision at header commit. |
L3Budget |
Optional maxBytes and maxTags limits. |
L3Emission |
Eligibility, emitted cache tags, and optional ineligibility reason. |
L3Ineligibility |
late-tag, budget, scope, or scope-unreadable. |
Explanation |
Discriminated present or absent witness returned by explain(). |
ExplainIdentity |
Stored tags, scope evidence, birth epoch, TTL evidence, and entry kind. |
ExplainVerdict |
Current local validity plus the soft and hard epochs behind it. |
ExplainReaderState |
Applied epoch, suspicion state, and terminal recovery state. |
ExplainScope, ExplainTtl |
Readable-versus-unreadable scope and stored-versus-not-stored TTL evidence. |
ExplainedDependency, ExplainDependencyScope |
Request-scoped render attribution and its scope evidence. |
The collector and React Router header integration are implemented. The CDN purge path remains incomplete.
RenderCollector.dependsOn(tag, { l3? }) records a render-only dependency with no managed scope claim. Setting l3: false excludes its tag from emission, timing, and budget checks. commitHeaders({ maxBytes?, maxTags? }) returns an L3Emission. Automatically recorded hits and fills carry scope evidence; any non-public or unreadable scope makes the emission ineligible and empty.
explain(key) probes L1 then L2 without hydrating L1, live-checking the Registry, or resynchronizing the reader. It addresses the default public canonical key because the signature has no scope input. The present arm contains identity and verdict; both arms contain key, tier, reader, and optional request-scoped requestDependencies. Current entries report TTL as { kind: “not-stored” }.
HTTP failures and errors
Section titled “HTTP failures and errors”HTTP helpers
Section titled “HTTP helpers”httpError(response) returns an HttpError carrying the response and status. isRetriableHttp(error) is the implemented default stale-on-error classifier: it accepts network TypeError values, cache-originated timeouts, selected transient HTTP statuses, and Cloudflare 52x/530 statuses. It does not classify caller aborts or fact-like 403, 404, and 410 responses as retriable.
Error exports
Section titled “Error exports”| Export | Meaning and current boundary |
|---|---|
HttpError |
Typed non-success HTTP response with status and response. |
CacheTimeoutError |
Timeout carrying a CacheTimeoutSource of cache or caller. The kernel does not currently create cache-deadline aborts. |
FencedError |
A plain-value fill was fenced by a conflicting hard invalidation, leaving no value to return. |
InvalidTagError |
Caller supplied a malformed or reserved tag at the cache boundary. |
InvalidDurationError |
duration() received a non-positive, non-finite, fractional-millisecond, or unsafe computed duration. |
FactorySettledError |
A retained factory context declared tags after its factory promise settled. Carries the offending key. |
NotImplementedError |
A declared preview surface was called before implementation. |
RegistryUnavailableError |
Intended strong-read Registry failure. Exported but not emitted by the current path. |
Telemetry
Section titled “Telemetry”| Export | Meaning |
|---|---|
TelemetryEvent |
Event name in type plus event-specific fields. |
TelemetrySink |
Function receiving each emitted event. |
TelemetryEventName |
Union of all values in the event catalog. |
TELEMETRY_EVENTS |
Public event-name catalog for kernel, memory, React Router, and Cloudflare events, including reserved names. |
SinkErrorHook |
Optional observer for a sink failure that built-in delivery swallowed. |
TelemetryConfig |
Sink plus optional hosted flag, project salt, and onSinkError. |
A plain sink may receive raw identifiers. Hosted mode with a salt HMAC-pseudonymizes emitted string fields except the structural event type. Hosted mode without a salt suppresses events rather than forwarding raw strings. Built-in delivery swallows synchronous throws and asynchronous rejections from the sink; it also guards the optional error hook.
Cloudflare adapter exports
Section titled “Cloudflare adapter exports”Import these names from @astilba/cache/cloudflare. The subpath resolves only in a Workers-compatible runtime because Coordinator uses cloudflare:workers.
| Export | Purpose and current boundary |
|---|---|
createWorkersCache(config) |
Composes a Workers Clock and Rng, bounded memory L1, KV L2, named Coordinator Registry, and redialing Bus. |
WorkersCacheConfig |
Requires name, kv, and coordinator; accepts optional CacheDefaults overrides. |
Coordinator |
Durable Object class the Worker must export and bind with a SQLite migration. Its environment requires REGISTRY_KV and accepts Registry heartbeat and snapshot tuning variables. |
cloudflareKV(namespace) |
Builds the Cloudflare KV Store driver. |
doRegistry(stub, regId?) |
Builds the thin Coordinator RPC Registry. The Registry ID must match the named Durable Object identity. |
doBus(dial, options) |
Builds a mechanism-only WebSocket Bus client. It reports closure but does not reconnect itself. |
Dial |
Function returning a compatible client socket synchronously or asynchronously. |
DoBusOptions |
Requires regId and accepts an onClose status callback. |
DoBusCloseInfo |
Close code, reason, and whether the client initiated the closure. |
redialingDoBus(dial, options) |
Wraps doBus() with jittered exponential reconnection. |
RedialOptions |
Registry identity, injected Rng, and optional close callback, scheduler, base delay, and jitter fraction. |
Scheduler |
Injectable delayed-redial seam; the default uses platform timers. |
InvalidRegistryNameError |
A named Coordinator identity violates the lowercase [a-z0-9._-], 1–64-character Registry grammar. |
See Cloudflare Workers for the binding relationship and operational limits.
React Router adapter exports
Section titled “React Router adapter exports”Import these names from @astilba/cache/react-router. React and React Router are optional peer dependencies so root and Cloudflare-only consumers do not need them.
| Export | Purpose and current boundary |
|---|---|
cacheMiddleware(options) |
Creates React Router v8 server middleware that provides Cache, opens request and render frames, triggers poll ticks, and commits scope-safe response headers. |
CacheMiddlewareOptions |
Requires cache; accepts synchronous request identity derivation, waitUntil, telemetry, onSinkError, and an L3 budget override. |
CacheMiddlewareArgs |
The argument object React Router passes to server middleware, re-exported for identity mappers. |
cacheContext |
Typed Router context key. Loaders and actions read the request’s Cache with context.get(cacheContext). |
currentRequest() |
Returns the current AsyncLocalStorage-backed RequestContext, or undefined outside the middleware frame. |
POLL_TICK_FAILED |
The “poll_tick_failed” telemetry event name emitted when out-of-band recovery work rejects. |
TICK_MIN_INTERVAL_MS |
One-second minimum between request-piggyback ticks for the same Cache instance. |
L3_INELIGIBLE |
The “l3_ineligible” event name emitted once for a demoted managed response. |
L3_BUDGET_DEFAULT |
Default 16 KB and 1,000-occurrence response-tag budget. |
The adapter requires nodejs_als on Cloudflare Workers. It preserves an application-authored cache policy for eligible public renders, emits deduplicated user tags, and forces private posture for unsafe renders. It never writes public or s-maxage. See React Router.
Export boundary
Section titled “Export boundary”The publish configuration contains four supported doors: the root entry point, ./cloudflare, ./react-router, and ./package.json. Deep source paths are not public APIs.
The source workspace also exposes @astilba/cache/registry so its test harness and Coordinator can share the state machine. The publish configuration deliberately omits it; applications must not import that source-only subpath.
For implementation gaps, inert fields, and integration availability, continue to Implementation status.