@akanjs/devkit 3.2.0-rc.18 → 3.2.0-rc.19
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.
- package/CHANGELOG.md +44 -4
- package/DEV_RUNTIME_KNOBS.md +4 -3
- package/akanApp/akanApp.host.test.ts +18 -2
- package/akanApp/akanApp.host.wiring.test.ts +723 -0
- package/akanApp/devIdleSuspend.test.ts +107 -20
- package/akanApp/devIdleSuspend.ts +31 -14
- package/akanApp/devIdleSuspend.watcher.test.ts +77 -0
- package/apiReport/apiReport.test.ts +29 -0
- package/apiReport/apiReportDiff.ts +35 -1
- package/app/applicationBuildReporter.ts +2 -49
- package/artifact/implicitRootLayoutRender.test.tsx +23 -3
- package/codeAgent/agent/akanSystemPrompt.ts +1 -1
- package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
- package/commandDecorators/command.ts +2 -1
- package/commandDecorators/commandBuilder.ts +1 -1
- package/commandDecorators/commandDecorators.test.ts +28 -4
- package/context/akanContext.ts +20 -527
- package/context/akanContextInspection.ts +296 -0
- package/context/akanMcpContract.ts +13 -253
- package/context/doctor/agentGuideCheck.ts +81 -0
- package/context/doctor/configLeftoverCheck.ts +35 -0
- package/context/doctor/doctorFindings.ts +70 -0
- package/context/doctor/generatedFreshness.ts +56 -0
- package/context/doctor/moduleShapeCheck.ts +88 -0
- package/context/doctor/recipeDuplicateCheck.ts +39 -0
- package/context/doctor/recipeIndexCheck.ts +87 -0
- package/context/doctor/rootShapeCheck.ts +55 -0
- package/context/doctor/workflowScope.ts +97 -0
- package/context/safeRead.ts +9 -0
- package/devkitUtils.test.ts +34 -0
- package/executors/executors.test.ts +1 -4
- package/executors/workspaceExecutor.ts +1 -2
- package/frontendBuild/hmrWatcher.stop.test.ts +36 -0
- package/frontendBuild/hmrWatcher.ts +2 -0
- package/incrementalBuilder/buildBatch.proc.ts +13 -3
- package/incrementalBuilder/buildBatchProtocol.ts +2 -0
- package/incrementalBuilder/buildBatchRunner.test.ts +61 -0
- package/incrementalBuilder/buildBatchRunner.ts +6 -3
- package/incrementalBuilder/builderBoot.ts +106 -0
- package/incrementalBuilder/builderBuildStatus.ts +23 -0
- package/incrementalBuilder/builderChannel.ts +11 -0
- package/incrementalBuilder/builderLanes.ts +157 -0
- package/incrementalBuilder/builderWatch.ts +213 -0
- package/incrementalBuilder/csrRegistry.ts +234 -0
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +92 -1
- package/incrementalBuilder/incrementalBuilder.proc.ts +80 -822
- package/incrementalBuilder/ssrRegistry.ts +278 -0
- package/integration/devStability.integration.test.ts +62 -56
- package/package.json +3 -3
- package/test/testHelpers.ts +36 -0
- package/util/errorReport.ts +66 -0
- package/workflow/constantSource.ts +187 -0
- package/workflow/dictionarySource.ts +184 -0
- package/workflow/executor.ts +5 -8
- package/workflow/fieldExpression.ts +153 -0
- package/workflow/fieldLabel.ts +61 -0
- package/workflow/fieldOrder.ts +117 -0
- package/workflow/fieldType.ts +2 -1
- package/workflow/keyRename.ts +1 -1
- package/workflow/moduleIndex.ts +1 -1
- package/workflow/modulePaths.ts +27 -0
- package/workflow/mutationScaffold.ts +7 -15
- package/workflow/mutationSource.ts +2 -1
- package/workflow/plan.ts +2 -1
- package/workflow/primitiveReport.ts +78 -0
- package/workflow/serviceSource.ts +33 -0
- package/workflow/signalSource.ts +96 -0
- package/workflow/source.ts +50 -1100
- package/workflow/sourceAst.ts +30 -0
- package/workflow/sourceImports.ts +105 -0
- package/workflow/sourceText.ts +13 -0
- package/workflow/templateSource.ts +30 -0
- package/workflow/testSource.ts +31 -0
- package/workflow/types.ts +1 -1
- package/workflow/uiPolicy.ts +1 -1
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { rm } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ApplicationBuildReporter } from "@akanjs/devkit/app/applicationBuildReporter";
|
|
4
|
+
import type { App } from "@akanjs/devkit/commandDecorators";
|
|
5
|
+
import type { ClientEntryDiscovery } from "@akanjs/devkit/frontendBuild/clientBuildTypes";
|
|
6
|
+
import { CsrDevPatcher } from "@akanjs/devkit/frontendBuild/csrDevPatcher";
|
|
7
|
+
import { ServerGraphFile } from "@akanjs/devkit/frontendBuild/serverGraphFile";
|
|
8
|
+
import { SsrDevBundler } from "@akanjs/devkit/frontendBuild/ssrDevBundler";
|
|
9
|
+
import type { Logger } from "akanjs/common";
|
|
10
|
+
import type { HmrTrace } from "akanjs/server";
|
|
11
|
+
import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
|
|
12
|
+
import type { BatchWork, BuildBatchResult } from "./buildBatchProtocol";
|
|
13
|
+
import { isCompileError, sendBuildStatus } from "./builderBuildStatus";
|
|
14
|
+
import { BuilderChannel } from "./builderChannel";
|
|
15
|
+
import type { BuilderLanes } from "./builderLanes";
|
|
16
|
+
|
|
17
|
+
interface SsrRegistryLinks {
|
|
18
|
+
generation: () => number;
|
|
19
|
+
discovery: () => ClientEntryDiscovery;
|
|
20
|
+
runBatch: (work: BatchWork) => Promise<BuildBatchResult>;
|
|
21
|
+
countDelegation: (registry: "csr" | "ssr", reason: string) => string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class SsrRegistry {
|
|
25
|
+
readonly #app: App;
|
|
26
|
+
readonly #logger: Logger;
|
|
27
|
+
readonly #lanes: BuilderLanes;
|
|
28
|
+
readonly #artifactDir: string;
|
|
29
|
+
readonly #links: SsrRegistryLinks;
|
|
30
|
+
#crashRetryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
31
|
+
readonly #crashRetryEntries = new Set<string>();
|
|
32
|
+
/** Where SSR pages load their client code from in dev; route builds bundle only its server half. */
|
|
33
|
+
#ssrBundler: SsrDevBundler;
|
|
34
|
+
/** Null when `AKAN_DEV_CSR_PATCHER=off`: every registry save then goes to a build worker. */
|
|
35
|
+
#ssrPatcher: CsrDevPatcher | null;
|
|
36
|
+
//* Serializes everything that writes ssr-dev: a save's patch (fast lane), a route build adding the entries it names,
|
|
37
|
+
//* a queued worker batch with the ssr need, and the boot build. Never held while awaiting the slow lane.
|
|
38
|
+
#ssrLock: Promise<void> = Promise.resolve();
|
|
39
|
+
/** The boot build of the SSR registry while it runs; it holds every entry the routes reach once it lands. */
|
|
40
|
+
#ssrArming: Promise<void> | null = null;
|
|
41
|
+
//* A registry build that failed on the user's code fails again until the code changes, so route builds do not retry
|
|
42
|
+
//* it; the next attempt that touches the registry (a save's patch, a worker batch) settles it. A worker that died
|
|
43
|
+
//* before reporting (an OOM kill) route builds do retry, at most every `#crashRetryMs`.
|
|
44
|
+
#ssrBroken = false;
|
|
45
|
+
#ssrCrashedAt: number | null = null;
|
|
46
|
+
static readonly #crashRetryMs = 10_000;
|
|
47
|
+
|
|
48
|
+
constructor(
|
|
49
|
+
app: App,
|
|
50
|
+
{ logger, lanes, artifactDir }: { logger: Logger; lanes: BuilderLanes; artifactDir: string },
|
|
51
|
+
links: SsrRegistryLinks,
|
|
52
|
+
) {
|
|
53
|
+
this.#app = app;
|
|
54
|
+
this.#logger = logger;
|
|
55
|
+
this.#lanes = lanes;
|
|
56
|
+
this.#artifactDir = artifactDir;
|
|
57
|
+
this.#links = links;
|
|
58
|
+
this.#ssrBundler = new SsrDevBundler(app, { discovery: links.discovery });
|
|
59
|
+
this.#ssrPatcher =
|
|
60
|
+
process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
get ssrPatcher(): CsrDevPatcher | null {
|
|
64
|
+
return this.#ssrPatcher;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// True when the save has to go to a build worker, as for CSR.
|
|
68
|
+
async patchSsr(generation: number, files: string[], trace: HmrTrace): Promise<boolean> {
|
|
69
|
+
const patcher = this.#ssrPatcher;
|
|
70
|
+
if (!patcher) return true;
|
|
71
|
+
const hold = await ServerGraphFile.touches(await ServerGraphFile.read(this.#artifactDir), files, (file) =>
|
|
72
|
+
ServerGraphFile.clientExportsOf(file),
|
|
73
|
+
);
|
|
74
|
+
//? Ahead of this save's own discovery job in the slow lane: which client entries a page still names decides which
|
|
75
|
+
//? pending roots this patch keeps.
|
|
76
|
+
this.#links.discovery().invalidate?.(files);
|
|
77
|
+
return await this.withSsrLock(
|
|
78
|
+
async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//* Adds the entries a route build names to the registry, since the tab requires them by id. A registry that cannot
|
|
83
|
+
//* take them fails no route build: the page answers, and its tab waits for the registry while the overlay says why.
|
|
84
|
+
async ensureSsrEntries(entries: string[], { crashRetry = false }: { crashRetry?: boolean } = {}): Promise<void> {
|
|
85
|
+
if (entries.length === 0) return;
|
|
86
|
+
//? The boot build takes every entry the routes reach, so the first page answers now and its tab waits for the
|
|
87
|
+
//? registry (boot.json) instead; whatever that build missed is added right after it lands.
|
|
88
|
+
const arming = this.#ssrArming;
|
|
89
|
+
if (arming) {
|
|
90
|
+
void this.#lanes.runBeside(
|
|
91
|
+
arming
|
|
92
|
+
.then(async () => await this.ensureSsrEntries(entries, { crashRetry }))
|
|
93
|
+
.catch(this.#lanes.slowLaneFailed("ssr-ensure")),
|
|
94
|
+
);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
await this.withSsrLock(async () => {
|
|
98
|
+
const patcher = this.#ssrPatcher;
|
|
99
|
+
// The builder's generation, not the request's: its build-status joins the saves' `ssr` ones.
|
|
100
|
+
const generation = this.#links.generation();
|
|
101
|
+
if (
|
|
102
|
+
patcher &&
|
|
103
|
+
!(await this.#runSsrPatcher(patcher, [], { roots: entries, onlyRoots: true, batchGeneration: generation }))
|
|
104
|
+
)
|
|
105
|
+
return;
|
|
106
|
+
//? Read, not compiled: with the patcher off, the save's own worker batch already built every entry.
|
|
107
|
+
if (!patcher && (await this.#ssrBundler.holds(entries))) return;
|
|
108
|
+
//? Not retried per route build: the save that fixes the error rebuilds it, where each route build retrying held
|
|
109
|
+
//? the SSR lock that save's patch waits on.
|
|
110
|
+
if (this.#ssrBroken) return;
|
|
111
|
+
if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < SsrRegistry.#crashRetryMs) {
|
|
112
|
+
//? Handed over just now with nothing run for them: the retry must find them to hand over again.
|
|
113
|
+
patcher?.releaseHandedOver();
|
|
114
|
+
this.#retryAfterCrash(this.#ssrCrashedAt, entries);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
await this.#runSsrWorker(generation).catch((err: unknown) => {
|
|
118
|
+
this.#logger.error(
|
|
119
|
+
`ssr-registry could not take a route's entries; the save that fixes it rebuilds it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
|
|
120
|
+
);
|
|
121
|
+
});
|
|
122
|
+
//? A worker that died took these entries with it and left them pending nowhere: they are tried once more after the
|
|
123
|
+
//? crash window, but a retry that crashes again waits for the next route build or save.
|
|
124
|
+
if (this.#ssrCrashedAt !== null && !crashRetry) this.#retryAfterCrash(this.#ssrCrashedAt, entries);
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
//? Once the crash window closes, for the entries skipped in it: later route builds may name none (the first one
|
|
129
|
+
//? announced every entry to the route cache), so without this a tab could wait on boot.json until the next save.
|
|
130
|
+
#retryAfterCrash(crashedAt: number, entries: string[]): void {
|
|
131
|
+
for (const entry of entries) this.#crashRetryEntries.add(entry);
|
|
132
|
+
if (this.#crashRetryTimer) return;
|
|
133
|
+
const timer = setTimeout(
|
|
134
|
+
() => {
|
|
135
|
+
this.#crashRetryTimer = null;
|
|
136
|
+
const retried = [...this.#crashRetryEntries];
|
|
137
|
+
this.#crashRetryEntries.clear();
|
|
138
|
+
if (this.#lanes.shuttingDown || retried.length === 0) return;
|
|
139
|
+
void this.#lanes
|
|
140
|
+
.runBeside(this.ensureSsrEntries(retried, { crashRetry: true }))
|
|
141
|
+
.catch(this.#lanes.slowLaneFailed("ssr-crash-retry"));
|
|
142
|
+
},
|
|
143
|
+
Math.max(0, crashedAt + SsrRegistry.#crashRetryMs - Date.now()),
|
|
144
|
+
);
|
|
145
|
+
timer.unref?.();
|
|
146
|
+
this.#crashRetryTimer = timer;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
//* The boot build of the SSR registry runs beside the slow lane, holding only the SSR lock: the first page's route
|
|
150
|
+
//* build bundles meanwhile instead of queueing behind it (on apps/akan it cost the first page about a second).
|
|
151
|
+
async armSsrRegistry(): Promise<void> {
|
|
152
|
+
//? `AKAN_DEV_SSR_ARM_DELAY_MS` is a test hook: an E2E has a tab reconnect before the boot build has run.
|
|
153
|
+
const delayMs = Number(process.env.AKAN_DEV_SSR_ARM_DELAY_MS);
|
|
154
|
+
if (Number.isInteger(delayMs) && delayMs > 0) await Bun.sleep(delayMs);
|
|
155
|
+
const arm = async () =>
|
|
156
|
+
await this.withSsrLock(async () => {
|
|
157
|
+
const generation = this.#links.generation();
|
|
158
|
+
if (this.#ssrPatcher && !(await this.#runSsrPatcher(this.#ssrPatcher, [], { batchGeneration: generation })))
|
|
159
|
+
return;
|
|
160
|
+
await this.#runSsrWorker(generation);
|
|
161
|
+
}).catch((err: unknown) => {
|
|
162
|
+
this.#logger.error(
|
|
163
|
+
`ssr-registry boot build failed; the next save retries it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
|
|
164
|
+
);
|
|
165
|
+
});
|
|
166
|
+
const arming = this.#lanes.runBeside(
|
|
167
|
+
(async () => {
|
|
168
|
+
await arm();
|
|
169
|
+
//? A boot build whose worker was killed (a small container's OOM) is tried once more before `boot-armed` lets
|
|
170
|
+
//? the next app boot: retried after that, the two biggest workers of a boot would run side by side.
|
|
171
|
+
const crashedAt = this.#ssrCrashedAt;
|
|
172
|
+
if (crashedAt === null) return;
|
|
173
|
+
while (!this.#lanes.shuttingDown && Date.now() < crashedAt + SsrRegistry.#crashRetryMs) await Bun.sleep(250);
|
|
174
|
+
if (!this.#lanes.shuttingDown) await arm();
|
|
175
|
+
})(),
|
|
176
|
+
);
|
|
177
|
+
this.#ssrArming = arming;
|
|
178
|
+
await arming;
|
|
179
|
+
this.#ssrArming = null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async withSsrLock<T>(fn: () => Promise<T>): Promise<T> {
|
|
183
|
+
const run = this.#ssrLock.then(fn, fn);
|
|
184
|
+
this.#ssrLock = run.then(
|
|
185
|
+
() => undefined,
|
|
186
|
+
() => undefined,
|
|
187
|
+
);
|
|
188
|
+
return await run;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Runs the worker directly, under the SSR lock its callers hold: queueing it could wait on a batch that waits on them.
|
|
192
|
+
async #runSsrWorker(generation: number): Promise<void> {
|
|
193
|
+
let result: BuildBatchResult;
|
|
194
|
+
try {
|
|
195
|
+
result = await this.#links.runBatch({ generation, needs: ["ssr"], changedFiles: [] });
|
|
196
|
+
} finally {
|
|
197
|
+
this.#ssrPatcher?.forget();
|
|
198
|
+
}
|
|
199
|
+
this.noteSsrWorker(result);
|
|
200
|
+
if (result.errors.ssr) throw new Error(result.errors.ssr);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
noteSsrWorker(result: BuildBatchResult): void {
|
|
204
|
+
const crashed = !!result.crashed && (result.crashedNeeds ?? ["ssr"]).includes("ssr");
|
|
205
|
+
this.#ssrBroken = !!result.errors.ssr && !crashed;
|
|
206
|
+
this.#ssrCrashedAt = crashed ? Date.now() : null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async #runSsrPatcher(
|
|
210
|
+
patcher: CsrDevPatcher,
|
|
211
|
+
files: string[],
|
|
212
|
+
{
|
|
213
|
+
roots,
|
|
214
|
+
onlyRoots,
|
|
215
|
+
trace,
|
|
216
|
+
hold,
|
|
217
|
+
batchGeneration,
|
|
218
|
+
}: { roots?: string[]; onlyRoots?: boolean; trace?: HmrTrace; hold?: boolean; batchGeneration?: number } = {},
|
|
219
|
+
): Promise<boolean> {
|
|
220
|
+
const started = Date.now();
|
|
221
|
+
const marker = path.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER);
|
|
222
|
+
await Bun.write(marker, String(process.pid));
|
|
223
|
+
try {
|
|
224
|
+
const result = await patcher.update(files, {
|
|
225
|
+
roots,
|
|
226
|
+
onlyRoots,
|
|
227
|
+
announce: (update) => {
|
|
228
|
+
const now = Date.now();
|
|
229
|
+
BuilderChannel.emit({
|
|
230
|
+
type: "ssr-updated",
|
|
231
|
+
data: {
|
|
232
|
+
generation: update.generation,
|
|
233
|
+
reload: update.reload,
|
|
234
|
+
reason: update.reason,
|
|
235
|
+
patchUrl: update.patchUrl,
|
|
236
|
+
changedIds: update.changedIds,
|
|
237
|
+
...(trace ? { trace: { ...trace, patchAt: now, sentAt: now } } : {}),
|
|
238
|
+
...(hold ? { hold } : {}),
|
|
239
|
+
...(batchGeneration !== undefined ? { batchGeneration } : {}),
|
|
240
|
+
...(update.epoch !== undefined ? { epoch: update.epoch } : {}),
|
|
241
|
+
...(update.first ? { first: true } : {}),
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
if (result.kind === "delegate") {
|
|
247
|
+
this.#logger.verbose(
|
|
248
|
+
`ssr-patch handed to a build worker (${this.#links.countDelegation("ssr", result.reason)}): ${result.reason}`,
|
|
249
|
+
);
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
//? A route build's check reports only a failure: it compiles the roots the registry lacks and nothing else, so
|
|
253
|
+
//? its ok, of the builder's current generation, would read as the fix of a save that broke something else.
|
|
254
|
+
if (!onlyRoots) {
|
|
255
|
+
this.#ssrBroken = false;
|
|
256
|
+
this.#ssrCrashedAt = null;
|
|
257
|
+
sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
|
|
258
|
+
}
|
|
259
|
+
this.#logger.verbose(
|
|
260
|
+
result.kind === "unchanged"
|
|
261
|
+
? `ssr-patch unchanged (${Date.now() - started}ms)`
|
|
262
|
+
: `ssr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`,
|
|
263
|
+
);
|
|
264
|
+
return false;
|
|
265
|
+
} catch (err) {
|
|
266
|
+
const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
|
|
267
|
+
if (isCompileError(err)) {
|
|
268
|
+
sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
this.#logger.verbose(`ssr-patch threw; a build worker takes it: ${message}`);
|
|
272
|
+
patcher.forget();
|
|
273
|
+
return true;
|
|
274
|
+
} finally {
|
|
275
|
+
await rm(marker, { force: true });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
|
|
2
|
+
import { rm } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
2
4
|
import { AkanAppHost } from "../akanApp";
|
|
3
5
|
import { DevGeneratedIndexSync } from "../frontendBuild";
|
|
6
|
+
import { tempDirs } from "../test/testHelpers";
|
|
4
7
|
import { DevStabilityHarness, type DevStabilityHmrProbe } from "./devStabilityHarness.fixture";
|
|
5
8
|
|
|
6
9
|
const integrationEnabled = process.env.AKAN_DEV_STABILITY_INTEGRATION === "1";
|
|
7
10
|
// Contention pushes a cold dev-server boot from ~3s to nearly a minute; 120s ran out mid-restart.
|
|
8
11
|
const INTEGRATION_TIMEOUT_MS = 180_000;
|
|
12
|
+
const WAIT_MS = 90_000;
|
|
9
13
|
const MB = 1024 * 1024;
|
|
10
14
|
const harnesses: DevStabilityHarness[] = [];
|
|
15
|
+
const tempDir = tempDirs("akan-builder-gate-");
|
|
11
16
|
|
|
12
17
|
const integrationTest = (name: string, fn: () => Promise<void>): void => {
|
|
13
18
|
if (integrationEnabled) test(name, fn, INTEGRATION_TIMEOUT_MS);
|
|
@@ -193,12 +198,7 @@ describe("dev stability integration harness", () => {
|
|
|
193
198
|
const harness = await createHarness();
|
|
194
199
|
const host = await harness.startHost();
|
|
195
200
|
const hmr = await harness.tryConnectHmrProbe();
|
|
196
|
-
|
|
197
|
-
if (!initialHtml) {
|
|
198
|
-
expect(host.proc.killed).toBe(false);
|
|
199
|
-
hmr?.close();
|
|
200
|
-
return;
|
|
201
|
-
}
|
|
201
|
+
await harness.waitForHttpText("initial-client-marker", WAIT_MS);
|
|
202
202
|
const hmrMark = hmr?.mark() ?? 0;
|
|
203
203
|
|
|
204
204
|
const { mark } = await harness.editUntilSeen(
|
|
@@ -228,12 +228,7 @@ describe("dev stability integration harness", () => {
|
|
|
228
228
|
const harness = await createHarness();
|
|
229
229
|
const host = await harness.startHost();
|
|
230
230
|
const hmr = await harness.tryConnectHmrProbe();
|
|
231
|
-
|
|
232
|
-
if (!initialHtml) {
|
|
233
|
-
expect(host.proc.killed).toBe(false);
|
|
234
|
-
hmr?.close();
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
231
|
+
await harness.waitForHttpText("initial-shared-marker", WAIT_MS);
|
|
237
232
|
const { mark, evidence } = await harness.editUntilSeen(
|
|
238
233
|
host,
|
|
239
234
|
(attempt) => harness.replaceText("common/marker.ts", /"[^"]*"/, `"updated-shared-marker-${attempt}"`),
|
|
@@ -251,12 +246,7 @@ describe("dev stability integration harness", () => {
|
|
|
251
246
|
const harness = await createHarness();
|
|
252
247
|
const host = await harness.startHost();
|
|
253
248
|
const hmr = await harness.tryConnectHmrProbe();
|
|
254
|
-
|
|
255
|
-
if (!initialHtml) {
|
|
256
|
-
expect(host.proc.killed).toBe(false);
|
|
257
|
-
hmr?.close();
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
249
|
+
await harness.waitForHttpText("initial-shared-marker", WAIT_MS);
|
|
260
250
|
const { mark } = await harness.editUntilSeen(
|
|
261
251
|
host,
|
|
262
252
|
(attempt) =>
|
|
@@ -287,11 +277,7 @@ export const dictionary = serviceDictionary(["en", "ko"])
|
|
|
287
277
|
integrationTest("config edits restart the dev host and keep serving", async () => {
|
|
288
278
|
const harness = await createHarness();
|
|
289
279
|
const host = await harness.startHost();
|
|
290
|
-
|
|
291
|
-
if (!initialHtml) {
|
|
292
|
-
expect(host.proc.killed).toBe(false);
|
|
293
|
-
return;
|
|
294
|
-
}
|
|
280
|
+
await harness.waitForHttpText("initial-shared-marker", WAIT_MS);
|
|
295
281
|
const { mark } = await harness.editUntilSeen(
|
|
296
282
|
host,
|
|
297
283
|
(attempt) =>
|
|
@@ -318,12 +304,7 @@ export default config;
|
|
|
318
304
|
const harness = await createHarness();
|
|
319
305
|
const host = await harness.startHost();
|
|
320
306
|
const hmr = await harness.tryConnectHmrProbe();
|
|
321
|
-
|
|
322
|
-
if (!initialHtml) {
|
|
323
|
-
expect(host.proc.killed).toBe(false);
|
|
324
|
-
hmr?.close();
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
307
|
+
await harness.waitForHttpText("initial-client-marker", WAIT_MS);
|
|
327
308
|
const failureHmrMark = hmr?.mark() ?? 0;
|
|
328
309
|
|
|
329
310
|
const { mark: failureMark } = await harness.editUntilSeen(host, (attempt) =>
|
|
@@ -495,7 +476,6 @@ export class FixtureService extends serve("fixture" as const, { serverMode: "bat
|
|
|
495
476
|
// not parallel-safe: run this block alone on an idle machine (`-t "dev resource budgets"`), never loosen it.
|
|
496
477
|
describe("dev resource budgets", () => {
|
|
497
478
|
const BOOT_MS = 150_000;
|
|
498
|
-
const WAIT_MS = 90_000;
|
|
499
479
|
// ~6x the measured 260-516ms per save: catches a path that got slower by a factor, not jitter.
|
|
500
480
|
const SAVE_LATENCY_BUDGET_MS = 3_000;
|
|
501
481
|
const budgetTest = (name: string, fn: () => Promise<void>): void => {
|
|
@@ -630,31 +610,50 @@ describe("dev resource budgets", () => {
|
|
|
630
610
|
// throttled), never disabled for the session. Whether it is back over depends on the machine's allocator, so the
|
|
631
611
|
// warning is asserted only when it is; the decision itself is unit-tested (devHostPolicy).
|
|
632
612
|
const settledFrom = host.markLog();
|
|
633
|
-
|
|
613
|
+
const armed = /\[builder-recycle\] armed/;
|
|
614
|
+
const settleOutcome = /recycling builder pid=\d+|\[builder-recycle\] (?:skipped|settle check abandoned)/;
|
|
615
|
+
const answered = () =>
|
|
616
|
+
/ceiling costs about one boot build per interval/.test(host.logs.join("").slice(start)) ||
|
|
617
|
+
armed.test(host.logs.join("").slice(settledFrom)) ||
|
|
618
|
+
settleOutcome.test(host.logs.join("").slice(settledFrom));
|
|
619
|
+
let deadline = Number.POSITIVE_INFINITY;
|
|
620
|
+
for (let i = 1; ; i++) {
|
|
634
621
|
const { mark } = await harness.editUntilSeen(host, (attempt) =>
|
|
635
622
|
harness.replaceText("ui/ClientMarker.tsx", /marker(-[\w-]+)?/, `marker-settled-${i}-${attempt}`),
|
|
636
623
|
);
|
|
637
|
-
|
|
624
|
+
//? The builder reports its rss to the host only once idle, which is after `pages-rebundle ok`.
|
|
625
|
+
await host.waitForLogSince(mark, /\[work-queue\] batch finished/, WAIT_MS);
|
|
626
|
+
if (i < 3) continue;
|
|
627
|
+
if (i === 3) deadline = performance.now() + WAIT_MS;
|
|
628
|
+
const settled = await DevStabilityHarness.builderProcess(host.proc.pid);
|
|
629
|
+
//? Read as the host reads it: on macOS `ps` also counts the pages the builder freed.
|
|
630
|
+
const settledRss = settled ? await AkanAppHost.readProcessRssBytes(settled.pid) : null;
|
|
631
|
+
//? The host is silent on a report under the ceiling and on a first one over it: only another save asks again.
|
|
632
|
+
if (answered() || (settledRss ?? 0) < CEILING_MB * MB) break;
|
|
633
|
+
if (performance.now() > deadline)
|
|
634
|
+
throw new Error(
|
|
635
|
+
`The builder stayed over the ${CEILING_MB}MiB ceiling (${Math.round((settledRss ?? 0) / MB)}MiB) for ${i} saves and the host never answered`,
|
|
636
|
+
);
|
|
638
637
|
}
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
const warned = /ceiling costs about one boot build per interval/.test(host.logs.join("").slice(start));
|
|
643
|
-
//? Past the interval (a slow machine) the next report recycles instead of warning: either answer settles it.
|
|
644
|
-
if ((settledRss ?? 0) >= CEILING_MB * MB && !warned)
|
|
645
|
-
await host.waitForLogSince(
|
|
646
|
-
settledFrom,
|
|
647
|
-
/ceiling costs about one boot build per interval|recycling builder pid=\d+|skipped: the builder fell to/,
|
|
648
|
-
WAIT_MS,
|
|
649
|
-
);
|
|
638
|
+
//? Past the interval (a slow machine) the host arms a recycle instead, and answers once its settle hold ends.
|
|
639
|
+
if (armed.test(host.logs.join("").slice(settledFrom)))
|
|
640
|
+
await host.waitForLogSince(settledFrom, settleOutcome, WAIT_MS);
|
|
650
641
|
expect(host.logs.join("").slice(start)).not.toMatch(/no longer enforcing it this session/);
|
|
651
642
|
});
|
|
652
643
|
|
|
653
644
|
budgetTest("serves a page requested while the builder is being replaced", async () => {
|
|
654
645
|
const harness = await createHarness();
|
|
655
|
-
|
|
646
|
+
// Outside the app, whose watcher would take a write to the gate for a save.
|
|
647
|
+
const readyGate = path.join(await tempDir(), "ready");
|
|
648
|
+
await Bun.write(readyGate, "");
|
|
649
|
+
const host = await harness.startHost({
|
|
650
|
+
timeoutMs: BOOT_MS,
|
|
651
|
+
env: { AKAN_BUILDER_MAX_RSS_MB: String(CEILING_MB), AKAN_DEV_BUILDER_READY_GATE: readyGate },
|
|
652
|
+
});
|
|
656
653
|
const port = await harness.resolvePort();
|
|
657
654
|
await harness.waitForHttpText("initial-client-marker", WAIT_MS);
|
|
655
|
+
// Shut from here on: the replacement stays between its spawn and its ready until the gate opens again.
|
|
656
|
+
await rm(readyGate);
|
|
658
657
|
|
|
659
658
|
const start = host.markLog();
|
|
660
659
|
// One save both evicts the route's cached client entries and arms the recycle.
|
|
@@ -670,28 +669,35 @@ describe("dev resource budgets", () => {
|
|
|
670
669
|
async (response) => ({ status: response.status, html: await response.text() }),
|
|
671
670
|
);
|
|
672
671
|
|
|
673
|
-
// Anchored on the spawn: the replacement's boot build leaves a wide, known window rather than a race.
|
|
674
672
|
await host.waitForLogSince(start, /exiting for recycle/, WAIT_MS);
|
|
675
673
|
await host.waitForLogSince(start, /builder spawned pid=\d+ .*restart=1/, WAIT_MS);
|
|
676
674
|
|
|
677
|
-
const holdMark = host.markLog();
|
|
678
|
-
const startedAtMono = performance.now();
|
|
679
675
|
// Never requested before, so no route cache can answer it; it has to reach a builder that is not there yet.
|
|
680
|
-
const
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
676
|
+
const second = fetch(`http://127.0.0.1:${port}/second`, { signal: AbortSignal.timeout(WAIT_MS) }).then(
|
|
677
|
+
async (response) => ({ status: response.status, html: await response.text() }),
|
|
678
|
+
);
|
|
679
|
+
// Two waiting are the drain request and this one; with the gate shut, an earlier answer is a refusal.
|
|
680
|
+
const answeredUnheld = await Promise.race([
|
|
681
|
+
host
|
|
682
|
+
.waitForLogSince(start, /holding build-route until the builder is ready \(2 waiting\)/, WAIT_MS)
|
|
683
|
+
.then(() => null),
|
|
684
|
+
second.then((response) => response.status),
|
|
685
|
+
]);
|
|
686
|
+
expect(answeredUnheld).toBeNull();
|
|
687
|
+
await Bun.write(readyGate, "");
|
|
688
|
+
const held = await host.waitForLogSince(start, /holding build-route until the builder is ready \(2 waiting\)/);
|
|
689
|
+
const ready = await host.waitForLogSince(start, /builder ready after restart/, WAIT_MS);
|
|
690
|
+
expect(ready.index ?? -1).toBeGreaterThan(held.index ?? Number.POSITIVE_INFINITY);
|
|
691
|
+
|
|
692
|
+
const res = await second;
|
|
684
693
|
// Without the hold this is a 500 from the dev error page, which never retries on its own.
|
|
685
694
|
expect(res.status).toBe(200);
|
|
686
|
-
expect(html).toContain("marker-through-recycle");
|
|
687
|
-
expect(html).not.toContain("reload after the builder is ready");
|
|
688
|
-
// Proves the request reached the hold, rather than arriving after the replacement was already ready.
|
|
689
|
-
expect(host.logs.join("").slice(holdMark)).toMatch(/holding build-route until the builder is ready/);
|
|
695
|
+
expect(res.html).toContain("marker-through-recycle");
|
|
696
|
+
expect(res.html).not.toContain("reload after the builder is ready");
|
|
690
697
|
|
|
691
698
|
const drained = await drainRequest;
|
|
692
699
|
expect(drained.status).toBe(200);
|
|
693
700
|
expect(drained.html).toContain("marker-through-recycle");
|
|
694
|
-
console.info(`[restart-guard] page held ${heldMs}ms across the recycle, then rendered`);
|
|
695
701
|
});
|
|
696
702
|
|
|
697
703
|
budgetTest("keeps a save's round trip inside its budget", async () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@akanjs/devkit",
|
|
3
|
-
"version": "3.2.0-rc.
|
|
3
|
+
"version": "3.2.0-rc.19",
|
|
4
4
|
"sourceType": "module",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -205,7 +205,7 @@
|
|
|
205
205
|
"./*": "./*.ts"
|
|
206
206
|
},
|
|
207
207
|
"dependencies": {
|
|
208
|
-
"@akanjs/language": "3.2.0-rc.
|
|
208
|
+
"@akanjs/language": "3.2.0-rc.19",
|
|
209
209
|
"@earendil-works/pi-agent-core": "1.3.0",
|
|
210
210
|
"@earendil-works/pi-ai": "1.3.0",
|
|
211
211
|
"@earendil-works/pi-codemode": "1.3.0",
|
|
@@ -214,7 +214,7 @@
|
|
|
214
214
|
"@earendil-works/pi-tui": "1.3.0",
|
|
215
215
|
"@inquirer/prompts": "^8.7.3",
|
|
216
216
|
"@tailwindcss/node": "^4.3.3",
|
|
217
|
-
"akanjs": "3.2.0-rc.
|
|
217
|
+
"akanjs": "3.2.0-rc.19",
|
|
218
218
|
"chalk": "^6.0.1",
|
|
219
219
|
"commander": "^15.0.0",
|
|
220
220
|
"dayjs": "^1.11.23",
|
package/test/testHelpers.ts
CHANGED
|
@@ -129,6 +129,42 @@ export const writeJson = async (filePath: string, value: object) => {
|
|
|
129
129
|
await writeText(filePath, `${JSON.stringify(value, null, 2)}\n`);
|
|
130
130
|
};
|
|
131
131
|
|
|
132
|
+
export const heldMtimeIndex = () => {
|
|
133
|
+
const primes: PromiseWithResolvers<void>[] = [];
|
|
134
|
+
const scans: PromiseWithResolvers<string[]>[] = [];
|
|
135
|
+
class SourceMtimeIndex {
|
|
136
|
+
#primed = false;
|
|
137
|
+
readonly trackedFileCount = 0;
|
|
138
|
+
readonly coverageGaps: { path: string; code: string }[] = [];
|
|
139
|
+
readonly hasUnsettledDirs = false;
|
|
140
|
+
get primed() {
|
|
141
|
+
return this.#primed;
|
|
142
|
+
}
|
|
143
|
+
async prime() {
|
|
144
|
+
const gate = Promise.withResolvers<void>();
|
|
145
|
+
primes.push(gate);
|
|
146
|
+
await gate.promise;
|
|
147
|
+
this.#primed = true;
|
|
148
|
+
}
|
|
149
|
+
collectChanges() {
|
|
150
|
+
const scan = Promise.withResolvers<string[]>();
|
|
151
|
+
scans.push(scan);
|
|
152
|
+
return scan.promise;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { SourceMtimeIndex, primes, scans };
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
//? FSEvents drops what lands before its stream is up, so the save repeats until the watcher has acted on one.
|
|
159
|
+
export const saveUntil = async (file: string, seen: () => boolean, timeoutMs = 5_000) => {
|
|
160
|
+
const deadline = Date.now() + timeoutMs;
|
|
161
|
+
for (let n = 0; !seen() && Date.now() < deadline; n++) {
|
|
162
|
+
await writeFile(file, `export const x = ${n};\n`);
|
|
163
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
164
|
+
}
|
|
165
|
+
return seen();
|
|
166
|
+
};
|
|
167
|
+
|
|
132
168
|
const repoRoot = path.resolve(import.meta.dir, "../../../..");
|
|
133
169
|
const biomeBin = path.join(repoRoot, "node_modules", ".bin", process.platform === "win32" ? "biome.exe" : "biome");
|
|
134
170
|
export const hasBiome = existsSync(biomeBin);
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
export class ErrorReport {
|
|
5
|
+
static readonly shownNestedErrors = 20;
|
|
6
|
+
|
|
7
|
+
static format(error: unknown, workspaceRoot = process.cwd()): string {
|
|
8
|
+
return ErrorReport.#format(error, workspaceRoot, []);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
static #format(error: unknown, workspaceRoot: string, ancestors: readonly unknown[]): string {
|
|
12
|
+
if (ancestors.includes(error)) return "[circular]";
|
|
13
|
+
const chain = [...ancestors, error];
|
|
14
|
+
if (error instanceof AggregateError) {
|
|
15
|
+
const shown = error.errors.slice(0, ErrorReport.shownNestedErrors);
|
|
16
|
+
const hidden = error.errors.length - shown.length;
|
|
17
|
+
const nestedMessages = [
|
|
18
|
+
...shown.map(
|
|
19
|
+
(nestedError, index) =>
|
|
20
|
+
ErrorReport.#format(nestedError, workspaceRoot, chain).trim() || `Unknown error ${index + 1}`,
|
|
21
|
+
),
|
|
22
|
+
...(hidden > 0 ? [`…and ${hidden} more`] : []),
|
|
23
|
+
]
|
|
24
|
+
.map((message) => message.replace(/^/gm, " "))
|
|
25
|
+
.join("\n");
|
|
26
|
+
const message = nestedMessages ? `${error.message}\n${nestedMessages}` : error.message;
|
|
27
|
+
return `${message}${ErrorReport.#causeOf(error, workspaceRoot, chain)}`;
|
|
28
|
+
}
|
|
29
|
+
if (error instanceof Error)
|
|
30
|
+
return `${ErrorReport.#withLocation(error.message, error, workspaceRoot)}${ErrorReport.#causeOf(error, workspaceRoot, chain)}`;
|
|
31
|
+
if (typeof error === "object" && error !== null && "message" in error)
|
|
32
|
+
return ErrorReport.#withLocation(String(error.message), error, workspaceRoot);
|
|
33
|
+
return String(error);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
static #causeOf(error: Error, workspaceRoot: string, chain: readonly unknown[]): string {
|
|
37
|
+
return error.cause ? `\nCaused by: ${ErrorReport.#format(error.cause, workspaceRoot, chain)}` : "";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static #withLocation(message: string, error: object, workspaceRoot: string): string {
|
|
41
|
+
const { position } = error as { position?: { file: string; line: number; column: number } | null };
|
|
42
|
+
if (!position?.file) return message;
|
|
43
|
+
const file = ErrorReport.#relativeToWorkspace(position.file, workspaceRoot);
|
|
44
|
+
const location = position.line > 0 ? `${file}:${position.line}:${position.column}` : file;
|
|
45
|
+
return message.includes(location) ? message : message.replace(/^.*/, (headline) => `${headline} (${location})`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Bun names the file by its realpath, so a workspace root reached through a symlink is matched by its own too.
|
|
49
|
+
static #relativeToWorkspace(file: string, workspaceRoot: string): string {
|
|
50
|
+
if (!path.isAbsolute(file)) return file;
|
|
51
|
+
for (const root of [workspaceRoot, ErrorReport.#realpathOf(workspaceRoot)]) {
|
|
52
|
+
const relative = path.relative(root, file);
|
|
53
|
+
if (!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
|
54
|
+
return relative.replaceAll(path.sep, "/");
|
|
55
|
+
}
|
|
56
|
+
return file;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
static #realpathOf(dir: string): string {
|
|
60
|
+
try {
|
|
61
|
+
return realpathSync(dir);
|
|
62
|
+
} catch {
|
|
63
|
+
return dir;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|