@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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  The 1.0 release candidates of `@mistriwork/mistri`. Every earlier release is in the full changelog.
4
4
 
5
+ ## 1.0.0-rc.83
6
+
7
+ One start now uses every core it is given.
8
+
9
+ - A production start (`mistri <app>`) on PostgreSQL or MySQL now runs one worker process per core, sharing one port.
10
+ `--workers <n>` sets the count, and `--workers 1` or `MISTRI_WORKERS=1` turns it off. `mistri dev` stays one process.
11
+ Before, a start was one Node process, and the other cores of its machine sat idle.
12
+ - In a container the count follows the CPU quota, not the host's cores, with at least 256 MiB of memory per worker. The
13
+ startup log says how many workers it started and why.
14
+ - A SQLite start, or one whose sign-in store is SQLite, runs as one process and says why: SQLite has one writer. An
15
+ explicit `--workers` above 1 there is refused.
16
+ - The workers of one start share sign-in lockouts, Better Auth's request budget and the public forms' budgets, so a
17
+ visitor gets one budget, not one per worker. When a worker cannot reach the others, a lockout check refuses rather
18
+ than guess, and a plain request budget goes on in that worker's own count.
19
+ - Signing out, revoking a session and changing a password take effect on every worker at once.
20
+ - `mistri check --deploy` warns about per-process limits only for replicas without a cache service, not for the workers
21
+ of one start.
22
+
5
23
  ## 1.0.0-rc.82
6
24
 
7
25
  Fixes from a field report: the server and access first, then the client, then speed.
package/README.md CHANGED
@@ -30,7 +30,7 @@ App build to run on the supported Node 24 runtime; TypeScript examples also
30
30
  have an explicit typecheck (TypeScript 7 or later, the native compiler), and `mistri build` is the optional production
31
31
  step that runs it, validates the App and bundles it — see
32
32
  [Build and deploy an App](https://mistriwork.dev/docs/build-and-deploy/).
33
- These App features ship in mistri 1.0.0-rc.82; the
33
+ These App features ship in mistri 1.0.0-rc.83; the
34
34
  [status page](https://mistriwork.dev/docs/status/) says what is stable
35
35
  and what comes next. Start with the sample catalog (`examples/apps/README.md`),
36
36
  written for people and coding agents, then the [App DSL reference](https://mistriwork.dev/docs/app-dsl/) (the same pages read offline with `npx @mistriwork/mistri docs`).
@@ -239,6 +239,14 @@ mistri mail-dns [<config>] the SPF, DKIM and DMARC records tenant mail is sen
239
239
  (default 10, 1 to 300); hold both inside the
240
240
  platform's stop timeout. Or set
241
241
  MISTRI_SHUTDOWN_GRACE
242
+ --workers <n|auto> processes serving the one port (default auto:
243
+ one per core the container is given, its CPU
244
+ quota and 256 MiB of its memory limit each, at
245
+ most 64); a session's requests stay on one. More
246
+ requests at once, not a faster page. PostgreSQL
247
+ or MySQL only: a SQLite start is one process
248
+ unless asked. 1 turns it off; mistri dev is
249
+ always one. Or set MISTRI_WORKERS
242
250
  --host <addr> interface to bind (default 127.0.0.1)
243
251
  --allowed-host <name> also answer for this Host header; repeatable
244
252
  --trust-proxy <address|CIDR>
@@ -459,7 +467,7 @@ mistri check [--app <dir>] [--app-entry <file>]
459
467
  [--no-index-check] [--no-query-check]
460
468
  [--pending [--pending-on <url>] [--migrations <dir>] [--history-table <name>]]
461
469
  [--schema-file [<schema.sql>] [--dev-url <url>]]
462
- [--deploy [--replicas <n>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]
470
+ [--deploy [--replicas <n>] [--workers <n|auto>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]
463
471
  the authoring loop in one command: regenerate the
464
472
  App's mistri-schema.d.ts when the database
465
473
  has changed, its mistri-commands.d.ts from
@@ -491,7 +499,8 @@ mistri check [--app <dir>] [--app-entry <file>]
491
499
  --deploy judges whether the App
492
500
  survives a replaced container (no SQLite
493
501
  source or auth.store, BETTER_AUTH_SECRET set;
494
- --replicas <n> warns of per-process rate
502
+ --replicas <n> (and --workers <n|auto>, each
503
+ replica's processes) warns of per-process rate
495
504
  limits and, with --connection-limit <n>,
496
505
  refuses pools that sum past it, counting the
497
506
  hosts the App serves with; --cpus <n> sizes
@@ -61,6 +61,9 @@ const ACTOR_KINDS = ['account', 'service', 'public', 'proven'];
61
61
  const list = (values) => values.map((value) => `'${value}'`).join(', ');
62
62
  /* Messages and calls are kept ninety days: long enough to answer "did it go?", short enough not to become an archive. */
63
63
  const KEEP_MS = 90 * 86_400_000;
64
+ /* How long a held message a process took to send stays out of the others' reach: a page is 32 sends of at most 12
65
+ seconds each (integrationChannels.ts), so ten minutes outlasts any page a live process is still working through. */
66
+ const DUE_LEASE_MS = 10 * 60_000;
64
67
  /* Who made the write, and the index the email caps count by. */
65
68
  const ACTOR_KIND_SQLITE = `actor_kind TEXT CHECK (actor_kind IN (${list(ACTOR_KINDS)}))`;
66
69
  const ACTOR_KIND_POSTGRES = `actor_kind text CHECK (actor_kind IN (${list(ACTOR_KINDS)}))`;
@@ -635,14 +638,21 @@ async function openPostgresIntegrationStore(url) {
635
638
  heldWords(row),
636
639
  ]);
637
640
  },
641
+ /* Every process of a deployment (replicas, --workers) runs the held-message loop, so a page is leased as it is
642
+ read: the rows taken move their due moment past the time a page of sends can take, and another process's look
643
+ skips them (SKIP LOCKED for one taken this instant), where two plain reads sent the same text twice. Each send
644
+ puts its row's next state, which ends the lease; a process that dies holding one leaves the row to be looked at
645
+ again once the lease runs out, as a failed send is. SQLite has one process, so its read stays plain. */
638
646
  async due(app, now, limit, channel) {
639
- return (channel === undefined
640
- ? await query(`SELECT * FROM ${table(t.message)} WHERE app = $1 AND state = 'held' AND due_at <= $2 ORDER BY due_at LIMIT $3`, [
641
- app,
642
- now,
643
- limit,
644
- ])
645
- : await query(`SELECT * FROM ${table(t.message)} WHERE app = $1 AND state = 'held' AND due_at <= $2 AND channel = $3 ORDER BY due_at LIMIT $4`, [app, now, channel, limit])).map(messageOf);
647
+ const filter = channel === undefined ? '' : ' AND channel = $5';
648
+ const rows = await query(`UPDATE ${table(t.message)} AS m SET due_at = $3
649
+ FROM (SELECT * FROM ${table(t.message)} WHERE app = $1 AND state = 'held' AND due_at <= $2${filter}
650
+ ORDER BY due_at LIMIT $4 FOR UPDATE SKIP LOCKED) AS taken
651
+ WHERE m.app = taken.app AND m.key = taken.key
652
+ RETURNING taken.*`, channel === undefined ? [app, now, now + DUE_LEASE_MS, limit] : [app, now, now + DUE_LEASE_MS, limit, channel]);
653
+ /* The rows as they were read, their own due moments kept: the lease is the store's, and a send that holds one
654
+ again puts the moment it chooses. RETURNING keeps no order. */
655
+ return rows.map(messageOf).sort((a, b) => (a.dueAt ?? 0) - (b.dueAt ?? 0));
646
656
  },
647
657
  async sentSince(app, tenant, channel, since, recipient) {
648
658
  const [row] = recipient === undefined
@@ -229,6 +229,7 @@ Run several instances of the same image and config, each stateless:
229
229
  - **Health checks** poll `/healthz` for liveness and `/readyz` for readiness ([health and readiness](/docs/observe/#health-and-readiness)). Under `--base-path /desk` every route moves, the probes too: `/desk/healthz`, `/desk/readyz`.
230
230
  - **Stopping**: on SIGTERM `/readyz` answers 503 at once, then the listener closes, accepted work drains, and a response that never finishes is cut after `--shutdown-grace` (10 s). A balancer that probes needs a beat between the first 503 and the close: `--drain-delay 5` (or `MISTRI_DRAIN_DELAY`) keeps the listener answering that long. Cloud Run allows 10 s in all, so leave the drain at 0 there or lower the grace; ECS and Kubernetes allow more (`stopTimeout`, `terminationGracePeriodSeconds`), and the drain plus the grace must fit inside them.
231
231
  - **Every instance runs `--jobs`**: a job's slot runs once however many processes serve the App (leases in the job store), and `--jobs` is also what serves the App's inbound endpoints, so whichever instance the balancer picks must have it.
232
+ - **Every core of one instance**: a start runs one process per core the container is given (its CPU quota, and 256 MiB of its memory limit each) behind the instance's one port, on PostgreSQL or MySQL; `--workers 1` (or `MISTRI_WORKERS=1`) turns it off, and a SQLite start is one process. It buys capacity under concurrent load on one machine, not a faster page; for more than one machine, add replicas.
232
233
  - **Migrations run before the rollout**, never at start; every instance only checks that the stores are there.
233
234
 
234
235
  ## A suite: mounted Apps
@@ -209,7 +209,7 @@ These belong to the validation step. Problems fail it; warnings explain what a r
209
209
  | `deploy-missing-secret` | <span id="deploy-missing-secret"></span>deploy | `check --deploy`: `BETTER_AUTH_SECRET` is unset or under 32 characters, and a start refuses without it | `openssl rand -base64 32`, kept in the platform's secret store |
210
210
  | `deploy-unset-reference` | <span id="deploy-unset-reference"></span>deploy | `check --deploy`: a connection or `auth.store` references a `${NAME}` the environment lacks, and a start would refuse | Export it when you run check; the deployment's secret store holds the real value |
211
211
  | `deploy-public-url` | <span id="deploy-public-url"></span>deploy | `check --deploy` warning: `MISTRI_PUBLIC_URL` is not set, so cookies and emailed links name the loopback address | Set it to the public `https` address |
212
- | `deploy-per-process-limits` | <span id="deploy-per-process-limits"></span>deploy | `check --deploy --replicas <n>` warning: more than one replica and no `cache` service, so each keeps its own rate limits and sign-in lockout | Add a `cache` service (Valkey), or run one replica |
212
+ | `deploy-per-process-limits` | <span id="deploy-per-process-limits"></span>deploy | `check --deploy --replicas <n>` warning: more than one replica and no `cache` service, so each keeps its own rate limits and sign-in lockout (a start's workers share one count) | Add a `cache` service (Valkey), or run one replica |
213
213
  | `deploy-form-key` | <span id="deploy-form-key"></span>deploy | `check --deploy`: the App opens a public page's door and `MISTRI_FORM_KEY` is not set, so each instance signs that door's tickets with a key of its own; an error with `--replicas` above one, a warning otherwise | `openssl rand -base64 32`, exposed as `MISTRI_FORM_KEY` to every instance |
214
214
  | `deploy-server-timing-public` | <span id="deploy-server-timing-public"></span>deploy | `check --deploy` warning: `MISTRI_SERVER_TIMING=1` is set without `MISTRI_SERVER_TIMING_TOKEN`, so every response shows the process's heap, GC and pool use to any requester | Unset `MISTRI_SERVER_TIMING`, or set the token and send it as an `x-mistri-timing` header |
215
215
  | `migration-breaks-running-code` | <span id="migration-breaks-running-code"></span>deploy | `check --deploy` warning (error with `--strict-migrations`, note when marked): a pending migration drops or renames a table or column, changes a column's type, sets NOT NULL, adds a NOT NULL column without a default, or drops a view or function, which the code still running during the deploy reads | Expand, deploy, contract: add the new shape, ship code that uses it, remove the old in a later migration marked `-- mistri: contract` |
package/dist/docs/cli.md CHANGED
@@ -77,6 +77,7 @@ The server's flags: where the data is, how it is served, and what an App adds.
77
77
  | `--pooler <mode>` | session (the default): PostgreSQL is reached directly, or through a pooler that keeps a client on one server connection. transaction: through PgBouncer in transaction mode or RDS Proxy; the read-only guard and the statement cap are then set per transaction. Or set MISTRI_POOLER. |
78
78
  | `--drain-delay <s>` | Seconds /readyz answers 503 before the listener closes on SIGTERM, so a balancer that probes takes this instance out first (default 0, up to 120). Or set MISTRI_DRAIN_DELAY. |
79
79
  | `--shutdown-grace <s>` | Seconds a response still unfinished after the drain may keep the process before it is cut (default 10, 1 to 300). Hold the drain and this inside the platform's stop timeout. Or set MISTRI_SHUTDOWN_GRACE. |
80
+ | `--workers <n|auto>` | Processes serving the one port (default auto: one per core the container is given, its CPU quota and 256 MiB of its memory limit each, at most 64); a session's requests stay on one. More requests at once, not a faster page. PostgreSQL or MySQL only: a SQLite start is one process unless asked. 1 turns it off; mistri dev is always one. Or set MISTRI_WORKERS. |
80
81
  | `--config <path>` | Read connections from this file, and the cache, search, webhook, email (smtps://, smtp:// or log:) and OAuth services beside them; the paths in it are relative to its folder |
81
82
  | `--no-config` | Ignore any config file |
82
83
  | `--no-live` | Turn live sync off, even for an App that asks for it (live: true): its open pages then refresh on focus and after their own saves. Nothing is written to the change store and /api/live answers 204. |
@@ -122,7 +123,7 @@ mistri check [--app <dir>] [--app-entry <file>]
122
123
  [--no-index-check] [--no-query-check]
123
124
  [--pending [--pending-on <url>] [--migrations <dir>] [--history-table <name>]]
124
125
  [--schema-file [<schema.sql>] [--dev-url <url>]]
125
- [--deploy [--replicas <n>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]
126
+ [--deploy [--replicas <n>] [--workers <n|auto>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]
126
127
 
127
128
  Three or four steps, each with its own verdict line. Schema types: regenerates
128
129
  the App's mistri-schema.d.ts from the database when it has drifted (a
@@ -176,14 +177,15 @@ every step reads it, and it is dropped after. Its tables are empty. --deploy add
176
177
  judges whether the App survives a container being replaced: it refuses a
177
178
  source or auth.store on a SQLite file, the default auth.store, a missing
178
179
  BETTER_AUTH_SECRET and a \${NAME} the environment lacks (run it with the
179
- deployment's environment), and with --replicas <n> above one it warns that
180
- rate limits are per process without a cache service and refuses a public
180
+ deployment's environment), and with --replicas <n> (or --workers <n|auto>,
181
+ each replica's processes) above one process it warns that rate limits are
182
+ per process without a cache service and refuses a public
181
183
  page's door without MISTRI_FORM_KEY. It also prints, per database, the
182
184
  connections one process may hold (read and write pools, the background
183
185
  writer, LISTEN, each read replica, the sign-in store's pool, and the
184
186
  hosts the App serves with: jobs, effects, integrations, decisions, the
185
187
  API event feed, the assistant; given --jobs, its module is read for them)
186
- times --replicas, and with --connection-limit <n> (the connections the
188
+ times the processes (--replicas times --workers), and with --connection-limit <n> (the connections the
187
189
  database allows this role) refuses a total above it. Pool defaults follow
188
190
  the cores: --cpus <n> says the deployment's (this machine's otherwise,
189
191
  and the line says which it assumed). It also reads the migrations not yet
@@ -1115,6 +1117,7 @@ Browsing a database with no App is the database browser's: npx tablewalk <db>.
1115
1117
  | `--warnings` | [Checking an App while authoring it](#checking-an-app-while-authoring-it) |
1116
1118
  | `--where` | [Starting flows on records already there](#starting-flows-on-records-already-there) |
1117
1119
  | `--width` | [Looking at an App](#looking-at-an-app) |
1120
+ | `--workers` | [Options](#options), [Checking an App while authoring it](#checking-an-app-while-authoring-it) |
1118
1121
  | `--write-authority` | [Options](#options) |
1119
1122
  | `--write-pool` | [Options](#options) |
1120
1123
  | `--yes` | [Measuring a decision before it applies](#measuring-a-decision-before-it-applies), [Deploying an App to Cloudflare Containers](#deploying-an-app-to-cloudflare-containers) |
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: Status & roadmap
3
- description: The 1.0.0-rc.82 scope, stable and preview features, current limitations and planned work.
3
+ description: The 1.0.0-rc.83 scope, stable and preview features, current limitations and planned work.
4
4
  ---
5
5
 
6
6
  The scope of this release, stable and preview features, current limitations and planned work.
@@ -10,7 +10,7 @@ npx @mistriwork/mistri check --app .
10
10
  # preview: This App uses Preview features (…). They work as documented and may change in any 1.x release.
11
11
  ```
12
12
 
13
- This site describes **mistri 1.0.0-rc.82**, a release candidate. Since rc.2, the first release under the mistri name,
13
+ This site describes **mistri 1.0.0-rc.83**, a release candidate. Since rc.2, the first release under the mistri name,
14
14
  the App framework is split out of tablewalk, which stays the standalone database browser. A save is a fixed number of
15
15
  database round trips, the runtime forgets what it wrote about an App after the App's own retention windows, and on
16
16
  PostgreSQL the runtime lives in one schema named `mistri`. There is no upgrade from a tablewalk 0.9 App database.
@@ -173,7 +173,7 @@ entry points above:
173
173
  "version": "1.0.0",
174
174
  "type": "module",
175
175
  "exports": { ".": "./src/index.ts" },
176
- "peerDependencies": { "@mistriwork/mistri": "^1.0.0-rc.82" }
176
+ "peerDependencies": { "@mistriwork/mistri": "^1.0.0-rc.83" }
177
177
  }
178
178
  ```
179
179
 
@@ -4513,7 +4513,7 @@ async function Bi(e, t, n, r, i) {
4513
4513
  if (!o.ok) throw Error(s?.error ?? `The surface "${r}" could not be opened (${o.status}).`);
4514
4514
  return s?.signedIn && s.surface ? s.surface : void 0;
4515
4515
  }
4516
- var Vi = "1.0.0-rc.82";
4516
+ var Vi = "1.0.0-rc.83";
4517
4517
  function Hi({ endpoint: e, auth: t, app: n, surface: r, basePath: c, navigator: d, version: f = Vi, fallback: m, children: h }) {
4518
4518
  let g = e.replace(/\/+$/, ""), _ = o(t);
4519
4519
  _.current = t;
@@ -4,7 +4,7 @@ import { n as s, r as c, t as l } from "./chunks/router-CAJxIEw4.js";
4
4
  import { createContext as u, useContext as d, useEffect as f, useMemo as p, useRef as m, useState as h } from "react";
5
5
  import { jsx as g } from "react/jsx-runtime";
6
6
  // packages/mistri/src/embed/index.tsx
7
- var _ = "1.0.0-rc.82", v = u(null), y;
7
+ var _ = "1.0.0-rc.83", v = u(null), y;
8
8
  async function b(n, i, a) {
9
9
  let o = i?.authorization(), s = a ? `?${new URLSearchParams({
10
10
  app: a.app,
@@ -2,6 +2,7 @@ import { openPostgresPreferences } from '../../adapters/preferences/postgresPref
2
2
  import { openSqlitePreferences } from '../../adapters/preferences/sqlitePreferences.js';
3
3
  import { provenPicks } from './appChoices.js';
4
4
  import { appEntrypoint } from './appEntrypoint.js';
5
+ import { publish, subscribe } from '../processBus.js';
5
6
  /** The key a pick is kept under. */
6
7
  const choiceKey = (name) => `choose.${name}`;
7
8
  /* A store that did not open is asked again after this, not on every request: the operator may provision in between. */
@@ -48,12 +49,16 @@ export const preferencesFor = (registry, host) => {
48
49
  /** A tenant App's store: beside its tenant source, where the host's enrollment says that is. */
49
50
  export const preferencesAt = (app, where) => app.choose ? once(app, () => where, Date.now()) : Promise.resolve(undefined);
50
51
  /* What a person's picks were read as, for a moment: every read of a request asks them (the person's row, a loader, a
51
- command), and a round trip to PostgreSQL for each would be paid again and again. A change made here forgets them; a
52
- change another process made is read after TTL_MS. */
52
+ command), and a round trip to PostgreSQL for each would be paid again and again. A change made here forgets them, in
53
+ every worker of this start too (processBus.ts); a change a replica made is read after TTL_MS. */
53
54
  const TTL_MS = 3000;
54
55
  const recent = new Map();
55
56
  const RECENT_MOST = 2000;
56
57
  const remembered = (app, subject, scope) => JSON.stringify([app, subject, scope]);
58
+ subscribe('preferences.evict', (key) => {
59
+ if (typeof key === 'string')
60
+ recent.delete(key);
61
+ });
57
62
  /** The picks this person holds in this scope, by choice name: only names the App declares, and none without a store. */
58
63
  export async function storedPicks(app, store, subject, scope = '') {
59
64
  if (!store || !subject || !app.choose)
@@ -86,7 +91,7 @@ export async function storedPicks(app, store, subject, scope = '') {
86
91
  /** One pick kept (or cleared, null) for this person; their next read sees it at once. */
87
92
  export async function storePick(app, store, subject, scope, name, value) {
88
93
  await store.set({ app: app.id, subject, scope }, choiceKey(name), value);
89
- recent.delete(remembered(app.id, subject, scope));
94
+ publish('preferences.evict', remembered(app.id, subject, scope));
90
95
  }
91
96
  /** What this person has stored for the App on this deployment: nothing for a visitor, an App with no `choose`, or a database with no store. */
92
97
  export async function storedForPerson(registry, host, account) {
@@ -28,7 +28,10 @@
28
28
  * - A change another process makes (another instance, a maintenance command,
29
29
  * an operator's SQL) is not seen until what was kept expires: a session
30
30
  * revoked elsewhere is honored here for at most `ttlMs`. That is the price
31
- * of the cache, and the setting's reason to exist.
31
+ * of the cache, and the setting's reason to exist. The workers of one
32
+ * `--workers` start are not another process here: each tells the others
33
+ * when it changes the store (processBus.ts `session.evict`), and they drop
34
+ * what they kept as the one that made the change does.
32
35
  * - Reads asked together while one is in flight share it, so a burst that
33
36
  * arrives cold reads once.
34
37
  *
@@ -36,7 +39,9 @@
36
39
  * header a request presents), one map per store handle, so nothing is shared
37
40
  * across Apps but the knowledge that the store changed.
38
41
  */
42
+ import { createHash } from 'node:crypto';
39
43
  import { statementHead } from '@mistriwork/engine/adapters/postgresPooler.js';
44
+ import { publish, subscribe } from '../processBus.js';
40
45
  /**
41
46
  * Sixty seconds, the maintainer's call. Everything this process does to a
42
47
  * session (a sign-out, a revocation, a password change, a ban) drops what is
@@ -65,6 +70,22 @@ export function authReadTtlMs(environment = process.env) {
65
70
  /* The store's epoch, shared by every handle on the same URL in this process:
66
71
  one App's sign-out drops what another kept of the same rows. */
67
72
  const epochs = new Map();
73
+ /* The same epochs by a digest of the URL, as the process bus names a store: the URL carries credentials. A worker
74
+ that hears another changed a store moves its epoch on, which is all a change here does to the other handles. */
75
+ const byDigest = new Map();
76
+ const storeKey = (store) => createHash('sha256').update(store).digest('base64url').slice(0, 22);
77
+ let listening = false;
78
+ function listen() {
79
+ if (listening)
80
+ return;
81
+ listening = true;
82
+ subscribe('session.evict', (payload) => {
83
+ const said = payload;
84
+ const epoch = said?.from !== process.pid && typeof said?.store === 'string' ? byDigest.get(said.store) : undefined;
85
+ if (epoch)
86
+ epoch.value += 1;
87
+ });
88
+ }
68
89
  const READ = /^SELECT\b/i;
69
90
  const BEGINS = /^(?:BEGIN|START\s+TRANSACTION)\b/i;
70
91
  /** As postgresPooler.ts reads a transaction's end: not ROLLBACK TO a savepoint, and not the PREPARED forms. */
@@ -72,15 +93,20 @@ const ENDS = /^(?:COMMIT|END|ABORT|ROLLBACK)\b(?!\s+(?:(?:WORK|TRANSACTION)\s+)?
72
93
  /** Change nothing a session read sees. */
73
94
  const NEUTRAL = /^(?:SAVEPOINT|RELEASE|ROLLBACK\s+(?:(?:WORK|TRANSACTION)\s+)?TO|SET|RESET|SHOW)\b/i;
74
95
  export function createAuthStoreReads(store, ttlMs, clock = Date.now) {
96
+ const digest = storeKey(store);
75
97
  let epoch = epochs.get(store);
76
- if (!epoch)
98
+ if (!epoch) {
77
99
  epochs.set(store, (epoch = { value: 0 }));
100
+ byDigest.set(digest, epoch);
101
+ }
102
+ listen();
78
103
  const shared = epoch;
79
104
  const entries = new Map();
80
105
  const flights = new Map();
81
106
  const changed = () => {
82
107
  shared.value += 1;
83
108
  entries.clear();
109
+ publish('session.evict', { store: digest, from: process.pid });
84
110
  };
85
111
  const put = (key, value, mark) => {
86
112
  if (ttlMs <= 0 || shared.value !== mark.epoch || clock() - mark.at >= ttlMs)
@@ -11,13 +11,18 @@
11
11
  * A cache that stops answering is read as this process's own store until it
12
12
  * answers again, as the budgets fall back to theirs: the state an outage
13
13
  * strands is at most one window's, and nothing is opened that was not proved.
14
+ *
15
+ * A `--workers` start with no cache keeps this state in its primary
16
+ * (cli/primaryCounters.ts), and a primary that does not answer is treated
17
+ * otherwise; see `closed` below.
14
18
  */
15
19
  import { type CacheStore } from '@mistriwork/engine/adapters/cache/cacheStore.js';
16
- /** Keep sign-in state in `cache` (a Valkey the config names) under `namespace`; `undefined` or a memory cache keeps it here. */
17
- export declare function configureSignInState(cache: CacheStore | undefined, namespace: string): void;
20
+ /** Keep sign-in state in `cache` (a Valkey the config names, or a worker's primary) under `namespace`; `undefined` or a
21
+ memory cache keeps it here. `pending`, when given, holds the OAuth pending requests apart, as this process does. */
22
+ export declare function configureSignInState(cache: CacheStore | undefined, namespace: string, pending?: CacheStore): void;
18
23
  /** Forget everything this process holds: tests use it. A configured cache is kept; `configureSignInState(undefined, …)` lets it go. */
19
24
  export declare function resetSignInState(): void;
20
- type Run = <T>(work: (store: CacheStore) => Promise<T>, kind?: string) => Promise<T>;
25
+ type Run = <T>(work: (store: CacheStore) => Promise<T>, kind?: string, closed?: () => T) => Promise<T>;
21
26
  declare const stateOn: (on: Run) => {
22
27
  /** The failures counted under `key` in its current window. */
23
28
  failures: (key: string) => Promise<number>;
@@ -11,6 +11,10 @@
11
11
  * A cache that stops answering is read as this process's own store until it
12
12
  * answers again, as the budgets fall back to theirs: the state an outage
13
13
  * strands is at most one window's, and nothing is opened that was not proved.
14
+ *
15
+ * A `--workers` start with no cache keeps this state in its primary
16
+ * (cli/primaryCounters.ts), and a primary that does not answer is treated
17
+ * otherwise; see `closed` below.
14
18
  */
15
19
  import { CacheUnavailable, MemoryCacheStore, scopedCache } from '@mistriwork/engine/adapters/cache/cacheStore.js';
16
20
  let local = new MemoryCacheStore(50_000);
@@ -20,27 +24,50 @@ let local = new MemoryCacheStore(50_000);
20
24
  let pending = new MemoryCacheStore(10_000);
21
25
  const PENDING_KINDS = new Set(['oauth-request', 'oauth-consent']);
22
26
  let shared;
23
- /** Keep sign-in state in `cache` (a Valkey the config names) under `namespace`; `undefined` or a memory cache keeps it here. */
24
- export function configureSignInState(cache, namespace) {
27
+ let sharedPending;
28
+ /** Keep sign-in state in `cache` (a Valkey the config names, or a worker's primary) under `namespace`; `undefined` or a
29
+ memory cache keeps it here. `pending`, when given, holds the OAuth pending requests apart, as this process does. */
30
+ export function configureSignInState(cache, namespace, pending) {
25
31
  shared = !cache || cache.kind === 'memory' ? undefined : scopedCache(cache, `mistri:${namespace}:signin:`);
32
+ sharedPending = shared && pending ? scopedCache(pending, `mistri:${namespace}:signin:`) : undefined;
26
33
  }
27
34
  /** Forget everything this process holds: tests use it. A configured cache is kept; `configureSignInState(undefined, …)` lets it go. */
28
35
  export function resetSignInState() {
29
36
  local = new MemoryCacheStore(50_000);
30
37
  pending = new MemoryCacheStore(10_000);
31
38
  }
32
- async function on(work, kind) {
33
- if (shared) {
39
+ /* `closed`: what an operation answers when a worker's primary (cli/primaryCounters.ts) does not, rather than this
40
+ process's own store. A Valkey outage is every instance's at once, and each counting alone for a window is the
41
+ best left; a primary that does not answer is one stuck process of a start whose other workers may still reach it,
42
+ and this worker's own store was never in step with theirs. So there a lockout fails CLOSED: a failure count reads
43
+ as past every limit (the attempt is refused, and with nothing kept no lock outlives the outage), a proof or a held
44
+ request reads as absent, and a write is dropped rather than kept where the other workers cannot see it. Better
45
+ Auth's plain request budget (`consume`) passes no `closed` and fails OPEN to this process's count: refusing every
46
+ sign-in for a late answer would lock everyone out, and each attempt is still judged by the lockout. */
47
+ async function on(work, kind, closed) {
48
+ const isPending = kind !== undefined && PENDING_KINDS.has(kind);
49
+ const store = isPending ? (sharedPending ?? shared) : shared;
50
+ if (store) {
34
51
  try {
35
- return await work(shared);
52
+ return await work(store);
36
53
  }
37
54
  catch (error) {
38
55
  if (!(error instanceof CacheUnavailable))
39
56
  throw error;
57
+ if (store.kind === 'primary' && closed)
58
+ return closed();
40
59
  }
41
60
  }
42
- return work(kind !== undefined && PENDING_KINDS.has(kind) ? pending : local);
61
+ return work(isPending ? pending : local);
43
62
  }
63
+ const PAST_EVERY_LIMIT = () => Number.MAX_SAFE_INTEGER;
64
+ const NOTHING = () => undefined;
65
+ /* Taking a one-use OAuth record away is what makes it one use: a removal the primary did not hear would leave it for a
66
+ second post through another worker, so that removal refuses, and the request it belongs to fails before it issues
67
+ anything. */
68
+ const REFUSE = () => {
69
+ throw new CacheUnavailable('The primary did not answer.');
70
+ };
44
71
  /** Bounded so a crafted key cannot make an entry outlive the cache's own ceiling. */
45
72
  const ttl = (ms) => Math.max(1, Math.min(Math.ceil(ms), 30 * 24 * 3_600_000));
46
73
  const stateOn = (on) => ({
@@ -48,10 +75,10 @@ const stateOn = (on) => ({
48
75
  failures: (key) => on(async (store) => {
49
76
  const value = Number(await store.get(`fail:${key}`));
50
77
  return Number.isSafeInteger(value) && value > 0 ? value : 0;
51
- }),
78
+ }, undefined, PAST_EVERY_LIMIT),
52
79
  /** Count one more failure; the window starts at the first and lasts `windowMs`. */
53
- fail: (key, windowMs) => on(async (store) => (await store.incr(`fail:${key}`, ttl(windowMs))).count),
54
- clearFailures: (key) => on((store) => store.delete(`fail:${key}`)),
80
+ fail: (key, windowMs) => on(async (store) => (await store.incr(`fail:${key}`, ttl(windowMs))).count, undefined, PAST_EVERY_LIMIT),
81
+ clearFailures: (key) => on((store) => store.delete(`fail:${key}`), undefined, NOTHING),
55
82
  /** Better Auth's own request budget (its `rateLimit.customStorage`): one
56
83
  more request under `key` in a fixed window of `windowSeconds`, allowed
57
84
  while the count is within `max`. Kept here so instances behind one load
@@ -64,9 +91,9 @@ const stateOn = (on) => ({
64
91
  : { allowed: false, retryAfter: Math.max(1, Math.ceil(counted.ttlMs / 1000)) };
65
92
  }),
66
93
  /** A JSON record that lives until `until` (epoch ms). */
67
- put: (kind, key, value, until, now = Date.now()) => until <= now ? Promise.resolve() : on((store) => store.set(`${kind}:${key}`, JSON.stringify(value), ttl(until - now)), kind),
94
+ put: (kind, key, value, until, now = Date.now()) => until <= now ? Promise.resolve() : on((store) => store.set(`${kind}:${key}`, JSON.stringify(value), ttl(until - now)), kind, NOTHING),
68
95
  read: async (kind, key) => {
69
- const text = await on((store) => store.get(`${kind}:${key}`), kind);
96
+ const text = await on((store) => store.get(`${kind}:${key}`), kind, NOTHING);
70
97
  if (text === undefined)
71
98
  return undefined;
72
99
  try {
@@ -76,7 +103,7 @@ const stateOn = (on) => ({
76
103
  return undefined;
77
104
  }
78
105
  },
79
- remove: (kind, key) => on((store) => store.delete(`${kind}:${key}`), kind),
106
+ remove: (kind, key) => on((store) => store.delete(`${kind}:${key}`), kind, PENDING_KINDS.has(kind) ? REFUSE : NOTHING),
80
107
  });
81
108
  export const signInState = stateOn(on);
82
109
  /** The same state over one store, as every instance of a deployment sees its shared cache: tests stand two instances
@@ -48,7 +48,7 @@ import { tableNamed } from '@mistriwork/engine/shared/schema.js';
48
48
  import { getCommandEvents } from '../commands/businessCommands.js';
49
49
  import { NO_OUTPUT } from '../commands/commandShapes.js';
50
50
  import { AppProblems, homeSourceOf, isFormView, logicalResource, withRollups } from '../../shared/app.js';
51
- import { parseArgs, postgresPoolFlags } from '@mistriwork/engine/server/cli/args.js';
51
+ import { availableCores, parseArgs, postgresPoolFlags, workerCount } from '@mistriwork/engine/server/cli/args.js';
52
52
  import { sayBudget } from '@mistriwork/engine/adapters/connectionBudget.js';
53
53
  import { readStartupConfig } from '@mistriwork/engine/server/cli/config.js';
54
54
  import { moduleTypeProblem } from '../cli/projectSetup.js';
@@ -115,7 +115,7 @@ const CHECK_EXIT = {
115
115
  /* The App's stores are not in its database yet: the migrate step's to make, not the App's to fix (store-pending). */
116
116
  stores: 8,
117
117
  };
118
- const CHECK_USAGE = 'mistri check [--app <dir>] [--app-entry <file>] [<db> | --db <target> | --config <path>] [--commands <file>] [--jobs <file>] [--policy <file>] [--bump <command>] [--routes [--mount <app>=<path>] [--base-path <path>]] [--design] [--fix] [--fail-on-design-warning] [--defaults] [--no-index-check] [--no-query-check] [--warnings] [--pending [--pending-on <url>] [--migrations <dir>] [--history-table <name>]] [--schema-file [<schema.sql>] [--dev-url <url>]] [--deploy [--replicas <n>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]';
118
+ const CHECK_USAGE = 'mistri check [--app <dir>] [--app-entry <file>] [<db> | --db <target> | --config <path>] [--commands <file>] [--jobs <file>] [--policy <file>] [--bump <command>] [--routes [--mount <app>=<path>] [--base-path <path>]] [--design] [--fix] [--fail-on-design-warning] [--defaults] [--no-index-check] [--no-query-check] [--warnings] [--pending [--pending-on <url>] [--migrations <dir>] [--history-table <name>]] [--schema-file [<schema.sql>] [--dev-url <url>]] [--deploy [--replicas <n>] [--workers <n|auto>] [--connection-limit <n>] [--cpus <n>] [--strict-migrations]] [--json | --brief]';
119
119
  const TYPES = 'mistri-schema.d.ts';
120
120
  /** The App's commands by name, from its commands module (typegen.ts commandTypes). */
121
121
  const COMMAND_TYPES = 'mistri-commands.d.ts';
@@ -721,7 +721,7 @@ async function runSteps(argv, write, emit) {
721
721
  "--no-query-check skips the queries step: the database EXPLAINs each read the App's pages would make (lists, related and grouped lists, timelines, breakdowns, figures, rollups) and says the ones it refuses (query-invalid, with the page:section); nothing is run, and PostgreSQL plans them in a READ ONLY transaction.\n" +
722
722
  '--bump <command> moves a command whose contract changed to its next version in authority.lock (its API route, receipts and jobs follow).\n' +
723
723
  "--pending judges the App against the schema as it will be after the pending migrations (mistri migrate), applied to a scratch copy, or with --pending-on <url> to the scratch database that URL names (a branch of the database, never the App's own). Exit 6: one failed there. The backstop step is not judged on a copy: check without --pending once they are applied.\n" +
724
- "--deploy judges whether the App survives a container being replaced (mistri docs build-and-deploy): it refuses a source or auth.store on a SQLite file, the default auth.store, and a missing BETTER_AUTH_SECRET or ${NAME} the environment lacks, and with --replicas <n> above one it warns about per-process rate limits. It also reads the migrations not yet applied and warns about a statement that breaks the code still running (a dropped or renamed column or table, a type change, SET NOT NULL, a NOT NULL column without a default), as expand/contract steps; mark a deliberate one with a '-- mistri: contract' comment on the line before it, and add --strict-migrations to fail on the rest. Run it with the deployment's environment. Exit 7.\n" +
724
+ "--deploy judges whether the App survives a container being replaced (mistri docs build-and-deploy): it refuses a source or auth.store on a SQLite file, the default auth.store, and a missing BETTER_AUTH_SECRET or ${NAME} the environment lacks, and with --replicas <n> (or --workers <n|auto>, each replica's processes) above one process it warns about per-process rate limits and counts every process's pools. It also reads the migrations not yet applied and warns about a statement that breaks the code still running (a dropped or renamed column or table, a type change, SET NOT NULL, a NOT NULL column without a default), as expand/contract steps; mark a deliberate one with a '-- mistri: contract' comment on the line before it, and add --strict-migrations to fail on the rest. Run it with the deployment's environment. Exit 7.\n" +
725
725
  '--json prints one JSON document instead (schema/check.schema.json): every finding with its code, file, line, column, path and fix.\n' +
726
726
  '--brief prints one line per problem, `code file:line message — fix: …`, and nothing else (ok when there is none): errors each in full, warnings a group by code and resource with its count and one example (--warnings lists every one). Exit codes are the same. mistri explain <code> says more.');
727
727
  return CHECK_EXIT.passed;
@@ -878,6 +878,19 @@ async function runSteps(argv, write, emit) {
878
878
  return CHECK_EXIT.couldNotCheck;
879
879
  }
880
880
  let opts = parseArgs(rest);
881
+ /* --workers is the start's flag, read by parseArgs as the start reads it (and MISTRI_WORKERS with it, the
882
+ deployment's environment being what --deploy is run with): here it multiplies the processes --deploy counts. */
883
+ if (rest.includes('--workers') && !deploy) {
884
+ console.error(`mistri check: --workers says how many processes each instance runs, for --deploy to count. ${CHECK_USAGE}`);
885
+ return CHECK_EXIT.couldNotCheck;
886
+ }
887
+ /* The count a start here would run (`auto` unless asked: the cores, narrowed by a container's limits), or the
888
+ cores --cpus names. */
889
+ const workers = deploy ? workerCount(opts, cpus ?? availableCores().cores) : 1;
890
+ if (typeof workers === 'string') {
891
+ console.error(`mistri check: ${workers} ${CHECK_USAGE}`);
892
+ return CHECK_EXIT.couldNotCheck;
893
+ }
881
894
  const mode = MODES.find(([key]) => opts[key] !== undefined && opts[key] !== false);
882
895
  const refusal = opts.unknown
883
896
  ? `unknown option "${opts.unknown}"`
@@ -1782,6 +1795,7 @@ async function runSteps(argv, write, emit) {
1782
1795
  activeId: registry.active ?? undefined,
1783
1796
  cache: registry.serviceConfigs().some((service) => service.kind === 'cache'),
1784
1797
  ...(replicas !== undefined ? { replicas } : {}),
1798
+ ...(workers > 1 ? { workers } : {}),
1785
1799
  ...(connectionLimit !== undefined ? { connectionLimit } : {}),
1786
1800
  ...(cpus !== undefined ? { cpus } : {}),
1787
1801
  served: await servedFactsOf(loaded.app, loaded.commands?.registry, opts.jobs),
@@ -14,7 +14,7 @@
14
14
  * file is a deployment this project supports; refusing there would break it.
15
15
  */
16
16
  import { isAbsolute } from 'node:path';
17
- import { availableParallelism } from 'node:os';
17
+ import { availableCores } from '@mistriwork/engine/server/cli/args.js';
18
18
  import { appReaders } from '@mistriwork/engine/adapters/postgresPool.js';
19
19
  import { balancedPoolSize } from '@mistriwork/engine/adapters/writeLanes.js';
20
20
  import { databaseOf, primaryConnections, sayBudget } from '@mistriwork/engine/adapters/connectionBudget.js';
@@ -136,6 +136,8 @@ export function deployFindings(input) {
136
136
  fix: 'Unset MISTRI_SERVER_TIMING in production, or set MISTRI_SERVER_TIMING_TOKEN and send it as an x-mistri-timing header from the load driver.',
137
137
  });
138
138
  }
139
+ /* Rate limits and lockout counters are each replica's own without a cache service. A start's workers are not
140
+ counted: they share their primary's (cli/primaryCounters.ts), as they share one form key (processKey.ts). */
139
141
  if ((input.replicas ?? 1) > 1 && !input.cache) {
140
142
  found.push({
141
143
  code: 'deploy-per-process-limits',
@@ -146,20 +148,23 @@ export function deployFindings(input) {
146
148
  }
147
149
  return found;
148
150
  }
151
+ /** The processes the deployment runs: each replica's workers (`--replicas` × `--workers`). */
152
+ const processCount = (input) => (input.replicas ?? 1) * (input.workers ?? 1);
149
153
  const count = (value) => typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;
150
154
  /**
151
- * What the replicas of this App may hold against each database: one process's pools times the replicas, summed by
152
- * database, because two connections or the auth store may name one. Per process, a PostgreSQL source holds its
153
- * readers, its writers and the background writer, one LISTEN connection for live sync, and each read replica
154
- * another reader pool; the sign-in store holds `MISTRI_AUTH_POOL`. Sizes follow the flags, a connection's `pool`,
155
- * and else the defaults an App gets (writers: twice the cores, 4 to 16; readers: as many as the writers) — the cores
156
- * of the machine that runs the check, which are the deployment's only when the two match. The hosts the App builds
157
- * from what it declares — a tenant App's shared request manager, the server's own stores — are servedHosts.ts's,
155
+ * What the processes of this App may hold against each database: one process's pools times the replicas times each
156
+ * one's workers, summed by database, because two connections or the auth store may name one. Per process, a
157
+ * PostgreSQL source holds its readers, its writers and the background writer, one LISTEN connection for live sync,
158
+ * and each read replica another reader pool; the sign-in store holds `MISTRI_AUTH_POOL`. Sizes follow the flags, a
159
+ * connection's `pool`, and else the defaults an App gets (writers: twice the cores, 4 to 16; readers: as many as the
160
+ * writers) — the cores of the machine that runs the check, which are the deployment's only when the two match, and a
161
+ * worker's share of them under `--workers`. The hosts the App builds from what it declares — a tenant App's shared
162
+ * request manager, the server's own stores — are servedHosts.ts's,
158
163
  * on the home connection (docs/postgresql.md).
159
164
  */
160
165
  export function connectionBudgets(input) {
161
166
  const { app, env } = input;
162
- const processes = input.replicas ?? 1;
167
+ const processes = processCount(input);
163
168
  const perProcess = new Map();
164
169
  const parts = new Map();
165
170
  const add = (url, connections, host) => {
@@ -167,7 +172,9 @@ export function connectionBudgets(input) {
167
172
  perProcess.set(database, (perProcess.get(database) ?? 0) + connections);
168
173
  parts.set(database, [...(parts.get(database) ?? []), { host, connections }]);
169
174
  };
170
- const cores = input.cpus ?? availableParallelism();
175
+ const cores = input.cpus ?? availableCores().cpus;
176
+ /* A worker's default pools are sized for its share of the cores, as the start sizes them (cli/mistriMain.ts). */
177
+ const share = Math.ceil(cores / (input.workers ?? 1));
171
178
  let sized = false;
172
179
  const bound = [
173
180
  ...new Set([...Object.values(app.sources ?? {}).map((source) => source.connection), ...(app.connection ? [app.connection] : [])]),
@@ -188,8 +195,8 @@ export function connectionBudgets(input) {
188
195
  const given = { write: count(pool.write) ?? input.pools?.writers, read: count(pool.read) ?? input.pools?.readers };
189
196
  if (given.write === undefined || given.read === undefined)
190
197
  sized = true;
191
- const writers = given.write ?? balancedPoolSize(cores);
192
- const readers = given.read ?? appReaders(writers, cores);
198
+ const writers = given.write ?? balancedPoolSize(share);
199
+ const readers = given.read ?? appReaders(writers, share);
193
200
  /* A tenant App opens no adapter of its own on its home connection: its request paths share one manager there,
194
201
  which servedHosts counts with the LISTEN (tenant/tenantConnections.ts). */
195
202
  if (!(home && input.served?.tenant))
@@ -219,11 +219,18 @@ export async function loadStartupApps(opts, registry, config) {
219
219
  throw new Error(ticketKey.refuse);
220
220
  if (ticketKey)
221
221
  console.warn(`warning: ${'refuse' in ticketKey ? ticketKey.refuse : ticketKey.warn}`);
222
+ const namespace = loadedApps.length === 1 ? loadedApps[0].app.id : 'deployment';
222
223
  if (sharedCache) {
223
- const namespace = loadedApps.length === 1 ? loadedApps[0].app.id : 'deployment';
224
224
  configurePublicFormLimits(registry.cache(), namespace);
225
225
  configureSignInState(registry.cache(), namespace);
226
226
  }
227
+ else if ((await import('./workers.js')).workerIndex() !== undefined) {
228
+ /* Without one, the workers of a `--workers` start count in their primary, so the start spends one budget, as
229
+ one process would (primaryCounters.ts). */
230
+ const { primaryCounters } = await import('./primaryCounters.js');
231
+ configurePublicFormLimits(primaryCounters('forms'), namespace);
232
+ configureSignInState(primaryCounters('signin'), namespace, primaryCounters('pending'));
233
+ }
227
234
  for (const loaded of loadedApps) {
228
235
  pages = mergeAppPages(pages, loaded, config.configPath);
229
236
  }