@powerhousedao/switchboard 6.2.3-dev.74 → 6.2.3-dev.75
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/.tsbuild/test/pglite-store.test.d.ts +2 -0
- package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +31 -0
- package/dist/boot.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/plugins/attachments.mjs +3 -3
- package/dist/{reactor-feature-flags-BVu9wggF.mjs → reactor-feature-flags-BtWVQDt6.mjs} +4 -4
- package/dist/{reactor-feature-flags-BVu9wggF.mjs.map → reactor-feature-flags-BtWVQDt6.mjs.map} +1 -1
- package/dist/{server-nRWFjnu3.mjs → server-CJjK7WpR.mjs} +202 -35
- package/dist/server-CJjK7WpR.mjs.map +1 -0
- package/dist/server.d.mts +10 -2
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +3 -3
- package/package.json +16 -16
- package/test/pglite-dialect.test.ts +39 -19
- package/test/pglite-store.test.ts +311 -0
- package/dist/server-nRWFjnu3.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
+
## 6.2.3-dev.75 (2026-10-24)
|
|
2
|
+
|
|
3
|
+
### 🚀 Features
|
|
4
|
+
|
|
5
|
+
- **ph-cli,ph-cmd,shared:** ph host check behind FEATURE_UNIFORM_RUNNERS_ENABLED ([3a41a17991](https://github.com/powerhouse-inc/powerhouse/commit/3a41a17991))
|
|
6
|
+
- **switchboard,reactor-api:** honor PH_NO_DOTENV at import-time dotenv sites ([9d451ce0d0](https://github.com/powerhouse-inc/powerhouse/commit/9d451ce0d0))
|
|
7
|
+
- **codegen:** ph migrate moves connect's theme overrides from style.css to the host stylesheet ([b113414352](https://github.com/powerhouse-inc/powerhouse/commit/b113414352))
|
|
8
|
+
- **switchboard:** pace catch-up by PH_CATCH_UP_PRIORITY and request load ([278d0ec3cd](https://github.com/powerhouse-inc/powerhouse/commit/278d0ec3cd))
|
|
9
|
+
- **switchboard:** run PGlite stores in worker threads by default ([ee8a84ff4d](https://github.com/powerhouse-inc/powerhouse/commit/ee8a84ff4d))
|
|
10
|
+
- **reactor-api,switchboard:** a deferred VACUUM FULL runs once overdue, and both timings are configurable ([0d083c8745](https://github.com/powerhouse-inc/powerhouse/commit/0d083c8745))
|
|
11
|
+
- **switchboard:** open reactor-storage in a PGlite worker thread behind PH_PGLITE_WORKERS ([06a1916860](https://github.com/powerhouse-inc/powerhouse/commit/06a1916860))
|
|
12
|
+
- **switchboard:** open read-storage in a PGlite worker thread behind PH_PGLITE_WORKERS ([0e0917a3d8](https://github.com/powerhouse-inc/powerhouse/commit/0e0917a3d8))
|
|
13
|
+
- **reactor-api,switchboard:** accept a PGlite stand-in wherever the stores take a PGlite ([f1c7754d57](https://github.com/powerhouse-inc/powerhouse/commit/f1c7754d57))
|
|
14
|
+
- **ph-cli,switchboard:** a catch-up progress display, and the inspector on the switchboard handle ([96ca0d3c29](https://github.com/powerhouse-inc/powerhouse/commit/96ca0d3c29))
|
|
15
|
+
|
|
16
|
+
### 🩹 Fixes
|
|
17
|
+
|
|
18
|
+
- **switchboard,ph-cli:** checkBoot shares the server's boot inputs; ./boot leaves process.env alone ([c613c635bc](https://github.com/powerhouse-inc/powerhouse/commit/c613c635bc))
|
|
19
|
+
- **switchboard:** renown key storage stays out of cwd under an explicit keypair path ([d3d5d527c6](https://github.com/powerhouse-inc/powerhouse/commit/d3d5d527c6))
|
|
20
|
+
- **switchboard:** renown user storage follows PH_USER_DATA_DIR ([18b7914617](https://github.com/powerhouse-inc/powerhouse/commit/18b7914617))
|
|
21
|
+
- **builder-tools:** the worker-safe vendor check parses imports, so import-like text in strings and comments no longer counts ([9d3e167f4b](https://github.com/powerhouse-inc/powerhouse/commit/9d3e167f4b))
|
|
22
|
+
- **reactor-browser,connect,reactor-monitor:** the worker reactor loads a registry package's module graph, and packages added or updated after boot ([5348ffa792](https://github.com/powerhouse-inc/powerhouse/commit/5348ffa792))
|
|
23
|
+
- **powerhouse-vetra-packages:** the document-model editor writes nothing on open unless the model is blank ([f5dc33dd0a](https://github.com/powerhouse-inc/powerhouse/commit/f5dc33dd0a))
|
|
24
|
+
|
|
25
|
+
### ❤️ Thank You
|
|
26
|
+
|
|
27
|
+
- acaldas
|
|
28
|
+
- Benjamin Jordan
|
|
29
|
+
- Claude Opus 5.5
|
|
30
|
+
- Wouter Kampmann
|
|
31
|
+
|
|
1
32
|
## 6.2.3-dev.74 (2026-10-24)
|
|
2
33
|
|
|
3
34
|
### 🚀 Features
|
package/dist/boot.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
2
|
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d46863b7-efdb-5eab-b6d7-a864cf6c4cad")}catch(e){}}();
|
|
3
|
-
import { c as resolveProjectionWorkerOptions, d as reactorDbUrlOf, f as switchboardBootIssues, m as workerTrustPolicyIssue, o as resolveWorkerPoolOptions, p as workerPoolIssues, t as resolveReactorFeatureFlags, u as projectionWorkerIssues } from "./reactor-feature-flags-
|
|
3
|
+
import { c as resolveProjectionWorkerOptions, d as reactorDbUrlOf, f as switchboardBootIssues, m as workerTrustPolicyIssue, o as resolveWorkerPoolOptions, p as workerPoolIssues, t as resolveReactorFeatureFlags, u as projectionWorkerIssues } from "./reactor-feature-flags-BtWVQDt6.mjs";
|
|
4
4
|
//#region src/boot.mts
|
|
5
5
|
const noop = () => {};
|
|
6
6
|
const silent = {
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="970d13d2-8fb1-53c8-819e-786cc25376f0")}catch(e){}}();
|
|
4
|
-
import { a as startSwitchboard, d as initProfilerFromEnv, f as parseForcePgVersion, o as StoredDocumentsRefusedError } from "./server-
|
|
4
|
+
import { a as startSwitchboard, d as initProfilerFromEnv, f as parseForcePgVersion, o as StoredDocumentsRefusedError } from "./server-CJjK7WpR.mjs";
|
|
5
5
|
import { metrics } from "@opentelemetry/api";
|
|
6
6
|
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
7
7
|
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as attachmentsPlugin, l as attachmentsPluginConfigSchema } from "../server-
|
|
1
|
+
import { c as attachmentsPlugin, l as attachmentsPluginConfigSchema } from "../server-CJjK7WpR.mjs";
|
|
2
2
|
export { attachmentsPlugin, attachmentsPlugin as default, attachmentsPluginConfigSchema };
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
4
|
-
//# debugId=
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c8c8de12-12b0-59fd-b8ff-cfaccbcef3e8")}catch(e){}}();
|
|
4
|
+
//# debugId=c8c8de12-12b0-59fd-b8ff-cfaccbcef3e8
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a4b06ccf-4ddd-58ea-8612-b04c83e1ab46")}catch(e){}}();
|
|
3
3
|
import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
|
|
4
4
|
import { existsSync, realpathSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
7
|
import { readFile } from "node:fs/promises";
|
|
7
8
|
import os from "node:os";
|
|
8
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
9
|
//#region src/boot-preconditions.mts
|
|
10
10
|
/** The reactor database the server boots with: its `dbPath` option, then the env. */
|
|
11
11
|
function reactorDbUrlOf(dbPath, env) {
|
|
@@ -320,5 +320,5 @@ function resolveReactorFeatureFlags(env) {
|
|
|
320
320
|
//#endregion
|
|
321
321
|
export { resolveWorkerModelSources as a, resolveProjectionWorkerOptions as c, reactorDbUrlOf as d, switchboardBootIssues as f, resolveHostPoolSize as i, parseNonNegativeInt as l, workerTrustPolicyIssue as m, buildWorkerDbConfig as n, resolveWorkerPoolOptions as o, workerPoolIssues as p, keepImportableSources as r, assertProjectionWorkerSupported as s, resolveReactorFeatureFlags as t, projectionWorkerIssues as u };
|
|
322
322
|
|
|
323
|
-
//# sourceMappingURL=reactor-feature-flags-
|
|
324
|
-
//# debugId=
|
|
323
|
+
//# sourceMappingURL=reactor-feature-flags-BtWVQDt6.mjs.map
|
|
324
|
+
//# debugId=a4b06ccf-4ddd-58ea-8612-b04c83e1ab46
|
package/dist/{reactor-feature-flags-BVu9wggF.mjs.map → reactor-feature-flags-BtWVQDt6.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactor-feature-flags-BVu9wggF.mjs","sources":["../src/boot-preconditions.mts","../src/env.mts","../src/projection-worker.mts","../src/worker-pool.mts","../src/reactor-feature-flags.mts"],"sourcesContent":["import { isPostgresUrl } from \"./postgres-url.mjs\";\n\n/** What the server refuses to boot with; it throws the first, `ph host check` reports all. */\nexport interface SwitchboardBootFacts {\n dev: boolean;\n /** Executor pool size; 0 when the pool is off. */\n workers: number;\n projectionWorker: boolean;\n reactorDbUrl: string | undefined;\n authEnforcement: boolean;\n renownSource: \"self\" | \"remote\";\n}\n\n/** The reactor database the server boots with: its `dbPath` option, then the env. */\nexport function reactorDbUrlOf(\n dbPath: string | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n return (\n dbPath ?? env.PH_REACTOR_DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL\n );\n}\n\nexport function workerTrustPolicyIssue(\n facts: Pick<\n SwitchboardBootFacts,\n \"workers\" | \"authEnforcement\" | \"renownSource\"\n >,\n): string | undefined {\n if (\n facts.workers > 0 &&\n facts.authEnforcement &&\n facts.renownSource === \"self\"\n ) {\n return (\n \"The executor worker pool (REACTOR_WORKERS) cannot verify signers when \" +\n \"REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from \" +\n 'this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): ' +\n \"pooled workers have no trust policy and would refuse every signed \" +\n \"write. Set RENOWN_SOURCE=remote, or disable the worker pool \" +\n \"(REACTOR_WORKERS=0).\"\n );\n }\n return undefined;\n}\n\n/** In the order the server checks them; empty when the pool is off. */\nexport function workerPoolIssues(facts: SwitchboardBootFacts): string[] {\n if (facts.workers <= 0) return [];\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\n \"The executor worker pool (REACTOR_WORKERS) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n const trust = workerTrustPolicyIssue(facts);\n if (trust) issues.push(trust);\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\n \"The executor worker pool (REACTOR_WORKERS) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n return issues;\n}\n\n/** The projection worker's preconditions, assuming it is enabled. */\nexport function projectionWorkerIssues(\n facts: Pick<SwitchboardBootFacts, \"dev\" | \"reactorDbUrl\">,\n): string[] {\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\n \"The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\n \"The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n return issues;\n}\n\nexport function switchboardBootIssues(facts: SwitchboardBootFacts): string[] {\n return [\n ...workerPoolIssues(facts),\n ...(facts.projectionWorker ? projectionWorkerIssues(facts) : []),\n ];\n}\n","export function parseNonNegativeInt(\n raw: string | undefined,\n name: string,\n): number | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(`${name} must be a non-negative integer, got \"${raw}\"`);\n }\n return value;\n}\n","import { projectionWorkerIssues } from \"./boot-preconditions.mjs\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nexport type SwitchboardProjectionWorkerOptions = {\n dbPoolSize: number;\n};\n\nexport type SwitchboardProjectionWorkerInput = {\n enabled?: boolean;\n dbPoolSize?: number;\n};\n\n// Run 11 of the bench sweep saw chain.depth ~6.5 at one shard, so 8 covers the\n// working set; behind a 25-slot transaction pooler a larger pool is not spendable.\nconst DEFAULT_DB_POOL_SIZE_PROJECTION = 8;\n\nconst ON_TOKENS = [\"1\", \"true\", \"on\", \"yes\"];\nconst OFF_TOKENS = [\"0\", \"false\", \"off\", \"no\"];\n\n/**\n * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or\n * `input.enabled`, which wins when defined; null when off (the default).\n */\nexport function resolveProjectionWorkerOptions(\n input: SwitchboardProjectionWorkerInput | undefined,\n env: NodeJS.ProcessEnv,\n): SwitchboardProjectionWorkerOptions | null {\n const enabled =\n input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false;\n if (!enabled) {\n return null;\n }\n const dbPoolSize =\n input?.dbPoolSize ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_PROJECTION,\n \"REACTOR_DB_POOL_SIZE_PROJECTION\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PROJECTION;\n if (dbPoolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool\",\n );\n }\n return { dbPoolSize };\n}\n\n/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */\nexport function assertProjectionWorkerSupported(args: {\n dev: boolean;\n reactorDbUrl: string | undefined;\n}): void {\n const issue = projectionWorkerIssues(args).at(0);\n if (issue) throw new Error(issue);\n}\n\nfunction parseOnOff(raw: string | undefined): boolean | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const token = raw.trim().toLowerCase();\n if (ON_TOKENS.includes(token)) {\n return true;\n }\n if (OFF_TOKENS.includes(token)) {\n return false;\n }\n throw new Error(\n `REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got \"${raw}\"`,\n );\n}\n","import type { DbConfig, FileModelSource } from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nexport type WorkerCountInput = number | \"auto\";\n\nexport type SwitchboardWorkerPoolOptions = {\n numWorkers: number;\n /** Whether numWorkers was given explicitly or sized from the core count. */\n mode: \"explicit\" | \"auto\";\n dbPoolSizePerWorker: number;\n acquireTimeoutMs: number;\n};\n\nexport type SwitchboardWorkerPoolInput = {\n numWorkers?: WorkerCountInput;\n dbPoolSizePerWorker?: number;\n acquireTimeoutMs?: number;\n};\n\nconst DEFAULT_DB_POOL_SIZE_PER_WORKER = 2;\nconst DEFAULT_ACQUIRE_TIMEOUT_MS = 5000;\n\n// Host reactor pool. pg-pool's own default is 10, below the bench harness's\n// floor of 16 (bench/host/src/main.ts, REACTOR_DB_POOL_SIZE_HOST). Run 8 of\n// the sweep found throughput flat from 16 to 96 but per-op index p50\n// collapsing 262ms -> 43ms, so this buys latency, not throughput — and only\n// up to whatever the connection budget in front of Postgres allows.\nconst DEFAULT_DB_POOL_SIZE_HOST = 16;\n\n// Auto-sizing: reserve cores for the host event loop (queue, read models,\n// HTTP) and cap at the top of the bench sweep envelope, which also bounds\n// the worker Postgres-connection budget.\nconst AUTO_RESERVED_CORES = 2;\nconst AUTO_WORKER_CAP = 8;\n\n/** Worker count for \"auto\": always at least 1 — auto sizes the pool, it does not turn worker mode off. */\nexport function autoWorkerCount(availableCores: number): number {\n return Math.max(\n 1,\n Math.min(AUTO_WORKER_CAP, availableCores - AUTO_RESERVED_CORES),\n );\n}\n\n/**\n * Effective worker-pool config from programmatic options (which win) and the\n * REACTOR_* env vars; null when disabled (numWorkers 0, the default).\n * `\"auto\"` sizes the pool from the machine's available cores.\n */\nexport function resolveWorkerPoolOptions(\n input: SwitchboardWorkerPoolInput | undefined,\n env: NodeJS.ProcessEnv,\n availableCores: number = os.availableParallelism(),\n): SwitchboardWorkerPoolOptions | null {\n const requested =\n input?.numWorkers ?? parseWorkerCount(env.REACTOR_WORKERS) ?? 0;\n const mode = requested === \"auto\" ? \"auto\" : \"explicit\";\n const numWorkers =\n requested === \"auto\" ? autoWorkerCount(availableCores) : requested;\n if (!Number.isInteger(numWorkers) || numWorkers < 0) {\n throw new Error(\n `workerPool.numWorkers must be \"auto\" or a non-negative integer, got ${numWorkers}`,\n );\n }\n if (numWorkers === 0) {\n return null;\n }\n return {\n numWorkers,\n mode,\n dbPoolSizePerWorker:\n input?.dbPoolSizePerWorker ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_WORKER,\n \"REACTOR_DB_POOL_SIZE_WORKER\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PER_WORKER,\n acquireTimeoutMs:\n input?.acquireTimeoutMs ??\n parseNonNegativeInt(\n env.REACTOR_DB_ACQUIRE_TIMEOUT_MS,\n \"REACTOR_DB_ACQUIRE_TIMEOUT_MS\",\n ) ??\n DEFAULT_ACQUIRE_TIMEOUT_MS,\n };\n}\n\n/**\n * Size of the reactor's own (host) Postgres pool. Unlike the worker pool there\n * is no \"disabled\" state — the host pool is the only Postgres pool in the\n * server path, backing both reactor storage and the read models that reach it\n * via `withSchema` — so 0 is rejected rather than read as \"off\".\n *\n * The acquire timeout is deliberately not configurable here: the host pool\n * waits indefinitely today, and making it finite converts saturation from a\n * latency problem into a thrown error on the read-model path. That is a\n * behavior change worth making separately, once the retry semantics of a\n * rejected `pool.connect()` inside the read-model coordinator are settled.\n */\nexport function resolveHostPoolSize(env: NodeJS.ProcessEnv): number {\n const poolSize =\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_HOST,\n \"REACTOR_DB_POOL_SIZE_HOST\",\n ) ?? DEFAULT_DB_POOL_SIZE_HOST;\n if (poolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_HOST must be at least 1; the host pool cannot be disabled\",\n );\n }\n return poolSize;\n}\n\n/**\n * DbConfig for each worker's own pool, parsed from a postgres:// URL.\n * Explicit host, database, and user are required — no pg-side defaults.\n */\nexport function buildWorkerDbConfig(\n postgresUrl: string,\n options: Pick<\n SwitchboardWorkerPoolOptions,\n \"dbPoolSizePerWorker\" | \"acquireTimeoutMs\"\n >,\n): DbConfig {\n let parsed: URL;\n try {\n parsed = new URL(postgresUrl);\n } catch {\n throw new Error(\n `Worker pool requires a valid postgres:// URL for the reactor database, got \"${postgresUrl}\"`,\n );\n }\n const database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n if (!parsed.hostname || !database) {\n throw new Error(\n `Worker pool requires a postgres URL with a host and database name, got \"${postgresUrl}\"`,\n );\n }\n if (!parsed.username) {\n throw new Error(\n `Worker pool requires explicit credentials in the postgres URL (workers open their own connections), got \"${postgresUrl}\"`,\n );\n }\n const sslmode = parsed.searchParams.get(\"sslmode\");\n const ssl =\n parsed.searchParams.get(\"ssl\") === \"true\" ||\n (sslmode !== null && sslmode !== \"disable\");\n return {\n host: parsed.hostname,\n port: parsed.port ? Number(parsed.port) : 5432,\n database,\n user: decodeURIComponent(parsed.username),\n password: decodeURIComponent(parsed.password),\n ssl,\n applicationName: \"switchboard-worker\",\n poolSize: options.dbPoolSizePerWorker,\n connectionTimeoutMillis: options.acquireTimeoutMs,\n };\n}\n\n/** Specifiers of the base models switchboard always registers. */\nconst BASE_MODEL_SPECIFIERS = [\n \"document-model\",\n \"@powerhousedao/shared/document-drive\",\n \"@powerhousedao/reactor-drive\",\n \"@powerhousedao/reactor-group/document-models\",\n];\n\n// As the reactor builder tells a module from the rest of a source's exports.\nfunction isModelModule(value: unknown): boolean {\n const candidate = value as {\n reducer?: unknown;\n documentModel?: { global?: { id?: unknown } };\n } | null;\n return (\n typeof candidate?.reducer === \"function\" &&\n typeof candidate.documentModel?.global?.id === \"string\"\n );\n}\n\n// Drops sources that fail to import or export no model. For workflow pieces\n// only: a missing model means \"unavailable to pieces\", not a failed boot.\nexport async function keepImportableSources(\n sources: FileModelSource[],\n logger: ILogger,\n): Promise<FileModelSource[]> {\n const kept: FileModelSource[] = [];\n for (const source of sources) {\n try {\n const exports = (await import(\n pathToFileURL(source.filePath).href\n )) as Record<string, unknown>;\n if (Object.values(exports).some(isModelModule)) kept.push(source);\n } catch (error) {\n logger.warn(\n `Worker model sources: \"${source.filePath}\" does not import, so workflow pieces will not see its models: ${String(error)}`,\n );\n }\n }\n return kept;\n}\n\n/**\n * Resolves base models and configured package identifiers to `{ filePath }`\n * sources for the reactor builder. Resolution to absolute paths happens here\n * because workers (and the builder) resolve bare specifiers from the reactor\n * package's own dependency context, which cannot see switchboard or project\n * packages. Unresolvable identifiers are skipped with a warning; the builder\n * fails the boot if a registered model ends up without an importable source.\n */\nexport async function resolveWorkerModelSources(\n packages: string[],\n logger: ILogger,\n options: {\n /** Cached file for a package not installed locally, e.g. from a registry. */\n resolveRemote?: (identifier: string) => Promise<string | null>;\n } = {},\n): Promise<FileModelSource[]> {\n const sources: FileModelSource[] = [];\n for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {\n const filePath =\n (await resolveModelModuleFile(identifier)) ??\n (await resolveRemoteSafely(identifier, options.resolveRemote, logger));\n if (!filePath) {\n logger.warn(\n `Worker model sources: no importable document-models entry for \"${identifier}\", skipping`,\n );\n continue;\n }\n sources.push({ filePath });\n }\n return sources;\n}\n\nasync function resolveRemoteSafely(\n identifier: string,\n resolveRemote: ((identifier: string) => Promise<string | null>) | undefined,\n logger: ILogger,\n): Promise<string | null> {\n if (!resolveRemote) return null;\n try {\n return await resolveRemote(identifier);\n } catch (error) {\n logger.warn(\n `Worker model sources: could not cache \"${identifier}\" from the registry: ${String(error)}`,\n );\n return null;\n }\n}\n\n/**\n * Absolute file path of a source's models barrel. Mirrors reactor-api's\n * import-resolver: import.meta.resolve, then the project's node_modules via\n * the package.json exports map / dist layout.\n */\nasync function resolveModelModuleFile(source: string): Promise<string | null> {\n if (isFsPath(source)) {\n return resolveFromPackageDir(source, \"./document-models\");\n }\n\n const specifier = BASE_MODEL_SPECIFIERS.includes(source)\n ? source\n : `${source}/document-models`;\n\n try {\n const resolved = import.meta.resolve(specifier);\n if (resolved.startsWith(\"file:\")) {\n return fileURLToPath(resolved);\n }\n } catch {\n // fall through to node_modules resolution from the project dir\n }\n\n const { packageName, subpath } = splitSpecifier(specifier);\n const packageDir = path.join(process.cwd(), \"node_modules\", packageName);\n if (!existsSync(packageDir)) {\n return null;\n }\n let realDir: string;\n try {\n realDir = realpathSync(packageDir);\n } catch {\n return null;\n }\n return resolveFromPackageDir(realDir, subpath);\n}\n\nfunction splitSpecifier(specifier: string): {\n packageName: string;\n subpath: string;\n} {\n const parts = specifier.split(\"/\");\n const packageSegments = specifier.startsWith(\"@\") ? 2 : 1;\n const packageName = parts.slice(0, packageSegments).join(\"/\");\n const rest = parts.slice(packageSegments).join(\"/\");\n return { packageName, subpath: rest ? `./${rest}` : \".\" };\n}\n\n/** Exports-map lookup (import condition), then conventional dist paths. */\nasync function resolveFromPackageDir(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n const fromManifest = await resolveViaManifest(packageDir, subpath);\n if (fromManifest) {\n return fromManifest;\n }\n const candidates =\n subpath === \".\"\n ? [path.join(packageDir, \"dist\", \"index.js\")]\n : [\n path.join(packageDir, \"dist\", subpath.slice(2), \"index.js\"),\n path.join(packageDir, \"dist\", `${subpath.slice(2)}.js`),\n path.join(packageDir, subpath.slice(2), \"index.js\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\nasync function resolveViaManifest(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n let raw: string;\n try {\n raw = await readFile(path.join(packageDir, \"package.json\"), \"utf8\");\n } catch {\n return null;\n }\n let manifest: { exports?: unknown; main?: unknown };\n try {\n manifest = JSON.parse(raw) as { exports?: unknown; main?: unknown };\n } catch {\n return null;\n }\n\n let entry: unknown;\n const exportsField = manifest.exports;\n if (\n exportsField !== null &&\n typeof exportsField === \"object\" &&\n !Array.isArray(exportsField)\n ) {\n const map = exportsField as Record<string, unknown>;\n const hasSubpathKeys = Object.keys(map).some((key) => key.startsWith(\".\"));\n entry = hasSubpathKeys ? map[subpath] : subpath === \".\" ? map : undefined;\n } else if (typeof exportsField === \"string\" && subpath === \".\") {\n entry = exportsField;\n }\n\n let target = pickImportTarget(entry);\n if (!target && subpath === \".\" && typeof manifest.main === \"string\") {\n target = manifest.main;\n }\n if (!target) {\n return null;\n }\n const resolved = path.join(packageDir, target);\n return existsSync(resolved) ? resolved : null;\n}\n\nfunction pickImportTarget(entry: unknown): string | null {\n if (typeof entry === \"string\") {\n return entry;\n }\n if (typeof entry !== \"object\" || entry === null) {\n return null;\n }\n const conditions = entry as Record<string, unknown>;\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const value = conditions[condition];\n if (typeof value === \"string\") {\n return value;\n }\n }\n return null;\n}\n\nfunction isFsPath(identifier: string): boolean {\n return (\n path.isAbsolute(identifier) ||\n identifier.startsWith(\"./\") ||\n identifier.startsWith(\"../\")\n );\n}\n\nfunction parseWorkerCount(\n raw: string | undefined,\n): WorkerCountInput | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n if (raw.trim().toLowerCase() === \"auto\") {\n return \"auto\";\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(\n `REACTOR_WORKERS must be \"auto\" or a non-negative integer, got \"${raw}\"`,\n );\n }\n return value;\n}\n","import type { ReactorFeatureFlags } from \"@powerhousedao/reactor\";\n\nexport type ResolvedReactorFeatureFlags = {\n flags: Partial<ReactorFeatureFlags>;\n /** Names of the flags set to true, in prerequisite order. */\n enabled: string[];\n};\n\n/**\n * Enforcement flags from the REACTOR_* env vars. Each flag requires the ones\n * before it; the reactor rejects an inconsistent set rather than enforcing less\n * than the operator asked for, so this reports what was asked without\n * correcting it.\n */\nexport function resolveReactorFeatureFlags(\n env: NodeJS.ProcessEnv,\n): ResolvedReactorFeatureFlags {\n const flags: Partial<ReactorFeatureFlags> = {\n documentDecisions: env.REACTOR_DOCUMENT_DECISIONS === \"true\",\n authEnforcement: env.REACTOR_AUTH_ENFORCEMENT === \"true\",\n authGroups: env.REACTOR_AUTH_GROUPS === \"true\",\n authConditions: env.REACTOR_AUTH_CONDITIONS === \"true\",\n };\n\n const enabled = Object.entries(flags)\n .filter(([, isEnabled]) => isEnabled)\n .map(([name]) => name);\n\n return { flags, enabled };\n}\n"],"names":[],"mappings":";;;;;;;;;;AAcA,SAAgB,eACd,QACA,KACoB;CACpB,OACE,UAAU,IAAI,2BAA2B,IAAI;AAEjD;AAEA,SAAgB,uBACd,OAIoB;CACpB,IACE,MAAM,UAAU,KAChB,MAAM,mBACN,MAAM,iBAAiB,QAEvB,OACE;AASN;;AAGA,SAAgB,iBAAiB,OAAuC;CACtE,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC;CAChC,MAAM,SAAmB,CAAC;CAC1B,IAAI,MAAM,KACR,OAAO,KACL,4IACF;CAEF,MAAM,QAAQ,uBAAuB,KAAK;CAC1C,IAAI,OAAO,OAAO,KAAK,KAAK;CAC5B,IAAI,CAAC,MAAM,gBAAgB,CAAC,cAAc,MAAM,YAAY,GAC1D,OAAO,KACL,8LACF;CAEF,OAAO;AACT;;AAGA,SAAgB,uBACd,OACU;CACV,MAAM,SAAmB,CAAC;CAC1B,IAAI,MAAM,KACR,OAAO,KACL,mJACF;CAEF,IAAI,CAAC,MAAM,gBAAgB,CAAC,cAAc,MAAM,YAAY,GAC1D,OAAO,KACL,qMACF;CAEF,OAAO;AACT;AAEA,SAAgB,sBAAsB,OAAuC;CAC3E,OAAO,CACL,GAAG,iBAAiB,KAAK,GACzB,GAAI,MAAM,mBAAmB,uBAAuB,KAAK,IAAI,CAAC,CAChE;AACF;;;ACxFA,SAAgB,oBACd,KACA,MACoB;CACpB,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IACtC;CAEF,MAAM,QAAQ,OAAO,SAAS,KAAK,EAAE;CACrC,IAA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QAAQ,KAAK,OAAO,KAAK,MAAM,IAAI,KAAK,GACtE,MAAM,IAAI,MACR,kEAAkE,IAAI,EACxE;CAEF,OAAO;AACT;;;;;;;;;AC7YA,SAAgB,2BACd,KAC6B;CAC7B,MAAM,QAAsC;EAC1C,mBAAmB,IAAI,+BAA+B;EACtD,iBAAiB,IAAI,6BAA6B;EAClD,YAAY,IAAI,wBAAwB;EACxC,gBAAgB,IAAI,4BAA4B;CAClD;CAMA,OAAO;EAAE;EAAO,SAJA,OAAO,QAAQ,KAAK,CAAC,CAClC,QAAQ,GAAG,eAAe,SAAS,CAAC,CACpC,KAAK,CAAC,UAAU,IAEG;CAAE;AAC1B","debug_id":"1057b63d-f987-5f18-b6fd-3ca194a2c099"}
|
|
1
|
+
{"version":3,"file":"reactor-feature-flags-BtWVQDt6.mjs","sources":["../src/boot-preconditions.mts","../src/env.mts","../src/projection-worker.mts","../src/worker-pool.mts","../src/reactor-feature-flags.mts"],"sourcesContent":["import { isPostgresUrl } from \"./postgres-url.mjs\";\n\n/** What the server refuses to boot with; it throws the first, `ph host check` reports all. */\nexport interface SwitchboardBootFacts {\n dev: boolean;\n /** Executor pool size; 0 when the pool is off. */\n workers: number;\n projectionWorker: boolean;\n reactorDbUrl: string | undefined;\n authEnforcement: boolean;\n renownSource: \"self\" | \"remote\";\n}\n\n/** The reactor database the server boots with: its `dbPath` option, then the env. */\nexport function reactorDbUrlOf(\n dbPath: string | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n return (\n dbPath ?? env.PH_REACTOR_DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL\n );\n}\n\nexport function workerTrustPolicyIssue(\n facts: Pick<\n SwitchboardBootFacts,\n \"workers\" | \"authEnforcement\" | \"renownSource\"\n >,\n): string | undefined {\n if (\n facts.workers > 0 &&\n facts.authEnforcement &&\n facts.renownSource === \"self\"\n ) {\n return (\n \"The executor worker pool (REACTOR_WORKERS) cannot verify signers when \" +\n \"REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from \" +\n 'this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): ' +\n \"pooled workers have no trust policy and would refuse every signed \" +\n \"write. Set RENOWN_SOURCE=remote, or disable the worker pool \" +\n \"(REACTOR_WORKERS=0).\"\n );\n }\n return undefined;\n}\n\n/** In the order the server checks them; empty when the pool is off. */\nexport function workerPoolIssues(facts: SwitchboardBootFacts): string[] {\n if (facts.workers <= 0) return [];\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\n \"The executor worker pool (REACTOR_WORKERS) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n const trust = workerTrustPolicyIssue(facts);\n if (trust) issues.push(trust);\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\n \"The executor worker pool (REACTOR_WORKERS) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n return issues;\n}\n\n/** The projection worker's preconditions, assuming it is enabled. */\nexport function projectionWorkerIssues(\n facts: Pick<SwitchboardBootFacts, \"dev\" | \"reactorDbUrl\">,\n): string[] {\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\n \"The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\n \"The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n return issues;\n}\n\nexport function switchboardBootIssues(facts: SwitchboardBootFacts): string[] {\n return [\n ...workerPoolIssues(facts),\n ...(facts.projectionWorker ? projectionWorkerIssues(facts) : []),\n ];\n}\n","export function parseNonNegativeInt(\n raw: string | undefined,\n name: string,\n): number | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(`${name} must be a non-negative integer, got \"${raw}\"`);\n }\n return value;\n}\n","import { projectionWorkerIssues } from \"./boot-preconditions.mjs\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nexport type SwitchboardProjectionWorkerOptions = {\n dbPoolSize: number;\n};\n\nexport type SwitchboardProjectionWorkerInput = {\n enabled?: boolean;\n dbPoolSize?: number;\n};\n\n// Run 11 of the bench sweep saw chain.depth ~6.5 at one shard, so 8 covers the\n// working set; behind a 25-slot transaction pooler a larger pool is not spendable.\nconst DEFAULT_DB_POOL_SIZE_PROJECTION = 8;\n\nconst ON_TOKENS = [\"1\", \"true\", \"on\", \"yes\"];\nconst OFF_TOKENS = [\"0\", \"false\", \"off\", \"no\"];\n\n/**\n * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or\n * `input.enabled`, which wins when defined; null when off (the default).\n */\nexport function resolveProjectionWorkerOptions(\n input: SwitchboardProjectionWorkerInput | undefined,\n env: NodeJS.ProcessEnv,\n): SwitchboardProjectionWorkerOptions | null {\n const enabled =\n input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false;\n if (!enabled) {\n return null;\n }\n const dbPoolSize =\n input?.dbPoolSize ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_PROJECTION,\n \"REACTOR_DB_POOL_SIZE_PROJECTION\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PROJECTION;\n if (dbPoolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool\",\n );\n }\n return { dbPoolSize };\n}\n\n/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */\nexport function assertProjectionWorkerSupported(args: {\n dev: boolean;\n reactorDbUrl: string | undefined;\n}): void {\n const issue = projectionWorkerIssues(args).at(0);\n if (issue) throw new Error(issue);\n}\n\nfunction parseOnOff(raw: string | undefined): boolean | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const token = raw.trim().toLowerCase();\n if (ON_TOKENS.includes(token)) {\n return true;\n }\n if (OFF_TOKENS.includes(token)) {\n return false;\n }\n throw new Error(\n `REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got \"${raw}\"`,\n );\n}\n","import type { DbConfig, FileModelSource } from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nexport type WorkerCountInput = number | \"auto\";\n\nexport type SwitchboardWorkerPoolOptions = {\n numWorkers: number;\n /** Whether numWorkers was given explicitly or sized from the core count. */\n mode: \"explicit\" | \"auto\";\n dbPoolSizePerWorker: number;\n acquireTimeoutMs: number;\n};\n\nexport type SwitchboardWorkerPoolInput = {\n numWorkers?: WorkerCountInput;\n dbPoolSizePerWorker?: number;\n acquireTimeoutMs?: number;\n};\n\nconst DEFAULT_DB_POOL_SIZE_PER_WORKER = 2;\nconst DEFAULT_ACQUIRE_TIMEOUT_MS = 5000;\n\n// Host reactor pool. pg-pool's own default is 10, below the bench harness's\n// floor of 16 (bench/host/src/main.ts, REACTOR_DB_POOL_SIZE_HOST). Run 8 of\n// the sweep found throughput flat from 16 to 96 but per-op index p50\n// collapsing 262ms -> 43ms, so this buys latency, not throughput — and only\n// up to whatever the connection budget in front of Postgres allows.\nconst DEFAULT_DB_POOL_SIZE_HOST = 16;\n\n// Auto-sizing: reserve cores for the host event loop (queue, read models,\n// HTTP) and cap at the top of the bench sweep envelope, which also bounds\n// the worker Postgres-connection budget.\nconst AUTO_RESERVED_CORES = 2;\nconst AUTO_WORKER_CAP = 8;\n\n/** Worker count for \"auto\": always at least 1 — auto sizes the pool, it does not turn worker mode off. */\nexport function autoWorkerCount(availableCores: number): number {\n return Math.max(\n 1,\n Math.min(AUTO_WORKER_CAP, availableCores - AUTO_RESERVED_CORES),\n );\n}\n\n/**\n * Effective worker-pool config from programmatic options (which win) and the\n * REACTOR_* env vars; null when disabled (numWorkers 0, the default).\n * `\"auto\"` sizes the pool from the machine's available cores.\n */\nexport function resolveWorkerPoolOptions(\n input: SwitchboardWorkerPoolInput | undefined,\n env: NodeJS.ProcessEnv,\n availableCores: number = os.availableParallelism(),\n): SwitchboardWorkerPoolOptions | null {\n const requested =\n input?.numWorkers ?? parseWorkerCount(env.REACTOR_WORKERS) ?? 0;\n const mode = requested === \"auto\" ? \"auto\" : \"explicit\";\n const numWorkers =\n requested === \"auto\" ? autoWorkerCount(availableCores) : requested;\n if (!Number.isInteger(numWorkers) || numWorkers < 0) {\n throw new Error(\n `workerPool.numWorkers must be \"auto\" or a non-negative integer, got ${numWorkers}`,\n );\n }\n if (numWorkers === 0) {\n return null;\n }\n return {\n numWorkers,\n mode,\n dbPoolSizePerWorker:\n input?.dbPoolSizePerWorker ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_WORKER,\n \"REACTOR_DB_POOL_SIZE_WORKER\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PER_WORKER,\n acquireTimeoutMs:\n input?.acquireTimeoutMs ??\n parseNonNegativeInt(\n env.REACTOR_DB_ACQUIRE_TIMEOUT_MS,\n \"REACTOR_DB_ACQUIRE_TIMEOUT_MS\",\n ) ??\n DEFAULT_ACQUIRE_TIMEOUT_MS,\n };\n}\n\n/**\n * Size of the reactor's own (host) Postgres pool. Unlike the worker pool there\n * is no \"disabled\" state — the host pool is the only Postgres pool in the\n * server path, backing both reactor storage and the read models that reach it\n * via `withSchema` — so 0 is rejected rather than read as \"off\".\n *\n * The acquire timeout is deliberately not configurable here: the host pool\n * waits indefinitely today, and making it finite converts saturation from a\n * latency problem into a thrown error on the read-model path. That is a\n * behavior change worth making separately, once the retry semantics of a\n * rejected `pool.connect()` inside the read-model coordinator are settled.\n */\nexport function resolveHostPoolSize(env: NodeJS.ProcessEnv): number {\n const poolSize =\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_HOST,\n \"REACTOR_DB_POOL_SIZE_HOST\",\n ) ?? DEFAULT_DB_POOL_SIZE_HOST;\n if (poolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_HOST must be at least 1; the host pool cannot be disabled\",\n );\n }\n return poolSize;\n}\n\n/**\n * DbConfig for each worker's own pool, parsed from a postgres:// URL.\n * Explicit host, database, and user are required — no pg-side defaults.\n */\nexport function buildWorkerDbConfig(\n postgresUrl: string,\n options: Pick<\n SwitchboardWorkerPoolOptions,\n \"dbPoolSizePerWorker\" | \"acquireTimeoutMs\"\n >,\n): DbConfig {\n let parsed: URL;\n try {\n parsed = new URL(postgresUrl);\n } catch {\n throw new Error(\n `Worker pool requires a valid postgres:// URL for the reactor database, got \"${postgresUrl}\"`,\n );\n }\n const database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n if (!parsed.hostname || !database) {\n throw new Error(\n `Worker pool requires a postgres URL with a host and database name, got \"${postgresUrl}\"`,\n );\n }\n if (!parsed.username) {\n throw new Error(\n `Worker pool requires explicit credentials in the postgres URL (workers open their own connections), got \"${postgresUrl}\"`,\n );\n }\n const sslmode = parsed.searchParams.get(\"sslmode\");\n const ssl =\n parsed.searchParams.get(\"ssl\") === \"true\" ||\n (sslmode !== null && sslmode !== \"disable\");\n return {\n host: parsed.hostname,\n port: parsed.port ? Number(parsed.port) : 5432,\n database,\n user: decodeURIComponent(parsed.username),\n password: decodeURIComponent(parsed.password),\n ssl,\n applicationName: \"switchboard-worker\",\n poolSize: options.dbPoolSizePerWorker,\n connectionTimeoutMillis: options.acquireTimeoutMs,\n };\n}\n\n/** Specifiers of the base models switchboard always registers. */\nconst BASE_MODEL_SPECIFIERS = [\n \"document-model\",\n \"@powerhousedao/shared/document-drive\",\n \"@powerhousedao/reactor-drive\",\n \"@powerhousedao/reactor-group/document-models\",\n];\n\n// As the reactor builder tells a module from the rest of a source's exports.\nfunction isModelModule(value: unknown): boolean {\n const candidate = value as {\n reducer?: unknown;\n documentModel?: { global?: { id?: unknown } };\n } | null;\n return (\n typeof candidate?.reducer === \"function\" &&\n typeof candidate.documentModel?.global?.id === \"string\"\n );\n}\n\n// Drops sources that fail to import or export no model. For workflow pieces\n// only: a missing model means \"unavailable to pieces\", not a failed boot.\nexport async function keepImportableSources(\n sources: FileModelSource[],\n logger: ILogger,\n): Promise<FileModelSource[]> {\n const kept: FileModelSource[] = [];\n for (const source of sources) {\n try {\n const exports = (await import(\n pathToFileURL(source.filePath).href\n )) as Record<string, unknown>;\n if (Object.values(exports).some(isModelModule)) kept.push(source);\n } catch (error) {\n logger.warn(\n `Worker model sources: \"${source.filePath}\" does not import, so workflow pieces will not see its models: ${String(error)}`,\n );\n }\n }\n return kept;\n}\n\n/**\n * Resolves base models and configured package identifiers to `{ filePath }`\n * sources for the reactor builder. Resolution to absolute paths happens here\n * because workers (and the builder) resolve bare specifiers from the reactor\n * package's own dependency context, which cannot see switchboard or project\n * packages. Unresolvable identifiers are skipped with a warning; the builder\n * fails the boot if a registered model ends up without an importable source.\n */\nexport async function resolveWorkerModelSources(\n packages: string[],\n logger: ILogger,\n options: {\n /** Cached file for a package not installed locally, e.g. from a registry. */\n resolveRemote?: (identifier: string) => Promise<string | null>;\n } = {},\n): Promise<FileModelSource[]> {\n const sources: FileModelSource[] = [];\n for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {\n const filePath =\n (await resolveModelModuleFile(identifier)) ??\n (await resolveRemoteSafely(identifier, options.resolveRemote, logger));\n if (!filePath) {\n logger.warn(\n `Worker model sources: no importable document-models entry for \"${identifier}\", skipping`,\n );\n continue;\n }\n sources.push({ filePath });\n }\n return sources;\n}\n\nasync function resolveRemoteSafely(\n identifier: string,\n resolveRemote: ((identifier: string) => Promise<string | null>) | undefined,\n logger: ILogger,\n): Promise<string | null> {\n if (!resolveRemote) return null;\n try {\n return await resolveRemote(identifier);\n } catch (error) {\n logger.warn(\n `Worker model sources: could not cache \"${identifier}\" from the registry: ${String(error)}`,\n );\n return null;\n }\n}\n\n/**\n * Absolute file path of a source's models barrel. Mirrors reactor-api's\n * import-resolver: import.meta.resolve, then the project's node_modules via\n * the package.json exports map / dist layout.\n */\nasync function resolveModelModuleFile(source: string): Promise<string | null> {\n if (isFsPath(source)) {\n return resolveFromPackageDir(source, \"./document-models\");\n }\n\n const specifier = BASE_MODEL_SPECIFIERS.includes(source)\n ? source\n : `${source}/document-models`;\n\n try {\n const resolved = import.meta.resolve(specifier);\n if (resolved.startsWith(\"file:\")) {\n return fileURLToPath(resolved);\n }\n } catch {\n // fall through to node_modules resolution from the project dir\n }\n\n const { packageName, subpath } = splitSpecifier(specifier);\n const packageDir = path.join(process.cwd(), \"node_modules\", packageName);\n if (!existsSync(packageDir)) {\n return null;\n }\n let realDir: string;\n try {\n realDir = realpathSync(packageDir);\n } catch {\n return null;\n }\n return resolveFromPackageDir(realDir, subpath);\n}\n\nfunction splitSpecifier(specifier: string): {\n packageName: string;\n subpath: string;\n} {\n const parts = specifier.split(\"/\");\n const packageSegments = specifier.startsWith(\"@\") ? 2 : 1;\n const packageName = parts.slice(0, packageSegments).join(\"/\");\n const rest = parts.slice(packageSegments).join(\"/\");\n return { packageName, subpath: rest ? `./${rest}` : \".\" };\n}\n\n/** Exports-map lookup (import condition), then conventional dist paths. */\nasync function resolveFromPackageDir(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n const fromManifest = await resolveViaManifest(packageDir, subpath);\n if (fromManifest) {\n return fromManifest;\n }\n const candidates =\n subpath === \".\"\n ? [path.join(packageDir, \"dist\", \"index.js\")]\n : [\n path.join(packageDir, \"dist\", subpath.slice(2), \"index.js\"),\n path.join(packageDir, \"dist\", `${subpath.slice(2)}.js`),\n path.join(packageDir, subpath.slice(2), \"index.js\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\nasync function resolveViaManifest(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n let raw: string;\n try {\n raw = await readFile(path.join(packageDir, \"package.json\"), \"utf8\");\n } catch {\n return null;\n }\n let manifest: { exports?: unknown; main?: unknown };\n try {\n manifest = JSON.parse(raw) as { exports?: unknown; main?: unknown };\n } catch {\n return null;\n }\n\n let entry: unknown;\n const exportsField = manifest.exports;\n if (\n exportsField !== null &&\n typeof exportsField === \"object\" &&\n !Array.isArray(exportsField)\n ) {\n const map = exportsField as Record<string, unknown>;\n const hasSubpathKeys = Object.keys(map).some((key) => key.startsWith(\".\"));\n entry = hasSubpathKeys ? map[subpath] : subpath === \".\" ? map : undefined;\n } else if (typeof exportsField === \"string\" && subpath === \".\") {\n entry = exportsField;\n }\n\n let target = pickImportTarget(entry);\n if (!target && subpath === \".\" && typeof manifest.main === \"string\") {\n target = manifest.main;\n }\n if (!target) {\n return null;\n }\n const resolved = path.join(packageDir, target);\n return existsSync(resolved) ? resolved : null;\n}\n\nfunction pickImportTarget(entry: unknown): string | null {\n if (typeof entry === \"string\") {\n return entry;\n }\n if (typeof entry !== \"object\" || entry === null) {\n return null;\n }\n const conditions = entry as Record<string, unknown>;\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const value = conditions[condition];\n if (typeof value === \"string\") {\n return value;\n }\n }\n return null;\n}\n\nfunction isFsPath(identifier: string): boolean {\n return (\n path.isAbsolute(identifier) ||\n identifier.startsWith(\"./\") ||\n identifier.startsWith(\"../\")\n );\n}\n\nfunction parseWorkerCount(\n raw: string | undefined,\n): WorkerCountInput | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n if (raw.trim().toLowerCase() === \"auto\") {\n return \"auto\";\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(\n `REACTOR_WORKERS must be \"auto\" or a non-negative integer, got \"${raw}\"`,\n );\n }\n return value;\n}\n","import type { ReactorFeatureFlags } from \"@powerhousedao/reactor\";\n\nexport type ResolvedReactorFeatureFlags = {\n flags: Partial<ReactorFeatureFlags>;\n /** Names of the flags set to true, in prerequisite order. */\n enabled: string[];\n};\n\n/**\n * Enforcement flags from the REACTOR_* env vars. Each flag requires the ones\n * before it; the reactor rejects an inconsistent set rather than enforcing less\n * than the operator asked for, so this reports what was asked without\n * correcting it.\n */\nexport function resolveReactorFeatureFlags(\n env: NodeJS.ProcessEnv,\n): ResolvedReactorFeatureFlags {\n const flags: Partial<ReactorFeatureFlags> = {\n documentDecisions: env.REACTOR_DOCUMENT_DECISIONS === \"true\",\n authEnforcement: env.REACTOR_AUTH_ENFORCEMENT === \"true\",\n authGroups: env.REACTOR_AUTH_GROUPS === \"true\",\n authConditions: env.REACTOR_AUTH_CONDITIONS === \"true\",\n };\n\n const enabled = Object.entries(flags)\n .filter(([, isEnabled]) => isEnabled)\n .map(([name]) => name);\n\n return { flags, enabled };\n}\n"],"names":[],"mappings":";;;;;;;;;;AAcA,SAAgB,eACd,QACA,KACoB;CACpB,OACE,UAAU,IAAI,2BAA2B,IAAI;AAEjD;AAEA,SAAgB,uBACd,OAIoB;CACpB,IACE,MAAM,UAAU,KAChB,MAAM,mBACN,MAAM,iBAAiB,QAEvB,OACE;AASN;;AAGA,SAAgB,iBAAiB,OAAuC;CACtE,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC;CAChC,MAAM,SAAmB,CAAC;CAC1B,IAAI,MAAM,KACR,OAAO,KACL,4IACF;CAEF,MAAM,QAAQ,uBAAuB,KAAK;CAC1C,IAAI,OAAO,OAAO,KAAK,KAAK;CAC5B,IAAI,CAAC,MAAM,gBAAgB,CAAC,cAAc,MAAM,YAAY,GAC1D,OAAO,KACL,8LACF;CAEF,OAAO;AACT;;AAGA,SAAgB,uBACd,OACU;CACV,MAAM,SAAmB,CAAC;CAC1B,IAAI,MA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zB,IAAI,OAAO,UAAU,UACnB,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,SAAS,YAA6B;CAC7C,OACE,KAAK,WAAW,UAAU,KAC1B,WAAW,WAAW,IAAI,KAC1B,WAAW,WAAW,KAAK;AAE/B;AAEA,SAAS,iBACP,KAC8B;CAC9B,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IACtC;CAEF,IAAI,IAAI,KAAK,CAAC,CAAC,YAAY,MAAM,QAC/B,OAAO;CAET,MAAM,QAAQ,OAAO,SAAS,KAAK,EAAE;CACrC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,OAAO,KAAK,MAAM,IAAI,KAAK,GACtE,MAAM,IAAI,MACR,kEAAkE,IAAI,EACxE;CAEF,OAAO;AACT;;;;;;;;;AC7YA,SAAgB,2BACd,KAC6B;CAC7B,MAAM,QAAsC;EAC1C,mBAAmB,IAAI,+BAA+B;EACtD,iBAAiB,IAAI,6BAA6B;EAClD,YAAY,IAAI,wBAAwB;EACxC,gBAAgB,IAAI,4BAA4B;CAClD;CAMA,OAAO;EAAE;EAAO,SAJA,OAAO,QAAQ,KAAK,CAAC,CAClC,QAAQ,GAAG,eAAe,SAAS,CAAC,CACpC,KAAK,CAAC,UAAU,IAEG;CAAE;AAC1B","debug_id":"a4b06ccf-4ddd-58ea-8612-b04c83e1ab46"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="23ac9e84-b25f-5218-b443-313ef3078eee")}catch(e){}}();
|
|
3
3
|
import { _ as triggerFatalShutdown, a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as installFatalErrorShutdown, h as workflowSingletonLossHandler, l as assertWorkflowPackageLoadable, m as retryWorkflowSingleton, p as resolveWorkflowsEnabled, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-fsBcElEi.mjs";
|
|
4
4
|
import { i as startPrivacy, r as resolvePrivacy, t as privacyPlugin } from "./privacy-BsFl7GzK.mjs";
|
|
5
5
|
import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
|
|
6
6
|
import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
|
|
7
|
-
import { a as resolveWorkerModelSources, c as resolveProjectionWorkerOptions, d as reactorDbUrlOf, i as resolveHostPoolSize, l as parseNonNegativeInt, n as buildWorkerDbConfig, o as resolveWorkerPoolOptions, p as workerPoolIssues, r as keepImportableSources, s as assertProjectionWorkerSupported, t as resolveReactorFeatureFlags } from "./reactor-feature-flags-
|
|
7
|
+
import { a as resolveWorkerModelSources, c as resolveProjectionWorkerOptions, d as reactorDbUrlOf, i as resolveHostPoolSize, l as parseNonNegativeInt, n as buildWorkerDbConfig, o as resolveWorkerPoolOptions, p as workerPoolIssues, r as keepImportableSources, s as assertProjectionWorkerSupported, t as resolveReactorFeatureFlags } from "./reactor-feature-flags-BtWVQDt6.mjs";
|
|
8
8
|
import { n as addDefaultReactorDrive, t as addDefaultDrive } from "./utils-CTtD7Oti.mjs";
|
|
9
9
|
import { createRequire, register } from "node:module";
|
|
10
10
|
import { metrics, trace } from "@opentelemetry/api";
|
|
@@ -16,10 +16,11 @@ import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
|
16
16
|
import { getConfig } from "@powerhousedao/config/node";
|
|
17
17
|
import fs, { promises } from "node:fs";
|
|
18
18
|
import path, { join, resolve } from "node:path";
|
|
19
|
-
import {
|
|
20
|
-
import { ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
|
|
21
|
-
import { HttpPackageLoader, ImportPackageLoader,
|
|
19
|
+
import { pathToFileURL } from "node:url";
|
|
20
|
+
import { CatchUpPriority, ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseCatchUpPriority, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
|
|
21
|
+
import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
|
|
22
22
|
import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
|
|
23
|
+
import { PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, resolvePgliteWorkerMemoryMb, syncTree } from "@powerhousedao/reactor-api/pglite-node";
|
|
23
24
|
import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
24
25
|
import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
|
|
25
26
|
import { DriveNodeView, NodeProcessor, ReactorDriveClient } from "@powerhousedao/reactor-drive";
|
|
@@ -67,6 +68,25 @@ async function loadPGliteModule(major) {
|
|
|
67
68
|
if (major === 16) return await import("pglite-legacy-02");
|
|
68
69
|
return import("@electric-sql/pglite");
|
|
69
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Where a PGlite worker imports the module that opens `major` dirs from,
|
|
73
|
+
* resolved here because the worker's own package cannot see the
|
|
74
|
+
* `pglite-legacy-02` alias.
|
|
75
|
+
*/
|
|
76
|
+
function pgliteModuleSpec(major) {
|
|
77
|
+
const base = major === 16 ? "pglite-legacy-02" : "@electric-sql/pglite";
|
|
78
|
+
return {
|
|
79
|
+
pglite: resolveModuleUrl(base),
|
|
80
|
+
nodefs: resolveModuleUrl(`${base}/nodefs`)
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function resolveModuleUrl(specifier) {
|
|
84
|
+
try {
|
|
85
|
+
return import.meta.resolve(specifier);
|
|
86
|
+
} catch {
|
|
87
|
+
return pathToFileURL(createRequire(import.meta.url).resolve(specifier)).href;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
70
90
|
/** The stock NodeFS class of the PGlite module that opens `major` dirs. */
|
|
71
91
|
async function loadNodeFsClass(major) {
|
|
72
92
|
if (major === 16) return (await import("pglite-legacy-02/nodefs")).NodeFS;
|
|
@@ -1277,6 +1297,129 @@ async function runPglitePreflight(options) {
|
|
|
1277
1297
|
return detectedMajors;
|
|
1278
1298
|
}
|
|
1279
1299
|
//#endregion
|
|
1300
|
+
//#region src/pglite-store.mts
|
|
1301
|
+
/** The env var and OpenFeature flag key that moves each PGlite store into its own worker thread. */
|
|
1302
|
+
const PH_PGLITE_WORKERS = "PH_PGLITE_WORKERS";
|
|
1303
|
+
/** Whether each PGlite store opens in its own worker thread: the host's
|
|
1304
|
+
* option, else PH_PGLITE_WORKERS ("true"/"false"), else PGLITE_WORKERS_DEFAULT. */
|
|
1305
|
+
async function resolvePgliteWorkersEnabled({ featureFlags, option }) {
|
|
1306
|
+
if (option !== void 0) return option;
|
|
1307
|
+
return featureFlags.getBooleanValue(PH_PGLITE_WORKERS, true);
|
|
1308
|
+
}
|
|
1309
|
+
function onPgliteAbort(logger, what, proc) {
|
|
1310
|
+
if (!triggerFatalShutdown("PGlite aborted", what, proc)) logger.error("PGlite aborted: @error", what);
|
|
1311
|
+
}
|
|
1312
|
+
/** A store's worker thread died: every later query would fail, so the process shuts down. */
|
|
1313
|
+
function onPgliteWorkerExit(logger, error, proc) {
|
|
1314
|
+
if (!triggerFatalShutdown("PGlite worker exited", error, proc)) logger.error("PGlite worker exited: @error", error);
|
|
1315
|
+
}
|
|
1316
|
+
/** Sends a worker's abort and its unexpected exit to the fatal shutdown. */
|
|
1317
|
+
function routePgliteWorkerFailures(store, logger, proc) {
|
|
1318
|
+
store.onAbort((reason) => onPgliteAbort(logger, reason, proc));
|
|
1319
|
+
store.onExit((error) => {
|
|
1320
|
+
if (error !== null) onPgliteWorkerExit(logger, error, proc);
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Adds a terminate of the store's worker to the dialect's `onPoisoned`: a
|
|
1325
|
+
* statement that never settled holds the worker's only connection, and the
|
|
1326
|
+
* fatal shutdown's close would otherwise queue behind it until its grace ran
|
|
1327
|
+
* out.
|
|
1328
|
+
*/
|
|
1329
|
+
function terminateOnPoisoned(options, store) {
|
|
1330
|
+
const reportPoisoned = options.onPoisoned;
|
|
1331
|
+
return {
|
|
1332
|
+
...options,
|
|
1333
|
+
onPoisoned: (cause) => {
|
|
1334
|
+
reportPoisoned?.(cause);
|
|
1335
|
+
store.terminate();
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
function pgliteFsyncFor(major, dir, logger) {
|
|
1340
|
+
const wanted = resolvePgliteFsync(process.env);
|
|
1341
|
+
if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
|
|
1342
|
+
return wanted;
|
|
1343
|
+
}
|
|
1344
|
+
/** VACUUM FULL timing from the environment; unset or invalid keeps the defaults. */
|
|
1345
|
+
function vacuumFullTimingFromEnv(env) {
|
|
1346
|
+
const ms = (value) => {
|
|
1347
|
+
if (value === void 0 || value.trim() === "") return void 0;
|
|
1348
|
+
const parsed = Number(value);
|
|
1349
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
1350
|
+
};
|
|
1351
|
+
const quiet = ms(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);
|
|
1352
|
+
const maxDefer = ms(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);
|
|
1353
|
+
return {
|
|
1354
|
+
...quiet === void 0 ? {} : { vacuumFullQuietMs: quiet },
|
|
1355
|
+
...maxDefer === void 0 ? {} : { vacuumFullMaxDeferMs: maxDefer }
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1359
|
+
async function loadDurableFsFactory(major, logger, proc) {
|
|
1360
|
+
const NodeFS = await loadNodeFsClass(major);
|
|
1361
|
+
const timing = vacuumFullTimingFromEnv(process.env);
|
|
1362
|
+
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1363
|
+
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1364
|
+
...timing,
|
|
1365
|
+
logger,
|
|
1366
|
+
onAbort: (what) => onPgliteAbort(logger, what, proc)
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* The factory for one PGlite store: in a worker thread when `threaded` (and a
|
|
1371
|
+
* worker script exists here), else in the main thread as before. Either way
|
|
1372
|
+
* the store runs DurableNodeFs over its dir with the same fsync choice, and a
|
|
1373
|
+
* wasm abort takes the fatal shutdown.
|
|
1374
|
+
*/
|
|
1375
|
+
async function createPgliteStoreFactory(options) {
|
|
1376
|
+
if (options.threaded) {
|
|
1377
|
+
if (pgliteWorkerEntryPath !== null) return threadedStoreFactory(options);
|
|
1378
|
+
options.logger.warn(`${options.label}: no PGlite worker script is available (unbuilt @powerhousedao/reactor-api); PGlite runs in the main thread`);
|
|
1379
|
+
}
|
|
1380
|
+
return mainThreadStoreFactory(options);
|
|
1381
|
+
}
|
|
1382
|
+
function threadedStoreFactory(options) {
|
|
1383
|
+
const { label, major, parsers, inMemory, logger, proc } = options;
|
|
1384
|
+
const memoryLimitMb = resolvePgliteWorkerMemoryMb(process.env);
|
|
1385
|
+
const module = pgliteModuleSpec(major);
|
|
1386
|
+
return (dir) => {
|
|
1387
|
+
const store = new ThreadedPGlite({
|
|
1388
|
+
store: {
|
|
1389
|
+
label,
|
|
1390
|
+
dataDir: inMemory ? null : dir,
|
|
1391
|
+
module,
|
|
1392
|
+
durableFs: inMemory ? null : {
|
|
1393
|
+
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1394
|
+
...vacuumFullTimingFromEnv(process.env)
|
|
1395
|
+
},
|
|
1396
|
+
parsers
|
|
1397
|
+
},
|
|
1398
|
+
memoryLimitMb,
|
|
1399
|
+
logger
|
|
1400
|
+
});
|
|
1401
|
+
routePgliteWorkerFailures(store, logger, proc);
|
|
1402
|
+
logger.info(`${label}: PGlite (PG${major}) in a worker thread (memory limit ${memoryLimitMb} MB)${where(inMemory, dir)}`);
|
|
1403
|
+
return store;
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
async function mainThreadStoreFactory(options) {
|
|
1407
|
+
const { label, major, inMemory, logger, proc } = options;
|
|
1408
|
+
const { PGlite } = await loadPGliteModule(major);
|
|
1409
|
+
const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc);
|
|
1410
|
+
const base = options.parsers === "utc-timestamps" ? { parsers: PGLITE_UTC_PARSERS } : {};
|
|
1411
|
+
return (dir) => {
|
|
1412
|
+
logger.info(`${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`);
|
|
1413
|
+
return durableFs === null ? new PGlite(base) : new PGlite({
|
|
1414
|
+
...base,
|
|
1415
|
+
fs: durableFs(dir)
|
|
1416
|
+
});
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
function where(inMemory, dir) {
|
|
1420
|
+
return inMemory ? ", in memory [PH_PGLITE_IN_MEMORY=1]" : ` at ${dir}`;
|
|
1421
|
+
}
|
|
1422
|
+
//#endregion
|
|
1280
1423
|
//#region src/create-signature-policy.mts
|
|
1281
1424
|
/**
|
|
1282
1425
|
* What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a
|
|
@@ -1504,23 +1647,6 @@ function warnIgnoredFlushInterval(logger) {
|
|
|
1504
1647
|
flushIntervalWarned = true;
|
|
1505
1648
|
logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
|
|
1506
1649
|
}
|
|
1507
|
-
function onPgliteAbort(logger, what) {
|
|
1508
|
-
if (!triggerFatalShutdown("PGlite aborted", what)) logger.error("PGlite aborted: @error", what);
|
|
1509
|
-
}
|
|
1510
|
-
function pgliteFsyncFor(major, dir, logger) {
|
|
1511
|
-
const wanted = resolvePgliteFsync(process.env);
|
|
1512
|
-
if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
|
|
1513
|
-
return wanted;
|
|
1514
|
-
}
|
|
1515
|
-
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1516
|
-
async function loadDurableFsFactory(major, logger) {
|
|
1517
|
-
const NodeFS = await loadNodeFsClass(major);
|
|
1518
|
-
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1519
|
-
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1520
|
-
logger,
|
|
1521
|
-
onAbort: (what) => onPgliteAbort(logger, what)
|
|
1522
|
-
});
|
|
1523
|
-
}
|
|
1524
1650
|
const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
|
|
1525
1651
|
/**
|
|
1526
1652
|
* Attempt to bind a throwaway TCP server to the given port. Resolves true if
|
|
@@ -1580,7 +1706,7 @@ async function resolveServerPort(requested, strictPort, logger) {
|
|
|
1580
1706
|
return requested;
|
|
1581
1707
|
}
|
|
1582
1708
|
async function createReactorKysely(opts) {
|
|
1583
|
-
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, logger } = opts;
|
|
1709
|
+
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, logger } = opts;
|
|
1584
1710
|
if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
|
|
1585
1711
|
const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
|
|
1586
1712
|
const poolSize = hostPoolSize();
|
|
@@ -1597,11 +1723,17 @@ async function createReactorKysely(opts) {
|
|
|
1597
1723
|
};
|
|
1598
1724
|
}
|
|
1599
1725
|
if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
|
|
1600
|
-
const
|
|
1601
|
-
|
|
1602
|
-
|
|
1726
|
+
const pglite = (await createPgliteStoreFactory({
|
|
1727
|
+
label: "reactor-storage",
|
|
1728
|
+
major: reactorPgliteMajor,
|
|
1729
|
+
parsers: "none",
|
|
1730
|
+
inMemory,
|
|
1731
|
+
threaded: pgliteWorkers,
|
|
1732
|
+
logger
|
|
1733
|
+
}))(reactorPgliteDir);
|
|
1734
|
+
const dialectOptions = pglite instanceof ThreadedPGlite ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite) : reactorPgliteDialectOptions(logger);
|
|
1603
1735
|
return {
|
|
1604
|
-
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite,
|
|
1736
|
+
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, dialectOptions) }),
|
|
1605
1737
|
poolInstrumentation: void 0,
|
|
1606
1738
|
storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
|
|
1607
1739
|
};
|
|
@@ -1744,6 +1876,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1744
1876
|
if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
|
|
1745
1877
|
}
|
|
1746
1878
|
let ownedReactorModule;
|
|
1879
|
+
const catchUpPriority = new CatchUpPriority(catchUpPrioritySettingFromEnv(process.env.PH_CATCH_UP_PRIORITY, logger));
|
|
1747
1880
|
let workerModels;
|
|
1748
1881
|
let localRenownRequest;
|
|
1749
1882
|
const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
|
|
@@ -1764,6 +1897,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1764
1897
|
reactorPgliteMajor,
|
|
1765
1898
|
inMemory: PGLITE_IN_MEMORY,
|
|
1766
1899
|
hostPoolSize: () => resolveHostPoolSize(process.env),
|
|
1900
|
+
pgliteWorkers: options.pgliteWorkers === true,
|
|
1767
1901
|
logger
|
|
1768
1902
|
});
|
|
1769
1903
|
const maxSkipThreshold = parseInt(process.env.MAX_SKIP_THRESHOLD ?? "", 10);
|
|
@@ -1771,7 +1905,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1771
1905
|
if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
|
|
1772
1906
|
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = resolveReactorFeatureFlags(process.env);
|
|
1773
1907
|
if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
|
|
1774
|
-
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" }).withUnsupportedStoredDocuments(unsupportedStoredDocuments);
|
|
1908
|
+
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" }).withUnsupportedStoredDocuments(unsupportedStoredDocuments).withCatchUpPriority(catchUpPriority);
|
|
1775
1909
|
if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
|
|
1776
1910
|
const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
|
|
1777
1911
|
const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
|
|
@@ -1928,12 +2062,15 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1928
2062
|
const apiLogger = logger.child(["reactor-api"]);
|
|
1929
2063
|
let pgliteFactory;
|
|
1930
2064
|
if (readModelPgliteDir && readModelPgliteMajor !== null) {
|
|
1931
|
-
const
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
2065
|
+
const openReadStore = await createPgliteStoreFactory({
|
|
2066
|
+
label: "read-storage",
|
|
2067
|
+
major: readModelPgliteMajor,
|
|
2068
|
+
parsers: "utc-timestamps",
|
|
2069
|
+
inMemory: PGLITE_IN_MEMORY,
|
|
2070
|
+
threaded: options.pgliteWorkers === true,
|
|
2071
|
+
logger
|
|
1936
2072
|
});
|
|
2073
|
+
pgliteFactory = (connectionString) => openReadStore(connectionString ?? readModelPgliteDir);
|
|
1937
2074
|
}
|
|
1938
2075
|
const api = await initializeAndStartAPI(initializeClient, {
|
|
1939
2076
|
port: serverPort,
|
|
@@ -2101,8 +2238,10 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2101
2238
|
throw error;
|
|
2102
2239
|
}
|
|
2103
2240
|
}
|
|
2241
|
+
const stopCatchUpLoad = ownedReactorModule ? feedCatchUpPriority(catchUpPriority, api.httpServer) : () => {};
|
|
2104
2242
|
let apiDrained;
|
|
2105
2243
|
const drainApi = () => apiDrained ??= (async () => {
|
|
2244
|
+
stopCatchUpLoad();
|
|
2106
2245
|
if (pluginHost) await pluginHost.observe("onShutdown");
|
|
2107
2246
|
await privacy?.stop();
|
|
2108
2247
|
await workflowsRetry?.stop();
|
|
@@ -2213,6 +2352,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2213
2352
|
})(),
|
|
2214
2353
|
mcpEnabled: options.mcp !== false,
|
|
2215
2354
|
inspectionEnabled: options.inspection !== false,
|
|
2355
|
+
inspector: api.inspection?.inspector,
|
|
2216
2356
|
renown,
|
|
2217
2357
|
port: serverPort,
|
|
2218
2358
|
shutdown
|
|
@@ -2260,6 +2400,10 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2260
2400
|
featureFlags,
|
|
2261
2401
|
option: options.inspection
|
|
2262
2402
|
});
|
|
2403
|
+
options.pgliteWorkers = await resolvePgliteWorkersEnabled({
|
|
2404
|
+
featureFlags,
|
|
2405
|
+
option: options.pgliteWorkers
|
|
2406
|
+
});
|
|
2263
2407
|
const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
|
|
2264
2408
|
options.identity = {
|
|
2265
2409
|
...options.identity,
|
|
@@ -2270,6 +2414,7 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2270
2414
|
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
|
|
2271
2415
|
MCP_ENABLED: options.mcp,
|
|
2272
2416
|
INSPECTION_ENABLED: options.inspection,
|
|
2417
|
+
PH_PGLITE_WORKERS: options.pgliteWorkers,
|
|
2273
2418
|
PH_WORKFLOWS_ENABLED: options.workflows?.enabled
|
|
2274
2419
|
}, null, 2));
|
|
2275
2420
|
let renown = null;
|
|
@@ -2289,8 +2434,30 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2289
2434
|
}
|
|
2290
2435
|
};
|
|
2291
2436
|
if (import.meta.main) await startSwitchboard({ fatalErrorShutdown: true });
|
|
2437
|
+
/** `PH_CATCH_UP_PRIORITY`: `dynamic` (the default) or a fixed level `0`-`7`. */
|
|
2438
|
+
function catchUpPrioritySettingFromEnv(value, logger) {
|
|
2439
|
+
const setting = parseCatchUpPriority(value);
|
|
2440
|
+
if (setting) return setting;
|
|
2441
|
+
logger.warn("PH_CATCH_UP_PRIORITY=@Value is neither dynamic nor a level 0-7; using dynamic", JSON.stringify(value));
|
|
2442
|
+
return { mode: "dynamic" };
|
|
2443
|
+
}
|
|
2444
|
+
/**
|
|
2445
|
+
* Feeds the priority this server's request load and main-thread event-loop
|
|
2446
|
+
* delay, and ticks its controller every second. Returns the stop.
|
|
2447
|
+
*/
|
|
2448
|
+
function feedCatchUpPriority(priority, server) {
|
|
2449
|
+
const recorder = new RequestLoadRecorder({ eventLoopDelay: new NodeEventLoopDelay() });
|
|
2450
|
+
recorder.attach(server);
|
|
2451
|
+
priority.setLoadSource(recorder);
|
|
2452
|
+
const stopTicking = priority.startTicking();
|
|
2453
|
+
return () => {
|
|
2454
|
+
stopTicking();
|
|
2455
|
+
priority.setLoadSource(void 0);
|
|
2456
|
+
recorder.stop();
|
|
2457
|
+
};
|
|
2458
|
+
}
|
|
2292
2459
|
//#endregion
|
|
2293
2460
|
export { startSwitchboard as a, attachmentsPlugin as c, initProfilerFromEnv as d, parseForcePgVersion as f, resolvePgliteStorageDirs as i, attachmentsPluginConfigSchema as l, deriveAttachmentServiceConfig as n, StoredDocumentsRefusedError as o, isPortAvailable as r, resolveUnsupportedStoredDocuments as s, createReactorKysely as t, applySwitchboardReactorDefaults as u };
|
|
2294
2461
|
|
|
2295
|
-
//# sourceMappingURL=server-
|
|
2296
|
-
//# debugId=
|
|
2462
|
+
//# sourceMappingURL=server-CJjK7WpR.mjs.map
|
|
2463
|
+
//# debugId=23ac9e84-b25f-5218-b443-313ef3078eee
|