@mistriwork/mistri 1.0.0-rc.82 → 1.0.0-rc.83

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.
@@ -0,0 +1,585 @@
1
+ /**
2
+ * `--workers <n|auto>`: one start served by several processes, so a host's cores all answer requests.
3
+ *
4
+ * A Node process runs its JavaScript on one core. Replicas behind a balancer were the only way to use more, and on one
5
+ * host that is a balancer to run for nothing (a field report: a four-core host, three cores idle). Here the process
6
+ * the person started becomes a primary that serves nothing itself: it holds the port, forks the workers (node:cluster),
7
+ * starts one again that dies, and stops them all on SIGTERM or SIGINT. Each worker is a whole start, as a replica is:
8
+ * whatever keeps two replicas correct (jobs leased in the database, live sync over LISTEN, a cache named in the config)
9
+ * keeps two workers correct, and what replicas lack, workers have through the primary: the process bus
10
+ * (processBus.ts) and one secret for the keys each process would otherwise make up (processKey.ts).
11
+ *
12
+ * The primary hands each connection to a worker itself rather than letting cluster share the port, because a tenant
13
+ * App's contexts live in the process that made them (tenant/tenantContexts.ts): a person's requests must reach the
14
+ * worker that knows their context. So it reads the head of a connection's first request, takes the session cookie,
15
+ * and sends the socket to the worker that cookie hashes to; a connection with none goes round the workers in turn. As
16
+ * the dev parent does (devSupervisor.ts), handing the socket keeps the peer address, Host and every byte untouched,
17
+ * and a stream or an upgrade works with nothing more. The bytes the primary read go with the socket and are given to
18
+ * the worker's HTTP server before anything else it reads.
19
+ *
20
+ * A connection is kept alive across requests, and the cookie can change on it: a sign-in sets one. A response that
21
+ * sets the session cookie closes the connection, so the next request is routed by the new one; a request that still
22
+ * arrives on a connection routed by another cookie is sent to the same address again (307, closed), which a browser
23
+ * follows on a new connection. A worker that is down has its sessions served by the next one until it is back.
24
+ *
25
+ * The first worker starts alone and the rest once it serves, so startup work (a validation record, a store's first
26
+ * file, a cache warmed in the database) is done once and the others find it done; a first worker that cannot start
27
+ * is the start failing, with its exit code, as a single process would have. Only the first worker's first start
28
+ * prints its lines and opens the browser; the others say nothing until they serve.
29
+ */
30
+ import cluster, {} from 'node:cluster';
31
+ import { randomBytes } from 'node:crypto';
32
+ import { writeSync } from 'node:fs';
33
+ import { createServer } from 'node:net';
34
+ import { format } from 'node:util';
35
+ import { answer, publish, relay, subscribe } from '../processBus.js';
36
+ import { answerCounters } from './primaryCounters.js';
37
+ /** Which worker this is, from 0, and how many there are. Not flags, not documented. */
38
+ const WORKER_INDEX_ENV = 'MISTRI_WORKER_INDEX';
39
+ const WORKER_COUNT_ENV = 'MISTRI_WORKER_COUNT';
40
+ /** The port the primary holds; a worker's addresses are made with it. */
41
+ const WORKER_PORT_ENV = 'MISTRI_WORKER_PORT';
42
+ /** Set for the one start whose lines are printed: the first worker's first. */
43
+ const WORKER_SPEAKS_ENV = 'MISTRI_WORKER_SPEAKS';
44
+ /** Set when nobody asked for workers: a start that cannot run several then serves as one process instead of refusing. */
45
+ const WORKERS_DEFAULTED_ENV = 'MISTRI_WORKERS_DEFAULTED';
46
+ function workerMessage(message) {
47
+ if (typeof message !== 'object' || message === null || !('mistriWorker' in message))
48
+ return undefined;
49
+ return message;
50
+ }
51
+ /** In a worker of a `--workers` start: its index from 0; undefined in any other process. */
52
+ export function workerIndex() {
53
+ if (!cluster.isWorker)
54
+ return undefined;
55
+ const index = Number(process.env[WORKER_INDEX_ENV]);
56
+ return Number.isInteger(index) && index >= 0 ? index : undefined;
57
+ }
58
+ /** In a worker: how many workers the start runs. */
59
+ export function workerTotal() {
60
+ const count = Number(process.env[WORKER_COUNT_ENV]);
61
+ return Number.isInteger(count) && count >= 1 ? count : 1;
62
+ }
63
+ /** In a worker: the public port its primary holds. */
64
+ export function workerPort() {
65
+ if (workerIndex() === undefined)
66
+ return undefined;
67
+ const port = Number(process.env[WORKER_PORT_ENV]);
68
+ return Number.isInteger(port) && port >= 0 ? port : undefined;
69
+ }
70
+ /** In a worker: whether this start prints its startup lines (the first worker's first start). */
71
+ function workerSpeaks() {
72
+ return process.env[WORKER_SPEAKS_ENV] === '1';
73
+ }
74
+ /** In a worker: whether the count was the default rather than asked for (`--workers` or its variable). */
75
+ export function workersDefaulted() {
76
+ return workerIndex() !== undefined && process.env[WORKERS_DEFAULTED_ENV] === '1';
77
+ }
78
+ /* ---------- which worker a request belongs to ---------- */
79
+ /** Better Auth names its session cookie `<prefix>.session_token`, `__Secure-` in front over https (auth/auth.ts cookiePrefix). */
80
+ const SESSION_COOKIE = /\.session_token$/;
81
+ /** The session cookies a Cookie header carries, as one key: every `name=value` whose name is a session token's, sorted. */
82
+ export function sessionKey(cookie) {
83
+ if (!cookie)
84
+ return '';
85
+ const found = [];
86
+ for (const part of cookie.split(';')) {
87
+ const at = part.indexOf('=');
88
+ if (at < 0)
89
+ continue;
90
+ const name = part.slice(0, at).trim();
91
+ if (SESSION_COOKIE.test(name))
92
+ found.push(`${name}=${part.slice(at + 1).trim()}`);
93
+ }
94
+ return found.sort().join('; ');
95
+ }
96
+ /** FNV-1a, 32 bits: a key's worker must be the same in every process, and needs no more than that. */
97
+ export function slotOf(key, count) {
98
+ let hash = 0x811c9dc5;
99
+ for (let i = 0; i < key.length; i++) {
100
+ hash ^= key.charCodeAt(i);
101
+ hash = Math.imul(hash, 0x01000193) >>> 0;
102
+ }
103
+ return hash % count;
104
+ }
105
+ /** The Cookie header of a request head read off the wire, or undefined; the head's other lines are not looked at. */
106
+ export function cookieOfHead(head) {
107
+ const end = head.indexOf('\r\n\r\n');
108
+ const text = head.subarray(0, end < 0 ? head.length : end).toString('latin1');
109
+ const cookies = [];
110
+ for (const line of text.split('\r\n').slice(1)) {
111
+ const colon = line.indexOf(':');
112
+ if (colon > 0 && line.slice(0, colon).trim().toLowerCase() === 'cookie')
113
+ cookies.push(line.slice(colon + 1).trim());
114
+ }
115
+ return cookies.length ? cookies.join('; ') : undefined;
116
+ }
117
+ /* ---------- the primary ---------- */
118
+ /** How long the primary waits for a request's head before routing a connection on what it has. */
119
+ const HEAD_MS = 10_000;
120
+ /** The most of a head the primary reads; a longer one is routed on what was read. */
121
+ const HEAD_BYTES = 64 * 1024;
122
+ /** How long a connection waits for a worker that serves, while none does (starting, or all restarting). */
123
+ const HOLD_MS = 30_000;
124
+ /** A worker that dies is started again after this, doubled for each death in a row, up to RESTART_MAX_MS. */
125
+ const RESTART_MS = 500;
126
+ const RESTART_MAX_MS = 30_000;
127
+ /** More deaths than this within CRASH_WINDOW_MS is a crash loop: the primary stops everything and says so. */
128
+ const CRASH_LIMIT = 5;
129
+ const CRASH_WINDOW_MS = 60_000;
130
+ /**
131
+ * Runs the workers until a signal stops them; resolves to the exit code the primary should leave with: 0 when every
132
+ * worker stopped cleanly, the first worker's own code when it could not start, 1 on a crash loop. Resolves to
133
+ * `{ alone }`, with the port let go, when a defaulted start's first worker found it cannot run several (serveAlone):
134
+ * the caller then serves as one process, and says `alone` (why) when the worker gave a reason.
135
+ */
136
+ export async function superviseWorkers(options) {
137
+ const { count } = options;
138
+ /* One secret for every worker, so the keys each would make up alone (a public form's ticket, a sealed field) are the
139
+ same in all of them (processKey.ts). Made here and passed in the environment, never written anywhere. */
140
+ const secret = randomBytes(32).toString('base64');
141
+ const slots = Array.from({ length: count }, () => ({ ready: false, starting: true, deaths: [], streak: 0 }));
142
+ const waiting = new Set();
143
+ let stopping = false;
144
+ let turn = 0;
145
+ let firstStart = true;
146
+ let settle;
147
+ const done = new Promise((resolve) => (settle = resolve));
148
+ let exitCode;
149
+ let alone = false;
150
+ let aloneSay;
151
+ const server = createServer({ pauseOnConnect: true });
152
+ try {
153
+ await new Promise((resolve, reject) => {
154
+ server.once('error', reject);
155
+ server.listen(options.port, options.host, () => {
156
+ server.off('error', reject);
157
+ resolve();
158
+ });
159
+ });
160
+ }
161
+ catch (error) {
162
+ const code = error.code;
163
+ console.error(code === 'EADDRINUSE'
164
+ ? `mistri: port ${options.port} is already in use.` +
165
+ (options.portGiven ? ' Pick another with --port <n>.' : ' Give it a free one with --port <n>.')
166
+ : `mistri: could not listen on ${options.host}:${options.port}: ${error.message}`);
167
+ return 1;
168
+ }
169
+ const address = server.address();
170
+ const port = address && typeof address !== 'string' ? address.port : options.port;
171
+ const readyIndexes = () => slots.flatMap((slot, index) => (slot.ready && slot.worker?.isConnected() ? [index] : []));
172
+ /** The worker a key belongs to, or the next that serves when that one does not; round in turn without a key. */
173
+ const route = (key) => {
174
+ const ready = readyIndexes();
175
+ if (!ready.length)
176
+ return undefined;
177
+ if (!key)
178
+ return slots[ready[turn++ % ready.length]];
179
+ const home = slotOf(key, count);
180
+ for (let step = 0; step < count; step++) {
181
+ const slot = slots[(home + step) % count];
182
+ if (slot.ready && slot.worker?.isConnected())
183
+ return slot;
184
+ }
185
+ return undefined;
186
+ };
187
+ const hand = (socket, head, key) => {
188
+ const slot = route(key);
189
+ if (!slot?.worker)
190
+ return false;
191
+ slot.worker.send({ mistriWorker: 'connection', head: head.toString('base64'), key }, socket, (error) => {
192
+ if (error)
193
+ socket.destroy();
194
+ });
195
+ return true;
196
+ };
197
+ const hold = (socket, head, key) => {
198
+ if (hand(socket, head, key))
199
+ return;
200
+ const held = {
201
+ socket,
202
+ head,
203
+ key,
204
+ timer: setTimeout(() => {
205
+ waiting.delete(held);
206
+ // Nobody to serve it in time: said plainly, as the dev parent says it, rather than left hanging.
207
+ socket.end('HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
208
+ }, HOLD_MS),
209
+ };
210
+ held.timer.unref();
211
+ waiting.add(held);
212
+ socket.once('close', () => {
213
+ clearTimeout(held.timer);
214
+ waiting.delete(held);
215
+ });
216
+ };
217
+ const flush = () => {
218
+ for (const held of [...waiting]) {
219
+ if (!hand(held.socket, held.head, held.key))
220
+ return;
221
+ clearTimeout(held.timer);
222
+ waiting.delete(held);
223
+ }
224
+ };
225
+ server.on('connection', (socket) => {
226
+ socket.on('error', () => socket.destroy());
227
+ const chunks = [];
228
+ let size = 0;
229
+ let routed = false;
230
+ const finish = () => {
231
+ if (routed)
232
+ return;
233
+ routed = true;
234
+ clearTimeout(timer);
235
+ socket.off('data', onData);
236
+ /* No more is read here: what the kernel holds past this point is the worker's to read. The handle is stopped in
237
+ this same turn, before it can hand the stream another chunk the send would then drop. */
238
+ const handle = socket._handle;
239
+ if (handle) {
240
+ handle.reading = false;
241
+ handle.readStop?.();
242
+ }
243
+ socket.pause();
244
+ for (let more; socket.readableLength > 0 && (more = socket.read()) !== null;)
245
+ chunks.push(more);
246
+ const head = Buffer.concat(chunks);
247
+ if (stopping) {
248
+ socket.destroy();
249
+ return;
250
+ }
251
+ hold(socket, head, sessionKey(cookieOfHead(head)));
252
+ };
253
+ const onData = (chunk) => {
254
+ chunks.push(chunk);
255
+ size += chunk.length;
256
+ if (size >= HEAD_BYTES || Buffer.concat(chunks).includes('\r\n\r\n'))
257
+ finish();
258
+ };
259
+ const timer = setTimeout(finish, HEAD_MS);
260
+ timer.unref();
261
+ socket.on('data', onData);
262
+ // A client that closes before saying anything is gone; nothing to route.
263
+ socket.once('end', () => {
264
+ if (!routed && size === 0) {
265
+ routed = true;
266
+ clearTimeout(timer);
267
+ socket.destroy();
268
+ }
269
+ else
270
+ finish();
271
+ });
272
+ socket.resume();
273
+ });
274
+ const stopAll = (signal) => {
275
+ for (const slot of slots) {
276
+ clearTimeout(slot.timer);
277
+ if (slot.worker && !slot.worker.isDead())
278
+ slot.worker.process.kill(signal);
279
+ }
280
+ };
281
+ const finishIfDone = () => {
282
+ if (slots.every((slot) => !slot.worker || slot.worker.isDead()))
283
+ settle?.(exitCode ?? 0);
284
+ };
285
+ const stop = (code) => {
286
+ if (stopping) {
287
+ // A second signal: the person wants it gone now.
288
+ stopAll('SIGKILL');
289
+ return;
290
+ }
291
+ stopping = true;
292
+ if (code !== undefined)
293
+ exitCode = code;
294
+ server.close();
295
+ for (const held of waiting) {
296
+ clearTimeout(held.timer);
297
+ held.socket.destroy();
298
+ }
299
+ waiting.clear();
300
+ stopAll('SIGTERM');
301
+ finishIfDone();
302
+ };
303
+ const onSignal = () => stop();
304
+ process.on('SIGINT', onSignal);
305
+ process.on('SIGTERM', onSignal);
306
+ const fork = (index) => {
307
+ const slot = slots[index];
308
+ const speaks = index === 0 && firstStart;
309
+ const worker = cluster.fork({
310
+ [WORKER_INDEX_ENV]: String(index),
311
+ [WORKER_COUNT_ENV]: String(count),
312
+ [WORKER_PORT_ENV]: String(port),
313
+ MISTRI_WORKER_SECRET: secret,
314
+ [WORKERS_DEFAULTED_ENV]: options.defaulted ? '1' : '',
315
+ ...(speaks ? { [WORKER_SPEAKS_ENV]: '1' } : { [WORKER_SPEAKS_ENV]: '', MISTRI_OPEN: '' }),
316
+ });
317
+ slot.worker = worker;
318
+ slot.ready = false;
319
+ worker.on('message', (message) => {
320
+ if (relay(message, worker, slots.map((s) => s.worker)) ||
321
+ answer(message, worker, answerCounters))
322
+ return;
323
+ const said = workerMessage(message);
324
+ if (said?.mistriWorker === 'ready') {
325
+ slot.ready = true;
326
+ slot.streak = 0;
327
+ if (index === 0 && firstStart) {
328
+ firstStart = false;
329
+ // The first worker serves: startup work is done, and the rest start beside it.
330
+ for (let next = 1; next < count; next++)
331
+ fork(next);
332
+ }
333
+ if (slot.starting) {
334
+ slot.starting = false;
335
+ if (slots.every((each) => !each.starting))
336
+ console.log(`mistri: serving with ${count} workers${options.reason ? `: ${options.reason}` : ''} ` +
337
+ `(pids ${slots.map((each) => each.worker?.process.pid ?? '-').join(', ')}); stop with Ctrl-C.`);
338
+ }
339
+ else
340
+ console.log(`mistri: worker ${index + 1} serves again (pid ${worker.process.pid}).`);
341
+ flush();
342
+ }
343
+ else if (said?.mistriWorker === 'alone' && index === 0 && firstStart && options.defaulted) {
344
+ /* Its exit is then the start going on as one process, not the start failing. Answered, so the worker exits
345
+ only once this is known here: its exit could otherwise be seen before its message. */
346
+ alone = true;
347
+ aloneSay = said.say;
348
+ worker.send({ mistriWorker: 'released' }, undefined, () => { });
349
+ }
350
+ else if (said?.mistriWorker === 'retiring') {
351
+ // Stop handing it connections; the answer arrives after every one already sent, so none reaches it closing.
352
+ slot.ready = false;
353
+ worker.send({ mistriWorker: 'released' }, undefined, () => { });
354
+ }
355
+ });
356
+ worker.on('exit', (code, signal) => {
357
+ slot.ready = false;
358
+ if (slot.worker === worker)
359
+ slot.worker = undefined;
360
+ if (stopping) {
361
+ if (code !== 0 && exitCode === undefined)
362
+ exitCode = code ?? 1;
363
+ finishIfDone();
364
+ return;
365
+ }
366
+ // The first worker's first start failing is the start failing: its code, and what it printed, are the answer.
367
+ if (index === 0 && firstStart) {
368
+ exitCode = alone ? 0 : (code ?? 1);
369
+ stop(exitCode);
370
+ return;
371
+ }
372
+ const now = Date.now();
373
+ slot.deaths = [...slot.deaths.filter((at) => now - at < CRASH_WINDOW_MS), now];
374
+ const how = `(pid ${worker.process.pid}) ${signal ? `was stopped by ${signal}` : `exited with code ${code}`}`;
375
+ if (slot.deaths.length > CRASH_LIMIT) {
376
+ console.error(`mistri: worker ${index + 1} ${how}, its ${slot.deaths.length}th death within a minute: it is crash-looping, so every worker is stopped. ` +
377
+ 'Run with --workers 1 to see why it fails.');
378
+ stop(1);
379
+ return;
380
+ }
381
+ const wait = Math.min(RESTART_MAX_MS, RESTART_MS * 2 ** slot.streak);
382
+ slot.streak += 1;
383
+ console.error(`mistri: worker ${index + 1} ${how}; starting it again in ${wait} ms.`);
384
+ slot.timer = setTimeout(() => {
385
+ if (!stopping)
386
+ fork(index);
387
+ }, wait);
388
+ });
389
+ };
390
+ fork(0);
391
+ const code = await done;
392
+ process.off('SIGINT', onSignal);
393
+ process.off('SIGTERM', onSignal);
394
+ // The port is let go before this resolves: a start that goes on alone listens on it next.
395
+ await new Promise((resolve) => server.close(() => resolve()));
396
+ return alone ? { alone: aloneSay } : code;
397
+ }
398
+ /* ---------- a worker ---------- */
399
+ /** The key each connection was routed by, so a request whose session belongs elsewhere is sent there. */
400
+ const routedBy = new WeakMap();
401
+ let released;
402
+ let releasing;
403
+ /**
404
+ * In a worker, where a host would `server.listen(port, host)`: it serves the sockets the primary hands it, and listens
405
+ * on an ephemeral loopback port only so its listening and closing work as they do alone; nothing connects to it.
406
+ */
407
+ export function listenAsWorker(server) {
408
+ const index = workerIndex();
409
+ const count = workerTotal();
410
+ /* A request on a connection routed by another session (a cookie set on it since, or one the client sent along a
411
+ kept-alive connection) belongs to another worker while that one serves: sent there again, the connection closed. */
412
+ const listeners = server.listeners('request');
413
+ server.removeAllListeners('request');
414
+ server.on('request', (req, res) => {
415
+ const key = sessionKey(req.headers.cookie);
416
+ const routed = routedBy.get(req.socket);
417
+ if (key && routed !== undefined && key !== routed && slotOf(key, count) !== index) {
418
+ res.writeHead(307, { Location: req.url ?? '/', Connection: 'close', 'Content-Length': '0' });
419
+ res.end();
420
+ return;
421
+ }
422
+ closeOnSessionChange(res);
423
+ // Which worker answered (its number, not its pid): what a person reading a response, or a test, tells them apart by.
424
+ res.setHeader('X-Mistri-Worker', String(index + 1));
425
+ for (const listener of listeners)
426
+ listener.call(server, req, res);
427
+ });
428
+ server.once('listening', () => {
429
+ speakAgain();
430
+ process.send?.({ mistriWorker: 'ready' }, undefined, undefined, () => { });
431
+ });
432
+ process.on('message', (message, socket) => {
433
+ const said = workerMessage(message);
434
+ if (said?.mistriWorker === 'connection' && socket instanceof Object && 'resume' in socket) {
435
+ const handed = socket;
436
+ routedBy.set(handed, said.key);
437
+ server.emit('connection', handed);
438
+ // What the primary read to route it: given to the HTTP server before anything the socket reads from here on.
439
+ const head = Buffer.from(said.head, 'base64');
440
+ if (head.length)
441
+ handed.emit('data', head);
442
+ handed.resume();
443
+ }
444
+ else if (said?.mistriWorker === 'released')
445
+ released?.();
446
+ });
447
+ // The channel must not keep a worker alive that would otherwise have exited.
448
+ process.channel?.unref();
449
+ server.listen({ port: 0, host: '127.0.0.1', exclusive: true });
450
+ }
451
+ /** A response that sets the session cookie ends its connection, so the next request is routed by the new cookie. */
452
+ function closeOnSessionChange(res) {
453
+ const setsSession = (set) => (Array.isArray(set) ? set : set === undefined ? [] : [set]).some((value) => SESSION_COOKIE.test(String(value).split('=')[0].trim()));
454
+ const writeHead = res.writeHead;
455
+ res.writeHead = function (...args) {
456
+ // Headers given to writeHead itself are not on the response until it runs; either place counts.
457
+ const given = args.slice(1).find((arg) => typeof arg === 'object' && arg !== null && !Array.isArray(arg));
458
+ const fromArgs = given && Object.entries(given).find(([name]) => name.toLowerCase() === 'set-cookie')?.[1];
459
+ if (setsSession(fromArgs) || setsSession(res.getHeader('set-cookie')))
460
+ res.shouldKeepAlive = false;
461
+ return writeHead.apply(this, args);
462
+ };
463
+ }
464
+ /**
465
+ * In a worker, before it retires: asks the primary to stop handing it connections and resolves once every one already
466
+ * sent has arrived. Undefined outside a worker.
467
+ */
468
+ export function releaseWorker() {
469
+ if (workerIndex() === undefined || !process.connected)
470
+ return undefined;
471
+ return (releasing ??= new Promise((resolve) => {
472
+ // A primary that does not answer (stopping too) does not hold the worker up.
473
+ const timer = setTimeout(resolve, 1000);
474
+ released = () => {
475
+ clearTimeout(timer);
476
+ resolve();
477
+ };
478
+ process.send?.({ mistriWorker: 'retiring' }, undefined, undefined, (error) => {
479
+ if (error)
480
+ released?.();
481
+ });
482
+ }));
483
+ }
484
+ /* A worker that does not speak keeps its startup lines to itself until it serves: n copies of the same banner say
485
+ nothing the first did not. What it says after that (a request's error, a job's line) is its own and printed. The
486
+ one that speaks holds its lines when nobody asked for workers: if it hands the start back (serveAlone), the
487
+ process that serves alone says them, and they are not to be said twice. */
488
+ const quiet = {};
489
+ /** In a worker: quiet until it serves, unless it is the one that speaks. */
490
+ export function quietUntilServing() {
491
+ if (quiet.log)
492
+ return;
493
+ if (workerSpeaks()) {
494
+ if (!workersDefaulted())
495
+ return;
496
+ const held = (quiet.held = []);
497
+ Object.assign(quiet, { log: console.log, error: console.error });
498
+ console.log = (...args) => void held.push([1, `${format(...args)}\n`]);
499
+ console.error = (...args) => void held.push([2, `${format(...args)}\n`]);
500
+ // A start that fails before it serves says what it held, as it would have alone; synchronous, as an exit must be.
501
+ process.once('exit', () => sayHeld((fd, text) => writeSync(fd, text)));
502
+ return;
503
+ }
504
+ quiet.log = console.log;
505
+ console.log = () => { };
506
+ }
507
+ function speakAgain() {
508
+ if (quiet.log)
509
+ console.log = quiet.log;
510
+ if (quiet.error)
511
+ console.error = quiet.error;
512
+ sayHeld((fd, text) => (fd === 1 ? process.stdout : process.stderr).write(text));
513
+ }
514
+ function sayHeld(say) {
515
+ const held = quiet.held;
516
+ quiet.held = undefined;
517
+ for (const [fd, text] of held ?? []) {
518
+ try {
519
+ say(fd, text);
520
+ }
521
+ catch {
522
+ // A closed stream at exit: nothing left to say it to.
523
+ }
524
+ }
525
+ }
526
+ /**
527
+ * In the first worker of a start whose count was the default, when the start cannot run several processes or will not
528
+ * serve at all (a refusal): tells the primary, which then takes the start as one process, and exits without a word.
529
+ * What it held is the primary's to say: `say`, the reason one process serves, or nothing when the primary will reach
530
+ * the same refusal itself and say it once.
531
+ */
532
+ export function serveAlone(say) {
533
+ quiet.held = undefined;
534
+ return new Promise(() => {
535
+ const leave = () => process.exit(0);
536
+ if (!process.send)
537
+ return leave();
538
+ // The primary answers once it has taken the start back; one that does not (stopping too) does not hold this up.
539
+ setTimeout(leave, 2000);
540
+ process.on('message', (message) => {
541
+ if (workerMessage(message)?.mistriWorker === 'released')
542
+ leave();
543
+ });
544
+ process.send({ mistriWorker: 'alone', say }, undefined, undefined, (error) => {
545
+ if (error)
546
+ leave();
547
+ });
548
+ });
549
+ }
550
+ /**
551
+ * When a worker's start returns: the IPC channel must not keep it alive. A worker that serves let it go as it listened
552
+ * (listenAsWorker); one that returned before serving (a refusal, which sets the exit code and returns) would otherwise
553
+ * wait on the channel forever, and so would its primary, waiting for the first worker's exit.
554
+ */
555
+ export function leaveWhenDone() {
556
+ if (workerIndex() !== undefined)
557
+ process.channel?.unref();
558
+ }
559
+ /* ---------- a cache whose deletions reach every worker ---------- */
560
+ /**
561
+ * The Registry's in-process cache (engine connections.ts `cache()`), for a worker: a key deleted in one worker is
562
+ * deleted in the others, so a change one of them saved (a tenant's branding) is not served stale by the rest until
563
+ * it expires. Only a delete is told: a write is each process's own fill of the same answer, and telling it would
564
+ * have the workers evict each other's on every read. The counters a request can be refused by are not kept here but in
565
+ * the primary (primaryCounters.ts), so the workers of one start spend one budget.
566
+ */
567
+ export function busEvictingCache(inner) {
568
+ const self = process.pid;
569
+ subscribe('cache.evict', (payload) => {
570
+ const said = payload;
571
+ if (said && said.from !== self && typeof said.key === 'string')
572
+ void inner.delete(said.key).catch(() => { });
573
+ });
574
+ return new Proxy(inner, {
575
+ get(target, name, receiver) {
576
+ if (name === 'delete')
577
+ return async (key) => {
578
+ await target.delete(key);
579
+ publish('cache.evict', { key, from: self });
580
+ };
581
+ const value = Reflect.get(target, name, receiver);
582
+ return typeof value === 'function' ? value.bind(target) : value;
583
+ },
584
+ });
585
+ }
@@ -11,7 +11,8 @@
11
11
  * environment, never printed or stored; a deployment with a keyed input and
12
12
  * no key refuses to start rather than falling back to a digest.
13
13
  */
14
- import { createHmac, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto';
14
+ import { createHmac, hkdfSync, timingSafeEqual } from 'node:crypto';
15
+ import { processKey } from '../processKey.js';
15
16
  const FORM_KEY_VARIABLE = 'MISTRI_FORM_KEY';
16
17
  const AUTH_SECRET_VARIABLE = 'BETTER_AUTH_SECRET';
17
18
  export class FormKeyMissing extends Error {
@@ -65,7 +66,6 @@ export function purposeKey(purpose, appId) {
65
66
  }
66
67
  return key;
67
68
  }
68
- const PROCESS_SEAL = randomBytes(32);
69
69
  /**
70
70
  * A key for sealing what the server writes and later reads back as its own — a link reference a command minted, which
71
71
  * a visitor's typed look-alike must not pass for. The form key's purpose key where the App has one; else one derived
@@ -82,7 +82,7 @@ export function sealKey(purpose, appId) {
82
82
  }
83
83
  const secret = appId !== undefined && configuredAuth.has(appId) ? configuredAuth.get(appId) : process.env[AUTH_SECRET_VARIABLE];
84
84
  if (typeof secret !== 'string' || Buffer.byteLength(secret, 'utf8') < 32)
85
- return PROCESS_SEAL;
85
+ return processKey(`seal\u0000${purpose}`);
86
86
  const cacheKey = `seal\u0000${purpose}\u0000${secret}`;
87
87
  let key = derived.get(cacheKey);
88
88
  if (!key) {
@@ -11,16 +11,16 @@
11
11
  * is one of several processes refuses without the key, and a production start warns (`ticketKeyStart`).
12
12
  */
13
13
  import { createHmac, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto';
14
+ import { processKey } from '../processKey.js';
14
15
  /** Younger than this, the form was not filled by a person. */
15
16
  const TICKET_MIN_AGE_MS = 3_000;
16
17
  /** Older than this, the page was left open for a day: loaded again, it gets a new one. */
17
18
  export const TICKET_MAX_AGE_MS = 24 * 60 * 60 * 1000;
18
- const PROCESS_KEY = randomBytes(32);
19
19
  const derived = new Map();
20
20
  function ticketKey() {
21
21
  const secret = process.env.MISTRI_FORM_KEY;
22
22
  if (typeof secret !== 'string' || Buffer.byteLength(secret, 'utf8') < 32)
23
- return PROCESS_KEY;
23
+ return processKey('public-ticket.v1');
24
24
  let key = derived.get(secret);
25
25
  if (!key) {
26
26
  key = Buffer.from(hkdfSync('sha256', Buffer.from(secret, 'utf8'), 'mistri.form-key', 'public-ticket.v1', 32));