@ultimat3/cli 31.48.0 → 31.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CLAUDE.md +30 -23
  2. package/README.md +96 -4
  3. package/package.json +30 -30
  4. package/src/api-registration.ts +45 -14
  5. package/src/api-routes.ts +1 -0
  6. package/src/app-load.ts +7 -3
  7. package/src/app-openapi.ts +7 -1
  8. package/src/app-root.ts +7 -1
  9. package/src/budgets.ts +2 -1
  10. package/src/clean-services.ts +142 -0
  11. package/src/cmd-auth.ts +3 -0
  12. package/src/cmd-clean-spec.ts +10 -3
  13. package/src/cmd-clean.ts +23 -9
  14. package/src/cmd-db-backfill.ts +6 -0
  15. package/src/cmd-db-branch.ts +10 -4
  16. package/src/cmd-db-recount.ts +5 -12
  17. package/src/cmd-db-rollback.ts +77 -0
  18. package/src/cmd-db-spec.ts +18 -2
  19. package/src/cmd-db-status.ts +5 -10
  20. package/src/cmd-db.ts +105 -33
  21. package/src/cmd-deploy-verify.ts +14 -6
  22. package/src/cmd-docs-topic.ts +94 -0
  23. package/src/cmd-docs.ts +15 -1
  24. package/src/cmd-doctor.ts +109 -41
  25. package/src/cmd-drill.ts +80 -18
  26. package/src/cmd-env.ts +30 -8
  27. package/src/cmd-errors-app.ts +63 -0
  28. package/src/cmd-errors.ts +50 -14
  29. package/src/cmd-generate.ts +17 -4
  30. package/src/cmd-heavy-spec.ts +9 -1
  31. package/src/cmd-heavy.ts +111 -27
  32. package/src/cmd-i18n.ts +33 -1
  33. package/src/cmd-jobs.ts +27 -1
  34. package/src/cmd-merge-driver-spec.ts +12 -0
  35. package/src/cmd-merge-driver.ts +95 -0
  36. package/src/cmd-new.ts +23 -3
  37. package/src/cmd-policy-spec.ts +9 -1
  38. package/src/cmd-policy.ts +72 -17
  39. package/src/cmd-stop.ts +18 -4
  40. package/src/cmd-tasks-run.ts +87 -0
  41. package/src/cmd-tasks-spec.ts +10 -3
  42. package/src/cmd-tasks.ts +8 -5
  43. package/src/cmd-test.ts +2 -1
  44. package/src/cmd-upgrade-spec.ts +8 -1
  45. package/src/cmd-upgrade.ts +15 -1
  46. package/src/cmd-verify.ts +9 -41
  47. package/src/codemods/agents-doc-row.ts +73 -0
  48. package/src/codemods/define-error-leaf.ts +37 -12
  49. package/src/codemods/docs-many-agents.ts +11 -15
  50. package/src/codemods/docs-worker-commands.ts +26 -0
  51. package/src/codemods/engine-fs.ts +9 -2
  52. package/src/codemods/index.ts +4 -0
  53. package/src/codemods/merge-drivers.ts +147 -0
  54. package/src/command.ts +3 -0
  55. package/src/db-applied-edits.ts +117 -0
  56. package/src/db-dev-wire.ts +18 -0
  57. package/src/db-diagnostics.ts +5 -10
  58. package/src/db-generate.ts +82 -7
  59. package/src/db-migrate-pass.ts +51 -0
  60. package/src/db-migrate-through-dev.ts +209 -0
  61. package/src/db-rollback-consent.ts +128 -0
  62. package/src/db-rollback-pass.ts +76 -0
  63. package/src/db-seed-generate.ts +5 -1
  64. package/src/db-seed.ts +7 -1
  65. package/src/deploy-verify-findings.ts +3 -0
  66. package/src/deploy-verify-grade.ts +3 -0
  67. package/src/deploy-verify-processes.ts +32 -0
  68. package/src/dev-boot.ts +3 -0
  69. package/src/dev-db-migrate.ts +155 -0
  70. package/src/dev-db-rollback.ts +33 -0
  71. package/src/dev-db-settled.ts +22 -0
  72. package/src/dev-lock-errors.ts +78 -0
  73. package/src/dev-lock-holder-dir.ts +64 -0
  74. package/src/dev-lock-live.ts +44 -0
  75. package/src/dev-lock.ts +59 -84
  76. package/src/dev-policy.ts +11 -8
  77. package/src/dev-rebuild-schema.ts +116 -13
  78. package/src/dev-rebuild.ts +13 -4
  79. package/src/dev-route-table.ts +7 -0
  80. package/src/dispatch.ts +21 -1
  81. package/src/doctor-api-listing.ts +114 -0
  82. package/src/doctor-guarded.ts +41 -0
  83. package/src/doctor-port.ts +90 -17
  84. package/src/doctor-probe.ts +36 -5
  85. package/src/doctor-processes-probe.ts +127 -0
  86. package/src/doctor-processes.ts +136 -0
  87. package/src/doctor-warnings.ts +17 -0
  88. package/src/error-codes-agents.ts +35 -0
  89. package/src/error-codes-processes.ts +30 -0
  90. package/src/error-codes-tooling.ts +2 -0
  91. package/src/error-codes.ts +12 -13
  92. package/src/errors-suite.ts +27 -0
  93. package/src/errors.ts +18 -22
  94. package/src/exercise-registration.ts +4 -3
  95. package/src/exercise-services.ts +13 -3
  96. package/src/framework-env.ts +7 -3
  97. package/src/framework-schema.ts +15 -5
  98. package/src/generate-files.ts +1 -0
  99. package/src/generate-grant-findings.ts +7 -5
  100. package/src/generate-grants.ts +9 -8
  101. package/src/generate-kinds.ts +30 -6
  102. package/src/generate-roles-file.ts +30 -0
  103. package/src/generate-slice-policy.ts +3 -3
  104. package/src/guard-sources.ts +1 -2
  105. package/src/guards.ts +2 -2
  106. package/src/heavy-env.ts +2 -0
  107. package/src/heavy-errors.ts +18 -0
  108. package/src/heavy-holders.ts +78 -0
  109. package/src/heavy-ledger.ts +56 -14
  110. package/src/heavy-pressure.ts +104 -0
  111. package/src/heavy.ts +31 -13
  112. package/src/i18n-registration.ts +22 -2
  113. package/src/island-harness.ts +2 -2
  114. package/src/job-budget.ts +4 -2
  115. package/src/job-registration.ts +64 -8
  116. package/src/jobs-queue-known.ts +43 -0
  117. package/src/mcp-errors-agents.ts +20 -0
  118. package/src/mcp-errors-doctor.ts +27 -0
  119. package/src/mcp-errors-processes.ts +23 -0
  120. package/src/mcp-errors.ts +15 -29
  121. package/src/mcp-host.ts +2 -2
  122. package/src/merge-driver-catalog.ts +58 -0
  123. package/src/merge-driver-config.ts +43 -0
  124. package/src/merge-driver-lines.ts +140 -0
  125. package/src/merge-state.ts +105 -0
  126. package/src/messages-db.ts +22 -1
  127. package/src/messages-processes.ts +13 -0
  128. package/src/messages-upgrade.ts +10 -0
  129. package/src/messages.ts +54 -4
  130. package/src/output-findings.ts +48 -21
  131. package/src/page-navigation.ts +5 -2
  132. package/src/parse.ts +37 -6
  133. package/src/policy-facts.ts +38 -21
  134. package/src/policy-row.ts +99 -0
  135. package/src/port-pair-free.ts +28 -0
  136. package/src/pwa-artifacts.ts +1 -1
  137. package/src/registry-lines.ts +110 -0
  138. package/src/registry.ts +2 -0
  139. package/src/retain-sweep.ts +1 -1
  140. package/src/retained-assets-boot.ts +1 -1
  141. package/src/role-replicator.ts +4 -1
  142. package/src/role-select.ts +86 -0
  143. package/src/role-start.ts +13 -55
  144. package/src/role-sync.ts +10 -5
  145. package/src/runtime-assets-site.ts +2 -2
  146. package/src/runtime-assets.ts +1 -1
  147. package/src/runtime-cache-frame.ts +46 -0
  148. package/src/runtime-cache-ttl.ts +23 -0
  149. package/src/runtime-cache.ts +33 -16
  150. package/src/runtime-database-ssl.ts +84 -0
  151. package/src/runtime-idempotency-scope.ts +16 -2
  152. package/src/runtime-jobs-share.ts +52 -0
  153. package/src/runtime-jobs.ts +43 -12
  154. package/src/runtime-queue.ts +18 -3
  155. package/src/runtime-render-document.ts +1 -2
  156. package/src/runtime-services.ts +8 -1
  157. package/src/schema-drift.ts +19 -2
  158. package/src/schema-dump-drift.ts +4 -1
  159. package/src/serve-boot-probe.ts +30 -2
  160. package/src/serve-boot.ts +11 -1
  161. package/src/serve-env.ts +39 -3
  162. package/src/serve.ts +61 -10
  163. package/src/site-asset-routes.ts +2 -2
  164. package/src/site-assets.ts +5 -158
  165. package/src/stop-run-start.ts +12 -0
  166. package/src/supervise-boot.ts +61 -0
  167. package/src/supervise-cgroup.ts +84 -0
  168. package/src/supervise-child.ts +206 -0
  169. package/src/supervise-count.ts +244 -0
  170. package/src/supervise-errors.ts +83 -0
  171. package/src/supervise-facts.ts +40 -0
  172. package/src/supervise-messages.ts +84 -0
  173. package/src/supervise-policy.ts +46 -0
  174. package/src/supervise-pool.ts +10 -0
  175. package/src/supervise-probe.ts +158 -0
  176. package/src/supervise-run.ts +54 -0
  177. package/src/supervise.ts +383 -0
  178. package/src/sw-precache-plan.ts +1 -1
  179. package/src/templates/generate-purge.ts +6 -6
  180. package/src/templates/guard-animated-layout-property.ts +2 -2
  181. package/src/templates/guard-bare-error.ts +1 -1
  182. package/src/templates/guard-error-declared.ts +2 -2
  183. package/src/templates/guard-focus-visible.ts +1 -1
  184. package/src/templates/guard-image-dimensions.ts +2 -2
  185. package/src/templates/guard-island-mount-clears.ts +1 -1
  186. package/src/templates/guard-native-confirm.ts +1 -1
  187. package/src/templates/guard-raw-breakpoint.ts +2 -2
  188. package/src/templates/guard-raw-colour.ts +2 -2
  189. package/src/templates/guard-raw-fetch.ts +1 -1
  190. package/src/templates/guard-raw-interval.ts +1 -1
  191. package/src/templates/guard-raw-length.ts +3 -3
  192. package/src/templates/guard-raw-motion.ts +97 -1
  193. package/src/templates/guard-raw-shadow.ts +1 -1
  194. package/src/templates/guard-raw-z-index.ts +1 -1
  195. package/src/templates/guard-released-forms.ts +58 -9
  196. package/src/templates/guard-repo-await-in-loop.ts +1 -1
  197. package/src/templates/guard-repo-raw-sql.ts +4 -4
  198. package/src/templates/guard-repo-unbounded.ts +1 -1
  199. package/src/templates/guard-runtime-pin.ts +1 -1
  200. package/src/templates/guard-semantic-interactive.ts +2 -2
  201. package/src/templates/guard-unbounded-fanout.ts +1 -1
  202. package/src/templates/guard-undeclared-custom-property.ts +3 -3
  203. package/src/templates/guard-undefined-style-class.ts +3 -3
  204. package/src/templates/guard-unzoned-date.ts +3 -3
  205. package/src/templates/query-slice.ts +82 -0
  206. package/src/templates/query.ts +76 -30
  207. package/src/templates/resource-page.ts +3 -2
  208. package/src/templates/scaffold-bin.ts +2 -0
  209. package/src/templates/scaffold-claude-commands.ts +6 -0
  210. package/src/templates/scaffold-claude.ts +4 -4
  211. package/src/templates/scaffold-container-compose.ts +47 -7
  212. package/src/templates/scaffold-docs.ts +7 -3
  213. package/src/templates/scaffold-gitattributes.ts +18 -1
  214. package/src/templates/scaffold-helm-templates.ts +9 -0
  215. package/src/templates/scaffold-repo.ts +5 -2
  216. package/src/templates/scaffold-test-services.ts +33 -11
  217. package/src/templates/shapes/offline.ts +0 -7
  218. package/src/templates/shapes/realtime.ts +2 -6
  219. package/src/templates/sign-in-action-tests.ts +6 -4
  220. package/src/templates/sign-in-challenge.ts +62 -0
  221. package/src/templates/sign-in-oidc-mfa.ts +31 -0
  222. package/src/templates/sign-in-oidc.ts +11 -3
  223. package/src/templates/sign-in-password.ts +18 -56
  224. package/src/test-only-shipped.ts +29 -2
  225. package/src/test-shards.ts +134 -42
  226. package/src/test-verdict.ts +79 -0
  227. package/src/test-workers.ts +15 -0
  228. package/src/upgrade-coverage-ratchet.ts +95 -0
  229. package/src/upgrade-gate-codemods.ts +5 -3
  230. package/src/upgrade-gate.ts +42 -4
  231. package/src/upgrade-merge-drivers.ts +25 -0
  232. package/src/upgrade-report.ts +32 -4
  233. package/src/upgrade-scope.ts +62 -0
  234. package/src/verify-checks.ts +2 -8
  235. package/src/verify-coverage-run.ts +4 -1
  236. package/src/verify-e2e.ts +21 -3
  237. package/src/verify-live.ts +38 -14
  238. package/src/verify-only.ts +67 -0
  239. package/src/verify-progress.ts +7 -3
  240. package/src/verify-run.ts +20 -2
  241. package/src/verify-services-stack.ts +165 -0
  242. package/src/verify-services.ts +84 -2
  243. package/src/verify-test-run.ts +6 -7
  244. package/src/verify-tests.ts +8 -2
  245. package/src/verify-typecheck.ts +25 -2
  246. package/src/workspace-checks.ts +4 -1
  247. package/wiki/Actions.md +66 -3
  248. package/wiki/Admin-Dashboard.md +2 -2
  249. package/wiki/Agents.md +5 -5
  250. package/wiki/Auth.md +20 -6
  251. package/wiki/Bare-VM.md +1 -1
  252. package/wiki/CI-Parallel-Gate.md +2 -1
  253. package/wiki/CLI-Reference.md +115 -42
  254. package/wiki/Caching-And-Invalidation.md +1 -1
  255. package/wiki/Client-Navigation.md +35 -5
  256. package/wiki/Configuration.md +12 -10
  257. package/wiki/Deployment.md +44 -4
  258. package/wiki/Entities-And-Migrations.md +17 -3
  259. package/wiki/FAQ.md +1 -1
  260. package/wiki/Getting-Started.md +2 -2
  261. package/wiki/Home.md +3 -3
  262. package/wiki/I18n.md +6 -4
  263. package/wiki/Installation.md +12 -11
  264. package/wiki/Interface-Rules.md +3 -1
  265. package/wiki/Jobs-And-Workflows.md +24 -4
  266. package/wiki/Known-Gaps.md +2 -2
  267. package/wiki/MCP-And-AI.md +48 -13
  268. package/wiki/Many-Agents.md +69 -2
  269. package/wiki/Migrations-And-Backfills.md +18 -0
  270. package/wiki/Notify.md +5 -3
  271. package/wiki/Observability.md +13 -0
  272. package/wiki/Outbound-HTTP.md +53 -2
  273. package/wiki/Policies-And-Authz.md +1 -1
  274. package/wiki/Queries-And-Live-Queries.md +2 -2
  275. package/wiki/Realtime.md +24 -7
  276. package/wiki/Routes-And-Render-Modes.md +2 -2
  277. package/wiki/Scheduled-Tasks.md +4 -1
  278. package/wiki/Static-Assets.md +5 -3
  279. package/wiki/Testing.md +64 -7
  280. package/wiki/Theming.md +6 -3
  281. package/wiki/Timezones-And-Dates.md +5 -1
  282. package/wiki/Troubleshooting.md +1 -0
  283. package/wiki/Tutorial-01-First-App.md +3 -3
  284. package/wiki/Tutorial-02-First-Feature.md +1 -1
  285. package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
  286. package/wiki/UI-Components.md +1 -0
  287. package/wiki/Upgrading.md +38 -0
@@ -0,0 +1,206 @@
1
+ // A supervised child's half of the link: say `ready` once booted and bound, acknowledge a drain
2
+ // the moment its handler runs, drain on the supervisor's message, and leave when the supervisor
3
+ // is gone — IPC `disconnect` first, a poll of the ORIGINAL ppid behind it (an orphan is re-parented
4
+ // to the nearest subreaper, not to pid 1: measured), so a SIGKILLed supervisor leaves no orphan.
5
+
6
+ import {
7
+ DRAIN_TIMEOUT_EXIT_CODE,
8
+ drain,
9
+ drainDeadlineMs,
10
+ isUltimateError,
11
+ logger,
12
+ readinessGraceMs,
13
+ renderThrowable,
14
+ supervisedChild,
15
+ } from '@ultimat3/core';
16
+ import type { ChildMessage, DrainSignal } from './supervise-messages';
17
+ import { PROCESS_MESSAGE_TYPE, readDrainMessage } from './supervise-messages';
18
+
19
+ /** How often the ppid is asked; `disconnect` usually answers first (~20 ms, measured). */
20
+ export const PARENT_POLL_MS = 1_000;
21
+ /** Past its own drain bound, a child whose supervisor is gone exits whatever the drain did. */
22
+ export const ORPHAN_EXIT_SLACK_MS = 2_000;
23
+
24
+ type Release = () => void;
25
+
26
+ /**
27
+ * Boot refusals that are a function of the image and its environment alone: a restart of the same
28
+ * child meets each again, unchanged, so the supervisor stops at the first and the container exits 1
29
+ * with the child's own code and fix. Never what can heal by itself while the child waits — a
30
+ * database, Redis or NATS still starting, migrations the migrate job has not applied yet
31
+ * (`X_APP_MIGRATIONS_UNAPPLIED`, `X_FRAMEWORK_SCHEMA_UNAPPLIED`), a port still held, a pool
32
+ * timeout — nor state outside the image (`X_DB_ROW_SECURITY_BYPASSED`: a grant;
33
+ * `X_SEAL_KEY_UNKNOWN`: rows), nor `X_APP_MODULE_LOAD_FAILED`, which wraps whatever an app module
34
+ * threw at import.
35
+ */
36
+ export const FATAL_BOOT_CODES: ReadonlySet<string> = new Set([
37
+ // The environment: a required variable missing or malformed, a value no deploy names.
38
+ 'X_ENV_MISSING',
39
+ 'X_ROLE_UNKNOWN',
40
+ 'X_ROLE_INVALID',
41
+ 'X_ENVIRONMENT_INVALID',
42
+ 'X_PORT_INVALID',
43
+ 'X_CURSOR_SECRET_DEV',
44
+ // `app.config.ts`, the TLS pair, a role the config does not list, a database a newer major
45
+ // stamped.
46
+ 'X_CONFIG_INVALID',
47
+ // The committed secrets against the key the environment holds.
48
+ 'X_SEAL_KEY_MISSING',
49
+ 'X_SECRETS_KEY_MISSING',
50
+ 'X_SECRETS_KEY_INVALID',
51
+ 'X_SECRETS_KEY_MISMATCH',
52
+ 'X_SECRETS_FILE_INVALID',
53
+ 'X_SECRETS_TAMPERED',
54
+ // What the image holds: an import that resolves nowhere, an app that registers nothing, a role
55
+ // missing what the manifest names, a queue, disk or store the app never declared.
56
+ 'X_APP_IMPORT_UNRESOLVED',
57
+ 'X_APP_EMPTY',
58
+ 'X_ROLE_LOAD_INCOMPLETE',
59
+ 'X_WORKER_QUEUE_UNKNOWN',
60
+ 'X_STORAGE_DISK_UNKNOWN',
61
+ 'X_IDEMPOTENCY_NOT_SHARED',
62
+ 'X_NOTIFY_STORE_MISSING',
63
+ // The count itself and per-process state under it.
64
+ 'X_PROCESSES_INVALID',
65
+ 'X_PROCESSES_ROLE_SINGLETON',
66
+ 'X_PROCESSES_UNSHARED_STATE',
67
+ 'X_PROCESSES_OVER_POOL',
68
+ 'X_PROCESSES_UNBALANCED',
69
+ ]);
70
+
71
+ /** Every process seam the link touches, injected so a test drives it without a second process. */
72
+ export interface ChildLinkHost {
73
+ send(message: ChildMessage): void;
74
+ onMessage(listener: (message: unknown) => void): Release;
75
+ onDisconnect(listener: () => void): Release;
76
+ onSignal(signal: DrainSignal, listener: () => void): Release;
77
+ /** Delivers `signal` to this process, so a drain by message takes the signal's own path. */
78
+ raise(signal: DrainSignal): void;
79
+ ppid(): number;
80
+ every(ms: number, run: () => void): Release;
81
+ /** A timer that is NOT unref'd: the one that must still fire when everything else is stuck. */
82
+ after(ms: number, run: () => void): void;
83
+ drain(reason: string): Promise<void>;
84
+ exit(code: number): void;
85
+ budgetMs(): number;
86
+ }
87
+
88
+ const processHost: ChildLinkHost = {
89
+ send: (message) => {
90
+ try {
91
+ process.send?.(message);
92
+ } catch {
93
+ // The channel closed under us: the supervisor is gone, and `disconnect` says so.
94
+ }
95
+ },
96
+ onMessage: (listener) => {
97
+ process.on('message', listener);
98
+ return () => process.off('message', listener);
99
+ },
100
+ onDisconnect: (listener) => {
101
+ process.on('disconnect', listener);
102
+ return () => process.off('disconnect', listener);
103
+ },
104
+ onSignal: (signal, listener) => {
105
+ process.on(signal, listener);
106
+ return () => process.off(signal, listener);
107
+ },
108
+ raise: (signal) => process.kill(process.pid, signal),
109
+ ppid: () => process.ppid,
110
+ every: (ms, run) => {
111
+ const timer = setInterval(run, ms);
112
+ // Never what keeps a child alive: its hold is.
113
+ timer.unref();
114
+ return () => clearInterval(timer);
115
+ },
116
+ after: (ms, run) => {
117
+ setTimeout(run, ms);
118
+ },
119
+ drain,
120
+ exit: (code) => process.exit(code),
121
+ // What core's drain is bounded by: the readiness grace runs first, outside the deadline.
122
+ budgetMs: () => readinessGraceMs() + drainDeadlineMs(),
123
+ };
124
+
125
+ export interface ChildLink {
126
+ readonly index: number;
127
+ readonly count: number;
128
+ /** Booted, and the shared port bound: `metricsUrl` is this child's loopback scrape base. */
129
+ ready(metricsUrl: string): void;
130
+ /** Leaving with `code` — said before the exit, which the supervisor reads anyway. */
131
+ gone(code: number): void;
132
+ /** A refusal no restart can fix: the supervisor stops restarting and the container exits 1. */
133
+ fatal(code: string): void;
134
+ /**
135
+ * The boot threw: one `error` line through the logger, so it carries this child's index (Bun's
136
+ * own print of the uncaught throw names none, and the crash loop's fix points at this line);
137
+ * `fatal` too when it is a refusal only a redeploy changes (`FATAL_BOOT_CODES`).
138
+ */
139
+ refused(error: unknown): void;
140
+ release(): void;
141
+ }
142
+
143
+ /** `undefined` for a process no supervisor started (`ULTIMATE_CHILD` unset). */
144
+ export function linkToSupervisor(
145
+ env: Readonly<Record<string, string | undefined>>,
146
+ host: ChildLinkHost = processHost,
147
+ ): ChildLink | undefined {
148
+ const place = supervisedChild(env);
149
+ if (place === undefined) return undefined;
150
+ const originalPpid = host.ppid();
151
+ let acked = false;
152
+ let orphaned = false;
153
+ const ack = (): void => {
154
+ if (acked) return;
155
+ acked = true;
156
+ host.send({ type: PROCESS_MESSAGE_TYPE, event: 'draining', budgetMs: host.budgetMs() });
157
+ };
158
+ const orphan = (why: string): void => {
159
+ if (orphaned) return;
160
+ orphaned = true;
161
+ logger.warn('ultimate supervisor gone', {
162
+ cause: `${why}, so this child drains and exits rather than serve with nobody to restart or stop it`,
163
+ });
164
+ host.after(host.budgetMs() + ORPHAN_EXIT_SLACK_MS, () => host.exit(DRAIN_TIMEOUT_EXIT_CODE));
165
+ void host.drain('supervisor-gone');
166
+ };
167
+ const releases: Release[] = [
168
+ // Beside core's own handlers, never instead of them: the drain is theirs, the ack is this.
169
+ ...(['SIGTERM', 'SIGINT', 'SIGUSR2'] as const).map((signal) => host.onSignal(signal, ack)),
170
+ host.onMessage((message) => {
171
+ const asked = readDrainMessage(message);
172
+ if (asked !== undefined) host.raise(asked.signal);
173
+ }),
174
+ host.onDisconnect(() => orphan('the supervisor closed its IPC channel')),
175
+ host.every(PARENT_POLL_MS, () => {
176
+ if (host.ppid() !== originalPpid) orphan('this child was re-parented');
177
+ }),
178
+ ];
179
+ return {
180
+ index: place.index,
181
+ count: place.count,
182
+ ready: (metricsUrl) =>
183
+ host.send({
184
+ type: PROCESS_MESSAGE_TYPE,
185
+ event: 'ready',
186
+ metricsUrl,
187
+ budgetMs: host.budgetMs(),
188
+ }),
189
+ gone: (code) => host.send({ type: PROCESS_MESSAGE_TYPE, event: 'gone', code }),
190
+ fatal: (code) => host.send({ type: PROCESS_MESSAGE_TYPE, event: 'fatal', code }),
191
+ refused: (error) => {
192
+ logger.error(
193
+ 'ultimate child refused to boot',
194
+ isUltimateError(error)
195
+ ? { code: error.code, cause: error.cause, fix: error.fix }
196
+ : { cause: renderThrowable(error) },
197
+ );
198
+ if (isUltimateError(error) && FATAL_BOOT_CODES.has(error.code)) {
199
+ host.send({ type: PROCESS_MESSAGE_TYPE, event: 'fatal', code: error.code });
200
+ }
201
+ },
202
+ release: () => {
203
+ for (const release of releases.splice(0)) release();
204
+ },
205
+ };
206
+ }
@@ -0,0 +1,244 @@
1
+ // How many processes one production container runs: `ULTIMATE_PROCESSES` = auto | a count. auto is
2
+ // the minimum of every clamp below and names the one that bound it; an explicit count is honoured
3
+ // and checked. ONE decision for per-process state (`unsharedState`): auto clamps on it, an
4
+ // explicit count is refused on it, and a supervised child refuses what only its boot can see.
5
+
6
+ import type { Environment, Role } from '@ultimat3/core';
7
+ import { ROLE_INFO, renderFixShellArg } from '@ultimat3/core';
8
+ import type { CgroupFacts } from './supervise-cgroup';
9
+ import {
10
+ PROCESSES_ENV,
11
+ ProcessesInvalidError,
12
+ ProcessesOverPoolError,
13
+ ProcessesRoleSingletonError,
14
+ ProcessesUnbalancedError,
15
+ ProcessesUnsharedStateError,
16
+ } from './supervise-errors';
17
+
18
+ /** Measured private memory of a reference-app child at peak (227 MiB), rounded up. */
19
+ export const CHILD_MEMORY_BYTES = 256 * 1024 * 1024;
20
+ /** The supervisor's own share of the ceiling, kept out before children are counted. */
21
+ export const SUPERVISOR_MEMORY_BYTES = 32 * 1024 * 1024;
22
+
23
+ export type ProcessesRequest = 'auto' | number;
24
+
25
+ /** `auto` (also unset or blank) or a positive whole number; anything else refuses. */
26
+ export function readProcessesRequest(
27
+ env: Readonly<Record<string, string | undefined>>,
28
+ ): ProcessesRequest {
29
+ const raw = env[PROCESSES_ENV]?.trim() ?? '';
30
+ if (raw === '' || raw === 'auto') return 'auto';
31
+ if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(Number(raw))) {
32
+ throw new ProcessesInvalidError(raw);
33
+ }
34
+ return Number(raw);
35
+ }
36
+
37
+ /** A store the boot was handed, by the name an operator finds it under in `runtime.ts`. */
38
+ export interface StoreScope {
39
+ readonly name: string;
40
+ readonly scope: string | undefined;
41
+ }
42
+
43
+ export interface SharedStateFacts {
44
+ readonly role: Role;
45
+ /** `cache.tiers` names `lru`. */
46
+ readonly lruTier: boolean;
47
+ /** `NATS_URL` is set, or `runtime.ts` supplied a transport that is not the in-process bus. */
48
+ readonly crossingBus: boolean;
49
+ /** `REDIS_URL` / `VALKEY_URL`: the cache's invalidations ride Redis pub/sub. */
50
+ readonly redis: boolean;
51
+ /** No `DATABASE_URL`: PGlite in a directory one process owns. */
52
+ readonly embeddedDatabase: boolean;
53
+ readonly stores: readonly StoreScope[];
54
+ }
55
+
56
+ /**
57
+ * The stores among `stores` whose scope is not `'shared'`. Its own export because one store is only
58
+ * seen by a child, after the app's modules ran (`runtime-idempotency-scope.ts`): same rule, later.
59
+ */
60
+ export const unsharedStores = (stores: readonly StoreScope[]): readonly string[] =>
61
+ stores
62
+ .filter((store) => store.scope !== 'shared')
63
+ .map(
64
+ (store) =>
65
+ `${store.name} keeps its records per process (scope ${store.scope ?? 'undeclared'})`,
66
+ );
67
+
68
+ /** Every piece of state N children would each keep to themselves, as a cause names it. */
69
+ export function unsharedState(facts: SharedStateFacts): readonly string[] {
70
+ return [
71
+ ...(facts.lruTier && !facts.crossingBus && !facts.redis
72
+ ? [
73
+ 'the lru cache tier, whose invalidations ride the in-process bus (no NATS_URL, REDIS_URL or VALKEY_URL)',
74
+ ]
75
+ : []),
76
+ ...unsharedStores(facts.stores),
77
+ ...(facts.embeddedDatabase
78
+ ? ['the embedded database (no DATABASE_URL), one directory per process']
79
+ : []),
80
+ ...(facts.role === 'sync' && !facts.crossingBus
81
+ ? ['the sync role with no NATS_URL: channel fan-out and presence stay inside one process']
82
+ : []),
83
+ ];
84
+ }
85
+
86
+ /** What the resolver reads. Every source is injected, so each branch is a unit test. */
87
+ export interface CountSources {
88
+ readonly env: Readonly<Record<string, string | undefined>>;
89
+ readonly role: Role;
90
+ readonly platform: string;
91
+ readonly environment: Environment | undefined;
92
+ readonly cgroup: () => Promise<CgroupFacts>;
93
+ /** `navigator.hardwareConcurrency`: the cores this process may run on, the cap under a quota. */
94
+ readonly parallelism: () => number;
95
+ /** The container's pool: `DATABASE_POOL_MAX`, else the role's profile. */
96
+ readonly pool: () => number;
97
+ readonly shared: () => Promise<SharedStateFacts>;
98
+ /** The image carries `x build --target prebuilt`'s store; a boot without it compiles. */
99
+ readonly prebuilt: () => Promise<boolean>;
100
+ }
101
+
102
+ export type ClampName =
103
+ | 'environment'
104
+ | 'platform'
105
+ | 'role'
106
+ | 'cpu'
107
+ | 'memory'
108
+ | 'pool'
109
+ | 'shared-state'
110
+ | 'image'
111
+ | 'requested';
112
+
113
+ export interface ProcessCount {
114
+ readonly count: number;
115
+ readonly requested: ProcessesRequest;
116
+ /** The clamp that set the count: what the boot line names. */
117
+ readonly binding: ClampName;
118
+ /** Each clamp's value, in the order auto takes their minimum. */
119
+ readonly clamps: Readonly<Partial<Record<ClampName, number>>>;
120
+ /** A line the boot owes beside the count: an ignored request, a count above the memory fit. */
121
+ readonly note?: {
122
+ readonly level: 'info' | 'warn';
123
+ readonly msg: string;
124
+ readonly cause: string;
125
+ readonly fix?: string;
126
+ };
127
+ }
128
+
129
+ const memoryFit = (bytes: number | undefined): number | undefined =>
130
+ bytes === undefined
131
+ ? undefined
132
+ : Math.max(1, Math.floor((bytes - SUPERVISOR_MEMORY_BYTES) / CHILD_MEMORY_BYTES));
133
+
134
+ const singleton = (role: Role): boolean => ROLE_INFO[role].maxReplicas === 1;
135
+
136
+ const PRODUCTION_LIKE: ReadonlySet<Environment | undefined> = new Set(['production', 'staging']);
137
+
138
+ /** The minimum of the clamps that are bounded; the first one at that minimum is the binding. */
139
+ function lowest(clamps: Partial<Record<ClampName, number>>): {
140
+ count: number;
141
+ binding: ClampName;
142
+ } {
143
+ let best: { count: number; binding: ClampName } = {
144
+ count: Number.POSITIVE_INFINITY,
145
+ binding: 'cpu',
146
+ };
147
+ for (const [name, value] of Object.entries(clamps) as [ClampName, number][]) {
148
+ if (value < best.count) best = { count: value, binding: name };
149
+ }
150
+ return best;
151
+ }
152
+
153
+ async function resolveAuto(sources: CountSources): Promise<ProcessCount> {
154
+ if (sources.platform !== 'linux') return one('platform', { platform: 1 });
155
+ if (singleton(sources.role)) return one('role', { role: 1 });
156
+ const cgroup = await sources.cgroup();
157
+ // No quota declared reads as one process: a quota-less pod must never read the node's cores.
158
+ if (cgroup.cpus === undefined) return one('cpu', { cpu: 1 });
159
+ const fit = memoryFit(cgroup.memoryBytes);
160
+ // Insertion order IS the tie-break: the first clamp at the minimum is the one the line names.
161
+ const clamps: Partial<Record<ClampName, number>> = {
162
+ cpu: Math.min(cgroup.cpus, Math.max(1, sources.parallelism())),
163
+ ...(fit === undefined ? {} : { memory: fit }),
164
+ pool: sources.pool(),
165
+ ...(unsharedState(await sources.shared()).length === 0 ? {} : { 'shared-state': 1 }),
166
+ ...((await sources.prebuilt()) ? {} : { image: 1 }),
167
+ };
168
+ return { ...lowest(clamps), requested: 'auto', clamps };
169
+ }
170
+
171
+ const one = (binding: ClampName, clamps: Partial<Record<ClampName, number>>): ProcessCount => ({
172
+ count: 1,
173
+ requested: 'auto',
174
+ binding,
175
+ clamps,
176
+ });
177
+
178
+ async function checkExplicit(sources: CountSources, requested: number): Promise<ProcessCount> {
179
+ if (requested === 1) return { count: 1, requested, binding: 'requested', clamps: {} };
180
+ if (singleton(sources.role))
181
+ throw new ProcessesRoleSingletonError({ role: sources.role, requested });
182
+ if (sources.platform !== 'linux') {
183
+ throw new ProcessesUnbalancedError({ requested, platform: sources.platform });
184
+ }
185
+ const reasons = unsharedState(await sources.shared());
186
+ if (reasons.length > 0) throw new ProcessesUnsharedStateError({ requested, reasons });
187
+ const pool = sources.pool();
188
+ if (requested > pool) throw new ProcessesOverPoolError({ requested, pool });
189
+ const fit = memoryFit((await sources.cgroup()).memoryBytes);
190
+ const result: ProcessCount = {
191
+ count: requested,
192
+ requested,
193
+ binding: 'requested',
194
+ clamps: { pool, ...(fit === undefined ? {} : { memory: fit }) },
195
+ };
196
+ if (fit === undefined || requested <= fit) return result;
197
+ return {
198
+ ...result,
199
+ note: {
200
+ level: 'warn',
201
+ msg: 'ultimate processes above the memory fit',
202
+ cause: `${PROCESSES_ENV}=${String(requested)} children at about 256 MiB each fit ${String(fit)} into this container's memory ceiling, so an OOM kill takes a child under load`,
203
+ fix: `export ULTIMATE_PROCESSES=${renderFixShellArg(String(fit), '<count>')} # in this service's deploy environment, or raise the service's memory limit (mem_limit, resources.limits.memory)`,
204
+ },
205
+ };
206
+ }
207
+
208
+ /**
209
+ * The count, or a coded refusal. Only a production-like container supervises: `x dev`, the test
210
+ * runner and any other environment run one process, and a valid count asked for there is ignored
211
+ * with one info line rather than refused — a `.env` shared with production must not stop a laptop.
212
+ * A value that is no count at all (`two`, `0`) is refused everywhere: production would refuse it.
213
+ */
214
+ export async function resolveProcessCount(sources: CountSources): Promise<ProcessCount> {
215
+ const requested = readProcessesRequest(sources.env);
216
+ if (!PRODUCTION_LIKE.has(sources.environment)) {
217
+ return {
218
+ count: 1,
219
+ requested,
220
+ binding: 'environment',
221
+ clamps: { environment: 1 },
222
+ ...ignoredRequest(requested, sources.environment ?? 'unnamed'),
223
+ };
224
+ }
225
+ return requested === 'auto' ? resolveAuto(sources) : checkExplicit(sources, requested);
226
+ }
227
+
228
+ /**
229
+ * The one line a process that always runs as one owes a count asked of it: the test runner and any
230
+ * non-production environment here, `x dev` (`dev-boot.ts`) everywhere. Nothing for auto or `1`.
231
+ */
232
+ export function ignoredRequest(
233
+ requested: ProcessesRequest,
234
+ where: string,
235
+ ): { readonly note?: NonNullable<ProcessCount['note']> } {
236
+ if (requested === 'auto' || requested === 1) return {};
237
+ return {
238
+ note: {
239
+ level: 'info',
240
+ msg: 'ultimate processes ignored',
241
+ cause: `${PROCESSES_ENV}=${String(requested)} applies to production containers only; this ${where} process runs as one`,
242
+ },
243
+ };
244
+ }
@@ -0,0 +1,83 @@
1
+ // The refusals a production container's process count can meet: the count itself, the role, the
2
+ // state the children would not share, the pool they split, the platform, and a child that keeps
3
+ // crashing. Beside their throwers (`supervise-count.ts`, `supervise.ts`), one class per condition.
4
+
5
+ import type { Role } from '@ultimat3/core';
6
+ import { renderCauseValue, renderFixShellArg, UltimateError } from '@ultimat3/core';
7
+
8
+ /**
9
+ * The variable every cause below names. Each fix spells it out: `export ${…}` would put a value in
10
+ * a pasted command's position (`fix-shell-arg`); `supervise-errors.test.ts` holds the two equal.
11
+ */
12
+ export const PROCESSES_ENV = 'ULTIMATE_PROCESSES';
13
+
14
+ export class ProcessesInvalidError extends UltimateError {
15
+ constructor(raw: string) {
16
+ super({
17
+ code: 'X_PROCESSES_INVALID',
18
+ cause: `${PROCESSES_ENV}=${renderCauseValue(raw)} is neither auto nor a positive whole number, so the container cannot tell how many processes to start`,
19
+ fix: `export ULTIMATE_PROCESSES=auto # in this service's deploy environment, or a positive whole number such as 2`,
20
+ });
21
+ }
22
+ }
23
+
24
+ export class ProcessesRoleSingletonError extends UltimateError {
25
+ constructor(input: { readonly role: Role; readonly requested: number }) {
26
+ super({
27
+ code: 'X_PROCESSES_ROLE_SINGLETON',
28
+ cause: `${PROCESSES_ENV}=${String(input.requested)} on ROLE=${input.role}, which holds a leader lease, a replication slot or runs once — a second process is idle at best`,
29
+ fix: `export ULTIMATE_PROCESSES=1 # in the environment of the ${input.role} service`,
30
+ meta: { role: input.role, requested: input.requested },
31
+ });
32
+ }
33
+ }
34
+
35
+ export class ProcessesUnsharedStateError extends UltimateError {
36
+ constructor(input: { readonly requested: number; readonly reasons: readonly string[] }) {
37
+ super({
38
+ code: 'X_PROCESSES_UNSHARED_STATE',
39
+ cause: `${PROCESSES_ENV}=${String(input.requested)} over state each child would keep to itself: ${input.reasons.join('; ')}`,
40
+ fix: `export ULTIMATE_PROCESSES=1 # in this service's deploy environment, or share the state: NATS_URL=nats://<host>:4222 (REDIS_URL or VALKEY_URL for the cache), DATABASE_URL for an embedded database, and drop the per-process store from apps/<app>/runtime.ts`,
41
+ meta: { requested: input.requested, reasons: [...input.reasons] },
42
+ });
43
+ }
44
+ }
45
+
46
+ export class ProcessesOverPoolError extends UltimateError {
47
+ constructor(input: { readonly requested: number; readonly pool: number }) {
48
+ super({
49
+ code: 'X_PROCESSES_OVER_POOL',
50
+ cause: `${PROCESSES_ENV}=${String(input.requested)} is more than the container's ${String(input.pool)} database connections (DATABASE_POOL_MAX, else the role's profile): the pool is split across the children, never multiplied, so a child would get none`,
51
+ fix: `export DATABASE_POOL_MAX=${renderFixShellArg(String(input.requested), '<processes>')} # or ${PROCESSES_ENV}=${String(input.pool)}`,
52
+ meta: { requested: input.requested, pool: input.pool },
53
+ });
54
+ }
55
+ }
56
+
57
+ export class ProcessesUnbalancedError extends UltimateError {
58
+ constructor(input: { readonly requested: number; readonly platform: string }) {
59
+ super({
60
+ code: 'X_PROCESSES_UNBALANCED',
61
+ cause: `${PROCESSES_ENV}=${String(input.requested)} on ${renderCauseValue(input.platform)}, where Bun ignores reusePort (SO_REUSEPORT is Linux only), so the children cannot share one port`,
62
+ fix: `export ULTIMATE_PROCESSES=1 # in this service's deploy environment, or run the image in a Linux container`,
63
+ meta: { requested: input.requested, platform: input.platform },
64
+ });
65
+ }
66
+ }
67
+
68
+ export class ProcessCrashLoopError extends UltimateError {
69
+ constructor(input: {
70
+ readonly index: number;
71
+ readonly code: number | null;
72
+ readonly crashes: number;
73
+ readonly windowMs: number;
74
+ }) {
75
+ const exit = input.code === null ? 'was killed' : `exited ${String(input.code)}`;
76
+ super({
77
+ code: 'X_PROCESS_CRASH_LOOP',
78
+ cause: `child ${String(input.index)} ${exit}, its ${String(input.crashes)}th unexpected exit within ${String(Math.round(input.windowMs / 60_000))} minutes, so the supervisor drained its siblings and the container exits 1 for the platform to restart`,
79
+ fix: `docker compose logs --tail 200 <service> # the last error line with "child":${String(input.index)} names the boot error to fix`,
80
+ meta: { child: input.index, exitCode: input.code, crashes: input.crashes },
81
+ });
82
+ }
83
+ }
@@ -0,0 +1,40 @@
1
+ // What the supervisor can see of per-process state before any child boots: the environment,
2
+ // `apps/<app>/runtime.ts`'s stores and transport, and `app.config.ts`'s cache tiers. Loaded only
3
+ // when the CPU budget already allows more than one process (`supervise-boot.ts`).
4
+
5
+ import type { Role } from '@ultimat3/core';
6
+ import { redisUrlSource } from '@ultimat3/core/redis';
7
+ import { InProcessTransport } from '@ultimat3/realtime/server';
8
+ import { loadAppConfig } from './app-config-load';
9
+ import { cacheTiersOf } from './runtime-cache';
10
+ import type { ServeOptions } from './serve-types';
11
+ import type { SharedStateFacts, StoreScope } from './supervise-count';
12
+
13
+ const set = (value: string | undefined): boolean => value !== undefined && value.trim() !== '';
14
+
15
+ /** What the supervisor can see before any child boots: env, `runtime.ts`, `app.config.ts`. */
16
+ export async function sharedStateFacts(
17
+ options: ServeOptions,
18
+ role: Role,
19
+ ): Promise<SharedStateFacts> {
20
+ const runtime = options.runtime;
21
+ const transport = runtime?.transport;
22
+ const stores: StoreScope[] = [
23
+ ...(runtime?.rateLimitStore === undefined
24
+ ? []
25
+ : [{ name: 'runtime.rateLimitStore', scope: runtime.rateLimitStore.scope }]),
26
+ ...(runtime?.idempotencyStore === undefined
27
+ ? []
28
+ : [{ name: 'runtime.idempotencyStore', scope: runtime.idempotencyStore.scope }]),
29
+ ];
30
+ return {
31
+ role,
32
+ lruTier: cacheTiersOf(await loadAppConfig(options.root)).includes('lru'),
33
+ crossingBus:
34
+ set(options.env['NATS_URL']) ||
35
+ (transport !== undefined && !(transport instanceof InProcessTransport)),
36
+ redis: redisUrlSource(options.env) !== undefined,
37
+ embeddedDatabase: !set(options.env['DATABASE_URL']),
38
+ stores,
39
+ };
40
+ }
@@ -0,0 +1,84 @@
1
+ // The control messages between the production supervisor and its children, over `ipc` with
2
+ // `serialization: 'json'`. Every value is a string, a number or a boolean: JSON turns a `Date` into
3
+ // a string and a `Map` into `{}` silently, and a `BigInt` throws on send (measured on Bun 1.4.4).
4
+
5
+ /** Every message carries it, so a stray `process.send` from an app module is never read as one. */
6
+ export const PROCESS_MESSAGE_TYPE = 'x-proc';
7
+
8
+ export type DrainSignal = 'SIGTERM' | 'SIGINT' | 'SIGUSR2';
9
+
10
+ /** Child → supervisor. */
11
+ export type ChildMessage =
12
+ /** Booted and bound: `metricsUrl` is its loopback scrape base; `budgetMs` its drain bound. */
13
+ | {
14
+ readonly type: typeof PROCESS_MESSAGE_TYPE;
15
+ readonly event: 'ready';
16
+ readonly metricsUrl: string;
17
+ readonly budgetMs: number;
18
+ }
19
+ /** Its drain began; the supervisor's per-child budget starts HERE, not at its own send. */
20
+ | {
21
+ readonly type: typeof PROCESS_MESSAGE_TYPE;
22
+ readonly event: 'draining';
23
+ readonly budgetMs: number;
24
+ }
25
+ /** Leaving with `code`: the supervisor reads the exit, this is said first. */
26
+ | { readonly type: typeof PROCESS_MESSAGE_TYPE; readonly event: 'gone'; readonly code: number }
27
+ /** A refusal no restart can fix (`X_PROCESSES_UNSHARED_STATE`): stop restarting, exit 1. */
28
+ | { readonly type: typeof PROCESS_MESSAGE_TYPE; readonly event: 'fatal'; readonly code: string };
29
+
30
+ /** Supervisor → child: drain as if `signal` had arrived. */
31
+ export interface DrainMessage {
32
+ readonly type: typeof PROCESS_MESSAGE_TYPE;
33
+ readonly event: 'drain';
34
+ readonly signal: DrainSignal;
35
+ }
36
+
37
+ const SIGNALS: ReadonlySet<unknown> = new Set(['SIGTERM', 'SIGINT', 'SIGUSR2']);
38
+
39
+ const fieldsOf = (message: unknown): Record<string, unknown> | undefined =>
40
+ typeof message === 'object' &&
41
+ message !== null &&
42
+ (message as Record<string, unknown>)['type'] === PROCESS_MESSAGE_TYPE
43
+ ? (message as Record<string, unknown>)
44
+ : undefined;
45
+
46
+ const count = (value: unknown): value is number =>
47
+ typeof value === 'number' && Number.isFinite(value) && value >= 0;
48
+
49
+ /** A child's message, screened: anything else is `undefined` and ignored. */
50
+ export function readChildMessage(message: unknown): ChildMessage | undefined {
51
+ const fields = fieldsOf(message);
52
+ if (fields === undefined) return undefined;
53
+ const { event } = fields;
54
+ if (event === 'ready' && typeof fields['metricsUrl'] === 'string' && count(fields['budgetMs'])) {
55
+ return {
56
+ type: PROCESS_MESSAGE_TYPE,
57
+ event,
58
+ metricsUrl: fields['metricsUrl'],
59
+ budgetMs: fields['budgetMs'],
60
+ };
61
+ }
62
+ if (event === 'draining' && count(fields['budgetMs'])) {
63
+ return { type: PROCESS_MESSAGE_TYPE, event, budgetMs: fields['budgetMs'] };
64
+ }
65
+ if (event === 'gone' && typeof fields['code'] === 'number') {
66
+ return { type: PROCESS_MESSAGE_TYPE, event, code: fields['code'] };
67
+ }
68
+ if (event === 'fatal' && typeof fields['code'] === 'string') {
69
+ return { type: PROCESS_MESSAGE_TYPE, event, code: fields['code'] };
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ export function readDrainMessage(message: unknown): DrainMessage | undefined {
75
+ const fields = fieldsOf(message);
76
+ if (fields?.['event'] !== 'drain' || !SIGNALS.has(fields['signal'])) return undefined;
77
+ return { type: PROCESS_MESSAGE_TYPE, event: 'drain', signal: fields['signal'] as DrainSignal };
78
+ }
79
+
80
+ export const drainMessage = (signal: DrainSignal): DrainMessage => ({
81
+ type: PROCESS_MESSAGE_TYPE,
82
+ event: 'drain',
83
+ signal,
84
+ });