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:
@@ -5,7 +5,7 @@
|
||||
"contextMaxFeatures": 200,
|
||||
"appMaxContexts": 20
|
||||
},
|
||||
"summary": "상한은 개수를 제한할 뿐, 검증된 수용량이 아니다. 앱 하나의 실제 한계는 먼저 초기 JavaScript budget이고, 그다음 typecheck 메모리다. Service Worker를 켜면(SERVICE_WORKER: ACTIVE) 그 전에 precache 자산 수 상한(SERVICE_WORKER_BOUNDS.assets)이 올 수 있다. 기능마다 lazy 청크가 늘고 그 전부를 precache하기 때문이다. 이 한계는 기능 수로 재지 않았다. 400개 feature는 재지 않았다(D-18이 선택 사항으로 둔다).",
|
||||
"summary": "상한은 개수를 제한할 뿐, 검증된 수용량이 아니다. 앱 하나의 실제 한계는 먼저 초기 JavaScript budget이고, 그다음 typecheck 메모리다. Service Worker를 켜면(SERVICE_WORKER: ACTIVE) 그 전에 precache 자산 수 상한(SERVICE_WORKER_BOUNDS.assets)이 올 수 있다. 기능마다 lazy 청크가 늘고 그 전부를 precache하기 때문이다. 기능 하나가 더하는 파일 수는 아래 serviceWorkerPrecache에 있다. 400개 feature는 재지 않았다(D-18이 선택 사항으로 둔다).",
|
||||
"axes": [
|
||||
{
|
||||
"axis": "Typecheck of one app",
|
||||
@@ -31,6 +31,12 @@
|
||||
"condition": "위와 같음",
|
||||
"notVerified": "lazy 파일이 많을 때의 다운로드 비용"
|
||||
},
|
||||
{
|
||||
"axis": "Service Worker precache",
|
||||
"verified": "Service Worker를 켜면(SERVICE_WORKER: ACTIVE) dist/assets의 해시 파일을 모두 precache한다. 아래 serviceWorkerPrecache에 지금 템플릿 빌드의 파일 수(assets), 첫 feature가 한 번 더하는 수(firstFeatureAssets), 기존 context에 feature 하나를 더할 때 느는 수(perFeatureAssets), 두 번째 context가 더하는 수(perContextAssets)가 있다. tests/unit/feature-shape-growth.test.ts가 unit 실행마다 Initial JavaScript와 같은 빌드로 잰다",
|
||||
"condition": "Initial JavaScript와 같은 빌드. 그 빌드는 Service Worker를 끈 것이라, 켠 빌드는 등록 코드의 파일만큼 더 많다",
|
||||
"notVerified": "feature가 몇 개까지 precache 자산 수 상한(src/contracts/service-worker.ts의 SERVICE_WORKER_BOUNDS.assets) 안에 드는지. 상한에서 assets와 firstFeatureAssets를 빼고 perFeatureAssets로 나눈 값이다(새 context마다 perContextAssets를 더한다). 상한과 precache 범위는 Service Worker 계약이다"
|
||||
},
|
||||
{
|
||||
"axis": "Routes",
|
||||
"verified": "feature 하나에 3개(list, detail, create). 충돌 없이 조합된다",
|
||||
@@ -44,5 +50,11 @@
|
||||
"firstFeatureGzipBytes": 6355,
|
||||
"perFeatureGzipBytes": 528,
|
||||
"perContextGzipBytes": 21
|
||||
},
|
||||
"serviceWorkerPrecache": {
|
||||
"assets": 24,
|
||||
"firstFeatureAssets": 14,
|
||||
"perFeatureAssets": 12,
|
||||
"perContextAssets": 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
|
||||
@@ -7,11 +7,13 @@ import {
|
||||
FEATURE_SHAPE_CEILINGS_PATH,
|
||||
FEATURES_PER_CONTEXT,
|
||||
initialJavascriptRecordDrift,
|
||||
measureInitialJavascriptCosts,
|
||||
measureFeatureShapeCosts,
|
||||
planShapeFeatures,
|
||||
precacheRecordDrift,
|
||||
SHAPE_FEATURE_COMMAND,
|
||||
shapeFeature,
|
||||
type InitialJavascriptCosts,
|
||||
type PrecacheCosts,
|
||||
} from "../../scripts/scale/measure-feature-shape-growth.ts";
|
||||
import { APP_MAX_CONTEXTS } from "../../src/apps/template-app/app-module.ts";
|
||||
|
||||
@@ -150,12 +152,23 @@ describe("feature-shape growth measurement (11-04)", () => {
|
||||
* hand, it went stale twice; it now has to match this build.
|
||||
*/
|
||||
it("bounds what one more feature and one more context add, and matches the record (15-01)", async () => {
|
||||
const measured = await measureInitialJavascriptCosts();
|
||||
const { initialJavascript: record } = JSON.parse(
|
||||
const { initialJavascript: measured, serviceWorkerPrecache: precache } =
|
||||
await measureFeatureShapeCosts();
|
||||
const { initialJavascript: record, serviceWorkerPrecache: precacheRecord } = JSON.parse(
|
||||
await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8"),
|
||||
) as { initialJavascript: InitialJavascriptCosts };
|
||||
) as { initialJavascript: InitialJavascriptCosts; serviceWorkerPrecache?: PrecacheCosts };
|
||||
const observed = `measured ${JSON.stringify(measured)}`;
|
||||
|
||||
// 1112/06-02. With the Service Worker on, each feature's lazy chunks are
|
||||
// precached too; the record says how many, so the feature count where
|
||||
// the precache asset bound comes is read, not guessed.
|
||||
expect(precache.perFeatureAssets, `precache ${JSON.stringify(precache)}`).toBeGreaterThan(0);
|
||||
expect(
|
||||
precacheRecord === undefined ? ["serviceWorkerPrecache: no record"] : precacheRecordDrift(precache, precacheRecord),
|
||||
`${FEATURE_SHAPE_CEILINGS_PATH} serviceWorkerPrecache is stale (measured ${JSON.stringify(precache)}); ` +
|
||||
"rewrite it with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write",
|
||||
).toEqual([]);
|
||||
|
||||
expect(measured.perFeatureGzipBytes, `one more feature in an existing context: ${observed}`)
|
||||
.toBeLessThanOrEqual(1_024);
|
||||
expect(measured.perContextGzipBytes, `one more context: ${observed}`)
|
||||
@@ -174,6 +187,15 @@ describe("feature-shape growth measurement (11-04)", () => {
|
||||
* record. Now a few hundred bytes are enough to fail: above the build id
|
||||
* spread (tens of bytes), below one feature.
|
||||
*/
|
||||
// 1112/06-02. File counts repeat exactly: any difference is a stale record.
|
||||
it("reports a precache record that differs from the build by one file", () => {
|
||||
const measured = { assets: 20, firstFeatureAssets: 12, perFeatureAssets: 9, perContextAssets: 1 };
|
||||
expect(precacheRecordDrift(measured, measured)).toEqual([]);
|
||||
expect(precacheRecordDrift({ ...measured, perFeatureAssets: 10 }, measured)).toEqual([
|
||||
"perFeatureAssets: record 9, build 10",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a record a few hundred bytes off the build, or a different file count", () => {
|
||||
const measured = {
|
||||
gzipBytes: 200_000,
|
||||
|
||||
@@ -4,7 +4,10 @@ import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { collectStaticAssets } from "../../scripts/generate-service-worker-assets.ts";
|
||||
import {
|
||||
collectStaticAssets,
|
||||
countPrecachedAssets,
|
||||
} from "../../scripts/generate-service-worker-assets.ts";
|
||||
import { SERVICE_WORKER_BOUNDS } from "../../src/contracts/service-worker.ts";
|
||||
|
||||
/**
|
||||
@@ -49,3 +52,20 @@ describe("Service Worker precache bounds", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// 1112/06-02. The feature-shape measurement counts what the worker would
|
||||
// precache with the same rule: hashed names under assets/ with a cacheable
|
||||
// type, the worker, the page and public files left out.
|
||||
describe("countPrecachedAssets", () => {
|
||||
it("counts the files collectStaticAssets precaches", async () => {
|
||||
const dist = await distWith(3);
|
||||
await writeFile(path.join(dist, "index.html"), "<html></html>");
|
||||
await writeFile(path.join(dist, "android-chrome-192x192.png"), "png");
|
||||
await writeFile(path.join(dist, "assets", "unhashed.js"), "x");
|
||||
await writeFile(path.join(dist, "assets", "notes-Abcdefgh.txt"), "x");
|
||||
|
||||
const { assets } = await collectStaticAssets(dist, "build-1", "release-1");
|
||||
expect(await countPrecachedAssets(dist)).toBe(assets.length);
|
||||
expect(assets).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user