@akanjs/devkit 3.2.0-rc.11 → 3.2.0-rc.13
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 +16 -0
- package/akanApp/akanApp.host.test.ts +113 -0
- package/akanApp/akanApp.host.ts +145 -1215
- package/akanApp/builderGap.ts +68 -0
- package/akanApp/builderRequestRelay.test.ts +93 -0
- package/akanApp/builderRequestRelay.ts +101 -0
- package/akanApp/builderRssRecycler.ts +182 -0
- package/akanApp/devBackend.ts +392 -0
- package/akanApp/devBuildStatusBoard.ts +128 -0
- package/akanApp/devBuilder.ts +196 -0
- package/akanApp/devIdleSuspend.test.ts +130 -0
- package/akanApp/devIdleSuspend.ts +169 -0
- package/akanApp/devRecycler.test.ts +66 -0
- package/akanApp/devRecycler.ts +305 -0
- package/akanApp/processRss.ts +61 -0
- package/akanConfig/akanConfig.test.ts +23 -0
- package/akanConfig/akanConfig.ts +9 -9
- package/executors/appExecutor.ts +448 -0
- package/executors/commandExecutionError.ts +53 -0
- package/executors/executor.ts +527 -0
- package/executors/libExecutor.ts +23 -0
- package/executors/moduleExecutor.ts +18 -0
- package/executors/pkgExecutor.ts +129 -0
- package/executors/sysExecutor.ts +301 -0
- package/executors/workspaceExecutor.ts +278 -0
- package/executors.test.ts +44 -0
- package/executors.ts +8 -1749
- package/frontendBuild/frontendBuild.test.ts +2 -2
- package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
- package/frontendBuild/pagesBundleBuilder.ts +1 -1
- package/package.json +3 -3
- package/scanInfo.ts +19 -8
- package/transforms/barrelAnalyzer.ts +26 -8
- package/transforms/transforms.test.ts +27 -0
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import { type Logger, RestartSchedule } from "akanjs/common";
|
|
2
|
+
import type { BuilderMessage, DevBuildStatus } from "akanjs/server";
|
|
3
|
+
import type { App } from "../commandDecorators";
|
|
4
|
+
import type { DevStdioMode } from "../incrementalBuilder";
|
|
5
|
+
import type { BackendImportGraph } from "./BackendImportGraph";
|
|
6
|
+
import type { DevBuildStatusBoard } from "./devBuildStatusBoard";
|
|
7
|
+
import {
|
|
8
|
+
type BackendLifecycleState,
|
|
9
|
+
type BackendRestartReason,
|
|
10
|
+
backendRecoveryPolicy,
|
|
11
|
+
type DevHostState,
|
|
12
|
+
devHostStateOf,
|
|
13
|
+
mergeBackendRestartReasons,
|
|
14
|
+
normalizeBackendReportedGeneration,
|
|
15
|
+
shouldQueueBuildStatusReplay,
|
|
16
|
+
} from "./devHostPolicy";
|
|
17
|
+
|
|
18
|
+
const backendMsgTypeSet = new Set<BuilderMessage["type"]>(["build-route", "build-csr", "build-graph"]);
|
|
19
|
+
|
|
20
|
+
const BACKEND_RESTART_DEBOUNCE_MS = 120;
|
|
21
|
+
|
|
22
|
+
// Above the gateway's ~5s child-shutdown wait: a gateway SIGKILLed mid-shutdown strands orphan replicas.
|
|
23
|
+
const BACKEND_GRACEFUL_TIMEOUT_MS = 8_000;
|
|
24
|
+
|
|
25
|
+
const BACKEND_STDERR_TAIL_LIMIT = 40;
|
|
26
|
+
|
|
27
|
+
type BackendProcess = Bun.Subprocess<"ignore", "inherit" | "pipe", "inherit" | "pipe">;
|
|
28
|
+
|
|
29
|
+
interface DevBackendLinks {
|
|
30
|
+
isStopping: () => boolean;
|
|
31
|
+
emit: (state: DevHostState, detail?: string) => void;
|
|
32
|
+
beforeSpawn: () => void;
|
|
33
|
+
toBuilder: (message: BuilderMessage) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class DevBackend {
|
|
37
|
+
readonly #app: App;
|
|
38
|
+
readonly #env: Record<string, string>;
|
|
39
|
+
readonly #stdio: DevStdioMode;
|
|
40
|
+
readonly #logger: Logger;
|
|
41
|
+
readonly #statuses: DevBuildStatusBoard;
|
|
42
|
+
readonly #graph: BackendImportGraph;
|
|
43
|
+
readonly #links: DevBackendLinks;
|
|
44
|
+
#process: BackendProcess | null = null;
|
|
45
|
+
#ready = false;
|
|
46
|
+
#plannedStops = new WeakSet<Bun.Subprocess<"ignore", "inherit", "inherit">>();
|
|
47
|
+
#restartTimer: ReturnType<typeof setTimeout> | null = null;
|
|
48
|
+
readonly #recovery = new RestartSchedule(backendRecoveryPolicy);
|
|
49
|
+
#gaveUp = false;
|
|
50
|
+
#lifecycleState: BackendLifecycleState = "stopped";
|
|
51
|
+
#pendingRestartReason: BackendRestartReason | null = null;
|
|
52
|
+
//? One replacement at a time: `stop()` clears `#process` only once the old process exits, so a second restart inside
|
|
53
|
+
//? that wait signals the same pid and spawns a second backend, and the one the host stops tracking keeps the port.
|
|
54
|
+
#restart: Promise<void> | null = null;
|
|
55
|
+
#startStatus: { generation?: number; files: string[] } | null = null;
|
|
56
|
+
#stderrTail: string[] = [];
|
|
57
|
+
#queuedStatuses: DevBuildStatus[] = [];
|
|
58
|
+
|
|
59
|
+
constructor(
|
|
60
|
+
app: App,
|
|
61
|
+
{
|
|
62
|
+
env,
|
|
63
|
+
stdio,
|
|
64
|
+
logger,
|
|
65
|
+
statuses,
|
|
66
|
+
graph,
|
|
67
|
+
}: {
|
|
68
|
+
env: Record<string, string>;
|
|
69
|
+
stdio: DevStdioMode;
|
|
70
|
+
logger: Logger;
|
|
71
|
+
statuses: DevBuildStatusBoard;
|
|
72
|
+
graph: BackendImportGraph;
|
|
73
|
+
},
|
|
74
|
+
links: DevBackendLinks,
|
|
75
|
+
) {
|
|
76
|
+
this.#app = app;
|
|
77
|
+
this.#env = env;
|
|
78
|
+
this.#stdio = stdio;
|
|
79
|
+
this.#logger = logger;
|
|
80
|
+
this.#statuses = statuses;
|
|
81
|
+
this.#graph = graph;
|
|
82
|
+
this.#links = links;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
get running(): boolean {
|
|
86
|
+
return !!this.#process;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get ready(): boolean {
|
|
90
|
+
return this.#ready;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get gaveUp(): boolean {
|
|
94
|
+
return this.#gaveUp;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
get lifecycleState(): BackendLifecycleState {
|
|
98
|
+
return this.#lifecycleState;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
get restartScheduled(): boolean {
|
|
102
|
+
return !!this.#restartTimer;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
get recovering(): boolean {
|
|
106
|
+
return this.#recovery.pending;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
get restartPending(): boolean {
|
|
110
|
+
return !!(this.#restartTimer || this.#restart || this.#recovery.pending);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
get restarting(): Promise<void> | null {
|
|
114
|
+
return this.#restart;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
start(startStatus: { generation?: number; files: string[] } | null = null) {
|
|
118
|
+
if (this.#links.isStopping()) return;
|
|
119
|
+
if (this.#process) {
|
|
120
|
+
this.#logger.warn(`backend pid=${this.#process.pid} is still running; not starting a second one`);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
this.#links.beforeSpawn();
|
|
124
|
+
this.#startStatus = startStatus;
|
|
125
|
+
this.#gaveUp = false;
|
|
126
|
+
this.#setLifecycleState("starting");
|
|
127
|
+
this.#ready = false;
|
|
128
|
+
this.#stderrTail = [];
|
|
129
|
+
const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
|
|
130
|
+
cwd: this.#app.workspace.workspaceRoot,
|
|
131
|
+
stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
|
|
132
|
+
env: this.#env,
|
|
133
|
+
ipc: (msg: BuilderMessage) => {
|
|
134
|
+
if (!msg || typeof msg !== "object") return;
|
|
135
|
+
if (msg.type === "backend-ready") {
|
|
136
|
+
this.#ready = true;
|
|
137
|
+
this.#recovery.reset();
|
|
138
|
+
this.#setLifecycleState("ready", `pid=${msg.pid}`);
|
|
139
|
+
this.#recordReadyStatus();
|
|
140
|
+
this.#logger.verbose(`backend ready pid=${msg.pid}`);
|
|
141
|
+
this.#forgetRouteBuildStatus();
|
|
142
|
+
this.replay();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (msg.type === "build-status") {
|
|
146
|
+
// The gateway reports replica boot failures (crash loops, port conflicts) as build-status.
|
|
147
|
+
const status = this.#statuses.recordBackend({
|
|
148
|
+
generation: normalizeBackendReportedGeneration(msg.data.generation),
|
|
149
|
+
ok: msg.data.ok,
|
|
150
|
+
files: msg.data.files,
|
|
151
|
+
message: msg.data.message,
|
|
152
|
+
});
|
|
153
|
+
this.sendOrQueueStatus(status);
|
|
154
|
+
//? A replica crash loop leaves the gateway up, waiting for an edit: no exit reaches the host's own give-up.
|
|
155
|
+
if (!status.ok) this.#links.emit("failed", status.message);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (backendMsgTypeSet.has(msg.type)) this.#links.toBuilder(msg);
|
|
159
|
+
},
|
|
160
|
+
serialization: "advanced",
|
|
161
|
+
onExit: () => {
|
|
162
|
+
this.#ready = false;
|
|
163
|
+
if (this.#process === backend) this.#process = null;
|
|
164
|
+
if (this.#plannedStops.has(backend)) {
|
|
165
|
+
this.#plannedStops.delete(backend);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
this.#scheduleRecovery("backend-exit");
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
this.#process = backend;
|
|
172
|
+
this.#logger.verbose(`backend spawned pid=${backend.pid}`);
|
|
173
|
+
if (this.#stdio === "pipe") {
|
|
174
|
+
// Undrained pipes swallow runtime errors and leave the crash-loop stderr tail empty.
|
|
175
|
+
void this.#forwardStream(backend.stderr as unknown as ReadableStream<Uint8Array> | undefined, "stderr");
|
|
176
|
+
void this.#forwardStream(backend.stdout as unknown as ReadableStream<Uint8Array> | undefined, "stdout");
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
send(message: BuilderMessage) {
|
|
181
|
+
if (!this.#process || !this.#ready) {
|
|
182
|
+
if (message.type === "css-updated" || message.type === "pages-updated" || message.type === "build-status") {
|
|
183
|
+
this.#logger.verbose(`backend is not ready; will replay ${message.type}`);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (message.type !== "builder-ready") this.#logger.warn(`backend is not ready; dropping ${message.type}`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
this.#process.send(message);
|
|
191
|
+
} catch (err) {
|
|
192
|
+
this.#logger.warn(
|
|
193
|
+
`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
sendOrQueueStatus(status: DevBuildStatus): void {
|
|
199
|
+
if (!this.#process || shouldQueueBuildStatusReplay(this.#ready, this.#queuedStatuses.length)) {
|
|
200
|
+
this.#queuedStatuses.push(status);
|
|
201
|
+
this.#logger.verbose(
|
|
202
|
+
`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`,
|
|
203
|
+
);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
this.send({ type: "build-status", data: status });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
replay(): void {
|
|
210
|
+
if (!this.#ready) return;
|
|
211
|
+
const { css, pages } = this.#statuses.lastGood;
|
|
212
|
+
if (css) this.send(css);
|
|
213
|
+
if (pages) this.send(pages);
|
|
214
|
+
const queuedStatuses = this.#queuedStatuses.splice(0);
|
|
215
|
+
for (const status of this.#statuses.replaySequence(queuedStatuses)) {
|
|
216
|
+
this.send({ type: "build-status", data: status });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
dropQueuedStatuses(): void {
|
|
221
|
+
this.#queuedStatuses = [];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async stop() {
|
|
225
|
+
if (!this.#process) return;
|
|
226
|
+
const backend = this.#process;
|
|
227
|
+
this.#plannedStops.add(backend);
|
|
228
|
+
this.#ready = false;
|
|
229
|
+
this.#setLifecycleState("stopping", `pid=${backend.pid}`);
|
|
230
|
+
this.#logger.verbose(`stopping backend pid=${backend.pid}`);
|
|
231
|
+
try {
|
|
232
|
+
backend.kill("SIGTERM");
|
|
233
|
+
const timeout = new Promise<"timeout">((resolve) =>
|
|
234
|
+
setTimeout(() => resolve("timeout"), BACKEND_GRACEFUL_TIMEOUT_MS),
|
|
235
|
+
);
|
|
236
|
+
const result = await Promise.race([backend.exited, timeout]);
|
|
237
|
+
if (result === "timeout") {
|
|
238
|
+
this.#logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
|
|
239
|
+
backend.kill("SIGKILL");
|
|
240
|
+
await backend.exited.catch(() => undefined);
|
|
241
|
+
}
|
|
242
|
+
} finally {
|
|
243
|
+
if (this.#process === backend) this.#process = null;
|
|
244
|
+
this.#setLifecycleState("stopped", `pid=${backend.pid}`);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
cancelTimers(): void {
|
|
249
|
+
if (this.#restartTimer) clearTimeout(this.#restartTimer);
|
|
250
|
+
this.#restartTimer = null;
|
|
251
|
+
this.#recovery.cancel();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
dropPendingRestart(): void {
|
|
255
|
+
this.#pendingRestartReason = null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
scheduleRestart(reason: BackendRestartReason) {
|
|
259
|
+
this.#pendingRestartReason = mergeBackendRestartReasons(this.#pendingRestartReason, reason);
|
|
260
|
+
const pending = this.#pendingRestartReason;
|
|
261
|
+
this.#setLifecycleState(
|
|
262
|
+
"restart-pending",
|
|
263
|
+
`generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`,
|
|
264
|
+
);
|
|
265
|
+
this.#recovery.cancel();
|
|
266
|
+
if (this.#restartTimer) clearTimeout(this.#restartTimer);
|
|
267
|
+
this.#restartTimer = setTimeout(() => {
|
|
268
|
+
this.#restartTimer = null;
|
|
269
|
+
this.#restart ??= this.#drainRestarts().finally(() => {
|
|
270
|
+
this.#restart = null;
|
|
271
|
+
});
|
|
272
|
+
}, BACKEND_RESTART_DEBOUNCE_MS);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
reviveAfterGreenBuild(status: DevBuildStatus): void {
|
|
276
|
+
if (!status.ok || !this.#gaveUp || this.#process || this.#recovery.pending) return;
|
|
277
|
+
this.#logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
|
|
278
|
+
this.#recovery.reset();
|
|
279
|
+
this.start({ generation: status.generation, files: status.files });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
#recordStderr(chunk: string) {
|
|
283
|
+
const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
|
|
284
|
+
if (lines.length === 0) return;
|
|
285
|
+
this.#stderrTail.push(...lines);
|
|
286
|
+
if (this.#stderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
|
|
287
|
+
this.#stderrTail.splice(0, this.#stderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Verbatim, not re-logged: a level floor would swallow runtime output and re-rendering doubles the timestamp.
|
|
292
|
+
async #forwardStream(stream: ReadableStream<Uint8Array> | undefined | null, kind: "stdout" | "stderr") {
|
|
293
|
+
if (!stream) return;
|
|
294
|
+
const decoder = new TextDecoder();
|
|
295
|
+
try {
|
|
296
|
+
for await (const chunk of stream) {
|
|
297
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
298
|
+
if (!text) continue;
|
|
299
|
+
if (kind === "stderr") {
|
|
300
|
+
this.#recordStderr(text);
|
|
301
|
+
process.stderr.write(text);
|
|
302
|
+
} else process.stdout.write(text);
|
|
303
|
+
}
|
|
304
|
+
} catch {
|
|
305
|
+
// The stream closes when the backend exits; nothing further to surface here.
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
#recordReadyStatus(): void {
|
|
310
|
+
const previous = this.#statuses.phase("backend");
|
|
311
|
+
const startStatus = this.#startStatus;
|
|
312
|
+
if (startStatus || previous?.ok === false) {
|
|
313
|
+
const status = this.#statuses.recordBackend({
|
|
314
|
+
generation: startStatus?.generation ?? previous?.generation,
|
|
315
|
+
ok: true,
|
|
316
|
+
files: startStatus?.files ?? previous?.files ?? [],
|
|
317
|
+
message: "Backend ready",
|
|
318
|
+
});
|
|
319
|
+
this.sendOrQueueStatus(status);
|
|
320
|
+
}
|
|
321
|
+
this.#startStatus = null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
//? A route status belongs to the route cache of the backend that asked for the build: a new backend builds its routes
|
|
325
|
+
//? again, and reports each one itself.
|
|
326
|
+
#forgetRouteBuildStatus(): void {
|
|
327
|
+
this.#statuses.forgetRoute();
|
|
328
|
+
this.#queuedStatuses = this.#queuedStatuses.filter((status) => status.phase !== "route");
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
#setLifecycleState(next: BackendLifecycleState, detail?: string): void {
|
|
332
|
+
if (this.#lifecycleState === next && !detail) return;
|
|
333
|
+
const prev = this.#lifecycleState;
|
|
334
|
+
this.#lifecycleState = next;
|
|
335
|
+
this.#logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
|
|
336
|
+
this.#links.emit(devHostStateOf(next, this.#gaveUp), detail);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
//? A reason that arrived during a restart runs after it; one whose debounce is still pending waits for its timer.
|
|
340
|
+
async #drainRestarts() {
|
|
341
|
+
while (this.#pendingRestartReason && !this.#restartTimer && !this.#links.isStopping()) {
|
|
342
|
+
const next = this.#pendingRestartReason;
|
|
343
|
+
this.#pendingRestartReason = null;
|
|
344
|
+
await this.#restartWith(next);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async #restartWith(reason: BackendRestartReason) {
|
|
349
|
+
this.#logger.verbose(
|
|
350
|
+
`[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`,
|
|
351
|
+
);
|
|
352
|
+
this.#recovery.reset();
|
|
353
|
+
await Promise.all([this.stop(), this.#graph.refresh()]);
|
|
354
|
+
this.start({ generation: reason.generation, files: reason.files });
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
#scheduleRecovery(reason: string) {
|
|
358
|
+
if (this.#recovery.pending || this.#process) return;
|
|
359
|
+
if (this.#recovery.exhausted) {
|
|
360
|
+
const message = `Backend exited ${this.#recovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
|
|
361
|
+
this.#gaveUp = true;
|
|
362
|
+
this.#setLifecycleState("stopped", `gave up after ${this.#recovery.attempts} recovery attempts`);
|
|
363
|
+
this.#logger.error(`[backend-recovery] ${message}`);
|
|
364
|
+
if (this.#stderrTail.length > 0) {
|
|
365
|
+
this.#logger.error(`[backend-recovery] recent backend stderr:\n${this.#stderrTail.join("\n")}`);
|
|
366
|
+
}
|
|
367
|
+
const abandonedStatus = this.#statuses.recordBackend({ ok: false, files: [], message });
|
|
368
|
+
this.sendOrQueueStatus(abandonedStatus);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
this.#setLifecycleState("recovering", reason);
|
|
372
|
+
const delay = this.#recovery.next();
|
|
373
|
+
const failureStatus = this.#statuses.recordBackend({
|
|
374
|
+
ok: false,
|
|
375
|
+
files: [],
|
|
376
|
+
message: `Backend exited unexpectedly (${reason}); restarting in ${delay}ms`,
|
|
377
|
+
});
|
|
378
|
+
this.sendOrQueueStatus(failureStatus);
|
|
379
|
+
this.#logger.warn(
|
|
380
|
+
`[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#recovery.attempts})`,
|
|
381
|
+
);
|
|
382
|
+
if (this.#stderrTail.length > 0) {
|
|
383
|
+
this.#logger.warn(`[backend-recovery] recent backend stderr:\n${this.#stderrTail.join("\n")}`);
|
|
384
|
+
}
|
|
385
|
+
this.#recovery.arm(delay, () => {
|
|
386
|
+
if (this.#process) return;
|
|
387
|
+
void this.#graph.refresh().finally(() => {
|
|
388
|
+
if (!this.#process) this.start({ generation: failureStatus.generation, files: failureStatus.files });
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
2
|
+
import type { BuilderMessage, BuildPhase, DevBuildStatus } from "akanjs/server";
|
|
3
|
+
import {
|
|
4
|
+
buildStatusReplaySequence,
|
|
5
|
+
createBackendBuildStatus,
|
|
6
|
+
hasAnyBuildFailure,
|
|
7
|
+
hasBuildFailureForGeneration,
|
|
8
|
+
shouldKeepBuildFailure,
|
|
9
|
+
shouldMarkBuildPhaseRecovered,
|
|
10
|
+
shouldRelayRecycledFrontendState,
|
|
11
|
+
shouldReplaceLastGoodMessage,
|
|
12
|
+
} from "./devHostPolicy";
|
|
13
|
+
|
|
14
|
+
type FrontendStateMessage =
|
|
15
|
+
| Extract<BuilderMessage, { type: "pages-updated" }>
|
|
16
|
+
| Extract<BuilderMessage, { type: "css-updated" }>;
|
|
17
|
+
|
|
18
|
+
interface LastGoodFrontendState {
|
|
19
|
+
pages?: Extract<BuilderMessage, { type: "pages-updated" }>;
|
|
20
|
+
css?: Extract<BuilderMessage, { type: "css-updated" }>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class DevBuildStatusBoard {
|
|
24
|
+
readonly #logger: Logger;
|
|
25
|
+
readonly #byPhase = new Map<BuildPhase, DevBuildStatus>();
|
|
26
|
+
#backendGeneration = 0;
|
|
27
|
+
#lastGood: LastGoodFrontendState = {};
|
|
28
|
+
|
|
29
|
+
constructor(logger: Logger) {
|
|
30
|
+
this.#logger = logger;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get lastGood(): Readonly<LastGoodFrontendState> {
|
|
34
|
+
return this.#lastGood;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
get failing(): boolean {
|
|
38
|
+
return hasAnyBuildFailure(this.#byPhase);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
phase(phase: BuildPhase): DevBuildStatus | undefined {
|
|
42
|
+
return this.#byPhase.get(phase);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
failedAt(generation: number | undefined): boolean {
|
|
46
|
+
return hasBuildFailureForGeneration(this.#byPhase, generation);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
replaySequence(queued: readonly DevBuildStatus[]): DevBuildStatus[] {
|
|
50
|
+
return buildStatusReplaySequence(queued, this.#byPhase);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
nextBackendGeneration(generation?: number): number {
|
|
54
|
+
if (typeof generation === "number") {
|
|
55
|
+
this.#backendGeneration = Math.max(this.#backendGeneration, generation);
|
|
56
|
+
return generation;
|
|
57
|
+
}
|
|
58
|
+
this.#backendGeneration += 1;
|
|
59
|
+
return this.#backendGeneration;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
record(status: DevBuildStatus): void {
|
|
63
|
+
const recovered = shouldMarkBuildPhaseRecovered(this.#byPhase, status);
|
|
64
|
+
if (shouldKeepBuildFailure(this.#byPhase, status)) return;
|
|
65
|
+
this.#byPhase.set(status.phase, status);
|
|
66
|
+
const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
|
|
67
|
+
if (status.ok) this.#logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
|
|
68
|
+
else this.#logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
recordBackend({
|
|
72
|
+
generation,
|
|
73
|
+
ok,
|
|
74
|
+
files,
|
|
75
|
+
message,
|
|
76
|
+
}: {
|
|
77
|
+
generation?: number;
|
|
78
|
+
ok: boolean;
|
|
79
|
+
files?: string[];
|
|
80
|
+
message?: string;
|
|
81
|
+
}): DevBuildStatus {
|
|
82
|
+
const status = createBackendBuildStatus({
|
|
83
|
+
generation: this.nextBackendGeneration(generation),
|
|
84
|
+
ok,
|
|
85
|
+
files,
|
|
86
|
+
message,
|
|
87
|
+
});
|
|
88
|
+
this.record(status);
|
|
89
|
+
return status;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
forgetRoute(): void {
|
|
93
|
+
this.#byPhase.delete("route");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
reset(): void {
|
|
97
|
+
this.#lastGood = {};
|
|
98
|
+
this.#byPhase.clear();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// `supersede`: a recycled builder's re-announcement is what is on disk now, whatever generation it carries.
|
|
102
|
+
recordLastGood(message: FrontendStateMessage, { supersede = false }: { supersede?: boolean } = {}): void {
|
|
103
|
+
if (message.type === "pages-updated") {
|
|
104
|
+
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.pages, message)) return;
|
|
105
|
+
this.#lastGood.pages = message;
|
|
106
|
+
this.#logger.verbose(
|
|
107
|
+
`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`,
|
|
108
|
+
);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.css, message)) return;
|
|
112
|
+
this.#lastGood.css = message;
|
|
113
|
+
this.#logger.verbose(
|
|
114
|
+
`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// The backend reads `base-artifact.json` once, so a recycled builder re-announces it; unchanged hashes are dropped.
|
|
119
|
+
shouldRelayRecycled(message: FrontendStateMessage): boolean {
|
|
120
|
+
const current = message.type === "pages-updated" ? this.#lastGood.pages : this.#lastGood.css;
|
|
121
|
+
if (shouldRelayRecycledFrontendState(current, message)) {
|
|
122
|
+
this.#logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
this.#logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|