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