cursedbelt-server 4.77.0 → 4.78.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.
@@ -0,0 +1,11 @@
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>;
@@ -0,0 +1,61 @@
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.77.0",
3
+ "version": "4.78.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.28.0",
457
463
  "hono": "4.12.28",
458
464
  "kysely": "^0.28.17",
459
465
  "kysely-bun-sqlite": "^0.4.0",
@@ -0,0 +1,38 @@
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 { createRequestScope } 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
+ });
@@ -0,0 +1,74 @@
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
+ }