Files
clean-architecture-frontend…/scripts/generate-artifact-schemas.ts
DongHyeonka 198e9856f6
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / checker self-tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / static checks (pull_request) Canceled after 0s
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
test(schemas): 스키마 생성 시험이 fsync 없는 writer로 임시 폴더에 쓴다
문제: json-schema 시험 「generates deterministic … detects drift」가
임시 폴더에 스키마 넷을 쓸 때 파일과 폴더를 fsync한다. 이 시험의
대부분이 fsync이고, 디스크가 바쁘면 시간이 크게 뛴다(desktop
89~1,075ms, CPU를 제한한 coverage 측정에서 7.4초). 이 시험은 생성한
바이트와 drift 판정을 보고, 내구성은 validated-json-artifact 시험이
본다. 기본 timeout 10초 아래라 자기 timeout도 없다.

고른 방법: `generateArtifactSchemas`가 writer를 받는다(기본은 지금의
`writeValidatedJsonArtifact`). 시험은 같은 검증·원자적 rename writer를
`createValidatedJsonArtifactWriter`로 만들고 sync만 뺀다.
- 버린 대안: 시험에 timeout 선언. 시간을 줄이지 않고 흔들림을 덮는다.

위험·한계: 생성 명령과 check:artifact-schemas의 쓰기는 그대로다.

검증(desktop, 고치기 전·후 번갈아 3회, 부하 11~16): 89/1,075/98 →
36/48/35ms. coverage + CPU 소모 12개에서도 208~519 → 73~151ms. 시험
통과, check:artifact-schemas rc=0, check:types·eslint rc=0. 로그
/tmp/claude-gates/w2fe2-slow2·6/.
2026-11-12 22:17:32 +09:00

142 lines
4.5 KiB
TypeScript

import { mkdir, readFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { z } from "zod";
import {
buildManifestArtifactSchema,
dependencyInventoryArtifactSchema,
jsonSchemaDocumentArtifactSchema,
registrySnapshotArtifactSchema,
supplyChainVerificationArtifactSchema,
} from "./contracts/release-artifacts.ts";
import {
type ValidatedJsonArtifactInput,
writeValidatedJsonArtifact,
} from "./lib/validated-json-artifact.ts";
const ARTIFACT_SCHEMA_DEFINITIONS = Object.freeze([
{
relativePath: "config/schemas/artifacts/build-manifest.schema.json",
id: undefined,
schema: buildManifestArtifactSchema,
},
{
relativePath: "config/schemas/artifacts/dependency-inventory.schema.json",
id: "https://clean-architecture-frontend.local/schemas/dependency-inventory.schema.json",
schema: dependencyInventoryArtifactSchema,
},
{
relativePath: "config/schemas/artifacts/registry-snapshot.schema.json",
id: undefined,
schema: registrySnapshotArtifactSchema,
},
{
relativePath: "config/schemas/artifacts/supply-chain-verification.schema.json",
id: "https://clean-architecture-frontend.local/schemas/supply-chain-verification.schema.json",
schema: supplyChainVerificationArtifactSchema,
},
] as const);
type GenerateArtifactSchemasOptions = Readonly<{
root?: string;
check?: boolean;
/**
* Publishes one schema document. The default writes durably (fsync of the
* file and its directory). A test that only checks the generated bytes in a
* temporary root passes a writer without fsync: four fsync pairs were most
* of its time and grew to seconds under the parallel suite's disk load.
*/
writeArtifact?: (input: ValidatedJsonArtifactInput) => Promise<void>;
}>;
function canonicalize(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonicalize);
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, item]) => [key, canonicalize(item)]),
);
}
return value;
}
function generatedSchema(
definition: (typeof ARTIFACT_SCHEMA_DEFINITIONS)[number],
): Readonly<Record<string, unknown>> {
const schema = z.toJSONSchema(definition.schema, {
target: "draft-2020-12",
});
return canonicalize({
...schema,
...(definition.id === undefined ? {} : { $id: definition.id }),
}) as Readonly<Record<string, unknown>>;
}
export async function generateArtifactSchemas(
options: GenerateArtifactSchemasOptions = {},
): Promise<void> {
const root = path.resolve(options.root ?? process.cwd());
const documents = ARTIFACT_SCHEMA_DEFINITIONS.map((definition) => ({
definition,
document: generatedSchema(definition),
}));
const drift: string[] = [];
for (const { definition, document } of documents) {
const destination = path.join(root, definition.relativePath);
const validatedDocument = jsonSchemaDocumentArtifactSchema.parse(document);
const expected = `${JSON.stringify(validatedDocument, null, 2)}\n`;
if (options.check) {
let actual: string | null = null;
try {
actual = await readFile(destination, "utf8");
} catch {
// A missing or unreadable checked-in schema is drift.
}
if (actual !== expected) drift.push(definition.relativePath);
continue;
}
await mkdir(path.dirname(destination), { recursive: true });
await (options.writeArtifact ?? writeValidatedJsonArtifact)({
path: destination,
schema: jsonSchemaDocumentArtifactSchema,
value: document,
});
}
if (drift.length > 0) {
throw new Error(`Artifact JSON Schema drift:\n- ${drift.join("\n- ")}`);
}
}
function argumentValue(name: string): string | undefined {
const index = process.argv.indexOf(name);
return index >= 0 ? process.argv[index + 1] : undefined;
}
const invokedPath = process.argv[1];
if (
invokedPath !== undefined &&
import.meta.url === pathToFileURL(invokedPath).href
) {
try {
await generateArtifactSchemas({
root: argumentValue("--root"),
check: process.argv.includes("--check"),
});
process.stdout.write(
process.argv.includes("--check")
? "Artifact JSON Schemas: PASS\n"
: "Artifact JSON Schemas: GENERATED\n",
);
} catch (error) {
process.stderr.write(
`${error instanceof Error ? error.message : String(error)}\n`,
);
process.exitCode = 1;
}
}