API reference
Reference every export from the documented @astilba/cache preview snapshot.
This page documents the complete root export surface for this documentation’s preview snapshot. Start with the overview or preview 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 current implementation requires namespace, clock, and rng. A factory fill also requires l2; without it, the fill throws NotImplementedError.
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 a Registry is also configured; L2 separately enables mirror resync and is required for factory fills. |
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. |
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 |
Declared maximum synchronization lag. The documented snapshot does not consume it. |
acceptCodecs |
Additional stored codec identities the current Codec is allowed to decode. |
heartbeatInterval |
Declared coordination heartbeat interval. The documented snapshot does not consume it. |
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 an L3 tag collector. The budget decision works, but Cache hits and framework header commit are not integrated. |
explain(key) |
Promise<Explanation> |
Intended to report dependencies and applied replication positions; currently throws NotImplementedError. |
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 when coordinated invalidation is active; the documented snapshot does not add a separate pre-fill check on a bare miss. |
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?) |
Declared factory-time dependency contribution; currently a no-op. |
setTags(tags) |
Declared factory-time replacement of tags; currently a no-op. |
setTtl(ttl) |
Declared factory-time TTL override; currently a no-op. |
reuseGraced() |
Intended typed reuse of the graced value after provenance checks; currently throws NotImplementedError. |
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 Invalidating data for safe mutation order and API 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 tag builder with escaping and explicit arity. |
t |
Tagged-template builder declared for readable tags; currently throws NotImplementedError. |
globalTag(name) |
Declared globally scoped tag helper; currently throws NotImplementedError. |
User tags beginning with __ are reserved and rejected with InvalidTagError at the cache boundary. compound() is the usable helper in the current source.
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 computed-value helper, but currently throws NotImplementedError. Duration strings can still 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): 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. |
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 |
Declares maxEntries and maxBytes for the planned local Store. |
memory(options?) |
Planned in-process L1 Store; currently throws NotImplementedError. |
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 |
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, or reset 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 |
|---|---|
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” }when delivery loss is known;{ kind: “reset” }when the transport is re-established.
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 Drivers and runtime status 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 or budget. |
Explanation |
Intended output of explain(): key, tags, applied epoch and batch, and dependencies. |
The standalone collector decision exists. Cache-hit contribution, supported header integration, explain(), and the CDN path are incomplete.
RenderCollector.dependsOn(tag, { l3? }) records a dependency; setting l3: false makes it droppable from shared-cache emission. commitHeaders({ maxBytes?, maxTags? }) returns an L3Emission with eligible, cacheTags, and an optional ineligibleReason. Explanation declares key, tags, appliedEpoch, appliedBatch, and dependencies.
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. |
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. |
TelemetryConfig |
Sink plus optional hosted flag and project salt. |
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.
Export boundary
Section titled “Export boundary”The root entry point exports every symbol documented above. The source workspace also exposes an internal @astilba/cache/registry state-machine subpath for the test harness and Cloudflare Coordinator, but the publish configuration omits it. It is not a supported application API and should not be imported from source.
For implementation gaps, inert fields, and integration availability, continue to API status.