Files
clean-architecture-frontend…/scripts/check-request-fanout.ts
DongHyeonka c2fb6cf7c2
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m15s
frontend-quality-gates / merge / tests (pull_request) Successful in 13m20s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m16s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
fix(scripts): 실행 가드를 실패로 닫히는 helper 하나로 바꾼다
스크립트 22곳이 argv[1]로 직접 실행을 판정해서, checkout 경로에
공백·한글이 있거나 symlink 절대 경로로 부르면 18곳이 검사 없이 rc=0으로
끝날 수 있다. merge 게이트 명령 셋이 여기 걸린다.

isEntryModule(import.meta) 하나로 바꾸고, process.argv 둘째 값 읽기와
helper 밖 판정은 시험으로 막는다. 맨 import.meta.main은 그 값이 없는
Node에서 같은 거짓 통과가 나서 버렸다. realpath 비교는 같은 판정의 사본
22개가 남고, argv 값의 쓰임을 따라가는 시험은 return·대입으로 피할 수
있어 버렸다.

위험·한계: 건너뛰던 검사가 실패하기 시작할 수 있고, 실행 판정이 아닌
process.argv[1] 읽기도 실패한다. import.meta.main이 없는 Node에서 직접
실행하거나 import하면 실패한다. verify-extreme-scale도 그 Node에서는
rc=2보다 먼저 rc=1로 끝나고, 이전 기록(passed일 수 있다)이 그대로
남아 종료 code로 본다. 코드로 읽은 것이고 그 Node로 돌려 보지 않았다.
막는 시험은 process·argv 별칭과 계산한 index를 따라가지 않는다.

검증(노트북, main으로 옮기기 전 트리 a806088b): 새 시험 고치기 전 실패,
고친 뒤 통과. test:unit 3707개, types, lint, check:ci,
verify:documentation rc=0. desktop merge 단계는 따로 확인한다.

Refs: REV-FE-0040
2026-11-23 02:25:03 +09:00

238 lines
9.9 KiB
TypeScript

import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { parseAsync } from "@babel/core";
import { isEntryModule } from "./lib/entry-module.ts";
/**
* scale-architecture.md §12 / §41. Source gate against frontend N+1 request fan-out.
*
* In feature code and application use cases, a physical-request dispatch must
* not run once per element of a collection. The gate rejects a dispatch call
* - inside a loop statement (for / for-of / for-in / while / do-while), or
* - inside a callback passed to an array iteration method
* (map, flatMap, forEach, filter, reduce, some, every, find, findIndex),
* where a dispatch is `fetch(...)`, or any method call on a receiver named like
* a transport (`http`, `executor`, `client`, `gateway`, `api`, `transport`).
*
* The HTTP runtime itself (src/adapters/http) owns its bounded retry loop and is
* out of scope. A reviewed exception is written on the call's line as
* `// fanout-reviewed: <reason>`.
*
* 0929/12-01. A failure names both ways out: fetch page after page through
* `createCursorPaginationRuntime` (src/adapters/query-cache) assembled in the
* feature's `adapters/`, or mark a bounded, reviewed repetition on the call's
* line. Every reviewed exception is counted and listed in the result line.
*
* What it does not see: a dispatch through a receiver named otherwise
* (`repository.load()`, a destructured `get`), a dispatch in a named function
* that a loop calls, recursion, and promises built before an iteration and
* awaited inside it. Reviews still look for those.
*/
export const REQUEST_FANOUT_ROOTS = Object.freeze(["src/features", "src/application"]);
const TRANSPORT_RECEIVER = /^(?:http|executor|client|gateway|api|transport)$|(?:Http|Executor|Client|Gateway|Api|Transport)$/u;
const ITERATION_METHODS = new Set([
"map",
"flatMap",
"forEach",
"filter",
"reduce",
"some",
"every",
"find",
"findIndex",
]);
const LOOP_TYPES = new Set([
"ForStatement",
"ForOfStatement",
"ForInStatement",
"WhileStatement",
"DoWhileStatement",
]);
const FUNCTION_TYPES = new Set(["ArrowFunctionExpression", "FunctionExpression"]);
type Node = { type: string; loc?: { start: { line: number } } } & Record<string, unknown>;
export type FanoutViolation = Readonly<{ file: string; line: number; call: string; context: string }>;
export type FanoutReviewedException = Readonly<{ file: string; line: number; call: string; reason: string }>;
const REVIEWED = /fanout-reviewed:\s*(\S.*?)\s*$/u;
/** How to fix a failure; both ways the source gate accepts. */
export const FANOUT_REMEDY =
"load one page per request with createCursorPaginationRuntime (src/adapters/query-cache) assembled in the " +
"feature's adapters/, or, for a bounded repetition someone reviewed, write `// fanout-reviewed: <reason>` on the call's line";
function receiverName(node: Node | undefined): string | null {
if (!node) return null;
if (node.type === "Identifier") return node["name"] as string;
if (node.type === "MemberExpression" && (node["property"] as Node).type === "Identifier") {
return ((node["property"] as Node)["name"] as string) ?? null;
}
if (node.type === "ThisExpression") return "this";
return null;
}
function dispatchDescription(call: Node): string | null {
const callee = call["callee"] as Node;
if (callee.type === "Identifier" && callee["name"] === "fetch") return "fetch()";
if (callee.type === "MemberExpression") {
const receiver = receiverName(callee["object"] as Node);
const property = callee["property"] as Node;
const method = property.type === "Identifier" ? (property["name"] as string) : "?";
if (receiver && TRANSPORT_RECEIVER.test(receiver)) return `${receiver}.${method}()`;
}
return null;
}
function iterationCallback(parent: Node | undefined, child: Node): string | null {
if (!parent || parent.type !== "CallExpression" || !FUNCTION_TYPES.has(child.type)) return null;
if (!(parent["arguments"] as Node[]).includes(child)) return null;
const callee = parent["callee"] as Node;
if (callee.type !== "MemberExpression") return null;
const property = callee["property"] as Node;
const method = property.type === "Identifier" ? (property["name"] as string) : "";
return ITERATION_METHODS.has(method) ? `.${method}() callback` : null;
}
export async function findRequestFanout(
file: string,
sourceText: string,
): Promise<readonly FanoutViolation[]> {
return (await inspectRequestFanout(file, sourceText)).violations;
}
/** Per-row dispatches, and the ones a `fanout-reviewed:` comment let through. */
export async function inspectRequestFanout(
file: string,
sourceText: string,
): Promise<Readonly<{ violations: readonly FanoutViolation[]; reviewed: readonly FanoutReviewedException[] }>> {
const plugins: ("jsx" | ["typescript", { dts: boolean }])[] = [["typescript", { dts: false }]];
if (file.endsWith(".tsx")) plugins.push("jsx");
const tree = (await parseAsync(sourceText, {
filename: file,
babelrc: false,
configFile: false,
sourceType: "module",
parserOpts: { plugins },
})) as unknown as Node | null;
if (!tree) throw new Error(`cannot parse ${file}`);
const lines = sourceText.split("\n");
const violations: FanoutViolation[] = [];
const reviewed: FanoutReviewedException[] = [];
const visit = (node: Node, parent: Node | undefined, repeating: string | null): void => {
let context = repeating;
if (LOOP_TYPES.has(node.type)) context = node.type.replace("Statement", " loop");
const callback = iterationCallback(parent, node);
if (callback) context = callback;
// A nested function declared (not iterated) resets the repetition context.
if (!callback && FUNCTION_TYPES.has(node.type)) context = null;
if (node.type === "FunctionDeclaration") context = null;
if (node.type === "CallExpression" && context) {
const call = dispatchDescription(node);
const line = node.loc?.start.line ?? 0;
const reason = REVIEWED.exec(lines[line - 1] ?? "")?.[1];
if (call && reason !== undefined) reviewed.push({ file, line, call, reason });
else if (call) violations.push({ file, line, call, context });
}
for (const [key, value] of Object.entries(node)) {
if (key === "loc" || key === "start" || key === "end" || key === "extra") continue;
const children = Array.isArray(value) ? value : [value];
for (const child of children) {
if (child && typeof child === "object" && typeof (child as Node).type === "string") {
visit(child as Node, node, context);
}
}
}
};
visit(tree, undefined, null);
return { violations, reviewed };
}
async function sourceFiles(directory: string): Promise<string[]> {
const found: string[] = [];
let entries;
try {
entries = await readdir(directory, { withFileTypes: true });
} catch {
return found;
}
for (const entry of entries) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) found.push(...(await sourceFiles(target)));
else if (/\.tsx?$/u.test(entry.name) && !/\.d\.ts$/u.test(entry.name)) found.push(target);
}
return found;
}
export async function scanRequestFanout(
root: string,
roots: readonly string[] = REQUEST_FANOUT_ROOTS,
): Promise<Readonly<{
files: number;
violations: readonly FanoutViolation[];
reviewed: readonly FanoutReviewedException[];
}>> {
const files = (await Promise.all(roots.map((entry) => sourceFiles(path.join(root, entry))))).flat();
const violations: FanoutViolation[] = [];
const reviewed: FanoutReviewedException[] = [];
for (const file of files) {
const found = await inspectRequestFanout(path.relative(root, file), await readFile(file, "utf8"));
violations.push(...found.violations);
reviewed.push(...found.reviewed);
}
return { files: files.length, violations, reviewed };
}
export function formatFanoutViolation(violation: FanoutViolation): string {
return `FAIL ${violation.file}:${violation.line} ${violation.call} inside ${violation.context}: ${FANOUT_REMEDY}`;
}
function formatReviewed(reviewed: readonly FanoutReviewedException[]): string {
if (reviewed.length === 0) return "0 reviewed exceptions";
return `${reviewed.length} reviewed exception${reviewed.length === 1 ? "" : "s"} (` +
`${reviewed.map((entry) => `${entry.file}:${entry.line} ${entry.reason}`).join("; ")})`;
}
/**
* The forbidden fixture must be rejected; the allowed fixture must pass, with
* its reviewed cursor loop counted as a reviewed exception.
*/
export async function checkRequestFanoutFixtures(root: string): Promise<Readonly<{ ok: boolean; line: string }>> {
const forbidden = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/forbidden"]);
const allowed = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/allowed"]);
const ok = forbidden.violations.length >= forbidden.files && forbidden.files > 0 &&
allowed.violations.length === 0 && allowed.reviewed.length > 0;
return {
ok,
line: `request fan-out fixtures: forbidden ${forbidden.violations.length} rejected in ${forbidden.files} files, ` +
`allowed ${allowed.violations.length} violations and ${formatReviewed(allowed.reviewed)} ${ok ? "PASS" : "FAIL"}`,
};
}
async function main(): Promise<void> {
const fixture = process.argv.includes("--fixture");
const root = process.cwd();
if (fixture) {
const result = await checkRequestFanoutFixtures(root);
process.stdout.write(`${result.line}\n`);
if (!result.ok) process.exitCode = 1;
return;
}
const result = await scanRequestFanout(root);
for (const violation of result.violations) process.stderr.write(`${formatFanoutViolation(violation)}\n`);
process.stdout.write(
`request fan-out: ${result.files} files scanned, ${result.violations.length} per-row dispatches, ` +
`${formatReviewed(result.reviewed)} ${result.violations.length === 0 ? "PASS" : "FAIL"}\n`,
);
if (result.violations.length > 0) process.exitCode = 1;
}
if (isEntryModule(import.meta)) {
await main();
}