feat(scale): 기능 모양 기록에 Service Worker precache 축을 측정으로 더한다
앞 커밋은 precache 상한 실패 문구만 고쳤다. 1112/06-02 완료 기준의 둘째 「기록에 SW 축과 그 기능 수가 있고, 측정이 그 값을 다시 쓴다」가 남았다(확인 리뷰). 기록은 SW를 켜면 상한이 먼저 올 수 있다고만 적고 몇 개에서인지는 없었다. 고른 방법: SW가 precache할 파일의 판정을 generate-service-worker-assets.ts의 함수 하나로 빼고(collectStaticAssets와 새 countPrecachedAssets가 같이 쓴다), 기능 모양 측정이 초기 JavaScript를 재는 같은 빌드 넷에서 그 수를 센다. `--initial-baseline --write`가 serviceWorkerPrecache(assets, firstFeatureAssets, perFeatureAssets, perContextAssets)를 기록에 쓰고, unit 시험이 매번 빌드와 정확히 대조한다. 기록의 축 설명은 상한에서 몇 개가 들어가는지 계산하는 법을 적고 숫자는 옮기지 않는다. 버린 대안: SW를 켠 빌드를 따로 더 재기(unit 시험이 빌드 둘을 더 돈다. 등록 코드 파일 몇 개 차이는 축 설명에 적었다). 측정 결과(desktop, 이 커밋의 기록): 템플릿 24개, 첫 기능 +14, 기능 하나당 +12, context 하나당 +0. 상한 256이면 기능 19개 안팎에서 닿는다. 상한과 precache 범위는 Service Worker 계약이라 바꾸지 않았다. 위험·한계: 기능 템플릿이 lazy 파일을 늘리면 unit 시험이 기록과 달라져 실패한다. 그때 측정 스크립트로 기록을 다시 쓴다(초기 JavaScript와 같은 방식). 검증: 새 시험(판정 함수, 기록 대조, 기록 차이 문구)이 고치기 전 코드에서 실패하고, 측정으로 쓴 기록에서 통과한다(desktop, PR 본문). Refs: 1112/06-02
This commit is contained in:
@@ -69,13 +69,8 @@ export async function collectStaticAssets(
|
||||
const assets: StaticAssetManifestV1["assets"][number][] = [];
|
||||
|
||||
for (const relative of files.sort()) {
|
||||
const base = path.basename(relative);
|
||||
if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) {
|
||||
continue;
|
||||
}
|
||||
if (EXCLUDED_FILES.has(base)) continue;
|
||||
const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
|
||||
if (!contentType || !HASHED_NAME.test(base)) continue;
|
||||
const contentType = precachedContentType(relative);
|
||||
if (!contentType) continue;
|
||||
|
||||
const absolute = path.join(distDirectory, relative);
|
||||
const bytes = await readFile(absolute);
|
||||
@@ -140,6 +135,29 @@ export async function collectStaticAssets(
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The content type of a dist file the worker precaches, or undefined: a
|
||||
* content-hashed name with a cacheable type under `BUILD_ASSET_DIRECTORY`,
|
||||
* not one of `EXCLUDED_FILES`.
|
||||
*/
|
||||
function precachedContentType(relative: string): string | undefined {
|
||||
const base = path.basename(relative);
|
||||
if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) return undefined;
|
||||
if (EXCLUDED_FILES.has(base) || !HASHED_NAME.test(base)) return undefined;
|
||||
return CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
|
||||
}
|
||||
|
||||
/**
|
||||
* 1112/06-02. How many files of a dist the worker would precache, by the
|
||||
* rule collectStaticAssets applies, without its bounds. The feature-shape
|
||||
* measurement records it per feature.
|
||||
*/
|
||||
export async function countPrecachedAssets(distDirectory: string): Promise<number> {
|
||||
return (await walk(distDirectory, distDirectory)).filter(
|
||||
(relative) => precachedContentType(relative) !== undefined,
|
||||
).length;
|
||||
}
|
||||
|
||||
async function walk(root: string, current: string): Promise<string[]> {
|
||||
const entries = await readdir(current, { withFileTypes: true });
|
||||
const files: string[] = [];
|
||||
|
||||
@@ -7,6 +7,7 @@ import { gzipSync } from "node:zlib";
|
||||
|
||||
import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts";
|
||||
import { planFeature, type InstalledFacts } from "../create-feature.ts";
|
||||
import { countPrecachedAssets } from "../generate-service-worker-assets.ts";
|
||||
import { classifyViteJavascript } from "../lib/classify-vite-bundle.ts";
|
||||
import { linkFixtureNodeModules } from "../lib/fixture-node-modules.ts";
|
||||
import { VITE_BUILD_INPUTS } from "../lib/vite-build-inputs.ts";
|
||||
@@ -192,14 +193,18 @@ async function javascriptGzipBytes(root: string, files: readonly string[]) {
|
||||
async function measureInitialJavascript(
|
||||
features: number,
|
||||
featuresPerContext = FEATURES_PER_CONTEXT,
|
||||
): Promise<Readonly<{ gzipBytes: number; files: number }>> {
|
||||
): Promise<Readonly<{ gzipBytes: number; files: number; precacheAssets: number }>> {
|
||||
const root = await createFixture(features, featuresPerContext);
|
||||
try {
|
||||
run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root);
|
||||
run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root);
|
||||
const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8"));
|
||||
const { initialFiles } = classifyViteJavascript(manifest);
|
||||
return { gzipBytes: await javascriptGzipBytes(root, initialFiles), files: initialFiles.length };
|
||||
return {
|
||||
gzipBytes: await javascriptGzipBytes(root, initialFiles),
|
||||
files: initialFiles.length,
|
||||
precacheAssets: await countPrecachedAssets(path.join(root, "dist")),
|
||||
};
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
@@ -224,20 +229,55 @@ export type InitialJavascriptCosts = Readonly<{
|
||||
perContextGzipBytes: number;
|
||||
}>;
|
||||
|
||||
export async function measureInitialJavascriptCosts(): Promise<InitialJavascriptCosts> {
|
||||
/**
|
||||
* 1112/06-02. With the Service Worker on, it precaches every hashed file
|
||||
* under `assets/` (collectStaticAssets), so each feature's lazy chunks count
|
||||
* towards the precache asset bound (`SERVICE_WORKER_BOUNDS.assets`). The
|
||||
* same builds as the initial JavaScript, counted by the worker's rule. The
|
||||
* builds leave the worker off: a build with it on adds the files of its own
|
||||
* registration code.
|
||||
*/
|
||||
export type PrecacheCosts = Readonly<{
|
||||
assets: number;
|
||||
firstFeatureAssets: number;
|
||||
perFeatureAssets: number;
|
||||
perContextAssets: number;
|
||||
}>;
|
||||
|
||||
export type FeatureShapeCosts = Readonly<{
|
||||
initialJavascript: InitialJavascriptCosts;
|
||||
serviceWorkerPrecache: PrecacheCosts;
|
||||
}>;
|
||||
|
||||
export async function measureFeatureShapeCosts(): Promise<FeatureShapeCosts> {
|
||||
const none = await measureInitialJavascript(0);
|
||||
const one = await measureInitialJavascript(1);
|
||||
const twoInOneContext = await measureInitialJavascript(2);
|
||||
const twoInTwoContexts = await measureInitialJavascript(2, 1);
|
||||
return {
|
||||
gzipBytes: none.gzipBytes,
|
||||
files: none.files,
|
||||
firstFeatureGzipBytes: one.gzipBytes - none.gzipBytes,
|
||||
perFeatureGzipBytes: twoInOneContext.gzipBytes - one.gzipBytes,
|
||||
perContextGzipBytes: twoInTwoContexts.gzipBytes - twoInOneContext.gzipBytes,
|
||||
initialJavascript: {
|
||||
gzipBytes: none.gzipBytes,
|
||||
files: none.files,
|
||||
firstFeatureGzipBytes: one.gzipBytes - none.gzipBytes,
|
||||
perFeatureGzipBytes: twoInOneContext.gzipBytes - one.gzipBytes,
|
||||
perContextGzipBytes: twoInTwoContexts.gzipBytes - twoInOneContext.gzipBytes,
|
||||
},
|
||||
serviceWorkerPrecache: {
|
||||
assets: none.precacheAssets,
|
||||
firstFeatureAssets: one.precacheAssets - none.precacheAssets,
|
||||
perFeatureAssets: twoInOneContext.precacheAssets - one.precacheAssets,
|
||||
perContextAssets: twoInTwoContexts.precacheAssets - twoInOneContext.precacheAssets,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 1112/06-02. Fields of the precache record that differ from the build: counts are exact. */
|
||||
export function precacheRecordDrift(measured: PrecacheCosts, record: PrecacheCosts): string[] {
|
||||
return (Object.keys(measured) as (keyof PrecacheCosts)[])
|
||||
.filter((field) => record[field] !== measured[field])
|
||||
.map((field) => `${field}: record ${record[field]}, build ${measured[field]}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1105/15-02. How far the total may be from the record, in gzip bytes. The
|
||||
* total moves by tens of bytes with the build id (CI and local builds
|
||||
@@ -364,11 +404,13 @@ function version(bin: string): string {
|
||||
* the initial JavaScript.
|
||||
*/
|
||||
async function writeInitialBaseline(): Promise<void> {
|
||||
const measured = await measureInitialJavascriptCosts();
|
||||
process.stdout.write(`initial JavaScript: ${JSON.stringify(measured)}\n`);
|
||||
const measured = await measureFeatureShapeCosts();
|
||||
process.stdout.write(`initial JavaScript: ${JSON.stringify(measured.initialJavascript)}\n`);
|
||||
process.stdout.write(`service worker precache: ${JSON.stringify(measured.serviceWorkerPrecache)}\n`);
|
||||
if (!process.argv.includes("--write")) return;
|
||||
const ceilings = JSON.parse(await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8")) as Record<string, unknown>;
|
||||
ceilings["initialJavascript"] = measured;
|
||||
ceilings["initialJavascript"] = measured.initialJavascript;
|
||||
ceilings["serviceWorkerPrecache"] = measured.serviceWorkerPrecache;
|
||||
await writeFile(FEATURE_SHAPE_CEILINGS_PATH, `${JSON.stringify(ceilings, null, 2)}\n`);
|
||||
process.stdout.write(`feature-shape initial baseline: ${FEATURE_SHAPE_CEILINGS_PATH}\n`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user