@powerhousedao/switchboard 6.2.3-dev.7 → 6.2.3-dev.71
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/attachments/byte-grants.test.d.ts +2 -0
- package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
- package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
- package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
- package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
- package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
- package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
- package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
- package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
- package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
- package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
- package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
- package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
- package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
- package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
- package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
- package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
- package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
- package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
- package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
- package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
- package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
- package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
- package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
- package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
- package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
- package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
- package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
- package/.tsbuild/test/inspection-flag.test.d.ts +2 -0
- package/.tsbuild/test/inspection-flag.test.d.ts.map +1 -0
- package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
- package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
- package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
- package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
- package/.tsbuild/test/observability-signals.test.d.ts +2 -0
- package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
- package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
- package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
- package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
- package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
- package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
- package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
- package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
- package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
- package/.tsbuild/test/port-probe.test.d.ts +2 -0
- package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
- package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
- package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
- package/.tsbuild/test/shutdown.test.d.ts +2 -0
- package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
- package/.tsbuild/test/snapshot-writer.d.ts +18 -0
- package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
- package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
- package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/harness.d.ts +56 -0
- package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
- package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
- package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
- package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
- package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
- package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
- package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
- package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
- package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
- package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
- package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
- package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
- package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
- package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/.tsbuild/tsdown.config.d.ts.map +1 -1
- package/.tsbuild/vitest.config.d.ts.map +1 -1
- package/Auth.md +144 -2
- package/CHANGELOG.md +869 -0
- package/README.md +47 -10
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +50 -50
- package/dist/index.mjs.map +1 -1
- package/dist/install-packages.d.mts +2 -1
- package/dist/install-packages.mjs +2 -2
- package/dist/install-packages.mjs.map +1 -1
- package/dist/mcp-SsBK14Jm.mjs +32 -0
- package/dist/mcp-SsBK14Jm.mjs.map +1 -0
- package/dist/migrate.d.mts +2 -1
- package/dist/migrate.mjs +4 -3
- package/dist/migrate.mjs.map +1 -1
- package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
- package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
- package/dist/plugins/attachments.d.mts +33 -0
- package/dist/plugins/attachments.d.mts.map +1 -0
- package/dist/plugins/attachments.mjs +4 -0
- package/dist/plugins/mcp.d.mts +31 -0
- package/dist/plugins/mcp.d.mts.map +1 -0
- package/dist/plugins/mcp.mjs +4 -0
- package/dist/plugins/privacy.d.mts +22 -0
- package/dist/plugins/privacy.d.mts.map +1 -0
- package/dist/plugins/privacy.mjs +4 -0
- package/dist/plugins/workflows.d.mts +79 -0
- package/dist/plugins/workflows.d.mts.map +1 -0
- package/dist/plugins/workflows.mjs +4 -0
- package/dist/privacy-BsFl7GzK.mjs +118 -0
- package/dist/privacy-BsFl7GzK.mjs.map +1 -0
- package/dist/{server-CiKkVE6g.mjs → server-Be1vmpxu.mjs} +1213 -244
- package/dist/server-Be1vmpxu.mjs.map +1 -0
- package/dist/server.d.mts +208 -45
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +4 -5
- package/dist/{utils-Baw7rThP.mjs → utils-Dh845exv.mjs} +48 -9
- package/dist/utils-Dh845exv.mjs.map +1 -0
- package/dist/utils.d.mts +10 -5
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +3 -3
- package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
- package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
- package/dist/workflows-fsBcElEi.mjs +1382 -0
- package/dist/workflows-fsBcElEi.mjs.map +1 -0
- package/package.json +50 -20
- package/scripts/install-packages.sh +0 -0
- package/test/attachment-reference-read-model.test.ts +6 -1
- package/test/attachments/auth.test.ts +85 -0
- package/test/attachments/byte-grants.test.ts +290 -0
- package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
- package/test/attachments/download-target.test.ts +201 -32
- package/test/attachments/index.test.ts +47 -4
- package/test/attachments/reserve-metadata-parity.test.ts +96 -0
- package/test/attachments/routes-integration.test.ts +60 -4
- package/test/attachments/routes.test.ts +271 -24
- package/test/attachments/service-config.test.ts +13 -3
- package/test/attachments/url-signer.test.ts +105 -0
- package/test/boot-create-signature-policy.test.ts +108 -0
- package/test/boot-inspection-enabled.test.ts +150 -0
- package/test/boot-mcp-enabled.test.ts +130 -0
- package/test/boot-privacy.test.ts +243 -0
- package/test/boot-unsupported-stored-documents.test.ts +213 -0
- package/test/boot-without-renown.test.ts +81 -0
- package/test/boot-without-require-signatures.test.ts +74 -0
- package/test/boot-worker-trust-policy.test.ts +90 -0
- package/test/boot-workflow-singleton-conflict.test.ts +107 -0
- package/test/boot-workflow-singleton-retry.test.ts +133 -0
- package/test/builder-defaults.test.ts +80 -0
- package/test/create-signature-policy.test.ts +69 -0
- package/test/default-drive-slug.test.ts +97 -0
- package/test/durable-node-fs-pg16.test.ts +80 -0
- package/test/fatal-shutdown.test.ts +165 -0
- package/test/inspection-flag.test.ts +62 -0
- package/test/inspection-throttle.test.ts +23 -0
- package/test/mcp-flag.test.ts +56 -0
- package/test/observability-signals.test.ts +131 -0
- package/test/pglite-dialect.test.ts +217 -2
- package/test/pglite-preflight.test.ts +313 -0
- package/test/pglite-storage-dirs.test.ts +103 -0
- package/test/pglite-version.test.ts +9 -1
- package/test/plugin-config-schemas.test.ts +83 -0
- package/test/plugin-presence.test.ts +269 -0
- package/test/port-probe.test.ts +45 -0
- package/test/renown-trust-policy.test.ts +315 -0
- package/test/shutdown.test.ts +278 -0
- package/test/snapshot-writer.ts +94 -0
- package/test/unsupported-stored-documents.test.ts +72 -0
- package/test/worker-pool.test.ts +27 -1
- package/test/workflow/harness.ts +289 -0
- package/test/workflow/oauth.test.ts +214 -0
- package/test/workflow/resolvers.test.ts +357 -0
- package/test/workflow/webhook-dedupe.test.ts +295 -0
- package/test/workflow/webhook-signed.test.ts +509 -0
- package/test/workflow/webhook-trigger-test.test.ts +82 -0
- package/test/workflow/webhook-unsigned.test.ts +345 -0
- package/test/workflow-reactor-access.test.ts +384 -0
- package/test/workflow-reactor-enforcement.test.ts +808 -0
- package/test/workflow-read-gate.test.ts +213 -0
- package/test/workflow-runtime.test.ts +1122 -0
- package/test/workflows-plugin-config.test.ts +77 -0
- package/tsconfig.json +11 -2
- package/tsdown.config.ts +9 -1
- package/dist/server-CiKkVE6g.mjs.map +0 -1
- package/dist/utils-Baw7rThP.mjs.map +0 -1
|
@@ -1,34 +1,42 @@
|
|
|
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 {
|
|
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]="eb9f9f91-b014-5be8-a29c-f37efe0c4ad0")}catch(e){}}();
|
|
3
|
+
import { _ as triggerFatalShutdown, a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as installFatalErrorShutdown, h as workflowSingletonLossHandler, l as assertWorkflowPackageLoadable, m as retryWorkflowSingleton, p as resolveWorkflowsEnabled, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-fsBcElEi.mjs";
|
|
4
|
+
import { i as startPrivacy, r as resolvePrivacy, t as privacyPlugin } from "./privacy-BsFl7GzK.mjs";
|
|
5
|
+
import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
|
|
6
|
+
import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-Dh845exv.mjs";
|
|
7
|
+
import { createRequire, register } from "node:module";
|
|
8
|
+
import { metrics, trace } from "@opentelemetry/api";
|
|
5
9
|
import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
|
|
6
10
|
import * as Sentry from "@sentry/node";
|
|
7
|
-
import { childLogger,
|
|
11
|
+
import { childLogger, setLogLevel } from "document-model";
|
|
8
12
|
import dotenv from "dotenv";
|
|
9
13
|
import { getConfig } from "@powerhousedao/config/node";
|
|
10
14
|
import { existsSync, promises, realpathSync } from "node:fs";
|
|
11
|
-
import path from "node:path";
|
|
12
|
-
import {
|
|
13
|
-
import { ChannelScheme, DriveCollectionId, EventBus, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
|
|
14
|
-
import { HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, getUniqueDocumentModels, initializeAndStartAPI, resolveRenownConfig } from "@powerhousedao/reactor-api";
|
|
15
|
+
import path, { resolve } from "node:path";
|
|
16
|
+
import { createDurableNodeFs, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, syncTree } from "@powerhousedao/reactor-api/pglite-node";
|
|
17
|
+
import { ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
|
|
18
|
+
import { HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
|
|
15
19
|
import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
|
|
16
|
-
import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget } from "@powerhousedao/reactor-attachments";
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
20
|
+
import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
21
|
+
import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
|
|
22
|
+
import { DriveNodeView, NodeProcessor, ReactorDriveClient } from "@powerhousedao/reactor-drive";
|
|
23
|
+
import { REACTOR_DRIVE_SUBGRAPH_NAME, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive/subgraph";
|
|
24
|
+
import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
|
|
19
25
|
import { Kysely, PostgresDialect } from "kysely";
|
|
20
26
|
import net from "node:net";
|
|
21
27
|
import path$1 from "path";
|
|
22
28
|
import { Pool } from "pg";
|
|
23
29
|
import { Readable } from "node:stream";
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
30
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
31
|
+
import { z } from "zod";
|
|
32
|
+
import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
|
|
33
|
+
import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
26
34
|
import { readFile } from "node:fs/promises";
|
|
27
35
|
import os from "node:os";
|
|
28
|
-
import { fileURLToPath } from "node:url";
|
|
36
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
29
37
|
import { EnvVarProvider } from "@openfeature/env-var-provider";
|
|
30
38
|
import { OpenFeature } from "@openfeature/server-sdk";
|
|
31
|
-
import {
|
|
39
|
+
import { defaultStoreDirs, resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
|
|
32
40
|
//#region src/pglite-version.ts
|
|
33
41
|
const SUPPORTED_PG_MAJORS = [16, 17];
|
|
34
42
|
async function readPgVersionFile(dataDir) {
|
|
@@ -59,11 +67,63 @@ async function loadPGliteModule(major) {
|
|
|
59
67
|
if (major === 16) return await import("pglite-legacy-02");
|
|
60
68
|
return import("@electric-sql/pglite");
|
|
61
69
|
}
|
|
70
|
+
/** The stock NodeFS class of the PGlite module that opens `major` dirs. */
|
|
71
|
+
async function loadNodeFsClass(major) {
|
|
72
|
+
if (major === 16) return (await import("pglite-legacy-02/nodefs")).NodeFS;
|
|
73
|
+
return (await import("@electric-sql/pglite/nodefs")).NodeFS;
|
|
74
|
+
}
|
|
75
|
+
/** Opens a converted dir over stock NodeFS so the conversion can check it. */
|
|
76
|
+
async function openForVerify(major, dataDir) {
|
|
77
|
+
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(", ")})`);
|
|
78
|
+
const [{ PGlite }, NodeFS] = await Promise.all([loadPGliteModule(major), loadNodeFsClass(major)]);
|
|
79
|
+
const pg = new PGlite({ fs: new NodeFS(dataDir) });
|
|
80
|
+
await pg.waitReady;
|
|
81
|
+
return pg;
|
|
82
|
+
}
|
|
62
83
|
async function loadPgDump(major) {
|
|
63
84
|
if (major === 16) return (await import("pglite-tools-legacy-02/pg_dump")).pgDump;
|
|
64
85
|
return (await import("@electric-sql/pglite-tools/pg_dump")).pgDump;
|
|
65
86
|
}
|
|
66
87
|
//#endregion
|
|
88
|
+
//#region src/profiler.ts
|
|
89
|
+
let started = false;
|
|
90
|
+
async function initProfilerFromEnv(env) {
|
|
91
|
+
if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;
|
|
92
|
+
started = true;
|
|
93
|
+
const { PYROSCOPE_SERVER_ADDRESS: serverAddress, PYROSCOPE_APPLICATION_NAME: appName, PYROSCOPE_USER: basicAuthUser, PYROSCOPE_PASSWORD: basicAuthPassword, PYROSCOPE_WALL_ENABLED: wallEnabled, PYROSCOPE_HEAP_ENABLED: heapEnabled } = env;
|
|
94
|
+
return initProfiler({
|
|
95
|
+
serverAddress,
|
|
96
|
+
appName,
|
|
97
|
+
basicAuthUser,
|
|
98
|
+
basicAuthPassword,
|
|
99
|
+
wall: {
|
|
100
|
+
samplingDurationMs: 1e4,
|
|
101
|
+
samplingIntervalMicros: 1e4,
|
|
102
|
+
collectCpuTime: true
|
|
103
|
+
},
|
|
104
|
+
heap: {
|
|
105
|
+
samplingIntervalBytes: 524288,
|
|
106
|
+
stackDepth: 64
|
|
107
|
+
}
|
|
108
|
+
}, {
|
|
109
|
+
wallEnabled: wallEnabled !== "false",
|
|
110
|
+
heapEnabled: heapEnabled === "true"
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
async function initProfiler(options, flags = {
|
|
114
|
+
wallEnabled: true,
|
|
115
|
+
heapEnabled: false
|
|
116
|
+
}) {
|
|
117
|
+
console.log("Initializing Pyroscope profiler at:", options?.serverAddress);
|
|
118
|
+
console.log(" Wall profiling:", flags.wallEnabled ? "enabled" : "disabled");
|
|
119
|
+
console.log(" Heap profiling:", flags.heapEnabled ? "enabled" : "disabled");
|
|
120
|
+
const { default: Pyroscope } = await import("@pyroscope/nodejs");
|
|
121
|
+
Pyroscope.init(options);
|
|
122
|
+
if (flags.wallEnabled) Pyroscope.startWallProfiling();
|
|
123
|
+
Pyroscope.startCpuProfiling();
|
|
124
|
+
if (flags.heapEnabled) Pyroscope.startHeapProfiling();
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
67
127
|
//#region src/attachments/auth.ts
|
|
68
128
|
const ANONYMOUS_ACTOR = {
|
|
69
129
|
user: void 0,
|
|
@@ -74,7 +134,15 @@ const ANONYMOUS_ACTOR = {
|
|
|
74
134
|
* enabled, the request must carry a verifiable Bearer token. The handler always
|
|
75
135
|
* receives an actor context: the verified bearer user when auth is enabled, or
|
|
76
136
|
* the anonymous context when it is disabled. With `allowAnonymous`, a missing
|
|
77
|
-
* bearer yields an anonymous actor with `authEnabled: true` instead of a 401
|
|
137
|
+
* bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —
|
|
138
|
+
* unless `requireAuthenticatedCaller` says the deployment refuses anonymous
|
|
139
|
+
* callers outright, which overrides it.
|
|
140
|
+
*
|
|
141
|
+
* With no `authService` there is no bearer to read and every caller is
|
|
142
|
+
* anonymous, so nothing is refused here. That combination cannot carry the
|
|
143
|
+
* floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with
|
|
144
|
+
* `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity
|
|
145
|
+
* resolution is what builds the service.
|
|
78
146
|
*/
|
|
79
147
|
function requireAuth(authService, handler, options) {
|
|
80
148
|
if (!authService) return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);
|
|
@@ -96,11 +164,13 @@ function requireAuth(authService, handler, options) {
|
|
|
96
164
|
res.end(body);
|
|
97
165
|
return;
|
|
98
166
|
}
|
|
99
|
-
if (
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
167
|
+
if (!result.user) {
|
|
168
|
+
if (options?.requireAuthenticatedCaller === true || result.auth_enabled && !options?.allowAnonymous) {
|
|
169
|
+
res.statusCode = 401;
|
|
170
|
+
res.setHeader("Content-Type", "application/json");
|
|
171
|
+
res.end(JSON.stringify({ error: "Authentication required" }));
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
104
174
|
}
|
|
105
175
|
await handler(req, res, body, {
|
|
106
176
|
user: result.user,
|
|
@@ -118,20 +188,25 @@ function requireAuth(authService, handler, options) {
|
|
|
118
188
|
* wrapping you must call `api.httpAdapter.mountNodeRoute` directly.
|
|
119
189
|
*
|
|
120
190
|
* `allowAnonymous` is reserved for routes whose handlers make a per-document
|
|
121
|
-
* authorization decision themselves; identity-only routes must not use it.
|
|
191
|
+
* authorization decision themselves; identity-only routes must not use it. It
|
|
192
|
+
* is also not the last word: a deployment that refuses anonymous callers
|
|
193
|
+
* (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes
|
|
194
|
+
* are mounted on the HTTP adapter and never reach the fetch chain that carries
|
|
195
|
+
* that floor for GraphQL. The flag is read from the API, so every route
|
|
196
|
+
* mounted through here inherits it without each one remembering to.
|
|
122
197
|
*/
|
|
123
198
|
function mountAuthenticatedNodeRoute(api, method, path, handler, options) {
|
|
124
|
-
|
|
199
|
+
const { rawBody, ...authOptions } = options ?? {};
|
|
200
|
+
api.httpAdapter.mountNodeRoute(method, path, requireAuth(api.authService, handler, {
|
|
201
|
+
...authOptions,
|
|
202
|
+
requireAuthenticatedCaller: api.requireAuthenticatedCaller
|
|
203
|
+
}), { rawBody: rawBody ?? false });
|
|
125
204
|
}
|
|
126
205
|
//#endregion
|
|
127
206
|
//#region src/attachments/routes.ts
|
|
128
|
-
const logger$
|
|
207
|
+
const logger$2 = childLogger(["switchboard", "attachments"]);
|
|
129
208
|
const RETRY_AFTER_SECONDS = 5;
|
|
130
209
|
const HASH_PATTERN = /^[a-f0-9]{64}$/i;
|
|
131
|
-
const CONTROL_CHARS = /[\x00-\x1f\x7f]/;
|
|
132
|
-
const MIME_TYPE_PATTERN = /^[!#$%&'*+\-.^_`|~\w]+\/[!#$%&'*+\-.^_`|~\w]+(?:\s*;\s*[!#$%&'*+\-.^_`|~\w]+=(?:[!#$%&'*+\-.^_`|~\w]+|"(?:[^"\\\r\n]|\\[^\r\n])*"))*$/;
|
|
133
|
-
const MAX_FILENAME_LEN = 255;
|
|
134
|
-
const MAX_MIMETYPE_LEN = 255;
|
|
135
210
|
function sendJson(res, status, body) {
|
|
136
211
|
res.statusCode = status;
|
|
137
212
|
res.setHeader("Content-Type", "application/json");
|
|
@@ -150,7 +225,7 @@ function statusForError(err) {
|
|
|
150
225
|
function sendErrorFromException(res, err) {
|
|
151
226
|
const status = statusForError(err);
|
|
152
227
|
if (status >= 500) {
|
|
153
|
-
logger$
|
|
228
|
+
logger$2.error("Attachment route error: @error", err);
|
|
154
229
|
sendError(res, status, "Internal error");
|
|
155
230
|
return;
|
|
156
231
|
}
|
|
@@ -168,27 +243,34 @@ async function readJsonBody(req, body) {
|
|
|
168
243
|
function parseReserveOptions(input) {
|
|
169
244
|
if (input === null || typeof input !== "object") return null;
|
|
170
245
|
const obj = input;
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
246
|
+
const { mimeType, fileName } = obj;
|
|
247
|
+
const extension = obj.extension ?? null;
|
|
248
|
+
try {
|
|
249
|
+
validateReserveMetadata({
|
|
250
|
+
mimeType,
|
|
251
|
+
fileName,
|
|
252
|
+
extension
|
|
253
|
+
});
|
|
254
|
+
} catch (err) {
|
|
255
|
+
if (err instanceof InvalidAttachmentMetadata) return null;
|
|
256
|
+
throw err;
|
|
257
|
+
}
|
|
258
|
+
if (typeof mimeType !== "string" || typeof fileName !== "string") return null;
|
|
259
|
+
if (extension !== null && typeof extension !== "string") return null;
|
|
178
260
|
if (obj.clientHash !== void 0) {
|
|
179
261
|
if (typeof obj.clientHash !== "string" || !HASH_PATTERN.test(obj.clientHash)) return null;
|
|
180
262
|
if (typeof obj.sizeBytes !== "number" || !Number.isInteger(obj.sizeBytes) || obj.sizeBytes <= 0 || !Number.isSafeInteger(obj.sizeBytes)) return null;
|
|
181
263
|
return {
|
|
182
|
-
mimeType
|
|
183
|
-
fileName
|
|
264
|
+
mimeType,
|
|
265
|
+
fileName,
|
|
184
266
|
extension,
|
|
185
267
|
clientHash: obj.clientHash.toLowerCase(),
|
|
186
268
|
sizeBytes: obj.sizeBytes
|
|
187
269
|
};
|
|
188
270
|
}
|
|
189
271
|
return {
|
|
190
|
-
mimeType
|
|
191
|
-
fileName
|
|
272
|
+
mimeType,
|
|
273
|
+
fileName,
|
|
192
274
|
extension
|
|
193
275
|
};
|
|
194
276
|
}
|
|
@@ -279,24 +361,27 @@ function makeUploadHandler(attachments) {
|
|
|
279
361
|
}
|
|
280
362
|
};
|
|
281
363
|
}
|
|
282
|
-
function makeDownloadHandler(attachments) {
|
|
283
|
-
return async (req, res) => {
|
|
364
|
+
function makeDownloadHandler(attachments, attachmentAccess, urlSigner) {
|
|
365
|
+
return async (req, res, _body, actor) => {
|
|
284
366
|
const hash = extractParam(req, "hash");
|
|
285
367
|
if (!hash || !HASH_PATTERN.test(hash)) {
|
|
286
368
|
sendError(res, 400, "Invalid attachment hash");
|
|
287
369
|
return;
|
|
288
370
|
}
|
|
371
|
+
const canonicalHash = hash.toLowerCase();
|
|
372
|
+
const grant = await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner);
|
|
373
|
+
if (!admitGrant(res, grant)) return;
|
|
289
374
|
const controller = new AbortController();
|
|
290
375
|
req.once("close", () => controller.abort());
|
|
291
|
-
const canonicalHash = hash.toLowerCase();
|
|
292
376
|
let response;
|
|
293
377
|
try {
|
|
294
|
-
response = await attachments.store.get(canonicalHash, controller.signal);
|
|
378
|
+
response = await attachments.store.get(canonicalHash, controller.signal, grant.documentId);
|
|
295
379
|
} catch (err) {
|
|
296
380
|
if (err instanceof AttachmentPending) {
|
|
297
381
|
res.statusCode = 202;
|
|
382
|
+
res.setHeader("Cache-Control", "private");
|
|
298
383
|
res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
|
|
299
|
-
res.setHeader("Attachment-Pending",
|
|
384
|
+
res.setHeader("Attachment-Pending", buildPendingHeader({
|
|
300
385
|
expiresAtUtc: err.expiresAtUtc,
|
|
301
386
|
...err.metadata ?? {}
|
|
302
387
|
}));
|
|
@@ -308,15 +393,41 @@ function makeDownloadHandler(attachments) {
|
|
|
308
393
|
}
|
|
309
394
|
const { header, body } = response;
|
|
310
395
|
res.statusCode = 200;
|
|
396
|
+
res.setHeader("Cache-Control", "private");
|
|
311
397
|
res.setHeader("Content-Type", header.mimeType);
|
|
312
398
|
res.setHeader("Content-Length", String(header.sizeBytes));
|
|
313
399
|
res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
|
|
314
400
|
res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
|
|
315
|
-
Readable.fromWeb(body)
|
|
401
|
+
const source = Readable.fromWeb(body);
|
|
402
|
+
source.once("error", (err) => handleDownloadStreamError(res, hash, err));
|
|
403
|
+
source.pipe(res);
|
|
316
404
|
};
|
|
317
405
|
}
|
|
406
|
+
function handleDownloadStreamError(res, hash, err) {
|
|
407
|
+
if (res.headersSent) {
|
|
408
|
+
logger$2.error("Attachment stream failed mid-download: @error", err);
|
|
409
|
+
res.destroy();
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
res.removeHeader("Content-Length");
|
|
413
|
+
res.removeHeader("Content-Disposition");
|
|
414
|
+
res.removeHeader("Attachment-Metadata");
|
|
415
|
+
if (err?.code === "ENOENT") {
|
|
416
|
+
logger$2.warn("Attachment @hash is recorded as available but its blob is missing", hash);
|
|
417
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
logger$2.error("Attachment stream failed before sending: @error", err);
|
|
421
|
+
sendError(res, 500, "Internal error");
|
|
422
|
+
}
|
|
423
|
+
function toAsciiJson(value) {
|
|
424
|
+
return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
425
|
+
}
|
|
426
|
+
function buildPendingHeader(pending) {
|
|
427
|
+
return toAsciiJson(pending);
|
|
428
|
+
}
|
|
318
429
|
function buildMetadataHeader(header) {
|
|
319
|
-
return
|
|
430
|
+
return toAsciiJson({
|
|
320
431
|
mimeType: header.mimeType,
|
|
321
432
|
fileName: header.fileName,
|
|
322
433
|
sizeBytes: header.sizeBytes,
|
|
@@ -325,14 +436,15 @@ function buildMetadataHeader(header) {
|
|
|
325
436
|
lastAccessedAtUtc: header.lastAccessedAtUtc
|
|
326
437
|
});
|
|
327
438
|
}
|
|
328
|
-
function makeStatHandler(attachments) {
|
|
329
|
-
return async (req, res) => {
|
|
439
|
+
function makeStatHandler(attachments, attachmentAccess, urlSigner) {
|
|
440
|
+
return async (req, res, _body, actor) => {
|
|
330
441
|
const hash = extractParam(req, "hash");
|
|
331
442
|
if (!hash || !HASH_PATTERN.test(hash)) {
|
|
332
443
|
sendError(res, 400, "Invalid attachment hash");
|
|
333
444
|
return;
|
|
334
445
|
}
|
|
335
446
|
const canonicalHash = hash.toLowerCase();
|
|
447
|
+
if (!admitGrant(res, await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner))) return;
|
|
336
448
|
let header;
|
|
337
449
|
try {
|
|
338
450
|
header = await attachments.store.stat(canonicalHash);
|
|
@@ -340,10 +452,11 @@ function makeStatHandler(attachments) {
|
|
|
340
452
|
sendErrorFromException(res, err);
|
|
341
453
|
return;
|
|
342
454
|
}
|
|
455
|
+
res.setHeader("Cache-Control", "private");
|
|
343
456
|
if (header.status === "pending") {
|
|
344
457
|
res.statusCode = 202;
|
|
345
458
|
res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
|
|
346
|
-
res.setHeader("Attachment-Pending",
|
|
459
|
+
res.setHeader("Attachment-Pending", buildPendingHeader({
|
|
347
460
|
expiresAtUtc: header.expiresAtUtc,
|
|
348
461
|
mimeType: header.mimeType,
|
|
349
462
|
fileName: header.fileName,
|
|
@@ -395,7 +508,37 @@ function extractParam(req, name) {
|
|
|
395
508
|
}
|
|
396
509
|
const MAX_DOCUMENT_ID_LEN = 512;
|
|
397
510
|
const ATTACHMENT_NOT_FOUND_BODY = { error: "Attachment not found" };
|
|
398
|
-
const MAX_DOWNLOAD_TARGET_TTL_SECONDS =
|
|
511
|
+
const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 604800;
|
|
512
|
+
/**
|
|
513
|
+
* How long a download target may live, by default.
|
|
514
|
+
*
|
|
515
|
+
* The authorization behind a presigned URL is decided once, when it is issued,
|
|
516
|
+
* and the URL keeps working until it expires however the document's policy
|
|
517
|
+
* changes in between. A week of that is a revocation that does not revoke: an
|
|
518
|
+
* account deactivated, a company reassigned or a group left, and the bytes stay
|
|
519
|
+
* fetchable by anyone holding the link. Minutes are enough to open a file;
|
|
520
|
+
* days are only enough to lose control of it.
|
|
521
|
+
*
|
|
522
|
+
* A deployment that needs longer sets ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS,
|
|
523
|
+
* still bounded by the signing ceiling above.
|
|
524
|
+
*/
|
|
525
|
+
const DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;
|
|
526
|
+
/**
|
|
527
|
+
* The ceiling in force, read per call so a deployment can set it without the
|
|
528
|
+
* value being frozen at import — which is also what lets a test cover it.
|
|
529
|
+
* Anything unparseable falls back to the default rather than to the maximum:
|
|
530
|
+
* a typo must not quietly widen the window it was meant to narrow.
|
|
531
|
+
*/
|
|
532
|
+
function downloadTargetTtlCapSeconds() {
|
|
533
|
+
const configured = process.env.ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS;
|
|
534
|
+
if (configured === void 0) return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
|
|
535
|
+
const parsed = Number(configured);
|
|
536
|
+
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
537
|
+
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}`);
|
|
538
|
+
return DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS;
|
|
539
|
+
}
|
|
540
|
+
return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
|
|
541
|
+
}
|
|
399
542
|
/**
|
|
400
543
|
* Returns the single `documentId` query value, or null when it is missing,
|
|
401
544
|
* duplicated, blank, or oversized. Validation happens before authorization so
|
|
@@ -416,29 +559,95 @@ function extractSingleDocumentId(req) {
|
|
|
416
559
|
return value;
|
|
417
560
|
}
|
|
418
561
|
/**
|
|
419
|
-
* Returns the
|
|
420
|
-
*
|
|
421
|
-
*
|
|
562
|
+
* Returns the target TTL in seconds, or "invalid" when the caller's own value
|
|
563
|
+
* is malformed (duplicated, non-integer, or non-positive).
|
|
564
|
+
*
|
|
565
|
+
* The cap applies whether or not the caller asked for a lifetime: omitting
|
|
566
|
+
* `expiresIn` used to fall through to whatever the storage backend was
|
|
567
|
+
* configured with, which would make the ceiling something a client opts out of
|
|
568
|
+
* by saying nothing.
|
|
422
569
|
*/
|
|
423
570
|
function extractExpiresIn(req) {
|
|
424
|
-
|
|
571
|
+
const cap = downloadTargetTtlCapSeconds();
|
|
572
|
+
if (!req.url) return cap;
|
|
425
573
|
let url;
|
|
426
574
|
try {
|
|
427
575
|
url = new URL(req.url, "http://switchboard.invalid");
|
|
428
576
|
} catch {
|
|
429
|
-
return;
|
|
577
|
+
return cap;
|
|
430
578
|
}
|
|
431
579
|
const values = url.searchParams.getAll("expiresIn");
|
|
432
|
-
if (values.length === 0) return
|
|
580
|
+
if (values.length === 0) return cap;
|
|
433
581
|
if (values.length > 1) return "invalid";
|
|
434
582
|
const parsed = Number(values[0]);
|
|
435
583
|
if (!Number.isInteger(parsed) || parsed <= 0) return "invalid";
|
|
436
|
-
return Math.min(parsed,
|
|
584
|
+
return Math.min(parsed, cap);
|
|
585
|
+
}
|
|
586
|
+
function singleQueryValue(params, name) {
|
|
587
|
+
const values = params.getAll(name);
|
|
588
|
+
return values.length === 1 ? values[0] : null;
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Byte routes serve only under a grant: a signed URL minted by the
|
|
592
|
+
* download-target route, or a documentId the caller may read the attachment
|
|
593
|
+
* through. A signed request is judged by its signature alone.
|
|
594
|
+
*/
|
|
595
|
+
async function resolveByteGrant(req, hash, actor, attachmentAccess, urlSigner) {
|
|
596
|
+
let params;
|
|
597
|
+
try {
|
|
598
|
+
params = new URL(req.url ?? "", "http://switchboard.invalid").searchParams;
|
|
599
|
+
} catch {
|
|
600
|
+
return { kind: "denied" };
|
|
601
|
+
}
|
|
602
|
+
const documentId = extractSingleDocumentId(req);
|
|
603
|
+
if (documentId === null) return { kind: "denied" };
|
|
604
|
+
if (params.has("signature") || params.has("expires")) {
|
|
605
|
+
const signature = singleQueryValue(params, "signature");
|
|
606
|
+
const expires = singleQueryValue(params, "expires");
|
|
607
|
+
if (!urlSigner || signature === null || expires === null) return { kind: "denied" };
|
|
608
|
+
return urlSigner.verify(hash, documentId, expires, signature) ? {
|
|
609
|
+
kind: "granted",
|
|
610
|
+
documentId
|
|
611
|
+
} : { kind: "denied" };
|
|
612
|
+
}
|
|
613
|
+
let decision;
|
|
614
|
+
try {
|
|
615
|
+
decision = await attachmentAccess.canReadAttachment({
|
|
616
|
+
documentId,
|
|
617
|
+
attachmentRef: createRef(hash),
|
|
618
|
+
userAddress: actor?.user?.address,
|
|
619
|
+
appKey: actor?.user?.appKey
|
|
620
|
+
});
|
|
621
|
+
} catch (err) {
|
|
622
|
+
logger$2.error("Attachment access decision failed: @error", err);
|
|
623
|
+
return { kind: "error" };
|
|
624
|
+
}
|
|
625
|
+
if (decision.kind === "projection-unavailable") return { kind: "unavailable" };
|
|
626
|
+
if (decision.kind === "denied") return { kind: "denied" };
|
|
627
|
+
return {
|
|
628
|
+
kind: "granted",
|
|
629
|
+
documentId: decision.documentId
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
/** Answers a refused grant; true when the request may proceed. */
|
|
633
|
+
function admitGrant(res, grant) {
|
|
634
|
+
switch (grant.kind) {
|
|
635
|
+
case "granted": return true;
|
|
636
|
+
case "denied":
|
|
637
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
638
|
+
return false;
|
|
639
|
+
case "unavailable":
|
|
640
|
+
sendError(res, 503, "Attachment downloads are temporarily unavailable");
|
|
641
|
+
return false;
|
|
642
|
+
case "error":
|
|
643
|
+
sendError(res, 500, "Internal error");
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
437
646
|
}
|
|
438
647
|
/**
|
|
439
648
|
* Base URL of this Switchboard as seen by the caller, used to build
|
|
440
|
-
* filesystem `switchboard` download targets that point back at the
|
|
441
|
-
*
|
|
649
|
+
* filesystem `switchboard` download targets that point back at the signed
|
|
650
|
+
* byte route.
|
|
442
651
|
*/
|
|
443
652
|
function requestBaseUrl(req) {
|
|
444
653
|
const forwardedProto = req.headers["x-forwarded-proto"];
|
|
@@ -448,7 +657,7 @@ function requestBaseUrl(req) {
|
|
|
448
657
|
if (!host) return null;
|
|
449
658
|
return `${proto}://${host}`;
|
|
450
659
|
}
|
|
451
|
-
function makeDownloadTargetHandler(attachments, attachmentAccess) {
|
|
660
|
+
function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner) {
|
|
452
661
|
return async (req, res, _body, actor) => {
|
|
453
662
|
res.setHeader("Cache-Control", "no-store");
|
|
454
663
|
const hash = extractParam(req, "hash");
|
|
@@ -472,10 +681,11 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
|
|
|
472
681
|
decision = await attachmentAccess.canReadAttachment({
|
|
473
682
|
documentId,
|
|
474
683
|
attachmentRef: createRef(canonicalHash),
|
|
475
|
-
userAddress: actor?.user?.address
|
|
684
|
+
userAddress: actor?.user?.address,
|
|
685
|
+
appKey: actor?.user?.appKey
|
|
476
686
|
});
|
|
477
687
|
} catch (err) {
|
|
478
|
-
logger$
|
|
688
|
+
logger$2.error("Attachment access decision failed: @error", err);
|
|
479
689
|
sendError(res, 500, "Internal error");
|
|
480
690
|
return;
|
|
481
691
|
}
|
|
@@ -495,7 +705,7 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
|
|
|
495
705
|
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
496
706
|
return;
|
|
497
707
|
}
|
|
498
|
-
logger$
|
|
708
|
+
logger$2.error("Attachment metadata lookup failed: @error", err);
|
|
499
709
|
sendError(res, 500, "Internal error");
|
|
500
710
|
return;
|
|
501
711
|
}
|
|
@@ -511,17 +721,23 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
|
|
|
511
721
|
return;
|
|
512
722
|
}
|
|
513
723
|
else {
|
|
724
|
+
if (!urlSigner) {
|
|
725
|
+
sendError(res, 503, "Attachment download signing is not configured");
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
514
728
|
const base = requestBaseUrl(req);
|
|
515
729
|
if (!base) {
|
|
516
730
|
sendError(res, 500, "Internal error");
|
|
517
731
|
return;
|
|
518
732
|
}
|
|
733
|
+
const signed = urlSigner.sign(canonicalHash, decision.documentId, expiresIn);
|
|
519
734
|
try {
|
|
520
735
|
target = parseAttachmentDownloadTarget({
|
|
521
736
|
kind: "switchboard",
|
|
522
737
|
method: "GET",
|
|
523
|
-
url: `${base}/attachments/${canonicalHash}`,
|
|
524
|
-
headers: {}
|
|
738
|
+
url: `${base}/attachments/${canonicalHash}?${signed.query}`,
|
|
739
|
+
headers: {},
|
|
740
|
+
expiresAtUtc: signed.expiresAtUtc
|
|
525
741
|
});
|
|
526
742
|
} catch {
|
|
527
743
|
sendError(res, 500, "Internal error");
|
|
@@ -532,16 +748,82 @@ function makeDownloadTargetHandler(attachments, attachmentAccess) {
|
|
|
532
748
|
};
|
|
533
749
|
}
|
|
534
750
|
//#endregion
|
|
751
|
+
//#region src/attachments/url-signer.ts
|
|
752
|
+
const ATTACHMENT_URL_SIGNING_SECRET_ENV = "PH_ATTACHMENT_URL_SIGNING_SECRET";
|
|
753
|
+
const MIN_SECRET_LENGTH = 32;
|
|
754
|
+
const EXPIRES_PATTERN = /^[1-9]\d{0,15}$/;
|
|
755
|
+
const SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
756
|
+
var AttachmentUrlSigner = class {
|
|
757
|
+
secret;
|
|
758
|
+
now;
|
|
759
|
+
constructor(secret, now = Date.now) {
|
|
760
|
+
this.secret = secret;
|
|
761
|
+
this.now = now;
|
|
762
|
+
}
|
|
763
|
+
sign(hash, documentId, ttlSeconds) {
|
|
764
|
+
const expires = Math.floor(this.now() / 1e3) + ttlSeconds;
|
|
765
|
+
return {
|
|
766
|
+
query: new URLSearchParams({
|
|
767
|
+
documentId,
|
|
768
|
+
expires: String(expires),
|
|
769
|
+
signature: this.mac(hash, documentId, String(expires))
|
|
770
|
+
}).toString(),
|
|
771
|
+
expiresAtUtc: (/* @__PURE__ */ new Date(expires * 1e3)).toISOString()
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
verify(hash, documentId, expires, signature) {
|
|
775
|
+
if (!EXPIRES_PATTERN.test(expires) || !SIGNATURE_PATTERN.test(signature)) return false;
|
|
776
|
+
if (Number(expires) * 1e3 <= this.now()) return false;
|
|
777
|
+
const expected = Buffer.from(this.mac(hash, documentId, expires));
|
|
778
|
+
const presented = Buffer.from(signature);
|
|
779
|
+
return expected.length === presented.length && timingSafeEqual(expected, presented);
|
|
780
|
+
}
|
|
781
|
+
mac(hash, documentId, expires) {
|
|
782
|
+
return createHmac("sha256", this.secret).update(JSON.stringify([
|
|
783
|
+
"attachment-download/v1",
|
|
784
|
+
hash,
|
|
785
|
+
documentId,
|
|
786
|
+
expires
|
|
787
|
+
])).digest("base64url");
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
function resolveAttachmentUrlSigning(env = process.env) {
|
|
791
|
+
const secret = env[ATTACHMENT_URL_SIGNING_SECRET_ENV];
|
|
792
|
+
if (secret !== void 0) {
|
|
793
|
+
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`);
|
|
794
|
+
return {
|
|
795
|
+
status: "configured",
|
|
796
|
+
signer: new AttachmentUrlSigner(secret)
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
if (env.NODE_ENV === "production") return { status: "unconfigured" };
|
|
800
|
+
return {
|
|
801
|
+
status: "ephemeral",
|
|
802
|
+
signer: new AttachmentUrlSigner(randomBytes(32))
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
//#endregion
|
|
535
806
|
//#region src/attachments/index.ts
|
|
536
|
-
|
|
537
|
-
|
|
807
|
+
const logger$1 = childLogger(["switchboard", "attachments"]);
|
|
808
|
+
function registerAttachmentRoutes(api, options = {}) {
|
|
809
|
+
const { attachments, attachmentAccess } = api;
|
|
810
|
+
const urlSigner = options.urlSigner === void 0 ? signerFromEnvironment(attachments.backend?.kind ?? "filesystem") : options.urlSigner;
|
|
538
811
|
mountAuthenticatedNodeRoute(api, "POST", "/attachments/reservations", makeReserveHandler(attachments));
|
|
539
812
|
mountAuthenticatedNodeRoute(api, "GET", "/attachments/reservations/:reservationId", makeGetReservationHandler(attachments));
|
|
540
813
|
mountAuthenticatedNodeRoute(api, "DELETE", "/attachments/reservations/:reservationId", makeDeleteReservationHandler(attachments));
|
|
541
|
-
mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments));
|
|
542
|
-
mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments));
|
|
543
|
-
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments,
|
|
544
|
-
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments));
|
|
814
|
+
mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments), { rawBody: true });
|
|
815
|
+
mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
816
|
+
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
817
|
+
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
818
|
+
}
|
|
819
|
+
function signerFromEnvironment(backend) {
|
|
820
|
+
const signing = resolveAttachmentUrlSigning();
|
|
821
|
+
if (signing.status === "unconfigured") {
|
|
822
|
+
if (backend === "filesystem") logger$1.error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`);
|
|
823
|
+
return null;
|
|
824
|
+
}
|
|
825
|
+
if (signing.status === "ephemeral" && backend === "filesystem") logger$1.warn(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: signing attachment download URLs with a per-process secret`);
|
|
826
|
+
return signing.signer;
|
|
545
827
|
}
|
|
546
828
|
//#endregion
|
|
547
829
|
//#region src/attachment-reference-read-model.mts
|
|
@@ -596,12 +878,7 @@ async function registerAttachmentReferenceReadModelOnModule(clientModule, attach
|
|
|
596
878
|
*/
|
|
597
879
|
/** The models switchboard always registers alongside package models. */
|
|
598
880
|
function switchboardBaseDocumentModels() {
|
|
599
|
-
return [
|
|
600
|
-
documentModelDocumentModelModule,
|
|
601
|
-
driveDocumentModelModule,
|
|
602
|
-
reactorDriveDocumentModelModule,
|
|
603
|
-
ReactorGroupV1
|
|
604
|
-
];
|
|
881
|
+
return baseDocumentModels.map(([, model]) => model);
|
|
605
882
|
}
|
|
606
883
|
function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options = {}) {
|
|
607
884
|
const baseModels = options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];
|
|
@@ -617,7 +894,188 @@ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options
|
|
|
617
894
|
});
|
|
618
895
|
if (options.documentModelLoader) reactorBuilder.withDocumentModelLoader(options.documentModelLoader);
|
|
619
896
|
if (options.logger) reactorBuilder.withLogger(options.logger);
|
|
620
|
-
if (options.signer)
|
|
897
|
+
if (options.signer) {
|
|
898
|
+
clientBuilder.withSigner(options.signer);
|
|
899
|
+
reactorBuilder.withSigner(options.signer.signer, options.signer.workerSigner);
|
|
900
|
+
}
|
|
901
|
+
if (options.createSignaturePolicy) clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);
|
|
902
|
+
const trust = options.trustPolicy ?? options.signer;
|
|
903
|
+
if (trust?.trustPolicy) reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);
|
|
904
|
+
}
|
|
905
|
+
//#endregion
|
|
906
|
+
//#region src/plugins/attachments.mts
|
|
907
|
+
/** No entry config: presence is the whole activation. A typo'd config key
|
|
908
|
+
* fails at resolution instead of being silently ignored. */
|
|
909
|
+
const attachmentsPluginConfigSchema = z.strictObject({});
|
|
910
|
+
/**
|
|
911
|
+
* R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
|
|
912
|
+
* routes mount at onHttpMounting and the remote attachment service is created
|
|
913
|
+
* for the returned handle. Presence is activation — removed from the
|
|
914
|
+
* composition, the routes and service do not exist. NOT yet carved: the
|
|
915
|
+
* attachment-reference read model registered inside reactor construction
|
|
916
|
+
* (carve map: server.mts initializeClient) — it follows with the
|
|
917
|
+
* onReadModelsRegistering step in R2 step 2; until then it registers on both
|
|
918
|
+
* paths (a dormant read model when the plugin is absent, harmless).
|
|
919
|
+
*
|
|
920
|
+
* Inputs (carve map): api (routes), options.attachmentServiceUrl /
|
|
921
|
+
* PH_SWITCHBOARD_PUBLIC_URL / https + serverPort + renown (service config).
|
|
922
|
+
*/
|
|
923
|
+
const attachmentsPlugin = {
|
|
924
|
+
name: "switchboard-attachments",
|
|
925
|
+
appliesTo: "switchboard",
|
|
926
|
+
configSchema: attachmentsPluginConfigSchema,
|
|
927
|
+
hooks: { onHttpMounting: (ctx) => {
|
|
928
|
+
registerAttachmentRoutes(ctx.api);
|
|
929
|
+
ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
|
|
930
|
+
} }
|
|
931
|
+
};
|
|
932
|
+
//#endregion
|
|
933
|
+
//#region src/plugin-host.mts
|
|
934
|
+
/**
|
|
935
|
+
* R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:
|
|
936
|
+
* uniform-runners-plan/rewire/r2-carve-map.md). Behind
|
|
937
|
+
* FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing
|
|
938
|
+
* inline path byte-identically; flag on, the five subsystems run as built-in
|
|
939
|
+
* plugins through these hook moments. Subsystems carve one per commit; until
|
|
940
|
+
* a subsystem is carved, its inline code runs on BOTH paths and its plugin
|
|
941
|
+
* twin does not exist.
|
|
942
|
+
*
|
|
943
|
+
* Hook vocabulary (SwitchboardHooks), anchored to the boot spine:
|
|
944
|
+
* - transformServerOptions — after option/flag resolution, before anything opens
|
|
945
|
+
* - onReadModelsRegistering — inside reactor construction (build-time read models)
|
|
946
|
+
* - onHttpMounting — api exists; routes mount here
|
|
947
|
+
* - onSubgraphsRegistering — push into lateSubgraphs before the drain
|
|
948
|
+
* - onReactorReady — client + graphqlManager destructured
|
|
949
|
+
* - onDrivesReady — after core drive seeding / remote attachment
|
|
950
|
+
* - onShutdown — first in the subsystem-ordered teardown
|
|
951
|
+
*/
|
|
952
|
+
const PLUGIN_HOST_FLAG = "FEATURE_PLUGIN_HOST_ENABLED";
|
|
953
|
+
function isPluginHostEnabled(env = process.env) {
|
|
954
|
+
const value = env[PLUGIN_HOST_FLAG]?.trim().toLowerCase();
|
|
955
|
+
return value === "1" || value === "true";
|
|
956
|
+
}
|
|
957
|
+
/** Built-in plugins, pre-listed (the default composition until host.js
|
|
958
|
+
* entries map in R2 step 2). Subsystems join as R2 carves them. */
|
|
959
|
+
function builtinSwitchboardPlugins() {
|
|
960
|
+
const entry = {
|
|
961
|
+
enabled: true,
|
|
962
|
+
verbs: "*",
|
|
963
|
+
config: {}
|
|
964
|
+
};
|
|
965
|
+
return [
|
|
966
|
+
{
|
|
967
|
+
plugin: mcpPlugin,
|
|
968
|
+
provenance: "built-in",
|
|
969
|
+
entry: {
|
|
970
|
+
...entry,
|
|
971
|
+
module: "@powerhousedao/switchboard/plugins/mcp"
|
|
972
|
+
}
|
|
973
|
+
},
|
|
974
|
+
{
|
|
975
|
+
plugin: attachmentsPlugin,
|
|
976
|
+
provenance: "built-in",
|
|
977
|
+
entry: {
|
|
978
|
+
...entry,
|
|
979
|
+
module: "@powerhousedao/switchboard/plugins/attachments"
|
|
980
|
+
}
|
|
981
|
+
},
|
|
982
|
+
{
|
|
983
|
+
plugin: privacyPlugin,
|
|
984
|
+
provenance: "built-in",
|
|
985
|
+
entry: {
|
|
986
|
+
...entry,
|
|
987
|
+
module: "@powerhousedao/switchboard/plugins/privacy"
|
|
988
|
+
}
|
|
989
|
+
},
|
|
990
|
+
{
|
|
991
|
+
plugin: workflowsPlugin,
|
|
992
|
+
provenance: "built-in",
|
|
993
|
+
entry: {
|
|
994
|
+
...entry,
|
|
995
|
+
module: "@powerhousedao/switchboard/plugins/workflows"
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
];
|
|
999
|
+
}
|
|
1000
|
+
function createSwitchboardPluginHost(ctx, resolved) {
|
|
1001
|
+
resolved ??= builtinSwitchboardPlugins();
|
|
1002
|
+
const ordered = resolveOrder(resolved.map((r) => r.plugin));
|
|
1003
|
+
const contributions = mergeContributions(resolved.map((r) => ({
|
|
1004
|
+
plugin: r.plugin,
|
|
1005
|
+
provenance: r.provenance
|
|
1006
|
+
})));
|
|
1007
|
+
const fullCtx = {
|
|
1008
|
+
...ctx,
|
|
1009
|
+
contributions
|
|
1010
|
+
};
|
|
1011
|
+
const LOG = "[switchboard:plugins]";
|
|
1012
|
+
console.log(`${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(", ") || "(none)"}`);
|
|
1013
|
+
for (const r of resolved) {
|
|
1014
|
+
const cfg = Object.keys(r.entry.config ?? {});
|
|
1015
|
+
console.log(`${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` + (cfg.length ? ` config: {${cfg.join(", ")}}` : ""));
|
|
1016
|
+
}
|
|
1017
|
+
const ranBy = (hook) => ordered.filter((p) => p.hooks?.[hook]);
|
|
1018
|
+
const logHook = (hook) => {
|
|
1019
|
+
const names = ranBy(hook).map((p) => p.name);
|
|
1020
|
+
console.log(`${LOG} hook ${hook} → ${names.length ? names.join(", ") : "(no implementers)"}`);
|
|
1021
|
+
};
|
|
1022
|
+
return {
|
|
1023
|
+
plugins: ordered,
|
|
1024
|
+
ctx: fullCtx,
|
|
1025
|
+
transformOptions: (seed) => {
|
|
1026
|
+
logHook("transformServerOptions");
|
|
1027
|
+
return runTransformHook("transformServerOptions", ordered, fullCtx, seed);
|
|
1028
|
+
},
|
|
1029
|
+
observe: (hook) => {
|
|
1030
|
+
logHook(hook);
|
|
1031
|
+
return hook === "onShutdown" ? runObserveHookSequential(hook, ordered, fullCtx) : runObserveHook(hook, ordered, fullCtx);
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
//#endregion
|
|
1036
|
+
//#region src/env.mts
|
|
1037
|
+
function parseNonNegativeInt(raw, name) {
|
|
1038
|
+
if (raw === void 0 || raw.trim() === "") return;
|
|
1039
|
+
const value = Number.parseInt(raw, 10);
|
|
1040
|
+
if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
|
|
1041
|
+
return value;
|
|
1042
|
+
}
|
|
1043
|
+
//#endregion
|
|
1044
|
+
//#region src/projection-worker.mts
|
|
1045
|
+
const DEFAULT_DB_POOL_SIZE_PROJECTION = 8;
|
|
1046
|
+
const ON_TOKENS = [
|
|
1047
|
+
"1",
|
|
1048
|
+
"true",
|
|
1049
|
+
"on",
|
|
1050
|
+
"yes"
|
|
1051
|
+
];
|
|
1052
|
+
const OFF_TOKENS = [
|
|
1053
|
+
"0",
|
|
1054
|
+
"false",
|
|
1055
|
+
"off",
|
|
1056
|
+
"no"
|
|
1057
|
+
];
|
|
1058
|
+
/**
|
|
1059
|
+
* Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or
|
|
1060
|
+
* `input.enabled`, which wins when defined; null when off (the default).
|
|
1061
|
+
*/
|
|
1062
|
+
function resolveProjectionWorkerOptions(input, env) {
|
|
1063
|
+
if (!(input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false)) return null;
|
|
1064
|
+
const dbPoolSize = input?.dbPoolSize ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_PROJECTION, "REACTOR_DB_POOL_SIZE_PROJECTION") ?? DEFAULT_DB_POOL_SIZE_PROJECTION;
|
|
1065
|
+
if (dbPoolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool");
|
|
1066
|
+
return { dbPoolSize };
|
|
1067
|
+
}
|
|
1068
|
+
/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */
|
|
1069
|
+
function assertProjectionWorkerSupported(args) {
|
|
1070
|
+
if (args.dev) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary");
|
|
1071
|
+
if (!args.reactorDbUrl || !isPostgresUrl(args.reactorDbUrl)) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.");
|
|
1072
|
+
}
|
|
1073
|
+
function parseOnOff(raw) {
|
|
1074
|
+
if (raw === void 0 || raw.trim() === "") return;
|
|
1075
|
+
const token = raw.trim().toLowerCase();
|
|
1076
|
+
if (ON_TOKENS.includes(token)) return true;
|
|
1077
|
+
if (OFF_TOKENS.includes(token)) return false;
|
|
1078
|
+
throw new Error(`REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got "${raw}"`);
|
|
621
1079
|
}
|
|
622
1080
|
//#endregion
|
|
623
1081
|
//#region src/worker-pool.mts
|
|
@@ -700,6 +1158,20 @@ const BASE_MODEL_SPECIFIERS = [
|
|
|
700
1158
|
"@powerhousedao/reactor-drive",
|
|
701
1159
|
"@powerhousedao/reactor-group/document-models"
|
|
702
1160
|
];
|
|
1161
|
+
function isModelModule(value) {
|
|
1162
|
+
const candidate = value;
|
|
1163
|
+
return typeof candidate?.reducer === "function" && typeof candidate.documentModel?.global?.id === "string";
|
|
1164
|
+
}
|
|
1165
|
+
async function keepImportableSources(sources, logger) {
|
|
1166
|
+
const kept = [];
|
|
1167
|
+
for (const source of sources) try {
|
|
1168
|
+
const exports = await import(pathToFileURL(source.filePath).href);
|
|
1169
|
+
if (Object.values(exports).some(isModelModule)) kept.push(source);
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
logger.warn(`Worker model sources: "${source.filePath}" does not import, so workflow pieces will not see its models: ${String(error)}`);
|
|
1172
|
+
}
|
|
1173
|
+
return kept;
|
|
1174
|
+
}
|
|
703
1175
|
/**
|
|
704
1176
|
* Resolves base models and configured package identifiers to `{ filePath }`
|
|
705
1177
|
* sources for the reactor builder. Resolution to absolute paths happens here
|
|
@@ -708,10 +1180,10 @@ const BASE_MODEL_SPECIFIERS = [
|
|
|
708
1180
|
* packages. Unresolvable identifiers are skipped with a warning; the builder
|
|
709
1181
|
* fails the boot if a registered model ends up without an importable source.
|
|
710
1182
|
*/
|
|
711
|
-
async function resolveWorkerModelSources(packages, logger) {
|
|
1183
|
+
async function resolveWorkerModelSources(packages, logger, options = {}) {
|
|
712
1184
|
const sources = [];
|
|
713
1185
|
for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {
|
|
714
|
-
const filePath = await resolveModelModuleFile(identifier);
|
|
1186
|
+
const filePath = await resolveModelModuleFile(identifier) ?? await resolveRemoteSafely(identifier, options.resolveRemote, logger);
|
|
715
1187
|
if (!filePath) {
|
|
716
1188
|
logger.warn(`Worker model sources: no importable document-models entry for "${identifier}", skipping`);
|
|
717
1189
|
continue;
|
|
@@ -720,6 +1192,15 @@ async function resolveWorkerModelSources(packages, logger) {
|
|
|
720
1192
|
}
|
|
721
1193
|
return sources;
|
|
722
1194
|
}
|
|
1195
|
+
async function resolveRemoteSafely(identifier, resolveRemote, logger) {
|
|
1196
|
+
if (!resolveRemote) return null;
|
|
1197
|
+
try {
|
|
1198
|
+
return await resolveRemote(identifier);
|
|
1199
|
+
} catch (error) {
|
|
1200
|
+
logger.warn(`Worker model sources: could not cache "${identifier}" from the registry: ${String(error)}`);
|
|
1201
|
+
return null;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
723
1204
|
/**
|
|
724
1205
|
* Absolute file path of a source's models barrel. Mirrors reactor-api's
|
|
725
1206
|
* import-resolver: import.meta.resolve, then the project's node_modules via
|
|
@@ -814,48 +1295,15 @@ function parseWorkerCount(raw) {
|
|
|
814
1295
|
if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`REACTOR_WORKERS must be "auto" or a non-negative integer, got "${raw}"`);
|
|
815
1296
|
return value;
|
|
816
1297
|
}
|
|
817
|
-
function parseNonNegativeInt(raw, name) {
|
|
818
|
-
if (raw === void 0 || raw.trim() === "") return;
|
|
819
|
-
const value = Number.parseInt(raw, 10);
|
|
820
|
-
if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
|
|
821
|
-
return value;
|
|
822
|
-
}
|
|
823
1298
|
//#endregion
|
|
824
|
-
//#region src/
|
|
825
|
-
const
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
"
|
|
831
|
-
|
|
832
|
-
const OFF_TOKENS = [
|
|
833
|
-
"0",
|
|
834
|
-
"false",
|
|
835
|
-
"off",
|
|
836
|
-
"no"
|
|
837
|
-
];
|
|
838
|
-
/**
|
|
839
|
-
* Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or
|
|
840
|
-
* `input.enabled`, which wins when defined; null when off (the default).
|
|
841
|
-
*/
|
|
842
|
-
function resolveProjectionWorkerOptions(input, env) {
|
|
843
|
-
if (!(input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false)) return null;
|
|
844
|
-
const dbPoolSize = input?.dbPoolSize ?? parseNonNegativeInt(env.REACTOR_DB_POOL_SIZE_PROJECTION, "REACTOR_DB_POOL_SIZE_PROJECTION") ?? DEFAULT_DB_POOL_SIZE_PROJECTION;
|
|
845
|
-
if (dbPoolSize < 1) throw new Error("REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool");
|
|
846
|
-
return { dbPoolSize };
|
|
847
|
-
}
|
|
848
|
-
/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */
|
|
849
|
-
function assertProjectionWorkerSupported(args) {
|
|
850
|
-
if (args.dev) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary");
|
|
851
|
-
if (!args.reactorDbUrl || !isPostgresUrl(args.reactorDbUrl)) throw new Error("The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.");
|
|
852
|
-
}
|
|
853
|
-
function parseOnOff(raw) {
|
|
854
|
-
if (raw === void 0 || raw.trim() === "") return;
|
|
855
|
-
const token = raw.trim().toLowerCase();
|
|
856
|
-
if (ON_TOKENS.includes(token)) return true;
|
|
857
|
-
if (OFF_TOKENS.includes(token)) return false;
|
|
858
|
-
throw new Error(`REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got "${raw}"`);
|
|
1299
|
+
//#region src/inspection-throttle.mts
|
|
1300
|
+
const NAME = "PH_INSPECTION_CALLS_PER_MINUTE";
|
|
1301
|
+
/** Unset keeps reactor-api's default; an invalid value fails boot. */
|
|
1302
|
+
function inspectionThrottleFromEnv(env) {
|
|
1303
|
+
const callsPerMinute = parseNonNegativeInt(env[NAME], NAME);
|
|
1304
|
+
if (callsPerMinute === void 0) return {};
|
|
1305
|
+
if (callsPerMinute < 1) throw new Error(`${NAME} must be at least 1, got "${env[NAME]}"`);
|
|
1306
|
+
return { callsPerMinute };
|
|
859
1307
|
}
|
|
860
1308
|
//#endregion
|
|
861
1309
|
//#region src/feature-flags.ts
|
|
@@ -865,23 +1313,70 @@ async function initFeatureFlags() {
|
|
|
865
1313
|
return OpenFeature.getClient();
|
|
866
1314
|
}
|
|
867
1315
|
//#endregion
|
|
1316
|
+
//#region src/inspection-flag.mts
|
|
1317
|
+
/** The env var and OpenFeature flag key that can keep the inspection subgraph unmounted. */
|
|
1318
|
+
const INSPECTION_ENABLED = "INSPECTION_ENABLED";
|
|
1319
|
+
/** Whether to mount `/graphql/inspection`. A host's `inspection: false` wins;
|
|
1320
|
+
* otherwise INSPECTION_ENABLED decides, falling back to the host's option and
|
|
1321
|
+
* then INSPECTION_ENABLED_DEFAULT. */
|
|
1322
|
+
async function resolveInspectionEnabled({ featureFlags, option }) {
|
|
1323
|
+
if (option === false) return false;
|
|
1324
|
+
return featureFlags.getBooleanValue(INSPECTION_ENABLED, option ?? true);
|
|
1325
|
+
}
|
|
1326
|
+
//#endregion
|
|
1327
|
+
//#region src/mcp-flag.mts
|
|
1328
|
+
/** The env var and OpenFeature flag key that can keep the MCP server unmounted. */
|
|
1329
|
+
const MCP_ENABLED = "MCP_ENABLED";
|
|
1330
|
+
/** Whether to mount the MCP server at `/mcp`. On unless the host passes
|
|
1331
|
+
* `mcp: false` or MCP_ENABLED is "false": the env var can turn a host's MCP
|
|
1332
|
+
* off, never on, so a deployment that serves no MCP client can close the
|
|
1333
|
+
* endpoint without the bin growing a flag of its own. */
|
|
1334
|
+
async function resolveMcpEnabled({ featureFlags, option }) {
|
|
1335
|
+
if (option === false) return false;
|
|
1336
|
+
return featureFlags.getBooleanValue(MCP_ENABLED, true);
|
|
1337
|
+
}
|
|
1338
|
+
//#endregion
|
|
868
1339
|
//#region src/pglite-dialect.ts
|
|
869
|
-
|
|
1340
|
+
/** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
|
|
1341
|
+
function reactorPgliteDialectOptions(logger, proc) {
|
|
1342
|
+
return {
|
|
1343
|
+
onDiagnostic: (message, error) => logger.error(`[pglite-dialect] ${message}: @error`, error),
|
|
1344
|
+
onPoisoned: (cause) => {
|
|
1345
|
+
if (!triggerFatalShutdown("PGlite session poisoned", cause, proc)) logger.error("PGlite session poisoned: @error", cause);
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
var ClosablePGliteDialect = class {
|
|
1350
|
+
#inner;
|
|
870
1351
|
#pglite;
|
|
871
|
-
constructor(pglite) {
|
|
872
|
-
super(pglite);
|
|
1352
|
+
constructor(pglite, options = {}) {
|
|
873
1353
|
this.#pglite = pglite;
|
|
1354
|
+
this.#inner = new HardenedPGliteDialect(pglite, options);
|
|
1355
|
+
}
|
|
1356
|
+
createAdapter() {
|
|
1357
|
+
return this.#inner.createAdapter();
|
|
874
1358
|
}
|
|
875
1359
|
createDriver() {
|
|
876
|
-
const driver =
|
|
1360
|
+
const driver = this.#inner.createDriver();
|
|
877
1361
|
const pglite = this.#pglite;
|
|
878
1362
|
const innerDestroy = driver.destroy.bind(driver);
|
|
879
1363
|
driver.destroy = async () => {
|
|
880
1364
|
await innerDestroy();
|
|
881
|
-
if (
|
|
1365
|
+
if (pglite.closed) return;
|
|
1366
|
+
try {
|
|
1367
|
+
await pglite.close();
|
|
1368
|
+
} catch (err) {
|
|
1369
|
+
if (!/PGlite aborted/.test(String(err))) throw err;
|
|
1370
|
+
}
|
|
882
1371
|
};
|
|
883
1372
|
return driver;
|
|
884
1373
|
}
|
|
1374
|
+
createQueryCompiler() {
|
|
1375
|
+
return this.#inner.createQueryCompiler();
|
|
1376
|
+
}
|
|
1377
|
+
createIntrospector(db) {
|
|
1378
|
+
return this.#inner.createIntrospector(db);
|
|
1379
|
+
}
|
|
885
1380
|
};
|
|
886
1381
|
//#endregion
|
|
887
1382
|
//#region src/pglite-migration.ts
|
|
@@ -933,7 +1428,15 @@ async function migratePgliteDir(dataDir, logger) {
|
|
|
933
1428
|
try {
|
|
934
1429
|
const [legacyMod, pgDump] = await Promise.all([loadPGliteModule(major), loadPgDump(major)]);
|
|
935
1430
|
const LegacyPGlite = legacyMod.PGlite;
|
|
936
|
-
const
|
|
1431
|
+
const onDisk = new LegacyPGlite(backupDir);
|
|
1432
|
+
let tar;
|
|
1433
|
+
try {
|
|
1434
|
+
await onDisk.waitReady;
|
|
1435
|
+
tar = await onDisk.dumpDataDir("none");
|
|
1436
|
+
} finally {
|
|
1437
|
+
await onDisk.close();
|
|
1438
|
+
}
|
|
1439
|
+
const pg = new LegacyPGlite({ loadDataDir: tar });
|
|
937
1440
|
try {
|
|
938
1441
|
await pg.waitReady;
|
|
939
1442
|
sql = await (await pgDump({ pg })).text();
|
|
@@ -963,6 +1466,7 @@ async function migratePgliteDir(dataDir, logger) {
|
|
|
963
1466
|
} finally {
|
|
964
1467
|
await pg.close();
|
|
965
1468
|
}
|
|
1469
|
+
syncTree(dataDir);
|
|
966
1470
|
} catch (err) {
|
|
967
1471
|
await rollback(dataDir, backupDir, err, logger);
|
|
968
1472
|
throw err;
|
|
@@ -983,6 +1487,59 @@ async function rollback(dataDir, backupDir, originalError, logger) {
|
|
|
983
1487
|
logger.error(`[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`);
|
|
984
1488
|
}
|
|
985
1489
|
//#endregion
|
|
1490
|
+
//#region src/pglite-preflight.ts
|
|
1491
|
+
const RM_OPTIONS = {
|
|
1492
|
+
recursive: true,
|
|
1493
|
+
force: true,
|
|
1494
|
+
maxRetries: 10,
|
|
1495
|
+
retryDelay: 100
|
|
1496
|
+
};
|
|
1497
|
+
/**
|
|
1498
|
+
* Prepares every local PGlite dir before the first open and returns the
|
|
1499
|
+
* PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot
|
|
1500
|
+
* runs for every dir, before the major is read, so a pure-snapshot PG16 dir
|
|
1501
|
+
* is converted and then migrated.
|
|
1502
|
+
*/
|
|
1503
|
+
async function runPglitePreflight(options) {
|
|
1504
|
+
const { dirs, logger } = options;
|
|
1505
|
+
const detectedMajors = /* @__PURE__ */ new Map();
|
|
1506
|
+
if (options.inMemory || dirs.length === 0) return detectedMajors;
|
|
1507
|
+
if (options.forcePgVersion !== void 0) {
|
|
1508
|
+
if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
|
|
1509
|
+
logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
|
|
1510
|
+
for (const dir of dirs) {
|
|
1511
|
+
for (const p of [
|
|
1512
|
+
dir,
|
|
1513
|
+
`${dir}.converting`,
|
|
1514
|
+
`${dir}.old`
|
|
1515
|
+
]) await promises.rm(p, RM_OPTIONS);
|
|
1516
|
+
logger.info(`Wiped PGLite data dir ${dir}`);
|
|
1517
|
+
}
|
|
1518
|
+
return detectedMajors;
|
|
1519
|
+
}
|
|
1520
|
+
const deps = {
|
|
1521
|
+
openForVerify: options.openForVerify ?? openForVerify,
|
|
1522
|
+
logger
|
|
1523
|
+
};
|
|
1524
|
+
for (const dir of dirs) {
|
|
1525
|
+
await preparePgliteDataDir(dir, deps);
|
|
1526
|
+
const major = await readPgVersionFile(dir);
|
|
1527
|
+
if (major !== null) detectedMajors.set(dir, major);
|
|
1528
|
+
}
|
|
1529
|
+
if (options.migratePglite) for (const [dir, major] of detectedMajors) {
|
|
1530
|
+
if (major === 17) continue;
|
|
1531
|
+
await migratePgliteDir(dir, logger);
|
|
1532
|
+
await removeStalePgliteFiles(dir, logger);
|
|
1533
|
+
const after = await readPgVersionFile(dir);
|
|
1534
|
+
if (after !== null) detectedMajors.set(dir, after);
|
|
1535
|
+
}
|
|
1536
|
+
else for (const [dir, major] of detectedMajors) {
|
|
1537
|
+
if (major === 17) continue;
|
|
1538
|
+
logger.warn(`PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG17. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`);
|
|
1539
|
+
}
|
|
1540
|
+
return detectedMajors;
|
|
1541
|
+
}
|
|
1542
|
+
//#endregion
|
|
986
1543
|
//#region src/reactor-feature-flags.mts
|
|
987
1544
|
/**
|
|
988
1545
|
* Enforcement flags from the REACTOR_* env vars. Each flag requires the ones
|
|
@@ -1003,6 +1560,26 @@ function resolveReactorFeatureFlags(env) {
|
|
|
1003
1560
|
};
|
|
1004
1561
|
}
|
|
1005
1562
|
//#endregion
|
|
1563
|
+
//#region src/create-signature-policy.mts
|
|
1564
|
+
/**
|
|
1565
|
+
* What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a
|
|
1566
|
+
* signer this switchboard cannot write to a v2-required document, so it falls
|
|
1567
|
+
* back to legacy and says so.
|
|
1568
|
+
*/
|
|
1569
|
+
function resolveCreateSignaturePolicy(env, options) {
|
|
1570
|
+
const raw = env.CREATE_SIGNATURE_POLICY?.trim();
|
|
1571
|
+
let policy = DEFAULT_SIGNATURE_POLICY;
|
|
1572
|
+
if (raw) {
|
|
1573
|
+
if (!isSignaturePolicy(raw)) throw new Error(`CREATE_SIGNATURE_POLICY must be "legacy" or "v2-required", got "${raw}"`);
|
|
1574
|
+
policy = raw;
|
|
1575
|
+
}
|
|
1576
|
+
if (policy === "v2-required" && !options.hasSigner) {
|
|
1577
|
+
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.");
|
|
1578
|
+
return "legacy";
|
|
1579
|
+
}
|
|
1580
|
+
return policy;
|
|
1581
|
+
}
|
|
1582
|
+
//#endregion
|
|
1006
1583
|
//#region src/renown.ts
|
|
1007
1584
|
const logger = childLogger(["switchboard", "renown"]);
|
|
1008
1585
|
/**
|
|
@@ -1025,15 +1602,123 @@ async function initRenown(options = {}) {
|
|
|
1025
1602
|
* Get the signer config for the given renown instance.
|
|
1026
1603
|
*
|
|
1027
1604
|
* @param renown - The renown instance
|
|
1028
|
-
* @param
|
|
1605
|
+
* @param keypairPath - Where `initRenown` loaded the key from
|
|
1029
1606
|
*/
|
|
1030
|
-
function getRenownSignerConfig(renown,
|
|
1607
|
+
function getRenownSignerConfig(renown, keypairPath) {
|
|
1031
1608
|
return {
|
|
1032
1609
|
signer: renown.signer,
|
|
1033
|
-
|
|
1610
|
+
workerSigner: getRenownWorkerSignerSpec(renown, keypairPath)
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* What a pooled executor worker imports to sign as this switchboard: it
|
|
1615
|
+
* reloads the key `initRenown` stored, and takes the user known at boot.
|
|
1616
|
+
*/
|
|
1617
|
+
function getRenownWorkerSignerSpec(renown, keypairPath) {
|
|
1618
|
+
const { signer } = renown;
|
|
1619
|
+
const user = signer.user;
|
|
1620
|
+
return {
|
|
1621
|
+
module: {
|
|
1622
|
+
filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
|
|
1623
|
+
exportName: "createNodeRenownSigner"
|
|
1624
|
+
},
|
|
1625
|
+
initArgs: {
|
|
1626
|
+
appName: signer.app?.name ?? "switchboard",
|
|
1627
|
+
keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),
|
|
1628
|
+
...signer.app?.key ? { did: signer.app.key } : {},
|
|
1629
|
+
...user ? { user: {
|
|
1630
|
+
address: user.address,
|
|
1631
|
+
networkId: user.networkId,
|
|
1632
|
+
chainId: user.chainId
|
|
1633
|
+
} } : {}
|
|
1634
|
+
}
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Admits a key as a signer for an address a Renown credential binds it to; a
|
|
1639
|
+
* `self` source has no worker spec. In process, the switchboard's own key is
|
|
1640
|
+
* matched against its current user; the worker spec carries the user known now.
|
|
1641
|
+
*/
|
|
1642
|
+
async function getRenownTrustPolicyConfig(trustSource, renown) {
|
|
1643
|
+
const ownSigner = renown?.signer;
|
|
1644
|
+
if (trustSource.source === "self") return { trustPolicy: createRenownTrustPolicy({
|
|
1645
|
+
switchboard: trustSource.request,
|
|
1646
|
+
ownSigner
|
|
1647
|
+
}) };
|
|
1648
|
+
const switchboardUrl = await resolveSwitchboardEndpoint({
|
|
1649
|
+
switchboardUrl: trustSource.switchboardUrl,
|
|
1650
|
+
baseUrl: trustSource.renownUrl
|
|
1651
|
+
});
|
|
1652
|
+
const options = {
|
|
1653
|
+
...switchboardUrl ? { switchboard: switchboardUrl } : {},
|
|
1654
|
+
...trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}
|
|
1655
|
+
};
|
|
1656
|
+
const self = ownIdentity(renown);
|
|
1657
|
+
return {
|
|
1658
|
+
trustPolicy: createRenownTrustPolicy({
|
|
1659
|
+
...options,
|
|
1660
|
+
ownSigner
|
|
1661
|
+
}),
|
|
1662
|
+
workerTrustPolicy: {
|
|
1663
|
+
module: {
|
|
1664
|
+
filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
|
|
1665
|
+
exportName: "createRenownTrustPolicy"
|
|
1666
|
+
},
|
|
1667
|
+
initArgs: {
|
|
1668
|
+
...options,
|
|
1669
|
+
...self ? { self } : {}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Fails the boot when pooled workers would refuse every signed write the
|
|
1676
|
+
* in-process executor accepts: a `self` Renown source gives workers no trust
|
|
1677
|
+
* policy spec, so under authEnforcement they apply the default.
|
|
1678
|
+
*/
|
|
1679
|
+
function assertWorkerTrustPolicy(config) {
|
|
1680
|
+
if (config.workers > 0 && config.authEnforcement && config.renownSource === "self") throw new Error("The executor worker pool (REACTOR_WORKERS) cannot verify signers when REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): pooled workers have no trust policy and would refuse every signed write. Set RENOWN_SOURCE=remote, or disable the worker pool (REACTOR_WORKERS=0).");
|
|
1681
|
+
}
|
|
1682
|
+
function ownIdentity(renown) {
|
|
1683
|
+
const key = renown?.signer.app?.key;
|
|
1684
|
+
if (!key) return;
|
|
1685
|
+
const user = renown.signer.user;
|
|
1686
|
+
return {
|
|
1687
|
+
key,
|
|
1688
|
+
user: {
|
|
1689
|
+
address: user?.address ?? "",
|
|
1690
|
+
networkId: user?.networkId ?? "",
|
|
1691
|
+
chainId: user?.chainId ?? 0
|
|
1692
|
+
}
|
|
1034
1693
|
};
|
|
1035
1694
|
}
|
|
1036
1695
|
//#endregion
|
|
1696
|
+
//#region src/unsupported-stored-documents.mts
|
|
1697
|
+
const MODES = ["refuse", "read-only"];
|
|
1698
|
+
/** From REACTOR_UNSUPPORTED_STORED_DOCUMENTS; `input` wins when defined. */
|
|
1699
|
+
function resolveUnsupportedStoredDocuments(input, env) {
|
|
1700
|
+
if (input !== void 0) return input;
|
|
1701
|
+
const raw = env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS?.trim();
|
|
1702
|
+
if (!raw) return "refuse";
|
|
1703
|
+
if (!MODES.includes(raw)) throw new Error(`REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "${raw}"`);
|
|
1704
|
+
return raw;
|
|
1705
|
+
}
|
|
1706
|
+
/** The reactor refused to start over documents this build does not run. */
|
|
1707
|
+
var StoredDocumentsRefusedError = class extends Error {
|
|
1708
|
+
versions;
|
|
1709
|
+
documents;
|
|
1710
|
+
constructor(cause) {
|
|
1711
|
+
const named = cause.versions.map(({ protocol, version }) => `${protocol} ${version}`).join(", ");
|
|
1712
|
+
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 });
|
|
1713
|
+
this.name = "StoredDocumentsRefusedError";
|
|
1714
|
+
this.versions = cause.versions;
|
|
1715
|
+
this.documents = cause.documents;
|
|
1716
|
+
}
|
|
1717
|
+
static isError(error) {
|
|
1718
|
+
return Error.isError(error) && error.name === "StoredDocumentsRefusedError";
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
//#endregion
|
|
1037
1722
|
//#region src/server.mts
|
|
1038
1723
|
const defaultLogger = childLogger(["switchboard"]);
|
|
1039
1724
|
const LogLevel = process.env.LOG_LEVEL || "info";
|
|
@@ -1041,23 +1726,53 @@ setLogLevel(LogLevel);
|
|
|
1041
1726
|
dotenv.config();
|
|
1042
1727
|
const DOCUMENT_MODEL_SUBGRAPHS_ENABLED = "DOCUMENT_MODEL_SUBGRAPHS_ENABLED";
|
|
1043
1728
|
const DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT = true;
|
|
1044
|
-
const REQUIRE_SIGNATURES = "REQUIRE_SIGNATURES";
|
|
1045
|
-
const REQUIRE_SIGNATURES_DEFAULT = false;
|
|
1046
1729
|
const DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 4001;
|
|
1047
1730
|
const PORT_FALLBACK_ATTEMPTS = 20;
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
if (
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1731
|
+
let flushIntervalWarned = false;
|
|
1732
|
+
function warnIgnoredFlushInterval(logger) {
|
|
1733
|
+
if (flushIntervalWarned) return;
|
|
1734
|
+
if (process.env.PGLITE_FLUSH_INTERVAL_MS === void 0) return;
|
|
1735
|
+
flushIntervalWarned = true;
|
|
1736
|
+
logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
|
|
1737
|
+
}
|
|
1738
|
+
function onPgliteAbort(logger, what) {
|
|
1739
|
+
if (!triggerFatalShutdown("PGlite aborted", what)) logger.error("PGlite aborted: @error", what);
|
|
1740
|
+
}
|
|
1741
|
+
function pgliteFsyncFor(major, dir, logger) {
|
|
1742
|
+
const wanted = resolvePgliteFsync(process.env);
|
|
1743
|
+
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.`);
|
|
1744
|
+
return wanted;
|
|
1745
|
+
}
|
|
1746
|
+
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1747
|
+
async function loadDurableFsFactory(major, logger) {
|
|
1748
|
+
const NodeFS = await loadNodeFsClass(major);
|
|
1749
|
+
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1750
|
+
fsync: pgliteFsyncFor(major, dir, logger),
|
|
1751
|
+
logger,
|
|
1752
|
+
onAbort: (what) => onPgliteAbort(logger, what)
|
|
1753
|
+
});
|
|
1754
|
+
}
|
|
1054
1755
|
const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
|
|
1055
1756
|
/**
|
|
1056
1757
|
* Attempt to bind a throwaway TCP server to the given port. Resolves true if
|
|
1057
1758
|
* the port is free, false if the OS reports it in use. Any other error is
|
|
1058
1759
|
* surfaced so we don't silently mask real issues (permissions, bad host, …).
|
|
1059
1760
|
*/
|
|
1060
|
-
function isPortAvailable(port) {
|
|
1761
|
+
async function isPortAvailable(port) {
|
|
1762
|
+
try {
|
|
1763
|
+
return await probePort(port, "::");
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
if (!isNoIpv6Error(error)) throw portProbeError(port, error);
|
|
1766
|
+
try {
|
|
1767
|
+
return await probePort(port, "0.0.0.0");
|
|
1768
|
+
} catch (ipv4Error) {
|
|
1769
|
+
throw portProbeError(port, ipv4Error);
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
const isNoIpv6Error = (error) => ["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(error.code ?? "");
|
|
1774
|
+
const portProbeError = (port, error) => new Error(`Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1775
|
+
function probePort(port, host) {
|
|
1061
1776
|
return new Promise((resolve, reject) => {
|
|
1062
1777
|
const tester = net.createServer();
|
|
1063
1778
|
tester.once("error", (err) => {
|
|
@@ -1069,7 +1784,7 @@ function isPortAvailable(port) {
|
|
|
1069
1784
|
});
|
|
1070
1785
|
tester.listen({
|
|
1071
1786
|
port,
|
|
1072
|
-
host
|
|
1787
|
+
host
|
|
1073
1788
|
});
|
|
1074
1789
|
});
|
|
1075
1790
|
}
|
|
@@ -1077,6 +1792,13 @@ function isPortAvailable(port) {
|
|
|
1077
1792
|
function resolveConfigPath(configFile) {
|
|
1078
1793
|
return configFile ?? path$1.join(process.cwd(), "powerhouse.config.json");
|
|
1079
1794
|
}
|
|
1795
|
+
function readConfigWorkflowsEnabled(configPath) {
|
|
1796
|
+
try {
|
|
1797
|
+
return getConfig(configPath).workflows?.enabled ?? false;
|
|
1798
|
+
} catch {
|
|
1799
|
+
return false;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1080
1802
|
async function resolveServerPort(requested, strictPort, logger) {
|
|
1081
1803
|
if (strictPort) return requested;
|
|
1082
1804
|
for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
|
|
@@ -1089,7 +1811,7 @@ async function resolveServerPort(requested, strictPort, logger) {
|
|
|
1089
1811
|
return requested;
|
|
1090
1812
|
}
|
|
1091
1813
|
async function createReactorKysely(opts) {
|
|
1092
|
-
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory,
|
|
1814
|
+
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, logger } = opts;
|
|
1093
1815
|
if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
|
|
1094
1816
|
const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
|
|
1095
1817
|
const poolSize = hostPoolSize();
|
|
@@ -1101,19 +1823,46 @@ async function createReactorKysely(opts) {
|
|
|
1101
1823
|
logger.info(`Using PostgreSQL for reactor storage (host pool max ${poolSize})`);
|
|
1102
1824
|
return {
|
|
1103
1825
|
kysely: new Kysely({ dialect: new PostgresDialect({ pool }) }),
|
|
1104
|
-
poolInstrumentation
|
|
1826
|
+
poolInstrumentation,
|
|
1827
|
+
storageFacts: POSTGRES_STORAGE_FACTS
|
|
1105
1828
|
};
|
|
1106
1829
|
}
|
|
1107
1830
|
if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
|
|
1108
1831
|
const { PGlite } = await loadPGliteModule(reactorPgliteMajor);
|
|
1109
|
-
const pglite = inMemory ? new PGlite() : new PGlite({ fs:
|
|
1110
|
-
logger,
|
|
1111
|
-
flushIntervalMs
|
|
1112
|
-
}) });
|
|
1832
|
+
const pglite = inMemory ? new PGlite() : new PGlite({ fs: (await loadDurableFsFactory(reactorPgliteMajor, logger))(reactorPgliteDir) });
|
|
1113
1833
|
logger.info(inMemory ? `Using in-memory PGlite (PG${reactorPgliteMajor}) for reactor storage [PH_PGLITE_IN_MEMORY=1]` : `Using PGlite (PG${reactorPgliteMajor}) for reactor storage at ${reactorPgliteDir}`);
|
|
1114
1834
|
return {
|
|
1115
|
-
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite) }),
|
|
1116
|
-
poolInstrumentation: void 0
|
|
1835
|
+
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, reactorPgliteDialectOptions(logger)) }),
|
|
1836
|
+
poolInstrumentation: void 0,
|
|
1837
|
+
storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Where the two stores live — the classic resolution, relocated verbatim.
|
|
1842
|
+
* Classic layout: `./.ph/reactor-storage` for the reactor and
|
|
1843
|
+
* `.ph/read-storage` for the read model (the same names inside
|
|
1844
|
+
* `${userData}/.ph` under a shell's PH_USER_DATA_DIR). `dbPath` also names
|
|
1845
|
+
* the reactor store unless PH_REACTOR_DATABASE_URL does: with `dbPath` alone
|
|
1846
|
+
* both stores share one location. That is the long-standing contract of
|
|
1847
|
+
* `--db-path` and fine for one Postgres database, but for PGlite it is two
|
|
1848
|
+
* postmasters on one data dir — reported via `sharedPgliteDir` so the caller
|
|
1849
|
+
* warns. Not refused: changing that contract is a separate decision.
|
|
1850
|
+
*/
|
|
1851
|
+
function resolvePgliteStorageDirs(opts) {
|
|
1852
|
+
const { dbPath, reactorDbUrl, callerReactor } = opts;
|
|
1853
|
+
const defaults = defaultStoreDirs(process.env, opts.phDir);
|
|
1854
|
+
const readModelPath = dbPath || defaults.readModel;
|
|
1855
|
+
const reactorPath = reactorDbUrl || defaults.reactor;
|
|
1856
|
+
const reactorPgliteDir = callerReactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
|
|
1857
|
+
const readModelPgliteDir = !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;
|
|
1858
|
+
const sharedPgliteDir = reactorPgliteDir !== null && readModelPgliteDir !== null && path$1.resolve(reactorPgliteDir) === path$1.resolve(readModelPgliteDir) ? path$1.resolve(reactorPgliteDir) : null;
|
|
1859
|
+
return {
|
|
1860
|
+
readModelPath,
|
|
1861
|
+
reactorPath,
|
|
1862
|
+
reactorPgliteDir,
|
|
1863
|
+
readModelPgliteDir,
|
|
1864
|
+
pgliteDirs: [reactorPgliteDir, readModelPgliteDir].filter((d) => d !== null),
|
|
1865
|
+
sharedPgliteDir
|
|
1117
1866
|
};
|
|
1118
1867
|
}
|
|
1119
1868
|
/** Derive the remote attachment service config for switchboard's own `/attachments/*` API. */
|
|
@@ -1129,50 +1878,33 @@ function deriveAttachmentServiceConfig(options, serverPort, renown) {
|
|
|
1129
1878
|
}
|
|
1130
1879
|
async function initServer(serverPort, options, renown, renownConfig) {
|
|
1131
1880
|
const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
|
|
1881
|
+
const pluginHost = isPluginHostEnabled() ? createSwitchboardPluginHost({
|
|
1882
|
+
logger,
|
|
1883
|
+
options,
|
|
1884
|
+
renown
|
|
1885
|
+
}, options.pluginComposition) : null;
|
|
1886
|
+
if (pluginHost) {
|
|
1887
|
+
options = await pluginHost.transformOptions(options);
|
|
1888
|
+
options.mcp ??= false;
|
|
1889
|
+
options.workflows = { enabled: options.workflows?.enabled === true };
|
|
1890
|
+
}
|
|
1132
1891
|
logger.level = LogLevel;
|
|
1133
1892
|
const dbPath = options.dbPath ?? process.env.DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
|
|
1134
|
-
const readModelPath = dbPath || ".ph/read-storage";
|
|
1135
1893
|
const reactorDbUrl = options.dbPath ?? process.env.PH_REACTOR_DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
|
|
1136
|
-
const
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
}
|
|
1150
|
-
if (options.forcePgVersion !== void 0 && pgliteDirs.length > 0) {
|
|
1151
|
-
if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
|
|
1152
|
-
logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
|
|
1153
|
-
for (const dir of pgliteDirs) {
|
|
1154
|
-
await promises.rm(dir, {
|
|
1155
|
-
recursive: true,
|
|
1156
|
-
force: true
|
|
1157
|
-
});
|
|
1158
|
-
logger.info(`Wiped PGLite data dir ${dir}`);
|
|
1159
|
-
}
|
|
1160
|
-
} else if (options.forcePgVersion === void 0) {
|
|
1161
|
-
for (const dir of pgliteDirs) {
|
|
1162
|
-
const major = await readPgVersionFile(dir);
|
|
1163
|
-
if (major !== null) detectedMajors.set(dir, major);
|
|
1164
|
-
}
|
|
1165
|
-
if (options.migratePglite) for (const [dir, major] of detectedMajors) {
|
|
1166
|
-
if (major === 17) continue;
|
|
1167
|
-
await migratePgliteDir(dir, logger);
|
|
1168
|
-
const after = await readPgVersionFile(dir);
|
|
1169
|
-
if (after !== null) detectedMajors.set(dir, after);
|
|
1170
|
-
}
|
|
1171
|
-
else for (const [dir, major] of detectedMajors) {
|
|
1172
|
-
if (major === 17) continue;
|
|
1173
|
-
logger.warn(`PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG17. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`);
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1894
|
+
const { readModelPath, reactorPgliteDir, readModelPgliteDir, pgliteDirs, sharedPgliteDir } = resolvePgliteStorageDirs({
|
|
1895
|
+
dbPath,
|
|
1896
|
+
reactorDbUrl,
|
|
1897
|
+
callerReactor: options.reactor !== void 0
|
|
1898
|
+
});
|
|
1899
|
+
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.`);
|
|
1900
|
+
warnIgnoredFlushInterval(logger);
|
|
1901
|
+
const detectedMajors = await runPglitePreflight({
|
|
1902
|
+
dirs: pgliteDirs,
|
|
1903
|
+
forcePgVersion: options.forcePgVersion,
|
|
1904
|
+
migratePglite: options.migratePglite,
|
|
1905
|
+
inMemory: PGLITE_IN_MEMORY,
|
|
1906
|
+
logger
|
|
1907
|
+
});
|
|
1176
1908
|
function resolvePgliteMajorForDir(dir) {
|
|
1177
1909
|
if (options.forcePgVersion !== void 0) return options.forcePgVersion;
|
|
1178
1910
|
const detected = detectedMajors.get(dir);
|
|
@@ -1182,6 +1914,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1182
1914
|
}
|
|
1183
1915
|
const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
|
|
1184
1916
|
const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
|
|
1917
|
+
const inspectionThrottle = inspectionThrottleFromEnv(process.env);
|
|
1185
1918
|
let workerPool = resolveWorkerPoolOptions(options.workerPool, process.env);
|
|
1186
1919
|
if (workerPool && options.reactor) {
|
|
1187
1920
|
logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
|
|
@@ -1189,8 +1922,14 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1189
1922
|
}
|
|
1190
1923
|
if (workerPool) {
|
|
1191
1924
|
if (dev) throw new Error("The executor worker pool (REACTOR_WORKERS) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary");
|
|
1925
|
+
assertWorkerTrustPolicy({
|
|
1926
|
+
workers: workerPool.numWorkers,
|
|
1927
|
+
authEnforcement: resolveReactorFeatureFlags(process.env).flags.authEnforcement === true,
|
|
1928
|
+
renownSource: renownConfig.source
|
|
1929
|
+
});
|
|
1192
1930
|
if (!reactorDbUrl || !isPostgresUrl(reactorDbUrl)) throw new Error("The executor worker pool (REACTOR_WORKERS) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.");
|
|
1193
1931
|
}
|
|
1932
|
+
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, process.env);
|
|
1194
1933
|
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, process.env);
|
|
1195
1934
|
if (projectionWorker && options.reactor) {
|
|
1196
1935
|
logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
|
|
@@ -1216,6 +1955,8 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1216
1955
|
if (!packages.includes(name)) packages.push(name);
|
|
1217
1956
|
});
|
|
1218
1957
|
}
|
|
1958
|
+
const registryPackageNames = new Set((registryPackages ?? "").split(",").map((p) => p.trim()).filter(Boolean));
|
|
1959
|
+
const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
|
|
1219
1960
|
const reactorLogger = logger.child(["reactor"]);
|
|
1220
1961
|
let projectionWorkerFatalFired = false;
|
|
1221
1962
|
const onProjectionWorkerFatal = (shardId, reason) => {
|
|
@@ -1224,7 +1965,15 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1224
1965
|
reactorLogger.error(`Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`, reason);
|
|
1225
1966
|
process.kill(process.pid, "SIGTERM");
|
|
1226
1967
|
};
|
|
1968
|
+
const workflowsEnabled = options.workflows?.enabled === true;
|
|
1969
|
+
const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, process.env);
|
|
1970
|
+
if (workflowsEnabled) {
|
|
1971
|
+
await assertWorkflowPackageLoadable();
|
|
1972
|
+
if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
|
|
1973
|
+
}
|
|
1227
1974
|
let ownedReactorModule;
|
|
1975
|
+
let workerModels;
|
|
1976
|
+
let localRenownRequest;
|
|
1228
1977
|
const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
|
|
1229
1978
|
if (options.reactor) {
|
|
1230
1979
|
const attachmentReferenceProjection = await registerAttachmentReferenceReadModelOnModule(options.reactor, attachmentReferenceWriter);
|
|
@@ -1237,12 +1986,11 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1237
1986
|
attachmentReferenceProjection
|
|
1238
1987
|
};
|
|
1239
1988
|
}
|
|
1240
|
-
const { kysely: baseKysely, poolInstrumentation } = await createReactorKysely({
|
|
1989
|
+
const { kysely: baseKysely, poolInstrumentation, storageFacts } = await createReactorKysely({
|
|
1241
1990
|
reactorDbUrl,
|
|
1242
1991
|
reactorPgliteDir,
|
|
1243
1992
|
reactorPgliteMajor,
|
|
1244
1993
|
inMemory: PGLITE_IN_MEMORY,
|
|
1245
|
-
flushIntervalMs: PGLITE_FLUSH_INTERVAL_MS,
|
|
1246
1994
|
hostPoolSize: () => resolveHostPoolSize(process.env),
|
|
1247
1995
|
logger
|
|
1248
1996
|
});
|
|
@@ -1251,11 +1999,12 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1251
1999
|
if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
|
|
1252
2000
|
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = resolveReactorFeatureFlags(process.env);
|
|
1253
2001
|
if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
|
|
1254
|
-
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" });
|
|
2002
|
+
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: process.env.REACTOR_LEGACY_PROCESSOR_IDS !== "false" }).withUnsupportedStoredDocuments(unsupportedStoredDocuments);
|
|
1255
2003
|
if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
|
|
1256
2004
|
const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
|
|
1257
2005
|
const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
|
|
1258
2006
|
applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
|
|
2007
|
+
signalHandlers: options.signalHandlers,
|
|
1259
2008
|
documentModels: [...documentModels, ...vetraDocumentModels],
|
|
1260
2009
|
upgradeManifests,
|
|
1261
2010
|
executorConfig: hasSkipThreshold || enabledFeatureFlags.length > 0 ? {
|
|
@@ -1264,12 +2013,28 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1264
2013
|
} : void 0,
|
|
1265
2014
|
documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
|
|
1266
2015
|
logger: reactorLogger,
|
|
1267
|
-
signer: renown ? getRenownSignerConfig(renown, options.identity?.
|
|
2016
|
+
signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
|
|
2017
|
+
createSignaturePolicy: resolveCreateSignaturePolicy(process.env, {
|
|
2018
|
+
hasSigner: renown !== null,
|
|
2019
|
+
logger
|
|
2020
|
+
}),
|
|
2021
|
+
trustPolicy: reactorFeatureFlags.authEnforcement ? await getRenownTrustPolicyConfig(renownConfig.source === "self" ? {
|
|
2022
|
+
source: "self",
|
|
2023
|
+
request: (query, variables) => localRenownRequest ? localRenownRequest(query, variables) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet"))
|
|
2024
|
+
} : {
|
|
2025
|
+
source: "remote",
|
|
2026
|
+
renownUrl: renownConfig.url,
|
|
2027
|
+
switchboardUrl: renownConfig.switchboardUrl
|
|
2028
|
+
}, renown) : void 0
|
|
1268
2029
|
});
|
|
2030
|
+
if (workerPool || projectionWorker || workflowsEnabled) {
|
|
2031
|
+
const sources = await resolveWorkerModelSources(packages, reactorLogger, { resolveRemote: resolveRegistryModels });
|
|
2032
|
+
reactorBuilder.withDocumentModelSources(workerPool || projectionWorker ? sources : await keepImportableSources(sources, reactorLogger));
|
|
2033
|
+
}
|
|
2034
|
+
workerModels = modelManifestSource(reactorBuilder);
|
|
1269
2035
|
if (workerPool) {
|
|
1270
2036
|
if (!reactorDbUrl) throw new Error("unreachable: worker pool enabled without a reactor database URL");
|
|
1271
|
-
|
|
1272
|
-
reactorBuilder.withDocumentModelSources(workerSources).withWorkerPool({
|
|
2037
|
+
reactorBuilder.withWorkerPool({
|
|
1273
2038
|
numWorkers: workerPool.numWorkers,
|
|
1274
2039
|
db: buildWorkerDbConfig(reactorDbUrl, workerPool)
|
|
1275
2040
|
});
|
|
@@ -1286,10 +2051,6 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1286
2051
|
});
|
|
1287
2052
|
if (projectionWorker) {
|
|
1288
2053
|
if (!reactorDbUrl) throw new Error("unreachable: projection worker enabled without a reactor database URL");
|
|
1289
|
-
if (!workerPool) {
|
|
1290
|
-
const workerSources = await resolveWorkerModelSources(packages, reactorLogger);
|
|
1291
|
-
reactorBuilder.withDocumentModelSources(workerSources);
|
|
1292
|
-
}
|
|
1293
2054
|
const db = {
|
|
1294
2055
|
...buildWorkerDbConfig(reactorDbUrl, {
|
|
1295
2056
|
dbPoolSizePerWorker: projectionWorker.dbPoolSize,
|
|
@@ -1308,17 +2069,30 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1308
2069
|
reactorBuilder.withShutdownHook(async () => {
|
|
1309
2070
|
if (apiRef.current) await apiRef.current.dispose();
|
|
1310
2071
|
});
|
|
1311
|
-
|
|
2072
|
+
let module;
|
|
2073
|
+
try {
|
|
2074
|
+
module = await clientBuilder.buildModule();
|
|
2075
|
+
} catch (error) {
|
|
2076
|
+
try {
|
|
2077
|
+
await baseKysely.destroy();
|
|
2078
|
+
} catch (destroyError) {
|
|
2079
|
+
logger.error("Aborting boot: reactor database destroy failed: @error", destroyError);
|
|
2080
|
+
}
|
|
2081
|
+
if (UnsupportedStoredProtocolError.isError(error)) throw new StoredDocumentsRefusedError(error);
|
|
2082
|
+
throw error;
|
|
2083
|
+
}
|
|
1312
2084
|
if (module.reactorModule) {
|
|
1313
2085
|
new ReactorInstrumentation(module.reactorModule).start();
|
|
1314
2086
|
reactorLogger.info("Reactor metrics instrumentation started");
|
|
1315
2087
|
}
|
|
1316
|
-
|
|
2088
|
+
const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
|
|
2089
|
+
driveNodeView = new DriveNodeView(reactorDriveSchemaDb);
|
|
1317
2090
|
const reactorDriveClient = new ReactorDriveClient({
|
|
1318
2091
|
reactor: module.client,
|
|
1319
2092
|
readModel: driveNodeView
|
|
1320
2093
|
});
|
|
1321
2094
|
ownedReactorModule = module;
|
|
2095
|
+
if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
|
|
1322
2096
|
return {
|
|
1323
2097
|
module,
|
|
1324
2098
|
reactorDriveClient,
|
|
@@ -1326,33 +2100,46 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1326
2100
|
};
|
|
1327
2101
|
};
|
|
1328
2102
|
const abortBoot = async (api) => {
|
|
2103
|
+
let disposed;
|
|
2104
|
+
const disposeApi = () => disposed ??= api.dispose();
|
|
2105
|
+
apiRef.current = { dispose: disposeApi };
|
|
1329
2106
|
const owned = ownedReactorModule;
|
|
1330
|
-
if (owned) try {
|
|
2107
|
+
if (owned?.reactorModule) try {
|
|
2108
|
+
await owned.reactorModule.shutdown();
|
|
2109
|
+
} catch (error) {
|
|
2110
|
+
logger.error("Aborting boot: reactor shutdown failed: @error", error);
|
|
2111
|
+
}
|
|
2112
|
+
else if (owned) try {
|
|
1331
2113
|
await owned.reactor.kill().completed;
|
|
1332
2114
|
} catch (error) {
|
|
1333
2115
|
logger.error("Aborting boot: reactor shutdown failed: @error", error);
|
|
1334
2116
|
}
|
|
1335
2117
|
try {
|
|
1336
|
-
await
|
|
2118
|
+
await disposeApi();
|
|
1337
2119
|
} catch (error) {
|
|
1338
2120
|
logger.error("Aborting boot: api dispose failed: @error", error);
|
|
1339
2121
|
}
|
|
1340
|
-
if (owned?.reactorModule) try {
|
|
1341
|
-
await owned.reactorModule.database.destroy();
|
|
1342
|
-
} catch (error) {
|
|
1343
|
-
logger.error("Aborting boot: database destroy failed: @error", error);
|
|
1344
|
-
}
|
|
1345
2122
|
};
|
|
1346
2123
|
let localCredentialCheck;
|
|
1347
2124
|
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;
|
|
1348
2125
|
let defaultDriveUrl = void 0;
|
|
1349
2126
|
const basePath = process.cwd();
|
|
2127
|
+
const reportError = (error) => {
|
|
2128
|
+
Sentry.captureException(error);
|
|
2129
|
+
};
|
|
2130
|
+
const reporting = {
|
|
2131
|
+
logger,
|
|
2132
|
+
report: reportError
|
|
2133
|
+
};
|
|
1350
2134
|
let vite;
|
|
1351
2135
|
let viteLoader;
|
|
1352
2136
|
if (dev) {
|
|
1353
2137
|
const { VitePackageLoader, createViteLogger, startViteServer } = await import("@powerhousedao/reactor-api/vite");
|
|
1354
2138
|
vite = await startViteServer(process.cwd(), createViteLogger(logger));
|
|
1355
|
-
viteLoader = VitePackageLoader.build(vite
|
|
2139
|
+
viteLoader = VitePackageLoader.build(vite, {
|
|
2140
|
+
resolveFrom: [import.meta.url],
|
|
2141
|
+
reportError
|
|
2142
|
+
});
|
|
1356
2143
|
}
|
|
1357
2144
|
const vetraProcessorFactory = dev ? (await import("@powerhousedao/vetra/processors")).processorFactory : void 0;
|
|
1358
2145
|
if (!options.disableLocalPackages) packages.push(basePath);
|
|
@@ -1370,11 +2157,9 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1370
2157
|
let pgliteFactory;
|
|
1371
2158
|
if (readModelPgliteDir && readModelPgliteMajor !== null) {
|
|
1372
2159
|
const { PGlite: ReadModelPGlite } = await loadPGliteModule(readModelPgliteMajor);
|
|
2160
|
+
const durableFs = await loadDurableFsFactory(readModelPgliteMajor, logger);
|
|
1373
2161
|
pgliteFactory = PGLITE_IN_MEMORY ? () => new ReadModelPGlite({ parsers: PGLITE_UTC_PARSERS }) : (connectionString) => new ReadModelPGlite({
|
|
1374
|
-
fs:
|
|
1375
|
-
logger,
|
|
1376
|
-
flushIntervalMs: PGLITE_FLUSH_INTERVAL_MS
|
|
1377
|
-
}),
|
|
2162
|
+
fs: durableFs(connectionString ?? readModelPgliteDir),
|
|
1378
2163
|
parsers: PGLITE_UTC_PARSERS
|
|
1379
2164
|
});
|
|
1380
2165
|
}
|
|
@@ -1389,7 +2174,9 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1389
2174
|
processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
|
|
1390
2175
|
configFile: configPath,
|
|
1391
2176
|
mcp: options.mcp ?? true,
|
|
2177
|
+
inspection: options.inspection === false ? false : { throttle: inspectionThrottle },
|
|
1392
2178
|
logger: apiLogger,
|
|
2179
|
+
reportError,
|
|
1393
2180
|
enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
|
|
1394
2181
|
renown: renownConfig,
|
|
1395
2182
|
verifyCredential
|
|
@@ -1401,14 +2188,158 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1401
2188
|
await abortBoot(api);
|
|
1402
2189
|
throw new Error(`Renown credential verification is set to "self" (auth.renown.source or RENOWN_SOURCE) but no loaded package serves the "${RENOWN_READ_MODEL_SUBGRAPH}" subgraph. Install one (@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.`);
|
|
1403
2190
|
}
|
|
1404
|
-
|
|
2191
|
+
localRenownRequest = (query, variables) => manager.executeSubgraphQuery(RENOWN_READ_MODEL_SUBGRAPH, query, variables);
|
|
2192
|
+
localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, { onError: (error) => logger.error("Renown read model query failed: @error", error) });
|
|
1405
2193
|
logger.info("Renown credentials will be verified against this switchboard's own renown read model");
|
|
1406
2194
|
}
|
|
1407
|
-
|
|
1408
|
-
|
|
2195
|
+
let attachmentService;
|
|
2196
|
+
if (pluginHost) {
|
|
2197
|
+
pluginHost.ctx.api = api;
|
|
2198
|
+
pluginHost.ctx.serverPort = serverPort;
|
|
2199
|
+
await pluginHost.observe("onHttpMounting");
|
|
2200
|
+
attachmentService = pluginHost.ctx.attachmentService;
|
|
2201
|
+
} else {
|
|
2202
|
+
registerAttachmentRoutes(api);
|
|
2203
|
+
attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
|
|
2204
|
+
}
|
|
1409
2205
|
if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
|
|
1410
2206
|
const { client, graphqlManager, documentModelRegistry } = api;
|
|
1411
2207
|
const lateSubgraphs = [];
|
|
2208
|
+
if (pluginHost) {
|
|
2209
|
+
pluginHost.ctx.client = client;
|
|
2210
|
+
pluginHost.ctx.graphqlManager = graphqlManager;
|
|
2211
|
+
pluginHost.ctx.lateSubgraphs = lateSubgraphs;
|
|
2212
|
+
pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;
|
|
2213
|
+
await pluginHost.observe("onReactorReady");
|
|
2214
|
+
}
|
|
2215
|
+
let workflows;
|
|
2216
|
+
let workflowsRetry;
|
|
2217
|
+
const composeWorkflows = () => composeWorkflowRuntime({
|
|
2218
|
+
reactorClient: client,
|
|
2219
|
+
clientModule: options.reactor ?? ownedReactorModule,
|
|
2220
|
+
relationalDb: api.relationalDb,
|
|
2221
|
+
secretsKeyFile: readModelPgliteDir === null ? false : void 0,
|
|
2222
|
+
storageId: readModelPgliteDir === null ? readModelPath : path$1.resolve(readModelPath),
|
|
2223
|
+
attachments: createAttachmentClient(api.attachments.service),
|
|
2224
|
+
attachmentAccess: api.attachmentAccess,
|
|
2225
|
+
webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,
|
|
2226
|
+
http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),
|
|
2227
|
+
authorizationService: api.authorizationService,
|
|
2228
|
+
pieces: api.packageManager,
|
|
2229
|
+
pieceRegistryUrl: registryUrl,
|
|
2230
|
+
models: workerModels,
|
|
2231
|
+
reactorThreads: (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),
|
|
2232
|
+
logger: logger.child(["workflow-runtime"]),
|
|
2233
|
+
exclusiveJournal: readModelPgliteDir !== null,
|
|
2234
|
+
onSingletonLost: workflowSingletonLossHandler(logger),
|
|
2235
|
+
telemetry: {
|
|
2236
|
+
tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),
|
|
2237
|
+
meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE)
|
|
2238
|
+
}
|
|
2239
|
+
});
|
|
2240
|
+
const registerWorkflowSubgraph = (composed) => {
|
|
2241
|
+
const WorkflowRuntimeSubgraph = composed.subgraph;
|
|
2242
|
+
const workflowSubgraph = new WorkflowRuntimeSubgraph({
|
|
2243
|
+
reactorClient: client,
|
|
2244
|
+
http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),
|
|
2245
|
+
relationalDb: api.relationalDb,
|
|
2246
|
+
analyticsStore: void 0,
|
|
2247
|
+
graphqlManager,
|
|
2248
|
+
syncManager: api.syncManager,
|
|
2249
|
+
authorizationService: graphqlManager.getAuthorizationService(),
|
|
2250
|
+
path: graphqlManager.getBasePath(),
|
|
2251
|
+
attachments: api.attachmentClientProvider
|
|
2252
|
+
});
|
|
2253
|
+
return graphqlManager.registerSubgraphInstance(workflowSubgraph, "graphql", false).catch((error) => {
|
|
2254
|
+
reportFailure(reporting, error, "Failed to register workflow-runtime subgraph: @error");
|
|
2255
|
+
});
|
|
2256
|
+
};
|
|
2257
|
+
if (!pluginHost && workflowsEnabled) try {
|
|
2258
|
+
workflows = await composeWorkflows();
|
|
2259
|
+
} catch (error) {
|
|
2260
|
+
if (!isWorkflowSingletonConflict(error)) throw error;
|
|
2261
|
+
logger.warn(`Workflows are enabled but another live process ("${error.owner ?? "unknown"}") holds the workflow singleton until ${error.expiresAt ?? "unknown"}. This Switchboard has booted WITHOUT the workflow runtime: no trigger of any kind fires here, and the workflow GraphQL face is absent. Everything else serves normally. Stop the other owner, or set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the slot that owns workflows. This Switchboard retries the claim and starts workflows once the lease comes free.`);
|
|
2262
|
+
workflowsRetry = retryWorkflowSingleton({
|
|
2263
|
+
compose: composeWorkflows,
|
|
2264
|
+
onComposed: async (composed) => {
|
|
2265
|
+
try {
|
|
2266
|
+
await composed.start();
|
|
2267
|
+
} catch (error) {
|
|
2268
|
+
try {
|
|
2269
|
+
await composed.stop();
|
|
2270
|
+
} catch (stopError) {
|
|
2271
|
+
logger.error("Stopping the late workflow runtime failed: @error", stopError);
|
|
2272
|
+
}
|
|
2273
|
+
throw error;
|
|
2274
|
+
}
|
|
2275
|
+
logger.info("Workflow runtime started");
|
|
2276
|
+
workflows = composed;
|
|
2277
|
+
await registerWorkflowSubgraph(composed);
|
|
2278
|
+
try {
|
|
2279
|
+
await graphqlManager.updateRouter(true);
|
|
2280
|
+
} catch (error) {
|
|
2281
|
+
reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error");
|
|
2282
|
+
}
|
|
2283
|
+
},
|
|
2284
|
+
logger
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
if (workflows) {
|
|
2288
|
+
lateSubgraphs.push(registerWorkflowSubgraph(workflows));
|
|
2289
|
+
await workflows.start();
|
|
2290
|
+
logger.info("Workflow runtime started");
|
|
2291
|
+
api.inspection?.facts.setWorkflows(true);
|
|
2292
|
+
}
|
|
2293
|
+
if (pluginHost) {
|
|
2294
|
+
pluginHost.ctx.workflowsOrchestration = {
|
|
2295
|
+
enabled: options.workflows?.enabled === true,
|
|
2296
|
+
composeWorkflows,
|
|
2297
|
+
registerWorkflowSubgraph,
|
|
2298
|
+
updateRouter: () => graphqlManager.updateRouter(true),
|
|
2299
|
+
reportMountFailure: (error) => reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error"),
|
|
2300
|
+
setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true)
|
|
2301
|
+
};
|
|
2302
|
+
try {
|
|
2303
|
+
await pluginHost.observe("onSubgraphsRegistering");
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
await pluginHost.ctx.workflowsRetry?.stop();
|
|
2306
|
+
await pluginHost.ctx.workflows?.stop();
|
|
2307
|
+
await abortBoot(api);
|
|
2308
|
+
throw error;
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
let privacy;
|
|
2312
|
+
if (!pluginHost && privacyConfig.enabled) {
|
|
2313
|
+
const signer = options.reactor ? options.privacy?.signer : options.privacy?.signer ?? renown?.signer;
|
|
2314
|
+
try {
|
|
2315
|
+
privacy = await startPrivacy({
|
|
2316
|
+
config: privacyConfig,
|
|
2317
|
+
reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,
|
|
2318
|
+
signer,
|
|
2319
|
+
authorizationService: api.authorizationService,
|
|
2320
|
+
documentPermissionService: api.documentPermissionService,
|
|
2321
|
+
graphqlManager,
|
|
2322
|
+
reactorClient: client,
|
|
2323
|
+
logger: logger.child(["privacy"])
|
|
2324
|
+
});
|
|
2325
|
+
} catch (error) {
|
|
2326
|
+
await workflowsRetry?.stop();
|
|
2327
|
+
await workflows?.stop();
|
|
2328
|
+
await abortBoot(api);
|
|
2329
|
+
throw error;
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
let apiDrained;
|
|
2333
|
+
const drainApi = () => apiDrained ??= (async () => {
|
|
2334
|
+
if (pluginHost) await pluginHost.observe("onShutdown");
|
|
2335
|
+
await privacy?.stop();
|
|
2336
|
+
await workflowsRetry?.stop();
|
|
2337
|
+
await workflows?.stop();
|
|
2338
|
+
await api.dispose();
|
|
2339
|
+
})();
|
|
2340
|
+
apiRef.current = { dispose: drainApi };
|
|
2341
|
+
const ownedReactor = ownedReactorModule?.reactorModule;
|
|
2342
|
+
const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;
|
|
1412
2343
|
if (httpLoader) {
|
|
1413
2344
|
const packageManagementService = new PackageManagementService({
|
|
1414
2345
|
defaultRegistryUrl: registryUrl,
|
|
@@ -1418,7 +2349,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1418
2349
|
});
|
|
1419
2350
|
packageManagementService.setOnModelsChanged(() => {
|
|
1420
2351
|
graphqlManager.regenerateDocumentModelSubgraphs().catch((error) => {
|
|
1421
|
-
|
|
2352
|
+
reportFailure(reporting, error, "Failed to regenerate document model subgraphs: @error");
|
|
1422
2353
|
});
|
|
1423
2354
|
});
|
|
1424
2355
|
const packagesSubgraph = new PackagesSubgraph({
|
|
@@ -1430,39 +2361,45 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1430
2361
|
path: graphqlManager.getBasePath(),
|
|
1431
2362
|
authorizationService: graphqlManager.getAuthorizationService(),
|
|
1432
2363
|
packageManagementService,
|
|
1433
|
-
http: graphqlManager.scopeForPackage("@powerhousedao/switchboard")
|
|
2364
|
+
http: graphqlManager.scopeForPackage("@powerhousedao/switchboard"),
|
|
2365
|
+
attachments: api.attachmentClientProvider
|
|
1434
2366
|
});
|
|
1435
2367
|
lateSubgraphs.push(graphqlManager.registerSubgraphInstance(packagesSubgraph, "graphql", false).catch((error) => {
|
|
1436
|
-
|
|
2368
|
+
reportFailure(reporting, error, "Failed to register packages subgraph: @error");
|
|
1437
2369
|
}));
|
|
1438
2370
|
}
|
|
1439
2371
|
if (driveNodeView) {
|
|
1440
2372
|
graphqlManager.setAdditionalContextFields({ readModel: driveNodeView });
|
|
2373
|
+
const authorizationService = graphqlManager.getAuthorizationService();
|
|
1441
2374
|
const reactorDriveSubgraph = {
|
|
1442
|
-
name:
|
|
2375
|
+
name: REACTOR_DRIVE_SUBGRAPH_NAME,
|
|
1443
2376
|
path: graphqlManager.getBasePath(),
|
|
1444
|
-
resolvers: createReactorDriveResolvers(
|
|
2377
|
+
resolvers: createReactorDriveResolvers({
|
|
2378
|
+
reactorClient: client,
|
|
2379
|
+
readModel: driveNodeView,
|
|
2380
|
+
hostCanRead: (documentId, address) => authorizationService.canRead(documentId, address)
|
|
2381
|
+
}),
|
|
1445
2382
|
typeDefs: reactorDriveSubgraphTypeDefs,
|
|
1446
2383
|
reactorClient: client,
|
|
1447
2384
|
relationalDb: void 0
|
|
1448
2385
|
};
|
|
1449
2386
|
lateSubgraphs.push(graphqlManager.registerSubgraphInstance(reactorDriveSubgraph, "graphql", false).catch((error) => {
|
|
1450
|
-
|
|
2387
|
+
reportFailure(reporting, error, "Failed to register reactor-drive subgraph: @error");
|
|
1451
2388
|
}));
|
|
1452
2389
|
}
|
|
1453
|
-
(async () => {
|
|
1454
|
-
await Promise.
|
|
2390
|
+
runDetached("Marking the API ready", async () => {
|
|
2391
|
+
await Promise.allSettled(lateSubgraphs);
|
|
1455
2392
|
try {
|
|
1456
2393
|
await graphqlManager.updateRouter(true);
|
|
1457
2394
|
} catch (error) {
|
|
1458
|
-
|
|
2395
|
+
reportFailure(reporting, error, "Final router update before readiness failed: @error");
|
|
1459
2396
|
}
|
|
1460
2397
|
api.readiness.markReady();
|
|
1461
|
-
})
|
|
2398
|
+
}, reporting);
|
|
1462
2399
|
if (options.drive) {
|
|
1463
2400
|
if (!renown) throw new Error("Cannot create default drive without Renown identity");
|
|
1464
|
-
if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort);
|
|
1465
|
-
else defaultDriveUrl = await addDefaultDrive(client, options.drive, serverPort);
|
|
2401
|
+
if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort, logger);
|
|
2402
|
+
else defaultDriveUrl = await addDefaultDrive(client, options.drive, serverPort, logger);
|
|
1466
2403
|
}
|
|
1467
2404
|
if (vite) api.httpAdapter.mountRawMiddleware(vite.middlewares);
|
|
1468
2405
|
if (remoteDrives.length > 0) for (const remoteDriveUrl of remoteDrives) {
|
|
@@ -1486,15 +2423,27 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1486
2423
|
if (!defaultDriveUrl && driveId) defaultDriveUrl = `${options.https ? "https" : "http"}://localhost:${serverPort}/d/${driveId}`;
|
|
1487
2424
|
}
|
|
1488
2425
|
}
|
|
2426
|
+
if (pluginHost) await pluginHost.observe("onDrivesReady");
|
|
1489
2427
|
return {
|
|
1490
2428
|
defaultDriveUrl,
|
|
1491
2429
|
api,
|
|
1492
2430
|
reactor: client,
|
|
1493
2431
|
attachmentService,
|
|
1494
2432
|
attachmentReferenceProjection: api.attachmentReferenceProjection,
|
|
2433
|
+
get workflowTriggers() {
|
|
2434
|
+
return (workflows ?? pluginHost?.ctx.workflows)?.triggers;
|
|
2435
|
+
},
|
|
2436
|
+
workflowsEnabled,
|
|
2437
|
+
modelManifest: () => workerModels?.modelManifest() ?? [],
|
|
2438
|
+
privacy: (() => {
|
|
2439
|
+
const running = privacy ?? pluginHost?.ctx.privacy;
|
|
2440
|
+
return running ? { erasure: running.erasure } : void 0;
|
|
2441
|
+
})(),
|
|
2442
|
+
mcpEnabled: options.mcp !== false,
|
|
2443
|
+
inspectionEnabled: options.inspection !== false,
|
|
1495
2444
|
renown,
|
|
1496
2445
|
port: serverPort,
|
|
1497
|
-
shutdown
|
|
2446
|
+
shutdown
|
|
1498
2447
|
};
|
|
1499
2448
|
}
|
|
1500
2449
|
/**
|
|
@@ -1508,29 +2457,48 @@ async function initServer(serverPort, options, renown, renownConfig) {
|
|
|
1508
2457
|
* dangling until the process exits.
|
|
1509
2458
|
*
|
|
1510
2459
|
* When `options.reactor` is omitted, the switchboard builds and owns the
|
|
1511
|
-
* reactor. `shutdown()` on the returned handle
|
|
1512
|
-
*
|
|
1513
|
-
*
|
|
1514
|
-
*
|
|
1515
|
-
*
|
|
2460
|
+
* reactor. `shutdown()` on the returned handle then runs the reactor
|
|
2461
|
+
* module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains
|
|
2462
|
+
* the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the
|
|
2463
|
+
* reactor database. It does not exit the process. It is the same memoized
|
|
2464
|
+
* teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling
|
|
2465
|
+
* it twice, or receiving a signal around it, tears down once.
|
|
1516
2466
|
*/
|
|
1517
2467
|
const startSwitchboard = async (options = {}) => {
|
|
1518
2468
|
const requestedPort = options.port ?? DEFAULT_PORT;
|
|
1519
2469
|
const logger = options.logger ?? defaultLogger;
|
|
2470
|
+
if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
|
|
1520
2471
|
const serverPort = await resolveServerPort(requestedPort, options.strictPort ?? false, logger);
|
|
1521
2472
|
const featureFlags = await initFeatureFlags();
|
|
1522
2473
|
const enableDocumentModelSubgraphs = await featureFlags.getBooleanValue(DOCUMENT_MODEL_SUBGRAPHS_ENABLED, options.enableDocumentModelSubgraphs ?? DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT);
|
|
1523
2474
|
options.enableDocumentModelSubgraphs = enableDocumentModelSubgraphs;
|
|
1524
|
-
|
|
2475
|
+
if (!isPluginHostEnabled()) {
|
|
2476
|
+
options.mcp = await resolveMcpEnabled({
|
|
2477
|
+
featureFlags,
|
|
2478
|
+
option: options.mcp
|
|
2479
|
+
});
|
|
2480
|
+
const configPathForFlags = resolveConfigPath(options.configFile);
|
|
2481
|
+
options.workflows = { enabled: await resolveWorkflowsEnabled({
|
|
2482
|
+
featureFlags,
|
|
2483
|
+
override: options.workflows?.enabled,
|
|
2484
|
+
configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
|
|
2485
|
+
}) };
|
|
2486
|
+
}
|
|
2487
|
+
options.inspection = await resolveInspectionEnabled({
|
|
2488
|
+
featureFlags,
|
|
2489
|
+
option: options.inspection
|
|
2490
|
+
});
|
|
1525
2491
|
const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
|
|
1526
2492
|
options.identity = {
|
|
1527
2493
|
...options.identity,
|
|
1528
|
-
|
|
1529
|
-
|
|
2494
|
+
baseUrl: options.identity?.baseUrl ?? renownConfig.url,
|
|
2495
|
+
keypairPath: options.identity?.keypairPath ?? (process.env.PH_USER_DATA_DIR ? path$1.join(resolvePhDir(), ".keypair.json") : void 0)
|
|
1530
2496
|
};
|
|
1531
2497
|
logger.info("Feature flags: @flags", JSON.stringify({
|
|
1532
2498
|
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
|
|
1533
|
-
|
|
2499
|
+
MCP_ENABLED: options.mcp,
|
|
2500
|
+
INSPECTION_ENABLED: options.inspection,
|
|
2501
|
+
PH_WORKFLOWS_ENABLED: options.workflows?.enabled
|
|
1534
2502
|
}, null, 2));
|
|
1535
2503
|
let renown = null;
|
|
1536
2504
|
try {
|
|
@@ -1543,13 +2511,14 @@ const startSwitchboard = async (options = {}) => {
|
|
|
1543
2511
|
return await initServer(serverPort, options, renown, renownConfig);
|
|
1544
2512
|
} catch (e) {
|
|
1545
2513
|
Sentry.captureException(e);
|
|
1546
|
-
logger.error(
|
|
2514
|
+
if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
|
|
2515
|
+
else logger.error("App crashed: @error", e);
|
|
1547
2516
|
throw e;
|
|
1548
2517
|
}
|
|
1549
2518
|
};
|
|
1550
|
-
if (import.meta.main) await startSwitchboard();
|
|
2519
|
+
if (import.meta.main) await startSwitchboard({ fatalErrorShutdown: true });
|
|
1551
2520
|
//#endregion
|
|
1552
|
-
export {
|
|
2521
|
+
export { startSwitchboard as a, attachmentsPlugin as c, initProfilerFromEnv as d, parseForcePgVersion as f, resolvePgliteStorageDirs as i, attachmentsPluginConfigSchema as l, deriveAttachmentServiceConfig as n, StoredDocumentsRefusedError as o, isPortAvailable as r, resolveUnsupportedStoredDocuments as s, createReactorKysely as t, applySwitchboardReactorDefaults as u };
|
|
1553
2522
|
|
|
1554
|
-
//# sourceMappingURL=server-
|
|
1555
|
-
//# debugId=
|
|
2523
|
+
//# sourceMappingURL=server-Be1vmpxu.mjs.map
|
|
2524
|
+
//# debugId=eb9f9f91-b014-5be8-a29c-f37efe0c4ad0
|