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 source walkthrough 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. Construction performs no I/O; retention registration and Bus establishment are deferred until the first read or purge that needs them. 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. Timing fields remain partial; consistency and unavailable-policy fields are active. |
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 |
Makes unknown invalidation knowledge throw UnknownTagError. A true value here or in defaults activates the safety override; false at one level does not cancel true at the other. |
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 lazily when a configured Registry is first used. It has no registration target without that driver. |
consistency |
Default eventual or strong consistency. A per-call value wins; an omitted value otherwise resolves to eventual. |
unknownPolicy |
Chooses registry-check, miss, or error for unknown invalidation knowledge. The error posture throws UnknownTagError. |
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 |
With “eventual”, a failed strong Registry check degrades that call to eventual and emits strong_degraded. Otherwise the read throws RegistryUnavailableError. |
takedownSensitive |
The defaults-level form of the unknown-as-error safety override. If either this value or the top-level value is true, it outranks unknownPolicy and unknown knowledge throws UnknownTagError. |
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. When an opted-in 404 takes the negative disposition, it resolves as undefined; include undefined in T. 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. It distinguishes a present entry, proven absence, and a suppressed Store read failure. |
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 attempt a negative L2 entry. A negative fill and a later read that reaches an invalidation-fresh negative surface undefined; the duration is not enforced. A current servable value in that L2 can refuse the negative write. |
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.
Compatible calls share one foreground factory execution only when key, tags, TTL, grace, negative-cache TTL, resolved scope, codec identity, consistency, and API form agree. A successful fill or an already-revalidated stale serve is shared with its evidence. If the factory-running call had no stale candidate and shares only a classified transient failure, each waiting caller makes its own stale-on-error decision using the candidate it read before joining. The classifier is not invoked when grace is absent. If no caller has a candidate, both API forms propagate the error. If serve-time revalidation rejects a waiting caller’s candidate after a hard invalidation, the plain form propagates the classified error while the entry form returns its documented miss result.
When serve-time validation completes, an opted-in shared 404 has three served dispositions:
- A factory-running caller with
graceand a still-servable stale value suppresses the negative write. Every compatible joiner inherits that value and its evidence. - If that grace-eligible candidate revalidates as dead or unknown, the leader attempts one negative L2 write and every compatible joiner inherits the negative result.
- If the leader has no grace-eligible candidate, it attempts the negative once inside the singleflight window and shares the not-found fact. Each waiter then uses its own earlier read: one with a grace-eligible, still-servable stale value returns it, while one without a servable stale candidate returns
undefined.
Without grace, every compatible caller takes the negative disposition even if it observed a stale value. Validation may instead throw RegistryUnavailableError under the configured unavailable posture.
Before persistence, every negative attempt passes through the L2 negative-write guard. A decodable existing value whose invalidation verdict is fresh or stale—or cannot be established—refuses the write. The not-found disposition still surfaces undefined from origin with durable: false, while the existing L2 value and L1 state remain unchanged. Codec-incompatible, undecodable, or dead L2 bytes do not trigger this guard; normal newer-envelope arbitration still applies afterward.
A negative result that reaches the serve path skips L1 hydration and triggers best-effort deletion of any older L1 copy unless the guard refused the write. This cleanup still runs after a classified retryable write failure. Both a stale-candidate suppression and a guard refusal emit neg_suppressed.
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. A fresh negative keeps the tier, age, and durability evidence of the entry that supplied that fact. |
skipped |
The entry factory called skip(). |
stale |
The returned value was not fresh at this read’s consistency level. |
age |
Whole milliseconds since the served envelope’s bornMs fill-start timestamp, measured with the injected Clock and clamped at zero. A miss or skip reports zero. This is observability, not TTL enforcement. |
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 |
Optional serve evidence. Every newly filled origin result reports whether L2 accepted what that turn produced or a newer durable entry won. A refused negative and a suppressed Store write report false; an L2 hit reports true; a principal-scoped L1 hit reports false. A public or tenant L1 hit omits the field because that serve does not consult L2. |
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.
Serving reads recognize the following structural rejection:
interface ClassifiedStoreReadFailure { readonly code: "throttled" | "unavailable" readonly retryable: boolean readonly cause?: unknown}The shape and its guard are deliberately not root exports, but classification is shape-based rather than instanceof-based. A custom Store can therefore reject get() with that exact shape; the bundled cloudflareKV() driver provides the covered implementation. A classified failure emits store_read_suppressed and acts as a tier miss, while any rejection without both a recognized code and boolean retryable propagates unchanged. explain() reports read-failed when a classified failure prevents it from proving either presence or absence.
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, hello, or lost 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;{ kind: “lost” }when a live transport is unavailable, whether it never established or was later lost.
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 throwing error policy. |
ChannelState |
Reader-observed live-channel state: never-established, established, or lost. |
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 after decoding. For kind: “neg”, the decoded placeholder is internal and a serving read returns undefined instead. |
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 |
Three-arm kind-discriminated witness returned by explain(): present, absent, or read-failed. |
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, terminal recovery state, and ChannelState. |
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. Every arm contains key, reader, and optional request-scoped requestDependencies. The present arm adds tier, identity, and verdict; the proven absent arm reports tier: “miss”; read-failed has no tier or identity because at least one Store did not answer and no other tier supplied the entry. 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 |
A strong Registry check failed and the call was not configured to degrade to eventual. |
UnknownTagError |
Unknown invalidation knowledge reached the error posture. Carries the affected user tags. |
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. |
StrongDegradedReason |
Current reason union for strong_degraded: registry_unreachable. |
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, lazily redialed Bus, and a request-driven recovery carrier. Construction performs no I/O. |
WorkersCacheConfig |
Requires name, kv, and coordinator; accepts optional defaults, kernel telemetry, and takedownSensitive. |
Coordinator |
Durable Object class the Worker must export and bind with a SQLite lifecycle declaration. Prefer the top-level exports map for a new Worker; legacy migrations remain supported. Its environment requires REGISTRY_KV and accepts Registry heartbeat and snapshot tuning variables. |
cloudflareKV(namespace) |
Builds the Cloudflare KV Store driver. |
doRegistry(source, regId?) |
Builds the thin Coordinator RPC Registry from a stub or a thunk that mints one. The Registry ID must match the named Durable Object identity. |
StubSource |
A Coordinator stub or a zero-argument stub factory. Use the thunk form when the Registry outlives a request. |
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 whose due attempts are performed by request-time ticks, never platform timers. |
RedialOptions |
Registry identity, injected Rng, and optional close callback, base delay, and jitter fraction. |
RedialingBusHandle |
A Bus with tick(nowMs); a due tick performs one lazy redial and otherwise does nothing. |
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 middleware request-entry 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. |
On Cloudflare Workers, the package requires a compatibility date of 2024-09-23 or later and the nodejs_compat flag: the root uses node:crypto, and that flag also supplies the AsyncLocalStorage support used by this adapter. nodejs_als alone is insufficient. The middleware 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.