@powerhousedao/switchboard 6.2.3-dev.77 → 6.2.3-dev.79
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-auth-config.test.d.ts +2 -0
- package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-helpers.d.ts +5 -0
- package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
- package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
- package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
- package/.tsbuild/test/config-from-env.test.d.ts +2 -0
- package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
- package/.tsbuild/test/config-merge.test.d.ts +2 -0
- package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
- package/.tsbuild/test/config-schema.test.d.ts +2 -0
- package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
- package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
- package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
- package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
- package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +56 -0
- package/README.md +9 -5
- package/dist/boot.d.mts +8 -0
- package/dist/boot.d.mts.map +1 -1
- package/dist/boot.mjs +22 -16
- package/dist/boot.mjs.map +1 -1
- package/dist/config/from-env.d.mts +15 -0
- package/dist/config/from-env.d.mts.map +1 -0
- package/dist/config/from-env.mjs +4 -0
- package/dist/config/schema.d.mts +3 -0
- package/dist/config/schema.mjs +4 -0
- package/dist/from-env-BO0n9R02.mjs +401 -0
- package/dist/from-env-BO0n9R02.mjs.map +1 -0
- package/dist/index.mjs +34 -38
- package/dist/index.mjs.map +1 -1
- package/dist/migrate.mjs +2 -2
- package/dist/{plugin-host-BBqojyyY.d.mts → plugin-host-C1sYEm8g.d.mts} +4 -1
- package/dist/plugin-host-C1sYEm8g.d.mts.map +1 -0
- package/dist/plugins/attachments.d.mts +3 -3
- package/dist/plugins/attachments.mjs +3 -3
- package/dist/plugins/mcp.d.mts +1 -1
- package/dist/plugins/privacy.d.mts +1 -1
- package/dist/plugins/privacy.mjs +3 -3
- package/dist/plugins/workflows.d.mts +1 -1
- package/dist/plugins/workflows.mjs +3 -3
- package/dist/privacy-BO8Q25xI.mjs +44 -0
- package/dist/privacy-BO8Q25xI.mjs.map +1 -0
- package/dist/{privacy-BsFl7GzK.mjs → privacy-DxIJGH4P.mjs} +14 -41
- package/dist/privacy-DxIJGH4P.mjs.map +1 -0
- package/dist/renown-layers-COZsrGQT.mjs +40 -0
- package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
- package/dist/schema-0g_QdOWn.mjs +267 -0
- package/dist/schema-0g_QdOWn.mjs.map +1 -0
- package/dist/schema-ivUWPQOn.d.mts +202 -0
- package/dist/schema-ivUWPQOn.d.mts.map +1 -0
- package/dist/{server-BkL_NyGG.mjs → server-CtGBZlTg.mjs} +239 -399
- package/dist/server-CtGBZlTg.mjs.map +1 -0
- package/dist/server.d.mts +54 -13
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +5 -4
- package/dist/{utils-CTtD7Oti.mjs → utils-BbV_nodR.mjs} +23 -20
- package/dist/utils-BbV_nodR.mjs.map +1 -0
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +3 -3
- package/dist/{reactor-feature-flags-BtWVQDt6.mjs → worker-pool-BWHBLBJd.mjs} +12 -32
- package/dist/worker-pool-BWHBLBJd.mjs.map +1 -0
- package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -1
- package/dist/{workflows-fsBcElEi.mjs → workflows-QY9Y2eoD.mjs} +5 -16
- package/dist/workflows-QY9Y2eoD.mjs.map +1 -0
- package/package.json +29 -19
- package/test/attachment-reference-read-model.test.ts +22 -19
- package/test/attachments/download-target.test.ts +29 -19
- package/test/attachments/service-config.test.ts +28 -16
- package/test/boot-auth-config.test.ts +109 -0
- package/test/boot-create-signature-policy.test.ts +15 -13
- package/test/boot-env-isolation.test.ts +2 -2
- package/test/boot-helpers.ts +18 -0
- package/test/boot-inspection-enabled.test.ts +16 -26
- package/test/boot-mcp-enabled.test.ts +15 -26
- package/test/boot-port-zero.test.ts +101 -0
- package/test/boot-preconditions.test.ts +51 -0
- package/test/boot-privacy.test.ts +12 -23
- package/test/boot-unsupported-stored-documents.test.ts +10 -9
- package/test/boot-without-renown.test.ts +11 -9
- package/test/boot-without-require-signatures.test.ts +12 -10
- package/test/boot-worker-trust-policy.test.ts +11 -10
- package/test/boot-workflow-singleton-conflict.test.ts +11 -9
- package/test/boot-workflow-singleton-retry.test.ts +12 -23
- package/test/config-from-env.test.ts +758 -0
- package/test/config-merge.test.ts +215 -0
- package/test/config-schema.test.ts +128 -0
- package/test/default-drive-protocol-versions.test.ts +78 -0
- package/test/pglite-storage-dirs.test.ts +24 -14
- package/test/pglite-store.test.ts +16 -63
- package/test/plugin-presence.test.ts +27 -34
- package/test/renown-storage-path.test.ts +9 -8
- package/test/shutdown.test.ts +22 -22
- package/test/two-switchboards.test.ts +146 -0
- package/test/workflow-runtime.test.ts +12 -69
- package/tsdown.config.ts +2 -0
- package/vitest.config.ts +2 -0
- package/.tsbuild/test/inspection-flag.test.d.ts +0 -2
- package/.tsbuild/test/inspection-flag.test.d.ts.map +0 -1
- package/.tsbuild/test/mcp-flag.test.d.ts +0 -2
- package/.tsbuild/test/mcp-flag.test.d.ts.map +0 -1
- package/dist/plugin-host-BBqojyyY.d.mts.map +0 -1
- package/dist/privacy-BsFl7GzK.mjs.map +0 -1
- package/dist/reactor-feature-flags-BtWVQDt6.mjs.map +0 -1
- package/dist/server-BkL_NyGG.mjs.map +0 -1
- package/dist/utils-CTtD7Oti.mjs.map +0 -1
- package/dist/workflows-fsBcElEi.mjs.map +0 -1
- package/test/inspection-flag.test.ts +0 -62
- package/test/mcp-flag.test.ts +0 -56
|
@@ -1,110 +1,43 @@
|
|
|
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]="
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
|
|
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]="adb8b57f-cca7-5667-a44f-f042b16d51a1")}catch(e){}}();
|
|
3
|
+
import { a as loadNodeFsClass, c as openForVerify, d as ATTACHMENT_URL_SIGNING_SECRET_ENV, f as resolveAttachmentUrlSigning, i as isSupportedMajor, l as pgliteModuleSpec, n as StoredDocumentsRefusedError, o as loadPGliteModule, r as resolveUnsupportedStoredDocuments, s as loadPgDump, t as switchboardConfigFromEnv, u as readPgVersionFile } from "./from-env-BO0n9R02.mjs";
|
|
4
|
+
import { a as resolveWorkerModelSources, l as resolveProjectionWorkerOptions, n as keepImportableSources, o as resolveWorkerPoolOptions, p as workerPoolIssues, s as assertProjectionWorkerSupported, t as buildWorkerDbConfig } from "./worker-pool-BWHBLBJd.mjs";
|
|
6
5
|
import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { n as resolvePrivacy, r as startPrivacy } from "./privacy-DxIJGH4P.mjs";
|
|
7
|
+
import { i as switchboardConfigSchema, o as mergeSwitchboardConfig } from "./schema-0g_QdOWn.mjs";
|
|
8
|
+
import { a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as triggerFatalShutdown, h as installFatalErrorShutdown, l as assertWorkflowPackageLoadable, m as workflowSingletonLossHandler, p as retryWorkflowSingleton, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-QY9Y2eoD.mjs";
|
|
9
|
+
import { t as privacyPlugin } from "./privacy-BO8Q25xI.mjs";
|
|
10
|
+
import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
|
|
11
|
+
import { n as reactorFeatureFlagsOf, t as renownLayers } from "./renown-layers-COZsrGQT.mjs";
|
|
12
|
+
import { n as addDefaultReactorDrive, t as addDefaultDrive } from "./utils-BbV_nodR.mjs";
|
|
9
13
|
import { createRequire, register } from "node:module";
|
|
10
14
|
import { metrics, trace } from "@opentelemetry/api";
|
|
11
15
|
import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
|
|
12
16
|
import * as Sentry from "@sentry/node";
|
|
13
17
|
import { childLogger, setLogLevel } from "document-model";
|
|
14
|
-
import dotenv from "dotenv";
|
|
15
|
-
import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
16
18
|
import { getConfig } from "@powerhousedao/config/node";
|
|
19
|
+
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, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
|
|
20
|
+
import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
|
|
21
|
+
import { DEFAULT_PGLITE_WORKER_MEMORY_MB, PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, disableWasmWrapperTiering, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteMaintenance, syncTree } from "@powerhousedao/reactor-api/pglite-node";
|
|
22
|
+
import "@powerhousedao/shared/document-model";
|
|
17
23
|
import fs, { promises } from "node:fs";
|
|
18
24
|
import path, { join, resolve } from "node:path";
|
|
19
|
-
import {
|
|
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";
|
|
25
|
+
import { z } from "zod";
|
|
22
26
|
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";
|
|
24
27
|
import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
25
28
|
import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
|
|
26
|
-
import { DriveNodeView, NodeProcessor, ReactorDriveClient } from "@powerhousedao/reactor-drive";
|
|
29
|
+
import { DriveNodeView, NodeProcessor, REACTOR_DRIVE_DOCUMENT_TYPE, ReactorDriveClient, createReactorDriveWriteStrategy } from "@powerhousedao/reactor-drive";
|
|
27
30
|
import { REACTOR_DRIVE_SUBGRAPH_NAME, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive/subgraph";
|
|
28
31
|
import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
|
|
32
|
+
import dotenv from "dotenv";
|
|
29
33
|
import { Kysely, PostgresDialect, sql } from "kysely";
|
|
30
34
|
import net from "node:net";
|
|
31
35
|
import path$1 from "path";
|
|
32
36
|
import { Pool } from "pg";
|
|
33
37
|
import { Readable } from "node:stream";
|
|
34
|
-
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
35
|
-
import { z } from "zod";
|
|
36
38
|
import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
|
|
37
|
-
import { EnvVarProvider } from "@openfeature/env-var-provider";
|
|
38
|
-
import { OpenFeature } from "@openfeature/server-sdk";
|
|
39
|
-
import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
40
39
|
import { defaultStoreDirs, resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
|
|
41
|
-
|
|
42
|
-
const SUPPORTED_PG_MAJORS = [16, 17];
|
|
43
|
-
async function readPgVersionFile(dataDir) {
|
|
44
|
-
try {
|
|
45
|
-
const raw = await promises.readFile(path.join(dataDir, "PG_VERSION"), "utf8");
|
|
46
|
-
const major = parseInt(raw.trim(), 10);
|
|
47
|
-
return Number.isFinite(major) ? major : null;
|
|
48
|
-
} catch {
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
function isSupportedMajor(major) {
|
|
53
|
-
return SUPPORTED_PG_MAJORS.includes(major);
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Parses the `PH_FORCE_PG_VERSION` env var. Returns the validated major, or
|
|
57
|
-
* `null` when the var is unset/empty. Throws on any value that is not a
|
|
58
|
-
* supported major — invalid configuration must fail before the server starts
|
|
59
|
-
* touching disk.
|
|
60
|
-
*/
|
|
61
|
-
function parseForcePgVersion(raw) {
|
|
62
|
-
if (raw === void 0 || raw.trim() === "") return null;
|
|
63
|
-
const parsed = Number(raw);
|
|
64
|
-
if (Number.isInteger(parsed) && isSupportedMajor(parsed)) return parsed;
|
|
65
|
-
throw new Error(`PH_FORCE_PG_VERSION must be one of: ${SUPPORTED_PG_MAJORS.join(", ")} (got: ${raw})`);
|
|
66
|
-
}
|
|
67
|
-
async function loadPGliteModule(major) {
|
|
68
|
-
if (major === 16) return await import("pglite-legacy-02");
|
|
69
|
-
return import("@electric-sql/pglite");
|
|
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
|
-
}
|
|
90
|
-
/** The stock NodeFS class of the PGlite module that opens `major` dirs. */
|
|
91
|
-
async function loadNodeFsClass(major) {
|
|
92
|
-
if (major === 16) return (await import("pglite-legacy-02/nodefs")).NodeFS;
|
|
93
|
-
return (await import("@electric-sql/pglite/nodefs")).NodeFS;
|
|
94
|
-
}
|
|
95
|
-
/** Opens a converted dir over stock NodeFS so the conversion can check it. */
|
|
96
|
-
async function openForVerify(major, dataDir) {
|
|
97
|
-
if (!isSupportedMajor(major)) throw new Error(`Cannot verify PGlite data dir ${dataDir}: PG_VERSION=${major} is not supported (expected one of ${SUPPORTED_PG_MAJORS.join(", ")})`);
|
|
98
|
-
const [{ PGlite }, NodeFS] = await Promise.all([loadPGliteModule(major), loadNodeFsClass(major)]);
|
|
99
|
-
const pg = new PGlite({ fs: new NodeFS(dataDir) });
|
|
100
|
-
await pg.waitReady;
|
|
101
|
-
return pg;
|
|
102
|
-
}
|
|
103
|
-
async function loadPgDump(major) {
|
|
104
|
-
if (major === 16) return (await import("pglite-tools-legacy-02/pg_dump")).pgDump;
|
|
105
|
-
return (await import("@electric-sql/pglite-tools/pg_dump")).pgDump;
|
|
106
|
-
}
|
|
107
|
-
//#endregion
|
|
40
|
+
import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
108
41
|
//#region src/profiler.ts
|
|
109
42
|
let started = false;
|
|
110
43
|
async function initProfilerFromEnv(env) {
|
|
@@ -686,25 +619,14 @@ const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 604800;
|
|
|
686
619
|
* fetchable by anyone holding the link. Minutes are enough to open a file;
|
|
687
620
|
* days are only enough to lose control of it.
|
|
688
621
|
*
|
|
689
|
-
* A deployment that needs longer sets
|
|
690
|
-
* still bounded by the
|
|
622
|
+
* A deployment that needs longer sets `attachments.downloadTargetMaxTtlSeconds`
|
|
623
|
+
* (ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS at the edge), still bounded by the
|
|
624
|
+
* signing ceiling above.
|
|
691
625
|
*/
|
|
692
626
|
const DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;
|
|
693
|
-
/**
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
* Anything unparseable falls back to the default rather than to the maximum:
|
|
697
|
-
* a typo must not quietly widen the window it was meant to narrow.
|
|
698
|
-
*/
|
|
699
|
-
function downloadTargetTtlCapSeconds() {
|
|
700
|
-
const configured = process.env.ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS;
|
|
701
|
-
if (configured === void 0) return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
|
|
702
|
-
const parsed = Number(configured);
|
|
703
|
-
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
704
|
-
logger$2.warn(`Ignoring invalid ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS="${configured}" (expected a positive integer number of seconds) — using ${DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS}`);
|
|
705
|
-
return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
|
|
706
|
-
}
|
|
707
|
-
return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
|
|
627
|
+
/** A configured ceiling, bounded by the signing maximum; unset is the default. */
|
|
628
|
+
function downloadTargetTtlCapSeconds(configured) {
|
|
629
|
+
return configured === void 0 ? DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS : Math.min(configured, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
|
|
708
630
|
}
|
|
709
631
|
/**
|
|
710
632
|
* Returns the single `documentId` query value, or null when it is missing,
|
|
@@ -734,8 +656,7 @@ function extractSingleDocumentId(req) {
|
|
|
734
656
|
* configured with, which would make the ceiling something a client opts out of
|
|
735
657
|
* by saying nothing.
|
|
736
658
|
*/
|
|
737
|
-
function extractExpiresIn(req) {
|
|
738
|
-
const cap = downloadTargetTtlCapSeconds();
|
|
659
|
+
function extractExpiresIn(req, cap) {
|
|
739
660
|
if (!req.url) return cap;
|
|
740
661
|
let url;
|
|
741
662
|
try {
|
|
@@ -824,7 +745,7 @@ function requestBaseUrl(req) {
|
|
|
824
745
|
if (!host) return null;
|
|
825
746
|
return `${proto}://${host}`;
|
|
826
747
|
}
|
|
827
|
-
function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner) {
|
|
748
|
+
function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner, ttlCapSeconds = downloadTargetTtlCapSeconds(void 0)) {
|
|
828
749
|
return async (req, res, _body, actor) => {
|
|
829
750
|
res.setHeader("Cache-Control", "no-store");
|
|
830
751
|
const hash = extractParam(req, "hash");
|
|
@@ -837,7 +758,7 @@ function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner) {
|
|
|
837
758
|
sendError(res, 400, "documentId is required exactly once as a non-empty query parameter");
|
|
838
759
|
return;
|
|
839
760
|
}
|
|
840
|
-
const expiresIn = extractExpiresIn(req);
|
|
761
|
+
const expiresIn = extractExpiresIn(req, ttlCapSeconds);
|
|
841
762
|
if (expiresIn === "invalid") {
|
|
842
763
|
sendError(res, 400, "expiresIn must be a single positive integer number of seconds");
|
|
843
764
|
return;
|
|
@@ -915,76 +836,26 @@ function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner) {
|
|
|
915
836
|
};
|
|
916
837
|
}
|
|
917
838
|
//#endregion
|
|
918
|
-
//#region src/attachments/url-signer.ts
|
|
919
|
-
const ATTACHMENT_URL_SIGNING_SECRET_ENV = "PH_ATTACHMENT_URL_SIGNING_SECRET";
|
|
920
|
-
const MIN_SECRET_LENGTH = 32;
|
|
921
|
-
const EXPIRES_PATTERN = /^[1-9]\d{0,15}$/;
|
|
922
|
-
const SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
923
|
-
var AttachmentUrlSigner = class {
|
|
924
|
-
secret;
|
|
925
|
-
now;
|
|
926
|
-
constructor(secret, now = Date.now) {
|
|
927
|
-
this.secret = secret;
|
|
928
|
-
this.now = now;
|
|
929
|
-
}
|
|
930
|
-
sign(hash, documentId, ttlSeconds) {
|
|
931
|
-
const expires = Math.floor(this.now() / 1e3) + ttlSeconds;
|
|
932
|
-
return {
|
|
933
|
-
query: new URLSearchParams({
|
|
934
|
-
documentId,
|
|
935
|
-
expires: String(expires),
|
|
936
|
-
signature: this.mac(hash, documentId, String(expires))
|
|
937
|
-
}).toString(),
|
|
938
|
-
expiresAtUtc: (/* @__PURE__ */ new Date(expires * 1e3)).toISOString()
|
|
939
|
-
};
|
|
940
|
-
}
|
|
941
|
-
verify(hash, documentId, expires, signature) {
|
|
942
|
-
if (!EXPIRES_PATTERN.test(expires) || !SIGNATURE_PATTERN.test(signature)) return false;
|
|
943
|
-
if (Number(expires) * 1e3 <= this.now()) return false;
|
|
944
|
-
const expected = Buffer.from(this.mac(hash, documentId, expires));
|
|
945
|
-
const presented = Buffer.from(signature);
|
|
946
|
-
return expected.length === presented.length && timingSafeEqual(expected, presented);
|
|
947
|
-
}
|
|
948
|
-
mac(hash, documentId, expires) {
|
|
949
|
-
return createHmac("sha256", this.secret).update(JSON.stringify([
|
|
950
|
-
"attachment-download/v1",
|
|
951
|
-
hash,
|
|
952
|
-
documentId,
|
|
953
|
-
expires
|
|
954
|
-
])).digest("base64url");
|
|
955
|
-
}
|
|
956
|
-
};
|
|
957
|
-
function resolveAttachmentUrlSigning(env = process.env) {
|
|
958
|
-
const secret = env[ATTACHMENT_URL_SIGNING_SECRET_ENV];
|
|
959
|
-
if (secret !== void 0) {
|
|
960
|
-
if (secret.trim() !== secret || secret.length < MIN_SECRET_LENGTH) throw new Error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} must be at least ${MIN_SECRET_LENGTH} characters with no leading or trailing whitespace`);
|
|
961
|
-
return {
|
|
962
|
-
status: "configured",
|
|
963
|
-
signer: new AttachmentUrlSigner(secret)
|
|
964
|
-
};
|
|
965
|
-
}
|
|
966
|
-
if (env.NODE_ENV === "production") return { status: "unconfigured" };
|
|
967
|
-
return {
|
|
968
|
-
status: "ephemeral",
|
|
969
|
-
signer: new AttachmentUrlSigner(randomBytes(32))
|
|
970
|
-
};
|
|
971
|
-
}
|
|
972
|
-
//#endregion
|
|
973
839
|
//#region src/attachments/index.ts
|
|
974
840
|
const logger$1 = childLogger(["switchboard", "attachments"]);
|
|
975
841
|
function registerAttachmentRoutes(api, options = {}) {
|
|
976
842
|
const { attachments, attachmentAccess } = api;
|
|
977
|
-
const
|
|
843
|
+
const { config } = options;
|
|
844
|
+
const urlSigner = options.urlSigner === void 0 ? signerFromEnvironment(attachments.backend?.kind ?? "filesystem", {
|
|
845
|
+
[ATTACHMENT_URL_SIGNING_SECRET_ENV]: config?.urlSigningSecret,
|
|
846
|
+
NODE_ENV: process.env.NODE_ENV
|
|
847
|
+
}) : options.urlSigner;
|
|
848
|
+
const ttlCapSeconds = downloadTargetTtlCapSeconds(config?.downloadTargetMaxTtlSeconds);
|
|
978
849
|
mountAuthenticatedNodeRoute(api, "POST", "/attachments/reservations", makeReserveHandler(attachments));
|
|
979
850
|
mountAuthenticatedNodeRoute(api, "GET", "/attachments/reservations/:reservationId", makeGetReservationHandler(attachments));
|
|
980
851
|
mountAuthenticatedNodeRoute(api, "DELETE", "/attachments/reservations/:reservationId", makeDeleteReservationHandler(attachments));
|
|
981
852
|
mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments), { rawBody: true });
|
|
982
853
|
mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
983
|
-
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
854
|
+
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner, ttlCapSeconds), { allowAnonymous: true });
|
|
984
855
|
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
985
856
|
}
|
|
986
|
-
function signerFromEnvironment(backend) {
|
|
987
|
-
const signing = resolveAttachmentUrlSigning();
|
|
857
|
+
function signerFromEnvironment(backend, env) {
|
|
858
|
+
const signing = resolveAttachmentUrlSigning(env);
|
|
988
859
|
if (signing.status === "unconfigured") {
|
|
989
860
|
if (backend === "filesystem") logger$1.error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`);
|
|
990
861
|
return null;
|
|
@@ -1084,43 +955,20 @@ const attachmentsPluginConfigSchema = z.strictObject({});
|
|
|
1084
955
|
* onReadModelsRegistering step in R2 step 2; until then it registers on both
|
|
1085
956
|
* paths (a dormant read model when the plugin is absent, harmless).
|
|
1086
957
|
*
|
|
1087
|
-
* Inputs (carve map): api (routes),
|
|
1088
|
-
*
|
|
958
|
+
* Inputs (carve map): api (routes), config.attachments (signing, TTL),
|
|
959
|
+
* options.attachmentServiceUrl / https + serverPort + renown (service config).
|
|
1089
960
|
*/
|
|
1090
961
|
const attachmentsPlugin = {
|
|
1091
962
|
name: "switchboard-attachments",
|
|
1092
963
|
appliesTo: "switchboard",
|
|
1093
964
|
configSchema: attachmentsPluginConfigSchema,
|
|
1094
965
|
hooks: { onHttpMounting: (ctx) => {
|
|
1095
|
-
registerAttachmentRoutes(ctx.api);
|
|
966
|
+
registerAttachmentRoutes(ctx.api, { config: ctx.config?.attachments });
|
|
1096
967
|
ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
|
|
1097
968
|
} }
|
|
1098
969
|
};
|
|
1099
970
|
//#endregion
|
|
1100
971
|
//#region src/plugin-host.mts
|
|
1101
|
-
/**
|
|
1102
|
-
* R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:
|
|
1103
|
-
* uniform-runners-plan/rewire/r2-carve-map.md). Behind
|
|
1104
|
-
* FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing
|
|
1105
|
-
* inline path byte-identically; flag on, the five subsystems run as built-in
|
|
1106
|
-
* plugins through these hook moments. Subsystems carve one per commit; until
|
|
1107
|
-
* a subsystem is carved, its inline code runs on BOTH paths and its plugin
|
|
1108
|
-
* twin does not exist.
|
|
1109
|
-
*
|
|
1110
|
-
* Hook vocabulary (SwitchboardHooks), anchored to the boot spine:
|
|
1111
|
-
* - transformServerOptions — after option/flag resolution, before anything opens
|
|
1112
|
-
* - onReadModelsRegistering — inside reactor construction (build-time read models)
|
|
1113
|
-
* - onHttpMounting — api exists; routes mount here
|
|
1114
|
-
* - onSubgraphsRegistering — push into lateSubgraphs before the drain
|
|
1115
|
-
* - onReactorReady — client + graphqlManager destructured
|
|
1116
|
-
* - onDrivesReady — after core drive seeding / remote attachment
|
|
1117
|
-
* - onShutdown — first in the subsystem-ordered teardown
|
|
1118
|
-
*/
|
|
1119
|
-
const PLUGIN_HOST_FLAG = "FEATURE_PLUGIN_HOST_ENABLED";
|
|
1120
|
-
function isPluginHostEnabled(env = process.env) {
|
|
1121
|
-
const value = env[PLUGIN_HOST_FLAG]?.trim().toLowerCase();
|
|
1122
|
-
return value === "1" || value === "true";
|
|
1123
|
-
}
|
|
1124
972
|
/** Built-in plugins, pre-listed (the default composition until host.js
|
|
1125
973
|
* entries map in R2 step 2). Subsystems join as R2 carves them. */
|
|
1126
974
|
function builtinSwitchboardPlugins() {
|
|
@@ -1200,46 +1048,6 @@ function createSwitchboardPluginHost(ctx, resolved) {
|
|
|
1200
1048
|
};
|
|
1201
1049
|
}
|
|
1202
1050
|
//#endregion
|
|
1203
|
-
//#region src/inspection-throttle.mts
|
|
1204
|
-
const NAME = "PH_INSPECTION_CALLS_PER_MINUTE";
|
|
1205
|
-
/** Unset keeps reactor-api's default; an invalid value fails boot. */
|
|
1206
|
-
function inspectionThrottleFromEnv(env) {
|
|
1207
|
-
const callsPerMinute = parseNonNegativeInt(env[NAME], NAME);
|
|
1208
|
-
if (callsPerMinute === void 0) return {};
|
|
1209
|
-
if (callsPerMinute < 1) throw new Error(`${NAME} must be at least 1, got "${env[NAME]}"`);
|
|
1210
|
-
return { callsPerMinute };
|
|
1211
|
-
}
|
|
1212
|
-
//#endregion
|
|
1213
|
-
//#region src/feature-flags.ts
|
|
1214
|
-
async function initFeatureFlags() {
|
|
1215
|
-
const provider = new EnvVarProvider();
|
|
1216
|
-
await OpenFeature.setProviderAndWait(provider);
|
|
1217
|
-
return OpenFeature.getClient();
|
|
1218
|
-
}
|
|
1219
|
-
//#endregion
|
|
1220
|
-
//#region src/inspection-flag.mts
|
|
1221
|
-
/** The env var and OpenFeature flag key that can keep the inspection subgraph unmounted. */
|
|
1222
|
-
const INSPECTION_ENABLED = "INSPECTION_ENABLED";
|
|
1223
|
-
/** Whether to mount `/graphql/inspection`. A host's `inspection: false` wins;
|
|
1224
|
-
* otherwise INSPECTION_ENABLED decides, falling back to the host's option and
|
|
1225
|
-
* then INSPECTION_ENABLED_DEFAULT. */
|
|
1226
|
-
async function resolveInspectionEnabled({ featureFlags, option }) {
|
|
1227
|
-
if (option === false) return false;
|
|
1228
|
-
return featureFlags.getBooleanValue(INSPECTION_ENABLED, option ?? true);
|
|
1229
|
-
}
|
|
1230
|
-
//#endregion
|
|
1231
|
-
//#region src/mcp-flag.mts
|
|
1232
|
-
/** The env var and OpenFeature flag key that can keep the MCP server unmounted. */
|
|
1233
|
-
const MCP_ENABLED = "MCP_ENABLED";
|
|
1234
|
-
/** Whether to mount the MCP server at `/mcp`. On unless the host passes
|
|
1235
|
-
* `mcp: false` or MCP_ENABLED is "false": the env var can turn a host's MCP
|
|
1236
|
-
* off, never on, so a deployment that serves no MCP client can close the
|
|
1237
|
-
* endpoint without the bin growing a flag of its own. */
|
|
1238
|
-
async function resolveMcpEnabled({ featureFlags, option }) {
|
|
1239
|
-
if (option === false) return false;
|
|
1240
|
-
return featureFlags.getBooleanValue(MCP_ENABLED, true);
|
|
1241
|
-
}
|
|
1242
|
-
//#endregion
|
|
1243
1051
|
//#region src/pglite-dialect.ts
|
|
1244
1052
|
/** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
|
|
1245
1053
|
function reactorPgliteDialectOptions(logger, proc) {
|
|
@@ -1445,14 +1253,6 @@ async function runPglitePreflight(options) {
|
|
|
1445
1253
|
}
|
|
1446
1254
|
//#endregion
|
|
1447
1255
|
//#region src/pglite-store.mts
|
|
1448
|
-
/** The env var and OpenFeature flag key that moves each PGlite store into its own worker thread. */
|
|
1449
|
-
const PH_PGLITE_WORKERS = "PH_PGLITE_WORKERS";
|
|
1450
|
-
/** Whether each PGlite store opens in its own worker thread: the host's
|
|
1451
|
-
* option, else PH_PGLITE_WORKERS ("true"/"false"), else PGLITE_WORKERS_DEFAULT. */
|
|
1452
|
-
async function resolvePgliteWorkersEnabled({ featureFlags, option }) {
|
|
1453
|
-
if (option !== void 0) return option;
|
|
1454
|
-
return featureFlags.getBooleanValue(PH_PGLITE_WORKERS, true);
|
|
1455
|
-
}
|
|
1456
1256
|
function onPgliteAbort(logger, what, proc) {
|
|
1457
1257
|
if (!triggerFatalShutdown("PGlite aborted", what, proc)) logger.error("PGlite aborted: @error", what);
|
|
1458
1258
|
}
|
|
@@ -1483,31 +1283,26 @@ function terminateOnPoisoned(options, store) {
|
|
|
1483
1283
|
}
|
|
1484
1284
|
};
|
|
1485
1285
|
}
|
|
1486
|
-
function pgliteFsyncFor(major, dir, logger) {
|
|
1487
|
-
const wanted = resolvePgliteFsync(process.env);
|
|
1286
|
+
function pgliteFsyncFor(wanted, major, dir, logger) {
|
|
1488
1287
|
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.`);
|
|
1489
1288
|
return wanted;
|
|
1490
1289
|
}
|
|
1491
|
-
/** VACUUM FULL
|
|
1492
|
-
function
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
const maxDefer = ms(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);
|
|
1500
|
-
return {
|
|
1501
|
-
...quiet === void 0 ? {} : { vacuumFullQuietMs: quiet },
|
|
1502
|
-
...maxDefer === void 0 ? {} : { vacuumFullMaxDeferMs: maxDefer }
|
|
1503
|
-
};
|
|
1290
|
+
/** The VACUUM FULL settings a config asks for, with the env parser's rules. */
|
|
1291
|
+
function vacuumFullTimingOf(vacuumFull) {
|
|
1292
|
+
return resolvePgliteMaintenance({
|
|
1293
|
+
PH_PGLITE_VACUUM_FULL: vacuumFull.mode,
|
|
1294
|
+
PH_PGLITE_VACUUM_FULL_ABOVE_MB: vacuumFull.aboveMb?.toString(),
|
|
1295
|
+
PH_PGLITE_VACUUM_FULL_QUIET_MS: vacuumFull.quietMs?.toString(),
|
|
1296
|
+
PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS: vacuumFull.maxDeferMs?.toString()
|
|
1297
|
+
});
|
|
1504
1298
|
}
|
|
1299
|
+
const DEFAULT_MAINTENANCE = { vacuumFullAboveBytes: 0 };
|
|
1505
1300
|
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1506
|
-
async function loadDurableFsFactory(major, logger, proc) {
|
|
1301
|
+
async function loadDurableFsFactory(major, logger, proc, settings = {}) {
|
|
1507
1302
|
const NodeFS = await loadNodeFsClass(major);
|
|
1508
|
-
const timing =
|
|
1303
|
+
const timing = settings.maintenance ?? DEFAULT_MAINTENANCE;
|
|
1509
1304
|
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1510
|
-
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1305
|
+
fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
|
|
1511
1306
|
...timing,
|
|
1512
1307
|
logger,
|
|
1513
1308
|
onAbort: (what) => onPgliteAbort(logger, what, proc)
|
|
@@ -1528,7 +1323,8 @@ async function createPgliteStoreFactory(options) {
|
|
|
1528
1323
|
}
|
|
1529
1324
|
function threadedStoreFactory(options) {
|
|
1530
1325
|
const { label, major, parsers, inMemory, logger, proc } = options;
|
|
1531
|
-
const
|
|
1326
|
+
const settings = options.settings ?? {};
|
|
1327
|
+
const memoryLimitMb = settings.workerMemoryMb ?? DEFAULT_PGLITE_WORKER_MEMORY_MB;
|
|
1532
1328
|
const module = pgliteModuleSpec(major);
|
|
1533
1329
|
return (dir) => {
|
|
1534
1330
|
const store = new ThreadedPGlite({
|
|
@@ -1537,8 +1333,8 @@ function threadedStoreFactory(options) {
|
|
|
1537
1333
|
dataDir: inMemory ? null : dir,
|
|
1538
1334
|
module,
|
|
1539
1335
|
durableFs: inMemory ? null : {
|
|
1540
|
-
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1541
|
-
...
|
|
1336
|
+
fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
|
|
1337
|
+
...settings.maintenance ?? DEFAULT_MAINTENANCE
|
|
1542
1338
|
},
|
|
1543
1339
|
parsers
|
|
1544
1340
|
},
|
|
@@ -1553,7 +1349,7 @@ function threadedStoreFactory(options) {
|
|
|
1553
1349
|
async function mainThreadStoreFactory(options) {
|
|
1554
1350
|
const { label, major, inMemory, logger, proc } = options;
|
|
1555
1351
|
const { PGlite } = await loadPGliteModule(major);
|
|
1556
|
-
const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc);
|
|
1352
|
+
const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc, options.settings);
|
|
1557
1353
|
const base = options.parsers === "utc-timestamps" ? { parsers: PGLITE_UTC_PARSERS } : {};
|
|
1558
1354
|
return (dir) => {
|
|
1559
1355
|
logger.info(`${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`);
|
|
@@ -1568,18 +1364,8 @@ function where(inMemory, dir) {
|
|
|
1568
1364
|
}
|
|
1569
1365
|
//#endregion
|
|
1570
1366
|
//#region src/create-signature-policy.mts
|
|
1571
|
-
/**
|
|
1572
|
-
|
|
1573
|
-
* signer this switchboard cannot write to a v2-required document, so it falls
|
|
1574
|
-
* back to legacy and says so.
|
|
1575
|
-
*/
|
|
1576
|
-
function resolveCreateSignaturePolicy(env, options) {
|
|
1577
|
-
const raw = env.CREATE_SIGNATURE_POLICY?.trim();
|
|
1578
|
-
let policy = DEFAULT_SIGNATURE_POLICY;
|
|
1579
|
-
if (raw) {
|
|
1580
|
-
if (!isSignaturePolicy(raw)) throw new Error(`CREATE_SIGNATURE_POLICY must be "legacy" or "v2-required", got "${raw}"`);
|
|
1581
|
-
policy = raw;
|
|
1582
|
-
}
|
|
1367
|
+
/** The requested policy, or legacy when it needs a signer this switchboard lacks. */
|
|
1368
|
+
function createSignaturePolicyFor(policy, options) {
|
|
1583
1369
|
if (policy === "v2-required" && !options.hasSigner) {
|
|
1584
1370
|
options.logger?.warn("No signer is configured, so new documents are created legacy: a v2-required document refuses the unsigned operations this switchboard would write. Set up an identity (ph login) to create v2-required documents.");
|
|
1585
1371
|
return "legacy";
|
|
@@ -1595,7 +1381,7 @@ const logger = childLogger(["switchboard", "renown"]);
|
|
|
1595
1381
|
* using the same identity established during `ph login`.
|
|
1596
1382
|
*/
|
|
1597
1383
|
async function initRenown(options = {}) {
|
|
1598
|
-
const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL, storagePath =
|
|
1384
|
+
const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL, userDataDir, storagePath = userDataDir ? join(resolvePhDir(void 0, { PH_USER_DATA_DIR: userDataDir }), ".renown.json") : void 0 } = options;
|
|
1599
1385
|
const keyStorage = new NodeKeyStorage(keypairPath, { logger });
|
|
1600
1386
|
const existingKeyPair = await keyStorage.loadKeyPair();
|
|
1601
1387
|
if (!existingKeyPair && requireExisting) throw new Error("No existing keypair found and requireExisting is true. Run \"ph login\" to create one.");
|
|
@@ -1695,32 +1481,6 @@ function ownIdentity(renown) {
|
|
|
1695
1481
|
};
|
|
1696
1482
|
}
|
|
1697
1483
|
//#endregion
|
|
1698
|
-
//#region src/unsupported-stored-documents.mts
|
|
1699
|
-
const MODES = ["refuse", "read-only"];
|
|
1700
|
-
/** From REACTOR_UNSUPPORTED_STORED_DOCUMENTS; `input` wins when defined. */
|
|
1701
|
-
function resolveUnsupportedStoredDocuments(input, env) {
|
|
1702
|
-
if (input !== void 0) return input;
|
|
1703
|
-
const raw = env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS?.trim();
|
|
1704
|
-
if (!raw) return "refuse";
|
|
1705
|
-
if (!MODES.includes(raw)) throw new Error(`REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "${raw}"`);
|
|
1706
|
-
return raw;
|
|
1707
|
-
}
|
|
1708
|
-
/** The reactor refused to start over documents this build does not run. */
|
|
1709
|
-
var StoredDocumentsRefusedError = class extends Error {
|
|
1710
|
-
versions;
|
|
1711
|
-
documents;
|
|
1712
|
-
constructor(cause) {
|
|
1713
|
-
const named = cause.versions.map(({ protocol, version }) => `${protocol} ${version}`).join(", ");
|
|
1714
|
-
super(`Refusing to start: ${cause.documents} stored document(s) require ${named}, which this switchboard does not run. Either start a switchboard build that runs ${named}, or set REACTOR_UNSUPPORTED_STORED_DOCUMENTS=read-only to start with those documents read-only.`, { cause });
|
|
1715
|
-
this.name = "StoredDocumentsRefusedError";
|
|
1716
|
-
this.versions = cause.versions;
|
|
1717
|
-
this.documents = cause.documents;
|
|
1718
|
-
}
|
|
1719
|
-
static isError(error) {
|
|
1720
|
-
return Error.isError(error) && error.name === "StoredDocumentsRefusedError";
|
|
1721
|
-
}
|
|
1722
|
-
};
|
|
1723
|
-
//#endregion
|
|
1724
1484
|
//#region src/store-lock.mts
|
|
1725
1485
|
var StoreInUseError = class extends Error {
|
|
1726
1486
|
dir;
|
|
@@ -1780,12 +1540,17 @@ function acquireStoreLocks(dirs, isPidAlive = isAlive) {
|
|
|
1780
1540
|
//#endregion
|
|
1781
1541
|
//#region src/server.mts
|
|
1782
1542
|
const defaultLogger = childLogger(["switchboard"]);
|
|
1783
|
-
const LogLevel = process.env.LOG_LEVEL || "info";
|
|
1784
|
-
setLogLevel(LogLevel);
|
|
1785
1543
|
if (!isDotenvDisabled()) dotenv.config();
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1544
|
+
/** Process-wide settings an edge applies once, before its first `startSwitchboard`. */
|
|
1545
|
+
function initSwitchboardProcess(options = {}) {
|
|
1546
|
+
setLogLevel(options.logLevel ?? "info");
|
|
1547
|
+
}
|
|
1548
|
+
let httpsHooksRegistered = false;
|
|
1549
|
+
function registerHttpsHooks() {
|
|
1550
|
+
if (httpsHooksRegistered) return;
|
|
1551
|
+
httpsHooksRegistered = true;
|
|
1552
|
+
register(httpsHooksPath, import.meta.url);
|
|
1553
|
+
}
|
|
1789
1554
|
const PORT_FALLBACK_ATTEMPTS = 20;
|
|
1790
1555
|
let flushIntervalWarned = false;
|
|
1791
1556
|
function warnIgnoredFlushInterval(logger) {
|
|
@@ -1794,7 +1559,6 @@ function warnIgnoredFlushInterval(logger) {
|
|
|
1794
1559
|
flushIntervalWarned = true;
|
|
1795
1560
|
logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
|
|
1796
1561
|
}
|
|
1797
|
-
const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
|
|
1798
1562
|
/**
|
|
1799
1563
|
* Attempt to bind a throwaway TCP server to the given port. Resolves true if
|
|
1800
1564
|
* the port is free, false if the OS reports it in use. Any other error is
|
|
@@ -1842,7 +1606,7 @@ function readConfigWorkflowsEnabled(configPath) {
|
|
|
1842
1606
|
}
|
|
1843
1607
|
}
|
|
1844
1608
|
async function resolveServerPort(requested, strictPort, logger) {
|
|
1845
|
-
if (strictPort) return requested;
|
|
1609
|
+
if (requested === 0 || strictPort) return requested;
|
|
1846
1610
|
for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
|
|
1847
1611
|
const candidate = requested + i;
|
|
1848
1612
|
if (await isPortAvailable(candidate)) {
|
|
@@ -1853,7 +1617,7 @@ async function resolveServerPort(requested, strictPort, logger) {
|
|
|
1853
1617
|
return requested;
|
|
1854
1618
|
}
|
|
1855
1619
|
async function createReactorKysely(opts) {
|
|
1856
|
-
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, logger } = opts;
|
|
1620
|
+
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, pgliteSettings, logger } = opts;
|
|
1857
1621
|
if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
|
|
1858
1622
|
const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
|
|
1859
1623
|
const poolSize = hostPoolSize();
|
|
@@ -1876,6 +1640,7 @@ async function createReactorKysely(opts) {
|
|
|
1876
1640
|
parsers: "none",
|
|
1877
1641
|
inMemory,
|
|
1878
1642
|
threaded: pgliteWorkers,
|
|
1643
|
+
settings: pgliteSettings,
|
|
1879
1644
|
logger
|
|
1880
1645
|
}))(reactorPgliteDir);
|
|
1881
1646
|
const dialectOptions = pglite instanceof ThreadedPGlite ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite) : reactorPgliteDialectOptions(logger);
|
|
@@ -1898,7 +1663,7 @@ async function createReactorKysely(opts) {
|
|
|
1898
1663
|
*/
|
|
1899
1664
|
function resolvePgliteStorageDirs(opts) {
|
|
1900
1665
|
const { dbPath, reactorDbUrl, callerReactor } = opts;
|
|
1901
|
-
const defaults = defaultStoreDirs(
|
|
1666
|
+
const defaults = defaultStoreDirs({ PH_USER_DATA_DIR: opts.userDataDir }, opts.phDir);
|
|
1902
1667
|
const readModelPath = dbPath || defaults.readModel;
|
|
1903
1668
|
const reactorPath = reactorDbUrl || defaults.reactor;
|
|
1904
1669
|
const reactorPgliteDir = callerReactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
|
|
@@ -1913,22 +1678,23 @@ function resolvePgliteStorageDirs(opts) {
|
|
|
1913
1678
|
sharedPgliteDir
|
|
1914
1679
|
};
|
|
1915
1680
|
}
|
|
1916
|
-
/**
|
|
1681
|
+
/** The remote attachment service config for switchboard's own `/attachments/*` API; `attachments.serviceUrl` carries PH_SWITCHBOARD_PUBLIC_URL. */
|
|
1917
1682
|
function deriveAttachmentServiceConfig(options, serverPort, renown) {
|
|
1918
1683
|
const protocol = options.https ? "https" : "http";
|
|
1919
1684
|
return {
|
|
1920
|
-
remoteUrl: options.attachmentServiceUrl ??
|
|
1685
|
+
remoteUrl: options.attachmentServiceUrl ?? `${protocol}://localhost:${serverPort}`,
|
|
1921
1686
|
jwtHandler: renown ? async (url) => renown.user ? renown.getBearerToken({
|
|
1922
1687
|
expiresIn: 10,
|
|
1923
1688
|
aud: url
|
|
1924
1689
|
}) : void 0 : void 0
|
|
1925
1690
|
};
|
|
1926
1691
|
}
|
|
1927
|
-
async function initServer(
|
|
1692
|
+
async function initServer(requestedPort, options, config, renown, renownConfig, reportError) {
|
|
1928
1693
|
const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
|
|
1929
|
-
const pluginHost =
|
|
1694
|
+
const pluginHost = config.features.pluginHost ? createSwitchboardPluginHost({
|
|
1930
1695
|
logger,
|
|
1931
1696
|
options,
|
|
1697
|
+
config,
|
|
1932
1698
|
renown
|
|
1933
1699
|
}, options.pluginComposition) : null;
|
|
1934
1700
|
if (pluginHost) {
|
|
@@ -1936,22 +1702,29 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1936
1702
|
options.mcp ??= false;
|
|
1937
1703
|
options.workflows = { enabled: options.workflows?.enabled === true };
|
|
1938
1704
|
}
|
|
1939
|
-
logger.level =
|
|
1940
|
-
const dbPath =
|
|
1941
|
-
const reactorDbUrl =
|
|
1705
|
+
logger.level = config.logLevel;
|
|
1706
|
+
const dbPath = config.storage.readModel.url;
|
|
1707
|
+
const reactorDbUrl = config.storage.reactor.url;
|
|
1708
|
+
const inMemory = config.storage.inMemory;
|
|
1709
|
+
const pgliteSettings = {
|
|
1710
|
+
fsync: config.storage.pglite.fsync,
|
|
1711
|
+
maintenance: vacuumFullTimingOf(config.storage.pglite.vacuumFull),
|
|
1712
|
+
workerMemoryMb: config.storage.pglite.workerMemoryMb
|
|
1713
|
+
};
|
|
1942
1714
|
const { readModelPath, reactorPgliteDir, readModelPgliteDir, pgliteDirs, sharedPgliteDir } = resolvePgliteStorageDirs({
|
|
1943
1715
|
dbPath,
|
|
1944
1716
|
reactorDbUrl,
|
|
1945
|
-
callerReactor: options.reactor !== void 0
|
|
1717
|
+
callerReactor: options.reactor !== void 0,
|
|
1718
|
+
userDataDir: config.storage.userDataDir
|
|
1946
1719
|
});
|
|
1947
1720
|
if (sharedPgliteDir !== null) logger.warn(`The reactor and read-model PGlite stores share one directory (${sharedPgliteDir}): two PGlite instances on one data dir can abort at the first checkpoint and leave the store unopenable. Set PH_REACTOR_DATABASE_URL to a separate directory, or leave dbPath unset for the classic ./.ph/reactor-storage + .ph/read-storage layout.`);
|
|
1948
|
-
if (!
|
|
1721
|
+
if (!inMemory) acquireStoreLocks(pgliteDirs);
|
|
1949
1722
|
warnIgnoredFlushInterval(logger);
|
|
1950
1723
|
const detectedMajors = await runPglitePreflight({
|
|
1951
1724
|
dirs: pgliteDirs,
|
|
1952
1725
|
forcePgVersion: options.forcePgVersion,
|
|
1953
1726
|
migratePglite: options.migratePglite,
|
|
1954
|
-
inMemory
|
|
1727
|
+
inMemory,
|
|
1955
1728
|
logger
|
|
1956
1729
|
});
|
|
1957
1730
|
function resolvePgliteMajorForDir(dir) {
|
|
@@ -1963,8 +1736,8 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1963
1736
|
}
|
|
1964
1737
|
const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
|
|
1965
1738
|
const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
|
|
1966
|
-
const inspectionThrottle =
|
|
1967
|
-
let workerPool = resolveWorkerPoolOptions(options.workerPool,
|
|
1739
|
+
const inspectionThrottle = config.inspection.callsPerMinute === void 0 ? {} : { callsPerMinute: config.inspection.callsPerMinute };
|
|
1740
|
+
let workerPool = resolveWorkerPoolOptions(options.workerPool, {});
|
|
1968
1741
|
if (workerPool && options.reactor) {
|
|
1969
1742
|
logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
|
|
1970
1743
|
workerPool = null;
|
|
@@ -1975,13 +1748,13 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1975
1748
|
workers: workerPool.numWorkers,
|
|
1976
1749
|
projectionWorker: false,
|
|
1977
1750
|
reactorDbUrl,
|
|
1978
|
-
authEnforcement:
|
|
1751
|
+
authEnforcement: config.protocol.featureFlags.authEnforcement,
|
|
1979
1752
|
renownSource: renownConfig.source
|
|
1980
1753
|
}).at(0);
|
|
1981
1754
|
if (issue) throw new Error(issue);
|
|
1982
1755
|
}
|
|
1983
|
-
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments,
|
|
1984
|
-
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker,
|
|
1756
|
+
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, {});
|
|
1757
|
+
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, {});
|
|
1985
1758
|
if (projectionWorker && options.reactor) {
|
|
1986
1759
|
logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
|
|
1987
1760
|
projectionWorker = null;
|
|
@@ -1993,20 +1766,20 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1993
1766
|
const apiRef = { current: void 0 };
|
|
1994
1767
|
let driveNodeView;
|
|
1995
1768
|
const configPath = resolveConfigPath(options.configFile);
|
|
1996
|
-
const
|
|
1997
|
-
const registryUrl = options.registryUrl ??
|
|
1998
|
-
const registryPackages =
|
|
1999
|
-
const dynamicModelLoading = options.dynamicModelLoading
|
|
1769
|
+
const fileConfig = getConfig(configPath);
|
|
1770
|
+
const registryUrl = options.registryUrl ?? fileConfig.packageRegistryUrl;
|
|
1771
|
+
const registryPackages = config.packages.registryPackages;
|
|
1772
|
+
const dynamicModelLoading = options.dynamicModelLoading === true;
|
|
2000
1773
|
let httpLoader;
|
|
2001
1774
|
if (registryUrl) {
|
|
2002
|
-
|
|
2003
|
-
httpLoader = new HttpPackageLoader({
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
if (!packages.includes(name)) packages.push(name);
|
|
1775
|
+
registerHttpsHooks();
|
|
1776
|
+
httpLoader = new HttpPackageLoader({
|
|
1777
|
+
registryUrl,
|
|
1778
|
+
cacheDir: path$1.join(resolvePhDir(void 0, { PH_USER_DATA_DIR: config.storage.userDataDir }), "registry-packages")
|
|
2007
1779
|
});
|
|
1780
|
+
for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
|
|
2008
1781
|
}
|
|
2009
|
-
const registryPackageNames = new Set(
|
|
1782
|
+
const registryPackageNames = new Set(registryPackages.filter(Boolean));
|
|
2010
1783
|
const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
|
|
2011
1784
|
const reactorLogger = logger.child(["reactor"]);
|
|
2012
1785
|
let projectionWorkerFatalFired = false;
|
|
@@ -2017,13 +1790,16 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2017
1790
|
process.kill(process.pid, "SIGTERM");
|
|
2018
1791
|
};
|
|
2019
1792
|
const workflowsEnabled = options.workflows?.enabled === true;
|
|
2020
|
-
const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy,
|
|
1793
|
+
const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, {});
|
|
2021
1794
|
if (workflowsEnabled) {
|
|
2022
1795
|
await assertWorkflowPackageLoadable();
|
|
2023
1796
|
if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
|
|
2024
1797
|
}
|
|
2025
1798
|
let ownedReactorModule;
|
|
2026
|
-
const catchUpPriority = new CatchUpPriority(
|
|
1799
|
+
const catchUpPriority = new CatchUpPriority(config.protocol.catchUpPriority === "dynamic" ? { mode: "dynamic" } : {
|
|
1800
|
+
mode: "fixed",
|
|
1801
|
+
level: config.protocol.catchUpPriority
|
|
1802
|
+
});
|
|
2027
1803
|
let workerModels;
|
|
2028
1804
|
let localRenownRequest;
|
|
2029
1805
|
const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests, readModelDb }) => {
|
|
@@ -2042,17 +1818,18 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2042
1818
|
reactorDbUrl,
|
|
2043
1819
|
reactorPgliteDir,
|
|
2044
1820
|
reactorPgliteMajor,
|
|
2045
|
-
inMemory
|
|
2046
|
-
hostPoolSize: () =>
|
|
1821
|
+
inMemory,
|
|
1822
|
+
hostPoolSize: () => config.workers.hostPoolSize,
|
|
2047
1823
|
pgliteWorkers: options.pgliteWorkers === true,
|
|
1824
|
+
pgliteSettings,
|
|
2048
1825
|
logger
|
|
2049
1826
|
});
|
|
2050
|
-
const maxSkipThreshold =
|
|
2051
|
-
const hasSkipThreshold =
|
|
1827
|
+
const maxSkipThreshold = config.protocol.maxSkipThreshold;
|
|
1828
|
+
const hasSkipThreshold = maxSkipThreshold !== void 0;
|
|
2052
1829
|
if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
|
|
2053
|
-
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } =
|
|
1830
|
+
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = reactorFeatureFlagsOf(config.protocol.featureFlags);
|
|
2054
1831
|
if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
|
|
2055
|
-
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds:
|
|
1832
|
+
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: config.protocol.legacyProcessorIds }).withUnsupportedStoredDocuments(unsupportedStoredDocuments).withCatchUpPriority(catchUpPriority);
|
|
2056
1833
|
if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
|
|
2057
1834
|
const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
|
|
2058
1835
|
const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
|
|
@@ -2067,7 +1844,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2067
1844
|
documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
|
|
2068
1845
|
logger: reactorLogger,
|
|
2069
1846
|
signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
|
|
2070
|
-
createSignaturePolicy:
|
|
1847
|
+
createSignaturePolicy: createSignaturePolicyFor(config.protocol.createSignaturePolicy, {
|
|
2071
1848
|
hasSigner: renown !== null,
|
|
2072
1849
|
logger
|
|
2073
1850
|
}),
|
|
@@ -2122,6 +1899,10 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2122
1899
|
reactorBuilder.withShutdownHook(async () => {
|
|
2123
1900
|
if (apiRef.current) await apiRef.current.dispose();
|
|
2124
1901
|
});
|
|
1902
|
+
const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
|
|
1903
|
+
const nodeView = new DriveNodeView(reactorDriveSchemaDb);
|
|
1904
|
+
driveNodeView = nodeView;
|
|
1905
|
+
clientBuilder.withDriveNodeSource(nodeView).withDriveWriteStrategy(REACTOR_DRIVE_DOCUMENT_TYPE, createReactorDriveWriteStrategy);
|
|
2125
1906
|
let module;
|
|
2126
1907
|
try {
|
|
2127
1908
|
module = await clientBuilder.buildModule();
|
|
@@ -2138,12 +1919,10 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2138
1919
|
new ReactorInstrumentation(module.reactorModule).start();
|
|
2139
1920
|
reactorLogger.info("Reactor metrics instrumentation started");
|
|
2140
1921
|
}
|
|
2141
|
-
const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
|
|
2142
|
-
driveNodeView = new DriveNodeView(reactorDriveSchemaDb);
|
|
2143
1922
|
const reactorDriveClient = new ReactorDriveClient({
|
|
2144
1923
|
read: module.read,
|
|
2145
1924
|
write: module.write,
|
|
2146
|
-
readModel:
|
|
1925
|
+
readModel: nodeView
|
|
2147
1926
|
});
|
|
2148
1927
|
ownedReactorModule = module;
|
|
2149
1928
|
if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
|
|
@@ -2162,6 +1941,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2162
1941
|
return {
|
|
2163
1942
|
module,
|
|
2164
1943
|
reactorDriveClient,
|
|
1944
|
+
driveNodes: nodeView,
|
|
2165
1945
|
attachmentReferenceProjection: { status: "available" },
|
|
2166
1946
|
permissionsDb
|
|
2167
1947
|
};
|
|
@@ -2191,9 +1971,6 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2191
1971
|
const verifyCredential = renownConfig.source === "self" ? (params) => localCredentialCheck ? localCredentialCheck(params) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet")) : void 0;
|
|
2192
1972
|
let defaultDriveUrl = void 0;
|
|
2193
1973
|
const basePath = process.cwd();
|
|
2194
|
-
const reportError = (error) => {
|
|
2195
|
-
Sentry.captureException(error);
|
|
2196
|
-
};
|
|
2197
1974
|
const reporting = {
|
|
2198
1975
|
logger,
|
|
2199
1976
|
report: reportError
|
|
@@ -2215,10 +1992,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2215
1992
|
else packageLoaders.push(new ImportPackageLoader());
|
|
2216
1993
|
if (httpLoader) {
|
|
2217
1994
|
packageLoaders.push(httpLoader);
|
|
2218
|
-
registryPackages
|
|
2219
|
-
const name = p.trim();
|
|
2220
|
-
if (!packages.includes(name)) packages.push(name);
|
|
2221
|
-
});
|
|
1995
|
+
for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
|
|
2222
1996
|
}
|
|
2223
1997
|
const apiLogger = logger.child(["reactor-api"]);
|
|
2224
1998
|
let pgliteFactory;
|
|
@@ -2227,14 +2001,15 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2227
2001
|
label: "read-storage",
|
|
2228
2002
|
major: readModelPgliteMajor,
|
|
2229
2003
|
parsers: "utc-timestamps",
|
|
2230
|
-
inMemory
|
|
2004
|
+
inMemory,
|
|
2231
2005
|
threaded: options.pgliteWorkers === true,
|
|
2006
|
+
settings: pgliteSettings,
|
|
2232
2007
|
logger
|
|
2233
2008
|
});
|
|
2234
2009
|
pgliteFactory = (connectionString) => openReadStore(connectionString ?? readModelPgliteDir);
|
|
2235
2010
|
}
|
|
2236
2011
|
const api = await initializeAndStartAPI(initializeClient, {
|
|
2237
|
-
port:
|
|
2012
|
+
port: requestedPort,
|
|
2238
2013
|
dbPath: readModelPath,
|
|
2239
2014
|
pgliteFactory,
|
|
2240
2015
|
https: options.https,
|
|
@@ -2243,8 +2018,18 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2243
2018
|
processorConfig: options.processorConfig,
|
|
2244
2019
|
processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
|
|
2245
2020
|
configFile: configPath,
|
|
2021
|
+
server: {
|
|
2022
|
+
basePath: config.server.basePath,
|
|
2023
|
+
gatewayAdapter: config.server.gatewayAdapter,
|
|
2024
|
+
publicUrl: config.server.publicUrl
|
|
2025
|
+
},
|
|
2026
|
+
auth: authSectionOf(config.auth),
|
|
2027
|
+
attachments: { storage: config.attachments.storage },
|
|
2246
2028
|
mcp: options.mcp ?? true,
|
|
2247
|
-
inspection: options.inspection === false ? false : {
|
|
2029
|
+
inspection: options.inspection === false ? false : {
|
|
2030
|
+
throttle: inspectionThrottle,
|
|
2031
|
+
admin: config.inspection.admin
|
|
2032
|
+
},
|
|
2248
2033
|
logger: apiLogger,
|
|
2249
2034
|
reportError,
|
|
2250
2035
|
enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
|
|
@@ -2252,6 +2037,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2252
2037
|
verifyCredential
|
|
2253
2038
|
}, "switchboard");
|
|
2254
2039
|
apiRef.current = api;
|
|
2040
|
+
const serverPort = api.port;
|
|
2255
2041
|
if (renownConfig.source === "self") {
|
|
2256
2042
|
const { graphqlManager: manager } = api;
|
|
2257
2043
|
if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {
|
|
@@ -2269,7 +2055,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2269
2055
|
await pluginHost.observe("onHttpMounting");
|
|
2270
2056
|
attachmentService = pluginHost.ctx.attachmentService;
|
|
2271
2057
|
} else {
|
|
2272
|
-
registerAttachmentRoutes(api);
|
|
2058
|
+
registerAttachmentRoutes(api, { config: config.attachments });
|
|
2273
2059
|
attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
|
|
2274
2060
|
}
|
|
2275
2061
|
if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
|
|
@@ -2542,42 +2328,32 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
2542
2328
|
* teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling
|
|
2543
2329
|
* it twice, or receiving a signal around it, tears down once.
|
|
2544
2330
|
*/
|
|
2545
|
-
const startSwitchboard = async (
|
|
2546
|
-
|
|
2547
|
-
const
|
|
2331
|
+
const startSwitchboard = async (input = {}, deps = {}) => {
|
|
2332
|
+
assertConfigShape(input);
|
|
2333
|
+
const configPath = resolveConfigPath(input.configFile);
|
|
2334
|
+
const fileConfig = getConfig(configPath);
|
|
2335
|
+
const config = switchboardConfigSchema.parse(mergeSwitchboardConfig({ auth: {
|
|
2336
|
+
enabled: fileConfig.auth?.enabled,
|
|
2337
|
+
admins: fileConfig.auth?.admins
|
|
2338
|
+
} }, input));
|
|
2339
|
+
const logger = deps.logger ?? defaultLogger;
|
|
2340
|
+
if (disableWasmWrapperTiering()) logger.info("Wasm wrapper tier-up off on Node 24 (nodejs/node#66366)");
|
|
2548
2341
|
if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
|
|
2549
|
-
const serverPort = await resolveServerPort(
|
|
2550
|
-
const
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
});
|
|
2558
|
-
const configPathForFlags = resolveConfigPath(options.configFile);
|
|
2559
|
-
options.workflows = { enabled: await resolveWorkflowsEnabled({
|
|
2560
|
-
featureFlags,
|
|
2561
|
-
override: options.workflows?.enabled,
|
|
2562
|
-
configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
|
|
2563
|
-
}) };
|
|
2564
|
-
}
|
|
2565
|
-
options.inspection = await resolveInspectionEnabled({
|
|
2566
|
-
featureFlags,
|
|
2567
|
-
option: options.inspection
|
|
2568
|
-
});
|
|
2569
|
-
options.pgliteWorkers = await resolvePgliteWorkersEnabled({
|
|
2570
|
-
featureFlags,
|
|
2571
|
-
option: options.pgliteWorkers
|
|
2572
|
-
});
|
|
2573
|
-
const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
|
|
2342
|
+
const serverPort = await resolveServerPort(config.server.port, config.server.strictPort, logger);
|
|
2343
|
+
const options = serverOptionsOf(config, deps);
|
|
2344
|
+
if (!config.features.pluginHost) {
|
|
2345
|
+
options.mcp = config.features.mcp ?? true;
|
|
2346
|
+
options.workflows = { enabled: config.features.workflows ?? readConfigWorkflowsEnabled(configPath) };
|
|
2347
|
+
}
|
|
2348
|
+
const renownConfig = resolveRenownConfig(renownLayers(fileConfig.auth?.renown, config.auth.renown), {}, logger);
|
|
2349
|
+
const userDataDir = config.storage.userDataDir;
|
|
2574
2350
|
options.identity = {
|
|
2575
2351
|
...options.identity,
|
|
2576
2352
|
baseUrl: options.identity?.baseUrl ?? renownConfig.url,
|
|
2577
|
-
keypairPath: options.identity?.keypairPath ?? (
|
|
2353
|
+
keypairPath: options.identity?.keypairPath ?? (userDataDir ? path$1.join(resolvePhDir(void 0, { PH_USER_DATA_DIR: userDataDir }), ".keypair.json") : void 0)
|
|
2578
2354
|
};
|
|
2579
2355
|
logger.info("Feature flags: @flags", JSON.stringify({
|
|
2580
|
-
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
|
|
2356
|
+
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: options.enableDocumentModelSubgraphs,
|
|
2581
2357
|
MCP_ENABLED: options.mcp,
|
|
2582
2358
|
INSPECTION_ENABLED: options.inspection,
|
|
2583
2359
|
PH_PGLITE_WORKERS: options.pgliteWorkers,
|
|
@@ -2585,13 +2361,19 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2585
2361
|
}, null, 2));
|
|
2586
2362
|
let renown = null;
|
|
2587
2363
|
try {
|
|
2588
|
-
renown = await initRenown(
|
|
2364
|
+
renown = await initRenown({
|
|
2365
|
+
...options.identity,
|
|
2366
|
+
userDataDir
|
|
2367
|
+
});
|
|
2589
2368
|
} catch (e) {
|
|
2590
2369
|
logger.warn("Failed to initialize ConnectCrypto: @error", e);
|
|
2591
2370
|
if (options.identity.requireExisting) throw new Error("Identity required but failed to initialize. Run \"ph login\" first.", { cause: e });
|
|
2592
2371
|
}
|
|
2372
|
+
const reportError = deps.reportError ?? ((error) => {
|
|
2373
|
+
Sentry.captureException(error);
|
|
2374
|
+
});
|
|
2593
2375
|
try {
|
|
2594
|
-
return await initServer(serverPort, options, renown, renownConfig);
|
|
2376
|
+
return await initServer(serverPort, options, config, renown, renownConfig, reportError);
|
|
2595
2377
|
} catch (e) {
|
|
2596
2378
|
Sentry.captureException(e);
|
|
2597
2379
|
if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
|
|
@@ -2599,13 +2381,71 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2599
2381
|
throw e;
|
|
2600
2382
|
}
|
|
2601
2383
|
};
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2384
|
+
function assertConfigShape(input) {
|
|
2385
|
+
const unknown = Object.keys(input).filter((key) => !(key in switchboardConfigSchema.shape));
|
|
2386
|
+
if (unknown.length > 0) throw new Error(`startSwitchboard(config, deps) got unknown config keys: ${unknown.join(", ")}. It takes the @powerhousedao/switchboard/config shape; runtime objects go in deps.`);
|
|
2387
|
+
}
|
|
2388
|
+
/** The options view plugins transform, from the config and deps. */
|
|
2389
|
+
function serverOptionsOf(config, deps) {
|
|
2390
|
+
const { executor, projection } = config.workers;
|
|
2391
|
+
return {
|
|
2392
|
+
reactor: deps.reactor,
|
|
2393
|
+
fatalErrorShutdown: deps.fatalErrorShutdown,
|
|
2394
|
+
signalHandlers: deps.signalHandlers,
|
|
2395
|
+
pluginComposition: deps.pluginComposition,
|
|
2396
|
+
logger: deps.logger,
|
|
2397
|
+
registryUrl: config.packages.registryUrl,
|
|
2398
|
+
configFile: config.configFile,
|
|
2399
|
+
port: config.server.port,
|
|
2400
|
+
strictPort: config.server.strictPort,
|
|
2401
|
+
dev: config.server.dev,
|
|
2402
|
+
dbPath: config.storage.readModel.url,
|
|
2403
|
+
drive: config.drive,
|
|
2404
|
+
packages: [...config.packages.list],
|
|
2405
|
+
remoteDrives: [...config.remoteDrives],
|
|
2406
|
+
https: config.server.https,
|
|
2407
|
+
identity: config.identity,
|
|
2408
|
+
attachmentServiceUrl: config.attachments.serviceUrl,
|
|
2409
|
+
mcp: config.features.mcp,
|
|
2410
|
+
inspection: config.inspection.enabled,
|
|
2411
|
+
pgliteWorkers: config.storage.pglite.workers,
|
|
2412
|
+
workflows: config.features.workflows === void 0 ? void 0 : { enabled: config.features.workflows },
|
|
2413
|
+
privacy: {
|
|
2414
|
+
enabled: config.features.privacy.enabled,
|
|
2415
|
+
deploymentSecret: config.features.privacy.deploymentSecret,
|
|
2416
|
+
intervalMs: config.features.privacy.intervalMs,
|
|
2417
|
+
deadlineMs: config.features.privacy.deadlineMs,
|
|
2418
|
+
markerGraceMs: config.features.privacy.markerGraceMs,
|
|
2419
|
+
purgeTimeoutMs: config.features.privacy.purgeTimeoutMs,
|
|
2420
|
+
signer: deps.privacySigner
|
|
2421
|
+
},
|
|
2422
|
+
processorConfig: config.processorConfig,
|
|
2423
|
+
disableLocalPackages: config.packages.disableLocal,
|
|
2424
|
+
enableDocumentModelSubgraphs: config.features.documentModelSubgraphs,
|
|
2425
|
+
dynamicModelLoading: config.packages.dynamic,
|
|
2426
|
+
migratePglite: config.storage.migratePglite,
|
|
2427
|
+
forcePgVersion: config.storage.forcePgVersion,
|
|
2428
|
+
workerPool: {
|
|
2429
|
+
numWorkers: executor.count,
|
|
2430
|
+
dbPoolSizePerWorker: executor.poolSize,
|
|
2431
|
+
acquireTimeoutMs: executor.acquireTimeoutMs
|
|
2432
|
+
},
|
|
2433
|
+
projectionWorker: {
|
|
2434
|
+
enabled: projection.enabled,
|
|
2435
|
+
dbPoolSize: projection.poolSize
|
|
2436
|
+
},
|
|
2437
|
+
unsupportedStoredDocuments: config.protocol.unsupportedStoredDocuments
|
|
2438
|
+
};
|
|
2439
|
+
}
|
|
2440
|
+
/** reactor-api's auth section; renown is resolved here, not there. */
|
|
2441
|
+
function authSectionOf(auth) {
|
|
2442
|
+
const { renown: _renown, ...section } = auth;
|
|
2443
|
+
return section;
|
|
2444
|
+
}
|
|
2445
|
+
if (import.meta.main) {
|
|
2446
|
+
const config = switchboardConfigFromEnv(process.env);
|
|
2447
|
+
initSwitchboardProcess(config);
|
|
2448
|
+
await startSwitchboard(config, { fatalErrorShutdown: true });
|
|
2609
2449
|
}
|
|
2610
2450
|
/**
|
|
2611
2451
|
* Feeds the priority this server's request load and main-thread event-loop
|
|
@@ -2623,7 +2463,7 @@ function feedCatchUpPriority(priority, server) {
|
|
|
2623
2463
|
};
|
|
2624
2464
|
}
|
|
2625
2465
|
//#endregion
|
|
2626
|
-
export {
|
|
2466
|
+
export { resolvePgliteStorageDirs as a, attachmentsPluginConfigSchema as c, isPortAvailable as i, applySwitchboardReactorDefaults as l, deriveAttachmentServiceConfig as n, startSwitchboard as o, initSwitchboardProcess as r, attachmentsPlugin as s, createReactorKysely as t, initProfilerFromEnv as u };
|
|
2627
2467
|
|
|
2628
|
-
//# sourceMappingURL=server-
|
|
2629
|
-
//# debugId=
|
|
2468
|
+
//# sourceMappingURL=server-CtGBZlTg.mjs.map
|
|
2469
|
+
//# debugId=adb8b57f-cca7-5667-a44f-f042b16d51a1
|