/** * Copyright (c) 2025 Elara AI Pty Ltd * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details. */ /** * Runtime implementation for the `Record.bind` platform function — reading an * `e3.record`'s current state and applying its typed mutations from East UI. * * Hybrid of the two existing patterns: the READ side (`read`/`status`) is * served from the shared dataset cache (a record IS a dataset at * `.records.`, preloaded + polled by the manifest like any dataset), so * there is no parallel fetcher; the WRITE side (`mutate.`) is a * Func-style launch/latest-wins channel. On a committed mutation the runtime * fires one `cache.refresh(ws)` so the record's bytes are re-fetched and * `read()` re-renders, and drops the history cache so the next `history()` * refetches. `commit.` is the same write awaited, on the same channel: * it resolves to the server's outcome, and a conflict fetches the record and * its history again before it settles. The refresh is the workspace poll's, * which fetches the content of the paths the manifest preloads and no other: * a record also bound with `Data.bindPaged` (#1199) is not among them, so it * is never fetched whole — its windows hear its new revision through the * poll's hash watch instead. * * A record read whole does not say which of its states the cache holds: its * bytes name no commit, and a record another write put back exactly as it was * reads as it did before a Save. The runtime knows when it read: it marks the * workspace's polls as each of a record's writes is answered, and says what * the cache holds of the record once a poll started since that answer has * found it the record's ({@link RecordRuntime.settledOf}) — which an editing * session reads a Save back at (east-ui-components' `settled-source.ts`). Of * a record read a page at a time, whose hash the cache follows, it says * whether a poll started since that answer has read the hash * ({@link RecordRuntime.followedOf}): from then the revision its pages are * pinned to is the record's as of a read made after the write. * * All handles bound to the same record in the same workspace share one mutation * channel (mutations serialize server-side under compare-and-swap). Mutation * signatures are validated against the deployed record's describe output. * * @packageDocumentation */ import { type EastType, type EastTypeValue, type ValueTypeOf } from "@elaraai/east"; import { type PlatformFunction } from "@elaraai/east/internal"; import { type RecordErrorType } from "@elaraai/e3-ui/internal"; import { type RecordSignature, type MutationResult, type RecordHistoryResult, type RequestOptions } from "@elaraai/e3-api-client"; import { type SettledSource } from "@elaraai/east-ui-components/platform"; import { TrackedChannelStore } from "./tracked-channel.js"; import { type ReactiveDatasetCacheInterface } from "./dataset-store.js"; import type { TreePath } from "@elaraai/e3-types"; /** Request shape for {@link RecordApi.mutate} — beast2-encoded positional * args (the extra reducer parameters, after the implicit state). */ export interface RecordMutateArgs { args: Uint8Array[]; /** The write's idempotency key: a retry with the same key after an * unanswered call resolves to the first call's commit instead of writing * twice. */ idempotencyKey?: string; } /** * Adapter for the workspace record endpoints. The default wraps * `@elaraai/e3-api-client`'s `workspaceRecordDescribe` / * `workspaceRecordMutate` / `workspaceRecordHistory`. `read()` does NOT go * through here — it reads the record's dataset bytes from the shared cache. */ export interface RecordApi { /** Describe a record's mutations (name + extra arg types), for validation. */ describe(workspace: string, record: string): Promise; /** Apply a mutation synchronously, returning its terminal MutationResult. */ mutate(workspace: string, record: string, mutation: string, req: RecordMutateArgs): Promise; /** Read a record's commit chain (newest first). */ history(workspace: string, record: string, limit: number | undefined, from?: string): Promise; } /** * Build the default {@link RecordApi} that talks to a real e3 server via * `@elaraai/e3-api-client`. * * @param apiUrl - Base URL of the e3 API server * @param repo - Repository name * @param getOptions - Reads the current request options — the token, and the * `fetch` requests go through — so a rotated one is used at once * @returns The adapter */ export declare function createDefaultRecordApi(apiUrl: string, repo: string, getOptions: () => RequestOptions): RecordApi; type RecordError = ValueTypeOf; type RecordMutateTag = "idle" | "running" | "committed" | "failed" | "cancelled"; /** A handle's signature, recovered from the instantiated handle type. */ interface RecordHandleSignature { readonly stateType: EastTypeValue; readonly mutations: ReadonlyMap; } /** * Introspect the instantiated handle struct type `H`: the state type comes * from the `read` field's FunctionType output, and the mutation names + arg * types come from the `mutate` sub-struct's non-reserved FunctionType fields. * The handle's shape IS the signature — there are no duplicate signature * arguments to drift out of sync. */ export declare function signatureOfRecordHandleType(handleType: EastTypeValue): RecordHandleSignature; /** * The record a dataset path is the current value of. * * @param path - A dataset's path * @returns The record's name; `undefined` for a path that is no record's */ export declare function recordOfPath(path: TreePath): string | undefined; /** Tracked mutation-channel key (one per record). */ export declare function recordChannelKey(workspace: string, name: string): string; /** One tracked mutation channel per `(workspace, record)`. */ interface RecordEntry { status: RecordMutateTag; /** Monotonic; a settling mutation whose seq is no longer current is * discarded (latest-wins, and `cancel` orphans by bumping it). */ launchSeq: number; /** Detail of the last `failed` mutation. */ error?: RecordError; /** The settle promise of the in-flight mutation, if one is running. `start()` * awaits it so a commit lands before the dataflow run reads the record. */ inflight?: Promise; } /** * Encapsulates all `Record.bind` runtime state. The module-level * {@link defaultRecordRuntime} instance backs the registered platform; tests * construct their own for isolation. */ export declare class RecordRuntime extends TrackedChannelStore { private api; private cache; private workspace; private readonly signatureCache; private readonly histories; private readonly historyInFlight; private readonly historyFailed; private readonly handleCache; private readonly answered; protected createEntry(): RecordEntry; /** Install the API adapter + dataset cache + workspace — called by the * React provider (or a test, or the snapshot harness) before any handle * is used. */ initialize(api: RecordApi, cache: ReactiveDatasetCacheInterface, workspace: string): void; /** * Tear down the adapter and all record state. * * @param api - Clear only while this is the installed adapter, so a * provider tearing down after another installed its own leaves that one * in place */ clear(api?: RecordApi): void; private resolveWorkspace; /** The deployed describe signature for a record (fetched once, evicted on failure). */ private signature; /** Validate a mutation's declared arg types against the deployed signature. */ private validate; /** * Fetch a record's history once per channel (deduped); notify on settle. * * @param again - Fetch once more after a fetch in flight, which may have * read the chain before what the caller fetches it for * @returns The fetch, settled once the history or its failure is in */ private fetchHistory; /** * What the cache holds of a record read whole, once it has read the record * since the record's last write from here was answered. * * @remarks * The answer to a write names a commit the record holds, and what the cache * holds of the record is from a read after it once a status poll started * since the answer has found that content the record's — fetched it, or * found it held under the hash the poll read. Until then the cache may * hold the record as it was before the write. A record another write put * back exactly as it was holds, after the write, the bytes it held before: * only when they were read tells the two apart. * * @param name - The record's name * @returns A tracked reader of the record's bytes — `undefined` from it * until the cache has read the record since; `undefined` for a record no * write from here has been answered for, or whose content the cache's * polls do not reconcile (one read a page at a time, or held offline) */ settledOf(name: string): SettledSource | undefined; /** * Whether the workspace has read a record's state since the record's last * write from here was answered, for a record whose hash the cache follows: * one read a page at a time. * * @remarks * The pages of such a record are pinned to a revision, which follows the * hash the workspace's status polls read. The answer to a write names the * revision the write made, and a page that has moved to another one since * the write was drafted cannot tell whether that one is older or newer: * revisions name content, and have no order. A status poll started since * the answer reads the record after the write, so from the moment one has * read its hash — telling its watchers, or finding them holding it — the * revision the pages are pinned to is the record's as of a read made * after the write. * * @param name - The record's name * @returns A tracked reader: whether a poll started since the answer has * read the record's hash; `undefined` for a record no write from here * has been answered for, or whose hash no watch follows */ followedOf(name: string): (() => boolean) | undefined; /** * Run one mutation on the record's channel, and settle to the server's * outcome. * * @remarks * The channel shows the write as it shows every launch, latest-wins; the * outcome returned is the server's own, whatever became of the channel. A * commit refreshes the record's bytes and drops its history. A conflict * fetches both again before the outcome settles, so an awaiting caller * reads the state and the history its write lost to. * * @param idempotencyKey - The write's request id, when it has one * @returns The outcome */ private runMutation; /** * The low-level primitives backing handle methods, bound to THIS runtime. * Registered globally (extension registry) and included by the scoped * platform (e3 `ui()` tasks) so a decoded handle re-binds here. The host * effects (dataset-cache reads + reactive tracking + mutation launch) live * here, keyed only on the plain-data record name; the state type rides as a * type-arg on `record_read`, and per-mutation arg types come from the * `record_mutate` ArgsStruct type-arg. */ buildPrimitives(): PlatformFunction[]; /** * Build the handle value for one `Record.bind` evaluation. Every method — * top-level AND nested `mutate.*` (incl. the dynamic per-mutation closures) — * is a thin IR-bearing `East.function` over {@link buildPrimitives}, capturing * only the record name (+ per-mutation name), so the handle is ordinary * serializable East data (issue #106). */ buildHandle(handleType: EastTypeValue, name: string): Record; /** Build a `Record.bind` PlatformFunction bound to this runtime. Pass * `allowed=null` for an unscoped impl; pass a Set of record names for * manifest scoping. */ buildPlatform(allowed: ReadonlySet | null): PlatformFunction; } /** Process-global runtime backing the `RecordPlatform` export. */ export declare const defaultRecordRuntime: RecordRuntime; /** Install the record API adapter + dataset cache + workspace — called by the * React provider on mount (or by a test, or the snapshot harness). */ export declare function initializeRecordApi(api: RecordApi, cache: ReactiveDatasetCacheInterface, workspace: string): void; /** * Tear down the record API adapter and all record state. * * @param api - Clear only while this is the installed adapter */ export declare function clearRecordApi(api?: RecordApi): void; /** Global, manifest-unscoped `Record.bind` impl + its backing primitives. * Registered on module load (powers the extension registry decode path). */ export declare const RecordPlatform: PlatformFunction[]; /** Build a manifest-scoped `Record.bind` implementation + its backing primitives. * * The `record_*` primitives MUST ship with the scoped platform: e3 `ui()` tasks * render through `createScoped*()` arrays (UITaskPreview), NOT the global * registry, so a serialized handle's methods would otherwise decode to * "Platform function 'record_read' is not available". */ export declare function createScopedRecordPlatform(records: readonly string[]): PlatformFunction[]; /** One offline record implementation for {@link createInMemoryRecordApi}. */ export interface InMemoryRecordDef { /** Record name (what `Record.bind` is bound to). */ name: string; /** The record's state type. */ stateType: EastType | EastTypeValue; /** Initial state value (seeds the dataset cache); absent for a record * declared with no initial value, which holds no state — and refuses * every mutation — until its first state is committed, as a deployed one * does. */ initial?: unknown; /** Mutations — each a reducer over the decoded state + decoded args. */ mutations: { name: string; argTypes: (EastType | EastTypeValue)[]; reduce: (state: unknown, ...args: unknown[]) => unknown; }[]; } /** * Build an offline {@link RecordApi} from local implementations — the * snapshot harness's stand-in for a deployed record. Seeds each * record's current value into the dataset cache so `read()` works offline. * * @remarks * A reducer that throws a patch's `ConflictError` — `applyFor` over a patch * whose befores the state no longer holds — is the stale write the server * reports as a `conflict` naming the key; any other throw is a failed program. * A mutation carrying a key one of its last {@link KEYS_REMEMBERED} keyed * mutations carried runs nothing again: it answers with that mutation's commit * and the state it holds now, as the server answers a request it remembers. */ export declare function createInMemoryRecordApi(cache: ReactiveDatasetCacheInterface, workspace: string, defs: InMemoryRecordDef[]): RecordApi; export {}; //# sourceMappingURL=record-runtime.d.ts.map