@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.
@@ -30,7 +30,8 @@ interface DevSupervision {
30
30
  /** How long a connection is held for a host before the 503; HOLD_MS unless a test names less. */
31
31
  readonly holdMs?: number;
32
32
  }
33
- /** In the child: the public port its parent holds, when this host is served through handed sockets. */
33
+ /** In the child: the public port its parent holds, when this host is served through handed sockets. A worker of a
34
+ `--workers` start is served the same way, by its primary (workers.ts). */
34
35
  export declare function handedOffPort(): number | undefined;
35
36
  /**
36
37
  * In the child, where a host would `server.listen(port, host)`: under a parent that holds the port it listens on an
@@ -31,6 +31,7 @@ import { watch } from 'node:fs';
31
31
  import { createServer } from 'node:net';
32
32
  import { basename, dirname, resolve } from 'node:path';
33
33
  import { GENERATED_TYPE_FILES } from '../formatterConfig.js';
34
+ import { listenAsWorker, releaseWorker, workerPort } from './workers.js';
34
35
  /** Marks the child: it retires with DEV_CHANGED_EXIT instead of leaving the terminal to restart. Not a flag, not documented. */
35
36
  export const DEV_SUPERVISED_ENV = 'MISTRI_DEV_SUPERVISED';
36
37
  /** The child's "a save changed what I serve" (EX_TEMPFAIL): the parent starts it again. */
@@ -172,8 +173,12 @@ async function frontDoor(listen, holdMs) {
172
173
  },
173
174
  };
174
175
  }
175
- /** In the child: the public port its parent holds, when this host is served through handed sockets. */
176
+ /** In the child: the public port its parent holds, when this host is served through handed sockets. A worker of a
177
+ `--workers` start is served the same way, by its primary (workers.ts). */
176
178
  export function handedOffPort() {
179
+ const worker = workerPort();
180
+ if (worker !== undefined)
181
+ return worker;
177
182
  if (process.env[DEV_SUPERVISED_ENV] !== '1' || typeof process.send !== 'function')
178
183
  return undefined;
179
184
  const port = Number(process.env[DEV_PORT_ENV]);
@@ -186,6 +191,10 @@ let released;
186
191
  * ephemeral loopback port instead, says it is ready once listening, and serves the sockets it is handed.
187
192
  */
188
193
  export function listenForDev(server, port, host) {
194
+ if (workerPort() !== undefined) {
195
+ listenAsWorker(server);
196
+ return;
197
+ }
189
198
  if (handedOffPort() === undefined) {
190
199
  server.listen(port, host);
191
200
  return;
@@ -209,6 +218,8 @@ export function listenForDev(server, port, host) {
209
218
  * sent has arrived, so none reaches a host that is closing. Undefined where there is no parent holding the port.
210
219
  */
211
220
  export function releaseForDev() {
221
+ if (workerPort() !== undefined)
222
+ return releaseWorker();
212
223
  if (handedOffPort() === undefined || !process.connected)
213
224
  return undefined;
214
225
  return (releasing ??= new Promise((done) => {
@@ -60,6 +60,16 @@ const POSITIONAL_AT = {
60
60
  test: (argv) => (argv[0] === 'init' ? argv[1] : undefined),
61
61
  };
62
62
  export const main = async () => {
63
+ try {
64
+ await start();
65
+ }
66
+ finally {
67
+ // A worker's start that returned without serving must still exit (workers.ts leaveWhenDone).
68
+ if (process.env.MISTRI_WORKER_INDEX !== undefined)
69
+ (await import('./workers.js')).leaveWhenDone();
70
+ }
71
+ };
72
+ const start = async () => {
63
73
  /* Before any flag is read: the variables both binaries read are said in this one's name (MISTRI_*). */
64
74
  setProduct('mistri');
65
75
  /* From a source checkout, an App outside it still finds the framework (buildResolution.ts). */
@@ -133,7 +143,7 @@ export const main = async () => {
133
143
  return runSubcommand(command, argv, 'mistri');
134
144
  }
135
145
  /* Past the commands, a start: what it needs is loaded now, and not for a command above. */
136
- const [{ CHECK_VALIDATION, parseArgs }, { configureWriteOrder }, { apiReadStartupOptions, appMcpStartupOptions, readAppMcpToken }] = await Promise.all([
146
+ const [{ availableCores, CHECK_VALIDATION, coreSourceSaid, parseArgs, workerCount }, { configureWriteOrder }, { apiReadStartupOptions, appMcpStartupOptions, readAppMcpToken },] = await Promise.all([
137
147
  import('@mistriwork/engine/server/cli/args.js'),
138
148
  import('@mistriwork/engine/adapters/writeLanes.js'),
139
149
  import('@mistriwork/engine/server/cli/startupOptions.js'),
@@ -191,7 +201,11 @@ export const main = async () => {
191
201
  process.exitCode = 2;
192
202
  return;
193
203
  }
194
- if (!dev && process.env[CHECK_VALIDATION] !== '1') {
204
+ /* A worker of a `--workers` start (workers.ts) was forked with the arguments its primary settled, profile and all.
205
+ Only the cluster's own flag is read here: workers.ts and what it carries load after a print-and-exit flag is
206
+ answered, so `--help` stays the flag parser alone (test/cli-startup.test.ts). */
207
+ const forked = (await import('node:cluster')).default.isWorker;
208
+ if (!dev && process.env[CHECK_VALIDATION] !== '1' && !forked) {
195
209
  const argv = await profiled(process.argv.slice(2), false);
196
210
  if (!argv)
197
211
  return;
@@ -208,6 +222,57 @@ export const main = async () => {
208
222
  }
209
223
  if (await answeredFirst(opts, MISTRI))
210
224
  return;
225
+ const workers = await import('./workers.js');
226
+ const asWorker = workers.workerIndex() !== undefined;
227
+ /* `--workers` (workers.ts): how many processes serve this start, one per core this process may use unless asked
228
+ otherwise. `mistri dev` is one process, whose parent restarts it on a save; a deployment's MISTRI_WORKERS is not a
229
+ reason to refuse it, a flag typed at it is. */
230
+ let workerTotal = 1;
231
+ let workerReason;
232
+ /* Nobody asked: a start that cannot run several (SQLite) serves as one process rather than refusing. An explicit
233
+ count, from the flag or the variable, is a request, and is refused there. */
234
+ const workersDefaulted = opts.workers === undefined;
235
+ if (asWorker) {
236
+ /* Every address a worker makes is its primary's port, and the keys it would make up alone are the start's
237
+ (processKey.ts, which takes its secret out of the environment as it loads, before any App code runs). */
238
+ Object.assign(opts, { port: workers.workerPort(), portGiven: true });
239
+ workers.quietUntilServing();
240
+ await import('../processKey.js');
241
+ const [{ configureLocalCache, MemoryCacheStore }, { balancedPoolSize }, { appReaders }] = await Promise.all([
242
+ import('@mistriwork/engine/adapters/cache/cacheStore.js'),
243
+ import('@mistriwork/engine/adapters/writeLanes.js'),
244
+ import('@mistriwork/engine/adapters/postgresPool.js'),
245
+ ]);
246
+ configureLocalCache(() => workers.busEvictingCache(new MemoryCacheStore()));
247
+ /* The cores are shared: a worker's pools are what its share of them warrants, so n workers hold about the
248
+ connections one process would have (check --deploy counts them the same way). A pool the deployment named is
249
+ its own. */
250
+ const share = Math.ceil(availableCores().cpus / workers.workerTotal());
251
+ if (opts.writePool === undefined)
252
+ opts.writePool = String(balancedPoolSize(share));
253
+ if (opts.readPool === undefined)
254
+ opts.readPool = String(appReaders(Number(opts.writePool), share));
255
+ }
256
+ else {
257
+ const cores = availableCores();
258
+ const counted = workerCount(opts, cores.cores);
259
+ if (typeof counted === 'string') {
260
+ console.error(`mistri: ${counted}`);
261
+ process.exitCode = 2;
262
+ return;
263
+ }
264
+ if (dev || opts.dev) {
265
+ if (counted > 1 && typed.argv.includes('--workers')) {
266
+ console.error(`mistri${dev ? ' dev' : ''}: --workers is for a production start; dev runs one process, which it starts again on a save. Drop --workers.`);
267
+ process.exitCode = 2;
268
+ return;
269
+ }
270
+ }
271
+ else {
272
+ workerTotal = counted;
273
+ workerReason = opts.workers === undefined || opts.workers === 'auto' ? coreSourceSaid(cores) : 'as asked';
274
+ }
275
+ }
211
276
  /* The database browser's modes, before anything is read: they open a database with no App, which is the
212
277
  database browser's to do. */
213
278
  const browsing = opts.mcp
@@ -258,6 +323,31 @@ export const main = async () => {
258
323
  process.exitCode = await draftFromOpenapi(opts.fromOpenapi);
259
324
  return;
260
325
  }
326
+ /* Several workers: this process holds the port and serves nothing, so nothing below is for it (workers.ts). A
327
+ mode that serves no HTTP is one process whatever --workers says, as a mounted handler is its embedder's. */
328
+ if (workerTotal > 1 &&
329
+ !opts.embedded &&
330
+ !opts.appMcp &&
331
+ !opts.export &&
332
+ !opts.scaffoldApp &&
333
+ !opts.checkApp &&
334
+ opts.reindex === undefined) {
335
+ const supervised = await workers.superviseWorkers({
336
+ count: workerTotal,
337
+ port: opts.port,
338
+ host: opts.host,
339
+ portGiven: opts.portGiven,
340
+ reason: workerReason,
341
+ defaulted: workersDefaulted,
342
+ });
343
+ if (typeof supervised === 'number')
344
+ process.exit(supervised);
345
+ /* The first worker found the start cannot run several (refuseSqliteWorkers), or will not serve at all (a refusal
346
+ this process then reaches and says itself): it is served here, as one process. */
347
+ if (supervised.alone)
348
+ console.log(supervised.alone);
349
+ workerTotal = 1;
350
+ }
261
351
  configureProcess(opts, 'mistri');
262
352
  /* Published at an https address, the server stands behind a TLS front end: its cookies are Secure, its answers pin
263
353
  https and the pages it writes name https, though the front end forwards plain http (trust.ts arrivedOverHttps). */
@@ -351,10 +441,17 @@ export const main = async () => {
351
441
  }
352
442
  catch (error) {
353
443
  await registry.closeAll();
444
+ if (asWorker && workers.workersDefaulted())
445
+ await workers.serveAlone();
354
446
  console.error(`mistri: ${error.message}`);
355
447
  process.exitCode = 2;
356
448
  return;
357
449
  }
450
+ /* Nobody asked for workers: the primary takes the start back and says this once itself, rather than each worker. */
451
+ if (asWorker && workers.workersDefaulted()) {
452
+ await registry.closeAll();
453
+ await workers.serveAlone();
454
+ }
358
455
  return refuseBrowser('a server with no App', process.argv.slice(2), registry);
359
456
  }
360
457
  /* Before any App opens a writer: a tenant App's is bound to live sync as it is made (tenantLive.ts). */
@@ -384,6 +481,31 @@ export const main = async () => {
384
481
  configureWriteOrder(config.apps.length || opts.apps?.length || opts.appEntry !== undefined ? 'keyed' : 'serial');
385
482
  const apps = await (await import('./apps.js')).loadStartupApps(opts, registry, config);
386
483
  const { loadedApps } = apps;
484
+ /* Several workers write as several processes: a SQLite file has one writer, and each worker's writer pool would
485
+ queue behind the others' file lock (or a session store's), where one process orders its own. Refused in the
486
+ first worker once its connections are named (a demo's is made late) and before it serves or runs a job, so the
487
+ start fails with this sentence rather than serving slowly (workers.ts). */
488
+ const refuseSqliteWorkers = async () => {
489
+ if (!asWorker || workers.workerTotal() <= 1)
490
+ return;
491
+ const { deployFindings } = await import('../build/checkDeploy.js');
492
+ const sqlite = new Set(['deploy-sqlite-source', 'deploy-sqlite-auth-store', 'deploy-default-auth-store']);
493
+ const onSqlite = loadedApps.some((loaded) => deployFindings({
494
+ app: loaded.app,
495
+ connections: registry.configs(),
496
+ activeId: registry.active ?? undefined,
497
+ cache: false,
498
+ env: process.env,
499
+ }).some((finding) => sqlite.has(finding.code)));
500
+ if (!onSqlite)
501
+ return;
502
+ await registry.closeAll();
503
+ // Nobody asked for workers: the primary serves the start as one process and says why (workers.ts serveAlone).
504
+ if (workers.workersDefaulted())
505
+ await workers.serveAlone("mistri: one process: SQLite has one writer; workers need the App's data on PostgreSQL or MySQL and auth.store on PostgreSQL.");
506
+ console.error("mistri: --workers needs a network database; SQLite has one writer. Point the App's connections at postgres:// or mysql:// URLs and auth.store at a postgres:// URL, or run one process.");
507
+ process.exit(2);
508
+ };
387
509
  try {
388
510
  if (loadedApps.some((loaded) => loaded.build))
389
511
  latency.refuseForBuild();
@@ -482,6 +604,7 @@ export const main = async () => {
482
604
  process.exit(code);
483
605
  }
484
606
  // `mistri dev`: once it answers, a sign-in per role, each a member where it works (cli/devMode.ts).
607
+ await refuseSqliteWorkers();
485
608
  dev?.serving(opts, loadedApps, registry);
486
609
  await serveTenantApp(opts, registry, config, apps, Boolean(nonPolicyMode));
487
610
  return;
@@ -710,6 +833,7 @@ export const main = async () => {
710
833
  }));
711
834
  }
712
835
  }
836
+ await refuseSqliteWorkers();
713
837
  const { hostCommands } = await import('./commandHost.js');
714
838
  const hosted = await hostCommands(opts, registry, loadedApps);
715
839
  if (opts.checkApp) {
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The rate limits and sign-in lockouts a `--workers` start counts once (workers.ts): the public forms' budgets, Better
3
+ * Auth's request budget and the lockouts in auth/signInState.ts. Without a cache service each process counts its own,
4
+ * which across n workers of one start would give a visitor n times the budget and n times the guesses. So the primary,
5
+ * which serves no request and outlives its workers, holds the counts, and a worker reaches them as a cache store over
6
+ * the process bus (`ask`), as instances reach a Valkey the config names. With a cache service none of this is used: the
7
+ * service already counts for every process, and every replica.
8
+ *
9
+ * What a worker does when its primary does not answer in time is each caller's: the public forms' budgets go on in
10
+ * the worker's own count (open), and a lockout check is failed closed (auth/signInState.ts says why).
11
+ */
12
+ import { type CacheStore } from '@mistriwork/engine/adapters/cache/cacheStore.js';
13
+ import { ask } from '../processBus.js';
14
+ /** The one question these counters answer; the bus's other questions are their own. */
15
+ export declare const COUNTERS_OP = "counters";
16
+ /**
17
+ * Apart, as signInState keeps them apart in one process: a flood of public-form clients or of unauthenticated OAuth
18
+ * requests can push out only its own oldest entries, never a sign-in lock or its counters.
19
+ */
20
+ type CounterBucket = 'forms' | 'signin' | 'pending';
21
+ /** In the primary: answers a worker's `counters` question from the primary's own stores. */
22
+ export declare function answerCounters(op: string, args: unknown[]): unknown;
23
+ /** In the primary: forgets every count; tests use it. */
24
+ export declare function resetPrimaryCounters(): void;
25
+ /**
26
+ * In a worker: the counters of `bucket` its primary keeps. Every method throws CacheUnavailable when the primary does
27
+ * not answer within ASK_MS, reads included, so a caller can tell "no count" from "no answer".
28
+ */
29
+ export declare function primaryCounters(bucket: CounterBucket, asking?: typeof ask): CacheStore;
30
+ export {};
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The rate limits and sign-in lockouts a `--workers` start counts once (workers.ts): the public forms' budgets, Better
3
+ * Auth's request budget and the lockouts in auth/signInState.ts. Without a cache service each process counts its own,
4
+ * which across n workers of one start would give a visitor n times the budget and n times the guesses. So the primary,
5
+ * which serves no request and outlives its workers, holds the counts, and a worker reaches them as a cache store over
6
+ * the process bus (`ask`), as instances reach a Valkey the config names. With a cache service none of this is used: the
7
+ * service already counts for every process, and every replica.
8
+ *
9
+ * What a worker does when its primary does not answer in time is each caller's: the public forms' budgets go on in
10
+ * the worker's own count (open), and a lockout check is failed closed (auth/signInState.ts says why).
11
+ */
12
+ import { CacheUnavailable, MemoryCacheStore } from '@mistriwork/engine/adapters/cache/cacheStore.js';
13
+ import { ask, NoAnswer } from '../processBus.js';
14
+ /** The one question these counters answer; the bus's other questions are their own. */
15
+ export const COUNTERS_OP = 'counters';
16
+ /* The primary answers from memory in well under a millisecond: a second without an answer is a primary that is stuck
17
+ (or stopping), and a request is not held longer than that on it. */
18
+ const ASK_MS = 1_000;
19
+ const SIZES = { forms: 50_000, signin: 50_000, pending: 10_000 };
20
+ const METHODS = new Set(['get', 'set', 'delete', 'incr']);
21
+ let held;
22
+ /** In the primary: answers a worker's `counters` question from the primary's own stores. */
23
+ export function answerCounters(op, args) {
24
+ if (op !== COUNTERS_OP)
25
+ throw new Error(`The primary has no answer to ${op}.`);
26
+ const [bucket, method, key, ...rest] = args;
27
+ if (typeof bucket !== 'string' || !(bucket in SIZES) || typeof method !== 'string' || !METHODS.has(method) || typeof key !== 'string')
28
+ throw new Error('The primary was asked a counter it does not keep.');
29
+ held ??= {
30
+ forms: new MemoryCacheStore(SIZES.forms),
31
+ signin: new MemoryCacheStore(SIZES.signin),
32
+ pending: new MemoryCacheStore(SIZES.pending),
33
+ };
34
+ const store = held[bucket];
35
+ if (method === 'get')
36
+ return store.get(key);
37
+ if (method === 'delete')
38
+ return store.delete(key);
39
+ if (method === 'set')
40
+ return store.set(key, String(rest[0]), Number(rest[1]));
41
+ return store.incr(key, Number(rest[0]), rest[1] === undefined || rest[1] === null ? undefined : Number(rest[1]));
42
+ }
43
+ /** In the primary: forgets every count; tests use it. */
44
+ export function resetPrimaryCounters() {
45
+ held = undefined;
46
+ }
47
+ /**
48
+ * In a worker: the counters of `bucket` its primary keeps. Every method throws CacheUnavailable when the primary does
49
+ * not answer within ASK_MS, reads included, so a caller can tell "no count" from "no answer".
50
+ */
51
+ export function primaryCounters(bucket, asking = ask) {
52
+ const question = async (method, ...args) => {
53
+ try {
54
+ return await asking(COUNTERS_OP, [bucket, method, ...args], ASK_MS);
55
+ }
56
+ catch (error) {
57
+ if (error instanceof NoAnswer)
58
+ throw new CacheUnavailable(error.message);
59
+ throw error;
60
+ }
61
+ };
62
+ return {
63
+ kind: 'primary',
64
+ get: async (key) => {
65
+ const value = await question('get', key);
66
+ return typeof value === 'string' ? value : undefined;
67
+ },
68
+ set: async (key, value, ttlMs) => {
69
+ await question('set', key, value, ttlMs);
70
+ },
71
+ delete: async (key) => {
72
+ await question('delete', key);
73
+ },
74
+ incr: async (key, ttlMs, by) => {
75
+ const counted = (await question('incr', key, ttlMs, by));
76
+ if (typeof counted?.count !== 'number' || typeof counted.ttlMs !== 'number')
77
+ throw new CacheUnavailable('The primary answered a count with none.');
78
+ return { count: counted.count, ttlMs: counted.ttlMs };
79
+ },
80
+ // The counts are the primary's, kept for as long as the start runs; a worker has nothing of its own to close.
81
+ close: async () => { },
82
+ };
83
+ }
@@ -150,6 +150,14 @@ Options:
150
150
  keep the process before it is cut (default 10, 1 to 300).
151
151
  Hold the drain and this inside the platform's stop
152
152
  timeout. Or set MISTRI_SHUTDOWN_GRACE.
153
+ --workers <n|auto>
154
+ Processes serving the one port (default auto: one per
155
+ core the container is given, its CPU quota and 256 MiB
156
+ of its memory limit each, at most 64); a session's
157
+ requests stay on one. More requests at once, not a
158
+ faster page. PostgreSQL or MySQL only: a SQLite start
159
+ is one process unless asked. 1 turns it off; mistri dev
160
+ is always one. Or set MISTRI_WORKERS.
153
161
  --config <path> Read connections from this file, and the cache,
154
162
  search, webhook, email (smtps://, smtp:// or log:)
155
163
  and OAuth services beside them; the paths in it are
@@ -327,7 +335,7 @@ Checking an App while authoring it — the one command of the loop:
327
335
  [--no-index-check] [--no-query-check]
328
336
  [--pending [--pending-on <url>] [--migrations <dir>] [--history-table <name>]]
329
337
  [--schema-file [<schema.sql>] [--dev-url <url>]]
330
- [--deploy [--replicas <n>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]
338
+ [--deploy [--replicas <n>] [--workers <n|auto>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]
331
339
 
332
340
  Three or four steps, each with its own verdict line. Schema types: regenerates
333
341
  the App's mistri-schema.d.ts from the database when it has drifted (a
@@ -381,14 +389,15 @@ Checking an App while authoring it — the one command of the loop:
381
389
  judges whether the App survives a container being replaced: it refuses a
382
390
  source or auth.store on a SQLite file, the default auth.store, a missing
383
391
  BETTER_AUTH_SECRET and a \${NAME} the environment lacks (run it with the
384
- deployment's environment), and with --replicas <n> above one it warns that
385
- rate limits are per process without a cache service and refuses a public
392
+ deployment's environment), and with --replicas <n> (or --workers <n|auto>,
393
+ each replica's processes) above one process it warns that rate limits are
394
+ per process without a cache service and refuses a public
386
395
  page's door without MISTRI_FORM_KEY. It also prints, per database, the
387
396
  connections one process may hold (read and write pools, the background
388
397
  writer, LISTEN, each read replica, the sign-in store's pool, and the
389
398
  hosts the App serves with: jobs, effects, integrations, decisions, the
390
399
  API event feed, the assistant; given --jobs, its module is read for them)
391
- times --replicas, and with --connection-limit <n> (the connections the
400
+ times the processes (--replicas times --workers), and with --connection-limit <n> (the connections the
392
401
  database allows this role) refuses a total above it. Pool defaults follow
393
402
  the cores: --cpus <n> says the deployment's (this machine's otherwise,
394
403
  and the line says which it assumed). It also reads the migrations not yet
@@ -0,0 +1,70 @@
1
+ import type { Server as HttpServer } from 'node:http';
2
+ import type { CacheStore } from '@mistriwork/engine/adapters/cache/cacheStore.js';
3
+ /** In a worker of a `--workers` start: its index from 0; undefined in any other process. */
4
+ export declare function workerIndex(): number | undefined;
5
+ /** In a worker: how many workers the start runs. */
6
+ export declare function workerTotal(): number;
7
+ /** In a worker: the public port its primary holds. */
8
+ export declare function workerPort(): number | undefined;
9
+ /** In a worker: whether the count was the default rather than asked for (`--workers` or its variable). */
10
+ export declare function workersDefaulted(): boolean;
11
+ /** The session cookies a Cookie header carries, as one key: every `name=value` whose name is a session token's, sorted. */
12
+ export declare function sessionKey(cookie: string | undefined): string;
13
+ /** FNV-1a, 32 bits: a key's worker must be the same in every process, and needs no more than that. */
14
+ export declare function slotOf(key: string, count: number): number;
15
+ /** The Cookie header of a request head read off the wire, or undefined; the head's other lines are not looked at. */
16
+ export declare function cookieOfHead(head: Buffer): string | undefined;
17
+ interface WorkerSupervision {
18
+ count: number;
19
+ port: number;
20
+ host: string;
21
+ /** Said when the port is taken: whether the person named it. */
22
+ portGiven?: boolean;
23
+ /** Where the count came from, said on the serving line: "4 cores", "the container's CPU quota", "as asked". */
24
+ reason?: string;
25
+ /** Nobody asked for workers: a first worker that finds the start cannot run several hands it back (`'alone'`). */
26
+ defaulted?: boolean;
27
+ }
28
+ /**
29
+ * Runs the workers until a signal stops them; resolves to the exit code the primary should leave with: 0 when every
30
+ * worker stopped cleanly, the first worker's own code when it could not start, 1 on a crash loop. Resolves to
31
+ * `{ alone }`, with the port let go, when a defaulted start's first worker found it cannot run several (serveAlone):
32
+ * the caller then serves as one process, and says `alone` (why) when the worker gave a reason.
33
+ */
34
+ export declare function superviseWorkers(options: WorkerSupervision): Promise<number | {
35
+ alone: string | undefined;
36
+ }>;
37
+ /**
38
+ * In a worker, where a host would `server.listen(port, host)`: it serves the sockets the primary hands it, and listens
39
+ * on an ephemeral loopback port only so its listening and closing work as they do alone; nothing connects to it.
40
+ */
41
+ export declare function listenAsWorker(server: HttpServer): void;
42
+ /**
43
+ * In a worker, before it retires: asks the primary to stop handing it connections and resolves once every one already
44
+ * sent has arrived. Undefined outside a worker.
45
+ */
46
+ export declare function releaseWorker(): Promise<void> | undefined;
47
+ /** In a worker: quiet until it serves, unless it is the one that speaks. */
48
+ export declare function quietUntilServing(): void;
49
+ /**
50
+ * In the first worker of a start whose count was the default, when the start cannot run several processes or will not
51
+ * serve at all (a refusal): tells the primary, which then takes the start as one process, and exits without a word.
52
+ * What it held is the primary's to say: `say`, the reason one process serves, or nothing when the primary will reach
53
+ * the same refusal itself and say it once.
54
+ */
55
+ export declare function serveAlone(say?: string): Promise<never>;
56
+ /**
57
+ * When a worker's start returns: the IPC channel must not keep it alive. A worker that serves let it go as it listened
58
+ * (listenAsWorker); one that returned before serving (a refusal, which sets the exit code and returns) would otherwise
59
+ * wait on the channel forever, and so would its primary, waiting for the first worker's exit.
60
+ */
61
+ export declare function leaveWhenDone(): void;
62
+ /**
63
+ * The Registry's in-process cache (engine connections.ts `cache()`), for a worker: a key deleted in one worker is
64
+ * deleted in the others, so a change one of them saved (a tenant's branding) is not served stale by the rest until
65
+ * it expires. Only a delete is told: a write is each process's own fill of the same answer, and telling it would
66
+ * have the workers evict each other's on every read. The counters a request can be refused by are not kept here but in
67
+ * the primary (primaryCounters.ts), so the workers of one start spend one budget.
68
+ */
69
+ export declare function busEvictingCache(inner: CacheStore): CacheStore;
70
+ export {};