@decocms/tanstack 7.85.4 → 7.86.0
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/package.json +4 -4
- package/src/sdk/edgeCacheTelemetry.test.ts +354 -0
- package/src/sdk/edgeCacheTelemetry.ts +155 -0
- package/src/sdk/workerEntry.ts +189 -20
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decocms/tanstack",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.86.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Deco framework binding for TanStack Start + Cloudflare Workers",
|
|
6
6
|
"repository": {
|
|
@@ -26,9 +26,9 @@
|
|
|
26
26
|
"lint:unused": "knip"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@decocms/blocks": "7.
|
|
30
|
-
"@decocms/blocks-admin": "7.
|
|
31
|
-
"@decocms/blocks-cli": "7.
|
|
29
|
+
"@decocms/blocks": "7.86.0",
|
|
30
|
+
"@decocms/blocks-admin": "7.86.0",
|
|
31
|
+
"@decocms/blocks-cli": "7.86.0"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
34
|
"@tanstack/react-query": ">=5.0.0",
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
|
|
3
|
+
import { setBlocks } from "@decocms/blocks/cms";
|
|
4
|
+
import { clearLoaderCache } from "@decocms/blocks/sdk/cachedLoader";
|
|
5
|
+
import { type CacheKVNamespace, createKVCacheStorage } from "@decocms/blocks/sdk/cacheStorage";
|
|
6
|
+
import { configureTracer, type TracerAdapter } from "@decocms/blocks/sdk/observability";
|
|
7
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
8
|
+
import {
|
|
9
|
+
cacheKeyParts,
|
|
10
|
+
EdgeCacheAttr,
|
|
11
|
+
fnv1aHex,
|
|
12
|
+
segmentShape,
|
|
13
|
+
unsafeCookieNames,
|
|
14
|
+
} from "./edgeCacheTelemetry";
|
|
15
|
+
import { createDecoWorkerEntry } from "./workerEntry";
|
|
16
|
+
|
|
17
|
+
// decocms/blocks#824: the edge cache HIT rate of a production storefront sat far
|
|
18
|
+
// below what its own traffic allowed, and nothing the framework emitted could
|
|
19
|
+
// tell key fragmentation, colo spread and failed stores apart. These tests pin
|
|
20
|
+
// what each request records on its span — and that no visitor value leaks.
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// Pure helpers
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
describe("segmentShape", () => {
|
|
27
|
+
it("keeps device, auth and sales channel; reduces every other field to its name", () => {
|
|
28
|
+
expect(segmentShape("mobile|sc=1|r=v2.ABCDEF|gps=-23.55,-46.63|priceTables=1,7")).toBe(
|
|
29
|
+
"mobile|sc=1|r|gps|priceTables",
|
|
30
|
+
);
|
|
31
|
+
expect(segmentShape("desktop|auth|sc=2")).toBe("desktop|auth|sc=2");
|
|
32
|
+
expect(segmentShape("mobile|f=a,b|member")).toBe("mobile|f|member");
|
|
33
|
+
expect(segmentShape("")).toBe("");
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
describe("fnv1aHex", () => {
|
|
38
|
+
it("matches the fnv1a sites already use on X-Cache-Segment (Math.abs, hex)", () => {
|
|
39
|
+
// Reference values from the 32-bit FNV-1a spec, through Math.abs.
|
|
40
|
+
expect(fnv1aHex("")).toBe("811c9dc5");
|
|
41
|
+
expect(fnv1aHex("a")).toBe(Math.abs(0xe40c292c | 0).toString(16));
|
|
42
|
+
expect(fnv1aHex("mobile|sc=1")).toBe(fnv1aHex("mobile|sc=1"));
|
|
43
|
+
expect(fnv1aHex("mobile|sc=1")).not.toBe(fnv1aHex("mobile|sc=2"));
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe("cacheKeyParts", () => {
|
|
48
|
+
it("lists the extra key dimensions by name only", () => {
|
|
49
|
+
expect(
|
|
50
|
+
cacheKeyParts("https://s.test/?__v=abc&__cf_geo=BR%7CSP&__bot=1&__abf=x&__seg=mobile"),
|
|
51
|
+
).toBe("abf,bot,cf_geo");
|
|
52
|
+
expect(cacheKeyParts("https://s.test/p?__v=abc&__fetch=1&__cf_device=mobile")).toBe(
|
|
53
|
+
"fetch,cf_device",
|
|
54
|
+
);
|
|
55
|
+
expect(cacheKeyParts("https://s.test/?__v=abc&__seg=mobile")).toBe("");
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe("unsafeCookieNames", () => {
|
|
60
|
+
it("names the cookies outside the safe list, never their values", () => {
|
|
61
|
+
const res = new Response("x");
|
|
62
|
+
res.headers.append("set-cookie", "vtex_segment=abc; Path=/");
|
|
63
|
+
res.headers.append("set-cookie", "vtex_session=SECRET1; Path=/; HttpOnly");
|
|
64
|
+
res.headers.append("set-cookie", "checkout.vtex.com=__ofid=SECRET2; Path=/");
|
|
65
|
+
res.headers.append("set-cookie", "vtex_session=SECRET3; Domain=.shop.test");
|
|
66
|
+
const names = unsafeCookieNames(res, new Set(["vtex_segment"]));
|
|
67
|
+
expect(names).toBe("vtex_session,checkout.vtex.com");
|
|
68
|
+
expect(names).not.toContain("SECRET");
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Worker entry: what lands on the request span
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
interface RecordedSpan {
|
|
77
|
+
name: string;
|
|
78
|
+
attributes: Record<string, string | number | boolean>;
|
|
79
|
+
ended: boolean;
|
|
80
|
+
}
|
|
81
|
+
let spans: RecordedSpan[] = [];
|
|
82
|
+
const recordingTracer: TracerAdapter = {
|
|
83
|
+
startSpan(name, attributes) {
|
|
84
|
+
const rec: RecordedSpan = { name, attributes: { ...(attributes ?? {}) }, ended: false };
|
|
85
|
+
spans.push(rec);
|
|
86
|
+
return {
|
|
87
|
+
end() {
|
|
88
|
+
rec.ended = true;
|
|
89
|
+
},
|
|
90
|
+
setAttribute(key, value) {
|
|
91
|
+
rec.attributes[key] = value;
|
|
92
|
+
},
|
|
93
|
+
setError() {
|
|
94
|
+
rec.attributes["test.error"] = true;
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
const rootSpan = () => spans.filter((s) => s.name === "deco.http.request").at(-1)!;
|
|
100
|
+
const storeSpans = () => spans.filter((s) => s.name === "deco.cache.store");
|
|
101
|
+
|
|
102
|
+
function makeKV(failPut = false): CacheKVNamespace {
|
|
103
|
+
const values = new Map<string, string>();
|
|
104
|
+
return {
|
|
105
|
+
get: async (key) => values.get(key) ?? null,
|
|
106
|
+
put: async (key, value) => {
|
|
107
|
+
if (failPut) throw new Error("kv put failed");
|
|
108
|
+
values.set(key, value);
|
|
109
|
+
},
|
|
110
|
+
delete: async (key) => {
|
|
111
|
+
values.delete(key);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const jobs: Promise<unknown>[] = [];
|
|
117
|
+
const ctx = { waitUntil: (w: Promise<unknown>) => jobs.push(w), passThroughOnException() {} };
|
|
118
|
+
async function flush() {
|
|
119
|
+
while (jobs.length) await Promise.allSettled(jobs.splice(0));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const GPS = "-23.5505,-46.6333";
|
|
123
|
+
const options = {
|
|
124
|
+
observability: false as const,
|
|
125
|
+
outboundUserAgent: false as const,
|
|
126
|
+
geoCacheKey: "off" as const,
|
|
127
|
+
buildSegment: (req: Request) => ({
|
|
128
|
+
device: "mobile" as const,
|
|
129
|
+
loggedIn: (req.headers.get("cookie") ?? "").includes("VtexIdclientAutCookie"),
|
|
130
|
+
salesChannel: "1",
|
|
131
|
+
regionId: "v2.SECRETREGION",
|
|
132
|
+
gps: GPS,
|
|
133
|
+
}),
|
|
134
|
+
cacheStorage: (bindings: Record<string, unknown>) =>
|
|
135
|
+
createKVCacheStorage(bindings.CACHE as CacheKVNamespace),
|
|
136
|
+
};
|
|
137
|
+
const env = (failPut = false) => ({ CACHE: makeKV(failPut), BUILD_HASH: "0123456789abcdef" });
|
|
138
|
+
|
|
139
|
+
const htmlOrigin = (init?: ResponseInit) => ({
|
|
140
|
+
fetch: vi.fn(
|
|
141
|
+
async () =>
|
|
142
|
+
new Response("<html>ok</html>", {
|
|
143
|
+
...init,
|
|
144
|
+
headers: { "content-type": "text/html", ...(init?.headers ?? {}) },
|
|
145
|
+
}),
|
|
146
|
+
),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
function page(path: string, headers: Record<string, string> = {}) {
|
|
150
|
+
const req = new Request(`https://shop.test${path}`, {
|
|
151
|
+
headers: { accept: "text/html", ...headers },
|
|
152
|
+
});
|
|
153
|
+
// workerd attaches `cf`; Node's Request does not.
|
|
154
|
+
Object.defineProperty(req, "cf", { value: { colo: "GRU" } });
|
|
155
|
+
return req;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Every attribute value on every span, for the "no visitor value" assertion. */
|
|
159
|
+
const allValues = () => spans.flatMap((s) => Object.values(s.attributes).map(String)).join("\n");
|
|
160
|
+
|
|
161
|
+
beforeEach(() => {
|
|
162
|
+
clearLoaderCache();
|
|
163
|
+
setBlocks({});
|
|
164
|
+
spans = [];
|
|
165
|
+
configureTracer(recordingTracer);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
afterEach(async () => {
|
|
169
|
+
await flush();
|
|
170
|
+
configureTracer(null as unknown as TracerAdapter);
|
|
171
|
+
vi.restoreAllMocks();
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
describe("edge cache telemetry on the request span", () => {
|
|
175
|
+
it("MISS that is stored: key dimensions, put, and the settled store outcome", async () => {
|
|
176
|
+
const worker = createDecoWorkerEntry(htmlOrigin(), options);
|
|
177
|
+
const res = await worker.fetch(page("/"), env(), ctx);
|
|
178
|
+
expect(res.headers.get("X-Cache")).toBe("MISS");
|
|
179
|
+
await flush();
|
|
180
|
+
|
|
181
|
+
const attrs = rootSpan().attributes;
|
|
182
|
+
expect(attrs[EdgeCacheAttr.STATUS]).toBe("MISS");
|
|
183
|
+
expect(attrs[EdgeCacheAttr.KIND]).toBe("html");
|
|
184
|
+
expect(attrs[EdgeCacheAttr.PROFILE]).toBe(res.headers.get("X-Cache-Profile"));
|
|
185
|
+
expect(attrs[EdgeCacheAttr.VERSION]).toBe("01234567");
|
|
186
|
+
expect(attrs[EdgeCacheAttr.COLO]).toBe("GRU");
|
|
187
|
+
expect(attrs[EdgeCacheAttr.SEGMENT_SHAPE]).toBe("mobile|sc=1|r|gps");
|
|
188
|
+
// Same hash a site computes from the X-Cache-Segment header it receives.
|
|
189
|
+
expect(attrs[EdgeCacheAttr.SEGMENT_HASH]).toBe(
|
|
190
|
+
fnv1aHex(res.headers.get("X-Cache-Segment") ?? ""),
|
|
191
|
+
);
|
|
192
|
+
expect(attrs[EdgeCacheAttr.KEY_HASH]).toMatch(/^[0-9a-f]+$/);
|
|
193
|
+
expect(attrs[EdgeCacheAttr.KEY_PARTS]).toBe("");
|
|
194
|
+
expect(attrs[EdgeCacheAttr.STORE]).toBe("put");
|
|
195
|
+
expect(attrs[EdgeCacheAttr.BYPASS_REASON]).toBeUndefined();
|
|
196
|
+
|
|
197
|
+
expect(storeSpans()).toHaveLength(1);
|
|
198
|
+
expect(storeSpans()[0].attributes[EdgeCacheAttr.STORE_OUTCOME]).toBe("stored");
|
|
199
|
+
|
|
200
|
+
expect(allValues()).not.toContain(GPS);
|
|
201
|
+
expect(allValues()).not.toContain("SECRETREGION");
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it("HIT: same key hash as the MISS that filled it, no store", async () => {
|
|
205
|
+
const worker = createDecoWorkerEntry(htmlOrigin(), options);
|
|
206
|
+
const bindings = env();
|
|
207
|
+
await worker.fetch(page("/"), bindings, ctx);
|
|
208
|
+
await flush();
|
|
209
|
+
const missKey = rootSpan().attributes[EdgeCacheAttr.KEY_HASH];
|
|
210
|
+
|
|
211
|
+
spans = [];
|
|
212
|
+
const res = await worker.fetch(page("/"), bindings, ctx);
|
|
213
|
+
expect(res.headers.get("X-Cache")).toBe("HIT");
|
|
214
|
+
|
|
215
|
+
const attrs = rootSpan().attributes;
|
|
216
|
+
expect(attrs[EdgeCacheAttr.STATUS]).toBe("HIT");
|
|
217
|
+
expect(attrs[EdgeCacheAttr.KEY_HASH]).toBe(missKey);
|
|
218
|
+
expect(attrs[EdgeCacheAttr.COLO]).toBe("GRU");
|
|
219
|
+
expect(attrs[EdgeCacheAttr.SEGMENT_SHAPE]).toBe("mobile|sc=1|r|gps");
|
|
220
|
+
expect(attrs[EdgeCacheAttr.STORE]).toBeUndefined();
|
|
221
|
+
expect(storeSpans()).toHaveLength(0);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("MISS not stored because of an unsafe Set-Cookie: names the cookies, not their values", async () => {
|
|
225
|
+
const origin = {
|
|
226
|
+
fetch: vi.fn(async () => {
|
|
227
|
+
const r = new Response("<html>ok</html>", { headers: { "content-type": "text/html" } });
|
|
228
|
+
r.headers.append("set-cookie", "vtex_segment=public; Path=/");
|
|
229
|
+
r.headers.append("set-cookie", "vtex_session=TOKEN123; Path=/; HttpOnly");
|
|
230
|
+
return r;
|
|
231
|
+
}),
|
|
232
|
+
};
|
|
233
|
+
const worker = createDecoWorkerEntry(origin, options);
|
|
234
|
+
const res = await worker.fetch(page("/"), env(), ctx);
|
|
235
|
+
// The response is labelled BYPASS; the span keeps the lookup's MISS.
|
|
236
|
+
expect(res.headers.get("X-Cache")).toBe("BYPASS");
|
|
237
|
+
expect(res.headers.get("X-Cache-Reason")).toBe("private-set-cookie");
|
|
238
|
+
await flush();
|
|
239
|
+
|
|
240
|
+
const attrs = rootSpan().attributes;
|
|
241
|
+
expect(attrs[EdgeCacheAttr.STATUS]).toBe("MISS");
|
|
242
|
+
expect(attrs[EdgeCacheAttr.STORE]).toBe("skipped:unsafe-cookie");
|
|
243
|
+
expect(attrs[EdgeCacheAttr.STORE_UNSAFE_COOKIES]).toBe("vtex_session");
|
|
244
|
+
expect(storeSpans()).toHaveLength(0);
|
|
245
|
+
expect(allValues()).not.toContain("TOKEN123");
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("BYPASS for a logged-in visitor: reason, no key or store", async () => {
|
|
249
|
+
const worker = createDecoWorkerEntry(htmlOrigin(), options);
|
|
250
|
+
const res = await worker.fetch(
|
|
251
|
+
page("/", { cookie: "VtexIdclientAutCookie_store=JWTVALUE" }),
|
|
252
|
+
env(),
|
|
253
|
+
ctx,
|
|
254
|
+
);
|
|
255
|
+
expect(res.headers.get("X-Cache")).toBe("BYPASS");
|
|
256
|
+
|
|
257
|
+
const attrs = rootSpan().attributes;
|
|
258
|
+
expect(attrs[EdgeCacheAttr.STATUS]).toBe("BYPASS");
|
|
259
|
+
expect(attrs[EdgeCacheAttr.BYPASS_REASON]).toBe("logged-in");
|
|
260
|
+
expect(attrs[EdgeCacheAttr.KIND]).toBe("html");
|
|
261
|
+
expect(attrs[EdgeCacheAttr.COLO]).toBe("GRU");
|
|
262
|
+
expect(attrs[EdgeCacheAttr.STORE]).toBeUndefined();
|
|
263
|
+
expect(allValues()).not.toContain("JWTVALUE");
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("BYPASS for a non-GET document request names the method", async () => {
|
|
267
|
+
const worker = createDecoWorkerEntry(htmlOrigin(), options);
|
|
268
|
+
await worker.fetch(
|
|
269
|
+
new Request("https://shop.test/contact", { method: "PUT", body: "x" }),
|
|
270
|
+
env(),
|
|
271
|
+
ctx,
|
|
272
|
+
);
|
|
273
|
+
expect(rootSpan().attributes[EdgeCacheAttr.BYPASS_REASON]).toBe("method:PUT");
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("records extra key parts (bot, fetch) by name", async () => {
|
|
277
|
+
const worker = createDecoWorkerEntry(htmlOrigin(), options);
|
|
278
|
+
await worker.fetch(
|
|
279
|
+
page("/", { "user-agent": "Googlebot/2.1", "sec-fetch-dest": "empty" }),
|
|
280
|
+
env(),
|
|
281
|
+
ctx,
|
|
282
|
+
);
|
|
283
|
+
expect(rootSpan().attributes[EdgeCacheAttr.KEY_PARTS]).toBe("bot,fetch");
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it("a failed cache.put shows up as outcome=error on the store span", async () => {
|
|
287
|
+
const worker = createDecoWorkerEntry(htmlOrigin(), options);
|
|
288
|
+
await worker.fetch(page("/"), env(true), ctx);
|
|
289
|
+
await flush();
|
|
290
|
+
expect(rootSpan().attributes[EdgeCacheAttr.STORE]).toBe("put");
|
|
291
|
+
expect(storeSpans()[0].attributes[EdgeCacheAttr.STORE_OUTCOME]).toBe("error");
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("POST server fn: kind, key and store decision; a Set-Cookie lists every name", async () => {
|
|
295
|
+
const sfn = (cookie?: string) => ({
|
|
296
|
+
fetch: vi.fn(async () => {
|
|
297
|
+
const r = new Response("{}", {
|
|
298
|
+
headers: { "content-type": "application/json", "X-Deco-Cacheable": "true" },
|
|
299
|
+
});
|
|
300
|
+
if (cookie) r.headers.append("set-cookie", cookie);
|
|
301
|
+
return r;
|
|
302
|
+
}),
|
|
303
|
+
});
|
|
304
|
+
const post = () => {
|
|
305
|
+
const req = new Request("https://shop.test/_serverFn/abc", { method: "POST", body: "{}" });
|
|
306
|
+
Object.defineProperty(req, "cf", { value: { colo: "GIG" } });
|
|
307
|
+
return req;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
await createDecoWorkerEntry(sfn(), options).fetch(post(), env(), ctx);
|
|
311
|
+
await flush();
|
|
312
|
+
let attrs = rootSpan().attributes;
|
|
313
|
+
expect(attrs[EdgeCacheAttr.KIND]).toBe("serverFn");
|
|
314
|
+
expect(attrs[EdgeCacheAttr.STATUS]).toBe("MISS");
|
|
315
|
+
expect(attrs[EdgeCacheAttr.COLO]).toBe("GIG");
|
|
316
|
+
expect(attrs[EdgeCacheAttr.STORE]).toBe("put");
|
|
317
|
+
expect(storeSpans()[0].attributes[EdgeCacheAttr.STORE_OUTCOME]).toBe("stored");
|
|
318
|
+
|
|
319
|
+
spans = [];
|
|
320
|
+
await createDecoWorkerEntry(sfn("vtex_segment=v; Path=/"), options).fetch(post(), env(), ctx);
|
|
321
|
+
attrs = rootSpan().attributes;
|
|
322
|
+
expect(attrs[EdgeCacheAttr.STORE]).toBe("skipped:set-cookie");
|
|
323
|
+
expect(attrs[EdgeCacheAttr.STORE_UNSAFE_COOKIES]).toBe("vtex_segment");
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it("is observation only: the opt-out stamps nothing and serves the same", async () => {
|
|
327
|
+
const on = createDecoWorkerEntry(htmlOrigin(), options);
|
|
328
|
+
const off = createDecoWorkerEntry(htmlOrigin(), { ...options, edgeCacheTelemetry: false });
|
|
329
|
+
const bOn = env();
|
|
330
|
+
const bOff = env();
|
|
331
|
+
const seqOn: Array<string | null> = [];
|
|
332
|
+
const seqOff: Array<string | null> = [];
|
|
333
|
+
for (let i = 0; i < 2; i++) {
|
|
334
|
+
seqOn.push((await on.fetch(page("/"), bOn, ctx)).headers.get("X-Cache"));
|
|
335
|
+
await flush();
|
|
336
|
+
}
|
|
337
|
+
spans = [];
|
|
338
|
+
for (let i = 0; i < 2; i++) {
|
|
339
|
+
seqOff.push((await off.fetch(page("/"), bOff, ctx)).headers.get("X-Cache"));
|
|
340
|
+
await flush();
|
|
341
|
+
}
|
|
342
|
+
expect(seqOff).toEqual(seqOn);
|
|
343
|
+
expect(seqOn).toEqual(["MISS", "HIT"]);
|
|
344
|
+
const keys = spans.flatMap((s) => Object.keys(s.attributes));
|
|
345
|
+
for (const attr of [
|
|
346
|
+
EdgeCacheAttr.KEY_HASH,
|
|
347
|
+
EdgeCacheAttr.SEGMENT_SHAPE,
|
|
348
|
+
EdgeCacheAttr.STORE,
|
|
349
|
+
EdgeCacheAttr.STORE_OUTCOME,
|
|
350
|
+
]) {
|
|
351
|
+
expect(keys).not.toContain(attr);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
});
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edge cache telemetry — what `createDecoWorkerEntry` records about every
|
|
3
|
+
* cacheable document / server-function request, so a low HIT rate can be
|
|
4
|
+
* explained from traces instead of guessed at (decocms/blocks#824).
|
|
5
|
+
*
|
|
6
|
+
* Everything here is OBSERVATION ONLY: these helpers read the key, the segment
|
|
7
|
+
* and the origin response the worker already computed. They never feed back
|
|
8
|
+
* into the cache key, the TTLs or the store decision.
|
|
9
|
+
*
|
|
10
|
+
* The attributes are stamped on the active span — the `deco.http.request` root
|
|
11
|
+
* span — so they ride the existing OTLP trace export at the existing head
|
|
12
|
+
* sampling rate (`DECO_OTEL_TRACES_SAMPLING_RATE`, or `?__d=` for one request).
|
|
13
|
+
* No new span, metric point or log line is produced per request.
|
|
14
|
+
*
|
|
15
|
+
* Privacy: no attribute carries a value a visitor brings. The segment travels
|
|
16
|
+
* as a hash plus its "shape" (field names; device, login and sales channel are
|
|
17
|
+
* kept because they are a handful of values and what the key is for); cookies
|
|
18
|
+
* travel as names only.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Span attribute keys. `deco.cache.status` / `deco.cache.profile` are shared with `recordCacheMetric`. */
|
|
22
|
+
export const EdgeCacheAttr = {
|
|
23
|
+
/** `HIT` | `STALE-HIT` | `STALE-ERROR` | `MISS` (set by `recordCacheMetric`) or `BYPASS` (set here). */
|
|
24
|
+
STATUS: "deco.cache.status",
|
|
25
|
+
/** Why the lookup was skipped. Only on `BYPASS`. */
|
|
26
|
+
BYPASS_REASON: "deco.cache.bypass_reason",
|
|
27
|
+
/** `html` (document or GET server fn keyed as a page) | `serverFn` (POST server fn, body-hash key). */
|
|
28
|
+
KIND: "deco.cache.kind",
|
|
29
|
+
PROFILE: "deco.cache.profile",
|
|
30
|
+
/** First 8 chars of the cache-key version (`__v`, the build hash). */
|
|
31
|
+
VERSION: "deco.cache.version",
|
|
32
|
+
/** Cloudflare data center (`request.cf.colo`) — the Cache API is per colo. Same key as the request metric label. */
|
|
33
|
+
COLO: "deco.http.region",
|
|
34
|
+
/** fnv1a of the serialized segment (the `X-Cache-Segment` value), hex. */
|
|
35
|
+
SEGMENT_HASH: "deco.cache.segment.hash",
|
|
36
|
+
/** The serialized segment with values reduced to field names, e.g. `mobile|sc=1|r|gps`. */
|
|
37
|
+
SEGMENT_SHAPE: "deco.cache.segment.shape",
|
|
38
|
+
/** fnv1a of the full synthetic cache-key URL, hex: distinct keys per page. */
|
|
39
|
+
KEY_HASH: "deco.cache.key.hash",
|
|
40
|
+
/** Extra key dimensions present, comma-separated (`abf,bot,fetch,cf_geo,cf_device`); `""` for none. */
|
|
41
|
+
KEY_PARTS: "deco.cache.key.parts",
|
|
42
|
+
/** What happened to the origin response after a lookup that did not serve from cache. */
|
|
43
|
+
STORE: "deco.cache.store",
|
|
44
|
+
/** Names of the `Set-Cookie`s that kept a response out of the cache. */
|
|
45
|
+
STORE_UNSAFE_COOKIES: "deco.cache.store.unsafe_cookies",
|
|
46
|
+
/**
|
|
47
|
+
* On the `deco.cache.store` span, once `cache.put` settles: `stored` |
|
|
48
|
+
* `skipped:uncacheable` | `skipped:too-large` | `error` (`ResponseCachePutResult`).
|
|
49
|
+
*/
|
|
50
|
+
STORE_OUTCOME: "deco.cache.store.outcome",
|
|
51
|
+
} as const;
|
|
52
|
+
|
|
53
|
+
export type EdgeCacheKind = "html" | "serverFn";
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Why a request never looked the cache up. `method:<VERB>` covers everything
|
|
57
|
+
* that is not a GET (POST server functions have their own key and do look up).
|
|
58
|
+
*/
|
|
59
|
+
export type EdgeCacheBypassReason =
|
|
60
|
+
| "logged-in"
|
|
61
|
+
| "draft-preview"
|
|
62
|
+
| "preview"
|
|
63
|
+
| "path-template"
|
|
64
|
+
| "matchers-override"
|
|
65
|
+
| "bypass-path"
|
|
66
|
+
| `method:${string}`;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Outcome of a lookup that did not serve from cache.
|
|
70
|
+
*
|
|
71
|
+
* - `put` — `cache.put` was issued (in `waitUntil`); whether it landed is on the
|
|
72
|
+
* child `deco.cache.store` span as `deco.cache.store.outcome`.
|
|
73
|
+
* - `skipped:*` — not stored, and why. `unsafe-cookie` (HTML) means a
|
|
74
|
+
* `Set-Cookie` outside `safeCookies`; `set-cookie` (POST server fn) means any
|
|
75
|
+
* `Set-Cookie`, which that path refuses outright.
|
|
76
|
+
*/
|
|
77
|
+
export type EdgeCacheStoreDecision =
|
|
78
|
+
| "put"
|
|
79
|
+
| "skipped:unsafe-cookie"
|
|
80
|
+
| "skipped:set-cookie"
|
|
81
|
+
| "skipped:non-200"
|
|
82
|
+
| "skipped:degraded"
|
|
83
|
+
| "skipped:tracking"
|
|
84
|
+
| "skipped:profile"
|
|
85
|
+
| "skipped:not-cacheable"
|
|
86
|
+
| "skipped:no-cache";
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 32-bit FNV-1a, hex. Same function (including the `Math.abs`) sites already
|
|
90
|
+
* use to hash `X-Cache-Segment` in their own analytics rows, so a trace and a
|
|
91
|
+
* site-side row of the same request carry the same segment hash.
|
|
92
|
+
*/
|
|
93
|
+
export function fnv1aHex(str: string): string {
|
|
94
|
+
let hash = 0x811c9dc5;
|
|
95
|
+
for (let i = 0; i < str.length; i++) {
|
|
96
|
+
hash ^= str.charCodeAt(i);
|
|
97
|
+
hash = Math.imul(hash, 0x01000193);
|
|
98
|
+
}
|
|
99
|
+
return Math.abs(hash).toString(16);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const KEPT_SEGMENT_PART = /^(auth|sc=[^|]{0,16})$/;
|
|
103
|
+
const MAX_SHAPE_LENGTH = 128;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The serialized segment (`hashSegment` output: `device|auth|sc=1|r=…|k=v…`)
|
|
107
|
+
* with every value a visitor brings dropped: the device (first part), `auth`
|
|
108
|
+
* and `sc=<channel>` stay; any other part keeps only its name.
|
|
109
|
+
*
|
|
110
|
+
* `mobile|sc=1|r=v2.ABC|gps=-23.5,-46.6` → `mobile|sc=1|r|gps`.
|
|
111
|
+
*/
|
|
112
|
+
export function segmentShape(serialized: string): string {
|
|
113
|
+
if (!serialized) return "";
|
|
114
|
+
const parts = serialized.split("|");
|
|
115
|
+
const shaped = parts.map((part, i) => {
|
|
116
|
+
if (i === 0) return part.slice(0, 16);
|
|
117
|
+
if (KEPT_SEGMENT_PART.test(part)) return part;
|
|
118
|
+
return part.split("=")[0];
|
|
119
|
+
});
|
|
120
|
+
return shaped.join("|").slice(0, MAX_SHAPE_LENGTH);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const KEY_PART_PARAMS: ReadonlyArray<readonly [string, string]> = [
|
|
124
|
+
["__abf", "abf"],
|
|
125
|
+
["__bot", "bot"],
|
|
126
|
+
["__fetch", "fetch"],
|
|
127
|
+
["__cf_geo", "cf_geo"],
|
|
128
|
+
["__cf_device", "cf_device"],
|
|
129
|
+
];
|
|
130
|
+
|
|
131
|
+
/** Which optional dimensions the synthetic cache key carries — names only, never values. */
|
|
132
|
+
export function cacheKeyParts(keyUrl: string): string {
|
|
133
|
+
const params = new URL(keyUrl).searchParams;
|
|
134
|
+
return KEY_PART_PARAMS.filter(([param]) => params.has(param))
|
|
135
|
+
.map(([, name]) => name)
|
|
136
|
+
.join(",");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Names of the cookies a response sets that are not in `safe`, deduplicated,
|
|
141
|
+
* in order. Names only — the values are per-visitor tokens.
|
|
142
|
+
*/
|
|
143
|
+
export function unsafeCookieNames(response: Response, safe: ReadonlySet<string>): string {
|
|
144
|
+
const setCookies = response.headers.getSetCookie?.() ?? [];
|
|
145
|
+
const names: string[] = [];
|
|
146
|
+
for (const sc of setCookies) {
|
|
147
|
+
const eq = sc.indexOf("=");
|
|
148
|
+
const name = eq > 0 ? sc.slice(0, eq).trim() : "";
|
|
149
|
+
if (!name || safe.has(name) || names.includes(name)) continue;
|
|
150
|
+
names.push(name);
|
|
151
|
+
}
|
|
152
|
+
// A Set-Cookie the parser could not split is what made the response unsafe.
|
|
153
|
+
if (names.length === 0 && response.headers.has("set-cookie")) return "(unparsed)";
|
|
154
|
+
return names.join(",").slice(0, 256);
|
|
155
|
+
}
|
package/src/sdk/workerEntry.ts
CHANGED
|
@@ -88,7 +88,10 @@ import {
|
|
|
88
88
|
setRedirectSemantics,
|
|
89
89
|
} from "@decocms/blocks/sdk/redirects";
|
|
90
90
|
import { RequestContext } from "@decocms/blocks/sdk/requestContext";
|
|
91
|
-
import {
|
|
91
|
+
import {
|
|
92
|
+
createResponseCache,
|
|
93
|
+
type ResponseCachePutResult,
|
|
94
|
+
} from "@decocms/blocks/sdk/responseCache";
|
|
92
95
|
import { cleanPathForCacheKey, hasTrackingParams } from "@decocms/blocks/sdk/urlUtils";
|
|
93
96
|
import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
|
|
94
97
|
import { LIVE_CONTROLS_SCRIPT } from "@decocms/blocks-admin/admin/liveControls";
|
|
@@ -106,6 +109,16 @@ import {
|
|
|
106
109
|
registerDraftOverride,
|
|
107
110
|
requestCarriesDraft,
|
|
108
111
|
} from "./draft";
|
|
112
|
+
import {
|
|
113
|
+
cacheKeyParts,
|
|
114
|
+
EdgeCacheAttr,
|
|
115
|
+
type EdgeCacheBypassReason,
|
|
116
|
+
type EdgeCacheKind,
|
|
117
|
+
type EdgeCacheStoreDecision,
|
|
118
|
+
fnv1aHex,
|
|
119
|
+
segmentShape,
|
|
120
|
+
unsafeCookieNames,
|
|
121
|
+
} from "./edgeCacheTelemetry";
|
|
109
122
|
import { ensureBlocksHydrated, getDataCacheVersion, maybePollRevision } from "./kvHydration";
|
|
110
123
|
import { lookupExactRedirect } from "./kvRedirects";
|
|
111
124
|
import { DECO_POWERED_BY, installDefaultUserAgent } from "./outboundHeaders";
|
|
@@ -638,6 +651,25 @@ export interface DecoWorkerEntryOptions {
|
|
|
638
651
|
*/
|
|
639
652
|
observability?: OtelOptions | false;
|
|
640
653
|
|
|
654
|
+
/**
|
|
655
|
+
* Edge cache telemetry on the request span (`deco.http.request`): for every
|
|
656
|
+
* document / server-function request that reaches the cache layer, the
|
|
657
|
+
* decision and bypass reason, profile, short cache-key version, colo,
|
|
658
|
+
* segment hash and shape, a hash of the full key, which extra key parts
|
|
659
|
+
* applied (`__abf`, `__bot`, `__fetch`, `__cf_geo`, `__cf_device`) and, on a
|
|
660
|
+
* miss, what happened to the store. Attribute keys are in
|
|
661
|
+
* `EdgeCacheAttr` (`./edgeCacheTelemetry`).
|
|
662
|
+
*
|
|
663
|
+
* Observation only — keys, TTLs and store decisions are identical either
|
|
664
|
+
* way. Rides the existing trace export and its head sampling
|
|
665
|
+
* (`DECO_OTEL_TRACES_SAMPLING_RATE`); adds no span, metric point or log line.
|
|
666
|
+
* No visitor value is recorded: segment values are hashed or reduced to
|
|
667
|
+
* field names, cookies to names. Inert when no tracer is configured.
|
|
668
|
+
*
|
|
669
|
+
* @default true
|
|
670
|
+
*/
|
|
671
|
+
edgeCacheTelemetry?: boolean;
|
|
672
|
+
|
|
641
673
|
/**
|
|
642
674
|
* Default `User-Agent` for OUTBOUND `fetch` calls (loaders, commerce
|
|
643
675
|
* APIs, proxies). Cloudflare Workers sends no User-Agent at all, and
|
|
@@ -1315,6 +1347,7 @@ export function createDecoWorkerEntry(
|
|
|
1315
1347
|
staticPaths: staticPathsOpt = DEFAULT_STATIC_PATHS,
|
|
1316
1348
|
cdnCacheControl: cdnCacheControlOpt = "serverfn-segment",
|
|
1317
1349
|
observability: observabilityOpt,
|
|
1350
|
+
edgeCacheTelemetry: edgeCacheTelemetryOpt = true,
|
|
1318
1351
|
outboundUserAgent: outboundUserAgentOpt,
|
|
1319
1352
|
speculationRules: speculationRulesOpt,
|
|
1320
1353
|
} = options;
|
|
@@ -1501,20 +1534,111 @@ export function createDecoWorkerEntry(
|
|
|
1501
1534
|
return staticPathsOpt.some((sp) => pathname.startsWith(sp));
|
|
1502
1535
|
}
|
|
1503
1536
|
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
if (
|
|
1537
|
+
/** Why a request skips the edge cache, or `null` when it is cacheable. */
|
|
1538
|
+
function nonCacheableReason(request: Request, url: URL): EdgeCacheBypassReason | null {
|
|
1539
|
+
if (request.method !== "GET") return `method:${request.method}`;
|
|
1540
|
+
if (isBypassPath(url.pathname)) return "bypass-path";
|
|
1507
1541
|
// Draft preview: never cache a request in draft mode. Keys on the real
|
|
1508
1542
|
// `?__draft=` param OR the navigation cookie (SPA nav after entry), gated
|
|
1509
1543
|
// on an allowed preview host — see requestCarriesDraft.
|
|
1510
|
-
if (requestCarriesDraft(request, url)) return
|
|
1511
|
-
if (url.searchParams.has("__deco_preview")) return
|
|
1512
|
-
if (url.searchParams.has("pathTemplate")) return
|
|
1544
|
+
if (requestCarriesDraft(request, url)) return "draft-preview";
|
|
1545
|
+
if (url.searchParams.has("__deco_preview")) return "preview";
|
|
1546
|
+
if (url.searchParams.has("pathTemplate")) return "path-template";
|
|
1513
1547
|
// Forced matcher results must never be served from (or stored in) the
|
|
1514
1548
|
// shared edge cache.
|
|
1515
|
-
if (url.searchParams.has(DECO_MATCHERS_OVERRIDE_PARAM)) return
|
|
1516
|
-
if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) return
|
|
1517
|
-
return
|
|
1549
|
+
if (url.searchParams.has(DECO_MATCHERS_OVERRIDE_PARAM)) return "matchers-override";
|
|
1550
|
+
if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) return "matchers-override";
|
|
1551
|
+
return null;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// -- Edge cache telemetry (observation only, see ./edgeCacheTelemetry) ------
|
|
1555
|
+
|
|
1556
|
+
function requestColo(request: Request): string | undefined {
|
|
1557
|
+
const colo = (request as unknown as { cf?: { colo?: unknown } }).cf?.colo;
|
|
1558
|
+
return typeof colo === "string" && colo ? colo : undefined;
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
/**
|
|
1562
|
+
* Stamp edge-cache attributes on the active span (the request root span).
|
|
1563
|
+
* Skipped entirely — no hashing — when disabled or when there is no span.
|
|
1564
|
+
* Never throws: observability must not fail the request.
|
|
1565
|
+
*/
|
|
1566
|
+
function stampEdgeCache(build: () => Record<string, string | undefined>): void {
|
|
1567
|
+
if (!edgeCacheTelemetryOpt || !getActiveSpan()) return;
|
|
1568
|
+
try {
|
|
1569
|
+
for (const [k, v] of Object.entries(build())) {
|
|
1570
|
+
if (v !== undefined) setSpanAttribute(k, v);
|
|
1571
|
+
}
|
|
1572
|
+
} catch {
|
|
1573
|
+
/* swallow — observability must never fail the request */
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/** The dimensions of the key a request was looked up under. */
|
|
1578
|
+
function stampEdgeCacheKey(
|
|
1579
|
+
request: Request,
|
|
1580
|
+
env: Record<string, unknown>,
|
|
1581
|
+
kind: EdgeCacheKind,
|
|
1582
|
+
profile: string,
|
|
1583
|
+
keyUrl: string,
|
|
1584
|
+
segment: SegmentKey | undefined,
|
|
1585
|
+
): void {
|
|
1586
|
+
stampEdgeCache(() => {
|
|
1587
|
+
const serialized = segment ? hashSegment(segment) : undefined;
|
|
1588
|
+
return {
|
|
1589
|
+
[EdgeCacheAttr.KIND]: kind,
|
|
1590
|
+
[EdgeCacheAttr.PROFILE]: profile,
|
|
1591
|
+
[EdgeCacheAttr.VERSION]: getBuildHash(env).slice(0, 8) || undefined,
|
|
1592
|
+
[EdgeCacheAttr.COLO]: requestColo(request),
|
|
1593
|
+
[EdgeCacheAttr.SEGMENT_HASH]: serialized !== undefined ? fnv1aHex(serialized) : undefined,
|
|
1594
|
+
[EdgeCacheAttr.SEGMENT_SHAPE]:
|
|
1595
|
+
serialized !== undefined ? segmentShape(serialized) : undefined,
|
|
1596
|
+
[EdgeCacheAttr.KEY_HASH]: fnv1aHex(keyUrl),
|
|
1597
|
+
[EdgeCacheAttr.KEY_PARTS]: cacheKeyParts(keyUrl),
|
|
1598
|
+
};
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function stampEdgeCacheBypass(
|
|
1603
|
+
request: Request,
|
|
1604
|
+
kind: EdgeCacheKind,
|
|
1605
|
+
reason: EdgeCacheBypassReason,
|
|
1606
|
+
profile?: string,
|
|
1607
|
+
): void {
|
|
1608
|
+
stampEdgeCache(() => ({
|
|
1609
|
+
[EdgeCacheAttr.STATUS]: "BYPASS",
|
|
1610
|
+
[EdgeCacheAttr.BYPASS_REASON]: reason,
|
|
1611
|
+
[EdgeCacheAttr.KIND]: kind,
|
|
1612
|
+
[EdgeCacheAttr.PROFILE]: profile,
|
|
1613
|
+
[EdgeCacheAttr.COLO]: requestColo(request),
|
|
1614
|
+
}));
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
function stampEdgeCacheStore(decision: EdgeCacheStoreDecision, unsafeCookies?: string): void {
|
|
1618
|
+
stampEdgeCache(() => ({
|
|
1619
|
+
[EdgeCacheAttr.STORE]: decision,
|
|
1620
|
+
[EdgeCacheAttr.STORE_UNSAFE_COOKIES]: unsafeCookies,
|
|
1621
|
+
}));
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
/**
|
|
1625
|
+
* `cache.put` inside the `deco.cache.store` span, with what the put did on
|
|
1626
|
+
* that span (`stored`, `skipped:too-large`, `error`, …). It runs in
|
|
1627
|
+
* `waitUntil`, after the root span has ended, so the outcome cannot go on the
|
|
1628
|
+
* root — the child shares its trace id. Returns what `put` returned.
|
|
1629
|
+
*/
|
|
1630
|
+
async function putWithOutcome(
|
|
1631
|
+
put: () => Promise<ResponseCachePutResult>,
|
|
1632
|
+
): Promise<ResponseCachePutResult> {
|
|
1633
|
+
try {
|
|
1634
|
+
const result = await put();
|
|
1635
|
+
if (edgeCacheTelemetryOpt) setSpanAttribute(EdgeCacheAttr.STORE_OUTCOME, result);
|
|
1636
|
+
return result;
|
|
1637
|
+
} catch (err) {
|
|
1638
|
+
// Not expected: `put` swallows adapter errors itself.
|
|
1639
|
+
if (edgeCacheTelemetryOpt) setSpanAttribute(EdgeCacheAttr.STORE_OUTCOME, "error");
|
|
1640
|
+
throw err;
|
|
1641
|
+
}
|
|
1518
1642
|
}
|
|
1519
1643
|
|
|
1520
1644
|
function getProfile(url: URL): CacheProfileName {
|
|
@@ -2827,6 +2951,7 @@ export function createDecoWorkerEntry(
|
|
|
2827
2951
|
// body-hash cache key does not vary on the cookie, so it must bypass the
|
|
2828
2952
|
// shared cache entirely or it would leak drafts / serve stale published.
|
|
2829
2953
|
if (requestCarriesDraft(request, url)) {
|
|
2954
|
+
stampEdgeCacheBypass(request, "serverFn", "draft-preview");
|
|
2830
2955
|
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2831
2956
|
const resp = new Response(origin.body, origin);
|
|
2832
2957
|
resp.headers.set("Cache-Control", "no-store, private");
|
|
@@ -2840,6 +2965,7 @@ export function createDecoWorkerEntry(
|
|
|
2840
2965
|
|
|
2841
2966
|
// Logged-in users always bypass — personalized content must not leak
|
|
2842
2967
|
if (sfnSegment?.loggedIn) {
|
|
2968
|
+
stampEdgeCacheBypass(request, "serverFn", "logged-in");
|
|
2843
2969
|
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2844
2970
|
const resp = new Response(origin.body, origin);
|
|
2845
2971
|
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
@@ -2853,6 +2979,7 @@ export function createDecoWorkerEntry(
|
|
|
2853
2979
|
// (QS overrides travel inside the payload's pageUrl, so they already
|
|
2854
2980
|
// produce a distinct body hash.)
|
|
2855
2981
|
if (request.headers.has(DECO_MATCHERS_OVERRIDE_PARAM)) {
|
|
2982
|
+
stampEdgeCacheBypass(request, "serverFn", "matchers-override");
|
|
2856
2983
|
const origin = await serverEntry.fetch(request, env, ctx);
|
|
2857
2984
|
const resp = new Response(origin.body, origin);
|
|
2858
2985
|
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
@@ -2901,6 +3028,7 @@ export function createDecoWorkerEntry(
|
|
|
2901
3028
|
// Use "listing" profile for server function responses
|
|
2902
3029
|
const sfnProfile: CacheProfileName = "listing";
|
|
2903
3030
|
const sfnEdge = edgeCacheConfig(sfnProfile);
|
|
3031
|
+
stampEdgeCacheKey(request, env, "serverFn", sfnProfile, sfnCacheKey.url, sfnSegment);
|
|
2904
3032
|
|
|
2905
3033
|
// Check edge cache
|
|
2906
3034
|
let sfnCached: Response | undefined;
|
|
@@ -2997,6 +3125,13 @@ export function createDecoWorkerEntry(
|
|
|
2997
3125
|
origin.status === 200;
|
|
2998
3126
|
|
|
2999
3127
|
if (!isCacheableResponse) {
|
|
3128
|
+
// Same precedence as the X-Cache-Reason below. This path refuses ANY
|
|
3129
|
+
// Set-Cookie, so every name is listed.
|
|
3130
|
+
if (origin.headers.has("set-cookie")) {
|
|
3131
|
+
stampEdgeCacheStore("skipped:set-cookie", unsafeCookieNames(origin, new Set()));
|
|
3132
|
+
} else {
|
|
3133
|
+
stampEdgeCacheStore(origin.status !== 200 ? "skipped:non-200" : "skipped:not-cacheable");
|
|
3134
|
+
}
|
|
3000
3135
|
const resp = new Response(origin.body, origin);
|
|
3001
3136
|
resp.headers.delete("X-Deco-Cacheable");
|
|
3002
3137
|
resp.headers.set("X-Cache", "BYPASS");
|
|
@@ -3008,6 +3143,9 @@ export function createDecoWorkerEntry(
|
|
|
3008
3143
|
}
|
|
3009
3144
|
|
|
3010
3145
|
// Store in edge cache (see sfnCarriesTracking above)
|
|
3146
|
+
stampEdgeCacheStore(
|
|
3147
|
+
sfnCarriesTracking ? "skipped:tracking" : serverFnCache ? "put" : "skipped:no-cache",
|
|
3148
|
+
);
|
|
3011
3149
|
if (serverFnCache && !sfnCarriesTracking) {
|
|
3012
3150
|
try {
|
|
3013
3151
|
const ttl = sfnEdge.fresh + Math.max(sfnEdge.swr, sfnEdge.sie);
|
|
@@ -3017,10 +3155,14 @@ export function createDecoWorkerEntry(
|
|
|
3017
3155
|
toStore.headers.delete("CDN-Cache-Control");
|
|
3018
3156
|
toStore.headers.delete("X-Deco-Cacheable");
|
|
3019
3157
|
ctx.waitUntil(
|
|
3020
|
-
withTracing(
|
|
3021
|
-
"cache.
|
|
3022
|
-
|
|
3023
|
-
|
|
3158
|
+
withTracing(
|
|
3159
|
+
"deco.cache.store",
|
|
3160
|
+
() => putWithOutcome(() => serverFnCache.put(sfnCacheKey, toStore)),
|
|
3161
|
+
{
|
|
3162
|
+
"cache.profile": sfnProfile,
|
|
3163
|
+
"cache.kind": "serverFn",
|
|
3164
|
+
},
|
|
3165
|
+
),
|
|
3024
3166
|
);
|
|
3025
3167
|
} catch {
|
|
3026
3168
|
/* Cache API unavailable */
|
|
@@ -3040,9 +3182,16 @@ export function createDecoWorkerEntry(
|
|
|
3040
3182
|
}
|
|
3041
3183
|
|
|
3042
3184
|
// Non-cacheable requests — pass through but protect against accidental caching
|
|
3043
|
-
|
|
3185
|
+
const bypassReason = nonCacheableReason(request, url);
|
|
3186
|
+
if (bypassReason !== null) {
|
|
3044
3187
|
const origin = await serverEntry.fetch(request, env, ctx);
|
|
3045
3188
|
const profile = getProfile(url);
|
|
3189
|
+
stampEdgeCacheBypass(
|
|
3190
|
+
request,
|
|
3191
|
+
isServerFnPathname(url.pathname) ? "serverFn" : "html",
|
|
3192
|
+
bypassReason,
|
|
3193
|
+
profile,
|
|
3194
|
+
);
|
|
3046
3195
|
|
|
3047
3196
|
if (profile === "private" || profile === "none" || profile === "cart") {
|
|
3048
3197
|
const resp = new Response(origin.body, origin);
|
|
@@ -3090,6 +3239,7 @@ export function createDecoWorkerEntry(
|
|
|
3090
3239
|
|
|
3091
3240
|
// Logged-in users always bypass the cache (personalized content)
|
|
3092
3241
|
if (segment?.loggedIn) {
|
|
3242
|
+
stampEdgeCacheBypass(request, "html", "logged-in", getProfile(url));
|
|
3093
3243
|
const origin = await serverEntry.fetch(request, env, ctx);
|
|
3094
3244
|
const resp = new Response(origin.body, origin);
|
|
3095
3245
|
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
@@ -3103,6 +3253,8 @@ export function createDecoWorkerEntry(
|
|
|
3103
3253
|
|
|
3104
3254
|
const profile = getProfile(url);
|
|
3105
3255
|
const edgeConfig = edgeCacheConfig(profile);
|
|
3256
|
+
// A GET server fn (SPA navigation data) is keyed and profiled as its page.
|
|
3257
|
+
stampEdgeCacheKey(request, env, "html", profile, cacheKey.url, segment);
|
|
3106
3258
|
|
|
3107
3259
|
// Helper: dress a response with proper client-facing headers
|
|
3108
3260
|
function dressResponse(
|
|
@@ -3178,10 +3330,14 @@ export function createDecoWorkerEntry(
|
|
|
3178
3330
|
toStore.headers.set("Cache-Control", `public, max-age=${storageTtl}`);
|
|
3179
3331
|
toStore.headers.set("X-Deco-Stored-At", String(Date.now()));
|
|
3180
3332
|
toStore.headers.delete("CDN-Cache-Control");
|
|
3181
|
-
const stored = withTracing(
|
|
3182
|
-
"cache.
|
|
3183
|
-
|
|
3184
|
-
|
|
3333
|
+
const stored = withTracing(
|
|
3334
|
+
"deco.cache.store",
|
|
3335
|
+
() => putWithOutcome(() => cache.put(cacheKey, toStore)),
|
|
3336
|
+
{
|
|
3337
|
+
"cache.profile": profile,
|
|
3338
|
+
"cache.kind": "html",
|
|
3339
|
+
},
|
|
3340
|
+
);
|
|
3185
3341
|
ctx.waitUntil(stored);
|
|
3186
3342
|
return stored;
|
|
3187
3343
|
} catch {
|
|
@@ -3322,6 +3478,7 @@ export function createDecoWorkerEntry(
|
|
|
3322
3478
|
}
|
|
3323
3479
|
|
|
3324
3480
|
if (origin.status !== 200) {
|
|
3481
|
+
stampEdgeCacheStore("skipped:non-200");
|
|
3325
3482
|
// Non-200 origin — SIE fallback on 5xx/429
|
|
3326
3483
|
if (origin.status >= 500 || origin.status === 429) {
|
|
3327
3484
|
if (cached && edgeConfig.sie > 0) {
|
|
@@ -3352,6 +3509,9 @@ export function createDecoWorkerEntry(
|
|
|
3352
3509
|
// Safe/public cookies (IS session, segment, etc.) are stripped from the
|
|
3353
3510
|
// cached copy but kept on the response served to the current user.
|
|
3354
3511
|
if (origin.headers.has("set-cookie") && !hasOnlySafeCookies(origin, safeCookieSet)) {
|
|
3512
|
+
// Looked up as a MISS; the response says BYPASS. The span keeps the
|
|
3513
|
+
// MISS and records why nothing was stored.
|
|
3514
|
+
stampEdgeCacheStore("skipped:unsafe-cookie", unsafeCookieNames(origin, safeCookieSet));
|
|
3355
3515
|
const resp = new Response(origin.body, origin);
|
|
3356
3516
|
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
3357
3517
|
resp.headers.delete("CDN-Cache-Control");
|
|
@@ -3368,6 +3528,7 @@ export function createDecoWorkerEntry(
|
|
|
3368
3528
|
// for the full retention window and stale-if-error would never fire —
|
|
3369
3529
|
// turning a seconds-long blip into hours of empty pages.
|
|
3370
3530
|
if (origin.headers.get("X-Deco-Degraded") === "true") {
|
|
3531
|
+
stampEdgeCacheStore("skipped:degraded");
|
|
3371
3532
|
if (cached && edgeConfig.sie > 0) {
|
|
3372
3533
|
const storedAtStr = cached.headers.get("X-Deco-Stored-At");
|
|
3373
3534
|
const storedAt = storedAtStr ? Number(storedAtStr) : 0;
|
|
@@ -3396,6 +3557,7 @@ export function createDecoWorkerEntry(
|
|
|
3396
3557
|
const profileConfig = getCacheProfile(profile);
|
|
3397
3558
|
|
|
3398
3559
|
if (!profileConfig.isPublic || profileConfig.edge.fresh === 0) {
|
|
3560
|
+
stampEdgeCacheStore("skipped:profile");
|
|
3399
3561
|
const resp = new Response(origin.body, origin);
|
|
3400
3562
|
resp.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
|
|
3401
3563
|
resp.headers.set("X-Cache", "BYPASS");
|
|
@@ -3415,7 +3577,14 @@ export function createDecoWorkerEntry(
|
|
|
3415
3577
|
: origin;
|
|
3416
3578
|
// This render saw the tracked URL and embedded it — never store it under
|
|
3417
3579
|
// the clean key. The next clean visitor fills the entry.
|
|
3418
|
-
|
|
3580
|
+
// (Stamped here, not in storeInCache: background revalidation also stores,
|
|
3581
|
+
// after this request's span has ended.)
|
|
3582
|
+
if (skipStoreTracking) {
|
|
3583
|
+
stampEdgeCacheStore("skipped:tracking");
|
|
3584
|
+
} else {
|
|
3585
|
+
stampEdgeCacheStore(cache ? "put" : "skipped:no-cache");
|
|
3586
|
+
storeInCache(cacheOrigin);
|
|
3587
|
+
}
|
|
3419
3588
|
return dressResponse(
|
|
3420
3589
|
origin,
|
|
3421
3590
|
"MISS",
|