@powerhousedao/switchboard 6.2.3-dev.73 → 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/boot-env-isolation.test.d.ts +2 -0
- package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
- package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
- package/.tsbuild/test/pglite-store.test.d.ts +2 -0
- package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
- package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
- package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +51 -0
- package/dist/boot.d.mts +38 -0
- package/dist/boot.d.mts.map +1 -0
- package/dist/boot.mjs +61 -0
- package/dist/boot.mjs.map +1 -0
- package/dist/index.mjs +5 -4
- package/dist/index.mjs.map +1 -1
- package/dist/migrate.mjs +4 -3
- package/dist/migrate.mjs.map +1 -1
- package/dist/plugins/attachments.mjs +3 -3
- package/dist/postgres-url-DTDhBjXX.mjs +11 -0
- package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
- package/dist/reactor-feature-flags-BtWVQDt6.mjs +324 -0
- package/dist/reactor-feature-flags-BtWVQDt6.mjs.map +1 -0
- package/dist/{server-CrWPtMG6.mjs → server-CJjK7WpR.mjs} +214 -333
- package/dist/server-CJjK7WpR.mjs.map +1 -0
- package/dist/server.d.mts +11 -3
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +3 -3
- package/dist/{utils-Dh845exv.mjs → utils-CTtD7Oti.mjs} +5 -8
- package/dist/{utils-Dh845exv.mjs.map → utils-CTtD7Oti.mjs.map} +1 -1
- package/dist/utils.d.mts +3 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +4 -3
- package/package.json +21 -16
- package/test/boot-env-isolation.test.ts +26 -0
- package/test/boot-preconditions.test.ts +149 -0
- package/test/pglite-dialect.test.ts +39 -19
- package/test/pglite-store.test.ts +311 -0
- package/test/renown-storage-path.test.ts +39 -0
- package/test/renown-trust-policy.test.ts +7 -9
- package/tsdown.config.ts +1 -0
- package/dist/server-CrWPtMG6.mjs.map +0 -1
|
@@ -1,22 +1,26 @@
|
|
|
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
|
-
import {
|
|
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-BtWVQDt6.mjs";
|
|
8
|
+
import { n as addDefaultReactorDrive, t as addDefaultDrive } from "./utils-CTtD7Oti.mjs";
|
|
7
9
|
import { createRequire, register } from "node:module";
|
|
8
10
|
import { metrics, trace } from "@opentelemetry/api";
|
|
9
11
|
import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
|
|
10
12
|
import * as Sentry from "@sentry/node";
|
|
11
13
|
import { childLogger, setLogLevel } from "document-model";
|
|
12
14
|
import dotenv from "dotenv";
|
|
15
|
+
import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
13
16
|
import { getConfig } from "@powerhousedao/config/node";
|
|
14
|
-
import fs, {
|
|
15
|
-
import path, { resolve } from "node:path";
|
|
16
|
-
import {
|
|
17
|
-
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";
|
|
18
|
-
import { HttpPackageLoader, ImportPackageLoader,
|
|
17
|
+
import fs, { promises } from "node:fs";
|
|
18
|
+
import path, { join, resolve } from "node:path";
|
|
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";
|
|
19
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";
|
|
20
24
|
import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
21
25
|
import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
|
|
22
26
|
import { DriveNodeView, NodeProcessor, ReactorDriveClient } from "@powerhousedao/reactor-drive";
|
|
@@ -30,12 +34,9 @@ import { Readable } from "node:stream";
|
|
|
30
34
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
31
35
|
import { z } from "zod";
|
|
32
36
|
import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
|
|
33
|
-
import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
34
|
-
import { readFile } from "node:fs/promises";
|
|
35
|
-
import os from "node:os";
|
|
36
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
37
37
|
import { EnvVarProvider } from "@openfeature/env-var-provider";
|
|
38
38
|
import { OpenFeature } from "@openfeature/server-sdk";
|
|
39
|
+
import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
39
40
|
import { defaultStoreDirs, resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
|
|
40
41
|
//#region src/pglite-version.ts
|
|
41
42
|
const SUPPORTED_PG_MAJORS = [16, 17];
|
|
@@ -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;
|
|
@@ -1033,269 +1053,6 @@ function createSwitchboardPluginHost(ctx, resolved) {
|
|
|
1033
1053
|
};
|
|
1034
1054
|
}
|
|
1035
1055
|
//#endregion
|
|
1036
|
-
//#region src/env.mts
|
|
1037
|
-
function parseNonNegativeInt(raw, name) {
|
|
1038
|
-
if (raw === void 0 || raw.trim() === "") return;
|
|
1039
|
-
const value = Number.parseInt(raw, 10);
|
|
1040
|
-
if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
|
|
1041
|
-
return value;
|
|
1042
|
-
}
|
|
1043
|
-
//#endregion
|
|
1044
|
-
//#region src/projection-worker.mts
|
|
1045
|
-
const DEFAULT_DB_POOL_SIZE_PROJECTION = 8;
|
|
1046
|
-
const ON_TOKENS = [
|
|
1047
|
-
"1",
|
|
1048
|
-
"true",
|
|
1049
|
-
"on",
|
|
1050
|
-
"yes"
|
|
1051
|
-
];
|
|
1052
|
-
const OFF_TOKENS = [
|
|
1053
|
-
"0",
|
|
1054
|
-
"false",
|
|
1055
|
-
"off",
|
|
1056
|
-
"no"
|
|
1057
|
-
];
|
|
1058
|
-
/**
|
|
1059
|
-
* Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or
|
|
1060
|
-
* `input.enabled`, which wins when defined; null when off (the default).
|
|
1061
|
-
*/
|
|
1062
|
-
function resolveProjectionWorkerOptions(input, env) {
|
|
1063
|
-
if (!(input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false)) return null;
|
|
1064
|
-
const dbPoolSize = input?.dbPoolSize ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_PROJECTION, "REACTOR_DB_POOL_SIZE_PROJECTION") ?? DEFAULT_DB_POOL_SIZE_PROJECTION;
|
|
1065
|
-
if (dbPoolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool");
|
|
1066
|
-
return { dbPoolSize };
|
|
1067
|
-
}
|
|
1068
|
-
/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */
|
|
1069
|
-
function assertProjectionWorkerSupported(args) {
|
|
1070
|
-
if (args.dev) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary");
|
|
1071
|
-
if (!args.reactorDbUrl || !isPostgresUrl(args.reactorDbUrl)) throw new Error("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.");
|
|
1072
|
-
}
|
|
1073
|
-
function parseOnOff(raw) {
|
|
1074
|
-
if (raw === void 0 || raw.trim() === "") return;
|
|
1075
|
-
const token = raw.trim().toLowerCase();
|
|
1076
|
-
if (ON_TOKENS.includes(token)) return true;
|
|
1077
|
-
if (OFF_TOKENS.includes(token)) return false;
|
|
1078
|
-
throw new Error(`REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got "${raw}"`);
|
|
1079
|
-
}
|
|
1080
|
-
//#endregion
|
|
1081
|
-
//#region src/worker-pool.mts
|
|
1082
|
-
const DEFAULT_DB_POOL_SIZE_PER_WORKER = 2;
|
|
1083
|
-
const DEFAULT_ACQUIRE_TIMEOUT_MS = 5e3;
|
|
1084
|
-
const DEFAULT_DB_POOL_SIZE_HOST = 16;
|
|
1085
|
-
const AUTO_RESERVED_CORES = 2;
|
|
1086
|
-
const AUTO_WORKER_CAP = 8;
|
|
1087
|
-
/** Worker count for "auto": always at least 1 — auto sizes the pool, it does not turn worker mode off. */
|
|
1088
|
-
function autoWorkerCount(availableCores) {
|
|
1089
|
-
return Math.max(1, Math.min(AUTO_WORKER_CAP, availableCores - AUTO_RESERVED_CORES));
|
|
1090
|
-
}
|
|
1091
|
-
/**
|
|
1092
|
-
* Effective worker-pool config from programmatic options (which win) and the
|
|
1093
|
-
* REACTOR_* env vars; null when disabled (numWorkers 0, the default).
|
|
1094
|
-
* `"auto"` sizes the pool from the machine's available cores.
|
|
1095
|
-
*/
|
|
1096
|
-
function resolveWorkerPoolOptions(input, env, availableCores = os.availableParallelism()) {
|
|
1097
|
-
const requested = input?.numWorkers ?? parseWorkerCount(env.REACTOR_WORKERS) ?? 0;
|
|
1098
|
-
const mode = requested === "auto" ? "auto" : "explicit";
|
|
1099
|
-
const numWorkers = requested === "auto" ? autoWorkerCount(availableCores) : requested;
|
|
1100
|
-
if (!Number.isInteger(numWorkers) || numWorkers < 0) throw new Error(`workerPool.numWorkers must be "auto" or a non-negative integer, got ${numWorkers}`);
|
|
1101
|
-
if (numWorkers === 0) return null;
|
|
1102
|
-
return {
|
|
1103
|
-
numWorkers,
|
|
1104
|
-
mode,
|
|
1105
|
-
dbPoolSizePerWorker: input?.dbPoolSizePerWorker ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_WORKER, "REACTOR_DB_POOL_SIZE_WORKER") ?? DEFAULT_DB_POOL_SIZE_PER_WORKER,
|
|
1106
|
-
acquireTimeoutMs: input?.acquireTimeoutMs ?? parseNonNegativeInt(env.REACTOR_DB_ACQUIRE_TIMEOUT_MS, "REACTOR_DB_ACQUIRE_TIMEOUT_MS") ?? DEFAULT_ACQUIRE_TIMEOUT_MS
|
|
1107
|
-
};
|
|
1108
|
-
}
|
|
1109
|
-
/**
|
|
1110
|
-
* Size of the reactor's own (host) Postgres pool. Unlike the worker pool there
|
|
1111
|
-
* is no "disabled" state — the host pool is the only Postgres pool in the
|
|
1112
|
-
* server path, backing both reactor storage and the read models that reach it
|
|
1113
|
-
* via `withSchema` — so 0 is rejected rather than read as "off".
|
|
1114
|
-
*
|
|
1115
|
-
* The acquire timeout is deliberately not configurable here: the host pool
|
|
1116
|
-
* waits indefinitely today, and making it finite converts saturation from a
|
|
1117
|
-
* latency problem into a thrown error on the read-model path. That is a
|
|
1118
|
-
* behavior change worth making separately, once the retry semantics of a
|
|
1119
|
-
* rejected `pool.connect()` inside the read-model coordinator are settled.
|
|
1120
|
-
*/
|
|
1121
|
-
function resolveHostPoolSize(env) {
|
|
1122
|
-
const poolSize = parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_HOST, "REACTOR_DB_POOL_SIZE_HOST") ?? DEFAULT_DB_POOL_SIZE_HOST;
|
|
1123
|
-
if (poolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_HOST must be at least 1; the host pool cannot be disabled");
|
|
1124
|
-
return poolSize;
|
|
1125
|
-
}
|
|
1126
|
-
/**
|
|
1127
|
-
* DbConfig for each worker's own pool, parsed from a postgres:// URL.
|
|
1128
|
-
* Explicit host, database, and user are required — no pg-side defaults.
|
|
1129
|
-
*/
|
|
1130
|
-
function buildWorkerDbConfig(postgresUrl, options) {
|
|
1131
|
-
let parsed;
|
|
1132
|
-
try {
|
|
1133
|
-
parsed = new URL(postgresUrl);
|
|
1134
|
-
} catch {
|
|
1135
|
-
throw new Error(`Worker pool requires a valid postgres:// URL for the reactor database, got "${postgresUrl}"`);
|
|
1136
|
-
}
|
|
1137
|
-
const database = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
|
|
1138
|
-
if (!parsed.hostname || !database) throw new Error(`Worker pool requires a postgres URL with a host and database name, got "${postgresUrl}"`);
|
|
1139
|
-
if (!parsed.username) throw new Error(`Worker pool requires explicit credentials in the postgres URL (workers open their own connections), got "${postgresUrl}"`);
|
|
1140
|
-
const sslmode = parsed.searchParams.get("sslmode");
|
|
1141
|
-
const ssl = parsed.searchParams.get("ssl") === "true" || sslmode !== null && sslmode !== "disable";
|
|
1142
|
-
return {
|
|
1143
|
-
host: parsed.hostname,
|
|
1144
|
-
port: parsed.port ? Number(parsed.port) : 5432,
|
|
1145
|
-
database,
|
|
1146
|
-
user: decodeURIComponent(parsed.username),
|
|
1147
|
-
password: decodeURIComponent(parsed.password),
|
|
1148
|
-
ssl,
|
|
1149
|
-
applicationName: "switchboard-worker",
|
|
1150
|
-
poolSize: options.dbPoolSizePerWorker,
|
|
1151
|
-
connectionTimeoutMillis: options.acquireTimeoutMs
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
/** Specifiers of the base models switchboard always registers. */
|
|
1155
|
-
const BASE_MODEL_SPECIFIERS = [
|
|
1156
|
-
"document-model",
|
|
1157
|
-
"@powerhousedao/shared/document-drive",
|
|
1158
|
-
"@powerhousedao/reactor-drive",
|
|
1159
|
-
"@powerhousedao/reactor-group/document-models"
|
|
1160
|
-
];
|
|
1161
|
-
function isModelModule(value) {
|
|
1162
|
-
const candidate = value;
|
|
1163
|
-
return typeof candidate?.reducer === "function" && typeof candidate.documentModel?.global?.id === "string";
|
|
1164
|
-
}
|
|
1165
|
-
async function keepImportableSources(sources, logger) {
|
|
1166
|
-
const kept = [];
|
|
1167
|
-
for (const source of sources) try {
|
|
1168
|
-
const exports = await import(pathToFileURL(source.filePath).href);
|
|
1169
|
-
if (Object.values(exports).some(isModelModule)) kept.push(source);
|
|
1170
|
-
} catch (error) {
|
|
1171
|
-
logger.warn(`Worker model sources: "${source.filePath}" does not import, so workflow pieces will not see its models: ${String(error)}`);
|
|
1172
|
-
}
|
|
1173
|
-
return kept;
|
|
1174
|
-
}
|
|
1175
|
-
/**
|
|
1176
|
-
* Resolves base models and configured package identifiers to `{ filePath }`
|
|
1177
|
-
* sources for the reactor builder. Resolution to absolute paths happens here
|
|
1178
|
-
* because workers (and the builder) resolve bare specifiers from the reactor
|
|
1179
|
-
* package's own dependency context, which cannot see switchboard or project
|
|
1180
|
-
* packages. Unresolvable identifiers are skipped with a warning; the builder
|
|
1181
|
-
* fails the boot if a registered model ends up without an importable source.
|
|
1182
|
-
*/
|
|
1183
|
-
async function resolveWorkerModelSources(packages, logger, options = {}) {
|
|
1184
|
-
const sources = [];
|
|
1185
|
-
for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {
|
|
1186
|
-
const filePath = await resolveModelModuleFile(identifier) ?? await resolveRemoteSafely(identifier, options.resolveRemote, logger);
|
|
1187
|
-
if (!filePath) {
|
|
1188
|
-
logger.warn(`Worker model sources: no importable document-models entry for "${identifier}", skipping`);
|
|
1189
|
-
continue;
|
|
1190
|
-
}
|
|
1191
|
-
sources.push({ filePath });
|
|
1192
|
-
}
|
|
1193
|
-
return sources;
|
|
1194
|
-
}
|
|
1195
|
-
async function resolveRemoteSafely(identifier, resolveRemote, logger) {
|
|
1196
|
-
if (!resolveRemote) return null;
|
|
1197
|
-
try {
|
|
1198
|
-
return await resolveRemote(identifier);
|
|
1199
|
-
} catch (error) {
|
|
1200
|
-
logger.warn(`Worker model sources: could not cache "${identifier}" from the registry: ${String(error)}`);
|
|
1201
|
-
return null;
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
/**
|
|
1205
|
-
* Absolute file path of a source's models barrel. Mirrors reactor-api's
|
|
1206
|
-
* import-resolver: import.meta.resolve, then the project's node_modules via
|
|
1207
|
-
* the package.json exports map / dist layout.
|
|
1208
|
-
*/
|
|
1209
|
-
async function resolveModelModuleFile(source) {
|
|
1210
|
-
if (isFsPath(source)) return resolveFromPackageDir(source, "./document-models");
|
|
1211
|
-
const specifier = BASE_MODEL_SPECIFIERS.includes(source) ? source : `${source}/document-models`;
|
|
1212
|
-
try {
|
|
1213
|
-
const resolved = import.meta.resolve(specifier);
|
|
1214
|
-
if (resolved.startsWith("file:")) return fileURLToPath(resolved);
|
|
1215
|
-
} catch {}
|
|
1216
|
-
const { packageName, subpath } = splitSpecifier(specifier);
|
|
1217
|
-
const packageDir = path.join(process.cwd(), "node_modules", packageName);
|
|
1218
|
-
if (!existsSync(packageDir)) return null;
|
|
1219
|
-
let realDir;
|
|
1220
|
-
try {
|
|
1221
|
-
realDir = realpathSync(packageDir);
|
|
1222
|
-
} catch {
|
|
1223
|
-
return null;
|
|
1224
|
-
}
|
|
1225
|
-
return resolveFromPackageDir(realDir, subpath);
|
|
1226
|
-
}
|
|
1227
|
-
function splitSpecifier(specifier) {
|
|
1228
|
-
const parts = specifier.split("/");
|
|
1229
|
-
const packageSegments = specifier.startsWith("@") ? 2 : 1;
|
|
1230
|
-
const packageName = parts.slice(0, packageSegments).join("/");
|
|
1231
|
-
const rest = parts.slice(packageSegments).join("/");
|
|
1232
|
-
return {
|
|
1233
|
-
packageName,
|
|
1234
|
-
subpath: rest ? `./${rest}` : "."
|
|
1235
|
-
};
|
|
1236
|
-
}
|
|
1237
|
-
/** Exports-map lookup (import condition), then conventional dist paths. */
|
|
1238
|
-
async function resolveFromPackageDir(packageDir, subpath) {
|
|
1239
|
-
const fromManifest = await resolveViaManifest(packageDir, subpath);
|
|
1240
|
-
if (fromManifest) return fromManifest;
|
|
1241
|
-
const candidates = subpath === "." ? [path.join(packageDir, "dist", "index.js")] : [
|
|
1242
|
-
path.join(packageDir, "dist", subpath.slice(2), "index.js"),
|
|
1243
|
-
path.join(packageDir, "dist", `${subpath.slice(2)}.js`),
|
|
1244
|
-
path.join(packageDir, subpath.slice(2), "index.js")
|
|
1245
|
-
];
|
|
1246
|
-
for (const candidate of candidates) if (existsSync(candidate)) return candidate;
|
|
1247
|
-
return null;
|
|
1248
|
-
}
|
|
1249
|
-
async function resolveViaManifest(packageDir, subpath) {
|
|
1250
|
-
let raw;
|
|
1251
|
-
try {
|
|
1252
|
-
raw = await readFile(path.join(packageDir, "package.json"), "utf8");
|
|
1253
|
-
} catch {
|
|
1254
|
-
return null;
|
|
1255
|
-
}
|
|
1256
|
-
let manifest;
|
|
1257
|
-
try {
|
|
1258
|
-
manifest = JSON.parse(raw);
|
|
1259
|
-
} catch {
|
|
1260
|
-
return null;
|
|
1261
|
-
}
|
|
1262
|
-
let entry;
|
|
1263
|
-
const exportsField = manifest.exports;
|
|
1264
|
-
if (exportsField !== null && typeof exportsField === "object" && !Array.isArray(exportsField)) {
|
|
1265
|
-
const map = exportsField;
|
|
1266
|
-
entry = Object.keys(map).some((key) => key.startsWith(".")) ? map[subpath] : subpath === "." ? map : void 0;
|
|
1267
|
-
} else if (typeof exportsField === "string" && subpath === ".") entry = exportsField;
|
|
1268
|
-
let target = pickImportTarget(entry);
|
|
1269
|
-
if (!target && subpath === "." && typeof manifest.main === "string") target = manifest.main;
|
|
1270
|
-
if (!target) return null;
|
|
1271
|
-
const resolved = path.join(packageDir, target);
|
|
1272
|
-
return existsSync(resolved) ? resolved : null;
|
|
1273
|
-
}
|
|
1274
|
-
function pickImportTarget(entry) {
|
|
1275
|
-
if (typeof entry === "string") return entry;
|
|
1276
|
-
if (typeof entry !== "object" || entry === null) return null;
|
|
1277
|
-
const conditions = entry;
|
|
1278
|
-
for (const condition of [
|
|
1279
|
-
"import",
|
|
1280
|
-
"node",
|
|
1281
|
-
"default"
|
|
1282
|
-
]) {
|
|
1283
|
-
const value = conditions[condition];
|
|
1284
|
-
if (typeof value === "string") return value;
|
|
1285
|
-
}
|
|
1286
|
-
return null;
|
|
1287
|
-
}
|
|
1288
|
-
function isFsPath(identifier) {
|
|
1289
|
-
return path.isAbsolute(identifier) || identifier.startsWith("./") || identifier.startsWith("../");
|
|
1290
|
-
}
|
|
1291
|
-
function parseWorkerCount(raw) {
|
|
1292
|
-
if (raw === void 0 || raw.trim() === "") return;
|
|
1293
|
-
if (raw.trim().toLowerCase() === "auto") return "auto";
|
|
1294
|
-
const value = Number.parseInt(raw, 10);
|
|
1295
|
-
if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`REACTOR_WORKERS must be "auto" or a non-negative integer, got "${raw}"`);
|
|
1296
|
-
return value;
|
|
1297
|
-
}
|
|
1298
|
-
//#endregion
|
|
1299
1056
|
//#region src/inspection-throttle.mts
|
|
1300
1057
|
const NAME = "PH_INSPECTION_CALLS_PER_MINUTE";
|
|
1301
1058
|
/** Unset keeps reactor-api's default; an invalid value fails boot. */
|
|
@@ -1540,25 +1297,128 @@ async function runPglitePreflight(options) {
|
|
|
1540
1297
|
return detectedMajors;
|
|
1541
1298
|
}
|
|
1542
1299
|
//#endregion
|
|
1543
|
-
//#region src/
|
|
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
|
+
}
|
|
1544
1323
|
/**
|
|
1545
|
-
*
|
|
1546
|
-
*
|
|
1547
|
-
*
|
|
1548
|
-
*
|
|
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.
|
|
1549
1328
|
*/
|
|
1550
|
-
function
|
|
1551
|
-
const
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1329
|
+
function terminateOnPoisoned(options, store) {
|
|
1330
|
+
const reportPoisoned = options.onPoisoned;
|
|
1331
|
+
return {
|
|
1332
|
+
...options,
|
|
1333
|
+
onPoisoned: (cause) => {
|
|
1334
|
+
reportPoisoned?.(cause);
|
|
1335
|
+
store.terminate();
|
|
1336
|
+
}
|
|
1556
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);
|
|
1557
1353
|
return {
|
|
1558
|
-
|
|
1559
|
-
|
|
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;
|
|
1560
1404
|
};
|
|
1561
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
|
+
}
|
|
1562
1422
|
//#endregion
|
|
1563
1423
|
//#region src/create-signature-policy.mts
|
|
1564
1424
|
/**
|
|
@@ -1588,13 +1448,16 @@ const logger = childLogger(["switchboard", "renown"]);
|
|
|
1588
1448
|
* using the same identity established during `ph login`.
|
|
1589
1449
|
*/
|
|
1590
1450
|
async function initRenown(options = {}) {
|
|
1591
|
-
const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL } = options;
|
|
1451
|
+
const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL, storagePath = process.env.PH_USER_DATA_DIR ? join(resolvePhDir(), ".renown.json") : void 0 } = options;
|
|
1592
1452
|
const keyStorage = new NodeKeyStorage(keypairPath, { logger });
|
|
1593
1453
|
const existingKeyPair = await keyStorage.loadKeyPair();
|
|
1594
1454
|
if (!existingKeyPair && requireExisting) throw new Error("No existing keypair found and requireExisting is true. Run \"ph login\" to create one.");
|
|
1595
1455
|
if (!existingKeyPair) logger.info("No existing keypair found. A new one will be generated.");
|
|
1596
1456
|
const renownCrypto = await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();
|
|
1597
|
-
const renown = await new RenownBuilder("switchboard", {
|
|
1457
|
+
const renown = await new RenownBuilder("switchboard", {
|
|
1458
|
+
...storagePath ? { storagePath } : {},
|
|
1459
|
+
...keypairPath ? { keyPath: keypairPath } : {}
|
|
1460
|
+
}).withCrypto(renownCrypto).withBaseUrl(baseUrl).build();
|
|
1598
1461
|
logger.info("Switchboard identity initialized: @did", renownCrypto.did);
|
|
1599
1462
|
return renown;
|
|
1600
1463
|
}
|
|
@@ -1671,14 +1534,6 @@ async function getRenownTrustPolicyConfig(trustSource, renown) {
|
|
|
1671
1534
|
}
|
|
1672
1535
|
};
|
|
1673
1536
|
}
|
|
1674
|
-
/**
|
|
1675
|
-
* Fails the boot when pooled workers would refuse every signed write the
|
|
1676
|
-
* in-process executor accepts: a `self` Renown source gives workers no trust
|
|
1677
|
-
* policy spec, so under authEnforcement they apply the default.
|
|
1678
|
-
*/
|
|
1679
|
-
function assertWorkerTrustPolicy(config) {
|
|
1680
|
-
if (config.workers > 0 && config.authEnforcement && config.renownSource === "self") throw new Error("The executor worker pool (REACTOR_WORKERS) cannot verify signers when REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): pooled workers have no trust policy and would refuse every signed write. Set RENOWN_SOURCE=remote, or disable the worker pool (REACTOR_WORKERS=0).");
|
|
1681
|
-
}
|
|
1682
1537
|
function ownIdentity(renown) {
|
|
1683
1538
|
const key = renown?.signer.app?.key;
|
|
1684
1539
|
if (!key) return;
|
|
@@ -1780,7 +1635,7 @@ function acquireStoreLocks(dirs, isPidAlive = isAlive) {
|
|
|
1780
1635
|
const defaultLogger = childLogger(["switchboard"]);
|
|
1781
1636
|
const LogLevel = process.env.LOG_LEVEL || "info";
|
|
1782
1637
|
setLogLevel(LogLevel);
|
|
1783
|
-
dotenv.config();
|
|
1638
|
+
if (!isDotenvDisabled()) dotenv.config();
|
|
1784
1639
|
const DOCUMENT_MODEL_SUBGRAPHS_ENABLED = "DOCUMENT_MODEL_SUBGRAPHS_ENABLED";
|
|
1785
1640
|
const DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT = true;
|
|
1786
1641
|
const DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 4001;
|
|
@@ -1792,23 +1647,6 @@ function warnIgnoredFlushInterval(logger) {
|
|
|
1792
1647
|
flushIntervalWarned = true;
|
|
1793
1648
|
logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
|
|
1794
1649
|
}
|
|
1795
|
-
function onPgliteAbort(logger, what) {
|
|
1796
|
-
if (!triggerFatalShutdown("PGlite aborted", what)) logger.error("PGlite aborted: @error", what);
|
|
1797
|
-
}
|
|
1798
|
-
function pgliteFsyncFor(major, dir, logger) {
|
|
1799
|
-
const wanted = resolvePgliteFsync(process.env);
|
|
1800
|
-
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.`);
|
|
1801
|
-
return wanted;
|
|
1802
|
-
}
|
|
1803
|
-
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1804
|
-
async function loadDurableFsFactory(major, logger) {
|
|
1805
|
-
const NodeFS = await loadNodeFsClass(major);
|
|
1806
|
-
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1807
|
-
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1808
|
-
logger,
|
|
1809
|
-
onAbort: (what) => onPgliteAbort(logger, what)
|
|
1810
|
-
});
|
|
1811
|
-
}
|
|
1812
1650
|
const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
|
|
1813
1651
|
/**
|
|
1814
1652
|
* Attempt to bind a throwaway TCP server to the given port. Resolves true if
|
|
@@ -1868,7 +1706,7 @@ async function resolveServerPort(requested, strictPort, logger) {
|
|
|
1868
1706
|
return requested;
|
|
1869
1707
|
}
|
|
1870
1708
|
async function createReactorKysely(opts) {
|
|
1871
|
-
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, logger } = opts;
|
|
1709
|
+
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, logger } = opts;
|
|
1872
1710
|
if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
|
|
1873
1711
|
const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
|
|
1874
1712
|
const poolSize = hostPoolSize();
|
|
@@ -1885,11 +1723,17 @@ async function createReactorKysely(opts) {
|
|
|
1885
1723
|
};
|
|
1886
1724
|
}
|
|
1887
1725
|
if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
|
|
1888
|
-
const
|
|
1889
|
-
|
|
1890
|
-
|
|
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);
|
|
1891
1735
|
return {
|
|
1892
|
-
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite,
|
|
1736
|
+
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, dialectOptions) }),
|
|
1893
1737
|
poolInstrumentation: void 0,
|
|
1894
1738
|
storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
|
|
1895
1739
|
};
|
|
@@ -1947,7 +1791,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1947
1791
|
}
|
|
1948
1792
|
logger.level = LogLevel;
|
|
1949
1793
|
const dbPath = options.dbPath ?? process.env.DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
|
|
1950
|
-
const reactorDbUrl = options.dbPath
|
|
1794
|
+
const reactorDbUrl = reactorDbUrlOf(options.dbPath, process.env);
|
|
1951
1795
|
const { readModelPath, reactorPgliteDir, readModelPgliteDir, pgliteDirs, sharedPgliteDir } = resolvePgliteStorageDirs({
|
|
1952
1796
|
dbPath,
|
|
1953
1797
|
reactorDbUrl,
|
|
@@ -1979,13 +1823,15 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1979
1823
|
workerPool = null;
|
|
1980
1824
|
}
|
|
1981
1825
|
if (workerPool) {
|
|
1982
|
-
|
|
1983
|
-
|
|
1826
|
+
const issue = workerPoolIssues({
|
|
1827
|
+
dev: dev === true,
|
|
1984
1828
|
workers: workerPool.numWorkers,
|
|
1829
|
+
projectionWorker: false,
|
|
1830
|
+
reactorDbUrl,
|
|
1985
1831
|
authEnforcement: resolveReactorFeatureFlags(process.env).flags.authEnforcement === true,
|
|
1986
1832
|
renownSource: renownConfig.source
|
|
1987
|
-
});
|
|
1988
|
-
if (
|
|
1833
|
+
}).at(0);
|
|
1834
|
+
if (issue) throw new Error(issue);
|
|
1989
1835
|
}
|
|
1990
1836
|
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, process.env);
|
|
1991
1837
|
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, process.env);
|
|
@@ -2030,6 +1876,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2030
1876
|
if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
|
|
2031
1877
|
}
|
|
2032
1878
|
let ownedReactorModule;
|
|
1879
|
+
const catchUpPriority = new CatchUpPriority(catchUpPrioritySettingFromEnv(process.env.PH_CATCH_UP_PRIORITY, logger));
|
|
2033
1880
|
let workerModels;
|
|
2034
1881
|
let localRenownRequest;
|
|
2035
1882
|
const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
|
|
@@ -2050,6 +1897,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2050
1897
|
reactorPgliteMajor,
|
|
2051
1898
|
inMemory: PGLITE_IN_MEMORY,
|
|
2052
1899
|
hostPoolSize: () => resolveHostPoolSize(process.env),
|
|
1900
|
+
pgliteWorkers: options.pgliteWorkers === true,
|
|
2053
1901
|
logger
|
|
2054
1902
|
});
|
|
2055
1903
|
const maxSkipThreshold = parseInt(process.env.MAX_SKIP_THRESHOLD ?? "", 10);
|
|
@@ -2057,7 +1905,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2057
1905
|
if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
|
|
2058
1906
|
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = resolveReactorFeatureFlags(process.env);
|
|
2059
1907
|
if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
|
|
2060
|
-
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);
|
|
2061
1909
|
if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
|
|
2062
1910
|
const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
|
|
2063
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) : [];
|
|
@@ -2214,12 +2062,15 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2214
2062
|
const apiLogger = logger.child(["reactor-api"]);
|
|
2215
2063
|
let pgliteFactory;
|
|
2216
2064
|
if (readModelPgliteDir && readModelPgliteMajor !== null) {
|
|
2217
|
-
const
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
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
|
|
2222
2072
|
});
|
|
2073
|
+
pgliteFactory = (connectionString) => openReadStore(connectionString ?? readModelPgliteDir);
|
|
2223
2074
|
}
|
|
2224
2075
|
const api = await initializeAndStartAPI(initializeClient, {
|
|
2225
2076
|
port: serverPort,
|
|
@@ -2387,8 +2238,10 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2387
2238
|
throw error;
|
|
2388
2239
|
}
|
|
2389
2240
|
}
|
|
2241
|
+
const stopCatchUpLoad = ownedReactorModule ? feedCatchUpPriority(catchUpPriority, api.httpServer) : () => {};
|
|
2390
2242
|
let apiDrained;
|
|
2391
2243
|
const drainApi = () => apiDrained ??= (async () => {
|
|
2244
|
+
stopCatchUpLoad();
|
|
2392
2245
|
if (pluginHost) await pluginHost.observe("onShutdown");
|
|
2393
2246
|
await privacy?.stop();
|
|
2394
2247
|
await workflowsRetry?.stop();
|
|
@@ -2499,6 +2352,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2499
2352
|
})(),
|
|
2500
2353
|
mcpEnabled: options.mcp !== false,
|
|
2501
2354
|
inspectionEnabled: options.inspection !== false,
|
|
2355
|
+
inspector: api.inspection?.inspector,
|
|
2502
2356
|
renown,
|
|
2503
2357
|
port: serverPort,
|
|
2504
2358
|
shutdown
|
|
@@ -2546,6 +2400,10 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2546
2400
|
featureFlags,
|
|
2547
2401
|
option: options.inspection
|
|
2548
2402
|
});
|
|
2403
|
+
options.pgliteWorkers = await resolvePgliteWorkersEnabled({
|
|
2404
|
+
featureFlags,
|
|
2405
|
+
option: options.pgliteWorkers
|
|
2406
|
+
});
|
|
2549
2407
|
const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
|
|
2550
2408
|
options.identity = {
|
|
2551
2409
|
...options.identity,
|
|
@@ -2556,6 +2414,7 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2556
2414
|
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
|
|
2557
2415
|
MCP_ENABLED: options.mcp,
|
|
2558
2416
|
INSPECTION_ENABLED: options.inspection,
|
|
2417
|
+
PH_PGLITE_WORKERS: options.pgliteWorkers,
|
|
2559
2418
|
PH_WORKFLOWS_ENABLED: options.workflows?.enabled
|
|
2560
2419
|
}, null, 2));
|
|
2561
2420
|
let renown = null;
|
|
@@ -2575,8 +2434,30 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2575
2434
|
}
|
|
2576
2435
|
};
|
|
2577
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
|
+
}
|
|
2578
2459
|
//#endregion
|
|
2579
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 };
|
|
2580
2461
|
|
|
2581
|
-
//# sourceMappingURL=server-
|
|
2582
|
-
//# debugId=
|
|
2462
|
+
//# sourceMappingURL=server-CJjK7WpR.mjs.map
|
|
2463
|
+
//# debugId=23ac9e84-b25f-5218-b443-313ef3078eee
|