Files
clean-architecture-frontend…/scripts/scale/measure-feature-shape-growth.ts
T
DongHyeonka 6c5818faec refactor(contracts): bearer 인증 프로필을 EXTERNAL_BEARER로 바꾼다 (1101/16-03)
문제
유일한 bearer 인증 프로필 이름이 샘플 이름 REFERENCE_EXTERNAL_BEARER다.
세션이 필요한 제품 기능은 지운 샘플의 이름을 계속 쓰거나 템플릿 소유
파일에 프로필을 더해야 한다. 샘플 제거 드릴의 잔여 검사 정규식도 이
이름을 잡지 않아 샘플을 지운 제품에 그대로 남는다. 리뷰 (2) 오류
메시지는 abf3ce5가 했고 (1) 이름 변경이 남았다.

고른 방법 (2026-11-03 결정)
- 프로필 이름을 EXTERNAL_BEARER로 바꿨다. 참조 기능의 V2 operation 3개와
  V3 descriptor 3개, external-session-adapter 주석, 테스트, VD-23 문서를
  새 이름으로 옮겼다.
- 옛 이름은 한 릴리스 동안 REST_AUTH_PROFILES에 별칭 한 줄로 남기고
  JSDoc @deprecated를 붙였다. 레지스트리는 키와 authProfileId가 같아야
  하므로 별칭은 EXTERNAL_BEARER를 펼치고 id만 옛 이름으로 둔 객체다.
  그래서 옛 이름을 적은 다운스트림 operation도 같은 transport·헤더로
  해석된다.
- scripts/scale의 PLATFORM_TOKENS에서 이 이름을 뺐다. 참조 기능에 더는
  "REFERENCE"가 든 프로필 이름이 없어 이름 바꾸기에서 보호할 것이 없다.
- 새 테스트 두 개: 별칭이 id만 빼고 EXTERNAL_BEARER와 같게 설치되는지,
  src에 옛 이름이 별칭 한 줄 외에 없는지(완료 기준).

버린 대안
- 별칭 없이 바로 바꾸기: 옛 이름을 쓰는 다운스트림 기능이 모듈 로드에서
  바로 실패한다. 공개 이름을 깨는 변경은 BREAKING 결정이 있을 때만 한다.
- 조회 시점의 이름 매핑(alias 표): resolve·executor·composition 세 곳이
  매핑을 알아야 한다. 프로필 항목 하나가 더 작다.

위험·한계
- 설치된 프로필이 셋이 된다. 같은 설정이 두 id로 있을 뿐 권한이 넓어지지
  않는다. 별칭은 다음 minor에서 지우고 CHANGELOG [계약] 행을 남긴다.
  그때 "src only on the alias line" 테스트의 기대값을 빈 목록으로 바꾼다.
- 다운스트림 문자열 id("REFERENCE_EXTERNAL_BEARER")에는 @deprecated 표시가
  보이지 않는다. CHANGELOG로 알린다.
- FE-REG-API 행 3개의 authProfileId가 바뀐다. breakingFields가 아니라
  behavior-change이므로 증거 없이 게이트를 통과한다. 기준선 재승인은 이번
  작업 묶음 끝에서 한 번에 한다.
- 초기 JS gzip(초기 청크 파일별 gzip 합) 203,818 → 203,840 B(+22 B). 별칭
  항목이 rest-profiles가 있는 초기 청크에 실린다. 참조 기능 계약은 lazy
  청크라 초기 크기에 영향이 없다.

검증
- RED(수정 전): rest-profile-contract.test.ts 새 사례 2건 실패("expected
  undefined to match object { transport: 'BEARER_HEADER', …(1) }",
  "expected [ …(9) ] to deeply equal [ Array(1) ]").
- GREEN: 같은 파일 10/10 통과. check-registries "11 registries PASS"
  (FE-REG-API authProfileId 3건 behavior-change).
- 회귀: tests/{unit,integration,features,contract,runtime-schema}
  207 파일 2,366건 통과(pnpm·corepack을 띄우는 6개 제외:
  http-scenario-evidence, ci-workflow-generation, lab-performance,
  fixture-node-modules, deployment-admission, security-followup-archive).
  tsc app·test·node rc=0, 바꾼 파일 eslint rc=0. vite build 성공.
- 미실행: check:architecture, test:sample-removal(pnpm 필요), e2e.

Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md
2026-11-03 00:55:33 +09:00

327 lines
14 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { availableParallelism, cpus, loadavg, tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { gzipSync } from "node:zlib";
import { classifyViteJavascript } from "../lib/classify-vite-bundle.ts";
import { linkFixtureNodeModules } from "../lib/fixture-node-modules.ts";
import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc-diagnostics.ts";
/**
* 11-04 (D-18). Cost of one app as its feature count grows, measured with
* features shaped like the real one: `src/features/reference-feature` copied N
* times with every feature-owned identifier renamed (feature id, route ids and
* paths, API operations, schemas, query namespace, invalidation topic,
* messages). The copies live in contexts of their own (200 features each, the
* context ceiling) so the reference context is unchanged.
*
* For each N the script runs the product generator, `tsc --extendedDiagnostics`
* over tsconfig.app.json and `vite build`, and records compiler counts, wall
* times and initial/lazy JavaScript gzip bytes. Deterministic counts repeat
* exactly; times depend on the host, so the CPU and load average are recorded
* next to them. A typecheck that fails (for example TS2590, a union too complex
* to represent) is recorded as a result with its first error.
*
* node scripts/scale/measure-feature-shape-growth.ts [--sizes=0,25,100] [--repeats=2] [--write]
*
* `--write` stores the result as config/scale/feature-shape-growth.json.
*/
export const FEATURE_SHAPE_BASELINE_PATH = "config/scale/feature-shape-growth.json";
/** What the declared ceilings rest on, derived by hand from the baseline. */
export const FEATURE_SHAPE_CEILINGS_PATH = "config/scale/feature-shape-ceilings.json";
const SOURCE_FEATURE = "src/features/reference-feature";
const FEATURES_PER_CONTEXT = 200;
const BUILD_INPUTS = [
"src",
"public",
"index.html",
"package.json",
"vite.config.ts",
"tsconfig.base.json",
"tsconfig.app.json",
"scripts/lib/vite-module-inventory.ts",
] as const;
// Platform-owned names that only happen to contain "reference".
const PLATFORM_TOKENS = [
"REFERENCE_FEATURE_V1",
"supportReference",
] as const;
/** Renames every feature-owned identifier of the reference feature for copy `id`. */
export function renameReferenceFeature(
text: string,
id: string,
context: Readonly<{ id: string; routeRoot: string }>,
): string {
const upper = id.toUpperCase();
// 1101/07-04. Assembly refuses the reference fixture source in any other
// feature, so a copy pins an external package and declares it in its
// contracts, as a product feature would.
const contractPackage = [
"Object.freeze({",
` packageId: "@feature-shape/${id}",`,
' version: "1.0.0",',
' digest: `sha256:${"0".repeat(64)}`,',
" runtimeProtocolVersion: 1 as const,",
' sourceRevision: "0000000",',
" })",
].join("\n");
let renamed = text
.replace(
/source: Object\.freeze\(\{\s*kind: "TEMPLATE_FIXTURE" as const,\s*fixtureId: "REFERENCE_FEATURE_V1" as const,\s*revision: 1 as const,\s*\}\)/u,
`source: Object.freeze({\n kind: "EXTERNAL_PACKAGE" as const,\n package: ${contractPackage},\n })`,
)
.replace(
"contractPackages: Object.freeze([]),",
`contractPackages: Object.freeze([${contractPackage}]),`,
);
PLATFORM_TOKENS.forEach((token, index) => {
renamed = renamed.replaceAll(token, `\u0000${index}\u0000`);
});
renamed = renamed
.replaceAll("/examples/reference-resources", `/${context.routeRoot}/${id}-resources`)
.replaceAll("qinv.01k10f7m3w9p6r2c8v5n4x", `qinv.shape.${id}`)
.replaceAll("NoRequest", `${upper}NoRequest`)
.replaceAll("reference-context", context.id)
.replaceAll("REFERENCE", upper)
.replaceAll("Reference", upper)
.replaceAll("reference", id);
PLATFORM_TOKENS.forEach((token, index) => {
renamed = renamed.replaceAll(`\u0000${index}\u0000`, token);
});
return renamed;
}
async function copyRenamed(from: string, to: string, rename: (text: string) => string) {
await mkdir(to, { recursive: true });
for (const entry of await readdir(from, { withFileTypes: true })) {
const source = path.join(from, entry.name);
const target = path.join(to, rename(entry.name));
if (entry.isDirectory()) await copyRenamed(source, target, rename);
else await writeFile(target, rename(await readFile(source, "utf8")));
}
}
async function createFixture(features: number): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), `feature-shape-${features}-`));
for (const input of BUILD_INPUTS) {
await mkdir(path.dirname(path.join(root, input)), { recursive: true });
await cp(path.resolve(input), path.join(root, input), { recursive: true });
}
await rm(path.join(root, "src/.generated"), { recursive: true, force: true });
await linkFixtureNodeModules(root);
for (let index = 0; index < features; index += 1) {
const contextNumber = Math.floor(index / FEATURES_PER_CONTEXT);
const context = { id: `shape-context-${contextNumber}`, routeRoot: `shape-${contextNumber}` };
if (index % FEATURES_PER_CONTEXT === 0) {
const contextFile = path.join(root, "src/contexts", context.id, "context-module.ts");
await mkdir(path.dirname(contextFile), { recursive: true });
await writeFile(
contextFile,
`export const CONTEXT_MODULE_ID = "${context.id}";\n` +
`export const CONTEXT_APP_ID = "template-app";\n` +
`export const CONTEXT_ROUTE_PATH = "${context.routeRoot}/*";\n` +
`export const CONTEXT_MAX_FEATURES = ${FEATURES_PER_CONTEXT};\n`,
);
}
const id = `s${String(index).padStart(3, "0")}`;
await copyRenamed(
path.resolve(SOURCE_FEATURE),
path.join(root, "src/features", `${id}-feature`),
(text) => renameReferenceFeature(text, id, context),
);
}
return root;
}
function run(
command: string,
args: readonly string[],
cwd: string,
options: Readonly<{ allowFailure?: boolean }> = {},
) {
const started = performance.now();
const result = spawnSync(command, args, {
cwd,
encoding: "utf8",
maxBuffer: 64 * 1024 * 1024,
});
const ms = Math.round(performance.now() - started);
if (result.status !== 0 && !(options.allowFailure && result.stdout.includes("Instantiations:"))) {
throw new Error(
`${path.basename(command)} ${args.join(" ")} failed in ${cwd}:\n${(result.stdout + result.stderr).slice(0, 4_000)}`,
);
}
return { ms, passed: result.status === 0, stdout: result.stdout };
}
const load = () => loadavg().map((value) => Math.round(value * 100) / 100);
async function javascriptGzipBytes(root: string, files: readonly string[]) {
let bytes = 0;
for (const file of files) bytes += gzipSync(await readFile(path.join(root, "dist", file))).byteLength;
return bytes;
}
/**
* 15-01. Initial JavaScript gzip bytes of the app with `features` reference
* copies added: the generator and `vite build` only, no typecheck. The unit
* suite (merge stage) bounds what one more feature adds to the initial chunk
* with it, so the growth is caught on the PR instead of at the next release.
*/
export async function measureInitialJavascriptGzipBytes(features: number): Promise<number> {
const root = await createFixture(features);
try {
run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root);
run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root);
const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8"));
return await javascriptGzipBytes(root, classifyViteJavascript(manifest).initialFiles);
} finally {
await rm(root, { recursive: true, force: true });
}
}
async function measureOnce(root: string, features: number) {
const loadBefore = load();
run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root);
// The composed registries throw at module evaluation on a duplicate route,
// operation, schema, namespace or message key: prove the copies compose.
const contracts = (await import(
`${pathToFileURL(path.join(root, "src/features/installed-feature-contracts.ts")).href}?features=${features}`
)) as typeof import("../../src/features/installed-feature-contracts.ts");
// 15-01. Operations, schemas and contract contributions compose from the
// runtime halves, which only this module loads.
await import(
`${pathToFileURL(path.join(root, "src/features/loaded-feature-runtimes.ts")).href}?features=${features}`
);
const routes = Object.keys(contracts.ROUTE_REGISTRY).length;
const tsc = run(
path.resolve("node_modules/.bin/tsc"),
["--project", path.join(root, "tsconfig.app.json"), "--noEmit", "--extendedDiagnostics"],
root,
// A type error is a result here (the typecheck stops scaling), not a crash.
{ allowFailure: true },
);
await rm(path.join(root, "dist"), { recursive: true, force: true });
const build = run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root);
const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8"));
const javascript = classifyViteJavascript(manifest);
const diagnostics: TscDiagnostics = parseTscExtendedDiagnostics(tsc.stdout);
return {
addedFeatures: features,
routes,
tsc: {
passed: tsc.passed,
firstError: tsc.stdout.split("\n").find((line) => line.includes("error TS")) ?? null,
files: diagnostics.files,
types: diagnostics.types,
symbols: diagnostics.symbols,
instantiations: diagnostics.instantiations,
memoryKb: diagnostics.memoryKb ?? null,
wallMs: tsc.ms,
},
build: {
wallMs: build.ms,
initialJavascriptFiles: javascript.initialFiles.length,
initialJavascriptGzipBytes: await javascriptGzipBytes(root, javascript.initialFiles),
lazyJavascriptFiles: javascript.lazyFiles.length,
lazyJavascriptGzipBytes: await javascriptGzipBytes(root, javascript.lazyFiles),
},
loadBefore,
loadAfter: load(),
};
}
/**
* 11-05 (2026-09-29). The commit the run measured, so a later run can be
* compared with the same code and a reader can tell whether the baseline
* still describes the tree. Tracked files that differed from that commit are
* listed; an empty list means the commit alone reproduces the run.
*/
function sourceRevision(): Readonly<{ commit: string; modifiedPaths: string[] }> {
const git = (...args: string[]) => spawnSync("git", args, { encoding: "utf8" });
const head = git("rev-parse", "HEAD");
const status = git("status", "--porcelain", "--untracked-files=no");
if (head.status !== 0 || status.status !== 0) {
throw new Error("feature-shape growth: cannot read the source commit (git rev-parse HEAD, git status)");
}
return {
commit: head.stdout.trim(),
modifiedPaths: status.stdout
.split("\n")
.filter(Boolean)
.map((line) => line.slice(3)),
};
}
function version(bin: string): string {
const result = spawnSync(path.resolve("node_modules/.bin", bin), ["--version"], { encoding: "utf8" });
return (result.stdout ?? "").trim();
}
async function main(): Promise<void> {
const argument = (name: string) =>
process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3);
const sizes = (argument("sizes") ?? "0,25,100").split(",").map(Number);
const repeats = Number(argument("repeats") ?? "2");
if (!sizes.every((size) => Number.isSafeInteger(size) && size >= 0) || !(repeats >= 1)) {
throw new TypeError("--sizes must be nonnegative integers and --repeats at least 1");
}
// Read before measuring: the run takes minutes and the tree may move.
const source = sourceRevision();
const runs = [];
for (const features of sizes) {
const root = await createFixture(features);
try {
for (let repeat = 1; repeat <= repeats; repeat += 1) {
const measured = await measureOnce(root, features);
runs.push({ repeat, ...measured });
process.stdout.write(
`features +${features} (repeat ${repeat}): routes=${measured.routes} ` +
`instantiations=${measured.tsc.instantiations} tsc=${measured.tsc.wallMs}ms ` +
`build=${measured.build.wallMs}ms initial=${measured.build.initialJavascriptGzipBytes}B ` +
`lazy=${measured.build.lazyJavascriptGzipBytes}B load=${measured.loadBefore.join("/")}` +
`${measured.tsc.passed ? "" : ` typecheck FAILED: ${measured.tsc.firstError}`}\n`,
);
// Compiler results repeat exactly; a failed typecheck costs minutes and
// gigabytes again for no new information.
if (!measured.tsc.passed) break;
}
} finally {
await rm(root, { recursive: true, force: true });
}
}
const cpu = cpus();
const result = {
schemaVersion: 1,
measuredAt: new Date().toISOString(),
command: `node scripts/scale/measure-feature-shape-growth.ts --sizes=${sizes.join(",")} --repeats=${repeats}`,
environment: {
node: process.versions.node,
platform: process.platform,
arch: process.arch,
cpuModel: cpu[0]?.model.trim() ?? "unknown",
logicalCpus: cpu.length,
availableParallelism: availableParallelism(),
typescript: version("tsc"),
vite: version("vite"),
},
source,
sourceFeature: SOURCE_FEATURE,
runs,
};
const output = process.argv.includes("--write")
? FEATURE_SHAPE_BASELINE_PATH
: "artifacts/scale/feature-shape-growth.json";
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, `${JSON.stringify(result, null, 2)}\n`);
process.stdout.write(`feature-shape growth: ${output}\n`);
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
await main();
}