iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / itx / src / iterate-context.tsmain at 949894f

// The client is just capnweb: there is no client SDK, so anything that needs client-side smarts
// belongs here, behind an RpcTarget method. capnweb terminates here; the DO is reached over Workers
// RPC only. A client's rpc stub must live in this stateless worker, never in the DO.

import { RpcPromise as CapnwebRpcPromise, RpcStub as CapnwebRpcStub, RpcTarget } from "capnweb";
import { z } from "zod";
import { codedError, ITERATE_CAUSE_HEADER, loopLimitOf, resolveContextPath } from "iterate/lib";
import * as cloudflareWorkers from "cloudflare:workers";
import {
  canonicalItxExpressionPrefix,
  itxExpressionStepName,
  normalizedItxExpression,
  type ItxExpression,
  type ItxExpressionInput,
  installPrototypeInvokeFallback,
} from "iterate/expression";
import type { EventCopyTarget, FetchRouteInput, IterateContextApi } from "iterate/api";
import type { StreamEvent, StreamEventInput } from "iterate/stream/processor";
import { newChain, parseCause, type Cause } from "./cause.ts";
import {
  itxAnswerDetachedFromSession,
  materializeItxHandleReference,
  registerPipelinedRpcBrand,
  registerRpcSessionBrand,
} from "./context/dispatch.ts";
import type { Caller } from "./caller.ts";
import type { IterateContextDurableObject, Env } from "./iterate-context-durable-object.ts";
import { contexts } from "./host.ts";
import {
  ITX_EXPRESSION_FETCH_HEADER,
  encodeFetchExpression,
  parseFetchExpression,
  itxExpressionEndingInFetch,
  stampCallerHeaders,
  terminalFetchOf,
  type LenderStamp,
} from "./context/rpc-stubs.ts";
import {
  lendRpcStubOverPager,
  type ClientRpcStub,
  type IterateContextDurableObjectStub,
} from "./context/rpc-stub-relay.ts";
import {
  entersOwnRoot,
  implicitRootsAt,
  normalizeRewriteRuleConfigured,
  type ItxExpressionResolver,
} from "./context/itx-expression-rewriting.ts";
import { FETCH_UPGRADE_CONTEXT_HEADER, type LentFetchHolder } from "./context/fetch-upgrade.ts";
import { AWAKE_CONTEXT_PATH } from "./context/awake.ts";
import {
  CATALOG_WATCH_HEADER,
  CatalogWatchRelay,
  catalogWatchRelayOf,
  isCatalogWatchTicket,
  refuseLoadedCode,
  type CatalogWatchHandle,
} from "./context/catalog-watch.ts";
import { lendRefusal } from "./context/lent-names.ts";
import { FetchRouteConfiguredPayload } from "./fetch-routes.ts";
import type { BuiltInScope } from "./context/built-ins.ts";
import { statelessResolverFor } from "./context/stateless-context.ts";
import { DurableObjectNameCodec, type DurableObjectAddress } from "./context/paths.ts";
import { SessionTeardown } from "./session.ts";
import { contextStub } from "./context-stub.ts";
import { expressionFetchErrorAnswer } from "./unavailable.ts";

export type IterateContextNamespace = DurableObjectNamespace<IterateContextDurableObject>;
type WaitUntil = (p: Promise<unknown>) => void;

class RewriteRuleHandleRpcTarget extends RpcTarget {
  readonly #undo: () => void;
  readonly #lendEnded: Promise<string> | null;
  constructor(undo: () => void, lendEnded: Promise<string> | null = null) {
    super();
    this.#undo = undo;
    this.#lendEnded = lendEnded;
  }
  lendEnded(): Promise<string> {
    if (!this.#lendEnded)
      throw codedError("INVALID_INPUT", "provide lent no stub here: a rule has no lend to end");
    return this.#lendEnded;
  }
  [Symbol.dispose](): void {
    this.#undo();
  }
}

// `name` is a getter: capnweb exposes prototype members only.
class SubscriptionHandleRpcTarget extends RpcTarget {
  readonly #name: string;
  readonly #undo: () => void;
  constructor(name: string, undo: () => void) {
    super();
    this.#name = name;
    this.#undo = undo;
  }
  get name(): string {
    return this.#name;
  }
  [Symbol.dispose](): void {
    this.#undo();
  }
}

// Declaration merging types the built-in roots; the prototype fallback below is the runtime.
export interface IterateContextRpcTarget extends Omit<BuiltInScope, "cd" | "facets" | "contexts"> {
  facets: IterateContextApi["facets"];
  // `watch` is this edge's own (`#watchContexts`): the table answers its ticket alone
  contexts: IterateContextApi["contexts"];
}

type StatelessReach = (
  address: DurableObjectAddress,
  caller: Caller,
  expression: ItxExpression,
) => ItxExpressionResolver | undefined;

export class IterateContextRpcTarget extends RpcTarget {
  readonly #contextNamespace: IterateContextNamespace;
  readonly #durableObjectAddress: DurableObjectAddress;
  readonly #sessionTeardown: SessionTeardown;
  readonly #waitUntil: WaitUntil;
  readonly #caller: Caller;
  readonly #statelessResolverOf: StatelessReach | undefined;
  // Loaded code that keeps an answer keeps nothing open.
  readonly #detachAnswers: boolean;
  // Loaded code's `cd`: every call goes through the context it came from, where its wall stands.
  readonly #reachedThrough:
    | ((steps: ItxExpression, args: unknown[]) => Promise<unknown>)
    | undefined;

  constructor(
    contextNamespace: IterateContextNamespace,
    durableObjectAddress: DurableObjectAddress,
    sessionTeardown: SessionTeardown,
    waitUntil: WaitUntil,
    caller: Caller,
    statelessResolverOf?: StatelessReach,
    detachAnswers = false,
    reachedThrough?: (steps: ItxExpression, args: unknown[]) => Promise<unknown>,
  ) {
    super();
    this.#detachAnswers = detachAnswers;
    this.#reachedThrough = reachedThrough;
    this.#contextNamespace = contextNamespace;
    this.#durableObjectAddress = durableObjectAddress;
    this.#sessionTeardown = sessionTeardown;
    this.#waitUntil = waitUntil;
    this.#caller = caller;
    this.#statelessResolverOf = statelessResolverOf;
  }

  // Per call: an exception can leave a stub broken (Cloudflare's error-handling guide).
  get #durableObject(): IterateContextDurableObjectStub {
    return this.#contextNamespace.getByName(this.#durableObjectAddress.name);
  }

  // A handle the DO names becomes a handle of this edge object, so no session onto the actor
  // outlives a call.
  async #invokeOnDurableObject(
    itxExpression: ItxExpression,
    args: unknown[] = [],
  ): Promise<unknown> {
    const result = await contextStub(
      this.#contextNamespace,
      this.#durableObjectAddress,
      "itx",
    ).invoke(itxExpression, args, this.#caller);
    return materializeItxHandleReference(
      this.#detachAnswers ? itxAnswerDetachedFromSession(result, itxExpression, args) : result,
      (expression) => this.invoke(expression),
    );
  }

  cd(path: string): IterateContextRpcTarget {
    const durableObjectAddress = DurableObjectNameCodec.address(
      resolveContextPath(this.#durableObjectAddress.path, path),
    );
    return new IterateContextRpcTarget(
      this.#contextNamespace,
      durableObjectAddress,
      this.#sessionTeardown,
      this.#waitUntil,
      this.#caller,
      this.#statelessResolverOf,
      this.#detachAnswers,
      // Loaded code's `cd` is an expression through this context's table, where its wall stands.
      // Its `subscribe` and `provide` stay this class's own methods: their rows take that road, and
      // only the lend goes to the context itself.
      this.#caller.app
        ? (steps, args) => this.invoke(["itx", ["cd", path], ...steps], ...args)
        : undefined,
    );
  }

  // A terminal `fetch(request)` rides the DO's fetch channel, which carries a socket-bearing
  // Response back to this invocation. Workers RPC from here on does not: `fetchUpgradeDial`.
  async invoke(call: ItxExpressionInput, ...args: unknown[]): Promise<unknown> {
    // the context it was reached through has read its answer already
    if (this.#reachedThrough)
      return this.#reachedThrough(normalizedItxExpression(call).slice(1), args);
    const expression = normalizedItxExpression(call);
    const watch = contextsWatchOf(expression, args);
    if (watch) return this.#watchContexts(watch);
    const answer = await this.#dispatch(expression, args);
    if (!(answer instanceof Response)) return answer;
    const refused = await loopLimitOf(answer);
    if (refused) throw refused;
    if (!answer.body) return answer;
    // Workaround: a DO's body pumped natively into a Workers-RPC answer can arrive with its chunks
    // out of order; through a JS stream, workerd reads it in order.
    return new Response(answer.body.pipeThrough(new TransformStream()), answer);
  }

  async #dispatch(call: ItxExpressionInput, args: unknown[]): Promise<unknown> {
    const itxExpression = normalizedItxExpression(call);
    const resolver = this.#statelessResolverOf?.(
      this.#durableObjectAddress,
      this.#caller,
      itxExpression,
    );
    const terminalFetch = terminalFetchOf(itxExpression, args);
    if (resolver && terminalFetch)
      return statelessExpressionFetch(
        resolver,
        () => terminalFetch.steps,
        terminalFetch.request,
        encodeFetchExpression(terminalFetch.steps),
      );
    if (resolver) {
      const result = await resolver.invoke(itxExpression, ...args);
      return materializeItxHandleReference(
        itxAnswerDetachedFromSession(result, itxExpression, args),
        (expression) => this.invoke(expression),
      );
    }
    if (terminalFetch)
      return this.#durableObject.fetch(
        this.#contextFetchRequest(terminalFetch.steps, terminalFetch.request),
      );
    return this.#invokeOnDurableObject(itxExpression, args);
  }

  /** `itx.contexts.watch(query, onFrame, options?)`: THE CATALOG KEEPS ANSWERING A QUERY, and each
   *  frame of its answer goes to the caller's function over the caller's own session. The
   *  function is a live stub, which stays at this edge (the head of this file). So the call has
   *  two halves:
   *    1. the query goes through this context's table, as `contexts.list` goes, to the built-in
   *       `contexts.watch`, which answers a ticket. Who may list may watch, and a table that
   *       sends `contexts` elsewhere sends the watch there too;
   *    2. with the ticket, the session's ONE socket into the catalog takes the query
   *       (./context/catalog-watch.ts), and its frames are handed to the function.
   *  Loaded code has no session whose end could hold the socket, and reads `contexts.list`. */
  async #watchContexts(watch: {
    root: ItxExpression;
    query: unknown;
    onFrame: unknown;
    options: unknown;
  }): Promise<CatalogWatchHandle> {
    refuseLoadedCode(this.#caller, "watch");
    if (typeof watch.onFrame !== "function")
      throw codedError(
        "INVALID_INPUT",
        "contexts.watch(query, onFrame, options?): onFrame is the function that each frame goes to",
      );
    const ticket = await this.#dispatch(
      [
        ...watch.root,
        // an absent option stays absent: the built-in refuses any second argument but `{ cursor? }`
        watch.options === undefined
          ? ["watch", watch.query]
          : ["watch", watch.query, watch.options],
      ],
      [],
    );
    if (!isCatalogWatchTicket(ticket))
      throw codedError(
        "NOT_A_METHOD",
        "contexts.watch: what answers `contexts` at this context is not the mind's catalog",
      );
    return catalogWatchRelayOf(
      this.#sessionTeardown,
      () =>
        new CatalogWatchRelay({
          dial: () =>
            this.#contextNamespace
              .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH))
              .fetch("https://catalog-watch/", {
                headers: { Upgrade: "websocket", [CATALOG_WATCH_HEADER]: "1" },
              }),
          waitUntil: this.#waitUntil,
        }),
      (relay) => this.#sessionTeardown.add("catalog-watch", relay),
    ).watch(ticket, watch.onFrame as Parameters<CatalogWatchRelay["watch"]>[1]);
  }

  /** What this context's Durable Object answers as `<steps>.fetch(request)` by this caller. */
  #contextFetchRequest(steps: ItxExpression, request: Request): Request {
    const headers = new Headers(request.headers);
    stampCallerHeaders(headers, this.#caller);
    headers.set(ITX_EXPRESSION_FETCH_HEADER, encodeFetchExpression(steps));
    return new Request(request, { headers });
  }

  /** THE DIAL OF `itx.fetch(request)` THAT OPENS A WEBSOCKET, for the Worker that holds this
   *  context over Workers RPC: the boundary, which ends a session of the API
   *  (core/boundary-worker/src/session-mind.ts `SessionMind.fetch`). A Response that holds a
   *  WebSocket cannot be returned over Workers RPC ("Could not serialize object of type
   *  "WebSocket"", workerd 1.20261116.1), so `fetch` would open the upstream and then fail. The
   *  holder sends this Request through the mind Worker's own `fetch` instead, which carries the
   *  socket, to this context's Durable Object (../serve-host.ts `fetchUpgradeLegResponse`). It is
   *  the Request that `fetch` sends there, stamped with this caller, so the context answers it as
   *  it answers `fetch`: its rows, the gate and the egress all hold. Not for loaded code, whose
   *  calls go through its own table (`ItxEntrypoint.fetch` carries its socket). */
  fetchUpgradeDial(request: Request): Request {
    if (this.#reachedThrough || this.#statelessResolverOf)
      throw codedError(
        "FORBIDDEN",
        "fetchUpgradeDial: loaded code opens a socket through env.ITX.fetch(request)",
      );
    if (!(request instanceof Request))
      throw codedError("INVALID_INPUT", "fetchUpgradeDial(request): one Request");
    const dial = this.#contextFetchRequest(["itx"], request);
    const headers = new Headers(dial.headers);
    headers.set(FETCH_UPGRADE_CONTEXT_HEADER, this.#durableObjectAddress.name);
    return new Request(dial, { headers });
  }

  async provide(
    match: ItxExpressionInput,
    target: ClientRpcStub | ItxExpressionInput | null,
    options: {
      description?: string;
      fetchRoute?: Omit<FetchRouteInput, "target"> & { fetchRouteName: string };
      /** This lend takes the name only when no other lender holds it (rpc-stubs.ts
       *  `appendAtAttach`): a live stub's, from a caller with a grant. */
      onlyFromItself?: true;
    } = {},
    /** Given by the Worker that ends the lender's session, and by no client: where this lend's
     *  `fetch` is made (./context/fetch-upgrade.ts `LentFetchHolder`). A caller that gives one of
     *  its own gets the fetches of its own lend as calls, and reaches nothing by it: a leg into a
     *  context is dialled by the boundary alone. */
    lentFetch?: LentFetchHolder,
  ): Promise<RewriteRuleHandleRpcTarget> {
    // A row from loaded code must go through its context's table, where a jail's wall stands.
    if (this.#caller.app && (!target || typeof target === "string" || Array.isArray(target)))
      throw codedError(
        "FORBIDDEN",
        "loaded code writes a row with itx.append({ type: 'events.iterate.com/itx/rewrite-rule-configured', payload: { match, target, description } }); provide lends a live stub only",
      );
    const description = options.description ? { description: options.description } : {};
    const matchString = canonicalItxExpressionPrefix(match);
    const sessionTeardownKey = this.#sessionTeardownKey(matchString);
    const isRow = !target || typeof target === "string" || Array.isArray(target);
    if (
      options.fetchRoute &&
      (isRow || this.#caller.app || this.#durableObjectAddress.path !== "/")
    )
      throw codedError(
        "INVALID_INPUT",
        "provide's fetchRoute rides a lent stub on the mind's root \"/\"; set any other route with itx.fetchRoutes.set",
      );
    // The attach checks the lender by the grant, and loaded code's rule is appended before its lend,
    // where no attach checks it: neither such lend can say who it is.
    if (options.onlyFromItself && (isRow || this.#caller.app || !this.#caller.grant))
      throw codedError(
        "INVALID_INPUT",
        "provide's onlyFromItself is for a live stub lent by a caller with a grant: this lend cannot say who lends it",
      );
    if (isRow) {
      // Appended before this session's lend is recalled, so the DO's un-set on the pager close
      // finds a row that no longer names the stub and cannot take the fresh one with it.
      const { target: expectedTarget } = normalizeRewriteRuleConfigured({
        match: matchString,
        target,
        ...description,
      });
      const event: StreamEventInput = {
        type: "events.iterate.com/itx/rewrite-rule-configured",
        payload: { match: matchString, target: expectedTarget, ...description },
      };
      await this.#append(event);
      this.#sessionTeardown.dispose(sessionTeardownKey);
      return new RewriteRuleHandleRpcTarget(() =>
        this.#removeRuleInBackground(matchString, expectedTarget),
      );
    }
    // Whoever lends, at whichever context: a name that is the platform's at the mind's root.
    const refused = lendRefusal(matchString, implicitRootsAt("/"));
    if (refused) throw codedError("FORBIDDEN", `itx.provide: ${refused}`);
    // Built before the lend, so a match the codec refuses throws with nothing lent.
    const ruleEvent: StreamEventInput = {
      type: "events.iterate.com/itx/rewrite-rule-configured",
      payload: {
        match: matchString,
        target: ["itx", "builtins", "rpcStubs", ["get", matchString]],
        ...description,
        // Who lends: a lend with `onlyFromItself` takes no name that another lender holds
        // (rpc-stubs.ts `appendAtAttach`).
        ...(this.#caller.grant && { lentBy: this.#caller.grant }),
      },
    };
    const fetchRouteEvents = options.fetchRoute
      ? [fetchRouteEventTo(normalizedItxExpression(matchString), options.fetchRoute)]
      : [];
    // Loaded code's row goes through its own table first, so a jail's mask refuses it before a lend.
    if (this.#caller.app) await this.#appendBeforeLend(ruleEvent);
    const pager = await lendRpcStubOverPager(
      () => this.#durableObject,
      target,
      matchString,
      this.#caller.app ? [] : [ruleEvent, ...fetchRouteEvents],
      this.#waitUntil,
      this.#lenderStamp,
      options.onlyFromItself && this.#caller.grant,
      lentFetch && { holder: lentFetch, context: this.#durableObjectAddress.name },
    );
    // The DO, not this session, un-sets the rule when the key's last pager closes.
    const lease = this.#sessionTeardown.add(sessionTeardownKey, pager);
    return new RewriteRuleHandleRpcTarget(() => lease.dispose(), pager.lendEnded);
  }

  async subscribe(input: {
    name?: string;
    target:
      | ItxExpressionInput
      | ClientRpcStub
      | ((events: unknown[], range: unknown) => void)
      | EventCopyTarget
      | null;
    consumes?: string[];
    afterOffset?: number;
    ordered?: false;
    filter?: string;
  }): Promise<SubscriptionHandleRpcTarget> {
    // An expression target is a row the delivery loop runs as the kernel, so loaded code may only
    // lend a live callback. Reading `path` on a live stub gives another stub, never a string.
    const isLiveCallback =
      !!input.target &&
      typeof input.target !== "string" &&
      !Array.isArray(input.target) &&
      typeof (input.target as { path?: unknown }).path !== "string";
    if (this.#caller.app && !isLiveCallback)
      throw codedError(
        "FORBIDDEN",
        "loaded code writes a subscription row with itx.append({ type: 'events.iterate.com/itx/subscription-configured', payload: { name, target, consumes } }); subscribe lends a live callback only",
      );
    // oxlint-disable-next-line iterate/simple-truthiness-check -- an empty name must reach the reduce and be refused, not get a minted one
    const name = input.name ?? `sub-${crypto.randomUUID().slice(0, 8)}`;
    const rpcStubKey = `subscription:${name}`;
    const sessionTeardownKey = this.#sessionTeardownKey(rpcStubKey);
    const delivery = {
      consumes: input.consumes,
      afterOffset: input.afterOffset,
      ordered: input.ordered,
      filter: input.filter,
    };
    if (isLiveCallback) {
      const row: StreamEventInput = {
        type: "events.iterate.com/itx/subscription-configured",
        payload: {
          name,
          target: ["itx", "builtins", "rpcStubs", ["get", rpcStubKey]],
          ...delivery,
        },
      };
      if (this.#caller.app) await this.#appendBeforeLend(row);
      const pager = await lendRpcStubOverPager(
        () => this.#durableObject,
        input.target as ClientRpcStub,
        rpcStubKey,
        this.#caller.app ? [] : [row],
        this.#waitUntil,
        this.#lenderStamp,
      );
      const lease = this.#sessionTeardown.add(sessionTeardownKey, pager);
      return new SubscriptionHandleRpcTarget(name, () => lease.dispose());
    }
    // Appended before the recall, as in `provide`.
    const target = input.target as ItxExpressionInput | EventCopyTarget | null;
    const [committed] = (await this.#append({
      type: "events.iterate.com/itx/subscription-configured",
      payload: { name, target, ...delivery },
    })) as StreamEvent[];
    this.#sessionTeardown.dispose(sessionTeardownKey);
    return new SubscriptionHandleRpcTarget(name, () => {
      if (target) this.#removeSubscriptionInBackground(name, committed.offset);
    });
  }

  // What the context stamps on the rows a lend appends at its attach: who this caller is, never
  // what it may do. A key's token is no member's (core/boundary-worker/src/stamp.ts), and its
  // session's principal only names the service it speaks for (core/mind-worker/src/api.ts): its
  // lend names nobody, and the rule's `lentBy` says which key lends.
  get #lenderStamp(): LenderStamp {
    const { principal, grant, via, onBehalfOf } = this.#caller;
    return { principal: grant?.startsWith("key:") ? null : principal, grant, via, onBehalfOf };
  }

  // The platform's is spelled `itx.builtins.append`, so a context's own rows never redirect it.
  #append(event: StreamEventInput): Promise<unknown> {
    if (this.#reachedThrough) return this.#reachedThrough([["append", event]], []);
    return this.#invokeOnDurableObject(
      this.#caller.app ? ["itx", ["append", event]] : ["itx", "builtins", ["append", event]],
    );
  }

  // Loaded code's row goes through its own table first, so a jail's mask refuses it before a lend.
  // A rule may send a `cd` elsewhere: then the row is not here, and nor is the lend.
  async #appendBeforeLend(row: StreamEventInput): Promise<void> {
    const [committed] = (await this.#append(row)) as StreamEvent[];
    if (this.#reachedThrough && committed?.path !== this.#durableObjectAddress.path)
      throw codedError(
        "FORBIDDEN",
        `a rule sent this row to ${JSON.stringify(committed?.path)}, not ${JSON.stringify(this.#durableObjectAddress.path)}: no live stub is lent there`,
      );
  }

  // A compare-and-set delete of the row this handle wrote, never a mask: at a child, a "restore"
  // would be a grant.
  #removeRuleInBackground(matchString: string, expectedTarget: ItxExpression | null): void {
    this.#waitUntil(
      this.#append({
        type: "events.iterate.com/itx/rewrite-rule-configured",
        payload: { match: matchString, target: null, ifTarget: expectedTarget },
      }).catch(() => undefined),
    );
  }

  #removeSubscriptionInBackground(name: string, configuredAtOffset: number): void {
    this.#waitUntil(
      this.#append({
        type: "events.iterate.com/itx/subscription-configured",
        payload: { name, target: null, ifConfiguredAtOffset: configuredAtOffset },
      }).catch(() => undefined),
    );
  }

  // The teardown is shared across the session's contexts, and a stub key is unique per context.
  #sessionTeardownKey(rpcStubKey: string): string {
    return JSON.stringify([this.#durableObjectAddress.name, rpcStubKey]);
  }
}

installPrototypeInvokeFallback(IterateContextRpcTarget, ["itx"]);

/** The parts of `itx.contexts.watch(query, onFrame, options?)` (or `itx.builtins.contexts.watch`),
 *  when `expression` is that call, however its arguments came: in its last step, as the dotted
 *  call puts them, or beside the expression. `root` is what stands before `watch`. */
function contextsWatchOf(
  expression: ItxExpression,
  args: unknown[],
): { root: ItxExpression; query: unknown; onFrame: unknown; options: unknown } | undefined {
  const last = expression.at(-1);
  const root = expression.slice(0, -1);
  if (!last || itxExpressionStepName(last) !== "watch" || root.at(-1) !== "contexts")
    return undefined;
  if (root.length !== (root[1] === "builtins" ? 3 : 2)) return undefined;
  const [query, onFrame, options] = typeof last === "string" ? args : [...last.slice(1), ...args];
  return { root, query, onFrame, options };
}

/** THE MIND'S ROOT CONTEXT FOR ONE SESSION THAT ENDS IN ANOTHER WORKER: the boundary ends every
 *  session of the API and holds what this answers as a Workers RPC stub (the mind Worker's
 *  `Mind.api`). The invocation that makes it lives for as long as that stub does.
 *
 *  WHAT ENDS ITS LENDS, in the order that they act:
 *    1. the disposer below, when the holder lets go of its stub. workerd runs it while this
 *       invocation has I/O open, and a lend's pager is an open WebSocket;
 *    2. the end of this invocation, which workerd cancels when the holder's own invocation is gone
 *       (measured 2026-11-18 in local workerd: within about 70 ms). Its pagers close with it, and
 *       the context un-sets a lend's rows at its pager's close (./context/rpc-stubs.ts);
 *    3. the error of the next call on a lent stub whose invocation is gone, which the context
 *       reads as a stub that went offline.
 *  A Workers RPC stub has no `onRpcBroken`, so nothing here waits for one. The other way round,
 *  the holder hears that this invocation is gone by asking `sessionLives`. */
export function sessionContext(
  waitUntil: (promise: Promise<unknown>) => void,
  caller: Caller,
): IterateContextRpcTarget & Disposable & { sessionLives(): true } {
  return new SessionRootContext(
    contexts(),
    DurableObjectNameCodec.address("/"),
    new SessionTeardown(),
    waitUntil,
    caller,
  );
}

class SessionRootContext extends IterateContextRpcTarget {
  readonly #teardown: SessionTeardown;
  constructor(...args: ConstructorParameters<typeof IterateContextRpcTarget>) {
    super(...args);
    this.#teardown = args[2];
  }
  /** WHETHER THIS PART OF THE SESSION LIVES: true, at once. The Worker that ends the session asks
   *  every few seconds, and a question that fails tells it that this invocation is gone, or the
   *  way to it: it then ends the client's session (core/boundary-worker `#watchedMind`). An answer
   *  at once, and never a call that stays open: a call in flight would keep this invocation, and
   *  what the session lent, after its holder let go of it. No client reaches this name: the
   *  boundary's wrapper does not forward it. */
  sessionLives(): true {
    return true;
  }
  [Symbol.dispose](): void {
    this.#teardown.disposeAll();
  }
}

// The runtime exports these classes, but the workers-types .d.ts does not declare them.
const {
  RpcStub: NativeRpcStub,
  RpcPromise: NativeRpcPromise,
  RpcProperty: NativeRpcProperty,
} = cloudflareWorkers as unknown as Record<
  "RpcStub" | "RpcPromise" | "RpcProperty",
  abstract new () => unknown
>;
registerPipelinedRpcBrand(NativeRpcPromise);
registerPipelinedRpcBrand(NativeRpcProperty);
registerRpcSessionBrand(NativeRpcStub);
registerRpcSessionBrand(NativeRpcPromise);
registerRpcSessionBrand(NativeRpcProperty);
// A capnweb chain must stay unawaited between steps, or a one-shot batch session dies after its
// first message.
registerPipelinedRpcBrand(CapnwebRpcPromise as unknown as abstract new () => unknown);
registerPipelinedRpcBrand(CapnwebRpcStub as unknown as abstract new () => unknown);

export function nameActiveSpan({ path }: { path: string }): void {
  cloudflareWorkers.tracing.getActiveSpan()?.setAttributes({ "iterate.path": path });
}

// The context is a prop of the stub, never a binding loaded code could reach around.
export type ItxEntrypointScope = ReturnType<Service<ItxEntrypoint>["get"]>;
export class ItxEntrypoint extends cloudflareWorkers.WorkerEntrypoint<
  Env,
  { iterateContextName: string; platform?: true; config?: true }
> {
  get(cause?: unknown): IterateContextRpcTarget {
    // A loaded isolate's `ctx.exports` are its own module's, so `platform` cannot be forged from one.
    const address = DurableObjectNameCodec.parse(this.ctx.props.iterateContextName);
    nameActiveSpan(address);
    const namespace = contexts();
    return new IterateContextRpcTarget(
      namespace,
      address,
      new SessionTeardown(),
      (p) => this.ctx.waitUntil(p),
      this.#caller(address, parseCause(cause)),
      // A call into the context's own root skips the resolver, which would only send it on after
      // building every portable root. A terminal fetch keeps the resolver's fetch channel and retry.
      (at, caller, expression) =>
        entersOwnRoot(expression) && itxExpressionStepName(expression.at(-1)) !== "fetch"
          ? undefined
          : statelessResolverFor({
              namespace,
              address: at,
              caller,
              ctx: this.ctx,
            }),
      true,
    );
  }

  override async fetch(request: Request): Promise<Response> {
    const address = DurableObjectNameCodec.parse(this.ctx.props.iterateContextName);
    nameActiveSpan(address);
    const caller = this.#caller(address, parseCause(request.headers.get(ITERATE_CAUSE_HEADER)));
    // Loaded code's raw fetch goes through its table, the platform's to its own egress.
    const expression =
      request.headers.get(ITX_EXPRESSION_FETCH_HEADER) ??
      (caller.app ? "itx.fetch" : "itx.builtins.fetch");
    return statelessExpressionFetch(
      statelessResolverFor({
        namespace: contexts(),
        address,
        caller,
        ctx: this.ctx,
      }),
      () => parseFetchExpression(expression),
      request,
      expression,
    );
  }

  #caller(address: DurableObjectAddress, cause: Cause | undefined): Caller {
    return {
      principal: null,
      cause: cause || newChain("loaded code"),
      ...(this.ctx.props.platform
        ? { path: address.path }
        : { app: true as const, ...(this.ctx.props.config && { config: true as const }) }),
    };
  }
}

// Loaded code may have forged any caller stamp, so every one is stripped. Not in the resolver: the
// context's fetch channel hands the edge's principal on to the app.
export async function statelessExpressionFetch(
  resolver: Pick<ItxExpressionResolver, "invoke">,
  steps: () => ItxExpression,
  request: Request,
  label: string,
): Promise<Response> {
  const headers = new Headers(request.headers);
  stampCallerHeaders(headers, null);
  try {
    const result = await resolver.invoke(
      itxExpressionEndingInFetch(steps()),
      new Request(request, { headers }),
    );
    return result instanceof Response
      ? result
      : new Response(`expression fetch: ${JSON.stringify(result)}\n`);
  } catch (error) {
    return expressionFetchErrorAnswer(error, label);
  }
}

function fetchRouteEventTo(
  target: ItxExpression,
  route: Omit<FetchRouteInput, "target"> & { fetchRouteName: string },
): StreamEventInput {
  const parsed = FetchRouteConfiguredPayload.safeParse({
    fetchRouteName: route.fetchRouteName,
    requestMatcher: route.requestMatcher,
    target,
    authRequirement: route.authRequirement || null,
    priority: route.priority || 0,
  });
  if (!parsed.success)
    throw codedError(
      "INVALID_INPUT",
      `provide's fetchRoute ${JSON.stringify(route.fetchRouteName)}: ${z.prettifyError(parsed.error)}`,
    );
  return { type: "events.iterate.com/itx/fetch-route-configured", payload: parsed.data };
}