Files
clean-architecture-frontend…/tests/unit/lab-performance.test.ts
T
DongHyeonka 81701add7e feat(perf): lab이 기능 라우트 첫 진입을 재고 500 ms 예산으로 판정한다
문제: lab(FE-GATE-026)은 플랫폼 구성 화면(EXAMPLES_PLATFORM) 하나만 잰다.
이 화면은 기능 코드를 받지 않아 기능을 더해도 수치가 거의 그대로다
(146 → 154 ms). 기능 라우트는 처음 들어갈 때 context 라우트 모듈과 기능
실행부를 받고, 그다음 페이지 청크를 받는 두 번의 요청 묶음을 거친다.
lab 조건에서 EXAMPLES_UI 첫 진입은 중앙값 406 ms(403~410, 리뷰 15-R1)로
대상 화면의 2.7배인데 어느 게이트도 재지 않는다. 다운스트림의 화면은
모두 기능 라우트다.

고른 방법:
- labFeatureRoute(scripts/lib/lab-performance.ts): 설치된 기능이 가진,
  세션 없이 열리는 첫 내비게이션 라우트. 템플릿에서는 EXAMPLES_UI다.
  없으면 null이고 lab은 measured: false로 남기고 판정하지 않는다.
- lab은 run마다 `/`에서 그 라우트의 내비게이션 링크를 눌러 heading까지를
  같은 페이지 시계로 잰다(새 cold context). metrics.featureRouteInteractionMs
  (중앙값), context.sampling.featureRoute(표본, owner)에 남긴다. 기존 대상
  라우트와 그 예산(200 ms)은 그대로라 회귀 비교가 이어진다.
- 예산 config/performance/budgets.json lab.featureRouteInteractionMs = 500 ms.
  측정 406 ms(8a44226, i5-10400F, lab 조건)를 통과시키고, 지금 둘째 요청
  묶음 크기(약 100 ms, 클릭 뒤 98~204 ms)의 왕복이 하나 더 붙으면 넘는다.
  lab 자가 검사 fixture에 feature-route-over-threshold를 더해 이 예산이
  실패할 수 있음을 매번 확인한다.
- 단위 테스트: 라우트 선택 규칙, 설치된 레지스트리에서의 선택, 커밋된
  예산이 406 ms는 통과·516 ms는 실패·null은 판정 제외.
버린 대안:
- 두 요청 묶음을 하나로 줄이기(진입한 URL의 페이지 청크를 context 라우트
  모듈과 같이 받기): 페이지 청크 이름이 context 라우트 모듈 안의 lazy()에만
  있어, 첫 묶음에서 받으려면 초기 청크의 라우트 선언이 페이지 로더를 가져야
  한다. 선언 모양·생성기·초기 JS를 바꾸는 일이라 이 커밋에서 하지 않았다
  (결정 대기, performance-evidence.md에 적음).
- 처음에는 기록만 하기: 기록만 하면 늘어도 아무도 모른다. 측정값이 있으니
  예산을 같이 둔다.
- 라우트별 예산 표: 다운스트림이 채워야 하는 표가 는다.

위험·한계: 예산 여유가 94 ms(23%)라 lab 호스트가 지금보다 20% 이상 느리면
기능 라우트 판정이 흔들릴 수 있다(0929/11-04 lab 부하 가드는 여전히 없음).
FE-GATE-026 시간이 run마다 cold navigation 하나(약 2~3초) 늘어 5회면
+10~15초다. 생성 기능의 목록 라우트는 session-required라 lab 대상이 되지
않는다. 기능 라우트의 heading은 계약 `title`과 같은 글자로 찾는다(대상
라우트와 같은 방식). CHANGELOG의 "기능 라우트 첫 진입은 어느 게이트도
재지 않는다" 제한 문장은 이 커밋에서 고치지 않았다(오케스트레이터 몫).

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/lab-performance.test.ts
tests/unit/performance-budgets.test.ts
corepack pnpm build && corepack pnpm test:performance -- --runs=5
(featureRoute EXAMPLES_UI 중앙값이 500 ms 안인지, 표본 기록)

Refs: 1105/15-04
2026-11-06 01:23:48 +09:00

188 lines
6.4 KiB
TypeScript

import { spawn } from "node:child_process";
import { readFile } from "node:fs/promises";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
assertPortUnused,
assertServedRelease,
labBrowserLaunchOptions,
labFeatureRoute,
previewArguments,
summarizeSamples,
} from "../../scripts/lib/lab-performance.ts";
import {
NAVIGATION_ROUTES,
ROUTE_FEATURE_OWNER,
ROUTE_REGISTRY,
} from "../../src/features/installed-feature-contracts.ts";
/**
* 11-07. The lab performance gate measured once, and measured whatever server
* held its port: `vite preview` without `--strictPort` moved elsewhere and the
* script never checked which build answered.
*/
const servers: Server[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map(
(server) => new Promise<void>((resolve) => server.close(() => resolve())),
),
);
});
async function foreignServer(manifest: unknown): Promise<string> {
const server = createServer((_request, response) => {
response
.writeHead(200, { "content-type": "application/json" })
.end(JSON.stringify(manifest));
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
}
describe("lab performance gate (11-07)", () => {
it("starts the preview server on exactly the requested port", () => {
expect(previewArguments(4173)).toEqual([
"pnpm",
"preview",
"--host",
"127.0.0.1",
"--port",
"4173",
"--strictPort",
]);
});
it("summarizes repeated runs by their median and keeps every sample", () => {
expect(summarizeSamples([326, 1103, 410, 390, 505])).toEqual({
median: 410,
min: 326,
max: 1103,
samples: [326, 1103, 410, 390, 505],
});
expect(summarizeSamples([1, 4, 2, 3]).median).toBe(2.5);
expect(() => summarizeSamples([])).toThrow(RangeError);
});
it("refuses a port that another server already answers on", async () => {
const baseUrl = await foreignServer({});
await expect(assertPortUnused(baseUrl)).rejects.toThrow(/another server/u);
await expect(assertPortUnused("http://127.0.0.1:9")).resolves.toBeUndefined();
});
it("refuses a server that serves a different build", async () => {
const baseUrl = await foreignServer({ buildId: "other", releaseId: "r1" });
await expect(
assertServedRelease(baseUrl, { buildId: "measured", releaseId: "r1" }),
).rejects.toThrow(/serves build other\/r1, not the measured measured\/r1/u);
await expect(
assertServedRelease(baseUrl, { buildId: "other", releaseId: "r1" }),
).resolves.toBeUndefined();
});
it("fails the gate before measuring when its port is taken", async () => {
const baseUrl = await foreignServer({ buildId: "other", releaseId: "r1" });
const child = spawn(
process.execPath,
[path.resolve("scripts/test-performance.ts")],
{
env: { ...process.env, LAB_PERFORMANCE_PORT: new URL(baseUrl).port },
stdio: ["ignore", "ignore", "pipe"],
},
);
let stderr = "";
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
const code = await new Promise<number | null>((resolve) => {
const timer = setTimeout(() => child.kill("SIGKILL"), 20_000);
child.on("exit", (exitCode) => {
clearTimeout(timer);
resolve(exitCode);
});
});
expect(code).not.toBe(0);
expect(stderr).toMatch(/another server holds the port/u);
}, 30_000);
});
/**
* 1105/15-05. The home page's first render added a vertical scrollbar and
* pushed the header's right side 15 px (CLS 0.0002 at 1280x720 and
* 1366x657). Every gate's Chromium hid scrollbars, the lab included, so no
* gate could see it. The page reserves the gutter, and the lab measures with
* the scrollbar a Windows or Linux desktop draws.
*/
describe("lab performance with real scrollbars (1105/15-05)", () => {
it("starts Chromium without Playwright's --hide-scrollbars", () => {
expect(labBrowserLaunchOptions().ignoreDefaultArgs).toContain("--hide-scrollbars");
});
it("reserves the root scrollbar gutter before the first route renders", async () => {
const base = await readFile("src/presentation/styles/theme/base.css", "utf8");
const root = base.match(/:root\s*\{([^}]*)\}/u)?.[1] ?? "";
expect(root).toMatch(/scrollbar-gutter:\s*stable\s*;/u);
});
});
/**
* 1105/15-04. The lab timed only the platform screen, which loads no feature
* code; a feature route's first entry (two request rounds, 406 ms under the
* lab conditions) had no gate. The lab now times the first public navigation
* route an installed feature owns, with the same clock.
*/
describe("lab feature route (1105/15-04)", () => {
const route = (
routeId: string,
navigationOrder: number | null,
access: "public" | "session-required" = "public",
) => ({
routeId,
path: `/${routeId.toLowerCase()}`,
access,
title: routeId,
navigationLabel: navigationOrder === null ? null : routeId,
navigationOrder,
});
it("takes the first public navigation route a feature owns", () => {
const routes = [
route("APP_HOME", 10),
route("EXAMPLES_PLATFORM", 15),
route("ORDERS_LIST", 50, "session-required"),
route("ORDERS_DETAIL", null),
route("GALLERY", 30),
route("CATALOG", 20),
];
const owners = {
ORDERS_LIST: "orders-feature",
ORDERS_DETAIL: "orders-feature",
GALLERY: "gallery-feature",
CATALOG: "catalog-feature",
};
expect(labFeatureRoute(routes, owners)?.routeId).toBe("CATALOG");
expect(labFeatureRoute(routes, { ORDERS_LIST: "orders-feature" })).toBeNull();
expect(labFeatureRoute(routes, {})).toBeNull();
});
it("finds one in the installed registry while a feature has a public screen", () => {
const selected = labFeatureRoute(Object.values(ROUTE_REGISTRY), ROUTE_FEATURE_OWNER);
const publicFeatureRoutes = NAVIGATION_ROUTES.filter(
(definition) =>
definition.access === "public" && ROUTE_FEATURE_OWNER[definition.routeId] !== undefined,
);
expect(selected?.routeId ?? null).toBe(publicFeatureRoutes[0]?.routeId ?? null);
if (selected) expect(ROUTE_FEATURE_OWNER[selected.routeId]).toEqual(expect.any(String));
});
});