@cloudflare/workers-response-store 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -14
- package/dist/binding.d.ts +1 -0
- package/dist/binding.js +35 -24
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -175,13 +175,13 @@ This is the minimum integration loop. A framework can add its own cacheability r
|
|
|
175
175
|
|
|
176
176
|
The object returned by `createWorkersResponseStore()` and `createWorkersResponseStoreClient()` implements the same API:
|
|
177
177
|
|
|
178
|
-
| Method | Behavior
|
|
179
|
-
| ------------------------------------------------ |
|
|
180
|
-
| `fetch(request)` | Reads a canonical `GET` cache key. Returns a stored response or a `404` Response Store miss.
|
|
181
|
-
| `put(request, response, options?)` | Stores a response under a canonical `GET` cache key. `options.revalidator` supplies `{ id, args }` for future regeneration. Set `purgeExisting: true` when replacing an entry that may already be in Workers Cache.
|
|
182
|
-
| `refresh({ tags, pathPrefixes })` | Regenerates matching entries and purges their prior edge responses. At least one selector is required.
|
|
183
|
-
| `purge({ tags, pathPrefixes, purgeEverything })` | Removes matching metadata, records tag invalidations, deletes response bodies, and purges corresponding edge responses. At least one selector or `purgeEverything: true` is required.
|
|
184
|
-
| `getTagExpiration(tags)` | Returns the latest invalidation timestamp for a set of framework-managed soft tags. Most integrations do not need this low-level method.
|
|
178
|
+
| Method | Behavior |
|
|
179
|
+
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
180
|
+
| `fetch(request)` | Reads a canonical `GET` cache key. Returns a stored response or a `404` Response Store miss. Unconditional stale reads return immediately and regenerate in the background; Workers Cache conditional revalidations and hard-expired reads wait for regeneration. |
|
|
181
|
+
| `put(request, response, options?)` | Stores a response under a canonical `GET` cache key. `options.revalidator` supplies `{ id, args }` for future regeneration. Set `purgeExisting: true` when replacing an entry that may already be in Workers Cache. |
|
|
182
|
+
| `refresh({ tags, pathPrefixes })` | Regenerates matching entries and purges their prior edge responses. At least one selector is required. |
|
|
183
|
+
| `purge({ tags, pathPrefixes, purgeEverything })` | Removes matching metadata, records tag invalidations, deletes response bodies, and purges corresponding edge responses. At least one selector or `purgeEverything: true` is required. |
|
|
184
|
+
| `getTagExpiration(tags)` | Returns the latest invalidation timestamp for a set of framework-managed soft tags. Most integrations do not need this low-level method. |
|
|
185
185
|
|
|
186
186
|
Mutation methods return:
|
|
187
187
|
|
|
@@ -204,16 +204,18 @@ type ResponseStoreMutationResult = {
|
|
|
204
204
|
|
|
205
205
|
Freshness is derived from `Cloudflare-CDN-Cache-Control`, then `CDN-Cache-Control`, then `Cache-Control`. The store preserves an incoming `Age` value and advances it while the response is stored.
|
|
206
206
|
|
|
207
|
+
Stored responses preserve application-provided validators and include a revision-specific `ETag` when none is provided. A generated `Last-Modified` would conflate revisions written within the same second. Workers Cache sends validators back as `If-None-Match` or `If-Modified-Since` when revalidating. If the backing response is stale, that invocation claims regeneration and returns the committed response directly to Workers Cache, avoiding a second layer of SWR. If another invocation already holds the claim, the callback fails so Workers Cache can retain its stale response and retry. Fresh backing responses are reused without regeneration. Conditional headers identify revalidation, including foreground expiry; they do not identify background execution specifically.
|
|
208
|
+
|
|
207
209
|
Set `Cache-Tag` on the response passed to `put()` to associate comma-separated purge tags. `refresh()` and `purge()` also accept pathname prefixes. Tags are matched case-insensitively for invalidation.
|
|
208
210
|
|
|
209
211
|
The `regenerate` callback receives the stored `id` and `args`, a canonical cache-key request, and one of these reasons:
|
|
210
212
|
|
|
211
|
-
| Reason | Trigger
|
|
212
|
-
| --------- |
|
|
213
|
-
| `swr` | A stale
|
|
214
|
-
| `expired` | The response passed its SWR window and the read must wait.
|
|
215
|
-
| `missing` | The R2 object exists but its committed response content is unavailable.
|
|
216
|
-
| `manual` | `refresh()` selected the entry.
|
|
213
|
+
| Reason | Trigger |
|
|
214
|
+
| --------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
215
|
+
| `swr` | A stale entry inside its SWR window is regenerated, either for an unconditional read or a Workers Cache revalidation. |
|
|
216
|
+
| `expired` | The response passed its SWR window and the read must wait. |
|
|
217
|
+
| `missing` | The R2 object exists but its committed response content is unavailable. |
|
|
218
|
+
| `manual` | `refresh()` selected the entry. |
|
|
217
219
|
|
|
218
220
|
### Response headers
|
|
219
221
|
|
|
@@ -278,7 +280,7 @@ application Worker
|
|
|
278
280
|
- SQLite revisions and conditional publication prevent slow writes from replacing newer writes or resurrecting purged entries. User RPC, R2, and cache-purge I/O run outside SQLite transactions.
|
|
279
281
|
- Purging replaces the active R2 object with a higher-revision tombstone. A later put can replace that tombstone, but an older delayed write cannot recreate purged content.
|
|
280
282
|
- R2 tombstones are durably queued in SQLite and drained in bounded batches. A failed R2 operation leaves its tombstone queued so a later purge can retry it instead of losing the anti-resurrection fence.
|
|
281
|
-
-
|
|
283
|
+
- An unconditional read of stale R2 content returns immediately while `ctx.waitUntil()` runs one claimed regeneration. A conditional Workers Cache revalidation instead waits for regeneration and returns the committed replacement in that same invocation.
|
|
282
284
|
- Hard-expired responses are never served. Reads wait for regeneration and therefore require a stored revalidator descriptor.
|
|
283
285
|
- Abandoned write reservations are retained for one hour before alarm-driven cleanup fences them from later publication. Response bodies are written only after Durable Object publication, so this cleanup does not perform R2 operations.
|
|
284
286
|
- RPC-transferred response bodies are buffered before R2 writes because transferred streams do not retain the fixed-length marker required by R2's single-part put API. Account for Worker memory limits when choosing maximum response sizes.
|
package/dist/binding.d.ts
CHANGED
|
@@ -136,6 +136,7 @@ export declare class ResponseStoreBinding extends WorkerEntrypoint<WorkersRespon
|
|
|
136
136
|
private readStoredResponse;
|
|
137
137
|
private storeResponse;
|
|
138
138
|
private regenerateEntry;
|
|
139
|
+
private revalidateEntry;
|
|
139
140
|
private revalidateEntryInBackground;
|
|
140
141
|
fetch(request: Request): Promise<Response>;
|
|
141
142
|
getTagExpiration(tags: string[]): Promise<number>;
|
package/dist/binding.js
CHANGED
|
@@ -252,7 +252,7 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
252
252
|
message: "Workers Response Store cache purge failed",
|
|
253
253
|
error: error instanceof Error ? error.message : String(error)
|
|
254
254
|
}));
|
|
255
|
-
|
|
255
|
+
return false;
|
|
256
256
|
}
|
|
257
257
|
}
|
|
258
258
|
async purgeEdgeCacheByTags(tags) {
|
|
@@ -420,6 +420,7 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
420
420
|
}
|
|
421
421
|
createStoredResponse(entry, body, status, createdAt, initialAge, now = Date.now()) {
|
|
422
422
|
const headers = new Headers(entry.responseHeaders);
|
|
423
|
+
if (!headers.has("ETag")) headers.set("ETag", `W/"${encodeURIComponent(entry.objectKey)}:${entry.activeRevision}"`);
|
|
423
424
|
headers.set(AGE_BASIS_HEADER, `${createdAt}:${initialAge}`);
|
|
424
425
|
headers.set("Age", String(representationAge(createdAt, initialAge, now)));
|
|
425
426
|
headers.set("Cloudflare-CDN-Cache-Control", edgeCacheControl(entry.freshUntil, entry.swrUntil, now));
|
|
@@ -513,8 +514,7 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
513
514
|
}));
|
|
514
515
|
const reconciliationFailures = reconciliation.failures.map((failure) => new Error(failure));
|
|
515
516
|
if (reconciliation.purged.length) try {
|
|
516
|
-
await this.purgeEdgeCacheByTags(reconciliation.purged.map(purgeTagForEntry));
|
|
517
|
-
await metadata.markTombstonesEdgePurged(reconciliation.purged);
|
|
517
|
+
if (await this.purgeEdgeCacheByTags(reconciliation.purged.map(purgeTagForEntry))) await metadata.markTombstonesEdgePurged(reconciliation.purged);
|
|
518
518
|
} catch (reconciliationError) {
|
|
519
519
|
reconciliationFailures.push(reconciliationError instanceof Error ? reconciliationError : new Error(String(reconciliationError)));
|
|
520
520
|
}
|
|
@@ -557,18 +557,21 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
557
557
|
}
|
|
558
558
|
return this.storeResponse(metadata, cacheRequest, response, entry.revalidator, writeReservation, void 0, expectedR2Etag);
|
|
559
559
|
}
|
|
560
|
-
async
|
|
560
|
+
async revalidateEntry(metadata, entry, expectedR2Etag) {
|
|
561
561
|
const claim = await metadata.claimRevalidation(entry.keyHash, entry.activeRevision, entry.cacheKey, this.objectKeyPrefix(entry.keyHash), Date.now(), BACKGROUND_REVALIDATION_LEASE_MS);
|
|
562
|
-
if (!claim) return;
|
|
562
|
+
if (!claim) return null;
|
|
563
|
+
return this.regenerateEntry(metadata, claim.entry, "swr", {
|
|
564
|
+
cacheKey: claim.entry.cacheKey,
|
|
565
|
+
claimId: claim.claimId,
|
|
566
|
+
fenceTags: claim.entry.cacheTags,
|
|
567
|
+
keyHash: claim.entry.keyHash,
|
|
568
|
+
objectKey: claim.objectKey,
|
|
569
|
+
revision: claim.revision
|
|
570
|
+
}, expectedR2Etag);
|
|
571
|
+
}
|
|
572
|
+
async revalidateEntryInBackground(metadata, entry, expectedR2Etag) {
|
|
563
573
|
try {
|
|
564
|
-
await this.
|
|
565
|
-
cacheKey: claim.entry.cacheKey,
|
|
566
|
-
claimId: claim.claimId,
|
|
567
|
-
fenceTags: claim.entry.cacheTags,
|
|
568
|
-
keyHash: claim.entry.keyHash,
|
|
569
|
-
objectKey: claim.objectKey,
|
|
570
|
-
revision: claim.revision
|
|
571
|
-
}, expectedR2Etag);
|
|
574
|
+
await this.revalidateEntry(metadata, entry, expectedR2Etag);
|
|
572
575
|
} catch (error) {
|
|
573
576
|
console.error(JSON.stringify({
|
|
574
577
|
message: "Workers Response Store SWR regeneration failed",
|
|
@@ -588,7 +591,8 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
588
591
|
headers: MISS_HEADERS
|
|
589
592
|
});
|
|
590
593
|
const now = Date.now();
|
|
591
|
-
|
|
594
|
+
const revalidateStale = now >= entry.freshUntil && (request.headers.has("If-None-Match") || request.headers.has("If-Modified-Since"));
|
|
595
|
+
if (now < entry.swrUntil && !revalidateStale) {
|
|
592
596
|
const stored = await this.readStoredResponse(entry, now, r2Read?.object);
|
|
593
597
|
if (stored) {
|
|
594
598
|
if (now < entry.freshUntil) return stored;
|
|
@@ -601,16 +605,23 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
601
605
|
}
|
|
602
606
|
await r2Read?.object?.body.cancel().catch(() => {});
|
|
603
607
|
const metadata = this.getMetadata(keyHash);
|
|
604
|
-
|
|
605
|
-
if (
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
608
|
+
let regenerated;
|
|
609
|
+
if (revalidateStale && now < entry.swrUntil) {
|
|
610
|
+
const result = await this.revalidateEntry(metadata, entry, expectedR2Etag);
|
|
611
|
+
if (!result?.published) throw new Error("Cache entry revalidation is already in progress or was superseded");
|
|
612
|
+
regenerated = result;
|
|
613
|
+
} else {
|
|
614
|
+
const regeneration = await metadata.reserveRegeneration(keyHash, cacheKey.cacheKey, this.objectKeyPrefix(keyHash), now);
|
|
615
|
+
if (!regeneration) return new Response("Workers Response Store miss", {
|
|
616
|
+
status: 404,
|
|
617
|
+
headers: MISS_HEADERS
|
|
618
|
+
});
|
|
619
|
+
regenerated = await this.regenerateEntry(metadata, regeneration.entry, now >= entry.swrUntil ? "expired" : "missing", regeneration.reservation ? {
|
|
620
|
+
...cacheKey,
|
|
621
|
+
fenceTags: regeneration.entry.cacheTags,
|
|
622
|
+
...regeneration.reservation
|
|
623
|
+
} : void 0, expectedR2Etag);
|
|
624
|
+
}
|
|
614
625
|
if (!regenerated.entry) throw new Error("Regeneration was superseded and no active entry remains");
|
|
615
626
|
let response = regenerated.response;
|
|
616
627
|
if (!response) {
|