diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index 5740e956..26100243 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -1,5 +1,6 @@ -import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; -import { dirname, relative, resolve } from "node:path"; +import { randomUUID } from "node:crypto"; +import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { basename, dirname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts"; @@ -404,6 +405,26 @@ export async function generateAppIndexes( ); } +/** + * 1105/12-04. Every build, dev server, type check and test run renders these + * files first, so two runs in one checkout render them at the same time while + * the other run's Vite or tsc reads them. `writeFile` truncated the file in + * place, and a reader could see it empty or half written. An index that has + * not changed is left alone; a changed one replaces the old file with one + * rename, so a reader sees the old file or the new one, never a part. + */ +export async function writeIndexIfChanged(file: string, content: string): Promise { + if ((await readFile(file, "utf8").catch(() => null)) === content) return; + const temporary = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`); + try { + await writeFile(temporary, content, { encoding: "utf8", flag: "wx" }); + await rename(temporary, file); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } +} + async function main(): Promise { const scriptDir = dirname(fileURLToPath(import.meta.url)); // `--root=` points the same production command at another checkout (used by @@ -448,7 +469,7 @@ async function main(): Promise { await Promise.all( (["feature", "context", "app"] as const).map((key) => - writeFile(outputs[key], rendered[key], "utf8"), + writeIndexIfChanged(outputs[key], rendered[key]), ), ); } diff --git a/tests/unit/product-feature-index-write.test.ts b/tests/unit/product-feature-index-write.test.ts new file mode 100644 index 00000000..5439e35c --- /dev/null +++ b/tests/unit/product-feature-index-write.test.ts @@ -0,0 +1,85 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +/** + * 1105/12-04. Every build, dev server, type check and test run renders + * src/.generated first, so two runs in one checkout render it while the other + * run's Vite or tsc reads it. The generator truncated each file in place on + * every run, and a reader could see it empty or half written. It now leaves an + * unchanged file alone and replaces a changed one with a rename. + * + * The generator runs against a copy (`--root=`), so the checkout's own index + * is never touched while other test files read it. + */ +const DECLARATIONS = ["src/apps", "src/contexts", "src/features"] as const; +const OUTPUTS = [ + "product-feature-index.ts", + "product-context-index.ts", + "product-app.ts", +] as const; +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function declarationCopy(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "feature-index-write-")); + roots.push(root); + for (const input of DECLARATIONS) { + await cp(input, path.join(root, input), { recursive: true }); + } + return root; +} + +function generate(root: string): void { + const environment: NodeJS.ProcessEnv = { ...process.env }; + delete environment["PRODUCT_APP_ID"]; + delete environment["VITE_PRODUCT_FEATURES"]; + const run = spawnSync( + process.execPath, + ["scripts/generate-product-feature-index.ts", `--root=${root}`], + { encoding: "utf8", env: environment }, + ); + expect(run.status, run.stderr).toBe(0); +} + +async function identity(file: string): Promise { + const metadata = await stat(file, { bigint: true }); + return `${metadata.ino}:${metadata.mtimeNs}`; +} + +describe("product feature index writes (1105/12-04)", () => { + it("leaves an index that has not changed untouched", async () => { + const root = await declarationCopy(); + const files = OUTPUTS.map((name) => path.join(root, "src/.generated", name)); + generate(root); + const before = await Promise.all(files.map(identity)); + + generate(root); + + expect(await Promise.all(files.map(identity))).toEqual(before); + }); + + it("replaces a stale index with a new file instead of rewriting it in place", async () => { + const root = await declarationCopy(); + const file = path.join(root, "src/.generated/product-feature-index.ts"); + generate(root); + const rendered = await readFile(file, "utf8"); + await writeFile(file, "// stale\n", "utf8"); + const { ino: staleInode } = await stat(file, { bigint: true }); + + generate(root); + + expect(await readFile(file, "utf8")).toBe(rendered); + // A reader that opened the stale file keeps reading the stale file. + expect((await stat(file, { bigint: true })).ino).not.toBe(staleInode); + expect( + (await readdir(path.dirname(file))).filter((name) => name.endsWith(".tmp")), + ).toEqual([]); + }); +});