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/akanApp.ts
CHANGED
|
@@ -1,26 +1,20 @@
|
|
|
1
1
|
|
|
2
|
-
|
|
3
2
|
import "./lifecycle/loadBuildEnv";
|
|
4
|
-
import { mkdir, readdir, rm } from "node:fs/promises";
|
|
5
|
-
import path from "node:path";
|
|
6
3
|
import { Logger, TrustedProxy } from "akanjs/common";
|
|
7
|
-
import type {
|
|
8
|
-
import {
|
|
9
|
-
import
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
4
|
+
import type { AkanIpcMessage } from "akanjs/service";
|
|
5
|
+
import { resetEnvCache } from "../base/baseEnv";
|
|
6
|
+
import type { BuilderMessage } from "./artifact";
|
|
7
|
+
import { ChildSupervisor } from "./gateway/childSupervisor";
|
|
8
|
+
import { DevHostChannel } from "./gateway/devHostChannel";
|
|
9
|
+
import { GatewayChildren } from "./gateway/gatewayChildren";
|
|
10
|
+
import { type AkanAppOptions, GatewayConfig } from "./gateway/gatewayConfig";
|
|
11
|
+
import { GatewayHttpProxy } from "./gateway/gatewayHttpProxy";
|
|
12
|
+
import { GatewayLogging } from "./gateway/gatewayLogging";
|
|
13
|
+
import { GatewayRooms } from "./gateway/gatewayRooms";
|
|
14
|
+
import { GatewayStatus } from "./gateway/gatewayStatus";
|
|
15
|
+
import { GatewayWebSocketRelay, type GatewayWsData } from "./gateway/gatewayWebSocketRelay";
|
|
16
16
|
import { isPortInUseError } from "./lifecycle/portInUse";
|
|
17
|
-
import { resolveRuntimeDir } from "./lifecycle/runtimeDir";
|
|
18
|
-
import { ChildOutputReader } from "./logging/childOutputReader";
|
|
19
|
-
import { HubFileSink } from "./logging/hubFileSink";
|
|
20
|
-
import { LogControlSocket } from "./logging/logControlSocket";
|
|
21
|
-
import { LogHub } from "./logging/logHub";
|
|
22
17
|
import { LogStreamRoute } from "./logging/logStreamRoute";
|
|
23
|
-
import { RotatingLogWriter } from "./logging/rotatingLogWriter";
|
|
24
18
|
import { AppInfo } from "./ops/appInfo";
|
|
25
19
|
import type { OpsHost } from "./ops/opsCommand";
|
|
26
20
|
import type { OpsRoute } from "./ops/opsRoute";
|
|
@@ -29,235 +23,65 @@ import { ProcessMetricsCollector } from "./processMetricsCollector";
|
|
|
29
23
|
import { HostAllowlist } from "./routing/hostAllowlist";
|
|
30
24
|
import { RouteHosts } from "./routing/routeHosts";
|
|
31
25
|
import { ServerLimits } from "./routing/serverLimits";
|
|
32
|
-
import { WsUpgrade } from "./routing/wsUpgrade";
|
|
33
26
|
import { SelfExec } from "./selfExec";
|
|
34
|
-
import { resolveStaticPath } from "./staticPath";
|
|
35
|
-
import { getWebConfigFromEnv } from "./types";
|
|
36
27
|
|
|
37
|
-
|
|
38
|
-
idx: number;
|
|
39
|
-
role: AkanChildRole;
|
|
40
|
-
proc: Bun.Subprocess<"ignore", "pipe", "pipe">;
|
|
41
|
-
ready: boolean;
|
|
42
|
-
status: AkanChildStatus;
|
|
43
|
-
pid?: number;
|
|
44
|
-
upstream?: AkanUpstream;
|
|
45
|
-
wsUpstream?: Extract<AkanUpstream, { type: "tcp" }>;
|
|
46
|
-
healthPath?: string;
|
|
47
|
-
metrics: AkanMetricsReport;
|
|
48
|
-
/** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
|
|
49
|
-
lastPongAtMono?: number;
|
|
50
|
-
restart: RestartSchedule;
|
|
51
|
-
restartCount: number;
|
|
52
|
-
restartPending: boolean;
|
|
53
|
-
lastExitCode?: number | null;
|
|
54
|
-
lastRestartAt?: number;
|
|
55
|
-
lastRestartReason?: string;
|
|
56
|
-
lastErrorMessage?: string;
|
|
57
|
-
}
|
|
28
|
+
export type { AkanAppOptions } from "./gateway/gatewayConfig";
|
|
58
29
|
|
|
59
30
|
interface SoloServer {
|
|
60
31
|
start: (options: { listen: boolean }) => Promise<unknown>;
|
|
61
32
|
}
|
|
62
33
|
|
|
63
|
-
interface GatewayWsData {
|
|
64
|
-
childIdx: number;
|
|
65
|
-
upstream: WebSocket;
|
|
66
|
-
clientIp: string | null;
|
|
67
|
-
pending: (string | ArrayBuffer)[];
|
|
68
|
-
pendingBytes: number;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
type GatewayUpstream = {
|
|
72
|
-
http: Extract<AkanUpstream, { type: "unix" }>;
|
|
73
|
-
ws?: Extract<AkanUpstream, { type: "tcp" }>;
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const relayableCloseCode = (code: number): number => {
|
|
77
|
-
if (code >= 3000 && code <= 4999) return code;
|
|
78
|
-
if (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) return code;
|
|
79
|
-
return 1001;
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
export interface AkanAppOptions {
|
|
83
|
-
replica?: number | string;
|
|
84
|
-
serverPath?: string;
|
|
85
|
-
runtimeDir?: string;
|
|
86
|
-
port?: number;
|
|
87
|
-
wsBasePort?: number;
|
|
88
|
-
openapi?: boolean;
|
|
89
|
-
/** Signal endpoint mount, `/api` by default; handed down as `AKAN_API_PREFIX` (CSR/mobile follow akan.config.ts). */
|
|
90
|
-
prefix?: string;
|
|
91
|
-
/** Where the websocket upgrade sits under `prefix`, `/ws` by default. Handed down as `AKAN_WS_PREFIX`. */
|
|
92
|
-
websocketPrefix?: string;
|
|
93
|
-
/** Boot only these modules and what they reach; omitted or empty mounts every enabled one. `AKAN_MODULES`. */
|
|
94
|
-
modules?: string[];
|
|
95
|
-
/** Mount all but these and whatever reaches them, applied after `modules`. `AKAN_DISABLE_MODULES`. */
|
|
96
|
-
disableModules?: string[];
|
|
97
|
-
/** Like `disableModules`, by owning lib. `AKAN_DISABLE_LIBS`. */
|
|
98
|
-
disableLibs?: string[];
|
|
99
|
-
/** In-process replica; default on for one env-set traffic replica, off if `replica` is passed or AKAN_SOLO=false. */
|
|
100
|
-
solo?: boolean;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
interface AkanReplicaConfig {
|
|
104
|
-
federation: number;
|
|
105
|
-
batch: number;
|
|
106
|
-
all: number;
|
|
107
|
-
total: number;
|
|
108
|
-
value: string;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
34
|
export class AkanApp {
|
|
112
|
-
static readonly #childRestartGraceMs = 5_000;
|
|
113
|
-
static readonly #devMaxChildBootFailures = 3;
|
|
114
|
-
|
|
115
35
|
readonly logger = new Logger("AkanApp");
|
|
116
|
-
readonly #
|
|
117
|
-
readonly #
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
readonly #
|
|
123
|
-
readonly #
|
|
124
|
-
|
|
125
|
-
readonly #printChildStderr = process.env.AKAN_CHILD_STDERR === "1";
|
|
126
|
-
readonly #serverPath: string;
|
|
127
|
-
readonly #artifactDir: string;
|
|
128
|
-
readonly #replica: AkanReplicaConfig;
|
|
129
|
-
readonly #runtimeDir: string;
|
|
130
|
-
readonly #socketRunId = `${process.pid}-${Date.now().toString(36)}`;
|
|
131
|
-
readonly #port: number;
|
|
132
|
-
readonly #wsBasePort: number;
|
|
133
|
-
readonly #openapi?: boolean;
|
|
134
|
-
readonly #prefix: string;
|
|
135
|
-
readonly #websocketPrefix: string;
|
|
136
|
-
readonly #web = getWebConfigFromEnv();
|
|
137
|
-
readonly #modules: string[];
|
|
138
|
-
readonly #disableModules: string[];
|
|
139
|
-
readonly #disableLibs: string[];
|
|
140
|
-
readonly #solo: boolean;
|
|
141
|
-
readonly #children = new Map<number, ChildState>();
|
|
142
|
-
readonly #roomChildren = new Map<string, Set<number>>();
|
|
143
|
-
readonly #childRooms = new Map<number, Map<string, Set<string>>>();
|
|
144
|
-
readonly #socketRooms = new Map<string, { childIdx: number; rooms: Set<string> }>();
|
|
145
|
-
readonly #childLiveModels = new Map<number, Set<string>>();
|
|
146
|
-
#nextBuilderReqId = 1;
|
|
147
|
-
readonly #builderReqMap = new Map<number, { childIdx: number; childLocalId: number }>();
|
|
36
|
+
readonly #config: GatewayConfig;
|
|
37
|
+
readonly #children: GatewayChildren;
|
|
38
|
+
readonly #logging: GatewayLogging;
|
|
39
|
+
readonly #rooms: GatewayRooms;
|
|
40
|
+
readonly #host: DevHostChannel;
|
|
41
|
+
readonly #supervisor: ChildSupervisor;
|
|
42
|
+
readonly #status: GatewayStatus;
|
|
43
|
+
readonly #proxy: GatewayHttpProxy;
|
|
44
|
+
readonly #ws: GatewayWebSocketRelay;
|
|
148
45
|
#server: Bun.Server<GatewayWsData> | null = null;
|
|
149
|
-
#rrIdx = 0;
|
|
150
|
-
#federationChildCache: ChildState[] | null = null;
|
|
151
46
|
#snapshotTimer: Timer | null = null;
|
|
152
47
|
#healthTimer: Timer | null = null;
|
|
153
48
|
#metricsTimer: Timer | null = null;
|
|
154
|
-
#logWriter: RotatingLogWriter | null = null;
|
|
155
|
-
#detachFileLog: (() => void) | null = null;
|
|
156
|
-
#logHub: LogHub | null = null;
|
|
157
|
-
#logControl: LogControlSocket | null = null;
|
|
158
|
-
#logStream: LogStreamRoute | null = null;
|
|
159
49
|
#ops: OpsRoute | null = null;
|
|
160
50
|
#hostAllowlist = HostAllowlist.fromEnv();
|
|
161
51
|
readonly #limits = new ServerLimits();
|
|
162
|
-
|
|
163
|
-
static readonly #wsPendingLimitBytes = 1024 * 1024;
|
|
164
|
-
static readonly #wsUpstreamOpenTimeoutMs = 10_000;
|
|
165
|
-
readonly #wsCaps = {
|
|
166
|
-
total: AkanApp.#positiveIntEnv("AKAN_MAX_WEBSOCKETS"),
|
|
167
|
-
perIp: AkanApp.#positiveIntEnv("AKAN_MAX_WEBSOCKETS_PER_IP"),
|
|
168
|
-
};
|
|
169
|
-
#wsOpen = 0;
|
|
170
|
-
readonly #wsOpenByIp = new Map<string, number>();
|
|
171
52
|
readonly #statusAccess = StatusAccess.fromEnv();
|
|
172
|
-
static readonly #ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
|
|
173
|
-
#gatewayMetrics: AkanMetricsReport = {};
|
|
174
|
-
#proxyHopCount = 0;
|
|
175
|
-
#proxyHopSumMs = 0;
|
|
176
|
-
#proxyHopMaxMs = 0;
|
|
177
53
|
#resolveStopped: (() => void) | null = null;
|
|
178
54
|
#exitAfterStop = false;
|
|
179
|
-
#stopping = false;
|
|
180
55
|
|
|
181
56
|
constructor(serverPathOrOptions: string | AkanAppOptions = "./server", options: AkanAppOptions = {}) {
|
|
182
57
|
SelfExec.adopt();
|
|
183
58
|
const resolvedOptions = typeof serverPathOrOptions === "string" ? options : serverPathOrOptions;
|
|
184
59
|
const serverPath = typeof serverPathOrOptions === "string" ? serverPathOrOptions : "./server";
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
const baseDir = path.dirname(Bun.main);
|
|
211
|
-
const resolved = path.isAbsolute(serverPath) ? serverPath : path.resolve(baseDir, serverPath);
|
|
212
|
-
if (path.extname(resolved)) return resolved;
|
|
213
|
-
return Bun.main.endsWith(".js") ? `${resolved}.js` : `${resolved}.ts`;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
static #parseReplicaConfig(value?: number | string): AkanReplicaConfig {
|
|
217
|
-
const configured = value ?? process.env.AKAN_REPLICA;
|
|
218
|
-
const raw = String(configured ?? "0,0,1").trim();
|
|
219
|
-
const [federationRaw, batchRaw, allRaw] = raw.split(",");
|
|
220
|
-
const federation = AkanApp.#parseReplicaCount(federationRaw, 0);
|
|
221
|
-
const batch = AkanApp.#parseReplicaCount(batchRaw, 0);
|
|
222
|
-
const all = AkanApp.#parseReplicaCount(allRaw, configured == null ? 1 : 0);
|
|
223
|
-
const normalizedAll = federation + batch + all > 0 ? all : 1;
|
|
224
|
-
return {
|
|
225
|
-
federation,
|
|
226
|
-
batch,
|
|
227
|
-
all: normalizedAll,
|
|
228
|
-
total: federation + batch + normalizedAll,
|
|
229
|
-
value: `${federation},${batch},${normalizedAll}`,
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
static #parseReplicaCount(value: string | undefined, fallback: number) {
|
|
234
|
-
const parsed = Number.parseInt(value ?? "", 10);
|
|
235
|
-
return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
static #defaultChildNodeEnv() {
|
|
239
|
-
if (process.env.AKAN_COMMAND_TYPE === "start") return "development";
|
|
240
|
-
if (process.env.AKAN_COMMAND_TYPE === "build") return "production";
|
|
241
|
-
if (process.env.NODE_ENV) return process.env.NODE_ENV;
|
|
242
|
-
return Bun.main.endsWith(".js") ? "production" : "development";
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
static #parseHealthTimeoutMs() {
|
|
246
|
-
const configured = Number(process.env.AKAN_HEALTH_TIMEOUT_MS);
|
|
247
|
-
if (Number.isFinite(configured) && configured > 0) return configured;
|
|
248
|
-
return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
static #parseUpstreamWaitMs() {
|
|
252
|
-
const configured = Number(process.env.AKAN_UPSTREAM_WAIT_MS);
|
|
253
|
-
if (Number.isFinite(configured) && configured >= 0) return configured;
|
|
254
|
-
return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
static #childShutdownWaitMs() {
|
|
258
|
-
const configured = Number(process.env.AKAN_CHILD_SHUTDOWN_WAIT_MS);
|
|
259
|
-
if (Number.isFinite(configured) && configured > 0) return configured;
|
|
260
|
-
return process.env.AKAN_COMMAND_TYPE === "start" ? 5_000 : 30_000;
|
|
60
|
+
const logger = this.logger;
|
|
61
|
+
const config = new GatewayConfig(serverPath, resolvedOptions);
|
|
62
|
+
const children = new GatewayChildren(logger);
|
|
63
|
+
const logging = new GatewayLogging(config, children, logger);
|
|
64
|
+
const rooms = new GatewayRooms(children, logger);
|
|
65
|
+
const host = new DevHostChannel(children, logger);
|
|
66
|
+
const supervisor = new ChildSupervisor({
|
|
67
|
+
config,
|
|
68
|
+
children,
|
|
69
|
+
rooms,
|
|
70
|
+
logging,
|
|
71
|
+
host,
|
|
72
|
+
logger,
|
|
73
|
+
onMessage: (idx, message, proc) => this.#handleMessage(idx, message, proc),
|
|
74
|
+
});
|
|
75
|
+
const status = new GatewayStatus(config, children, rooms, logger);
|
|
76
|
+
this.#config = config;
|
|
77
|
+
this.#children = children;
|
|
78
|
+
this.#logging = logging;
|
|
79
|
+
this.#rooms = rooms;
|
|
80
|
+
this.#host = host;
|
|
81
|
+
this.#supervisor = supervisor;
|
|
82
|
+
this.#status = status;
|
|
83
|
+
this.#proxy = new GatewayHttpProxy({ config, children, supervisor, status, limits: this.#limits, logger });
|
|
84
|
+
this.#ws = new GatewayWebSocketRelay(config, children);
|
|
261
85
|
}
|
|
262
86
|
|
|
263
87
|
async start() {
|
|
@@ -267,31 +91,35 @@ export class AkanApp {
|
|
|
267
91
|
await OpsCommand.run(process.argv.slice(3), { importServer: async () => await this.#importServer() }),
|
|
268
92
|
);
|
|
269
93
|
}
|
|
270
|
-
if (this.#solo) return await this.#startSolo();
|
|
94
|
+
if (this.#config.solo) return await this.#startSolo();
|
|
271
95
|
if (SelfExec.carried)
|
|
272
96
|
throw new Error(
|
|
273
97
|
"A desktop app's server runs in one process, and this one was asked for a gateway and replicas, which would start with the `bun` on the user's PATH: by `replica` or `solo: false` in main.ts, or by AKAN_SOLO=false, an AKAN_REPLICA other than one traffic replica, or AKAN_COMMAND_TYPE=start in its env. Leave them out of the app the desktop build carries.",
|
|
274
98
|
);
|
|
275
99
|
Logger.role = "gateway";
|
|
276
|
-
await this.#prepareRuntimeDir();
|
|
277
|
-
await this.#
|
|
278
|
-
this.#startFileLogging();
|
|
100
|
+
await this.#supervisor.prepareRuntimeDir();
|
|
101
|
+
await this.#logging.start();
|
|
279
102
|
await this.#startOps();
|
|
280
|
-
|
|
103
|
+
|
|
104
|
+
if (this.#children.stopping) {
|
|
105
|
+
await this.#logging.stop();
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
for (let idx = 0; idx < this.#config.replica.total; idx++) this.#supervisor.spawn(idx);
|
|
281
109
|
try {
|
|
282
110
|
this.#listen();
|
|
283
111
|
} catch (error) {
|
|
284
112
|
if (isPortInUseError(error)) {
|
|
285
|
-
const message = `Port ${this.#port} is already in use — another \`akan start\` or an orphaned gateway may still be running (try: lsof -ti :${this.#port}).`;
|
|
113
|
+
const message = `Port ${this.#config.port} is already in use — another \`akan start\` or an orphaned gateway may still be running (try: lsof -ti :${this.#config.port}).`;
|
|
286
114
|
this.logger.error(message);
|
|
287
|
-
this.#reportBackendBuildStatus({ ok: false, message });
|
|
115
|
+
this.#host.reportBackendBuildStatus({ ok: false, message });
|
|
288
116
|
}
|
|
289
117
|
await this.stop("listen-failed");
|
|
290
118
|
throw error;
|
|
291
119
|
}
|
|
292
|
-
this.#snapshotTimer = setInterval(() => this.#requestRoomSnapshots(), 30_000);
|
|
293
|
-
this.#healthTimer = setInterval(() => this.#checkHealth(), 2_000);
|
|
294
|
-
this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#reportMetrics());
|
|
120
|
+
this.#snapshotTimer = setInterval(() => this.#rooms.requestRoomSnapshots(), 30_000);
|
|
121
|
+
this.#healthTimer = setInterval(() => this.#supervisor.checkHealth(), 2_000);
|
|
122
|
+
this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#status.reportMetrics());
|
|
295
123
|
process.on("message", (message) => this.#handleHostMessage(message as BuilderMessage));
|
|
296
124
|
process.on("disconnect", () => this.#handleHostDisconnect());
|
|
297
125
|
process.on("SIGINT", () => this.#handleShutdownSignal("SIGINT"));
|
|
@@ -302,55 +130,42 @@ export class AkanApp {
|
|
|
302
130
|
}
|
|
303
131
|
|
|
304
132
|
async #importServer() {
|
|
305
|
-
Object.assign(process.env, this.#childEnv(0, this.#
|
|
133
|
+
Object.assign(process.env, this.#config.childEnv(0, this.#config.roleOf(0)), { AKAN_COMMAND_TYPE: "script" });
|
|
306
134
|
resetEnvCache();
|
|
307
|
-
return (await import(this.#serverPath)) as Awaited<ReturnType<OpsHost["importServer"]>>;
|
|
135
|
+
return (await import(this.#config.serverPath)) as Awaited<ReturnType<OpsHost["importServer"]>>;
|
|
308
136
|
}
|
|
309
137
|
|
|
310
138
|
async #startSolo() {
|
|
311
|
-
const role = this.#
|
|
139
|
+
const role = this.#config.roleOf(0);
|
|
312
140
|
|
|
313
|
-
Object.assign(process.env, this.#childEnv(0, role));
|
|
141
|
+
Object.assign(process.env, this.#config.childEnv(0, role));
|
|
314
142
|
|
|
315
143
|
resetEnvCache();
|
|
316
144
|
this.logger.info(`Starting ${role} replica in this process (solo); set AKAN_SOLO=false for the gateway`);
|
|
317
|
-
const mod = (await import(this.#serverPath)) as { server?: SoloServer; app?: SoloServer };
|
|
145
|
+
const mod = (await import(this.#config.serverPath)) as { server?: SoloServer; app?: SoloServer };
|
|
318
146
|
const server = mod.server ?? mod.app;
|
|
319
147
|
if (!server?.start) throw new Error("server.ts must export server or app with start()");
|
|
320
148
|
await server.start({ listen: true });
|
|
321
149
|
}
|
|
322
150
|
|
|
323
151
|
async stop(signal = "SIGTERM") {
|
|
324
|
-
if (this.#stopping) return;
|
|
325
|
-
this.#
|
|
152
|
+
if (this.#children.stopping) return;
|
|
153
|
+
this.#children.markStopping();
|
|
326
154
|
for (const timer of [this.#snapshotTimer, this.#healthTimer, this.#metricsTimer]) if (timer) clearInterval(timer);
|
|
327
155
|
this.#snapshotTimer = null;
|
|
328
156
|
this.#healthTimer = null;
|
|
329
157
|
this.#metricsTimer = null;
|
|
330
158
|
this.#server?.stop(true);
|
|
331
159
|
this.#server = null;
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
this.#sendToChild(child, { type: "shutdown", signal } satisfies AkanIpcMessage);
|
|
335
|
-
}
|
|
336
|
-
await Promise.race([
|
|
337
|
-
Promise.all([...this.#children.values()].map((child) => child.proc.exited.catch(() => undefined))),
|
|
338
|
-
new Promise((resolve) => setTimeout(resolve, AkanApp.#childShutdownWaitMs())),
|
|
339
|
-
]);
|
|
340
|
-
|
|
341
|
-
const stragglers = [...this.#children.values()].filter((child) => !child.proc.killed);
|
|
342
|
-
for (const child of stragglers) child.proc.kill("SIGKILL");
|
|
343
|
-
await Promise.all(stragglers.map((child) => child.proc.exited.catch(() => undefined)));
|
|
344
|
-
this.#children.clear();
|
|
345
|
-
await this.#stopLogHub();
|
|
346
|
-
await this.#stopFileLogging();
|
|
160
|
+
await this.#supervisor.stopAll(signal);
|
|
161
|
+
await this.#logging.stop();
|
|
347
162
|
this.#resolveStopped?.();
|
|
348
163
|
this.#resolveStopped = null;
|
|
349
164
|
if (this.#exitAfterStop) process.exit(0);
|
|
350
165
|
}
|
|
351
166
|
|
|
352
167
|
#handleShutdownSignal(signal: NodeJS.Signals) {
|
|
353
|
-
if (this.#stopping) process.exit(1);
|
|
168
|
+
if (this.#children.stopping) process.exit(1);
|
|
354
169
|
this.#exitAfterStop = true;
|
|
355
170
|
void this.stop(signal).catch((error) => {
|
|
356
171
|
this.logger.error(`Failed to shutdown gateway: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -359,247 +174,13 @@ export class AkanApp {
|
|
|
359
174
|
}
|
|
360
175
|
|
|
361
176
|
#handleHostDisconnect() {
|
|
362
|
-
if (this.#stopping) return;
|
|
177
|
+
if (this.#children.stopping) return;
|
|
363
178
|
this.logger.warn("Host IPC channel closed; shutting down gateway and children");
|
|
364
179
|
this.#exitAfterStop = true;
|
|
365
|
-
setTimeout(() => process.exit(1),
|
|
180
|
+
setTimeout(() => process.exit(1), GatewayConfig.childShutdownWaitMs() + 5_000);
|
|
366
181
|
void this.stop("ipc-disconnect").catch(() => process.exit(1));
|
|
367
182
|
}
|
|
368
183
|
|
|
369
|
-
#spawn(idx: number) {
|
|
370
|
-
const role = this.#getRole(idx);
|
|
371
|
-
const upstream = this.#getChildUpstream(idx, role);
|
|
372
|
-
|
|
373
|
-
const childCode = `import(${JSON.stringify(path.resolve(this.#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); });`;
|
|
374
|
-
const proc: Bun.Subprocess<"ignore", "pipe", "pipe"> = Bun.spawn(["bun", "-e", childCode], {
|
|
375
|
-
cwd: process.cwd(),
|
|
376
|
-
env: {
|
|
377
|
-
...process.env,
|
|
378
|
-
|
|
379
|
-
...this.#childEnv(idx, role),
|
|
380
|
-
AKAN_CHILD_SOCKET: upstream.http.socketPath,
|
|
381
|
-
AKAN_CHILD_WS_PORT: upstream.ws ? String(upstream.ws.port) : "",
|
|
382
|
-
...(this.#printChildStderr || Logger.isNdjson ? {} : { AKAN_CHILD_STDERR_HIDDEN: "1" }),
|
|
383
|
-
},
|
|
384
|
-
ipc: (message) => this.#handleMessage(idx, message as AkanIpcMessage, proc),
|
|
385
|
-
stdout: "pipe",
|
|
386
|
-
stderr: "pipe",
|
|
387
|
-
stdin: "ignore",
|
|
388
|
-
});
|
|
389
|
-
const previous = this.#children.get(idx);
|
|
390
|
-
this.#children.set(idx, {
|
|
391
|
-
idx,
|
|
392
|
-
role,
|
|
393
|
-
proc,
|
|
394
|
-
ready: false,
|
|
395
|
-
status: "starting",
|
|
396
|
-
metrics: {},
|
|
397
|
-
|
|
398
|
-
restart: previous?.restart ?? new RestartSchedule(this.#childRestartPolicy),
|
|
399
|
-
restartCount: previous?.restartCount ?? 0,
|
|
400
|
-
restartPending: false,
|
|
401
|
-
lastExitCode: previous?.lastExitCode,
|
|
402
|
-
lastRestartAt: previous?.lastRestartAt,
|
|
403
|
-
lastRestartReason: previous?.lastRestartReason,
|
|
404
|
-
});
|
|
405
|
-
this.#federationChildCache = null;
|
|
406
|
-
const output = new ChildOutputReader({
|
|
407
|
-
onLine: (line) => this.#writeChildLine(idx, role, proc.pid, "stdout", line),
|
|
408
|
-
onBlock: (lines) => this.#writeChildStderrBlock(idx, role, proc.pid, lines),
|
|
409
|
-
});
|
|
410
|
-
void output.pipe(proc.stdout, "stdout");
|
|
411
|
-
void output.pipe(proc.stderr, "stderr");
|
|
412
|
-
proc.exited.then((code) => this.#handleChildExit(idx, proc, code));
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
#childEnv(idx: number, role: AkanChildRole) {
|
|
416
|
-
return {
|
|
417
|
-
PORT: String(this.#port),
|
|
418
|
-
NODE_ENV: AkanApp.#defaultChildNodeEnv(),
|
|
419
|
-
AKAN_REPLICA: this.#replica.value,
|
|
420
|
-
AKAN_REPLICA_IDX: String(idx),
|
|
421
|
-
AKAN_APP_DIR: path.dirname(this.#serverPath),
|
|
422
|
-
SERVER_MODE: role,
|
|
423
|
-
AKAN_API_PREFIX: this.#prefix,
|
|
424
|
-
AKAN_WS_PREFIX: this.#websocketPrefix,
|
|
425
|
-
...(this.#openapi === undefined ? {} : { AKAN_OPENAPI: this.#openapi ? "true" : "false" }),
|
|
426
|
-
...(this.#modules.length ? { AKAN_MODULES: this.#modules.join(",") } : {}),
|
|
427
|
-
...(this.#disableModules.length ? { AKAN_DISABLE_MODULES: this.#disableModules.join(",") } : {}),
|
|
428
|
-
...(this.#disableLibs.length ? { AKAN_DISABLE_LIBS: this.#disableLibs.join(",") } : {}),
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
#handleChildExit(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, code: number | null) {
|
|
433
|
-
const child = this.#children.get(idx);
|
|
434
|
-
if (!child || child.proc !== proc) return;
|
|
435
|
-
if (child.status === "crashed") return;
|
|
436
|
-
child.status = "exited";
|
|
437
|
-
child.lastExitCode = code;
|
|
438
|
-
this.#federationChildCache = null;
|
|
439
|
-
this.#removeChildRooms(idx);
|
|
440
|
-
if (this.#stopping) return;
|
|
441
|
-
void this.#scheduleChildRestart(child, proc, `exit:${code ?? "unknown"}`);
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
#scheduleChildRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string): void {
|
|
445
|
-
if (this.#stopping) return;
|
|
446
|
-
if (child.proc !== proc) return;
|
|
447
|
-
if (child.restartPending || child.restart.pending) {
|
|
448
|
-
child.lastRestartReason = reason;
|
|
449
|
-
return;
|
|
450
|
-
}
|
|
451
|
-
if (child.restart.exhausted && !child.ready) {
|
|
452
|
-
this.#markChildCrashed(child, reason);
|
|
453
|
-
return;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
child.restartPending = true;
|
|
457
|
-
child.ready = false;
|
|
458
|
-
child.status = reason === "health-timeout" || reason === "upstream-open-failed" ? "unhealthy" : "exited";
|
|
459
|
-
child.upstream = undefined;
|
|
460
|
-
child.wsUpstream = undefined;
|
|
461
|
-
child.healthPath = undefined;
|
|
462
|
-
this.#federationChildCache = null;
|
|
463
|
-
child.lastRestartReason = reason;
|
|
464
|
-
child.lastRestartAt = Date.now();
|
|
465
|
-
this.#removeChildRooms(child.idx);
|
|
466
|
-
|
|
467
|
-
const delay = child.restart.next();
|
|
468
|
-
child.restartCount += 1;
|
|
469
|
-
this.logger.error(
|
|
470
|
-
`Child ${child.idx}/${child.role} failed (${reason}); restarting in ${delay}ms (attempt ${child.restart.attempts})`,
|
|
471
|
-
);
|
|
472
|
-
|
|
473
|
-
void this.#restartChildAfterDelay(child.idx, proc, reason, delay).catch((error) => {
|
|
474
|
-
const current = this.#children.get(child.idx);
|
|
475
|
-
if (!current || current.proc !== proc || this.#stopping) return;
|
|
476
|
-
current.restartPending = false;
|
|
477
|
-
this.logger.error(
|
|
478
|
-
`Failed to restart child ${child.idx}/${child.role}: ${error instanceof Error ? error.message : String(error)}`,
|
|
479
|
-
);
|
|
480
|
-
this.#scheduleChildRestart(current, proc, "restart-failed");
|
|
481
|
-
});
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
async #restartChildAfterDelay(
|
|
485
|
-
idx: number,
|
|
486
|
-
proc: Bun.Subprocess<"ignore", "pipe", "pipe">,
|
|
487
|
-
reason: string,
|
|
488
|
-
delay: number,
|
|
489
|
-
) {
|
|
490
|
-
const child = this.#children.get(idx);
|
|
491
|
-
if (!child || child.proc !== proc || this.#stopping) return;
|
|
492
|
-
await this.#stopChildForRestart(child, proc, reason);
|
|
493
|
-
if (this.#stopping) return;
|
|
494
|
-
const current = this.#children.get(idx);
|
|
495
|
-
if (!current || current.proc !== proc) return;
|
|
496
|
-
current.restart.arm(delay, () => {
|
|
497
|
-
void this.#respawnChild(idx, proc).catch((error) => {
|
|
498
|
-
const latest = this.#children.get(idx);
|
|
499
|
-
if (!latest || latest.proc !== proc || this.#stopping) return;
|
|
500
|
-
latest.restartPending = false;
|
|
501
|
-
this.logger.error(
|
|
502
|
-
`Failed to respawn child ${idx}/${latest.role}: ${error instanceof Error ? error.message : String(error)}`,
|
|
503
|
-
);
|
|
504
|
-
this.#scheduleChildRestart(latest, proc, "respawn-failed");
|
|
505
|
-
});
|
|
506
|
-
});
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
async #respawnChild(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">) {
|
|
510
|
-
if (this.#stopping) return;
|
|
511
|
-
const current = this.#children.get(idx);
|
|
512
|
-
if (!current || current.proc !== proc) return;
|
|
513
|
-
await this.#removeChildSocket(idx, current.role);
|
|
514
|
-
if (this.#stopping) return;
|
|
515
|
-
current.restartPending = false;
|
|
516
|
-
this.#spawn(idx);
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
#markChildCrashed(child: ChildState, reason: string) {
|
|
520
|
-
|
|
521
|
-
if (child.status === "crashed") return;
|
|
522
|
-
child.ready = false;
|
|
523
|
-
child.status = "crashed";
|
|
524
|
-
child.restartPending = false;
|
|
525
|
-
child.upstream = undefined;
|
|
526
|
-
child.wsUpstream = undefined;
|
|
527
|
-
child.healthPath = undefined;
|
|
528
|
-
child.lastRestartReason = reason;
|
|
529
|
-
this.#federationChildCache = null;
|
|
530
|
-
this.#removeChildRooms(child.idx);
|
|
531
|
-
const attempts = child.restart.attempts + 1;
|
|
532
|
-
const detail = child.lastErrorMessage ?? reason;
|
|
533
|
-
const message = `Backend replica ${child.idx}/${child.role} failed ${attempts} consecutive boots; waiting for a code change to retry: ${detail}`;
|
|
534
|
-
this.logger.error(`[child-crash-loop] ${message}`);
|
|
535
|
-
this.#reportBackendBuildStatus({ ok: false, message });
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
#reportBackendBuildStatus({ ok, message }: { ok: boolean; message: string }) {
|
|
539
|
-
process.send?.({
|
|
540
|
-
type: "build-status",
|
|
541
|
-
data: { generation: -1, phase: "backend", ok, files: [], message },
|
|
542
|
-
} satisfies BuilderMessage);
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
#isChildUnavailable(child: ChildState): boolean {
|
|
546
|
-
return child.proc.killed || child.status === "exited" || child.status === "crashed";
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
async #stopChildForRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string) {
|
|
550
|
-
if (reason.startsWith("exit:") || proc.killed) return;
|
|
551
|
-
this.#sendToChild(child, { type: "shutdown", signal: reason } satisfies AkanIpcMessage);
|
|
552
|
-
const result = await Promise.race([
|
|
553
|
-
proc.exited.then(() => "exited" as const).catch(() => "exited" as const),
|
|
554
|
-
new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), AkanApp.#childRestartGraceMs)),
|
|
555
|
-
]);
|
|
556
|
-
if (result === "timeout" && !proc.killed) {
|
|
557
|
-
this.logger.warn(`Child ${child.idx}/${child.role} did not stop in ${AkanApp.#childRestartGraceMs}ms; killing`);
|
|
558
|
-
proc.kill();
|
|
559
|
-
await proc.exited.catch(() => undefined);
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
async #prepareRuntimeDir() {
|
|
564
|
-
await mkdir(this.#runtimeDir, { recursive: true });
|
|
565
|
-
|
|
566
|
-
const entries = await readdir(this.#runtimeDir).catch(() => []);
|
|
567
|
-
await Promise.all(
|
|
568
|
-
entries
|
|
569
|
-
.filter((name) => /^akan-(child-.*|control)\.sock$/.test(name))
|
|
570
|
-
.map((name) => rm(path.join(this.#runtimeDir, name), { force: true }).catch(() => undefined)),
|
|
571
|
-
);
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
async #removeChildSocket(idx: number, role: AkanChildRole) {
|
|
575
|
-
const socketPath = this.#getChildUpstream(idx, role).http.socketPath;
|
|
576
|
-
try {
|
|
577
|
-
await rm(socketPath, { force: true });
|
|
578
|
-
} catch {
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
#startFileLogging() {
|
|
583
|
-
this.#logWriter = RotatingLogWriter.fromRuntimeDir(this.#runtimeDir);
|
|
584
|
-
if (this.#logWriter) this.#detachFileLog = HubFileSink.attach(this.#logWriter, this.#logHub, "gateway");
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
async #stopFileLogging() {
|
|
588
|
-
this.#detachFileLog?.();
|
|
589
|
-
this.#detachFileLog = null;
|
|
590
|
-
const writer = this.#logWriter;
|
|
591
|
-
this.#logWriter = null;
|
|
592
|
-
await writer?.close();
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
async #startLogHub() {
|
|
596
|
-
const hub = LogHub.attach();
|
|
597
|
-
this.#logHub = hub;
|
|
598
|
-
hub.onFloorChange((minSev) => this.#fanoutToAll({ type: "log.level", minSev }));
|
|
599
|
-
this.#logStream = LogStreamRoute.fromEnv(() => this.#logHub);
|
|
600
|
-
this.#logControl = await LogControlSocket.open(hub, this.#runtimeDir, this.logger);
|
|
601
|
-
}
|
|
602
|
-
|
|
603
184
|
async #startOps() {
|
|
604
185
|
if (!process.env.AKAN_OPS_PUBLIC_KEY?.trim()) return;
|
|
605
186
|
const { OpsRoute } = await import("./ops/opsRoute");
|
|
@@ -608,21 +189,13 @@ export class AkanApp {
|
|
|
608
189
|
});
|
|
609
190
|
}
|
|
610
191
|
|
|
611
|
-
async #stopLogHub() {
|
|
612
|
-
await this.#logControl?.stop();
|
|
613
|
-
this.#logControl = null;
|
|
614
|
-
this.#logStream = null;
|
|
615
|
-
this.#logHub?.close();
|
|
616
|
-
this.#logHub = null;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
192
|
#listen() {
|
|
620
193
|
|
|
621
|
-
if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#artifactDir);
|
|
194
|
+
if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
|
|
622
195
|
this.#server = Bun.serve({
|
|
623
196
|
idleTimeout: this.#limits.idleTimeout,
|
|
624
197
|
maxRequestBodySize: this.#limits.uploadBodyBytes,
|
|
625
|
-
port: this.#port,
|
|
198
|
+
port: this.#config.port,
|
|
626
199
|
hostname: ServerLimits.listenHostname(),
|
|
627
200
|
fetch: (req, server) =>
|
|
628
201
|
ServerLimits.holdOpen(server, req, this.#limits.idleTimeout, () => this.#handleFetch(req, server)),
|
|
@@ -631,13 +204,13 @@ export class AkanApp {
|
|
|
631
204
|
maxPayloadLength: 16 * 1024 * 1024,
|
|
632
205
|
backpressureLimit: 1024 * 1024,
|
|
633
206
|
closeOnBackpressureLimit: true,
|
|
634
|
-
open: (ws) => this.#
|
|
635
|
-
message: (ws, message) => this.#
|
|
636
|
-
close: (ws, code, reason) => this.#
|
|
207
|
+
open: (ws) => this.#ws.open(ws),
|
|
208
|
+
message: (ws, message) => this.#ws.message(ws, message),
|
|
209
|
+
close: (ws, code, reason) => this.#ws.close(ws, code, reason),
|
|
637
210
|
data: {} as GatewayWsData,
|
|
638
211
|
},
|
|
639
212
|
});
|
|
640
|
-
this.logger.info(`AkanApp gateway is running on port http://localhost:${this.#port}`);
|
|
213
|
+
this.logger.info(`AkanApp gateway is running on port http://localhost:${this.#config.port}`);
|
|
641
214
|
}
|
|
642
215
|
|
|
643
216
|
async #handleFetch(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response | undefined> {
|
|
@@ -646,485 +219,26 @@ export class AkanApp {
|
|
|
646
219
|
if (oversized) return oversized;
|
|
647
220
|
const url = new URL(req.url);
|
|
648
221
|
if (url.pathname === "/_akan/app/health")
|
|
649
|
-
return this.#statusAccess.health(req, () => this.#
|
|
222
|
+
return this.#statusAccess.health(req, () => this.#status.healthStatus(), AkanApp.#clientOf(req, server));
|
|
650
223
|
if (url.pathname === "/_akan/app/ready")
|
|
651
|
-
return this.#statusAccess.ready(req, () => this.#
|
|
224
|
+
return this.#statusAccess.ready(req, () => this.#status.readyStatus(), AkanApp.#clientOf(req, server));
|
|
652
225
|
if (url.pathname === "/_akan/app/metrics")
|
|
653
|
-
return this.#statusAccess.metrics(req, () => this.#
|
|
654
|
-
|
|
655
|
-
|
|
226
|
+
return this.#statusAccess.metrics(req, () => this.#status.metricsStatus(), AkanApp.#clientOf(req, server));
|
|
227
|
+
const logStream = this.#logging.stream;
|
|
228
|
+
if (url.pathname === LogStreamRoute.path && logStream) return logStream.handle(req, AkanApp.#clientOf(req, server));
|
|
656
229
|
if (url.pathname === "/_akan/bench/ping") return new Response("ok");
|
|
657
230
|
if (url.pathname === AppInfo.publicPath) return AppInfo.handlePublic();
|
|
658
231
|
if (this.#ops?.matches(url.pathname)) return await this.#ops.handle(req, AkanApp.#clientOf(req, server));
|
|
659
|
-
if (this.#isWebSocketPath(url.pathname)) return this.#
|
|
660
|
-
const assetResponse = await this.#serveImmutableArtifact(req, url);
|
|
232
|
+
if (this.#config.isWebSocketPath(url.pathname)) return this.#ws.upgrade(req, server);
|
|
233
|
+
const assetResponse = await this.#proxy.serveImmutableArtifact(req, url);
|
|
661
234
|
if (assetResponse) return assetResponse;
|
|
662
|
-
return await this.#proxyHttp(req, server);
|
|
235
|
+
return await this.#proxy.proxyHttp(req, server);
|
|
663
236
|
}
|
|
664
237
|
|
|
665
238
|
static #clientOf(req: Request, server: Bun.Server<GatewayWsData>) {
|
|
666
239
|
return TrustedProxy.clientAddress(req.headers, server.requestIP(req)?.address);
|
|
667
240
|
}
|
|
668
241
|
|
|
669
|
-
#isWebSocketPath(pathname: string) {
|
|
670
|
-
return pathname === `${this.#prefix}${this.#websocketPrefix}` || pathname === "/_akan/hmr";
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
static readonly #immutableArtifacts = [
|
|
674
|
-
{ prefix: "/_akan/client/", root: "client", strip: "/_akan/client/".length, type: "application/javascript" },
|
|
675
|
-
{ prefix: "/_akan/styles/", root: "styles", strip: "/_akan/styles/".length, type: "text/css; charset=utf-8" },
|
|
676
|
-
{ prefix: "/_akan/fonts/", root: "fonts", strip: "/_akan/fonts/".length, type: "font/woff2", anyOrigin: true },
|
|
677
|
-
{ prefix: "/_akan/dict/", root: "dict", strip: "/_akan/dict/".length, type: "text/javascript; charset=utf-8" },
|
|
678
|
-
] as const;
|
|
679
|
-
|
|
680
|
-
async #serveImmutableArtifact(req: Request, url: URL): Promise<Response | null> {
|
|
681
|
-
if (!this.#web.ssr) return null;
|
|
682
|
-
const artifact = AkanApp.#immutableArtifacts.find(({ prefix }) => url.pathname.startsWith(prefix));
|
|
683
|
-
if (!artifact) return null;
|
|
684
|
-
const filePath = resolveStaticPath(path.join(this.#artifactDir, artifact.root), url.pathname.slice(artifact.strip));
|
|
685
|
-
if (!filePath) return new Response("Not Found", { status: 404 });
|
|
686
|
-
const file = Bun.file(filePath);
|
|
687
|
-
if (!(await file.exists())) return new Response("Not Found", { status: 404 });
|
|
688
|
-
return this.#fileResponse(req, filePath, {
|
|
689
|
-
contentType: file.type || artifact.type,
|
|
690
|
-
cacheControl: "public, max-age=31536000, immutable",
|
|
691
|
-
anyOrigin: "anyOrigin" in artifact,
|
|
692
|
-
});
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
#upgradeWebSocket(req: Request, server: Bun.Server<GatewayWsData>): Response | undefined {
|
|
696
|
-
const child = this.#pickFederationChild();
|
|
697
|
-
|
|
698
|
-
const upstream = child?.upstream ? (child.wsUpstream ?? this.#getChildUpstream(child.idx, child.role).ws) : null;
|
|
699
|
-
if (!child || !upstream) return new Response("No websocket upstream is ready", { status: 503 });
|
|
700
|
-
const url = new URL(req.url);
|
|
701
|
-
|
|
702
|
-
try {
|
|
703
|
-
CrossSiteGuard.assertOrigin(req, url, url.pathname === "/_akan/hmr" ? "hmr" : "websocket");
|
|
704
|
-
} catch {
|
|
705
|
-
return new Response("Forbidden", { status: 403 });
|
|
706
|
-
}
|
|
707
|
-
if (!WsUpgrade.isRequested(req)) return WsUpgrade.required();
|
|
708
|
-
const peer = server.requestIP(req) ?? undefined;
|
|
709
|
-
const clientIp = TrustedProxy.clientAddress(req.headers, peer?.address);
|
|
710
|
-
const refused = this.#refuseWebSocket(clientIp);
|
|
711
|
-
if (refused) return refused;
|
|
712
|
-
const upstreamWs = new WebSocket(`ws://${upstream.host}:${upstream.port}${url.pathname}${url.search}`, {
|
|
713
|
-
headers: makeAkanChildProxyHeaders(req, child.idx, peer),
|
|
714
|
-
} as unknown as string[]);
|
|
715
|
-
|
|
716
|
-
const upgraded = server.upgrade(req, {
|
|
717
|
-
data: { childIdx: child.idx, upstream: upstreamWs, clientIp, pending: [], pendingBytes: 0 },
|
|
718
|
-
});
|
|
719
|
-
if (!upgraded) {
|
|
720
|
-
upstreamWs.close();
|
|
721
|
-
return new Response("WebSocket upgrade failed", { status: 500 });
|
|
722
|
-
}
|
|
723
|
-
child.metrics.activeWebSockets = (child.metrics.activeWebSockets ?? 0) + 1;
|
|
724
|
-
this.#wsOpen += 1;
|
|
725
|
-
if (clientIp) this.#wsOpenByIp.set(clientIp, (this.#wsOpenByIp.get(clientIp) ?? 0) + 1);
|
|
726
|
-
return undefined;
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
#refuseWebSocket(clientIp: string | null): Response | null {
|
|
730
|
-
const headers = { "cache-control": "no-store" };
|
|
731
|
-
if (this.#wsCaps.total && this.#wsOpen >= this.#wsCaps.total)
|
|
732
|
-
return new Response("Too many open websockets", { status: 503, headers });
|
|
733
|
-
if (this.#wsCaps.perIp && clientIp && (this.#wsOpenByIp.get(clientIp) ?? 0) >= this.#wsCaps.perIp)
|
|
734
|
-
return new Response("Too many open websockets from this address", { status: 429, headers });
|
|
735
|
-
return null;
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
static #positiveIntEnv(name: string): number | null {
|
|
739
|
-
const value = Number(process.env[name]);
|
|
740
|
-
return Number.isInteger(value) && value > 0 ? value : null;
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
#handleWsOpen(ws: Bun.ServerWebSocket<GatewayWsData>) {
|
|
744
|
-
const upstream = ws.data.upstream;
|
|
745
|
-
const openTimer =
|
|
746
|
-
upstream.readyState === WebSocket.CONNECTING
|
|
747
|
-
? setTimeout(() => {
|
|
748
|
-
if (upstream.readyState === WebSocket.OPEN) return;
|
|
749
|
-
upstream.close();
|
|
750
|
-
ws.close(1013, "upstream websocket did not open");
|
|
751
|
-
}, AkanApp.#wsUpstreamOpenTimeoutMs)
|
|
752
|
-
: null;
|
|
753
|
-
upstream.addEventListener("open", () => {
|
|
754
|
-
if (openTimer) clearTimeout(openTimer);
|
|
755
|
-
for (const message of ws.data.pending.splice(0)) upstream.send(message);
|
|
756
|
-
ws.data.pendingBytes = 0;
|
|
757
|
-
});
|
|
758
|
-
upstream.addEventListener("message", (event) => {
|
|
759
|
-
const result = ws.send(event.data as string | ArrayBuffer);
|
|
760
|
-
if (result === 0) upstream.close();
|
|
761
|
-
});
|
|
762
|
-
upstream.addEventListener("close", (event) => {
|
|
763
|
-
if (openTimer) clearTimeout(openTimer);
|
|
764
|
-
ws.close(relayableCloseCode(event.code), event.reason);
|
|
765
|
-
});
|
|
766
|
-
upstream.addEventListener("error", () => ws.close(1011, "upstream websocket error"));
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
#handleWsMessage(ws: Bun.ServerWebSocket<GatewayWsData>, message: string | ArrayBuffer | Uint8Array) {
|
|
770
|
-
const upstream = ws.data.upstream;
|
|
771
|
-
const payload =
|
|
772
|
-
typeof message === "string"
|
|
773
|
-
? message
|
|
774
|
-
: message instanceof ArrayBuffer
|
|
775
|
-
? message
|
|
776
|
-
: new Uint8Array(message).slice().buffer;
|
|
777
|
-
if (upstream.readyState === WebSocket.OPEN) {
|
|
778
|
-
upstream.send(payload);
|
|
779
|
-
return;
|
|
780
|
-
}
|
|
781
|
-
const size = typeof payload === "string" ? Buffer.byteLength(payload) : payload.byteLength;
|
|
782
|
-
if (ws.data.pendingBytes + size > AkanApp.#wsPendingLimitBytes) {
|
|
783
|
-
ws.data.pending.length = 0;
|
|
784
|
-
ws.close(1009, "too much data before the upstream opened");
|
|
785
|
-
return;
|
|
786
|
-
}
|
|
787
|
-
ws.data.pending.push(payload as string | ArrayBuffer);
|
|
788
|
-
ws.data.pendingBytes += size;
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
#handleWsClose(ws: Bun.ServerWebSocket<GatewayWsData>, code: number, reason: string) {
|
|
792
|
-
ws.data.upstream.close(relayableCloseCode(code), reason);
|
|
793
|
-
const child = this.#children.get(ws.data.childIdx);
|
|
794
|
-
if (child) child.metrics.activeWebSockets = Math.max(0, (child.metrics.activeWebSockets ?? 1) - 1);
|
|
795
|
-
this.#wsOpen = Math.max(0, this.#wsOpen - 1);
|
|
796
|
-
const { clientIp } = ws.data;
|
|
797
|
-
const remaining = clientIp ? (this.#wsOpenByIp.get(clientIp) ?? 1) - 1 : 0;
|
|
798
|
-
if (clientIp && remaining > 0) this.#wsOpenByIp.set(clientIp, remaining);
|
|
799
|
-
else if (clientIp) this.#wsOpenByIp.delete(clientIp);
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
#getHealthStatus() {
|
|
803
|
-
return {
|
|
804
|
-
status: this.#stopping ? "stopping" : "running",
|
|
805
|
-
pid: process.pid,
|
|
806
|
-
children: [...this.#children.values()].map((child) => ({
|
|
807
|
-
idx: child.idx,
|
|
808
|
-
role: child.role,
|
|
809
|
-
status: child.status,
|
|
810
|
-
ready: child.ready,
|
|
811
|
-
pid: child.pid,
|
|
812
|
-
upstream: child.upstream,
|
|
813
|
-
restartAttempts: child.restart.attempts,
|
|
814
|
-
restartCount: child.restartCount,
|
|
815
|
-
restartPending: child.restartPending,
|
|
816
|
-
lastExitCode: child.lastExitCode,
|
|
817
|
-
lastRestartAt: child.lastRestartAt,
|
|
818
|
-
lastRestartReason: child.lastRestartReason,
|
|
819
|
-
lastErrorMessage: child.lastErrorMessage,
|
|
820
|
-
})),
|
|
821
|
-
};
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
#getReadyStatus() {
|
|
825
|
-
return {
|
|
826
|
-
ready: this.#isReady(),
|
|
827
|
-
pid: process.pid,
|
|
828
|
-
children: [...this.#children.values()].map(({ idx, role, status, ready }) => ({ idx, role, status, ready })),
|
|
829
|
-
};
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
#isReady() {
|
|
833
|
-
if (this.#stopping) return false;
|
|
834
|
-
if (this.#replica.federation + this.#replica.all > 0) return this.#federationCandidates().length > 0;
|
|
835
|
-
return [...this.#children.values()].some((child) => child.ready && !this.#isChildUnavailable(child));
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
#getMetricsStatus() {
|
|
839
|
-
return {
|
|
840
|
-
rooms: this.#roomChildren.size,
|
|
841
|
-
sockets: this.#socketRooms.size,
|
|
842
|
-
gateway: this.#gatewayMetrics,
|
|
843
|
-
proxyHop: this.#proxyHopCount
|
|
844
|
-
? {
|
|
845
|
-
count: this.#proxyHopCount,
|
|
846
|
-
meanMs: Math.round((this.#proxyHopSumMs / this.#proxyHopCount) * 1000) / 1000,
|
|
847
|
-
maxMs: Math.round(this.#proxyHopMaxMs * 1000) / 1000,
|
|
848
|
-
}
|
|
849
|
-
: null,
|
|
850
|
-
children: [...this.#children.values()].map((child) => ({
|
|
851
|
-
idx: child.idx,
|
|
852
|
-
role: child.role,
|
|
853
|
-
metrics: child.metrics,
|
|
854
|
-
rooms: this.#childRooms.get(child.idx)?.size ?? 0,
|
|
855
|
-
restartAttempts: child.restart.attempts,
|
|
856
|
-
restartCount: child.restartCount,
|
|
857
|
-
restartPending: child.restartPending,
|
|
858
|
-
lastExitCode: child.lastExitCode,
|
|
859
|
-
lastRestartAt: child.lastRestartAt,
|
|
860
|
-
lastRestartReason: child.lastRestartReason,
|
|
861
|
-
})),
|
|
862
|
-
};
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
async #proxyHttp(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response> {
|
|
866
|
-
const child = await this.#pickReadyFederationChild(req);
|
|
867
|
-
if (child?.upstream?.type !== "unix") return this.#respondWithUnavailable(req);
|
|
868
|
-
|
|
869
|
-
const { socketPath } = child.upstream;
|
|
870
|
-
const url = new URL(req.url);
|
|
871
|
-
const upstreamUrl = `http://akan-child${url.pathname}${url.search}`;
|
|
872
|
-
const headers = makeAkanChildProxyHeaders(req, child.idx, server.requestIP(req) ?? undefined);
|
|
873
|
-
child.metrics.activeRequests = (child.metrics.activeRequests ?? 0) + 1;
|
|
874
|
-
child.metrics.totalRequests = (child.metrics.totalRequests ?? 0) + 1;
|
|
875
|
-
const traced = isTraceEnabled();
|
|
876
|
-
const hopStart = traced ? performance.now() : 0;
|
|
877
|
-
const chunkedLimit = req.headers.has("content-length") ? null : this.#limits.bodyLimitOf(req);
|
|
878
|
-
try {
|
|
879
|
-
const upstreamRes = await fetch(upstreamUrl, {
|
|
880
|
-
unix: socketPath,
|
|
881
|
-
method: req.method,
|
|
882
|
-
headers,
|
|
883
|
-
body:
|
|
884
|
-
req.method === "GET" || req.method === "HEAD"
|
|
885
|
-
? undefined
|
|
886
|
-
: chunkedLimit !== null && req.body
|
|
887
|
-
? ServerLimits.limitBody(req.body, chunkedLimit)
|
|
888
|
-
: req.body,
|
|
889
|
-
signal: req.signal,
|
|
890
|
-
redirect: "manual",
|
|
891
|
-
decompress: false,
|
|
892
|
-
});
|
|
893
|
-
return await this.#proxyResponse(req, upstreamRes);
|
|
894
|
-
} catch (error) {
|
|
895
|
-
if (ServerLimits.isPayloadTooLarge(error)) return ServerLimits.payloadTooLarge();
|
|
896
|
-
if (AkanApp.#isUpstreamOpenFailure(error)) {
|
|
897
|
-
this.logger.error(`Child ${child.idx}/${child.role} upstream is unreachable (${socketPath}); restarting`);
|
|
898
|
-
this.#scheduleChildRestart(child, child.proc, "upstream-open-failed");
|
|
899
|
-
return AkanApp.#unavailableResponse(req, "Federation child upstream is unreachable; restarting");
|
|
900
|
-
}
|
|
901
|
-
if (req.signal.aborted) return AkanApp.#clientClosedResponse();
|
|
902
|
-
if (AkanApp.#isUpstreamMidFlightClose(error)) {
|
|
903
|
-
this.logger.warn(
|
|
904
|
-
`Child ${child.idx}/${child.role} closed the connection mid-request (${req.method} ${new URL(req.url).pathname})`,
|
|
905
|
-
);
|
|
906
|
-
return AkanApp.#badGatewayResponse(req);
|
|
907
|
-
}
|
|
908
|
-
throw error;
|
|
909
|
-
} finally {
|
|
910
|
-
child.metrics.activeRequests = Math.max(0, (child.metrics.activeRequests ?? 1) - 1);
|
|
911
|
-
if (traced) this.#recordProxyHop(performance.now() - hopStart);
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
static readonly #upstreamOpenFailureCodes = new Set(["FailedToOpenSocket", "ENOENT", "ECONNREFUSED", "ENOTSOCK"]);
|
|
916
|
-
|
|
917
|
-
static #isUpstreamOpenFailure(error: unknown): boolean {
|
|
918
|
-
if (!error || typeof error !== "object") return false;
|
|
919
|
-
const candidate = error as { code?: unknown; message?: unknown };
|
|
920
|
-
if (typeof candidate.code === "string" && AkanApp.#upstreamOpenFailureCodes.has(candidate.code)) return true;
|
|
921
|
-
return String(candidate.message ?? "").includes("FailedToOpenSocket");
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
static #isUpstreamMidFlightClose(error: unknown): boolean {
|
|
925
|
-
if (!error || typeof error !== "object") return false;
|
|
926
|
-
const candidate = error as { code?: unknown; message?: unknown };
|
|
927
|
-
if (candidate.code === "ECONNRESET" || candidate.code === "ConnectionClosed") return true;
|
|
928
|
-
return String(candidate.message ?? "").includes("connection was closed");
|
|
929
|
-
}
|
|
930
|
-
|
|
931
|
-
static #clientClosedResponse(): Response {
|
|
932
|
-
return new Response(null, { status: 499, headers: { "cache-control": "no-store" } });
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
static #badGatewayResponse(req: Request): Response {
|
|
936
|
-
const detail = "The replica closed the connection before it finished answering.";
|
|
937
|
-
if (req.headers.get("accept")?.includes("text/html")) {
|
|
938
|
-
return new Response(
|
|
939
|
-
AkanApp.#statusPageHtml({
|
|
940
|
-
heading: "Backend dropped the connection",
|
|
941
|
-
detail,
|
|
942
|
-
note: "The replica is restarting — this page reloads itself as soon as it answers.",
|
|
943
|
-
}),
|
|
944
|
-
{ status: 502, headers: AkanApp.#statusHeaders("text/html; charset=utf-8") },
|
|
945
|
-
);
|
|
946
|
-
}
|
|
947
|
-
return new Response(detail, { status: 502, headers: AkanApp.#statusHeaders("text/plain; charset=utf-8") });
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
async #pickReadyFederationChild(req: Request): Promise<ChildState | null> {
|
|
951
|
-
const ready = this.#pickFederationChild();
|
|
952
|
-
if (ready?.upstream) return ready;
|
|
953
|
-
const deadline = performance.now() + this.#upstreamWaitMs;
|
|
954
|
-
while (performance.now() < deadline) {
|
|
955
|
-
if (this.#stopping || req.signal.aborted || this.#getCrashLoopDetail()) return null;
|
|
956
|
-
await Bun.sleep(50);
|
|
957
|
-
const child = this.#pickFederationChild();
|
|
958
|
-
if (child?.upstream) return child;
|
|
959
|
-
}
|
|
960
|
-
return null;
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
#getCrashLoopDetail(): string | null {
|
|
964
|
-
if (!this.#devHosted) return null;
|
|
965
|
-
const trafficChildren = [...this.#children.values()].filter((child) => child.role !== "batch");
|
|
966
|
-
if (trafficChildren.length === 0) return null;
|
|
967
|
-
if (!trafficChildren.every((child) => child.status === "crashed")) return null;
|
|
968
|
-
return (
|
|
969
|
-
trafficChildren.map((child) => child.lastErrorMessage ?? child.lastRestartReason).find(Boolean) ??
|
|
970
|
-
"unknown boot error"
|
|
971
|
-
);
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
#respondWithUnavailable(req: Request): Response {
|
|
975
|
-
const crashDetail = this.#getCrashLoopDetail();
|
|
976
|
-
const page = crashDetail
|
|
977
|
-
? {
|
|
978
|
-
heading: "Backend failed to start",
|
|
979
|
-
detail: crashDetail,
|
|
980
|
-
text: `Backend failed to start after ${AkanApp.#devMaxChildBootFailures} boot attempts: ${crashDetail}`,
|
|
981
|
-
note: `The dev server stopped retrying after ${AkanApp.#devMaxChildBootFailures} failed boots. Fix the error and save — this page reloads automatically.`,
|
|
982
|
-
}
|
|
983
|
-
: {
|
|
984
|
-
heading: "Backend is starting",
|
|
985
|
-
detail: "No healthy federation child is ready",
|
|
986
|
-
text: "No healthy federation child is ready",
|
|
987
|
-
note: "A replica is booting or restarting — this page reloads itself as soon as it answers.",
|
|
988
|
-
};
|
|
989
|
-
if (req.headers.get("accept")?.includes("text/html")) {
|
|
990
|
-
return new Response(AkanApp.#statusPageHtml(page), {
|
|
991
|
-
status: 503,
|
|
992
|
-
headers: AkanApp.#statusHeaders("text/html; charset=utf-8"),
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
return AkanApp.#unavailableResponse(req, page.text);
|
|
996
|
-
}
|
|
997
|
-
|
|
998
|
-
static #unavailableResponse(req: Request, detail: string): Response {
|
|
999
|
-
const headers = { "cache-control": "no-store" };
|
|
1000
|
-
if (!req.headers.get("accept")?.includes("application/json")) return new Response(detail, { status: 503, headers });
|
|
1001
|
-
return Response.json(
|
|
1002
|
-
{ error: "base.error.serverUnavailable", statusCode: 503, data: { status: 503 }, details: detail },
|
|
1003
|
-
{ status: 503, headers },
|
|
1004
|
-
);
|
|
1005
|
-
}
|
|
1006
|
-
|
|
1007
|
-
static #statusHeaders(contentType: string): Headers {
|
|
1008
|
-
const headers = new Headers({ "content-type": contentType, "cache-control": "no-store" });
|
|
1009
|
-
return applySecurityHeaders(headers, { html: contentType.startsWith("text/html") });
|
|
1010
|
-
}
|
|
1011
|
-
|
|
1012
|
-
static #statusPageHtml({ heading, detail, note }: { heading: string; detail: string; note: string }) {
|
|
1013
|
-
return `<!doctype html>
|
|
1014
|
-
<html>
|
|
1015
|
-
<head>
|
|
1016
|
-
<meta charset="utf-8" />
|
|
1017
|
-
<title>${AkanApp.#escapeHtml(heading)}</title>
|
|
1018
|
-
<style>
|
|
1019
|
-
body { margin: 0; padding: 48px 24px; background: #111827; color: #e5e7eb; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
1020
|
-
main { max-width: 720px; margin: 0 auto; }
|
|
1021
|
-
h1 { font-size: 20px; color: #f87171; }
|
|
1022
|
-
pre { padding: 16px; border-radius: 8px; background: #1f2937; color: #fca5a5; white-space: pre-wrap; word-break: break-word; }
|
|
1023
|
-
p { color: #9ca3af; font-size: 14px; }
|
|
1024
|
-
</style>
|
|
1025
|
-
</head>
|
|
1026
|
-
<body>
|
|
1027
|
-
<main>
|
|
1028
|
-
<h1>${AkanApp.#escapeHtml(heading)}</h1>
|
|
1029
|
-
<pre>${AkanApp.#escapeHtml(detail)}</pre>
|
|
1030
|
-
<p>${AkanApp.#escapeHtml(note)}</p>
|
|
1031
|
-
</main>
|
|
1032
|
-
<script>
|
|
1033
|
-
const poll = async () => {
|
|
1034
|
-
try {
|
|
1035
|
-
const res = await fetch(location.href, { cache: "no-store" });
|
|
1036
|
-
if (res.ok) { location.reload(); return; }
|
|
1037
|
-
} catch {}
|
|
1038
|
-
setTimeout(poll, 1000);
|
|
1039
|
-
};
|
|
1040
|
-
setTimeout(poll, 1000);
|
|
1041
|
-
</script>
|
|
1042
|
-
</body>
|
|
1043
|
-
</html>`;
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
static #escapeHtml(text: string) {
|
|
1047
|
-
const replacements: Record<string, string> = {
|
|
1048
|
-
"&": "&",
|
|
1049
|
-
"<": "<",
|
|
1050
|
-
">": ">",
|
|
1051
|
-
'"': """,
|
|
1052
|
-
"'": "'",
|
|
1053
|
-
};
|
|
1054
|
-
return text.replace(/[&<>"']/g, (ch) => replacements[ch] ?? ch);
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
#recordProxyHop(durationMs: number) {
|
|
1058
|
-
this.#proxyHopCount += 1;
|
|
1059
|
-
this.#proxyHopSumMs += durationMs;
|
|
1060
|
-
this.#proxyHopMaxMs = Math.max(this.#proxyHopMaxMs, durationMs);
|
|
1061
|
-
}
|
|
1062
|
-
|
|
1063
|
-
async #proxyResponse(req: Request, upstreamRes: Response): Promise<Response> {
|
|
1064
|
-
const headers = new Headers(upstreamRes.headers);
|
|
1065
|
-
this.#rewriteInternalLocation(headers);
|
|
1066
|
-
const proxied = new Response(upstreamRes.body, {
|
|
1067
|
-
status: upstreamRes.status,
|
|
1068
|
-
statusText: upstreamRes.statusText,
|
|
1069
|
-
headers,
|
|
1070
|
-
});
|
|
1071
|
-
|
|
1072
|
-
return AkanApp.#isProxiedJson(headers)
|
|
1073
|
-
? await compressResponse(req, proxied)
|
|
1074
|
-
: compressStreamResponse(req, proxied);
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
static #isProxiedJson(headers: Headers): boolean {
|
|
1078
|
-
return (headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() === "application/json";
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
#rewriteInternalLocation(headers: Headers) {
|
|
1082
|
-
const location = headers.get("location");
|
|
1083
|
-
if (!location) return;
|
|
1084
|
-
try {
|
|
1085
|
-
const parsed = new URL(location);
|
|
1086
|
-
if (parsed.hostname === AKAN_CHILD_HOST)
|
|
1087
|
-
headers.set("location", `${parsed.pathname}${parsed.search}${parsed.hash}`);
|
|
1088
|
-
} catch {
|
|
1089
|
-
}
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
async #fileResponse(req: Request, filePath: string, options: AssetHeaderOptions): Promise<Response> {
|
|
1093
|
-
return await encodedFileResponse(req, filePath, options.contentType, assetHeaders(options));
|
|
1094
|
-
}
|
|
1095
|
-
|
|
1096
|
-
#federationCandidates() {
|
|
1097
|
-
this.#federationChildCache ??= [...this.#children.values()].filter(
|
|
1098
|
-
(child) =>
|
|
1099
|
-
(child.role === "federation" || child.role === "all") &&
|
|
1100
|
-
child.ready &&
|
|
1101
|
-
child.status !== "unhealthy" &&
|
|
1102
|
-
!this.#isChildUnavailable(child),
|
|
1103
|
-
);
|
|
1104
|
-
return this.#federationChildCache;
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
|
-
#pickFederationChild() {
|
|
1108
|
-
const candidates = this.#federationCandidates();
|
|
1109
|
-
if (candidates.length === 0) return null;
|
|
1110
|
-
const child = candidates[this.#rrIdx % candidates.length];
|
|
1111
|
-
this.#rrIdx++;
|
|
1112
|
-
return child;
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
#getRole(idx: number): AkanChildRole {
|
|
1116
|
-
if (idx < this.#replica.federation) return "federation";
|
|
1117
|
-
if (idx < this.#replica.federation + this.#replica.batch) return "batch";
|
|
1118
|
-
return "all";
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
#getChildUpstream(idx: number, role: AkanChildRole): GatewayUpstream {
|
|
1122
|
-
return {
|
|
1123
|
-
http: { type: "unix", socketPath: path.join(this.#runtimeDir, `akan-child-${this.#socketRunId}-${idx}.sock`) },
|
|
1124
|
-
ws: role === "batch" ? undefined : { type: "tcp", host: "127.0.0.1", port: this.#wsBasePort + idx },
|
|
1125
|
-
};
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
242
|
#handleMessage(
|
|
1129
243
|
idx: number,
|
|
1130
244
|
message: AkanIpcMessage | BuilderMessage,
|
|
@@ -1135,49 +249,49 @@ export class AkanApp {
|
|
|
1135
249
|
if (!message || typeof message !== "object") return;
|
|
1136
250
|
switch (message.type) {
|
|
1137
251
|
case "ready":
|
|
1138
|
-
this.#markReady(idx, message);
|
|
252
|
+
this.#supervisor.markReady(idx, message);
|
|
1139
253
|
return;
|
|
1140
254
|
case "pubsub.publish":
|
|
1141
|
-
this.#deliverPubsub(idx, message);
|
|
255
|
+
this.#rooms.deliverPubsub(idx, message);
|
|
1142
256
|
return;
|
|
1143
257
|
case "pubsub.subscribe":
|
|
1144
|
-
this.#addRoomMembership(idx, message.roomId, message.socketId);
|
|
258
|
+
this.#rooms.addRoomMembership(idx, message.roomId, message.socketId);
|
|
1145
259
|
return;
|
|
1146
260
|
case "pubsub.unsubscribe":
|
|
1147
|
-
this.#removeRoomMembership(idx, message.roomId, message.socketId);
|
|
261
|
+
this.#rooms.removeRoomMembership(idx, message.roomId, message.socketId);
|
|
1148
262
|
return;
|
|
1149
263
|
case "pubsub.snapshot":
|
|
1150
|
-
this.#replaceRoomSnapshot(idx, message.rooms);
|
|
1151
|
-
if (message.liveModels) this.#setLiveModels(idx, message.liveModels);
|
|
264
|
+
this.#rooms.replaceRoomSnapshot(idx, message.rooms);
|
|
265
|
+
if (message.liveModels) this.#rooms.setLiveModels(idx, message.liveModels);
|
|
1152
266
|
return;
|
|
1153
267
|
case "live.change":
|
|
1154
|
-
this.#fanoutLiveChange(idx, message);
|
|
268
|
+
this.#rooms.fanoutLiveChange(idx, message);
|
|
1155
269
|
return;
|
|
1156
270
|
case "live.models":
|
|
1157
|
-
this.#setLiveModels(idx, message.models);
|
|
271
|
+
this.#rooms.setLiveModels(idx, message.models);
|
|
1158
272
|
return;
|
|
1159
273
|
case "metrics.report":
|
|
1160
|
-
this.#updateMetrics(idx, message.metrics);
|
|
274
|
+
this.#children.updateMetrics(idx, message.metrics);
|
|
1161
275
|
return;
|
|
1162
276
|
case "log.records":
|
|
1163
|
-
this.#
|
|
277
|
+
this.#logging.hub?.ingestMany(message.records);
|
|
1164
278
|
if (message.dropped) this.logger.warn(`Child ${idx} dropped ${message.dropped} log records (ipc backpressure)`);
|
|
1165
279
|
return;
|
|
1166
280
|
case "health.pong":
|
|
1167
|
-
this.#markHealthy(idx);
|
|
281
|
+
this.#supervisor.markHealthy(idx);
|
|
1168
282
|
return;
|
|
1169
283
|
case "queue.enqueued":
|
|
1170
|
-
this.#fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
|
|
284
|
+
this.#children.fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
|
|
1171
285
|
return;
|
|
1172
286
|
case "error":
|
|
1173
287
|
this.logger.error(message.message);
|
|
1174
288
|
if (child) child.lastErrorMessage = message.message;
|
|
1175
|
-
if (child && proc) void this.#
|
|
289
|
+
if (child && proc) void this.#supervisor.scheduleRestart(child, proc, "child-error");
|
|
1176
290
|
return;
|
|
1177
291
|
case "build-route":
|
|
1178
292
|
case "build-csr":
|
|
1179
293
|
case "build-graph":
|
|
1180
|
-
this.#forwardBuilderReq(idx, message);
|
|
294
|
+
this.#host.forwardBuilderReq(idx, message);
|
|
1181
295
|
return;
|
|
1182
296
|
}
|
|
1183
297
|
}
|
|
@@ -1192,294 +306,13 @@ export class AkanApp {
|
|
|
1192
306
|
case "csr-updated":
|
|
1193
307
|
case "ssr-updated":
|
|
1194
308
|
case "build-status":
|
|
1195
|
-
this.#fanoutToFederation(message);
|
|
309
|
+
this.#children.fanoutToFederation(message);
|
|
1196
310
|
return;
|
|
1197
311
|
case "build-route-res":
|
|
1198
312
|
case "build-csr-res":
|
|
1199
313
|
case "build-graph-res":
|
|
1200
|
-
this.#forwardBuilderRes(message);
|
|
314
|
+
this.#host.forwardBuilderRes(message);
|
|
1201
315
|
return;
|
|
1202
316
|
}
|
|
1203
317
|
}
|
|
1204
|
-
|
|
1205
|
-
#markReady(idx: number, message: Extract<AkanIpcMessage, { type: "ready" }>) {
|
|
1206
|
-
const child = this.#children.get(idx);
|
|
1207
|
-
if (!child) return;
|
|
1208
|
-
child.ready = true;
|
|
1209
|
-
child.status = "ready";
|
|
1210
|
-
child.pid = message.pid;
|
|
1211
|
-
child.upstream = message.upstream;
|
|
1212
|
-
child.wsUpstream = message.wsUpstream;
|
|
1213
|
-
child.healthPath = message.healthPath;
|
|
1214
|
-
if (message.crossSite) CrossSiteGuard.configure(message.crossSite);
|
|
1215
|
-
child.lastPongAtMono = performance.now();
|
|
1216
|
-
child.restart.reset();
|
|
1217
|
-
|
|
1218
|
-
if (this.#logHub && this.#logHub.floor !== null)
|
|
1219
|
-
this.#sendToChild(child, { type: "log.level", minSev: this.#logHub.floor });
|
|
1220
|
-
child.restartPending = false;
|
|
1221
|
-
child.lastErrorMessage = undefined;
|
|
1222
|
-
this.#federationChildCache = null;
|
|
1223
|
-
|
|
1224
|
-
const trafficChildren = [...this.#children.values()].filter((item) => item.role !== "batch");
|
|
1225
|
-
|
|
1226
|
-
if (!this.#stopping && child.role !== "batch" && trafficChildren.every((item) => item.ready)) {
|
|
1227
|
-
process.send?.({ type: "backend-ready", pid: process.pid } satisfies BuilderMessage);
|
|
1228
|
-
}
|
|
1229
|
-
if ([...this.#children.values()].every((item) => item.ready)) {
|
|
1230
|
-
this.logger.verbose(`All ${this.#children.size} child process(es) are ready`);
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
#markHealthy(idx: number) {
|
|
1235
|
-
const child = this.#children.get(idx);
|
|
1236
|
-
if (!child) return;
|
|
1237
|
-
child.status = "healthy";
|
|
1238
|
-
child.lastPongAtMono = performance.now();
|
|
1239
|
-
this.#federationChildCache = null;
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
#deliverPubsub(originIdx: number, message: Extract<AkanIpcMessage, { type: "pubsub.publish" }>) {
|
|
1243
|
-
const targets = this.#roomChildren.get(message.roomId);
|
|
1244
|
-
if (!targets?.size) {
|
|
1245
|
-
const child = this.#children.get(originIdx);
|
|
1246
|
-
if (child) child.metrics.pubsubDropCount = (child.metrics.pubsubDropCount ?? 0) + 1;
|
|
1247
|
-
this.logger.verbose(`Dropping pubsub ${message.roomId}; no subscribers`);
|
|
1248
|
-
return;
|
|
1249
|
-
}
|
|
1250
|
-
for (const childIdx of targets) {
|
|
1251
|
-
if (childIdx === originIdx) continue;
|
|
1252
|
-
const child = this.#children.get(childIdx);
|
|
1253
|
-
if (!child || this.#isChildUnavailable(child)) continue;
|
|
1254
|
-
if (
|
|
1255
|
-
!this.#sendToChild(child, {
|
|
1256
|
-
type: "pubsub.deliver",
|
|
1257
|
-
roomId: message.roomId,
|
|
1258
|
-
data: message.data,
|
|
1259
|
-
origin: message.origin,
|
|
1260
|
-
} satisfies AkanIpcMessage)
|
|
1261
|
-
)
|
|
1262
|
-
continue;
|
|
1263
|
-
child.metrics.pubsubDeliverCount = (child.metrics.pubsubDeliverCount ?? 0) + 1;
|
|
1264
|
-
}
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
#addRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
1268
|
-
const roomChildren = this.#roomChildren.get(roomId) ?? new Set<number>();
|
|
1269
|
-
roomChildren.add(childIdx);
|
|
1270
|
-
this.#roomChildren.set(roomId, roomChildren);
|
|
1271
|
-
|
|
1272
|
-
const childRooms = this.#childRooms.get(childIdx) ?? new Map<string, Set<string>>();
|
|
1273
|
-
const roomSockets = childRooms.get(roomId) ?? new Set<string>();
|
|
1274
|
-
childRooms.set(roomId, roomSockets);
|
|
1275
|
-
this.#childRooms.set(childIdx, childRooms);
|
|
1276
|
-
|
|
1277
|
-
if (socketId) {
|
|
1278
|
-
roomSockets.add(socketId);
|
|
1279
|
-
const socketRooms = this.#socketRooms.get(socketId) ?? { childIdx, rooms: new Set<string>() };
|
|
1280
|
-
socketRooms.rooms.add(roomId);
|
|
1281
|
-
this.#socketRooms.set(socketId, socketRooms);
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
|
|
1285
|
-
#leaveRoom(childIdx: number, roomId: string) {
|
|
1286
|
-
const roomChildren = this.#roomChildren.get(roomId);
|
|
1287
|
-
roomChildren?.delete(childIdx);
|
|
1288
|
-
if (roomChildren?.size === 0) this.#roomChildren.delete(roomId);
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
#removeRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
1292
|
-
const childRooms = this.#childRooms.get(childIdx);
|
|
1293
|
-
const roomSockets = childRooms?.get(roomId);
|
|
1294
|
-
if (socketId) {
|
|
1295
|
-
this.#forgetSocketRoom(socketId, roomId);
|
|
1296
|
-
roomSockets?.delete(socketId);
|
|
1297
|
-
if (roomSockets?.size) return;
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
for (const staleSocketId of roomSockets ?? []) this.#forgetSocketRoom(staleSocketId, roomId);
|
|
1301
|
-
this.#leaveRoom(childIdx, roomId);
|
|
1302
|
-
childRooms?.delete(roomId);
|
|
1303
|
-
if (childRooms?.size === 0) this.#childRooms.delete(childIdx);
|
|
1304
|
-
}
|
|
1305
|
-
|
|
1306
|
-
#forgetSocketRoom(socketId: string, roomId: string) {
|
|
1307
|
-
const socketRooms = this.#socketRooms.get(socketId);
|
|
1308
|
-
socketRooms?.rooms.delete(roomId);
|
|
1309
|
-
if (!socketRooms || socketRooms.rooms.size === 0) this.#socketRooms.delete(socketId);
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
#replaceRoomSnapshot(childIdx: number, rooms: string[]) {
|
|
1313
|
-
const held = new Set(rooms);
|
|
1314
|
-
for (const roomId of [...(this.#childRooms.get(childIdx)?.keys() ?? [])])
|
|
1315
|
-
if (!held.has(roomId)) this.#removeRoomMembership(childIdx, roomId);
|
|
1316
|
-
for (const roomId of held) this.#addRoomMembership(childIdx, roomId);
|
|
1317
|
-
}
|
|
1318
|
-
|
|
1319
|
-
#removeChildRooms(childIdx: number) {
|
|
1320
|
-
for (const roomId of this.#childRooms.get(childIdx)?.keys() ?? []) this.#leaveRoom(childIdx, roomId);
|
|
1321
|
-
this.#childRooms.delete(childIdx);
|
|
1322
|
-
for (const [socketId, socket] of this.#socketRooms.entries()) {
|
|
1323
|
-
if (socket.childIdx === childIdx) this.#socketRooms.delete(socketId);
|
|
1324
|
-
}
|
|
1325
|
-
this.#setLiveModels(childIdx, []);
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
#setLiveModels(childIdx: number, models: string[]) {
|
|
1329
|
-
if (models.length) this.#childLiveModels.set(childIdx, new Set(models));
|
|
1330
|
-
else this.#childLiveModels.delete(childIdx);
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
#updateMetrics(childIdx: number, metrics: AkanMetricsReport) {
|
|
1334
|
-
const child = this.#children.get(childIdx);
|
|
1335
|
-
if (!child) return;
|
|
1336
|
-
child.metrics = { ...child.metrics, pid: metrics.pid ?? child.pid, ...metrics };
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
async #reportMetrics() {
|
|
1340
|
-
this.#gatewayMetrics = await ProcessMetricsCollector.collect({ role: "gateway" });
|
|
1341
|
-
if (process.env.AKAN_MEMORY_LOG !== "1") return;
|
|
1342
|
-
this.logger.verbose(
|
|
1343
|
-
`memory role=gateway ${ProcessMetricsCollector.format(this.#gatewayMetrics)} children=${this.#children.size}`,
|
|
1344
|
-
);
|
|
1345
|
-
for (const child of this.#children.values()) {
|
|
1346
|
-
if (!child.metrics.rssBytes) continue;
|
|
1347
|
-
const rooms = this.#childRooms.get(child.idx)?.size ?? 0;
|
|
1348
|
-
this.logger.verbose(
|
|
1349
|
-
`memory role=${child.role} idx=${child.idx} ${ProcessMetricsCollector.format({
|
|
1350
|
-
...child.metrics,
|
|
1351
|
-
pid: child.metrics.pid ?? child.pid,
|
|
1352
|
-
})} activeRequests=${child.metrics.activeRequests ?? 0} activeWebSockets=${
|
|
1353
|
-
child.metrics.activeWebSockets ?? 0
|
|
1354
|
-
} rooms=${rooms} rscPending=${child.metrics.rscPendingRenderCount ?? 0} rscModules=${
|
|
1355
|
-
child.metrics.rscLoadedRouteModuleCount ?? 0
|
|
1356
|
-
}`,
|
|
1357
|
-
);
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
#requestRoomSnapshots() {
|
|
1362
|
-
for (const child of this.#children.values()) {
|
|
1363
|
-
if (this.#isChildUnavailable(child)) continue;
|
|
1364
|
-
this.#sendToChild(child, { type: "pubsub.snapshot.request" } satisfies AkanIpcMessage);
|
|
1365
|
-
}
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
#checkHealth() {
|
|
1369
|
-
const nowMono = performance.now();
|
|
1370
|
-
for (const child of this.#children.values()) {
|
|
1371
|
-
if (this.#isChildUnavailable(child)) continue;
|
|
1372
|
-
if (child.lastPongAtMono && nowMono - child.lastPongAtMono > this.#healthTimeoutMs) {
|
|
1373
|
-
child.status = "unhealthy";
|
|
1374
|
-
this.#federationChildCache = null;
|
|
1375
|
-
void this.#scheduleChildRestart(child, child.proc, "health-timeout");
|
|
1376
|
-
continue;
|
|
1377
|
-
}
|
|
1378
|
-
const sent = this.#sendToChild(child, {
|
|
1379
|
-
type: "health.ping",
|
|
1380
|
-
nonce: crypto.randomUUID(),
|
|
1381
|
-
sentAt: Date.now(),
|
|
1382
|
-
} satisfies AkanIpcMessage);
|
|
1383
|
-
if (!sent) {
|
|
1384
|
-
child.status = "unhealthy";
|
|
1385
|
-
this.#federationChildCache = null;
|
|
1386
|
-
void this.#scheduleChildRestart(child, child.proc, "health-send-failed");
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
#forwardBuilderReq(childIdx: number, message: BuilderRequest) {
|
|
1392
|
-
const gatewayReqId = this.#nextBuilderReqId++;
|
|
1393
|
-
this.#builderReqMap.set(gatewayReqId, { childIdx, childLocalId: message.id });
|
|
1394
|
-
process.send?.({ ...message, id: gatewayReqId } satisfies BuilderRequest);
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
#forwardBuilderRes(message: BuilderResponse) {
|
|
1398
|
-
const request = this.#builderReqMap.get(message.id);
|
|
1399
|
-
if (!request) {
|
|
1400
|
-
this.logger.warn(`No child found for ${message.type} id=${message.id}`);
|
|
1401
|
-
return;
|
|
1402
|
-
}
|
|
1403
|
-
this.#builderReqMap.delete(message.id);
|
|
1404
|
-
const child = this.#children.get(request.childIdx);
|
|
1405
|
-
if (!child || child.proc.killed) return;
|
|
1406
|
-
this.#sendToChild(child, { ...message, id: request.childLocalId } satisfies BuilderResponse);
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
#fanoutToFederation(message: AkanIpcMessage | BuilderMessage, exceptIdx?: number) {
|
|
1410
|
-
for (const child of this.#children.values()) {
|
|
1411
|
-
if (child.idx === exceptIdx) continue;
|
|
1412
|
-
if (child.role === "federation" || child.role === "all") this.#sendToChild(child, message);
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
|
|
1416
|
-
#fanoutToAll(message: AkanIpcMessage) {
|
|
1417
|
-
for (const child of this.#children.values()) this.#sendToChild(child, message);
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
#fanoutLiveChange(originIdx: number, message: Extract<AkanIpcMessage, { type: "live.change" }>) {
|
|
1421
|
-
for (const [childIdx, models] of this.#childLiveModels) {
|
|
1422
|
-
const child = this.#children.get(childIdx);
|
|
1423
|
-
if (child && childIdx !== originIdx && models.has(message.change.refName)) this.#sendToChild(child, message);
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
#fanoutToBatch(message: AkanIpcMessage) {
|
|
1428
|
-
for (const child of this.#children.values()) {
|
|
1429
|
-
if (child.role === "batch" || child.role === "all") {
|
|
1430
|
-
if (this.#sendToChild(child, message) && message.type === "queue.wake") {
|
|
1431
|
-
child.metrics.queueWakeCount = (child.metrics.queueWakeCount ?? 0) + 1;
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
#sendToChild(child: ChildState, message: AkanIpcMessage | BuilderMessage): boolean {
|
|
1438
|
-
if (this.#isChildUnavailable(child)) return false;
|
|
1439
|
-
try {
|
|
1440
|
-
child.proc.send(message);
|
|
1441
|
-
return true;
|
|
1442
|
-
} catch (error) {
|
|
1443
|
-
this.logger.warn(
|
|
1444
|
-
`Failed to send ${message.type} to child ${child.idx}/${child.role}: ${
|
|
1445
|
-
error instanceof Error ? error.message : String(error)
|
|
1446
|
-
}`,
|
|
1447
|
-
);
|
|
1448
|
-
return false;
|
|
1449
|
-
}
|
|
1450
|
-
}
|
|
1451
|
-
|
|
1452
|
-
#writeChildLine(idx: number, role: AkanChildRole, pid: number | null, type: "stdout" | "stderr", line: string) {
|
|
1453
|
-
if (Logger.isNdjson) {
|
|
1454
|
-
this.#logHub?.ingest(ChildOutputReader.toRecord({ type, text: line, name: "child", role, replicaIdx: idx, pid }));
|
|
1455
|
-
return;
|
|
1456
|
-
}
|
|
1457
|
-
const prefixedLine = `[child:${idx} ${role}] [${type}] ${line}`;
|
|
1458
|
-
if (type === "stdout" || this.#printChildStderr || !this.#logWriter) process[type].write(prefixedLine);
|
|
1459
|
-
this.#logWriter?.write(`${idx}-${role}`, AkanApp.#stripAnsi(prefixedLine));
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
#writeChildStderrBlock(idx: number, role: AkanChildRole, pid: number | null, lines: string[]) {
|
|
1463
|
-
const text = lines.join("");
|
|
1464
|
-
if (AkanApp.#isBenignRsdwConnectionClosedBlock(text)) return;
|
|
1465
|
-
if (Logger.isNdjson) {
|
|
1466
|
-
this.#logHub?.ingest(
|
|
1467
|
-
ChildOutputReader.toRecord({ type: "stderr", text, name: "child", role, replicaIdx: idx, pid }),
|
|
1468
|
-
);
|
|
1469
|
-
return;
|
|
1470
|
-
}
|
|
1471
|
-
for (const line of lines) this.#writeChildLine(idx, role, pid, "stderr", line);
|
|
1472
|
-
}
|
|
1473
|
-
|
|
1474
|
-
static #isBenignRsdwConnectionClosedBlock(text: string): boolean {
|
|
1475
|
-
return (
|
|
1476
|
-
text.includes('reportGlobalError(weakResponse, Error("Connection closed."))') &&
|
|
1477
|
-
text.includes("error: Connection closed.") &&
|
|
1478
|
-
text.includes("react-server-dom-webpack")
|
|
1479
|
-
);
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
static #stripAnsi(msg: string) {
|
|
1483
|
-
return msg.replace(AkanApp.#ansiPattern, "");
|
|
1484
|
-
}
|
|
1485
318
|
}
|