@akanjs/devkit 3.3.0-rc.1 → 3.3.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +229 -2
  2. package/README.ko.md +3 -2
  3. package/README.md +3 -3
  4. package/akanApp/akanApp.host.test.ts +22 -5
  5. package/akanApp/akanApp.host.ts +46 -9
  6. package/akanApp/akanApp.host.wiring.test.ts +206 -2
  7. package/akanApp/devBackend.ts +3 -1
  8. package/akanApp/devBuilder.ts +5 -1
  9. package/akanApp/devStartTimeline.test.ts +115 -0
  10. package/akanApp/devStartTimeline.ts +69 -0
  11. package/akanConfig/akanConfig.test.ts +57 -8
  12. package/akanConfig/akanConfig.ts +12 -65
  13. package/akanConfig/dockerImage.ts +17 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/app/applicationBuildRunner.test.ts +49 -1
  16. package/app/applicationBuildRunner.ts +3 -1
  17. package/codeAgent/agent/CodeAgent.ts +36 -16
  18. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  19. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  20. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  21. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  22. package/codeAgent/agent/codeAgent.test.ts +62 -0
  23. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  24. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  25. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  26. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  27. package/codeAgent/skills/akan-page/SKILL.md +18 -13
  28. package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
  29. package/codeAgent/skills/akan-service/SKILL.md +2 -2
  30. package/docs/apiReference.test.ts +5 -0
  31. package/docs/apiReference.ts +7 -3
  32. package/docs/declarationReader.ts +28 -1
  33. package/executors/appExecutor.ts +35 -11
  34. package/executors/executors.test.ts +30 -3
  35. package/frontendBuild/buildCacheStamp.test.ts +42 -0
  36. package/frontendBuild/buildCacheStamp.ts +23 -0
  37. package/frontendBuild/buildRouteClient.test.ts +2 -7
  38. package/frontendBuild/clientEntryDiscovery.ts +2 -2
  39. package/frontendBuild/cssCandidateCache.test.ts +70 -1
  40. package/frontendBuild/cssCandidateCache.ts +17 -10
  41. package/frontendBuild/cssCompiler.test.ts +112 -0
  42. package/frontendBuild/cssCompiler.ts +41 -21
  43. package/frontendBuild/devBarrelImports.test.ts +30 -0
  44. package/frontendBuild/devBarrelImports.ts +2 -2
  45. package/frontendBuild/fontOptimizer.test.ts +144 -3
  46. package/frontendBuild/fontOptimizer.ts +103 -18
  47. package/frontendBuild/pagesBundleBuilder.ts +3 -1
  48. package/frontendBuild/plainStylesheet.test.ts +155 -0
  49. package/frontendBuild/plainStylesheet.ts +197 -0
  50. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  51. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  52. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
  53. package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
  54. package/guideline/agentAssets.test.ts +10 -0
  55. package/guideline/agentAssets.ts +52 -11
  56. package/incrementalBuilder/buildBatch.proc.ts +11 -10
  57. package/incrementalBuilder/buildBatchProtocol.ts +2 -1
  58. package/incrementalBuilder/builderBoot.ts +14 -7
  59. package/incrementalBuilder/builderChannel.ts +8 -2
  60. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  61. package/incrementalBuilder/builderLanes.ts +2 -2
  62. package/incrementalBuilder/builderWatch.ts +8 -8
  63. package/incrementalBuilder/csrRegistry.ts +4 -4
  64. package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
  65. package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
  66. package/incrementalBuilder/incrementalBuilder.proc.test.ts +41 -0
  67. package/incrementalBuilder/incrementalBuilder.proc.ts +9 -8
  68. package/incrementalBuilder/ssrRegistry.ts +6 -6
  69. package/index.ts +1 -1
  70. package/integration/renderAdmissionSoak.test.ts +99 -0
  71. package/integration/renderAdmissionSoak.ts +609 -0
  72. package/mobile/nativeConfig.test.ts +100 -0
  73. package/mobile/nativeConfig.ts +55 -16
  74. package/mobile/nativePublicEnv.ts +2 -1
  75. package/package.json +14 -169
  76. package/packageExports.test.ts +38 -24
  77. package/transforms/barrelAnalyzer.ts +2 -2
  78. package/transforms/transforms.test.ts +3 -3
  79. package/tunnel/createTunnel.test.ts +29 -8
  80. package/tunnel/createTunnel.ts +18 -11
  81. package/util/fileEditor.ts +1 -0
  82. package/util/fileSys.test.ts +13 -0
  83. package/util/fileSys.ts +2 -2
  84. package/util/selectModel.ts +1 -0
  85. package/workspace/getRelatedCnsts.ts +7 -0
@@ -0,0 +1,609 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { DevResourceProbe, type DevResourceProc } from "./devResourceProbe";
6
+
7
+ export type SoakMix = "cpu" | "io" | "mixed";
8
+ export type SoakKind = "cpu" | "io" | "hit";
9
+ export type SoakArrival = "burst" | "steady";
10
+ type SoakRole = "server" | "rsc" | "other";
11
+
12
+ export interface RenderAdmissionSoakOptions {
13
+ appName: string;
14
+ workspaceRoot: string;
15
+ cliEntry: string;
16
+ distDir: string;
17
+ port: number;
18
+ caps: number[];
19
+ mixes: SoakMix[];
20
+ runs: number;
21
+ seconds: number;
22
+ concurrency: number;
23
+ arrival: SoakArrival;
24
+ softNavigationPercent: number;
25
+ abortPercent: number;
26
+ maxQueue: string | null;
27
+ prepare: boolean;
28
+ logPath: string;
29
+ outPath: string | null;
30
+ }
31
+
32
+ interface SoakRequest {
33
+ kind: SoakKind;
34
+ soft: boolean;
35
+ url: string;
36
+ credentialed: boolean;
37
+ abortAfterMs: number | null;
38
+ }
39
+
40
+ interface SoakTally {
41
+ latencies: Record<SoakKind, number[]>;
42
+ documents: number[];
43
+ softNavigations: number[];
44
+ refused: number;
45
+ aborted: number;
46
+ failed: number;
47
+ }
48
+
49
+ interface SoakMemory {
50
+ workerRssMb: number;
51
+ serverRssMb: number;
52
+ workerHeapMb: number;
53
+ queueDepth: number;
54
+ inFlight: number;
55
+ }
56
+
57
+ interface SoakWait {
58
+ count: number;
59
+ sumSeconds: number;
60
+ buckets: Map<number, number>;
61
+ refusals: number;
62
+ }
63
+
64
+ export interface SoakRunResult {
65
+ cap: number;
66
+ mix: SoakMix;
67
+ run: number;
68
+ ok: number;
69
+ refused: number;
70
+ aborted: number;
71
+ failed: number;
72
+ throughput: number;
73
+ p50: number;
74
+ p95: number;
75
+ p99: number;
76
+ p50ByKind: Record<SoakKind, number | null>;
77
+ p50Document: number;
78
+ p50SoftNavigation: number;
79
+ waitMeanMs: number;
80
+ waitP95Ms: number;
81
+ refusals: number;
82
+ peakDepth: number;
83
+ peakInFlight: number;
84
+ peakWorkerRssMb: number;
85
+ workerRssGrowthMb: number;
86
+ peakServerRssMb: number;
87
+ workerHeapGrowthMb: number;
88
+ }
89
+
90
+ // Usage, from the workspace root: bun pkgs/@akanjs/devkit/integration/renderAdmissionSoak.ts <app> --prepare
91
+ // With a fixed number in flight (`--arrival=steady`) the mean latency is that number over the throughput whatever
92
+ // order renders run in; only rounds sent at once (`burst`) show what first come, first served does to the median.
93
+ // Every row is a fresh server: RSS only grows within a process, so a shared one would carry the last cap's peak.
94
+ export class RenderAdmissionSoak {
95
+ static readonly #pagePath = "soak/io";
96
+ static readonly #markerName = ".render-admission-soak.json";
97
+ static readonly #page = `import { page } from "akanjs/client";
98
+
99
+ export default page()
100
+ .search("ms", String)
101
+ .render(async ({ ms }) => {
102
+ const waitMs = Number(ms) || 50;
103
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
104
+ return (
105
+ <ul>
106
+ {Array.from({ length: 120 }, (_, index) => (
107
+ <li key={index}>{\`row \${index} of a page that waited \${waitMs} ms on its data\`}</li>
108
+ ))}
109
+ </ul>
110
+ );
111
+ });
112
+ `;
113
+ static readonly #shares: Record<SoakMix, Record<SoakKind, number>> = {
114
+ cpu: { cpu: 100, io: 0, hit: 0 },
115
+ io: { cpu: 0, io: 100, hit: 0 },
116
+ mixed: { cpu: 40, io: 30, hit: 30 },
117
+ };
118
+ static readonly #routeCount = 32;
119
+ static readonly #hotRouteCount = 8;
120
+ static readonly #reportIntervalMs = 250;
121
+
122
+ static parseArgs(argv: string[]): RenderAdmissionSoakOptions {
123
+ const { appName, args, num } = DevResourceProbe.parseArgMap(argv);
124
+ const workspaceRoot = args.get("root") ?? process.cwd();
125
+ const numbers = (key: string, fallback: number[]) =>
126
+ args.has(key)
127
+ ? (args.get(key) ?? "")
128
+ .split(",")
129
+ .map(Number)
130
+ .filter((value) => Number.isInteger(value) && value >= 0)
131
+ : fallback;
132
+ const mixes = (args.get("mixes") ?? "cpu,io,mixed")
133
+ .split(",")
134
+ .filter((mix): mix is SoakMix => mix in RenderAdmissionSoak.#shares);
135
+ return {
136
+ appName,
137
+ workspaceRoot,
138
+ cliEntry: args.get("cli") ?? "dist/pkgs/@akanjs/cli/index.js",
139
+ distDir: args.get("dist") ?? path.join(workspaceRoot, "dist", "apps", appName),
140
+ port: num("port", 8483),
141
+ caps: numbers("caps", [2, 4, 8, 16, 32, 0]),
142
+ mixes,
143
+ runs: num("runs", 3),
144
+ seconds: num("seconds", 12),
145
+ concurrency: num("concurrency", 32),
146
+ arrival: args.get("arrival") === "steady" ? "steady" : "burst",
147
+ softNavigationPercent: num("soft", 30),
148
+ abortPercent: num("aborts", 5),
149
+ maxQueue: args.get("queue") ?? null,
150
+ prepare: args.has("prepare"),
151
+ logPath: args.get("log") ?? path.join(os.tmpdir(), `akan-render-admission-soak-${appName}.log`),
152
+ outPath: args.get("out") ?? null,
153
+ };
154
+ }
155
+
156
+ readonly #options: RenderAdmissionSoakOptions;
157
+ readonly #statusToken = randomBytes(32).toString("hex");
158
+ #serverPid = 0;
159
+ #server: { kill: (signal: NodeJS.Signals) => void } | null = null;
160
+ #build: { kill: (signal: NodeJS.Signals) => void } | null = null;
161
+ #injected = false;
162
+
163
+ constructor(options: RenderAdmissionSoakOptions) {
164
+ this.#options = options;
165
+ }
166
+
167
+ get #origin(): string {
168
+ return `http://127.0.0.1:${this.#options.port}`;
169
+ }
170
+
171
+ static pageDirOf(workspaceRoot: string, appName: string): string {
172
+ return path.join(workspaceRoot, "apps", appName, "page", path.dirname(RenderAdmissionSoak.#pagePath));
173
+ }
174
+
175
+ //? The marker lists what this script wrote, so a `page/soak` an app owns is neither overwritten nor removed.
176
+ static injectPage(pageDir: string): void {
177
+ const marker = path.join(pageDir, RenderAdmissionSoak.#markerName);
178
+ if (fs.existsSync(pageDir) && !fs.existsSync(marker))
179
+ throw new Error(`${pageDir} already exists and this script did not create it; the soak page needs that name`);
180
+ RenderAdmissionSoak.removePage(pageDir);
181
+ const file = `${path.basename(RenderAdmissionSoak.#pagePath)}.tsx`;
182
+ fs.mkdirSync(pageDir, { recursive: true });
183
+ fs.writeFileSync(marker, JSON.stringify({ files: [file] }));
184
+ fs.writeFileSync(path.join(pageDir, file), RenderAdmissionSoak.#page);
185
+ }
186
+
187
+ static removePage(pageDir: string): void {
188
+ const marker = path.join(pageDir, RenderAdmissionSoak.#markerName);
189
+ if (!fs.existsSync(marker)) return;
190
+ const { files } = JSON.parse(fs.readFileSync(marker, "utf8")) as { files: string[] };
191
+ for (const file of files) fs.rmSync(path.join(pageDir, path.basename(file)), { force: true });
192
+ fs.rmSync(marker, { force: true });
193
+ if (fs.readdirSync(pageDir).length === 0) fs.rmdirSync(pageDir);
194
+ }
195
+
196
+ async run(): Promise<SoakRunResult[]> {
197
+ const stop = () => void this.#stop().finally(() => process.exit(130));
198
+ process.once("SIGINT", stop);
199
+ process.once("SIGTERM", stop);
200
+ try {
201
+ return await this.#measure();
202
+ } finally {
203
+ process.off("SIGINT", stop);
204
+ process.off("SIGTERM", stop);
205
+ }
206
+ }
207
+
208
+ async #stop(): Promise<void> {
209
+ this.#build?.kill("SIGTERM");
210
+ if (this.#injected) RenderAdmissionSoak.removePage(this.#pageDir);
211
+ if (this.#server) await DevResourceProbe.killTree(this.#server, () => this.#sampleTree());
212
+ }
213
+
214
+ get #pageDir(): string {
215
+ return RenderAdmissionSoak.pageDirOf(this.#options.workspaceRoot, this.#options.appName);
216
+ }
217
+
218
+ async #measure(): Promise<SoakRunResult[]> {
219
+ const { appName, distDir, caps, mixes, runs, outPath } = this.#options;
220
+ if (this.#options.prepare) await this.#prepare();
221
+ if (!fs.existsSync(path.join(distDir, "main.js")))
222
+ throw new Error(
223
+ `no built app at ${distDir} — run this with --prepare, which builds ${appName} with the soak page`,
224
+ );
225
+ const routes = await this.#routes();
226
+ console.info(
227
+ `[soak] app=${appName} arrival=${this.#options.arrival} caps=${caps.join(",")} mixes=${mixes.join(",")} runs=${runs} routes=${routes.docs.length}`,
228
+ );
229
+ const results: SoakRunResult[] = [];
230
+ for (let run = 1; run <= runs; run += 1)
231
+ for (const cap of caps)
232
+ for (const mix of mixes) {
233
+ const result = await this.#runOnce(cap, mix, run, routes);
234
+ results.push(result);
235
+ console.info(RenderAdmissionSoak.#line(result));
236
+ if (outPath) await Bun.write(outPath, JSON.stringify(results, null, 2));
237
+ }
238
+ console.info(`\n${RenderAdmissionSoak.summary(results, caps, mixes)}`);
239
+ return results;
240
+ }
241
+
242
+ async #prepare(): Promise<void> {
243
+ const { appName, workspaceRoot, cliEntry } = this.#options;
244
+ RenderAdmissionSoak.injectPage(this.#pageDir);
245
+ this.#injected = true;
246
+ try {
247
+ const build = Bun.spawn(["bun", cliEntry, "build", appName], {
248
+ cwd: workspaceRoot,
249
+ stdout: "inherit",
250
+ stderr: "inherit",
251
+ });
252
+ this.#build = build;
253
+ if ((await build.exited) !== 0) throw new Error(`akan build ${appName} failed`);
254
+ } finally {
255
+ this.#build = null;
256
+ RenderAdmissionSoak.removePage(this.#pageDir);
257
+ this.#injected = false;
258
+ }
259
+ }
260
+
261
+ async #routes(): Promise<{ docs: string[]; io: string }> {
262
+ const artifactDir = path.join(this.#options.distDir, ".akan", "artifact");
263
+ const seed = (await Bun.file(path.join(artifactDir, "route-seed-index.json")).json()) as {
264
+ entries: { routeId: string }[];
265
+ };
266
+ const artifact = (await Bun.file(path.join(artifactDir, "base-artifact.json")).json()) as {
267
+ i18n?: { defaultLocale?: string };
268
+ };
269
+ const locale = artifact.i18n?.defaultLocale ?? "en";
270
+ const urls = seed.entries
271
+ .map((entry) => entry.routeId.replace(/:lang\b/g, locale))
272
+ .filter((url) => !/[:[]/.test(url))
273
+ .sort((a, b) => a.localeCompare(b));
274
+ const io = urls.find((url) => url.endsWith(`/${RenderAdmissionSoak.#pagePath}`));
275
+ if (!io) throw new Error("the built app has no soak page — build it with --prepare");
276
+ const docs = urls.filter((url) => url !== io && url.split("/").length > 3);
277
+ return { docs: docs.slice(0, RenderAdmissionSoak.#routeCount), io };
278
+ }
279
+
280
+ async #runOnce(
281
+ cap: number,
282
+ mix: SoakMix,
283
+ run: number,
284
+ routes: { docs: string[]; io: string },
285
+ ): Promise<SoakRunResult> {
286
+ const server = this.#spawn(cap);
287
+ this.#serverPid = server.pid;
288
+ this.#server = server;
289
+ try {
290
+ if (!(await this.#waitForReady(120_000)))
291
+ throw new Error(`the server did not become ready within 120s — see ${this.#options.logPath}`);
292
+ await this.#warmUp(routes);
293
+ await Bun.sleep(RenderAdmissionSoak.#reportIntervalMs * 6);
294
+ const [baseline, waitBefore] = [await this.#memory(), await this.#wait()];
295
+ const peak = { ...baseline };
296
+ let sampling = true;
297
+ const sampler = (async () => {
298
+ while (sampling) {
299
+ const sample = await this.#memory();
300
+ for (const key of Object.keys(peak) as (keyof SoakMemory)[]) peak[key] = Math.max(peak[key], sample[key]);
301
+ await Bun.sleep(RenderAdmissionSoak.#reportIntervalMs);
302
+ }
303
+ })();
304
+ const startedAt = performance.now();
305
+ const tally = await this.#load(mix, run, routes);
306
+ const elapsedSeconds = (performance.now() - startedAt) / 1000;
307
+ sampling = false;
308
+ await sampler;
309
+ await Bun.sleep(RenderAdmissionSoak.#reportIntervalMs * 6);
310
+ const waitAfter = await this.#wait();
311
+ return RenderAdmissionSoak.#result({ cap, mix, run }, tally, elapsedSeconds, { baseline, peak }, [
312
+ waitBefore,
313
+ waitAfter,
314
+ ]);
315
+ } finally {
316
+ await DevResourceProbe.killTree(server, () => this.#sampleTree());
317
+ this.#server = null;
318
+ }
319
+ }
320
+
321
+ #spawn(cap: number) {
322
+ const { appName, distDir, port, logPath, maxQueue } = this.#options;
323
+ return Bun.spawn(["bun", "main.js"], {
324
+ cwd: distDir,
325
+ env: {
326
+ ...process.env,
327
+ NODE_ENV: "production",
328
+ USE_AKANJS_PKGS: "true",
329
+ AKAN_PUBLIC_APP_NAME: appName,
330
+ AKAN_PUBLIC_REPO_NAME: process.env.AKAN_PUBLIC_REPO_NAME ?? path.basename(this.#options.workspaceRoot),
331
+ AKAN_PUBLIC_SERVE_DOMAIN: process.env.AKAN_PUBLIC_SERVE_DOMAIN ?? "localhost",
332
+ AKAN_PUBLIC_ENV: "local",
333
+ AKAN_PUBLIC_OPERATION_MODE: "local",
334
+ PORT: String(port),
335
+ AKAN_STATUS_TOKEN: this.#statusToken,
336
+ AKAN_MEMORY_LOG_INTERVAL_MS: String(RenderAdmissionSoak.#reportIntervalMs),
337
+ AKAN_RSC_WORKER_MAX_CONCURRENCY: String(cap),
338
+ ...(maxQueue ? { AKAN_RSC_WORKER_MAX_QUEUE: maxQueue } : {}),
339
+ },
340
+ stdout: Bun.file(logPath),
341
+ stderr: Bun.file(logPath),
342
+ });
343
+ }
344
+
345
+ //? Route modules load on their first render and the stored pages have to exist before a hit can be measured.
346
+ async #warmUp(routes: { docs: string[]; io: string }): Promise<void> {
347
+ const visit = async (url: string, credentialed: boolean) => {
348
+ const response = await fetch(`${this.#origin}${url}`, { headers: credentialed ? { cookie: "soak=1" } : {} });
349
+ await response.arrayBuffer();
350
+ if (!response.ok) throw new Error(`warm-up of ${url} answered ${response.status}`);
351
+ };
352
+ for (const route of routes.docs) await visit(route, true);
353
+ await visit(`${routes.io}?ms=20`, true);
354
+ for (const route of routes.docs.slice(0, RenderAdmissionSoak.#hotRouteCount)) {
355
+ await visit(route, false);
356
+ await visit(RenderAdmissionSoak.#softNavigation(route), false);
357
+ }
358
+ }
359
+
360
+ static #softNavigation(url: string): string {
361
+ return `/__rsc?url=${encodeURIComponent(url)}`;
362
+ }
363
+
364
+ async #load(mix: SoakMix, run: number, routes: { docs: string[]; io: string }): Promise<SoakTally> {
365
+ const { seconds, concurrency } = this.#options;
366
+ const tally: SoakTally = {
367
+ latencies: { cpu: [], io: [], hit: [] },
368
+ documents: [],
369
+ softNavigations: [],
370
+ refused: 0,
371
+ aborted: 0,
372
+ failed: 0,
373
+ };
374
+ const random = RenderAdmissionSoak.#random(run * 7919 + mix.length);
375
+ const deadline = performance.now() + seconds * 1000;
376
+ const one = () => this.#request(this.#next(mix, routes, random), tally);
377
+ const client = async () => {
378
+ while (performance.now() < deadline) await one();
379
+ };
380
+ if (this.#options.arrival === "steady") await Promise.all(Array.from({ length: concurrency }, client));
381
+ else while (performance.now() < deadline) await Promise.all(Array.from({ length: concurrency }, one));
382
+ return tally;
383
+ }
384
+
385
+ #next(mix: SoakMix, routes: { docs: string[]; io: string }, random: () => number): SoakRequest {
386
+ const shares = RenderAdmissionSoak.#shares[mix];
387
+ const roll = random() * 100;
388
+ const kind: SoakKind = roll < shares.cpu ? "cpu" : roll < shares.cpu + shares.io ? "io" : "hit";
389
+ const pick = (list: string[]) => list[Math.floor(random() * list.length)] ?? "/";
390
+ const target =
391
+ kind === "io"
392
+ ? `${routes.io}?ms=${20 + Math.floor(random() * 181)}`
393
+ : pick(kind === "hit" ? routes.docs.slice(0, RenderAdmissionSoak.#hotRouteCount) : routes.docs);
394
+ const soft = random() * 100 < this.#options.softNavigationPercent;
395
+ const aborts = kind !== "hit" && random() * 100 < this.#options.abortPercent;
396
+ return {
397
+ kind,
398
+ soft,
399
+ url: soft ? RenderAdmissionSoak.#softNavigation(target) : target,
400
+ credentialed: kind !== "hit",
401
+ abortAfterMs: aborts ? 5 + Math.floor(random() * 55) : null,
402
+ };
403
+ }
404
+
405
+ async #request(request: SoakRequest, tally: SoakTally): Promise<void> {
406
+ const startedAt = performance.now();
407
+ try {
408
+ const response = await fetch(`${this.#origin}${request.url}`, {
409
+ headers: request.credentialed ? { cookie: "soak=1" } : {},
410
+ signal: AbortSignal.timeout(request.abortAfterMs ?? 60_000),
411
+ });
412
+ await response.arrayBuffer();
413
+ const elapsed = performance.now() - startedAt;
414
+ if (response.ok) {
415
+ tally.latencies[request.kind].push(elapsed);
416
+ (request.soft ? tally.softNavigations : tally.documents).push(elapsed);
417
+ } else if (response.status === 503) tally.refused += 1;
418
+ else tally.failed += 1;
419
+ } catch {
420
+ if (request.abortAfterMs === null) tally.failed += 1;
421
+ else tally.aborted += 1;
422
+ }
423
+ }
424
+
425
+ static #random(seed: number): () => number {
426
+ let state = seed >>> 0;
427
+ return () => {
428
+ state = (state + 0x6d2b79f5) >>> 0;
429
+ let mixed = Math.imul(state ^ (state >>> 15), state | 1);
430
+ mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61);
431
+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
432
+ };
433
+ }
434
+
435
+ static #result(
436
+ row: { cap: number; mix: SoakMix; run: number },
437
+ tally: SoakTally,
438
+ elapsedSeconds: number,
439
+ memory: { baseline: SoakMemory; peak: SoakMemory },
440
+ [before, after]: [SoakWait, SoakWait],
441
+ ): SoakRunResult {
442
+ const kinds: SoakKind[] = ["cpu", "io", "hit"];
443
+ const all = kinds.flatMap((kind) => tally.latencies[kind]).sort((a, b) => a - b);
444
+ const at = (sorted: number[], share: number) =>
445
+ sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * share))] ?? 0;
446
+ const round = (value: number) => Math.round(value * 10) / 10;
447
+ const median = (values: number[]) =>
448
+ round(
449
+ at(
450
+ [...values].sort((a, b) => a - b),
451
+ 0.5,
452
+ ),
453
+ );
454
+ const waited = after.count - before.count;
455
+ const p95Bound = [...after.buckets.keys()]
456
+ .sort((a, b) => a - b)
457
+ .find((bound) => (after.buckets.get(bound) ?? 0) - (before.buckets.get(bound) ?? 0) >= waited * 0.95);
458
+ return {
459
+ ...row,
460
+ ok: all.length,
461
+ refused: tally.refused,
462
+ aborted: tally.aborted,
463
+ failed: tally.failed,
464
+ throughput: round(all.length / elapsedSeconds),
465
+ p50: round(at(all, 0.5)),
466
+ p95: round(at(all, 0.95)),
467
+ p99: round(at(all, 0.99)),
468
+ p50ByKind: Object.fromEntries(
469
+ kinds.map((kind) => [kind, tally.latencies[kind].length ? median(tally.latencies[kind]) : null]),
470
+ ) as Record<SoakKind, number | null>,
471
+ p50Document: median(tally.documents),
472
+ p50SoftNavigation: median(tally.softNavigations),
473
+ waitMeanMs: waited > 0 ? round(((after.sumSeconds - before.sumSeconds) / waited) * 1000) : 0,
474
+ waitP95Ms: waited > 0 && p95Bound !== undefined && Number.isFinite(p95Bound) ? p95Bound * 1000 : 0,
475
+ refusals: after.refusals - before.refusals,
476
+ peakDepth: memory.peak.queueDepth,
477
+ peakInFlight: memory.peak.inFlight,
478
+ peakWorkerRssMb: round(memory.peak.workerRssMb),
479
+ workerRssGrowthMb: round(memory.peak.workerRssMb - memory.baseline.workerRssMb),
480
+ peakServerRssMb: round(memory.peak.serverRssMb),
481
+ workerHeapGrowthMb: round(memory.peak.workerHeapMb - memory.baseline.workerHeapMb),
482
+ };
483
+ }
484
+
485
+ static #line(result: SoakRunResult): string {
486
+ return (
487
+ `[soak] run=${result.run} cap=${result.cap || "off"} mix=${result.mix}: ${result.throughput} req/s ` +
488
+ `p50=${result.p50} (document ${result.p50Document}, soft ${result.p50SoftNavigation}) p95=${result.p95} ` +
489
+ `p99=${result.p99}ms wait=${result.waitMeanMs}ms(p95<=${result.waitP95Ms}) ` +
490
+ `ok=${result.ok} 503=${result.refused} aborted=${result.aborted} failed=${result.failed} ` +
491
+ `depth<=${result.peakDepth} inFlight<=${result.peakInFlight} rscRss=${result.peakWorkerRssMb}MB ` +
492
+ `(+${result.workerRssGrowthMb}) rscHeap=+${result.workerHeapGrowthMb}MB`
493
+ );
494
+ }
495
+
496
+ static summary(results: SoakRunResult[], caps: number[], mixes: SoakMix[]): string {
497
+ const spread = (values: number[]) => {
498
+ const sorted = [...values].sort((a, b) => a - b);
499
+ const median = sorted[Math.floor(sorted.length / 2)] ?? 0;
500
+ return `${median} (${sorted[0] ?? 0}–${sorted.at(-1) ?? 0})`;
501
+ };
502
+ const lines = [
503
+ "| mix | cap | req/s | p50 ms | document p50 | soft p50 | p95 ms | p99 ms | wait ms | 503 | rsc peak RSS MB | rsc heap growth MB |",
504
+ "|---|---|---|---|---|---|---|---|---|---|---|---|",
505
+ ];
506
+ for (const mix of mixes)
507
+ for (const cap of caps) {
508
+ const rows = results.filter((result) => result.mix === mix && result.cap === cap);
509
+ if (!rows.length) continue;
510
+ const column = (pick: (result: SoakRunResult) => number) => spread(rows.map(pick));
511
+ lines.push(
512
+ `| ${mix} | ${cap || "off"} | ${column((r) => r.throughput)} | ${column((r) => r.p50)} | ` +
513
+ `${column((r) => r.p50Document)} | ${column((r) => r.p50SoftNavigation)} | ${column((r) => r.p95)} | ` +
514
+ `${column((r) => r.p99)} | ${column((r) => r.waitMeanMs)} | ${column((r) => r.refused)} | ` +
515
+ `${column((r) => r.peakWorkerRssMb)} | ${column((r) => r.workerHeapGrowthMb)} |`,
516
+ );
517
+ }
518
+ return lines.join("\n");
519
+ }
520
+
521
+ async #memory(): Promise<SoakMemory> {
522
+ const procs = await this.#sampleTree();
523
+ const rss = (role: SoakRole) =>
524
+ procs.filter((proc) => proc.role === role).reduce((sum, proc) => sum + proc.rssMb, 0);
525
+ const report = await this.#report();
526
+ const gauge = (name: string) =>
527
+ report.families.find((family) => family.name === name)?.samples.reduce((sum, sample) => sum + sample.value, 0) ??
528
+ 0;
529
+ return {
530
+ workerRssMb: rss("rsc"),
531
+ serverRssMb: rss("server"),
532
+ workerHeapMb: report.workerHeapUsedBytes / 1024 / 1024,
533
+ queueDepth: gauge("akan_rsc_render_queue_depth"),
534
+ inFlight: gauge("akan_rsc_renders_in_flight"),
535
+ };
536
+ }
537
+
538
+ async #report(): Promise<{
539
+ workerHeapUsedBytes: number;
540
+ families: { name: string; samples: { value: number }[] }[];
541
+ }> {
542
+ try {
543
+ const response = await fetch(`${this.#origin}/_akan/app/metrics`, {
544
+ headers: { authorization: `Bearer ${this.#statusToken}` },
545
+ signal: AbortSignal.timeout(5_000),
546
+ });
547
+ const body = (await response.json()) as {
548
+ children?: { metrics?: Record<string, number> }[];
549
+ metricFamilies?: { name: string; samples: { value: number }[] }[];
550
+ };
551
+ const heap = (body.children ?? []).reduce(
552
+ (sum, child) => sum + Number(child.metrics?.rscWorkerHeapUsedBytes ?? 0),
553
+ 0,
554
+ );
555
+ return { workerHeapUsedBytes: heap, families: body.metricFamilies ?? [] };
556
+ } catch {
557
+ return { workerHeapUsedBytes: 0, families: [] };
558
+ }
559
+ }
560
+
561
+ async #wait(): Promise<SoakWait> {
562
+ const response = await fetch(`${this.#origin}/_akan/app/metrics`, {
563
+ headers: { authorization: `Bearer ${this.#statusToken}`, accept: "text/plain" },
564
+ signal: AbortSignal.timeout(5_000),
565
+ });
566
+ const wait: SoakWait = { count: 0, sumSeconds: 0, buckets: new Map(), refusals: 0 };
567
+ for (const line of (await response.text()).split("\n")) {
568
+ const match = /^(akan_rsc_render_[a-z_]+)(?:\{([^}]*)\})? (\S+)$/.exec(line);
569
+ if (!match) continue;
570
+ const [, name, labels = "", raw] = match;
571
+ const value = Number(raw);
572
+ if (name === "akan_rsc_render_queue_wait_seconds_count") wait.count += value;
573
+ else if (name === "akan_rsc_render_queue_wait_seconds_sum") wait.sumSeconds += value;
574
+ else if (name === "akan_rsc_render_refusals_total") wait.refusals += value;
575
+ else if (name === "akan_rsc_render_queue_wait_seconds_bucket") {
576
+ const bound = /(?:^|,)le="([^"]+)"/.exec(labels)?.[1] ?? "+Inf";
577
+ const le = bound === "+Inf" ? Number.POSITIVE_INFINITY : Number(bound);
578
+ wait.buckets.set(le, (wait.buckets.get(le) ?? 0) + value);
579
+ }
580
+ }
581
+ return wait;
582
+ }
583
+
584
+ #sampleTree(): Promise<DevResourceProc<SoakRole>[]> {
585
+ return DevResourceProbe.sampleTree(this.#serverPid, (command) =>
586
+ /rscWorker\.js|react-server/.test(command) ? "rsc" : /\bmain\.js\b/.test(command) ? "server" : "other",
587
+ );
588
+ }
589
+
590
+ async #waitForReady(timeoutMs: number): Promise<boolean> {
591
+ const deadline = Date.now() + timeoutMs;
592
+ while (Date.now() < deadline) {
593
+ try {
594
+ const response = await fetch(`${this.#origin}/_akan/app/health`, {
595
+ headers: { authorization: `Bearer ${this.#statusToken}` },
596
+ signal: AbortSignal.timeout(2_000),
597
+ });
598
+ const body = (await response.json()) as { children?: { ready?: boolean }[] };
599
+ if (response.ok && body.children?.some((child) => child.ready)) return true;
600
+ } catch {
601
+ // The port is bound only once the server has booted.
602
+ }
603
+ await Bun.sleep(250);
604
+ }
605
+ return false;
606
+ }
607
+ }
608
+
609
+ if (import.meta.main) await new RenderAdmissionSoak(RenderAdmissionSoak.parseArgs(process.argv.slice(2))).run();