@decocms/tanstack 7.86.0 → 7.86.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.86.0",
3
+ "version": "7.86.1",
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.86.0",
30
- "@decocms/blocks-admin": "7.86.0",
31
- "@decocms/blocks-cli": "7.86.0"
29
+ "@decocms/blocks": "7.86.1",
30
+ "@decocms/blocks-admin": "7.86.1",
31
+ "@decocms/blocks-cli": "7.86.1"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "@tanstack/react-query": ">=5.0.0",
@@ -1,3 +1,4 @@
1
+ import { redirectPathHash } from "@decocms/blocks/cms";
1
2
  import {
2
3
  loadRedirects,
3
4
  matchExactRedirect,
@@ -7,10 +8,14 @@ import {
7
8
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8
9
  import { clearRedirectCache, lookupExactRedirect } from "./kvRedirects";
9
10
 
10
- /** Minimal KV binding that records every read. */
11
+ /** Minimal KV binding: `rules` records the `redirect:*` reads, `index` the
12
+ * reads of the deployment's `index:redirects:<id>`. */
11
13
  function makeKV(values: Record<string, string> = {}) {
12
- const get = vi.fn((key: string) => Promise.resolve(values[key] ?? null));
13
- return { get, put: vi.fn(), delete: vi.fn() };
14
+ const read = (key: string) => Promise.resolve(values[key] ?? null);
15
+ const rules = vi.fn(read);
16
+ const index = vi.fn(read);
17
+ const get = (key: string) => (key.startsWith("index:redirects:") ? index(key) : rules(key));
18
+ return { get, rules, index, put: vi.fn(), delete: vi.fn() };
14
19
  }
15
20
 
16
21
  const ID = "sha-abc";
@@ -39,9 +44,9 @@ describe("lookupExactRedirect", () => {
39
44
  const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new","status":301}' });
40
45
  await expect(lookupExactRedirect(enabled(kv), "/old", "POST")).resolves.toBeNull();
41
46
  await expect(lookupExactRedirect(enabled(kv), "/old", "PUT")).resolves.toBeNull();
42
- expect(kv.get).not.toHaveBeenCalled();
47
+ expect(kv.rules).not.toHaveBeenCalled();
43
48
  await expect(lookupExactRedirect(enabled(kv), "/old", "HEAD")).resolves.toMatchObject({ to: "/new" });
44
- expect(kv.get).toHaveBeenCalledTimes(1);
49
+ expect(kv.rules).toHaveBeenCalledTimes(1);
45
50
  });
46
51
 
47
52
  it("returns null for a missing key", async () => {
@@ -52,14 +57,14 @@ describe("lookupExactRedirect", () => {
52
57
  const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new","status":307}' });
53
58
  await lookupExactRedirect(enabled(kv), "/old");
54
59
  await lookupExactRedirect(enabled(kv), "/old");
55
- expect(kv.get).toHaveBeenCalledTimes(1);
60
+ expect(kv.rules).toHaveBeenCalledTimes(1);
56
61
  });
57
62
 
58
63
  it("caches a MISS too — that is the common case on every request", async () => {
59
64
  const kv = makeKV();
60
65
  await lookupExactRedirect(enabled(kv), "/nope");
61
66
  await lookupExactRedirect(enabled(kv), "/nope");
62
- expect(kv.get).toHaveBeenCalledTimes(1);
67
+ expect(kv.rules).toHaveBeenCalledTimes(1);
63
68
  });
64
69
 
65
70
  it("re-reads after the TTL, which is how a redirect edit propagates", async () => {
@@ -71,20 +76,20 @@ describe("lookupExactRedirect", () => {
71
76
  vi.useFakeTimers();
72
77
  vi.setSystemTime(Date.now() + 61_000);
73
78
  await lookupExactRedirect(enabled(kv), "/soon");
74
- expect(kv.get).toHaveBeenCalledTimes(2);
79
+ expect(kv.rules).toHaveBeenCalledTimes(2);
75
80
  });
76
81
 
77
82
  it("is inert when fast-deploy is off", async () => {
78
83
  const kv = makeKV({ [`redirect:${ID}:/old`]: '{"to":"/new","status":301}' });
79
84
  const env = { DECO_KV: kv, DECO_DEPLOYMENT_ID: ID }; // no DECO_FAST_DEPLOY
80
85
  await expect(lookupExactRedirect(env, "/old")).resolves.toBeNull();
81
- expect(kv.get).not.toHaveBeenCalled();
86
+ expect(kv.rules).not.toHaveBeenCalled();
82
87
  });
83
88
 
84
89
  it("never reads another deployment's keys when the id is unresolvable", async () => {
85
90
  const kv = makeKV();
86
91
  await lookupExactRedirect({ DECO_FAST_DEPLOY: "1", DECO_KV: kv }, "/old");
87
- expect(kv.get).not.toHaveBeenCalled();
92
+ expect(kv.rules).not.toHaveBeenCalled();
88
93
  });
89
94
 
90
95
  it("treats a KV failure as no-redirect, never a throw", async () => {
@@ -112,6 +117,54 @@ describe("lookupExactRedirect", () => {
112
117
  });
113
118
  });
114
119
 
120
+ describe("lookupExactRedirect — index:redirects:<id>", () => {
121
+ const indexOf = (...paths: string[]) => JSON.stringify(paths.map(redirectPathHash).sort((a, b) => a - b));
122
+ const stored = { [`redirect:${ID}:/old`]: '{"to":"/new","status":301}' };
123
+
124
+ it("a path outside the index reads no rule, and the index is read once", async () => {
125
+ const kv = makeKV({ ...stored, [`index:redirects:${ID}`]: indexOf("/old", "/other") });
126
+ await expect(lookupExactRedirect(enabled(kv), "/p/1")).resolves.toBeNull();
127
+ await expect(lookupExactRedirect(enabled(kv), "/p/2")).resolves.toBeNull();
128
+ expect(kv.rules).not.toHaveBeenCalled();
129
+ expect(kv.index).toHaveBeenCalledTimes(1);
130
+ });
131
+
132
+ it("a path in the index is still read and redirects", async () => {
133
+ const kv = makeKV({ ...stored, [`index:redirects:${ID}`]: indexOf("/old") });
134
+ await expect(lookupExactRedirect(enabled(kv), "/OLD/")).resolves.toMatchObject({ to: "/new" });
135
+ expect(kv.rules).toHaveBeenCalledTimes(1);
136
+ });
137
+
138
+ it("an empty index means no rule is ever read", async () => {
139
+ const kv = makeKV({ ...stored, [`index:redirects:${ID}`]: "[]" });
140
+ await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toBeNull();
141
+ expect(kv.rules).not.toHaveBeenCalled();
142
+ });
143
+
144
+ it("without an index (a deployment synced before it existed) every path is read", async () => {
145
+ const kv = makeKV(stored);
146
+ await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toMatchObject({ to: "/new" });
147
+ await expect(lookupExactRedirect(enabled(kv), "/p/1")).resolves.toBeNull();
148
+ expect(kv.rules).toHaveBeenCalledTimes(2);
149
+ });
150
+
151
+ it("a malformed index is no index", async () => {
152
+ const kv = makeKV({ ...stored, [`index:redirects:${ID}`]: "not json" });
153
+ await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toMatchObject({ to: "/new" });
154
+ });
155
+
156
+ it("is read again after the TTL, so a rule added by a sync starts redirecting", async () => {
157
+ const values: Record<string, string> = { ...stored, [`index:redirects:${ID}`]: "[]" };
158
+ const kv = makeKV(values);
159
+ await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toBeNull();
160
+ values[`index:redirects:${ID}`] = indexOf("/old");
161
+ vi.useFakeTimers();
162
+ vi.setSystemTime(Date.now() + 61_000);
163
+ await expect(lookupExactRedirect(enabled(kv), "/old")).resolves.toMatchObject({ to: "/new" });
164
+ expect(kv.index).toHaveBeenCalledTimes(2);
165
+ });
166
+ });
167
+
115
168
  describe("lookupExactRedirect — semantics", () => {
116
169
  afterEach(() => setRedirectSemantics("legacy"));
117
170
  const value = JSON.stringify([
@@ -17,7 +17,13 @@
17
17
  * up with redirects in neither place.
18
18
  */
19
19
 
20
- import { getDeploymentId, redirectKey, type StoredRedirect } from "@decocms/blocks/cms";
20
+ import {
21
+ getDeploymentId,
22
+ redirectIndexKey,
23
+ redirectKey,
24
+ redirectPathHash,
25
+ type StoredRedirect,
26
+ } from "@decocms/blocks/cms";
21
27
  import { normalizePath, type Redirect, selectExactRedirect } from "@decocms/blocks/sdk/redirects";
22
28
  import { getFastDeployKV } from "./kvHydration";
23
29
 
@@ -48,7 +54,64 @@ interface CacheEntry {
48
54
 
49
55
  // globalThis-backed so every Vite server-function split-module copy shares one
50
56
  // cache (same reason as `loader.ts` and `kvHydration.ts`).
51
- const G = globalThis as unknown as { __decoRedirectCache?: Map<string, CacheEntry> };
57
+ const G = globalThis as unknown as {
58
+ __decoRedirectCache?: Map<string, CacheEntry>;
59
+ __decoRedirectIndex?: RedirectIndex;
60
+ };
61
+
62
+ /**
63
+ * The deployment's `index:redirects:<id>`: which paths have a rule at all.
64
+ * Nearly every request is for a path that has none, and each of those used to
65
+ * be a billed KV read that found nothing.
66
+ * One read per isolate per `TTL_MS` replaces them. `hashes` is null when the
67
+ * deployment has no index (synced before the key existed) or the read failed:
68
+ * then every path is looked up as before.
69
+ */
70
+ interface RedirectIndex {
71
+ id: string;
72
+ hashes: Uint32Array | null;
73
+ expiresAt: number;
74
+ pending?: Promise<Uint32Array | null>;
75
+ }
76
+
77
+ async function redirectIndex(
78
+ kv: { get(key: string): Promise<string | null> },
79
+ id: string,
80
+ ): Promise<Uint32Array | null> {
81
+ const current = G.__decoRedirectIndex;
82
+ if (current?.id === id) {
83
+ if (current.pending) return current.pending;
84
+ if (Date.now() < current.expiresAt) return current.hashes;
85
+ }
86
+ const entry: RedirectIndex = { id, hashes: null, expiresAt: 0 };
87
+ entry.pending = kv
88
+ .get(redirectIndexKey(id))
89
+ .then((raw) => {
90
+ const parsed = raw === null ? null : (JSON.parse(raw) as unknown);
91
+ return Array.isArray(parsed) ? Uint32Array.from(parsed as number[]).sort() : null;
92
+ })
93
+ .catch(() => null)
94
+ .then((hashes) => {
95
+ entry.hashes = hashes;
96
+ entry.expiresAt = Date.now() + TTL_MS;
97
+ entry.pending = undefined;
98
+ return hashes;
99
+ });
100
+ G.__decoRedirectIndex = entry;
101
+ return entry.pending;
102
+ }
103
+
104
+ function hasHash(sorted: Uint32Array, hash: number): boolean {
105
+ let lo = 0;
106
+ let hi = sorted.length - 1;
107
+ while (lo <= hi) {
108
+ const mid = (lo + hi) >>> 1;
109
+ if (sorted[mid] === hash) return true;
110
+ if (sorted[mid] < hash) lo = mid + 1;
111
+ else hi = mid - 1;
112
+ }
113
+ return false;
114
+ }
52
115
  function cache(): Map<string, CacheEntry> {
53
116
  G.__decoRedirectCache ??= new Map();
54
117
  return G.__decoRedirectCache;
@@ -79,6 +142,7 @@ function peek(key: string): CacheEntry | undefined {
79
142
  /** Test seam — the cache is process-global, so suites must be able to reset it. */
80
143
  export function clearRedirectCache(): void {
81
144
  G.__decoRedirectCache = new Map();
145
+ G.__decoRedirectIndex = undefined;
82
146
  }
83
147
 
84
148
  /**
@@ -118,7 +182,11 @@ export async function lookupExactRedirect(
118
182
  const deploymentId = getDeploymentId(env);
119
183
  if (!deploymentId) return null;
120
184
 
121
- const key = redirectKey(deploymentId, normalizePath(pathname));
185
+ const path = normalizePath(pathname);
186
+ const index = await redirectIndex(kv, deploymentId);
187
+ if (index && !hasHash(index, redirectPathHash(path))) return null;
188
+
189
+ const key = redirectKey(deploymentId, path);
122
190
  const cached = peek(key);
123
191
  const stored = cached !== undefined ? cached.value : await read(kv, key);
124
192
  if (cached === undefined) remember(key, stored);