The best way to control Claude Code, Codex and more from any computer or phone

main
ts 61 lines 2.77 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Scope from "effect/Scope";
3
4 /**
5 * Per-execution memos, keyed on the execution's `Scope` object. Every bridge
6 * (Worker event, Durable Object call, Workflow run, Lambda invoke) provides a
7 * fresh `Scope` per execution, so an entry lives exactly as long as its
8 * execution and is garbage-collected with the scope object.
9 */
10 const caches = new WeakMap<Scope.Scope, Map<symbol, Effect.Effect<any, any, any>>>();
11
12 /**
13 * Allocate a per-execution memo cell for `build`. The returned accessor runs
14 * `build` at most once per execution scope (Worker fetch/queue/scheduled
15 * event, DO call, Workflow run, Lambda invoke) and builds it WITH that scope
16 * (`Layer.build` / `Scope`-requiring acquires see the execution scope), so
17 * release finalizers fire when the event settles — never held across events.
18 * This is the only legal pooling shape on workerd (sockets are
19 * IoContext-pinned) and the correct one on Lambda (the instance scope must
20 * not own disposables).
21 *
22 * The `Effect.sync` wrapper allocates the memo's symbol key once per *call
23 * site* (i.e. once per layer construction), so distinct clients built from
24 * distinct `makeExecutionMemo` calls never share a memo cell even inside the
25 * same execution.
26 *
27 * The memo key and the finalizer target are always the same scope object
28 * (`yield* Effect.scope`), so they cannot disagree: wrapping queries in a
29 * nested `Effect.scoped` narrows both the memo and the resource's lifetime
30 * to that block.
31 *
32 * The accessor's `Scope` requirement is erased from its type — every runtime
33 * bridge provides a fresh execution `Scope`, exactly like
34 * `Drizzle.Postgres` before this primitive was extracted. Evaluating the
35 * accessor outside an execution scope is a defect.
36 */
37 export const makeExecutionMemo = <A, E, R>(
38 build: Effect.Effect<A, E, R | Scope.Scope>,
39 ): Effect.Effect<Effect.Effect<A, E, Exclude<R, Scope.Scope>>> =>
40 Effect.sync(function () {
41 const symbol = Symbol();
42
43 return Effect.gen(function* () {
44 const scope = yield* Effect.scope;
45 let cache = caches.get(scope);
46 if (cache === undefined) {
47 caches.set(scope, (cache = new Map()));
48 }
49 let memo = cache.get(symbol);
50 if (memo === undefined) {
51 // `Effect.cached` only allocates the memo cell — the build runs
52 // on first evaluation — so this yield is synchronous and the
53 // fiber cannot be interleaved between the miss check and the
54 // set: a concurrent first access joins this memo (evaluating the
55 // same cached effect) instead of building a second resource.
56 memo = yield* Effect.cached(build.pipe(Scope.provide(scope)));
57 cache.set(symbol, memo);
58 }
59 return yield* memo;
60 }) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;
61 });