@powerhousedao/switchboard 6.2.3-dev.78 → 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/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 +35 -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-Bdq8xquD.mjs → server-CtGBZlTg.mjs} +230 -382
- package/dist/server-CtGBZlTg.mjs.map +1 -0
- package/dist/server.d.mts +46 -11
- 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 -13
- package/test/boot-mcp-enabled.test.ts +15 -13
- package/test/boot-port-zero.test.ts +15 -13
- package/test/boot-preconditions.test.ts +51 -0
- package/test/boot-privacy.test.ts +12 -10
- 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 -10
- 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 +1 -62
- package/test/plugin-presence.test.ts +27 -21
- package/test/renown-storage-path.test.ts +9 -8
- package/test/shutdown.test.ts +22 -21
- 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-Bdq8xquD.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, resolvePgliteMaintenance, 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
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,19 +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
|
-
/** The VACUUM FULL settings
|
|
1492
|
-
|
|
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
|
+
});
|
|
1298
|
+
}
|
|
1299
|
+
const DEFAULT_MAINTENANCE = { vacuumFullAboveBytes: 0 };
|
|
1493
1300
|
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1494
|
-
async function loadDurableFsFactory(major, logger, proc) {
|
|
1301
|
+
async function loadDurableFsFactory(major, logger, proc, settings = {}) {
|
|
1495
1302
|
const NodeFS = await loadNodeFsClass(major);
|
|
1496
|
-
const timing =
|
|
1303
|
+
const timing = settings.maintenance ?? DEFAULT_MAINTENANCE;
|
|
1497
1304
|
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1498
|
-
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1305
|
+
fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
|
|
1499
1306
|
...timing,
|
|
1500
1307
|
logger,
|
|
1501
1308
|
onAbort: (what) => onPgliteAbort(logger, what, proc)
|
|
@@ -1516,7 +1323,8 @@ async function createPgliteStoreFactory(options) {
|
|
|
1516
1323
|
}
|
|
1517
1324
|
function threadedStoreFactory(options) {
|
|
1518
1325
|
const { label, major, parsers, inMemory, logger, proc } = options;
|
|
1519
|
-
const
|
|
1326
|
+
const settings = options.settings ?? {};
|
|
1327
|
+
const memoryLimitMb = settings.workerMemoryMb ?? DEFAULT_PGLITE_WORKER_MEMORY_MB;
|
|
1520
1328
|
const module = pgliteModuleSpec(major);
|
|
1521
1329
|
return (dir) => {
|
|
1522
1330
|
const store = new ThreadedPGlite({
|
|
@@ -1525,8 +1333,8 @@ function threadedStoreFactory(options) {
|
|
|
1525
1333
|
dataDir: inMemory ? null : dir,
|
|
1526
1334
|
module,
|
|
1527
1335
|
durableFs: inMemory ? null : {
|
|
1528
|
-
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1529
|
-
...
|
|
1336
|
+
fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
|
|
1337
|
+
...settings.maintenance ?? DEFAULT_MAINTENANCE
|
|
1530
1338
|
},
|
|
1531
1339
|
parsers
|
|
1532
1340
|
},
|
|
@@ -1541,7 +1349,7 @@ function threadedStoreFactory(options) {
|
|
|
1541
1349
|
async function mainThreadStoreFactory(options) {
|
|
1542
1350
|
const { label, major, inMemory, logger, proc } = options;
|
|
1543
1351
|
const { PGlite } = await loadPGliteModule(major);
|
|
1544
|
-
const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc);
|
|
1352
|
+
const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc, options.settings);
|
|
1545
1353
|
const base = options.parsers === "utc-timestamps" ? { parsers: PGLITE_UTC_PARSERS } : {};
|
|
1546
1354
|
return (dir) => {
|
|
1547
1355
|
logger.info(`${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`);
|
|
@@ -1556,18 +1364,8 @@ function where(inMemory, dir) {
|
|
|
1556
1364
|
}
|
|
1557
1365
|
//#endregion
|
|
1558
1366
|
//#region src/create-signature-policy.mts
|
|
1559
|
-
/**
|
|
1560
|
-
|
|
1561
|
-
* signer this switchboard cannot write to a v2-required document, so it falls
|
|
1562
|
-
* back to legacy and says so.
|
|
1563
|
-
*/
|
|
1564
|
-
function resolveCreateSignaturePolicy(env, options) {
|
|
1565
|
-
const raw = env.CREATE_SIGNATURE_POLICY?.trim();
|
|
1566
|
-
let policy = DEFAULT_SIGNATURE_POLICY;
|
|
1567
|
-
if (raw) {
|
|
1568
|
-
if (!isSignaturePolicy(raw)) throw new Error(`CREATE_SIGNATURE_POLICY must be "legacy" or "v2-required", got "${raw}"`);
|
|
1569
|
-
policy = raw;
|
|
1570
|
-
}
|
|
1367
|
+
/** The requested policy, or legacy when it needs a signer this switchboard lacks. */
|
|
1368
|
+
function createSignaturePolicyFor(policy, options) {
|
|
1571
1369
|
if (policy === "v2-required" && !options.hasSigner) {
|
|
1572
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.");
|
|
1573
1371
|
return "legacy";
|
|
@@ -1583,7 +1381,7 @@ const logger = childLogger(["switchboard", "renown"]);
|
|
|
1583
1381
|
* using the same identity established during `ph login`.
|
|
1584
1382
|
*/
|
|
1585
1383
|
async function initRenown(options = {}) {
|
|
1586
|
-
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;
|
|
1587
1385
|
const keyStorage = new NodeKeyStorage(keypairPath, { logger });
|
|
1588
1386
|
const existingKeyPair = await keyStorage.loadKeyPair();
|
|
1589
1387
|
if (!existingKeyPair && requireExisting) throw new Error("No existing keypair found and requireExisting is true. Run \"ph login\" to create one.");
|
|
@@ -1683,32 +1481,6 @@ function ownIdentity(renown) {
|
|
|
1683
1481
|
};
|
|
1684
1482
|
}
|
|
1685
1483
|
//#endregion
|
|
1686
|
-
//#region src/unsupported-stored-documents.mts
|
|
1687
|
-
const MODES = ["refuse", "read-only"];
|
|
1688
|
-
/** From REACTOR_UNSUPPORTED_STORED_DOCUMENTS; `input` wins when defined. */
|
|
1689
|
-
function resolveUnsupportedStoredDocuments(input, env) {
|
|
1690
|
-
if (input !== void 0) return input;
|
|
1691
|
-
const raw = env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS?.trim();
|
|
1692
|
-
if (!raw) return "refuse";
|
|
1693
|
-
if (!MODES.includes(raw)) throw new Error(`REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "${raw}"`);
|
|
1694
|
-
return raw;
|
|
1695
|
-
}
|
|
1696
|
-
/** The reactor refused to start over documents this build does not run. */
|
|
1697
|
-
var StoredDocumentsRefusedError = class extends Error {
|
|
1698
|
-
versions;
|
|
1699
|
-
documents;
|
|
1700
|
-
constructor(cause) {
|
|
1701
|
-
const named = cause.versions.map(({ protocol, version }) => `${protocol} ${version}`).join(", ");
|
|
1702
|
-
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 });
|
|
1703
|
-
this.name = "StoredDocumentsRefusedError";
|
|
1704
|
-
this.versions = cause.versions;
|
|
1705
|
-
this.documents = cause.documents;
|
|
1706
|
-
}
|
|
1707
|
-
static isError(error) {
|
|
1708
|
-
return Error.isError(error) && error.name === "StoredDocumentsRefusedError";
|
|
1709
|
-
}
|
|
1710
|
-
};
|
|
1711
|
-
//#endregion
|
|
1712
1484
|
//#region src/store-lock.mts
|
|
1713
1485
|
var StoreInUseError = class extends Error {
|
|
1714
1486
|
dir;
|
|
@@ -1768,12 +1540,17 @@ function acquireStoreLocks(dirs, isPidAlive = isAlive) {
|
|
|
1768
1540
|
//#endregion
|
|
1769
1541
|
//#region src/server.mts
|
|
1770
1542
|
const defaultLogger = childLogger(["switchboard"]);
|
|
1771
|
-
const LogLevel = process.env.LOG_LEVEL || "info";
|
|
1772
|
-
setLogLevel(LogLevel);
|
|
1773
1543
|
if (!isDotenvDisabled()) dotenv.config();
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
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
|
+
}
|
|
1777
1554
|
const PORT_FALLBACK_ATTEMPTS = 20;
|
|
1778
1555
|
let flushIntervalWarned = false;
|
|
1779
1556
|
function warnIgnoredFlushInterval(logger) {
|
|
@@ -1782,7 +1559,6 @@ function warnIgnoredFlushInterval(logger) {
|
|
|
1782
1559
|
flushIntervalWarned = true;
|
|
1783
1560
|
logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
|
|
1784
1561
|
}
|
|
1785
|
-
const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
|
|
1786
1562
|
/**
|
|
1787
1563
|
* Attempt to bind a throwaway TCP server to the given port. Resolves true if
|
|
1788
1564
|
* the port is free, false if the OS reports it in use. Any other error is
|
|
@@ -1841,7 +1617,7 @@ async function resolveServerPort(requested, strictPort, logger) {
|
|
|
1841
1617
|
return requested;
|
|
1842
1618
|
}
|
|
1843
1619
|
async function createReactorKysely(opts) {
|
|
1844
|
-
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, logger } = opts;
|
|
1620
|
+
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, pgliteSettings, logger } = opts;
|
|
1845
1621
|
if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
|
|
1846
1622
|
const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
|
|
1847
1623
|
const poolSize = hostPoolSize();
|
|
@@ -1864,6 +1640,7 @@ async function createReactorKysely(opts) {
|
|
|
1864
1640
|
parsers: "none",
|
|
1865
1641
|
inMemory,
|
|
1866
1642
|
threaded: pgliteWorkers,
|
|
1643
|
+
settings: pgliteSettings,
|
|
1867
1644
|
logger
|
|
1868
1645
|
}))(reactorPgliteDir);
|
|
1869
1646
|
const dialectOptions = pglite instanceof ThreadedPGlite ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite) : reactorPgliteDialectOptions(logger);
|
|
@@ -1886,7 +1663,7 @@ async function createReactorKysely(opts) {
|
|
|
1886
1663
|
*/
|
|
1887
1664
|
function resolvePgliteStorageDirs(opts) {
|
|
1888
1665
|
const { dbPath, reactorDbUrl, callerReactor } = opts;
|
|
1889
|
-
const defaults = defaultStoreDirs(
|
|
1666
|
+
const defaults = defaultStoreDirs({ PH_USER_DATA_DIR: opts.userDataDir }, opts.phDir);
|
|
1890
1667
|
const readModelPath = dbPath || defaults.readModel;
|
|
1891
1668
|
const reactorPath = reactorDbUrl || defaults.reactor;
|
|
1892
1669
|
const reactorPgliteDir = callerReactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
|
|
@@ -1901,22 +1678,23 @@ function resolvePgliteStorageDirs(opts) {
|
|
|
1901
1678
|
sharedPgliteDir
|
|
1902
1679
|
};
|
|
1903
1680
|
}
|
|
1904
|
-
/**
|
|
1681
|
+
/** The remote attachment service config for switchboard's own `/attachments/*` API; `attachments.serviceUrl` carries PH_SWITCHBOARD_PUBLIC_URL. */
|
|
1905
1682
|
function deriveAttachmentServiceConfig(options, serverPort, renown) {
|
|
1906
1683
|
const protocol = options.https ? "https" : "http";
|
|
1907
1684
|
return {
|
|
1908
|
-
remoteUrl: options.attachmentServiceUrl ??
|
|
1685
|
+
remoteUrl: options.attachmentServiceUrl ?? `${protocol}://localhost:${serverPort}`,
|
|
1909
1686
|
jwtHandler: renown ? async (url) => renown.user ? renown.getBearerToken({
|
|
1910
1687
|
expiresIn: 10,
|
|
1911
1688
|
aud: url
|
|
1912
1689
|
}) : void 0 : void 0
|
|
1913
1690
|
};
|
|
1914
1691
|
}
|
|
1915
|
-
async function initServer(requestedPort, options, renown, renownConfig) {
|
|
1692
|
+
async function initServer(requestedPort, options, config, renown, renownConfig, reportError) {
|
|
1916
1693
|
const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
|
|
1917
|
-
const pluginHost =
|
|
1694
|
+
const pluginHost = config.features.pluginHost ? createSwitchboardPluginHost({
|
|
1918
1695
|
logger,
|
|
1919
1696
|
options,
|
|
1697
|
+
config,
|
|
1920
1698
|
renown
|
|
1921
1699
|
}, options.pluginComposition) : null;
|
|
1922
1700
|
if (pluginHost) {
|
|
@@ -1924,22 +1702,29 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
1924
1702
|
options.mcp ??= false;
|
|
1925
1703
|
options.workflows = { enabled: options.workflows?.enabled === true };
|
|
1926
1704
|
}
|
|
1927
|
-
logger.level =
|
|
1928
|
-
const dbPath =
|
|
1929
|
-
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
|
+
};
|
|
1930
1714
|
const { readModelPath, reactorPgliteDir, readModelPgliteDir, pgliteDirs, sharedPgliteDir } = resolvePgliteStorageDirs({
|
|
1931
1715
|
dbPath,
|
|
1932
1716
|
reactorDbUrl,
|
|
1933
|
-
callerReactor: options.reactor !== void 0
|
|
1717
|
+
callerReactor: options.reactor !== void 0,
|
|
1718
|
+
userDataDir: config.storage.userDataDir
|
|
1934
1719
|
});
|
|
1935
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.`);
|
|
1936
|
-
if (!
|
|
1721
|
+
if (!inMemory) acquireStoreLocks(pgliteDirs);
|
|
1937
1722
|
warnIgnoredFlushInterval(logger);
|
|
1938
1723
|
const detectedMajors = await runPglitePreflight({
|
|
1939
1724
|
dirs: pgliteDirs,
|
|
1940
1725
|
forcePgVersion: options.forcePgVersion,
|
|
1941
1726
|
migratePglite: options.migratePglite,
|
|
1942
|
-
inMemory
|
|
1727
|
+
inMemory,
|
|
1943
1728
|
logger
|
|
1944
1729
|
});
|
|
1945
1730
|
function resolvePgliteMajorForDir(dir) {
|
|
@@ -1951,8 +1736,8 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
1951
1736
|
}
|
|
1952
1737
|
const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
|
|
1953
1738
|
const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
|
|
1954
|
-
const inspectionThrottle =
|
|
1955
|
-
let workerPool = resolveWorkerPoolOptions(options.workerPool,
|
|
1739
|
+
const inspectionThrottle = config.inspection.callsPerMinute === void 0 ? {} : { callsPerMinute: config.inspection.callsPerMinute };
|
|
1740
|
+
let workerPool = resolveWorkerPoolOptions(options.workerPool, {});
|
|
1956
1741
|
if (workerPool && options.reactor) {
|
|
1957
1742
|
logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
|
|
1958
1743
|
workerPool = null;
|
|
@@ -1963,13 +1748,13 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
1963
1748
|
workers: workerPool.numWorkers,
|
|
1964
1749
|
projectionWorker: false,
|
|
1965
1750
|
reactorDbUrl,
|
|
1966
|
-
authEnforcement:
|
|
1751
|
+
authEnforcement: config.protocol.featureFlags.authEnforcement,
|
|
1967
1752
|
renownSource: renownConfig.source
|
|
1968
1753
|
}).at(0);
|
|
1969
1754
|
if (issue) throw new Error(issue);
|
|
1970
1755
|
}
|
|
1971
|
-
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments,
|
|
1972
|
-
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker,
|
|
1756
|
+
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, {});
|
|
1757
|
+
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, {});
|
|
1973
1758
|
if (projectionWorker && options.reactor) {
|
|
1974
1759
|
logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
|
|
1975
1760
|
projectionWorker = null;
|
|
@@ -1981,20 +1766,20 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
1981
1766
|
const apiRef = { current: void 0 };
|
|
1982
1767
|
let driveNodeView;
|
|
1983
1768
|
const configPath = resolveConfigPath(options.configFile);
|
|
1984
|
-
const
|
|
1985
|
-
const registryUrl = options.registryUrl ??
|
|
1986
|
-
const registryPackages =
|
|
1987
|
-
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;
|
|
1988
1773
|
let httpLoader;
|
|
1989
1774
|
if (registryUrl) {
|
|
1990
|
-
|
|
1991
|
-
httpLoader = new HttpPackageLoader({
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
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")
|
|
1995
1779
|
});
|
|
1780
|
+
for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
|
|
1996
1781
|
}
|
|
1997
|
-
const registryPackageNames = new Set(
|
|
1782
|
+
const registryPackageNames = new Set(registryPackages.filter(Boolean));
|
|
1998
1783
|
const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
|
|
1999
1784
|
const reactorLogger = logger.child(["reactor"]);
|
|
2000
1785
|
let projectionWorkerFatalFired = false;
|
|
@@ -2005,13 +1790,16 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2005
1790
|
process.kill(process.pid, "SIGTERM");
|
|
2006
1791
|
};
|
|
2007
1792
|
const workflowsEnabled = options.workflows?.enabled === true;
|
|
2008
|
-
const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy,
|
|
1793
|
+
const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, {});
|
|
2009
1794
|
if (workflowsEnabled) {
|
|
2010
1795
|
await assertWorkflowPackageLoadable();
|
|
2011
1796
|
if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
|
|
2012
1797
|
}
|
|
2013
1798
|
let ownedReactorModule;
|
|
2014
|
-
const catchUpPriority = new CatchUpPriority(
|
|
1799
|
+
const catchUpPriority = new CatchUpPriority(config.protocol.catchUpPriority === "dynamic" ? { mode: "dynamic" } : {
|
|
1800
|
+
mode: "fixed",
|
|
1801
|
+
level: config.protocol.catchUpPriority
|
|
1802
|
+
});
|
|
2015
1803
|
let workerModels;
|
|
2016
1804
|
let localRenownRequest;
|
|
2017
1805
|
const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests, readModelDb }) => {
|
|
@@ -2030,17 +1818,18 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2030
1818
|
reactorDbUrl,
|
|
2031
1819
|
reactorPgliteDir,
|
|
2032
1820
|
reactorPgliteMajor,
|
|
2033
|
-
inMemory
|
|
2034
|
-
hostPoolSize: () =>
|
|
1821
|
+
inMemory,
|
|
1822
|
+
hostPoolSize: () => config.workers.hostPoolSize,
|
|
2035
1823
|
pgliteWorkers: options.pgliteWorkers === true,
|
|
1824
|
+
pgliteSettings,
|
|
2036
1825
|
logger
|
|
2037
1826
|
});
|
|
2038
|
-
const maxSkipThreshold =
|
|
2039
|
-
const hasSkipThreshold =
|
|
1827
|
+
const maxSkipThreshold = config.protocol.maxSkipThreshold;
|
|
1828
|
+
const hasSkipThreshold = maxSkipThreshold !== void 0;
|
|
2040
1829
|
if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
|
|
2041
|
-
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } =
|
|
1830
|
+
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = reactorFeatureFlagsOf(config.protocol.featureFlags);
|
|
2042
1831
|
if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
|
|
2043
|
-
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);
|
|
2044
1833
|
if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
|
|
2045
1834
|
const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
|
|
2046
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) : [];
|
|
@@ -2055,7 +1844,7 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2055
1844
|
documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
|
|
2056
1845
|
logger: reactorLogger,
|
|
2057
1846
|
signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
|
|
2058
|
-
createSignaturePolicy:
|
|
1847
|
+
createSignaturePolicy: createSignaturePolicyFor(config.protocol.createSignaturePolicy, {
|
|
2059
1848
|
hasSigner: renown !== null,
|
|
2060
1849
|
logger
|
|
2061
1850
|
}),
|
|
@@ -2182,9 +1971,6 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2182
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;
|
|
2183
1972
|
let defaultDriveUrl = void 0;
|
|
2184
1973
|
const basePath = process.cwd();
|
|
2185
|
-
const reportError = (error) => {
|
|
2186
|
-
Sentry.captureException(error);
|
|
2187
|
-
};
|
|
2188
1974
|
const reporting = {
|
|
2189
1975
|
logger,
|
|
2190
1976
|
report: reportError
|
|
@@ -2206,10 +1992,7 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2206
1992
|
else packageLoaders.push(new ImportPackageLoader());
|
|
2207
1993
|
if (httpLoader) {
|
|
2208
1994
|
packageLoaders.push(httpLoader);
|
|
2209
|
-
registryPackages
|
|
2210
|
-
const name = p.trim();
|
|
2211
|
-
if (!packages.includes(name)) packages.push(name);
|
|
2212
|
-
});
|
|
1995
|
+
for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
|
|
2213
1996
|
}
|
|
2214
1997
|
const apiLogger = logger.child(["reactor-api"]);
|
|
2215
1998
|
let pgliteFactory;
|
|
@@ -2218,8 +2001,9 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2218
2001
|
label: "read-storage",
|
|
2219
2002
|
major: readModelPgliteMajor,
|
|
2220
2003
|
parsers: "utc-timestamps",
|
|
2221
|
-
inMemory
|
|
2004
|
+
inMemory,
|
|
2222
2005
|
threaded: options.pgliteWorkers === true,
|
|
2006
|
+
settings: pgliteSettings,
|
|
2223
2007
|
logger
|
|
2224
2008
|
});
|
|
2225
2009
|
pgliteFactory = (connectionString) => openReadStore(connectionString ?? readModelPgliteDir);
|
|
@@ -2234,8 +2018,18 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2234
2018
|
processorConfig: options.processorConfig,
|
|
2235
2019
|
processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
|
|
2236
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 },
|
|
2237
2028
|
mcp: options.mcp ?? true,
|
|
2238
|
-
inspection: options.inspection === false ? false : {
|
|
2029
|
+
inspection: options.inspection === false ? false : {
|
|
2030
|
+
throttle: inspectionThrottle,
|
|
2031
|
+
admin: config.inspection.admin
|
|
2032
|
+
},
|
|
2239
2033
|
logger: apiLogger,
|
|
2240
2034
|
reportError,
|
|
2241
2035
|
enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
|
|
@@ -2261,7 +2055,7 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2261
2055
|
await pluginHost.observe("onHttpMounting");
|
|
2262
2056
|
attachmentService = pluginHost.ctx.attachmentService;
|
|
2263
2057
|
} else {
|
|
2264
|
-
registerAttachmentRoutes(api);
|
|
2058
|
+
registerAttachmentRoutes(api, { config: config.attachments });
|
|
2265
2059
|
attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
|
|
2266
2060
|
}
|
|
2267
2061
|
if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
|
|
@@ -2534,42 +2328,32 @@ async function initServer(requestedPort, options, renown, renownConfig) {
|
|
|
2534
2328
|
* teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling
|
|
2535
2329
|
* it twice, or receiving a signal around it, tears down once.
|
|
2536
2330
|
*/
|
|
2537
|
-
const startSwitchboard = async (
|
|
2538
|
-
|
|
2539
|
-
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)");
|
|
2540
2341
|
if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
|
|
2541
|
-
const serverPort = await resolveServerPort(
|
|
2542
|
-
const
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
});
|
|
2550
|
-
const configPathForFlags = resolveConfigPath(options.configFile);
|
|
2551
|
-
options.workflows = { enabled: await resolveWorkflowsEnabled({
|
|
2552
|
-
featureFlags,
|
|
2553
|
-
override: options.workflows?.enabled,
|
|
2554
|
-
configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
|
|
2555
|
-
}) };
|
|
2556
|
-
}
|
|
2557
|
-
options.inspection = await resolveInspectionEnabled({
|
|
2558
|
-
featureFlags,
|
|
2559
|
-
option: options.inspection
|
|
2560
|
-
});
|
|
2561
|
-
options.pgliteWorkers = await resolvePgliteWorkersEnabled({
|
|
2562
|
-
featureFlags,
|
|
2563
|
-
option: options.pgliteWorkers
|
|
2564
|
-
});
|
|
2565
|
-
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;
|
|
2566
2350
|
options.identity = {
|
|
2567
2351
|
...options.identity,
|
|
2568
2352
|
baseUrl: options.identity?.baseUrl ?? renownConfig.url,
|
|
2569
|
-
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)
|
|
2570
2354
|
};
|
|
2571
2355
|
logger.info("Feature flags: @flags", JSON.stringify({
|
|
2572
|
-
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
|
|
2356
|
+
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: options.enableDocumentModelSubgraphs,
|
|
2573
2357
|
MCP_ENABLED: options.mcp,
|
|
2574
2358
|
INSPECTION_ENABLED: options.inspection,
|
|
2575
2359
|
PH_PGLITE_WORKERS: options.pgliteWorkers,
|
|
@@ -2577,13 +2361,19 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2577
2361
|
}, null, 2));
|
|
2578
2362
|
let renown = null;
|
|
2579
2363
|
try {
|
|
2580
|
-
renown = await initRenown(
|
|
2364
|
+
renown = await initRenown({
|
|
2365
|
+
...options.identity,
|
|
2366
|
+
userDataDir
|
|
2367
|
+
});
|
|
2581
2368
|
} catch (e) {
|
|
2582
2369
|
logger.warn("Failed to initialize ConnectCrypto: @error", e);
|
|
2583
2370
|
if (options.identity.requireExisting) throw new Error("Identity required but failed to initialize. Run \"ph login\" first.", { cause: e });
|
|
2584
2371
|
}
|
|
2372
|
+
const reportError = deps.reportError ?? ((error) => {
|
|
2373
|
+
Sentry.captureException(error);
|
|
2374
|
+
});
|
|
2585
2375
|
try {
|
|
2586
|
-
return await initServer(serverPort, options, renown, renownConfig);
|
|
2376
|
+
return await initServer(serverPort, options, config, renown, renownConfig, reportError);
|
|
2587
2377
|
} catch (e) {
|
|
2588
2378
|
Sentry.captureException(e);
|
|
2589
2379
|
if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
|
|
@@ -2591,13 +2381,71 @@ const startSwitchboard = async (options = {}) => {
|
|
|
2591
2381
|
throw e;
|
|
2592
2382
|
}
|
|
2593
2383
|
};
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
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 });
|
|
2601
2449
|
}
|
|
2602
2450
|
/**
|
|
2603
2451
|
* Feeds the priority this server's request load and main-thread event-loop
|
|
@@ -2615,7 +2463,7 @@ function feedCatchUpPriority(priority, server) {
|
|
|
2615
2463
|
};
|
|
2616
2464
|
}
|
|
2617
2465
|
//#endregion
|
|
2618
|
-
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 };
|
|
2619
2467
|
|
|
2620
|
-
//# sourceMappingURL=server-
|
|
2621
|
-
//# debugId=
|
|
2468
|
+
//# sourceMappingURL=server-CtGBZlTg.mjs.map
|
|
2469
|
+
//# debugId=adb8b57f-cca7-5667-a44f-f042b16d51a1
|