Files
clean-architecture-frontend…/scripts/test-browser-file-storage-runtime-removal.ts
T
DongHyeonka e1a458081d refactor(recipes)!: runtime이 있는 port는 src port를 다시 내보낸다 (0929/05-03)
문제: `recipes/frontend-capabilities/`가 `src/application/ports/`와
같은 이름의 타입 34개를 따로 정의한다(`DurableObjectStorePort`,
`FilePickerPort`, `StorageDurabilityPort`, `TransferProgress`,
`PublicCacheInspection` 등). 7월 이후 runtime port가 바뀌어도(0929
05-01~05-14) recipe 복사본은 한 번도 따라오지 않았다. catalog는 이
복사본을 구현한 fake를 runtime의 fake로 안내해서, 그 fake로 쓴 테스트는
runtime에 없는 resume·quarantine을 전제했다.

고른 방법 (리뷰의 (c)):
- runtime이 있는 port와 그 표면의 타입은 recipe 정의를 지우고
  `src/application/ports`의 것을 같은 이름으로 다시 내보낸다. 옛 recipe
  port에만 쓰이던 `DurableObjectDataClass`, `DurableObjectIntegrity`,
  `DurableObjectRead`, `ObjectStoreRecoverySummary`도 지운다. src에 없는
  `DurableObjectId`·`ObjectGeneration` 브랜드와 `as*` 헬퍼는 남긴다(src
  port가 그대로 받는다).
- fake는 src port를 `implements`한다.
  - 파일 picker·content·preview·download fake와 storage durability fake:
    결과를 `BrowserDataResult`(`error`, 닫힌 코드, operation)로 바꿨다.
    `PROVIDER_UNAVAILABLE`은 src 코드 `UNAVAILABLE`이 된다.
  - `MemoryDurableObjectStore`: src OPFS port에 맞춰 다시 썼다. 생성자는
    scope·storagePolicy·maxObjectBytes를 받는다. 멈춘 put의 행은
    reconcile이 rollback만 한다(resume·quarantine 없음, runtime과 같다).
    LOGOUT·ACCOUNT_DELETION만 지원하고 나머지 reason은 `UNSUPPORTED`다.
  - 고칠 수 없는 fake: `MemoryStructuredOfflineStore`는
    `IndexedDbRepositoryPort`와 설계가 달라(배치 commit·idempotency 대
    CAS·lifecycle batch) catalog offline-indexeddb 행의 fake 칸에서 뺐다.
    recipe 전용 `StructuredOfflineStore`의 fake로는 남는다.
- recipe 전용 port 두 곳:
  - `PublicResponseCacheAdmin.inspect`는 runtime의 `PublicCacheInspection`
    모양으로 보고한다. `MemoryPublicResponseCache`가 그 모양을 만든다.
  - `FileTransferPort`(runtime 없음)의 progress는 `FileTransferProgress`로
    나눴다. `TransferProgress`라는 이름은 recipe barrel에서 src 타입으로
    계속 나간다. 일반 recipe인 `contracts.ts`가 선택형 runtime port를
    import하지 않게 하려는 것이다.
- 다시 갈라지지 않게 `optional-capability-contracts.test.ts`에 검사를
  더했다. recipes/가 src/application/ports/에 있는 이름으로 타입을
  정의하면 실패한다(다시 내보내기는 허용).
- runtime 제거 fixture(`test-browser-file-storage-runtime-removal.ts`)는
  이 runtime의 port를 다시 내보내는 recipe 두 파일과 그 테스트를 함께
  지우고, recipe barrel에서 두 export 줄을 먼저 뺀다.
버린 대안: 현상 유지(변경 누락 계속), 이름만 바꿔 `*Sketch`로 표시(중복
유지비가 남음), 두 벌을 비교하는 타입 테스트(두 벌을 계속 유지).

위험·한계:
- recipe에서 위 타입·fake를 쓰던 다운스트림은 컴파일 오류로 드러난다
  (조용히 깨지지 않는다). 같은 이름 타입의 모양, `MemoryDurableObjectStore`
  생성자·메서드, 파일 fake의 실패 결과(`failure` → `error`), 지운 타입
  4개가 바뀌었다. 두 제품 repo의 사용 여부는 확인하지 않았다.
- `MemoryDurableObjectStore`의 integrity digest는 runtime의 tree digest가
  아니다(주석에 적음). worker·Web Lock·authority·GC는 흉내내지 않는다.
- `test:browser-file-storage-removal`은 pnpm이 필요해 돌리지 못했다.
  barrel 줄 제거와 경로 추가는 코드로만 확인했다.

검증:
- RED: 새 검사를 수정 전 recipe 소스로 돌리면 실패한다.
  `expected [ 'LocalFileRef', …(33) ] to deeply equal []` (34개).
- GREEN: `node scripts/run-vitest.ts run tests/unit tests/recipes
  tests/contract` 180 files 2,548건 통과. `tsc` app·recipes·test·node
  통과, 바꾼 파일 eslint 통과, `check-registries` PASS(재승인 불필요),
  `verify-documentation-readiness` PASS_SCOPED.
  `check-optional-recipes`(source)는 0929/05-01의 offline-indexeddb 예산
  초과(37,327 > 36,900)만 실패하고 catalog·source 검사는 통과했다.
  이 커밋은 그 번들 크기를 바꾸지 않는다(recipes/는 sourceRoots 밖).

BREAKING CHANGE: recipes/frontend-capabilities의 browser-file·OPFS·
storage durability·public cache 타입 중 src/application/ports와 이름이
같은 것은 이제 그 src 타입이다. file·durability·OPFS fake는 src port를
구현하고 BrowserDataResult를 돌려준다(`result.failure.code` →
`result.error.code`). `MemoryDurableObjectStore`는 `{ scope, storagePolicy,
maxObjectBytes }`로 만든다. `FileTransferPort`의 progress 타입은
`FileTransferProgress`다. `DurableObjectDataClass`·`DurableObjectIntegrity`
·`DurableObjectRead`·`ObjectStoreRecoverySummary`는 없어졌다.
Refs: docs/reviews/2026-09-29-maturity-review/05-adapters-storage-kernel.md 05-03
2026-11-03 01:23:05 +09:00

201 lines
6.2 KiB
TypeScript

import {
mkdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import {
assertNoRuntimeImports,
createRemovalFixtureRoot,
prepareRemovalFixture,
pruneRemovalFixtureCiContract,
regenerateRemovalFixtureWorkflow,
removeRuntimeDependentTests,
renderRemovalJunit,
requireRemovalFixtureEnvironment,
runRemovalFixtureCheck,
type RemovalCheck,
} from "./lib/removal-fixture.ts";
const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath");
const fixtureRoot = await createRemovalFixtureRoot("browser-file-storage-runtime-removal");
const RUNTIME_RECIPE_MODULES = [
"browser-file-storage-contracts.ts",
"browser-file-storage-fakes.ts",
] as const;
const runtimePaths = [
"src/application/ports/browser-file-storage",
"src/application/ports/browser-transfer",
"src/adapters/browser-file-storage",
"src/adapters/browser-files",
"src/adapters/browser-transfer",
"src/adapters/cache-storage",
"src/adapters/storage/indexeddb",
"src/adapters/storage/opfs",
"tests/browser-capabilities",
"tests/fixtures/browser-file-storage-boundaries",
// The composition example of this runtime goes with it.
"recipes/frontend-capabilities/indexeddb-feature-capability.ts",
// [0929] 05-03. These recipe contracts re-export this runtime's ports and
// their fakes implement them, so they go with it too, with their test.
...RUNTIME_RECIPE_MODULES.map(
(module) => `recipes/frontend-capabilities/${module}`,
),
"tests/recipes/browser-file-storage-contracts.test.ts",
] as const;
const runtimeSourceRoots = runtimePaths.filter((entry) =>
entry.startsWith("src/"),
);
const removedScripts = new Set([
"test:browser-capabilities",
"verify:browser-capability-evidence",
"check:browser-file-storage-boundaries",
"test:browser-file-storage-removal",
]);
const removedEvidencePathFragments = [
"browser-capabilities",
"browser-file-storage-runtime-removal",
] as const;
function check(name: string, script: string): RemovalCheck {
return runRemovalFixtureCheck(name, fixtureRoot, pnpmCli, script);
}
let checks: RemovalCheck[];
let removedRuntimeTests: number;
try {
await prepareRemovalFixture(fixtureRoot);
// The recipe barrel stops exporting the removed recipe modules first, so the
// import graph below does not count every other recipe test as dependent.
const recipeIndexPath = path.join(
fixtureRoot,
"recipes/frontend-capabilities/index.ts",
);
const recipeIndex = await readFile(recipeIndexPath, "utf8");
const keptRecipeExports = recipeIndex
.split("\n")
.filter(
(line) =>
!RUNTIME_RECIPE_MODULES.some((module) =>
line.includes(`"./${module}"`),
),
);
if (
keptRecipeExports.length !==
recipeIndex.split("\n").length - RUNTIME_RECIPE_MODULES.length
) {
throw new Error("Expected the recipe barrel to export each runtime recipe module once");
}
await writeFile(recipeIndexPath, keptRecipeExports.join("\n"));
removedRuntimeTests =
await removeRuntimeDependentTests(fixtureRoot, runtimeSourceRoots);
for (const runtimePath of runtimePaths) {
await rm(path.join(fixtureRoot, runtimePath), {
recursive: true,
force: true,
});
}
const catalogPath = path.join(
fixtureRoot,
"config/recipes/frontend-capability-recipes.json",
);
const catalog = JSON.parse(await readFile(catalogPath, "utf8")) as {
recipes: Array<Record<string, unknown>>;
};
const browserFileRuntimeRecipeIds = new Set([
"offline-indexeddb",
"service-worker-pwa",
"file-transfer",
]);
let removedRuntimeEntries = 0;
for (const recipe of catalog.recipes) {
if (
typeof recipe.id !== "string" ||
!browserFileRuntimeRecipeIds.has(recipe.id) ||
!Object.hasOwn(recipe, "referenceRuntime")
) {
continue;
}
delete recipe.referenceRuntime;
removedRuntimeEntries += 1;
}
if (removedRuntimeEntries !== 3) {
throw new Error(
`Expected three reference runtime catalog entries, removed ${removedRuntimeEntries}`,
);
}
await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`);
await rm(path.join(fixtureRoot, "playwright.capabilities.config.ts"), {
force: true,
});
await rm(
path.join(fixtureRoot, "scripts/check-browser-file-storage-boundaries.ts"),
{ force: true },
);
await rm(
path.join(fixtureRoot, "scripts/verify-browser-capability-evidence.ts"),
{ force: true },
);
await rm(
path.join(fixtureRoot, "scripts/test-browser-file-storage-runtime-removal.ts"),
{ force: true },
);
// The root snapshot locks the full repository inventory. This removal fixture
// validates its smaller registry through check:ci and its regenerated workflow.
await rm(
path.join(fixtureRoot, "tests/unit/ci-workflow-generation.test.ts"),
{ force: true },
);
await rm(
path.join(
fixtureRoot,
"tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap",
),
{ force: true },
);
await pruneRemovalFixtureCiContract({
root: fixtureRoot,
removedScripts,
removedEvidencePathFragments,
});
await regenerateRemovalFixtureWorkflow(fixtureRoot);
await assertNoRuntimeImports(
fixtureRoot,
runtimeSourceRoots,
"browser file/storage",
);
checks = [
check("typecheck", "check:types"),
check("lint", "lint"),
check("architecture", "check:architecture"),
check("test", "test:all"),
check("build", "build"),
check("optional-catalog", "check:optional-recipes:source"),
check("ci-contract", "check:ci"),
];
} finally {
await rm(fixtureRoot, { recursive: true, force: true });
}
const failed = checks.filter((entry) => !entry.passed);
await mkdir("artifacts/tests", { recursive: true });
await writeFile(
"artifacts/tests/browser-file-storage-runtime-removal.xml",
renderRemovalJunit("browser-file-storage-runtime-removal", checks),
);
if (failed.length > 0) {
process.stderr.write(
`Browser file/storage runtime removal failed: ${failed.map((entry) => entry.name).join(", ")}\n`,
);
process.exit(1);
}
process.stdout.write(
`Browser file/storage runtime removal: PASS (${checks.length} base checks, ${removedRuntimeTests} runtime-dependent tests removed by import graph)\n`,
);