UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

1 lines • 12.3 kB
{"version":3,"file":"confirm.mjs","names":[],"sources":["../../../src/services/registry/confirm.ts"],"sourcesContent":["import { registryClientShape } from \"./client\";\nimport { keyPathOf, type RegistryKey } from \"./keys\";\n\n/**\n * The publish-confirmation state machine: a registry write is verified, not\n * assumed. Every leg the publish wrote — the runtime config always, the\n * manifest tag and its version record on release trains — must read back\n * byte-equal before the publish counts, because FastKV writes are\n * action-indexed: the on-chain transaction's execution is irrelevant\n * (CodeDoesNotExist is the designed success path), the read-back is the\n * only authority.\n *\n * States: Pending → Indexed (the tx is visible in the registry's history;\n * the cheap probe) → Verified (every leg reads back deep-equal) | TimedOut\n * (deadline; the unverified legs are named). Two provisions carry over from\n * the polling loop this replaces: the history probe is informative only —\n * after two informative-but-absent probes, or any history failure, the\n * machine falls back permanently to plain content polling, so a registry\n * whose history never carries the tx still verifies; and a leg read failure\n * never skips the leg — it retries until the deadline. The transaction probe\n * is consultative: it runs only after a content miss and may terminate a\n * wait content has already failed to satisfy, never preempt a verify — the\n * read-back outranks it (a landed publish executes with CodeDoesNotExist on\n * the codeless namespace and that is success).\n */\n\nexport type ConfirmLegKind = \"runtimeConfig\" | \"manifest\" | \"version\";\n\n/** The submit's transaction as the chain sees it, from the `txStatus` seam.\n * `invalid` is explicit rejection (stale nonce, expired); `unknown` means no\n * node has the transaction; `unreachable` is a failed status probe — always\n * treated as informative-only, never proof of anything. */\nexport type TxStatus = \"included\" | \"invalid\" | \"unknown\" | \"unreachable\";\n\nexport interface ConfigConfirmLeg {\n readonly kind: ConfirmLegKind;\n readonly key: RegistryKey;\n /** The expected value — the exact publish payload (deep-equality via\n * JSON compare; the registry serves the written value verbatim). */\n readonly expected: unknown;\n /** Overrides the default keyed read — the manifest/version legs read\n * through pointer.ts's transports (the train binds account/gateway and\n * the registry override); the config leg reads through the injected\n * `read` seam. */\n readonly read?: () => Promise<unknown>;\n}\n\nexport type ConfirmLeg = ConfigConfirmLeg;\n\nexport type ConfirmVerdict =\n | { readonly ok: true; readonly verified: readonly ConfirmLegKind[] }\n | {\n readonly ok: false;\n readonly unverified: readonly ConfirmLegKind[];\n readonly lastError?: string;\n /** The transaction reached a terminal-unapplied outcome — rejected on-chain\n * or dropped at broadcast (most often a stale nonce). The registry was\n * never written; content polling is pointless. The caller may resubmit\n * identical bytes. */\n readonly terminalTx?: true;\n };\n\nexport interface ConfirmOptions {\n readonly legs: readonly ConfirmLeg[];\n /** The submit's tx hash (#430) — enables the indexed-probe fast path. */\n readonly txHash?: string;\n readonly timeoutMs?: number;\n readonly intervalMs?: number;\n /** Seams — tests substitute fakes; production defaults to the client. */\n readonly read?: (key: RegistryKey) => Promise<unknown>;\n readonly history?: (key: RegistryKey, limit: number) => Promise<Array<{ txHash?: string }>>;\n /** The submit's transaction status as the chain sees it. `invalid` and an\n * `unknown` state persisting past {@link TX_UNKNOWN_GRACE_MS} end the wait\n * early with a terminal verdict; everything else keeps content polling. */\n readonly txStatus?: (txHash: string) => Promise<TxStatus>;\n readonly now?: () => number;\n readonly sleep?: (ms: number) => Promise<void>;\n}\n\nconst envMs = (name: string): number | undefined => {\n const raw = Number(process.env[name]);\n return Number.isFinite(raw) && raw > 0 ? raw : undefined;\n};\n\nconst deepEqual = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/** How long a transaction may stay unknown to the chain before the wait is\n * declared terminal: a broadcast that landed is visible within seconds; one\n * still unknown past this grace was dropped (most often a stale nonce from a\n * lagging RPC at broadcast) and will never apply. */\nexport const TX_UNKNOWN_GRACE_MS = 30_000;\n\nconst terminalVerdict = (\n txHash: string,\n reason: string,\n unverified: readonly ConfirmLegKind[],\n): Extract<ConfirmVerdict, { ok: false }> => ({\n ok: false,\n unverified: [...unverified],\n lastError: `transaction ${txHash} will never apply (${reason}) — the registry was not written`,\n terminalTx: true,\n});\n\nexport async function confirmPublish(opts: ConfirmOptions): Promise<ConfirmVerdict> {\n const timeoutMs = opts.timeoutMs ?? envMs(\"BOS_PUBLISH_CONFIRMATION_TIMEOUT_MS\") ?? 120_000;\n const intervalMs = opts.intervalMs ?? envMs(\"BOS_PUBLISH_CONFIRMATION_INTERVAL_MS\") ?? 3_000;\n const read = opts.read ?? ((key: RegistryKey) => registryClientShape.read(key));\n const history =\n opts.history ?? ((key: RegistryKey, limit: number) => registryClientShape.history(key, limit));\n const now = opts.now ?? Date.now;\n const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n\n const verified = new Set<ConfirmLegKind>();\n const pending = () => opts.legs.filter((leg) => !verified.has(leg.kind));\n const lastErrors = new Map<ConfirmLegKind, string>();\n\n // The tx probe is informative only: after TX_PROBE_SKIP_LIMIT\n // informative-but-absent probes — or any probe failure — the machine\n // tracks by content alone. It probes the first keyed leg (the runtime\n // config, always present in a real publish).\n const TX_PROBE_SKIP_LIMIT = 2;\n const probeLeg = opts.legs[0];\n let trackByTx = opts.txHash !== undefined && opts.history !== undefined && probeLeg !== undefined;\n let txProbeSkips = 0;\n let indexed = false;\n\n const startedAt = now();\n let txUnknownSince: number | undefined;\n while (now() - startedAt < timeoutMs) {\n if (trackByTx && !indexed) {\n try {\n const entries = await history(probeLeg!.key, 5);\n if (entries.some((entry) => entry.txHash === opts.txHash)) {\n indexed = true;\n txProbeSkips = 0;\n } else {\n txProbeSkips += 1;\n if (txProbeSkips >= TX_PROBE_SKIP_LIMIT) trackByTx = false;\n await sleep(intervalMs);\n continue;\n }\n } catch {\n trackByTx = false;\n }\n }\n\n let contentMissed = false;\n for (const leg of pending()) {\n try {\n const served = leg.read ? await leg.read() : await read(leg.key);\n if (deepEqual(served, leg.expected)) {\n verified.add(leg.kind);\n lastErrors.delete(leg.kind);\n } else {\n lastErrors.set(leg.kind, \"registry serves a different value\");\n contentMissed = true;\n }\n } catch (error) {\n lastErrors.set(leg.kind, error instanceof Error ? error.message : String(error));\n contentMissed = true;\n }\n }\n\n if (pending().length === 0) {\n return { ok: true, verified: [...verified] };\n }\n\n // The transaction probe runs only after content failed to verify: the\n // read-back is the authority (a landed publish executes with\n // CodeDoesNotExist on the codeless namespace and that is success), so the\n // probe may terminate a wait content has already failed to satisfy — it\n // must never preempt a verify.\n if (contentMissed && opts.txHash && opts.txStatus && !indexed) {\n let status: TxStatus;\n try {\n status = await opts.txStatus(opts.txHash);\n } catch {\n status = \"unreachable\";\n }\n if (status === \"invalid\") {\n return terminalVerdict(\n opts.txHash,\n \"rejected on-chain (stale nonce, missing publish key, or expired — re-mint with `bos login --key` and update NEAR_PRIVATE_KEY)\",\n pending().map((leg) => leg.kind),\n );\n }\n if (status === \"unknown\") {\n if (txUnknownSince === undefined) {\n txUnknownSince = now();\n } else if (now() - txUnknownSince >= TX_UNKNOWN_GRACE_MS) {\n return terminalVerdict(\n opts.txHash,\n `unknown to the chain past ${TX_UNKNOWN_GRACE_MS / 1000}s — dropped at broadcast`,\n pending().map((leg) => leg.kind),\n );\n }\n } else {\n txUnknownSince = undefined;\n }\n }\n await sleep(intervalMs);\n }\n\n const unverified = pending().map((leg) => leg.kind);\n const lastError = [...lastErrors.values()].at(-1);\n return { ok: false, unverified, ...(lastError ? { lastError } : {}) };\n}\n\n/** The train-facing failure message — the wire form of `TimedOut` (#422's\n * confirm channel): the legs' actual wire keys, named. */\nexport function describeConfirmTimeout(\n legs: readonly ConfirmLeg[],\n verdict: Extract<ConfirmVerdict, { ok: false }>,\n): string {\n const unverifiedKeys = legs\n .filter((leg) => verdict.unverified.includes(leg.kind))\n .map((leg) => keyPathOf(leg.key));\n return (\n `Timed out waiting for publish confirmation — unverified: ${unverifiedKeys.join(\", \")}` +\n (verdict.lastError ? ` (last error: ${verdict.lastError})` : \"\")\n );\n}\n"],"mappings":";;;;AA+EA,MAAM,SAAS,SAAqC;CAClD,MAAM,MAAM,OAAO,QAAQ,IAAI,KAAK;CACpC,OAAO,OAAO,SAAS,GAAG,KAAK,MAAM,IAAI,MAAM;AACjD;AAEA,MAA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