cloud / core / lib / src / sdk / itx-scope.tsmain at aacbc74
// sdk/itx-scope.ts — `itxScope`, what every `getItx` is: the SDK's hosts' (index.ts) and every
// loaded entrypoint's (loaded-worker.ts). THE one way code reaches its context is
// `using itx = this.getItx()` in the smallest block that holds its calls: the `using` releases a
// Workers-RPC scope completely when the block ends — the scope and every call made through it, not
// only the last. A value code keeps from its context past that — an undisposed call, a handle, a
// stub — keeps the context, and any facet holding it, running and billed: pinned by
// test/vitest/os/context-residency.e2e.test.ts ("… does not outlive …"). No workerd import, so the
// unit tests run it in node (itx-scope.test.ts). Lint refuses the raw `env.ITX.get()`, and a
// `getItx()` no `using` binds (iterate/no-raw-itx-get).
import { causeMarkOf, currentCause } from "../cause.ts";
import { ITERATE_CAUSE_HEADER, loopLimitOf, releaseRpcSessions } from "../lib.ts";
/** What hands a scope over: `env.ITX`, the loopback of the code's context (core/itx
* `ItxEntrypoint`). `get` answers the scope over Workers RPC; `fetch` sends a Request through the
* context's own table, and its answer may hold a WebSocket. */
type ItxEntrypointOf<Scope> = {
get(): Scope;
fetch?(request: Request): Promise<Response>;
};
/** ONE get on `entrypoint`, under the cause running when the scope is made, for a `using`
* declaration, made on the scope's first use: a block that never touches its context (most
* `processEvent`s) opens no session. Its `[Symbol.dispose]` releases the scope and every call made
* through it or through a handle it awaited, the last first. A release that throws is reported and the rest still run (lib.ts
* `releaseRpcSessions`), so an answer already awaited stands. Data stays usable after the block;
* a stub or handle is released with the rest, so a block hands out data. Await every call before
* the block ends: `return await itx.whoami()`, never `return itx.whoami()`.
*
* using itx = this.getItx();
* const { mindSlug } = await itx.whoami();
*/
export function itxScope<Scope>(entrypoint: ItxEntrypointOf<Scope>): Scope & Disposable {
const steps: unknown[] = [];
const cause = currentCause();
let opened: { itx: Scope; scope: Scope } | undefined;
const open = () => {
if (!opened) {
// `get` also takes why the code runs (../cause.ts), a word on no declared signature
const itx = (entrypoint as { get(cause: unknown): Scope }).get(cause);
opened = { itx, scope: recordPipelinedSteps(itx, steps) };
}
return opened.scope;
};
// A function, as the stub it stands for is: callable, and handed across RPC as a stub. Its
// members are the opened stub's; `[Symbol.dispose]` releases what was opened. The casts: a
// Workers-RPC stub is a callable object, whatever `Scope` declares.
const root = new Proxy(() => {}, {
get: (_, key) =>
key === Symbol.dispose
? () => opened && releaseRpcSessions([opened.itx, ...steps])
: key === "fetch" && entrypoint.fetch
? scopeFetch(entrypoint.fetch.bind(entrypoint), cause, () =>
Reflect.get(open() as object, key),
)
: Reflect.get(open() as object, key),
apply: (_, thisArg, args) => Reflect.apply(open() as () => unknown, thisArg, args),
});
scopeRoots.set(root, () => {
open();
return opened!.itx;
});
return root as Scope & Disposable;
}
/** THE SCOPE'S `itx.fetch`, but a WebSocket upgrade goes by `entrypoint.fetch`. A Response that
* holds a WebSocket cannot be returned over Workers RPC ("Could not serialize object of type
* "WebSocket"", workerd 1.20261116.1), and the scope is a Workers RPC stub: its `fetch` would open
* the upstream and then fail. A Worker's `fetch` carries the socket. The context answers it as
* the scope's `fetch`, through the code's table, under the cause of the scope; a refusal is an
* answer there, not a throw, but past the loop limit it throws, as the scope's `fetch` does.
* Anything else, `fetch(request, { signFor })` too, is the scope's own call. */
function scopeFetch(
entrypointFetch: (request: Request) => Promise<Response>,
cause: unknown,
scopeFetchOf: () => (...args: unknown[]) => unknown,
) {
const upgrade = async (request: Request) => {
const headers = new Headers(request.headers);
const mark = causeMarkOf(cause);
if (mark) headers.set(ITERATE_CAUSE_HEADER, mark);
const answer = await entrypointFetch(new Request(request, { headers }));
const refused = await loopLimitOf(answer);
if (refused) throw refused;
return answer;
};
return (...args: unknown[]) => {
const [request] = args;
return args.length === 1 &&
request instanceof Request &&
request.headers.get("upgrade")?.toLowerCase() === "websocket"
? upgrade(request)
: scopeFetchOf()(...args);
};
}
/** Each scope `itxScope` made, to the stub it opens: a recorded call handed the scope crosses the
* wire with that stub, as it would with any recorded value. */
const scopeRoots = new WeakMap<object, () => unknown>();
/** `stub` as the caller sees it, except that every CALL made through it — at any depth, on the stub,
* on a call's result, or on the handle a call's result resolves to once awaited — is pushed onto
* `steps`, so the caller can dispose each one: a Workers-RPC call's result is a stub-bearing promise
* that keeps its session open until disposed, awaited or not. Awaiting hands back a handle (a stub
* is callable, in workerd and capnweb alike) recorded and pushed too, and plain data untouched, so
* data still copies across RPC. `catch`/`finally` and symbol members (`Symbol.dispose`) are the
* value's own, bound to it, so disposing behaves exactly as on the bare stub; an argument that is
* itself a recorded value, or an `itxScope`, crosses the wire as the stub it wraps. */
export function recordPipelinedSteps<T>(stub: T, steps: unknown[]): T {
const wrapped = new WeakMap<object, object>();
const record = (value: unknown, receiver: unknown): unknown => {
// oxlint-disable-next-line iterate/simple-truthiness-check -- a Proxy target must be an object or a function: a call may answer any value, and only those two can be wrapped
if (!value || (typeof value !== "object" && typeof value !== "function")) return value;
const proxy = new Proxy(value, {
get(target, key) {
const member: unknown = Reflect.get(target, key);
if (key === "then" && typeof member === "function")
// `const repo = await itx.repos.get(p); await repo.whoami()`: disposing the step releases
// `repo` (workerd disposes a promise's result with it), never `whoami`'s call, and an
// awaited property (`await itx.repos`) is no step at all.
return (onFulfilled?: unknown, onRejected?: unknown) =>
Reflect.apply(member, target, [
typeof onFulfilled === "function"
? (answer: unknown) => {
if (typeof answer !== "function") return onFulfilled(answer);
steps.push(answer);
return onFulfilled(record(answer, undefined));
}
: onFulfilled,
onRejected,
]);
if (typeof key === "symbol" || key === "then" || key === "catch" || key === "finally")
return typeof member === "function" ? member.bind(target) : member;
return record(member, target);
},
apply(target, _proxyReceiver, args: unknown[]) {
// Only a callable target reaches this trap; the call runs on the unwrapped receiver, as
// `stub.method(…)` would have.
const result: unknown = Reflect.apply(
target as (...args: unknown[]) => unknown,
receiver,
// `Object(arg)` is a fresh wrapper for a primitive, so only a recorded value is found.
args.map((arg) => wrapped.get(Object(arg)) ?? scopeRoots.get(Object(arg))?.() ?? arg),
);
steps.push(result);
return record(result, undefined);
},
});
wrapped.set(proxy, value);
return proxy;
};
// The proxy answers every member the stub does (it forwards each one), so it is the stub's type.
return record(stub, undefined) as T;
}