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
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { Logger } from "akanjs/common";
|
|
3
|
+
import { isTraceEnabled } from "../../signal/trace";
|
|
4
|
+
import { AKAN_CHILD_HOST, makeAkanChildProxyHeaders } from "../akanAppHeaders";
|
|
5
|
+
import { type AssetHeaderOptions, assetHeaders } from "../assetHeaders";
|
|
6
|
+
import { compressResponse, compressStreamResponse, encodedFileResponse } from "../contentEncoding";
|
|
7
|
+
import { ServerLimits } from "../routing/serverLimits";
|
|
8
|
+
import { resolveStaticPath } from "../staticPath";
|
|
9
|
+
import type { ChildSupervisor } from "./childSupervisor";
|
|
10
|
+
import type { ChildState, GatewayChildren } from "./gatewayChildren";
|
|
11
|
+
import { GatewayConfig } from "./gatewayConfig";
|
|
12
|
+
import type { GatewayStatus } from "./gatewayStatus";
|
|
13
|
+
import { GatewayStatusPage } from "./gatewayStatusPage";
|
|
14
|
+
import type { GatewayWsData } from "./gatewayWebSocketRelay";
|
|
15
|
+
|
|
16
|
+
interface GatewayHttpProxyParts {
|
|
17
|
+
config: GatewayConfig;
|
|
18
|
+
children: GatewayChildren;
|
|
19
|
+
supervisor: ChildSupervisor;
|
|
20
|
+
status: GatewayStatus;
|
|
21
|
+
limits: ServerLimits;
|
|
22
|
+
logger: Logger;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class GatewayHttpProxy {
|
|
26
|
+
static readonly #immutableArtifacts = [
|
|
27
|
+
{ prefix: "/_akan/client/", root: "client", strip: "/_akan/client/".length, type: "application/javascript" },
|
|
28
|
+
{ prefix: "/_akan/styles/", root: "styles", strip: "/_akan/styles/".length, type: "text/css; charset=utf-8" },
|
|
29
|
+
{ prefix: "/_akan/fonts/", root: "fonts", strip: "/_akan/fonts/".length, type: "font/woff2", anyOrigin: true },
|
|
30
|
+
{ prefix: "/_akan/dict/", root: "dict", strip: "/_akan/dict/".length, type: "text/javascript; charset=utf-8" },
|
|
31
|
+
] as const;
|
|
32
|
+
|
|
33
|
+
static readonly #upstreamOpenFailureCodes = new Set(["FailedToOpenSocket", "ENOENT", "ECONNREFUSED", "ENOTSOCK"]);
|
|
34
|
+
|
|
35
|
+
readonly #config: GatewayConfig;
|
|
36
|
+
readonly #children: GatewayChildren;
|
|
37
|
+
readonly #supervisor: ChildSupervisor;
|
|
38
|
+
readonly #status: GatewayStatus;
|
|
39
|
+
readonly #limits: ServerLimits;
|
|
40
|
+
readonly #logger: Logger;
|
|
41
|
+
|
|
42
|
+
constructor({ config, children, supervisor, status, limits, logger }: GatewayHttpProxyParts) {
|
|
43
|
+
this.#config = config;
|
|
44
|
+
this.#children = children;
|
|
45
|
+
this.#supervisor = supervisor;
|
|
46
|
+
this.#status = status;
|
|
47
|
+
this.#limits = limits;
|
|
48
|
+
this.#logger = logger;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async serveImmutableArtifact(req: Request, url: URL): Promise<Response | null> {
|
|
52
|
+
if (!this.#config.web.ssr) return null;
|
|
53
|
+
const artifact = GatewayHttpProxy.#immutableArtifacts.find(({ prefix }) => url.pathname.startsWith(prefix));
|
|
54
|
+
if (!artifact) return null;
|
|
55
|
+
const filePath = resolveStaticPath(
|
|
56
|
+
path.join(this.#config.artifactDir, artifact.root),
|
|
57
|
+
url.pathname.slice(artifact.strip),
|
|
58
|
+
);
|
|
59
|
+
if (!filePath) return new Response("Not Found", { status: 404 });
|
|
60
|
+
const file = Bun.file(filePath);
|
|
61
|
+
if (!(await file.exists())) return new Response("Not Found", { status: 404 });
|
|
62
|
+
return this.#fileResponse(req, filePath, {
|
|
63
|
+
contentType: file.type || artifact.type,
|
|
64
|
+
cacheControl: "public, max-age=31536000, immutable",
|
|
65
|
+
anyOrigin: "anyOrigin" in artifact,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async proxyHttp(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response> {
|
|
70
|
+
const child = await this.#pickReadyFederationChild(req);
|
|
71
|
+
if (child?.upstream?.type !== "unix") return this.#respondWithUnavailable(req);
|
|
72
|
+
|
|
73
|
+
const { socketPath } = child.upstream;
|
|
74
|
+
const url = new URL(req.url);
|
|
75
|
+
const upstreamUrl = `http://akan-child${url.pathname}${url.search}`;
|
|
76
|
+
const headers = makeAkanChildProxyHeaders(req, child.idx, server.requestIP(req) ?? undefined);
|
|
77
|
+
child.metrics.activeRequests = (child.metrics.activeRequests ?? 0) + 1;
|
|
78
|
+
child.metrics.totalRequests = (child.metrics.totalRequests ?? 0) + 1;
|
|
79
|
+
const traced = isTraceEnabled();
|
|
80
|
+
const hopStart = traced ? performance.now() : 0;
|
|
81
|
+
const chunkedLimit = req.headers.has("content-length") ? null : this.#limits.bodyLimitOf(req);
|
|
82
|
+
try {
|
|
83
|
+
const upstreamRes = await fetch(upstreamUrl, {
|
|
84
|
+
unix: socketPath,
|
|
85
|
+
method: req.method,
|
|
86
|
+
headers,
|
|
87
|
+
body:
|
|
88
|
+
req.method === "GET" || req.method === "HEAD"
|
|
89
|
+
? undefined
|
|
90
|
+
: chunkedLimit !== null && req.body
|
|
91
|
+
? ServerLimits.limitBody(req.body, chunkedLimit)
|
|
92
|
+
: req.body,
|
|
93
|
+
signal: req.signal,
|
|
94
|
+
redirect: "manual",
|
|
95
|
+
decompress: false,
|
|
96
|
+
});
|
|
97
|
+
return await this.#proxyResponse(req, upstreamRes);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (ServerLimits.isPayloadTooLarge(error)) return ServerLimits.payloadTooLarge();
|
|
100
|
+
if (GatewayHttpProxy.#isUpstreamOpenFailure(error)) {
|
|
101
|
+
this.#logger.error(`Child ${child.idx}/${child.role} upstream is unreachable (${socketPath}); restarting`);
|
|
102
|
+
this.#supervisor.scheduleRestart(child, child.proc, "upstream-open-failed");
|
|
103
|
+
return GatewayHttpProxy.#unavailableResponse(req, "Federation child upstream is unreachable; restarting");
|
|
104
|
+
}
|
|
105
|
+
if (req.signal.aborted) return GatewayHttpProxy.#clientClosedResponse();
|
|
106
|
+
if (GatewayHttpProxy.#isUpstreamMidFlightClose(error)) {
|
|
107
|
+
this.#logger.warn(
|
|
108
|
+
`Child ${child.idx}/${child.role} closed the connection mid-request (${req.method} ${new URL(req.url).pathname})`,
|
|
109
|
+
);
|
|
110
|
+
return GatewayHttpProxy.#badGatewayResponse(req);
|
|
111
|
+
}
|
|
112
|
+
throw error;
|
|
113
|
+
} finally {
|
|
114
|
+
child.metrics.activeRequests = Math.max(0, (child.metrics.activeRequests ?? 1) - 1);
|
|
115
|
+
if (traced) this.#status.recordProxyHop(performance.now() - hopStart);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
static #isUpstreamOpenFailure(error: unknown): boolean {
|
|
120
|
+
if (!error || typeof error !== "object") return false;
|
|
121
|
+
const candidate = error as { code?: unknown; message?: unknown };
|
|
122
|
+
if (typeof candidate.code === "string" && GatewayHttpProxy.#upstreamOpenFailureCodes.has(candidate.code))
|
|
123
|
+
return true;
|
|
124
|
+
return String(candidate.message ?? "").includes("FailedToOpenSocket");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
static #isUpstreamMidFlightClose(error: unknown): boolean {
|
|
128
|
+
if (!error || typeof error !== "object") return false;
|
|
129
|
+
const candidate = error as { code?: unknown; message?: unknown };
|
|
130
|
+
if (candidate.code === "ECONNRESET" || candidate.code === "ConnectionClosed") return true;
|
|
131
|
+
return String(candidate.message ?? "").includes("connection was closed");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
static #clientClosedResponse(): Response {
|
|
135
|
+
return new Response(null, { status: 499, headers: { "cache-control": "no-store" } });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
static #badGatewayResponse(req: Request): Response {
|
|
139
|
+
const detail = "The replica closed the connection before it finished answering.";
|
|
140
|
+
if (req.headers.get("accept")?.includes("text/html")) {
|
|
141
|
+
return new Response(
|
|
142
|
+
GatewayStatusPage.html({
|
|
143
|
+
heading: "Backend dropped the connection",
|
|
144
|
+
detail,
|
|
145
|
+
note: "The replica is restarting — this page reloads itself as soon as it answers.",
|
|
146
|
+
}),
|
|
147
|
+
{ status: 502, headers: GatewayStatusPage.headers("text/html; charset=utf-8") },
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
return new Response(detail, { status: 502, headers: GatewayStatusPage.headers("text/plain; charset=utf-8") });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async #pickReadyFederationChild(req: Request): Promise<ChildState | null> {
|
|
154
|
+
const ready = this.#children.pickFederationChild();
|
|
155
|
+
if (ready?.upstream) return ready;
|
|
156
|
+
const deadline = performance.now() + this.#config.upstreamWaitMs;
|
|
157
|
+
while (performance.now() < deadline) {
|
|
158
|
+
if (this.#children.stopping || req.signal.aborted || this.#supervisor.crashLoopDetail()) return null;
|
|
159
|
+
await Bun.sleep(50);
|
|
160
|
+
const child = this.#children.pickFederationChild();
|
|
161
|
+
if (child?.upstream) return child;
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
#respondWithUnavailable(req: Request): Response {
|
|
167
|
+
const crashDetail = this.#supervisor.crashLoopDetail();
|
|
168
|
+
const page = crashDetail
|
|
169
|
+
? {
|
|
170
|
+
heading: "Backend failed to start",
|
|
171
|
+
detail: crashDetail,
|
|
172
|
+
text: `Backend failed to start after ${GatewayConfig.devMaxChildBootFailures} boot attempts: ${crashDetail}`,
|
|
173
|
+
note: `The dev server stopped retrying after ${GatewayConfig.devMaxChildBootFailures} failed boots. Fix the error and save — this page reloads automatically.`,
|
|
174
|
+
}
|
|
175
|
+
: {
|
|
176
|
+
heading: "Backend is starting",
|
|
177
|
+
detail: "No healthy federation child is ready",
|
|
178
|
+
text: "No healthy federation child is ready",
|
|
179
|
+
note: "A replica is booting or restarting — this page reloads itself as soon as it answers.",
|
|
180
|
+
};
|
|
181
|
+
if (req.headers.get("accept")?.includes("text/html")) {
|
|
182
|
+
return new Response(GatewayStatusPage.html(page), {
|
|
183
|
+
status: 503,
|
|
184
|
+
headers: GatewayStatusPage.headers("text/html; charset=utf-8"),
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return GatewayHttpProxy.#unavailableResponse(req, page.text);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
static #unavailableResponse(req: Request, detail: string): Response {
|
|
191
|
+
const headers = { "cache-control": "no-store" };
|
|
192
|
+
if (!req.headers.get("accept")?.includes("application/json")) return new Response(detail, { status: 503, headers });
|
|
193
|
+
return Response.json(
|
|
194
|
+
{ error: "base.error.serverUnavailable", statusCode: 503, data: { status: 503 }, details: detail },
|
|
195
|
+
{ status: 503, headers },
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async #proxyResponse(req: Request, upstreamRes: Response): Promise<Response> {
|
|
200
|
+
const headers = new Headers(upstreamRes.headers);
|
|
201
|
+
this.#rewriteInternalLocation(headers);
|
|
202
|
+
const proxied = new Response(upstreamRes.body, {
|
|
203
|
+
status: upstreamRes.status,
|
|
204
|
+
statusText: upstreamRes.statusText,
|
|
205
|
+
headers,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
return GatewayHttpProxy.#isProxiedJson(headers)
|
|
209
|
+
? await compressResponse(req, proxied)
|
|
210
|
+
: compressStreamResponse(req, proxied);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
static #isProxiedJson(headers: Headers): boolean {
|
|
214
|
+
return (headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() === "application/json";
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
#rewriteInternalLocation(headers: Headers) {
|
|
218
|
+
const location = headers.get("location");
|
|
219
|
+
if (!location) return;
|
|
220
|
+
try {
|
|
221
|
+
const parsed = new URL(location);
|
|
222
|
+
if (parsed.hostname === AKAN_CHILD_HOST)
|
|
223
|
+
headers.set("location", `${parsed.pathname}${parsed.search}${parsed.hash}`);
|
|
224
|
+
} catch {
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async #fileResponse(req: Request, filePath: string, options: AssetHeaderOptions): Promise<Response> {
|
|
229
|
+
return await encodedFileResponse(req, filePath, options.contentType, assetHeaders(options));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Logger } from "akanjs/common";
|
|
2
|
+
import type { AkanChildRole } from "akanjs/service";
|
|
3
|
+
import { ChildOutputReader } from "../logging/childOutputReader";
|
|
4
|
+
import { HubFileSink } from "../logging/hubFileSink";
|
|
5
|
+
import { LogControlSocket } from "../logging/logControlSocket";
|
|
6
|
+
import { LogHub } from "../logging/logHub";
|
|
7
|
+
import { LogStreamRoute } from "../logging/logStreamRoute";
|
|
8
|
+
import { RotatingLogWriter } from "../logging/rotatingLogWriter";
|
|
9
|
+
import type { GatewayChildren } from "./gatewayChildren";
|
|
10
|
+
import type { GatewayConfig } from "./gatewayConfig";
|
|
11
|
+
|
|
12
|
+
export class GatewayLogging {
|
|
13
|
+
static readonly #ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
|
|
14
|
+
|
|
15
|
+
readonly #config: GatewayConfig;
|
|
16
|
+
readonly #children: GatewayChildren;
|
|
17
|
+
readonly #logger: Logger;
|
|
18
|
+
#logWriter: RotatingLogWriter | null = null;
|
|
19
|
+
#detachFileLog: (() => void) | null = null;
|
|
20
|
+
#logHub: LogHub | null;
|
|
21
|
+
#logControl: LogControlSocket | null = null;
|
|
22
|
+
#logStream: LogStreamRoute | null = null;
|
|
23
|
+
|
|
24
|
+
constructor(config: GatewayConfig, children: GatewayChildren, logger: Logger) {
|
|
25
|
+
this.#config = config;
|
|
26
|
+
this.#children = children;
|
|
27
|
+
this.#logger = logger;
|
|
28
|
+
this.#logHub = LogHub.attach();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
get hub() {
|
|
32
|
+
return this.#logHub;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
get stream() {
|
|
36
|
+
return this.#logStream;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async start() {
|
|
40
|
+
await this.#startLogHub();
|
|
41
|
+
this.#startFileLogging();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async stop() {
|
|
45
|
+
await this.#stopLogHub();
|
|
46
|
+
await this.#stopFileLogging();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#startFileLogging() {
|
|
50
|
+
this.#logWriter = RotatingLogWriter.fromRuntimeDir(this.#config.runtimeDir);
|
|
51
|
+
if (this.#logWriter) this.#detachFileLog = HubFileSink.attach(this.#logWriter, this.#logHub, "gateway");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async #stopFileLogging() {
|
|
55
|
+
this.#detachFileLog?.();
|
|
56
|
+
this.#detachFileLog = null;
|
|
57
|
+
const writer = this.#logWriter;
|
|
58
|
+
this.#logWriter = null;
|
|
59
|
+
await writer?.close();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async #startLogHub() {
|
|
63
|
+
const hub = LogHub.attach();
|
|
64
|
+
this.#logHub = hub;
|
|
65
|
+
hub.onFloorChange((minSev) => this.#children.fanoutToAll({ type: "log.level", minSev }));
|
|
66
|
+
this.#logStream = LogStreamRoute.fromEnv(() => this.#logHub);
|
|
67
|
+
this.#logControl = await LogControlSocket.open(hub, this.#config.runtimeDir, this.#logger);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async #stopLogHub() {
|
|
71
|
+
await this.#logControl?.stop();
|
|
72
|
+
this.#logControl = null;
|
|
73
|
+
this.#logStream = null;
|
|
74
|
+
this.#logHub?.close();
|
|
75
|
+
this.#logHub = null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
writeChildLine(idx: number, role: AkanChildRole, pid: number | null, type: "stdout" | "stderr", line: string) {
|
|
79
|
+
if (Logger.isNdjson) {
|
|
80
|
+
this.#logHub?.ingest(ChildOutputReader.toRecord({ type, text: line, name: "child", role, replicaIdx: idx, pid }));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const prefixedLine = `[child:${idx} ${role}] [${type}] ${line}`;
|
|
84
|
+
if (type === "stdout" || this.#config.printChildStderr || !this.#logWriter) process[type].write(prefixedLine);
|
|
85
|
+
this.#logWriter?.write(`${idx}-${role}`, GatewayLogging.#stripAnsi(prefixedLine));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
writeChildStderrBlock(idx: number, role: AkanChildRole, pid: number | null, lines: string[]) {
|
|
89
|
+
const text = lines.join("");
|
|
90
|
+
if (GatewayLogging.#isBenignRsdwConnectionClosedBlock(text)) return;
|
|
91
|
+
if (Logger.isNdjson) {
|
|
92
|
+
this.#logHub?.ingest(
|
|
93
|
+
ChildOutputReader.toRecord({ type: "stderr", text, name: "child", role, replicaIdx: idx, pid }),
|
|
94
|
+
);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
for (const line of lines) this.writeChildLine(idx, role, pid, "stderr", line);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
static #isBenignRsdwConnectionClosedBlock(text: string): boolean {
|
|
101
|
+
return (
|
|
102
|
+
text.includes('reportGlobalError(weakResponse, Error("Connection closed."))') &&
|
|
103
|
+
text.includes("error: Connection closed.") &&
|
|
104
|
+
text.includes("react-server-dom-webpack")
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
static #stripAnsi(msg: string) {
|
|
109
|
+
return msg.replace(GatewayLogging.#ansiPattern, "");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
2
|
+
import type { AkanIpcMessage } from "akanjs/service";
|
|
3
|
+
import type { GatewayChildren } from "./gatewayChildren";
|
|
4
|
+
|
|
5
|
+
export class GatewayRooms {
|
|
6
|
+
readonly #children: GatewayChildren;
|
|
7
|
+
readonly #logger: Logger;
|
|
8
|
+
readonly #roomChildren = new Map<string, Set<number>>();
|
|
9
|
+
readonly #childRooms = new Map<number, Map<string, Set<string>>>();
|
|
10
|
+
readonly #socketRooms = new Map<string, { childIdx: number; rooms: Set<string> }>();
|
|
11
|
+
readonly #childLiveModels = new Map<number, Set<string>>();
|
|
12
|
+
|
|
13
|
+
constructor(children: GatewayChildren, logger: Logger) {
|
|
14
|
+
this.#children = children;
|
|
15
|
+
this.#logger = logger;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
get roomCount() {
|
|
19
|
+
return this.#roomChildren.size;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
get socketCount() {
|
|
23
|
+
return this.#socketRooms.size;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
roomCountOf(childIdx: number) {
|
|
27
|
+
return this.#childRooms.get(childIdx)?.size ?? 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
deliverPubsub(originIdx: number, message: Extract<AkanIpcMessage, { type: "pubsub.publish" }>) {
|
|
31
|
+
const targets = this.#roomChildren.get(message.roomId);
|
|
32
|
+
if (!targets?.size) {
|
|
33
|
+
const child = this.#children.get(originIdx);
|
|
34
|
+
if (child) child.metrics.pubsubDropCount = (child.metrics.pubsubDropCount ?? 0) + 1;
|
|
35
|
+
this.#logger.verbose(`Dropping pubsub ${message.roomId}; no subscribers`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
for (const childIdx of targets) {
|
|
39
|
+
if (childIdx === originIdx) continue;
|
|
40
|
+
const child = this.#children.get(childIdx);
|
|
41
|
+
if (!child || this.#children.isUnavailable(child)) continue;
|
|
42
|
+
if (
|
|
43
|
+
!this.#children.send(child, {
|
|
44
|
+
type: "pubsub.deliver",
|
|
45
|
+
roomId: message.roomId,
|
|
46
|
+
data: message.data,
|
|
47
|
+
origin: message.origin,
|
|
48
|
+
} satisfies AkanIpcMessage)
|
|
49
|
+
)
|
|
50
|
+
continue;
|
|
51
|
+
child.metrics.pubsubDeliverCount = (child.metrics.pubsubDeliverCount ?? 0) + 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
addRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
56
|
+
const roomChildren = this.#roomChildren.get(roomId) ?? new Set<number>();
|
|
57
|
+
roomChildren.add(childIdx);
|
|
58
|
+
this.#roomChildren.set(roomId, roomChildren);
|
|
59
|
+
|
|
60
|
+
const childRooms = this.#childRooms.get(childIdx) ?? new Map<string, Set<string>>();
|
|
61
|
+
const roomSockets = childRooms.get(roomId) ?? new Set<string>();
|
|
62
|
+
childRooms.set(roomId, roomSockets);
|
|
63
|
+
this.#childRooms.set(childIdx, childRooms);
|
|
64
|
+
|
|
65
|
+
if (socketId) {
|
|
66
|
+
roomSockets.add(socketId);
|
|
67
|
+
const socketRooms = this.#socketRooms.get(socketId) ?? { childIdx, rooms: new Set<string>() };
|
|
68
|
+
socketRooms.rooms.add(roomId);
|
|
69
|
+
this.#socketRooms.set(socketId, socketRooms);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#leaveRoom(childIdx: number, roomId: string) {
|
|
74
|
+
const roomChildren = this.#roomChildren.get(roomId);
|
|
75
|
+
roomChildren?.delete(childIdx);
|
|
76
|
+
if (roomChildren?.size === 0) this.#roomChildren.delete(roomId);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
removeRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
80
|
+
const childRooms = this.#childRooms.get(childIdx);
|
|
81
|
+
const roomSockets = childRooms?.get(roomId);
|
|
82
|
+
if (socketId) {
|
|
83
|
+
this.#forgetSocketRoom(socketId, roomId);
|
|
84
|
+
roomSockets?.delete(socketId);
|
|
85
|
+
if (roomSockets?.size) return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
for (const staleSocketId of roomSockets ?? []) this.#forgetSocketRoom(staleSocketId, roomId);
|
|
89
|
+
this.#leaveRoom(childIdx, roomId);
|
|
90
|
+
childRooms?.delete(roomId);
|
|
91
|
+
if (childRooms?.size === 0) this.#childRooms.delete(childIdx);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
#forgetSocketRoom(socketId: string, roomId: string) {
|
|
95
|
+
const socketRooms = this.#socketRooms.get(socketId);
|
|
96
|
+
socketRooms?.rooms.delete(roomId);
|
|
97
|
+
if (!socketRooms || socketRooms.rooms.size === 0) this.#socketRooms.delete(socketId);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
replaceRoomSnapshot(childIdx: number, rooms: string[]) {
|
|
101
|
+
const held = new Set(rooms);
|
|
102
|
+
for (const roomId of [...(this.#childRooms.get(childIdx)?.keys() ?? [])])
|
|
103
|
+
if (!held.has(roomId)) this.removeRoomMembership(childIdx, roomId);
|
|
104
|
+
for (const roomId of held) this.addRoomMembership(childIdx, roomId);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
removeChildRooms(childIdx: number) {
|
|
108
|
+
for (const roomId of this.#childRooms.get(childIdx)?.keys() ?? []) this.#leaveRoom(childIdx, roomId);
|
|
109
|
+
this.#childRooms.delete(childIdx);
|
|
110
|
+
for (const [socketId, socket] of this.#socketRooms.entries()) {
|
|
111
|
+
if (socket.childIdx === childIdx) this.#socketRooms.delete(socketId);
|
|
112
|
+
}
|
|
113
|
+
this.setLiveModels(childIdx, []);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
setLiveModels(childIdx: number, models: string[]) {
|
|
117
|
+
if (models.length) this.#childLiveModels.set(childIdx, new Set(models));
|
|
118
|
+
else this.#childLiveModels.delete(childIdx);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
fanoutLiveChange(originIdx: number, message: Extract<AkanIpcMessage, { type: "live.change" }>) {
|
|
122
|
+
for (const [childIdx, models] of this.#childLiveModels) {
|
|
123
|
+
const child = this.#children.get(childIdx);
|
|
124
|
+
if (child && childIdx !== originIdx && models.has(message.change.refName)) this.#children.send(child, message);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
requestRoomSnapshots() {
|
|
129
|
+
for (const child of this.#children.values()) {
|
|
130
|
+
if (this.#children.isUnavailable(child)) continue;
|
|
131
|
+
this.#children.send(child, { type: "pubsub.snapshot.request" } satisfies AkanIpcMessage);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
2
|
+
import type { AkanMetricsReport } from "akanjs/service";
|
|
3
|
+
import { ProcessMetricsCollector } from "../processMetricsCollector";
|
|
4
|
+
import type { GatewayChildren } from "./gatewayChildren";
|
|
5
|
+
import type { GatewayConfig } from "./gatewayConfig";
|
|
6
|
+
import type { GatewayRooms } from "./gatewayRooms";
|
|
7
|
+
|
|
8
|
+
export class GatewayStatus {
|
|
9
|
+
readonly #config: GatewayConfig;
|
|
10
|
+
readonly #children: GatewayChildren;
|
|
11
|
+
readonly #rooms: GatewayRooms;
|
|
12
|
+
readonly #logger: Logger;
|
|
13
|
+
#gatewayMetrics: AkanMetricsReport = {};
|
|
14
|
+
#proxyHopCount = 0;
|
|
15
|
+
#proxyHopSumMs = 0;
|
|
16
|
+
#proxyHopMaxMs = 0;
|
|
17
|
+
|
|
18
|
+
constructor(config: GatewayConfig, children: GatewayChildren, rooms: GatewayRooms, logger: Logger) {
|
|
19
|
+
this.#config = config;
|
|
20
|
+
this.#children = children;
|
|
21
|
+
this.#rooms = rooms;
|
|
22
|
+
this.#logger = logger;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
healthStatus() {
|
|
26
|
+
return {
|
|
27
|
+
status: this.#children.stopping ? "stopping" : "running",
|
|
28
|
+
pid: process.pid,
|
|
29
|
+
children: [...this.#children.values()].map((child) => ({
|
|
30
|
+
idx: child.idx,
|
|
31
|
+
role: child.role,
|
|
32
|
+
status: child.status,
|
|
33
|
+
ready: child.ready,
|
|
34
|
+
pid: child.pid,
|
|
35
|
+
upstream: child.upstream,
|
|
36
|
+
restartAttempts: child.restart.attempts,
|
|
37
|
+
restartCount: child.restartCount,
|
|
38
|
+
restartPending: child.restartPending,
|
|
39
|
+
lastExitCode: child.lastExitCode,
|
|
40
|
+
lastRestartAt: child.lastRestartAt,
|
|
41
|
+
lastRestartReason: child.lastRestartReason,
|
|
42
|
+
lastErrorMessage: child.lastErrorMessage,
|
|
43
|
+
})),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
readyStatus() {
|
|
48
|
+
return {
|
|
49
|
+
ready: this.#isReady(),
|
|
50
|
+
pid: process.pid,
|
|
51
|
+
children: [...this.#children.values()].map(({ idx, role, status, ready }) => ({ idx, role, status, ready })),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
#isReady() {
|
|
56
|
+
if (this.#children.stopping) return false;
|
|
57
|
+
if (this.#config.replica.federation + this.#config.replica.all > 0)
|
|
58
|
+
return this.#children.federationCandidates().length > 0;
|
|
59
|
+
return [...this.#children.values()].some((child) => child.ready && !this.#children.isUnavailable(child));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
metricsStatus() {
|
|
63
|
+
return {
|
|
64
|
+
rooms: this.#rooms.roomCount,
|
|
65
|
+
sockets: this.#rooms.socketCount,
|
|
66
|
+
gateway: this.#gatewayMetrics,
|
|
67
|
+
proxyHop: this.#proxyHopCount
|
|
68
|
+
? {
|
|
69
|
+
count: this.#proxyHopCount,
|
|
70
|
+
meanMs: Math.round((this.#proxyHopSumMs / this.#proxyHopCount) * 1000) / 1000,
|
|
71
|
+
maxMs: Math.round(this.#proxyHopMaxMs * 1000) / 1000,
|
|
72
|
+
}
|
|
73
|
+
: null,
|
|
74
|
+
children: [...this.#children.values()].map((child) => ({
|
|
75
|
+
idx: child.idx,
|
|
76
|
+
role: child.role,
|
|
77
|
+
metrics: child.metrics,
|
|
78
|
+
rooms: this.#rooms.roomCountOf(child.idx),
|
|
79
|
+
restartAttempts: child.restart.attempts,
|
|
80
|
+
restartCount: child.restartCount,
|
|
81
|
+
restartPending: child.restartPending,
|
|
82
|
+
lastExitCode: child.lastExitCode,
|
|
83
|
+
lastRestartAt: child.lastRestartAt,
|
|
84
|
+
lastRestartReason: child.lastRestartReason,
|
|
85
|
+
})),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
recordProxyHop(durationMs: number) {
|
|
90
|
+
this.#proxyHopCount += 1;
|
|
91
|
+
this.#proxyHopSumMs += durationMs;
|
|
92
|
+
this.#proxyHopMaxMs = Math.max(this.#proxyHopMaxMs, durationMs);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async reportMetrics() {
|
|
96
|
+
this.#gatewayMetrics = await ProcessMetricsCollector.collect({ role: "gateway" });
|
|
97
|
+
if (process.env.AKAN_MEMORY_LOG !== "1") return;
|
|
98
|
+
this.#logger.verbose(
|
|
99
|
+
`memory role=gateway ${ProcessMetricsCollector.format(this.#gatewayMetrics)} children=${this.#children.size}`,
|
|
100
|
+
);
|
|
101
|
+
for (const child of this.#children.values()) {
|
|
102
|
+
if (!child.metrics.rssBytes) continue;
|
|
103
|
+
const rooms = this.#rooms.roomCountOf(child.idx);
|
|
104
|
+
this.#logger.verbose(
|
|
105
|
+
`memory role=${child.role} idx=${child.idx} ${ProcessMetricsCollector.format({
|
|
106
|
+
...child.metrics,
|
|
107
|
+
pid: child.metrics.pid ?? child.pid,
|
|
108
|
+
})} activeRequests=${child.metrics.activeRequests ?? 0} activeWebSockets=${
|
|
109
|
+
child.metrics.activeWebSockets ?? 0
|
|
110
|
+
} rooms=${rooms} rscPending=${child.metrics.rscPendingRenderCount ?? 0} rscModules=${
|
|
111
|
+
child.metrics.rscLoadedRouteModuleCount ?? 0
|
|
112
|
+
}`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
|
|
2
|
+
import { applySecurityHeaders } from "../assetHeaders";
|
|
3
|
+
|
|
4
|
+
export class GatewayStatusPage {
|
|
5
|
+
static headers(contentType: string): Headers {
|
|
6
|
+
const headers = new Headers({ "content-type": contentType, "cache-control": "no-store" });
|
|
7
|
+
return applySecurityHeaders(headers, { html: contentType.startsWith("text/html") });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
static html({ heading, detail, note }: { heading: string; detail: string; note: string }) {
|
|
11
|
+
return `<!doctype html>
|
|
12
|
+
<html>
|
|
13
|
+
<head>
|
|
14
|
+
<meta charset="utf-8" />
|
|
15
|
+
<title>${GatewayStatusPage.#escapeHtml(heading)}</title>
|
|
16
|
+
<style>
|
|
17
|
+
body { margin: 0; padding: 48px 24px; background: #111827; color: #e5e7eb; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
18
|
+
main { max-width: 720px; margin: 0 auto; }
|
|
19
|
+
h1 { font-size: 20px; color: #f87171; }
|
|
20
|
+
pre { padding: 16px; border-radius: 8px; background: #1f2937; color: #fca5a5; white-space: pre-wrap; word-break: break-word; }
|
|
21
|
+
p { color: #9ca3af; font-size: 14px; }
|
|
22
|
+
</style>
|
|
23
|
+
</head>
|
|
24
|
+
<body>
|
|
25
|
+
<main>
|
|
26
|
+
<h1>${GatewayStatusPage.#escapeHtml(heading)}</h1>
|
|
27
|
+
<pre>${GatewayStatusPage.#escapeHtml(detail)}</pre>
|
|
28
|
+
<p>${GatewayStatusPage.#escapeHtml(note)}</p>
|
|
29
|
+
</main>
|
|
30
|
+
<script>
|
|
31
|
+
const poll = async () => {
|
|
32
|
+
try {
|
|
33
|
+
const res = await fetch(location.href, { cache: "no-store" });
|
|
34
|
+
if (res.ok) { location.reload(); return; }
|
|
35
|
+
} catch {}
|
|
36
|
+
setTimeout(poll, 1000);
|
|
37
|
+
};
|
|
38
|
+
setTimeout(poll, 1000);
|
|
39
|
+
</script>
|
|
40
|
+
</body>
|
|
41
|
+
</html>`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
static #escapeHtml(text: string) {
|
|
45
|
+
const replacements: Record<string, string> = {
|
|
46
|
+
"&": "&",
|
|
47
|
+
"<": "<",
|
|
48
|
+
">": ">",
|
|
49
|
+
'"': """,
|
|
50
|
+
"'": "'",
|
|
51
|
+
};
|
|
52
|
+
return text.replace(/[&<>"']/g, (ch) => replacements[ch] ?? ch);
|
|
53
|
+
}
|
|
54
|
+
}
|