@akanjs/cli 3.2.0-rc.3 → 3.2.0-rc.30
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 -1
- package/CodeAgent-c17abdbf.js +11 -0
- package/{CodeTui-wv9yf7eq.js → CodeTui-jed1nj82.js} +822 -666
- package/README.ko.md +26 -1
- package/README.md +26 -1
- package/TunnelShare-mbfcaqg0.js +18 -0
- package/agent.command-9whnc6vb.js +56 -0
- package/akanCode.js +12 -12
- package/appExecutor-020cyesq.js +11 -0
- package/{application.command-6515t682.js → application.command-4eqvyxkw.js} +77 -36
- package/{applicationBuildRunner-bqbyeg84.js → applicationBuildRunner-frtcrqfd.js} +18 -13
- package/buildBatch.proc.js +26 -11
- package/{cloud.command-32esk0v1.js → cloud.command-hbvmeezn.js} +31 -28
- package/cloud.script-9kmbr3d6.js +35 -0
- package/{code.command-xk7rwq2x.js → code.command-0ayrenk4.js} +14 -9
- package/{context.command-jwenkkf0.js → context.command-php852kf.js} +28 -23
- package/context.runner-nngmn7c0.js +34 -0
- package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
- package/{devTui-cd03z4mx.js → devTui-rf374y2w.js} +1 -1
- package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
- package/{guideline.command-w6yqpdec.js → guideline.command-w1grfwh7.js} +9 -4
- package/guidelines/agentRule/agentRule.instruction.md +29 -12
- package/guidelines/akanApi/akanApi.instruction.md +5 -3
- package/guidelines/conventions/core.md +23 -5
- package/guidelines/conventions/rules/app.md +4 -1
- package/guidelines/conventions/rules/page.md +5 -0
- package/guidelines/conventions/rules/ts.md +3 -3
- package/guidelines/errorCodes/errorCodes.instruction.md +158 -0
- package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
- package/guidelines/mcpRule/mcpRule.instruction.md +96 -2
- package/guidelines/pageRule/pageRule.instruction.md +15 -1
- package/guidelines/runtimeRule/runtimeRule.instruction.md +12 -6
- package/guidelines/transportRule/transportRule.instruction.md +8 -1
- package/incrementalBuilder.proc.js +574 -410
- package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
- package/{index-xrmrvafh.js → index-0gaj78wn.js} +808 -694
- package/{index-j1hjb477.js → index-11d7nh8a.js} +1 -1
- package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
- package/{index-ygrdw6jw.js → index-1pjwsh2g.js} +65 -8
- package/{index-43acpsc7.js → index-28nk8w3j.js} +12 -12
- package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
- package/{index-8gm4yag8.js → index-42jhx2ya.js} +6 -6
- package/{index-2rqyrvcy.js → index-4st0hq72.js} +62 -33
- package/{index-bak9f2br.js → index-5d57kx0s.js} +15 -11
- package/{index-bdmgqzb5.js → index-6469101k.js} +58 -29
- package/{index-7kmbqp0b.js → index-6pxmcaq8.js} +1 -1
- package/{index-54s6knqe.js → index-6zb17wcm.js} +12 -10
- package/{index-0ba8nj4d.js → index-7bs463x7.js} +50 -38
- package/{index-y725zb1a.js → index-7v7tvgt7.js} +196 -168
- package/{index-r0a604h4.js → index-99kjwyma.js} +1 -1
- package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
- package/{index-386canwe.js → index-9rv2zt48.js} +186 -121
- package/{index-20wvskt8.js → index-9wab2ngg.js} +1 -1
- package/{index-2eym1yjb.js → index-9wjrwjgz.js} +288 -209
- package/{index-kcpk2d20.js → index-at6haq2x.js} +1474 -1139
- package/{index-6h775rv3.js → index-ba2xd32s.js} +53 -12
- package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
- package/{index-ngpt3zz3.js → index-bj8s07s7.js} +525 -440
- package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
- package/{index-vbhx60x5.js → index-cb91b6d8.js} +2140 -2165
- package/index-dss3ds74.js +127 -0
- package/{index-e22zedc2.js → index-f16kr6vj.js} +3 -3
- package/{index-ny2k80mv.js → index-ffa52fwf.js} +1 -1
- package/{index-djc5nxpy.js → index-fp5xf6ef.js} +6 -6
- package/{index-qrk06tfp.js → index-g45y5f3e.js} +2 -2
- package/{index-8jpc5fqv.js → index-g7jgd4xs.js} +2 -2
- package/index-j4yvgfhr.js +70 -0
- package/{index-ytpmk3pb.js → index-jgj31xvw.js} +18 -11
- package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
- package/{index-s34v3y28.js → index-m3t28rt3.js} +11 -11
- package/{index-dpgywgeq.js → index-m5gg0wzv.js} +27 -16
- package/index-na8r4a27.js +30 -0
- package/{index-h0p6n4k1.js → index-nm7nt9vm.js} +3 -3
- package/{index-j4hkbzj6.js → index-p06kfhdf.js} +6 -6
- package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
- package/{index-cmg5ngqa.js → index-p7beqww9.js} +2 -2
- package/{index-zhkcab5a.js → index-prgvqqxe.js} +580 -364
- package/{index-wfmpxke3.js → index-qssq2d41.js} +2775 -3677
- package/{index-sc0g6zbm.js → index-rwgqba9p.js} +24 -11
- package/{index-zcdmnfrf.js → index-s3m89wt2.js} +9 -9
- package/{index-v50xjbbe.js → index-t4d0ckde.js} +1 -1
- package/{index-9p260r4e.js → index-trffs83s.js} +538 -250
- package/{index-ddk49ypz.js → index-v929w7j7.js} +133 -49
- package/index-va90m8nd.js +25 -0
- package/index-vjbne22r.js +80 -0
- package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
- package/{index-39jz41jb.js → index-xs9a3ddt.js} +3 -3
- package/{index-84c2pgak.js → index-yvzm8mby.js} +94 -82
- package/{index-wr9magsr.js → index-yxkjsyx8.js} +3 -3
- package/index-ze48c0vd.js +788 -0
- package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
- package/index.js +29 -24
- package/libExecutor-tq994592.js +10 -0
- package/{library.command-qs8beggh.js → library.command-x219mhcx.js} +9 -4
- package/{localRegistry.command-hz4ged9n.js → localRegistry.command-zvdcejhn.js} +30 -24
- package/{module.command-z9js77m2.js → module.command-k6cwcm7g.js} +17 -8
- package/{package.command-zqenq8c0.js → package.command-vw7x09f8.js} +13 -8
- package/package.json +2 -2
- package/{page.command-t0nx1jat.js → page.command-gf06paq2.js} +9 -4
- package/{pipeline.command-2yjeas7m.js → pipeline.command-y07dgj9b.js} +14 -8
- package/pkgExecutor-stde3yc3.js +10 -0
- package/{primitive.command-v5kypwy4.js → primitive.command-edydvh07.js} +13 -8
- package/{projectTypecheck-s9hhe5sa.js → projectTypecheck-mk8wefvd.js} +2 -1
- package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
- package/{quality.command-q55j2htd.js → quality.command-mdb45vyr.js} +23 -16
- package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
- package/{repair.command-7ssbbdq2.js → repair.command-kvtaeecy.js} +13 -8
- package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
- package/{scalar.command-p5jb7z57.js → scalar.command-sjt9p5e1.js} +11 -6
- package/skills/akan-debug/SKILL.md +10 -3
- package/skills/akan-err/SKILL.md +7 -0
- package/skills/akan-mcp/SKILL.md +14 -2
- package/skills/akan-scaffold/SKILL.md +2 -2
- package/skills/akan-transport/SKILL.md +2 -0
- package/skills/akan-validate/SKILL.md +1 -0
- package/{subspace.command-7wxy6ptj.js → subspace.command-mkkqync4.js} +29 -23
- package/templates/app/page/_layout.tsx +13 -0
- package/templates/app/page/styles.css.template +40 -0
- package/templates/appSample/page/_index.tsx +9 -9
- package/templates/appSample/page/_layout.tsx +1 -0
- package/templates/appSample/page/styles.css.template +40 -5
- package/templates/appSample/ui/Recipe/jellyButton.ts +1 -1
- package/templates/biomeForm.ts +1 -1
- package/templates/env/_env.server.type.ts +1 -1
- package/templates/facetIndex/index.ts +2 -37
- package/templates/lib/sig.ts +0 -4
- package/templates/lib/useClient.ts +1 -1
- package/templates/workspaceRoot/AGENTS.md.template +2 -1
- package/{tunnel.command-22g11n0x.js → tunnel.command-tr5b3030.js} +17 -12
- package/{typeChecker-s640r6c0.js → typeChecker-bfrd1n9n.js} +1 -1
- package/typecheck.proc.js +6 -3
- package/{verify.command-m0wnndd7.js → verify.command-0p9h8tpp.js} +26 -20
- package/{workflow.command-jx8dqs9n.js → workflow.command-9mfcwqzj.js} +37 -19
- package/{workspace.command-ca9kfyt3.js → workspace.command-5hjtmcfs.js} +61 -54
- package/CodeAgent-e9c712an.js +0 -11
- package/TunnelShare-zkfkrw8w.js +0 -14
- package/agent.command-9erafkcb.js +0 -51
- package/cloud.script-arsagnq6.js +0 -30
- package/context.runner-mqpp67br.js +0 -29
- package/index-x3x31df8.js +0 -14
- /package/templates/{appSample → app}/public/fonts/Pretendard-Bold.woff2 +0 -0
- /package/templates/{appSample → app}/public/fonts/Pretendard-Medium.woff2 +0 -0
- /package/templates/{appSample → app}/public/fonts/Pretendard-Regular.woff2 +0 -0
- /package/templates/{appSample → app}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
|
@@ -1,24 +1,33 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import {
|
|
3
|
-
AppInfo,
|
|
4
3
|
CommandExecutionError,
|
|
5
|
-
WorkspaceExecutor,
|
|
6
4
|
SysExecutor,
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
} from "./index-wfmpxke3.js";
|
|
5
|
+
AppInfo,
|
|
6
|
+
WorkspaceExecutor
|
|
7
|
+
} from "./index-qssq2d41.js";
|
|
11
8
|
import {
|
|
12
9
|
FileSys2
|
|
13
|
-
} from "./index-
|
|
10
|
+
} from "./index-by2tvsq6.js";
|
|
11
|
+
import {
|
|
12
|
+
CliError
|
|
13
|
+
} from "./index-j4yvgfhr.js";
|
|
14
|
+
import {
|
|
15
|
+
AppExecutor2
|
|
16
|
+
} from "./index-ze48c0vd.js";
|
|
17
|
+
import {
|
|
18
|
+
LibExecutor2
|
|
19
|
+
} from "./index-na8r4a27.js";
|
|
20
|
+
import {
|
|
21
|
+
PkgExecutor2
|
|
22
|
+
} from "./index-dss3ds74.js";
|
|
14
23
|
import {
|
|
15
24
|
UNAVAILABLE_REDIS_HOST,
|
|
16
25
|
redisTunnelPolicy,
|
|
26
|
+
backendRecoveryPolicy,
|
|
17
27
|
BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS,
|
|
18
28
|
SOURCE_EXTS,
|
|
19
29
|
shouldRestartBackendByDevPlan,
|
|
20
30
|
shouldRestartBuilderByDevPlan,
|
|
21
|
-
shouldAbandonBackendRecovery,
|
|
22
31
|
normalizeBackendReportedGeneration,
|
|
23
32
|
shouldRestartDevHostByDevPlan,
|
|
24
33
|
devHostStateOf,
|
|
@@ -46,34 +55,33 @@ import {
|
|
|
46
55
|
filesChangedSince,
|
|
47
56
|
HmrWatcher,
|
|
48
57
|
WatchRootResolver
|
|
49
|
-
} from "./index-
|
|
58
|
+
} from "./index-7v7tvgt7.js";
|
|
50
59
|
import {
|
|
51
60
|
runner,
|
|
52
|
-
ExitCodeError,
|
|
53
61
|
assertPromptable
|
|
54
|
-
} from "./index-
|
|
62
|
+
} from "./index-9rv2zt48.js";
|
|
55
63
|
import {
|
|
56
64
|
UpdatePackFolder,
|
|
57
65
|
UpdateUploader,
|
|
58
66
|
NativePublicEnv,
|
|
59
67
|
NativeApp
|
|
60
|
-
} from "./index-
|
|
68
|
+
} from "./index-fp5xf6ef.js";
|
|
61
69
|
import {
|
|
62
70
|
DesktopServerStage
|
|
63
|
-
} from "./index-
|
|
71
|
+
} from "./index-9wab2ngg.js";
|
|
64
72
|
import {
|
|
65
73
|
resolveMobileTargets,
|
|
66
74
|
resolveAppId
|
|
67
75
|
} from "./index-m9jj544v.js";
|
|
68
76
|
import {
|
|
69
77
|
SlicePlanner
|
|
70
|
-
} from "./index-
|
|
78
|
+
} from "./index-g7jgd4xs.js";
|
|
71
79
|
import {
|
|
72
80
|
openBrowser
|
|
73
81
|
} from "./index-9dp031by.js";
|
|
74
82
|
import {
|
|
75
83
|
ShellOnlyEnv
|
|
76
|
-
} from "./index-
|
|
84
|
+
} from "./index-bejy9zyc.js";
|
|
77
85
|
import {
|
|
78
86
|
ConfigLock
|
|
79
87
|
} from "./index-bqbf654f.js";
|
|
@@ -83,13 +91,12 @@ import { existsSync, realpathSync as realpathSync2 } from "fs";
|
|
|
83
91
|
import path7 from "path";
|
|
84
92
|
|
|
85
93
|
// pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
|
|
86
|
-
import path4 from "path";
|
|
87
94
|
import { Logger as Logger2 } from "akanjs/common";
|
|
88
95
|
|
|
89
|
-
// pkgs/@akanjs/devkit/createTunnel.ts
|
|
96
|
+
// pkgs/@akanjs/devkit/tunnel/createTunnel.ts
|
|
90
97
|
import { readFileSync } from "fs";
|
|
91
98
|
|
|
92
|
-
// pkgs/@akanjs/devkit/sshHostKeys.ts
|
|
99
|
+
// pkgs/@akanjs/devkit/tunnel/sshHostKeys.ts
|
|
93
100
|
import { createHash } from "crypto";
|
|
94
101
|
import { mkdir, rm, writeFile } from "fs/promises";
|
|
95
102
|
import path from "path";
|
|
@@ -136,7 +143,7 @@ class SshHostKeys {
|
|
|
136
143
|
}
|
|
137
144
|
}
|
|
138
145
|
|
|
139
|
-
// pkgs/@akanjs/devkit/sshTunnel.ts
|
|
146
|
+
// pkgs/@akanjs/devkit/tunnel/sshTunnel.ts
|
|
140
147
|
import { Client } from "ssh2";
|
|
141
148
|
var closeQuietly = (close) => {
|
|
142
149
|
try {
|
|
@@ -244,7 +251,7 @@ var closeBunSocket = (socket, error) => {
|
|
|
244
251
|
closeQuietly(() => socket.end());
|
|
245
252
|
};
|
|
246
253
|
|
|
247
|
-
// pkgs/@akanjs/devkit/createTunnel.ts
|
|
254
|
+
// pkgs/@akanjs/devkit/tunnel/createTunnel.ts
|
|
248
255
|
var tunnelEnv = new ShellOnlyEnv([
|
|
249
256
|
"SSH_TUNNEL_PRIVATE_KEY_PATH",
|
|
250
257
|
"SSH_TUNNEL_PASSPHRASE",
|
|
@@ -322,10 +329,323 @@ var createTunnel = async (service, { app, environment, port = service === "postg
|
|
|
322
329
|
}
|
|
323
330
|
return `localhost:${port}`;
|
|
324
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
|
+
const request = message.type === "build-route" ? `build-route ${message.routeId}` : message.type;
|
|
604
|
+
this.#logger.verbose(`[builder] holding ${request} until the builder is ready (${this.#held.length} waiting)`);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (this.#failRequest(message, `builder is ${status}; reload after the builder is ready`))
|
|
608
|
+
return;
|
|
609
|
+
this.#logger.warn("akanAppHost builder is not running");
|
|
610
|
+
}
|
|
611
|
+
flush() {
|
|
612
|
+
const pending = this.#held.splice(0);
|
|
613
|
+
if (pending.length === 0)
|
|
614
|
+
return;
|
|
615
|
+
this.#logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
|
|
616
|
+
for (const message of pending)
|
|
617
|
+
this.send(message);
|
|
618
|
+
}
|
|
619
|
+
discard(reason) {
|
|
620
|
+
const held = this.#held.splice(0);
|
|
621
|
+
if (held.length === 0)
|
|
622
|
+
return;
|
|
623
|
+
this.#logger.verbose(`[builder] dropped ${held.length} held builder request(s): ${reason}`);
|
|
624
|
+
}
|
|
625
|
+
fail(reason) {
|
|
626
|
+
const held = this.#held.splice(0);
|
|
627
|
+
if (held.length === 0)
|
|
628
|
+
return;
|
|
629
|
+
this.#logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
|
|
630
|
+
for (const message of held)
|
|
631
|
+
this.#failRequest(message, reason);
|
|
632
|
+
}
|
|
633
|
+
#failRequest(message, error) {
|
|
634
|
+
if (message.type === "build-route")
|
|
635
|
+
this.#links.toBackend({ type: "build-route-res", id: message.id, ok: false, error, kind: "unavailable" });
|
|
636
|
+
else if (message.type === "build-csr")
|
|
637
|
+
this.#links.toBackend({ type: "build-csr-res", id: message.id, ok: false, error, kind: "unavailable" });
|
|
638
|
+
else if (message.type === "build-graph")
|
|
639
|
+
this.#links.toBackend({ type: "build-graph-res", id: message.id, ok: false, error, kind: "unavailable" });
|
|
640
|
+
else
|
|
641
|
+
return false;
|
|
642
|
+
return true;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
325
645
|
// pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.host.ts
|
|
326
646
|
import fs from "fs";
|
|
327
|
-
import
|
|
328
|
-
import { Logger } from "akanjs/common";
|
|
647
|
+
import path3 from "path";
|
|
648
|
+
import { Logger, RestartSchedule } from "akanjs/common";
|
|
329
649
|
import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
|
|
330
650
|
import { MemoryLimit } from "akanjs/server/memoryLimit";
|
|
331
651
|
var builderMsgTypeSet = new Set([
|
|
@@ -344,8 +664,6 @@ var builderMsgTypeSet = new Set([
|
|
|
344
664
|
]);
|
|
345
665
|
|
|
346
666
|
class IncrementalBuilderHost {
|
|
347
|
-
static #restartBaseDelayMs = 1000;
|
|
348
|
-
static #restartMaxDelayMs = 30000;
|
|
349
667
|
static #recycleDrainTimeoutMs = 30000;
|
|
350
668
|
static #devMaxRssBytes = 2048 * 1024 * 1024;
|
|
351
669
|
logger = new Logger("IncrementalBuilderHost");
|
|
@@ -358,8 +676,7 @@ class IncrementalBuilderHost {
|
|
|
358
676
|
#onOutput;
|
|
359
677
|
#proc = null;
|
|
360
678
|
#status = "stopped";
|
|
361
|
-
#
|
|
362
|
-
#restartTimer = null;
|
|
679
|
+
#restart = new RestartSchedule({ min: 1000, max: 30000 });
|
|
363
680
|
#recycleTimer = null;
|
|
364
681
|
#recycleRequested = false;
|
|
365
682
|
#spawnAfterRecycle = false;
|
|
@@ -430,7 +747,7 @@ class IncrementalBuilderHost {
|
|
|
430
747
|
if (msg.type === "builder-ready" && !this.ready) {
|
|
431
748
|
this.ready = true;
|
|
432
749
|
this.#status = "ready";
|
|
433
|
-
this.#
|
|
750
|
+
this.#restart.reset();
|
|
434
751
|
if (isRestart)
|
|
435
752
|
this.#startOptions.onRestartReady?.();
|
|
436
753
|
else
|
|
@@ -472,7 +789,7 @@ class IncrementalBuilderHost {
|
|
|
472
789
|
this.logger.verbose(`builder spawned pid=${proc.pid} entry=${this.entry}${isRestart ? " restart=1" : ""}`);
|
|
473
790
|
}
|
|
474
791
|
#checkPatchingMarker(afterCrash) {
|
|
475
|
-
const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) =>
|
|
792
|
+
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));
|
|
476
793
|
if (markers.length === 0)
|
|
477
794
|
return;
|
|
478
795
|
if (afterCrash && !this.#patcherOff) {
|
|
@@ -495,19 +812,15 @@ class IncrementalBuilderHost {
|
|
|
495
812
|
} catch {}
|
|
496
813
|
}
|
|
497
814
|
#scheduleRestart() {
|
|
498
|
-
if (this.#manualStop || this.#
|
|
815
|
+
if (this.#manualStop || this.#restart.pending)
|
|
499
816
|
return;
|
|
500
817
|
this.#status = "restarting";
|
|
501
|
-
const
|
|
502
|
-
const delay = Math.min(IncrementalBuilderHost.#restartBaseDelayMs * 2 ** attempt, IncrementalBuilderHost.#restartMaxDelayMs);
|
|
503
|
-
this.#restartAttempts = attempt + 1;
|
|
504
|
-
this.logger.warn(`builder exited after ready; restarting in ${delay}ms (attempt ${this.#restartAttempts})`);
|
|
505
|
-
this.#restartTimer = setTimeout(() => {
|
|
506
|
-
this.#restartTimer = null;
|
|
818
|
+
const delay = this.#restart.schedule(() => {
|
|
507
819
|
if (this.#manualStop)
|
|
508
820
|
return;
|
|
509
821
|
this.#spawn(true);
|
|
510
|
-
}
|
|
822
|
+
});
|
|
823
|
+
this.logger.warn(`builder exited after ready; restarting in ${delay}ms (attempt ${this.#restart.attempts})`);
|
|
511
824
|
}
|
|
512
825
|
recycle(reason) {
|
|
513
826
|
if (!this.#proc || this.#status !== "ready" || this.#recycleRequested)
|
|
@@ -569,16 +882,13 @@ class IncrementalBuilderHost {
|
|
|
569
882
|
this.#inFlight.clear();
|
|
570
883
|
this.logger.warn(`failing ${lost.length} unanswered builder request(s): ${reason}`);
|
|
571
884
|
for (const [id, type] of lost)
|
|
572
|
-
this.#onMessage({ type: `${type}-res`, id, ok: false, error: reason });
|
|
885
|
+
this.#onMessage({ type: `${type}-res`, id, ok: false, error: reason, kind: "unavailable" });
|
|
573
886
|
}
|
|
574
887
|
stop() {
|
|
575
888
|
this.#manualStop = true;
|
|
576
889
|
this.#clearRecycle();
|
|
577
890
|
this.#failInFlight("builder was stopped before answering");
|
|
578
|
-
|
|
579
|
-
clearTimeout(this.#restartTimer);
|
|
580
|
-
this.#restartTimer = null;
|
|
581
|
-
}
|
|
891
|
+
this.#restart.cancel();
|
|
582
892
|
if (this.#proc)
|
|
583
893
|
this.#proc.kill();
|
|
584
894
|
this.#proc = null;
|
|
@@ -591,10 +901,10 @@ class IncrementalBuilderHost {
|
|
|
591
901
|
patcherOff = false
|
|
592
902
|
} = {}) {
|
|
593
903
|
const candidates = [
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
904
|
+
path3.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
|
|
905
|
+
path3.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
|
|
906
|
+
path3.join(import.meta.dir, "incrementalBuilder.proc.js"),
|
|
907
|
+
path3.join(import.meta.dir, "incrementalBuilder.proc.ts")
|
|
598
908
|
];
|
|
599
909
|
for (const c of candidates)
|
|
600
910
|
if (await Bun.file(c).exists())
|
|
@@ -602,659 +912,664 @@ class IncrementalBuilderHost {
|
|
|
602
912
|
throw new Error(`[cli] frontend builder entry not found; looked in: ${candidates.join(", ")}`);
|
|
603
913
|
}
|
|
604
914
|
}
|
|
605
|
-
// pkgs/@akanjs/devkit/
|
|
606
|
-
|
|
607
|
-
#generation = 0;
|
|
608
|
-
#nextId = 1;
|
|
609
|
-
#inFlight = new Map;
|
|
610
|
-
get generation() {
|
|
611
|
-
return this.#generation;
|
|
612
|
-
}
|
|
613
|
-
get inFlightCount() {
|
|
614
|
-
return this.#inFlight.size;
|
|
615
|
-
}
|
|
616
|
-
startGeneration() {
|
|
617
|
-
this.#generation += 1;
|
|
618
|
-
this.#inFlight.clear();
|
|
619
|
-
return this.#generation;
|
|
620
|
-
}
|
|
621
|
-
issue(message) {
|
|
622
|
-
const id = this.#nextId++;
|
|
623
|
-
this.#inFlight.set(id, { backendId: message.id, generation: this.#generation });
|
|
624
|
-
return { ...message, id };
|
|
625
|
-
}
|
|
626
|
-
withdraw(id) {
|
|
627
|
-
this.#inFlight.delete(id);
|
|
628
|
-
}
|
|
629
|
-
settle(message) {
|
|
630
|
-
const request = this.#inFlight.get(message.id);
|
|
631
|
-
if (!request)
|
|
632
|
-
return null;
|
|
633
|
-
this.#inFlight.delete(message.id);
|
|
634
|
-
if (request.generation !== this.#generation)
|
|
635
|
-
return null;
|
|
636
|
-
return { ...message, id: request.backendId };
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
// pkgs/@akanjs/devkit/akanApp/BackendImportGraph.ts
|
|
641
|
-
import { stat } from "fs/promises";
|
|
642
|
-
import path3 from "path";
|
|
643
|
-
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;
|
|
644
|
-
var GRAPH_IMPORT_KINDS = new Set([
|
|
645
|
-
"import-statement",
|
|
646
|
-
"require-call",
|
|
647
|
-
"require-resolve",
|
|
648
|
-
"dynamic-import"
|
|
649
|
-
]);
|
|
915
|
+
// pkgs/@akanjs/devkit/akanApp/processRss.ts
|
|
916
|
+
var PS_RSS_TIMEOUT_MS = 2000;
|
|
650
917
|
|
|
651
|
-
class
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
#scanCache = new Map;
|
|
660
|
-
#ready = false;
|
|
661
|
-
#lastRefreshSucceeded = false;
|
|
662
|
-
constructor(app, logger) {
|
|
663
|
-
this.#app = app;
|
|
664
|
-
this.#logger = logger;
|
|
665
|
-
}
|
|
666
|
-
get ready() {
|
|
667
|
-
return this.#ready;
|
|
668
|
-
}
|
|
669
|
-
get lastRefreshSucceeded() {
|
|
670
|
-
return this.#lastRefreshSucceeded;
|
|
671
|
-
}
|
|
672
|
-
has(file) {
|
|
673
|
-
return this.#files.has(path3.resolve(file));
|
|
674
|
-
}
|
|
675
|
-
async fingerprint() {
|
|
676
|
-
const stamps = await Promise.all([...this.#files].map(async (file) => {
|
|
677
|
-
const stats = await stat(file).catch(() => null);
|
|
678
|
-
return [file, stats ? `${Math.round(stats.mtimeMs)}:${stats.size}` : "(gone)"];
|
|
679
|
-
}));
|
|
680
|
-
return new Map(stamps);
|
|
681
|
-
}
|
|
682
|
-
async refresh() {
|
|
683
|
-
try {
|
|
684
|
-
const files = await this.#build();
|
|
685
|
-
this.#files = files;
|
|
686
|
-
this.#ready = true;
|
|
687
|
-
this.#lastRefreshSucceeded = true;
|
|
688
|
-
this.#logger.verbose(`[backend-graph] scanned ${files.size} files`);
|
|
689
|
-
return true;
|
|
690
|
-
} catch (err) {
|
|
691
|
-
this.#ready = this.#files.size > 0;
|
|
692
|
-
this.#lastRefreshSucceeded = false;
|
|
693
|
-
this.#logger.warn(`[backend-graph] scan failed; ${this.#ready ? "using previous graph" : "using fallback rules"}: ${err instanceof Error ? err.message : String(err)}`);
|
|
694
|
-
return this.#ready;
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
async#build() {
|
|
698
|
-
const roots = await this.#entrypoints();
|
|
699
|
-
const files = new Set;
|
|
700
|
-
const queue = [...roots];
|
|
701
|
-
const workspaceRoot = path3.resolve(this.#app.workspace.workspaceRoot);
|
|
702
|
-
while (queue.length > 0) {
|
|
703
|
-
const current = path3.resolve(queue.pop());
|
|
704
|
-
if (files.has(current))
|
|
705
|
-
continue;
|
|
706
|
-
if (!this.#isWorkspaceSource(current, workspaceRoot))
|
|
707
|
-
continue;
|
|
708
|
-
const imports = await this.#importsOf(current);
|
|
709
|
-
if (!imports)
|
|
710
|
-
continue;
|
|
711
|
-
files.add(current);
|
|
712
|
-
const importerDir = path3.dirname(current);
|
|
713
|
-
for (const imp of imports) {
|
|
714
|
-
if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
|
|
715
|
-
continue;
|
|
716
|
-
const resolved = this.#resolve(imp.path, importerDir);
|
|
717
|
-
if (!resolved || files.has(resolved))
|
|
718
|
-
continue;
|
|
719
|
-
queue.push(resolved);
|
|
720
|
-
}
|
|
918
|
+
class ProcessRss {
|
|
919
|
+
static async bytesOf(pid) {
|
|
920
|
+
if (process.platform === "win32")
|
|
921
|
+
return await ProcessRss.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], ProcessRss.#tasklistRssKb);
|
|
922
|
+
if (process.platform === "darwin") {
|
|
923
|
+
const footprintBytes = await ProcessRss.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], ProcessRss.#footprintKb);
|
|
924
|
+
if (footprintBytes !== null)
|
|
925
|
+
return footprintBytes;
|
|
721
926
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
927
|
+
const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
|
|
928
|
+
const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
|
|
929
|
+
if (vmRssKb)
|
|
930
|
+
return Number(vmRssKb) * 1024;
|
|
931
|
+
return await ProcessRss.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
|
|
726
932
|
}
|
|
727
|
-
async#
|
|
728
|
-
|
|
729
|
-
|
|
933
|
+
static async#readRssKbVia(command, parseKb, timeoutMs = PS_RSS_TIMEOUT_MS) {
|
|
934
|
+
let proc;
|
|
935
|
+
try {
|
|
936
|
+
proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
|
|
937
|
+
} catch {
|
|
730
938
|
return null;
|
|
731
|
-
const mtimeMs = Math.round(stats.mtimeMs);
|
|
732
|
-
const cached = this.#scanCache.get(file);
|
|
733
|
-
if (cached && cached.mtimeMs === mtimeMs && cached.size === stats.size)
|
|
734
|
-
return cached.specifiers;
|
|
735
|
-
const specifiers = this.#scanImports(file, await Bun.file(file).text());
|
|
736
|
-
this.#scanCache.set(file, { mtimeMs, size: stats.size, specifiers });
|
|
737
|
-
return specifiers;
|
|
738
|
-
}
|
|
739
|
-
async#entrypoints() {
|
|
740
|
-
const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
|
|
741
|
-
const existing = [];
|
|
742
|
-
for (const root of roots) {
|
|
743
|
-
const abs = path3.resolve(root);
|
|
744
|
-
if (await Bun.file(abs).exists())
|
|
745
|
-
existing.push(abs);
|
|
746
939
|
}
|
|
747
|
-
|
|
748
|
-
}
|
|
749
|
-
#resolve(specifier, importerDir) {
|
|
940
|
+
const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
|
|
750
941
|
try {
|
|
751
|
-
const
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
return null;
|
|
756
|
-
return path3.resolve(resolved);
|
|
942
|
+
const output = await new Response(proc.stdout).text();
|
|
943
|
+
await proc.exited;
|
|
944
|
+
const rssKb = parseKb(output);
|
|
945
|
+
return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
|
|
757
946
|
} catch {
|
|
758
947
|
return null;
|
|
948
|
+
} finally {
|
|
949
|
+
clearTimeout(killer);
|
|
759
950
|
}
|
|
760
951
|
}
|
|
761
|
-
#
|
|
762
|
-
const
|
|
763
|
-
|
|
764
|
-
return false;
|
|
765
|
-
if (rel.includes(`${path3.sep}node_modules${path3.sep}`) || rel.includes(`${path3.sep}.akan${path3.sep}`))
|
|
766
|
-
return false;
|
|
767
|
-
return SOURCE_EXTS.has(path3.extname(file).toLowerCase());
|
|
952
|
+
static #tasklistRssKb(output) {
|
|
953
|
+
const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
|
|
954
|
+
return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
|
|
768
955
|
}
|
|
769
|
-
#
|
|
770
|
-
const
|
|
771
|
-
|
|
772
|
-
return this.#tsxTranspiler.scanImports(source);
|
|
773
|
-
if (ext === ".jsx")
|
|
774
|
-
return this.#jsxTranspiler.scanImports(source);
|
|
775
|
-
if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
|
|
776
|
-
return this.#jsTranspiler.scanImports(source);
|
|
777
|
-
return this.#tsTranspiler.scanImports(source);
|
|
956
|
+
static #footprintKb(output) {
|
|
957
|
+
const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
|
|
958
|
+
return bytes ? Number(bytes) / 1024 : Number.NaN;
|
|
778
959
|
}
|
|
779
960
|
}
|
|
780
961
|
|
|
781
|
-
// pkgs/@akanjs/devkit/akanApp/
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
#
|
|
962
|
+
// pkgs/@akanjs/devkit/akanApp/builderRssRecycler.ts
|
|
963
|
+
var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
|
|
964
|
+
var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
|
|
965
|
+
var BUILDER_RSS_SETTLE_MS = 20000;
|
|
966
|
+
|
|
967
|
+
class BuilderRssRecycler {
|
|
968
|
+
#logger;
|
|
969
|
+
#statuses;
|
|
970
|
+
#links;
|
|
788
971
|
#timer = null;
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
972
|
+
#reason = null;
|
|
973
|
+
#lastRecycleAtMono = null;
|
|
974
|
+
#ceilingTightReports = 0;
|
|
975
|
+
#ceilingTightWarned = false;
|
|
976
|
+
#settleToken = 0;
|
|
977
|
+
#over = null;
|
|
978
|
+
#ceilingAbandoned = false;
|
|
979
|
+
constructor({ logger, statuses }, links) {
|
|
980
|
+
this.#logger = logger;
|
|
981
|
+
this.#statuses = statuses;
|
|
982
|
+
this.#links = links;
|
|
792
983
|
}
|
|
793
|
-
|
|
794
|
-
this.#
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
984
|
+
get armed() {
|
|
985
|
+
return !!this.#reason;
|
|
986
|
+
}
|
|
987
|
+
handleMetrics(metrics) {
|
|
988
|
+
if (this.#ceilingAbandoned)
|
|
989
|
+
return;
|
|
990
|
+
const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
|
|
991
|
+
const decision = decideBuilderRssRecycle({
|
|
992
|
+
rssBytes: metrics.rssBytes,
|
|
993
|
+
ceilingBytes,
|
|
994
|
+
buildFailed: this.#statuses.failedAt(metrics.generation),
|
|
995
|
+
msSinceLastRecycle: this.#lastRecycleAtMono === null ? null : performance.now() - this.#lastRecycleAtMono
|
|
996
|
+
});
|
|
997
|
+
if (decision === "below-ceiling") {
|
|
998
|
+
this.#ceilingTightReports = 0;
|
|
999
|
+
return;
|
|
798
1000
|
}
|
|
799
|
-
|
|
1001
|
+
if (decision === "unbounded")
|
|
1002
|
+
return;
|
|
1003
|
+
if (decision === "build-failed") {
|
|
1004
|
+
this.#logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
if (decision === "too-soon") {
|
|
1008
|
+
this.#ceilingTightReports += 1;
|
|
1009
|
+
if (this.#ceilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#ceilingTightReports))
|
|
1010
|
+
return;
|
|
1011
|
+
this.#ceilingTightWarned = true;
|
|
1012
|
+
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.`);
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
this.#arm(`rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`, {
|
|
1016
|
+
rssBytes: metrics.rssBytes,
|
|
1017
|
+
ceilingBytes: ceilingBytes ?? 0
|
|
1018
|
+
});
|
|
800
1019
|
}
|
|
801
|
-
|
|
802
|
-
this.#
|
|
803
|
-
|
|
1020
|
+
async checkRecycledFloor() {
|
|
1021
|
+
if (this.#ceilingAbandoned || this.#lastRecycleAtMono === null)
|
|
1022
|
+
return;
|
|
1023
|
+
const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
|
|
1024
|
+
const pid = this.#links.builder()?.pid;
|
|
1025
|
+
if (!ceilingBytes || !pid)
|
|
1026
|
+
return;
|
|
1027
|
+
const freshRssBytes = await ProcessRss.bytesOf(pid);
|
|
1028
|
+
if (!isRssCeilingUnreachable(freshRssBytes, ceilingBytes))
|
|
1029
|
+
return;
|
|
1030
|
+
this.#ceilingAbandoned = true;
|
|
1031
|
+
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.`);
|
|
804
1032
|
}
|
|
805
|
-
|
|
806
|
-
if (this.#
|
|
1033
|
+
rearm() {
|
|
1034
|
+
if (this.#reason)
|
|
1035
|
+
this.#arm(this.#reason);
|
|
1036
|
+
}
|
|
1037
|
+
cancel() {
|
|
1038
|
+
this.#reason = null;
|
|
1039
|
+
this.#over = null;
|
|
1040
|
+
this.#settleToken += 1;
|
|
1041
|
+
if (!this.#timer)
|
|
807
1042
|
return;
|
|
808
|
-
this.#
|
|
1043
|
+
clearTimeout(this.#timer);
|
|
1044
|
+
this.#timer = null;
|
|
1045
|
+
}
|
|
1046
|
+
#arm(reason, over) {
|
|
1047
|
+
if (this.#reason !== reason)
|
|
1048
|
+
this.#logger.verbose(`[builder-recycle] armed (${reason}); replacing the builder once it stays quiet`);
|
|
1049
|
+
this.#reason = reason;
|
|
1050
|
+
if (over)
|
|
1051
|
+
this.#over = over;
|
|
809
1052
|
if (this.#timer)
|
|
810
1053
|
clearTimeout(this.#timer);
|
|
811
|
-
this.#timer =
|
|
812
|
-
|
|
1054
|
+
this.#timer = setTimeout(() => {
|
|
1055
|
+
this.#timer = null;
|
|
1056
|
+
const pendingReason = this.#reason;
|
|
1057
|
+
const pendingOver = this.#over;
|
|
1058
|
+
this.#reason = null;
|
|
1059
|
+
this.#over = null;
|
|
1060
|
+
if (!pendingReason)
|
|
1061
|
+
return;
|
|
1062
|
+
if (!pendingOver) {
|
|
1063
|
+
this.#recycle(pendingReason);
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
this.#recycleWhenStillOver(pendingReason, pendingOver);
|
|
1067
|
+
}, BUILDER_RSS_RECYCLE_QUIET_MS);
|
|
1068
|
+
}
|
|
1069
|
+
async#recycleWhenStillOver(reason, { rssBytes, ceilingBytes }) {
|
|
1070
|
+
if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
|
|
1071
|
+
this.#recycle(reason);
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
const pid = this.#links.builder()?.pid;
|
|
1075
|
+
if (!pid) {
|
|
1076
|
+
this.#recycle(reason);
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
this.#settleToken += 1;
|
|
1080
|
+
const token = this.#settleToken;
|
|
1081
|
+
this.#logger.verbose(`[builder-recycle] holding ${Math.round(BUILDER_RSS_SETTLE_MS / 1000)}s to see whether the allocator returns it (${reason})`);
|
|
1082
|
+
await Bun.sleep(BUILDER_RSS_SETTLE_MS);
|
|
1083
|
+
if (token !== this.#settleToken || this.#links.builder()?.pid !== pid || this.#links.away()) {
|
|
1084
|
+
this.#logger.verbose("[builder-recycle] settle check abandoned; the builder moved on");
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
const settledBytes = await ProcessRss.bytesOf(pid);
|
|
1088
|
+
if (settledBytes !== null && settledBytes < ceilingBytes) {
|
|
1089
|
+
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`);
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
this.#recycle(settledBytes === null ? reason : `${reason}; still ${asMib(settledBytes)}MiB after settling`);
|
|
1093
|
+
}
|
|
1094
|
+
#recycle(reason) {
|
|
1095
|
+
if (this.#links.restartQueued()) {
|
|
1096
|
+
this.#logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
if (!this.#links.builder()?.recycle(reason))
|
|
1100
|
+
return;
|
|
1101
|
+
this.#lastRecycleAtMono = performance.now();
|
|
1102
|
+
this.#links.onRecycle();
|
|
813
1103
|
}
|
|
814
1104
|
}
|
|
815
1105
|
|
|
816
|
-
// pkgs/@akanjs/devkit/akanApp/
|
|
1106
|
+
// pkgs/@akanjs/devkit/akanApp/devBackend.ts
|
|
1107
|
+
import { RestartSchedule as RestartSchedule2 } from "akanjs/common";
|
|
817
1108
|
var backendMsgTypeSet = new Set(["build-route", "build-csr", "build-graph"]);
|
|
818
|
-
var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
|
|
819
1109
|
var BACKEND_RESTART_DEBOUNCE_MS = 120;
|
|
820
1110
|
var BACKEND_GRACEFUL_TIMEOUT_MS = 8000;
|
|
821
|
-
var BACKEND_RECOVERY_BASE_DELAY_MS = 1000;
|
|
822
|
-
var BACKEND_RECOVERY_MAX_DELAY_MS = 30000;
|
|
823
1111
|
var BACKEND_STDERR_TAIL_LIMIT = 40;
|
|
824
|
-
var BUILDER_READY_TIMEOUT_MS = 150000;
|
|
825
|
-
var BUILDER_START_MAX_ATTEMPTS = 3;
|
|
826
|
-
var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
|
|
827
|
-
var BUILDER_RSS_SETTLE_MS = 20000;
|
|
828
|
-
var PS_RSS_TIMEOUT_MS = 2000;
|
|
829
|
-
var BUILDER_RECOVERY_BASE_DELAY_MS = 2000;
|
|
830
|
-
var BUILDER_RECOVERY_MAX_DELAY_MS = 60000;
|
|
831
1112
|
|
|
832
|
-
class
|
|
833
|
-
app;
|
|
834
|
-
|
|
835
|
-
stdio;
|
|
836
|
-
|
|
837
|
-
#
|
|
838
|
-
#
|
|
839
|
-
#
|
|
840
|
-
#
|
|
841
|
-
#
|
|
842
|
-
#
|
|
843
|
-
#backendReady = false;
|
|
844
|
-
#plannedBackendStops = new WeakSet;
|
|
1113
|
+
class DevBackend {
|
|
1114
|
+
#app;
|
|
1115
|
+
#env;
|
|
1116
|
+
#stdio;
|
|
1117
|
+
#logger;
|
|
1118
|
+
#statuses;
|
|
1119
|
+
#graph;
|
|
1120
|
+
#links;
|
|
1121
|
+
#process = null;
|
|
1122
|
+
#ready = false;
|
|
1123
|
+
#plannedStops = new WeakSet;
|
|
845
1124
|
#restartTimer = null;
|
|
846
|
-
#
|
|
847
|
-
#
|
|
848
|
-
#
|
|
849
|
-
#backendLifecycleState = "stopped";
|
|
1125
|
+
#recovery = new RestartSchedule2(backendRecoveryPolicy);
|
|
1126
|
+
#gaveUp = false;
|
|
1127
|
+
#lifecycleState = "stopped";
|
|
850
1128
|
#pendingRestartReason = null;
|
|
851
|
-
#
|
|
852
|
-
#
|
|
853
|
-
#
|
|
854
|
-
#
|
|
855
|
-
#builderRecoveryTimer = null;
|
|
856
|
-
#builderRecoveryAttempts = 0;
|
|
857
|
-
#backendStartStatus = null;
|
|
858
|
-
#backendBuildStatusGeneration = 0;
|
|
859
|
-
#backendStderrTail = [];
|
|
860
|
-
#lastGoodFrontend = {};
|
|
861
|
-
#rssRecycleTimer = null;
|
|
862
|
-
#rssRecycleReason = null;
|
|
863
|
-
#lastRssRecycleAtMono = null;
|
|
864
|
-
#rssCeilingTightReports = 0;
|
|
865
|
-
#rssCeilingTightWarned = false;
|
|
866
|
-
#rssSettleToken = 0;
|
|
867
|
-
#rssRecycleOver = null;
|
|
868
|
-
#rssCeilingAbandoned = false;
|
|
869
|
-
#buildStatusByPhase = new Map;
|
|
870
|
-
#pendingBuildStatusReplay = [];
|
|
871
|
-
#builderMessageQueue = Promise.resolve();
|
|
872
|
-
#backendGraph;
|
|
873
|
-
#idleSuspendTimer = null;
|
|
874
|
-
#suspended = false;
|
|
875
|
-
#waking = false;
|
|
876
|
-
#wokeAtMono = null;
|
|
877
|
-
#idleWatcher = null;
|
|
878
|
-
#suspendedChanges = null;
|
|
879
|
-
#builderGapStamp = null;
|
|
880
|
-
#pendingBuilderMessages = [];
|
|
881
|
-
#builderRequests = new BuilderRequestRouter;
|
|
882
|
-
#builderGeneration = 0;
|
|
1129
|
+
#restart = null;
|
|
1130
|
+
#startStatus = null;
|
|
1131
|
+
#stderrTail = [];
|
|
1132
|
+
#queuedStatuses = [];
|
|
883
1133
|
constructor(app, {
|
|
884
1134
|
env,
|
|
885
|
-
stdio
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
this
|
|
891
|
-
this.#
|
|
892
|
-
this.#
|
|
1135
|
+
stdio,
|
|
1136
|
+
logger,
|
|
1137
|
+
statuses,
|
|
1138
|
+
graph
|
|
1139
|
+
}, links) {
|
|
1140
|
+
this.#app = app;
|
|
1141
|
+
this.#env = env;
|
|
1142
|
+
this.#stdio = stdio;
|
|
1143
|
+
this.#logger = logger;
|
|
1144
|
+
this.#statuses = statuses;
|
|
1145
|
+
this.#graph = graph;
|
|
1146
|
+
this.#links = links;
|
|
893
1147
|
}
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
return;
|
|
897
|
-
this.#lastDevState = state;
|
|
898
|
-
this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
|
|
899
|
-
if (state === "ready")
|
|
900
|
-
this.#bootLatch.ready();
|
|
1148
|
+
get running() {
|
|
1149
|
+
return !!this.#process;
|
|
901
1150
|
}
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
await this.#stopBackend();
|
|
905
|
-
if (this.#builder)
|
|
906
|
-
this.#stopBuilder();
|
|
907
|
-
const [redisHost] = await Promise.all([
|
|
908
|
-
this.#prepareDatabase("redis"),
|
|
909
|
-
this.#backendGraph.refresh(),
|
|
910
|
-
this.#startBuilder()
|
|
911
|
-
]);
|
|
912
|
-
Object.assign(this.env, { REDIS_HOST: redisHost });
|
|
913
|
-
this.#startBackend();
|
|
914
|
-
this.#armIdleSuspend();
|
|
915
|
-
return this;
|
|
1151
|
+
get ready() {
|
|
1152
|
+
return this.#ready;
|
|
916
1153
|
}
|
|
917
|
-
|
|
918
|
-
this.#
|
|
919
|
-
this.#pendingRecycle = null;
|
|
920
|
-
this.#cancelIdleSuspend();
|
|
921
|
-
this.#stopIdleWatcher();
|
|
922
|
-
this.#clearRestartTimers();
|
|
923
|
-
this.#pendingRestartReason = null;
|
|
924
|
-
this.#failPendingBuilderMessages("dev server is shutting down");
|
|
925
|
-
await this.#backendRestart;
|
|
926
|
-
await this.#stopBackend();
|
|
927
|
-
this.#stopBuilder();
|
|
928
|
-
return this;
|
|
1154
|
+
get gaveUp() {
|
|
1155
|
+
return this.#gaveUp;
|
|
929
1156
|
}
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
if (timer)
|
|
933
|
-
clearTimeout(timer);
|
|
934
|
-
this.#restartTimer = this.#backendRecoveryTimer = this.#builderRecoveryTimer = null;
|
|
1157
|
+
get lifecycleState() {
|
|
1158
|
+
return this.#lifecycleState;
|
|
935
1159
|
}
|
|
936
|
-
|
|
937
|
-
this
|
|
1160
|
+
get restartScheduled() {
|
|
1161
|
+
return !!this.#restartTimer;
|
|
938
1162
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
|
|
942
|
-
if (policy === "none")
|
|
943
|
-
return "localhost";
|
|
944
|
-
if (policy === "required")
|
|
945
|
-
return await createTunnel(type, { app: this.app, environment });
|
|
946
|
-
try {
|
|
947
|
-
return await createTunnel(type, { app: this.app, environment });
|
|
948
|
-
} catch (error) {
|
|
949
|
-
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`);
|
|
950
|
-
return UNAVAILABLE_REDIS_HOST;
|
|
951
|
-
}
|
|
1163
|
+
get recovering() {
|
|
1164
|
+
return this.#recovery.pending;
|
|
952
1165
|
}
|
|
953
|
-
|
|
954
|
-
|
|
1166
|
+
get restartPending() {
|
|
1167
|
+
return !!(this.#restartTimer || this.#restart || this.#recovery.pending);
|
|
1168
|
+
}
|
|
1169
|
+
get restarting() {
|
|
1170
|
+
return this.#restart;
|
|
1171
|
+
}
|
|
1172
|
+
start(startStatus = null) {
|
|
1173
|
+
if (this.#links.isStopping())
|
|
955
1174
|
return;
|
|
956
|
-
if (this.#
|
|
957
|
-
this
|
|
958
|
-
return;
|
|
959
|
-
}
|
|
960
|
-
this.#
|
|
961
|
-
this.#
|
|
962
|
-
this.#
|
|
963
|
-
this.#
|
|
964
|
-
this.#
|
|
965
|
-
this.#
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
env: this.env,
|
|
1175
|
+
if (this.#process) {
|
|
1176
|
+
this.#logger.warn(`backend pid=${this.#process.pid} is still running; not starting a second one`);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
this.#links.beforeSpawn();
|
|
1180
|
+
this.#startStatus = startStatus;
|
|
1181
|
+
this.#gaveUp = false;
|
|
1182
|
+
this.#setLifecycleState("starting");
|
|
1183
|
+
this.#ready = false;
|
|
1184
|
+
this.#stderrTail = [];
|
|
1185
|
+
const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
|
|
1186
|
+
cwd: this.#app.workspace.workspaceRoot,
|
|
1187
|
+
stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
|
|
1188
|
+
env: this.#env,
|
|
971
1189
|
ipc: (msg) => {
|
|
972
1190
|
if (!msg || typeof msg !== "object")
|
|
973
1191
|
return;
|
|
974
1192
|
if (msg.type === "backend-ready") {
|
|
975
|
-
this.#
|
|
976
|
-
this.#
|
|
977
|
-
this.#
|
|
978
|
-
this.#
|
|
979
|
-
this
|
|
1193
|
+
this.#ready = true;
|
|
1194
|
+
this.#recovery.reset();
|
|
1195
|
+
this.#setLifecycleState("ready", `pid=${msg.pid}`);
|
|
1196
|
+
this.#recordReadyStatus();
|
|
1197
|
+
this.#logger.verbose(`backend ready pid=${msg.pid}`);
|
|
980
1198
|
this.#forgetRouteBuildStatus();
|
|
981
|
-
this
|
|
1199
|
+
this.replay();
|
|
982
1200
|
return;
|
|
983
1201
|
}
|
|
984
1202
|
if (msg.type === "build-status") {
|
|
985
|
-
const status = this.#
|
|
1203
|
+
const status = this.#statuses.recordBackend({
|
|
986
1204
|
generation: normalizeBackendReportedGeneration(msg.data.generation),
|
|
987
1205
|
ok: msg.data.ok,
|
|
988
1206
|
files: msg.data.files,
|
|
989
1207
|
message: msg.data.message
|
|
990
1208
|
});
|
|
991
|
-
this
|
|
1209
|
+
this.sendOrQueueStatus(status);
|
|
992
1210
|
if (!status.ok)
|
|
993
|
-
this.#
|
|
1211
|
+
this.#links.emit("failed", status.message);
|
|
994
1212
|
return;
|
|
995
1213
|
}
|
|
996
1214
|
if (backendMsgTypeSet.has(msg.type))
|
|
997
|
-
this.#
|
|
1215
|
+
this.#links.toBuilder(msg);
|
|
998
1216
|
},
|
|
999
1217
|
serialization: "advanced",
|
|
1000
1218
|
onExit: () => {
|
|
1001
|
-
this.#
|
|
1002
|
-
if (this.#
|
|
1003
|
-
this.#
|
|
1004
|
-
if (this.#
|
|
1005
|
-
this.#
|
|
1219
|
+
this.#ready = false;
|
|
1220
|
+
if (this.#process === backend)
|
|
1221
|
+
this.#process = null;
|
|
1222
|
+
if (this.#plannedStops.has(backend)) {
|
|
1223
|
+
this.#plannedStops.delete(backend);
|
|
1006
1224
|
return;
|
|
1007
1225
|
}
|
|
1008
|
-
this.#
|
|
1009
|
-
}
|
|
1010
|
-
});
|
|
1011
|
-
this.#backend = backend;
|
|
1012
|
-
this.logger.verbose(`backend spawned pid=${backend.pid}`);
|
|
1013
|
-
if (this.stdio === "pipe") {
|
|
1014
|
-
this.#forwardBackendStream(backend.stderr, "stderr");
|
|
1015
|
-
this.#forwardBackendStream(backend.stdout, "stdout");
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
#recordBackendStderr(chunk) {
|
|
1019
|
-
const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
|
|
1020
|
-
if (lines.length === 0)
|
|
1021
|
-
return;
|
|
1022
|
-
this.#backendStderrTail.push(...lines);
|
|
1023
|
-
if (this.#backendStderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
|
|
1024
|
-
this.#backendStderrTail.splice(0, this.#backendStderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
async#forwardBackendStream(stream, kind) {
|
|
1028
|
-
if (!stream)
|
|
1029
|
-
return;
|
|
1030
|
-
const decoder = new TextDecoder;
|
|
1031
|
-
try {
|
|
1032
|
-
for await (const chunk of stream) {
|
|
1033
|
-
const text = decoder.decode(chunk, { stream: true });
|
|
1034
|
-
if (!text)
|
|
1035
|
-
continue;
|
|
1036
|
-
if (kind === "stderr") {
|
|
1037
|
-
this.#recordBackendStderr(text);
|
|
1038
|
-
process.stderr.write(text);
|
|
1039
|
-
} else
|
|
1040
|
-
process.stdout.write(text);
|
|
1226
|
+
this.#scheduleRecovery("backend-exit");
|
|
1041
1227
|
}
|
|
1042
|
-
} catch {}
|
|
1043
|
-
}
|
|
1044
|
-
#nextBackendBuildStatusGeneration(generation) {
|
|
1045
|
-
if (typeof generation === "number") {
|
|
1046
|
-
this.#backendBuildStatusGeneration = Math.max(this.#backendBuildStatusGeneration, generation);
|
|
1047
|
-
return generation;
|
|
1048
|
-
}
|
|
1049
|
-
this.#backendBuildStatusGeneration += 1;
|
|
1050
|
-
return this.#backendBuildStatusGeneration;
|
|
1051
|
-
}
|
|
1052
|
-
#recordBackendBuildStatus({
|
|
1053
|
-
generation,
|
|
1054
|
-
ok,
|
|
1055
|
-
files,
|
|
1056
|
-
message
|
|
1057
|
-
}) {
|
|
1058
|
-
const status = createBackendBuildStatus({
|
|
1059
|
-
generation: this.#nextBackendBuildStatusGeneration(generation),
|
|
1060
|
-
ok,
|
|
1061
|
-
files,
|
|
1062
|
-
message
|
|
1063
1228
|
});
|
|
1064
|
-
this.#
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
const startStatus = this.#backendStartStatus;
|
|
1070
|
-
if (startStatus || previous?.ok === false) {
|
|
1071
|
-
const status = this.#recordBackendBuildStatus({
|
|
1072
|
-
generation: startStatus?.generation ?? previous?.generation,
|
|
1073
|
-
ok: true,
|
|
1074
|
-
files: startStatus?.files ?? previous?.files ?? [],
|
|
1075
|
-
message: "Backend ready"
|
|
1076
|
-
});
|
|
1077
|
-
this.#sendOrQueueBuildStatus(status);
|
|
1229
|
+
this.#process = backend;
|
|
1230
|
+
this.#logger.verbose(`backend spawned pid=${backend.pid}`);
|
|
1231
|
+
if (this.#stdio === "pipe") {
|
|
1232
|
+
this.#forwardStream(backend.stderr, "stderr");
|
|
1233
|
+
this.#forwardStream(backend.stdout, "stdout");
|
|
1078
1234
|
}
|
|
1079
|
-
this.#backendStartStatus = null;
|
|
1080
|
-
}
|
|
1081
|
-
#setBackendLifecycleState(next, detail) {
|
|
1082
|
-
if (this.#backendLifecycleState === next && !detail)
|
|
1083
|
-
return;
|
|
1084
|
-
const prev = this.#backendLifecycleState;
|
|
1085
|
-
this.#backendLifecycleState = next;
|
|
1086
|
-
this.logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
|
|
1087
|
-
this.#emitDevEvent(devHostStateOf(next, this.#backendGaveUp), detail);
|
|
1088
1235
|
}
|
|
1089
|
-
|
|
1090
|
-
if (!this.#
|
|
1236
|
+
send(message) {
|
|
1237
|
+
if (!this.#process || !this.#ready) {
|
|
1091
1238
|
if (message.type === "css-updated" || message.type === "pages-updated" || message.type === "build-status") {
|
|
1092
|
-
this
|
|
1239
|
+
this.#logger.verbose(`backend is not ready; will replay ${message.type}`);
|
|
1093
1240
|
return;
|
|
1094
1241
|
}
|
|
1095
1242
|
if (message.type !== "builder-ready")
|
|
1096
|
-
this
|
|
1243
|
+
this.#logger.warn(`backend is not ready; dropping ${message.type}`);
|
|
1097
1244
|
return;
|
|
1098
1245
|
}
|
|
1099
1246
|
try {
|
|
1100
|
-
this.#
|
|
1247
|
+
this.#process.send(message);
|
|
1101
1248
|
} catch (err) {
|
|
1102
|
-
this
|
|
1249
|
+
this.#logger.warn(`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
sendOrQueueStatus(status) {
|
|
1253
|
+
if (!this.#process || shouldQueueBuildStatusReplay(this.#ready, this.#queuedStatuses.length)) {
|
|
1254
|
+
this.#queuedStatuses.push(status);
|
|
1255
|
+
this.#logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
this.send({ type: "build-status", data: status });
|
|
1259
|
+
}
|
|
1260
|
+
replay() {
|
|
1261
|
+
if (!this.#ready)
|
|
1262
|
+
return;
|
|
1263
|
+
const { css, pages } = this.#statuses.lastGood;
|
|
1264
|
+
if (css)
|
|
1265
|
+
this.send(css);
|
|
1266
|
+
if (pages)
|
|
1267
|
+
this.send(pages);
|
|
1268
|
+
const queuedStatuses = this.#queuedStatuses.splice(0);
|
|
1269
|
+
for (const status of this.#statuses.replaySequence(queuedStatuses)) {
|
|
1270
|
+
this.send({ type: "build-status", data: status });
|
|
1103
1271
|
}
|
|
1104
1272
|
}
|
|
1105
|
-
|
|
1106
|
-
|
|
1273
|
+
dropQueuedStatuses() {
|
|
1274
|
+
this.#queuedStatuses = [];
|
|
1275
|
+
}
|
|
1276
|
+
async stop() {
|
|
1277
|
+
if (!this.#process)
|
|
1107
1278
|
return;
|
|
1108
|
-
const backend = this.#
|
|
1109
|
-
this.#
|
|
1110
|
-
this.#
|
|
1111
|
-
this.#
|
|
1112
|
-
this
|
|
1279
|
+
const backend = this.#process;
|
|
1280
|
+
this.#plannedStops.add(backend);
|
|
1281
|
+
this.#ready = false;
|
|
1282
|
+
this.#setLifecycleState("stopping", `pid=${backend.pid}`);
|
|
1283
|
+
this.#logger.verbose(`stopping backend pid=${backend.pid}`);
|
|
1113
1284
|
try {
|
|
1114
1285
|
backend.kill("SIGTERM");
|
|
1115
1286
|
const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), BACKEND_GRACEFUL_TIMEOUT_MS));
|
|
1116
1287
|
const result = await Promise.race([backend.exited, timeout]);
|
|
1117
1288
|
if (result === "timeout") {
|
|
1118
|
-
this
|
|
1289
|
+
this.#logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
|
|
1119
1290
|
backend.kill("SIGKILL");
|
|
1120
1291
|
await backend.exited.catch(() => {
|
|
1121
1292
|
return;
|
|
1122
1293
|
});
|
|
1123
1294
|
}
|
|
1124
1295
|
} finally {
|
|
1125
|
-
if (this.#
|
|
1126
|
-
this.#
|
|
1127
|
-
this.#
|
|
1296
|
+
if (this.#process === backend)
|
|
1297
|
+
this.#process = null;
|
|
1298
|
+
this.#setLifecycleState("stopped", `pid=${backend.pid}`);
|
|
1128
1299
|
}
|
|
1129
1300
|
}
|
|
1130
|
-
|
|
1301
|
+
cancelTimers() {
|
|
1302
|
+
if (this.#restartTimer)
|
|
1303
|
+
clearTimeout(this.#restartTimer);
|
|
1304
|
+
this.#restartTimer = null;
|
|
1305
|
+
this.#recovery.cancel();
|
|
1306
|
+
}
|
|
1307
|
+
dropPendingRestart() {
|
|
1308
|
+
this.#pendingRestartReason = null;
|
|
1309
|
+
}
|
|
1310
|
+
scheduleRestart(reason) {
|
|
1131
1311
|
this.#pendingRestartReason = mergeBackendRestartReasons(this.#pendingRestartReason, reason);
|
|
1132
1312
|
const pending = this.#pendingRestartReason;
|
|
1133
|
-
this.#
|
|
1134
|
-
|
|
1135
|
-
clearTimeout(this.#backendRecoveryTimer);
|
|
1136
|
-
this.#backendRecoveryTimer = null;
|
|
1137
|
-
}
|
|
1313
|
+
this.#setLifecycleState("restart-pending", `generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`);
|
|
1314
|
+
this.#recovery.cancel();
|
|
1138
1315
|
if (this.#restartTimer)
|
|
1139
1316
|
clearTimeout(this.#restartTimer);
|
|
1140
1317
|
this.#restartTimer = setTimeout(() => {
|
|
1141
1318
|
this.#restartTimer = null;
|
|
1142
|
-
this.#
|
|
1143
|
-
this.#
|
|
1319
|
+
this.#restart ??= this.#drainRestarts().finally(() => {
|
|
1320
|
+
this.#restart = null;
|
|
1144
1321
|
});
|
|
1145
1322
|
}, BACKEND_RESTART_DEBOUNCE_MS);
|
|
1146
1323
|
}
|
|
1147
|
-
|
|
1148
|
-
|
|
1324
|
+
reviveAfterGreenBuild(status) {
|
|
1325
|
+
if (!status.ok || !this.#gaveUp || this.#process || this.#recovery.pending)
|
|
1326
|
+
return;
|
|
1327
|
+
this.#logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
|
|
1328
|
+
this.#recovery.reset();
|
|
1329
|
+
this.start({ generation: status.generation, files: status.files });
|
|
1330
|
+
}
|
|
1331
|
+
#recordStderr(chunk) {
|
|
1332
|
+
const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
|
|
1333
|
+
if (lines.length === 0)
|
|
1334
|
+
return;
|
|
1335
|
+
this.#stderrTail.push(...lines);
|
|
1336
|
+
if (this.#stderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
|
|
1337
|
+
this.#stderrTail.splice(0, this.#stderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
async#forwardStream(stream, kind) {
|
|
1341
|
+
if (!stream)
|
|
1342
|
+
return;
|
|
1343
|
+
const decoder = new TextDecoder;
|
|
1344
|
+
try {
|
|
1345
|
+
for await (const chunk of stream) {
|
|
1346
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
1347
|
+
if (!text)
|
|
1348
|
+
continue;
|
|
1349
|
+
if (kind === "stderr") {
|
|
1350
|
+
this.#recordStderr(text);
|
|
1351
|
+
process.stderr.write(text);
|
|
1352
|
+
} else
|
|
1353
|
+
process.stdout.write(text);
|
|
1354
|
+
}
|
|
1355
|
+
} catch {}
|
|
1356
|
+
}
|
|
1357
|
+
#recordReadyStatus() {
|
|
1358
|
+
const previous = this.#statuses.phase("backend");
|
|
1359
|
+
const startStatus = this.#startStatus;
|
|
1360
|
+
if (startStatus || previous?.ok === false) {
|
|
1361
|
+
const status = this.#statuses.recordBackend({
|
|
1362
|
+
generation: startStatus?.generation ?? previous?.generation,
|
|
1363
|
+
ok: true,
|
|
1364
|
+
files: startStatus?.files ?? previous?.files ?? [],
|
|
1365
|
+
message: "Backend ready"
|
|
1366
|
+
});
|
|
1367
|
+
this.sendOrQueueStatus(status);
|
|
1368
|
+
}
|
|
1369
|
+
this.#startStatus = null;
|
|
1370
|
+
}
|
|
1371
|
+
#forgetRouteBuildStatus() {
|
|
1372
|
+
this.#statuses.forgetRoute();
|
|
1373
|
+
this.#queuedStatuses = this.#queuedStatuses.filter((status) => status.phase !== "route");
|
|
1374
|
+
}
|
|
1375
|
+
#setLifecycleState(next, detail) {
|
|
1376
|
+
if (this.#lifecycleState === next && !detail)
|
|
1377
|
+
return;
|
|
1378
|
+
const prev = this.#lifecycleState;
|
|
1379
|
+
this.#lifecycleState = next;
|
|
1380
|
+
this.#logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
|
|
1381
|
+
this.#links.emit(devHostStateOf(next, this.#gaveUp), detail);
|
|
1382
|
+
}
|
|
1383
|
+
async#drainRestarts() {
|
|
1384
|
+
while (this.#pendingRestartReason && !this.#restartTimer && !this.#links.isStopping()) {
|
|
1149
1385
|
const next = this.#pendingRestartReason;
|
|
1150
1386
|
this.#pendingRestartReason = null;
|
|
1151
|
-
await this.#
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
async#
|
|
1155
|
-
this
|
|
1156
|
-
this.#
|
|
1157
|
-
await Promise.all([this
|
|
1158
|
-
this
|
|
1159
|
-
}
|
|
1160
|
-
#
|
|
1161
|
-
if (this.#
|
|
1162
|
-
return;
|
|
1163
|
-
if (
|
|
1164
|
-
const message = `Backend exited ${this.#
|
|
1165
|
-
this.#
|
|
1166
|
-
this.#
|
|
1167
|
-
this
|
|
1168
|
-
if (this.#
|
|
1169
|
-
this
|
|
1170
|
-
${this.#
|
|
1387
|
+
await this.#restartWith(next);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
async#restartWith(reason) {
|
|
1391
|
+
this.#logger.verbose(`[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`);
|
|
1392
|
+
this.#recovery.reset();
|
|
1393
|
+
await Promise.all([this.stop(), this.#graph.refresh()]);
|
|
1394
|
+
this.start({ generation: reason.generation, files: reason.files });
|
|
1395
|
+
}
|
|
1396
|
+
#scheduleRecovery(reason) {
|
|
1397
|
+
if (this.#recovery.pending || this.#process)
|
|
1398
|
+
return;
|
|
1399
|
+
if (this.#recovery.exhausted) {
|
|
1400
|
+
const message = `Backend exited ${this.#recovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
|
|
1401
|
+
this.#gaveUp = true;
|
|
1402
|
+
this.#setLifecycleState("stopped", `gave up after ${this.#recovery.attempts} recovery attempts`);
|
|
1403
|
+
this.#logger.error(`[backend-recovery] ${message}`);
|
|
1404
|
+
if (this.#stderrTail.length > 0) {
|
|
1405
|
+
this.#logger.error(`[backend-recovery] recent backend stderr:
|
|
1406
|
+
${this.#stderrTail.join(`
|
|
1171
1407
|
`)}`);
|
|
1172
1408
|
}
|
|
1173
|
-
const abandonedStatus = this.#
|
|
1174
|
-
this
|
|
1409
|
+
const abandonedStatus = this.#statuses.recordBackend({ ok: false, files: [], message });
|
|
1410
|
+
this.sendOrQueueStatus(abandonedStatus);
|
|
1175
1411
|
return;
|
|
1176
1412
|
}
|
|
1177
|
-
this.#
|
|
1178
|
-
const
|
|
1179
|
-
const
|
|
1180
|
-
this.#backendRecoveryAttempts = attempt + 1;
|
|
1181
|
-
const failureStatus = this.#recordBackendBuildStatus({
|
|
1413
|
+
this.#setLifecycleState("recovering", reason);
|
|
1414
|
+
const delay = this.#recovery.next();
|
|
1415
|
+
const failureStatus = this.#statuses.recordBackend({
|
|
1182
1416
|
ok: false,
|
|
1183
1417
|
files: [],
|
|
1184
1418
|
message: `Backend exited unexpectedly (${reason}); restarting in ${delay}ms`
|
|
1185
1419
|
});
|
|
1186
|
-
this
|
|
1187
|
-
this
|
|
1188
|
-
if (this.#
|
|
1189
|
-
this
|
|
1190
|
-
${this.#
|
|
1420
|
+
this.sendOrQueueStatus(failureStatus);
|
|
1421
|
+
this.#logger.warn(`[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#recovery.attempts})`);
|
|
1422
|
+
if (this.#stderrTail.length > 0) {
|
|
1423
|
+
this.#logger.warn(`[backend-recovery] recent backend stderr:
|
|
1424
|
+
${this.#stderrTail.join(`
|
|
1191
1425
|
`)}`);
|
|
1192
1426
|
}
|
|
1193
|
-
this.#
|
|
1194
|
-
this.#
|
|
1195
|
-
if (this.#backend)
|
|
1427
|
+
this.#recovery.arm(delay, () => {
|
|
1428
|
+
if (this.#process)
|
|
1196
1429
|
return;
|
|
1197
|
-
this.#
|
|
1198
|
-
if (!this.#
|
|
1199
|
-
this
|
|
1430
|
+
this.#graph.refresh().finally(() => {
|
|
1431
|
+
if (!this.#process)
|
|
1432
|
+
this.start({ generation: failureStatus.generation, files: failureStatus.files });
|
|
1200
1433
|
});
|
|
1201
|
-
}, delay);
|
|
1202
|
-
}
|
|
1203
|
-
#enqueueBuilderMessage(message) {
|
|
1204
|
-
this.#builderMessageQueue = this.#builderMessageQueue.then(() => this.#handleBuilderMessage(message)).catch((err) => {
|
|
1205
|
-
this.logger.warn(`failed to handle builder message: ${err instanceof Error ? err.message : String(err)}`);
|
|
1206
1434
|
});
|
|
1207
1435
|
}
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// pkgs/@akanjs/devkit/akanApp/devBootLatch.ts
|
|
1439
|
+
class DevBootLatch {
|
|
1440
|
+
#onBooted;
|
|
1441
|
+
#waitMs;
|
|
1442
|
+
#ready = false;
|
|
1443
|
+
#armed = false;
|
|
1444
|
+
#booted = false;
|
|
1445
|
+
#timer = null;
|
|
1446
|
+
constructor(onBooted, { waitMs = 30000 } = {}) {
|
|
1447
|
+
this.#onBooted = onBooted;
|
|
1448
|
+
this.#waitMs = waitMs;
|
|
1449
|
+
}
|
|
1450
|
+
ready() {
|
|
1451
|
+
this.#ready = true;
|
|
1452
|
+
if (!this.#armed && !this.#timer) {
|
|
1453
|
+
this.#timer = setTimeout(() => this.armed(), this.#waitMs);
|
|
1454
|
+
this.#timer.unref?.();
|
|
1219
1455
|
}
|
|
1220
|
-
|
|
1221
|
-
|
|
1456
|
+
this.#release();
|
|
1457
|
+
}
|
|
1458
|
+
armed() {
|
|
1459
|
+
this.#armed = true;
|
|
1460
|
+
this.#release();
|
|
1461
|
+
}
|
|
1462
|
+
#release() {
|
|
1463
|
+
if (this.#booted || !this.#ready || !this.#armed)
|
|
1222
1464
|
return;
|
|
1465
|
+
this.#booted = true;
|
|
1466
|
+
if (this.#timer)
|
|
1467
|
+
clearTimeout(this.#timer);
|
|
1468
|
+
this.#timer = null;
|
|
1469
|
+
this.#onBooted();
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
// pkgs/@akanjs/devkit/akanApp/devBuilder.ts
|
|
1474
|
+
import { RestartSchedule as RestartSchedule3 } from "akanjs/common";
|
|
1475
|
+
var BUILDER_READY_TIMEOUT_MS = 150000;
|
|
1476
|
+
var BUILDER_START_MAX_ATTEMPTS = 3;
|
|
1477
|
+
|
|
1478
|
+
class DevBuilder {
|
|
1479
|
+
#app;
|
|
1480
|
+
#env;
|
|
1481
|
+
#stdio;
|
|
1482
|
+
#logger;
|
|
1483
|
+
#links;
|
|
1484
|
+
#host = null;
|
|
1485
|
+
#patcherOff = false;
|
|
1486
|
+
#recovery = new RestartSchedule3({ min: 2000, max: 60000 });
|
|
1487
|
+
#abandonStart = null;
|
|
1488
|
+
#generation = 0;
|
|
1489
|
+
constructor(app, { env, stdio, logger }, links) {
|
|
1490
|
+
this.#app = app;
|
|
1491
|
+
this.#env = env;
|
|
1492
|
+
this.#stdio = stdio;
|
|
1493
|
+
this.#logger = logger;
|
|
1494
|
+
this.#links = links;
|
|
1495
|
+
}
|
|
1496
|
+
get current() {
|
|
1497
|
+
return this.#host;
|
|
1498
|
+
}
|
|
1499
|
+
get recovering() {
|
|
1500
|
+
return this.#recovery.pending;
|
|
1501
|
+
}
|
|
1502
|
+
async start({ announceBootState = false } = {}) {
|
|
1503
|
+
const startTime = Date.now();
|
|
1504
|
+
this.#app.verbose(`[cli] waiting for builder to complete initial base build\u2026`);
|
|
1505
|
+
let lastError;
|
|
1506
|
+
for (let attempt = 1;attempt <= BUILDER_START_MAX_ATTEMPTS; attempt++) {
|
|
1507
|
+
const builder = await IncrementalBuilderHost.create(this.#app, this.#env, (msg) => {
|
|
1508
|
+
this.#links.onMessage(msg);
|
|
1509
|
+
}, {
|
|
1510
|
+
stdio: this.#stdio,
|
|
1511
|
+
onOutput: (kind, text) => void (kind === "stderr" ? process.stderr : process.stdout).write(text),
|
|
1512
|
+
patcherOff: this.#patcherOff
|
|
1513
|
+
});
|
|
1514
|
+
if (this.#links.isStopping()) {
|
|
1515
|
+
builder.stop();
|
|
1516
|
+
throw new Error("dev server stopped before the builder started");
|
|
1517
|
+
}
|
|
1518
|
+
this.#host = builder;
|
|
1519
|
+
try {
|
|
1520
|
+
await this.#waitForReady(attempt, { announceBootState });
|
|
1521
|
+
this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms \u2014 starting backend`);
|
|
1522
|
+
return this.#host;
|
|
1523
|
+
} catch (err) {
|
|
1524
|
+
lastError = err;
|
|
1525
|
+
this.stop();
|
|
1526
|
+
if (attempt >= BUILDER_START_MAX_ATTEMPTS || this.#links.isStopping())
|
|
1527
|
+
break;
|
|
1528
|
+
this.#app.verbose(`[cli] builder failed before ready; retrying (${attempt + 1}/${BUILDER_START_MAX_ATTEMPTS})`);
|
|
1529
|
+
}
|
|
1223
1530
|
}
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1531
|
+
this.#links.onStartFailed();
|
|
1532
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
1533
|
+
}
|
|
1534
|
+
stop() {
|
|
1535
|
+
this.#links.onStop();
|
|
1536
|
+
if (!this.#host)
|
|
1227
1537
|
return;
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1538
|
+
if (this.#host.patcherOff)
|
|
1539
|
+
this.#patcherOff = true;
|
|
1540
|
+
this.#host.stop();
|
|
1541
|
+
this.#host = null;
|
|
1542
|
+
}
|
|
1543
|
+
abandonStart(error) {
|
|
1544
|
+
this.#abandonStart?.(error);
|
|
1545
|
+
}
|
|
1546
|
+
cancelRecovery() {
|
|
1547
|
+
this.#recovery.cancel();
|
|
1548
|
+
}
|
|
1549
|
+
resetRecovery() {
|
|
1550
|
+
this.#recovery.reset();
|
|
1551
|
+
}
|
|
1552
|
+
clearPatcherOff() {
|
|
1553
|
+
this.#patcherOff = false;
|
|
1554
|
+
}
|
|
1555
|
+
scheduleRecovery(reason) {
|
|
1556
|
+
if (this.#links.isStopping() || this.#recovery.pending || this.#host)
|
|
1237
1557
|
return;
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
const answer = this.#builderRequests.settle(message);
|
|
1241
|
-
if (!answer) {
|
|
1242
|
-
this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
|
|
1558
|
+
const delay = this.#recovery.schedule(() => {
|
|
1559
|
+
if (this.#links.isStopping() || this.#host)
|
|
1243
1560
|
return;
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
}
|
|
1248
|
-
this.#sendToBackend(message);
|
|
1561
|
+
this.#recover(reason);
|
|
1562
|
+
});
|
|
1563
|
+
this.#logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#recovery.attempts})`);
|
|
1249
1564
|
}
|
|
1250
|
-
|
|
1251
|
-
const generation =
|
|
1252
|
-
if (generation === undefined || generation <= this.#
|
|
1565
|
+
trackGeneration(message) {
|
|
1566
|
+
const generation = DevBuilder.#generationOf(message);
|
|
1567
|
+
if (generation === undefined || generation <= this.#generation)
|
|
1253
1568
|
return;
|
|
1254
|
-
this.#
|
|
1255
|
-
Object.assign(this
|
|
1569
|
+
this.#generation = generation;
|
|
1570
|
+
Object.assign(this.#env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
|
|
1256
1571
|
}
|
|
1257
|
-
static #
|
|
1572
|
+
static #generationOf(message) {
|
|
1258
1573
|
if (message.type === "invalidate")
|
|
1259
1574
|
return message.generation;
|
|
1260
1575
|
if (message.type === "build-status" || message.type === "builder-metrics")
|
|
@@ -1263,398 +1578,366 @@ ${this.#backendStderrTail.join(`
|
|
|
1263
1578
|
return message.data.generation;
|
|
1264
1579
|
return;
|
|
1265
1580
|
}
|
|
1266
|
-
#
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
}
|
|
1272
|
-
this.logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
|
|
1273
|
-
return false;
|
|
1274
|
-
}
|
|
1275
|
-
#handleBuilderMetrics(metrics) {
|
|
1276
|
-
if (this.#rssCeilingAbandoned)
|
|
1277
|
-
return;
|
|
1278
|
-
const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
|
|
1279
|
-
const decision = decideBuilderRssRecycle({
|
|
1280
|
-
rssBytes: metrics.rssBytes,
|
|
1281
|
-
ceilingBytes,
|
|
1282
|
-
buildFailed: hasBuildFailureForGeneration(this.#buildStatusByPhase, metrics.generation),
|
|
1283
|
-
msSinceLastRecycle: this.#lastRssRecycleAtMono === null ? null : performance.now() - this.#lastRssRecycleAtMono
|
|
1284
|
-
});
|
|
1285
|
-
if (decision === "below-ceiling") {
|
|
1286
|
-
this.#rssCeilingTightReports = 0;
|
|
1287
|
-
return;
|
|
1288
|
-
}
|
|
1289
|
-
if (decision === "unbounded")
|
|
1290
|
-
return;
|
|
1291
|
-
if (decision === "build-failed") {
|
|
1292
|
-
this.logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
|
|
1293
|
-
return;
|
|
1294
|
-
}
|
|
1295
|
-
if (decision === "too-soon") {
|
|
1296
|
-
this.#rssCeilingTightReports += 1;
|
|
1297
|
-
if (this.#rssCeilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#rssCeilingTightReports))
|
|
1581
|
+
async#recover(reason) {
|
|
1582
|
+
try {
|
|
1583
|
+
await this.start();
|
|
1584
|
+
} catch (err) {
|
|
1585
|
+
if (this.#links.isStopping())
|
|
1298
1586
|
return;
|
|
1299
|
-
this.#
|
|
1300
|
-
this.
|
|
1587
|
+
this.#logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1588
|
+
this.scheduleRecovery(reason);
|
|
1301
1589
|
return;
|
|
1302
1590
|
}
|
|
1303
|
-
this.#
|
|
1591
|
+
this.#recovery.reset();
|
|
1592
|
+
this.#logger.info("[builder-recovery] builder recovered");
|
|
1593
|
+
this.#links.onRecovered(reason);
|
|
1304
1594
|
}
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1595
|
+
#waitForReady(attempt, { announceBootState = false } = {}) {
|
|
1596
|
+
return new Promise((resolve, reject) => {
|
|
1597
|
+
if (!this.#host)
|
|
1598
|
+
throw new Error("Builder Not Found");
|
|
1599
|
+
let settled = false;
|
|
1600
|
+
const settle = (fn) => {
|
|
1601
|
+
if (settled)
|
|
1602
|
+
return;
|
|
1603
|
+
settled = true;
|
|
1604
|
+
clearTimeout(timeout);
|
|
1605
|
+
if (this.#abandonStart === abandon)
|
|
1606
|
+
this.#abandonStart = null;
|
|
1607
|
+
fn();
|
|
1608
|
+
};
|
|
1609
|
+
const abandon = (error) => settle(() => reject(error));
|
|
1610
|
+
this.#abandonStart = abandon;
|
|
1611
|
+
const timeout = setTimeout(() => {
|
|
1612
|
+
settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
|
|
1613
|
+
}, BUILDER_READY_TIMEOUT_MS);
|
|
1614
|
+
this.#host.start({
|
|
1615
|
+
announceBootState,
|
|
1616
|
+
onExit: () => {
|
|
1617
|
+
settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
|
|
1618
|
+
},
|
|
1619
|
+
onAway: () => {
|
|
1620
|
+
this.#links.onAway();
|
|
1621
|
+
},
|
|
1622
|
+
onReady: () => {
|
|
1623
|
+
settle(resolve);
|
|
1624
|
+
this.#links.onReady();
|
|
1625
|
+
},
|
|
1626
|
+
onRestartReady: () => {
|
|
1627
|
+
this.#links.onRestartReady();
|
|
1628
|
+
}
|
|
1629
|
+
});
|
|
1630
|
+
});
|
|
1317
1631
|
}
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
const pendingReason = this.#rssRecycleReason;
|
|
1329
|
-
const pendingOver = this.#rssRecycleOver;
|
|
1330
|
-
this.#rssRecycleReason = null;
|
|
1331
|
-
this.#rssRecycleOver = null;
|
|
1332
|
-
if (!pendingReason)
|
|
1333
|
-
return;
|
|
1334
|
-
if (!pendingOver) {
|
|
1335
|
-
this.#recycleBuilderForRss(pendingReason);
|
|
1336
|
-
return;
|
|
1337
|
-
}
|
|
1338
|
-
this.#recycleBuilderForRssWhenStillOver(pendingReason, pendingOver);
|
|
1339
|
-
}, BUILDER_RSS_RECYCLE_QUIET_MS);
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
// pkgs/@akanjs/devkit/akanApp/devBuildStatusBoard.ts
|
|
1635
|
+
class DevBuildStatusBoard {
|
|
1636
|
+
#logger;
|
|
1637
|
+
#byPhase = new Map;
|
|
1638
|
+
#backendGeneration = 0;
|
|
1639
|
+
#lastGood = {};
|
|
1640
|
+
constructor(logger) {
|
|
1641
|
+
this.#logger = logger;
|
|
1340
1642
|
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1643
|
+
get lastGood() {
|
|
1644
|
+
return this.#lastGood;
|
|
1645
|
+
}
|
|
1646
|
+
get failing() {
|
|
1647
|
+
return hasAnyBuildFailure(this.#byPhase);
|
|
1648
|
+
}
|
|
1649
|
+
phase(phase) {
|
|
1650
|
+
return this.#byPhase.get(phase);
|
|
1651
|
+
}
|
|
1652
|
+
failedAt(generation) {
|
|
1653
|
+
return hasBuildFailureForGeneration(this.#byPhase, generation);
|
|
1654
|
+
}
|
|
1655
|
+
replaySequence(queued) {
|
|
1656
|
+
return buildStatusReplaySequence(queued, this.#byPhase);
|
|
1657
|
+
}
|
|
1658
|
+
nextBackendGeneration(generation) {
|
|
1659
|
+
if (typeof generation === "number") {
|
|
1660
|
+
this.#backendGeneration = Math.max(this.#backendGeneration, generation);
|
|
1661
|
+
return generation;
|
|
1345
1662
|
}
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1663
|
+
this.#backendGeneration += 1;
|
|
1664
|
+
return this.#backendGeneration;
|
|
1665
|
+
}
|
|
1666
|
+
record(status) {
|
|
1667
|
+
const recovered = shouldMarkBuildPhaseRecovered(this.#byPhase, status);
|
|
1668
|
+
if (shouldKeepBuildFailure(this.#byPhase, status))
|
|
1349
1669
|
return;
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1670
|
+
this.#byPhase.set(status.phase, status);
|
|
1671
|
+
const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
|
|
1672
|
+
if (status.ok)
|
|
1673
|
+
this.#logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
|
|
1674
|
+
else
|
|
1675
|
+
this.#logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
|
|
1676
|
+
}
|
|
1677
|
+
recordBackend({
|
|
1678
|
+
generation,
|
|
1679
|
+
ok,
|
|
1680
|
+
files,
|
|
1681
|
+
message
|
|
1682
|
+
}) {
|
|
1683
|
+
const status = createBackendBuildStatus({
|
|
1684
|
+
generation: this.nextBackendGeneration(generation),
|
|
1685
|
+
ok,
|
|
1686
|
+
files,
|
|
1687
|
+
message
|
|
1688
|
+
});
|
|
1689
|
+
this.record(status);
|
|
1690
|
+
return status;
|
|
1691
|
+
}
|
|
1692
|
+
forgetRoute() {
|
|
1693
|
+
this.#byPhase.delete("route");
|
|
1694
|
+
}
|
|
1695
|
+
reset() {
|
|
1696
|
+
this.#lastGood = {};
|
|
1697
|
+
this.#byPhase.clear();
|
|
1698
|
+
}
|
|
1699
|
+
recordLastGood(message, { supersede = false } = {}) {
|
|
1700
|
+
if (message.type === "pages-updated") {
|
|
1701
|
+
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.pages, message))
|
|
1702
|
+
return;
|
|
1703
|
+
this.#lastGood.pages = message;
|
|
1704
|
+
this.#logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
|
|
1357
1705
|
return;
|
|
1358
1706
|
}
|
|
1359
|
-
|
|
1360
|
-
if (settledBytes !== null && settledBytes < ceilingBytes) {
|
|
1361
|
-
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`);
|
|
1707
|
+
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.css, message))
|
|
1362
1708
|
return;
|
|
1363
|
-
|
|
1364
|
-
this.#
|
|
1365
|
-
}
|
|
1366
|
-
static async readProcessRssBytes(pid) {
|
|
1367
|
-
if (process.platform === "win32")
|
|
1368
|
-
return await AkanAppHost.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], AkanAppHost.#tasklistRssKb);
|
|
1369
|
-
if (process.platform === "darwin") {
|
|
1370
|
-
const footprintBytes = await AkanAppHost.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], AkanAppHost.#footprintKb);
|
|
1371
|
-
if (footprintBytes !== null)
|
|
1372
|
-
return footprintBytes;
|
|
1373
|
-
}
|
|
1374
|
-
const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
|
|
1375
|
-
const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
|
|
1376
|
-
if (vmRssKb)
|
|
1377
|
-
return Number(vmRssKb) * 1024;
|
|
1378
|
-
return await AkanAppHost.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
|
|
1709
|
+
this.#lastGood.css = message;
|
|
1710
|
+
this.#logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
|
|
1379
1711
|
}
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
return null;
|
|
1386
|
-
}
|
|
1387
|
-
const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
|
|
1388
|
-
try {
|
|
1389
|
-
const output = await new Response(proc.stdout).text();
|
|
1390
|
-
await proc.exited;
|
|
1391
|
-
const rssKb = parseKb(output);
|
|
1392
|
-
return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
|
|
1393
|
-
} catch {
|
|
1394
|
-
return null;
|
|
1395
|
-
} finally {
|
|
1396
|
-
clearTimeout(killer);
|
|
1712
|
+
shouldRelayRecycled(message) {
|
|
1713
|
+
const current = message.type === "pages-updated" ? this.#lastGood.pages : this.#lastGood.css;
|
|
1714
|
+
if (shouldRelayRecycledFrontendState(current, message)) {
|
|
1715
|
+
this.#logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
|
|
1716
|
+
return true;
|
|
1397
1717
|
}
|
|
1718
|
+
this.#logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
|
|
1719
|
+
return false;
|
|
1398
1720
|
}
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
#
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
// pkgs/@akanjs/devkit/akanApp/devIdleSuspend.ts
|
|
1724
|
+
class DevIdleSuspend {
|
|
1725
|
+
#app;
|
|
1726
|
+
#logger;
|
|
1727
|
+
#links;
|
|
1728
|
+
#timer = null;
|
|
1729
|
+
#suspended = false;
|
|
1730
|
+
#waking = false;
|
|
1731
|
+
#stopped = false;
|
|
1732
|
+
#activity = 0;
|
|
1733
|
+
#wokeAtMono = null;
|
|
1734
|
+
#watcher = null;
|
|
1735
|
+
#suspendedChanges = null;
|
|
1736
|
+
constructor(app, { logger }, links) {
|
|
1737
|
+
this.#app = app;
|
|
1738
|
+
this.#logger = logger;
|
|
1739
|
+
this.#links = links;
|
|
1415
1740
|
}
|
|
1416
|
-
static
|
|
1741
|
+
static idleMs() {
|
|
1417
1742
|
return resolveIdleSuspendMs(process.env.AKAN_DEV_IDLE_SUSPEND_MS);
|
|
1418
1743
|
}
|
|
1419
|
-
|
|
1744
|
+
get away() {
|
|
1745
|
+
return !this.#stopped && (this.#suspended || this.#waking);
|
|
1746
|
+
}
|
|
1747
|
+
markActivity() {
|
|
1748
|
+
this.#activity++;
|
|
1420
1749
|
if (this.#suspended || this.#waking)
|
|
1421
1750
|
return;
|
|
1422
|
-
this
|
|
1751
|
+
this.arm();
|
|
1423
1752
|
}
|
|
1424
|
-
|
|
1425
|
-
const idleMs =
|
|
1426
|
-
this.#
|
|
1427
|
-
if (idleMs === null)
|
|
1753
|
+
arm() {
|
|
1754
|
+
const idleMs = DevIdleSuspend.idleMs();
|
|
1755
|
+
this.#cancel();
|
|
1756
|
+
if (idleMs === null || this.#stopped)
|
|
1428
1757
|
return;
|
|
1429
|
-
this.#
|
|
1430
|
-
this.#
|
|
1758
|
+
this.#timer = setTimeout(() => {
|
|
1759
|
+
this.#timer = null;
|
|
1431
1760
|
this.#suspendWhenIdle(idleMs);
|
|
1432
1761
|
}, idleMs);
|
|
1433
1762
|
}
|
|
1434
|
-
#
|
|
1435
|
-
if (!this.#
|
|
1436
|
-
return;
|
|
1437
|
-
clearTimeout(this.#idleSuspendTimer);
|
|
1438
|
-
this.#idleSuspendTimer = null;
|
|
1439
|
-
}
|
|
1440
|
-
async#suspendWhenIdle(idleMs) {
|
|
1441
|
-
const decision = decideIdleSuspend({
|
|
1442
|
-
enabled: true,
|
|
1443
|
-
suspended: this.#suspended,
|
|
1444
|
-
builderReady: this.#builder?.status === "ready",
|
|
1445
|
-
backendReady: this.#backendReady,
|
|
1446
|
-
buildFailed: hasAnyBuildFailure(this.#buildStatusByPhase),
|
|
1447
|
-
restartPending: this.#restartPending,
|
|
1448
|
-
msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
|
|
1449
|
-
});
|
|
1450
|
-
if (decision !== "suspend") {
|
|
1451
|
-
this.logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
|
|
1452
|
-
this.#armIdleSuspend();
|
|
1453
|
-
return;
|
|
1454
|
-
}
|
|
1455
|
-
if (!await this.#startIdleWatcher()) {
|
|
1456
|
-
this.#armIdleSuspend();
|
|
1763
|
+
#cancel() {
|
|
1764
|
+
if (!this.#timer)
|
|
1457
1765
|
return;
|
|
1458
|
-
|
|
1459
|
-
this.#
|
|
1460
|
-
this.#emitDevEvent("suspended", `idle ${Math.round(idleMs / 1000)}s`);
|
|
1461
|
-
this.#stopBuilder();
|
|
1462
|
-
this.#openBuilderGap("idle suspend");
|
|
1463
|
-
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`);
|
|
1464
|
-
}
|
|
1465
|
-
get #restartPending() {
|
|
1466
|
-
return !!(this.#pendingRecycle || this.#restartTimer || this.#backendRestart || this.#backendRecoveryTimer || this.#builderRecoveryTimer || this.#rssRecycleReason);
|
|
1467
|
-
}
|
|
1468
|
-
async#startIdleWatcher() {
|
|
1469
|
-
try {
|
|
1470
|
-
const roots = await new WatchRootResolver(this.app).resolve();
|
|
1471
|
-
const watcher = new HmrWatcher({
|
|
1472
|
-
roots,
|
|
1473
|
-
logger: this.logger,
|
|
1474
|
-
onBatch: (batch) => {
|
|
1475
|
-
this.#recordSuspendedChange(batch);
|
|
1476
|
-
this.#wakeFromIdle(`${batch.files.length} file(s) changed`);
|
|
1477
|
-
}
|
|
1478
|
-
});
|
|
1479
|
-
await watcher.start();
|
|
1480
|
-
this.#idleWatcher = watcher;
|
|
1481
|
-
return true;
|
|
1482
|
-
} catch (err) {
|
|
1483
|
-
this.logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
|
|
1484
|
-
this.#stopIdleWatcher();
|
|
1485
|
-
return false;
|
|
1486
|
-
}
|
|
1766
|
+
clearTimeout(this.#timer);
|
|
1767
|
+
this.#timer = null;
|
|
1487
1768
|
}
|
|
1488
|
-
#
|
|
1489
|
-
this.#
|
|
1490
|
-
this.#
|
|
1769
|
+
#stopWatcher() {
|
|
1770
|
+
this.#watcher?.stop();
|
|
1771
|
+
this.#watcher = null;
|
|
1491
1772
|
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
return;
|
|
1497
|
-
}
|
|
1498
|
-
this.#suspendedChanges = {
|
|
1499
|
-
files: [...new Set([...current.files, ...batch.files])],
|
|
1500
|
-
kinds: new Set([...current.kinds, ...batch.kinds])
|
|
1501
|
-
};
|
|
1773
|
+
stop() {
|
|
1774
|
+
this.#stopped = true;
|
|
1775
|
+
this.#cancel();
|
|
1776
|
+
this.#stopWatcher();
|
|
1502
1777
|
}
|
|
1503
|
-
async
|
|
1504
|
-
if (!this.#suspended || this.#waking)
|
|
1778
|
+
async wake(reason) {
|
|
1779
|
+
if (!this.#suspended || this.#waking || this.#stopped)
|
|
1505
1780
|
return;
|
|
1506
1781
|
this.#waking = true;
|
|
1507
|
-
this.#
|
|
1508
|
-
this.#stopIdleWatcher();
|
|
1509
|
-
const batch = this.#suspendedChanges;
|
|
1510
|
-
this.#suspendedChanges = null;
|
|
1782
|
+
this.#cancel();
|
|
1511
1783
|
const startedAtMono = performance.now();
|
|
1512
|
-
this
|
|
1784
|
+
this.#logger.info(`[idle-suspend] waking (${reason})`);
|
|
1785
|
+
const watcher = this.#watcher;
|
|
1786
|
+
this.#watcher = null;
|
|
1787
|
+
let batch = null;
|
|
1513
1788
|
try {
|
|
1514
|
-
await
|
|
1515
|
-
|
|
1789
|
+
const unreported = await watcher?.close();
|
|
1790
|
+
if (unreported)
|
|
1791
|
+
this.#recordSuspendedChange(unreported);
|
|
1792
|
+
batch = this.#suspendedChanges;
|
|
1793
|
+
this.#suspendedChanges = null;
|
|
1794
|
+
if (this.#stopped)
|
|
1795
|
+
return;
|
|
1796
|
+
await this.#links.wake(batch);
|
|
1797
|
+
this.#logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
|
|
1516
1798
|
} catch (err) {
|
|
1517
|
-
this
|
|
1518
|
-
this.#
|
|
1799
|
+
this.#logger.error(`[idle-suspend] wake failed; recovering the builder: ${err instanceof Error ? err.message : String(err)}`);
|
|
1800
|
+
this.#links.wakeFailed(batch?.files ?? []);
|
|
1519
1801
|
} finally {
|
|
1520
1802
|
this.#suspended = false;
|
|
1521
1803
|
this.#waking = false;
|
|
1522
|
-
this.#wokeAtMono = performance.now();
|
|
1523
|
-
this.#
|
|
1524
|
-
this
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
}
|
|
1528
|
-
async#applyIdleWake(batch) {
|
|
1529
|
-
const files = batch?.files ?? [];
|
|
1530
|
-
if (shouldRefreshConfigOnIdleWake(batch)) {
|
|
1531
|
-
this.logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
|
|
1532
|
-
this.#discardBuilderGap("config change replaces the backend anyway");
|
|
1533
|
-
await this.#applyRecycle({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
|
|
1534
|
-
return;
|
|
1535
|
-
}
|
|
1536
|
-
if (files.length > 0)
|
|
1537
|
-
await this.#backendGraph.refresh();
|
|
1538
|
-
await this.#startBuilder({ announceBootState: true });
|
|
1539
|
-
const missed = await this.#takeBuilderGapChanges();
|
|
1540
|
-
const backendFiles = [...new Set([...files.filter((file) => this.#backendGraph.has(file)), ...missed])];
|
|
1541
|
-
if (backendFiles.length === 0)
|
|
1542
|
-
return;
|
|
1543
|
-
this.logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
|
|
1544
|
-
this.#scheduleBackendRestart({ files: backendFiles, roles: [] });
|
|
1545
|
-
}
|
|
1546
|
-
#openBuilderGap(reason) {
|
|
1547
|
-
if (this.#builderGapStamp)
|
|
1548
|
-
return;
|
|
1549
|
-
if (!this.#backendGraph.ready) {
|
|
1550
|
-
this.logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
|
|
1551
|
-
return;
|
|
1552
|
-
}
|
|
1553
|
-
this.#builderGapStamp = this.#backendGraph.fingerprint().then((stamps) => {
|
|
1554
|
-
this.logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
|
|
1555
|
-
return stamps;
|
|
1556
|
-
}).catch((err) => {
|
|
1557
|
-
this.logger.warn(`[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`);
|
|
1558
|
-
return null;
|
|
1559
|
-
});
|
|
1560
|
-
}
|
|
1561
|
-
async#takeBuilderGapChanges() {
|
|
1562
|
-
const stamping = this.#builderGapStamp;
|
|
1563
|
-
this.#builderGapStamp = null;
|
|
1564
|
-
const before = stamping ? await stamping : null;
|
|
1565
|
-
if (!before)
|
|
1566
|
-
return [];
|
|
1567
|
-
const moved = filesChangedSince(before, await this.#backendGraph.fingerprint());
|
|
1568
|
-
if (moved.length === 0) {
|
|
1569
|
-
this.logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
|
|
1570
|
-
return moved;
|
|
1804
|
+
this.#wokeAtMono = performance.now();
|
|
1805
|
+
this.#links.flushHeld();
|
|
1806
|
+
this.arm();
|
|
1807
|
+
if (!this.#stopped)
|
|
1808
|
+
this.#links.awake();
|
|
1571
1809
|
}
|
|
1572
|
-
this.logger.info(`[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`);
|
|
1573
|
-
return moved;
|
|
1574
1810
|
}
|
|
1575
|
-
#
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1811
|
+
#decide() {
|
|
1812
|
+
return decideIdleSuspend({
|
|
1813
|
+
enabled: true,
|
|
1814
|
+
suspended: this.#suspended,
|
|
1815
|
+
...this.#links.readiness(),
|
|
1816
|
+
msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
|
|
1817
|
+
});
|
|
1580
1818
|
}
|
|
1581
|
-
async#
|
|
1582
|
-
const
|
|
1583
|
-
if (
|
|
1819
|
+
async#suspendWhenIdle(idleMs) {
|
|
1820
|
+
const decision = this.#decide();
|
|
1821
|
+
if (decision !== "suspend") {
|
|
1822
|
+
this.#logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
|
|
1823
|
+
this.arm();
|
|
1584
1824
|
return;
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1825
|
+
}
|
|
1826
|
+
const activity = this.#activity;
|
|
1827
|
+
const watcher = await this.#startWatcher();
|
|
1828
|
+
if (!watcher) {
|
|
1829
|
+
this.arm();
|
|
1590
1830
|
return;
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
}
|
|
1595
|
-
#discardPendingBuilderMessages(reason) {
|
|
1596
|
-
const held = this.#pendingBuilderMessages.splice(0);
|
|
1597
|
-
if (held.length === 0)
|
|
1831
|
+
}
|
|
1832
|
+
if (this.#stopped) {
|
|
1833
|
+
watcher.stop();
|
|
1598
1834
|
return;
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1835
|
+
}
|
|
1836
|
+
const recheck = this.#activity === activity ? this.#decide() : "busy";
|
|
1837
|
+
if (recheck !== "suspend") {
|
|
1838
|
+
this.#logger.verbose(`[idle-suspend] skipped (${recheck} while the idle watcher started); re-arming`);
|
|
1839
|
+
watcher.stop();
|
|
1840
|
+
this.arm();
|
|
1604
1841
|
return;
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1842
|
+
}
|
|
1843
|
+
this.#watcher = watcher;
|
|
1844
|
+
this.#suspended = true;
|
|
1845
|
+
this.#links.release(`idle ${Math.round(idleMs / 1000)}s`);
|
|
1846
|
+
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`);
|
|
1608
1847
|
}
|
|
1609
|
-
#
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1848
|
+
async#startWatcher() {
|
|
1849
|
+
let watcher = null;
|
|
1850
|
+
try {
|
|
1851
|
+
const roots = await new WatchRootResolver(this.#app).resolve();
|
|
1852
|
+
watcher = new HmrWatcher({
|
|
1853
|
+
roots,
|
|
1854
|
+
logger: this.#logger,
|
|
1855
|
+
onBatch: (batch) => {
|
|
1856
|
+
this.#recordSuspendedChange(batch);
|
|
1857
|
+
this.wake(`${batch.files.length} file(s) changed`);
|
|
1858
|
+
}
|
|
1859
|
+
});
|
|
1860
|
+
await watcher.start();
|
|
1861
|
+
return watcher;
|
|
1862
|
+
} catch (err) {
|
|
1863
|
+
this.#logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
|
|
1864
|
+
watcher?.stop();
|
|
1865
|
+
return null;
|
|
1866
|
+
}
|
|
1619
1867
|
}
|
|
1620
|
-
#
|
|
1621
|
-
|
|
1622
|
-
|
|
1868
|
+
#recordSuspendedChange(batch) {
|
|
1869
|
+
const current = this.#suspendedChanges;
|
|
1870
|
+
if (!current) {
|
|
1871
|
+
this.#suspendedChanges = { files: [...batch.files], kinds: new Set(batch.kinds) };
|
|
1623
1872
|
return;
|
|
1624
1873
|
}
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1874
|
+
this.#suspendedChanges = {
|
|
1875
|
+
files: [...new Set([...current.files, ...batch.files])],
|
|
1876
|
+
kinds: new Set([...current.kinds, ...batch.kinds])
|
|
1877
|
+
};
|
|
1629
1878
|
}
|
|
1630
|
-
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
// pkgs/@akanjs/devkit/akanApp/devRecycler.ts
|
|
1882
|
+
import path4 from "path";
|
|
1883
|
+
class DevRecycler {
|
|
1884
|
+
#app;
|
|
1885
|
+
#env;
|
|
1886
|
+
#logger;
|
|
1887
|
+
#isStopping;
|
|
1888
|
+
#graph;
|
|
1889
|
+
#statuses;
|
|
1890
|
+
#backend;
|
|
1891
|
+
#builder;
|
|
1892
|
+
#gap;
|
|
1893
|
+
#rss;
|
|
1894
|
+
#pending = null;
|
|
1895
|
+
#restartFailedAfterApply = null;
|
|
1896
|
+
constructor(app, parts) {
|
|
1897
|
+
this.#app = app;
|
|
1898
|
+
this.#env = parts.env;
|
|
1899
|
+
this.#logger = parts.logger;
|
|
1900
|
+
this.#isStopping = parts.isStopping;
|
|
1901
|
+
this.#graph = parts.graph;
|
|
1902
|
+
this.#statuses = parts.statuses;
|
|
1903
|
+
this.#backend = parts.backend;
|
|
1904
|
+
this.#builder = parts.builder;
|
|
1905
|
+
this.#gap = parts.gap;
|
|
1906
|
+
this.#rss = parts.rss;
|
|
1907
|
+
}
|
|
1908
|
+
get pending() {
|
|
1909
|
+
return !!this.#pending;
|
|
1910
|
+
}
|
|
1911
|
+
drop() {
|
|
1912
|
+
this.#pending = null;
|
|
1913
|
+
}
|
|
1914
|
+
async handleInvalidate(message) {
|
|
1631
1915
|
this.#logDevPlan(message);
|
|
1632
|
-
|
|
1633
|
-
this.#armRssRecycle(this.#rssRecycleReason);
|
|
1916
|
+
this.#rss.rearm();
|
|
1634
1917
|
const wantsDevHostRestart = shouldRestartDevHostByDevPlan(message);
|
|
1635
|
-
const pending = this.#
|
|
1918
|
+
const pending = this.#pending;
|
|
1636
1919
|
const resumes = !!pending && message.kinds.includes("code") && this.#touchesFailedRecycle(message.files);
|
|
1637
1920
|
if (wantsDevHostRestart || shouldRestartBuilderByDevPlan(message) || resumes) {
|
|
1638
1921
|
const refreshConfig = wantsDevHostRestart || (pending?.refreshConfig ?? false);
|
|
1639
1922
|
const merged = pending ? mergeInvalidateMessages(pending.message, message) : message;
|
|
1640
1923
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1641
|
-
if (
|
|
1642
|
-
this.#
|
|
1924
|
+
if (this.#statuses.failedAt(generation)) {
|
|
1925
|
+
this.#defer(merged, { refreshConfig, generation });
|
|
1643
1926
|
return;
|
|
1644
1927
|
}
|
|
1645
|
-
await this
|
|
1928
|
+
await this.apply(merged, refreshConfig);
|
|
1646
1929
|
return;
|
|
1647
1930
|
}
|
|
1648
1931
|
if (await this.#shouldRestartBackend(message)) {
|
|
1649
|
-
this.#
|
|
1932
|
+
this.#backend.scheduleRestart(backendRestartReasonFromMessage(message));
|
|
1650
1933
|
return;
|
|
1651
1934
|
}
|
|
1652
|
-
this.#
|
|
1935
|
+
this.#backend.send(message);
|
|
1653
1936
|
}
|
|
1654
|
-
async
|
|
1655
|
-
if (this.#
|
|
1937
|
+
async apply(message, refreshConfig) {
|
|
1938
|
+
if (this.#isStopping())
|
|
1656
1939
|
return;
|
|
1657
|
-
this.#
|
|
1940
|
+
this.#pending = null;
|
|
1658
1941
|
const progress = { applied: !refreshConfig };
|
|
1659
1942
|
try {
|
|
1660
1943
|
if (refreshConfig)
|
|
@@ -1663,146 +1946,121 @@ ${this.#backendStderrTail.join(`
|
|
|
1663
1946
|
await this.#restartDevChildren(message);
|
|
1664
1947
|
} catch (err) {
|
|
1665
1948
|
const kind = refreshConfig ? "Config" : "Runtime metadata";
|
|
1666
|
-
const generation = this.#
|
|
1949
|
+
const generation = this.#recordRestartFailure(message, err, kind, { applied: progress.applied });
|
|
1667
1950
|
if (progress.applied)
|
|
1668
1951
|
this.#restartFailedAfterApply = generation;
|
|
1669
1952
|
else
|
|
1670
|
-
this.#
|
|
1953
|
+
this.#pending = { message, refreshConfig, failed: true, failedGeneration: generation };
|
|
1671
1954
|
this.#resurrectDevChildren(message);
|
|
1672
1955
|
}
|
|
1673
1956
|
}
|
|
1674
|
-
async
|
|
1675
|
-
const pending = this.#
|
|
1957
|
+
async resumeFailed(status) {
|
|
1958
|
+
const pending = this.#pending;
|
|
1676
1959
|
if (!pending?.failed || !status.ok || status.phase !== "pages" || !this.#touchesFailedRecycle(status.files))
|
|
1677
1960
|
return;
|
|
1678
1961
|
if (status.generation <= (pending.failedGeneration ?? -1))
|
|
1679
1962
|
return;
|
|
1680
|
-
await this
|
|
1963
|
+
await this.apply(pending.message, pending.refreshConfig);
|
|
1964
|
+
}
|
|
1965
|
+
async applyIdleWake(batch) {
|
|
1966
|
+
const files = batch?.files ?? [];
|
|
1967
|
+
if (shouldRefreshConfigOnIdleWake(batch)) {
|
|
1968
|
+
this.#logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
|
|
1969
|
+
this.#gap.discard("config change replaces the backend anyway");
|
|
1970
|
+
await this.apply({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1973
|
+
if (files.length > 0)
|
|
1974
|
+
await this.#graph.refresh();
|
|
1975
|
+
await this.#builder.start({ announceBootState: true });
|
|
1976
|
+
const missed = await this.#gap.take();
|
|
1977
|
+
const backendFiles = [...new Set([...files.filter((file) => this.#graph.has(file)), ...missed])];
|
|
1978
|
+
if (backendFiles.length === 0)
|
|
1979
|
+
return;
|
|
1980
|
+
this.#logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
|
|
1981
|
+
this.#backend.scheduleRestart({ files: backendFiles, roles: [] });
|
|
1982
|
+
}
|
|
1983
|
+
builderRecovered(reason) {
|
|
1984
|
+
this.#gap.restartBackendForChanges();
|
|
1985
|
+
const failedAfterApply = this.#restartFailedAfterApply;
|
|
1986
|
+
this.#restartFailedAfterApply = null;
|
|
1987
|
+
const status = {
|
|
1988
|
+
generation: failedAfterApply !== null ? this.#statuses.nextBackendGeneration(failedAfterApply + 1) : reason.generation ?? this.#statuses.nextBackendGeneration(),
|
|
1989
|
+
phase: "scan",
|
|
1990
|
+
ok: true,
|
|
1991
|
+
files: reason.files,
|
|
1992
|
+
message: "Builder recovered"
|
|
1993
|
+
};
|
|
1994
|
+
this.#statuses.record(status);
|
|
1995
|
+
this.#backend.sendOrQueueStatus(status);
|
|
1996
|
+
if (!this.#backend.running && !this.#backend.recovering) {
|
|
1997
|
+
this.#backend.start({ generation: reason.generation, files: reason.files });
|
|
1998
|
+
}
|
|
1681
1999
|
}
|
|
1682
2000
|
#touchesFailedRecycle(files) {
|
|
1683
|
-
const pending = this.#
|
|
2001
|
+
const pending = this.#pending;
|
|
1684
2002
|
if (!pending?.failed)
|
|
1685
2003
|
return true;
|
|
1686
2004
|
const changed = new Set(pending.message.files);
|
|
1687
2005
|
return files.some((file) => changed.has(file));
|
|
1688
2006
|
}
|
|
1689
|
-
#
|
|
1690
|
-
this.#
|
|
2007
|
+
#defer(message, { refreshConfig, generation }) {
|
|
2008
|
+
this.#pending = { message, refreshConfig };
|
|
1691
2009
|
const kind = refreshConfig ? "Config" : "Runtime metadata";
|
|
1692
|
-
this
|
|
2010
|
+
this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart deferred generation=${generation ?? "(unknown)"}; keeping the running dev server until the build error is fixed`);
|
|
1693
2011
|
const status = {
|
|
1694
|
-
generation: generation ?? this.#
|
|
2012
|
+
generation: generation ?? this.#statuses.nextBackendGeneration(),
|
|
1695
2013
|
phase: "scan",
|
|
1696
2014
|
ok: false,
|
|
1697
2015
|
files: message.files,
|
|
1698
2016
|
message: `${kind} change is on hold while the build is failing; it will apply automatically once the error is fixed.`
|
|
1699
2017
|
};
|
|
1700
|
-
this.#
|
|
1701
|
-
this.#
|
|
2018
|
+
this.#statuses.record(status);
|
|
2019
|
+
this.#backend.sendOrQueueStatus(status);
|
|
1702
2020
|
}
|
|
1703
2021
|
#resurrectDevChildren(message) {
|
|
1704
2022
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1705
|
-
if (!this.#backend)
|
|
1706
|
-
this.#
|
|
1707
|
-
this.#
|
|
1708
|
-
}
|
|
1709
|
-
#scheduleBuilderRecovery(reason) {
|
|
1710
|
-
if (this.#builderRecoveryTimer || this.#builder)
|
|
1711
|
-
return;
|
|
1712
|
-
const attempt = this.#builderRecoveryAttempts;
|
|
1713
|
-
const delay = Math.min(BUILDER_RECOVERY_BASE_DELAY_MS * 2 ** attempt, BUILDER_RECOVERY_MAX_DELAY_MS);
|
|
1714
|
-
this.#builderRecoveryAttempts = attempt + 1;
|
|
1715
|
-
this.logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#builderRecoveryAttempts})`);
|
|
1716
|
-
this.#builderRecoveryTimer = setTimeout(() => {
|
|
1717
|
-
this.#builderRecoveryTimer = null;
|
|
1718
|
-
if (this.#builder)
|
|
1719
|
-
return;
|
|
1720
|
-
this.#recoverBuilder(reason);
|
|
1721
|
-
}, delay);
|
|
1722
|
-
}
|
|
1723
|
-
async#recoverBuilder(reason) {
|
|
1724
|
-
try {
|
|
1725
|
-
await this.#startBuilder();
|
|
1726
|
-
} catch (err) {
|
|
1727
|
-
this.logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1728
|
-
this.#scheduleBuilderRecovery(reason);
|
|
1729
|
-
return;
|
|
1730
|
-
}
|
|
1731
|
-
this.#builderRecoveryAttempts = 0;
|
|
1732
|
-
this.logger.info("[builder-recovery] builder recovered");
|
|
1733
|
-
this.#restartBackendForGapChanges();
|
|
1734
|
-
const failedAfterApply = this.#restartFailedAfterApply;
|
|
1735
|
-
this.#restartFailedAfterApply = null;
|
|
1736
|
-
const status = {
|
|
1737
|
-
generation: failedAfterApply !== null ? this.#nextBackendBuildStatusGeneration(failedAfterApply + 1) : reason.generation ?? this.#nextBackendBuildStatusGeneration(),
|
|
1738
|
-
phase: "scan",
|
|
1739
|
-
ok: true,
|
|
1740
|
-
files: reason.files,
|
|
1741
|
-
message: "Builder recovered"
|
|
1742
|
-
};
|
|
1743
|
-
this.#recordBuildStatus(status);
|
|
1744
|
-
this.#sendOrQueueBuildStatus(status);
|
|
1745
|
-
if (!this.#backend && !this.#backendRecoveryTimer) {
|
|
1746
|
-
this.#startBackend({ generation: reason.generation, files: reason.files });
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
#reviveBackendAfterGreenBuild(status) {
|
|
1750
|
-
if (!status.ok || !this.#backendGaveUp || this.#backend || this.#backendRecoveryTimer)
|
|
1751
|
-
return;
|
|
1752
|
-
this.logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
|
|
1753
|
-
this.#backendRecoveryAttempts = 0;
|
|
1754
|
-
this.#startBackend({ generation: status.generation, files: status.files });
|
|
2023
|
+
if (!this.#backend.running)
|
|
2024
|
+
this.#backend.start({ generation, files: message.files });
|
|
2025
|
+
this.#builder.scheduleRecovery({ generation, files: message.files });
|
|
1755
2026
|
}
|
|
1756
2027
|
async#restartDevChildren(message) {
|
|
1757
2028
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1758
|
-
this
|
|
2029
|
+
this.#logger.warn(`[dev-host] recycling builder/backend for runtime metadata generation=${generation ?? "(unknown)"} files=${message.files.length}`);
|
|
1759
2030
|
await this.#recycleDevChildren(message);
|
|
1760
2031
|
}
|
|
1761
2032
|
async#restartDevHost(message, progress) {
|
|
1762
2033
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1763
|
-
this
|
|
2034
|
+
this.#logger.warn(`[dev-host] config change detected; restarting dev host generation=${generation ?? "(unknown)"} files=${message.files.length}`);
|
|
1764
2035
|
await this.#recycleDevChildren(message, { refreshConfig: true, progress });
|
|
1765
2036
|
}
|
|
1766
2037
|
async#recycleDevChildren(message, { refreshConfig = false, progress } = {}) {
|
|
1767
2038
|
const generation = message.devPlan?.generation ?? message.generation;
|
|
1768
|
-
this.#
|
|
1769
|
-
this.#
|
|
1770
|
-
this.#
|
|
1771
|
-
|
|
1772
|
-
this.#
|
|
1773
|
-
this.#
|
|
1774
|
-
this.#
|
|
1775
|
-
await this.#
|
|
1776
|
-
this.#
|
|
1777
|
-
this.#
|
|
2039
|
+
this.#backend.cancelTimers();
|
|
2040
|
+
this.#builder.cancelRecovery();
|
|
2041
|
+
this.#builder.resetRecovery();
|
|
2042
|
+
this.#backend.dropPendingRestart();
|
|
2043
|
+
await this.#backend.restarting;
|
|
2044
|
+
this.#statuses.reset();
|
|
2045
|
+
this.#backend.dropQueuedStatuses();
|
|
2046
|
+
await this.#backend.stop();
|
|
2047
|
+
this.#builder.stop();
|
|
2048
|
+
this.#builder.clearPatcherOff();
|
|
1778
2049
|
if (refreshConfig) {
|
|
1779
|
-
await this
|
|
1780
|
-
const { env } = await this
|
|
1781
|
-
Object.assign(this
|
|
2050
|
+
await this.#app.getConfig({ refresh: true });
|
|
2051
|
+
const { env } = await this.#app.prepareCommand("start");
|
|
2052
|
+
Object.assign(this.#env, env);
|
|
1782
2053
|
if (progress)
|
|
1783
2054
|
progress.applied = true;
|
|
1784
2055
|
}
|
|
1785
|
-
await this.#
|
|
1786
|
-
await this.#
|
|
1787
|
-
this.#
|
|
1788
|
-
}
|
|
1789
|
-
#recordLastGood(message, { supersede = false } = {}) {
|
|
1790
|
-
if (message.type === "pages-updated") {
|
|
1791
|
-
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.pages, message))
|
|
1792
|
-
return;
|
|
1793
|
-
this.#lastGoodFrontend.pages = message;
|
|
1794
|
-
this.logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
|
|
1795
|
-
return;
|
|
1796
|
-
}
|
|
1797
|
-
if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.css, message))
|
|
1798
|
-
return;
|
|
1799
|
-
this.#lastGoodFrontend.css = message;
|
|
1800
|
-
this.logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
|
|
2056
|
+
await this.#graph.refresh();
|
|
2057
|
+
await this.#builder.start();
|
|
2058
|
+
this.#backend.start({ generation, files: message.files });
|
|
1801
2059
|
}
|
|
1802
|
-
#
|
|
1803
|
-
const generation = message.devPlan?.generation ?? message.generation ?? this.#
|
|
2060
|
+
#recordRestartFailure(message, err, kind, { applied }) {
|
|
2061
|
+
const generation = message.devPlan?.generation ?? message.generation ?? this.#statuses.nextBackendGeneration();
|
|
1804
2062
|
const detail = err instanceof Error ? err.message : String(err);
|
|
1805
|
-
this
|
|
2063
|
+
this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
|
|
1806
2064
|
const names = message.files.slice(0, 3).map((file) => path4.basename(file));
|
|
1807
2065
|
const saved = names.length > 0 ? names.join(", ") : "the changed file";
|
|
1808
2066
|
const status = {
|
|
@@ -1812,50 +2070,15 @@ ${this.#backendStderrTail.join(`
|
|
|
1812
2070
|
files: message.files,
|
|
1813
2071
|
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.`
|
|
1814
2072
|
};
|
|
1815
|
-
this.#
|
|
1816
|
-
this.#
|
|
2073
|
+
this.#statuses.record(status);
|
|
2074
|
+
this.#backend.sendOrQueueStatus(status);
|
|
1817
2075
|
return generation;
|
|
1818
2076
|
}
|
|
1819
|
-
#recordBuildStatus(status) {
|
|
1820
|
-
const recovered = shouldMarkBuildPhaseRecovered(this.#buildStatusByPhase, status);
|
|
1821
|
-
if (shouldKeepBuildFailure(this.#buildStatusByPhase, status))
|
|
1822
|
-
return;
|
|
1823
|
-
this.#buildStatusByPhase.set(status.phase, status);
|
|
1824
|
-
const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
|
|
1825
|
-
if (status.ok)
|
|
1826
|
-
this.logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
|
|
1827
|
-
else
|
|
1828
|
-
this.logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
|
|
1829
|
-
}
|
|
1830
|
-
#sendOrQueueBuildStatus(status) {
|
|
1831
|
-
if (!this.#backend || shouldQueueBuildStatusReplay(this.#backendReady, this.#pendingBuildStatusReplay.length)) {
|
|
1832
|
-
this.#pendingBuildStatusReplay.push(status);
|
|
1833
|
-
this.logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
|
|
1834
|
-
return;
|
|
1835
|
-
}
|
|
1836
|
-
this.#sendToBackend({ type: "build-status", data: status });
|
|
1837
|
-
}
|
|
1838
|
-
#forgetRouteBuildStatus() {
|
|
1839
|
-
this.#buildStatusByPhase.delete("route");
|
|
1840
|
-
this.#pendingBuildStatusReplay = this.#pendingBuildStatusReplay.filter((status) => status.phase !== "route");
|
|
1841
|
-
}
|
|
1842
|
-
#replayBuilderState() {
|
|
1843
|
-
if (!this.#backendReady)
|
|
1844
|
-
return;
|
|
1845
|
-
if (this.#lastGoodFrontend.css)
|
|
1846
|
-
this.#sendToBackend(this.#lastGoodFrontend.css);
|
|
1847
|
-
if (this.#lastGoodFrontend.pages)
|
|
1848
|
-
this.#sendToBackend(this.#lastGoodFrontend.pages);
|
|
1849
|
-
const queuedStatuses = this.#pendingBuildStatusReplay.splice(0);
|
|
1850
|
-
for (const status of buildStatusReplaySequence(queuedStatuses, this.#buildStatusByPhase)) {
|
|
1851
|
-
this.#sendToBackend({ type: "build-status", data: status });
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
2077
|
#logDevPlan(message) {
|
|
1855
2078
|
if (!message.devPlan)
|
|
1856
2079
|
return;
|
|
1857
2080
|
const { generation, roles, actions, reasonByFile } = message.devPlan;
|
|
1858
|
-
this
|
|
2081
|
+
this.#logger.verbose(`[dev-plan] generation=${generation} roles=${roles.join(",") || "(none)"} actions=${actions.join(",") || "(none)"} reasons=${Object.keys(reasonByFile).length}`);
|
|
1859
2082
|
}
|
|
1860
2083
|
async#shouldRestartBackend(message) {
|
|
1861
2084
|
if (message.kinds.length === 1 && message.kinds[0] === "css")
|
|
@@ -1863,127 +2086,239 @@ ${this.#backendStderrTail.join(`
|
|
|
1863
2086
|
if (message.devPlan) {
|
|
1864
2087
|
const shouldRestart = shouldRestartBackendByDevPlan(message) ?? false;
|
|
1865
2088
|
if (shouldRestart && message.kinds.includes("code"))
|
|
1866
|
-
await this.#
|
|
2089
|
+
await this.#graph.refresh();
|
|
1867
2090
|
return shouldRestart;
|
|
1868
2091
|
}
|
|
1869
2092
|
if (message.kinds.includes("code"))
|
|
1870
|
-
await this.#
|
|
1871
|
-
if (message.files.some((file) => this.#
|
|
2093
|
+
await this.#graph.refresh();
|
|
2094
|
+
if (message.files.some((file) => this.#graph.has(file)))
|
|
1872
2095
|
return true;
|
|
1873
|
-
if (!this.#
|
|
1874
|
-
const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this
|
|
2096
|
+
if (!this.#graph.lastRefreshSucceeded) {
|
|
2097
|
+
const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this.#app.workspace.workspaceRoot));
|
|
1875
2098
|
if (fallbackFiles.length > 0) {
|
|
1876
|
-
this
|
|
2099
|
+
this.#logger.warn(`[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`);
|
|
1877
2100
|
return true;
|
|
1878
2101
|
}
|
|
1879
2102
|
}
|
|
1880
2103
|
return false;
|
|
1881
2104
|
}
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
// pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
|
|
2108
|
+
class AkanAppHost {
|
|
2109
|
+
app;
|
|
2110
|
+
logger = new Logger2("AkanAppHost");
|
|
2111
|
+
stdio;
|
|
2112
|
+
env;
|
|
2113
|
+
#onDevEvent;
|
|
2114
|
+
#lastDevState = null;
|
|
2115
|
+
#bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
|
|
2116
|
+
#stopping = false;
|
|
2117
|
+
#builderMessageQueue = Promise.resolve();
|
|
2118
|
+
#backendGraph;
|
|
2119
|
+
#statuses;
|
|
2120
|
+
#backend;
|
|
2121
|
+
#gap;
|
|
2122
|
+
#requests;
|
|
2123
|
+
#rss;
|
|
2124
|
+
#builder;
|
|
2125
|
+
#idle;
|
|
2126
|
+
#recycler;
|
|
2127
|
+
constructor(app, {
|
|
2128
|
+
env,
|
|
2129
|
+
stdio = "inherit",
|
|
2130
|
+
onDevEvent
|
|
2131
|
+
}) {
|
|
2132
|
+
this.app = app;
|
|
2133
|
+
this.env = env;
|
|
2134
|
+
this.stdio = stdio;
|
|
2135
|
+
this.#onDevEvent = onDevEvent ?? null;
|
|
2136
|
+
this.#backendGraph = new BackendImportGraph(app, this.logger);
|
|
2137
|
+
const { logger } = this;
|
|
2138
|
+
const graph = this.#backendGraph;
|
|
2139
|
+
const isStopping = () => this.#stopping;
|
|
2140
|
+
const statuses = new DevBuildStatusBoard(logger);
|
|
2141
|
+
this.#statuses = statuses;
|
|
2142
|
+
this.#backend = new DevBackend(app, { env, stdio, logger, statuses, graph }, {
|
|
2143
|
+
isStopping,
|
|
2144
|
+
emit: (state, detail) => this.#emitDevEvent(state, detail),
|
|
2145
|
+
beforeSpawn: () => {
|
|
2146
|
+
this.#requests.startGeneration();
|
|
2147
|
+
this.#requests.discard("the backend restarted while the builder was away");
|
|
2148
|
+
},
|
|
2149
|
+
toBuilder: (message) => this.#requests.send(message)
|
|
2150
|
+
});
|
|
2151
|
+
this.#gap = new BuilderGap({ graph, backend: this.#backend, logger });
|
|
2152
|
+
this.#requests = new BuilderRequestRelay({ logger, env }, {
|
|
2153
|
+
builder: () => this.#builder.current,
|
|
2154
|
+
toBackend: (message) => this.#backend.send(message),
|
|
2155
|
+
markActivity: () => this.#idle.markActivity(),
|
|
2156
|
+
away: () => this.#idle.away,
|
|
2157
|
+
wake: (reason) => void this.#idle.wake(reason)
|
|
2158
|
+
});
|
|
2159
|
+
this.#rss = new BuilderRssRecycler({ logger, statuses }, {
|
|
2160
|
+
builder: () => this.#builder.current,
|
|
2161
|
+
away: () => this.#idle.away,
|
|
2162
|
+
restartQueued: () => this.#recycler.pending || this.#backend.restartScheduled,
|
|
2163
|
+
onRecycle: () => this.#gap.open("builder recycle")
|
|
2164
|
+
});
|
|
2165
|
+
this.#builder = new DevBuilder(app, { env, stdio, logger }, {
|
|
2166
|
+
isStopping,
|
|
2167
|
+
onMessage: (message) => this.#enqueueBuilderMessage(message),
|
|
2168
|
+
onAway: () => this.#gap.open("builder replacement"),
|
|
2169
|
+
onReady: () => this.#requests.flush(),
|
|
2170
|
+
onRestartReady: () => {
|
|
2171
|
+
this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
|
|
2172
|
+
this.#backend.replay();
|
|
2173
|
+
this.#requests.flush();
|
|
2174
|
+
this.#gap.restartBackendForChanges();
|
|
2175
|
+
this.#rss.checkRecycledFloor();
|
|
2176
|
+
},
|
|
2177
|
+
onStartFailed: () => this.#requests.fail("builder failed to start"),
|
|
2178
|
+
onStop: () => this.#rss.cancel(),
|
|
2179
|
+
onRecovered: (reason) => this.#recycler.builderRecovered(reason)
|
|
2180
|
+
});
|
|
2181
|
+
this.#idle = new DevIdleSuspend(app, { logger }, {
|
|
2182
|
+
readiness: () => ({
|
|
2183
|
+
builderReady: this.#builder.current?.status === "ready",
|
|
2184
|
+
backendReady: this.#backend.ready,
|
|
2185
|
+
buildFailed: this.#statuses.failing,
|
|
2186
|
+
restartPending: this.#restartPending
|
|
2187
|
+
}),
|
|
2188
|
+
release: (detail) => {
|
|
2189
|
+
this.#emitDevEvent("suspended", detail);
|
|
2190
|
+
this.#builder.stop();
|
|
2191
|
+
this.#gap.open("idle suspend");
|
|
2192
|
+
},
|
|
2193
|
+
wake: (batch) => this.#recycler.applyIdleWake(batch),
|
|
2194
|
+
wakeFailed: (files) => this.#builder.scheduleRecovery({ files }),
|
|
2195
|
+
flushHeld: () => this.#requests.flush(),
|
|
2196
|
+
awake: () => this.#emitDevEvent(devHostStateOf(this.#backend.lifecycleState, this.#backend.gaveUp))
|
|
2197
|
+
});
|
|
2198
|
+
this.#recycler = new DevRecycler(app, {
|
|
2199
|
+
env,
|
|
2200
|
+
logger,
|
|
2201
|
+
isStopping,
|
|
2202
|
+
graph,
|
|
2203
|
+
statuses,
|
|
2204
|
+
backend: this.#backend,
|
|
2205
|
+
builder: this.#builder,
|
|
2206
|
+
gap: this.#gap,
|
|
2207
|
+
rss: this.#rss
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
#emitDevEvent(state, detail) {
|
|
2211
|
+
if (!this.#onDevEvent || state === this.#lastDevState)
|
|
2212
|
+
return;
|
|
2213
|
+
this.#lastDevState = state;
|
|
2214
|
+
this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
|
|
2215
|
+
if (state === "ready")
|
|
2216
|
+
this.#bootLatch.ready();
|
|
2217
|
+
}
|
|
2218
|
+
async start() {
|
|
2219
|
+
if (this.#backend.running)
|
|
2220
|
+
await this.#backend.stop();
|
|
2221
|
+
if (this.#builder.current)
|
|
2222
|
+
this.#builder.stop();
|
|
2223
|
+
const [redisHost] = await Promise.all([
|
|
2224
|
+
this.#prepareDatabase("redis"),
|
|
2225
|
+
this.#backendGraph.refresh(),
|
|
2226
|
+
this.#builder.start()
|
|
2227
|
+
]);
|
|
2228
|
+
Object.assign(this.env, { REDIS_HOST: redisHost });
|
|
2229
|
+
this.#backend.start();
|
|
2230
|
+
this.#idle.arm();
|
|
2231
|
+
return this;
|
|
2232
|
+
}
|
|
2233
|
+
async stop() {
|
|
2234
|
+
this.#stopping = true;
|
|
2235
|
+
this.#recycler.drop();
|
|
2236
|
+
this.#idle.stop();
|
|
2237
|
+
this.#backend.cancelTimers();
|
|
2238
|
+
this.#builder.cancelRecovery();
|
|
2239
|
+
this.#builder.abandonStart(new Error("dev server stopped before the builder was ready"));
|
|
2240
|
+
this.#backend.dropPendingRestart();
|
|
2241
|
+
this.#requests.fail("dev server is shutting down");
|
|
2242
|
+
await this.#backend.restarting;
|
|
2243
|
+
await this.#backend.stop();
|
|
2244
|
+
this.#builder.stop();
|
|
2245
|
+
return this;
|
|
2246
|
+
}
|
|
2247
|
+
kill() {
|
|
2248
|
+
this.stop();
|
|
2249
|
+
}
|
|
2250
|
+
async#prepareDatabase(type) {
|
|
2251
|
+
const environment = WorkspaceExecutor.getBaseDevEnv().env;
|
|
2252
|
+
const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
|
|
2253
|
+
if (policy === "none")
|
|
2254
|
+
return "localhost";
|
|
2255
|
+
if (policy === "required")
|
|
2256
|
+
return await createTunnel(type, { app: this.app, environment });
|
|
2257
|
+
try {
|
|
2258
|
+
return await createTunnel(type, { app: this.app, environment });
|
|
2259
|
+
} catch (error) {
|
|
2260
|
+
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`);
|
|
2261
|
+
return UNAVAILABLE_REDIS_HOST;
|
|
1907
2262
|
}
|
|
1908
|
-
this.#failPendingBuilderMessages("builder failed to start");
|
|
1909
|
-
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
1910
2263
|
}
|
|
1911
|
-
#
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
throw new Error("Builder Not Found");
|
|
1915
|
-
let settled = false;
|
|
1916
|
-
const settle = (fn) => {
|
|
1917
|
-
if (settled)
|
|
1918
|
-
return;
|
|
1919
|
-
settled = true;
|
|
1920
|
-
clearTimeout(timeout);
|
|
1921
|
-
fn();
|
|
1922
|
-
};
|
|
1923
|
-
const timeout = setTimeout(() => {
|
|
1924
|
-
settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
|
|
1925
|
-
}, BUILDER_READY_TIMEOUT_MS);
|
|
1926
|
-
this.#builder.start({
|
|
1927
|
-
announceBootState,
|
|
1928
|
-
onExit: () => {
|
|
1929
|
-
settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
|
|
1930
|
-
},
|
|
1931
|
-
onAway: () => {
|
|
1932
|
-
this.#openBuilderGap("builder replacement");
|
|
1933
|
-
},
|
|
1934
|
-
onReady: () => {
|
|
1935
|
-
settle(resolve);
|
|
1936
|
-
this.#flushPendingBuilderMessages();
|
|
1937
|
-
},
|
|
1938
|
-
onRestartReady: () => {
|
|
1939
|
-
this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
|
|
1940
|
-
this.#replayBuilderState();
|
|
1941
|
-
this.#flushPendingBuilderMessages();
|
|
1942
|
-
this.#restartBackendForGapChanges();
|
|
1943
|
-
this.#checkRecycledBuilderFloor();
|
|
1944
|
-
}
|
|
1945
|
-
});
|
|
2264
|
+
#enqueueBuilderMessage(message) {
|
|
2265
|
+
this.#builderMessageQueue = this.#builderMessageQueue.then(() => this.#handleBuilderMessage(message)).catch((err) => {
|
|
2266
|
+
this.logger.warn(`failed to handle builder message: ${err instanceof Error ? err.message : String(err)}`);
|
|
1946
2267
|
});
|
|
1947
2268
|
}
|
|
1948
|
-
#
|
|
1949
|
-
this.#
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
2269
|
+
async#handleBuilderMessage(message) {
|
|
2270
|
+
if (this.#stopping)
|
|
2271
|
+
return;
|
|
2272
|
+
this.#idle.markActivity();
|
|
2273
|
+
this.#builder.trackGeneration(message);
|
|
2274
|
+
if (message.type === "build-status") {
|
|
2275
|
+
this.#statuses.record(message.data);
|
|
2276
|
+
this.#backend.sendOrQueueStatus(message.data);
|
|
2277
|
+
this.#backend.reviveAfterGreenBuild(message.data);
|
|
2278
|
+
await this.#recycler.resumeFailed(message.data);
|
|
1953
2279
|
return;
|
|
1954
2280
|
}
|
|
1955
|
-
if (message.type === "
|
|
1956
|
-
|
|
1957
|
-
|
|
2281
|
+
if (message.type === "builder-metrics") {
|
|
2282
|
+
this.#rss.handleMetrics(message.data);
|
|
2283
|
+
return;
|
|
1958
2284
|
}
|
|
1959
|
-
if (message.type === "
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
return;
|
|
1963
|
-
this.#builderRequests.withdraw(outgoing.id);
|
|
1964
|
-
} else if (this.#builder?.send(message))
|
|
2285
|
+
if (message.type === "boot-armed") {
|
|
2286
|
+
this.logger.verbose("[builder] boot builds settled");
|
|
2287
|
+
this.#bootLatch.armed();
|
|
1965
2288
|
return;
|
|
1966
|
-
|
|
1967
|
-
if (
|
|
1968
|
-
|
|
1969
|
-
|
|
2289
|
+
}
|
|
2290
|
+
if (message.type === "pages-updated" || message.type === "css-updated") {
|
|
2291
|
+
const recycled = message.data.reason === "builder-recycle";
|
|
2292
|
+
if (recycled && !this.#statuses.shouldRelayRecycled(message))
|
|
2293
|
+
return;
|
|
2294
|
+
this.#statuses.recordLastGood(message, { supersede: recycled });
|
|
2295
|
+
}
|
|
2296
|
+
if (message.type === "invalidate") {
|
|
2297
|
+
await this.#recycler.handleInvalidate(message);
|
|
1970
2298
|
return;
|
|
1971
2299
|
}
|
|
1972
|
-
if (
|
|
2300
|
+
if (message.type === "build-route-res" || message.type === "build-csr-res" || message.type === "build-graph-res") {
|
|
2301
|
+
const answer = this.#requests.settle(message);
|
|
2302
|
+
if (!answer) {
|
|
2303
|
+
this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
|
|
2304
|
+
return;
|
|
2305
|
+
}
|
|
2306
|
+
this.#backend.send(answer);
|
|
1973
2307
|
return;
|
|
1974
|
-
|
|
2308
|
+
}
|
|
2309
|
+
this.#backend.send(message);
|
|
1975
2310
|
}
|
|
1976
|
-
#
|
|
1977
|
-
this.#
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
2311
|
+
get #restartPending() {
|
|
2312
|
+
return this.#recycler.pending || this.#backend.restartPending || this.#builder.recovering || this.#rss.armed;
|
|
2313
|
+
}
|
|
2314
|
+
static async readProcessRssBytes(pid) {
|
|
2315
|
+
return await ProcessRss.bytesOf(pid);
|
|
2316
|
+
}
|
|
2317
|
+
static idleSuspendMs() {
|
|
2318
|
+
return DevIdleSuspend.idleMs();
|
|
1984
2319
|
}
|
|
1985
2320
|
}
|
|
1986
|
-
// pkgs/@akanjs/devkit/applicationTestPreload.ts
|
|
2321
|
+
// pkgs/@akanjs/devkit/app/applicationTestPreload.ts
|
|
1987
2322
|
import path5 from "path";
|
|
1988
2323
|
var SIGNAL_TEST_PRELOAD_PATH = "test/signalTest.preload.ts";
|
|
1989
2324
|
async function resolveSignalTestPreloadPath(target) {
|
|
@@ -1993,7 +2328,7 @@ async function resolveSignalTestPreloadPath(target) {
|
|
|
1993
2328
|
candidates.push(path5.join(path5.dirname(Bun.resolveSync("akanjs/package.json", basePath)), SIGNAL_TEST_PRELOAD_PATH));
|
|
1994
2329
|
} catch {}
|
|
1995
2330
|
}
|
|
1996
|
-
candidates.push(path5.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(path5.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.resolve(import.meta.dir, "
|
|
2331
|
+
candidates.push(path5.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(path5.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.resolve(import.meta.dir, "../../../akanjs", SIGNAL_TEST_PRELOAD_PATH));
|
|
1997
2332
|
const uniqueCandidates = [...new Set(candidates)];
|
|
1998
2333
|
for (const candidate of uniqueCandidates)
|
|
1999
2334
|
if (await Bun.file(candidate).exists())
|
|
@@ -2026,19 +2361,19 @@ var hasTestFile = (dir, seen = new Set) => {
|
|
|
2026
2361
|
});
|
|
2027
2362
|
};
|
|
2028
2363
|
var testTargetOf = (exec) => {
|
|
2029
|
-
const root = exec instanceof SysExecutor || exec instanceof
|
|
2364
|
+
const root = exec instanceof SysExecutor || exec instanceof PkgExecutor2 ? exec.workspace.workspaceRoot : process.cwd();
|
|
2030
2365
|
return { root, target: path6.relative(root, exec.cwdPath).split(path6.sep).join("/") };
|
|
2031
2366
|
};
|
|
2032
2367
|
var reportsNoTestFile = (exec) => {
|
|
2033
2368
|
if (hasTestFile(exec.cwdPath))
|
|
2034
2369
|
return false;
|
|
2035
|
-
const hint = exec instanceof
|
|
2370
|
+
const hint = exec instanceof AppExecutor2 || exec instanceof LibExecutor2 ? " A signal test goes beside its module, as lib/<model>/<model>.signal.test.ts." : "";
|
|
2036
2371
|
Logger3.rawLog(`No *.test.ts or *.spec.ts file in ${testTargetOf(exec).target}, so no test ran.${hint}`);
|
|
2037
2372
|
return true;
|
|
2038
2373
|
};
|
|
2039
2374
|
|
|
2040
2375
|
// pkgs/@akanjs/cli/application/application.runner.ts
|
|
2041
|
-
var loadBuildRunner = async () => (await import("./applicationBuildRunner-
|
|
2376
|
+
var loadBuildRunner = async () => (await import("./applicationBuildRunner-frtcrqfd.js")).ApplicationBuildRunner;
|
|
2042
2377
|
var loadPrompts = async () => await import("@inquirer/prompts");
|
|
2043
2378
|
|
|
2044
2379
|
class ApplicationRunner extends runner("application") {
|
|
@@ -2049,7 +2384,7 @@ class ApplicationRunner extends runner("application") {
|
|
|
2049
2384
|
dict: { appName },
|
|
2050
2385
|
options: { libs }
|
|
2051
2386
|
});
|
|
2052
|
-
return
|
|
2387
|
+
return AppExecutor2.from(workspace, appName);
|
|
2053
2388
|
}
|
|
2054
2389
|
async planSlice(app) {
|
|
2055
2390
|
return await new SlicePlanner(app).plan();
|
|
@@ -2239,7 +2574,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
|
|
|
2239
2574
|
await new (await loadBuildRunner())(app).typecheck(options);
|
|
2240
2575
|
}
|
|
2241
2576
|
async typecheckLibrary(lib, options = {}) {
|
|
2242
|
-
const { ProjectTypecheck } = await import("./projectTypecheck-
|
|
2577
|
+
const { ProjectTypecheck } = await import("./projectTypecheck-mk8wefvd.js");
|
|
2243
2578
|
const root = lib.workspace.workspaceRoot;
|
|
2244
2579
|
await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
|
|
2245
2580
|
"../../server.ts",
|
|
@@ -2263,7 +2598,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
|
|
|
2263
2598
|
});
|
|
2264
2599
|
}
|
|
2265
2600
|
async test(exec, testPaths = [], flags = []) {
|
|
2266
|
-
const isSignalTarget = exec instanceof
|
|
2601
|
+
const isSignalTarget = exec instanceof AppExecutor2 || exec instanceof LibExecutor2;
|
|
2267
2602
|
if (!testPaths.length && reportsNoTestFile(exec))
|
|
2268
2603
|
return;
|
|
2269
2604
|
const preloadPath = isSignalTarget ? await resolveSignalTestPreloadPath(exec) : null;
|
|
@@ -2715,7 +3050,7 @@ class VerifyScope {
|
|
|
2715
3050
|
const targets = requested.map((name) => {
|
|
2716
3051
|
const target = known.find((candidate) => candidate.name === name);
|
|
2717
3052
|
if (!target)
|
|
2718
|
-
throw new
|
|
3053
|
+
throw new CliError("unknownTarget", `${name} is not an app, library or package of this workspace`);
|
|
2719
3054
|
return { ...target, files: changedFilesOf(target.dir) };
|
|
2720
3055
|
});
|
|
2721
3056
|
return new VerifyScope(targets);
|