266 lines
9.6 KiB
TypeScript
266 lines
9.6 KiB
TypeScript
import { readdirSync, readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
|
|
import { loadReleaseManifest } from "../../src/bootstrap/load-release-manifest.ts";
|
|
import { loadRuntimeConfig } from "../../src/bootstrap/load-runtime-config.ts";
|
|
import { releaseMismatchKey } from "../../src/bootstrap/boot-release-recovery.ts";
|
|
import { computeContractSetDigest } from "../../src/contracts/contract-set-canonical.ts";
|
|
import type { ReleaseMismatchRecovery } from "../../src/platform/release/release-mismatch-recovery.ts";
|
|
|
|
/**
|
|
* A static multi-release deployment built from immutable fixture artifacts
|
|
* (tests/release/fixtures/<release>/). Responses carry the repository's real
|
|
* cache policy (config/hosting/cache-policy.json), and hashed assets of every
|
|
* retained release stay addressable after a newer release is activated.
|
|
*/
|
|
export type ReleaseName = "R10" | "R11";
|
|
export type Surface = "html" | "config" | "manifest";
|
|
|
|
const FIXTURE_ROOT = path.resolve("tests/release/fixtures");
|
|
const EMPTY_SET_DIGEST = await computeContractSetDigest([]);
|
|
|
|
type CachePolicy = Readonly<{
|
|
surfaces: Readonly<{
|
|
index: Readonly<{ cacheControl: string }>;
|
|
runtimeConfig: Readonly<{ cacheControl: string }>;
|
|
releaseManifest: Readonly<{ cacheControl: string }>;
|
|
hashedAsset: Readonly<{ cacheControl: string }>;
|
|
}>;
|
|
}>;
|
|
|
|
export const CACHE_POLICY = JSON.parse(
|
|
readFileSync(path.resolve("config/hosting/cache-policy.json"), "utf8"),
|
|
) as CachePolicy;
|
|
|
|
type ReleaseArtifacts = Readonly<{
|
|
html: string;
|
|
config: string;
|
|
manifest: string;
|
|
assets: ReadonlyMap<string, string>;
|
|
}>;
|
|
|
|
export function readRelease(release: ReleaseName): ReleaseArtifacts {
|
|
const root = path.join(FIXTURE_ROOT, release);
|
|
const assets = new Map<string, string>();
|
|
for (const file of readdirSync(path.join(root, "assets"))) {
|
|
// Fixtures are stored as `.js.fixture` so no executable JS lives in tests/.
|
|
assets.set(
|
|
file.replace(/\.fixture$/u, ""),
|
|
readFileSync(path.join(root, "assets", file), "utf8"),
|
|
);
|
|
}
|
|
return Object.freeze({
|
|
html: readFileSync(path.join(root, "index.html"), "utf8"),
|
|
config: readFileSync(path.join(root, "config.json"), "utf8"),
|
|
manifest: readFileSync(path.join(root, "release-manifest.json"), "utf8").replace(
|
|
"__EMPTY_SET_DIGEST__",
|
|
EMPTY_SET_DIGEST,
|
|
),
|
|
assets,
|
|
});
|
|
}
|
|
|
|
export type FixtureResponse = Readonly<{
|
|
status: number;
|
|
headers: Readonly<Record<string, string>>;
|
|
body: string;
|
|
release?: ReleaseName;
|
|
}>;
|
|
|
|
function respond(
|
|
status: number,
|
|
cacheControl: string,
|
|
contentType: string,
|
|
body: string,
|
|
release?: ReleaseName,
|
|
): FixtureResponse {
|
|
return Object.freeze({
|
|
status,
|
|
headers: Object.freeze({ "cache-control": cacheControl, "content-type": contentType }),
|
|
body,
|
|
...(release === undefined ? {} : { release }),
|
|
});
|
|
}
|
|
|
|
const NOT_FOUND = respond(404, "no-store", "text/plain", "not found");
|
|
|
|
export function createReleaseFixture(releases: readonly ReleaseName[]) {
|
|
const retained = new Map<ReleaseName, ReleaseArtifacts>(
|
|
releases.map((release) => [release, readRelease(release)]),
|
|
);
|
|
/** Hashed assets have their own retention: the rolling window. */
|
|
const assetStores = new Map<ReleaseName, ReadonlyMap<string, string>>(
|
|
[...retained].map(([release, artifacts]) => [release, artifacts.assets]),
|
|
);
|
|
let active: ReleaseName = releases[0] as ReleaseName;
|
|
const policy = CACHE_POLICY.surfaces;
|
|
|
|
function surface(release: ReleaseName, kind: Surface): FixtureResponse {
|
|
const artifacts = retained.get(release);
|
|
if (!artifacts) return NOT_FOUND;
|
|
switch (kind) {
|
|
case "html":
|
|
return respond(200, policy.index.cacheControl, "text/html; charset=utf-8", artifacts.html, release);
|
|
case "config":
|
|
return respond(200, policy.runtimeConfig.cacheControl, "application/json", artifacts.config, release);
|
|
case "manifest":
|
|
return respond(200, policy.releaseManifest.cacheControl, "application/json", artifacts.manifest, release);
|
|
}
|
|
}
|
|
|
|
function asset(file: string, onlyRelease?: string): FixtureResponse {
|
|
for (const [release, assets] of assetStores) {
|
|
if (onlyRelease !== undefined && release !== onlyRelease) continue;
|
|
const body = assets.get(file);
|
|
if (body !== undefined) {
|
|
return respond(200, policy.hashedAsset.cacheControl, "text/javascript", body, release);
|
|
}
|
|
}
|
|
return NOT_FOUND;
|
|
}
|
|
|
|
return Object.freeze({
|
|
activate(release: ReleaseName) {
|
|
if (!retained.has(release)) {
|
|
const artifacts = readRelease(release);
|
|
retained.set(release, artifacts);
|
|
assetStores.set(release, artifacts.assets);
|
|
}
|
|
active = release;
|
|
},
|
|
/**
|
|
* The rolling window closes for a release's hashed assets (an unsafe
|
|
* deploy would do this too early). Its mutable surfaces may still be
|
|
* served by a lagging replica.
|
|
*/
|
|
retireAssets(release: ReleaseName) {
|
|
assetStores.delete(release);
|
|
},
|
|
get active() {
|
|
return active;
|
|
},
|
|
surface,
|
|
/**
|
|
* Mutable surfaces come from the active release (or an explicit replica);
|
|
* hashed assets come from any retained release, addressed by name or by
|
|
* `/releases/<release>/assets/<file>`.
|
|
*/
|
|
async fetch(requestPath: string, replica?: ReleaseName): Promise<FixtureResponse> {
|
|
const releaseAddressed = /^\/releases\/(R\d+)\/assets\/([^/]+)$/u.exec(requestPath);
|
|
if (releaseAddressed) return asset(releaseAddressed[2] as string, releaseAddressed[1]);
|
|
const hashed = /^\/assets\/([^/]+)$/u.exec(requestPath);
|
|
if (hashed) return asset(hashed[1] as string);
|
|
const release = replica ?? active;
|
|
if (requestPath === "/" || requestPath === "/index.html") return surface(release, "html");
|
|
if (requestPath === "/config.json") return surface(release, "config");
|
|
if (requestPath === "/release-manifest.json") return surface(release, "manifest");
|
|
return NOT_FOUND;
|
|
},
|
|
});
|
|
}
|
|
|
|
export type ReleaseDeployment = ReturnType<typeof createReleaseFixture>;
|
|
|
|
export function response(kind: Surface, release: ReleaseName) {
|
|
return Object.freeze({ kind, release });
|
|
}
|
|
|
|
function toFetchResponse(fixture: FixtureResponse): Response {
|
|
return new Response(fixture.body, { status: fixture.status, headers: fixture.headers });
|
|
}
|
|
|
|
export type BootResult = Readonly<{
|
|
state: "booted" | "release-mismatch" | "asset-missing" | "boot-failed";
|
|
applicationMounted: boolean;
|
|
mismatchKey?: string;
|
|
release?: string;
|
|
}>;
|
|
|
|
/**
|
|
* Boots the real runtime-config and release-manifest loaders against an
|
|
* explicit sequence of replica responses (html, config, manifest), then loads
|
|
* the HTML's hashed entry asset. Nothing mounts unless every step is coherent.
|
|
*/
|
|
export async function bootAgainstReplicaSequence(
|
|
sequence: readonly Readonly<{ kind: Surface; release: ReleaseName }>[],
|
|
deployment: ReleaseDeployment = createReleaseFixture(["R10", "R11"]),
|
|
): Promise<BootResult> {
|
|
const pick = (kind: Surface) => {
|
|
const entry = sequence.find((candidate) => candidate.kind === kind);
|
|
if (!entry) throw new TypeError(`sequence has no ${kind} response`);
|
|
return deployment.surface(entry.release, kind);
|
|
};
|
|
const html = pick("html");
|
|
const buildId = /<meta name="build-id" content="([^"]+)"/u.exec(html.body)?.[1];
|
|
const entryAsset = /src="(\/assets\/[^"]+)"/u.exec(html.body)?.[1];
|
|
if (html.status !== 200 || !buildId || !entryAsset) {
|
|
return { state: "boot-failed", applicationMounted: false };
|
|
}
|
|
try {
|
|
const runtime = await loadRuntimeConfig({
|
|
buildConfig: Object.freeze({
|
|
buildId,
|
|
commitSha: "abc123",
|
|
routerBasePath: "/",
|
|
runtimeConfigUrl: "/config.json",
|
|
}),
|
|
fetcher: async () => toFetchResponse(pick("config")),
|
|
});
|
|
const manifest = await loadReleaseManifest(runtime, {
|
|
fetcher: async () => toFetchResponse(pick("manifest")),
|
|
});
|
|
const asset = await deployment.fetch(entryAsset);
|
|
if (asset.status !== 200) {
|
|
return { state: "asset-missing", applicationMounted: false };
|
|
}
|
|
return { state: "booted", applicationMounted: true, release: manifest.releaseId };
|
|
} catch (error) {
|
|
const key = releaseMismatchKey(error);
|
|
return key === null
|
|
? { state: "boot-failed", applicationMounted: false }
|
|
: { state: "release-mismatch", applicationMounted: false, mismatchKey: key };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Drives a browser session through repeated boots: a mismatch asks the
|
|
* recovery policy, and `reload-once` triggers another boot. Returns how many
|
|
* automatic reloads happened before the session settled.
|
|
*/
|
|
export async function runBootSession(
|
|
nextSequence: () => readonly Readonly<{ kind: Surface; release: ReleaseName }>[],
|
|
recovery: ReleaseMismatchRecovery,
|
|
deployment?: ReleaseDeployment,
|
|
maxBoots = 20,
|
|
): Promise<Readonly<{ reloads: number; final: BootResult }>> {
|
|
let reloads = 0;
|
|
for (let boot = 0; boot < maxBoots; boot += 1) {
|
|
const result = await bootAgainstReplicaSequence(nextSequence(), deployment);
|
|
if (result.state === "booted") {
|
|
recovery.markCoherentBoot();
|
|
return { reloads, final: result };
|
|
}
|
|
if (result.mismatchKey !== undefined && recovery.decide(result.mismatchKey) === "reload-once") {
|
|
reloads += 1;
|
|
continue;
|
|
}
|
|
return { reloads, final: result };
|
|
}
|
|
throw new Error("boot session did not settle: reload loop");
|
|
}
|
|
|
|
/** An in-memory session marker store for simulated browser sessions. */
|
|
export function memoryStorage() {
|
|
let marker: string | null = null;
|
|
return {
|
|
read: () => marker,
|
|
write: (value: string) => {
|
|
marker = value;
|
|
},
|
|
clear: () => {
|
|
marker = null;
|
|
},
|
|
size: () => (marker === null ? 0 : 1),
|
|
};
|
|
}
|