akanjs 3.2.0-rc.12 → 3.2.0-rc.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +17 -17
- package/CHANGELOG.md +18 -0
- package/client/csrTypes.ts +2 -0
- package/client/index.ts +1 -0
- package/client/route/RouteDefinition.ts +24 -7
- package/client/route/routeArgs.ts +7 -0
- package/client/router.ts +12 -2
- package/package.json +1 -1
- package/server/akanApp.ts +103 -1270
- package/server/akanServer.ts +1 -1
- package/server/gateway/childSupervisor.ts +325 -0
- package/server/gateway/devHostChannel.ts +40 -0
- package/server/gateway/gatewayChildren.ts +135 -0
- package/server/gateway/gatewayConfig.ts +182 -0
- package/server/gateway/gatewayHttpProxy.ts +231 -0
- package/server/gateway/gatewayLogging.ts +111 -0
- package/server/gateway/gatewayRooms.ts +134 -0
- package/server/gateway/gatewayStatus.ts +116 -0
- package/server/gateway/gatewayStatusPage.ts +54 -0
- package/server/gateway/gatewayWebSocketRelay.ts +149 -0
- package/server/mcp/McpDispatcher.ts +6 -24
- package/signal/SignalFailure.ts +21 -0
- package/signal/agentTurnStream.ts +5 -2
- package/types/client/csrTypes.d.ts +2 -0
- package/types/client/index.d.ts +1 -1
- package/types/client/route/RouteDefinition.d.ts +2 -2
- package/types/client/route/routeArgs.d.ts +6 -0
- package/types/client/router.d.ts +2 -1
- package/types/server/akanApp.d.ts +2 -20
- package/types/server/gateway/childSupervisor.d.ts +33 -0
- package/types/server/gateway/devHostChannel.d.ts +13 -0
- package/types/server/gateway/gatewayChildren.d.ts +47 -0
- package/types/server/gateway/gatewayConfig.d.ts +82 -0
- package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
- package/types/server/gateway/gatewayLogging.d.ts +16 -0
- package/types/server/gateway/gatewayRooms.d.ts +22 -0
- package/types/server/gateway/gatewayStatus.d.ts +62 -0
- package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
- package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/signal/SignalFailure.d.ts +1 -0
- package/types/signal/agentTurnStream.d.ts +1 -0
- package/types/ui/Agent/Chat.d.ts +5 -2
- package/types/ui/Agent/ChatHeader.d.ts +13 -0
- package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
- package/types/ui/overlayLayer.d.ts +6 -1
- package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
- package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +14 -10
- package/types/vendor/use-agentic/failureCode.d.ts +4 -0
- package/types/vendor/use-agentic/types.d.ts +6 -0
- package/types/webkit/CsrGuards.d.ts +2 -0
- package/ui/Agent/Chat.tsx +96 -116
- package/ui/Agent/ChatHeader.tsx +59 -0
- package/ui/Agent/ChatPendingCards.tsx +49 -0
- package/ui/Agent/fetchRunner.ts +8 -1
- package/ui/BottomSheet.tsx +1 -1
- package/ui/Dialog/LegacyModal.tsx +1 -1
- package/ui/Dialog/Modal.tsx +1 -1
- package/ui/Popconfirm.tsx +1 -1
- package/ui/overlayLayer.ts +22 -1
- package/vendor/@akanjs/native/CHANGELOG.md +6 -1
- package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
- package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
- package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +275 -0
- package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
- package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
- package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
- package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
- package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
- package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
- package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
- package/vendor/@akanjs/native/plugins/external-view/src/index.ts +14 -10
- package/vendor/use-agentic/AgentSession.ts +11 -11
- package/vendor/use-agentic/CHANGELOG.md +6 -0
- package/vendor/use-agentic/Compaction.ts +2 -1
- package/vendor/use-agentic/ToolRunner.ts +3 -15
- package/vendor/use-agentic/Transcript.ts +6 -3
- package/vendor/use-agentic/WIRE.md +12 -1
- package/vendor/use-agentic/failureCode.ts +44 -0
- package/vendor/use-agentic/httpRunner.ts +14 -3
- package/vendor/use-agentic/types.ts +6 -0
- package/webkit/CsrGuards.ts +7 -2
- package/webkit/useLocation.ts +3 -2
package/server/akanServer.ts
CHANGED
|
@@ -594,7 +594,7 @@ export class AkanServer {
|
|
|
594
594
|
replicaIdx: Number(process.env.AKAN_REPLICA_IDX ?? 0),
|
|
595
595
|
role: this.serverMode,
|
|
596
596
|
});
|
|
597
|
-
if (this.#schedules) await this.#di.runSchedulerInit();
|
|
597
|
+
if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
|
|
598
598
|
ShutdownManager.register(this.logger, () => this.stop());
|
|
599
599
|
}
|
|
600
600
|
return this;
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { mkdir, readdir, rm } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Logger } from "akanjs/common";
|
|
4
|
+
import type { AkanChildRole, AkanIpcMessage } from "akanjs/service";
|
|
5
|
+
import { RestartSchedule } from "../../common/restartSchedule";
|
|
6
|
+
import { CrossSiteGuard } from "../../signal/CrossSiteGuard";
|
|
7
|
+
import type { BuilderMessage } from "../artifact";
|
|
8
|
+
import { ChildOutputReader } from "../logging/childOutputReader";
|
|
9
|
+
import type { DevHostChannel } from "./devHostChannel";
|
|
10
|
+
import type { ChildState, GatewayChildren } from "./gatewayChildren";
|
|
11
|
+
import { GatewayConfig } from "./gatewayConfig";
|
|
12
|
+
import type { GatewayLogging } from "./gatewayLogging";
|
|
13
|
+
import type { GatewayRooms } from "./gatewayRooms";
|
|
14
|
+
|
|
15
|
+
type ChildMessageHandler = (
|
|
16
|
+
idx: number,
|
|
17
|
+
message: AkanIpcMessage | BuilderMessage,
|
|
18
|
+
proc?: Bun.Subprocess<"ignore", "pipe", "pipe">,
|
|
19
|
+
) => void;
|
|
20
|
+
|
|
21
|
+
interface ChildSupervisorParts {
|
|
22
|
+
config: GatewayConfig;
|
|
23
|
+
children: GatewayChildren;
|
|
24
|
+
rooms: GatewayRooms;
|
|
25
|
+
logging: GatewayLogging;
|
|
26
|
+
host: DevHostChannel;
|
|
27
|
+
logger: Logger;
|
|
28
|
+
onMessage: ChildMessageHandler;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class ChildSupervisor {
|
|
32
|
+
static readonly #childRestartGraceMs = 5_000;
|
|
33
|
+
|
|
34
|
+
readonly #config: GatewayConfig;
|
|
35
|
+
readonly #children: GatewayChildren;
|
|
36
|
+
readonly #rooms: GatewayRooms;
|
|
37
|
+
readonly #logging: GatewayLogging;
|
|
38
|
+
readonly #host: DevHostChannel;
|
|
39
|
+
readonly #logger: Logger;
|
|
40
|
+
readonly #onMessage: ChildMessageHandler;
|
|
41
|
+
|
|
42
|
+
constructor({ config, children, rooms, logging, host, logger, onMessage }: ChildSupervisorParts) {
|
|
43
|
+
this.#config = config;
|
|
44
|
+
this.#children = children;
|
|
45
|
+
this.#rooms = rooms;
|
|
46
|
+
this.#logging = logging;
|
|
47
|
+
this.#host = host;
|
|
48
|
+
this.#logger = logger;
|
|
49
|
+
this.#onMessage = onMessage;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async prepareRuntimeDir() {
|
|
53
|
+
await mkdir(this.#config.runtimeDir, { recursive: true });
|
|
54
|
+
|
|
55
|
+
const entries = await readdir(this.#config.runtimeDir).catch(() => []);
|
|
56
|
+
await Promise.all(
|
|
57
|
+
entries
|
|
58
|
+
.filter((name) => /^akan-(child-.*|control)\.sock$/.test(name))
|
|
59
|
+
.map((name) => rm(path.join(this.#config.runtimeDir, name), { force: true }).catch(() => undefined)),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
spawn(idx: number) {
|
|
64
|
+
const role = this.#config.roleOf(idx);
|
|
65
|
+
const upstream = this.#config.childUpstreamOf(idx, role);
|
|
66
|
+
|
|
67
|
+
const childCode = `import(${JSON.stringify(path.resolve(this.#config.serverPath))}).then((mod)=>{ const server = mod.server ?? mod.app; if (!server?.start) throw new Error("server.ts must export server or app with start()"); return server.start({ listen: process.env.SERVER_MODE !== "batch" }); }).catch((error)=>{ const exit = () => process.exit(1); setTimeout(exit, 2000); if (!process.send) return exit(); process.send({ type: "error", message: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, pid: process.pid }, undefined, undefined, exit); });`;
|
|
68
|
+
const proc: Bun.Subprocess<"ignore", "pipe", "pipe"> = Bun.spawn(["bun", "-e", childCode], {
|
|
69
|
+
cwd: process.cwd(),
|
|
70
|
+
env: {
|
|
71
|
+
...process.env,
|
|
72
|
+
|
|
73
|
+
...this.#config.childEnv(idx, role),
|
|
74
|
+
AKAN_CHILD_SOCKET: upstream.http.socketPath,
|
|
75
|
+
AKAN_CHILD_WS_PORT: upstream.ws ? String(upstream.ws.port) : "",
|
|
76
|
+
...(this.#config.printChildStderr || Logger.isNdjson ? {} : { AKAN_CHILD_STDERR_HIDDEN: "1" }),
|
|
77
|
+
},
|
|
78
|
+
ipc: (message) => this.#onMessage(idx, message as AkanIpcMessage, proc),
|
|
79
|
+
stdout: "pipe",
|
|
80
|
+
stderr: "pipe",
|
|
81
|
+
stdin: "ignore",
|
|
82
|
+
});
|
|
83
|
+
const previous = this.#children.get(idx);
|
|
84
|
+
this.#children.set(idx, {
|
|
85
|
+
idx,
|
|
86
|
+
role,
|
|
87
|
+
proc,
|
|
88
|
+
ready: false,
|
|
89
|
+
status: "starting",
|
|
90
|
+
metrics: {},
|
|
91
|
+
|
|
92
|
+
restart: previous?.restart ?? new RestartSchedule(this.#config.childRestartPolicy),
|
|
93
|
+
restartCount: previous?.restartCount ?? 0,
|
|
94
|
+
restartPending: false,
|
|
95
|
+
lastExitCode: previous?.lastExitCode,
|
|
96
|
+
lastRestartAt: previous?.lastRestartAt,
|
|
97
|
+
lastRestartReason: previous?.lastRestartReason,
|
|
98
|
+
});
|
|
99
|
+
this.#children.invalidateFederation();
|
|
100
|
+
const output = new ChildOutputReader({
|
|
101
|
+
onLine: (line) => this.#logging.writeChildLine(idx, role, proc.pid, "stdout", line),
|
|
102
|
+
onBlock: (lines) => this.#logging.writeChildStderrBlock(idx, role, proc.pid, lines),
|
|
103
|
+
});
|
|
104
|
+
void output.pipe(proc.stdout, "stdout");
|
|
105
|
+
void output.pipe(proc.stderr, "stderr");
|
|
106
|
+
proc.exited.then((code) => this.#handleChildExit(idx, proc, code));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
#handleChildExit(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, code: number | null) {
|
|
110
|
+
const child = this.#children.get(idx);
|
|
111
|
+
if (!child || child.proc !== proc) return;
|
|
112
|
+
if (child.status === "crashed") return;
|
|
113
|
+
child.status = "exited";
|
|
114
|
+
child.lastExitCode = code;
|
|
115
|
+
this.#children.invalidateFederation();
|
|
116
|
+
this.#rooms.removeChildRooms(idx);
|
|
117
|
+
if (this.#children.stopping) return;
|
|
118
|
+
void this.scheduleRestart(child, proc, `exit:${code ?? "unknown"}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
scheduleRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string): void {
|
|
122
|
+
if (this.#children.stopping) return;
|
|
123
|
+
if (child.proc !== proc) return;
|
|
124
|
+
if (child.restartPending || child.restart.pending) {
|
|
125
|
+
child.lastRestartReason = reason;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (child.restart.exhausted && !child.ready) {
|
|
129
|
+
this.#markChildCrashed(child, reason);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
child.restartPending = true;
|
|
134
|
+
child.ready = false;
|
|
135
|
+
child.status = reason === "health-timeout" || reason === "upstream-open-failed" ? "unhealthy" : "exited";
|
|
136
|
+
child.upstream = undefined;
|
|
137
|
+
child.wsUpstream = undefined;
|
|
138
|
+
child.healthPath = undefined;
|
|
139
|
+
this.#children.invalidateFederation();
|
|
140
|
+
child.lastRestartReason = reason;
|
|
141
|
+
child.lastRestartAt = Date.now();
|
|
142
|
+
this.#rooms.removeChildRooms(child.idx);
|
|
143
|
+
|
|
144
|
+
const delay = child.restart.next();
|
|
145
|
+
child.restartCount += 1;
|
|
146
|
+
this.#logger.error(
|
|
147
|
+
`Child ${child.idx}/${child.role} failed (${reason}); restarting in ${delay}ms (attempt ${child.restart.attempts})`,
|
|
148
|
+
);
|
|
149
|
+
|
|
150
|
+
void this.#restartChildAfterDelay(child.idx, proc, reason, delay).catch((error) => {
|
|
151
|
+
const current = this.#children.get(child.idx);
|
|
152
|
+
if (!current || current.proc !== proc || this.#children.stopping) return;
|
|
153
|
+
current.restartPending = false;
|
|
154
|
+
this.#logger.error(
|
|
155
|
+
`Failed to restart child ${child.idx}/${child.role}: ${error instanceof Error ? error.message : String(error)}`,
|
|
156
|
+
);
|
|
157
|
+
this.scheduleRestart(current, proc, "restart-failed");
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async #restartChildAfterDelay(
|
|
162
|
+
idx: number,
|
|
163
|
+
proc: Bun.Subprocess<"ignore", "pipe", "pipe">,
|
|
164
|
+
reason: string,
|
|
165
|
+
delay: number,
|
|
166
|
+
) {
|
|
167
|
+
const child = this.#children.get(idx);
|
|
168
|
+
if (!child || child.proc !== proc || this.#children.stopping) return;
|
|
169
|
+
await this.#stopChildForRestart(child, proc, reason);
|
|
170
|
+
if (this.#children.stopping) return;
|
|
171
|
+
const current = this.#children.get(idx);
|
|
172
|
+
if (!current || current.proc !== proc) return;
|
|
173
|
+
current.restart.arm(delay, () => {
|
|
174
|
+
void this.#respawnChild(idx, proc).catch((error) => {
|
|
175
|
+
const latest = this.#children.get(idx);
|
|
176
|
+
if (!latest || latest.proc !== proc || this.#children.stopping) return;
|
|
177
|
+
latest.restartPending = false;
|
|
178
|
+
this.#logger.error(
|
|
179
|
+
`Failed to respawn child ${idx}/${latest.role}: ${error instanceof Error ? error.message : String(error)}`,
|
|
180
|
+
);
|
|
181
|
+
this.scheduleRestart(latest, proc, "respawn-failed");
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async #respawnChild(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">) {
|
|
187
|
+
if (this.#children.stopping) return;
|
|
188
|
+
const current = this.#children.get(idx);
|
|
189
|
+
if (!current || current.proc !== proc) return;
|
|
190
|
+
await this.#removeChildSocket(idx, current.role);
|
|
191
|
+
if (this.#children.stopping) return;
|
|
192
|
+
current.restartPending = false;
|
|
193
|
+
this.spawn(idx);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
#markChildCrashed(child: ChildState, reason: string) {
|
|
197
|
+
|
|
198
|
+
if (child.status === "crashed") return;
|
|
199
|
+
child.ready = false;
|
|
200
|
+
child.status = "crashed";
|
|
201
|
+
child.restartPending = false;
|
|
202
|
+
child.upstream = undefined;
|
|
203
|
+
child.wsUpstream = undefined;
|
|
204
|
+
child.healthPath = undefined;
|
|
205
|
+
child.lastRestartReason = reason;
|
|
206
|
+
this.#children.invalidateFederation();
|
|
207
|
+
this.#rooms.removeChildRooms(child.idx);
|
|
208
|
+
const attempts = child.restart.attempts + 1;
|
|
209
|
+
const detail = child.lastErrorMessage ?? reason;
|
|
210
|
+
const message = `Backend replica ${child.idx}/${child.role} failed ${attempts} consecutive boots; waiting for a code change to retry: ${detail}`;
|
|
211
|
+
this.#logger.error(`[child-crash-loop] ${message}`);
|
|
212
|
+
this.#host.reportBackendBuildStatus({ ok: false, message });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async #stopChildForRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string) {
|
|
216
|
+
if (reason.startsWith("exit:") || proc.killed) return;
|
|
217
|
+
this.#children.send(child, { type: "shutdown", signal: reason } satisfies AkanIpcMessage);
|
|
218
|
+
const result = await Promise.race([
|
|
219
|
+
proc.exited.then(() => "exited" as const).catch(() => "exited" as const),
|
|
220
|
+
new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), ChildSupervisor.#childRestartGraceMs)),
|
|
221
|
+
]);
|
|
222
|
+
if (result === "timeout" && !proc.killed) {
|
|
223
|
+
this.#logger.warn(
|
|
224
|
+
`Child ${child.idx}/${child.role} did not stop in ${ChildSupervisor.#childRestartGraceMs}ms; killing`,
|
|
225
|
+
);
|
|
226
|
+
proc.kill();
|
|
227
|
+
await proc.exited.catch(() => undefined);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async #removeChildSocket(idx: number, role: AkanChildRole) {
|
|
232
|
+
const socketPath = this.#config.childUpstreamOf(idx, role).http.socketPath;
|
|
233
|
+
try {
|
|
234
|
+
await rm(socketPath, { force: true });
|
|
235
|
+
} catch {
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
markReady(idx: number, message: Extract<AkanIpcMessage, { type: "ready" }>) {
|
|
240
|
+
const child = this.#children.get(idx);
|
|
241
|
+
if (!child) return;
|
|
242
|
+
child.ready = true;
|
|
243
|
+
child.status = "ready";
|
|
244
|
+
child.pid = message.pid;
|
|
245
|
+
child.upstream = message.upstream;
|
|
246
|
+
child.wsUpstream = message.wsUpstream;
|
|
247
|
+
child.healthPath = message.healthPath;
|
|
248
|
+
if (message.crossSite) CrossSiteGuard.configure(message.crossSite);
|
|
249
|
+
child.lastPongAtMono = performance.now();
|
|
250
|
+
child.restart.reset();
|
|
251
|
+
|
|
252
|
+
const hub = this.#logging.hub;
|
|
253
|
+
if (hub && hub.floor !== null) this.#children.send(child, { type: "log.level", minSev: hub.floor });
|
|
254
|
+
child.restartPending = false;
|
|
255
|
+
child.lastErrorMessage = undefined;
|
|
256
|
+
this.#children.invalidateFederation();
|
|
257
|
+
|
|
258
|
+
const trafficChildren = [...this.#children.values()].filter((item) => item.role !== "batch");
|
|
259
|
+
|
|
260
|
+
if (!this.#children.stopping && child.role !== "batch" && trafficChildren.every((item) => item.ready)) {
|
|
261
|
+
process.send?.({ type: "backend-ready", pid: process.pid } satisfies BuilderMessage);
|
|
262
|
+
}
|
|
263
|
+
if ([...this.#children.values()].every((item) => item.ready)) {
|
|
264
|
+
this.#logger.verbose(`All ${this.#children.size} child process(es) are ready`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
markHealthy(idx: number) {
|
|
269
|
+
const child = this.#children.get(idx);
|
|
270
|
+
if (!child) return;
|
|
271
|
+
child.status = "healthy";
|
|
272
|
+
child.lastPongAtMono = performance.now();
|
|
273
|
+
this.#children.invalidateFederation();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
checkHealth() {
|
|
277
|
+
const nowMono = performance.now();
|
|
278
|
+
for (const child of this.#children.values()) {
|
|
279
|
+
if (this.#children.isUnavailable(child)) continue;
|
|
280
|
+
if (child.lastPongAtMono && nowMono - child.lastPongAtMono > this.#config.healthTimeoutMs) {
|
|
281
|
+
child.status = "unhealthy";
|
|
282
|
+
this.#children.invalidateFederation();
|
|
283
|
+
void this.scheduleRestart(child, child.proc, "health-timeout");
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const sent = this.#children.send(child, {
|
|
287
|
+
type: "health.ping",
|
|
288
|
+
nonce: crypto.randomUUID(),
|
|
289
|
+
sentAt: Date.now(),
|
|
290
|
+
} satisfies AkanIpcMessage);
|
|
291
|
+
if (!sent) {
|
|
292
|
+
child.status = "unhealthy";
|
|
293
|
+
this.#children.invalidateFederation();
|
|
294
|
+
void this.scheduleRestart(child, child.proc, "health-send-failed");
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
crashLoopDetail(): string | null {
|
|
300
|
+
if (!this.#config.devHosted) return null;
|
|
301
|
+
const trafficChildren = [...this.#children.values()].filter((child) => child.role !== "batch");
|
|
302
|
+
if (trafficChildren.length === 0) return null;
|
|
303
|
+
if (!trafficChildren.every((child) => child.status === "crashed")) return null;
|
|
304
|
+
return (
|
|
305
|
+
trafficChildren.map((child) => child.lastErrorMessage ?? child.lastRestartReason).find(Boolean) ??
|
|
306
|
+
"unknown boot error"
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async stopAll(signal: string) {
|
|
311
|
+
for (const child of this.#children.values()) {
|
|
312
|
+
child.restart.cancel();
|
|
313
|
+
this.#children.send(child, { type: "shutdown", signal } satisfies AkanIpcMessage);
|
|
314
|
+
}
|
|
315
|
+
await Promise.race([
|
|
316
|
+
Promise.all([...this.#children.values()].map((child) => child.proc.exited.catch(() => undefined))),
|
|
317
|
+
new Promise((resolve) => setTimeout(resolve, GatewayConfig.childShutdownWaitMs())),
|
|
318
|
+
]);
|
|
319
|
+
|
|
320
|
+
const stragglers = [...this.#children.values()].filter((child) => !child.proc.killed);
|
|
321
|
+
for (const child of stragglers) child.proc.kill("SIGKILL");
|
|
322
|
+
await Promise.all(stragglers.map((child) => child.proc.exited.catch(() => undefined)));
|
|
323
|
+
this.#children.clear();
|
|
324
|
+
}
|
|
325
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
2
|
+
import type { BuilderMessage, BuilderRequest, BuilderResponse } from "../artifact";
|
|
3
|
+
import type { GatewayChildren } from "./gatewayChildren";
|
|
4
|
+
|
|
5
|
+
export class DevHostChannel {
|
|
6
|
+
readonly #children: GatewayChildren;
|
|
7
|
+
readonly #logger: Logger;
|
|
8
|
+
#nextBuilderReqId = 1;
|
|
9
|
+
readonly #builderReqMap = new Map<number, { childIdx: number; childLocalId: number }>();
|
|
10
|
+
|
|
11
|
+
constructor(children: GatewayChildren, logger: Logger) {
|
|
12
|
+
this.#children = children;
|
|
13
|
+
this.#logger = logger;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
reportBackendBuildStatus({ ok, message }: { ok: boolean; message: string }) {
|
|
17
|
+
process.send?.({
|
|
18
|
+
type: "build-status",
|
|
19
|
+
data: { generation: -1, phase: "backend", ok, files: [], message },
|
|
20
|
+
} satisfies BuilderMessage);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
forwardBuilderReq(childIdx: number, message: BuilderRequest) {
|
|
24
|
+
const gatewayReqId = this.#nextBuilderReqId++;
|
|
25
|
+
this.#builderReqMap.set(gatewayReqId, { childIdx, childLocalId: message.id });
|
|
26
|
+
process.send?.({ ...message, id: gatewayReqId } satisfies BuilderRequest);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
forwardBuilderRes(message: BuilderResponse) {
|
|
30
|
+
const request = this.#builderReqMap.get(message.id);
|
|
31
|
+
if (!request) {
|
|
32
|
+
this.#logger.warn(`No child found for ${message.type} id=${message.id}`);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
this.#builderReqMap.delete(message.id);
|
|
36
|
+
const child = this.#children.get(request.childIdx);
|
|
37
|
+
if (!child || child.proc.killed) return;
|
|
38
|
+
this.#children.send(child, { ...message, id: request.childLocalId } satisfies BuilderResponse);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
2
|
+
import type { AkanChildRole, AkanChildStatus, AkanIpcMessage, AkanMetricsReport, AkanUpstream } from "akanjs/service";
|
|
3
|
+
import type { RestartSchedule } from "../../common/restartSchedule";
|
|
4
|
+
import type { BuilderMessage } from "../artifact";
|
|
5
|
+
|
|
6
|
+
export interface ChildState {
|
|
7
|
+
idx: number;
|
|
8
|
+
role: AkanChildRole;
|
|
9
|
+
proc: Bun.Subprocess<"ignore", "pipe", "pipe">;
|
|
10
|
+
ready: boolean;
|
|
11
|
+
status: AkanChildStatus;
|
|
12
|
+
pid?: number;
|
|
13
|
+
upstream?: AkanUpstream;
|
|
14
|
+
wsUpstream?: Extract<AkanUpstream, { type: "tcp" }>;
|
|
15
|
+
healthPath?: string;
|
|
16
|
+
metrics: AkanMetricsReport;
|
|
17
|
+
/** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
|
|
18
|
+
lastPongAtMono?: number;
|
|
19
|
+
restart: RestartSchedule;
|
|
20
|
+
restartCount: number;
|
|
21
|
+
restartPending: boolean;
|
|
22
|
+
lastExitCode?: number | null;
|
|
23
|
+
lastRestartAt?: number;
|
|
24
|
+
lastRestartReason?: string;
|
|
25
|
+
lastErrorMessage?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class GatewayChildren {
|
|
29
|
+
readonly #logger: Logger;
|
|
30
|
+
readonly #children = new Map<number, ChildState>();
|
|
31
|
+
#rrIdx = 0;
|
|
32
|
+
#federationChildCache: ChildState[] | null = null;
|
|
33
|
+
#stopping = false;
|
|
34
|
+
|
|
35
|
+
constructor(logger: Logger) {
|
|
36
|
+
this.#logger = logger;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
get stopping() {
|
|
40
|
+
return this.#stopping;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
markStopping() {
|
|
44
|
+
this.#stopping = true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get size() {
|
|
48
|
+
return this.#children.size;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
get(idx: number) {
|
|
52
|
+
return this.#children.get(idx);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
set(idx: number, child: ChildState) {
|
|
56
|
+
this.#children.set(idx, child);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
values() {
|
|
60
|
+
return this.#children.values();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
clear() {
|
|
64
|
+
this.#children.clear();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
invalidateFederation() {
|
|
68
|
+
this.#federationChildCache = null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
isUnavailable(child: ChildState): boolean {
|
|
72
|
+
return child.proc.killed || child.status === "exited" || child.status === "crashed";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
federationCandidates() {
|
|
76
|
+
this.#federationChildCache ??= [...this.#children.values()].filter(
|
|
77
|
+
(child) =>
|
|
78
|
+
(child.role === "federation" || child.role === "all") &&
|
|
79
|
+
child.ready &&
|
|
80
|
+
child.status !== "unhealthy" &&
|
|
81
|
+
!this.isUnavailable(child),
|
|
82
|
+
);
|
|
83
|
+
return this.#federationChildCache;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
pickFederationChild() {
|
|
87
|
+
const candidates = this.federationCandidates();
|
|
88
|
+
if (candidates.length === 0) return null;
|
|
89
|
+
const child = candidates[this.#rrIdx % candidates.length];
|
|
90
|
+
this.#rrIdx++;
|
|
91
|
+
return child;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
updateMetrics(childIdx: number, metrics: AkanMetricsReport) {
|
|
95
|
+
const child = this.#children.get(childIdx);
|
|
96
|
+
if (!child) return;
|
|
97
|
+
child.metrics = { ...child.metrics, pid: metrics.pid ?? child.pid, ...metrics };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
fanoutToFederation(message: AkanIpcMessage | BuilderMessage, exceptIdx?: number) {
|
|
101
|
+
for (const child of this.#children.values()) {
|
|
102
|
+
if (child.idx === exceptIdx) continue;
|
|
103
|
+
if (child.role === "federation" || child.role === "all") this.send(child, message);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
fanoutToAll(message: AkanIpcMessage) {
|
|
108
|
+
for (const child of this.#children.values()) this.send(child, message);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
fanoutToBatch(message: AkanIpcMessage) {
|
|
112
|
+
for (const child of this.#children.values()) {
|
|
113
|
+
if (child.role === "batch" || child.role === "all") {
|
|
114
|
+
if (this.send(child, message) && message.type === "queue.wake") {
|
|
115
|
+
child.metrics.queueWakeCount = (child.metrics.queueWakeCount ?? 0) + 1;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
send(child: ChildState, message: AkanIpcMessage | BuilderMessage): boolean {
|
|
122
|
+
if (this.isUnavailable(child)) return false;
|
|
123
|
+
try {
|
|
124
|
+
child.proc.send(message);
|
|
125
|
+
return true;
|
|
126
|
+
} catch (error) {
|
|
127
|
+
this.#logger.warn(
|
|
128
|
+
`Failed to send ${message.type} to child ${child.idx}/${child.role}: ${
|
|
129
|
+
error instanceof Error ? error.message : String(error)
|
|
130
|
+
}`,
|
|
131
|
+
);
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { AkanChildRole, AkanUpstream } from "akanjs/service";
|
|
3
|
+
import { getApiPrefix, getWsPrefix, normalizeRoutePrefix } from "../../base/baseEnv";
|
|
4
|
+
import type { RestartPolicy } from "../../common/restartSchedule";
|
|
5
|
+
import { resolveRuntimeDir } from "../lifecycle/runtimeDir";
|
|
6
|
+
import { getWebConfigFromEnv } from "../types";
|
|
7
|
+
|
|
8
|
+
export interface AkanAppOptions {
|
|
9
|
+
replica?: number | string;
|
|
10
|
+
serverPath?: string;
|
|
11
|
+
runtimeDir?: string;
|
|
12
|
+
port?: number;
|
|
13
|
+
wsBasePort?: number;
|
|
14
|
+
openapi?: boolean;
|
|
15
|
+
/** Signal endpoint mount, `/api` by default; handed down as `AKAN_API_PREFIX` (CSR/mobile follow akan.config.ts). */
|
|
16
|
+
prefix?: string;
|
|
17
|
+
/** Where the websocket upgrade sits under `prefix`, `/ws` by default. Handed down as `AKAN_WS_PREFIX`. */
|
|
18
|
+
websocketPrefix?: string;
|
|
19
|
+
/** Boot only these modules and what they reach; omitted or empty mounts every enabled one. `AKAN_MODULES`. */
|
|
20
|
+
modules?: string[];
|
|
21
|
+
/** Mount all but these and whatever reaches them, applied after `modules`. `AKAN_DISABLE_MODULES`. */
|
|
22
|
+
disableModules?: string[];
|
|
23
|
+
/** Like `disableModules`, by owning lib. `AKAN_DISABLE_LIBS`. */
|
|
24
|
+
disableLibs?: string[];
|
|
25
|
+
/** In-process replica; default on for one env-set traffic replica, off if `replica` is passed or AKAN_SOLO=false. */
|
|
26
|
+
solo?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface AkanReplicaConfig {
|
|
30
|
+
federation: number;
|
|
31
|
+
batch: number;
|
|
32
|
+
all: number;
|
|
33
|
+
total: number;
|
|
34
|
+
value: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface GatewayUpstream {
|
|
38
|
+
http: Extract<AkanUpstream, { type: "unix" }>;
|
|
39
|
+
ws?: Extract<AkanUpstream, { type: "tcp" }>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class GatewayConfig {
|
|
43
|
+
static readonly devMaxChildBootFailures = 3;
|
|
44
|
+
|
|
45
|
+
readonly devHosted = process.env.AKAN_COMMAND_TYPE === "start";
|
|
46
|
+
readonly childRestartPolicy: RestartPolicy = {
|
|
47
|
+
min: 1_000,
|
|
48
|
+
max: 30_000,
|
|
49
|
+
...(this.devHosted ? { maxAttempts: GatewayConfig.devMaxChildBootFailures - 1 } : {}),
|
|
50
|
+
};
|
|
51
|
+
readonly healthTimeoutMs = GatewayConfig.#parseHealthTimeoutMs();
|
|
52
|
+
readonly upstreamWaitMs = GatewayConfig.#parseUpstreamWaitMs();
|
|
53
|
+
/** Child stderr is mostly bundler/runtime noise, kept to the log file; with none it may be a crash's only trace. */
|
|
54
|
+
readonly printChildStderr = process.env.AKAN_CHILD_STDERR === "1";
|
|
55
|
+
readonly serverPath: string;
|
|
56
|
+
readonly artifactDir: string;
|
|
57
|
+
readonly replica: AkanReplicaConfig;
|
|
58
|
+
readonly runtimeDir: string;
|
|
59
|
+
readonly socketRunId = `${process.pid}-${Date.now().toString(36)}`;
|
|
60
|
+
readonly port: number;
|
|
61
|
+
readonly wsBasePort: number;
|
|
62
|
+
readonly openapi?: boolean;
|
|
63
|
+
readonly prefix: string;
|
|
64
|
+
readonly websocketPrefix: string;
|
|
65
|
+
readonly web = getWebConfigFromEnv();
|
|
66
|
+
readonly modules: string[];
|
|
67
|
+
readonly disableModules: string[];
|
|
68
|
+
readonly disableLibs: string[];
|
|
69
|
+
readonly solo: boolean;
|
|
70
|
+
|
|
71
|
+
constructor(serverPath: string, options: AkanAppOptions) {
|
|
72
|
+
this.serverPath = GatewayConfig.#resolveServerPath(options.serverPath ?? serverPath);
|
|
73
|
+
this.artifactDir = path.resolve(path.dirname(this.serverPath), ".akan", "artifact");
|
|
74
|
+
this.replica = GatewayConfig.#parseReplicaConfig(options.replica);
|
|
75
|
+
this.runtimeDir = resolveRuntimeDir(options.runtimeDir);
|
|
76
|
+
this.port = Number(options.port ?? process.env.PORT ?? 8282);
|
|
77
|
+
this.wsBasePort = Number(options.wsBasePort ?? process.env.AKAN_WS_BASE_PORT ?? this.port + 10_000);
|
|
78
|
+
this.openapi = options.openapi;
|
|
79
|
+
this.prefix = normalizeRoutePrefix(options.prefix) ?? getApiPrefix();
|
|
80
|
+
this.websocketPrefix = normalizeRoutePrefix(options.websocketPrefix) ?? getWsPrefix();
|
|
81
|
+
this.modules = options.modules ?? [];
|
|
82
|
+
this.disableModules = options.disableModules ?? [];
|
|
83
|
+
this.disableLibs = options.disableLibs ?? [];
|
|
84
|
+
this.solo = GatewayConfig.#resolveSolo(options, this.replica);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
static #resolveSolo(options: AkanAppOptions, replica: AkanReplicaConfig) {
|
|
88
|
+
if (options.solo !== undefined) return options.solo;
|
|
89
|
+
if (process.env.AKAN_SOLO === "false" || process.env.AKAN_SOLO === "0") return false;
|
|
90
|
+
if (process.env.AKAN_COMMAND_TYPE === "start") return false;
|
|
91
|
+
if (options.replica !== undefined) return false;
|
|
92
|
+
return replica.total === 1 && replica.batch === 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
static #resolveServerPath(serverPath: string) {
|
|
96
|
+
const baseDir = path.dirname(Bun.main);
|
|
97
|
+
const resolved = path.isAbsolute(serverPath) ? serverPath : path.resolve(baseDir, serverPath);
|
|
98
|
+
if (path.extname(resolved)) return resolved;
|
|
99
|
+
return Bun.main.endsWith(".js") ? `${resolved}.js` : `${resolved}.ts`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
static #parseReplicaConfig(value?: number | string): AkanReplicaConfig {
|
|
103
|
+
const configured = value ?? process.env.AKAN_REPLICA;
|
|
104
|
+
const raw = String(configured ?? "0,0,1").trim();
|
|
105
|
+
const [federationRaw, batchRaw, allRaw] = raw.split(",");
|
|
106
|
+
const federation = GatewayConfig.#parseReplicaCount(federationRaw, 0);
|
|
107
|
+
const batch = GatewayConfig.#parseReplicaCount(batchRaw, 0);
|
|
108
|
+
const all = GatewayConfig.#parseReplicaCount(allRaw, configured == null ? 1 : 0);
|
|
109
|
+
const normalizedAll = federation + batch + all > 0 ? all : 1;
|
|
110
|
+
return {
|
|
111
|
+
federation,
|
|
112
|
+
batch,
|
|
113
|
+
all: normalizedAll,
|
|
114
|
+
total: federation + batch + normalizedAll,
|
|
115
|
+
value: `${federation},${batch},${normalizedAll}`,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
static #parseReplicaCount(value: string | undefined, fallback: number) {
|
|
120
|
+
const parsed = Number.parseInt(value ?? "", 10);
|
|
121
|
+
return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
static #defaultChildNodeEnv() {
|
|
125
|
+
if (process.env.AKAN_COMMAND_TYPE === "start") return "development";
|
|
126
|
+
if (process.env.AKAN_COMMAND_TYPE === "build") return "production";
|
|
127
|
+
if (process.env.NODE_ENV) return process.env.NODE_ENV;
|
|
128
|
+
return Bun.main.endsWith(".js") ? "production" : "development";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
static #parseHealthTimeoutMs() {
|
|
132
|
+
const configured = Number(process.env.AKAN_HEALTH_TIMEOUT_MS);
|
|
133
|
+
if (Number.isFinite(configured) && configured > 0) return configured;
|
|
134
|
+
return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
static #parseUpstreamWaitMs() {
|
|
138
|
+
const configured = Number(process.env.AKAN_UPSTREAM_WAIT_MS);
|
|
139
|
+
if (Number.isFinite(configured) && configured >= 0) return configured;
|
|
140
|
+
return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
static childShutdownWaitMs() {
|
|
144
|
+
const configured = Number(process.env.AKAN_CHILD_SHUTDOWN_WAIT_MS);
|
|
145
|
+
if (Number.isFinite(configured) && configured > 0) return configured;
|
|
146
|
+
return process.env.AKAN_COMMAND_TYPE === "start" ? 5_000 : 30_000;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
childEnv(idx: number, role: AkanChildRole) {
|
|
150
|
+
return {
|
|
151
|
+
PORT: String(this.port),
|
|
152
|
+
NODE_ENV: GatewayConfig.#defaultChildNodeEnv(),
|
|
153
|
+
AKAN_REPLICA: this.replica.value,
|
|
154
|
+
AKAN_REPLICA_IDX: String(idx),
|
|
155
|
+
AKAN_APP_DIR: path.dirname(this.serverPath),
|
|
156
|
+
SERVER_MODE: role,
|
|
157
|
+
AKAN_API_PREFIX: this.prefix,
|
|
158
|
+
AKAN_WS_PREFIX: this.websocketPrefix,
|
|
159
|
+
...(this.openapi === undefined ? {} : { AKAN_OPENAPI: this.openapi ? "true" : "false" }),
|
|
160
|
+
...(this.modules.length ? { AKAN_MODULES: this.modules.join(",") } : {}),
|
|
161
|
+
...(this.disableModules.length ? { AKAN_DISABLE_MODULES: this.disableModules.join(",") } : {}),
|
|
162
|
+
...(this.disableLibs.length ? { AKAN_DISABLE_LIBS: this.disableLibs.join(",") } : {}),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
roleOf(idx: number): AkanChildRole {
|
|
167
|
+
if (idx < this.replica.federation) return "federation";
|
|
168
|
+
if (idx < this.replica.federation + this.replica.batch) return "batch";
|
|
169
|
+
return "all";
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
childUpstreamOf(idx: number, role: AkanChildRole): GatewayUpstream {
|
|
173
|
+
return {
|
|
174
|
+
http: { type: "unix", socketPath: path.join(this.runtimeDir, `akan-child-${this.socketRunId}-${idx}.sock`) },
|
|
175
|
+
ws: role === "batch" ? undefined : { type: "tcp", host: "127.0.0.1", port: this.wsBasePort + idx },
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
isWebSocketPath(pathname: string) {
|
|
180
|
+
return pathname === `${this.prefix}${this.websocketPrefix}` || pathname === "/_akan/hmr";
|
|
181
|
+
}
|
|
182
|
+
}
|