From ddbda4d21eda971255c92c4b086d83f881a307ee Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:12:33 +0900 Subject: [PATCH] =?UTF-8?q?fix(feature-index):=20=EB=B0=94=EB=80=8C?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EC=9D=80=20=EA=B8=B0=EB=8A=A5=20=EC=9D=B8?= =?UTF-8?q?=EB=8D=B1=EC=8A=A4=EB=8A=94=20=EB=8B=A4=EC=8B=9C=20=EC=93=B0?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 빌드, dev 서버, 타입 검사, vitest가 모두 시작할 때 `scripts/generate-product-feature-index.ts`로 `src/.generated/*.ts`를 다시 쓴다. 생성기는 `writeFile`로 파일을 제자리에서 비우고 다시 썼다. 한 checkout에서 두 실행이 겹치면, 한쪽이 파일을 비운 순간 다른 쪽의 Vite나 tsc가 빈 파일이나 반쯤 쓴 파일을 읽을 수 있다(1105/12-04의 "한 checkout 두 실행" 중 공유 소스 파일 부분). 고른 방법: 내용이 같으면 쓰지 않는다. 다르면 같은 폴더의 임시 파일에 쓰고 rename으로 바꾼다. 읽는 쪽은 옛 파일이나 새 파일 하나만 본다. 같은 선택(같은 PRODUCT_APP_ID·VITE_PRODUCT_FEATURES)으로 도는 두 실행은 아예 쓰지 않는다. 버린 대안: 실행마다 `src/.generated`를 따로 두기. 앱 소스가 이 경로를 import하므로 경로를 바꾸면 Vite·tsc·ESLint 설정이 모두 따라 바뀐다. 잠금 파일: 겹친 실행을 직렬로 만들 뿐이고, 죽은 프로세스가 잠금을 남긴다. 위험·한계: 선택이 서로 다른 두 실행(예: 한쪽만 VITE_PRODUCT_FEATURES=none)은 여전히 서로의 인덱스를 바꾼다. 그건 실행이 아니라 checkout 상태가 다른 것이라 이 커밋 범위 밖이다. 임시 파일은 `.tmp`로 끝나 tsc·Vite·ESLint 대상이 아니다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/product-feature-index-write.test.ts Refs: 1105/12-04 --- scripts/generate-product-feature-index.ts | 27 +++++- .../unit/product-feature-index-write.test.ts | 85 +++++++++++++++++++ 2 files changed, 109 insertions(+), 3 deletions(-) create mode 100644 tests/unit/product-feature-index-write.test.ts 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([]); + }); +});