@cloudflare/workers-response-store 1.1.2 → 1.1.3
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 +10 -9
- package/dist/binding.d.ts +4 -1
- package/dist/binding.js +11 -5
- package/dist/cache-policy.d.ts +1 -1
- package/dist/cache-policy.js +2 -1
- package/dist/metadata-do.d.ts +2 -1
- package/dist/metadata-do.js +4 -2
- package/package.json +4 -6
package/README.md
CHANGED
|
@@ -179,14 +179,14 @@ Workers Cache stays off for the Worker as a whole and for `default`; only `Respo
|
|
|
179
179
|
|
|
180
180
|
The object returned by `createWorkersResponseStore()` and `createWorkersResponseStoreClient()` implements the same API:
|
|
181
181
|
|
|
182
|
-
| Method | Behavior
|
|
183
|
-
| ------------------------------------------------ |
|
|
184
|
-
| `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, unless the entry was stored with `expiryBehavior: "miss"`.
|
|
185
|
-
| `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. Set `expiryBehavior: "miss"` to get a miss instead of a regeneration once the entry expires.
|
|
186
|
-
| `refresh({ tags, pathPrefixes })` | Regenerates matching entries, then invalidates their prior edge responses: Workers Cache marks them stale and refetches the committed revisions in the background. At least one selector is required.
|
|
187
|
-
| `invalidate({ tags, pathPrefixes, expire })` | Marks matching entries stale without regenerating them. Reads keep serving them through their stale-while-revalidate window, capped at `expire` seconds after the call when set, and regenerate them like any stale entry. Like Next.js, an `expire` deadline also caps entries with those tags published before it. Workers Cache refetches the edge responses of entries with a revalidator in the background and purges the others. At least one selector is required.
|
|
188
|
-
| `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.
|
|
189
|
-
| `getTagExpiration(tags)` | Returns the latest invalidation timestamp for a set of framework-managed soft tags. Most integrations do not need this low-level method.
|
|
182
|
+
| Method | Behavior |
|
|
183
|
+
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
184
|
+
| `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, unless the entry was stored with `expiryBehavior: "miss"`. A stale entry without a revalidator is returned as stored. |
|
|
185
|
+
| `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; the purge is skipped for a first write, or for a replaced entry without a revalidator once it is stale (unless an `invalidate()` edge purge for it is still queued). Set `expiryBehavior: "miss"` to get a miss instead of a regeneration once the entry expires. |
|
|
186
|
+
| `refresh({ tags, pathPrefixes })` | Regenerates matching entries, then invalidates their prior edge responses: Workers Cache marks them stale and refetches the committed revisions in the background. At least one selector is required. |
|
|
187
|
+
| `invalidate({ tags, pathPrefixes, expire })` | Marks matching entries stale without regenerating them. Reads keep serving them through their stale-while-revalidate window, capped at `expire` seconds after the call when set, and regenerate them like any stale entry. Like Next.js, an `expire` deadline also caps entries with those tags published before it. Workers Cache refetches the edge responses of entries with a revalidator in the background and purges the others. At least one selector is required. |
|
|
188
|
+
| `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. |
|
|
189
|
+
| `getTagExpiration(tags)` | Returns the latest invalidation timestamp for a set of framework-managed soft tags. Most integrations do not need this low-level method. |
|
|
190
190
|
|
|
191
191
|
Mutation methods return:
|
|
192
192
|
|
|
@@ -211,7 +211,7 @@ type ResponseStoreMutationResult = {
|
|
|
211
211
|
|
|
212
212
|
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.
|
|
213
213
|
|
|
214
|
-
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.
|
|
214
|
+
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 and has a revalidator, 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.
|
|
215
215
|
|
|
216
216
|
Set `Cache-Tag` on the response passed to `put()` to associate comma-separated purge tags. `refresh()`, `invalidate()`, and `purge()` also accept pathname prefixes. Tags are matched case-insensitively for invalidation.
|
|
217
217
|
|
|
@@ -289,6 +289,7 @@ application Worker
|
|
|
289
289
|
- 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.
|
|
290
290
|
- Invalidation rewrites each matching R2 object as a stale copy under a higher revision through the same queue, so a write reserved before the invalidation cannot publish over it. If R2 does not hold the entry's committed revision yet, the key is tombstoned instead.
|
|
291
291
|
- 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.
|
|
292
|
+
- An entry stored without a revalidator is served stale through its stale-while-revalidate window until its writer replaces it; nothing regenerates it. Its edge copy gets no stale-while-revalidate or stale-if-error window and expires when the entry goes stale, so a `put()` replacing it from then on needs no edge purge, unless an `invalidate()` made it stale and its edge purge is still queued. The skip assumes the edge holds only that entry's own copy: if an earlier, longer-lived copy outlived a refused purge (a shorter freshness than the entry it replaced, or an entry with a revalidator before it), Workers Cache can serve that copy until it expires, or until Workers Cache revalidates it. Until that replacement, every stale read reaches the binding and R2 instead of Workers Cache.
|
|
292
293
|
- Hard-expired responses are never served. Reads wait for regeneration and therefore require a stored revalidator descriptor, unless the entry was stored with `expiryBehavior: "miss"`: such a read returns a Response Store miss and starts no regeneration, so the caller regenerates the value itself. `refresh()` still regenerates the entry through its revalidator.
|
|
293
294
|
- 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.
|
|
294
295
|
- 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
|
@@ -73,6 +73,8 @@ export type StoredEntry = EntryMetadata & {
|
|
|
73
73
|
cacheKey: string;
|
|
74
74
|
activeRevision: number;
|
|
75
75
|
latestRevision: number;
|
|
76
|
+
/** Set on entries read from R2, whose metadata records only whether a revalidator exists. */
|
|
77
|
+
hasRevalidator?: boolean;
|
|
76
78
|
};
|
|
77
79
|
export type RefreshCandidate = Pick<StoredEntry, "keyHash" | "cacheKey" | "activeRevision" | "latestRevision"> & ({
|
|
78
80
|
hasRevalidator: boolean;
|
|
@@ -185,4 +187,5 @@ export declare class ResponseStoreBinding extends WorkerEntrypoint<WorkersRespon
|
|
|
185
187
|
private updatePendingEdges;
|
|
186
188
|
purge(options: ResponseStorePurgeOptions): Promise<ResponseStoreMutationResult>;
|
|
187
189
|
}
|
|
188
|
-
//#endregion
|
|
190
|
+
//#endregion
|
|
191
|
+
export {};
|
package/dist/binding.js
CHANGED
|
@@ -167,6 +167,9 @@ async function readBodyPrefix(body, prefixLength) {
|
|
|
167
167
|
})
|
|
168
168
|
};
|
|
169
169
|
}
|
|
170
|
+
function hasRevalidator(entry) {
|
|
171
|
+
return entry.hasRevalidator ?? entry.revalidator !== null;
|
|
172
|
+
}
|
|
170
173
|
function purgeTagForEntry(entry) {
|
|
171
174
|
return `runtime-cache-${entry.keyHash}`;
|
|
172
175
|
}
|
|
@@ -322,6 +325,7 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
322
325
|
freshUntil,
|
|
323
326
|
swrUntil,
|
|
324
327
|
revalidator: null,
|
|
328
|
+
hasRevalidator: metadata.noRevalidator !== "1",
|
|
325
329
|
expiryBehavior: metadata.expiryBehavior === "miss" ? "miss" : "regenerate",
|
|
326
330
|
cacheTags: [],
|
|
327
331
|
activeRevision: latestRevision,
|
|
@@ -394,7 +398,8 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
394
398
|
freshUntil: String(entry.freshUntil),
|
|
395
399
|
swrUntil: String(entry.swrUntil),
|
|
396
400
|
latestRevision: String(entry.activeRevision),
|
|
397
|
-
...entry.expiryBehavior === "miss" ? { expiryBehavior: "miss" } : {}
|
|
401
|
+
...entry.expiryBehavior === "miss" ? { expiryBehavior: "miss" } : {},
|
|
402
|
+
...hasRevalidator(entry) ? {} : { noRevalidator: "1" }
|
|
398
403
|
};
|
|
399
404
|
if (customMetadataSize(customMetadata) > R2_CUSTOM_METADATA_SAFE_BYTES) {
|
|
400
405
|
const responseMetadata = new TextEncoder().encode(JSON.stringify({
|
|
@@ -410,7 +415,8 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
410
415
|
freshUntil: String(entry.freshUntil),
|
|
411
416
|
swrUntil: String(entry.swrUntil),
|
|
412
417
|
latestRevision: String(entry.activeRevision),
|
|
413
|
-
...entry.expiryBehavior === "miss" ? { expiryBehavior: "miss" } : {}
|
|
418
|
+
...entry.expiryBehavior === "miss" ? { expiryBehavior: "miss" } : {},
|
|
419
|
+
...hasRevalidator(entry) ? {} : { noRevalidator: "1" }
|
|
414
420
|
};
|
|
415
421
|
}
|
|
416
422
|
return await this.writeR2Revision(this.r2ObjectKey(entry.keyHash), entry.activeRevision, storedBody, customMetadata, expectedEtag);
|
|
@@ -448,7 +454,7 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
448
454
|
if (!headers.has("ETag")) headers.set("ETag", `W/"${encodeURIComponent(entry.objectKey)}:${entry.activeRevision}"`);
|
|
449
455
|
headers.set(AGE_BASIS_HEADER, `${createdAt}:${initialAge}`);
|
|
450
456
|
headers.set("Age", String(representationAge(createdAt, initialAge, now)));
|
|
451
|
-
headers.set("Cloudflare-CDN-Cache-Control", edgeCacheControl(entry.freshUntil, entry.swrUntil, now));
|
|
457
|
+
headers.set("Cloudflare-CDN-Cache-Control", edgeCacheControl(entry.freshUntil, entry.swrUntil, now, hasRevalidator(entry)));
|
|
452
458
|
headers.set("Cache-Tag", cacheTagHeader(entry));
|
|
453
459
|
headers.set("X-Workers-Response-Store", now < entry.freshUntil ? "BLOB-FRESH" : "BLOB-STALE");
|
|
454
460
|
headers.set("X-Workers-Response-Store-Revision", String(entry.activeRevision));
|
|
@@ -617,11 +623,11 @@ var ResponseStoreBinding = class extends WorkerEntrypoint {
|
|
|
617
623
|
headers: MISS_HEADERS
|
|
618
624
|
});
|
|
619
625
|
const now = Date.now();
|
|
620
|
-
const revalidateStale = now >= entry.freshUntil && (request.headers.has("If-None-Match") || request.headers.has("If-Modified-Since"));
|
|
626
|
+
const revalidateStale = hasRevalidator(entry) && now >= entry.freshUntil && (request.headers.has("If-None-Match") || request.headers.has("If-Modified-Since"));
|
|
621
627
|
if (now < entry.swrUntil && !revalidateStale) {
|
|
622
628
|
const stored = await this.readStoredResponse(entry, now, r2Read?.object);
|
|
623
629
|
if (stored) {
|
|
624
|
-
if (now < entry.freshUntil) return stored;
|
|
630
|
+
if (now < entry.freshUntil || !hasRevalidator(entry)) return stored;
|
|
625
631
|
this.ctx.waitUntil(Promise.resolve().then(async () => {
|
|
626
632
|
const metadata = this.getMetadata(keyHash);
|
|
627
633
|
await this.revalidateEntryInBackground(metadata, entry, expectedR2Etag);
|
package/dist/cache-policy.d.ts
CHANGED
|
@@ -7,5 +7,5 @@ export type CachePolicy = {
|
|
|
7
7
|
};
|
|
8
8
|
export declare function deriveCachePolicy(headers: Headers, now?: number): CachePolicy;
|
|
9
9
|
export declare function representationAge(createdAt: number, initialAge: number, now?: number): number;
|
|
10
|
-
export declare function edgeCacheControl(freshUntil: number, swrUntil: number, now?: number): string;
|
|
10
|
+
export declare function edgeCacheControl(freshUntil: number, swrUntil: number, now?: number, hasRevalidator?: boolean): string;
|
|
11
11
|
//#endregion
|
package/dist/cache-policy.js
CHANGED
|
@@ -29,7 +29,8 @@ function deriveCachePolicy(headers, now = Date.now()) {
|
|
|
29
29
|
function representationAge(createdAt, initialAge, now = Date.now()) {
|
|
30
30
|
return initialAge + Math.max(0, Math.floor((now - createdAt) / 1e3));
|
|
31
31
|
}
|
|
32
|
-
function edgeCacheControl(freshUntil, swrUntil, now = Date.now()) {
|
|
32
|
+
function edgeCacheControl(freshUntil, swrUntil, now = Date.now(), hasRevalidator = true) {
|
|
33
|
+
if (!hasRevalidator) return `max-age=${Math.max(0, Math.floor((freshUntil - now) / 1e3))}, stale-while-revalidate=0, stale-if-error=0`;
|
|
33
34
|
if (now < freshUntil) return `max-age=${Math.max(0, Math.ceil((freshUntil - now) / 1e3))}, stale-while-revalidate=${Math.max(0, Math.ceil((swrUntil - freshUntil) / 1e3))}`;
|
|
34
35
|
return `max-age=0, stale-while-revalidate=${Math.max(0, Math.ceil((swrUntil - now) / 1e3))}`;
|
|
35
36
|
}
|
package/dist/metadata-do.d.ts
CHANGED
package/dist/metadata-do.js
CHANGED
|
@@ -461,7 +461,8 @@ var CacheMetadata = class extends DurableObject {
|
|
|
461
461
|
published: false
|
|
462
462
|
};
|
|
463
463
|
}
|
|
464
|
-
const
|
|
464
|
+
const now = Date.now();
|
|
465
|
+
const deadline = this.getTagExpiryDeadline(metadata.cacheTags, now);
|
|
465
466
|
const freshUntil = Math.min(metadata.freshUntil, deadline);
|
|
466
467
|
const swrUntil = Math.min(metadata.swrUntil, deadline);
|
|
467
468
|
const published = this.ctx.storage.sql.exec(`UPDATE entries SET
|
|
@@ -488,8 +489,9 @@ var CacheMetadata = class extends DurableObject {
|
|
|
488
489
|
expiryBehavior: metadata.expiryBehavior,
|
|
489
490
|
cacheTags: metadata.cacheTags
|
|
490
491
|
};
|
|
492
|
+
const replacedEdgeCopyExpired = current.revalidator_id === null && !current.tombstoned && current.fresh_until !== null && now >= current.fresh_until && this.ctx.storage.sql.exec("SELECT 1 FROM pending_r2_tombstones WHERE key_hash = ? AND edge_purge_complete = 0", keyHash).toArray().length === 0;
|
|
491
493
|
return {
|
|
492
|
-
edgePurgeRequired: published && current.active_revision !== null,
|
|
494
|
+
edgePurgeRequired: published && current.active_revision !== null && !replacedEdgeCopyExpired,
|
|
493
495
|
entry: published ? entry : null,
|
|
494
496
|
published
|
|
495
497
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/workers-response-store",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.3",
|
|
4
4
|
"description": "An R2-backed programmatic response store for Cloudflare Workers.",
|
|
5
5
|
"homepage": "https://vinext.dev/",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,9 +28,7 @@
|
|
|
28
28
|
"@types/node": "^25.9.2",
|
|
29
29
|
"miniflare": "5.20260730.0-alpha",
|
|
30
30
|
"typescript": "^7.0.0",
|
|
31
|
-
"vite": "
|
|
32
|
-
"vite-plus": "1.1.0",
|
|
33
|
-
"vitest": "5.0.3",
|
|
31
|
+
"vite-plus": "1.3.0",
|
|
34
32
|
"wrangler": "^4.118.0"
|
|
35
33
|
},
|
|
36
34
|
"engines": {
|
|
@@ -45,7 +43,7 @@
|
|
|
45
43
|
"deploy": "npm run build && wrangler deploy",
|
|
46
44
|
"deploy:service": "npm run build && wrangler deploy --config example/service-binding/wrangler.cache.jsonc && wrangler deploy --config example/service-binding/wrangler.user.jsonc",
|
|
47
45
|
"lint": "vp lint .",
|
|
48
|
-
"test": "npm run check && npm run build:examples &&
|
|
49
|
-
"test:live": "
|
|
46
|
+
"test": "npm run check && npm run build:examples && vp test run tests/e2e.test.ts tests/service-binding-e2e.test.ts",
|
|
47
|
+
"test:live": "vp test run tests/live-e2e.test.ts tests/service-binding-live-e2e.test.ts"
|
|
50
48
|
}
|
|
51
49
|
}
|