cursedbelt-server 4.77.0 β†’ 4.79.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.
@@ -212,3 +212,40 @@ export interface AsyncMapsBudget<Api extends string> {
212
212
  * under load is the one kind that cannot be trusted.
213
213
  */
214
214
  export declare function createMetaTableBudget<Api extends string>(db: Pick<D1LikeDatabase, 'prepare' | 'batch'>, options: Omit<MapsBudgetOptions<Api>, 'store'>): AsyncMapsBudget<Api>;
215
+ /**
216
+ * A Maps key Google REFUSED, remembered in the app's `meta (key, value)` table so the app stops asking
217
+ * (forge tasks 5592, 5764).
218
+ *
219
+ * πŸ”΄ On 2026-11-18 every Places viewport in photos spent a count of the ceiling on a key Google called
220
+ * "invalid", and the 404's reason said only "answered 403". A new key is the owner's hands, never minutes
221
+ * away, so a 401/403 is written down for an hour: until then the door answers with the refusal's own words
222
+ * and touches neither the ceiling nor the network. photos, trivia and family each held a copy of this; a
223
+ * fix to it (a new status Google uses to refuse) now reaches all three.
224
+ *
225
+ * One row per API (`maps-refused.<api>`), because a key restricted away from ONE API is still good for
226
+ * the rest.
227
+ */
228
+ /** How long an app stops asking after Google refused its key. */
229
+ export declare const KEY_REFUSED_HOLD_MS: number;
230
+ /** The `meta` row a refusal of `api` is remembered under: `{ at: ISO, reason }`. */
231
+ export declare const keyRefusedRow: (api: string) => string;
232
+ /** The HTTP statuses that mean Google refuses the KEY, not the request. */
233
+ export declare const isKeyRefusal: (status: number) => boolean;
234
+ export interface KeyRefusalOptions {
235
+ /** The app's own name, as a reader sees it in the reason ("photos", "trivia", "family"). */
236
+ app: string;
237
+ /** Defaults to the wall clock; a spec passes its own. */
238
+ now?: () => number;
239
+ /** Defaults to {@link KEY_REFUSED_HOLD_MS}. */
240
+ holdMs?: number;
241
+ }
242
+ export interface KeyRefusalMemory {
243
+ /** The refusal of `api` still holding now, in words a reader sees β€” or null. A malformed row is null. */
244
+ held(api: string): Promise<string | null>;
245
+ /**
246
+ * When `response` is Google refusing the key, remember it and return the reason; otherwise null.
247
+ * Reads the body (Google's one line of plain text, "The provided API key is invalid.") only then.
248
+ */
249
+ record(api: string, response: Response): Promise<string | null>;
250
+ }
251
+ export declare function createKeyRefusalMemory(db: Pick<D1LikeDatabase, 'prepare'>, options: KeyRefusalOptions): KeyRefusalMemory;
@@ -248,3 +248,55 @@ export function createMetaTableBudget(db, options) {
248
248
  },
249
249
  };
250
250
  }
251
+ // ───────────────────────────── a refused key ─────────────────────────────
252
+ /**
253
+ * A Maps key Google REFUSED, remembered in the app's `meta (key, value)` table so the app stops asking
254
+ * (forge tasks 5592, 5764).
255
+ *
256
+ * πŸ”΄ On 2026-11-18 every Places viewport in photos spent a count of the ceiling on a key Google called
257
+ * "invalid", and the 404's reason said only "answered 403". A new key is the owner's hands, never minutes
258
+ * away, so a 401/403 is written down for an hour: until then the door answers with the refusal's own words
259
+ * and touches neither the ceiling nor the network. photos, trivia and family each held a copy of this; a
260
+ * fix to it (a new status Google uses to refuse) now reaches all three.
261
+ *
262
+ * One row per API (`maps-refused.<api>`), because a key restricted away from ONE API is still good for
263
+ * the rest.
264
+ */
265
+ /** How long an app stops asking after Google refused its key. */
266
+ export const KEY_REFUSED_HOLD_MS = 60 * 60 * 1000;
267
+ /** The `meta` row a refusal of `api` is remembered under: `{ at: ISO, reason }`. */
268
+ export const keyRefusedRow = (api) => `maps-refused.${api}`;
269
+ /** The HTTP statuses that mean Google refuses the KEY, not the request. */
270
+ export const isKeyRefusal = (status) => status === 401 || status === 403;
271
+ export function createKeyRefusalMemory(db, options) {
272
+ const now = options.now ?? Date.now;
273
+ const holdMs = options.holdMs ?? KEY_REFUSED_HOLD_MS;
274
+ return {
275
+ async held(api) {
276
+ const row = await db.prepare('SELECT value FROM meta WHERE key = ?').bind(keyRefusedRow(api)).first();
277
+ if (!row)
278
+ return null;
279
+ try {
280
+ const mark = JSON.parse(row.value);
281
+ const at = typeof mark.at === 'string' ? Date.parse(mark.at) : Number.NaN;
282
+ if (!Number.isFinite(at) || now() - at >= holdMs || typeof mark.reason !== 'string')
283
+ return null;
284
+ return `${mark.reason} ${options.app} stopped asking at ${mark.at} and asks again an hour after.`;
285
+ }
286
+ catch {
287
+ return null;
288
+ }
289
+ },
290
+ async record(api, response) {
291
+ if (!isKeyRefusal(response.status))
292
+ return null;
293
+ const said = (await response.text().catch(() => '')).trim().slice(0, 200);
294
+ const reason = `Google refuses the Maps key ${options.app} holds, for ${api} (${response.status}${said ? `: ${said}` : ''}) β€” a new GOOGLE_MAPS_API_KEY is needed; the map draws every pin meanwhile.`;
295
+ await db
296
+ .prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
297
+ .bind(keyRefusedRow(api), JSON.stringify({ at: new Date(now()).toISOString(), reason }))
298
+ .run();
299
+ return reason;
300
+ },
301
+ };
302
+ }
@@ -7,13 +7,15 @@
7
7
  * request a query string may ask for (clamped, so the cache key space stays tiny), the URL with
8
8
  * the fleet's map styling, the cache key, and an LRU for the bytes.
9
9
  *
10
- * πŸ”΄ The FETCH is not here, on purpose. Each app keeps its own ONE DOOR to Google β€” the place
11
- * its `cursedbelt-server/maps-budget` ceiling is consumed immediately before the request β€” so
12
- * the ceiling and the call can never be separated. Build the URL here; spend it there.
10
+ * πŸ”΄ The FETCH is here only inside {@link renderStaticMap}, THE door: a key Google refused, then the
11
+ * app's `cursedbelt-server/maps-budget` ceiling consumed immediately before the one request, so the
12
+ * ceiling and the call can never be separated. photos and trivia each held a copy of it until forge
13
+ * task 5764; a fix to the refusal or the timeout now reaches every app that draws a map.
13
14
  *
14
15
  * πŸ”΄ The key NEVER reaches a browser: `GOOGLE_MAPS_API_KEY` is restricted by API and not by
15
16
  * HTTP referrer, so the imagery is proxied and the frame's overlay is our own SVG.
16
17
  */
18
+ import type { AsyncMapsBudget, KeyRefusalMemory } from '../maps-budget/mapsBudget.js';
17
19
  /** The one Static Maps endpoint. An app's door checks a URL starts with it. */
18
20
  export declare const STATIC_MAP_HOST = "https://maps.googleapis.com/maps/api/staticmap";
19
21
  /** A lat/lng. Structural, so the server tier needs nothing from the React package. */
@@ -101,3 +103,28 @@ export declare function createImageCache(max?: number): {
101
103
  set(key: string, value: Uint8Array): void;
102
104
  readonly size: number;
103
105
  };
106
+ /** The app's seam to Google: its key and its fetch (a spec passes a fake). */
107
+ export interface StaticMapSeam {
108
+ apiKey: string;
109
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
110
+ }
111
+ export type RenderedStaticMap = {
112
+ ok: true;
113
+ bytes: Uint8Array;
114
+ } | {
115
+ ok: false;
116
+ reason: string;
117
+ };
118
+ /** How long the door waits on Google before it gives up and the frame draws its graticule. */
119
+ export declare const STATIC_MAP_TIMEOUT_MS = 8000;
120
+ /**
121
+ * THE door to Google Static Maps: a refused key and the ceiling first, then the one request, with a
122
+ * timeout. A refusal touches no network, and a 401/403 is remembered so the next viewport does not ask.
123
+ */
124
+ export declare function renderStaticMap(input: {
125
+ request: StaticMapRequest;
126
+ maps: StaticMapSeam;
127
+ budget: Pick<AsyncMapsBudget<'staticmap'>, 'consume'>;
128
+ refusals: KeyRefusalMemory;
129
+ timeoutMs?: number;
130
+ }): Promise<RenderedStaticMap>;
@@ -7,9 +7,10 @@
7
7
  * request a query string may ask for (clamped, so the cache key space stays tiny), the URL with
8
8
  * the fleet's map styling, the cache key, and an LRU for the bytes.
9
9
  *
10
- * πŸ”΄ The FETCH is not here, on purpose. Each app keeps its own ONE DOOR to Google β€” the place
11
- * its `cursedbelt-server/maps-budget` ceiling is consumed immediately before the request β€” so
12
- * the ceiling and the call can never be separated. Build the URL here; spend it there.
10
+ * πŸ”΄ The FETCH is here only inside {@link renderStaticMap}, THE door: a key Google refused, then the
11
+ * app's `cursedbelt-server/maps-budget` ceiling consumed immediately before the one request, so the
12
+ * ceiling and the call can never be separated. photos and trivia each held a copy of it until forge
13
+ * task 5764; a fix to the refusal or the timeout now reaches every app that draws a map.
13
14
  *
14
15
  * πŸ”΄ The key NEVER reaches a browser: `GOOGLE_MAPS_API_KEY` is restricted by API and not by
15
16
  * HTTP referrer, so the imagery is proxied and the frame's overlay is our own SVG.
@@ -169,3 +170,34 @@ export function createImageCache(max = 160) {
169
170
  },
170
171
  };
171
172
  }
173
+ /** How long the door waits on Google before it gives up and the frame draws its graticule. */
174
+ export const STATIC_MAP_TIMEOUT_MS = 8000;
175
+ /**
176
+ * THE door to Google Static Maps: a refused key and the ceiling first, then the one request, with a
177
+ * timeout. A refusal touches no network, and a 401/403 is remembered so the next viewport does not ask.
178
+ */
179
+ export async function renderStaticMap(input) {
180
+ const held = await input.refusals.held('staticmap');
181
+ if (held)
182
+ return { ok: false, reason: held };
183
+ const verdict = await input.budget.consume('staticmap');
184
+ if (!verdict.allowed)
185
+ return { ok: false, reason: verdict.reason };
186
+ const controller = new AbortController();
187
+ const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? STATIC_MAP_TIMEOUT_MS);
188
+ try {
189
+ const response = await input.maps.fetch(staticMapUrl(input.request, input.maps.apiKey), { signal: controller.signal });
190
+ const refused = await input.refusals.record('staticmap', response);
191
+ if (refused)
192
+ return { ok: false, reason: refused };
193
+ if (!response.ok)
194
+ return { ok: false, reason: `Google staticmap answered ${response.status}` };
195
+ return { ok: true, bytes: new Uint8Array(await response.arrayBuffer()) };
196
+ }
197
+ catch (error) {
198
+ return { ok: false, reason: `Google staticmap did not answer (${error instanceof Error ? error.message : 'unknown'})` };
199
+ }
200
+ finally {
201
+ clearTimeout(timer);
202
+ }
203
+ }
@@ -0,0 +1,19 @@
1
+ export interface RequestScope<S extends object> {
2
+ /** Run `work` with `scope` as the current request's β€” everything it awaits, and defers, sees it. */
3
+ run<T>(scope: S, work: () => T): T;
4
+ /** The current request's scope; THROWS outside one (a stand-in used at isolate scope is a bug). */
5
+ current(): S;
6
+ /** A stand-in for `scope[key]` that reads the current request's value at every property access. */
7
+ late<K extends keyof S>(key: K): NonNullable<S[K]>;
8
+ /** The same, for a value derived from the scope (`(s) => s.env.AE`). */
9
+ lateOf<T extends object>(read: (scope: S) => T | null | undefined, what: string): T;
10
+ }
11
+ export declare function createRequestScope<S extends object>(name: string): RequestScope<S>;
12
+ /**
13
+ * What an isolate-built graph is keyed by: every binding by name β€” a string by value, an object (a D1, a
14
+ * service binding) by identity. A changed secret or a swapped binding builds afresh; the same env never does.
15
+ * photos and collections each held a copy of this until forge task 5830.
16
+ */
17
+ export declare function isolateKey(env: object): string;
18
+ /** `build(env)` once per {@link isolateKey}: the same env answers the same value, a changed one builds afresh. */
19
+ export declare function cacheByBindings<E extends object, T>(build: (env: E) => T): (env: E) => T;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * `cursedbelt-server/request-scope` β€” one request's things, for an app built ONCE per isolate.
3
+ *
4
+ * Born in auth (forge task 5632), promoted when photos took the same shape: a Worker that rebuilt
5
+ * its whole Hono graph per request paid a flat 5–40 CPU-ms floor on every call. Worker-safe: it
6
+ * needs `nodejs_compat` for `node:async_hooks`, nothing else.
7
+ *
8
+ * The assembly closes over its database, its session store, its throttle… β€” objects that belong to
9
+ * ONE request on a Worker (`perInvocation`'s query count, a D1 snapshot, a binding's I/O, which
10
+ * workerd refuses to touch from another request). Building the whole route tier per request cost
11
+ * 16–40 CPU-ms on auth-stage; building it once and handing it these values LATE costs nothing.
12
+ *
13
+ * `late(key)` is a stand-in that reads `key` from the CURRENT request's scope at every use, so the
14
+ * assembly can hold it from the first request on. The scope rides `AsyncLocalStorage`, never a
15
+ * module variable: an isolate serves requests concurrently, and a variable set by request B while
16
+ * request A awaits D1 would hand A B's sessions. Work handed to `waitUntil` keeps its own scope.
17
+ *
18
+ * πŸ”΄ A stand-in is for a LEAF service. One with a `mount` (a notification service) registers routes
19
+ * over the internals of whichever request built it β€” build that once over a late database instead.
20
+ */
21
+ import { AsyncLocalStorage } from "node:async_hooks";
22
+ export function createRequestScope(name) {
23
+ const storage = new AsyncLocalStorage();
24
+ const current = () => {
25
+ const scope = storage.getStore();
26
+ if (!scope)
27
+ throw new Error(`${name}: a request-scoped value was read outside a request`);
28
+ return scope;
29
+ };
30
+ const lateOf = (read, what) => {
31
+ const target = () => {
32
+ const value = read(current());
33
+ if (value === undefined || value === null)
34
+ throw new Error(`${name}: this request has no ${what}`);
35
+ return value;
36
+ };
37
+ return new Proxy({}, {
38
+ get(_shell, prop) {
39
+ const member = Reflect.get(target(), prop);
40
+ if (typeof member !== "function")
41
+ return member;
42
+ // Resolved again at CALL time: a method taken off the stand-in while the assembly is
43
+ // built (request 1) must still run on whichever request calls it.
44
+ return (...args) => {
45
+ const value = target();
46
+ return Reflect.apply(Reflect.get(value, prop, value), value, args);
47
+ };
48
+ },
49
+ has: (_shell, prop) => Reflect.has(target(), prop),
50
+ ownKeys: () => Reflect.ownKeys(target()),
51
+ getOwnPropertyDescriptor(_shell, prop) {
52
+ const descriptor = Reflect.getOwnPropertyDescriptor(target(), prop);
53
+ // A proxy may not report a property non-configurable that its (empty) shell lacks.
54
+ return descriptor ? { ...descriptor, configurable: true } : undefined;
55
+ },
56
+ set: (_shell, prop, value) => Reflect.set(target(), prop, value),
57
+ });
58
+ };
59
+ const late = (key) => lateOf((scope) => scope[key], String(key));
60
+ return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
61
+ }
62
+ /** A stable id per binding object, so a key changes when a binding is swapped, not only when a string is. */
63
+ const bindingIds = new WeakMap();
64
+ let lastBindingId = 0;
65
+ function bindingId(value) {
66
+ let id = bindingIds.get(value);
67
+ if (id === undefined) {
68
+ lastBindingId += 1;
69
+ id = lastBindingId;
70
+ bindingIds.set(value, id);
71
+ }
72
+ return id;
73
+ }
74
+ /**
75
+ * What an isolate-built graph is keyed by: every binding by name β€” a string by value, an object (a D1, a
76
+ * service binding) by identity. A changed secret or a swapped binding builds afresh; the same env never does.
77
+ * photos and collections each held a copy of this until forge task 5830.
78
+ */
79
+ export function isolateKey(env) {
80
+ const entries = Object.entries(env).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
81
+ return JSON.stringify(entries.map(([name, value]) => [name, value !== null && (typeof value === "object" || typeof value === "function") ? bindingId(value) : value]));
82
+ }
83
+ /** `build(env)` once per {@link isolateKey}: the same env answers the same value, a changed one builds afresh. */
84
+ export function cacheByBindings(build) {
85
+ let built = null;
86
+ return (env) => {
87
+ const key = isolateKey(env);
88
+ if (built?.key === key)
89
+ return built.value;
90
+ const value = build(env);
91
+ built = { key, value };
92
+ return value;
93
+ };
94
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.77.0",
3
+ "version": "4.79.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split β€” storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -60,6 +60,12 @@
60
60
  "source": "./src/server/context.ts",
61
61
  "import": "./dist/server/context.js"
62
62
  },
63
+ "./request-scope": {
64
+ "types": "./dist/server/requestScope.d.ts",
65
+ "bun": "./src/server/requestScope.ts",
66
+ "source": "./src/server/requestScope.ts",
67
+ "import": "./dist/server/requestScope.js"
68
+ },
63
69
  "./ctgr-tunnel": {
64
70
  "types": "./dist/server/ctgrTunnel.d.ts",
65
71
  "bun": "./src/server/ctgrTunnel.ts",
@@ -453,7 +459,7 @@
453
459
  "@node-rs/argon2": "^2.0.2",
454
460
  "@types/bun": "^1.3.14",
455
461
  "@types/node": "^24",
456
- "cursedbelt": "^6.15.0",
462
+ "cursedbelt": "^6.30.1",
457
463
  "hono": "4.12.28",
458
464
  "kysely": "^0.28.17",
459
465
  "kysely-bun-sqlite": "^0.4.0",
@@ -378,3 +378,76 @@ export function createMetaTableBudget<Api extends string>(
378
378
  },
379
379
  };
380
380
  }
381
+
382
+ // ───────────────────────────── a refused key ─────────────────────────────
383
+
384
+ /**
385
+ * A Maps key Google REFUSED, remembered in the app's `meta (key, value)` table so the app stops asking
386
+ * (forge tasks 5592, 5764).
387
+ *
388
+ * πŸ”΄ On 2026-11-18 every Places viewport in photos spent a count of the ceiling on a key Google called
389
+ * "invalid", and the 404's reason said only "answered 403". A new key is the owner's hands, never minutes
390
+ * away, so a 401/403 is written down for an hour: until then the door answers with the refusal's own words
391
+ * and touches neither the ceiling nor the network. photos, trivia and family each held a copy of this; a
392
+ * fix to it (a new status Google uses to refuse) now reaches all three.
393
+ *
394
+ * One row per API (`maps-refused.<api>`), because a key restricted away from ONE API is still good for
395
+ * the rest.
396
+ */
397
+
398
+ /** How long an app stops asking after Google refused its key. */
399
+ export const KEY_REFUSED_HOLD_MS = 60 * 60 * 1000;
400
+
401
+ /** The `meta` row a refusal of `api` is remembered under: `{ at: ISO, reason }`. */
402
+ export const keyRefusedRow = (api: string): string => `maps-refused.${api}`;
403
+
404
+ /** The HTTP statuses that mean Google refuses the KEY, not the request. */
405
+ export const isKeyRefusal = (status: number): boolean => status === 401 || status === 403;
406
+
407
+ export interface KeyRefusalOptions {
408
+ /** The app's own name, as a reader sees it in the reason ("photos", "trivia", "family"). */
409
+ app: string;
410
+ /** Defaults to the wall clock; a spec passes its own. */
411
+ now?: () => number;
412
+ /** Defaults to {@link KEY_REFUSED_HOLD_MS}. */
413
+ holdMs?: number;
414
+ }
415
+
416
+ export interface KeyRefusalMemory {
417
+ /** The refusal of `api` still holding now, in words a reader sees β€” or null. A malformed row is null. */
418
+ held(api: string): Promise<string | null>;
419
+ /**
420
+ * When `response` is Google refusing the key, remember it and return the reason; otherwise null.
421
+ * Reads the body (Google's one line of plain text, "The provided API key is invalid.") only then.
422
+ */
423
+ record(api: string, response: Response): Promise<string | null>;
424
+ }
425
+
426
+ export function createKeyRefusalMemory(db: Pick<D1LikeDatabase, 'prepare'>, options: KeyRefusalOptions): KeyRefusalMemory {
427
+ const now = options.now ?? Date.now;
428
+ const holdMs = options.holdMs ?? KEY_REFUSED_HOLD_MS;
429
+ return {
430
+ async held(api) {
431
+ const row = await db.prepare('SELECT value FROM meta WHERE key = ?').bind(keyRefusedRow(api)).first<{ value: string }>();
432
+ if (!row) return null;
433
+ try {
434
+ const mark = JSON.parse(row.value) as { at?: unknown; reason?: unknown };
435
+ const at = typeof mark.at === 'string' ? Date.parse(mark.at) : Number.NaN;
436
+ if (!Number.isFinite(at) || now() - at >= holdMs || typeof mark.reason !== 'string') return null;
437
+ return `${mark.reason} ${options.app} stopped asking at ${mark.at as string} and asks again an hour after.`;
438
+ } catch {
439
+ return null;
440
+ }
441
+ },
442
+ async record(api, response) {
443
+ if (!isKeyRefusal(response.status)) return null;
444
+ const said = (await response.text().catch(() => '')).trim().slice(0, 200);
445
+ const reason = `Google refuses the Maps key ${options.app} holds, for ${api} (${response.status}${said ? `: ${said}` : ''}) β€” a new GOOGLE_MAPS_API_KEY is needed; the map draws every pin meanwhile.`;
446
+ await db
447
+ .prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
448
+ .bind(keyRefusedRow(api), JSON.stringify({ at: new Date(now()).toISOString(), reason }))
449
+ .run();
450
+ return reason;
451
+ },
452
+ };
453
+ }
@@ -0,0 +1,79 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { describe, expect, it } from 'bun:test';
3
+ import { createLocalD1 } from '../d1/local.js';
4
+ import { createKeyRefusalMemory, createMetaTableBudget, KEY_REFUSED_HOLD_MS, keyRefusedRow } from '../maps-budget/mapsBudget.js';
5
+ import { renderStaticMap, type StaticMapRequest } from './staticMap.js';
6
+
7
+ const AT = Date.UTC(2026, 10, 18, 12);
8
+ const request: StaticMapRequest = { center: { lat: 30, lng: -97 }, zoom: 6, width: 320, height: 180, theme: 'light' };
9
+
10
+ function harness(answer: (signal?: AbortSignal) => Response | Promise<Response>) {
11
+ const sqlite = new Database(':memory:');
12
+ sqlite.run('CREATE TABLE meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL )');
13
+ const db = createLocalD1(sqlite);
14
+ let clock = AT;
15
+ const calls: string[] = [];
16
+ const budget = createMetaTableBudget<'staticmap'>(db, { ceilings: { staticmap: 300 }, refusal: () => ({ reason: 'over the ceiling' }), now: () => clock });
17
+ const render = () =>
18
+ renderStaticMap({
19
+ request,
20
+ maps: {
21
+ apiKey: 'key',
22
+ fetch: async (url, init) => {
23
+ calls.push(url);
24
+ return answer(init?.signal ?? undefined);
25
+ },
26
+ },
27
+ budget,
28
+ refusals: createKeyRefusalMemory(db, { app: 'photos', now: () => clock }),
29
+ timeoutMs: 20,
30
+ });
31
+ return { sqlite, render, calls, advance: (ms: number) => (clock += ms), spent: async () => (await budget.usage())[0]?.used };
32
+ }
33
+
34
+ describe('renderStaticMap β€” THE door to Google Static Maps', () => {
35
+ it('answers the bytes and counts one against the ceiling', async () => {
36
+ const h = harness(() => new Response(new Uint8Array([1, 2, 3])));
37
+ expect(await h.render()).toEqual({ ok: true, bytes: new Uint8Array([1, 2, 3]) });
38
+ expect(await h.spent()).toBe(1);
39
+ });
40
+
41
+ it('πŸ”΄ a key Google refuses is remembered: the next render touches neither the ceiling nor the network', async () => {
42
+ const h = harness(() => new Response('The provided API key is invalid.', { status: 403 }));
43
+ const first = await h.render();
44
+ expect(first).toEqual({ ok: false, reason: expect.stringContaining("Google refuses the Maps key photos holds, for staticmap (403: The provided API key is invalid.)") });
45
+ expect(h.sqlite.query('SELECT key FROM meta WHERE key = ?').get(keyRefusedRow('staticmap'))).not.toBeNull();
46
+ const second = await h.render();
47
+ expect(second.ok).toBe(false);
48
+ expect(second.ok ? '' : second.reason).toContain('photos stopped asking at 2026-11-18T12:00:00.000Z');
49
+ expect(h.calls).toHaveLength(1);
50
+ expect(await h.spent()).toBe(1);
51
+ // An hour on, it asks again.
52
+ h.advance(KEY_REFUSED_HOLD_MS);
53
+ await h.render();
54
+ expect(h.calls).toHaveLength(2);
55
+ });
56
+
57
+ it('a 401 is a refusal too; a 500 is not remembered', async () => {
58
+ const unauthorized = harness(() => new Response('', { status: 401 }));
59
+ await unauthorized.render();
60
+ await unauthorized.render();
61
+ expect(unauthorized.calls).toHaveLength(1);
62
+ const down = harness(() => new Response('', { status: 500 }));
63
+ expect(await down.render()).toEqual({ ok: false, reason: 'Google staticmap answered 500' });
64
+ await down.render();
65
+ expect(down.calls).toHaveLength(2);
66
+ });
67
+
68
+ it('gives up at the timeout, with the reason', async () => {
69
+ // Google never answers; only the door's own abort ends the wait.
70
+ const silent = harness((signal) => new Promise<Response>((_, reject) => signal?.addEventListener('abort', () => reject(new Error('The operation was aborted.')))));
71
+ expect(await silent.render()).toEqual({ ok: false, reason: 'Google staticmap did not answer (The operation was aborted.)' });
72
+ });
73
+
74
+ it('a malformed refusal row holds nothing', async () => {
75
+ const h = harness(() => new Response(new Uint8Array([9])));
76
+ h.sqlite.run('INSERT INTO meta (key, value) VALUES (?, ?)', [keyRefusedRow('staticmap'), '{not json']);
77
+ expect((await h.render()).ok).toBe(true);
78
+ });
79
+ });
@@ -7,14 +7,17 @@
7
7
  * request a query string may ask for (clamped, so the cache key space stays tiny), the URL with
8
8
  * the fleet's map styling, the cache key, and an LRU for the bytes.
9
9
  *
10
- * πŸ”΄ The FETCH is not here, on purpose. Each app keeps its own ONE DOOR to Google β€” the place
11
- * its `cursedbelt-server/maps-budget` ceiling is consumed immediately before the request β€” so
12
- * the ceiling and the call can never be separated. Build the URL here; spend it there.
10
+ * πŸ”΄ The FETCH is here only inside {@link renderStaticMap}, THE door: a key Google refused, then the
11
+ * app's `cursedbelt-server/maps-budget` ceiling consumed immediately before the one request, so the
12
+ * ceiling and the call can never be separated. photos and trivia each held a copy of it until forge
13
+ * task 5764; a fix to the refusal or the timeout now reaches every app that draws a map.
13
14
  *
14
15
  * πŸ”΄ The key NEVER reaches a browser: `GOOGLE_MAPS_API_KEY` is restricted by API and not by
15
16
  * HTTP referrer, so the imagery is proxied and the frame's overlay is our own SVG.
16
17
  */
17
18
 
19
+ import type { AsyncMapsBudget, KeyRefusalMemory } from '../maps-budget/mapsBudget.js';
20
+
18
21
  /** The one Static Maps endpoint. An app's door checks a URL starts with it. */
19
22
  export const STATIC_MAP_HOST = "https://maps.googleapis.com/maps/api/staticmap";
20
23
 
@@ -195,3 +198,44 @@ export function createImageCache(max = 160) {
195
198
  };
196
199
  }
197
200
 
201
+
202
+ /** The app's seam to Google: its key and its fetch (a spec passes a fake). */
203
+ export interface StaticMapSeam {
204
+ apiKey: string;
205
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
206
+ }
207
+
208
+ export type RenderedStaticMap = { ok: true; bytes: Uint8Array } | { ok: false; reason: string };
209
+
210
+ /** How long the door waits on Google before it gives up and the frame draws its graticule. */
211
+ export const STATIC_MAP_TIMEOUT_MS = 8000;
212
+
213
+ /**
214
+ * THE door to Google Static Maps: a refused key and the ceiling first, then the one request, with a
215
+ * timeout. A refusal touches no network, and a 401/403 is remembered so the next viewport does not ask.
216
+ */
217
+ export async function renderStaticMap(input: {
218
+ request: StaticMapRequest;
219
+ maps: StaticMapSeam;
220
+ budget: Pick<AsyncMapsBudget<'staticmap'>, 'consume'>;
221
+ refusals: KeyRefusalMemory;
222
+ timeoutMs?: number;
223
+ }): Promise<RenderedStaticMap> {
224
+ const held = await input.refusals.held('staticmap');
225
+ if (held) return { ok: false, reason: held };
226
+ const verdict = await input.budget.consume('staticmap');
227
+ if (!verdict.allowed) return { ok: false, reason: verdict.reason };
228
+ const controller = new AbortController();
229
+ const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? STATIC_MAP_TIMEOUT_MS);
230
+ try {
231
+ const response = await input.maps.fetch(staticMapUrl(input.request, input.maps.apiKey), { signal: controller.signal });
232
+ const refused = await input.refusals.record('staticmap', response);
233
+ if (refused) return { ok: false, reason: refused };
234
+ if (!response.ok) return { ok: false, reason: `Google staticmap answered ${response.status}` };
235
+ return { ok: true, bytes: new Uint8Array(await response.arrayBuffer()) };
236
+ } catch (error) {
237
+ return { ok: false, reason: `Google staticmap did not answer (${error instanceof Error ? error.message : 'unknown'})` };
238
+ } finally {
239
+ clearTimeout(timer);
240
+ }
241
+ }
@@ -0,0 +1,52 @@
1
+ /** `cursedbelt-server/request-scope` β€” the request scope a once-per-isolate route tier reads (forge tasks 5632, photos per-request floor). */
2
+ import { describe, expect, it } from "bun:test";
3
+ import { cacheByBindings, createRequestScope, isolateKey } from "./requestScope";
4
+
5
+ describe("πŸ”΄ a request scope never hands one request another's value", () => {
6
+ interface Scope {
7
+ name: string;
8
+ store: { whose(): string; label: string };
9
+ }
10
+ const scope = createRequestScope<Scope>("test");
11
+ const of = (name: string): Scope => ({ name, store: { label: name, whose: () => name } });
12
+
13
+ it("two requests interleaving across awaits each read their own", async () => {
14
+ const store = scope.late("store");
15
+ let releaseA: () => void = () => {};
16
+ const a = scope.run(of("a"), async () => {
17
+ await new Promise<void>((resolve) => {
18
+ releaseA = resolve;
19
+ });
20
+ return [store.whose(), store.label];
21
+ });
22
+ const b = scope.run(of("b"), async () => [store.whose(), store.label]);
23
+ expect(await b).toEqual(["b", "b"]);
24
+ releaseA();
25
+ expect(await a).toEqual(["a", "a"]);
26
+ });
27
+
28
+ it("a method taken off the stand-in in one request runs on the request that CALLS it", () => {
29
+ const store = scope.late("store");
30
+ const whose = scope.run(of("builder"), () => store.whose);
31
+ expect(scope.run(of("caller"), () => whose())).toBe("caller");
32
+ });
33
+
34
+ it("is refused outside any request β€” a stand-in used at isolate scope is a bug, never a silent undefined", () => {
35
+ const store = scope.late("store");
36
+ expect(() => store.whose()).toThrow(/outside a request/);
37
+ });
38
+ });
39
+
40
+ describe("isolateKey / cacheByBindings β€” build once per env", () => {
41
+ it("the same env builds once; a changed string or a swapped binding builds afresh", () => {
42
+ const d1 = { prepare() {} };
43
+ let builds = 0;
44
+ const graph = cacheByBindings((env: { DB: object; SECRET: string }) => ({ n: ++builds, env }));
45
+ const env = { DB: d1, SECRET: "a" };
46
+ expect(graph(env).n).toBe(1);
47
+ expect(graph({ SECRET: "a", DB: d1 }).n).toBe(1);
48
+ expect(graph({ DB: d1, SECRET: "b" }).n).toBe(2);
49
+ expect(graph({ DB: { prepare() {} }, SECRET: "b" }).n).toBe(3);
50
+ expect(isolateKey({ DB: d1 })).toBe(isolateKey({ DB: d1 }));
51
+ });
52
+ });
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `cursedbelt-server/request-scope` β€” one request's things, for an app built ONCE per isolate.
3
+ *
4
+ * Born in auth (forge task 5632), promoted when photos took the same shape: a Worker that rebuilt
5
+ * its whole Hono graph per request paid a flat 5–40 CPU-ms floor on every call. Worker-safe: it
6
+ * needs `nodejs_compat` for `node:async_hooks`, nothing else.
7
+ *
8
+ * The assembly closes over its database, its session store, its throttle… β€” objects that belong to
9
+ * ONE request on a Worker (`perInvocation`'s query count, a D1 snapshot, a binding's I/O, which
10
+ * workerd refuses to touch from another request). Building the whole route tier per request cost
11
+ * 16–40 CPU-ms on auth-stage; building it once and handing it these values LATE costs nothing.
12
+ *
13
+ * `late(key)` is a stand-in that reads `key` from the CURRENT request's scope at every use, so the
14
+ * assembly can hold it from the first request on. The scope rides `AsyncLocalStorage`, never a
15
+ * module variable: an isolate serves requests concurrently, and a variable set by request B while
16
+ * request A awaits D1 would hand A B's sessions. Work handed to `waitUntil` keeps its own scope.
17
+ *
18
+ * πŸ”΄ A stand-in is for a LEAF service. One with a `mount` (a notification service) registers routes
19
+ * over the internals of whichever request built it β€” build that once over a late database instead.
20
+ */
21
+ import { AsyncLocalStorage } from "node:async_hooks";
22
+
23
+ export interface RequestScope<S extends object> {
24
+ /** Run `work` with `scope` as the current request's β€” everything it awaits, and defers, sees it. */
25
+ run<T>(scope: S, work: () => T): T;
26
+ /** The current request's scope; THROWS outside one (a stand-in used at isolate scope is a bug). */
27
+ current(): S;
28
+ /** A stand-in for `scope[key]` that reads the current request's value at every property access. */
29
+ late<K extends keyof S>(key: K): NonNullable<S[K]>;
30
+ /** The same, for a value derived from the scope (`(s) => s.env.AE`). */
31
+ lateOf<T extends object>(read: (scope: S) => T | null | undefined, what: string): T;
32
+ }
33
+
34
+ export function createRequestScope<S extends object>(name: string): RequestScope<S> {
35
+ const storage = new AsyncLocalStorage<S>();
36
+ const current = (): S => {
37
+ const scope = storage.getStore();
38
+ if (!scope) throw new Error(`${name}: a request-scoped value was read outside a request`);
39
+ return scope;
40
+ };
41
+ const lateOf = <T extends object>(read: (scope: S) => T | null | undefined, what: string): T => {
42
+ const target = (): object => {
43
+ const value = read(current());
44
+ if (value === undefined || value === null) throw new Error(`${name}: this request has no ${what}`);
45
+ return value;
46
+ };
47
+ return new Proxy(
48
+ {},
49
+ {
50
+ get(_shell, prop) {
51
+ const member = Reflect.get(target(), prop);
52
+ if (typeof member !== "function") return member;
53
+ // Resolved again at CALL time: a method taken off the stand-in while the assembly is
54
+ // built (request 1) must still run on whichever request calls it.
55
+ return (...args: unknown[]) => {
56
+ const value = target();
57
+ return Reflect.apply(Reflect.get(value, prop, value) as (...a: unknown[]) => unknown, value, args);
58
+ };
59
+ },
60
+ has: (_shell, prop) => Reflect.has(target(), prop),
61
+ ownKeys: () => Reflect.ownKeys(target()),
62
+ getOwnPropertyDescriptor(_shell, prop) {
63
+ const descriptor = Reflect.getOwnPropertyDescriptor(target(), prop);
64
+ // A proxy may not report a property non-configurable that its (empty) shell lacks.
65
+ return descriptor ? { ...descriptor, configurable: true } : undefined;
66
+ },
67
+ set: (_shell, prop, value) => Reflect.set(target(), prop, value),
68
+ },
69
+ ) as T;
70
+ };
71
+ const late = <K extends keyof S>(key: K): NonNullable<S[K]> =>
72
+ lateOf((scope) => scope[key] as (NonNullable<S[K]> & object) | undefined, String(key)) as NonNullable<S[K]>;
73
+ return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
74
+ }
75
+
76
+ /** A stable id per binding object, so a key changes when a binding is swapped, not only when a string is. */
77
+ const bindingIds = new WeakMap<object, number>();
78
+ let lastBindingId = 0;
79
+ function bindingId(value: object): number {
80
+ let id = bindingIds.get(value);
81
+ if (id === undefined) {
82
+ lastBindingId += 1;
83
+ id = lastBindingId;
84
+ bindingIds.set(value, id);
85
+ }
86
+ return id;
87
+ }
88
+
89
+ /**
90
+ * What an isolate-built graph is keyed by: every binding by name β€” a string by value, an object (a D1, a
91
+ * service binding) by identity. A changed secret or a swapped binding builds afresh; the same env never does.
92
+ * photos and collections each held a copy of this until forge task 5830.
93
+ */
94
+ export function isolateKey(env: object): string {
95
+ const entries = Object.entries(env).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
96
+ return JSON.stringify(entries.map(([name, value]) => [name, value !== null && (typeof value === "object" || typeof value === "function") ? bindingId(value) : value]));
97
+ }
98
+
99
+ /** `build(env)` once per {@link isolateKey}: the same env answers the same value, a changed one builds afresh. */
100
+ export function cacheByBindings<E extends object, T>(build: (env: E) => T): (env: E) => T {
101
+ let built: { key: string; value: T } | null = null;
102
+ return (env) => {
103
+ const key = isolateKey(env);
104
+ if (built?.key === key) return built.value;
105
+ const value = build(env);
106
+ built = { key, value };
107
+ return value;
108
+ };
109
+ }