akanjs 3.2.0-rc.11 → 3.2.0-rc.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +17 -17
- package/CHANGELOG.md +24 -0
- package/base/base.ts +2 -1
- package/client/clientRuntime.ts +1 -0
- package/client/cn.ts +2 -2
- package/client/csrTypes.ts +2 -0
- package/client/frameConfig.ts +1 -0
- package/client/index.ts +249 -26
- package/client/locale.ts +1 -0
- package/client/route/RouteDefinition.ts +24 -7
- package/client/route/routeArgs.ts +7 -0
- package/client/router.ts +12 -2
- package/client/rscNavigation.ts +1 -0
- package/common/CodeTranscript.ts +1 -1
- package/constant/constantRegistry.ts +4 -8
- package/constant/crystalize.ts +1 -2
- package/constant/getDefault.ts +1 -1
- package/constant/immerify.ts +1 -1
- package/constant/index.ts +78 -21
- package/constant/purify.ts +4 -9
- package/constant/serialize.ts +4 -2
- package/constant/types.ts +1 -0
- package/constant/via.ts +1 -2
- package/dictionary/locale.ts +1 -1
- package/document/databaseRegistry.ts +2 -1
- package/document/documentSchema.ts +1 -0
- package/document/filterMeta.ts +4 -1
- package/document/into.ts +2 -1
- package/document/loaderInfo.ts +2 -1
- package/document/types.ts +1 -1
- package/fetch/client/fetchClient.ts +3 -3
- package/fetch/client/httpClient.ts +2 -0
- package/fetch/client/wsClient.ts +1 -0
- package/package.json +1 -1
- package/server/akanApp.ts +103 -1270
- package/server/akanServer.ts +1 -1
- package/server/console.ts +3 -2
- 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/index.ts +257 -17
- package/server/logging/logControlSocket.ts +42 -3
- package/server/mcp/McpDispatcher.ts +6 -24
- package/server/rscClient.tsx +14 -8
- package/server/sitemap.ts +1 -0
- package/service/injectInfo.ts +2 -1
- package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +3 -3
- package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
- package/service/serviceRegistry.ts +1 -0
- package/signal/SignalFailure.ts +21 -0
- package/signal/agentTurnStream.ts +5 -2
- package/signal/index.ts +298 -30
- package/signal/resolveFieldContext.ts +34 -0
- package/signal/serializer/fetch.serializer.ts +7 -10
- package/signal/signalContext.ts +4 -31
- package/signal/trace.ts +3 -0
- package/store/baseSt.ts +1 -0
- package/store/index.ts +125 -18
- package/store/stateBuilder.ts +2 -0
- package/types/base/base.d.ts +2 -1
- package/types/client/clientRuntime.d.ts +1 -0
- package/types/client/cn.d.ts +2 -2
- package/types/client/csrTypes.d.ts +2 -0
- package/types/client/frameConfig.d.ts +1 -0
- package/types/client/index.d.ts +25 -26
- package/types/client/locale.d.ts +1 -0
- 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/client/rscNavigation.d.ts +1 -0
- package/types/common/CodeTranscript.d.ts +1 -1
- package/types/constant/constantRegistry.d.ts +3 -1
- package/types/constant/crystalize.d.ts +1 -1
- package/types/constant/getDefault.d.ts +1 -1
- package/types/constant/immerify.d.ts +1 -1
- package/types/constant/index.d.ts +21 -21
- package/types/constant/purify.d.ts +2 -1
- package/types/constant/serialize.d.ts +1 -1
- package/types/constant/types.d.ts +1 -0
- package/types/dictionary/base.dictionary.d.ts +1 -1
- package/types/dictionary/dictionary.d.ts +8 -8
- package/types/dictionary/locale.d.ts +1 -1
- package/types/document/databaseRegistry.d.ts +2 -1
- package/types/document/documentSchema.d.ts +1 -0
- package/types/document/filterMeta.d.ts +4 -1
- package/types/document/into.d.ts +1 -1
- package/types/document/loaderInfo.d.ts +2 -1
- package/types/document/types.d.ts +1 -1
- package/types/fetch/client/fetchClient.d.ts +2 -1
- package/types/fetch/client/httpClient.d.ts +2 -0
- package/types/fetch/client/wsClient.d.ts +1 -0
- package/types/server/akanApp.d.ts +2 -20
- package/types/server/console.d.ts +3 -2
- 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/index.d.ts +17 -17
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/sitemap.d.ts +1 -0
- package/types/service/injectInfo.d.ts +2 -1
- package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +1 -14
- package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
- package/types/service/serviceRegistry.d.ts +1 -0
- package/types/signal/SignalFailure.d.ts +1 -0
- package/types/signal/agentTurnStream.d.ts +1 -0
- package/types/signal/index.d.ts +31 -30
- package/types/signal/resolveFieldContext.d.ts +15 -0
- package/types/signal/serializer/fetch.serializer.d.ts +3 -1
- package/types/signal/signalContext.d.ts +1 -13
- package/types/signal/trace.d.ts +3 -0
- package/types/store/baseSt.d.ts +1 -0
- package/types/store/index.d.ts +17 -17
- package/types/store/stateBuilder.d.ts +2 -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/Reference/origin.d.ts +1 -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/Reference/origin.ts +1 -0
- 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;
|
package/server/console.ts
CHANGED
|
@@ -18,7 +18,7 @@ export interface AkanConsoleOptions {
|
|
|
18
18
|
runtimeDir?: string;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
/** `level=warn grep="payment failed" endpoint=mutation:*` → a query object the socket parses. */
|
|
21
|
+
/** @internal `level=warn grep="payment failed" endpoint=mutation:*` → a query object the socket parses. */
|
|
22
22
|
export const parseAkanConsoleQuery = (args: string): Record<string, string> => {
|
|
23
23
|
const query: Record<string, string> = {};
|
|
24
24
|
for (const match of args.matchAll(/(?<![A-Za-z])([A-Za-z]+)=(?:"([^"]*)"|'([^']*)'|(\S+))/g)) {
|
|
@@ -28,7 +28,7 @@ export const parseAkanConsoleQuery = (args: string): Record<string, string> => {
|
|
|
28
28
|
return query;
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
-
/** Attaches to the running server's control socket, not the console's own `listen: false` server. */
|
|
31
|
+
/** @internal Attaches to the running server's control socket, not the console's own `listen: false` server. */
|
|
32
32
|
export const createAkanConsoleLogCommands = (
|
|
33
33
|
appName: string,
|
|
34
34
|
runtimeDir: string,
|
|
@@ -165,6 +165,7 @@ export const getAkanConsoleMethods = (value: unknown): string[] => {
|
|
|
165
165
|
return [...names].sort((a, b) => a.localeCompare(b));
|
|
166
166
|
};
|
|
167
167
|
|
|
168
|
+
/** @internal */
|
|
168
169
|
export const createAkanConsoleContext = (
|
|
169
170
|
server: AkanServer,
|
|
170
171
|
globals: Record<string, unknown> = {},
|
|
@@ -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
|
+
}
|