everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
1 lines • 10.7 kB
Source Map (JSON)
{"version":3,"file":"schema.mjs","names":[],"sources":["../../../src/services/snapshot/schema.ts"],"sourcesContent":["/**\n * The approved boot snapshot's wire schema (ADR 0041) — a leaf module so the\n * host's snapshot coordinator (write on adopt), the boot path (degraded load),\n * and the CLI verification tools (`bos smoke`, the sentinel) can all import it\n * without a cycle. The snapshot is the persisted, verified serving state: the\n * composition this host last adopted, stored so a restart can serve it during\n * a registry/CDN outage. The bundle cache (`registry/bundle-cache.ts`) is the\n * bytes-plane equivalent; the two never share a root (plan 043 — cached bytes\n * are a resilience artifact, never a deployment, and the same line holds for\n * the snapshot: it authorizes restarts of an already-approved generation, it\n * never activates a new one).\n */\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { type BosConfig, BosConfigSchema } from \"../../types\";\nimport { pointerFingerprint } from \"../registry/fingerprint\";\nimport { parseRuntimeRef } from \"../registry/keys\";\nimport { walkRemotes } from \"../remotes\";\n\n/** The immutable descriptor a pinned remote composes — the release manifest's\n * `remotes:` entry shape (ADR 0040), reused verbatim: one vocabulary for the\n * same bytes. */\nexport const RemoteDigestSchema = z.object({\n base: z.string().min(1),\n digest: z.object({\n manifest: z.string().min(1),\n integrity: z.string().min(1),\n }),\n});\nexport type RemoteDigest = z.infer<typeof RemoteDigestSchema>;\n\nexport const BootSnapshotSchema = z\n .object({\n schemaVersion: z.literal(1),\n kind: z.literal(\"everything-dev/boot-snapshot\"),\n runtimeRef: z.string().regex(/^bos:\\/\\/[^/]+\\/[^/]+$/),\n /** The manifest tag `{version, digest}` that authorized the generation —\n * null when the generation came from a registry config resolution that\n * read no release tag. Authorization facts come from the tag + version\n * record chain (ADR 0040). */\n manifestTag: z.object({ version: z.string().min(1), digest: z.string().min(1) }).nullable(),\n /** Hash over every remote coordinate of the stored config\n * (`pointerFingerprint`). The loader recomputes it from `config` and\n * refuses a mismatch — the file's own integrity check, independent of the\n * registry. */\n fingerprint: z.string().regex(/^[0-9a-f]{16}$/),\n /** The resolved published config the generation served. The loader parses\n * it (`BosConfigSchema`) and re-derives the runtime config\n * deterministically — env-derived fields are never persisted. */\n config: BosConfigSchema,\n /** Per-remote digest map mirrored from the config at write time (dotted\n * config path → descriptor), for verification and tooling. */\n remotes: z.record(z.string(), RemoteDigestSchema),\n /** The registry deploy record (`deploys/<ts>.json` key) naming the publish\n * that produced the generation. */\n deployRecordKey: z.string().nullable(),\n /** The composition lockfile's content digest (ADR 0042 ticket 04) — the\n * control-plane staging stamp (ADR 0043): the identity that ties this\n * approved generation to the deployment record that named it. */\n lockfileDigest: z\n .string()\n .regex(/^[0-9a-f]{64}$/)\n .optional(),\n writtenAt: z.string().min(1),\n })\n .strict();\nexport type BootSnapshot = z.infer<typeof BootSnapshotSchema>;\n\nexport function snapshotRoot(input?: { dir?: string }): string {\n return path.resolve(\n input?.dir ?? process.env.BOS_SNAPSHOT_DIR ?? path.join(process.cwd(), \".bos\", \"snapshot\"),\n );\n}\n\nexport function snapshotPath(account: string, gateway: string, input?: { dir?: string }): string {\n return path.join(snapshotRoot(input), account, `${gateway}.json`);\n}\n\nfunction pinnedRemotesOf(config: BosConfig): Record<string, RemoteDigest> {\n const remotes: Record<string, RemoteDigest> = {};\n walkRemotes(config as unknown as Record<string, unknown>, ({ remote, entry }) => {\n if (!entry || typeof entry !== \"object\") return;\n const ref = entry as {\n production?: unknown;\n digest?: { manifest?: unknown; integrity?: unknown };\n };\n const base = typeof ref.production === \"string\" ? ref.production : undefined;\n const manifest = typeof ref.digest?.manifest === \"string\" ? ref.digest.manifest : undefined;\n const integrity = typeof ref.digest?.integrity === \"string\" ? ref.digest.integrity : undefined;\n if (base && manifest && integrity) {\n remotes[remote] = { base, digest: { manifest, integrity } };\n }\n });\n return remotes;\n}\n\nexport function bootSnapshotOf(input: {\n account: string;\n gateway: string;\n config: BosConfig;\n manifestTag?: { version: string; digest: string } | null;\n deployRecordKey?: string | null;\n lockfileDigest?: string;\n writtenAt?: string;\n}): BootSnapshot {\n return BootSnapshotSchema.parse({\n schemaVersion: 1,\n kind: \"everything-dev/boot-snapshot\",\n runtimeRef: `bos://${input.account}/${input.gateway}`,\n manifestTag: input.manifestTag ?? null,\n fingerprint: pointerFingerprint(input.config),\n config: input.config,\n remotes: pinnedRemotesOf(input.config),\n deployRecordKey: input.deployRecordKey ?? null,\n ...(input.lockfileDigest ? { lockfileDigest: input.lockfileDigest } : {}),\n writtenAt: input.writtenAt ?? new Date().toISOString(),\n });\n}\n\n/** The load-side integrity check: recompute the fingerprint from the stored\n * config and compare. A mismatch means the file was hand-edited or written by\n * a different fingerprint implementation — refuse, loud. */\nexport function snapshotFingerprintMatches(snapshot: BootSnapshot): boolean {\n return pointerFingerprint(snapshot.config) === snapshot.fingerprint;\n}\n\nexport class BootSnapshotIntegrityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BootSnapshotIntegrityError\";\n }\n}\n\n/** Verified load: refuses a snapshot whose recomputed fingerprint mismatches\n * — the degraded boot rung serves this file, so it must be the exact\n * composition the coordinator verified when it wrote it. */\nexport function verifiedBootSnapshot(snapshot: BootSnapshot): BootSnapshot {\n if (!snapshotFingerprintMatches(snapshot)) {\n throw new BootSnapshotIntegrityError(\n `boot snapshot fingerprint mismatch: stored ${snapshot.fingerprint}, recomputed ${pointerFingerprint(snapshot.config)} — the file was hand-edited or written by a foreign writer; refusing to serve it`,\n );\n }\n return snapshot;\n}\n\n/** Absent → null; present-but-invalid → throws (the caller distinguishes a\n * missing snapshot from a corrupt one — both refuse, with different causes). */\nexport async function readBootSnapshot(\n account: string,\n gateway: string,\n input?: { dir?: string },\n): Promise<BootSnapshot | null> {\n let bytes: string;\n try {\n bytes = await readFile(snapshotPath(account, gateway, input), \"utf8\");\n } catch {\n return null;\n }\n return parseBootSnapshot(bytes);\n}\n\nexport function serializeBootSnapshot(snapshot: BootSnapshot): string {\n return `${JSON.stringify(snapshot, null, 2)}\\n`;\n}\n\nexport function parseBootSnapshot(bytes: string): BootSnapshot {\n return BootSnapshotSchema.parse(JSON.parse(bytes));\n}\n\n/** Atomic persist (temp + rename) — a reader never observes a partial write.\n * The account/gateway always derive from the snapshot's runtime ref. */\nexport async function writeBootSnapshot(\n snapshot: BootSnapshot,\n input?: { dir?: string },\n): Promise<string> {\n const { accountId, gatewayId } = parseRuntimeRef(snapshot.runtimeRef);\n const target = snapshotPath(accountId, gatewayId, input);\n await mkdir(path.dirname(target), { recursive: true });\n const temp = `${target}.tmp`;\n await writeFile(temp, serializeBootSnapshot(snapshot));\n await rename(temp, target);\n return target;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACtB,QAAQ,EAAE,OAAO;EACf,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EAC1B,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC7B,CAAC;AACH,CAAC;AAGD,MAAa,qBAAqB,EAC/B,OAAO;CACN,eAAe,EAAE,QAAQ,CAAC;CAC1B,MAAM,EAAE,QAAQ,8BAA8B;CAC9C,YAAY,EAAE,OAAO,CAAC,CAAC,MAAM,wBAAwB;;;;;CAKrD,aAAa,EAAE,OAAO;EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EAAG,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAAE,CAAC,CAAC,CAAC,SAAS;;;;;CAK1F,aAAa,EAAE,OAAO,CAAC,CAAC,MAAM,gBAAgB;;;;CAI9C,QAAQ;;;CAGR,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,kBAAkB;;;CAGhD,iBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS;;;;CAIrC,gBAAgB,EACb,OAAO,CAAC,CACR,MAAM,gBAAgB,CAAC,CACvB,SAAS;C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