@decocms/blocks 7.71.6 → 8.0.0-next.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/bin/deco.js +13 -0
- package/package.json +32 -3
- package/src/cms/schema.ts +1 -1
- package/src/hooks/LiveControls.tsx +2 -0
- package/src/hooks/useLoadMore.ts +2 -0
- package/src/index.ts +37 -0
- package/src/protocol/assets.ts +124 -0
- package/src/protocol/canonical.ts +7 -0
- package/src/protocol/ciphertext.ts +6 -0
- package/src/protocol/client.ts +170 -0
- package/src/protocol/conformance/cases/assets.ts +81 -0
- package/src/protocol/conformance/cases/guards.ts +314 -0
- package/src/protocol/conformance/cases/reads.ts +168 -0
- package/src/protocol/conformance/cases/types.ts +9 -0
- package/src/protocol/conformance/cases/wire.ts +138 -0
- package/src/protocol/conformance/cases/writes.ts +345 -0
- package/src/protocol/conformance/contentHashFixtures.ts +79 -0
- package/src/protocol/conformance/context.ts +222 -0
- package/src/protocol/conformance/index.ts +140 -0
- package/src/protocol/errors.ts +142 -0
- package/src/protocol/index.ts +39 -0
- package/src/protocol/keys.ts +279 -0
- package/src/protocol/params.ts +67 -0
- package/src/protocol/secrets.ts +231 -0
- package/src/protocol/server/assets.ts +119 -0
- package/src/protocol/server/auth.ts +49 -0
- package/src/protocol/server/bodyCache.ts +84 -0
- package/src/protocol/server/content.ts +175 -0
- package/src/protocol/server/core.ts +112 -0
- package/src/protocol/server/handler.ts +102 -0
- package/src/protocol/server/http.ts +139 -0
- package/src/protocol/server/index.ts +11 -0
- package/src/protocol/server/methods/apply.ts +341 -0
- package/src/protocol/server/methods/read.ts +156 -0
- package/src/protocol/server/rpc.ts +136 -0
- package/src/protocol/storage/fs/hash.ts +21 -0
- package/src/protocol/storage/fs/index.ts +338 -0
- package/src/protocol/storage/fs/lock.ts +68 -0
- package/src/protocol/storage/fs/transaction.ts +183 -0
- package/src/protocol/storage/fs/unsupported.ts +15 -0
- package/src/protocol/storage/memory.ts +238 -0
- package/src/protocol/storage.ts +182 -0
- package/src/protocol/types.ts +172 -0
- package/src/v8/analytics.ts +50 -0
- package/src/v8/background.ts +107 -0
- package/src/v8/builtins/data.ts +23 -0
- package/src/v8/builtins/index.ts +26 -0
- package/src/v8/builtins/lazy.ts +23 -0
- package/src/v8/builtins/legacy.ts +65 -0
- package/src/v8/builtins/matchers.ts +31 -0
- package/src/v8/builtins/multivariate.ts +25 -0
- package/src/v8/builtins/secret.ts +82 -0
- package/src/v8/canonical.ts +117 -0
- package/src/v8/ciphertext.ts +158 -0
- package/src/v8/cli/builtins.ts +20 -0
- package/src/v8/cli/check/index.ts +774 -0
- package/src/v8/cli/check/messages.ts +168 -0
- package/src/v8/cli/content.ts +287 -0
- package/src/v8/cli/index.ts +17 -0
- package/src/v8/cli/log.ts +18 -0
- package/src/v8/cli/main.ts +12 -0
- package/src/v8/cli/root.ts +66 -0
- package/src/v8/cli/run.ts +236 -0
- package/src/v8/cli/schema/builtinSchemas.ts +236 -0
- package/src/v8/cli/schema/generate.ts +507 -0
- package/src/v8/cli/schema/index.ts +63 -0
- package/src/v8/cli/schema/tsProgram.ts +497 -0
- package/src/v8/cli/schema/typeToSchema.ts +689 -0
- package/src/v8/cli/serve/server.ts +303 -0
- package/src/v8/cli/watch.ts +86 -0
- package/src/v8/client.ts +147 -0
- package/src/v8/cms.ts +237 -0
- package/src/v8/content.ts +195 -0
- package/src/v8/draft.ts +136 -0
- package/src/v8/errors.ts +59 -0
- package/src/v8/fetch.ts +152 -0
- package/src/v8/identity.ts +65 -0
- package/src/v8/index.ts +39 -0
- package/src/v8/json.ts +74 -0
- package/src/v8/matchRoute.ts +204 -0
- package/src/v8/remoteLoader.ts +282 -0
- package/src/v8/resolver.ts +278 -0
- package/src/v8/secrets.ts +17 -0
- package/src/v8/telemetry.ts +533 -0
- package/src/v8/types.ts +240 -0
- package/src/cms/blockSource.test.ts +0 -76
- package/src/cms/client.browserBundle.test.ts +0 -44
- package/src/cms/deferredTrigger.test.ts +0 -32
- package/src/cms/draftSource.test.ts +0 -519
- package/src/cms/layoutCacheRace.test.ts +0 -181
- package/src/cms/loadDecofileDirectory.test.ts +0 -109
- package/src/cms/loader.test.ts +0 -557
- package/src/cms/registry.test.ts +0 -110
- package/src/cms/renderJson.test.ts +0 -167
- package/src/cms/resolve.test.ts +0 -1492
- package/src/cms/schema.test.ts +0 -356
- package/src/cms/sectionLoaderContext.test.ts +0 -111
- package/src/cms/sectionLoaders.test.ts +0 -625
- package/src/cms/sectionMixins.test.ts +0 -167
- package/src/cms/stickyFlags.test.ts +0 -117
- package/src/flags/flags.test.ts +0 -148
- package/src/hooks/Image.test.ts +0 -239
- package/src/hooks/RenderSection.test.tsx +0 -81
- package/src/hooks/Stats.test.ts +0 -112
- package/src/hooks/useLoadMore.test.ts +0 -205
- package/src/matchers/builtins.test.ts +0 -318
- package/src/matchers/override.test.ts +0 -205
- package/src/middleware/hydrationContext.test.ts +0 -61
- package/src/middleware/observability.test.ts +0 -335
- package/src/middleware/validateSection.test.ts +0 -147
- package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
- package/src/preview/DraftPreviewBadge.test.ts +0 -55
- package/src/sdk/abTesting.test.ts +0 -381
- package/src/sdk/cacheHeaders.test.ts +0 -258
- package/src/sdk/cacheStorage.test.ts +0 -242
- package/src/sdk/cachedLoader.test.ts +0 -122
- package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
- package/src/sdk/cachedLoaderModule.test.ts +0 -209
- package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
- package/src/sdk/cn.test.ts +0 -34
- package/src/sdk/composite.test.ts +0 -121
- package/src/sdk/cookie.test.ts +0 -108
- package/src/sdk/crypto.test.ts +0 -65
- package/src/sdk/deepOmit.test.ts +0 -45
- package/src/sdk/encoding.test.ts +0 -71
- package/src/sdk/env.test.ts +0 -33
- package/src/sdk/experiments.test.ts +0 -328
- package/src/sdk/fetchCache.test.ts +0 -164
- package/src/sdk/flags.test.ts +0 -91
- package/src/sdk/http.test.ts +0 -71
- package/src/sdk/inflightTimeout.test.ts +0 -35
- package/src/sdk/instrumentedFetch.test.ts +0 -559
- package/src/sdk/invoke.test.ts +0 -115
- package/src/sdk/logger.test.ts +0 -432
- package/src/sdk/otel.test.ts +0 -691
- package/src/sdk/otelAdapters.test.ts +0 -89
- package/src/sdk/otelHttpLog.test.ts +0 -457
- package/src/sdk/otelHttpMeter.test.ts +0 -395
- package/src/sdk/otelHttpTracer.test.ts +0 -474
- package/src/sdk/replaceStream.test.ts +0 -117
- package/src/sdk/requestContextStorage.browser.test.ts +0 -29
- package/src/sdk/splitExactRedirects.test.ts +0 -154
- package/src/sdk/urlRedaction.test.ts +0 -73
- package/src/sdk/urlUtils.test.ts +0 -34
- package/src/sdk/useDevice.test.ts +0 -130
- package/src/sdk/useScript.test.ts +0 -128
- package/src/sdk/useSuggestions.test.ts +0 -230
- package/tsconfig.json +0 -7
|
@@ -1,242 +0,0 @@
|
|
|
1
|
-
// @vitest-environment node
|
|
2
|
-
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
3
|
-
import { clearLoaderCache, createCachedLoader } from "./cachedLoader";
|
|
4
|
-
import {
|
|
5
|
-
bindCacheStorage,
|
|
6
|
-
type CacheStorage,
|
|
7
|
-
createCacheStore,
|
|
8
|
-
createKVCacheStorage,
|
|
9
|
-
createMemoryCacheStorage,
|
|
10
|
-
createWebCacheStorage,
|
|
11
|
-
} from "./cacheStorage";
|
|
12
|
-
import { RequestContext } from "./requestContext";
|
|
13
|
-
import { createResponseCache } from "./responseCache";
|
|
14
|
-
|
|
15
|
-
function fakeKV() {
|
|
16
|
-
const values = new Map<string, string>();
|
|
17
|
-
return {
|
|
18
|
-
values,
|
|
19
|
-
get: vi.fn(async (key: string) => values.get(key) ?? null),
|
|
20
|
-
put: vi.fn(async (key: string, value: string, _opts: { expirationTtl: number }) => {
|
|
21
|
-
values.set(key, value);
|
|
22
|
-
}),
|
|
23
|
-
delete: vi.fn(async (key: string) => {
|
|
24
|
-
values.delete(key);
|
|
25
|
-
}),
|
|
26
|
-
};
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const pending: Promise<unknown>[] = [];
|
|
30
|
-
function run<T>(storage: CacheStorage | null, scope: string, fn: () => T): T {
|
|
31
|
-
return RequestContext.run(new Request("https://site.test/"), () => {
|
|
32
|
-
bindCacheStorage({ storage, scope, waitUntil: (work) => pending.push(work) });
|
|
33
|
-
return fn();
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
async function flush() {
|
|
37
|
-
await Promise.all(pending.splice(0));
|
|
38
|
-
}
|
|
39
|
-
afterEach(async () => {
|
|
40
|
-
await flush();
|
|
41
|
-
clearLoaderCache();
|
|
42
|
-
vi.useRealTimers();
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
function fakeWebCache(): Cache {
|
|
46
|
-
const values = new Map<string, Response>();
|
|
47
|
-
return {
|
|
48
|
-
async match(req: Request) {
|
|
49
|
-
return values.get(req.url)?.clone();
|
|
50
|
-
},
|
|
51
|
-
async put(req: Request, response: Response) {
|
|
52
|
-
values.set(req.url, response.clone());
|
|
53
|
-
},
|
|
54
|
-
async delete(req: Request) {
|
|
55
|
-
return values.delete(req.url);
|
|
56
|
-
},
|
|
57
|
-
} as Cache;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
for (const [name, make] of [
|
|
61
|
-
["memory", () => createMemoryCacheStorage()],
|
|
62
|
-
["KV", () => createKVCacheStorage(fakeKV())],
|
|
63
|
-
["Web Cache API", () => createWebCacheStorage(fakeWebCache(), "https://site.test")],
|
|
64
|
-
] as const) {
|
|
65
|
-
describe(`${name} storage contract`, () => {
|
|
66
|
-
it("round-trips, overwrites and deletes values", async () => {
|
|
67
|
-
const storage = make();
|
|
68
|
-
expect(await storage.get("missing")).toBeNull();
|
|
69
|
-
await storage.set("key", "first", Date.now() + 60_000);
|
|
70
|
-
expect(await storage.get("key")).toBe("first");
|
|
71
|
-
await storage.set("key", "second", Date.now() + 60_000);
|
|
72
|
-
expect(await storage.get("key")).toBe("second");
|
|
73
|
-
await storage.delete("key");
|
|
74
|
-
expect(await storage.get("key")).toBeNull();
|
|
75
|
-
});
|
|
76
|
-
it("enforces logical expiry even if the backend retains the record", async () => {
|
|
77
|
-
vi.useFakeTimers();
|
|
78
|
-
const storage = make();
|
|
79
|
-
await storage.set("short", "body", Date.now() + 500);
|
|
80
|
-
expect(await storage.get("short")).toBe("body");
|
|
81
|
-
vi.advanceTimersByTime(500);
|
|
82
|
-
expect(await storage.get("short")).toBeNull();
|
|
83
|
-
});
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
it("uses KV's minimum physical TTL while enforcing shorter logical expiry", async () => {
|
|
88
|
-
const kv = fakeKV();
|
|
89
|
-
await createKVCacheStorage(kv).set("a".repeat(1000), "value", Date.now() + 2000);
|
|
90
|
-
expect(kv.put.mock.calls[0][2]).toEqual({ expirationTtl: 60 });
|
|
91
|
-
expect(kv.put.mock.calls[0][0].length).toBeLessThan(512);
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
it("hydrates another store and isolates namespace, site and deployment", async () => {
|
|
95
|
-
const storage = createKVCacheStorage(fakeKV());
|
|
96
|
-
const first = createCacheStore<{ n: number }>("loaders");
|
|
97
|
-
await run(storage, "site:build-A", async () => {
|
|
98
|
-
first.set(first.key("item"), { n: 1 }, Date.now() + 60_000);
|
|
99
|
-
await flush();
|
|
100
|
-
});
|
|
101
|
-
const second = createCacheStore<{ n: number }>("loaders");
|
|
102
|
-
expect(await run(storage, "site:build-A", () => second.read(second.key("item")))).toEqual({
|
|
103
|
-
n: 1,
|
|
104
|
-
});
|
|
105
|
-
for (const scope of ["other-site:build-A", "site:build-B"]) {
|
|
106
|
-
expect(await run(storage, scope, () => second.read(second.key("item")))).toBeUndefined();
|
|
107
|
-
}
|
|
108
|
-
const sections = createCacheStore("sections");
|
|
109
|
-
expect(
|
|
110
|
-
await run(storage, "site:build-A", () => sections.read(sections.key("item"))),
|
|
111
|
-
).toBeUndefined();
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
it("does not switch bindings between concurrent requests", async () => {
|
|
115
|
-
const a = createMemoryCacheStorage();
|
|
116
|
-
const b = createMemoryCacheStorage();
|
|
117
|
-
const cache = createCacheStore<string>("concurrent");
|
|
118
|
-
await Promise.all(
|
|
119
|
-
[a, b].map((storage, i) =>
|
|
120
|
-
run(storage, `site-${i}`, async () => {
|
|
121
|
-
await Promise.resolve();
|
|
122
|
-
cache.set(cache.key("key"), String(i), Date.now() + 60_000);
|
|
123
|
-
}),
|
|
124
|
-
),
|
|
125
|
-
);
|
|
126
|
-
await flush();
|
|
127
|
-
cache.clear();
|
|
128
|
-
expect(await run(a, "site-0", () => cache.read(cache.key("key")))).toBe("0");
|
|
129
|
-
expect(await run(b, "site-1", () => cache.read(cache.key("key")))).toBe("1");
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
it("retains non-JSON values locally without silently corrupting them in KV", async () => {
|
|
133
|
-
const kv = fakeKV();
|
|
134
|
-
const cache = createCacheStore<{ date: Date }>("dates");
|
|
135
|
-
await run(createKVCacheStorage(kv), "site", async () => {
|
|
136
|
-
const value = { date: new Date() };
|
|
137
|
-
cache.set(cache.key("key"), value, Date.now() + 60_000);
|
|
138
|
-
expect(cache.get(cache.key("key"))).toBe(value);
|
|
139
|
-
await flush();
|
|
140
|
-
expect(kv.put).not.toHaveBeenCalled();
|
|
141
|
-
});
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
it("deduplicates a cold loader through slow storage and survives a memory wipe", async () => {
|
|
145
|
-
const storage = createKVCacheStorage(fakeKV());
|
|
146
|
-
const fn = vi.fn(async () => ({ product: 42 }));
|
|
147
|
-
const loader = createCachedLoader("test", fn, {
|
|
148
|
-
policy: "stale-while-revalidate",
|
|
149
|
-
maxAge: 60_000,
|
|
150
|
-
});
|
|
151
|
-
await run(storage, "site", async () => {
|
|
152
|
-
const values = await Promise.all([loader({}), loader({}), loader({})]);
|
|
153
|
-
expect(values).toEqual([{ product: 42 }, { product: 42 }, { product: 42 }]);
|
|
154
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
155
|
-
await flush();
|
|
156
|
-
clearLoaderCache();
|
|
157
|
-
expect(await loader({})).toEqual({ product: 42 });
|
|
158
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
159
|
-
});
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
it("falls back to the loader when storage reads and writes fail", async () => {
|
|
163
|
-
const failure = async () => {
|
|
164
|
-
throw new Error("KV unavailable");
|
|
165
|
-
};
|
|
166
|
-
const fn = vi.fn(async () => "origin");
|
|
167
|
-
const loader = createCachedLoader("failure", fn, { policy: "no-cache", maxAge: 1000 });
|
|
168
|
-
expect(await run({ get: failure, set: failure, delete: failure }, "site", () => loader({}))).toBe(
|
|
169
|
-
"origin",
|
|
170
|
-
);
|
|
171
|
-
await flush();
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
it("round-trips binary responses, headers and status through KV", async () => {
|
|
175
|
-
const cache = createResponseCache(createKVCacheStorage(fakeKV()), "site:build");
|
|
176
|
-
const req = new Request("https://site.test/image");
|
|
177
|
-
const bytes = new Uint8Array([0, 255, 128, 1]);
|
|
178
|
-
await cache.put(
|
|
179
|
-
req,
|
|
180
|
-
new Response(bytes, {
|
|
181
|
-
status: 203,
|
|
182
|
-
headers: {
|
|
183
|
-
"cache-control": "public, max-age=60",
|
|
184
|
-
"content-type": "application/octet-stream",
|
|
185
|
-
"x-deco-stored-at": "123",
|
|
186
|
-
},
|
|
187
|
-
}),
|
|
188
|
-
);
|
|
189
|
-
const response = await cache.match(req);
|
|
190
|
-
expect(response?.status).toBe(203);
|
|
191
|
-
expect(response?.headers.get("x-deco-stored-at")).toBe("123");
|
|
192
|
-
expect(new Uint8Array(await response!.arrayBuffer())).toEqual(bytes);
|
|
193
|
-
await cache.delete(req);
|
|
194
|
-
expect(await cache.match(req)).toBeUndefined();
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
it("refuses to serialize private HTTP responses or cookies", async () => {
|
|
198
|
-
const storage = createMemoryCacheStorage();
|
|
199
|
-
const cache = createResponseCache(storage, "site");
|
|
200
|
-
const req = new Request("https://site.test/");
|
|
201
|
-
await cache.put(
|
|
202
|
-
req,
|
|
203
|
-
new Response("private", { headers: { "cache-control": "private, max-age=60" } }),
|
|
204
|
-
);
|
|
205
|
-
expect(await cache.match(req)).toBeUndefined();
|
|
206
|
-
await cache.put(
|
|
207
|
-
req,
|
|
208
|
-
new Response("cookie", {
|
|
209
|
-
headers: { "cache-control": "public, max-age=60", "set-cookie": "session=secret" },
|
|
210
|
-
}),
|
|
211
|
-
);
|
|
212
|
-
expect(await cache.match(req)).toBeUndefined();
|
|
213
|
-
});
|
|
214
|
-
|
|
215
|
-
it("bounds SWR separately from stale-if-error and stops serving at the final TTL", async () => {
|
|
216
|
-
vi.useFakeTimers();
|
|
217
|
-
const storage = createKVCacheStorage(fakeKV());
|
|
218
|
-
let fail = false;
|
|
219
|
-
const origin = vi.fn(async () => {
|
|
220
|
-
if (fail) throw new Error("origin down");
|
|
221
|
-
return "last good";
|
|
222
|
-
});
|
|
223
|
-
const loader = createCachedLoader("bounded-stale", origin, {
|
|
224
|
-
policy: "stale-while-revalidate",
|
|
225
|
-
maxAge: 100,
|
|
226
|
-
staleWhileRevalidate: 100,
|
|
227
|
-
staleIfError: 300,
|
|
228
|
-
});
|
|
229
|
-
await run(storage, "bounded", async () => {
|
|
230
|
-
expect(await loader({})).toBe("last good");
|
|
231
|
-
await flush();
|
|
232
|
-
fail = true;
|
|
233
|
-
vi.advanceTimersByTime(150);
|
|
234
|
-
expect(await loader({})).toBe("last good");
|
|
235
|
-
await flush();
|
|
236
|
-
vi.advanceTimersByTime(100);
|
|
237
|
-
expect(await loader({})).toBe("last good");
|
|
238
|
-
expect(origin).toHaveBeenCalledTimes(3); // foreground retry once SWR has elapsed
|
|
239
|
-
vi.advanceTimersByTime(150);
|
|
240
|
-
await expect(loader({})).rejects.toThrow("origin down");
|
|
241
|
-
});
|
|
242
|
-
});
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
-
import { clearLoaderCache, createCachedLoader, getLoaderCacheStats } from "./cachedLoader";
|
|
3
|
-
|
|
4
|
-
describe("createCachedLoader", () => {
|
|
5
|
-
beforeEach(() => {
|
|
6
|
-
clearLoaderCache();
|
|
7
|
-
});
|
|
8
|
-
afterEach(() => {
|
|
9
|
-
clearLoaderCache();
|
|
10
|
-
vi.restoreAllMocks();
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it("serves a fresh entry from cache (MISS then HIT) within maxAge", async () => {
|
|
14
|
-
const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
|
|
15
|
-
const cached = createCachedLoader("t/basic", loaderFn, {
|
|
16
|
-
policy: "stale-while-revalidate",
|
|
17
|
-
maxAge: 60_000,
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
await cached({ id: 1 }); // MISS
|
|
21
|
-
await cached({ id: 1 }); // HIT — same key, within maxAge
|
|
22
|
-
|
|
23
|
-
expect(loaderFn).toHaveBeenCalledTimes(1);
|
|
24
|
-
expect(getLoaderCacheStats().entries).toBe(1);
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
it("distinct props produce distinct entries", async () => {
|
|
28
|
-
const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
|
|
29
|
-
const cached = createCachedLoader("t/props", loaderFn, {
|
|
30
|
-
policy: "stale-while-revalidate",
|
|
31
|
-
maxAge: 60_000,
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
await cached({ id: 1 });
|
|
35
|
-
await cached({ id: 2 });
|
|
36
|
-
|
|
37
|
-
expect(loaderFn).toHaveBeenCalledTimes(2);
|
|
38
|
-
expect(getLoaderCacheStats().entries).toBe(2);
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
it("clearLoaderCache() empties the cache so the next call is a MISS", async () => {
|
|
42
|
-
const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
|
|
43
|
-
const cached = createCachedLoader("t/bust", loaderFn, {
|
|
44
|
-
policy: "stale-while-revalidate",
|
|
45
|
-
maxAge: 60_000,
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
await cached({ id: 1 }); // MISS
|
|
49
|
-
await cached({ id: 1 }); // HIT
|
|
50
|
-
expect(loaderFn).toHaveBeenCalledTimes(1);
|
|
51
|
-
|
|
52
|
-
clearLoaderCache();
|
|
53
|
-
expect(getLoaderCacheStats().entries).toBe(0);
|
|
54
|
-
|
|
55
|
-
await cached({ id: 1 }); // MISS again — cache was cleared
|
|
56
|
-
expect(loaderFn).toHaveBeenCalledTimes(2);
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
it("a purge during an in-flight loader does not repopulate the cleared entry", async () => {
|
|
60
|
-
// Loader we can resolve manually, to hold it "in flight" across the purge.
|
|
61
|
-
let release!: (v: { v: number }) => void;
|
|
62
|
-
const loaderFn = vi.fn(
|
|
63
|
-
() =>
|
|
64
|
-
new Promise<{ v: number }>((res) => {
|
|
65
|
-
release = res;
|
|
66
|
-
}),
|
|
67
|
-
);
|
|
68
|
-
const cached = createCachedLoader("t/race", loaderFn, {
|
|
69
|
-
policy: "stale-while-revalidate",
|
|
70
|
-
maxAge: 60_000,
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
const inflight = cached({ id: 1 }); // MISS — loader now pending
|
|
74
|
-
clearLoaderCache(); // purge lands while the loader is in flight
|
|
75
|
-
release({ v: 99 }); // loader resolves with pre-purge data
|
|
76
|
-
await expect(inflight).resolves.toEqual({ v: 99 }); // caller still gets its value
|
|
77
|
-
|
|
78
|
-
// ...but the raced result must NOT have been written back to the cache.
|
|
79
|
-
expect(getLoaderCacheStats().entries).toBe(0);
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it("warns once per loader name when maxAge is very long", async () => {
|
|
83
|
-
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
84
|
-
const loaderFn = vi.fn(async () => ({}));
|
|
85
|
-
|
|
86
|
-
// > 10 min → warns
|
|
87
|
-
createCachedLoader("t/long-a", loaderFn, {
|
|
88
|
-
policy: "stale-while-revalidate",
|
|
89
|
-
maxAge: 3_600_000,
|
|
90
|
-
});
|
|
91
|
-
// same name again → deduped, no second warning
|
|
92
|
-
createCachedLoader("t/long-a", loaderFn, {
|
|
93
|
-
policy: "stale-while-revalidate",
|
|
94
|
-
maxAge: 3_600_000,
|
|
95
|
-
});
|
|
96
|
-
// short maxAge → no warning
|
|
97
|
-
createCachedLoader("t/short", loaderFn, {
|
|
98
|
-
policy: "stale-while-revalidate",
|
|
99
|
-
maxAge: 60_000,
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
const longWarnings = warn.mock.calls.filter(
|
|
103
|
-
(c) => typeof c[0] === "string" && c[0].includes("t/long-a"),
|
|
104
|
-
);
|
|
105
|
-
const shortWarnings = warn.mock.calls.filter(
|
|
106
|
-
(c) => typeof c[0] === "string" && c[0].includes("t/short"),
|
|
107
|
-
);
|
|
108
|
-
expect(longWarnings).toHaveLength(1);
|
|
109
|
-
expect(shortWarnings).toHaveLength(0);
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
it("no-store policy bypasses the cache entirely", async () => {
|
|
113
|
-
const loaderFn = vi.fn(async () => ({}));
|
|
114
|
-
const cached = createCachedLoader("t/nostore", loaderFn, { policy: "no-store" });
|
|
115
|
-
|
|
116
|
-
await cached({});
|
|
117
|
-
await cached({});
|
|
118
|
-
|
|
119
|
-
expect(loaderFn).toHaveBeenCalledTimes(2);
|
|
120
|
-
expect(getLoaderCacheStats().entries).toBe(0);
|
|
121
|
-
});
|
|
122
|
-
});
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { getLoaderCacheMaxBytes, setLoaderCacheMaxBytes } from "./cachedLoader";
|
|
3
|
-
|
|
4
|
-
describe("loader cache byte cap", () => {
|
|
5
|
-
it("defaults to 32 MB", () => {
|
|
6
|
-
// process.env is empty in workerd unless compatibility_date is new enough,
|
|
7
|
-
// which is exactly why the setter below exists.
|
|
8
|
-
expect(getLoaderCacheMaxBytes()).toBe(32 * 1024 * 1024);
|
|
9
|
-
});
|
|
10
|
-
|
|
11
|
-
it("can be raised programmatically", () => {
|
|
12
|
-
setLoaderCacheMaxBytes(64 * 1024 * 1024);
|
|
13
|
-
expect(getLoaderCacheMaxBytes()).toBe(64 * 1024 * 1024);
|
|
14
|
-
});
|
|
15
|
-
|
|
16
|
-
it("ignores nonsense instead of disabling eviction", () => {
|
|
17
|
-
setLoaderCacheMaxBytes(64 * 1024 * 1024);
|
|
18
|
-
for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
19
|
-
setLoaderCacheMaxBytes(bad);
|
|
20
|
-
expect(getLoaderCacheMaxBytes()).toBe(64 * 1024 * 1024);
|
|
21
|
-
}
|
|
22
|
-
});
|
|
23
|
-
});
|
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
-
import {
|
|
3
|
-
clearLoaderCache,
|
|
4
|
-
createCachedLoaderFromModule,
|
|
5
|
-
createLoaderEntry,
|
|
6
|
-
type LoaderModule,
|
|
7
|
-
} from "./cachedLoader";
|
|
8
|
-
import { RequestContext } from "./requestContext";
|
|
9
|
-
|
|
10
|
-
/** A loader whose `default` we can count calls on and control resolution of. */
|
|
11
|
-
function makeLoader<T>(result: T) {
|
|
12
|
-
let resolve!: (v: T) => void;
|
|
13
|
-
const gate = new Promise<T>((r) => (resolve = r));
|
|
14
|
-
const fn = vi.fn(async (_props: unknown, _req?: Request) => {
|
|
15
|
-
await gate;
|
|
16
|
-
return result;
|
|
17
|
-
});
|
|
18
|
-
return { fn, release: () => resolve(result) };
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
afterEach(() => {
|
|
22
|
-
clearLoaderCache();
|
|
23
|
-
vi.restoreAllMocks();
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
describe("createCachedLoaderFromModule — dedup-only (no SWR)", () => {
|
|
27
|
-
it("runs on every call when the module has no `cache` export (apps no-store default)", async () => {
|
|
28
|
-
const { fn, release } = makeLoader("x");
|
|
29
|
-
release();
|
|
30
|
-
const mod: LoaderModule = { default: fn };
|
|
31
|
-
const loader = createCachedLoaderFromModule("site/loaders/plain", mod);
|
|
32
|
-
|
|
33
|
-
// No wrap at all → returns the original function identity.
|
|
34
|
-
expect(loader).toBe(fn);
|
|
35
|
-
|
|
36
|
-
await loader({ a: 1 });
|
|
37
|
-
await loader({ a: 1 });
|
|
38
|
-
expect(fn).toHaveBeenCalledTimes(2);
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
it("runs on every call for `no-cache` (only stale-while-revalidate opts into dedup)", async () => {
|
|
42
|
-
const { fn, release } = makeLoader("x");
|
|
43
|
-
const mod: LoaderModule = { default: fn, cache: "no-cache" };
|
|
44
|
-
const loader = createCachedLoaderFromModule("site/loaders/nocache", mod);
|
|
45
|
-
|
|
46
|
-
expect(loader).toBe(fn);
|
|
47
|
-
const p1 = loader({ a: 1 });
|
|
48
|
-
const p2 = loader({ a: 1 });
|
|
49
|
-
release();
|
|
50
|
-
await Promise.all([p1, p2]);
|
|
51
|
-
expect(fn).toHaveBeenCalledTimes(2);
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
it("collapses concurrent identical calls into ONE upstream call when `cache` opts in", async () => {
|
|
55
|
-
const { fn, release } = makeLoader("shelf");
|
|
56
|
-
const mod: LoaderModule = { default: fn, cache: "stale-while-revalidate" };
|
|
57
|
-
const loader = createCachedLoaderFromModule("site/loaders/related", mod);
|
|
58
|
-
|
|
59
|
-
// Three sections on one render invoke the same loader concurrently.
|
|
60
|
-
const p1 = loader({ slug: "abc" });
|
|
61
|
-
const p2 = loader({ slug: "abc" });
|
|
62
|
-
const p3 = loader({ slug: "abc" });
|
|
63
|
-
release();
|
|
64
|
-
const [r1, r2, r3] = await Promise.all([p1, p2, p3]);
|
|
65
|
-
|
|
66
|
-
expect(r1).toBe("shelf");
|
|
67
|
-
expect(r2).toBe("shelf");
|
|
68
|
-
expect(r3).toBe("shelf");
|
|
69
|
-
// The #339 N+1 fix: 3 concurrent references → 1 upstream call.
|
|
70
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
it("does NOT retain results across settlement (no cross-request staleness)", async () => {
|
|
74
|
-
const { fn, release } = makeLoader("v");
|
|
75
|
-
release();
|
|
76
|
-
const mod: LoaderModule = { default: fn, cache: "stale-while-revalidate" };
|
|
77
|
-
const loader = createCachedLoaderFromModule("site/loaders/nostale", mod);
|
|
78
|
-
|
|
79
|
-
await loader({ slug: "abc" });
|
|
80
|
-
// Sequential (non-concurrent) call after the first settled → re-runs.
|
|
81
|
-
await loader({ slug: "abc" });
|
|
82
|
-
expect(fn).toHaveBeenCalledTimes(2);
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
it("dedups by the module's custom cacheKey(props, req), not raw props", async () => {
|
|
86
|
-
const { fn, release } = makeLoader("p");
|
|
87
|
-
const mod: LoaderModule = {
|
|
88
|
-
default: fn,
|
|
89
|
-
cache: "stale-while-revalidate",
|
|
90
|
-
// Key only on pathname — ignores tracking params on the URL.
|
|
91
|
-
cacheKey: (_props, req) => new URL(req!.url).pathname,
|
|
92
|
-
};
|
|
93
|
-
const loader = createCachedLoaderFromModule("site/loaders/pdp", mod);
|
|
94
|
-
|
|
95
|
-
const reqA = new Request("https://x.test/produto?utm_source=a");
|
|
96
|
-
const reqB = new Request("https://x.test/produto?utm_source=b");
|
|
97
|
-
const p1 = loader({ id: 1 }, reqA);
|
|
98
|
-
const p2 = loader({ id: 2 }, reqB); // different props + url, same pathname
|
|
99
|
-
release();
|
|
100
|
-
await Promise.all([p1, p2]);
|
|
101
|
-
|
|
102
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
it("runs fresh (no dedup) when cacheKey returns null", async () => {
|
|
106
|
-
const { fn, release } = makeLoader("p");
|
|
107
|
-
const mod: LoaderModule = {
|
|
108
|
-
default: fn,
|
|
109
|
-
cache: "stale-while-revalidate",
|
|
110
|
-
cacheKey: () => null,
|
|
111
|
-
};
|
|
112
|
-
const loader = createCachedLoaderFromModule("site/loaders/personalized", mod);
|
|
113
|
-
|
|
114
|
-
const req = new Request("https://x.test/");
|
|
115
|
-
const p1 = loader({ id: 1 }, req);
|
|
116
|
-
const p2 = loader({ id: 1 }, req);
|
|
117
|
-
release();
|
|
118
|
-
await Promise.all([p1, p2]);
|
|
119
|
-
|
|
120
|
-
expect(fn).toHaveBeenCalledTimes(2);
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
it("sources req from RequestContext when the caller passes none (CMS-resolution path)", async () => {
|
|
124
|
-
const { fn, release } = makeLoader("p");
|
|
125
|
-
const seen: string[] = [];
|
|
126
|
-
const mod: LoaderModule = {
|
|
127
|
-
default: fn,
|
|
128
|
-
cache: "stale-while-revalidate",
|
|
129
|
-
cacheKey: (_props, req) => {
|
|
130
|
-
seen.push(new URL(req!.url).pathname);
|
|
131
|
-
return new URL(req!.url).pathname;
|
|
132
|
-
},
|
|
133
|
-
};
|
|
134
|
-
const loader = createCachedLoaderFromModule("site/loaders/ctx", mod);
|
|
135
|
-
|
|
136
|
-
const req = new Request("https://x.test/categoria");
|
|
137
|
-
await RequestContext.run(req, async () => {
|
|
138
|
-
// Called with ONLY props, mirroring resolve.ts internalResolve.
|
|
139
|
-
const p1 = loader({ a: 1 });
|
|
140
|
-
const p2 = loader({ a: 1 });
|
|
141
|
-
release();
|
|
142
|
-
await Promise.all([p1, p2]);
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
expect(seen).toContain("/categoria");
|
|
146
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
it("falls back to props-hash dedup when cacheKey needs req but none is available", async () => {
|
|
150
|
-
const { fn, release } = makeLoader("p");
|
|
151
|
-
const mod: LoaderModule = {
|
|
152
|
-
default: fn,
|
|
153
|
-
cache: "stale-while-revalidate",
|
|
154
|
-
// Would throw on undefined req — the wrapper must not call it without one.
|
|
155
|
-
cacheKey: (_props, req) => new URL(req!.url).pathname,
|
|
156
|
-
};
|
|
157
|
-
const loader = createCachedLoaderFromModule("site/loaders/noreq", mod);
|
|
158
|
-
|
|
159
|
-
// No req arg, no RequestContext scope.
|
|
160
|
-
const p1 = loader({ a: 1 });
|
|
161
|
-
const p2 = loader({ a: 1 });
|
|
162
|
-
release();
|
|
163
|
-
await expect(Promise.all([p1, p2])).resolves.toEqual(["p", "p"]);
|
|
164
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
165
|
-
});
|
|
166
|
-
|
|
167
|
-
it("propagates loader errors and clears the in-flight entry", async () => {
|
|
168
|
-
const err = new Error("upstream down");
|
|
169
|
-
const fn = vi.fn(async () => {
|
|
170
|
-
throw err;
|
|
171
|
-
});
|
|
172
|
-
const mod: LoaderModule = { default: fn, cache: "stale-while-revalidate" };
|
|
173
|
-
const loader = createCachedLoaderFromModule("site/loaders/boom", mod);
|
|
174
|
-
|
|
175
|
-
await expect(loader({ a: 1 })).rejects.toThrow("upstream down");
|
|
176
|
-
// A retry after failure is not blocked by a stuck in-flight entry.
|
|
177
|
-
await expect(loader({ a: 1 })).rejects.toThrow("upstream down");
|
|
178
|
-
expect(fn).toHaveBeenCalledTimes(2);
|
|
179
|
-
});
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
describe("createLoaderEntry — lazy import + wrap", () => {
|
|
183
|
-
it("imports the module once and dedups concurrent calls", async () => {
|
|
184
|
-
const { fn, release } = makeLoader("lazy");
|
|
185
|
-
const importFn = vi.fn(async () => ({
|
|
186
|
-
default: fn,
|
|
187
|
-
cache: "stale-while-revalidate" as const,
|
|
188
|
-
}));
|
|
189
|
-
const entry = createLoaderEntry("site/loaders/lazy", importFn);
|
|
190
|
-
|
|
191
|
-
const p1 = entry({ a: 1 });
|
|
192
|
-
const p2 = entry({ a: 1 });
|
|
193
|
-
release();
|
|
194
|
-
await Promise.all([p1, p2]);
|
|
195
|
-
|
|
196
|
-
expect(importFn).toHaveBeenCalledTimes(1);
|
|
197
|
-
expect(fn).toHaveBeenCalledTimes(1);
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
it("passes non-opted-in loaders straight through", async () => {
|
|
201
|
-
const { fn, release } = makeLoader("plain");
|
|
202
|
-
release();
|
|
203
|
-
const entry = createLoaderEntry("site/loaders/plain", async () => ({ default: fn }));
|
|
204
|
-
|
|
205
|
-
await entry({ a: 1 });
|
|
206
|
-
await entry({ a: 1 });
|
|
207
|
-
expect(fn).toHaveBeenCalledTimes(2);
|
|
208
|
-
});
|
|
209
|
-
});
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
-
import { configureMeter, MetricNames } from "../middleware/observability";
|
|
3
|
-
import { clearLoaderCache, createCachedLoader } from "./cachedLoader";
|
|
4
|
-
|
|
5
|
-
type Sample = { name: string; value: number; labels?: Record<string, unknown> };
|
|
6
|
-
|
|
7
|
-
function fakeMeter(samples: Sample[]) {
|
|
8
|
-
return {
|
|
9
|
-
counterInc: () => {},
|
|
10
|
-
gaugeSet: () => {},
|
|
11
|
-
histogramRecord: (name: string, value: number, labels?: Record<string, unknown>) => {
|
|
12
|
-
samples.push({ name, value, labels });
|
|
13
|
-
},
|
|
14
|
-
};
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
const sizeSamples = (samples: Sample[]) => samples.filter((s) => s.name === MetricNames.CACHE_SIZE);
|
|
18
|
-
|
|
19
|
-
describe("deco.cache.size — emitted on every loader cache write", () => {
|
|
20
|
-
let samples: Sample[];
|
|
21
|
-
|
|
22
|
-
beforeEach(() => {
|
|
23
|
-
clearLoaderCache();
|
|
24
|
-
samples = [];
|
|
25
|
-
configureMeter(fakeMeter(samples));
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
afterEach(() => {
|
|
29
|
-
clearLoaderCache();
|
|
30
|
-
configureMeter({ counterInc: () => {} }); // drop the recorder
|
|
31
|
-
vi.useRealTimers();
|
|
32
|
-
vi.restoreAllMocks();
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
it("records one sample on the cold-miss write, labelled op=set + the loader name", async () => {
|
|
36
|
-
const cached = createCachedLoader("t/size-miss", async (p: { id: number }) => ({ v: p.id }), {
|
|
37
|
-
policy: "stale-while-revalidate",
|
|
38
|
-
maxAge: 60_000,
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
await cached({ id: 1 });
|
|
42
|
-
|
|
43
|
-
const sizes = sizeSamples(samples);
|
|
44
|
-
expect(sizes).toHaveLength(1);
|
|
45
|
-
expect(sizes[0].labels).toEqual({ op: "set", profile: "t/size-miss" });
|
|
46
|
-
// Bytes, not seconds — and floored at MIN_ENTRY_BYTES for a tiny payload.
|
|
47
|
-
expect(sizes[0].value).toBe(512);
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
it("does not re-record on a HIT — only writes are measured", async () => {
|
|
51
|
-
const cached = createCachedLoader("t/size-hit", async (p: { id: number }) => ({ v: p.id }), {
|
|
52
|
-
policy: "stale-while-revalidate",
|
|
53
|
-
maxAge: 60_000,
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
await cached({ id: 1 }); // MISS -> write
|
|
57
|
-
await cached({ id: 1 }); // HIT -> no write
|
|
58
|
-
|
|
59
|
-
expect(sizeSamples(samples)).toHaveLength(1);
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
it("records the SWR background-refresh write too, not just the cold miss", async () => {
|
|
63
|
-
vi.useFakeTimers();
|
|
64
|
-
vi.setSystemTime(new Date("2026-05-18T16:00:00.000Z"));
|
|
65
|
-
|
|
66
|
-
const cached = createCachedLoader("t/size-swr", async (p: { id: number }) => ({ v: p.id }), {
|
|
67
|
-
policy: "stale-while-revalidate",
|
|
68
|
-
maxAge: 1_000,
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
await cached({ id: 1 }); // MISS -> write #1
|
|
72
|
-
vi.setSystemTime(new Date("2026-05-18T16:00:05.000Z")); // now stale
|
|
73
|
-
await cached({ id: 1 }); // STALE-HIT -> background refresh
|
|
74
|
-
await vi.runAllTimersAsync(); // let the refresh settle
|
|
75
|
-
|
|
76
|
-
const sizes = sizeSamples(samples);
|
|
77
|
-
expect(sizes).toHaveLength(2); // write #2 came from the refresh
|
|
78
|
-
expect(sizes.every((s) => s.labels?.op === "set")).toBe(true);
|
|
79
|
-
expect(sizes.every((s) => s.labels?.profile === "t/size-swr")).toBe(true);
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it("scales with the payload so a fat loader is distinguishable from a thin one", async () => {
|
|
83
|
-
const big = { blob: "x".repeat(50_000) };
|
|
84
|
-
const cached = createCachedLoader("t/size-big", async () => big, {
|
|
85
|
-
policy: "stale-while-revalidate",
|
|
86
|
-
maxAge: 60_000,
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
await cached({});
|
|
90
|
-
|
|
91
|
-
expect(sizeSamples(samples)[0].value).toBeGreaterThan(50_000);
|
|
92
|
-
});
|
|
93
|
-
});
|