diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 785c38ba..61e5d39b 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -491,6 +491,14 @@ gate의 realtime source/fixture 검사는 native SSE/WebSocket/Web Push API가 bootstrap/installed-feature 조합을 차단한다. optional recipe source gate는 uncomposed runtime 전체를 tree-shaking 없이 합성해 catalog의 gzip 예산도 blocking으로 검증한다. +같은 gate의 `check:request-fanout`은 `src/features`·`src/application`에서 루프나 배열 +순회 callback 안의 요청(`fetch()`, 이름이 transport인 receiver의 method)을 거절한다. +실패 줄은 두 탈출 방법을 함께 적는다: 기능 `adapters/`에서 +`createCursorPaginationRuntime`(`src/adapters/query-cache`)으로 페이지를 받거나, 상한이 +있고 검토한 반복이면 그 호출 줄에 `// fanout-reviewed: <이유>`를 적는다. 결과 줄은 +주석으로 넘긴 호출의 수와 위치를 적는다. 이름이 다른 receiver(`repository.load()`), +루프가 부르는 이름 있는 함수 안의 요청, 재귀, 순회 전에 만든 promise는 보지 못한다 +(`scripts/check-request-fanout.ts` 머리 주석). `FE-GATE-030`(main 단계)은 reference runtime source·전용 test·catalog metadata를 제거한 임시 repository에서도 base typecheck, architecture, test, build가 통과하는지 검증해 skeleton의 선택성을 유지한다. browser file/storage와 realtime runtime은 diff --git a/scripts/check-request-fanout.ts b/scripts/check-request-fanout.ts index 3fcbe287..1a994599 100644 --- a/scripts/check-request-fanout.ts +++ b/scripts/check-request-fanout.ts @@ -17,6 +17,16 @@ import { parseAsync } from "@babel/core"; * 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: `. + * + * 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"]); @@ -44,6 +54,14 @@ const FUNCTION_TYPES = new Set(["ArrowFunctionExpression", "FunctionExpression"] type Node = { type: string; loc?: { start: { line: number } } } & Record; 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: ` on the call's line"; function receiverName(node: Node | undefined): string | null { if (!node) return null; @@ -81,6 +99,14 @@ export async function findRequestFanout( file: string, sourceText: string, ): Promise { + 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> { const plugins: ("jsx" | ["typescript", { dts: boolean }])[] = [["typescript", { dts: false }]]; if (file.endsWith(".tsx")) plugins.push("jsx"); const tree = (await parseAsync(sourceText, { @@ -93,6 +119,7 @@ export async function findRequestFanout( 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; @@ -106,9 +133,9 @@ export async function findRequestFanout( if (node.type === "CallExpression" && context) { const call = dispatchDescription(node); const line = node.loc?.start.line ?? 0; - if (call && !/fanout-reviewed:\s*\S/u.test(lines[line - 1] ?? "")) { - violations.push({ file, line, call, context }); - } + 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; @@ -121,7 +148,7 @@ export async function findRequestFanout( } }; visit(tree, undefined, null); - return violations; + return { violations, reviewed }; } async function sourceFiles(directory: string): Promise { @@ -143,39 +170,62 @@ async function sourceFiles(directory: string): Promise { export async function scanRequestFanout( root: string, roots: readonly string[] = REQUEST_FANOUT_ROOTS, -): Promise> { +): Promise> { 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) { - violations.push( - ...(await findRequestFanout(path.relative(root, file), await readFile(file, "utf8"))), - ); + 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 }; + 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> { + 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 { const fixture = process.argv.includes("--fixture"); const root = process.cwd(); if (fixture) { - // The forbidden fixture must be rejected; the allowed fixture must pass. - 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; - process.stdout.write( - `request fan-out fixtures: forbidden ${forbidden.violations.length} rejected in ${forbidden.files} files, allowed ${allowed.violations.length} violations ${ok ? "PASS" : "FAIL"}\n`, - ); - if (!ok) process.exitCode = 1; + 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( - `FAIL ${violation.file}:${violation.line} ${violation.call} inside ${violation.context}\n`, - ); - } + 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 ${result.violations.length === 0 ? "PASS" : "FAIL"}\n`, + `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; } diff --git a/tests/architecture/request-fanout.test.ts b/tests/architecture/request-fanout.test.ts index c764fc96..d0df201a 100644 --- a/tests/architecture/request-fanout.test.ts +++ b/tests/architecture/request-fanout.test.ts @@ -3,7 +3,9 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { + checkRequestFanoutFixtures, findRequestFanout, + formatFanoutViolation, scanRequestFanout, } from "../../scripts/check-request-fanout.ts"; @@ -21,6 +23,13 @@ describe("no per-row transport loop (frontend N+1 source gate)", () => { expect(new Set(forbidden.violations.map((violation) => violation.file)).size).toBe(forbidden.files); expect(forbidden.files).toBe(3); expect(allowed.violations).toEqual([]); + expect(allowed.reviewed).toEqual([ + expect.objectContaining({ + file: "tests/fixtures/architecture/request-fanout/allowed/reviewed-cursor-loop.ts", + call: "gateway.page()", + reason: "cursor pages, bounded by maxPages", + }), + ]); }); it("names the dispatch and the repeating construct", async () => { @@ -40,4 +49,24 @@ describe("no per-row transport loop (frontend N+1 source gate)", () => { ); expect(violations).toEqual([]); }); + + // 0929/12-01. The failure line named only the call, so a product team saw + // neither the cursor runtime nor the reviewed-exception comment, and the + // result line hid how many calls a comment let through. + it("tells the author both ways out on the failure line", async () => { + const [violation] = await findRequestFanout( + "inline.ts", + "export const load = (api: { get(id: string): Promise }, ids: string[]) =>\n Promise.all(ids.map((id) => api.get(id)));\n", + ); + const line = formatFanoutViolation(violation!); + expect(line).toMatch(/^FAIL inline\.ts:2 api\.get\(\) inside \.map\(\) callback: /u); + expect(line).toContain("createCursorPaginationRuntime (src/adapters/query-cache)"); + expect(line).toContain("`// fanout-reviewed: ` on the call's line"); + }); + + it("counts and lists the reviewed exceptions in the fixture result line", async () => { + const result = await checkRequestFanoutFixtures(path.resolve(".")); + expect(result.ok).toBe(true); + expect(result.line).toMatch(/allowed 0 violations and 1 reviewed exception \(tests\/fixtures\/architecture\/request-fanout\/allowed\/reviewed-cursor-loop\.ts:\d+ cursor pages, bounded by maxPages\) PASS/u); + }); }); diff --git a/tests/fixtures/architecture/request-fanout/allowed/reviewed-cursor-loop.ts b/tests/fixtures/architecture/request-fanout/allowed/reviewed-cursor-loop.ts new file mode 100644 index 00000000..aa3d5341 --- /dev/null +++ b/tests/fixtures/architecture/request-fanout/allowed/reviewed-cursor-loop.ts @@ -0,0 +1,18 @@ +// Allowed: a cursor loop someone reviewed. Each page needs the cursor the +// previous page returned, so the requests cannot be one bulk read; the count +// is bounded by the page cap. Feature code normally gets this from +// createCursorPaginationRuntime (src/adapters/query-cache). +type Page = Readonly<{ items: readonly string[]; nextCursor: string | null }>; +type Gateway = { page(cursor: string | null): Promise }; + +export async function loadAll(gateway: Gateway, maxPages: number) { + const items: string[] = []; + let cursor: string | null = null; + for (let page = 0; page < maxPages; page += 1) { + const next: Page = await gateway.page(cursor); // fanout-reviewed: cursor pages, bounded by maxPages + items.push(...next.items); + if (next.nextCursor === null) break; + cursor = next.nextCursor; + } + return items; +}