Files
clean-architecture-frontend…/src/presentation/examples/platform-overview-page.tsx
T
DongHyeonka 138c195fcd fix(examples): 릴리스 신원 칸의 자리를 미리 잡고 lab이 대상 화면 직접 진입 CLS를 잰다
문제: 플랫폼 구성 화면(lab 대상)은 getReleaseSummary()가 끝날 때까지
릴리스 신원 칸을 "상태" 한 칸으로 그리고, 끝나면 hint 줄이 있는 네 칸으로
바꾼다. 제목이 보인 뒤 약 30~100 ms에 grid가 hint 한 줄만큼 커져 아래
section이 21 px 내려간다(layout shift 0.00461, 리뷰 15-platform-shift
16회). lab은 `/`에서 클릭으로만 들어가고, 클릭 뒤 500 ms 안의 shift는
hadRecentInput이라 CLS에서 빠지므로 0을 낸다. `/` 밖의 라우트 CLS는 어느
게이트도 보지 않는다.

고른 방법:
- 화면: 요약 전·실패 때도 같은 네 칸(빌드·릴리스·설정 스키마·계약 집합
  다이제스트)을 같은 hint 줄 구성으로 그린다. 값만 "확인하고 있습니다."
  / "확인하지 못했습니다." / "—"다. 상태 문장은 가장 좁은 칸(13rem)에서도
  한 줄이 되게 짧게 했다. dl에 aria-busy를 둔다. 시각 테스트는 이미
  `main [aria-busy='true']`가 0개가 될 때까지 기다리므로, dt만 보고 찍던
  대기가 값이 채워진 뒤로 유지된다.
- lab: run마다 대상 라우트를 새 context에서 직접 열고 heading 뒤 network
  idle까지의 CLS를 잰다(metrics.targetDeepLinkCls, 중앙값,
  context.sampling.targetDeepLink에 표본). evaluateLabBudget가 lab.cls
  임계값으로 판정한다. 클릭 시계(상호작용 중앙값)와 대상 라우트는 그대로다.
- 컴포넌트 테스트: 요약 전과 후의 칸 이름·hint 유무가 같다. 실패 테스트는
  빌드 칸의 값으로 본다. 단위 테스트: 직접 진입 CLS가 임계값을 넘으면
  lab 판정이 실패한다.
버린 대안: 릴리스 요약을 동기로 읽기 — getReleaseSummary()가 비동기
포트 계약이라 포트를 바꿔야 한다. 클릭 run에서 hadRecentInput을 무시 —
CLS 정의와 달라져 field 값과 비교할 수 없다.

위험·한계: lab 시간이 run마다 cold navigation 하나(lab 조건 약 2~3초)
늘어 5회면 +10~15초다. 직접 진입 CLS 예산은 0.1이라 0.0046 같은 작은
shift는 실패시키지 않고 lab.json에 값으로만 남는다. layout shift 0건은
lab 값(0)과 15-platform-shift 방법으로 확인해야 한다. 상태 문구가 바뀌어
"런타임 정보를 확인하고 있습니다." 문장은 이 화면에서 사라졌다(홈 화면
문구는 그대로). lab.json 스키마 문서(config/schemas/lab-performance.schema.json)에
새 칸을 필수로 더했다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/component/starter-platform-overview-page.test.tsx
tests/unit/performance-budgets.test.ts
corepack pnpm build && corepack pnpm test:performance -- --runs=5
(lab.json metrics.targetDeepLinkCls가 0인지)

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

694 lines
23 KiB
TypeScript

import { Suspense, use, useEffect, useState } from "react";
import {
HTTP_EXECUTION_CEILINGS,
type ComposedContractContributions,
} from "../../contracts/external-contract-runtime.ts";
import {
listUnvalidatedPayloads,
type UnvalidatedPayloadEntry,
} from "../../contracts/unvalidated-payload.ts";
import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts";
import { ROUTE_REGISTRY } from "../../features/installed-feature-contracts.ts";
import type {
RuntimeCapabilityId,
RuntimeCapabilityStatus,
} from "../../contracts/runtime-capabilities.ts";
import {
Badge,
Card,
DataTable,
EmptySurface,
LoadingSurface,
PageHeader,
type DataTableColumn,
} from "../design-system/index.ts";
import { useApplicationRuntime } from "../providers/application-provider.tsx";
/**
* Every number and row on this page is read from an installed registry at
* render time. Nothing is transcribed by hand, so deleting a feature removes
* its rows and the page keeps describing what the repository actually is.
*/
function kilobytes(bytes: number): string {
if (bytes === 0) return "없음";
if (bytes >= 1_048_576) return `${bytes / 1_048_576} MiB`;
return `${bytes / 1024} KiB`;
}
function seconds(milliseconds: number): string {
return milliseconds < 1000
? `${milliseconds}ms`
: `${milliseconds / 1000}초`;
}
function Metric({
label,
value,
hint,
}: Readonly<{ label: string; value: string; hint?: string }>) {
return (
<div className="platform-metric">
<dt>{label}</dt>
<dd>
<span className="platform-metric__value">{value}</span>
{hint ? <span className="platform-metric__hint">{hint}</span> : null}
</dd>
</div>
);
}
/**
* 1105/15-01. The release metrics before the summary resolves, or after it
* failed: the resolved metrics' labels and hint lines, so the grid keeps its
* height. The status takes the first card's value and stays short enough for
* one line in the narrowest card (13rem), as a build id does.
*/
function ReleaseMetricsPlaceholder({ status }: Readonly<{ status: string }>) {
return (
<>
<Metric label="빌드" value={status} />
<Metric label="릴리스" value="—" />
<Metric label="설정 스키마" value="—" hint="—" />
<Metric label="계약 집합 다이제스트" value="—" hint="—" />
</>
);
}
type RouteRow = (typeof ROUTE_REGISTRY)[keyof typeof ROUTE_REGISTRY];
const ROUTE_COLUMNS: readonly DataTableColumn<RouteRow>[] = Object.freeze([
{
id: "routeId",
header: "라우트",
cell: (row) => <code>{row.routeId}</code>,
},
{ id: "path", header: "경로", cell: (row) => <code>{row.path}</code> },
{
id: "access",
header: "접근",
cell: (row) => (
<Badge variant={row.access === "public" ? "success" : "warning"}>
{row.access}
</Badge>
),
},
{
id: "schemas",
header: "입력 스키마",
cell: (row) =>
[row.paramsSchema, row.searchSchema].filter(Boolean).join(" · ") || "없음",
},
{
id: "chunkId",
header: "청크",
cell: (row) => <code>{row.chunkId}</code>,
},
]);
type OperationRow = Readonly<{
operationId: string;
method: string;
pathTemplate: string;
retrySemantics: string;
retryBudget: number;
totalDeadlineMs: number;
requestByteLimit: number;
responseByteLimit: number;
effect: string;
recovery: string;
}>;
const OPERATION_COLUMNS: readonly DataTableColumn<OperationRow>[] =
Object.freeze([
{
id: "operationId",
header: "오퍼레이션",
cell: (row) => (
<>
<code>{row.operationId}</code>
<span className="platform-operation__path">
{row.method} {row.pathTemplate}
</span>
</>
),
},
{
id: "retry",
header: "재시도",
cell: (row) => (
<>
<Badge variant={row.retrySemantics === "SAFE" ? "success" : "warning"}>
{row.retrySemantics}
</Badge>
<span className="platform-operation__path">
예산 {row.retryBudget}회
</span>
</>
),
},
{
id: "effect",
header: "효과 확정성",
cell: (row) => row.effect,
},
{
id: "recovery",
header: "복구",
cell: (row) => row.recovery,
},
{
id: "budget",
header: "예산",
cell: (row) => (
<>
<span className="platform-operation__path">
요청 {kilobytes(row.requestByteLimit)} · 응답{" "}
{kilobytes(row.responseByteLimit)}
</span>
<span className="platform-operation__path">
마감 {seconds(row.totalDeadlineMs)}
</span>
</>
),
},
]);
const UNVALIDATED_COLUMNS: readonly DataTableColumn<UnvalidatedPayloadEntry>[] =
Object.freeze([
{
id: "contractId",
header: "계약",
cell: (row) => <code>{row.contractId}</code>,
},
{
id: "validator",
header: "검증기",
cell: (row) => (
<>
<Badge variant="warning">{row.validator}</Badge>
<span className="platform-operation__path">{row.schemaId}</span>
</>
),
},
{
id: "reason",
header: "생략 이유",
cell: (row) => row.reason || "이유 없음",
},
]);
type ProfileRow = (typeof SERVER_STATE_PROFILES)[keyof typeof SERVER_STATE_PROFILES];
const PROFILE_COLUMNS: readonly DataTableColumn<ProfileRow>[] = Object.freeze([
{
id: "profileId",
header: "프로파일",
cell: (row) => <code>{row.profileId}</code>,
},
{ id: "stale", header: "stale", cell: (row) => seconds(row.staleTimeMs) },
{ id: "gc", header: "gc", cell: (row) => seconds(row.gcTimeMs) },
{
id: "refetch",
header: "재조회",
cell: (row) =>
[
row.refetchOnMount === "always"
? "mount(always)"
: row.refetchOnMount && "mount",
row.refetchOnFocus && "focus",
row.refetchOnReconnect && "reconnect",
]
.filter(Boolean)
.join(" · "),
},
{
id: "budget",
header: "결과 예산",
cell: (row) =>
`${row.maxResultItems}건 · ${kilobytes(row.maxEstimatedResultBytes)}`,
},
]);
const CAPABILITY_COPY: Readonly<
Record<RuntimeCapabilityId, Readonly<{ label: string; description: string }>>
> = Object.freeze({
REALTIME: Object.freeze({
label: "실시간 수신",
description:
"WebSocket, SSE, 경계 폴링 런타임은 구현되어 있습니다. 제품 기여물이 엔드포인트와 이벤트 서술자를 제공해야 설치됩니다.",
}),
WEB_WORKER: Object.freeze({
label: "웹 워커",
description:
"워커 실행 계약과 전용 타입 프로젝트가 준비되어 있습니다. 프로파일링으로 확인된 CPU 작업이 있어야 설치됩니다.",
}),
SERVICE_WORKER: Object.freeze({
label: "서비스 워커",
description:
"참조 런타임과 두 단계 빌드가 준비되어 있습니다. 설치하면 검증된 정적 자산 캐시와 등록 해제 경로가 함께 켜집니다.",
}),
OFFLINE_COMMANDS: Object.freeze({
label: "오프라인 명령",
description:
"명령 큐 상태 기계가 준비되어 있습니다. 복구 서술자를 가진 KEYED 오퍼레이션이 있어야 설치됩니다.",
}),
});
/**
* A capability that was never selected and one an operator switched off look
* identical if both are reported as "off". The snapshot separates them, and so
* does this badge.
*/
function capabilityBadge(
status: RuntimeCapabilityStatus,
): Readonly<{ text: string; variant: "success" | "warning" | "neutral" }> {
if (status.selected === 0) return { text: "미선택", variant: "neutral" };
if (status.active === 0) {
return { text: "운영자가 비활성화함", variant: "warning" };
}
return { text: `활성 (${status.active})`, variant: "success" };
}
/**
* §3.5. The three states an operator has to be able to tell apart: shipped and
* serving, shipped and switched off, and not in this build at all.
*/
const FEATURE_BADGE = Object.freeze({
ACTIVE: Object.freeze({
variant: "success" as const,
text: "사용 중",
description: "이 빌드에 설치되어 있고 런타임 설정이 끄지 않았습니다.",
}),
DISABLED_BY_CONFIG: Object.freeze({
variant: "warning" as const,
text: "설정으로 중지",
description:
"이 빌드에 포함되어 있으나 런타임 설정이 껐습니다. 재빌드 없이 다시 켤 수 있습니다.",
}),
NOT_INSTALLED: Object.freeze({
variant: "neutral" as const,
text: "미설치",
description:
"빌드 시 제품 매니페스트가 선택하지 않았습니다. 런타임 설정으로는 켤 수 없습니다.",
}),
});
function buildOperationRows(
contracts: ComposedContractContributions,
): readonly OperationRow[] {
return Object.freeze(
[...contracts.httpByOperationId.values()].map(
(installed) => {
const { contract, frontend } = installed;
return Object.freeze({
operationId: contract.operationId,
method: contract.method,
pathTemplate: contract.pathTemplate,
retrySemantics: contract.retrySemantics,
retryBudget: frontend.retryBudget,
totalDeadlineMs: frontend.totalDeadlineMs,
requestByteLimit: frontend.requestByteLimit,
responseByteLimit: frontend.responseByteLimit,
effect:
contract.commandEffect === null
? "해당 없음"
: contract.commandEffect.successEffect,
recovery:
contract.commandRecovery === null
? "해당 없음"
: contract.commandRecovery.mode,
});
},
),
);
}
const CONTRACTS_LOADING = "기능 실행부를 불러오고 있습니다.";
/** The summary counts that only the features' runtime halves know. */
function ContractMetrics({
contracts,
}: Readonly<{ contracts: Promise<ComposedContractContributions> }>) {
const composed = use(contracts);
const fixtureContributions = composed.contributions.filter(
(contribution) => contribution.source.kind === "TEMPLATE_FIXTURE",
).length;
return (
<>
<Metric
label="HTTP 오퍼레이션"
value={`${buildOperationRows(composed).length}개`}
/>
<Metric
label="외부 계약 패키지"
value={`${EXPECTED_CONTRACT_SET_PACKAGES.length}개`}
hint={`템플릿 픽스처 ${fixtureContributions}개`}
/>
</>
);
}
function ContractTables({
contracts,
}: Readonly<{ contracts: Promise<ComposedContractContributions> }>) {
const composed = use(contracts);
return (
<>
<DataTable
caption="설치된 HTTP 오퍼레이션"
columns={OPERATION_COLUMNS}
rows={buildOperationRows(composed)}
rowKey={(row) => row.operationId}
empty={
<EmptySurface
title="설치된 HTTP 오퍼레이션이 없습니다."
description="계약 기여물을 추가하면 이 표에 나타납니다."
/>
}
/>
{/* 1101/07-03. Drawn only when a contract skips validation by name. */}
<DataTable
caption="런타임 검증을 생략한 계약"
columns={UNVALIDATED_COLUMNS}
rows={listUnvalidatedPayloads(composed)}
rowKey={(row) => `${row.contractId}.${row.validator}`}
empty={null}
/>
</>
);
}
/**
* 15-01. The page lists every installed HTTP operation, which lives in the
* features' runtime halves; the boot never loads them. 1103/15-01: only the
* parts that read them wait (`contracts`). The title and everything the
* declarations know draw at once, so entering the route costs the page chunk
* alone, not a second request round for every feature's runtime.
*/
export function PlatformOverviewPage({
contracts,
}: Readonly<{ contracts: Promise<ComposedContractContributions> }>) {
const runtime = useApplicationRuntime();
const [release, setRelease] = useState<
Awaited<ReturnType<typeof runtime.getReleaseSummary>> | "failed" | null
>(null);
useEffect(() => {
let active = true;
runtime.getReleaseSummary().then(
(summary) => {
if (active) setRelease(summary);
},
() => {
if (active) setRelease("failed");
},
);
return () => {
active = false;
};
}, [runtime]);
const routes = Object.values(ROUTE_REGISTRY);
const capabilities = runtime.getCapabilitySnapshot();
const features = runtime.getFeatureSnapshot();
const activeCapabilityCount = capabilities.filter(
(status) => status.active > 0,
).length;
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="플랫폼 구성"
description="이 화면의 모든 값은 설치된 레지스트리에서 렌더 시점에 읽습니다. 손으로 옮겨 적은 숫자가 없으므로 코드가 바뀌면 이 화면도 함께 바뀝니다."
/>
<section
className="gallery-section"
aria-labelledby="platform-release-title"
>
<header className="gallery-section__header">
<h2 id="platform-release-title">릴리스 신원</h2>
<p>
부팅 시 경계 검사를 통과한 런타임 설정과 릴리스 매니페스트에서 옵니다.
</p>
</header>
{/* 1105/15-01. The same four metrics, with the same hint lines, in
every state: the grid used to grow from one card to four with
hints once the summary resolved, about 30-100 ms after the title,
and pushed everything below it 21 px (CLS 0.0046 on a direct
visit). Only the values change; `aria-busy` says when they are
not there yet (the visual test waits on it). */}
<dl
className="platform-metric-grid"
aria-live="polite"
aria-busy={release === null}
>
{release !== null && release !== "failed" ? (
<>
<Metric label="빌드" value={release.buildId} />
<Metric label="릴리스" value={release.releaseId} />
<Metric
label="설정 스키마"
value={release.configSchemaVersion}
hint={
release.apiContractVersion
? `레거시 계약 ${release.apiContractVersion}`
: "계약 집합 사용"
}
/>
<Metric
label="계약 집합 다이제스트"
value={
release.contractSetDigest
? `${release.contractSetDigest.slice(0, 20)}…`
: "없음"
}
hint={
release.contractSetDigest
? "릴리스 매니페스트 V2"
: "릴리스 매니페스트 V1"
}
/>
</>
) : (
<ReleaseMetricsPlaceholder
status={
release === "failed" ? "확인하지 못했습니다." : "확인하고 있습니다."
}
/>
)}
</dl>
</section>
<section
className="gallery-section"
aria-labelledby="platform-summary-title"
>
<header className="gallery-section__header">
<h2 id="platform-summary-title">설치 요약</h2>
<p>레지스트리 항목 수를 그대로 센 값입니다.</p>
</header>
<dl className="platform-metric-grid">
<Metric label="라우트" value={`${routes.length}개`} />
<Suspense
fallback={
<>
<Metric label="HTTP 오퍼레이션" value="확인 중" />
<Metric
label="외부 계약 패키지"
value={`${EXPECTED_CONTRACT_SET_PACKAGES.length}개`}
/>
</>
}
>
<ContractMetrics contracts={contracts} />
</Suspense>
<Metric
label="선택적 런타임 능력"
value={`${activeCapabilityCount} / ${capabilities.length}`}
hint="런타임 오버라이드 반영"
/>
</dl>
</section>
<section
className="gallery-section"
aria-labelledby="platform-routes-title"
>
<header className="gallery-section__header">
<h2 id="platform-routes-title">설치된 라우트</h2>
<p>
라우트 레지스트리가 단일 진실 공급원입니다. 접근 정책, 코드 분할 청크,
입력 스키마가 한 항목에 함께 선언됩니다.
</p>
</header>
<DataTable
caption="설치된 라우트 목록"
columns={ROUTE_COLUMNS}
rows={routes}
rowKey={(row) => row.routeId}
empty={
<EmptySurface
title="설치된 라우트가 없습니다."
description="라우트 레지스트리가 비어 있습니다."
/>
}
/>
</section>
<section
className="gallery-section"
aria-labelledby="platform-contracts-title"
>
<header className="gallery-section__header">
<h2 id="platform-contracts-title">계약과 HTTP 오퍼레이션</h2>
<p>
외부 계약 패키지 {EXPECTED_CONTRACT_SET_PACKAGES.length}개가 설치되어
있습니다. 아래 오퍼레이션은 템플릿 픽스처가 제공하며 릴리스 다이제스트에
포함되지 않습니다. 제품은 픽스처를 지우고 자기 패키지를 고정합니다.
</p>
</header>
<Suspense fallback={<LoadingSurface description={CONTRACTS_LOADING} />}>
<ContractTables contracts={contracts} />
</Suspense>
</section>
<section
className="gallery-section"
aria-labelledby="platform-server-state-title"
>
<header className="gallery-section__header">
<h2 id="platform-server-state-title">서버 상태와 실행 상한</h2>
<p>
조회는 네 개의 고정 프로파일 중 하나를 골라야 하고, 실행 정책은 아래
상한을 넘을 수 없습니다.
</p>
</header>
<DataTable
caption="서버 상태 프로파일"
columns={PROFILE_COLUMNS}
rows={Object.values(SERVER_STATE_PROFILES)}
rowKey={(row) => row.profileId}
empty={<EmptySurface title="프로파일이 없습니다." />}
/>
<dl className="platform-metric-grid">
<Metric
label="응답 상한"
value={kilobytes(HTTP_EXECUTION_CEILINGS.hardResponseBytes)}
hint={`기본 ${kilobytes(HTTP_EXECUTION_CEILINGS.defaultResponseBytes)}`}
/>
<Metric
label="요청 상한"
value={kilobytes(HTTP_EXECUTION_CEILINGS.hardRequestBytes)}
hint={`기본 ${kilobytes(HTTP_EXECUTION_CEILINGS.defaultRequestBytes)}`}
/>
<Metric
label="총 마감 상한"
value={seconds(HTTP_EXECUTION_CEILINGS.hardTotalDeadlineMs)}
hint={`기본 ${seconds(HTTP_EXECUTION_CEILINGS.defaultTotalDeadlineMs)}`}
/>
<Metric
label="재시도 상한"
value={`${HTTP_EXECUTION_CEILINGS.hardRetryCount}회`}
hint="전송 실패에만 적용"
/>
</dl>
</section>
<section
className="gallery-section"
aria-labelledby="platform-capabilities-title"
>
<header className="gallery-section__header">
<h2 id="platform-capabilities-title">선택적 런타임 능력</h2>
<p>
정적 선택 파일이 단일 진실 공급원입니다. 런타임 설정은 이미 선택된
능력을 끌 수만 있고, 설정 문자열로 새 능력을 켜거나 모듈 경로를 만들지
못합니다. 여기 표시되는 상태는 정적 선택에 런타임 오버라이드를 적용한
결과이므로, 애초에 선택되지 않은 능력과 운영자가 끈 능력이 구분됩니다.
</p>
</header>
<div className="component-grid component-grid--two">
{capabilities.map((status) => {
const copy = CAPABILITY_COPY[status.capabilityId];
const badge = capabilityBadge(status);
return (
<Card
key={status.capabilityId}
title={copy.label}
footer={<Badge variant={badge.variant}>{badge.text}</Badge>}
>
<p>{copy.description}</p>
</Card>
);
})}
</div>
</section>
<section
className="gallery-section"
aria-labelledby="platform-features-title"
>
<header className="gallery-section__header">
<h2 id="platform-features-title">제품 기능</h2>
<p>
제품 매니페스트가 이 빌드에 어떤 기능이 설치되었는지 정하고, 런타임
설정은 설치된 기능을 끌 수만 있습니다. 두 입력 모두 감산만 하므로
설정 문서가 없는 기능을 켜 낼 수는 없습니다. 그래서 「빌드에서 빠진
기능」과 「운영자가 끈 기능」이 여기서 구분됩니다.
</p>
</header>
<div className="component-grid component-grid--two">
{features.map((status) => {
const badge = FEATURE_BADGE[status.state];
return (
<Card
key={status.featureId}
title={status.featureId}
footer={<Badge variant={badge.variant}>{badge.text}</Badge>}
>
<p data-product-feature={status.featureId}>
{badge.description}
</p>
</Card>
);
})}
</div>
</section>
</section>
);
}
let installedContracts: Promise<ComposedContractContributions> | undefined;
/**
* One load shared by both waiting parts and by later visits. The composer is
* imported here too, so its code is not in the page chunk the title waits
* for. A duplicate across features rejects here and reaches the route
* boundary, as it did when the route awaited it; a failed load is dropped so
* the next visit retries.
*/
function loadInstalledContracts(): Promise<ComposedContractContributions> {
if (installedContracts === undefined) {
const loading = import(
"../../features/installed-feature-runtime-registries.ts"
)
.then((module) => module.loadInstalledFeatureRuntimeRegistries())
.then((registries) => registries.composedContractContributions);
loading.catch(() => {
if (installedContracts === loading) installedContracts = undefined;
});
installedContracts = loading;
}
return installedContracts;
}
/** The route module: the page bound to the installed registries. */
export default function InstalledPlatformOverviewPage() {
return <PlatformOverviewPage contracts={loadInstalledContracts()} />;
}