@sigil-dev/grimoire 0.9.2 → 0.9.4
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/index.ts +37 -35
- package/package.json +9 -12
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +31 -8
- package/src/client/enhance.ts +102 -98
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +5 -5
- package/src/client/router.ts +529 -371
- package/src/client/scope.ts +22 -22
- package/src/dev/compile-module.ts +163 -163
- package/src/dev/effect-registry.ts +23 -23
- package/src/dev/graph.ts +114 -114
- package/src/dev/hmr-client.ts +185 -185
- package/src/dev/loader.ts +47 -47
- package/src/dev/paths.ts +14 -14
- package/src/dev/runtime-bundle.ts +52 -52
- package/src/dev/watcher.ts +47 -46
- package/src/env/dynamic-private.ts +19 -19
- package/src/env/dynamic-public.ts +22 -22
- package/src/env/index.ts +25 -25
- package/src/env/plugin.ts +19 -19
- package/src/env/private.ts +5 -5
- package/src/env/public.ts +7 -7
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +114 -114
- package/src/integrations/vite.ts +73 -73
- package/src/logger/index.ts +4 -4
- package/src/logger/instance.ts +6 -6
- package/src/logger/logger.ts +113 -113
- package/src/logger/request-middleware.ts +24 -24
- package/src/logger/transports.ts +117 -117
- package/src/logger/types.ts +39 -39
- package/src/rendering/head.ts +47 -47
- package/src/rendering/hydrate.ts +146 -119
- package/src/rendering/index.ts +573 -372
- package/src/rendering/ssrPlugin.ts +69 -69
- package/src/routing/manifest-gen.ts +55 -42
- package/src/routing/router.ts +135 -109
- package/src/routing/scanner.ts +187 -141
- package/src/routing/transform-routes.ts +102 -102
- package/src/sentinels/error.ts +52 -52
- package/src/sentinels/fail.ts +41 -41
- package/src/sentinels/redirect.ts +35 -35
- package/src/server/build.ts +255 -219
- package/src/server/context.ts +10 -10
- package/src/server/cookie-utils.ts +66 -66
- package/src/server/coordinator.ts +364 -356
- package/src/server/hooks.ts +114 -114
- package/src/server/index.ts +677 -658
- package/src/server/interactive.ts +56 -56
- package/src/server/plugins.ts +121 -120
- package/src/server/worker.ts +58 -58
- package/src/typegen/index.ts +389 -356
- package/src/types.ts +8 -4
- package/test/client-router.test.ts +295 -35
- package/test/context.test.ts +52 -52
- package/test/env.test.ts +70 -70
- package/test/exports.test.ts +37 -37
- package/test/fail.test.ts +46 -46
- package/test/headers.test.ts +100 -100
- package/test/hydration.test.ts +119 -119
- package/test/middleware.test.ts +223 -223
- package/test/preload.ts +5 -5
- package/test/redirect-error.test.ts +112 -112
- package/test/rendering.test.ts +728 -579
- package/test/routing.test.ts +194 -81
- package/test/scanning.test.ts +254 -200
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +354 -249
- package/test/streaming.test.ts +242 -125
- package/test/transform-routes.test.ts +87 -84
- package/test/typegen.test.ts +697 -682
- package/tsconfig.json +10 -10
- package/.grimoire/_routes.dom.js +0 -8
- package/.grimoire/_routes.hydrate.js +0 -8
- package/.grimoire/tsconfig.generated.json +0 -11
- package/.grimoire/types/ambient.d.ts +0 -59
- package/.grimoire/types/api/hello/$types.d.ts +0 -50
- package/.grimoire/types/api/items/$types.d.ts +0 -50
- package/.grimoire/types/echo/$types.d.ts +0 -50
- package/.grimoire/types/env-private.d.ts +0 -5
- package/.grimoire/types/env-public.d.ts +0 -5
- package/.grimoire/types/mixed/$types.d.ts +0 -50
- package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
- package/.grimoire/types/reject/$types.d.ts +0 -50
- package/public/__grimoire__/hydrate.js +0 -585
- package/public/__grimoire__/index.js +0 -490
|
@@ -1,356 +1,364 @@
|
|
|
1
|
-
import { join } from "node:path";
|
|
2
|
-
import { type Subprocess, spawn } from "bun";
|
|
3
|
-
import { log } from "../logger/instance";
|
|
4
|
-
import { matchRoute } from "../routing/router";
|
|
5
|
-
import { type RouteFile, type RouteTree, scanRoutes } from "../routing/scanner";
|
|
6
|
-
import type {
|
|
7
|
-
CoordinatorContext,
|
|
8
|
-
GrimoireConfig,
|
|
9
|
-
GrimoirePlugin,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
return
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
lw.
|
|
153
|
-
lw.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
let
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
...
|
|
215
|
-
...
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
(
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
upstream
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
ws.
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
//@ts-expect-error we give it data upstream
|
|
310
|
-
ws.data.upstream
|
|
311
|
-
},
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
stop
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
function
|
|
350
|
-
const
|
|
351
|
-
const
|
|
352
|
-
.update(secret + payload)
|
|
353
|
-
.digest("hex");
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { type Subprocess, spawn } from "bun";
|
|
3
|
+
import { log } from "../logger/instance";
|
|
4
|
+
import { matchRoute } from "../routing/router";
|
|
5
|
+
import { type RouteFile, type RouteTree, scanRoutes } from "../routing/scanner";
|
|
6
|
+
import type {
|
|
7
|
+
CoordinatorContext,
|
|
8
|
+
GrimoireConfig,
|
|
9
|
+
GrimoirePlugin,
|
|
10
|
+
PluginContext,
|
|
11
|
+
WorkerDescriptor,
|
|
12
|
+
WorkerMode,
|
|
13
|
+
} from "../types";
|
|
14
|
+
import { buildProject } from "./build";
|
|
15
|
+
import {
|
|
16
|
+
runHook,
|
|
17
|
+
runRouteRequest,
|
|
18
|
+
runSerializeLocals,
|
|
19
|
+
runWorkerSpawn,
|
|
20
|
+
} from "./plugins";
|
|
21
|
+
|
|
22
|
+
const logger = log.scope("loom");
|
|
23
|
+
|
|
24
|
+
async function waitForWorkers(
|
|
25
|
+
workers: LiveWorker[],
|
|
26
|
+
timeoutMs = 10_000,
|
|
27
|
+
): Promise<void> {
|
|
28
|
+
const ready = new Set<number>();
|
|
29
|
+
const start = Date.now();
|
|
30
|
+
while (ready.size < workers.length) {
|
|
31
|
+
if (Date.now() - start > timeoutMs) {
|
|
32
|
+
const pending = workers
|
|
33
|
+
.filter((w) => !ready.has(w.descriptor.globalIndex))
|
|
34
|
+
.map(
|
|
35
|
+
(w) =>
|
|
36
|
+
w.descriptor.name ?? `${w.descriptor.mode}-${w.descriptor.index}`,
|
|
37
|
+
)
|
|
38
|
+
.join(", ");
|
|
39
|
+
throw new Error(`Grimoire: workers timed out: ${pending}`);
|
|
40
|
+
}
|
|
41
|
+
for (const w of workers) {
|
|
42
|
+
if (!ready.has(w.descriptor.globalIndex) && w.descriptor.pid != null) {
|
|
43
|
+
ready.add(w.descriptor.globalIndex);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
await Bun.sleep(50);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function roundRobin(workers: WorkerDescriptor[]): WorkerDescriptor {
|
|
51
|
+
const idx = roundRobinCounter++ % workers.length;
|
|
52
|
+
return workers[idx];
|
|
53
|
+
}
|
|
54
|
+
let roundRobinCounter = 0;
|
|
55
|
+
|
|
56
|
+
function consistentHash(
|
|
57
|
+
req: Request,
|
|
58
|
+
workers: WorkerDescriptor[],
|
|
59
|
+
): WorkerDescriptor {
|
|
60
|
+
const key = req.headers.get("cookie") ?? req.url;
|
|
61
|
+
let hash = 0;
|
|
62
|
+
for (let i = 0; i < key.length; i++)
|
|
63
|
+
hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
|
|
64
|
+
return workers[hash % workers.length];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function defaultRoute(
|
|
68
|
+
req: Request,
|
|
69
|
+
workers: WorkerDescriptor[],
|
|
70
|
+
tree: RouteTree,
|
|
71
|
+
): WorkerDescriptor {
|
|
72
|
+
const isWs = req.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
73
|
+
if (isWs) {
|
|
74
|
+
const ws = workers.filter((w) => w.mode === "ws" || w.mode === "full");
|
|
75
|
+
if (ws.length) return consistentHash(req, ws);
|
|
76
|
+
}
|
|
77
|
+
const url = new URL(req.url);
|
|
78
|
+
const matched = matchRoute(tree, url);
|
|
79
|
+
if (matched?.route.type === "server") {
|
|
80
|
+
const api = workers.filter((w) => w.mode === "api" || w.mode === "full");
|
|
81
|
+
if (api.length) return roundRobin(api);
|
|
82
|
+
}
|
|
83
|
+
const frontend = workers.filter(
|
|
84
|
+
(w) => w.mode === "frontend" || w.mode === "full",
|
|
85
|
+
);
|
|
86
|
+
if (frontend.length) return roundRobin(frontend);
|
|
87
|
+
return workers[0];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface ScaleSpec {
|
|
91
|
+
api?: number;
|
|
92
|
+
frontend?: number;
|
|
93
|
+
ws?: number;
|
|
94
|
+
[mode: string]: number | undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface CoordinatorOptions {
|
|
98
|
+
config: GrimoireConfig;
|
|
99
|
+
plugins: GrimoirePlugin[];
|
|
100
|
+
scale: ScaleSpec;
|
|
101
|
+
noBuild: boolean;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface LiveWorker {
|
|
105
|
+
descriptor: WorkerDescriptor;
|
|
106
|
+
process: Subprocess;
|
|
107
|
+
port: number;
|
|
108
|
+
env: Record<string, string>;
|
|
109
|
+
intentional: boolean; // ← add
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function startCoordinator(options: CoordinatorOptions) {
|
|
113
|
+
const { config, plugins, scale, noBuild } = options;
|
|
114
|
+
const { port = 3000, host = "localhost", routes = "src/routes" } = config;
|
|
115
|
+
let stopping = false;
|
|
116
|
+
|
|
117
|
+
const workerEntry = join(import.meta.dir, "./worker.ts");
|
|
118
|
+
|
|
119
|
+
// ── inner helpers (close over plugins/stopping/workerEntry) ──
|
|
120
|
+
|
|
121
|
+
function spawnWorker(lw: LiveWorker): void {
|
|
122
|
+
const proc = spawn(["bun", "run", workerEntry], {
|
|
123
|
+
env: lw.env,
|
|
124
|
+
ipc(message) {
|
|
125
|
+
if (message?.ready) {
|
|
126
|
+
lw.descriptor.pid = proc.pid;
|
|
127
|
+
runHook(plugins, "onWorkerReady", lw.descriptor);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
onExit(_, exitCode) {
|
|
131
|
+
if (lw.intentional) {
|
|
132
|
+
lw.intentional = false;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
runHook(
|
|
136
|
+
plugins,
|
|
137
|
+
"onWorkerDeath",
|
|
138
|
+
lw.descriptor,
|
|
139
|
+
stopping ? "intentional" : "crash",
|
|
140
|
+
);
|
|
141
|
+
if (!stopping) {
|
|
142
|
+
logger.error(
|
|
143
|
+
`worker ${lw.descriptor.name ?? `${lw.descriptor.mode}-${lw.descriptor.index}`} crashed (exit ${exitCode}), respawning...`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
lw.process = proc;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function respawnWorker(lw: LiveWorker): Promise<void> {
|
|
152
|
+
lw.intentional = true;
|
|
153
|
+
lw.process.kill();
|
|
154
|
+
lw.descriptor.pid = undefined;
|
|
155
|
+
spawnWorker(lw);
|
|
156
|
+
await waitForWorkers([lw]);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 0. plugin resolution
|
|
160
|
+
const pluginCtx: PluginContext = {
|
|
161
|
+
mode: config.dev ? "development" : "production",
|
|
162
|
+
plugins: new Map(plugins.map((p) => [p.name, p])),
|
|
163
|
+
logger: log.scope("plugins"),
|
|
164
|
+
};
|
|
165
|
+
await runHook(plugins, "onPluginsResolved", pluginCtx);
|
|
166
|
+
|
|
167
|
+
// 1. build
|
|
168
|
+
if (!noBuild) {
|
|
169
|
+
const { result } = await buildProject(config, plugins);
|
|
170
|
+
if (!result.success) throw new Error("Grimoire: build failed");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 2. ephemeral secret
|
|
174
|
+
const secret = crypto.randomUUID() + crypto.randomUUID();
|
|
175
|
+
|
|
176
|
+
// 3. scan routes
|
|
177
|
+
const tree = await scanRoutes(routes, process.cwd());
|
|
178
|
+
|
|
179
|
+
// 4. route slices
|
|
180
|
+
const slices: Record<string, RouteFile[]> = {
|
|
181
|
+
api: tree.routes.filter((r) => r.type === "server"),
|
|
182
|
+
ws: tree.routes.filter((r) => r.type === "server"),
|
|
183
|
+
frontend: tree.routes.filter(
|
|
184
|
+
(r) => r.type === "page" || r.type === "simple",
|
|
185
|
+
),
|
|
186
|
+
full: [...tree.routes],
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// 5. spawn workers
|
|
190
|
+
const liveWorkers: LiveWorker[] = [];
|
|
191
|
+
let globalIndex = 0;
|
|
192
|
+
let nextPort = port + 1;
|
|
193
|
+
|
|
194
|
+
for (const [mode, count = 0] of Object.entries(scale)) {
|
|
195
|
+
for (let i = 0; i < count; i++) {
|
|
196
|
+
const workerPort = nextPort++;
|
|
197
|
+
const descriptor: WorkerDescriptor = {
|
|
198
|
+
mode: mode as WorkerMode,
|
|
199
|
+
index: i + 1,
|
|
200
|
+
globalIndex: globalIndex++,
|
|
201
|
+
internalUrl: `http://127.0.0.1:${workerPort}`,
|
|
202
|
+
routes: slices[mode] ?? slices.full,
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const publicEnvVars: Record<string, string> = {};
|
|
206
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
207
|
+
if (k.startsWith("PUBLIC_") && v !== undefined) publicEnvVars[k] = v;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const workerEnv = await runWorkerSpawn(plugins, descriptor);
|
|
211
|
+
if (workerEnv.name) descriptor.name = workerEnv.name;
|
|
212
|
+
|
|
213
|
+
const env = {
|
|
214
|
+
...process.env,
|
|
215
|
+
...workerEnv.env,
|
|
216
|
+
...publicEnvVars,
|
|
217
|
+
GRIMOIRE_MODE: mode,
|
|
218
|
+
GRIMOIRE_WORKER_INDEX: String(i),
|
|
219
|
+
GRIMOIRE_WORKER_PORT: String(workerPort),
|
|
220
|
+
GRIMOIRE_INTERNAL_SECRET: secret,
|
|
221
|
+
GRIMOIRE_WORKER_NAME: descriptor.name ?? `${mode}-${i}`,
|
|
222
|
+
} as Record<string, string>;
|
|
223
|
+
|
|
224
|
+
const lw: LiveWorker = {
|
|
225
|
+
descriptor,
|
|
226
|
+
process: null as any,
|
|
227
|
+
port: workerPort,
|
|
228
|
+
env,
|
|
229
|
+
intentional: false,
|
|
230
|
+
};
|
|
231
|
+
spawnWorker(lw);
|
|
232
|
+
liveWorkers.push(lw);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// 6. wait for ready
|
|
237
|
+
await waitForWorkers(liveWorkers);
|
|
238
|
+
|
|
239
|
+
// 7. onCoordinatorStart
|
|
240
|
+
const ctx: CoordinatorContext = {
|
|
241
|
+
workers: liveWorkers.map((w) => w.descriptor),
|
|
242
|
+
port,
|
|
243
|
+
secret,
|
|
244
|
+
routes: tree,
|
|
245
|
+
};
|
|
246
|
+
await runHook(plugins, "onCoordinatorStart", ctx);
|
|
247
|
+
|
|
248
|
+
// 8. coordinator server
|
|
249
|
+
const server = Bun.serve({
|
|
250
|
+
port,
|
|
251
|
+
hostname: host,
|
|
252
|
+
fetch: async (req) => {
|
|
253
|
+
const url = new URL(req.url);
|
|
254
|
+
const isWsUpgrade =
|
|
255
|
+
req.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
256
|
+
|
|
257
|
+
if (isWsUpgrade) {
|
|
258
|
+
const descriptors = liveWorkers.map((w) => w.descriptor);
|
|
259
|
+
const chosen =
|
|
260
|
+
(await runRouteRequest(plugins, req, descriptors, tree)) ??
|
|
261
|
+
defaultRoute(req, descriptors, tree);
|
|
262
|
+
|
|
263
|
+
//@ts-expect-error
|
|
264
|
+
if (
|
|
265
|
+
server.upgrade(req, {
|
|
266
|
+
data: {
|
|
267
|
+
workerUrl: chosen.internalUrl,
|
|
268
|
+
pathname: url.pathname + url.search,
|
|
269
|
+
},
|
|
270
|
+
})
|
|
271
|
+
) {
|
|
272
|
+
return undefined as unknown as Response;
|
|
273
|
+
}
|
|
274
|
+
return new Response("Upgrade Required", { status: 426 });
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const locals: App.Locals = {};
|
|
278
|
+
const descriptors = liveWorkers.map((w) => w.descriptor);
|
|
279
|
+
const chosen =
|
|
280
|
+
(await runRouteRequest(plugins, req, descriptors, tree)) ??
|
|
281
|
+
defaultRoute(req, descriptors, tree);
|
|
282
|
+
const serialized =
|
|
283
|
+
(await runSerializeLocals(plugins, locals)) ??
|
|
284
|
+
defaultSerialize(locals, secret);
|
|
285
|
+
return fetch(chosen.internalUrl + url.pathname + url.search, {
|
|
286
|
+
method: req.method,
|
|
287
|
+
headers: {
|
|
288
|
+
//@ts-expect-error shut up
|
|
289
|
+
...Object.fromEntries(req.headers),
|
|
290
|
+
"X-Grimoire-Locals": serialized,
|
|
291
|
+
"X-Grimoire-Internal": secret,
|
|
292
|
+
},
|
|
293
|
+
body: req.body,
|
|
294
|
+
});
|
|
295
|
+
},
|
|
296
|
+
websocket: {
|
|
297
|
+
open(ws) {
|
|
298
|
+
const upstream = new WebSocket(
|
|
299
|
+
//@ts-expect-error we give it data upstream
|
|
300
|
+
ws.data.workerUrl
|
|
301
|
+
.replace("http://", "ws://")
|
|
302
|
+
.replace("https://", "wss://") +
|
|
303
|
+
//@ts-expect-error we give it data upstream
|
|
304
|
+
ws.data.pathname,
|
|
305
|
+
);
|
|
306
|
+
upstream.onmessage = (ev) => ws.send(ev.data);
|
|
307
|
+
upstream.onclose = () => ws.close();
|
|
308
|
+
upstream.onerror = () => ws.close();
|
|
309
|
+
//@ts-expect-error we give it data upstream
|
|
310
|
+
ws.data.upstream = upstream;
|
|
311
|
+
},
|
|
312
|
+
message(ws, data) {
|
|
313
|
+
//@ts-expect-error we give it data upstream
|
|
314
|
+
ws.data.upstream?.send(data);
|
|
315
|
+
},
|
|
316
|
+
close(ws) {
|
|
317
|
+
//@ts-expect-error we give it data upstream
|
|
318
|
+
ws.data.upstream?.close();
|
|
319
|
+
},
|
|
320
|
+
drain(_ws) {},
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
// 9. expose stop + restartAll — CLI owns process lifetime
|
|
325
|
+
const stop = async () => {
|
|
326
|
+
if (stopping) return;
|
|
327
|
+
stopping = true;
|
|
328
|
+
await runHook(plugins, "onStop", "shutdown");
|
|
329
|
+
for (const w of liveWorkers) w.process.kill();
|
|
330
|
+
server.stop();
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
const restartAll = () =>
|
|
334
|
+
Promise.all(liveWorkers.map((w) => respawnWorker(w)));
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
server,
|
|
338
|
+
stop,
|
|
339
|
+
restartAll,
|
|
340
|
+
workers: liveWorkers.map((w) => ({
|
|
341
|
+
name: w.descriptor.name,
|
|
342
|
+
mode: w.descriptor.mode,
|
|
343
|
+
port: w.port,
|
|
344
|
+
index: w.descriptor.index,
|
|
345
|
+
})),
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function defaultSerialize(locals: App.Locals, secret: string): string {
|
|
350
|
+
const payload = JSON.stringify(locals);
|
|
351
|
+
const sig = new Bun.CryptoHasher("sha256")
|
|
352
|
+
.update(secret + payload)
|
|
353
|
+
.digest("hex");
|
|
354
|
+
return Buffer.from(JSON.stringify({ payload, sig })).toString("base64");
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function _defaultDeserialize(raw: string, secret: string): App.Locals {
|
|
358
|
+
const { payload, sig } = JSON.parse(Buffer.from(raw, "base64").toString());
|
|
359
|
+
const expected = new Bun.CryptoHasher("sha256")
|
|
360
|
+
.update(secret + payload)
|
|
361
|
+
.digest("hex");
|
|
362
|
+
if (sig !== expected) throw new Error("Grimoire: locals signature invalid");
|
|
363
|
+
return JSON.parse(payload);
|
|
364
|
+
}
|