@akanjs/cli 3.2.0-rc.12 → 3.2.0-rc.14
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/.build-stamp +2 -2
- package/{CodeAgent-cr8pvdmv.js → CodeAgent-yd1f54yf.js} +2 -2
- package/{CodeTui-89ssa9rr.js → CodeTui-h7mksphk.js} +1 -1
- package/TunnelShare-hrjed2jf.js +19 -0
- package/{agent.command-rp9hpf0v.js → agent.command-hrc2dfas.js} +19 -15
- package/akanCode.js +2 -2
- package/appExecutor-0ssszyhf.js +11 -0
- package/{application.command-fydjdvce.js → application.command-b2194cpv.js} +15 -11
- package/{applicationBuildRunner-68sph7t4.js → applicationBuildRunner-gg03kydg.js} +12 -8
- package/buildBatch.proc.js +14 -9
- package/{cloud.command-0y1gg3sb.js → cloud.command-d8ps1564.js} +20 -16
- package/cloud.script-7j7w4m0w.js +35 -0
- package/{code.command-63fcz7a3.js → code.command-6h6jr0s7.js} +10 -6
- package/{context.command-pgwcx0na.js → context.command-t8akxhny.js} +20 -16
- package/context.runner-eawk1n8e.js +34 -0
- package/{guideline.command-6yz6d4hf.js → guideline.command-f41b5nv5.js} +6 -2
- package/guidelines/agentRule/agentRule.instruction.md +12 -2
- package/guidelines/akanApi/akanApi.instruction.md +1 -1
- package/guidelines/pageRule/pageRule.instruction.md +6 -1
- package/guidelines/runtimeRule/runtimeRule.instruction.md +2 -1
- package/incrementalBuilder.proc.js +12 -7
- package/{index-c3r23w24.js → index-1b1p83vq.js} +3 -3
- package/index-1jzdengt.js +30 -0
- package/{index-aybfcx58.js → index-2z8mxgs7.js} +6 -6
- package/{index-t8h09yjs.js → index-37k5vshx.js} +10 -8
- package/{index-frvjq1rd.js → index-3fbmyb2r.js} +1 -1
- package/{index-h0s3cjm0.js → index-3fn13v8p.js} +4 -4
- package/{index-axe04yqm.js → index-3fpv5v0t.js} +15 -11
- package/{index-23d8gw08.js → index-3gmskeq2.js} +37 -29
- package/{index-bper31wr.js → index-5np8zpep.js} +12 -8
- package/{index-41mfhgq0.js → index-66jt3m30.js} +1 -1
- package/{index-097bjwvm.js → index-6dwk5aej.js} +8 -8
- package/{index-qwzwzmvf.js → index-71z3pdsn.js} +4 -4
- package/{index-p54s83sz.js → index-8bkbexcy.js} +1 -1
- package/{index-cqrndcq0.js → index-8rmg8c0y.js} +3 -3
- package/{index-s0w78805.js → index-9w51aevd.js} +1 -1
- package/{index-bmscnt1t.js → index-9yfssbgg.js} +25 -19
- package/{index-adj7qmz9.js → index-asfx2dhe.js} +13 -9
- package/index-b3h37zk3.js +787 -0
- package/{index-wm4385pm.js → index-bb7cm060.js} +10 -10
- package/{index-6r5f768n.js → index-c0rnjeqn.js} +11 -9
- package/{index-apcr1qgk.js → index-c4k6e098.js} +19 -15
- package/{index-sq9d0jhj.js → index-crtscw7c.js} +2710 -3615
- package/{index-ahk6rvth.js → index-e599a0e4.js} +1 -1
- package/{index-6fnrhpn1.js → index-f5j09jnj.js} +5 -5
- package/{index-3m2cd8mm.js → index-g2ebpf0y.js} +6 -6
- package/{index-hf9nvwam.js → index-hbc0t3ng.js} +2 -2
- package/{index-cswgczrv.js → index-hg8s6nae.js} +9 -9
- package/{index-pcprf7ft.js → index-hpe12v1h.js} +1 -1
- package/{index-dfsa009c.js → index-j2me5hm4.js} +8 -6
- package/{index-e5f6czck.js → index-j33b0n38.js} +1 -1
- package/{index-mmgtnh44.js → index-k081wv4r.js} +1428 -1106
- package/{index-bgp0h8rx.js → index-nx4q5rey.js} +3 -3
- package/index-rx8r0cbe.js +18 -0
- package/{index-k2r3hmbz.js → index-vb8gd135.js} +21 -15
- package/{index-6js9ek5c.js → index-vy50ec2q.js} +2 -2
- package/index-x2bj2vyz.js +127 -0
- package/{index-wpgtyek3.js → index-xb1yh9km.js} +1 -1
- package/{index-70jkxbf6.js → index-xjj0h74q.js} +2 -2
- package/index.js +27 -23
- package/libExecutor-ex8jqksz.js +10 -0
- package/{library.command-kc1zahcg.js → library.command-a9p5yg4k.js} +7 -3
- package/{localRegistry.command-yz150pcw.js → localRegistry.command-zz64k5vy.js} +23 -18
- package/{module.command-cchwzz9r.js → module.command-1ht6dmxg.js} +9 -5
- package/{package.command-qcjajpv8.js → package.command-eabq20aq.js} +8 -4
- package/package.json +2 -2
- package/{page.command-1t86dx8a.js → page.command-xhmzmvjn.js} +7 -3
- package/{pipeline.command-2xx9z3d0.js → pipeline.command-wsbg3fpr.js} +11 -6
- package/pkgExecutor-d16x1xcb.js +10 -0
- package/{primitive.command-mc0x8txr.js → primitive.command-yyxtfhvq.js} +10 -6
- package/{projectTypecheck-tz497yx7.js → projectTypecheck-wcrt7sae.js} +1 -1
- package/{quality.command-11rayf5c.js → quality.command-n7hmt628.js} +16 -10
- package/{repair.command-8w41vy78.js → repair.command-pczdq4mv.js} +9 -5
- package/{scalar.command-rvwh98ny.js → scalar.command-cw3d32sv.js} +8 -4
- package/{subspace.command-ykxertx8.js → subspace.command-d8t8geyv.js} +17 -12
- package/{tunnel.command-qbcbj0vq.js → tunnel.command-mhm64m9n.js} +15 -11
- package/{verify.command-gvveq05z.js → verify.command-j4he0fbx.js} +16 -12
- package/{workflow.command-yp9ajthb.js → workflow.command-k064waza.js} +14 -10
- package/{workspace.command-jm7emxjh.js → workspace.command-pkpawft5.js} +47 -41
- package/TunnelShare-ndb5cts1.js +0 -15
- package/cloud.script-ewk72b3g.js +0 -31
- package/context.runner-5s2ytkjj.js +0 -30
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import {
|
|
3
|
-
AppInfo,
|
|
4
3
|
CommandExecutionError,
|
|
5
|
-
WorkspaceExecutor,
|
|
6
4
|
SysExecutor,
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
} from "./index-sq9d0jhj.js";
|
|
5
|
+
AppInfo,
|
|
6
|
+
WorkspaceExecutor
|
|
7
|
+
} from "./index-crtscw7c.js";
|
|
11
8
|
import {
|
|
12
9
|
FileSys2
|
|
13
10
|
} from "./index-bns3wcpc.js";
|
|
14
11
|
import {
|
|
15
12
|
CliError
|
|
16
13
|
} from "./index-j4yvgfhr.js";
|
|
14
|
+
import {
|
|
15
|
+
AppExecutor2
|
|
16
|
+
} from "./index-b3h37zk3.js";
|
|
17
|
+
import {
|
|
18
|
+
LibExecutor2
|
|
19
|
+
} from "./index-1jzdengt.js";
|
|
20
|
+
import {
|
|
21
|
+
PkgExecutor2
|
|
22
|
+
} from "./index-x2bj2vyz.js";
|
|
17
23
|
import {
|
|
18
24
|
UNAVAILABLE_REDIS_HOST,
|
|
19
25
|
redisTunnelPolicy,
|
|
@@ -49,27 +55,27 @@ import {
|
|
|
49
55
|
filesChangedSince,
|
|
50
56
|
HmrWatcher,
|
|
51
57
|
WatchRootResolver
|
|
52
|
-
} from "./index-
|
|
58
|
+
} from "./index-66jt3m30.js";
|
|
53
59
|
import {
|
|
54
60
|
runner,
|
|
55
61
|
assertPromptable
|
|
56
|
-
} from "./index-
|
|
62
|
+
} from "./index-3gmskeq2.js";
|
|
57
63
|
import {
|
|
58
64
|
UpdatePackFolder,
|
|
59
65
|
UpdateUploader,
|
|
60
66
|
NativePublicEnv,
|
|
61
67
|
NativeApp
|
|
62
|
-
} from "./index-
|
|
68
|
+
} from "./index-g2ebpf0y.js";
|
|
63
69
|
import {
|
|
64
70
|
DesktopServerStage
|
|
65
|
-
} from "./index-
|
|
71
|
+
} from "./index-9w51aevd.js";
|
|
66
72
|
import {
|
|
67
73
|
resolveMobileTargets,
|
|
68
74
|
resolveAppId
|
|
69
75
|
} from "./index-m9jj544v.js";
|
|
70
76
|
import {
|
|
71
77
|
SlicePlanner
|
|
72
|
-
} from "./index-
|
|
78
|
+
} from "./index-3fbmyb2r.js";
|
|
73
79
|
import {
|
|
74
80
|
openBrowser
|
|
75
81
|
} from "./index-9dp031by.js";
|
|
@@ -85,8 +91,7 @@ import { existsSync, realpathSync as realpathSync2 } from "fs";
|
|
|
85
91
|
import path7 from "path";
|
|
86
92
|
|
|
87
93
|
// pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
|
|
88
|
-
import
|
|
89
|
-
import { Logger as Logger2, RestartSchedule as RestartSchedule2 } from "akanjs/common";
|
|
94
|
+
import { Logger as Logger2 } from "akanjs/common";
|
|
90
95
|
|
|
91
96
|
// pkgs/@akanjs/devkit/createTunnel.ts
|
|
92
97
|
import { readFileSync } from "fs";
|
|
@@ -324,9 +329,321 @@ var createTunnel = async (service, { app, environment, port = service === "postg
|
|
|
324
329
|
}
|
|
325
330
|
return `localhost:${port}`;
|
|
326
331
|
};
|
|
332
|
+
|
|
333
|
+
// pkgs/@akanjs/devkit/akanApp/BackendImportGraph.ts
|
|
334
|
+
import { stat } from "fs/promises";
|
|
335
|
+
import path2 from "path";
|
|
336
|
+
var NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav|html)$/i;
|
|
337
|
+
var GRAPH_IMPORT_KINDS = new Set([
|
|
338
|
+
"import-statement",
|
|
339
|
+
"require-call",
|
|
340
|
+
"require-resolve",
|
|
341
|
+
"dynamic-import"
|
|
342
|
+
]);
|
|
343
|
+
|
|
344
|
+
class BackendImportGraph {
|
|
345
|
+
#app;
|
|
346
|
+
#logger;
|
|
347
|
+
#tsTranspiler = new Bun.Transpiler({ loader: "ts" });
|
|
348
|
+
#tsxTranspiler = new Bun.Transpiler({ loader: "tsx" });
|
|
349
|
+
#jsTranspiler = new Bun.Transpiler({ loader: "js" });
|
|
350
|
+
#jsxTranspiler = new Bun.Transpiler({ loader: "jsx" });
|
|
351
|
+
#files = new Set;
|
|
352
|
+
#scanCache = new Map;
|
|
353
|
+
#ready = false;
|
|
354
|
+
#lastRefreshSucceeded = false;
|
|
355
|
+
constructor(app, logger) {
|
|
356
|
+
this.#app = app;
|
|
357
|
+
this.#logger = logger;
|
|
358
|
+
}
|
|
359
|
+
get ready() {
|
|
360
|
+
return this.#ready;
|
|
361
|
+
}
|
|
362
|
+
get lastRefreshSucceeded() {
|
|
363
|
+
return this.#lastRefreshSucceeded;
|
|
364
|
+
}
|
|
365
|
+
has(file) {
|
|
366
|
+
return this.#files.has(path2.resolve(file));
|
|
367
|
+
}
|
|
368
|
+
async fingerprint() {
|
|
369
|
+
const stamps = await Promise.all([...this.#files].map(async (file) => {
|
|
370
|
+
const stats = await stat(file).catch(() => null);
|
|
371
|
+
return [file, stats ? `${Math.round(stats.mtimeMs)}:${stats.size}` : "(gone)"];
|
|
372
|
+
}));
|
|
373
|
+
return new Map(stamps);
|
|
374
|
+
}
|
|
375
|
+
async refresh() {
|
|
376
|
+
try {
|
|
377
|
+
const files = await this.#build();
|
|
378
|
+
this.#files = files;
|
|
379
|
+
this.#ready = true;
|
|
380
|
+
this.#lastRefreshSucceeded = true;
|
|
381
|
+
this.#logger.verbose(`[backend-graph] scanned ${files.size} files`);
|
|
382
|
+
return true;
|
|
383
|
+
} catch (err) {
|
|
384
|
+
this.#ready = this.#files.size > 0;
|
|
385
|
+
this.#lastRefreshSucceeded = false;
|
|
386
|
+
this.#logger.warn(`[backend-graph] scan failed; ${this.#ready ? "using previous graph" : "using fallback rules"}: ${err instanceof Error ? err.message : String(err)}`);
|
|
387
|
+
return this.#ready;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
async#build() {
|
|
391
|
+
const roots = await this.#entrypoints();
|
|
392
|
+
const files = new Set;
|
|
393
|
+
const queue = [...roots];
|
|
394
|
+
const workspaceRoot = path2.resolve(this.#app.workspace.workspaceRoot);
|
|
395
|
+
while (queue.length > 0) {
|
|
396
|
+
const current = path2.resolve(queue.pop());
|
|
397
|
+
if (files.has(current))
|
|
398
|
+
continue;
|
|
399
|
+
if (!this.#isWorkspaceSource(current, workspaceRoot))
|
|
400
|
+
continue;
|
|
401
|
+
const imports = await this.#importsOf(current);
|
|
402
|
+
if (!imports)
|
|
403
|
+
continue;
|
|
404
|
+
files.add(current);
|
|
405
|
+
const importerDir = path2.dirname(current);
|
|
406
|
+
for (const imp of imports) {
|
|
407
|
+
if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
|
|
408
|
+
continue;
|
|
409
|
+
const resolved = this.#resolve(imp.path, importerDir);
|
|
410
|
+
if (!resolved || files.has(resolved))
|
|
411
|
+
continue;
|
|
412
|
+
queue.push(resolved);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
for (const cached of this.#scanCache.keys())
|
|
416
|
+
if (!files.has(cached))
|
|
417
|
+
this.#scanCache.delete(cached);
|
|
418
|
+
return files;
|
|
419
|
+
}
|
|
420
|
+
async#importsOf(file) {
|
|
421
|
+
const stats = await stat(file).catch(() => null);
|
|
422
|
+
if (!stats?.isFile())
|
|
423
|
+
return null;
|
|
424
|
+
const mtimeMs = Math.round(stats.mtimeMs);
|
|
425
|
+
const cached = this.#scanCache.get(file);
|
|
426
|
+
if (cached && cached.mtimeMs === mtimeMs && cached.size === stats.size)
|
|
427
|
+
return cached.specifiers;
|
|
428
|
+
const specifiers = this.#scanImports(file, await Bun.file(file).text());
|
|
429
|
+
this.#scanCache.set(file, { mtimeMs, size: stats.size, specifiers });
|
|
430
|
+
return specifiers;
|
|
431
|
+
}
|
|
432
|
+
async#entrypoints() {
|
|
433
|
+
const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
|
|
434
|
+
const existing = [];
|
|
435
|
+
for (const root of roots) {
|
|
436
|
+
const abs = path2.resolve(root);
|
|
437
|
+
if (await Bun.file(abs).exists())
|
|
438
|
+
existing.push(abs);
|
|
439
|
+
}
|
|
440
|
+
return existing;
|
|
441
|
+
}
|
|
442
|
+
#resolve(specifier, importerDir) {
|
|
443
|
+
try {
|
|
444
|
+
const resolved = Bun.resolveSync(specifier, importerDir);
|
|
445
|
+
if (!path2.isAbsolute(resolved))
|
|
446
|
+
return null;
|
|
447
|
+
if (!SOURCE_EXTS.has(path2.extname(resolved).toLowerCase()))
|
|
448
|
+
return null;
|
|
449
|
+
return path2.resolve(resolved);
|
|
450
|
+
} catch {
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
#isWorkspaceSource(file, workspaceRoot) {
|
|
455
|
+
const rel = path2.relative(workspaceRoot, file);
|
|
456
|
+
if (rel.startsWith("..") || path2.isAbsolute(rel))
|
|
457
|
+
return false;
|
|
458
|
+
if (rel.includes(`${path2.sep}node_modules${path2.sep}`) || rel.includes(`${path2.sep}.akan${path2.sep}`))
|
|
459
|
+
return false;
|
|
460
|
+
return SOURCE_EXTS.has(path2.extname(file).toLowerCase());
|
|
461
|
+
}
|
|
462
|
+
#scanImports(file, source) {
|
|
463
|
+
const ext = path2.extname(file).toLowerCase();
|
|
464
|
+
if (ext === ".tsx")
|
|
465
|
+
return this.#tsxTranspiler.scanImports(source);
|
|
466
|
+
if (ext === ".jsx")
|
|
467
|
+
return this.#jsxTranspiler.scanImports(source);
|
|
468
|
+
if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
|
|
469
|
+
return this.#jsTranspiler.scanImports(source);
|
|
470
|
+
return this.#tsTranspiler.scanImports(source);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// pkgs/@akanjs/devkit/akanApp/builderGap.ts
|
|
475
|
+
class BuilderGap {
|
|
476
|
+
#graph;
|
|
477
|
+
#backend;
|
|
478
|
+
#logger;
|
|
479
|
+
#stamp = null;
|
|
480
|
+
constructor({ graph, backend, logger }) {
|
|
481
|
+
this.#graph = graph;
|
|
482
|
+
this.#backend = backend;
|
|
483
|
+
this.#logger = logger;
|
|
484
|
+
}
|
|
485
|
+
open(reason) {
|
|
486
|
+
if (this.#stamp)
|
|
487
|
+
return;
|
|
488
|
+
if (!this.#graph.ready) {
|
|
489
|
+
this.#logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
this.#stamp = this.#graph.fingerprint().then((stamps) => {
|
|
493
|
+
this.#logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
|
|
494
|
+
return stamps;
|
|
495
|
+
}).catch((err) => {
|
|
496
|
+
this.#logger.warn(`[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`);
|
|
497
|
+
return null;
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
async take() {
|
|
501
|
+
const stamping = this.#stamp;
|
|
502
|
+
this.#stamp = null;
|
|
503
|
+
const before = stamping ? await stamping : null;
|
|
504
|
+
if (!before)
|
|
505
|
+
return [];
|
|
506
|
+
const moved = filesChangedSince(before, await this.#graph.fingerprint());
|
|
507
|
+
if (moved.length === 0) {
|
|
508
|
+
this.#logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
|
|
509
|
+
return moved;
|
|
510
|
+
}
|
|
511
|
+
this.#logger.info(`[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`);
|
|
512
|
+
return moved;
|
|
513
|
+
}
|
|
514
|
+
discard(reason) {
|
|
515
|
+
if (!this.#stamp)
|
|
516
|
+
return;
|
|
517
|
+
this.#stamp = null;
|
|
518
|
+
this.#logger.verbose(`[builder-gap] stamps dropped (${reason})`);
|
|
519
|
+
}
|
|
520
|
+
async restartBackendForChanges() {
|
|
521
|
+
const moved = await this.take();
|
|
522
|
+
if (moved.length === 0)
|
|
523
|
+
return;
|
|
524
|
+
this.#backend.scheduleRestart({ files: moved, roles: [] });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// pkgs/@akanjs/devkit/incrementalBuilder/builderRequestRouter.ts
|
|
529
|
+
class BuilderRequestRouter {
|
|
530
|
+
#generation = 0;
|
|
531
|
+
#nextId = 1;
|
|
532
|
+
#inFlight = new Map;
|
|
533
|
+
get generation() {
|
|
534
|
+
return this.#generation;
|
|
535
|
+
}
|
|
536
|
+
get inFlightCount() {
|
|
537
|
+
return this.#inFlight.size;
|
|
538
|
+
}
|
|
539
|
+
startGeneration() {
|
|
540
|
+
this.#generation += 1;
|
|
541
|
+
this.#inFlight.clear();
|
|
542
|
+
return this.#generation;
|
|
543
|
+
}
|
|
544
|
+
issue(message) {
|
|
545
|
+
const id = this.#nextId++;
|
|
546
|
+
this.#inFlight.set(id, { backendId: message.id, generation: this.#generation });
|
|
547
|
+
return { ...message, id };
|
|
548
|
+
}
|
|
549
|
+
withdraw(id) {
|
|
550
|
+
this.#inFlight.delete(id);
|
|
551
|
+
}
|
|
552
|
+
settle(message) {
|
|
553
|
+
const request = this.#inFlight.get(message.id);
|
|
554
|
+
if (!request)
|
|
555
|
+
return null;
|
|
556
|
+
this.#inFlight.delete(message.id);
|
|
557
|
+
if (request.generation !== this.#generation)
|
|
558
|
+
return null;
|
|
559
|
+
return { ...message, id: request.backendId };
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// pkgs/@akanjs/devkit/akanApp/builderRequestRelay.ts
|
|
564
|
+
class BuilderRequestRelay {
|
|
565
|
+
#logger;
|
|
566
|
+
#env;
|
|
567
|
+
#links;
|
|
568
|
+
#requests = new BuilderRequestRouter;
|
|
569
|
+
#held = [];
|
|
570
|
+
constructor({ logger, env }, links) {
|
|
571
|
+
this.#logger = logger;
|
|
572
|
+
this.#env = env;
|
|
573
|
+
this.#links = links;
|
|
574
|
+
}
|
|
575
|
+
startGeneration() {
|
|
576
|
+
this.#requests.startGeneration();
|
|
577
|
+
}
|
|
578
|
+
settle(message) {
|
|
579
|
+
return this.#requests.settle(message);
|
|
580
|
+
}
|
|
581
|
+
send(message) {
|
|
582
|
+
this.#links.markActivity();
|
|
583
|
+
if (this.#links.away()) {
|
|
584
|
+
this.#held.push(message);
|
|
585
|
+
this.#links.wake(`${message.type} arrived while suspended`);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
if (message.type === "build-csr" && !message.shell && this.#env.AKAN_DEV_CSR_REBUILD !== "1") {
|
|
589
|
+
Object.assign(this.#env, { AKAN_DEV_CSR_REBUILD: "1" });
|
|
590
|
+
this.#logger.verbose(`[csr] armed dev CSR rebuilds (${message.reason})`);
|
|
591
|
+
}
|
|
592
|
+
const builder = this.#links.builder();
|
|
593
|
+
if (message.type === "build-route" || message.type === "build-csr" || message.type === "build-graph") {
|
|
594
|
+
const outgoing = this.#requests.issue(message);
|
|
595
|
+
if (builder?.send(outgoing))
|
|
596
|
+
return;
|
|
597
|
+
this.#requests.withdraw(outgoing.id);
|
|
598
|
+
} else if (builder?.send(message))
|
|
599
|
+
return;
|
|
600
|
+
const status = builder?.status ?? "stopped";
|
|
601
|
+
if (shouldHoldForReturningBuilder({ status, heldCount: this.#held.length })) {
|
|
602
|
+
this.#held.push(message);
|
|
603
|
+
this.#logger.verbose(`[builder] holding ${message.type} until the builder is ready (${this.#held.length} waiting)`);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
if (this.#failRequest(message, `builder is ${status}; reload after the builder is ready`))
|
|
607
|
+
return;
|
|
608
|
+
this.#logger.warn("akanAppHost builder is not running");
|
|
609
|
+
}
|
|
610
|
+
flush() {
|
|
611
|
+
const pending = this.#held.splice(0);
|
|
612
|
+
if (pending.length === 0)
|
|
613
|
+
return;
|
|
614
|
+
this.#logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
|
|
615
|
+
for (const message of pending)
|
|
616
|
+
this.send(message);
|
|
617
|
+
}
|
|
618
|
+
discard(reason) {
|
|
619
|
+
const held = this.#held.splice(0);
|
|
620
|
+
if (held.length === 0)
|
|
621
|
+
return;
|
|
622
|
+
this.#logger.verbose(`[builder] dropped ${held.length} held builder request(s): ${reason}`);
|
|
623
|
+
}
|
|
624
|
+
fail(reason) {
|
|
625
|
+
const held = this.#held.splice(0);
|
|
626
|
+
if (held.length === 0)
|
|
627
|
+
return;
|
|
628
|
+
this.#logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
|
|
629
|
+
for (const message of held)
|
|
630
|
+
this.#failRequest(message, reason);
|
|
631
|
+
}
|
|
632
|
+
#failRequest(message, error) {
|
|
633
|
+
if (message.type === "build-route")
|
|
634
|
+
this.#links.toBackend({ type: "build-route-res", id: message.id, ok: false, error, kind: "unavailable" });
|
|
635
|
+
else if (message.type === "build-csr")
|
|
636
|
+
this.#links.toBackend({ type: "build-csr-res", id: message.id, ok: false, error, kind: "unavailable" });
|
|
637
|
+
else if (message.type === "build-graph")
|
|
638
|
+
this.#links.toBackend({ type: "build-graph-res", id: message.id, ok: false, error, kind: "unavailable" });
|
|
639
|
+
else
|
|
640
|
+
return false;
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
327
644
|
// pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.host.ts
|
|
328
645
|
import fs from "fs";
|
|
329
|
-
import
|
|
646
|
+
import path3 from "path";
|
|
330
647
|
import { Logger, RestartSchedule } from "akanjs/common";
|
|
331
648
|
import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
|
|
332
649
|
import { MemoryLimit } from "akanjs/server/memoryLimit";
|
|
@@ -471,7 +788,7 @@ class IncrementalBuilderHost {
|
|
|
471
788
|
this.logger.verbose(`builder spawned pid=${proc.pid} entry=${this.entry}${isRestart ? " restart=1" : ""}`);
|
|
472
789
|
}
|
|
473
790
|
#checkPatchingMarker(afterCrash) {
|
|
474
|
-
const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) =>
|
|
791
|
+
const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) => path3.join(this.app.cwdPath, ".akan/artifact", dirName, CSR_DEV_PATCHING_MARKER)).filter((marker) => fs.existsSync(marker));
|
|
475
792
|
if (markers.length === 0)
|
|
476
793
|
return;
|
|
477
794
|
if (afterCrash && !this.#patcherOff) {
|
|
@@ -583,10 +900,10 @@ class IncrementalBuilderHost {
|
|
|
583
900
|
patcherOff = false
|
|
584
901
|
} = {}) {
|
|
585
902
|
const candidates = [
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
903
|
+
path3.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
|
|
904
|
+
path3.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
|
|
905
|
+
path3.join(import.meta.dir, "incrementalBuilder.proc.js"),
|
|
906
|
+
path3.join(import.meta.dir, "incrementalBuilder.proc.ts")
|
|
590
907
|
];
|
|
591
908
|
for (const c of candidates)
|
|
592
909
|
if (await Bun.file(c).exists())
|
|
@@ -594,650 +911,664 @@ class IncrementalBuilderHost {
|
|
|
594
911
|
throw new Error(`[cli] frontend builder entry not found; looked in: ${candidates.join(", ")}`);
|
|
595
912
|
}
|
|
596
913
|
}
|
|
597
|
-
// pkgs/@akanjs/devkit/
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
914
|
+
// pkgs/@akanjs/devkit/akanApp/processRss.ts
|
|
915
|
+
var PS_RSS_TIMEOUT_MS = 2000;
|
|
916
|
+
|
|
917
|
+
class ProcessRss {
|
|
918
|
+
static async bytesOf(pid) {
|
|
919
|
+
if (process.platform === "win32")
|
|
920
|
+
return await ProcessRss.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], ProcessRss.#tasklistRssKb);
|
|
921
|
+
if (process.platform === "darwin") {
|
|
922
|
+
const footprintBytes = await ProcessRss.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], ProcessRss.#footprintKb);
|
|
923
|
+
if (footprintBytes !== null)
|
|
924
|
+
return footprintBytes;
|
|
925
|
+
}
|
|
926
|
+
const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
|
|
927
|
+
const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
|
|
928
|
+
if (vmRssKb)
|
|
929
|
+
return Number(vmRssKb) * 1024;
|
|
930
|
+
return await ProcessRss.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
|
|
604
931
|
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
this.#inFlight.clear();
|
|
611
|
-
return this.#generation;
|
|
612
|
-
}
|
|
613
|
-
issue(message) {
|
|
614
|
-
const id = this.#nextId++;
|
|
615
|
-
this.#inFlight.set(id, { backendId: message.id, generation: this.#generation });
|
|
616
|
-
return { ...message, id };
|
|
617
|
-
}
|
|
618
|
-
withdraw(id) {
|
|
619
|
-
this.#inFlight.delete(id);
|
|
620
|
-
}
|
|
621
|
-
settle(message) {
|
|
622
|
-
const request = this.#inFlight.get(message.id);
|
|
623
|
-
if (!request)
|
|
932
|
+
static async#readRssKbVia(command, parseKb, timeoutMs = PS_RSS_TIMEOUT_MS) {
|
|
933
|
+
let proc;
|
|
934
|
+
try {
|
|
935
|
+
proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
|
|
936
|
+
} catch {
|
|
624
937
|
return null;
|
|
625
|
-
|
|
626
|
-
|
|
938
|
+
}
|
|
939
|
+
const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
|
|
940
|
+
try {
|
|
941
|
+
const output = await new Response(proc.stdout).text();
|
|
942
|
+
await proc.exited;
|
|
943
|
+
const rssKb = parseKb(output);
|
|
944
|
+
return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
|
|
945
|
+
} catch {
|
|
627
946
|
return null;
|
|
628
|
-
|
|
947
|
+
} finally {
|
|
948
|
+
clearTimeout(killer);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
static #tasklistRssKb(output) {
|
|
952
|
+
const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
|
|
953
|
+
return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
|
|
954
|
+
}
|
|
955
|
+
static #footprintKb(output) {
|
|
956
|
+
const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
|
|
957
|
+
return bytes ? Number(bytes) / 1024 : Number.NaN;
|
|
629
958
|
}
|
|
630
959
|
}
|
|
631
960
|
|
|
632
|
-
// pkgs/@akanjs/devkit/akanApp/
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
var
|
|
636
|
-
var GRAPH_IMPORT_KINDS = new Set([
|
|
637
|
-
"import-statement",
|
|
638
|
-
"require-call",
|
|
639
|
-
"require-resolve",
|
|
640
|
-
"dynamic-import"
|
|
641
|
-
]);
|
|
961
|
+
// pkgs/@akanjs/devkit/akanApp/builderRssRecycler.ts
|
|
962
|
+
var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
|
|
963
|
+
var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
|
|
964
|
+
var BUILDER_RSS_SETTLE_MS = 20000;
|
|
642
965
|
|
|
643
|
-
class
|
|
644
|
-
#app;
|
|
966
|
+
class BuilderRssRecycler {
|
|
645
967
|
#logger;
|
|
646
|
-
#
|
|
647
|
-
#
|
|
648
|
-
#
|
|
649
|
-
#
|
|
650
|
-
#
|
|
651
|
-
#
|
|
652
|
-
#
|
|
653
|
-
#
|
|
654
|
-
|
|
655
|
-
|
|
968
|
+
#statuses;
|
|
969
|
+
#links;
|
|
970
|
+
#timer = null;
|
|
971
|
+
#reason = null;
|
|
972
|
+
#lastRecycleAtMono = null;
|
|
973
|
+
#ceilingTightReports = 0;
|
|
974
|
+
#ceilingTightWarned = false;
|
|
975
|
+
#settleToken = 0;
|
|
976
|
+
#over = null;
|
|
977
|
+
#ceilingAbandoned = false;
|
|
978
|
+
constructor({ logger, statuses }, links) {
|
|
656
979
|
this.#logger = logger;
|
|
980
|
+
this.#statuses = statuses;
|
|
981
|
+
this.#links = links;
|
|
657
982
|
}
|
|
658
|
-
get
|
|
659
|
-
return this.#
|
|
660
|
-
}
|
|
661
|
-
get lastRefreshSucceeded() {
|
|
662
|
-
return this.#lastRefreshSucceeded;
|
|
663
|
-
}
|
|
664
|
-
has(file) {
|
|
665
|
-
return this.#files.has(path3.resolve(file));
|
|
983
|
+
get armed() {
|
|
984
|
+
return !!this.#reason;
|
|
666
985
|
}
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
this.#
|
|
679
|
-
|
|
680
|
-
this.#logger.verbose(`[backend-graph] scanned ${files.size} files`);
|
|
681
|
-
return true;
|
|
682
|
-
} catch (err) {
|
|
683
|
-
this.#ready = this.#files.size > 0;
|
|
684
|
-
this.#lastRefreshSucceeded = false;
|
|
685
|
-
this.#logger.warn(`[backend-graph] scan failed; ${this.#ready ? "using previous graph" : "using fallback rules"}: ${err instanceof Error ? err.message : String(err)}`);
|
|
686
|
-
return this.#ready;
|
|
986
|
+
handleMetrics(metrics) {
|
|
987
|
+
if (this.#ceilingAbandoned)
|
|
988
|
+
return;
|
|
989
|
+
const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
|
|
990
|
+
const decision = decideBuilderRssRecycle({
|
|
991
|
+
rssBytes: metrics.rssBytes,
|
|
992
|
+
ceilingBytes,
|
|
993
|
+
buildFailed: this.#statuses.failedAt(metrics.generation),
|
|
994
|
+
msSinceLastRecycle: this.#lastRecycleAtMono === null ? null : performance.now() - this.#lastRecycleAtMono
|
|
995
|
+
});
|
|
996
|
+
if (decision === "below-ceiling") {
|
|
997
|
+
this.#ceilingTightReports = 0;
|
|
998
|
+
return;
|
|
687
999
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
const workspaceRoot = path3.resolve(this.#app.workspace.workspaceRoot);
|
|
694
|
-
while (queue.length > 0) {
|
|
695
|
-
const current = path3.resolve(queue.pop());
|
|
696
|
-
if (files.has(current))
|
|
697
|
-
continue;
|
|
698
|
-
if (!this.#isWorkspaceSource(current, workspaceRoot))
|
|
699
|
-
continue;
|
|
700
|
-
const imports = await this.#importsOf(current);
|
|
701
|
-
if (!imports)
|
|
702
|
-
continue;
|
|
703
|
-
files.add(current);
|
|
704
|
-
const importerDir = path3.dirname(current);
|
|
705
|
-
for (const imp of imports) {
|
|
706
|
-
if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
|
|
707
|
-
continue;
|
|
708
|
-
const resolved = this.#resolve(imp.path, importerDir);
|
|
709
|
-
if (!resolved || files.has(resolved))
|
|
710
|
-
continue;
|
|
711
|
-
queue.push(resolved);
|
|
712
|
-
}
|
|
1000
|
+
if (decision === "unbounded")
|
|
1001
|
+
return;
|
|
1002
|
+
if (decision === "build-failed") {
|
|
1003
|
+
this.#logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
|
|
1004
|
+
return;
|
|
713
1005
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
if (!stats?.isFile())
|
|
722
|
-
return null;
|
|
723
|
-
const mtimeMs = Math.round(stats.mtimeMs);
|
|
724
|
-
const cached = this.#scanCache.get(file);
|
|
725
|
-
if (cached && cached.mtimeMs === mtimeMs && cached.size === stats.size)
|
|
726
|
-
return cached.specifiers;
|
|
727
|
-
const specifiers = this.#scanImports(file, await Bun.file(file).text());
|
|
728
|
-
this.#scanCache.set(file, { mtimeMs, size: stats.size, specifiers });
|
|
729
|
-
return specifiers;
|
|
730
|
-
}
|
|
731
|
-
async#entrypoints() {
|
|
732
|
-
const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
|
|
733
|
-
const existing = [];
|
|
734
|
-
for (const root of roots) {
|
|
735
|
-
const abs = path3.resolve(root);
|
|
736
|
-
if (await Bun.file(abs).exists())
|
|
737
|
-
existing.push(abs);
|
|
1006
|
+
if (decision === "too-soon") {
|
|
1007
|
+
this.#ceilingTightReports += 1;
|
|
1008
|
+
if (this.#ceilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#ceilingTightReports))
|
|
1009
|
+
return;
|
|
1010
|
+
this.#ceilingTightWarned = true;
|
|
1011
|
+
this.#logger.warn(`[builder-recycle] the builder is back at ${asMib(metrics.rssBytes)}MiB within ${Math.round(BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS / 1000)}s of a recycle, so the ${asMib(ceilingBytes ?? 0)}MiB ceiling costs about one boot build per interval while you keep building. Raise AKAN_BUILDER_MAX_RSS_MB if that trade is wrong for this app, or set it to 0 to leave the builder unbounded.`);
|
|
1012
|
+
return;
|
|
738
1013
|
}
|
|
739
|
-
|
|
1014
|
+
this.#arm(`rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`, {
|
|
1015
|
+
rssBytes: metrics.rssBytes,
|
|
1016
|
+
ceilingBytes: ceilingBytes ?? 0
|
|
1017
|
+
});
|
|
740
1018
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
return
|
|
751
|
-
|
|
1019
|
+
async checkRecycledFloor() {
|
|
1020
|
+
if (this.#ceilingAbandoned || this.#lastRecycleAtMono === null)
|
|
1021
|
+
return;
|
|
1022
|
+
const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
|
|
1023
|
+
const pid = this.#links.builder()?.pid;
|
|
1024
|
+
if (!ceilingBytes || !pid)
|
|
1025
|
+
return;
|
|
1026
|
+
const freshRssBytes = await ProcessRss.bytesOf(pid);
|
|
1027
|
+
if (!isRssCeilingUnreachable(freshRssBytes, ceilingBytes))
|
|
1028
|
+
return;
|
|
1029
|
+
this.#ceilingAbandoned = true;
|
|
1030
|
+
this.#logger.error(`[builder-recycle] a freshly recycled builder is already at ${asMib(freshRssBytes ?? 0)}MiB with nothing built on demand, so the ${asMib(ceilingBytes)}MiB ceiling cannot be met for this app; no longer enforcing it this session. Raise AKAN_BUILDER_MAX_RSS_MB, or set it to 0 to leave the builder unbounded.`);
|
|
752
1031
|
}
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
return false;
|
|
757
|
-
if (rel.includes(`${path3.sep}node_modules${path3.sep}`) || rel.includes(`${path3.sep}.akan${path3.sep}`))
|
|
758
|
-
return false;
|
|
759
|
-
return SOURCE_EXTS.has(path3.extname(file).toLowerCase());
|
|
1032
|
+
rearm() {
|
|
1033
|
+
if (this.#reason)
|
|
1034
|
+
this.#arm(this.#reason);
|
|
760
1035
|
}
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
if (
|
|
766
|
-
return
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
return this.#tsTranspiler.scanImports(source);
|
|
1036
|
+
cancel() {
|
|
1037
|
+
this.#reason = null;
|
|
1038
|
+
this.#over = null;
|
|
1039
|
+
this.#settleToken += 1;
|
|
1040
|
+
if (!this.#timer)
|
|
1041
|
+
return;
|
|
1042
|
+
clearTimeout(this.#timer);
|
|
1043
|
+
this.#timer = null;
|
|
770
1044
|
}
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
1045
|
+
#arm(reason, over) {
|
|
1046
|
+
if (this.#reason !== reason)
|
|
1047
|
+
this.#logger.verbose(`[builder-recycle] armed (${reason}); replacing the builder once it stays quiet`);
|
|
1048
|
+
this.#reason = reason;
|
|
1049
|
+
if (over)
|
|
1050
|
+
this.#over = over;
|
|
1051
|
+
if (this.#timer)
|
|
1052
|
+
clearTimeout(this.#timer);
|
|
1053
|
+
this.#timer = setTimeout(() => {
|
|
1054
|
+
this.#timer = null;
|
|
1055
|
+
const pendingReason = this.#reason;
|
|
1056
|
+
const pendingOver = this.#over;
|
|
1057
|
+
this.#reason = null;
|
|
1058
|
+
this.#over = null;
|
|
1059
|
+
if (!pendingReason)
|
|
1060
|
+
return;
|
|
1061
|
+
if (!pendingOver) {
|
|
1062
|
+
this.#recycle(pendingReason);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
this.#recycleWhenStillOver(pendingReason, pendingOver);
|
|
1066
|
+
}, BUILDER_RSS_RECYCLE_QUIET_MS);
|
|
784
1067
|
}
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
this.#timer.unref?.();
|
|
1068
|
+
async#recycleWhenStillOver(reason, { rssBytes, ceilingBytes }) {
|
|
1069
|
+
if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
|
|
1070
|
+
this.#recycle(reason);
|
|
1071
|
+
return;
|
|
790
1072
|
}
|
|
791
|
-
this.#
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
1073
|
+
const pid = this.#links.builder()?.pid;
|
|
1074
|
+
if (!pid) {
|
|
1075
|
+
this.#recycle(reason);
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
this.#settleToken += 1;
|
|
1079
|
+
const token = this.#settleToken;
|
|
1080
|
+
this.#logger.verbose(`[builder-recycle] holding ${Math.round(BUILDER_RSS_SETTLE_MS / 1000)}s to see whether the allocator returns it (${reason})`);
|
|
1081
|
+
await Bun.sleep(BUILDER_RSS_SETTLE_MS);
|
|
1082
|
+
if (token !== this.#settleToken || this.#links.builder()?.pid !== pid || this.#links.away()) {
|
|
1083
|
+
this.#logger.verbose("[builder-recycle] settle check abandoned; the builder moved on");
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
const settledBytes = await ProcessRss.bytesOf(pid);
|
|
1087
|
+
if (settledBytes !== null && settledBytes < ceilingBytes) {
|
|
1088
|
+
this.#logger.info(`[builder-recycle] skipped: the builder fell to ${asMib(settledBytes)}MiB (ceiling ${asMib(ceilingBytes)}MiB) on its own, so a recycle would have cost a boot build for nothing`);
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
this.#recycle(settledBytes === null ? reason : `${reason}; still ${asMib(settledBytes)}MiB after settling`);
|
|
796
1092
|
}
|
|
797
|
-
#
|
|
798
|
-
if (this.#
|
|
1093
|
+
#recycle(reason) {
|
|
1094
|
+
if (this.#links.restartQueued()) {
|
|
1095
|
+
this.#logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
|
|
799
1096
|
return;
|
|
800
|
-
|
|
801
|
-
if (this.#
|
|
802
|
-
|
|
803
|
-
this.#
|
|
804
|
-
this.#
|
|
1097
|
+
}
|
|
1098
|
+
if (!this.#links.builder()?.recycle(reason))
|
|
1099
|
+
return;
|
|
1100
|
+
this.#lastRecycleAtMono = performance.now();
|
|
1101
|
+
this.#links.onRecycle();
|
|
805
1102
|
}
|
|
806
1103
|
}
|
|
807
1104
|
|
|
808
|
-
// pkgs/@akanjs/devkit/akanApp/
|
|
1105
|
+
// pkgs/@akanjs/devkit/akanApp/devBackend.ts
|
|
1106
|
+
import { RestartSchedule as RestartSchedule2 } from "akanjs/common";
|
|
809
1107
|
var backendMsgTypeSet = new Set(["build-route", "build-csr", "build-graph"]);
|
|
810
|
-
var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
|
|
811
1108
|
var BACKEND_RESTART_DEBOUNCE_MS = 120;
|
|
812
1109
|
var BACKEND_GRACEFUL_TIMEOUT_MS = 8000;
|
|
813
1110
|
var BACKEND_STDERR_TAIL_LIMIT = 40;
|
|
814
|
-
var BUILDER_READY_TIMEOUT_MS = 150000;
|
|
815
|
-
var BUILDER_START_MAX_ATTEMPTS = 3;
|
|
816
|
-
var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
|
|
817
|
-
var BUILDER_RSS_SETTLE_MS = 20000;
|
|
818
|
-
var PS_RSS_TIMEOUT_MS = 2000;
|
|
819
1111
|
|
|
820
|
-
class
|
|
821
|
-
app;
|
|
822
|
-
|
|
823
|
-
stdio;
|
|
824
|
-
|
|
825
|
-
#
|
|
826
|
-
#
|
|
827
|
-
#
|
|
828
|
-
#
|
|
829
|
-
#
|
|
830
|
-
#
|
|
831
|
-
#backendReady = false;
|
|
832
|
-
#plannedBackendStops = new WeakSet;
|
|
1112
|
+
class DevBackend {
|
|
1113
|
+
#app;
|
|
1114
|
+
#env;
|
|
1115
|
+
#stdio;
|
|
1116
|
+
#logger;
|
|
1117
|
+
#statuses;
|
|
1118
|
+
#graph;
|
|
1119
|
+
#links;
|
|
1120
|
+
#process = null;
|
|
1121
|
+
#ready = false;
|
|
1122
|
+
#plannedStops = new WeakSet;
|
|
833
1123
|
#restartTimer = null;
|
|
834
|
-
#
|
|
835
|
-
#
|
|
836
|
-
#
|
|
1124
|
+
#recovery = new RestartSchedule2(backendRecoveryPolicy);
|
|
1125
|
+
#gaveUp = false;
|
|
1126
|
+
#lifecycleState = "stopped";
|
|
837
1127
|
#pendingRestartReason = null;
|
|
838
|
-
#
|
|
839
|
-
#
|
|
840
|
-
#
|
|
841
|
-
#
|
|
842
|
-
#builderRecovery = new RestartSchedule2({ min: 2000, max: 60000 });
|
|
843
|
-
#abandonBuilderStart = null;
|
|
844
|
-
#backendStartStatus = null;
|
|
845
|
-
#backendBuildStatusGeneration = 0;
|
|
846
|
-
#backendStderrTail = [];
|
|
847
|
-
#lastGoodFrontend = {};
|
|
848
|
-
#rssRecycleTimer = null;
|
|
849
|
-
#rssRecycleReason = null;
|
|
850
|
-
#lastRssRecycleAtMono = null;
|
|
851
|
-
#rssCeilingTightReports = 0;
|
|
852
|
-
#rssCeilingTightWarned = false;
|
|
853
|
-
#rssSettleToken = 0;
|
|
854
|
-
#rssRecycleOver = null;
|
|
855
|
-
#rssCeilingAbandoned = false;
|
|
856
|
-
#buildStatusByPhase = new Map;
|
|
857
|
-
#pendingBuildStatusReplay = [];
|
|
858
|
-
#builderMessageQueue = Promise.resolve();
|
|
859
|
-
#backendGraph;
|
|
860
|
-
#idleSuspendTimer = null;
|
|
861
|
-
#suspended = false;
|
|
862
|
-
#waking = false;
|
|
863
|
-
#wokeAtMono = null;
|
|
864
|
-
#idleWatcher = null;
|
|
865
|
-
#suspendedChanges = null;
|
|
866
|
-
#builderGapStamp = null;
|
|
867
|
-
#pendingBuilderMessages = [];
|
|
868
|
-
#builderRequests = new BuilderRequestRouter;
|
|
869
|
-
#builderGeneration = 0;
|
|
1128
|
+
#restart = null;
|
|
1129
|
+
#startStatus = null;
|
|
1130
|
+
#stderrTail = [];
|
|
1131
|
+
#queuedStatuses = [];
|
|
870
1132
|
constructor(app, {
|
|
871
1133
|
env,
|
|
872
|
-
stdio
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
this
|
|
878
|
-
this.#
|
|
879
|
-
this.#
|
|
1134
|
+
stdio,
|
|
1135
|
+
logger,
|
|
1136
|
+
statuses,
|
|
1137
|
+
graph
|
|
1138
|
+
}, links) {
|
|
1139
|
+
this.#app = app;
|
|
1140
|
+
this.#env = env;
|
|
1141
|
+
this.#stdio = stdio;
|
|
1142
|
+
this.#logger = logger;
|
|
1143
|
+
this.#statuses = statuses;
|
|
1144
|
+
this.#graph = graph;
|
|
1145
|
+
this.#links = links;
|
|
880
1146
|
}
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
return;
|
|
884
|
-
this.#lastDevState = state;
|
|
885
|
-
this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
|
|
886
|
-
if (state === "ready")
|
|
887
|
-
this.#bootLatch.ready();
|
|
1147
|
+
get running() {
|
|
1148
|
+
return !!this.#process;
|
|
888
1149
|
}
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
await this.#stopBackend();
|
|
892
|
-
if (this.#builder)
|
|
893
|
-
this.#stopBuilder();
|
|
894
|
-
const [redisHost] = await Promise.all([
|
|
895
|
-
this.#prepareDatabase("redis"),
|
|
896
|
-
this.#backendGraph.refresh(),
|
|
897
|
-
this.#startBuilder()
|
|
898
|
-
]);
|
|
899
|
-
Object.assign(this.env, { REDIS_HOST: redisHost });
|
|
900
|
-
this.#startBackend();
|
|
901
|
-
this.#armIdleSuspend();
|
|
902
|
-
return this;
|
|
1150
|
+
get ready() {
|
|
1151
|
+
return this.#ready;
|
|
903
1152
|
}
|
|
904
|
-
|
|
905
|
-
this.#
|
|
906
|
-
this.#pendingRecycle = null;
|
|
907
|
-
this.#cancelIdleSuspend();
|
|
908
|
-
this.#stopIdleWatcher();
|
|
909
|
-
this.#clearRestartTimers();
|
|
910
|
-
this.#abandonBuilderStart?.(new Error("dev server stopped before the builder was ready"));
|
|
911
|
-
this.#pendingRestartReason = null;
|
|
912
|
-
this.#failPendingBuilderMessages("dev server is shutting down");
|
|
913
|
-
await this.#backendRestart;
|
|
914
|
-
await this.#stopBackend();
|
|
915
|
-
this.#stopBuilder();
|
|
916
|
-
return this;
|
|
1153
|
+
get gaveUp() {
|
|
1154
|
+
return this.#gaveUp;
|
|
917
1155
|
}
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
clearTimeout(this.#restartTimer);
|
|
921
|
-
this.#restartTimer = null;
|
|
922
|
-
this.#backendRecovery.cancel();
|
|
923
|
-
this.#builderRecovery.cancel();
|
|
1156
|
+
get lifecycleState() {
|
|
1157
|
+
return this.#lifecycleState;
|
|
924
1158
|
}
|
|
925
|
-
|
|
926
|
-
this
|
|
1159
|
+
get restartScheduled() {
|
|
1160
|
+
return !!this.#restartTimer;
|
|
927
1161
|
}
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
|
|
931
|
-
if (policy === "none")
|
|
932
|
-
return "localhost";
|
|
933
|
-
if (policy === "required")
|
|
934
|
-
return await createTunnel(type, { app: this.app, environment });
|
|
935
|
-
try {
|
|
936
|
-
return await createTunnel(type, { app: this.app, environment });
|
|
937
|
-
} catch (error) {
|
|
938
|
-
this.logger.warn(`${error instanceof Error ? error.message : String(error)} - continuing without Redis: the single database mode does not use it unless an app adaptor does`);
|
|
939
|
-
return UNAVAILABLE_REDIS_HOST;
|
|
940
|
-
}
|
|
1162
|
+
get recovering() {
|
|
1163
|
+
return this.#recovery.pending;
|
|
941
1164
|
}
|
|
942
|
-
|
|
943
|
-
|
|
1165
|
+
get restartPending() {
|
|
1166
|
+
return !!(this.#restartTimer || this.#restart || this.#recovery.pending);
|
|
1167
|
+
}
|
|
1168
|
+
get restarting() {
|
|
1169
|
+
return this.#restart;
|
|
1170
|
+
}
|
|
1171
|
+
start(startStatus = null) {
|
|
1172
|
+
if (this.#links.isStopping())
|
|
944
1173
|
return;
|
|
945
|
-
if (this.#
|
|
946
|
-
this
|
|
947
|
-
return;
|
|
948
|
-
}
|
|
949
|
-
this.#
|
|
950
|
-
this.#
|
|
951
|
-
this.#
|
|
952
|
-
this.#
|
|
953
|
-
this.#
|
|
954
|
-
this.#
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
env: this.env,
|
|
1174
|
+
if (this.#process) {
|
|
1175
|
+
this.#logger.warn(`backend pid=${this.#process.pid} is still running; not starting a second one`);
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
this.#links.beforeSpawn();
|
|
1179
|
+
this.#startStatus = startStatus;
|
|
1180
|
+
this.#gaveUp = false;
|
|
1181
|
+
this.#setLifecycleState("starting");
|
|
1182
|
+
this.#ready = false;
|
|
1183
|
+
this.#stderrTail = [];
|
|
1184
|
+
const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
|
|
1185
|
+
cwd: this.#app.workspace.workspaceRoot,
|
|
1186
|
+
stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
|
|
1187
|
+
env: this.#env,
|
|
960
1188
|
ipc: (msg) => {
|
|
961
1189
|
if (!msg || typeof msg !== "object")
|
|
962
1190
|
return;
|
|
963
1191
|
if (msg.type === "backend-ready") {
|
|
964
|
-
this.#
|
|
965
|
-
this.#
|
|
966
|
-
this.#
|
|
967
|
-
this.#
|
|
968
|
-
this
|
|
1192
|
+
this.#ready = true;
|
|
1193
|
+
this.#recovery.reset();
|
|
1194
|
+
this.#setLifecycleState("ready", `pid=${msg.pid}`);
|
|
1195
|
+
this.#recordReadyStatus();
|
|
1196
|
+
this.#logger.verbose(`backend ready pid=${msg.pid}`);
|
|
969
1197
|
this.#forgetRouteBuildStatus();
|
|
970
|
-
this
|
|
1198
|
+
this.replay();
|
|
971
1199
|
return;
|
|
972
1200
|
}
|
|
973
1201
|
if (msg.type === "build-status") {
|
|
974
|
-
const status = this.#
|
|
1202
|
+
const status = this.#statuses.recordBackend({
|
|
975
1203
|
generation: normalizeBackendReportedGeneration(msg.data.generation),
|
|
976
1204
|
ok: msg.data.ok,
|
|
977
1205
|
files: msg.data.files,
|
|
978
1206
|
message: msg.data.message
|
|
979
1207
|
});
|
|
980
|
-
this
|
|
1208
|
+
this.sendOrQueueStatus(status);
|
|
981
1209
|
if (!status.ok)
|
|
982
|
-
this.#
|
|
1210
|
+
this.#links.emit("failed", status.message);
|
|
983
1211
|
return;
|
|
984
1212
|
}
|
|
985
1213
|
if (backendMsgTypeSet.has(msg.type))
|
|
986
|
-
this.#
|
|
1214
|
+
this.#links.toBuilder(msg);
|
|
987
1215
|
},
|
|
988
1216
|
serialization: "advanced",
|
|
989
1217
|
onExit: () => {
|
|
990
|
-
this.#
|
|
991
|
-
if (this.#
|
|
992
|
-
this.#
|
|
993
|
-
if (this.#
|
|
994
|
-
this.#
|
|
1218
|
+
this.#ready = false;
|
|
1219
|
+
if (this.#process === backend)
|
|
1220
|
+
this.#process = null;
|
|
1221
|
+
if (this.#plannedStops.has(backend)) {
|
|
1222
|
+
this.#plannedStops.delete(backend);
|
|
995
1223
|
return;
|
|
996
1224
|
}
|
|
997
|
-
this.#
|
|
1225
|
+
this.#scheduleRecovery("backend-exit");
|
|
998
1226
|
}
|
|
999
1227
|
});
|
|
1000
|
-
this.#
|
|
1001
|
-
this
|
|
1002
|
-
if (this
|
|
1003
|
-
this.#
|
|
1004
|
-
this.#
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
#recordBackendStderr(chunk) {
|
|
1008
|
-
const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
|
|
1009
|
-
if (lines.length === 0)
|
|
1010
|
-
return;
|
|
1011
|
-
this.#backendStderrTail.push(...lines);
|
|
1012
|
-
if (this.#backendStderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
|
|
1013
|
-
this.#backendStderrTail.splice(0, this.#backendStderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
async#forwardBackendStream(stream, kind) {
|
|
1017
|
-
if (!stream)
|
|
1018
|
-
return;
|
|
1019
|
-
const decoder = new TextDecoder;
|
|
1020
|
-
try {
|
|
1021
|
-
for await (const chunk of stream) {
|
|
1022
|
-
const text = decoder.decode(chunk, { stream: true });
|
|
1023
|
-
if (!text)
|
|
1024
|
-
continue;
|
|
1025
|
-
if (kind === "stderr") {
|
|
1026
|
-
this.#recordBackendStderr(text);
|
|
1027
|
-
process.stderr.write(text);
|
|
1028
|
-
} else
|
|
1029
|
-
process.stdout.write(text);
|
|
1030
|
-
}
|
|
1031
|
-
} catch {}
|
|
1032
|
-
}
|
|
1033
|
-
#nextBackendBuildStatusGeneration(generation) {
|
|
1034
|
-
if (typeof generation === "number") {
|
|
1035
|
-
this.#backendBuildStatusGeneration = Math.max(this.#backendBuildStatusGeneration, generation);
|
|
1036
|
-
return generation;
|
|
1037
|
-
}
|
|
1038
|
-
this.#backendBuildStatusGeneration += 1;
|
|
1039
|
-
return this.#backendBuildStatusGeneration;
|
|
1040
|
-
}
|
|
1041
|
-
#recordBackendBuildStatus({
|
|
1042
|
-
generation,
|
|
1043
|
-
ok,
|
|
1044
|
-
files,
|
|
1045
|
-
message
|
|
1046
|
-
}) {
|
|
1047
|
-
const status = createBackendBuildStatus({
|
|
1048
|
-
generation: this.#nextBackendBuildStatusGeneration(generation),
|
|
1049
|
-
ok,
|
|
1050
|
-
files,
|
|
1051
|
-
message
|
|
1052
|
-
});
|
|
1053
|
-
this.#recordBuildStatus(status);
|
|
1054
|
-
return status;
|
|
1055
|
-
}
|
|
1056
|
-
#recordBackendReadyStatus() {
|
|
1057
|
-
const previous = this.#buildStatusByPhase.get("backend");
|
|
1058
|
-
const startStatus = this.#backendStartStatus;
|
|
1059
|
-
if (startStatus || previous?.ok === false) {
|
|
1060
|
-
const status = this.#recordBackendBuildStatus({
|
|
1061
|
-
generation: startStatus?.generation ?? previous?.generation,
|
|
1062
|
-
ok: true,
|
|
1063
|
-
files: startStatus?.files ?? previous?.files ?? [],
|
|
1064
|
-
message: "Backend ready"
|
|
1065
|
-
});
|
|
1066
|
-
this.#sendOrQueueBuildStatus(status);
|
|
1228
|
+
this.#process = backend;
|
|
1229
|
+
this.#logger.verbose(`backend spawned pid=${backend.pid}`);
|
|
1230
|
+
if (this.#stdio === "pipe") {
|
|
1231
|
+
this.#forwardStream(backend.stderr, "stderr");
|
|
1232
|
+
this.#forwardStream(backend.stdout, "stdout");
|
|
1067
1233
|
}
|
|
1068
|
-
this.#backendStartStatus = null;
|
|
1069
1234
|
}
|
|
1070
|
-
|
|
1071
|
-
if (this.#
|
|
1072
|
-
return;
|
|
1073
|
-
const prev = this.#backendLifecycleState;
|
|
1074
|
-
this.#backendLifecycleState = next;
|
|
1075
|
-
this.logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
|
|
1076
|
-
this.#emitDevEvent(devHostStateOf(next, this.#backendGaveUp), detail);
|
|
1077
|
-
}
|
|
1078
|
-
#sendToBackend(message) {
|
|
1079
|
-
if (!this.#backend || !this.#backendReady) {
|
|
1235
|
+
send(message) {
|
|
1236
|
+
if (!this.#process || !this.#ready) {
|
|
1080
1237
|
if (message.type === "css-updated" || message.type === "pages-updated" || message.type === "build-status") {
|
|
1081
|
-
this
|
|
1238
|
+
this.#logger.verbose(`backend is not ready; will replay ${message.type}`);
|
|
1082
1239
|
return;
|
|
1083
1240
|
}
|
|
1084
1241
|
if (message.type !== "builder-ready")
|
|
1085
|
-
this
|
|
1242
|
+
this.#logger.warn(`backend is not ready; dropping ${message.type}`);
|
|
1086
1243
|
return;
|
|
1087
1244
|
}
|
|
1088
1245
|
try {
|
|
1089
|
-
this.#
|
|
1246
|
+
this.#process.send(message);
|
|
1090
1247
|
} catch (err) {
|
|
1091
|
-
this
|
|
1248
|
+
this.#logger.warn(`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
sendOrQueueStatus(status) {
|
|
1252
|
+
if (!this.#process || shouldQueueBuildStatusReplay(this.#ready, this.#queuedStatuses.length)) {
|
|
1253
|
+
this.#queuedStatuses.push(status);
|
|
1254
|
+
this.#logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
this.send({ type: "build-status", data: status });
|
|
1258
|
+
}
|
|
1259
|
+
replay() {
|
|
1260
|
+
if (!this.#ready)
|
|
1261
|
+
return;
|
|
1262
|
+
const { css, pages } = this.#statuses.lastGood;
|
|
1263
|
+
if (css)
|
|
1264
|
+
this.send(css);
|
|
1265
|
+
if (pages)
|
|
1266
|
+
this.send(pages);
|
|
1267
|
+
const queuedStatuses = this.#queuedStatuses.splice(0);
|
|
1268
|
+
for (const status of this.#statuses.replaySequence(queuedStatuses)) {
|
|
1269
|
+
this.send({ type: "build-status", data: status });
|
|
1092
1270
|
}
|
|
1093
1271
|
}
|
|
1094
|
-
|
|
1095
|
-
|
|
1272
|
+
dropQueuedStatuses() {
|
|
1273
|
+
this.#queuedStatuses = [];
|
|
1274
|
+
}
|
|
1275
|
+
async stop() {
|
|
1276
|
+
if (!this.#process)
|
|
1096
1277
|
return;
|
|
1097
|
-
const backend = this.#
|
|
1098
|
-
this.#
|
|
1099
|
-
this.#
|
|
1100
|
-
this.#
|
|
1101
|
-
this
|
|
1278
|
+
const backend = this.#process;
|
|
1279
|
+
this.#plannedStops.add(backend);
|
|
1280
|
+
this.#ready = false;
|
|
1281
|
+
this.#setLifecycleState("stopping", `pid=${backend.pid}`);
|
|
1282
|
+
this.#logger.verbose(`stopping backend pid=${backend.pid}`);
|
|
1102
1283
|
try {
|
|
1103
1284
|
backend.kill("SIGTERM");
|
|
1104
1285
|
const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), BACKEND_GRACEFUL_TIMEOUT_MS));
|
|
1105
1286
|
const result = await Promise.race([backend.exited, timeout]);
|
|
1106
1287
|
if (result === "timeout") {
|
|
1107
|
-
this
|
|
1288
|
+
this.#logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
|
|
1108
1289
|
backend.kill("SIGKILL");
|
|
1109
1290
|
await backend.exited.catch(() => {
|
|
1110
1291
|
return;
|
|
1111
1292
|
});
|
|
1112
1293
|
}
|
|
1113
1294
|
} finally {
|
|
1114
|
-
if (this.#
|
|
1115
|
-
this.#
|
|
1116
|
-
this.#
|
|
1295
|
+
if (this.#process === backend)
|
|
1296
|
+
this.#process = null;
|
|
1297
|
+
this.#setLifecycleState("stopped", `pid=${backend.pid}`);
|
|
1117
1298
|
}
|
|
1118
1299
|
}
|
|
1119
|
-
|
|
1300
|
+
cancelTimers() {
|
|
1301
|
+
if (this.#restartTimer)
|
|
1302
|
+
clearTimeout(this.#restartTimer);
|
|
1303
|
+
this.#restartTimer = null;
|
|
1304
|
+
this.#recovery.cancel();
|
|
1305
|
+
}
|
|
1306
|
+
dropPendingRestart() {
|
|
1307
|
+
this.#pendingRestartReason = null;
|
|
1308
|
+
}
|
|
1309
|
+
scheduleRestart(reason) {
|
|
1120
1310
|
this.#pendingRestartReason = mergeBackendRestartReasons(this.#pendingRestartReason, reason);
|
|
1121
1311
|
const pending = this.#pendingRestartReason;
|
|
1122
|
-
this.#
|
|
1123
|
-
this.#
|
|
1312
|
+
this.#setLifecycleState("restart-pending", `generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`);
|
|
1313
|
+
this.#recovery.cancel();
|
|
1124
1314
|
if (this.#restartTimer)
|
|
1125
1315
|
clearTimeout(this.#restartTimer);
|
|
1126
1316
|
this.#restartTimer = setTimeout(() => {
|
|
1127
1317
|
this.#restartTimer = null;
|
|
1128
|
-
this.#
|
|
1129
|
-
this.#
|
|
1318
|
+
this.#restart ??= this.#drainRestarts().finally(() => {
|
|
1319
|
+
this.#restart = null;
|
|
1130
1320
|
});
|
|
1131
1321
|
}, BACKEND_RESTART_DEBOUNCE_MS);
|
|
1132
1322
|
}
|
|
1133
|
-
|
|
1134
|
-
|
|
1323
|
+
reviveAfterGreenBuild(status) {
|
|
1324
|
+
if (!status.ok || !this.#gaveUp || this.#process || this.#recovery.pending)
|
|
1325
|
+
return;
|
|
1326
|
+
this.#logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
|
|
1327
|
+
this.#recovery.reset();
|
|
1328
|
+
this.start({ generation: status.generation, files: status.files });
|
|
1329
|
+
}
|
|
1330
|
+
#recordStderr(chunk) {
|
|
1331
|
+
const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
|
|
1332
|
+
if (lines.length === 0)
|
|
1333
|
+
return;
|
|
1334
|
+
this.#stderrTail.push(...lines);
|
|
1335
|
+
if (this.#stderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
|
|
1336
|
+
this.#stderrTail.splice(0, this.#stderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
async#forwardStream(stream, kind) {
|
|
1340
|
+
if (!stream)
|
|
1341
|
+
return;
|
|
1342
|
+
const decoder = new TextDecoder;
|
|
1343
|
+
try {
|
|
1344
|
+
for await (const chunk of stream) {
|
|
1345
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
1346
|
+
if (!text)
|
|
1347
|
+
continue;
|
|
1348
|
+
if (kind === "stderr") {
|
|
1349
|
+
this.#recordStderr(text);
|
|
1350
|
+
process.stderr.write(text);
|
|
1351
|
+
} else
|
|
1352
|
+
process.stdout.write(text);
|
|
1353
|
+
}
|
|
1354
|
+
} catch {}
|
|
1355
|
+
}
|
|
1356
|
+
#recordReadyStatus() {
|
|
1357
|
+
const previous = this.#statuses.phase("backend");
|
|
1358
|
+
const startStatus = this.#startStatus;
|
|
1359
|
+
if (startStatus || previous?.ok === false) {
|
|
1360
|
+
const status = this.#statuses.recordBackend({
|
|
1361
|
+
generation: startStatus?.generation ?? previous?.generation,
|
|
1362
|
+
ok: true,
|
|
1363
|
+
files: startStatus?.files ?? previous?.files ?? [],
|
|
1364
|
+
message: "Backend ready"
|
|
1365
|
+
});
|
|
1366
|
+
this.sendOrQueueStatus(status);
|
|
1367
|
+
}
|
|
1368
|
+
this.#startStatus = null;
|
|
1369
|
+
}
|
|
1370
|
+
#forgetRouteBuildStatus() {
|
|
1371
|
+
this.#statuses.forgetRoute();
|
|
1372
|
+
this.#queuedStatuses = this.#queuedStatuses.filter((status) => status.phase !== "route");
|
|
1373
|
+
}
|
|
1374
|
+
#setLifecycleState(next, detail) {
|
|
1375
|
+
if (this.#lifecycleState === next && !detail)
|
|
1376
|
+
return;
|
|
1377
|
+
const prev = this.#lifecycleState;
|
|
1378
|
+
this.#lifecycleState = next;
|
|
1379
|
+
this.#logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
|
|
1380
|
+
this.#links.emit(devHostStateOf(next, this.#gaveUp), detail);
|
|
1381
|
+
}
|
|
1382
|
+
async#drainRestarts() {
|
|
1383
|
+
while (this.#pendingRestartReason && !this.#restartTimer && !this.#links.isStopping()) {
|
|
1135
1384
|
const next = this.#pendingRestartReason;
|
|
1136
1385
|
this.#pendingRestartReason = null;
|
|
1137
|
-
await this.#
|
|
1138
|
-
}
|
|
1139
|
-
}
|
|
1140
|
-
async#
|
|
1141
|
-
this
|
|
1142
|
-
this.#
|
|
1143
|
-
await Promise.all([this
|
|
1144
|
-
this
|
|
1145
|
-
}
|
|
1146
|
-
#
|
|
1147
|
-
if (this.#
|
|
1148
|
-
return;
|
|
1149
|
-
if (this.#
|
|
1150
|
-
const message = `Backend exited ${this.#
|
|
1151
|
-
this.#
|
|
1152
|
-
this.#
|
|
1153
|
-
this
|
|
1154
|
-
if (this.#
|
|
1155
|
-
this
|
|
1156
|
-
${this.#
|
|
1386
|
+
await this.#restartWith(next);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
async#restartWith(reason) {
|
|
1390
|
+
this.#logger.verbose(`[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`);
|
|
1391
|
+
this.#recovery.reset();
|
|
1392
|
+
await Promise.all([this.stop(), this.#graph.refresh()]);
|
|
1393
|
+
this.start({ generation: reason.generation, files: reason.files });
|
|
1394
|
+
}
|
|
1395
|
+
#scheduleRecovery(reason) {
|
|
1396
|
+
if (this.#recovery.pending || this.#process)
|
|
1397
|
+
return;
|
|
1398
|
+
if (this.#recovery.exhausted) {
|
|
1399
|
+
const message = `Backend exited ${this.#recovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
|
|
1400
|
+
this.#gaveUp = true;
|
|
1401
|
+
this.#setLifecycleState("stopped", `gave up after ${this.#recovery.attempts} recovery attempts`);
|
|
1402
|
+
this.#logger.error(`[backend-recovery] ${message}`);
|
|
1403
|
+
if (this.#stderrTail.length > 0) {
|
|
1404
|
+
this.#logger.error(`[backend-recovery] recent backend stderr:
|
|
1405
|
+
${this.#stderrTail.join(`
|
|
1157
1406
|
`)}`);
|
|
1158
1407
|
}
|
|
1159
|
-
const abandonedStatus = this.#
|
|
1160
|
-
this
|
|
1408
|
+
const abandonedStatus = this.#statuses.recordBackend({ ok: false, files: [], message });
|
|
1409
|
+
this.sendOrQueueStatus(abandonedStatus);
|
|
1161
1410
|
return;
|
|
1162
1411
|
}
|
|
1163
|
-
this.#
|
|
1164
|
-
const delay = this.#
|
|
1165
|
-
const failureStatus = this.#
|
|
1412
|
+
this.#setLifecycleState("recovering", reason);
|
|
1413
|
+
const delay = this.#recovery.next();
|
|
1414
|
+
const failureStatus = this.#statuses.recordBackend({
|
|
1166
1415
|
ok: false,
|
|
1167
1416
|
files: [],
|
|
1168
1417
|
message: `Backend exited unexpectedly (${reason}); restarting in ${delay}ms`
|
|
1169
1418
|
});
|
|
1170
|
-
this
|
|
1171
|
-
this
|
|
1172
|
-
if (this.#
|
|
1173
|
-
this
|
|
1174
|
-
${this.#
|
|
1419
|
+
this.sendOrQueueStatus(failureStatus);
|
|
1420
|
+
this.#logger.warn(`[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#recovery.attempts})`);
|
|
1421
|
+
if (this.#stderrTail.length > 0) {
|
|
1422
|
+
this.#logger.warn(`[backend-recovery] recent backend stderr:
|
|
1423
|
+
${this.#stderrTail.join(`
|
|
1175
1424
|
`)}`);
|
|
1176
1425
|
}
|
|
1177
|
-
this.#
|
|
1178
|
-
if (this.#
|
|
1426
|
+
this.#recovery.arm(delay, () => {
|
|
1427
|
+
if (this.#process)
|
|
1179
1428
|
return;
|
|
1180
|
-
this.#
|
|
1181
|
-
if (!this.#
|
|
1182
|
-
this
|
|
1429
|
+
this.#graph.refresh().finally(() => {
|
|
1430
|
+
if (!this.#process)
|
|
1431
|
+
this.start({ generation: failureStatus.generation, files: failureStatus.files });
|
|
1183
1432
|
});
|
|
1184
1433
|
});
|
|
1185
1434
|
}
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
// pkgs/@akanjs/devkit/akanApp/devBootLatch.ts
|
|
1438
|
+
class DevBootLatch {
|
|
1439
|
+
#onBooted;
|
|
1440
|
+
#waitMs;
|
|
1441
|
+
#ready = false;
|
|
1442
|
+
#armed = false;
|
|
1443
|
+
#booted = false;
|
|
1444
|
+
#timer = null;
|
|
1445
|
+
constructor(onBooted, { waitMs = 30000 } = {}) {
|
|
1446
|
+
this.#onBooted = onBooted;
|
|
1447
|
+
this.#waitMs = waitMs;
|
|
1190
1448
|
}
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
if (message.type === "build-status") {
|
|
1197
|
-
this.#recordBuildStatus(message.data);
|
|
1198
|
-
this.#sendOrQueueBuildStatus(message.data);
|
|
1199
|
-
this.#reviveBackendAfterGreenBuild(message.data);
|
|
1200
|
-
await this.#resumeFailedRecycle(message.data);
|
|
1201
|
-
return;
|
|
1449
|
+
ready() {
|
|
1450
|
+
this.#ready = true;
|
|
1451
|
+
if (!this.#armed && !this.#timer) {
|
|
1452
|
+
this.#timer = setTimeout(() => this.armed(), this.#waitMs);
|
|
1453
|
+
this.#timer.unref?.();
|
|
1202
1454
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1455
|
+
this.#release();
|
|
1456
|
+
}
|
|
1457
|
+
armed() {
|
|
1458
|
+
this.#armed = true;
|
|
1459
|
+
this.#release();
|
|
1460
|
+
}
|
|
1461
|
+
#release() {
|
|
1462
|
+
if (this.#booted || !this.#ready || !this.#armed)
|
|
1205
1463
|
return;
|
|
1464
|
+
this.#booted = true;
|
|
1465
|
+
if (this.#timer)
|
|
1466
|
+
clearTimeout(this.#timer);
|
|
1467
|
+
this.#timer = null;
|
|
1468
|
+
this.#onBooted();
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// pkgs/@akanjs/devkit/akanApp/devBuilder.ts
|
|
1473
|
+
import { RestartSchedule as RestartSchedule3 } from "akanjs/common";
|
|
1474
|
+
var BUILDER_READY_TIMEOUT_MS = 150000;
|
|
1475
|
+
var BUILDER_START_MAX_ATTEMPTS = 3;
|
|
1476
|
+
|
|
1477
|
+
class DevBuilder {
|
|
1478
|
+
#app;
|
|
1479
|
+
#env;
|
|
1480
|
+
#stdio;
|
|
1481
|
+
#logger;
|
|
1482
|
+
#links;
|
|
1483
|
+
#host = null;
|
|
1484
|
+
#patcherOff = false;
|
|
1485
|
+
#recovery = new RestartSchedule3({ min: 2000, max: 60000 });
|
|
1486
|
+
#abandonStart = null;
|
|
1487
|
+
#generation = 0;
|
|
1488
|
+
constructor(app, { env, stdio, logger }, links) {
|
|
1489
|
+
this.#app = app;
|
|
1490
|
+
this.#env = env;
|
|
1491
|
+
this.#stdio = stdio;
|
|
1492
|
+
this.#logger = logger;
|
|
1493
|
+
this.#links = links;
|
|
1494
|
+
}
|
|
1495
|
+
get current() {
|
|
1496
|
+
return this.#host;
|
|
1497
|
+
}
|
|
1498
|
+
get recovering() {
|
|
1499
|
+
return this.#recovery.pending;
|
|
1500
|
+
}
|
|
1501
|
+
async start({ announceBootState = false } = {}) {
|
|
1502
|
+
const startTime = Date.now();
|
|
1503
|
+
this.#app.verbose(`[cli] waiting for builder to complete initial base build\u2026`);
|
|
1504
|
+
let lastError;
|
|
1505
|
+
for (let attempt = 1;attempt <= BUILDER_START_MAX_ATTEMPTS; attempt++) {
|
|
1506
|
+
const builder = await IncrementalBuilderHost.create(this.#app, this.#env, (msg) => {
|
|
1507
|
+
this.#links.onMessage(msg);
|
|
1508
|
+
}, {
|
|
1509
|
+
stdio: this.#stdio,
|
|
1510
|
+
onOutput: (kind, text) => void (kind === "stderr" ? process.stderr : process.stdout).write(text),
|
|
1511
|
+
patcherOff: this.#patcherOff
|
|
1512
|
+
});
|
|
1513
|
+
if (this.#links.isStopping()) {
|
|
1514
|
+
builder.stop();
|
|
1515
|
+
throw new Error("dev server stopped before the builder started");
|
|
1516
|
+
}
|
|
1517
|
+
this.#host = builder;
|
|
1518
|
+
try {
|
|
1519
|
+
await this.#waitForReady(attempt, { announceBootState });
|
|
1520
|
+
this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms \u2014 starting backend`);
|
|
1521
|
+
return this.#host;
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
lastError = err;
|
|
1524
|
+
this.stop();
|
|
1525
|
+
if (attempt >= BUILDER_START_MAX_ATTEMPTS || this.#links.isStopping())
|
|
1526
|
+
break;
|
|
1527
|
+
this.#app.verbose(`[cli] builder failed before ready; retrying (${attempt + 1}/${BUILDER_START_MAX_ATTEMPTS})`);
|
|
1528
|
+
}
|
|
1206
1529
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1530
|
+
this.#links.onStartFailed();
|
|
1531
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
1532
|
+
}
|
|
1533
|
+
stop() {
|
|
1534
|
+
this.#links.onStop();
|
|
1535
|
+
if (!this.#host)
|
|
1210
1536
|
return;
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1537
|
+
if (this.#host.patcherOff)
|
|
1538
|
+
this.#patcherOff = true;
|
|
1539
|
+
this.#host.stop();
|
|
1540
|
+
this.#host = null;
|
|
1541
|
+
}
|
|
1542
|
+
abandonStart(error) {
|
|
1543
|
+
this.#abandonStart?.(error);
|
|
1544
|
+
}
|
|
1545
|
+
cancelRecovery() {
|
|
1546
|
+
this.#recovery.cancel();
|
|
1547
|
+
}
|
|
1548
|
+
resetRecovery() {
|
|
1549
|
+
this.#recovery.reset();
|
|
1550
|
+
}
|
|
1551
|
+
clearPatcherOff() {
|
|
1552
|
+
this.#patcherOff = false;
|
|
1553
|
+
}
|
|
1554
|
+
scheduleRecovery(reason) {
|
|
1555
|
+
if (this.#links.isStopping() || this.#recovery.pending || this.#host)
|
|
1220
1556
|
return;
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
const answer = this.#builderRequests.settle(message);
|
|
1224
|
-
if (!answer) {
|
|
1225
|
-
this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
|
|
1557
|
+
const delay = this.#recovery.schedule(() => {
|
|
1558
|
+
if (this.#links.isStopping() || this.#host)
|
|
1226
1559
|
return;
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
}
|
|
1231
|
-
this.#sendToBackend(message);
|
|
1560
|
+
this.#recover(reason);
|
|
1561
|
+
});
|
|
1562
|
+
this.#logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#recovery.attempts})`);
|
|
1232
1563
|
}
|
|
1233
|
-
|
|
1234
|
-
const generation =
|
|
1235
|
-
if (generation === undefined || generation <= this.#
|
|
1564
|
+
trackGeneration(message) {
|
|
1565
|
+
const generation = DevBuilder.#generationOf(message);
|
|
1566
|
+
if (generation === undefined || generation <= this.#generation)
|
|
1236
1567
|
return;
|
|
1237
|
-
this.#
|
|
1238
|
-
Object.assign(this
|
|
1568
|
+
this.#generation = generation;
|
|
1569
|
+
Object.assign(this.#env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
|
|
1239
1570
|
}
|
|
1240
|
-
static #
|
|
1571
|
+
static #generationOf(message) {
|
|
1241
1572
|
if (message.type === "invalidate")
|
|
1242
1573
|
return message.generation;
|
|
1243
1574
|
if (message.type === "build-status" || message.type === "builder-metrics")
|
|
@@ -1246,398 +1577,344 @@ ${this.#backendStderrTail.join(`
|
|
|
1246
1577
|
return message.data.generation;
|
|
1247
1578
|
return;
|
|
1248
1579
|
}
|
|
1249
|
-
#
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
}
|
|
1255
|
-
this.logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
|
|
1256
|
-
return false;
|
|
1257
|
-
}
|
|
1258
|
-
#handleBuilderMetrics(metrics) {
|
|
1259
|
-
if (this.#rssCeilingAbandoned)
|
|
1260
|
-
return;
|
|
1261
|
-
const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
|
|
1262
|
-
const decision = decideBuilderRssRecycle({
|
|
1263
|
-
rssBytes: metrics.rssBytes,
|
|
1264
|
-
ceilingBytes,
|
|
1265
|
-
buildFailed: hasBuildFailureForGeneration(this.#buildStatusByPhase, metrics.generation),
|
|
1266
|
-
msSinceLastRecycle: this.#lastRssRecycleAtMono === null ? null : performance.now() - this.#lastRssRecycleAtMono
|
|
1267
|
-
});
|
|
1268
|
-
if (decision === "below-ceiling") {
|
|
1269
|
-
this.#rssCeilingTightReports = 0;
|
|
1270
|
-
return;
|
|
1271
|
-
}
|
|
1272
|
-
if (decision === "unbounded")
|
|
1273
|
-
return;
|
|
1274
|
-
if (decision === "build-failed") {
|
|
1275
|
-
this.logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
|
|
1276
|
-
return;
|
|
1277
|
-
}
|
|
1278
|
-
if (decision === "too-soon") {
|
|
1279
|
-
this.#rssCeilingTightReports += 1;
|
|
1280
|
-
if (this.#rssCeilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#rssCeilingTightReports))
|
|
1580
|
+
async#recover(reason) {
|
|
1581
|
+
try {
|
|
1582
|
+
await this.start();
|
|
1583
|
+
} catch (err) {
|
|
1584
|
+
if (this.#links.isStopping())
|
|
1281
1585
|
return;
|
|
1282
|
-
this.#
|
|
1283
|
-
this.
|
|
1586
|
+
this.#logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1587
|
+
this.scheduleRecovery(reason);
|
|
1284
1588
|
return;
|
|
1285
1589
|
}
|
|
1286
|
-
this.#
|
|
1590
|
+
this.#recovery.reset();
|
|
1591
|
+
this.#logger.info("[builder-recovery] builder recovered");
|
|
1592
|
+
this.#links.onRecovered(reason);
|
|
1287
1593
|
}
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1594
|
+
#waitForReady(attempt, { announceBootState = false } = {}) {
|
|
1595
|
+
return new Promise((resolve, reject) => {
|
|
1596
|
+
if (!this.#host)
|
|
1597
|
+
throw new Error("Builder Not Found");
|
|
1598
|
+
let settled = false;
|
|
1599
|
+
const settle = (fn) => {
|
|
1600
|
+
if (settled)
|
|
1601
|
+
return;
|
|
1602
|
+
settled = true;
|
|
1603
|
+
clearTimeout(timeout);
|
|
1604
|
+
if (this.#abandonStart === abandon)
|
|
1605
|
+
this.#abandonStart = null;
|
|
1606
|
+
fn();
|
|
1607
|
+
};
|
|
1608
|
+
const abandon = (error) => settle(() => reject(error));
|
|
1609
|
+
this.#abandonStart = abandon;
|
|
1610
|
+
const timeout = setTimeout(() => {
|
|
1611
|
+
settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
|
|
1612
|
+
}, BUILDER_READY_TIMEOUT_MS);
|
|
1613
|
+
this.#host.start({
|
|
1614
|
+
announceBootState,
|
|
1615
|
+
onExit: () => {
|
|
1616
|
+
settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
|
|
1617
|
+
},
|
|
1618
|
+
onAway: () => {
|
|
1619
|
+
this.#links.onAway();
|
|
1620
|
+
},
|
|
1621
|
+
onReady: () => {
|
|
1622
|
+
settle(resolve);
|
|
1623
|
+
this.#links.onReady();
|
|
1624
|
+
},
|
|
1625
|
+
onRestartReady: () => {
|
|
1626
|
+
this.#links.onRestartReady();
|
|
1627
|
+
}
|
|
1628
|
+
});
|
|
1629
|
+
});
|
|
1300
1630
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
const pendingReason = this.#rssRecycleReason;
|
|
1312
|
-
const pendingOver = this.#rssRecycleOver;
|
|
1313
|
-
this.#rssRecycleReason = null;
|
|
1314
|
-
this.#rssRecycleOver = null;
|
|
1315
|
-
if (!pendingReason)
|
|
1316
|
-
return;
|
|
1317
|
-
if (!pendingOver) {
|
|
1318
|
-
this.#recycleBuilderForRss(pendingReason);
|
|
1319
|
-
return;
|
|
1320
|
-
}
|
|
1321
|
-
this.#recycleBuilderForRssWhenStillOver(pendingReason, pendingOver);
|
|
1322
|
-
}, BUILDER_RSS_RECYCLE_QUIET_MS);
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// pkgs/@akanjs/devkit/akanApp/devBuildStatusBoard.ts
|
|
1634
|
+
class DevBuildStatusBoard {
|
|
1635
|
+
#logger;
|
|
1636
|
+
#byPhase = new Map;
|
|
1637
|
+
#backendGeneration = 0;
|
|
1638
|
+
#lastGood = {};
|
|
1639
|
+
constructor(logger) {
|
|
1640
|
+
this.#logger = logger;
|
|
1323
1641
|
}
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1642
|
+
get lastGood() {
|
|
1643
|
+
return this.#lastGood;
|
|
1644
|
+
}
|
|
1645
|
+
get failing() {
|
|
1646
|
+
return hasAnyBuildFailure(this.#byPhase);
|
|
1647
|
+
}
|
|
1648
|
+
phase(phase) {
|
|
1649
|
+
return this.#byPhase.get(phase);
|
|
1650
|
+
}
|
|
1651
|
+
failedAt(generation) {
|
|
1652
|
+
return hasBuildFailureForGeneration(this.#byPhase, generation);
|
|
1653
|
+
}
|
|
1654
|
+
replaySequence(queued) {
|
|
1655
|
+
return buildStatusReplaySequence(queued, this.#byPhase);
|
|
1656
|
+
}
|
|
1657
|
+
nextBackendGeneration(generation) {
|
|
1658
|
+
if (typeof generation === "number") {
|
|
1659
|
+
this.#backendGeneration = Math.max(this.#backendGeneration, generation);
|
|
1660
|
+
return generation;
|
|
1328
1661
|
}
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1662
|
+
this.#backendGeneration += 1;
|
|
1663
|
+
return this.#backendGeneration;
|
|
1664
|
+
}
|
|
1665
|
+
record(status) {
|
|
1666
|
+
const recovered = shouldMarkBuildPhaseRecovered(this.#byPhase, status);
|
|
1667
|
+
if (shouldKeepBuildFailure(this.#byPhase, status))
|
|
1332
1668
|
return;
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1669
|
+
this.#byPhase.set(status.phase, status);
|
|
1670
|
+
const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
|
|
1671
|
+
if (status.ok)
|
|
1672
|
+
this.#logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
|
|
1673
|
+
else
|
|
1674
|
+
this.#logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
|
|
1675
|
+
}
|
|
1676
|
+
recordBackend({
|
|
1677
|
+
generation,
|
|
1678
|
+
ok,
|
|
1679
|
+
files,
|
|
1680
|
+
message
|
|
1681
|
+
}) {
|
|
1682
|
+
const status = createBackendBuildStatus({
|
|
1683
|
+
generation: this.nextBackendGeneration(generation),
|
|
1684
|
+
ok,
|
|
1685
|
+
files,
|
|
1686
|
+
message
|
|
1687
|
+
});
|
|
1688
|
+
this.record(status);
|
|
1689
|
+
return status;
|
|
1690
|
+
}
|
|
1691
|
+
forgetRoute() {
|
|
1692
|
+
this.#byPhase.delete("route");
|
|
1693
|
+
}
|
|
1694
|
+
reset() {
|
|
1695
|
+
this.#lastGood = {};
|
|
1696
|
+
this.#byPhase.clear();
|
|
1697
|
+
}
|
|
1698
|
+
recordLastGood(message, { supersede = false } = {}) {
|
|
1699
|
+
if (message.type === "pages-updated") {
|
|
1700
|
+
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.pages, message))
|
|
1701
|
+
return;
|
|
1702
|
+
this.#lastGood.pages = message;
|
|
1703
|
+
this.#logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
|
|
1340
1704
|
return;
|
|
1341
1705
|
}
|
|
1342
|
-
|
|
1343
|
-
if (settledBytes !== null && settledBytes < ceilingBytes) {
|
|
1344
|
-
this.logger.info(`[builder-recycle] skipped: the builder fell to ${asMib(settledBytes)}MiB (ceiling ${asMib(ceilingBytes)}MiB) on its own, so a recycle would have cost a boot build for nothing`);
|
|
1706
|
+
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.css, message))
|
|
1345
1707
|
return;
|
|
1346
|
-
|
|
1347
|
-
this.#
|
|
1348
|
-
}
|
|
1349
|
-
static async readProcessRssBytes(pid) {
|
|
1350
|
-
if (process.platform === "win32")
|
|
1351
|
-
return await AkanAppHost.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], AkanAppHost.#tasklistRssKb);
|
|
1352
|
-
if (process.platform === "darwin") {
|
|
1353
|
-
const footprintBytes = await AkanAppHost.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], AkanAppHost.#footprintKb);
|
|
1354
|
-
if (footprintBytes !== null)
|
|
1355
|
-
return footprintBytes;
|
|
1356
|
-
}
|
|
1357
|
-
const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
|
|
1358
|
-
const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
|
|
1359
|
-
if (vmRssKb)
|
|
1360
|
-
return Number(vmRssKb) * 1024;
|
|
1361
|
-
return await AkanAppHost.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
|
|
1708
|
+
this.#lastGood.css = message;
|
|
1709
|
+
this.#logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
|
|
1362
1710
|
}
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
return null;
|
|
1369
|
-
}
|
|
1370
|
-
const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
|
|
1371
|
-
try {
|
|
1372
|
-
const output = await new Response(proc.stdout).text();
|
|
1373
|
-
await proc.exited;
|
|
1374
|
-
const rssKb = parseKb(output);
|
|
1375
|
-
return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
|
|
1376
|
-
} catch {
|
|
1377
|
-
return null;
|
|
1378
|
-
} finally {
|
|
1379
|
-
clearTimeout(killer);
|
|
1711
|
+
shouldRelayRecycled(message) {
|
|
1712
|
+
const current = message.type === "pages-updated" ? this.#lastGood.pages : this.#lastGood.css;
|
|
1713
|
+
if (shouldRelayRecycledFrontendState(current, message)) {
|
|
1714
|
+
this.#logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
|
|
1715
|
+
return true;
|
|
1380
1716
|
}
|
|
1717
|
+
this.#logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
|
|
1718
|
+
return false;
|
|
1381
1719
|
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
#
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
this.#
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
// pkgs/@akanjs/devkit/akanApp/devIdleSuspend.ts
|
|
1723
|
+
class DevIdleSuspend {
|
|
1724
|
+
#app;
|
|
1725
|
+
#logger;
|
|
1726
|
+
#links;
|
|
1727
|
+
#timer = null;
|
|
1728
|
+
#suspended = false;
|
|
1729
|
+
#waking = false;
|
|
1730
|
+
#stopped = false;
|
|
1731
|
+
#wokeAtMono = null;
|
|
1732
|
+
#watcher = null;
|
|
1733
|
+
#suspendedChanges = null;
|
|
1734
|
+
constructor(app, { logger }, links) {
|
|
1735
|
+
this.#app = app;
|
|
1736
|
+
this.#logger = logger;
|
|
1737
|
+
this.#links = links;
|
|
1398
1738
|
}
|
|
1399
|
-
static
|
|
1739
|
+
static idleMs() {
|
|
1400
1740
|
return resolveIdleSuspendMs(process.env.AKAN_DEV_IDLE_SUSPEND_MS);
|
|
1401
1741
|
}
|
|
1402
|
-
|
|
1742
|
+
get away() {
|
|
1743
|
+
return !this.#stopped && (this.#suspended || this.#waking);
|
|
1744
|
+
}
|
|
1745
|
+
markActivity() {
|
|
1403
1746
|
if (this.#suspended || this.#waking)
|
|
1404
1747
|
return;
|
|
1405
|
-
this
|
|
1748
|
+
this.arm();
|
|
1406
1749
|
}
|
|
1407
|
-
|
|
1408
|
-
const idleMs =
|
|
1409
|
-
this.#
|
|
1410
|
-
if (idleMs === null)
|
|
1750
|
+
arm() {
|
|
1751
|
+
const idleMs = DevIdleSuspend.idleMs();
|
|
1752
|
+
this.#cancel();
|
|
1753
|
+
if (idleMs === null || this.#stopped)
|
|
1411
1754
|
return;
|
|
1412
|
-
this.#
|
|
1413
|
-
this.#
|
|
1755
|
+
this.#timer = setTimeout(() => {
|
|
1756
|
+
this.#timer = null;
|
|
1414
1757
|
this.#suspendWhenIdle(idleMs);
|
|
1415
1758
|
}, idleMs);
|
|
1416
1759
|
}
|
|
1417
|
-
#
|
|
1418
|
-
if (!this.#
|
|
1419
|
-
return;
|
|
1420
|
-
clearTimeout(this.#idleSuspendTimer);
|
|
1421
|
-
this.#idleSuspendTimer = null;
|
|
1422
|
-
}
|
|
1423
|
-
async#suspendWhenIdle(idleMs) {
|
|
1424
|
-
const decision = decideIdleSuspend({
|
|
1425
|
-
enabled: true,
|
|
1426
|
-
suspended: this.#suspended,
|
|
1427
|
-
builderReady: this.#builder?.status === "ready",
|
|
1428
|
-
backendReady: this.#backendReady,
|
|
1429
|
-
buildFailed: hasAnyBuildFailure(this.#buildStatusByPhase),
|
|
1430
|
-
restartPending: this.#restartPending,
|
|
1431
|
-
msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
|
|
1432
|
-
});
|
|
1433
|
-
if (decision !== "suspend") {
|
|
1434
|
-
this.logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
|
|
1435
|
-
this.#armIdleSuspend();
|
|
1760
|
+
#cancel() {
|
|
1761
|
+
if (!this.#timer)
|
|
1436
1762
|
return;
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
this.#armIdleSuspend();
|
|
1440
|
-
return;
|
|
1441
|
-
}
|
|
1442
|
-
this.#suspended = true;
|
|
1443
|
-
this.#emitDevEvent("suspended", `idle ${Math.round(idleMs / 1000)}s`);
|
|
1444
|
-
this.#stopBuilder();
|
|
1445
|
-
this.#openBuilderGap("idle suspend");
|
|
1446
|
-
this.logger.info(`[idle-suspend] no build activity for ${Math.round(idleMs / 1000)}s; released the builder \u2014 the next edit or route request brings it back`);
|
|
1447
|
-
}
|
|
1448
|
-
get #restartPending() {
|
|
1449
|
-
return !!(this.#pendingRecycle || this.#restartTimer || this.#backendRestart || this.#backendRecovery.pending || this.#builderRecovery.pending || this.#rssRecycleReason);
|
|
1450
|
-
}
|
|
1451
|
-
async#startIdleWatcher() {
|
|
1452
|
-
try {
|
|
1453
|
-
const roots = await new WatchRootResolver(this.app).resolve();
|
|
1454
|
-
const watcher = new HmrWatcher({
|
|
1455
|
-
roots,
|
|
1456
|
-
logger: this.logger,
|
|
1457
|
-
onBatch: (batch) => {
|
|
1458
|
-
this.#recordSuspendedChange(batch);
|
|
1459
|
-
this.#wakeFromIdle(`${batch.files.length} file(s) changed`);
|
|
1460
|
-
}
|
|
1461
|
-
});
|
|
1462
|
-
await watcher.start();
|
|
1463
|
-
this.#idleWatcher = watcher;
|
|
1464
|
-
return true;
|
|
1465
|
-
} catch (err) {
|
|
1466
|
-
this.logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
|
|
1467
|
-
this.#stopIdleWatcher();
|
|
1468
|
-
return false;
|
|
1469
|
-
}
|
|
1763
|
+
clearTimeout(this.#timer);
|
|
1764
|
+
this.#timer = null;
|
|
1470
1765
|
}
|
|
1471
|
-
#
|
|
1472
|
-
this.#
|
|
1473
|
-
this.#
|
|
1766
|
+
#stopWatcher() {
|
|
1767
|
+
this.#watcher?.stop();
|
|
1768
|
+
this.#watcher = null;
|
|
1474
1769
|
}
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
return;
|
|
1480
|
-
}
|
|
1481
|
-
this.#suspendedChanges = {
|
|
1482
|
-
files: [...new Set([...current.files, ...batch.files])],
|
|
1483
|
-
kinds: new Set([...current.kinds, ...batch.kinds])
|
|
1484
|
-
};
|
|
1770
|
+
stop() {
|
|
1771
|
+
this.#stopped = true;
|
|
1772
|
+
this.#cancel();
|
|
1773
|
+
this.#stopWatcher();
|
|
1485
1774
|
}
|
|
1486
|
-
async
|
|
1487
|
-
if (!this.#suspended || this.#waking)
|
|
1775
|
+
async wake(reason) {
|
|
1776
|
+
if (!this.#suspended || this.#waking || this.#stopped)
|
|
1488
1777
|
return;
|
|
1489
1778
|
this.#waking = true;
|
|
1490
|
-
this.#
|
|
1491
|
-
this.#
|
|
1779
|
+
this.#cancel();
|
|
1780
|
+
this.#stopWatcher();
|
|
1492
1781
|
const batch = this.#suspendedChanges;
|
|
1493
1782
|
this.#suspendedChanges = null;
|
|
1494
1783
|
const startedAtMono = performance.now();
|
|
1495
|
-
this
|
|
1784
|
+
this.#logger.info(`[idle-suspend] waking (${reason})`);
|
|
1496
1785
|
try {
|
|
1497
|
-
await this.#
|
|
1498
|
-
this
|
|
1786
|
+
await this.#links.wake(batch);
|
|
1787
|
+
this.#logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
|
|
1499
1788
|
} catch (err) {
|
|
1500
|
-
this
|
|
1501
|
-
this.#
|
|
1789
|
+
this.#logger.error(`[idle-suspend] wake failed; recovering the builder: ${err instanceof Error ? err.message : String(err)}`);
|
|
1790
|
+
this.#links.wakeFailed(batch?.files ?? []);
|
|
1502
1791
|
} finally {
|
|
1503
1792
|
this.#suspended = false;
|
|
1504
1793
|
this.#waking = false;
|
|
1505
1794
|
this.#wokeAtMono = performance.now();
|
|
1506
|
-
this.#
|
|
1507
|
-
this
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
}
|
|
1511
|
-
async#applyIdleWake(batch) {
|
|
1512
|
-
const files = batch?.files ?? [];
|
|
1513
|
-
if (shouldRefreshConfigOnIdleWake(batch)) {
|
|
1514
|
-
this.logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
|
|
1515
|
-
this.#discardBuilderGap("config change replaces the backend anyway");
|
|
1516
|
-
await this.#applyRecycle({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
|
|
1517
|
-
return;
|
|
1518
|
-
}
|
|
1519
|
-
if (files.length > 0)
|
|
1520
|
-
await this.#backendGraph.refresh();
|
|
1521
|
-
await this.#startBuilder({ announceBootState: true });
|
|
1522
|
-
const missed = await this.#takeBuilderGapChanges();
|
|
1523
|
-
const backendFiles = [...new Set([...files.filter((file) => this.#backendGraph.has(file)), ...missed])];
|
|
1524
|
-
if (backendFiles.length === 0)
|
|
1525
|
-
return;
|
|
1526
|
-
this.logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
|
|
1527
|
-
this.#scheduleBackendRestart({ files: backendFiles, roles: [] });
|
|
1528
|
-
}
|
|
1529
|
-
#openBuilderGap(reason) {
|
|
1530
|
-
if (this.#builderGapStamp)
|
|
1531
|
-
return;
|
|
1532
|
-
if (!this.#backendGraph.ready) {
|
|
1533
|
-
this.logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
|
|
1534
|
-
return;
|
|
1535
|
-
}
|
|
1536
|
-
this.#builderGapStamp = this.#backendGraph.fingerprint().then((stamps) => {
|
|
1537
|
-
this.logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
|
|
1538
|
-
return stamps;
|
|
1539
|
-
}).catch((err) => {
|
|
1540
|
-
this.logger.warn(`[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`);
|
|
1541
|
-
return null;
|
|
1542
|
-
});
|
|
1543
|
-
}
|
|
1544
|
-
async#takeBuilderGapChanges() {
|
|
1545
|
-
const stamping = this.#builderGapStamp;
|
|
1546
|
-
this.#builderGapStamp = null;
|
|
1547
|
-
const before = stamping ? await stamping : null;
|
|
1548
|
-
if (!before)
|
|
1549
|
-
return [];
|
|
1550
|
-
const moved = filesChangedSince(before, await this.#backendGraph.fingerprint());
|
|
1551
|
-
if (moved.length === 0) {
|
|
1552
|
-
this.logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
|
|
1553
|
-
return moved;
|
|
1795
|
+
this.#links.flushHeld();
|
|
1796
|
+
this.arm();
|
|
1797
|
+
if (!this.#stopped)
|
|
1798
|
+
this.#links.awake();
|
|
1554
1799
|
}
|
|
1555
|
-
this.logger.info(`[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`);
|
|
1556
|
-
return moved;
|
|
1557
|
-
}
|
|
1558
|
-
#discardBuilderGap(reason) {
|
|
1559
|
-
if (!this.#builderGapStamp)
|
|
1560
|
-
return;
|
|
1561
|
-
this.#builderGapStamp = null;
|
|
1562
|
-
this.logger.verbose(`[builder-gap] stamps dropped (${reason})`);
|
|
1563
|
-
}
|
|
1564
|
-
async#restartBackendForGapChanges() {
|
|
1565
|
-
const moved = await this.#takeBuilderGapChanges();
|
|
1566
|
-
if (moved.length === 0)
|
|
1567
|
-
return;
|
|
1568
|
-
this.#scheduleBackendRestart({ files: moved, roles: [] });
|
|
1569
|
-
}
|
|
1570
|
-
#flushPendingBuilderMessages() {
|
|
1571
|
-
const pending = this.#pendingBuilderMessages.splice(0);
|
|
1572
|
-
if (pending.length === 0)
|
|
1573
|
-
return;
|
|
1574
|
-
this.logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
|
|
1575
|
-
for (const message of pending)
|
|
1576
|
-
this.#sendToBuilder(message);
|
|
1577
1800
|
}
|
|
1578
|
-
#
|
|
1579
|
-
const
|
|
1580
|
-
|
|
1801
|
+
async#suspendWhenIdle(idleMs) {
|
|
1802
|
+
const decision = decideIdleSuspend({
|
|
1803
|
+
enabled: true,
|
|
1804
|
+
suspended: this.#suspended,
|
|
1805
|
+
...this.#links.readiness(),
|
|
1806
|
+
msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
|
|
1807
|
+
});
|
|
1808
|
+
if (decision !== "suspend") {
|
|
1809
|
+
this.#logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
|
|
1810
|
+
this.arm();
|
|
1581
1811
|
return;
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
const held = this.#pendingBuilderMessages.splice(0);
|
|
1586
|
-
if (held.length === 0)
|
|
1812
|
+
}
|
|
1813
|
+
if (!await this.#startWatcher()) {
|
|
1814
|
+
this.arm();
|
|
1587
1815
|
return;
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1816
|
+
}
|
|
1817
|
+
this.#suspended = true;
|
|
1818
|
+
this.#links.release(`idle ${Math.round(idleMs / 1000)}s`);
|
|
1819
|
+
this.#logger.info(`[idle-suspend] no build activity for ${Math.round(idleMs / 1000)}s; released the builder \u2014 the next edit or route request brings it back`);
|
|
1591
1820
|
}
|
|
1592
|
-
#
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1821
|
+
async#startWatcher() {
|
|
1822
|
+
try {
|
|
1823
|
+
const roots = await new WatchRootResolver(this.#app).resolve();
|
|
1824
|
+
const watcher = new HmrWatcher({
|
|
1825
|
+
roots,
|
|
1826
|
+
logger: this.#logger,
|
|
1827
|
+
onBatch: (batch) => {
|
|
1828
|
+
this.#recordSuspendedChange(batch);
|
|
1829
|
+
this.wake(`${batch.files.length} file(s) changed`);
|
|
1830
|
+
}
|
|
1831
|
+
});
|
|
1832
|
+
await watcher.start();
|
|
1833
|
+
if (this.#stopped) {
|
|
1834
|
+
watcher.stop();
|
|
1835
|
+
return false;
|
|
1836
|
+
}
|
|
1837
|
+
this.#watcher = watcher;
|
|
1838
|
+
return true;
|
|
1839
|
+
} catch (err) {
|
|
1840
|
+
this.#logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
|
|
1841
|
+
this.#stopWatcher();
|
|
1600
1842
|
return false;
|
|
1601
|
-
|
|
1843
|
+
}
|
|
1602
1844
|
}
|
|
1603
|
-
#
|
|
1604
|
-
|
|
1605
|
-
|
|
1845
|
+
#recordSuspendedChange(batch) {
|
|
1846
|
+
const current = this.#suspendedChanges;
|
|
1847
|
+
if (!current) {
|
|
1848
|
+
this.#suspendedChanges = { files: [...batch.files], kinds: new Set(batch.kinds) };
|
|
1606
1849
|
return;
|
|
1607
1850
|
}
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1851
|
+
this.#suspendedChanges = {
|
|
1852
|
+
files: [...new Set([...current.files, ...batch.files])],
|
|
1853
|
+
kinds: new Set([...current.kinds, ...batch.kinds])
|
|
1854
|
+
};
|
|
1612
1855
|
}
|
|
1613
|
-
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
// pkgs/@akanjs/devkit/akanApp/devRecycler.ts
|
|
1859
|
+
import path4 from "path";
|
|
1860
|
+
class DevRecycler {
|
|
1861
|
+
#app;
|
|
1862
|
+
#env;
|
|
1863
|
+
#logger;
|
|
1864
|
+
#isStopping;
|
|
1865
|
+
#graph;
|
|
1866
|
+
#statuses;
|
|
1867
|
+
#backend;
|
|
1868
|
+
#builder;
|
|
1869
|
+
#gap;
|
|
1870
|
+
#rss;
|
|
1871
|
+
#pending = null;
|
|
1872
|
+
#restartFailedAfterApply = null;
|
|
1873
|
+
constructor(app, parts) {
|
|
1874
|
+
this.#app = app;
|
|
1875
|
+
this.#env = parts.env;
|
|
1876
|
+
this.#logger = parts.logger;
|
|
1877
|
+
this.#isStopping = parts.isStopping;
|
|
1878
|
+
this.#graph = parts.graph;
|
|
1879
|
+
this.#statuses = parts.statuses;
|
|
1880
|
+
this.#backend = parts.backend;
|
|
1881
|
+
this.#builder = parts.builder;
|
|
1882
|
+
this.#gap = parts.gap;
|
|
1883
|
+
this.#rss = parts.rss;
|
|
1884
|
+
}
|
|
1885
|
+
get pending() {
|
|
1886
|
+
return !!this.#pending;
|
|
1887
|
+
}
|
|
1888
|
+
drop() {
|
|
1889
|
+
this.#pending = null;
|
|
1890
|
+
}
|
|
1891
|
+
async handleInvalidate(message) {
|
|
1614
1892
|
this.#logDevPlan(message);
|
|
1615
|
-
|
|
1616
|
-
this.#armRssRecycle(this.#rssRecycleReason);
|
|
1893
|
+
this.#rss.rearm();
|
|
1617
1894
|
const wantsDevHostRestart = shouldRestartDevHostByDevPlan(message);
|
|
1618
|
-
const pending = this.#
|
|
1895
|
+
const pending = this.#pending;
|
|
1619
1896
|
const resumes = !!pending && message.kinds.includes("code") && this.#touchesFailedRecycle(message.files);
|
|
1620
1897
|
if (wantsDevHostRestart || shouldRestartBuilderByDevPlan(message) || resumes) {
|
|
1621
1898
|
const refreshConfig = wantsDevHostRestart || (pending?.refreshConfig ?? false);
|
|
1622
1899
|
const merged = pending ? mergeInvalidateMessages(pending.message, message) : message;
|
|
1623
1900
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1624
|
-
if (
|
|
1625
|
-
this.#
|
|
1901
|
+
if (this.#statuses.failedAt(generation)) {
|
|
1902
|
+
this.#defer(merged, { refreshConfig, generation });
|
|
1626
1903
|
return;
|
|
1627
1904
|
}
|
|
1628
|
-
await this
|
|
1905
|
+
await this.apply(merged, refreshConfig);
|
|
1629
1906
|
return;
|
|
1630
1907
|
}
|
|
1631
1908
|
if (await this.#shouldRestartBackend(message)) {
|
|
1632
|
-
this.#
|
|
1909
|
+
this.#backend.scheduleRestart(backendRestartReasonFromMessage(message));
|
|
1633
1910
|
return;
|
|
1634
1911
|
}
|
|
1635
|
-
this.#
|
|
1912
|
+
this.#backend.send(message);
|
|
1636
1913
|
}
|
|
1637
|
-
async
|
|
1638
|
-
if (this.#
|
|
1914
|
+
async apply(message, refreshConfig) {
|
|
1915
|
+
if (this.#isStopping())
|
|
1639
1916
|
return;
|
|
1640
|
-
this.#
|
|
1917
|
+
this.#pending = null;
|
|
1641
1918
|
const progress = { applied: !refreshConfig };
|
|
1642
1919
|
try {
|
|
1643
1920
|
if (refreshConfig)
|
|
@@ -1646,144 +1923,121 @@ ${this.#backendStderrTail.join(`
|
|
|
1646
1923
|
await this.#restartDevChildren(message);
|
|
1647
1924
|
} catch (err) {
|
|
1648
1925
|
const kind = refreshConfig ? "Config" : "Runtime metadata";
|
|
1649
|
-
const generation = this.#
|
|
1926
|
+
const generation = this.#recordRestartFailure(message, err, kind, { applied: progress.applied });
|
|
1650
1927
|
if (progress.applied)
|
|
1651
1928
|
this.#restartFailedAfterApply = generation;
|
|
1652
1929
|
else
|
|
1653
|
-
this.#
|
|
1930
|
+
this.#pending = { message, refreshConfig, failed: true, failedGeneration: generation };
|
|
1654
1931
|
this.#resurrectDevChildren(message);
|
|
1655
1932
|
}
|
|
1656
1933
|
}
|
|
1657
|
-
async
|
|
1658
|
-
const pending = this.#
|
|
1934
|
+
async resumeFailed(status) {
|
|
1935
|
+
const pending = this.#pending;
|
|
1659
1936
|
if (!pending?.failed || !status.ok || status.phase !== "pages" || !this.#touchesFailedRecycle(status.files))
|
|
1660
1937
|
return;
|
|
1661
1938
|
if (status.generation <= (pending.failedGeneration ?? -1))
|
|
1662
1939
|
return;
|
|
1663
|
-
await this
|
|
1940
|
+
await this.apply(pending.message, pending.refreshConfig);
|
|
1941
|
+
}
|
|
1942
|
+
async applyIdleWake(batch) {
|
|
1943
|
+
const files = batch?.files ?? [];
|
|
1944
|
+
if (shouldRefreshConfigOnIdleWake(batch)) {
|
|
1945
|
+
this.#logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
|
|
1946
|
+
this.#gap.discard("config change replaces the backend anyway");
|
|
1947
|
+
await this.apply({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
if (files.length > 0)
|
|
1951
|
+
await this.#graph.refresh();
|
|
1952
|
+
await this.#builder.start({ announceBootState: true });
|
|
1953
|
+
const missed = await this.#gap.take();
|
|
1954
|
+
const backendFiles = [...new Set([...files.filter((file) => this.#graph.has(file)), ...missed])];
|
|
1955
|
+
if (backendFiles.length === 0)
|
|
1956
|
+
return;
|
|
1957
|
+
this.#logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
|
|
1958
|
+
this.#backend.scheduleRestart({ files: backendFiles, roles: [] });
|
|
1959
|
+
}
|
|
1960
|
+
builderRecovered(reason) {
|
|
1961
|
+
this.#gap.restartBackendForChanges();
|
|
1962
|
+
const failedAfterApply = this.#restartFailedAfterApply;
|
|
1963
|
+
this.#restartFailedAfterApply = null;
|
|
1964
|
+
const status = {
|
|
1965
|
+
generation: failedAfterApply !== null ? this.#statuses.nextBackendGeneration(failedAfterApply + 1) : reason.generation ?? this.#statuses.nextBackendGeneration(),
|
|
1966
|
+
phase: "scan",
|
|
1967
|
+
ok: true,
|
|
1968
|
+
files: reason.files,
|
|
1969
|
+
message: "Builder recovered"
|
|
1970
|
+
};
|
|
1971
|
+
this.#statuses.record(status);
|
|
1972
|
+
this.#backend.sendOrQueueStatus(status);
|
|
1973
|
+
if (!this.#backend.running && !this.#backend.recovering) {
|
|
1974
|
+
this.#backend.start({ generation: reason.generation, files: reason.files });
|
|
1975
|
+
}
|
|
1664
1976
|
}
|
|
1665
1977
|
#touchesFailedRecycle(files) {
|
|
1666
|
-
const pending = this.#
|
|
1978
|
+
const pending = this.#pending;
|
|
1667
1979
|
if (!pending?.failed)
|
|
1668
1980
|
return true;
|
|
1669
1981
|
const changed = new Set(pending.message.files);
|
|
1670
1982
|
return files.some((file) => changed.has(file));
|
|
1671
1983
|
}
|
|
1672
|
-
#
|
|
1673
|
-
this.#
|
|
1984
|
+
#defer(message, { refreshConfig, generation }) {
|
|
1985
|
+
this.#pending = { message, refreshConfig };
|
|
1674
1986
|
const kind = refreshConfig ? "Config" : "Runtime metadata";
|
|
1675
|
-
this
|
|
1987
|
+
this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart deferred generation=${generation ?? "(unknown)"}; keeping the running dev server until the build error is fixed`);
|
|
1676
1988
|
const status = {
|
|
1677
|
-
generation: generation ?? this.#
|
|
1989
|
+
generation: generation ?? this.#statuses.nextBackendGeneration(),
|
|
1678
1990
|
phase: "scan",
|
|
1679
1991
|
ok: false,
|
|
1680
1992
|
files: message.files,
|
|
1681
1993
|
message: `${kind} change is on hold while the build is failing; it will apply automatically once the error is fixed.`
|
|
1682
1994
|
};
|
|
1683
|
-
this.#
|
|
1684
|
-
this.#
|
|
1995
|
+
this.#statuses.record(status);
|
|
1996
|
+
this.#backend.sendOrQueueStatus(status);
|
|
1685
1997
|
}
|
|
1686
1998
|
#resurrectDevChildren(message) {
|
|
1687
1999
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1688
|
-
if (!this.#backend)
|
|
1689
|
-
this.#
|
|
1690
|
-
this.#
|
|
1691
|
-
}
|
|
1692
|
-
#scheduleBuilderRecovery(reason) {
|
|
1693
|
-
if (this.#stopping || this.#builderRecovery.pending || this.#builder)
|
|
1694
|
-
return;
|
|
1695
|
-
const delay = this.#builderRecovery.schedule(() => {
|
|
1696
|
-
if (this.#stopping || this.#builder)
|
|
1697
|
-
return;
|
|
1698
|
-
this.#recoverBuilder(reason);
|
|
1699
|
-
});
|
|
1700
|
-
this.logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#builderRecovery.attempts})`);
|
|
1701
|
-
}
|
|
1702
|
-
async#recoverBuilder(reason) {
|
|
1703
|
-
try {
|
|
1704
|
-
await this.#startBuilder();
|
|
1705
|
-
} catch (err) {
|
|
1706
|
-
if (this.#stopping)
|
|
1707
|
-
return;
|
|
1708
|
-
this.logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1709
|
-
this.#scheduleBuilderRecovery(reason);
|
|
1710
|
-
return;
|
|
1711
|
-
}
|
|
1712
|
-
this.#builderRecovery.reset();
|
|
1713
|
-
this.logger.info("[builder-recovery] builder recovered");
|
|
1714
|
-
this.#restartBackendForGapChanges();
|
|
1715
|
-
const failedAfterApply = this.#restartFailedAfterApply;
|
|
1716
|
-
this.#restartFailedAfterApply = null;
|
|
1717
|
-
const status = {
|
|
1718
|
-
generation: failedAfterApply !== null ? this.#nextBackendBuildStatusGeneration(failedAfterApply + 1) : reason.generation ?? this.#nextBackendBuildStatusGeneration(),
|
|
1719
|
-
phase: "scan",
|
|
1720
|
-
ok: true,
|
|
1721
|
-
files: reason.files,
|
|
1722
|
-
message: "Builder recovered"
|
|
1723
|
-
};
|
|
1724
|
-
this.#recordBuildStatus(status);
|
|
1725
|
-
this.#sendOrQueueBuildStatus(status);
|
|
1726
|
-
if (!this.#backend && !this.#backendRecovery.pending) {
|
|
1727
|
-
this.#startBackend({ generation: reason.generation, files: reason.files });
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
#reviveBackendAfterGreenBuild(status) {
|
|
1731
|
-
if (!status.ok || !this.#backendGaveUp || this.#backend || this.#backendRecovery.pending)
|
|
1732
|
-
return;
|
|
1733
|
-
this.logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
|
|
1734
|
-
this.#backendRecovery.reset();
|
|
1735
|
-
this.#startBackend({ generation: status.generation, files: status.files });
|
|
2000
|
+
if (!this.#backend.running)
|
|
2001
|
+
this.#backend.start({ generation, files: message.files });
|
|
2002
|
+
this.#builder.scheduleRecovery({ generation, files: message.files });
|
|
1736
2003
|
}
|
|
1737
2004
|
async#restartDevChildren(message) {
|
|
1738
2005
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1739
|
-
this
|
|
2006
|
+
this.#logger.warn(`[dev-host] recycling builder/backend for runtime metadata generation=${generation ?? "(unknown)"} files=${message.files.length}`);
|
|
1740
2007
|
await this.#recycleDevChildren(message);
|
|
1741
2008
|
}
|
|
1742
2009
|
async#restartDevHost(message, progress) {
|
|
1743
2010
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1744
|
-
this
|
|
2011
|
+
this.#logger.warn(`[dev-host] config change detected; restarting dev host generation=${generation ?? "(unknown)"} files=${message.files.length}`);
|
|
1745
2012
|
await this.#recycleDevChildren(message, { refreshConfig: true, progress });
|
|
1746
2013
|
}
|
|
1747
2014
|
async#recycleDevChildren(message, { refreshConfig = false, progress } = {}) {
|
|
1748
2015
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1749
|
-
this.#
|
|
1750
|
-
this.#
|
|
1751
|
-
this.#
|
|
1752
|
-
|
|
1753
|
-
this.#
|
|
1754
|
-
this.#
|
|
1755
|
-
this.#
|
|
1756
|
-
await this.#
|
|
1757
|
-
this.#
|
|
1758
|
-
this.#
|
|
2016
|
+
this.#backend.cancelTimers();
|
|
2017
|
+
this.#builder.cancelRecovery();
|
|
2018
|
+
this.#builder.resetRecovery();
|
|
2019
|
+
this.#backend.dropPendingRestart();
|
|
2020
|
+
await this.#backend.restarting;
|
|
2021
|
+
this.#statuses.reset();
|
|
2022
|
+
this.#backend.dropQueuedStatuses();
|
|
2023
|
+
await this.#backend.stop();
|
|
2024
|
+
this.#builder.stop();
|
|
2025
|
+
this.#builder.clearPatcherOff();
|
|
1759
2026
|
if (refreshConfig) {
|
|
1760
|
-
await this
|
|
1761
|
-
const { env } = await this
|
|
1762
|
-
Object.assign(this
|
|
2027
|
+
await this.#app.getConfig({ refresh: true });
|
|
2028
|
+
const { env } = await this.#app.prepareCommand("start");
|
|
2029
|
+
Object.assign(this.#env, env);
|
|
1763
2030
|
if (progress)
|
|
1764
2031
|
progress.applied = true;
|
|
1765
2032
|
}
|
|
1766
|
-
await this.#
|
|
1767
|
-
await this.#
|
|
1768
|
-
this.#
|
|
1769
|
-
}
|
|
1770
|
-
#recordLastGood(message, { supersede = false } = {}) {
|
|
1771
|
-
if (message.type === "pages-updated") {
|
|
1772
|
-
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.pages, message))
|
|
1773
|
-
return;
|
|
1774
|
-
this.#lastGoodFrontend.pages = message;
|
|
1775
|
-
this.logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
|
|
1776
|
-
return;
|
|
1777
|
-
}
|
|
1778
|
-
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.css, message))
|
|
1779
|
-
return;
|
|
1780
|
-
this.#lastGoodFrontend.css = message;
|
|
1781
|
-
this.logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
|
|
2033
|
+
await this.#graph.refresh();
|
|
2034
|
+
await this.#builder.start();
|
|
2035
|
+
this.#backend.start({ generation, files: message.files });
|
|
1782
2036
|
}
|
|
1783
|
-
#
|
|
1784
|
-
const generation = message.devPlan?.generation ?? message.generation ?? this.#
|
|
2037
|
+
#recordRestartFailure(message, err, kind, { applied }) {
|
|
2038
|
+
const generation = message.devPlan?.generation ?? message.generation ?? this.#statuses.nextBackendGeneration();
|
|
1785
2039
|
const detail = err instanceof Error ? err.message : String(err);
|
|
1786
|
-
this
|
|
2040
|
+
this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
|
|
1787
2041
|
const names = message.files.slice(0, 3).map((file) => path4.basename(file));
|
|
1788
2042
|
const saved = names.length > 0 ? names.join(", ") : "the changed file";
|
|
1789
2043
|
const status = {
|
|
@@ -1793,50 +2047,15 @@ ${this.#backendStderrTail.join(`
|
|
|
1793
2047
|
files: message.files,
|
|
1794
2048
|
message: applied ? `${kind} change applied, but the dev server failed to restart: ${detail}. It is recovering on its own.` : `${kind} change failed to apply: ${detail}. The dev server keeps running on the previous ${kind.toLowerCase()}; once it is fixed, save ${saved} again or restart the dev server to apply it.`
|
|
1795
2049
|
};
|
|
1796
|
-
this.#
|
|
1797
|
-
this.#
|
|
2050
|
+
this.#statuses.record(status);
|
|
2051
|
+
this.#backend.sendOrQueueStatus(status);
|
|
1798
2052
|
return generation;
|
|
1799
2053
|
}
|
|
1800
|
-
#recordBuildStatus(status) {
|
|
1801
|
-
const recovered = shouldMarkBuildPhaseRecovered(this.#buildStatusByPhase, status);
|
|
1802
|
-
if (shouldKeepBuildFailure(this.#buildStatusByPhase, status))
|
|
1803
|
-
return;
|
|
1804
|
-
this.#buildStatusByPhase.set(status.phase, status);
|
|
1805
|
-
const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
|
|
1806
|
-
if (status.ok)
|
|
1807
|
-
this.logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
|
|
1808
|
-
else
|
|
1809
|
-
this.logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
|
|
1810
|
-
}
|
|
1811
|
-
#sendOrQueueBuildStatus(status) {
|
|
1812
|
-
if (!this.#backend || shouldQueueBuildStatusReplay(this.#backendReady, this.#pendingBuildStatusReplay.length)) {
|
|
1813
|
-
this.#pendingBuildStatusReplay.push(status);
|
|
1814
|
-
this.logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
|
|
1815
|
-
return;
|
|
1816
|
-
}
|
|
1817
|
-
this.#sendToBackend({ type: "build-status", data: status });
|
|
1818
|
-
}
|
|
1819
|
-
#forgetRouteBuildStatus() {
|
|
1820
|
-
this.#buildStatusByPhase.delete("route");
|
|
1821
|
-
this.#pendingBuildStatusReplay = this.#pendingBuildStatusReplay.filter((status) => status.phase !== "route");
|
|
1822
|
-
}
|
|
1823
|
-
#replayBuilderState() {
|
|
1824
|
-
if (!this.#backendReady)
|
|
1825
|
-
return;
|
|
1826
|
-
if (this.#lastGoodFrontend.css)
|
|
1827
|
-
this.#sendToBackend(this.#lastGoodFrontend.css);
|
|
1828
|
-
if (this.#lastGoodFrontend.pages)
|
|
1829
|
-
this.#sendToBackend(this.#lastGoodFrontend.pages);
|
|
1830
|
-
const queuedStatuses = this.#pendingBuildStatusReplay.splice(0);
|
|
1831
|
-
for (const status of buildStatusReplaySequence(queuedStatuses, this.#buildStatusByPhase)) {
|
|
1832
|
-
this.#sendToBackend({ type: "build-status", data: status });
|
|
1833
|
-
}
|
|
1834
|
-
}
|
|
1835
2054
|
#logDevPlan(message) {
|
|
1836
2055
|
if (!message.devPlan)
|
|
1837
2056
|
return;
|
|
1838
2057
|
const { generation, roles, actions, reasonByFile } = message.devPlan;
|
|
1839
|
-
this
|
|
2058
|
+
this.#logger.verbose(`[dev-plan] generation=${generation} roles=${roles.join(",") || "(none)"} actions=${actions.join(",") || "(none)"} reasons=${Object.keys(reasonByFile).length}`);
|
|
1840
2059
|
}
|
|
1841
2060
|
async#shouldRestartBackend(message) {
|
|
1842
2061
|
if (message.kinds.length === 1 && message.kinds[0] === "css")
|
|
@@ -1844,133 +2063,236 @@ ${this.#backendStderrTail.join(`
|
|
|
1844
2063
|
if (message.devPlan) {
|
|
1845
2064
|
const shouldRestart = shouldRestartBackendByDevPlan(message) ?? false;
|
|
1846
2065
|
if (shouldRestart && message.kinds.includes("code"))
|
|
1847
|
-
await this.#
|
|
2066
|
+
await this.#graph.refresh();
|
|
1848
2067
|
return shouldRestart;
|
|
1849
2068
|
}
|
|
1850
2069
|
if (message.kinds.includes("code"))
|
|
1851
|
-
await this.#
|
|
1852
|
-
if (message.files.some((file) => this.#
|
|
2070
|
+
await this.#graph.refresh();
|
|
2071
|
+
if (message.files.some((file) => this.#graph.has(file)))
|
|
1853
2072
|
return true;
|
|
1854
|
-
if (!this.#
|
|
1855
|
-
const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this
|
|
2073
|
+
if (!this.#graph.lastRefreshSucceeded) {
|
|
2074
|
+
const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this.#app.workspace.workspaceRoot));
|
|
1856
2075
|
if (fallbackFiles.length > 0) {
|
|
1857
|
-
this
|
|
2076
|
+
this.#logger.warn(`[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`);
|
|
1858
2077
|
return true;
|
|
1859
2078
|
}
|
|
1860
2079
|
}
|
|
1861
2080
|
return false;
|
|
1862
2081
|
}
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
// pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
|
|
2085
|
+
class AkanAppHost {
|
|
2086
|
+
app;
|
|
2087
|
+
logger = new Logger2("AkanAppHost");
|
|
2088
|
+
stdio;
|
|
2089
|
+
env;
|
|
2090
|
+
#onDevEvent;
|
|
2091
|
+
#lastDevState = null;
|
|
2092
|
+
#bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
|
|
2093
|
+
#stopping = false;
|
|
2094
|
+
#builderMessageQueue = Promise.resolve();
|
|
2095
|
+
#backendGraph;
|
|
2096
|
+
#statuses;
|
|
2097
|
+
#backend;
|
|
2098
|
+
#gap;
|
|
2099
|
+
#requests;
|
|
2100
|
+
#rss;
|
|
2101
|
+
#builder;
|
|
2102
|
+
#idle;
|
|
2103
|
+
#recycler;
|
|
2104
|
+
constructor(app, {
|
|
2105
|
+
env,
|
|
2106
|
+
stdio = "inherit",
|
|
2107
|
+
onDevEvent
|
|
2108
|
+
}) {
|
|
2109
|
+
this.app = app;
|
|
2110
|
+
this.env = env;
|
|
2111
|
+
this.stdio = stdio;
|
|
2112
|
+
this.#onDevEvent = onDevEvent ?? null;
|
|
2113
|
+
this.#backendGraph = new BackendImportGraph(app, this.logger);
|
|
2114
|
+
const { logger } = this;
|
|
2115
|
+
const graph = this.#backendGraph;
|
|
2116
|
+
const isStopping = () => this.#stopping;
|
|
2117
|
+
const statuses = new DevBuildStatusBoard(logger);
|
|
2118
|
+
this.#statuses = statuses;
|
|
2119
|
+
this.#backend = new DevBackend(app, { env, stdio, logger, statuses, graph }, {
|
|
2120
|
+
isStopping,
|
|
2121
|
+
emit: (state, detail) => this.#emitDevEvent(state, detail),
|
|
2122
|
+
beforeSpawn: () => {
|
|
2123
|
+
this.#requests.startGeneration();
|
|
2124
|
+
this.#requests.discard("the backend restarted while the builder was away");
|
|
2125
|
+
},
|
|
2126
|
+
toBuilder: (message) => this.#requests.send(message)
|
|
2127
|
+
});
|
|
2128
|
+
this.#gap = new BuilderGap({ graph, backend: this.#backend, logger });
|
|
2129
|
+
this.#requests = new BuilderRequestRelay({ logger, env }, {
|
|
2130
|
+
builder: () => this.#builder.current,
|
|
2131
|
+
toBackend: (message) => this.#backend.send(message),
|
|
2132
|
+
markActivity: () => this.#idle.markActivity(),
|
|
2133
|
+
away: () => this.#idle.away,
|
|
2134
|
+
wake: (reason) => void this.#idle.wake(reason)
|
|
2135
|
+
});
|
|
2136
|
+
this.#rss = new BuilderRssRecycler({ logger, statuses }, {
|
|
2137
|
+
builder: () => this.#builder.current,
|
|
2138
|
+
away: () => this.#idle.away,
|
|
2139
|
+
restartQueued: () => this.#recycler.pending || this.#backend.restartScheduled,
|
|
2140
|
+
onRecycle: () => this.#gap.open("builder recycle")
|
|
2141
|
+
});
|
|
2142
|
+
this.#builder = new DevBuilder(app, { env, stdio, logger }, {
|
|
2143
|
+
isStopping,
|
|
2144
|
+
onMessage: (message) => this.#enqueueBuilderMessage(message),
|
|
2145
|
+
onAway: () => this.#gap.open("builder replacement"),
|
|
2146
|
+
onReady: () => this.#requests.flush(),
|
|
2147
|
+
onRestartReady: () => {
|
|
2148
|
+
this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
|
|
2149
|
+
this.#backend.replay();
|
|
2150
|
+
this.#requests.flush();
|
|
2151
|
+
this.#gap.restartBackendForChanges();
|
|
2152
|
+
this.#rss.checkRecycledFloor();
|
|
2153
|
+
},
|
|
2154
|
+
onStartFailed: () => this.#requests.fail("builder failed to start"),
|
|
2155
|
+
onStop: () => this.#rss.cancel(),
|
|
2156
|
+
onRecovered: (reason) => this.#recycler.builderRecovered(reason)
|
|
2157
|
+
});
|
|
2158
|
+
this.#idle = new DevIdleSuspend(app, { logger }, {
|
|
2159
|
+
readiness: () => ({
|
|
2160
|
+
builderReady: this.#builder.current?.status === "ready",
|
|
2161
|
+
backendReady: this.#backend.ready,
|
|
2162
|
+
buildFailed: this.#statuses.failing,
|
|
2163
|
+
restartPending: this.#restartPending
|
|
2164
|
+
}),
|
|
2165
|
+
release: (detail) => {
|
|
2166
|
+
this.#emitDevEvent("suspended", detail);
|
|
2167
|
+
this.#builder.stop();
|
|
2168
|
+
this.#gap.open("idle suspend");
|
|
2169
|
+
},
|
|
2170
|
+
wake: (batch) => this.#recycler.applyIdleWake(batch),
|
|
2171
|
+
wakeFailed: (files) => this.#builder.scheduleRecovery({ files }),
|
|
2172
|
+
flushHeld: () => this.#requests.flush(),
|
|
2173
|
+
awake: () => this.#emitDevEvent(devHostStateOf(this.#backend.lifecycleState, this.#backend.gaveUp))
|
|
2174
|
+
});
|
|
2175
|
+
this.#recycler = new DevRecycler(app, {
|
|
2176
|
+
env,
|
|
2177
|
+
logger,
|
|
2178
|
+
isStopping,
|
|
2179
|
+
graph,
|
|
2180
|
+
statuses,
|
|
2181
|
+
backend: this.#backend,
|
|
2182
|
+
builder: this.#builder,
|
|
2183
|
+
gap: this.#gap,
|
|
2184
|
+
rss: this.#rss
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
#emitDevEvent(state, detail) {
|
|
2188
|
+
if (!this.#onDevEvent || state === this.#lastDevState)
|
|
2189
|
+
return;
|
|
2190
|
+
this.#lastDevState = state;
|
|
2191
|
+
this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
|
|
2192
|
+
if (state === "ready")
|
|
2193
|
+
this.#bootLatch.ready();
|
|
2194
|
+
}
|
|
2195
|
+
async start() {
|
|
2196
|
+
if (this.#backend.running)
|
|
2197
|
+
await this.#backend.stop();
|
|
2198
|
+
if (this.#builder.current)
|
|
2199
|
+
this.#builder.stop();
|
|
2200
|
+
const [redisHost] = await Promise.all([
|
|
2201
|
+
this.#prepareDatabase("redis"),
|
|
2202
|
+
this.#backendGraph.refresh(),
|
|
2203
|
+
this.#builder.start()
|
|
2204
|
+
]);
|
|
2205
|
+
Object.assign(this.env, { REDIS_HOST: redisHost });
|
|
2206
|
+
this.#backend.start();
|
|
2207
|
+
this.#idle.arm();
|
|
2208
|
+
return this;
|
|
2209
|
+
}
|
|
2210
|
+
async stop() {
|
|
2211
|
+
this.#stopping = true;
|
|
2212
|
+
this.#recycler.drop();
|
|
2213
|
+
this.#idle.stop();
|
|
2214
|
+
this.#backend.cancelTimers();
|
|
2215
|
+
this.#builder.cancelRecovery();
|
|
2216
|
+
this.#builder.abandonStart(new Error("dev server stopped before the builder was ready"));
|
|
2217
|
+
this.#backend.dropPendingRestart();
|
|
2218
|
+
this.#requests.fail("dev server is shutting down");
|
|
2219
|
+
await this.#backend.restarting;
|
|
2220
|
+
await this.#backend.stop();
|
|
2221
|
+
this.#builder.stop();
|
|
2222
|
+
return this;
|
|
2223
|
+
}
|
|
2224
|
+
kill() {
|
|
2225
|
+
this.stop();
|
|
2226
|
+
}
|
|
2227
|
+
async#prepareDatabase(type) {
|
|
2228
|
+
const environment = WorkspaceExecutor.getBaseDevEnv().env;
|
|
2229
|
+
const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
|
|
2230
|
+
if (policy === "none")
|
|
2231
|
+
return "localhost";
|
|
2232
|
+
if (policy === "required")
|
|
2233
|
+
return await createTunnel(type, { app: this.app, environment });
|
|
2234
|
+
try {
|
|
2235
|
+
return await createTunnel(type, { app: this.app, environment });
|
|
2236
|
+
} catch (error) {
|
|
2237
|
+
this.logger.warn(`${error instanceof Error ? error.message : String(error)} - continuing without Redis: the single database mode does not use it unless an app adaptor does`);
|
|
2238
|
+
return UNAVAILABLE_REDIS_HOST;
|
|
1893
2239
|
}
|
|
1894
|
-
this.#failPendingBuilderMessages("builder failed to start");
|
|
1895
|
-
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
1896
2240
|
}
|
|
1897
|
-
#
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
throw new Error("Builder Not Found");
|
|
1901
|
-
let settled = false;
|
|
1902
|
-
const settle = (fn) => {
|
|
1903
|
-
if (settled)
|
|
1904
|
-
return;
|
|
1905
|
-
settled = true;
|
|
1906
|
-
clearTimeout(timeout);
|
|
1907
|
-
if (this.#abandonBuilderStart === abandon)
|
|
1908
|
-
this.#abandonBuilderStart = null;
|
|
1909
|
-
fn();
|
|
1910
|
-
};
|
|
1911
|
-
const abandon = (error) => settle(() => reject(error));
|
|
1912
|
-
this.#abandonBuilderStart = abandon;
|
|
1913
|
-
const timeout = setTimeout(() => {
|
|
1914
|
-
settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
|
|
1915
|
-
}, BUILDER_READY_TIMEOUT_MS);
|
|
1916
|
-
this.#builder.start({
|
|
1917
|
-
announceBootState,
|
|
1918
|
-
onExit: () => {
|
|
1919
|
-
settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
|
|
1920
|
-
},
|
|
1921
|
-
onAway: () => {
|
|
1922
|
-
this.#openBuilderGap("builder replacement");
|
|
1923
|
-
},
|
|
1924
|
-
onReady: () => {
|
|
1925
|
-
settle(resolve);
|
|
1926
|
-
this.#flushPendingBuilderMessages();
|
|
1927
|
-
},
|
|
1928
|
-
onRestartReady: () => {
|
|
1929
|
-
this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
|
|
1930
|
-
this.#replayBuilderState();
|
|
1931
|
-
this.#flushPendingBuilderMessages();
|
|
1932
|
-
this.#restartBackendForGapChanges();
|
|
1933
|
-
this.#checkRecycledBuilderFloor();
|
|
1934
|
-
}
|
|
1935
|
-
});
|
|
2241
|
+
#enqueueBuilderMessage(message) {
|
|
2242
|
+
this.#builderMessageQueue = this.#builderMessageQueue.then(() => this.#handleBuilderMessage(message)).catch((err) => {
|
|
2243
|
+
this.logger.warn(`failed to handle builder message: ${err instanceof Error ? err.message : String(err)}`);
|
|
1936
2244
|
});
|
|
1937
2245
|
}
|
|
1938
|
-
#
|
|
1939
|
-
this.#
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
2246
|
+
async#handleBuilderMessage(message) {
|
|
2247
|
+
if (this.#stopping)
|
|
2248
|
+
return;
|
|
2249
|
+
this.#idle.markActivity();
|
|
2250
|
+
this.#builder.trackGeneration(message);
|
|
2251
|
+
if (message.type === "build-status") {
|
|
2252
|
+
this.#statuses.record(message.data);
|
|
2253
|
+
this.#backend.sendOrQueueStatus(message.data);
|
|
2254
|
+
this.#backend.reviveAfterGreenBuild(message.data);
|
|
2255
|
+
await this.#recycler.resumeFailed(message.data);
|
|
1943
2256
|
return;
|
|
1944
2257
|
}
|
|
1945
|
-
if (message.type === "
|
|
1946
|
-
|
|
1947
|
-
|
|
2258
|
+
if (message.type === "builder-metrics") {
|
|
2259
|
+
this.#rss.handleMetrics(message.data);
|
|
2260
|
+
return;
|
|
1948
2261
|
}
|
|
1949
|
-
if (message.type === "
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
return;
|
|
1953
|
-
this.#builderRequests.withdraw(outgoing.id);
|
|
1954
|
-
} else if (this.#builder?.send(message))
|
|
2262
|
+
if (message.type === "boot-armed") {
|
|
2263
|
+
this.logger.verbose("[builder] boot builds settled");
|
|
2264
|
+
this.#bootLatch.armed();
|
|
1955
2265
|
return;
|
|
1956
|
-
|
|
1957
|
-
if (
|
|
1958
|
-
|
|
1959
|
-
|
|
2266
|
+
}
|
|
2267
|
+
if (message.type === "pages-updated" || message.type === "css-updated") {
|
|
2268
|
+
const recycled = message.data.reason === "builder-recycle";
|
|
2269
|
+
if (recycled && !this.#statuses.shouldRelayRecycled(message))
|
|
2270
|
+
return;
|
|
2271
|
+
this.#statuses.recordLastGood(message, { supersede: recycled });
|
|
2272
|
+
}
|
|
2273
|
+
if (message.type === "invalidate") {
|
|
2274
|
+
await this.#recycler.handleInvalidate(message);
|
|
1960
2275
|
return;
|
|
1961
2276
|
}
|
|
1962
|
-
if (
|
|
2277
|
+
if (message.type === "build-route-res" || message.type === "build-csr-res" || message.type === "build-graph-res") {
|
|
2278
|
+
const answer = this.#requests.settle(message);
|
|
2279
|
+
if (!answer) {
|
|
2280
|
+
this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
this.#backend.send(answer);
|
|
1963
2284
|
return;
|
|
1964
|
-
|
|
2285
|
+
}
|
|
2286
|
+
this.#backend.send(message);
|
|
1965
2287
|
}
|
|
1966
|
-
#
|
|
1967
|
-
this.#
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
2288
|
+
get #restartPending() {
|
|
2289
|
+
return this.#recycler.pending || this.#backend.restartPending || this.#builder.recovering || this.#rss.armed;
|
|
2290
|
+
}
|
|
2291
|
+
static async readProcessRssBytes(pid) {
|
|
2292
|
+
return await ProcessRss.bytesOf(pid);
|
|
2293
|
+
}
|
|
2294
|
+
static idleSuspendMs() {
|
|
2295
|
+
return DevIdleSuspend.idleMs();
|
|
1974
2296
|
}
|
|
1975
2297
|
}
|
|
1976
2298
|
// pkgs/@akanjs/devkit/applicationTestPreload.ts
|
|
@@ -2016,19 +2338,19 @@ var hasTestFile = (dir, seen = new Set) => {
|
|
|
2016
2338
|
});
|
|
2017
2339
|
};
|
|
2018
2340
|
var testTargetOf = (exec) => {
|
|
2019
|
-
const root = exec instanceof SysExecutor || exec instanceof
|
|
2341
|
+
const root = exec instanceof SysExecutor || exec instanceof PkgExecutor2 ? exec.workspace.workspaceRoot : process.cwd();
|
|
2020
2342
|
return { root, target: path6.relative(root, exec.cwdPath).split(path6.sep).join("/") };
|
|
2021
2343
|
};
|
|
2022
2344
|
var reportsNoTestFile = (exec) => {
|
|
2023
2345
|
if (hasTestFile(exec.cwdPath))
|
|
2024
2346
|
return false;
|
|
2025
|
-
const hint = exec instanceof
|
|
2347
|
+
const hint = exec instanceof AppExecutor2 || exec instanceof LibExecutor2 ? " A signal test goes beside its module, as lib/<model>/<model>.signal.test.ts." : "";
|
|
2026
2348
|
Logger3.rawLog(`No *.test.ts or *.spec.ts file in ${testTargetOf(exec).target}, so no test ran.${hint}`);
|
|
2027
2349
|
return true;
|
|
2028
2350
|
};
|
|
2029
2351
|
|
|
2030
2352
|
// pkgs/@akanjs/cli/application/application.runner.ts
|
|
2031
|
-
var loadBuildRunner = async () => (await import("./applicationBuildRunner-
|
|
2353
|
+
var loadBuildRunner = async () => (await import("./applicationBuildRunner-gg03kydg.js")).ApplicationBuildRunner;
|
|
2032
2354
|
var loadPrompts = async () => await import("@inquirer/prompts");
|
|
2033
2355
|
|
|
2034
2356
|
class ApplicationRunner extends runner("application") {
|
|
@@ -2039,7 +2361,7 @@ class ApplicationRunner extends runner("application") {
|
|
|
2039
2361
|
dict: { appName },
|
|
2040
2362
|
options: { libs }
|
|
2041
2363
|
});
|
|
2042
|
-
return
|
|
2364
|
+
return AppExecutor2.from(workspace, appName);
|
|
2043
2365
|
}
|
|
2044
2366
|
async planSlice(app) {
|
|
2045
2367
|
return await new SlicePlanner(app).plan();
|
|
@@ -2229,7 +2551,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
|
|
|
2229
2551
|
await new (await loadBuildRunner())(app).typecheck(options);
|
|
2230
2552
|
}
|
|
2231
2553
|
async typecheckLibrary(lib, options = {}) {
|
|
2232
|
-
const { ProjectTypecheck } = await import("./projectTypecheck-
|
|
2554
|
+
const { ProjectTypecheck } = await import("./projectTypecheck-wcrt7sae.js");
|
|
2233
2555
|
const root = lib.workspace.workspaceRoot;
|
|
2234
2556
|
await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
|
|
2235
2557
|
"../../server.ts",
|
|
@@ -2253,7 +2575,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
|
|
|
2253
2575
|
});
|
|
2254
2576
|
}
|
|
2255
2577
|
async test(exec, testPaths = [], flags = []) {
|
|
2256
|
-
const isSignalTarget = exec instanceof
|
|
2578
|
+
const isSignalTarget = exec instanceof AppExecutor2 || exec instanceof LibExecutor2;
|
|
2257
2579
|
if (!testPaths.length && reportsNoTestFile(exec))
|
|
2258
2580
|
return;
|
|
2259
2581
|
const preloadPath = isSignalTarget ? await resolveSignalTestPreloadPath(exec) : null;
|