cursedbelt-server 4.78.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.
- package/dist/server/maps-budget/mapsBudget.d.ts +37 -0
- package/dist/server/maps-budget/mapsBudget.js +52 -0
- package/dist/server/maps-static/staticMap.d.ts +30 -3
- package/dist/server/maps-static/staticMap.js +35 -3
- package/dist/server/requestScope.d.ts +8 -0
- package/dist/server/requestScope.js +33 -0
- package/package.json +2 -2
- package/src/server/maps-budget/mapsBudget.ts +73 -0
- package/src/server/maps-static/renderStaticMap.spec.ts +79 -0
- package/src/server/maps-static/staticMap.ts +47 -3
- package/src/server/requestScope.spec.ts +15 -1
- package/src/server/requestScope.ts +35 -0
|
@@ -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
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
+
}
|
|
@@ -9,3 +9,11 @@ export interface RequestScope<S extends object> {
|
|
|
9
9
|
lateOf<T extends object>(read: (scope: S) => T | null | undefined, what: string): T;
|
|
10
10
|
}
|
|
11
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;
|
|
@@ -59,3 +59,36 @@ export function createRequestScope(name) {
|
|
|
59
59
|
const late = (key) => lateOf((scope) => scope[key], String(key));
|
|
60
60
|
return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
|
|
61
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.
|
|
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.",
|
|
@@ -459,7 +459,7 @@
|
|
|
459
459
|
"@node-rs/argon2": "^2.0.2",
|
|
460
460
|
"@types/bun": "^1.3.14",
|
|
461
461
|
"@types/node": "^24",
|
|
462
|
-
"cursedbelt": "^6.
|
|
462
|
+
"cursedbelt": "^6.30.1",
|
|
463
463
|
"hono": "4.12.28",
|
|
464
464
|
"kysely": "^0.28.17",
|
|
465
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
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** `cursedbelt-server/request-scope` — the request scope a once-per-isolate route tier reads (forge tasks 5632, photos per-request floor). */
|
|
2
2
|
import { describe, expect, it } from "bun:test";
|
|
3
|
-
import { createRequestScope } from "./requestScope";
|
|
3
|
+
import { cacheByBindings, createRequestScope, isolateKey } from "./requestScope";
|
|
4
4
|
|
|
5
5
|
describe("🔴 a request scope never hands one request another's value", () => {
|
|
6
6
|
interface Scope {
|
|
@@ -36,3 +36,17 @@ describe("🔴 a request scope never hands one request another's value", () => {
|
|
|
36
36
|
expect(() => store.whose()).toThrow(/outside a request/);
|
|
37
37
|
});
|
|
38
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
|
+
});
|
|
@@ -72,3 +72,38 @@ export function createRequestScope<S extends object>(name: string): RequestScope
|
|
|
72
72
|
lateOf((scope) => scope[key] as (NonNullable<S[K]> & object) | undefined, String(key)) as NonNullable<S[K]>;
|
|
73
73
|
return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
|
|
74
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
|
+
}
|