akanjs 3.2.0-rc.11 → 3.2.0-rc.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/CHANGELOG.md +24 -0
  3. package/base/base.ts +2 -1
  4. package/client/clientRuntime.ts +1 -0
  5. package/client/cn.ts +2 -2
  6. package/client/csrTypes.ts +2 -0
  7. package/client/frameConfig.ts +1 -0
  8. package/client/index.ts +249 -26
  9. package/client/locale.ts +1 -0
  10. package/client/route/RouteDefinition.ts +24 -7
  11. package/client/route/routeArgs.ts +7 -0
  12. package/client/router.ts +12 -2
  13. package/client/rscNavigation.ts +1 -0
  14. package/common/CodeTranscript.ts +1 -1
  15. package/constant/constantRegistry.ts +4 -8
  16. package/constant/crystalize.ts +1 -2
  17. package/constant/getDefault.ts +1 -1
  18. package/constant/immerify.ts +1 -1
  19. package/constant/index.ts +78 -21
  20. package/constant/purify.ts +4 -9
  21. package/constant/serialize.ts +4 -2
  22. package/constant/types.ts +1 -0
  23. package/constant/via.ts +1 -2
  24. package/dictionary/locale.ts +1 -1
  25. package/document/databaseRegistry.ts +2 -1
  26. package/document/documentSchema.ts +1 -0
  27. package/document/filterMeta.ts +4 -1
  28. package/document/into.ts +2 -1
  29. package/document/loaderInfo.ts +2 -1
  30. package/document/types.ts +1 -1
  31. package/fetch/client/fetchClient.ts +3 -3
  32. package/fetch/client/httpClient.ts +2 -0
  33. package/fetch/client/wsClient.ts +1 -0
  34. package/package.json +1 -1
  35. package/server/akanApp.ts +103 -1270
  36. package/server/akanServer.ts +1 -1
  37. package/server/console.ts +3 -2
  38. package/server/gateway/childSupervisor.ts +325 -0
  39. package/server/gateway/devHostChannel.ts +40 -0
  40. package/server/gateway/gatewayChildren.ts +135 -0
  41. package/server/gateway/gatewayConfig.ts +182 -0
  42. package/server/gateway/gatewayHttpProxy.ts +231 -0
  43. package/server/gateway/gatewayLogging.ts +111 -0
  44. package/server/gateway/gatewayRooms.ts +134 -0
  45. package/server/gateway/gatewayStatus.ts +116 -0
  46. package/server/gateway/gatewayStatusPage.ts +54 -0
  47. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  48. package/server/index.ts +257 -17
  49. package/server/logging/logControlSocket.ts +42 -3
  50. package/server/mcp/McpDispatcher.ts +6 -24
  51. package/server/rscClient.tsx +14 -8
  52. package/server/sitemap.ts +1 -0
  53. package/service/injectInfo.ts +2 -1
  54. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +3 -3
  55. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  56. package/service/serviceRegistry.ts +1 -0
  57. package/signal/SignalFailure.ts +21 -0
  58. package/signal/agentTurnStream.ts +5 -2
  59. package/signal/index.ts +298 -30
  60. package/signal/resolveFieldContext.ts +34 -0
  61. package/signal/serializer/fetch.serializer.ts +7 -10
  62. package/signal/signalContext.ts +4 -31
  63. package/signal/trace.ts +3 -0
  64. package/store/baseSt.ts +1 -0
  65. package/store/index.ts +125 -18
  66. package/store/stateBuilder.ts +2 -0
  67. package/types/base/base.d.ts +2 -1
  68. package/types/client/clientRuntime.d.ts +1 -0
  69. package/types/client/cn.d.ts +2 -2
  70. package/types/client/csrTypes.d.ts +2 -0
  71. package/types/client/frameConfig.d.ts +1 -0
  72. package/types/client/index.d.ts +25 -26
  73. package/types/client/locale.d.ts +1 -0
  74. package/types/client/route/RouteDefinition.d.ts +2 -2
  75. package/types/client/route/routeArgs.d.ts +6 -0
  76. package/types/client/router.d.ts +2 -1
  77. package/types/client/rscNavigation.d.ts +1 -0
  78. package/types/common/CodeTranscript.d.ts +1 -1
  79. package/types/constant/constantRegistry.d.ts +3 -1
  80. package/types/constant/crystalize.d.ts +1 -1
  81. package/types/constant/getDefault.d.ts +1 -1
  82. package/types/constant/immerify.d.ts +1 -1
  83. package/types/constant/index.d.ts +21 -21
  84. package/types/constant/purify.d.ts +2 -1
  85. package/types/constant/serialize.d.ts +1 -1
  86. package/types/constant/types.d.ts +1 -0
  87. package/types/dictionary/base.dictionary.d.ts +1 -1
  88. package/types/dictionary/dictionary.d.ts +8 -8
  89. package/types/dictionary/locale.d.ts +1 -1
  90. package/types/document/databaseRegistry.d.ts +2 -1
  91. package/types/document/documentSchema.d.ts +1 -0
  92. package/types/document/filterMeta.d.ts +4 -1
  93. package/types/document/into.d.ts +1 -1
  94. package/types/document/loaderInfo.d.ts +2 -1
  95. package/types/document/types.d.ts +1 -1
  96. package/types/fetch/client/fetchClient.d.ts +2 -1
  97. package/types/fetch/client/httpClient.d.ts +2 -0
  98. package/types/fetch/client/wsClient.d.ts +1 -0
  99. package/types/server/akanApp.d.ts +2 -20
  100. package/types/server/console.d.ts +3 -2
  101. package/types/server/gateway/childSupervisor.d.ts +33 -0
  102. package/types/server/gateway/devHostChannel.d.ts +13 -0
  103. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  104. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  105. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  106. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  107. package/types/server/gateway/gatewayRooms.d.ts +22 -0
  108. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  109. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  110. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  111. package/types/server/index.d.ts +17 -17
  112. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  113. package/types/server/sitemap.d.ts +1 -0
  114. package/types/service/injectInfo.d.ts +2 -1
  115. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +1 -14
  116. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  117. package/types/service/serviceRegistry.d.ts +1 -0
  118. package/types/signal/SignalFailure.d.ts +1 -0
  119. package/types/signal/agentTurnStream.d.ts +1 -0
  120. package/types/signal/index.d.ts +31 -30
  121. package/types/signal/resolveFieldContext.d.ts +15 -0
  122. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  123. package/types/signal/signalContext.d.ts +1 -13
  124. package/types/signal/trace.d.ts +3 -0
  125. package/types/store/baseSt.d.ts +1 -0
  126. package/types/store/index.d.ts +17 -17
  127. package/types/store/stateBuilder.d.ts +2 -0
  128. package/types/ui/Agent/Chat.d.ts +5 -2
  129. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  130. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  131. package/types/ui/Reference/origin.d.ts +1 -0
  132. package/types/ui/overlayLayer.d.ts +6 -1
  133. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  134. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  135. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +14 -10
  136. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  137. package/types/vendor/use-agentic/types.d.ts +6 -0
  138. package/types/webkit/CsrGuards.d.ts +2 -0
  139. package/ui/Agent/Chat.tsx +96 -116
  140. package/ui/Agent/ChatHeader.tsx +59 -0
  141. package/ui/Agent/ChatPendingCards.tsx +49 -0
  142. package/ui/Agent/fetchRunner.ts +8 -1
  143. package/ui/BottomSheet.tsx +1 -1
  144. package/ui/Dialog/LegacyModal.tsx +1 -1
  145. package/ui/Dialog/Modal.tsx +1 -1
  146. package/ui/Popconfirm.tsx +1 -1
  147. package/ui/Reference/origin.ts +1 -0
  148. package/ui/overlayLayer.ts +22 -1
  149. package/vendor/@akanjs/native/CHANGELOG.md +6 -1
  150. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  151. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  152. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +275 -0
  153. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  154. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  155. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  156. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  157. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  158. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  159. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  160. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  161. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  162. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +14 -10
  163. package/vendor/use-agentic/AgentSession.ts +11 -11
  164. package/vendor/use-agentic/CHANGELOG.md +6 -0
  165. package/vendor/use-agentic/Compaction.ts +2 -1
  166. package/vendor/use-agentic/ToolRunner.ts +3 -15
  167. package/vendor/use-agentic/Transcript.ts +6 -3
  168. package/vendor/use-agentic/WIRE.md +12 -1
  169. package/vendor/use-agentic/failureCode.ts +44 -0
  170. package/vendor/use-agentic/httpRunner.ts +14 -3
  171. package/vendor/use-agentic/types.ts +6 -0
  172. package/webkit/CsrGuards.ts +7 -2
  173. package/webkit/useLocation.ts +3 -2
@@ -0,0 +1,182 @@
1
+ import path from "node:path";
2
+ import type { AkanChildRole, AkanUpstream } from "akanjs/service";
3
+ import { getApiPrefix, getWsPrefix, normalizeRoutePrefix } from "../../base/baseEnv";
4
+ import type { RestartPolicy } from "../../common/restartSchedule";
5
+ import { resolveRuntimeDir } from "../lifecycle/runtimeDir";
6
+ import { getWebConfigFromEnv } from "../types";
7
+
8
+ export interface AkanAppOptions {
9
+ replica?: number | string;
10
+ serverPath?: string;
11
+ runtimeDir?: string;
12
+ port?: number;
13
+ wsBasePort?: number;
14
+ openapi?: boolean;
15
+ /** Signal endpoint mount, `/api` by default; handed down as `AKAN_API_PREFIX` (CSR/mobile follow akan.config.ts). */
16
+ prefix?: string;
17
+ /** Where the websocket upgrade sits under `prefix`, `/ws` by default. Handed down as `AKAN_WS_PREFIX`. */
18
+ websocketPrefix?: string;
19
+ /** Boot only these modules and what they reach; omitted or empty mounts every enabled one. `AKAN_MODULES`. */
20
+ modules?: string[];
21
+ /** Mount all but these and whatever reaches them, applied after `modules`. `AKAN_DISABLE_MODULES`. */
22
+ disableModules?: string[];
23
+ /** Like `disableModules`, by owning lib. `AKAN_DISABLE_LIBS`. */
24
+ disableLibs?: string[];
25
+ /** In-process replica; default on for one env-set traffic replica, off if `replica` is passed or AKAN_SOLO=false. */
26
+ solo?: boolean;
27
+ }
28
+
29
+ interface AkanReplicaConfig {
30
+ federation: number;
31
+ batch: number;
32
+ all: number;
33
+ total: number;
34
+ value: string;
35
+ }
36
+
37
+ export interface GatewayUpstream {
38
+ http: Extract<AkanUpstream, { type: "unix" }>;
39
+ ws?: Extract<AkanUpstream, { type: "tcp" }>;
40
+ }
41
+
42
+ export class GatewayConfig {
43
+ static readonly devMaxChildBootFailures = 3;
44
+
45
+ readonly devHosted = process.env.AKAN_COMMAND_TYPE === "start";
46
+ readonly childRestartPolicy: RestartPolicy = {
47
+ min: 1_000,
48
+ max: 30_000,
49
+ ...(this.devHosted ? { maxAttempts: GatewayConfig.devMaxChildBootFailures - 1 } : {}),
50
+ };
51
+ readonly healthTimeoutMs = GatewayConfig.#parseHealthTimeoutMs();
52
+ readonly upstreamWaitMs = GatewayConfig.#parseUpstreamWaitMs();
53
+ /** Child stderr is mostly bundler/runtime noise, kept to the log file; with none it may be a crash's only trace. */
54
+ readonly printChildStderr = process.env.AKAN_CHILD_STDERR === "1";
55
+ readonly serverPath: string;
56
+ readonly artifactDir: string;
57
+ readonly replica: AkanReplicaConfig;
58
+ readonly runtimeDir: string;
59
+ readonly socketRunId = `${process.pid}-${Date.now().toString(36)}`;
60
+ readonly port: number;
61
+ readonly wsBasePort: number;
62
+ readonly openapi?: boolean;
63
+ readonly prefix: string;
64
+ readonly websocketPrefix: string;
65
+ readonly web = getWebConfigFromEnv();
66
+ readonly modules: string[];
67
+ readonly disableModules: string[];
68
+ readonly disableLibs: string[];
69
+ readonly solo: boolean;
70
+
71
+ constructor(serverPath: string, options: AkanAppOptions) {
72
+ this.serverPath = GatewayConfig.#resolveServerPath(options.serverPath ?? serverPath);
73
+ this.artifactDir = path.resolve(path.dirname(this.serverPath), ".akan", "artifact");
74
+ this.replica = GatewayConfig.#parseReplicaConfig(options.replica);
75
+ this.runtimeDir = resolveRuntimeDir(options.runtimeDir);
76
+ this.port = Number(options.port ?? process.env.PORT ?? 8282);
77
+ this.wsBasePort = Number(options.wsBasePort ?? process.env.AKAN_WS_BASE_PORT ?? this.port + 10_000);
78
+ this.openapi = options.openapi;
79
+ this.prefix = normalizeRoutePrefix(options.prefix) ?? getApiPrefix();
80
+ this.websocketPrefix = normalizeRoutePrefix(options.websocketPrefix) ?? getWsPrefix();
81
+ this.modules = options.modules ?? [];
82
+ this.disableModules = options.disableModules ?? [];
83
+ this.disableLibs = options.disableLibs ?? [];
84
+ this.solo = GatewayConfig.#resolveSolo(options, this.replica);
85
+ }
86
+
87
+ static #resolveSolo(options: AkanAppOptions, replica: AkanReplicaConfig) {
88
+ if (options.solo !== undefined) return options.solo;
89
+ if (process.env.AKAN_SOLO === "false" || process.env.AKAN_SOLO === "0") return false;
90
+ if (process.env.AKAN_COMMAND_TYPE === "start") return false;
91
+ if (options.replica !== undefined) return false;
92
+ return replica.total === 1 && replica.batch === 0;
93
+ }
94
+
95
+ static #resolveServerPath(serverPath: string) {
96
+ const baseDir = path.dirname(Bun.main);
97
+ const resolved = path.isAbsolute(serverPath) ? serverPath : path.resolve(baseDir, serverPath);
98
+ if (path.extname(resolved)) return resolved;
99
+ return Bun.main.endsWith(".js") ? `${resolved}.js` : `${resolved}.ts`;
100
+ }
101
+
102
+ static #parseReplicaConfig(value?: number | string): AkanReplicaConfig {
103
+ const configured = value ?? process.env.AKAN_REPLICA;
104
+ const raw = String(configured ?? "0,0,1").trim();
105
+ const [federationRaw, batchRaw, allRaw] = raw.split(",");
106
+ const federation = GatewayConfig.#parseReplicaCount(federationRaw, 0);
107
+ const batch = GatewayConfig.#parseReplicaCount(batchRaw, 0);
108
+ const all = GatewayConfig.#parseReplicaCount(allRaw, configured == null ? 1 : 0);
109
+ const normalizedAll = federation + batch + all > 0 ? all : 1;
110
+ return {
111
+ federation,
112
+ batch,
113
+ all: normalizedAll,
114
+ total: federation + batch + normalizedAll,
115
+ value: `${federation},${batch},${normalizedAll}`,
116
+ };
117
+ }
118
+
119
+ static #parseReplicaCount(value: string | undefined, fallback: number) {
120
+ const parsed = Number.parseInt(value ?? "", 10);
121
+ return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
122
+ }
123
+
124
+ static #defaultChildNodeEnv() {
125
+ if (process.env.AKAN_COMMAND_TYPE === "start") return "development";
126
+ if (process.env.AKAN_COMMAND_TYPE === "build") return "production";
127
+ if (process.env.NODE_ENV) return process.env.NODE_ENV;
128
+ return Bun.main.endsWith(".js") ? "production" : "development";
129
+ }
130
+
131
+ static #parseHealthTimeoutMs() {
132
+ const configured = Number(process.env.AKAN_HEALTH_TIMEOUT_MS);
133
+ if (Number.isFinite(configured) && configured > 0) return configured;
134
+ return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
135
+ }
136
+
137
+ static #parseUpstreamWaitMs() {
138
+ const configured = Number(process.env.AKAN_UPSTREAM_WAIT_MS);
139
+ if (Number.isFinite(configured) && configured >= 0) return configured;
140
+ return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
141
+ }
142
+
143
+ static childShutdownWaitMs() {
144
+ const configured = Number(process.env.AKAN_CHILD_SHUTDOWN_WAIT_MS);
145
+ if (Number.isFinite(configured) && configured > 0) return configured;
146
+ return process.env.AKAN_COMMAND_TYPE === "start" ? 5_000 : 30_000;
147
+ }
148
+
149
+ childEnv(idx: number, role: AkanChildRole) {
150
+ return {
151
+ PORT: String(this.port),
152
+ NODE_ENV: GatewayConfig.#defaultChildNodeEnv(),
153
+ AKAN_REPLICA: this.replica.value,
154
+ AKAN_REPLICA_IDX: String(idx),
155
+ AKAN_APP_DIR: path.dirname(this.serverPath),
156
+ SERVER_MODE: role,
157
+ AKAN_API_PREFIX: this.prefix,
158
+ AKAN_WS_PREFIX: this.websocketPrefix,
159
+ ...(this.openapi === undefined ? {} : { AKAN_OPENAPI: this.openapi ? "true" : "false" }),
160
+ ...(this.modules.length ? { AKAN_MODULES: this.modules.join(",") } : {}),
161
+ ...(this.disableModules.length ? { AKAN_DISABLE_MODULES: this.disableModules.join(",") } : {}),
162
+ ...(this.disableLibs.length ? { AKAN_DISABLE_LIBS: this.disableLibs.join(",") } : {}),
163
+ };
164
+ }
165
+
166
+ roleOf(idx: number): AkanChildRole {
167
+ if (idx < this.replica.federation) return "federation";
168
+ if (idx < this.replica.federation + this.replica.batch) return "batch";
169
+ return "all";
170
+ }
171
+
172
+ childUpstreamOf(idx: number, role: AkanChildRole): GatewayUpstream {
173
+ return {
174
+ http: { type: "unix", socketPath: path.join(this.runtimeDir, `akan-child-${this.socketRunId}-${idx}.sock`) },
175
+ ws: role === "batch" ? undefined : { type: "tcp", host: "127.0.0.1", port: this.wsBasePort + idx },
176
+ };
177
+ }
178
+
179
+ isWebSocketPath(pathname: string) {
180
+ return pathname === `${this.prefix}${this.websocketPrefix}` || pathname === "/_akan/hmr";
181
+ }
182
+ }
@@ -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
+ }