@powerhousedao/switchboard 6.2.3-dev.8 → 6.2.3-dev.81
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-auth-config.test.d.ts +2 -0
- package/.tsbuild/test/boot-auth-config.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-env-isolation.test.d.ts +2 -0
- package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-helpers.d.ts +5 -0
- package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
- package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
- package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
- package/.tsbuild/test/boot-mcp-auth.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-port-zero.test.d.ts +2 -0
- package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
- package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
- package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
- package/.tsbuild/test/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/config-from-env.test.d.ts +2 -0
- package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
- package/.tsbuild/test/config-merge.test.d.ts +2 -0
- package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
- package/.tsbuild/test/config-schema.test.d.ts +2 -0
- package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
- package/.tsbuild/test/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-protocol-versions.test.d.ts +2 -0
- package/.tsbuild/test/default-drive-protocol-versions.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-throttle.test.d.ts +2 -0
- package/.tsbuild/test/inspection-throttle.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/permissions-backfill.test.d.ts +2 -0
- package/.tsbuild/test/permissions-backfill.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/pglite-store.test.d.ts +2 -0
- package/.tsbuild/test/pglite-store.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-storage-path.test.d.ts +2 -0
- package/.tsbuild/test/renown-storage-path.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/served-schemas.test.d.ts +2 -0
- package/.tsbuild/test/served-schemas.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/store-lock.test.d.ts +2 -0
- package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
- package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
- package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
- package/.tsbuild/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/runtime-host.test.d.ts +2 -0
- package/.tsbuild/test/workflow/runtime-host.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 +1074 -0
- package/README.md +55 -14
- package/dist/boot.d.mts +46 -0
- package/dist/boot.d.mts.map +1 -0
- package/dist/boot.mjs +67 -0
- package/dist/boot.mjs.map +1 -0
- package/dist/config/from-env.d.mts +15 -0
- package/dist/config/from-env.d.mts.map +1 -0
- package/dist/config/from-env.mjs +4 -0
- package/dist/config/schema.d.mts +3 -0
- package/dist/config/schema.mjs +4 -0
- package/dist/from-env-BO0n9R02.mjs +401 -0
- package/dist/from-env-BO0n9R02.mjs.map +1 -0
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +76 -79
- 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 +7 -5
- package/dist/migrate.mjs.map +1 -1
- package/dist/plugin-host-C1sYEm8g.d.mts +46 -0
- package/dist/plugin-host-C1sYEm8g.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/postgres-url-DTDhBjXX.mjs +11 -0
- package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
- package/dist/privacy-BO8Q25xI.mjs +44 -0
- package/dist/privacy-BO8Q25xI.mjs.map +1 -0
- package/dist/privacy-DxIJGH4P.mjs +91 -0
- package/dist/privacy-DxIJGH4P.mjs.map +1 -0
- package/dist/renown-layers-COZsrGQT.mjs +40 -0
- package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
- package/dist/schema-0g_QdOWn.mjs +267 -0
- package/dist/schema-0g_QdOWn.mjs.map +1 -0
- package/dist/schema-ivUWPQOn.d.mts +202 -0
- package/dist/schema-ivUWPQOn.d.mts.map +1 -0
- package/dist/server-cE1BWLQu.mjs +2518 -0
- package/dist/server-cE1BWLQu.mjs.map +1 -0
- package/dist/server.d.mts +270 -48
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +5 -5
- package/dist/utils-C6AIF38Z.mjs +133 -0
- package/dist/utils-C6AIF38Z.mjs.map +1 -0
- package/dist/utils.d.mts +12 -5
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +4 -3
- package/dist/worker-pool-BWHBLBJd.mjs +304 -0
- package/dist/worker-pool-BWHBLBJd.mjs.map +1 -0
- package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
- package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
- package/dist/workflows-COM3MKfD.mjs +1437 -0
- package/dist/workflows-COM3MKfD.mjs.map +1 -0
- package/package.json +68 -23
- package/scripts/install-packages.sh +0 -0
- package/test/attachment-reference-read-model.test.ts +28 -20
- 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 +211 -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 +297 -35
- package/test/attachments/service-config.test.ts +41 -19
- package/test/attachments/url-signer.test.ts +105 -0
- package/test/boot-auth-config.test.ts +109 -0
- package/test/boot-create-signature-policy.test.ts +110 -0
- package/test/boot-env-isolation.test.ts +26 -0
- package/test/boot-helpers.ts +19 -0
- package/test/boot-inspection-enabled.test.ts +140 -0
- package/test/boot-mcp-auth.test.ts +449 -0
- package/test/boot-mcp-enabled.test.ts +119 -0
- package/test/boot-port-zero.test.ts +101 -0
- package/test/boot-preconditions.test.ts +200 -0
- package/test/boot-privacy.test.ts +232 -0
- package/test/boot-unsupported-stored-documents.test.ts +214 -0
- package/test/boot-without-renown.test.ts +83 -0
- package/test/boot-without-require-signatures.test.ts +76 -0
- package/test/boot-worker-trust-policy.test.ts +91 -0
- package/test/boot-workflow-singleton-conflict.test.ts +109 -0
- package/test/boot-workflow-singleton-retry.test.ts +122 -0
- package/test/builder-defaults.test.ts +80 -0
- package/test/config-from-env.test.ts +758 -0
- package/test/config-merge.test.ts +215 -0
- package/test/config-schema.test.ts +128 -0
- package/test/create-signature-policy.test.ts +69 -0
- package/test/default-drive-protocol-versions.test.ts +102 -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/goldens/packages.graphql +797 -0
- package/test/goldens/privacy.graphql +853 -0
- package/test/goldens/reactor-drive-nodes.graphql +827 -0
- package/test/goldens/resolvers.json +322 -0
- package/test/goldens/supergraph.graphql +5652 -0
- package/test/goldens/workflow-runtime.graphql +1419 -0
- package/test/inspection-throttle.test.ts +23 -0
- package/test/observability-signals.test.ts +131 -0
- package/test/permissions-backfill.test.ts +486 -0
- package/test/pglite-dialect.test.ts +237 -2
- package/test/pglite-preflight.test.ts +313 -0
- package/test/pglite-storage-dirs.test.ts +113 -0
- package/test/pglite-store.test.ts +264 -0
- package/test/pglite-version.test.ts +9 -1
- package/test/plugin-config-schemas.test.ts +83 -0
- package/test/plugin-presence.test.ts +262 -0
- package/test/port-probe.test.ts +45 -0
- package/test/renown-storage-path.test.ts +40 -0
- package/test/renown-trust-policy.test.ts +313 -0
- package/test/served-schemas.test.ts +134 -0
- package/test/shutdown.test.ts +278 -0
- package/test/snapshot-writer.ts +94 -0
- package/test/store-lock.test.ts +65 -0
- package/test/two-switchboards.test.ts +146 -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 +205 -0
- package/test/workflow/resolvers.test.ts +369 -0
- package/test/workflow/runtime-host.test.ts +19 -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 +1135 -0
- package/test/workflows-plugin-config.test.ts +77 -0
- package/tsconfig.json +11 -2
- package/tsdown.config.ts +12 -1
- package/vitest.config.ts +65 -0
- package/dist/server-CiKkVE6g.mjs +0 -1555
- package/dist/server-CiKkVE6g.mjs.map +0 -1
- package/dist/utils-Baw7rThP.mjs +0 -80
- package/dist/utils-Baw7rThP.mjs.map +0 -1
|
@@ -0,0 +1,2518 @@
|
|
|
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]="4a0fe5f4-e71e-59f2-8cbd-cc08a5334040")}catch(e){}}();
|
|
3
|
+
import { a as loadNodeFsClass, c as openForVerify, d as ATTACHMENT_URL_SIGNING_SECRET_ENV, f as resolveAttachmentUrlSigning, i as isSupportedMajor, l as pgliteModuleSpec, n as StoredDocumentsRefusedError, o as loadPGliteModule, r as resolveUnsupportedStoredDocuments, s as loadPgDump, t as switchboardConfigFromEnv, u as readPgVersionFile } from "./from-env-BO0n9R02.mjs";
|
|
4
|
+
import { a as resolveWorkerModelSources, l as resolveProjectionWorkerOptions, n as keepImportableSources, o as resolveWorkerPoolOptions, p as workerPoolIssues, s as assertProjectionWorkerSupported, t as buildWorkerDbConfig } from "./worker-pool-BWHBLBJd.mjs";
|
|
5
|
+
import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
|
|
6
|
+
import { n as resolvePrivacy, r as startPrivacy } from "./privacy-DxIJGH4P.mjs";
|
|
7
|
+
import { i as switchboardConfigSchema, o as mergeSwitchboardConfig } from "./schema-0g_QdOWn.mjs";
|
|
8
|
+
import { a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as triggerFatalShutdown, h as installFatalErrorShutdown, l as assertWorkflowPackageLoadable, m as workflowSingletonLossHandler, p as retryWorkflowSingleton, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-COM3MKfD.mjs";
|
|
9
|
+
import { t as privacyPlugin } from "./privacy-BO8Q25xI.mjs";
|
|
10
|
+
import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
|
|
11
|
+
import { n as reactorFeatureFlagsOf, t as renownLayers } from "./renown-layers-COZsrGQT.mjs";
|
|
12
|
+
import { n as addDefaultReactorDrive, t as addDefaultDrive } from "./utils-C6AIF38Z.mjs";
|
|
13
|
+
import { createRequire, register } from "node:module";
|
|
14
|
+
import { metrics, trace } from "@opentelemetry/api";
|
|
15
|
+
import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
|
|
16
|
+
import * as Sentry from "@sentry/node";
|
|
17
|
+
import { childLogger, setLogLevel } from "document-model";
|
|
18
|
+
import { getConfig } from "@powerhousedao/config/node";
|
|
19
|
+
import { CatchUpPriority, ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, startProgressHeartbeat, supportsLiveReadModelRegistration, withProgressHeartbeat } from "@powerhousedao/reactor";
|
|
20
|
+
import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
|
|
21
|
+
import { DEFAULT_PGLITE_WORKER_MEMORY_MB, PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, disableWasmWrapperTiering, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteMaintenance, syncTree } from "@powerhousedao/reactor-api/pglite-node";
|
|
22
|
+
import "@powerhousedao/shared/document-model";
|
|
23
|
+
import fs, { promises } from "node:fs";
|
|
24
|
+
import path, { join, resolve } from "node:path";
|
|
25
|
+
import { z } from "zod";
|
|
26
|
+
import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
|
|
27
|
+
import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
28
|
+
import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
|
|
29
|
+
import { DriveNodeView, NodeProcessor, REACTOR_DRIVE_DOCUMENT_TYPE, ReactorDriveClient, createReactorDriveWriteStrategy } from "@powerhousedao/reactor-drive";
|
|
30
|
+
import { REACTOR_DRIVE_SUBGRAPH_NAME, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive/subgraph";
|
|
31
|
+
import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
|
|
32
|
+
import dotenv from "dotenv";
|
|
33
|
+
import { Kysely, PostgresDialect, sql } from "kysely";
|
|
34
|
+
import net from "node:net";
|
|
35
|
+
import path$1 from "path";
|
|
36
|
+
import { Pool } from "pg";
|
|
37
|
+
import { Readable } from "node:stream";
|
|
38
|
+
import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
|
|
39
|
+
import { defaultStoreDirs, resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
|
|
40
|
+
import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
41
|
+
//#region src/profiler.ts
|
|
42
|
+
let started = false;
|
|
43
|
+
async function initProfilerFromEnv(env) {
|
|
44
|
+
if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;
|
|
45
|
+
started = true;
|
|
46
|
+
const { PYROSCOPE_SERVER_ADDRESS: serverAddress, PYROSCOPE_APPLICATION_NAME: appName, PYROSCOPE_USER: basicAuthUser, PYROSCOPE_PASSWORD: basicAuthPassword, PYROSCOPE_WALL_ENABLED: wallEnabled, PYROSCOPE_HEAP_ENABLED: heapEnabled } = env;
|
|
47
|
+
return initProfiler({
|
|
48
|
+
serverAddress,
|
|
49
|
+
appName,
|
|
50
|
+
basicAuthUser,
|
|
51
|
+
basicAuthPassword,
|
|
52
|
+
wall: {
|
|
53
|
+
samplingDurationMs: 1e4,
|
|
54
|
+
samplingIntervalMicros: 1e4,
|
|
55
|
+
collectCpuTime: true
|
|
56
|
+
},
|
|
57
|
+
heap: {
|
|
58
|
+
samplingIntervalBytes: 524288,
|
|
59
|
+
stackDepth: 64
|
|
60
|
+
}
|
|
61
|
+
}, {
|
|
62
|
+
wallEnabled: wallEnabled !== "false",
|
|
63
|
+
heapEnabled: heapEnabled === "true"
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
async function initProfiler(options, flags = {
|
|
67
|
+
wallEnabled: true,
|
|
68
|
+
heapEnabled: false
|
|
69
|
+
}) {
|
|
70
|
+
console.log("Initializing Pyroscope profiler at:", options?.serverAddress);
|
|
71
|
+
console.log(" Wall profiling:", flags.wallEnabled ? "enabled" : "disabled");
|
|
72
|
+
console.log(" Heap profiling:", flags.heapEnabled ? "enabled" : "disabled");
|
|
73
|
+
const { default: Pyroscope } = await import("@pyroscope/nodejs");
|
|
74
|
+
Pyroscope.init(options);
|
|
75
|
+
if (flags.wallEnabled) Pyroscope.startWallProfiling();
|
|
76
|
+
Pyroscope.startCpuProfiling();
|
|
77
|
+
if (flags.heapEnabled) Pyroscope.startHeapProfiling();
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region src/permissions-backfill.mts
|
|
81
|
+
/** The permission tables, as reactor-api once kept them on the read-model store. */
|
|
82
|
+
const PERMISSION_TABLES = [
|
|
83
|
+
"DocumentPermission",
|
|
84
|
+
"OperationUserPermission",
|
|
85
|
+
"DocumentProtection"
|
|
86
|
+
];
|
|
87
|
+
/** What a read-model table is renamed to once its rows live in the reactor store. */
|
|
88
|
+
const MIGRATED_TABLE_SUFFIX = "_migrated_2026_10_25";
|
|
89
|
+
const INSERT_BATCH_SIZE = 500;
|
|
90
|
+
/**
|
|
91
|
+
* Moves the document permission rows from the read-model store into the
|
|
92
|
+
* reactor store, once.
|
|
93
|
+
*
|
|
94
|
+
* Runs at boot after the reactor's migrations (029 creates the target tables)
|
|
95
|
+
* and before the permission service serves a check. When the read-model
|
|
96
|
+
* store still has the legacy tables and the reactor store's are empty, every
|
|
97
|
+
* row is copied in one reactor-store transaction (ids are not carried: no
|
|
98
|
+
* table references them, and the target's serial assigns fresh ones), then
|
|
99
|
+
* the legacy tables are renamed to `<name>_migrated_2026_10_25` so the copy
|
|
100
|
+
* cannot run again. The renamed tables are kept for a release.
|
|
101
|
+
*
|
|
102
|
+
* Idempotent across crashes: when the copy committed but the rename did not,
|
|
103
|
+
* the next boot finds equal row counts on both sides and only renames. Any
|
|
104
|
+
* other mix of rows on both sides is refused with a warning and both stores
|
|
105
|
+
* are left as they are. Plain SQL throughout, so a PGlite or Postgres read
|
|
106
|
+
* store behaves the same.
|
|
107
|
+
*/
|
|
108
|
+
async function backfillPermissionTables(readModelDb, reactorDb, logger) {
|
|
109
|
+
const source = readModelDb;
|
|
110
|
+
const target = reactorDb;
|
|
111
|
+
const present = await existingTables(source);
|
|
112
|
+
const legacy = PERMISSION_TABLES.filter((table) => present.has(table));
|
|
113
|
+
if (legacy.length === 0) {
|
|
114
|
+
if (PERMISSION_TABLES.some((table) => present.has(migratedName(table)))) {
|
|
115
|
+
logger.debug("Permission tables backfill: already done; the read-model tables carry the _migrated_2026_10_25 suffix");
|
|
116
|
+
return { status: "already-backfilled" };
|
|
117
|
+
}
|
|
118
|
+
logger.debug("Permission tables backfill: the read-model store has no permission tables; nothing to copy");
|
|
119
|
+
return { status: "fresh-install" };
|
|
120
|
+
}
|
|
121
|
+
const blocked = legacy.filter((table) => present.has(migratedName(table)));
|
|
122
|
+
if (blocked.length > 0) return refuse(logger, `the read-model store has both ${blocked.join(", ")} and ${blocked.map(migratedName).join(", ")}; drop or rename one of each pair`);
|
|
123
|
+
const legacyCounts = await countRows(source, present);
|
|
124
|
+
const reactorCounts = await countRows(target, new Set(PERMISSION_TABLES));
|
|
125
|
+
if (PERMISSION_TABLES.reduce((sum, table) => sum + reactorCounts[table], 0) > 0) {
|
|
126
|
+
if (!countsEqual(legacyCounts, reactorCounts)) return refuse(logger, `the reactor store already has permission rows (${formatCounts(reactorCounts)}) that differ from the read-model store's (${formatCounts(legacyCounts)})`);
|
|
127
|
+
await renameLegacyTables(source, legacy);
|
|
128
|
+
logger.info(`Permission tables backfill: rows were copied by an earlier boot (${formatCounts(legacyCounts)}); renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`);
|
|
129
|
+
return {
|
|
130
|
+
status: "rename-completed",
|
|
131
|
+
counts: legacyCounts
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
await target.transaction().execute(async (trx) => {
|
|
135
|
+
if (present.has("DocumentPermission")) await copyDocumentPermissions(source, trx);
|
|
136
|
+
if (present.has("OperationUserPermission")) await copyOperationUserPermissions(source, trx);
|
|
137
|
+
if (present.has("DocumentProtection")) await copyDocumentProtections(source, trx);
|
|
138
|
+
const copied = await countRows(trx, new Set(PERMISSION_TABLES));
|
|
139
|
+
if (!countsEqual(copied, legacyCounts)) throw new Error(`Permission tables backfill copied ${formatCounts(copied)} but the read-model store has ${formatCounts(legacyCounts)}; rolled back`);
|
|
140
|
+
});
|
|
141
|
+
await renameLegacyTables(source, legacy);
|
|
142
|
+
logger.info(`Permission tables backfill: copied ${formatCounts(legacyCounts)} from the read-model store to the reactor store; renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`);
|
|
143
|
+
return {
|
|
144
|
+
status: "copied",
|
|
145
|
+
counts: legacyCounts
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function migratedName(table) {
|
|
149
|
+
return `${table}${MIGRATED_TABLE_SUFFIX}`;
|
|
150
|
+
}
|
|
151
|
+
function refuse(logger, reason) {
|
|
152
|
+
logger.warn(`Permission tables backfill refused: ${reason}. Permission checks read the reactor store; both stores were left unchanged.`);
|
|
153
|
+
return {
|
|
154
|
+
status: "refused",
|
|
155
|
+
reason
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/** The permission tables, legacy or renamed, in the read-model store's own schema. */
|
|
159
|
+
async function existingTables(db) {
|
|
160
|
+
const names = PERMISSION_TABLES.flatMap((table) => [table, migratedName(table)]);
|
|
161
|
+
const result = await sql`
|
|
162
|
+
select table_name from information_schema.tables
|
|
163
|
+
where table_schema = current_schema()
|
|
164
|
+
and table_name in (${sql.join(names)})
|
|
165
|
+
`.execute(db);
|
|
166
|
+
return new Set(result.rows.map((row) => row.table_name));
|
|
167
|
+
}
|
|
168
|
+
async function countRows(db, tables) {
|
|
169
|
+
const counts = {
|
|
170
|
+
DocumentPermission: 0,
|
|
171
|
+
OperationUserPermission: 0,
|
|
172
|
+
DocumentProtection: 0
|
|
173
|
+
};
|
|
174
|
+
for (const table of PERMISSION_TABLES) {
|
|
175
|
+
if (!tables.has(table)) continue;
|
|
176
|
+
const row = await db.selectFrom(table).select((eb) => eb.fn.countAll().as("count")).executeTakeFirstOrThrow();
|
|
177
|
+
counts[table] = Number(row.count);
|
|
178
|
+
}
|
|
179
|
+
return counts;
|
|
180
|
+
}
|
|
181
|
+
function countsEqual(a, b) {
|
|
182
|
+
return PERMISSION_TABLES.every((table) => a[table] === b[table]);
|
|
183
|
+
}
|
|
184
|
+
function formatCounts(counts) {
|
|
185
|
+
return PERMISSION_TABLES.map((table) => `${table}=${counts[table]}`).join(", ");
|
|
186
|
+
}
|
|
187
|
+
async function copyDocumentPermissions(source, trx) {
|
|
188
|
+
const rows = await source.selectFrom("DocumentPermission").select([
|
|
189
|
+
"documentId",
|
|
190
|
+
"userAddress",
|
|
191
|
+
"permission",
|
|
192
|
+
"grantedBy",
|
|
193
|
+
"createdAt",
|
|
194
|
+
"updatedAt"
|
|
195
|
+
]).orderBy("id").execute();
|
|
196
|
+
for (const batch of batches(rows)) await trx.insertInto("DocumentPermission").values(batch).execute();
|
|
197
|
+
}
|
|
198
|
+
async function copyOperationUserPermissions(source, trx) {
|
|
199
|
+
const rows = await source.selectFrom("OperationUserPermission").select([
|
|
200
|
+
"documentId",
|
|
201
|
+
"operationType",
|
|
202
|
+
"userAddress",
|
|
203
|
+
"grantedBy",
|
|
204
|
+
"createdAt"
|
|
205
|
+
]).orderBy("id").execute();
|
|
206
|
+
for (const batch of batches(rows)) await trx.insertInto("OperationUserPermission").values(batch).execute();
|
|
207
|
+
}
|
|
208
|
+
async function copyDocumentProtections(source, trx) {
|
|
209
|
+
const rows = await source.selectFrom("DocumentProtection").select([
|
|
210
|
+
"documentId",
|
|
211
|
+
"protected",
|
|
212
|
+
"ownerAddress",
|
|
213
|
+
"createdAt",
|
|
214
|
+
"updatedAt"
|
|
215
|
+
]).orderBy("documentId").execute();
|
|
216
|
+
for (const batch of batches(rows)) await trx.insertInto("DocumentProtection").values(batch).execute();
|
|
217
|
+
}
|
|
218
|
+
function* batches(rows) {
|
|
219
|
+
for (let start = 0; start < rows.length; start += INSERT_BATCH_SIZE) yield rows.slice(start, start + INSERT_BATCH_SIZE);
|
|
220
|
+
}
|
|
221
|
+
async function renameLegacyTables(db, tables) {
|
|
222
|
+
await db.transaction().execute(async (trx) => {
|
|
223
|
+
for (const table of tables) await sql`ALTER TABLE ${sql.id(table)} RENAME TO ${sql.id(migratedName(table))}`.execute(trx);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
//#endregion
|
|
227
|
+
//#region src/attachments/auth.ts
|
|
228
|
+
const ANONYMOUS_ACTOR = {
|
|
229
|
+
user: void 0,
|
|
230
|
+
authEnabled: false
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* Wrap a Node-style handler so that, when `authService` is provided and auth is
|
|
234
|
+
* enabled, the request must carry a verifiable Bearer token. The handler always
|
|
235
|
+
* receives an actor context: the verified bearer user when auth is enabled, or
|
|
236
|
+
* the anonymous context when it is disabled. With `allowAnonymous`, a missing
|
|
237
|
+
* bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —
|
|
238
|
+
* unless `requireAuthenticatedCaller` says the deployment refuses anonymous
|
|
239
|
+
* callers outright, which overrides it.
|
|
240
|
+
*
|
|
241
|
+
* With no `authService` there is no bearer to read and every caller is
|
|
242
|
+
* anonymous, so nothing is refused here. That combination cannot carry the
|
|
243
|
+
* floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with
|
|
244
|
+
* `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity
|
|
245
|
+
* resolution is what builds the service.
|
|
246
|
+
*/
|
|
247
|
+
function requireAuth(authService, handler, options) {
|
|
248
|
+
if (!authService) return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);
|
|
249
|
+
return async (req, res, body) => {
|
|
250
|
+
let result;
|
|
251
|
+
try {
|
|
252
|
+
result = await authService.verifyBearer(req.headers.authorization);
|
|
253
|
+
} catch {
|
|
254
|
+
res.statusCode = 500;
|
|
255
|
+
res.setHeader("Content-Type", "application/json");
|
|
256
|
+
res.end(JSON.stringify({ error: "Internal authentication error" }));
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (result instanceof Response) {
|
|
260
|
+
const body = await result.text();
|
|
261
|
+
res.statusCode = result.status;
|
|
262
|
+
const contentType = result.headers.get("content-type");
|
|
263
|
+
if (contentType) res.setHeader("Content-Type", contentType);
|
|
264
|
+
res.end(body);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (!result.user) {
|
|
268
|
+
if (options?.requireAuthenticatedCaller === true || result.auth_enabled && !options?.allowAnonymous) {
|
|
269
|
+
res.statusCode = 401;
|
|
270
|
+
res.setHeader("Content-Type", "application/json");
|
|
271
|
+
res.end(JSON.stringify({ error: "Authentication required" }));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
await handler(req, res, body, {
|
|
276
|
+
user: result.user,
|
|
277
|
+
authEnabled: result.auth_enabled
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region src/attachments/mount-auth.ts
|
|
283
|
+
/**
|
|
284
|
+
* Mount a Node-style attachment route with `requireAuth` applied unconditionally.
|
|
285
|
+
* When `api.authService` is undefined (auth disabled), the handler still runs
|
|
286
|
+
* through `requireAuth` and receives the anonymous actor context — that is the
|
|
287
|
+
* only way to opt out of bearer verification. To register a route without auth
|
|
288
|
+
* wrapping you must call `api.httpAdapter.mountNodeRoute` directly.
|
|
289
|
+
*
|
|
290
|
+
* `allowAnonymous` is reserved for routes whose handlers make a per-document
|
|
291
|
+
* authorization decision themselves; identity-only routes must not use it. It
|
|
292
|
+
* is also not the last word: a deployment that refuses anonymous callers
|
|
293
|
+
* (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes
|
|
294
|
+
* are mounted on the HTTP adapter and never reach the fetch chain that carries
|
|
295
|
+
* that floor for GraphQL. The flag is read from the API, so every route
|
|
296
|
+
* mounted through here inherits it without each one remembering to.
|
|
297
|
+
*/
|
|
298
|
+
function mountAuthenticatedNodeRoute(api, method, path, handler, options) {
|
|
299
|
+
const { rawBody, ...authOptions } = options ?? {};
|
|
300
|
+
api.httpAdapter.mountNodeRoute(method, path, requireAuth(api.authService, handler, {
|
|
301
|
+
...authOptions,
|
|
302
|
+
requireAuthenticatedCaller: api.requireAuthenticatedCaller
|
|
303
|
+
}), { rawBody: rawBody ?? false });
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region src/attachments/routes.ts
|
|
307
|
+
const logger$2 = childLogger(["switchboard", "attachments"]);
|
|
308
|
+
const RETRY_AFTER_SECONDS = 5;
|
|
309
|
+
const HASH_PATTERN = /^[a-f0-9]{64}$/i;
|
|
310
|
+
function sendJson(res, status, body) {
|
|
311
|
+
res.statusCode = status;
|
|
312
|
+
res.setHeader("Content-Type", "application/json");
|
|
313
|
+
res.end(JSON.stringify(body));
|
|
314
|
+
}
|
|
315
|
+
function sendError(res, status, message) {
|
|
316
|
+
sendJson(res, status, { error: message });
|
|
317
|
+
}
|
|
318
|
+
function statusForError(err) {
|
|
319
|
+
if (err instanceof AttachmentNotFound) return 404;
|
|
320
|
+
if (err instanceof ReservationNotFound) return 404;
|
|
321
|
+
if (err instanceof InvalidAttachmentRef) return 400;
|
|
322
|
+
if (err instanceof UploadTooLarge) return 413;
|
|
323
|
+
return 500;
|
|
324
|
+
}
|
|
325
|
+
function sendErrorFromException(res, err) {
|
|
326
|
+
const status = statusForError(err);
|
|
327
|
+
if (status >= 500) {
|
|
328
|
+
logger$2.error("Attachment route error: @error", err);
|
|
329
|
+
sendError(res, status, "Internal error");
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
sendError(res, status, err instanceof Error ? err.message : String(err));
|
|
333
|
+
}
|
|
334
|
+
async function readJsonBody(req, body) {
|
|
335
|
+
if (body !== void 0 && body !== null && typeof body === "object") return body;
|
|
336
|
+
const chunks = [];
|
|
337
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
338
|
+
if (chunks.length === 0) return void 0;
|
|
339
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
340
|
+
if (text.length === 0) return void 0;
|
|
341
|
+
return JSON.parse(text);
|
|
342
|
+
}
|
|
343
|
+
function parseReserveOptions(input) {
|
|
344
|
+
if (input === null || typeof input !== "object") return null;
|
|
345
|
+
const obj = input;
|
|
346
|
+
const { mimeType, fileName } = obj;
|
|
347
|
+
const extension = obj.extension ?? null;
|
|
348
|
+
try {
|
|
349
|
+
validateReserveMetadata({
|
|
350
|
+
mimeType,
|
|
351
|
+
fileName,
|
|
352
|
+
extension
|
|
353
|
+
});
|
|
354
|
+
} catch (err) {
|
|
355
|
+
if (err instanceof InvalidAttachmentMetadata) return null;
|
|
356
|
+
throw err;
|
|
357
|
+
}
|
|
358
|
+
if (typeof mimeType !== "string" || typeof fileName !== "string") return null;
|
|
359
|
+
if (extension !== null && typeof extension !== "string") return null;
|
|
360
|
+
if (obj.clientHash !== void 0) {
|
|
361
|
+
if (typeof obj.clientHash !== "string" || !HASH_PATTERN.test(obj.clientHash)) return null;
|
|
362
|
+
if (typeof obj.sizeBytes !== "number" || !Number.isSafeInteger(obj.sizeBytes) || obj.sizeBytes < 0) return null;
|
|
363
|
+
return {
|
|
364
|
+
mimeType,
|
|
365
|
+
fileName,
|
|
366
|
+
extension,
|
|
367
|
+
clientHash: obj.clientHash.toLowerCase(),
|
|
368
|
+
sizeBytes: obj.sizeBytes
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
return {
|
|
372
|
+
mimeType,
|
|
373
|
+
fileName,
|
|
374
|
+
extension
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
function quoteFilename(name) {
|
|
378
|
+
return `"${name.replace(/[\\"]/g, "\\$&")}"`;
|
|
379
|
+
}
|
|
380
|
+
function buildContentDisposition(fileName) {
|
|
381
|
+
const ascii = fileName.replace(/[^\x20-\x21\x23-\x5b\x5d-\x7e]/g, "_");
|
|
382
|
+
const encoded = encodeURIComponent(fileName).replace(/['()*!]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
383
|
+
return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;
|
|
384
|
+
}
|
|
385
|
+
function makeReserveHandler(attachments) {
|
|
386
|
+
return async (req, res, body) => {
|
|
387
|
+
let parsed;
|
|
388
|
+
try {
|
|
389
|
+
parsed = await readJsonBody(req, body);
|
|
390
|
+
} catch {
|
|
391
|
+
sendError(res, 400, "Invalid JSON body");
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const opts = parseReserveOptions(parsed);
|
|
395
|
+
if (!opts) {
|
|
396
|
+
sendError(res, 400, "Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }");
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
let upload;
|
|
400
|
+
try {
|
|
401
|
+
upload = await attachments.service.reserve(opts);
|
|
402
|
+
} catch (err) {
|
|
403
|
+
if (err instanceof AttachmentAlreadyExists) {
|
|
404
|
+
sendJson(res, 409, {
|
|
405
|
+
error: "already_exists",
|
|
406
|
+
ref: err.ref
|
|
407
|
+
});
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
sendErrorFromException(res, err);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
sendJson(res, 201, {
|
|
414
|
+
reservationId: upload.reservationId,
|
|
415
|
+
ref: upload.ref,
|
|
416
|
+
expiresAtUtc: upload.expiresAtUtc,
|
|
417
|
+
...upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}
|
|
418
|
+
});
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
function makeUploadHandler(attachments) {
|
|
422
|
+
return async (req, res) => {
|
|
423
|
+
const reservationId = extractParam(req, "reservationId");
|
|
424
|
+
if (!reservationId) {
|
|
425
|
+
sendError(res, 400, "Missing reservationId");
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (attachments.backend?.kind === "s3") {
|
|
429
|
+
sendError(res, 405, "Use the reservation uploadTarget for S3 uploads");
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
let reservation;
|
|
433
|
+
try {
|
|
434
|
+
reservation = await attachments.reservations.get(reservationId);
|
|
435
|
+
} catch (err) {
|
|
436
|
+
sendErrorFromException(res, err);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const upload = attachments.uploadFactory.createUpload(reservation);
|
|
440
|
+
const webStream = Readable.toWeb(req);
|
|
441
|
+
try {
|
|
442
|
+
sendJson(res, 200, await upload.send(webStream));
|
|
443
|
+
} catch (err) {
|
|
444
|
+
if (err instanceof HashMismatch) {
|
|
445
|
+
sendJson(res, 422, {
|
|
446
|
+
error: "hash_mismatch",
|
|
447
|
+
claimed: err.claimed,
|
|
448
|
+
actual: err.actual
|
|
449
|
+
});
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (err instanceof SizeMismatch) {
|
|
453
|
+
sendJson(res, 422, {
|
|
454
|
+
error: "size_mismatch",
|
|
455
|
+
declared: err.declared,
|
|
456
|
+
actual: err.actual
|
|
457
|
+
});
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
sendErrorFromException(res, err);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
function makeDownloadHandler(attachments, attachmentAccess, urlSigner) {
|
|
465
|
+
return async (req, res, _body, actor) => {
|
|
466
|
+
const hash = extractParam(req, "hash");
|
|
467
|
+
if (!hash || !HASH_PATTERN.test(hash)) {
|
|
468
|
+
sendError(res, 400, "Invalid attachment hash");
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const canonicalHash = hash.toLowerCase();
|
|
472
|
+
const grant = await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner);
|
|
473
|
+
if (!admitGrant(res, grant)) return;
|
|
474
|
+
const controller = new AbortController();
|
|
475
|
+
req.once("close", () => controller.abort());
|
|
476
|
+
let response;
|
|
477
|
+
try {
|
|
478
|
+
response = await attachments.store.get(canonicalHash, controller.signal, grant.documentId);
|
|
479
|
+
} catch (err) {
|
|
480
|
+
if (err instanceof AttachmentPending) {
|
|
481
|
+
res.statusCode = 202;
|
|
482
|
+
res.setHeader("Cache-Control", "private");
|
|
483
|
+
res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
|
|
484
|
+
res.setHeader("Attachment-Pending", buildPendingHeader({
|
|
485
|
+
expiresAtUtc: err.expiresAtUtc,
|
|
486
|
+
...err.metadata ?? {}
|
|
487
|
+
}));
|
|
488
|
+
res.end();
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
sendErrorFromException(res, err);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const { header, body } = response;
|
|
495
|
+
res.statusCode = 200;
|
|
496
|
+
res.setHeader("Cache-Control", "private");
|
|
497
|
+
res.setHeader("Content-Type", header.mimeType);
|
|
498
|
+
res.setHeader("Content-Length", String(header.sizeBytes));
|
|
499
|
+
res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
|
|
500
|
+
res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
|
|
501
|
+
const source = Readable.fromWeb(body);
|
|
502
|
+
source.once("error", (err) => handleDownloadStreamError(res, hash, err));
|
|
503
|
+
source.pipe(res);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function handleDownloadStreamError(res, hash, err) {
|
|
507
|
+
if (res.headersSent) {
|
|
508
|
+
logger$2.error("Attachment stream failed mid-download: @error", err);
|
|
509
|
+
res.destroy();
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
res.removeHeader("Content-Length");
|
|
513
|
+
res.removeHeader("Content-Disposition");
|
|
514
|
+
res.removeHeader("Attachment-Metadata");
|
|
515
|
+
if (err?.code === "ENOENT") {
|
|
516
|
+
logger$2.warn("Attachment @hash is recorded as available but its blob is missing", hash);
|
|
517
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
logger$2.error("Attachment stream failed before sending: @error", err);
|
|
521
|
+
sendError(res, 500, "Internal error");
|
|
522
|
+
}
|
|
523
|
+
function toAsciiJson(value) {
|
|
524
|
+
return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
525
|
+
}
|
|
526
|
+
function buildPendingHeader(pending) {
|
|
527
|
+
return toAsciiJson(pending);
|
|
528
|
+
}
|
|
529
|
+
function buildMetadataHeader(header) {
|
|
530
|
+
return toAsciiJson({
|
|
531
|
+
mimeType: header.mimeType,
|
|
532
|
+
fileName: header.fileName,
|
|
533
|
+
sizeBytes: header.sizeBytes,
|
|
534
|
+
extension: header.extension,
|
|
535
|
+
createdAtUtc: header.createdAtUtc,
|
|
536
|
+
lastAccessedAtUtc: header.lastAccessedAtUtc
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
function makeStatHandler(attachments, attachmentAccess, urlSigner) {
|
|
540
|
+
return async (req, res, _body, actor) => {
|
|
541
|
+
const hash = extractParam(req, "hash");
|
|
542
|
+
if (!hash || !HASH_PATTERN.test(hash)) {
|
|
543
|
+
sendError(res, 400, "Invalid attachment hash");
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
const canonicalHash = hash.toLowerCase();
|
|
547
|
+
if (!admitGrant(res, await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner))) return;
|
|
548
|
+
let header;
|
|
549
|
+
try {
|
|
550
|
+
header = await attachments.store.stat(canonicalHash);
|
|
551
|
+
} catch (err) {
|
|
552
|
+
sendErrorFromException(res, err);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
res.setHeader("Cache-Control", "private");
|
|
556
|
+
if (header.status === "pending") {
|
|
557
|
+
res.statusCode = 202;
|
|
558
|
+
res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
|
|
559
|
+
res.setHeader("Attachment-Pending", buildPendingHeader({
|
|
560
|
+
expiresAtUtc: header.expiresAtUtc,
|
|
561
|
+
mimeType: header.mimeType,
|
|
562
|
+
fileName: header.fileName,
|
|
563
|
+
sizeBytes: header.sizeBytes
|
|
564
|
+
}));
|
|
565
|
+
res.end();
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
res.statusCode = 200;
|
|
569
|
+
res.setHeader("Content-Type", header.mimeType);
|
|
570
|
+
res.setHeader("Content-Length", String(header.sizeBytes));
|
|
571
|
+
res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
|
|
572
|
+
res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
|
|
573
|
+
res.end();
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
function makeGetReservationHandler(attachments) {
|
|
577
|
+
return async (req, res) => {
|
|
578
|
+
const reservationId = extractParam(req, "reservationId");
|
|
579
|
+
if (!reservationId) {
|
|
580
|
+
sendError(res, 400, "Missing reservationId");
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
try {
|
|
584
|
+
sendJson(res, 200, await attachments.reservations.get(reservationId));
|
|
585
|
+
} catch (err) {
|
|
586
|
+
sendErrorFromException(res, err);
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
function makeDeleteReservationHandler(attachments) {
|
|
591
|
+
return async (req, res) => {
|
|
592
|
+
const reservationId = extractParam(req, "reservationId");
|
|
593
|
+
if (!reservationId) {
|
|
594
|
+
sendError(res, 400, "Missing reservationId");
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
try {
|
|
598
|
+
await attachments.reservations.delete(reservationId);
|
|
599
|
+
res.statusCode = 204;
|
|
600
|
+
res.end();
|
|
601
|
+
} catch (err) {
|
|
602
|
+
sendErrorFromException(res, err);
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function extractParam(req, name) {
|
|
607
|
+
return req.params?.[name];
|
|
608
|
+
}
|
|
609
|
+
const MAX_DOCUMENT_ID_LEN = 512;
|
|
610
|
+
const ATTACHMENT_NOT_FOUND_BODY = { error: "Attachment not found" };
|
|
611
|
+
const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 604800;
|
|
612
|
+
/**
|
|
613
|
+
* How long a download target may live, by default.
|
|
614
|
+
*
|
|
615
|
+
* The authorization behind a presigned URL is decided once, when it is issued,
|
|
616
|
+
* and the URL keeps working until it expires however the document's policy
|
|
617
|
+
* changes in between. A week of that is a revocation that does not revoke: an
|
|
618
|
+
* account deactivated, a company reassigned or a group left, and the bytes stay
|
|
619
|
+
* fetchable by anyone holding the link. Minutes are enough to open a file;
|
|
620
|
+
* days are only enough to lose control of it.
|
|
621
|
+
*
|
|
622
|
+
* A deployment that needs longer sets `attachments.downloadTargetMaxTtlSeconds`
|
|
623
|
+
* (ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS at the edge), still bounded by the
|
|
624
|
+
* signing ceiling above.
|
|
625
|
+
*/
|
|
626
|
+
const DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;
|
|
627
|
+
/** A configured ceiling, bounded by the signing maximum; unset is the default. */
|
|
628
|
+
function downloadTargetTtlCapSeconds(configured) {
|
|
629
|
+
return configured === void 0 ? DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS : Math.min(configured, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Returns the single `documentId` query value, or null when it is missing,
|
|
633
|
+
* duplicated, blank, or oversized. Validation happens before authorization so
|
|
634
|
+
* malformed requests never reach the access service.
|
|
635
|
+
*/
|
|
636
|
+
function extractSingleDocumentId(req) {
|
|
637
|
+
if (!req.url) return null;
|
|
638
|
+
let url;
|
|
639
|
+
try {
|
|
640
|
+
url = new URL(req.url, "http://switchboard.invalid");
|
|
641
|
+
} catch {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
const values = url.searchParams.getAll("documentId");
|
|
645
|
+
if (values.length !== 1) return null;
|
|
646
|
+
const value = values[0];
|
|
647
|
+
if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) return null;
|
|
648
|
+
return value;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Returns the target TTL in seconds, or "invalid" when the caller's own value
|
|
652
|
+
* is malformed (duplicated, non-integer, or non-positive).
|
|
653
|
+
*
|
|
654
|
+
* The cap applies whether or not the caller asked for a lifetime: omitting
|
|
655
|
+
* `expiresIn` used to fall through to whatever the storage backend was
|
|
656
|
+
* configured with, which would make the ceiling something a client opts out of
|
|
657
|
+
* by saying nothing.
|
|
658
|
+
*/
|
|
659
|
+
function extractExpiresIn(req, cap) {
|
|
660
|
+
if (!req.url) return cap;
|
|
661
|
+
let url;
|
|
662
|
+
try {
|
|
663
|
+
url = new URL(req.url, "http://switchboard.invalid");
|
|
664
|
+
} catch {
|
|
665
|
+
return cap;
|
|
666
|
+
}
|
|
667
|
+
const values = url.searchParams.getAll("expiresIn");
|
|
668
|
+
if (values.length === 0) return cap;
|
|
669
|
+
if (values.length > 1) return "invalid";
|
|
670
|
+
const parsed = Number(values[0]);
|
|
671
|
+
if (!Number.isInteger(parsed) || parsed <= 0) return "invalid";
|
|
672
|
+
return Math.min(parsed, cap);
|
|
673
|
+
}
|
|
674
|
+
function singleQueryValue(params, name) {
|
|
675
|
+
const values = params.getAll(name);
|
|
676
|
+
return values.length === 1 ? values[0] : null;
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Byte routes serve only under a grant: a signed URL minted by the
|
|
680
|
+
* download-target route, or a documentId the caller may read the attachment
|
|
681
|
+
* through. A signed request is judged by its signature alone.
|
|
682
|
+
*/
|
|
683
|
+
async function resolveByteGrant(req, hash, actor, attachmentAccess, urlSigner) {
|
|
684
|
+
let params;
|
|
685
|
+
try {
|
|
686
|
+
params = new URL(req.url ?? "", "http://switchboard.invalid").searchParams;
|
|
687
|
+
} catch {
|
|
688
|
+
return { kind: "denied" };
|
|
689
|
+
}
|
|
690
|
+
const documentId = extractSingleDocumentId(req);
|
|
691
|
+
if (documentId === null) return { kind: "denied" };
|
|
692
|
+
if (params.has("signature") || params.has("expires")) {
|
|
693
|
+
const signature = singleQueryValue(params, "signature");
|
|
694
|
+
const expires = singleQueryValue(params, "expires");
|
|
695
|
+
if (!urlSigner || signature === null || expires === null) return { kind: "denied" };
|
|
696
|
+
return urlSigner.verify(hash, documentId, expires, signature) ? {
|
|
697
|
+
kind: "granted",
|
|
698
|
+
documentId
|
|
699
|
+
} : { kind: "denied" };
|
|
700
|
+
}
|
|
701
|
+
let decision;
|
|
702
|
+
try {
|
|
703
|
+
decision = await attachmentAccess.canReadAttachment({
|
|
704
|
+
documentId,
|
|
705
|
+
attachmentRef: createRef(hash),
|
|
706
|
+
userAddress: actor?.user?.address,
|
|
707
|
+
appKey: actor?.user?.appKey
|
|
708
|
+
});
|
|
709
|
+
} catch (err) {
|
|
710
|
+
logger$2.error("Attachment access decision failed: @error", err);
|
|
711
|
+
return { kind: "error" };
|
|
712
|
+
}
|
|
713
|
+
if (decision.kind === "projection-unavailable") return { kind: "unavailable" };
|
|
714
|
+
if (decision.kind === "denied") return { kind: "denied" };
|
|
715
|
+
return {
|
|
716
|
+
kind: "granted",
|
|
717
|
+
documentId: decision.documentId
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
/** Answers a refused grant; true when the request may proceed. */
|
|
721
|
+
function admitGrant(res, grant) {
|
|
722
|
+
switch (grant.kind) {
|
|
723
|
+
case "granted": return true;
|
|
724
|
+
case "denied":
|
|
725
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
726
|
+
return false;
|
|
727
|
+
case "unavailable":
|
|
728
|
+
sendError(res, 503, "Attachment downloads are temporarily unavailable");
|
|
729
|
+
return false;
|
|
730
|
+
case "error":
|
|
731
|
+
sendError(res, 500, "Internal error");
|
|
732
|
+
return false;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Base URL of this Switchboard as seen by the caller, used to build
|
|
737
|
+
* filesystem `switchboard` download targets that point back at the signed
|
|
738
|
+
* byte route.
|
|
739
|
+
*/
|
|
740
|
+
function requestBaseUrl(req) {
|
|
741
|
+
const forwardedProto = req.headers["x-forwarded-proto"];
|
|
742
|
+
const proto = (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)?.split(",")[0]?.trim() || (req.socket.encrypted ? "https" : "http");
|
|
743
|
+
const forwardedHost = req.headers["x-forwarded-host"];
|
|
744
|
+
const host = (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ?? req.headers.host;
|
|
745
|
+
if (!host) return null;
|
|
746
|
+
return `${proto}://${host}`;
|
|
747
|
+
}
|
|
748
|
+
function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner, ttlCapSeconds = downloadTargetTtlCapSeconds(void 0)) {
|
|
749
|
+
return async (req, res, _body, actor) => {
|
|
750
|
+
res.setHeader("Cache-Control", "no-store");
|
|
751
|
+
const hash = extractParam(req, "hash");
|
|
752
|
+
if (!hash || !HASH_PATTERN.test(hash)) {
|
|
753
|
+
sendError(res, 400, "Invalid attachment hash");
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const documentId = extractSingleDocumentId(req);
|
|
757
|
+
if (documentId === null) {
|
|
758
|
+
sendError(res, 400, "documentId is required exactly once as a non-empty query parameter");
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
const expiresIn = extractExpiresIn(req, ttlCapSeconds);
|
|
762
|
+
if (expiresIn === "invalid") {
|
|
763
|
+
sendError(res, 400, "expiresIn must be a single positive integer number of seconds");
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
const canonicalHash = hash.toLowerCase();
|
|
767
|
+
let decision;
|
|
768
|
+
try {
|
|
769
|
+
decision = await attachmentAccess.canReadAttachment({
|
|
770
|
+
documentId,
|
|
771
|
+
attachmentRef: createRef(canonicalHash),
|
|
772
|
+
userAddress: actor?.user?.address,
|
|
773
|
+
appKey: actor?.user?.appKey
|
|
774
|
+
});
|
|
775
|
+
} catch (err) {
|
|
776
|
+
logger$2.error("Attachment access decision failed: @error", err);
|
|
777
|
+
sendError(res, 500, "Internal error");
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
if (decision.kind === "projection-unavailable") {
|
|
781
|
+
sendError(res, 503, "Attachment downloads are temporarily unavailable");
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
if (decision.kind === "denied") {
|
|
785
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
let header;
|
|
789
|
+
try {
|
|
790
|
+
header = await attachments.store.stat(canonicalHash);
|
|
791
|
+
} catch (err) {
|
|
792
|
+
if (err instanceof AttachmentNotFound) {
|
|
793
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
logger$2.error("Attachment metadata lookup failed: @error", err);
|
|
797
|
+
sendError(res, 500, "Internal error");
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (header.status !== "available") {
|
|
801
|
+
sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
let target;
|
|
805
|
+
if (attachments.backend && attachments.backend.kind !== "filesystem") try {
|
|
806
|
+
target = await attachments.backend.prepareDownloadTarget(canonicalHash, expiresIn);
|
|
807
|
+
} catch {
|
|
808
|
+
sendError(res, 502, "Attachment download target unavailable");
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
else {
|
|
812
|
+
if (!urlSigner) {
|
|
813
|
+
sendError(res, 503, "Attachment download signing is not configured");
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const base = requestBaseUrl(req);
|
|
817
|
+
if (!base) {
|
|
818
|
+
sendError(res, 500, "Internal error");
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
const signed = urlSigner.sign(canonicalHash, decision.documentId, expiresIn);
|
|
822
|
+
try {
|
|
823
|
+
target = parseAttachmentDownloadTarget({
|
|
824
|
+
kind: "switchboard",
|
|
825
|
+
method: "GET",
|
|
826
|
+
url: `${base}/attachments/${canonicalHash}?${signed.query}`,
|
|
827
|
+
headers: {},
|
|
828
|
+
expiresAtUtc: signed.expiresAtUtc
|
|
829
|
+
});
|
|
830
|
+
} catch {
|
|
831
|
+
sendError(res, 500, "Internal error");
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
sendJson(res, 200, target);
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
//#endregion
|
|
839
|
+
//#region src/attachments/index.ts
|
|
840
|
+
const logger$1 = childLogger(["switchboard", "attachments"]);
|
|
841
|
+
function registerAttachmentRoutes(api, options = {}) {
|
|
842
|
+
const { attachments, attachmentAccess } = api;
|
|
843
|
+
const { config } = options;
|
|
844
|
+
const urlSigner = options.urlSigner === void 0 ? signerFromEnvironment(attachments.backend?.kind ?? "filesystem", {
|
|
845
|
+
[ATTACHMENT_URL_SIGNING_SECRET_ENV]: config?.urlSigningSecret,
|
|
846
|
+
NODE_ENV: process.env.NODE_ENV
|
|
847
|
+
}) : options.urlSigner;
|
|
848
|
+
const ttlCapSeconds = downloadTargetTtlCapSeconds(config?.downloadTargetMaxTtlSeconds);
|
|
849
|
+
mountAuthenticatedNodeRoute(api, "POST", "/attachments/reservations", makeReserveHandler(attachments));
|
|
850
|
+
mountAuthenticatedNodeRoute(api, "GET", "/attachments/reservations/:reservationId", makeGetReservationHandler(attachments));
|
|
851
|
+
mountAuthenticatedNodeRoute(api, "DELETE", "/attachments/reservations/:reservationId", makeDeleteReservationHandler(attachments));
|
|
852
|
+
mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments), { rawBody: true });
|
|
853
|
+
mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
854
|
+
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner, ttlCapSeconds), { allowAnonymous: true });
|
|
855
|
+
mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
|
|
856
|
+
}
|
|
857
|
+
function signerFromEnvironment(backend, env) {
|
|
858
|
+
const signing = resolveAttachmentUrlSigning(env);
|
|
859
|
+
if (signing.status === "unconfigured") {
|
|
860
|
+
if (backend === "filesystem") logger$1.error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`);
|
|
861
|
+
return null;
|
|
862
|
+
}
|
|
863
|
+
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`);
|
|
864
|
+
return signing.signer;
|
|
865
|
+
}
|
|
866
|
+
//#endregion
|
|
867
|
+
//#region src/attachment-reference-read-model.mts
|
|
868
|
+
const attachmentSchemaCompiler = new AttachmentSchemaCompiler();
|
|
869
|
+
function createAttachmentReferenceReadModel(baseKysely, dependencies, attachmentReferenceWriter) {
|
|
870
|
+
return new AttachmentReferenceReadModel(baseKysely.withSchema(REACTOR_SCHEMA), dependencies.operationIndex, dependencies.writeCache, dependencies.processorManagerConsistencyTracker, dependencies.documentModelRegistry, attachmentSchemaCompiler, attachmentReferenceWriter);
|
|
871
|
+
}
|
|
872
|
+
function registerAttachmentReferenceReadModel(reactorBuilder, registration) {
|
|
873
|
+
reactorBuilder.withReadModelFactory(async ({ documentModelRegistry, operationIndex, writeCache, processorManagerConsistencyTracker }) => {
|
|
874
|
+
const readModel = createAttachmentReferenceReadModel(registration.baseKysely, {
|
|
875
|
+
operationIndex,
|
|
876
|
+
writeCache,
|
|
877
|
+
processorManagerConsistencyTracker,
|
|
878
|
+
documentModelRegistry
|
|
879
|
+
}, registration.attachmentReferenceWriter);
|
|
880
|
+
await readModel.init();
|
|
881
|
+
return readModel;
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
async function registerAttachmentReferenceReadModelOnModule(clientModule, attachmentReferenceWriter) {
|
|
885
|
+
const reactorModule = clientModule.reactorModule;
|
|
886
|
+
if (!reactorModule) return {
|
|
887
|
+
status: "unavailable",
|
|
888
|
+
reason: "in-process-reactor-module-unavailable"
|
|
889
|
+
};
|
|
890
|
+
const coordinator = reactorModule.readModelCoordinator;
|
|
891
|
+
if (!supportsLiveReadModelRegistration(coordinator)) return {
|
|
892
|
+
status: "unavailable",
|
|
893
|
+
reason: "live-read-model-registration-unsupported"
|
|
894
|
+
};
|
|
895
|
+
const readModel = createAttachmentReferenceReadModel(reactorModule.database, {
|
|
896
|
+
operationIndex: reactorModule.operationIndex,
|
|
897
|
+
writeCache: reactorModule.writeCache,
|
|
898
|
+
processorManagerConsistencyTracker: reactorModule.processorManagerConsistencyTracker,
|
|
899
|
+
documentModelRegistry: reactorModule.documentModelRegistry
|
|
900
|
+
}, attachmentReferenceWriter);
|
|
901
|
+
await readModel.init();
|
|
902
|
+
coordinator.addReadModel(readModel, "pre_ready");
|
|
903
|
+
await readModel.init();
|
|
904
|
+
return { status: "available" };
|
|
905
|
+
}
|
|
906
|
+
//#endregion
|
|
907
|
+
//#region src/builder-defaults.mts
|
|
908
|
+
/**
|
|
909
|
+
* Apply switchboard's standard configuration to a reactor + client builder
|
|
910
|
+
* pair. Each piece is opt-out via the options object; defaults mirror what
|
|
911
|
+
* `startSwitchboard` does when building a reactor itself. Mutates both
|
|
912
|
+
* builders in place.
|
|
913
|
+
*
|
|
914
|
+
* Does NOT touch kysely or read models — callers wire those themselves
|
|
915
|
+
* (see `withKysely` / `withReadModelFactory` on the reactor builder).
|
|
916
|
+
*/
|
|
917
|
+
/** The models switchboard always registers alongside package models. */
|
|
918
|
+
function switchboardBaseDocumentModels() {
|
|
919
|
+
return baseDocumentModels.map(([, model]) => model);
|
|
920
|
+
}
|
|
921
|
+
function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options = {}) {
|
|
922
|
+
const baseModels = options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];
|
|
923
|
+
const extra = options.documentModels ?? [];
|
|
924
|
+
if (baseModels.length || extra.length) reactorBuilder.withDocumentModelSources(getUniqueDocumentModels(baseModels, extra));
|
|
925
|
+
if (options.upgradeManifests?.length) reactorBuilder.withUpgradeManifests(options.upgradeManifests);
|
|
926
|
+
const scheme = options.channelScheme === void 0 ? ChannelScheme.SWITCHBOARD : options.channelScheme;
|
|
927
|
+
if (scheme !== false) reactorBuilder.withChannelScheme(scheme);
|
|
928
|
+
if (options.signalHandlers !== false) reactorBuilder.withSignalHandlers();
|
|
929
|
+
if (options.executorConfig?.maxSkipThreshold !== void 0 || options.executorConfig?.featureFlags !== void 0) reactorBuilder.withExecutorConfig({
|
|
930
|
+
...options.executorConfig.maxSkipThreshold !== void 0 ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold } : {},
|
|
931
|
+
...options.executorConfig.featureFlags !== void 0 ? { featureFlags: options.executorConfig.featureFlags } : {}
|
|
932
|
+
});
|
|
933
|
+
if (options.documentModelLoader) reactorBuilder.withDocumentModelLoader(options.documentModelLoader);
|
|
934
|
+
if (options.logger) reactorBuilder.withLogger(options.logger);
|
|
935
|
+
if (options.signer) {
|
|
936
|
+
clientBuilder.withSigner(options.signer);
|
|
937
|
+
reactorBuilder.withSigner(options.signer.signer, options.signer.workerSigner);
|
|
938
|
+
}
|
|
939
|
+
if (options.createSignaturePolicy) clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);
|
|
940
|
+
const trust = options.trustPolicy ?? options.signer;
|
|
941
|
+
if (trust?.trustPolicy) reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);
|
|
942
|
+
}
|
|
943
|
+
//#endregion
|
|
944
|
+
//#region src/plugins/attachments.mts
|
|
945
|
+
/** No entry config: presence is the whole activation. A typo'd config key
|
|
946
|
+
* fails at resolution instead of being silently ignored. */
|
|
947
|
+
const attachmentsPluginConfigSchema = z.strictObject({});
|
|
948
|
+
/**
|
|
949
|
+
* R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
|
|
950
|
+
* routes mount at onHttpMounting and the remote attachment service is created
|
|
951
|
+
* for the returned handle. Presence is activation — removed from the
|
|
952
|
+
* composition, the routes and service do not exist. NOT yet carved: the
|
|
953
|
+
* attachment-reference read model registered inside reactor construction
|
|
954
|
+
* (carve map: server.mts initializeClient) — it follows with the
|
|
955
|
+
* onReadModelsRegistering step in R2 step 2; until then it registers on both
|
|
956
|
+
* paths (a dormant read model when the plugin is absent, harmless).
|
|
957
|
+
*
|
|
958
|
+
* Inputs (carve map): api (routes), config.attachments (signing, TTL),
|
|
959
|
+
* options.attachmentServiceUrl / https + serverPort + renown (service config).
|
|
960
|
+
*/
|
|
961
|
+
const attachmentsPlugin = {
|
|
962
|
+
name: "switchboard-attachments",
|
|
963
|
+
appliesTo: "switchboard",
|
|
964
|
+
configSchema: attachmentsPluginConfigSchema,
|
|
965
|
+
hooks: { onHttpMounting: (ctx) => {
|
|
966
|
+
registerAttachmentRoutes(ctx.api, { config: ctx.config?.attachments });
|
|
967
|
+
ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
|
|
968
|
+
} }
|
|
969
|
+
};
|
|
970
|
+
//#endregion
|
|
971
|
+
//#region src/plugin-host.mts
|
|
972
|
+
/** Built-in plugins, pre-listed (the default composition until host.js
|
|
973
|
+
* entries map in R2 step 2). Subsystems join as R2 carves them. */
|
|
974
|
+
function builtinSwitchboardPlugins() {
|
|
975
|
+
const entry = {
|
|
976
|
+
enabled: true,
|
|
977
|
+
verbs: "*",
|
|
978
|
+
config: {}
|
|
979
|
+
};
|
|
980
|
+
return [
|
|
981
|
+
{
|
|
982
|
+
plugin: mcpPlugin,
|
|
983
|
+
provenance: "built-in",
|
|
984
|
+
entry: {
|
|
985
|
+
...entry,
|
|
986
|
+
module: "@powerhousedao/switchboard/plugins/mcp"
|
|
987
|
+
}
|
|
988
|
+
},
|
|
989
|
+
{
|
|
990
|
+
plugin: attachmentsPlugin,
|
|
991
|
+
provenance: "built-in",
|
|
992
|
+
entry: {
|
|
993
|
+
...entry,
|
|
994
|
+
module: "@powerhousedao/switchboard/plugins/attachments"
|
|
995
|
+
}
|
|
996
|
+
},
|
|
997
|
+
{
|
|
998
|
+
plugin: privacyPlugin,
|
|
999
|
+
provenance: "built-in",
|
|
1000
|
+
entry: {
|
|
1001
|
+
...entry,
|
|
1002
|
+
module: "@powerhousedao/switchboard/plugins/privacy"
|
|
1003
|
+
}
|
|
1004
|
+
},
|
|
1005
|
+
{
|
|
1006
|
+
plugin: workflowsPlugin,
|
|
1007
|
+
provenance: "built-in",
|
|
1008
|
+
entry: {
|
|
1009
|
+
...entry,
|
|
1010
|
+
module: "@powerhousedao/switchboard/plugins/workflows"
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
];
|
|
1014
|
+
}
|
|
1015
|
+
function createSwitchboardPluginHost(ctx, resolved) {
|
|
1016
|
+
resolved ??= builtinSwitchboardPlugins();
|
|
1017
|
+
const ordered = resolveOrder(resolved.map((r) => r.plugin));
|
|
1018
|
+
const contributions = mergeContributions(resolved.map((r) => ({
|
|
1019
|
+
plugin: r.plugin,
|
|
1020
|
+
provenance: r.provenance
|
|
1021
|
+
})));
|
|
1022
|
+
const fullCtx = {
|
|
1023
|
+
...ctx,
|
|
1024
|
+
contributions
|
|
1025
|
+
};
|
|
1026
|
+
const LOG = "[switchboard:plugins]";
|
|
1027
|
+
console.log(`${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(", ") || "(none)"}`);
|
|
1028
|
+
for (const r of resolved) {
|
|
1029
|
+
const cfg = Object.keys(r.entry.config ?? {});
|
|
1030
|
+
console.log(`${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` + (cfg.length ? ` config: {${cfg.join(", ")}}` : ""));
|
|
1031
|
+
}
|
|
1032
|
+
const ranBy = (hook) => ordered.filter((p) => p.hooks?.[hook]);
|
|
1033
|
+
const logHook = (hook) => {
|
|
1034
|
+
const names = ranBy(hook).map((p) => p.name);
|
|
1035
|
+
console.log(`${LOG} hook ${hook} → ${names.length ? names.join(", ") : "(no implementers)"}`);
|
|
1036
|
+
};
|
|
1037
|
+
return {
|
|
1038
|
+
plugins: ordered,
|
|
1039
|
+
ctx: fullCtx,
|
|
1040
|
+
transformOptions: (seed) => {
|
|
1041
|
+
logHook("transformServerOptions");
|
|
1042
|
+
return runTransformHook("transformServerOptions", ordered, fullCtx, seed);
|
|
1043
|
+
},
|
|
1044
|
+
observe: (hook) => {
|
|
1045
|
+
logHook(hook);
|
|
1046
|
+
return hook === "onShutdown" ? runObserveHookSequential(hook, ordered, fullCtx) : runObserveHook(hook, ordered, fullCtx);
|
|
1047
|
+
}
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
//#endregion
|
|
1051
|
+
//#region src/pglite-dialect.ts
|
|
1052
|
+
/** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
|
|
1053
|
+
function reactorPgliteDialectOptions(logger, proc) {
|
|
1054
|
+
return {
|
|
1055
|
+
onDiagnostic: (message, error) => logger.error(`[pglite-dialect] ${message}: @error`, error),
|
|
1056
|
+
onPoisoned: (cause) => {
|
|
1057
|
+
if (!triggerFatalShutdown("PGlite session poisoned", cause, proc)) logger.error("PGlite session poisoned: @error", cause);
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
var ClosablePGliteDialect = class {
|
|
1062
|
+
#inner;
|
|
1063
|
+
#pglite;
|
|
1064
|
+
constructor(pglite, options = {}) {
|
|
1065
|
+
this.#pglite = pglite;
|
|
1066
|
+
this.#inner = new HardenedPGliteDialect(pglite, options);
|
|
1067
|
+
}
|
|
1068
|
+
createAdapter() {
|
|
1069
|
+
return this.#inner.createAdapter();
|
|
1070
|
+
}
|
|
1071
|
+
createDriver() {
|
|
1072
|
+
const driver = this.#inner.createDriver();
|
|
1073
|
+
const pglite = this.#pglite;
|
|
1074
|
+
const innerDestroy = driver.destroy.bind(driver);
|
|
1075
|
+
driver.destroy = async () => {
|
|
1076
|
+
await innerDestroy();
|
|
1077
|
+
if (pglite.closed) return;
|
|
1078
|
+
try {
|
|
1079
|
+
await pglite.close();
|
|
1080
|
+
} catch (err) {
|
|
1081
|
+
if (!/PGlite aborted/.test(String(err))) throw err;
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
return driver;
|
|
1085
|
+
}
|
|
1086
|
+
createQueryCompiler() {
|
|
1087
|
+
return this.#inner.createQueryCompiler();
|
|
1088
|
+
}
|
|
1089
|
+
createIntrospector(db) {
|
|
1090
|
+
return this.#inner.createIntrospector(db);
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
//#endregion
|
|
1094
|
+
//#region src/pglite-migration.ts
|
|
1095
|
+
function backupPath(dataDir, major) {
|
|
1096
|
+
return `${dataDir}.backup-pg${major}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
|
|
1097
|
+
}
|
|
1098
|
+
async function pathExists(p) {
|
|
1099
|
+
try {
|
|
1100
|
+
await promises.stat(p);
|
|
1101
|
+
return true;
|
|
1102
|
+
} catch {
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
function logRestoreFailure(dataDir, sql, err, logger) {
|
|
1107
|
+
const errObj = err;
|
|
1108
|
+
const position = typeof errObj.position === "string" ? parseInt(errObj.position, 10) : typeof errObj.position === "number" ? errObj.position : NaN;
|
|
1109
|
+
logger.error(`[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? ""} severity=${errObj.severity ?? ""} message=${errObj.message ?? ""} sqlLength=${sql.length}`);
|
|
1110
|
+
if (Number.isFinite(position) && position > 0) {
|
|
1111
|
+
const zeroBased = position - 1;
|
|
1112
|
+
const start = Math.max(0, zeroBased - 200);
|
|
1113
|
+
const end = Math.min(sql.length, zeroBased + 200);
|
|
1114
|
+
const before = sql.slice(start, zeroBased);
|
|
1115
|
+
const at = sql.slice(zeroBased, zeroBased + 1);
|
|
1116
|
+
const after = sql.slice(zeroBased + 1, end);
|
|
1117
|
+
logger.error(`[pglite-migration] SQL context around position ${position}:\n${before}»${at}«${after}`);
|
|
1118
|
+
} else logger.error(`[pglite-migration] No position info. First 2000 chars of dump:\n${sql.slice(0, 2e3)}`);
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Migrate a filesystem PGLite data directory from a legacy PG major to the
|
|
1122
|
+
* current one. Renames the existing dir to a timestamped backup, dumps via the
|
|
1123
|
+
* matching legacy `pg_dump`, restores into a fresh current-version PGLite at
|
|
1124
|
+
* the original path. On failure, the original dir is restored from the backup.
|
|
1125
|
+
*
|
|
1126
|
+
* No-op when the dir is missing or already at the current major.
|
|
1127
|
+
*/
|
|
1128
|
+
async function migratePgliteDir(dataDir, logger) {
|
|
1129
|
+
const major = await readPgVersionFile(dataDir);
|
|
1130
|
+
if (major === null) {
|
|
1131
|
+
logger.info(`[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`);
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
if (major === 17) return;
|
|
1135
|
+
if (!isSupportedMajor(major)) throw new Error(`Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`);
|
|
1136
|
+
const backupDir = backupPath(dataDir, major);
|
|
1137
|
+
logger.info(`[pglite-migration] Migrating ${dataDir} from PG${major} to PG17; backup: ${backupDir}`);
|
|
1138
|
+
await promises.rename(dataDir, backupDir);
|
|
1139
|
+
let sql;
|
|
1140
|
+
try {
|
|
1141
|
+
const [legacyMod, pgDump] = await Promise.all([loadPGliteModule(major), loadPgDump(major)]);
|
|
1142
|
+
const LegacyPGlite = legacyMod.PGlite;
|
|
1143
|
+
const onDisk = new LegacyPGlite(backupDir);
|
|
1144
|
+
let tar;
|
|
1145
|
+
try {
|
|
1146
|
+
await onDisk.waitReady;
|
|
1147
|
+
tar = await onDisk.dumpDataDir("none");
|
|
1148
|
+
} finally {
|
|
1149
|
+
await onDisk.close();
|
|
1150
|
+
}
|
|
1151
|
+
const pg = new LegacyPGlite({ loadDataDir: tar });
|
|
1152
|
+
try {
|
|
1153
|
+
await pg.waitReady;
|
|
1154
|
+
sql = await (await pgDump({ pg })).text();
|
|
1155
|
+
} finally {
|
|
1156
|
+
await pg.close();
|
|
1157
|
+
}
|
|
1158
|
+
} catch (err) {
|
|
1159
|
+
await rollback(dataDir, backupDir, err, logger);
|
|
1160
|
+
throw err;
|
|
1161
|
+
}
|
|
1162
|
+
try {
|
|
1163
|
+
const CurrentPGlite = (await loadPGliteModule(17)).PGlite;
|
|
1164
|
+
const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });
|
|
1165
|
+
try {
|
|
1166
|
+
await pg.waitReady;
|
|
1167
|
+
try {
|
|
1168
|
+
await pg.exec("SET standard_conforming_strings = off;");
|
|
1169
|
+
} catch (gucErr) {
|
|
1170
|
+
logger.warn(`[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`);
|
|
1171
|
+
}
|
|
1172
|
+
try {
|
|
1173
|
+
await pg.exec(sql);
|
|
1174
|
+
} catch (execErr) {
|
|
1175
|
+
logRestoreFailure(dataDir, sql, execErr, logger);
|
|
1176
|
+
throw execErr;
|
|
1177
|
+
}
|
|
1178
|
+
} finally {
|
|
1179
|
+
await pg.close();
|
|
1180
|
+
}
|
|
1181
|
+
syncTree(dataDir);
|
|
1182
|
+
} catch (err) {
|
|
1183
|
+
await rollback(dataDir, backupDir, err, logger);
|
|
1184
|
+
throw err;
|
|
1185
|
+
}
|
|
1186
|
+
logger.info(`[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`);
|
|
1187
|
+
}
|
|
1188
|
+
async function rollback(dataDir, backupDir, originalError, logger) {
|
|
1189
|
+
try {
|
|
1190
|
+
if (await pathExists(dataDir)) await promises.rm(dataDir, {
|
|
1191
|
+
recursive: true,
|
|
1192
|
+
force: true
|
|
1193
|
+
});
|
|
1194
|
+
if (await pathExists(backupDir)) await promises.rename(backupDir, dataDir);
|
|
1195
|
+
} catch (rollbackErr) {
|
|
1196
|
+
logger.error(`[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`);
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
logger.error(`[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`);
|
|
1200
|
+
}
|
|
1201
|
+
//#endregion
|
|
1202
|
+
//#region src/pglite-preflight.ts
|
|
1203
|
+
const RM_OPTIONS = {
|
|
1204
|
+
recursive: true,
|
|
1205
|
+
force: true,
|
|
1206
|
+
maxRetries: 10,
|
|
1207
|
+
retryDelay: 100
|
|
1208
|
+
};
|
|
1209
|
+
/**
|
|
1210
|
+
* Prepares every local PGlite dir before the first open and returns the
|
|
1211
|
+
* PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot
|
|
1212
|
+
* runs for every dir, before the major is read, so a pure-snapshot PG16 dir
|
|
1213
|
+
* is converted and then migrated.
|
|
1214
|
+
*/
|
|
1215
|
+
async function runPglitePreflight(options) {
|
|
1216
|
+
const { dirs, logger } = options;
|
|
1217
|
+
const detectedMajors = /* @__PURE__ */ new Map();
|
|
1218
|
+
if (options.inMemory || dirs.length === 0) return detectedMajors;
|
|
1219
|
+
if (options.forcePgVersion !== void 0) {
|
|
1220
|
+
if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
|
|
1221
|
+
logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
|
|
1222
|
+
for (const dir of dirs) {
|
|
1223
|
+
for (const p of [
|
|
1224
|
+
dir,
|
|
1225
|
+
`${dir}.converting`,
|
|
1226
|
+
`${dir}.old`
|
|
1227
|
+
]) await promises.rm(p, RM_OPTIONS);
|
|
1228
|
+
logger.info(`Wiped PGLite data dir ${dir}`);
|
|
1229
|
+
}
|
|
1230
|
+
return detectedMajors;
|
|
1231
|
+
}
|
|
1232
|
+
const deps = {
|
|
1233
|
+
openForVerify: options.openForVerify ?? openForVerify,
|
|
1234
|
+
logger
|
|
1235
|
+
};
|
|
1236
|
+
for (const dir of dirs) {
|
|
1237
|
+
await preparePgliteDataDir(dir, deps);
|
|
1238
|
+
const major = await readPgVersionFile(dir);
|
|
1239
|
+
if (major !== null) detectedMajors.set(dir, major);
|
|
1240
|
+
}
|
|
1241
|
+
if (options.migratePglite) for (const [dir, major] of detectedMajors) {
|
|
1242
|
+
if (major === 17) continue;
|
|
1243
|
+
await migratePgliteDir(dir, logger);
|
|
1244
|
+
await removeStalePgliteFiles(dir, logger);
|
|
1245
|
+
const after = await readPgVersionFile(dir);
|
|
1246
|
+
if (after !== null) detectedMajors.set(dir, after);
|
|
1247
|
+
}
|
|
1248
|
+
else for (const [dir, major] of detectedMajors) {
|
|
1249
|
+
if (major === 17) continue;
|
|
1250
|
+
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.`);
|
|
1251
|
+
}
|
|
1252
|
+
return detectedMajors;
|
|
1253
|
+
}
|
|
1254
|
+
//#endregion
|
|
1255
|
+
//#region src/pglite-store.mts
|
|
1256
|
+
function onPgliteAbort(logger, what, proc) {
|
|
1257
|
+
if (!triggerFatalShutdown("PGlite aborted", what, proc)) logger.error("PGlite aborted: @error", what);
|
|
1258
|
+
}
|
|
1259
|
+
/** A store's worker thread died: every later query would fail, so the process shuts down. */
|
|
1260
|
+
function onPgliteWorkerExit(logger, error, proc) {
|
|
1261
|
+
if (!triggerFatalShutdown("PGlite worker exited", error, proc)) logger.error("PGlite worker exited: @error", error);
|
|
1262
|
+
}
|
|
1263
|
+
/** Sends a worker's abort and its unexpected exit to the fatal shutdown. */
|
|
1264
|
+
function routePgliteWorkerFailures(store, logger, proc) {
|
|
1265
|
+
store.onAbort((reason) => onPgliteAbort(logger, reason, proc));
|
|
1266
|
+
store.onExit((error) => {
|
|
1267
|
+
if (error !== null) onPgliteWorkerExit(logger, error, proc);
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
/**
|
|
1271
|
+
* Adds a terminate of the store's worker to the dialect's `onPoisoned`: a
|
|
1272
|
+
* statement that never settled holds the worker's only connection, and the
|
|
1273
|
+
* fatal shutdown's close would otherwise queue behind it until its grace ran
|
|
1274
|
+
* out.
|
|
1275
|
+
*/
|
|
1276
|
+
function terminateOnPoisoned(options, store) {
|
|
1277
|
+
const reportPoisoned = options.onPoisoned;
|
|
1278
|
+
return {
|
|
1279
|
+
...options,
|
|
1280
|
+
onPoisoned: (cause) => {
|
|
1281
|
+
reportPoisoned?.(cause);
|
|
1282
|
+
store.terminate();
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
function pgliteFsyncFor(wanted, major, dir, logger) {
|
|
1287
|
+
if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
|
|
1288
|
+
return wanted;
|
|
1289
|
+
}
|
|
1290
|
+
/** The VACUUM FULL settings a config asks for, with the env parser's rules. */
|
|
1291
|
+
function vacuumFullTimingOf(vacuumFull) {
|
|
1292
|
+
return resolvePgliteMaintenance({
|
|
1293
|
+
PH_PGLITE_VACUUM_FULL: vacuumFull.mode,
|
|
1294
|
+
PH_PGLITE_VACUUM_FULL_ABOVE_MB: vacuumFull.aboveMb?.toString(),
|
|
1295
|
+
PH_PGLITE_VACUUM_FULL_QUIET_MS: vacuumFull.quietMs?.toString(),
|
|
1296
|
+
PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS: vacuumFull.maxDeferMs?.toString()
|
|
1297
|
+
});
|
|
1298
|
+
}
|
|
1299
|
+
const DEFAULT_MAINTENANCE = { vacuumFullAboveBytes: 0 };
|
|
1300
|
+
/** Preloads the module's NodeFS so the returned factory can be synchronous. */
|
|
1301
|
+
async function loadDurableFsFactory(major, logger, proc, settings = {}) {
|
|
1302
|
+
const NodeFS = await loadNodeFsClass(major);
|
|
1303
|
+
const timing = settings.maintenance ?? DEFAULT_MAINTENANCE;
|
|
1304
|
+
return (dir) => createDurableNodeFs(NodeFS, dir, {
|
|
1305
|
+
fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
|
|
1306
|
+
...timing,
|
|
1307
|
+
logger,
|
|
1308
|
+
onAbort: (what) => onPgliteAbort(logger, what, proc)
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* The factory for one PGlite store: in a worker thread when `threaded` (and a
|
|
1313
|
+
* worker script exists here), else in the main thread as before. Either way
|
|
1314
|
+
* the store runs DurableNodeFs over its dir with the same fsync choice, and a
|
|
1315
|
+
* wasm abort takes the fatal shutdown.
|
|
1316
|
+
*/
|
|
1317
|
+
async function createPgliteStoreFactory(options) {
|
|
1318
|
+
if (options.threaded) {
|
|
1319
|
+
if (pgliteWorkerEntryPath !== null) return threadedStoreFactory(options);
|
|
1320
|
+
options.logger.warn(`${options.label}: no PGlite worker script is available (unbuilt @powerhousedao/reactor-api); PGlite runs in the main thread`);
|
|
1321
|
+
}
|
|
1322
|
+
return mainThreadStoreFactory(options);
|
|
1323
|
+
}
|
|
1324
|
+
function threadedStoreFactory(options) {
|
|
1325
|
+
const { label, major, parsers, inMemory, logger, proc } = options;
|
|
1326
|
+
const settings = options.settings ?? {};
|
|
1327
|
+
const memoryLimitMb = settings.workerMemoryMb ?? DEFAULT_PGLITE_WORKER_MEMORY_MB;
|
|
1328
|
+
const module = pgliteModuleSpec(major);
|
|
1329
|
+
return (dir) => {
|
|
1330
|
+
const store = new ThreadedPGlite({
|
|
1331
|
+
store: {
|
|
1332
|
+
label,
|
|
1333
|
+
dataDir: inMemory ? null : dir,
|
|
1334
|
+
module,
|
|
1335
|
+
durableFs: inMemory ? null : {
|
|
1336
|
+
fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
|
|
1337
|
+
...settings.maintenance ?? DEFAULT_MAINTENANCE
|
|
1338
|
+
},
|
|
1339
|
+
parsers
|
|
1340
|
+
},
|
|
1341
|
+
memoryLimitMb,
|
|
1342
|
+
logger
|
|
1343
|
+
});
|
|
1344
|
+
routePgliteWorkerFailures(store, logger, proc);
|
|
1345
|
+
logger.info(`${label}: PGlite (PG${major}) in a worker thread (memory limit ${memoryLimitMb} MB)${where(inMemory, dir)}`);
|
|
1346
|
+
const opening = startProgressHeartbeat({
|
|
1347
|
+
logger,
|
|
1348
|
+
label: `${label}: opening the store`
|
|
1349
|
+
});
|
|
1350
|
+
store.waitReady.then(() => opening.stop(), () => opening.stop("failed"));
|
|
1351
|
+
return store;
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
async function mainThreadStoreFactory(options) {
|
|
1355
|
+
const { label, major, inMemory, logger, proc } = options;
|
|
1356
|
+
const { PGlite } = await loadPGliteModule(major);
|
|
1357
|
+
const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc, options.settings);
|
|
1358
|
+
const base = options.parsers === "utc-timestamps" ? { parsers: PGLITE_UTC_PARSERS } : {};
|
|
1359
|
+
return (dir) => {
|
|
1360
|
+
logger.info(`${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`);
|
|
1361
|
+
return durableFs === null ? new PGlite(base) : new PGlite({
|
|
1362
|
+
...base,
|
|
1363
|
+
fs: durableFs(dir)
|
|
1364
|
+
});
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
function where(inMemory, dir) {
|
|
1368
|
+
return inMemory ? ", in memory [PH_PGLITE_IN_MEMORY=1]" : ` at ${dir}`;
|
|
1369
|
+
}
|
|
1370
|
+
//#endregion
|
|
1371
|
+
//#region src/create-signature-policy.mts
|
|
1372
|
+
/** The requested policy, or legacy when it needs a signer this switchboard lacks. */
|
|
1373
|
+
function createSignaturePolicyFor(policy, options) {
|
|
1374
|
+
if (policy === "v2-required" && !options.hasSigner) {
|
|
1375
|
+
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.");
|
|
1376
|
+
return "legacy";
|
|
1377
|
+
}
|
|
1378
|
+
return policy;
|
|
1379
|
+
}
|
|
1380
|
+
//#endregion
|
|
1381
|
+
//#region src/renown.ts
|
|
1382
|
+
const logger = childLogger(["switchboard", "renown"]);
|
|
1383
|
+
/**
|
|
1384
|
+
* Initialize Renown for the Switchboard instance.
|
|
1385
|
+
* This allows Switchboard to authenticate with remote services
|
|
1386
|
+
* using the same identity established during `ph login`.
|
|
1387
|
+
*/
|
|
1388
|
+
async function initRenown(options = {}) {
|
|
1389
|
+
const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL, userDataDir, storagePath = userDataDir ? join(resolvePhDir(void 0, { PH_USER_DATA_DIR: userDataDir }), ".renown.json") : void 0 } = options;
|
|
1390
|
+
const keyStorage = new NodeKeyStorage(keypairPath, { logger });
|
|
1391
|
+
const existingKeyPair = await keyStorage.loadKeyPair();
|
|
1392
|
+
if (!existingKeyPair && requireExisting) throw new Error("No existing keypair found and requireExisting is true. Run \"ph login\" to create one.");
|
|
1393
|
+
if (!existingKeyPair) logger.info("No existing keypair found. A new one will be generated.");
|
|
1394
|
+
const renownCrypto = await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();
|
|
1395
|
+
const renown = await new RenownBuilder("switchboard", {
|
|
1396
|
+
...storagePath ? { storagePath } : {},
|
|
1397
|
+
...keypairPath ? { keyPath: keypairPath } : {}
|
|
1398
|
+
}).withCrypto(renownCrypto).withBaseUrl(baseUrl).build();
|
|
1399
|
+
logger.info("Switchboard identity initialized: @did", renownCrypto.did);
|
|
1400
|
+
return renown;
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Get the signer config for the given renown instance.
|
|
1404
|
+
*
|
|
1405
|
+
* @param renown - The renown instance
|
|
1406
|
+
* @param keypairPath - Where `initRenown` loaded the key from
|
|
1407
|
+
*/
|
|
1408
|
+
function getRenownSignerConfig(renown, keypairPath) {
|
|
1409
|
+
return {
|
|
1410
|
+
signer: renown.signer,
|
|
1411
|
+
workerSigner: getRenownWorkerSignerSpec(renown, keypairPath)
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* What a pooled executor worker imports to sign as this switchboard: it
|
|
1416
|
+
* reloads the key `initRenown` stored, and takes the user known at boot.
|
|
1417
|
+
*/
|
|
1418
|
+
function getRenownWorkerSignerSpec(renown, keypairPath) {
|
|
1419
|
+
const { signer } = renown;
|
|
1420
|
+
const user = signer.user;
|
|
1421
|
+
return {
|
|
1422
|
+
module: {
|
|
1423
|
+
filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
|
|
1424
|
+
exportName: "createNodeRenownSigner"
|
|
1425
|
+
},
|
|
1426
|
+
initArgs: {
|
|
1427
|
+
appName: signer.app?.name ?? "switchboard",
|
|
1428
|
+
keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),
|
|
1429
|
+
...signer.app?.key ? { did: signer.app.key } : {},
|
|
1430
|
+
...user ? { user: {
|
|
1431
|
+
address: user.address,
|
|
1432
|
+
networkId: user.networkId,
|
|
1433
|
+
chainId: user.chainId
|
|
1434
|
+
} } : {}
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Admits a key as a signer for an address a Renown credential binds it to; a
|
|
1440
|
+
* `self` source has no worker spec. In process, the switchboard's own key is
|
|
1441
|
+
* matched against its current user; the worker spec carries the user known now.
|
|
1442
|
+
*/
|
|
1443
|
+
async function getRenownTrustPolicyConfig(trustSource, renown) {
|
|
1444
|
+
const ownSigner = renown?.signer;
|
|
1445
|
+
if (trustSource.source === "self") return { trustPolicy: createRenownTrustPolicy({
|
|
1446
|
+
switchboard: trustSource.request,
|
|
1447
|
+
ownSigner
|
|
1448
|
+
}) };
|
|
1449
|
+
const switchboardUrl = await resolveSwitchboardEndpoint({
|
|
1450
|
+
switchboardUrl: trustSource.switchboardUrl,
|
|
1451
|
+
baseUrl: trustSource.renownUrl
|
|
1452
|
+
});
|
|
1453
|
+
const options = {
|
|
1454
|
+
...switchboardUrl ? { switchboard: switchboardUrl } : {},
|
|
1455
|
+
...trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}
|
|
1456
|
+
};
|
|
1457
|
+
const self = ownIdentity(renown);
|
|
1458
|
+
return {
|
|
1459
|
+
trustPolicy: createRenownTrustPolicy({
|
|
1460
|
+
...options,
|
|
1461
|
+
ownSigner
|
|
1462
|
+
}),
|
|
1463
|
+
workerTrustPolicy: {
|
|
1464
|
+
module: {
|
|
1465
|
+
filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
|
|
1466
|
+
exportName: "createRenownTrustPolicy"
|
|
1467
|
+
},
|
|
1468
|
+
initArgs: {
|
|
1469
|
+
...options,
|
|
1470
|
+
...self ? { self } : {}
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
function ownIdentity(renown) {
|
|
1476
|
+
const key = renown?.signer.app?.key;
|
|
1477
|
+
if (!key) return;
|
|
1478
|
+
const user = renown.signer.user;
|
|
1479
|
+
return {
|
|
1480
|
+
key,
|
|
1481
|
+
user: {
|
|
1482
|
+
address: user?.address ?? "",
|
|
1483
|
+
networkId: user?.networkId ?? "",
|
|
1484
|
+
chainId: user?.chainId ?? 0
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
//#endregion
|
|
1489
|
+
//#region src/store-lock.mts
|
|
1490
|
+
var StoreInUseError = class extends Error {
|
|
1491
|
+
dir;
|
|
1492
|
+
owner;
|
|
1493
|
+
constructor(dir, owner) {
|
|
1494
|
+
super(`The PGlite store ${dir} is in use by another process (pid ${owner.pid}, since ${owner.startedAt}: ${owner.command}). Two processes on one PGlite store corrupt it. Stop that process first, or point this one at a different store.`);
|
|
1495
|
+
this.dir = dir;
|
|
1496
|
+
this.owner = owner;
|
|
1497
|
+
this.name = "StoreInUseError";
|
|
1498
|
+
}
|
|
1499
|
+
};
|
|
1500
|
+
const lockPathOf = (dir) => `${path.resolve(dir)}.lock`;
|
|
1501
|
+
function isAlive(pid) {
|
|
1502
|
+
try {
|
|
1503
|
+
process.kill(pid, 0);
|
|
1504
|
+
return true;
|
|
1505
|
+
} catch (error) {
|
|
1506
|
+
return error.code === "EPERM";
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
function readOwner(file) {
|
|
1510
|
+
try {
|
|
1511
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1512
|
+
} catch {
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
const held = /* @__PURE__ */ new Set();
|
|
1517
|
+
let exitHookInstalled = false;
|
|
1518
|
+
function releaseAll() {
|
|
1519
|
+
for (const file of held) if (readOwner(file)?.pid === process.pid) try {
|
|
1520
|
+
fs.rmSync(file);
|
|
1521
|
+
} catch {}
|
|
1522
|
+
held.clear();
|
|
1523
|
+
}
|
|
1524
|
+
/** Take the lock for each store dir, or throw StoreInUseError naming the
|
|
1525
|
+
* live owner. Idempotent within one process. */
|
|
1526
|
+
function acquireStoreLocks(dirs, isPidAlive = isAlive) {
|
|
1527
|
+
const mine = {
|
|
1528
|
+
pid: process.pid,
|
|
1529
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1530
|
+
command: process.argv.slice(1).join(" ").slice(0, 200)
|
|
1531
|
+
};
|
|
1532
|
+
for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {
|
|
1533
|
+
const file = lockPathOf(dir);
|
|
1534
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1535
|
+
const owner = readOwner(file);
|
|
1536
|
+
if (owner && owner.pid !== process.pid && isPidAlive(owner.pid)) throw new StoreInUseError(dir, owner);
|
|
1537
|
+
fs.writeFileSync(file, `${JSON.stringify(mine)}\n`);
|
|
1538
|
+
held.add(file);
|
|
1539
|
+
}
|
|
1540
|
+
if (!exitHookInstalled) {
|
|
1541
|
+
exitHookInstalled = true;
|
|
1542
|
+
process.on("exit", releaseAll);
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
//#endregion
|
|
1546
|
+
//#region src/server.mts
|
|
1547
|
+
const defaultLogger = childLogger(["switchboard"]);
|
|
1548
|
+
if (!isDotenvDisabled()) dotenv.config();
|
|
1549
|
+
/** Process-wide settings an edge applies once, before its first `startSwitchboard`. */
|
|
1550
|
+
function initSwitchboardProcess(options = {}) {
|
|
1551
|
+
setLogLevel(options.logLevel ?? "info");
|
|
1552
|
+
}
|
|
1553
|
+
let httpsHooksRegistered = false;
|
|
1554
|
+
function registerHttpsHooks() {
|
|
1555
|
+
if (httpsHooksRegistered) return;
|
|
1556
|
+
httpsHooksRegistered = true;
|
|
1557
|
+
register(httpsHooksPath, import.meta.url);
|
|
1558
|
+
}
|
|
1559
|
+
const PORT_FALLBACK_ATTEMPTS = 20;
|
|
1560
|
+
let flushIntervalWarned = false;
|
|
1561
|
+
function warnIgnoredFlushInterval(logger) {
|
|
1562
|
+
if (flushIntervalWarned) return;
|
|
1563
|
+
if (process.env.PGLITE_FLUSH_INTERVAL_MS === void 0) return;
|
|
1564
|
+
flushIntervalWarned = true;
|
|
1565
|
+
logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Attempt to bind a throwaway TCP server to the given port. Resolves true if
|
|
1569
|
+
* the port is free, false if the OS reports it in use. Any other error is
|
|
1570
|
+
* surfaced so we don't silently mask real issues (permissions, bad host, …).
|
|
1571
|
+
*/
|
|
1572
|
+
async function isPortAvailable(port) {
|
|
1573
|
+
try {
|
|
1574
|
+
return await probePort(port, "::");
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
if (!isNoIpv6Error(error)) throw portProbeError(port, error);
|
|
1577
|
+
try {
|
|
1578
|
+
return await probePort(port, "0.0.0.0");
|
|
1579
|
+
} catch (ipv4Error) {
|
|
1580
|
+
throw portProbeError(port, ipv4Error);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
const isNoIpv6Error = (error) => ["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(error.code ?? "");
|
|
1585
|
+
const portProbeError = (port, error) => new Error(`Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1586
|
+
function probePort(port, host) {
|
|
1587
|
+
return new Promise((resolve, reject) => {
|
|
1588
|
+
const tester = net.createServer();
|
|
1589
|
+
tester.once("error", (err) => {
|
|
1590
|
+
if (err.code === "EADDRINUSE" || err.code === "EACCES") resolve(false);
|
|
1591
|
+
else reject(err);
|
|
1592
|
+
});
|
|
1593
|
+
tester.once("listening", () => {
|
|
1594
|
+
tester.close(() => resolve(true));
|
|
1595
|
+
});
|
|
1596
|
+
tester.listen({
|
|
1597
|
+
port,
|
|
1598
|
+
host
|
|
1599
|
+
});
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
/** The powerhouse.config.json this run reads, defaulting to the cwd copy. */
|
|
1603
|
+
function resolveConfigPath(configFile) {
|
|
1604
|
+
return configFile ?? path$1.join(process.cwd(), "powerhouse.config.json");
|
|
1605
|
+
}
|
|
1606
|
+
/**
|
|
1607
|
+
* The config file's `workflows.oauthApps`, client file paths made absolute
|
|
1608
|
+
* from the config file's folder. An unreadable file or a malformed entry
|
|
1609
|
+
* means none: a missing app is reported when a sign-in asks for it.
|
|
1610
|
+
*/
|
|
1611
|
+
function readConfigOAuthApps(configPath) {
|
|
1612
|
+
let raw;
|
|
1613
|
+
try {
|
|
1614
|
+
raw = getConfig(configPath).workflows?.oauthApps;
|
|
1615
|
+
} catch {
|
|
1616
|
+
return [];
|
|
1617
|
+
}
|
|
1618
|
+
if (!Array.isArray(raw)) return [];
|
|
1619
|
+
const dir = path$1.dirname(path$1.resolve(configPath));
|
|
1620
|
+
const at = (p) => typeof p === "string" && p ? path$1.resolve(dir, p) : void 0;
|
|
1621
|
+
return raw.flatMap((entry) => {
|
|
1622
|
+
const app = entry ?? {};
|
|
1623
|
+
if (typeof app.id !== "string" || !app.id) return [];
|
|
1624
|
+
const desktop = at(app.clients?.desktop);
|
|
1625
|
+
const web = at(app.clients?.web);
|
|
1626
|
+
return [{
|
|
1627
|
+
id: app.id,
|
|
1628
|
+
clients: {
|
|
1629
|
+
...desktop ? { desktop } : {},
|
|
1630
|
+
...web ? { web } : {}
|
|
1631
|
+
}
|
|
1632
|
+
}];
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
function readConfigWorkflowsEnabled(configPath) {
|
|
1636
|
+
try {
|
|
1637
|
+
return getConfig(configPath).workflows?.enabled ?? false;
|
|
1638
|
+
} catch {
|
|
1639
|
+
return false;
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
async function resolveServerPort(requested, strictPort, logger) {
|
|
1643
|
+
if (requested === 0 || strictPort) return requested;
|
|
1644
|
+
for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
|
|
1645
|
+
const candidate = requested + i;
|
|
1646
|
+
if (await isPortAvailable(candidate)) {
|
|
1647
|
+
if (candidate !== requested) logger.info(`Port ${requested} is in use. Falling back to port ${candidate}.`);
|
|
1648
|
+
return candidate;
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
return requested;
|
|
1652
|
+
}
|
|
1653
|
+
async function createReactorKysely(opts) {
|
|
1654
|
+
const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, pgliteSettings, logger } = opts;
|
|
1655
|
+
if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
|
|
1656
|
+
const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
|
|
1657
|
+
const poolSize = hostPoolSize();
|
|
1658
|
+
const pool = new Pool({
|
|
1659
|
+
connectionString,
|
|
1660
|
+
max: poolSize
|
|
1661
|
+
});
|
|
1662
|
+
const poolInstrumentation = instrumentPgPool(pool, "reactor-host");
|
|
1663
|
+
logger.info(`Using PostgreSQL for reactor storage (host pool max ${poolSize})`);
|
|
1664
|
+
return {
|
|
1665
|
+
kysely: new Kysely({ dialect: new PostgresDialect({ pool }) }),
|
|
1666
|
+
poolInstrumentation,
|
|
1667
|
+
storageFacts: POSTGRES_STORAGE_FACTS
|
|
1668
|
+
};
|
|
1669
|
+
}
|
|
1670
|
+
if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
|
|
1671
|
+
const pglite = (await createPgliteStoreFactory({
|
|
1672
|
+
label: "reactor-storage",
|
|
1673
|
+
major: reactorPgliteMajor,
|
|
1674
|
+
parsers: "none",
|
|
1675
|
+
inMemory,
|
|
1676
|
+
threaded: pgliteWorkers,
|
|
1677
|
+
settings: pgliteSettings,
|
|
1678
|
+
logger
|
|
1679
|
+
}))(reactorPgliteDir);
|
|
1680
|
+
const dialectOptions = pglite instanceof ThreadedPGlite ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite) : reactorPgliteDialectOptions(logger);
|
|
1681
|
+
return {
|
|
1682
|
+
kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, dialectOptions) }),
|
|
1683
|
+
poolInstrumentation: void 0,
|
|
1684
|
+
storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Where the two stores live — the classic resolution, relocated verbatim.
|
|
1689
|
+
* Classic layout: `./.ph/reactor-storage` for the reactor and
|
|
1690
|
+
* `.ph/read-storage` for the read model (the same names inside
|
|
1691
|
+
* `${userData}/.ph` under a shell's PH_USER_DATA_DIR). `dbPath` also names
|
|
1692
|
+
* the reactor store unless PH_REACTOR_DATABASE_URL does: with `dbPath` alone
|
|
1693
|
+
* both stores share one location. That is the long-standing contract of
|
|
1694
|
+
* `--db-path` and fine for one Postgres database, but for PGlite it is two
|
|
1695
|
+
* postmasters on one data dir — reported via `sharedPgliteDir` so the caller
|
|
1696
|
+
* warns. Not refused: changing that contract is a separate decision.
|
|
1697
|
+
*/
|
|
1698
|
+
function resolvePgliteStorageDirs(opts) {
|
|
1699
|
+
const { dbPath, reactorDbUrl, callerReactor } = opts;
|
|
1700
|
+
const defaults = defaultStoreDirs({ PH_USER_DATA_DIR: opts.userDataDir }, opts.phDir);
|
|
1701
|
+
const readModelPath = dbPath || defaults.readModel;
|
|
1702
|
+
const reactorPath = reactorDbUrl || defaults.reactor;
|
|
1703
|
+
const reactorPgliteDir = callerReactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
|
|
1704
|
+
const readModelPgliteDir = !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;
|
|
1705
|
+
const sharedPgliteDir = reactorPgliteDir !== null && readModelPgliteDir !== null && path$1.resolve(reactorPgliteDir) === path$1.resolve(readModelPgliteDir) ? path$1.resolve(reactorPgliteDir) : null;
|
|
1706
|
+
return {
|
|
1707
|
+
readModelPath,
|
|
1708
|
+
reactorPath,
|
|
1709
|
+
reactorPgliteDir,
|
|
1710
|
+
readModelPgliteDir,
|
|
1711
|
+
pgliteDirs: [reactorPgliteDir, readModelPgliteDir].filter((d) => d !== null),
|
|
1712
|
+
sharedPgliteDir
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
/** The remote attachment service config for switchboard's own `/attachments/*` API; `attachments.serviceUrl` carries PH_SWITCHBOARD_PUBLIC_URL. */
|
|
1716
|
+
function deriveAttachmentServiceConfig(options, serverPort, renown) {
|
|
1717
|
+
const protocol = options.https ? "https" : "http";
|
|
1718
|
+
return {
|
|
1719
|
+
remoteUrl: options.attachmentServiceUrl ?? `${protocol}://localhost:${serverPort}`,
|
|
1720
|
+
jwtHandler: renown ? async (url) => renown.user ? renown.getBearerToken({
|
|
1721
|
+
expiresIn: 10,
|
|
1722
|
+
aud: url
|
|
1723
|
+
}) : void 0 : void 0
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
async function initServer(requestedPort, options, config, renown, renownConfig, reportError) {
|
|
1727
|
+
const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
|
|
1728
|
+
const pluginHost = config.features.pluginHost ? createSwitchboardPluginHost({
|
|
1729
|
+
logger,
|
|
1730
|
+
options,
|
|
1731
|
+
config,
|
|
1732
|
+
renown
|
|
1733
|
+
}, options.pluginComposition) : null;
|
|
1734
|
+
if (pluginHost) {
|
|
1735
|
+
options = await pluginHost.transformOptions(options);
|
|
1736
|
+
options.mcp ??= false;
|
|
1737
|
+
options.workflows = {
|
|
1738
|
+
...options.workflows,
|
|
1739
|
+
enabled: options.workflows?.enabled === true
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
logger.level = config.logLevel;
|
|
1743
|
+
const dbPath = config.storage.readModel.url;
|
|
1744
|
+
const reactorDbUrl = config.storage.reactor.url;
|
|
1745
|
+
const inMemory = config.storage.inMemory;
|
|
1746
|
+
const pgliteSettings = {
|
|
1747
|
+
fsync: config.storage.pglite.fsync,
|
|
1748
|
+
maintenance: vacuumFullTimingOf(config.storage.pglite.vacuumFull),
|
|
1749
|
+
workerMemoryMb: config.storage.pglite.workerMemoryMb
|
|
1750
|
+
};
|
|
1751
|
+
const { readModelPath, reactorPgliteDir, readModelPgliteDir, pgliteDirs, sharedPgliteDir } = resolvePgliteStorageDirs({
|
|
1752
|
+
dbPath,
|
|
1753
|
+
reactorDbUrl,
|
|
1754
|
+
callerReactor: options.reactor !== void 0,
|
|
1755
|
+
userDataDir: config.storage.userDataDir
|
|
1756
|
+
});
|
|
1757
|
+
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.`);
|
|
1758
|
+
if (!inMemory) acquireStoreLocks(pgliteDirs);
|
|
1759
|
+
warnIgnoredFlushInterval(logger);
|
|
1760
|
+
const detectedMajors = await runPglitePreflight({
|
|
1761
|
+
dirs: pgliteDirs,
|
|
1762
|
+
forcePgVersion: options.forcePgVersion,
|
|
1763
|
+
migratePglite: options.migratePglite,
|
|
1764
|
+
inMemory,
|
|
1765
|
+
logger
|
|
1766
|
+
});
|
|
1767
|
+
function resolvePgliteMajorForDir(dir) {
|
|
1768
|
+
if (options.forcePgVersion !== void 0) return options.forcePgVersion;
|
|
1769
|
+
const detected = detectedMajors.get(dir);
|
|
1770
|
+
if (detected === void 0) return 17;
|
|
1771
|
+
if (!isSupportedMajor(detected)) throw new Error(`Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`);
|
|
1772
|
+
return detected;
|
|
1773
|
+
}
|
|
1774
|
+
const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
|
|
1775
|
+
const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
|
|
1776
|
+
const inspectionThrottle = config.inspection.callsPerMinute === void 0 ? {} : { callsPerMinute: config.inspection.callsPerMinute };
|
|
1777
|
+
let workerPool = resolveWorkerPoolOptions(options.workerPool, {});
|
|
1778
|
+
if (workerPool && options.reactor) {
|
|
1779
|
+
logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
|
|
1780
|
+
workerPool = null;
|
|
1781
|
+
}
|
|
1782
|
+
if (workerPool) {
|
|
1783
|
+
const issue = workerPoolIssues({
|
|
1784
|
+
dev: dev === true,
|
|
1785
|
+
workers: workerPool.numWorkers,
|
|
1786
|
+
projectionWorker: false,
|
|
1787
|
+
reactorDbUrl,
|
|
1788
|
+
authEnforcement: config.protocol.featureFlags.authEnforcement,
|
|
1789
|
+
renownSource: renownConfig.source
|
|
1790
|
+
}).at(0);
|
|
1791
|
+
if (issue) throw new Error(issue);
|
|
1792
|
+
}
|
|
1793
|
+
const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, {});
|
|
1794
|
+
let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, {});
|
|
1795
|
+
if (projectionWorker && options.reactor) {
|
|
1796
|
+
logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
|
|
1797
|
+
projectionWorker = null;
|
|
1798
|
+
}
|
|
1799
|
+
if (projectionWorker) assertProjectionWorkerSupported({
|
|
1800
|
+
dev: dev === true,
|
|
1801
|
+
reactorDbUrl
|
|
1802
|
+
});
|
|
1803
|
+
const apiRef = { current: void 0 };
|
|
1804
|
+
let driveNodeView;
|
|
1805
|
+
const configPath = resolveConfigPath(options.configFile);
|
|
1806
|
+
const fileConfig = getConfig(configPath);
|
|
1807
|
+
const registryUrl = options.registryUrl ?? fileConfig.packageRegistryUrl;
|
|
1808
|
+
const registryPackages = config.packages.registryPackages;
|
|
1809
|
+
const dynamicModelLoading = options.dynamicModelLoading === true;
|
|
1810
|
+
let httpLoader;
|
|
1811
|
+
if (registryUrl) {
|
|
1812
|
+
registerHttpsHooks();
|
|
1813
|
+
httpLoader = new HttpPackageLoader({
|
|
1814
|
+
registryUrl,
|
|
1815
|
+
cacheDir: path$1.join(resolvePhDir(void 0, { PH_USER_DATA_DIR: config.storage.userDataDir }), "registry-packages")
|
|
1816
|
+
});
|
|
1817
|
+
for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
|
|
1818
|
+
}
|
|
1819
|
+
const registryPackageNames = new Set(registryPackages.filter(Boolean));
|
|
1820
|
+
const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
|
|
1821
|
+
const reactorLogger = logger.child(["reactor"]);
|
|
1822
|
+
let projectionWorkerFatalFired = false;
|
|
1823
|
+
const onProjectionWorkerFatal = (shardId, reason) => {
|
|
1824
|
+
if (projectionWorkerFatalFired) return;
|
|
1825
|
+
projectionWorkerFatalFired = true;
|
|
1826
|
+
reactorLogger.error(`Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`, reason);
|
|
1827
|
+
process.kill(process.pid, "SIGTERM");
|
|
1828
|
+
};
|
|
1829
|
+
const workflowsEnabled = options.workflows?.enabled === true;
|
|
1830
|
+
const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, {});
|
|
1831
|
+
if (workflowsEnabled) {
|
|
1832
|
+
await assertWorkflowPackageLoadable();
|
|
1833
|
+
if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
|
|
1834
|
+
}
|
|
1835
|
+
let ownedReactorModule;
|
|
1836
|
+
const catchUpPriority = new CatchUpPriority(config.protocol.catchUpPriority === "dynamic" ? { mode: "dynamic" } : {
|
|
1837
|
+
mode: "fixed",
|
|
1838
|
+
level: config.protocol.catchUpPriority
|
|
1839
|
+
});
|
|
1840
|
+
let workerModels;
|
|
1841
|
+
let localRenownRequest;
|
|
1842
|
+
const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests, readModelDb }) => {
|
|
1843
|
+
if (options.reactor) {
|
|
1844
|
+
const attachmentReferenceProjection = await registerAttachmentReferenceReadModelOnModule(options.reactor, attachmentReferenceWriter);
|
|
1845
|
+
if (options.reactor.reactorModule) {
|
|
1846
|
+
new ReactorInstrumentation(options.reactor.reactorModule).start();
|
|
1847
|
+
reactorLogger.info("Reactor metrics instrumentation started (using caller-provided reactor)");
|
|
1848
|
+
}
|
|
1849
|
+
return {
|
|
1850
|
+
module: options.reactor,
|
|
1851
|
+
attachmentReferenceProjection
|
|
1852
|
+
};
|
|
1853
|
+
}
|
|
1854
|
+
const { kysely: baseKysely, poolInstrumentation, storageFacts } = await createReactorKysely({
|
|
1855
|
+
reactorDbUrl,
|
|
1856
|
+
reactorPgliteDir,
|
|
1857
|
+
reactorPgliteMajor,
|
|
1858
|
+
inMemory,
|
|
1859
|
+
hostPoolSize: () => config.workers.hostPoolSize,
|
|
1860
|
+
pgliteWorkers: options.pgliteWorkers === true,
|
|
1861
|
+
pgliteSettings,
|
|
1862
|
+
logger
|
|
1863
|
+
});
|
|
1864
|
+
const maxSkipThreshold = config.protocol.maxSkipThreshold;
|
|
1865
|
+
const hasSkipThreshold = maxSkipThreshold !== void 0;
|
|
1866
|
+
if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
|
|
1867
|
+
const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = reactorFeatureFlagsOf(config.protocol.featureFlags);
|
|
1868
|
+
if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
|
|
1869
|
+
const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: config.protocol.legacyProcessorIds }).withUnsupportedStoredDocuments(unsupportedStoredDocuments).withCatchUpPriority(catchUpPriority);
|
|
1870
|
+
if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
|
|
1871
|
+
const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
|
|
1872
|
+
const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
|
|
1873
|
+
applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
|
|
1874
|
+
signalHandlers: options.signalHandlers,
|
|
1875
|
+
documentModels: [...documentModels, ...vetraDocumentModels],
|
|
1876
|
+
upgradeManifests,
|
|
1877
|
+
executorConfig: hasSkipThreshold || enabledFeatureFlags.length > 0 ? {
|
|
1878
|
+
...hasSkipThreshold ? { maxSkipThreshold } : {},
|
|
1879
|
+
...enabledFeatureFlags.length > 0 ? { featureFlags: reactorFeatureFlags } : {}
|
|
1880
|
+
} : void 0,
|
|
1881
|
+
documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
|
|
1882
|
+
logger: reactorLogger,
|
|
1883
|
+
signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
|
|
1884
|
+
createSignaturePolicy: createSignaturePolicyFor(config.protocol.createSignaturePolicy, {
|
|
1885
|
+
hasSigner: renown !== null,
|
|
1886
|
+
logger
|
|
1887
|
+
}),
|
|
1888
|
+
trustPolicy: reactorFeatureFlags.authEnforcement ? await getRenownTrustPolicyConfig(renownConfig.source === "self" ? {
|
|
1889
|
+
source: "self",
|
|
1890
|
+
request: (query, variables) => localRenownRequest ? localRenownRequest(query, variables) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet"))
|
|
1891
|
+
} : {
|
|
1892
|
+
source: "remote",
|
|
1893
|
+
renownUrl: renownConfig.url,
|
|
1894
|
+
switchboardUrl: renownConfig.switchboardUrl
|
|
1895
|
+
}, renown) : void 0
|
|
1896
|
+
});
|
|
1897
|
+
if (workerPool || projectionWorker || workflowsEnabled) {
|
|
1898
|
+
const sources = await resolveWorkerModelSources(packages, reactorLogger, { resolveRemote: resolveRegistryModels });
|
|
1899
|
+
reactorBuilder.withDocumentModelSources(workerPool || projectionWorker ? sources : await keepImportableSources(sources, reactorLogger));
|
|
1900
|
+
}
|
|
1901
|
+
workerModels = modelManifestSource(reactorBuilder);
|
|
1902
|
+
if (workerPool) {
|
|
1903
|
+
if (!reactorDbUrl) throw new Error("unreachable: worker pool enabled without a reactor database URL");
|
|
1904
|
+
reactorBuilder.withWorkerPool({
|
|
1905
|
+
numWorkers: workerPool.numWorkers,
|
|
1906
|
+
db: buildWorkerDbConfig(reactorDbUrl, workerPool)
|
|
1907
|
+
});
|
|
1908
|
+
reactorLogger.info(`Executor worker pool enabled: ${workerPool.numWorkers} worker threads${workerPool.mode === "auto" ? " (auto-sized from cores)" : ""}`);
|
|
1909
|
+
}
|
|
1910
|
+
reactorBuilder.withReadModelFactory(async ({ operationIndex, writeCache, processorManagerConsistencyTracker }) => {
|
|
1911
|
+
const nodeProcessor = new NodeProcessor(baseKysely, REACTOR_SCHEMA, operationIndex, writeCache, processorManagerConsistencyTracker);
|
|
1912
|
+
await nodeProcessor.init();
|
|
1913
|
+
return nodeProcessor;
|
|
1914
|
+
});
|
|
1915
|
+
registerAttachmentReferenceReadModel(reactorBuilder, {
|
|
1916
|
+
baseKysely,
|
|
1917
|
+
attachmentReferenceWriter
|
|
1918
|
+
});
|
|
1919
|
+
if (projectionWorker) {
|
|
1920
|
+
if (!reactorDbUrl) throw new Error("unreachable: projection worker enabled without a reactor database URL");
|
|
1921
|
+
const db = {
|
|
1922
|
+
...buildWorkerDbConfig(reactorDbUrl, {
|
|
1923
|
+
dbPoolSizePerWorker: projectionWorker.dbPoolSize,
|
|
1924
|
+
acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5e3
|
|
1925
|
+
}),
|
|
1926
|
+
applicationName: "switchboard-projection"
|
|
1927
|
+
};
|
|
1928
|
+
reactorBuilder.withReadModelCoordinatorFactory(createHybridProjectionCoordinatorFactory({
|
|
1929
|
+
shardCount: 1,
|
|
1930
|
+
poolSize: projectionWorker.dbPoolSize,
|
|
1931
|
+
db,
|
|
1932
|
+
onFatal: onProjectionWorkerFatal
|
|
1933
|
+
}));
|
|
1934
|
+
reactorLogger.info(`Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`);
|
|
1935
|
+
}
|
|
1936
|
+
reactorBuilder.withShutdownHook(async () => {
|
|
1937
|
+
if (apiRef.current) await apiRef.current.dispose();
|
|
1938
|
+
});
|
|
1939
|
+
const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
|
|
1940
|
+
const nodeView = new DriveNodeView(reactorDriveSchemaDb);
|
|
1941
|
+
driveNodeView = nodeView;
|
|
1942
|
+
clientBuilder.withDriveNodeSource(nodeView).withDriveWriteStrategy(REACTOR_DRIVE_DOCUMENT_TYPE, createReactorDriveWriteStrategy);
|
|
1943
|
+
let module;
|
|
1944
|
+
try {
|
|
1945
|
+
module = await withProgressHeartbeat({
|
|
1946
|
+
logger,
|
|
1947
|
+
label: "Starting the reactor (migrations, document view, indexer, processors)"
|
|
1948
|
+
}, () => clientBuilder.buildModule());
|
|
1949
|
+
} catch (error) {
|
|
1950
|
+
try {
|
|
1951
|
+
await baseKysely.destroy();
|
|
1952
|
+
} catch (destroyError) {
|
|
1953
|
+
logger.error("Aborting boot: reactor database destroy failed: @error", destroyError);
|
|
1954
|
+
}
|
|
1955
|
+
if (UnsupportedStoredProtocolError.isError(error)) throw new StoredDocumentsRefusedError(error);
|
|
1956
|
+
throw error;
|
|
1957
|
+
}
|
|
1958
|
+
if (module.reactorModule) {
|
|
1959
|
+
new ReactorInstrumentation(module.reactorModule).start();
|
|
1960
|
+
reactorLogger.info("Reactor metrics instrumentation started");
|
|
1961
|
+
}
|
|
1962
|
+
const reactorDriveClient = new ReactorDriveClient({
|
|
1963
|
+
read: module.read,
|
|
1964
|
+
write: module.write,
|
|
1965
|
+
readModel: nodeView
|
|
1966
|
+
});
|
|
1967
|
+
ownedReactorModule = module;
|
|
1968
|
+
if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
|
|
1969
|
+
const permissionsDb = baseKysely.withSchema(REACTOR_SCHEMA);
|
|
1970
|
+
try {
|
|
1971
|
+
if (readModelDb) await withProgressHeartbeat({
|
|
1972
|
+
logger,
|
|
1973
|
+
label: "Moving the permission tables"
|
|
1974
|
+
}, () => backfillPermissionTables(readModelDb, permissionsDb, logger));
|
|
1975
|
+
} catch (error) {
|
|
1976
|
+
logger.error("Aborting boot: permission tables backfill failed: @error", error);
|
|
1977
|
+
try {
|
|
1978
|
+
await module.reactorModule?.shutdown();
|
|
1979
|
+
} catch (shutdownError) {
|
|
1980
|
+
logger.error("Aborting boot: reactor shutdown failed: @error", shutdownError);
|
|
1981
|
+
}
|
|
1982
|
+
throw error;
|
|
1983
|
+
}
|
|
1984
|
+
return {
|
|
1985
|
+
module,
|
|
1986
|
+
reactorDriveClient,
|
|
1987
|
+
driveNodes: nodeView,
|
|
1988
|
+
attachmentReferenceProjection: { status: "available" },
|
|
1989
|
+
permissionsDb
|
|
1990
|
+
};
|
|
1991
|
+
};
|
|
1992
|
+
const abortBoot = async (api) => {
|
|
1993
|
+
let disposed;
|
|
1994
|
+
const disposeApi = () => disposed ??= api.dispose();
|
|
1995
|
+
apiRef.current = { dispose: disposeApi };
|
|
1996
|
+
const owned = ownedReactorModule;
|
|
1997
|
+
if (owned?.reactorModule) try {
|
|
1998
|
+
await owned.reactorModule.shutdown();
|
|
1999
|
+
} catch (error) {
|
|
2000
|
+
logger.error("Aborting boot: reactor shutdown failed: @error", error);
|
|
2001
|
+
}
|
|
2002
|
+
else if (owned) try {
|
|
2003
|
+
await owned.reactor.kill().completed;
|
|
2004
|
+
} catch (error) {
|
|
2005
|
+
logger.error("Aborting boot: reactor shutdown failed: @error", error);
|
|
2006
|
+
}
|
|
2007
|
+
try {
|
|
2008
|
+
await disposeApi();
|
|
2009
|
+
} catch (error) {
|
|
2010
|
+
logger.error("Aborting boot: api dispose failed: @error", error);
|
|
2011
|
+
}
|
|
2012
|
+
};
|
|
2013
|
+
let localCredentialCheck;
|
|
2014
|
+
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;
|
|
2015
|
+
let defaultDriveUrl = void 0;
|
|
2016
|
+
const basePath = process.cwd();
|
|
2017
|
+
const reporting = {
|
|
2018
|
+
logger,
|
|
2019
|
+
report: reportError
|
|
2020
|
+
};
|
|
2021
|
+
let vite;
|
|
2022
|
+
let viteLoader;
|
|
2023
|
+
if (dev) {
|
|
2024
|
+
const { VitePackageLoader, createViteLogger, startViteServer } = await import("@powerhousedao/reactor-api/vite");
|
|
2025
|
+
vite = await startViteServer(process.cwd(), createViteLogger(logger));
|
|
2026
|
+
viteLoader = VitePackageLoader.build(vite, {
|
|
2027
|
+
resolveFrom: [import.meta.url],
|
|
2028
|
+
reportError
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
const vetraProcessorFactory = dev ? (await import("@powerhousedao/vetra/processors")).processorFactory : void 0;
|
|
2032
|
+
if (!options.disableLocalPackages) packages.push(basePath);
|
|
2033
|
+
const packageLoaders = [];
|
|
2034
|
+
if (viteLoader) packageLoaders.push(viteLoader);
|
|
2035
|
+
else packageLoaders.push(new ImportPackageLoader());
|
|
2036
|
+
if (httpLoader) {
|
|
2037
|
+
packageLoaders.push(httpLoader);
|
|
2038
|
+
for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
|
|
2039
|
+
}
|
|
2040
|
+
const apiLogger = logger.child(["reactor-api"]);
|
|
2041
|
+
let pgliteFactory;
|
|
2042
|
+
if (readModelPgliteDir && readModelPgliteMajor !== null) {
|
|
2043
|
+
const openReadStore = await createPgliteStoreFactory({
|
|
2044
|
+
label: "read-storage",
|
|
2045
|
+
major: readModelPgliteMajor,
|
|
2046
|
+
parsers: "utc-timestamps",
|
|
2047
|
+
inMemory,
|
|
2048
|
+
threaded: options.pgliteWorkers === true,
|
|
2049
|
+
settings: pgliteSettings,
|
|
2050
|
+
logger
|
|
2051
|
+
});
|
|
2052
|
+
pgliteFactory = (connectionString) => openReadStore(connectionString ?? readModelPgliteDir);
|
|
2053
|
+
}
|
|
2054
|
+
const api = await initializeAndStartAPI(initializeClient, {
|
|
2055
|
+
port: requestedPort,
|
|
2056
|
+
dbPath: readModelPath,
|
|
2057
|
+
pgliteFactory,
|
|
2058
|
+
https: options.https,
|
|
2059
|
+
packageLoaders: packageLoaders.length > 0 ? packageLoaders : void 0,
|
|
2060
|
+
packages,
|
|
2061
|
+
processorConfig: options.processorConfig,
|
|
2062
|
+
processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
|
|
2063
|
+
configFile: configPath,
|
|
2064
|
+
server: {
|
|
2065
|
+
basePath: config.server.basePath,
|
|
2066
|
+
gatewayAdapter: config.server.gatewayAdapter,
|
|
2067
|
+
publicUrl: config.server.publicUrl
|
|
2068
|
+
},
|
|
2069
|
+
auth: authSectionOf(config.auth),
|
|
2070
|
+
attachments: { storage: config.attachments.storage },
|
|
2071
|
+
mcp: options.mcp ?? true,
|
|
2072
|
+
inspection: options.inspection === false ? false : {
|
|
2073
|
+
throttle: inspectionThrottle,
|
|
2074
|
+
admin: config.inspection.admin
|
|
2075
|
+
},
|
|
2076
|
+
logger: apiLogger,
|
|
2077
|
+
reportError,
|
|
2078
|
+
enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
|
|
2079
|
+
renown: renownConfig,
|
|
2080
|
+
verifyCredential
|
|
2081
|
+
}, "switchboard");
|
|
2082
|
+
apiRef.current = api;
|
|
2083
|
+
const serverPort = api.port;
|
|
2084
|
+
if (renownConfig.source === "self") {
|
|
2085
|
+
const { graphqlManager: manager } = api;
|
|
2086
|
+
if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {
|
|
2087
|
+
await abortBoot(api);
|
|
2088
|
+
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.`);
|
|
2089
|
+
}
|
|
2090
|
+
localRenownRequest = (query, variables) => manager.executeSubgraphQuery(RENOWN_READ_MODEL_SUBGRAPH, query, variables);
|
|
2091
|
+
localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, { onError: (error) => logger.error("Renown read model query failed: @error", error) });
|
|
2092
|
+
logger.info("Renown credentials will be verified against this switchboard's own renown read model");
|
|
2093
|
+
}
|
|
2094
|
+
let attachmentService;
|
|
2095
|
+
if (pluginHost) {
|
|
2096
|
+
pluginHost.ctx.api = api;
|
|
2097
|
+
pluginHost.ctx.serverPort = serverPort;
|
|
2098
|
+
await pluginHost.observe("onHttpMounting");
|
|
2099
|
+
attachmentService = pluginHost.ctx.attachmentService;
|
|
2100
|
+
} else {
|
|
2101
|
+
registerAttachmentRoutes(api, { config: config.attachments });
|
|
2102
|
+
attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
|
|
2103
|
+
}
|
|
2104
|
+
if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
|
|
2105
|
+
const { client, read, write, graphqlManager, documentModelRegistry } = api;
|
|
2106
|
+
const lateSubgraphs = [];
|
|
2107
|
+
if (pluginHost) {
|
|
2108
|
+
pluginHost.ctx.client = client;
|
|
2109
|
+
pluginHost.ctx.read = read;
|
|
2110
|
+
pluginHost.ctx.write = write;
|
|
2111
|
+
pluginHost.ctx.graphqlManager = graphqlManager;
|
|
2112
|
+
pluginHost.ctx.lateSubgraphs = lateSubgraphs;
|
|
2113
|
+
pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;
|
|
2114
|
+
await pluginHost.observe("onReactorReady");
|
|
2115
|
+
}
|
|
2116
|
+
let workflows;
|
|
2117
|
+
let workflowsRetry;
|
|
2118
|
+
const composeWorkflows = () => composeWorkflowRuntime({
|
|
2119
|
+
reactorClient: client,
|
|
2120
|
+
clientModule: options.reactor ?? ownedReactorModule,
|
|
2121
|
+
relationalDb: api.relationalDb,
|
|
2122
|
+
secretsKeyFile: readModelPgliteDir === null ? false : void 0,
|
|
2123
|
+
storageId: readModelPgliteDir === null ? readModelPath : path$1.resolve(readModelPath),
|
|
2124
|
+
attachments: createAttachmentClient(api.attachments.service),
|
|
2125
|
+
attachmentAccess: api.attachmentAccess,
|
|
2126
|
+
webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,
|
|
2127
|
+
http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),
|
|
2128
|
+
oauthApps: options.workflows?.oauthApps ?? readConfigOAuthApps(resolveConfigPath(options.configFile)),
|
|
2129
|
+
authorizationService: api.authorizationService,
|
|
2130
|
+
indexQueries: api.graphqlManager,
|
|
2131
|
+
pieces: api.packageManager,
|
|
2132
|
+
pieceRegistryUrl: registryUrl,
|
|
2133
|
+
models: workerModels,
|
|
2134
|
+
reactorThreads: (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),
|
|
2135
|
+
logger: logger.child(["workflow-runtime"]),
|
|
2136
|
+
exclusiveJournal: readModelPgliteDir !== null,
|
|
2137
|
+
onSingletonLost: workflowSingletonLossHandler(logger),
|
|
2138
|
+
telemetry: {
|
|
2139
|
+
tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),
|
|
2140
|
+
meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE)
|
|
2141
|
+
}
|
|
2142
|
+
});
|
|
2143
|
+
const registerWorkflowSubgraph = (composed) => {
|
|
2144
|
+
const WorkflowRuntimeSubgraph = composed.subgraph;
|
|
2145
|
+
const workflowSubgraph = new WorkflowRuntimeSubgraph({
|
|
2146
|
+
readClient: read,
|
|
2147
|
+
reactorClient: client,
|
|
2148
|
+
http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),
|
|
2149
|
+
relationalDb: api.relationalDb,
|
|
2150
|
+
analyticsStore: void 0,
|
|
2151
|
+
graphqlManager,
|
|
2152
|
+
syncManager: api.syncManager,
|
|
2153
|
+
authorizationService: graphqlManager.getAuthorizationService(),
|
|
2154
|
+
path: graphqlManager.getBasePath(),
|
|
2155
|
+
attachments: api.attachmentClientProvider
|
|
2156
|
+
});
|
|
2157
|
+
return graphqlManager.registerSubgraphInstance(workflowSubgraph, "graphql", false).catch((error) => {
|
|
2158
|
+
reportFailure(reporting, error, "Failed to register workflow-runtime subgraph: @error");
|
|
2159
|
+
});
|
|
2160
|
+
};
|
|
2161
|
+
if (!pluginHost && workflowsEnabled) try {
|
|
2162
|
+
workflows = await composeWorkflows();
|
|
2163
|
+
} catch (error) {
|
|
2164
|
+
if (!isWorkflowSingletonConflict(error)) throw error;
|
|
2165
|
+
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.`);
|
|
2166
|
+
workflowsRetry = retryWorkflowSingleton({
|
|
2167
|
+
compose: composeWorkflows,
|
|
2168
|
+
onComposed: async (composed) => {
|
|
2169
|
+
try {
|
|
2170
|
+
await composed.start();
|
|
2171
|
+
} catch (error) {
|
|
2172
|
+
try {
|
|
2173
|
+
await composed.stop();
|
|
2174
|
+
} catch (stopError) {
|
|
2175
|
+
logger.error("Stopping the late workflow runtime failed: @error", stopError);
|
|
2176
|
+
}
|
|
2177
|
+
throw error;
|
|
2178
|
+
}
|
|
2179
|
+
logger.info("Workflow runtime started");
|
|
2180
|
+
workflows = composed;
|
|
2181
|
+
await registerWorkflowSubgraph(composed);
|
|
2182
|
+
try {
|
|
2183
|
+
await graphqlManager.updateRouter(true);
|
|
2184
|
+
} catch (error) {
|
|
2185
|
+
reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error");
|
|
2186
|
+
}
|
|
2187
|
+
},
|
|
2188
|
+
logger
|
|
2189
|
+
});
|
|
2190
|
+
}
|
|
2191
|
+
if (workflows) {
|
|
2192
|
+
lateSubgraphs.push(registerWorkflowSubgraph(workflows));
|
|
2193
|
+
const runtime = workflows;
|
|
2194
|
+
await withProgressHeartbeat({
|
|
2195
|
+
logger,
|
|
2196
|
+
label: "Starting the workflow runtime"
|
|
2197
|
+
}, () => runtime.start());
|
|
2198
|
+
logger.info("Workflow runtime started");
|
|
2199
|
+
api.inspection?.facts.setWorkflows(true);
|
|
2200
|
+
}
|
|
2201
|
+
if (pluginHost) {
|
|
2202
|
+
pluginHost.ctx.workflowsOrchestration = {
|
|
2203
|
+
enabled: options.workflows?.enabled === true,
|
|
2204
|
+
composeWorkflows,
|
|
2205
|
+
registerWorkflowSubgraph,
|
|
2206
|
+
updateRouter: () => graphqlManager.updateRouter(true),
|
|
2207
|
+
reportMountFailure: (error) => reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error"),
|
|
2208
|
+
setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true)
|
|
2209
|
+
};
|
|
2210
|
+
try {
|
|
2211
|
+
await pluginHost.observe("onSubgraphsRegistering");
|
|
2212
|
+
} catch (error) {
|
|
2213
|
+
await pluginHost.ctx.workflowsRetry?.stop();
|
|
2214
|
+
await pluginHost.ctx.workflows?.stop();
|
|
2215
|
+
await abortBoot(api);
|
|
2216
|
+
throw error;
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
let privacy;
|
|
2220
|
+
if (!pluginHost && privacyConfig.enabled) {
|
|
2221
|
+
const signer = options.reactor ? options.privacy?.signer : options.privacy?.signer ?? renown?.signer;
|
|
2222
|
+
try {
|
|
2223
|
+
privacy = await startPrivacy({
|
|
2224
|
+
config: privacyConfig,
|
|
2225
|
+
reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,
|
|
2226
|
+
signer,
|
|
2227
|
+
authorizationService: api.authorizationService,
|
|
2228
|
+
documentPermissionService: api.documentPermissionService,
|
|
2229
|
+
graphqlManager,
|
|
2230
|
+
reactorClient: client,
|
|
2231
|
+
logger: logger.child(["privacy"])
|
|
2232
|
+
});
|
|
2233
|
+
} catch (error) {
|
|
2234
|
+
await workflowsRetry?.stop();
|
|
2235
|
+
await workflows?.stop();
|
|
2236
|
+
await abortBoot(api);
|
|
2237
|
+
throw error;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
const stopCatchUpLoad = ownedReactorModule ? feedCatchUpPriority(catchUpPriority, api.httpServer) : () => {};
|
|
2241
|
+
let apiDrained;
|
|
2242
|
+
const drainApi = () => apiDrained ??= (async () => {
|
|
2243
|
+
stopCatchUpLoad();
|
|
2244
|
+
if (pluginHost) await pluginHost.observe("onShutdown");
|
|
2245
|
+
await privacy?.stop();
|
|
2246
|
+
await workflowsRetry?.stop();
|
|
2247
|
+
await workflows?.stop();
|
|
2248
|
+
await api.dispose();
|
|
2249
|
+
})();
|
|
2250
|
+
apiRef.current = { dispose: drainApi };
|
|
2251
|
+
const ownedReactor = ownedReactorModule?.reactorModule;
|
|
2252
|
+
const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;
|
|
2253
|
+
if (httpLoader) {
|
|
2254
|
+
const packageManagementService = new PackageManagementService({
|
|
2255
|
+
defaultRegistryUrl: registryUrl,
|
|
2256
|
+
httpLoader,
|
|
2257
|
+
documentModelRegistry,
|
|
2258
|
+
packageManager: api.packageManager
|
|
2259
|
+
});
|
|
2260
|
+
packageManagementService.setOnModelsChanged(() => {
|
|
2261
|
+
graphqlManager.regenerateDocumentModelSubgraphs().catch((error) => {
|
|
2262
|
+
reportFailure(reporting, error, "Failed to regenerate document model subgraphs: @error");
|
|
2263
|
+
});
|
|
2264
|
+
});
|
|
2265
|
+
const packagesSubgraph = new PackagesSubgraph({
|
|
2266
|
+
relationalDb: void 0,
|
|
2267
|
+
analyticsStore: void 0,
|
|
2268
|
+
readClient: read,
|
|
2269
|
+
reactorClient: client,
|
|
2270
|
+
graphqlManager,
|
|
2271
|
+
syncManager: api.syncManager,
|
|
2272
|
+
path: graphqlManager.getBasePath(),
|
|
2273
|
+
authorizationService: graphqlManager.getAuthorizationService(),
|
|
2274
|
+
packageManagementService,
|
|
2275
|
+
http: graphqlManager.scopeForPackage("@powerhousedao/switchboard"),
|
|
2276
|
+
attachments: api.attachmentClientProvider
|
|
2277
|
+
});
|
|
2278
|
+
lateSubgraphs.push(graphqlManager.registerSubgraphInstance(packagesSubgraph, "graphql", false).catch((error) => {
|
|
2279
|
+
reportFailure(reporting, error, "Failed to register packages subgraph: @error");
|
|
2280
|
+
}));
|
|
2281
|
+
}
|
|
2282
|
+
if (driveNodeView) {
|
|
2283
|
+
graphqlManager.setAdditionalContextFields({ readModel: driveNodeView });
|
|
2284
|
+
const authorizationService = graphqlManager.getAuthorizationService();
|
|
2285
|
+
const reactorDriveSubgraph = {
|
|
2286
|
+
name: REACTOR_DRIVE_SUBGRAPH_NAME,
|
|
2287
|
+
path: graphqlManager.getBasePath(),
|
|
2288
|
+
resolvers: createReactorDriveResolvers({
|
|
2289
|
+
reactorClient: client,
|
|
2290
|
+
readModel: driveNodeView,
|
|
2291
|
+
hostCanRead: (documentId, address) => authorizationService.canRead(documentId, address)
|
|
2292
|
+
}),
|
|
2293
|
+
typeDefs: reactorDriveSubgraphTypeDefs,
|
|
2294
|
+
readClient: read,
|
|
2295
|
+
reactorClient: client,
|
|
2296
|
+
relationalDb: void 0
|
|
2297
|
+
};
|
|
2298
|
+
lateSubgraphs.push(graphqlManager.registerSubgraphInstance(reactorDriveSubgraph, "graphql", false).catch((error) => {
|
|
2299
|
+
reportFailure(reporting, error, "Failed to register reactor-drive subgraph: @error");
|
|
2300
|
+
}));
|
|
2301
|
+
}
|
|
2302
|
+
runDetached("Marking the API ready", async () => {
|
|
2303
|
+
await Promise.allSettled(lateSubgraphs);
|
|
2304
|
+
try {
|
|
2305
|
+
await graphqlManager.updateRouter(true);
|
|
2306
|
+
} catch (error) {
|
|
2307
|
+
reportFailure(reporting, error, "Final router update before readiness failed: @error");
|
|
2308
|
+
}
|
|
2309
|
+
api.readiness.markReady();
|
|
2310
|
+
}, reporting);
|
|
2311
|
+
if (options.drive) {
|
|
2312
|
+
if (!renown) throw new Error("Cannot create default drive without Renown identity");
|
|
2313
|
+
if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort, logger);
|
|
2314
|
+
else defaultDriveUrl = await addDefaultDrive(client, options.drive, serverPort, logger);
|
|
2315
|
+
}
|
|
2316
|
+
if (vite) api.httpAdapter.mountRawMiddleware(vite.middlewares);
|
|
2317
|
+
if (remoteDrives.length > 0) for (const remoteDriveUrl of remoteDrives) {
|
|
2318
|
+
let driveId;
|
|
2319
|
+
try {
|
|
2320
|
+
const { syncManager } = api;
|
|
2321
|
+
const parsed = parseDriveUrl(remoteDriveUrl);
|
|
2322
|
+
driveId = parsed.driveId;
|
|
2323
|
+
const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;
|
|
2324
|
+
await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {
|
|
2325
|
+
type: "gql",
|
|
2326
|
+
parameters: { url: parsed.graphqlEndpoint }
|
|
2327
|
+
});
|
|
2328
|
+
logger.debug("Remote drive @remoteDriveUrl synced", remoteDriveUrl);
|
|
2329
|
+
} catch (error) {
|
|
2330
|
+
if (error instanceof Error && error.message.includes("already exists")) {
|
|
2331
|
+
logger.debug("Remote drive already added: @remoteDriveUrl", remoteDriveUrl);
|
|
2332
|
+
driveId = remoteDriveUrl.split("/").pop();
|
|
2333
|
+
} else logger.error("Failed to connect to remote drive @remoteDriveUrl: @error", remoteDriveUrl, error);
|
|
2334
|
+
} finally {
|
|
2335
|
+
if (!defaultDriveUrl && driveId) defaultDriveUrl = `${options.https ? "https" : "http"}://localhost:${serverPort}/d/${driveId}`;
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
if (pluginHost) await pluginHost.observe("onDrivesReady");
|
|
2339
|
+
return {
|
|
2340
|
+
defaultDriveUrl,
|
|
2341
|
+
api,
|
|
2342
|
+
reactor: client,
|
|
2343
|
+
attachmentService,
|
|
2344
|
+
attachmentReferenceProjection: api.attachmentReferenceProjection,
|
|
2345
|
+
get workflowTriggers() {
|
|
2346
|
+
return (workflows ?? pluginHost?.ctx.workflows)?.triggers;
|
|
2347
|
+
},
|
|
2348
|
+
workflowsEnabled,
|
|
2349
|
+
modelManifest: () => workerModels?.modelManifest() ?? [],
|
|
2350
|
+
privacy: (() => {
|
|
2351
|
+
const running = privacy ?? pluginHost?.ctx.privacy;
|
|
2352
|
+
return running ? { erasure: running.erasure } : void 0;
|
|
2353
|
+
})(),
|
|
2354
|
+
mcpEnabled: options.mcp !== false,
|
|
2355
|
+
inspectionEnabled: options.inspection !== false,
|
|
2356
|
+
inspector: api.inspection?.inspector,
|
|
2357
|
+
renown,
|
|
2358
|
+
port: serverPort,
|
|
2359
|
+
shutdown
|
|
2360
|
+
};
|
|
2361
|
+
}
|
|
2362
|
+
/**
|
|
2363
|
+
* Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.
|
|
2364
|
+
*
|
|
2365
|
+
* If `options.reactor` is provided, the switchboard reuses it instead of
|
|
2366
|
+
* building its own — the caller then owns the reactor's lifecycle and is
|
|
2367
|
+
* responsible for invoking `SwitchboardReactor.shutdown()` from their own
|
|
2368
|
+
* teardown / SIGINT path. The switchboard will not reach into the caller's
|
|
2369
|
+
* reactor; killing the reactor alone leaves the api/GraphQL/MCP resources
|
|
2370
|
+
* dangling until the process exits.
|
|
2371
|
+
*
|
|
2372
|
+
* When `options.reactor` is omitted, the switchboard builds and owns the
|
|
2373
|
+
* reactor. `shutdown()` on the returned handle then runs the reactor
|
|
2374
|
+
* module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains
|
|
2375
|
+
* the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the
|
|
2376
|
+
* reactor database. It does not exit the process. It is the same memoized
|
|
2377
|
+
* teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling
|
|
2378
|
+
* it twice, or receiving a signal around it, tears down once.
|
|
2379
|
+
*/
|
|
2380
|
+
const startSwitchboard = async (input = {}, deps = {}) => {
|
|
2381
|
+
assertConfigShape(input);
|
|
2382
|
+
const configPath = resolveConfigPath(input.configFile);
|
|
2383
|
+
const fileConfig = getConfig(configPath);
|
|
2384
|
+
const config = switchboardConfigSchema.parse(mergeSwitchboardConfig({ auth: {
|
|
2385
|
+
enabled: fileConfig.auth?.enabled,
|
|
2386
|
+
admins: fileConfig.auth?.admins
|
|
2387
|
+
} }, input));
|
|
2388
|
+
const logger = deps.logger ?? defaultLogger;
|
|
2389
|
+
if (disableWasmWrapperTiering()) logger.info("Wasm wrapper tier-up off on Node 24 (nodejs/node#66366)");
|
|
2390
|
+
if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
|
|
2391
|
+
const serverPort = await resolveServerPort(config.server.port, config.server.strictPort, logger);
|
|
2392
|
+
const options = serverOptionsOf(config, deps);
|
|
2393
|
+
if (!config.features.pluginHost) {
|
|
2394
|
+
options.mcp = config.features.mcp ?? true;
|
|
2395
|
+
options.workflows = { enabled: config.features.workflows ?? readConfigWorkflowsEnabled(configPath) };
|
|
2396
|
+
}
|
|
2397
|
+
const renownConfig = resolveRenownConfig(renownLayers(fileConfig.auth?.renown, config.auth.renown), {}, logger);
|
|
2398
|
+
const userDataDir = config.storage.userDataDir;
|
|
2399
|
+
options.identity = {
|
|
2400
|
+
...options.identity,
|
|
2401
|
+
baseUrl: options.identity?.baseUrl ?? renownConfig.url,
|
|
2402
|
+
keypairPath: options.identity?.keypairPath ?? (userDataDir ? path$1.join(resolvePhDir(void 0, { PH_USER_DATA_DIR: userDataDir }), ".keypair.json") : void 0)
|
|
2403
|
+
};
|
|
2404
|
+
logger.info("Feature flags: @flags", JSON.stringify({
|
|
2405
|
+
DOCUMENT_MODEL_SUBGRAPHS_ENABLED: options.enableDocumentModelSubgraphs,
|
|
2406
|
+
MCP_ENABLED: options.mcp,
|
|
2407
|
+
INSPECTION_ENABLED: options.inspection,
|
|
2408
|
+
PH_PGLITE_WORKERS: options.pgliteWorkers,
|
|
2409
|
+
PH_WORKFLOWS_ENABLED: options.workflows?.enabled
|
|
2410
|
+
}, null, 2));
|
|
2411
|
+
let renown = null;
|
|
2412
|
+
try {
|
|
2413
|
+
renown = await initRenown({
|
|
2414
|
+
...options.identity,
|
|
2415
|
+
userDataDir
|
|
2416
|
+
});
|
|
2417
|
+
} catch (e) {
|
|
2418
|
+
logger.warn("Failed to initialize ConnectCrypto: @error", e);
|
|
2419
|
+
if (options.identity.requireExisting) throw new Error("Identity required but failed to initialize. Run \"ph login\" first.", { cause: e });
|
|
2420
|
+
}
|
|
2421
|
+
const reportError = deps.reportError ?? ((error) => {
|
|
2422
|
+
Sentry.captureException(error);
|
|
2423
|
+
});
|
|
2424
|
+
try {
|
|
2425
|
+
return await initServer(serverPort, options, config, renown, renownConfig, reportError);
|
|
2426
|
+
} catch (e) {
|
|
2427
|
+
Sentry.captureException(e);
|
|
2428
|
+
if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
|
|
2429
|
+
else logger.error("App crashed: @error", e);
|
|
2430
|
+
throw e;
|
|
2431
|
+
}
|
|
2432
|
+
};
|
|
2433
|
+
function assertConfigShape(input) {
|
|
2434
|
+
const unknown = Object.keys(input).filter((key) => !(key in switchboardConfigSchema.shape));
|
|
2435
|
+
if (unknown.length > 0) throw new Error(`startSwitchboard(config, deps) got unknown config keys: ${unknown.join(", ")}. It takes the @powerhousedao/switchboard/config shape; runtime objects go in deps.`);
|
|
2436
|
+
}
|
|
2437
|
+
/** The options view plugins transform, from the config and deps. */
|
|
2438
|
+
function serverOptionsOf(config, deps) {
|
|
2439
|
+
const { executor, projection } = config.workers;
|
|
2440
|
+
return {
|
|
2441
|
+
reactor: deps.reactor,
|
|
2442
|
+
fatalErrorShutdown: deps.fatalErrorShutdown,
|
|
2443
|
+
signalHandlers: deps.signalHandlers,
|
|
2444
|
+
pluginComposition: deps.pluginComposition,
|
|
2445
|
+
logger: deps.logger,
|
|
2446
|
+
registryUrl: config.packages.registryUrl,
|
|
2447
|
+
configFile: config.configFile,
|
|
2448
|
+
port: config.server.port,
|
|
2449
|
+
strictPort: config.server.strictPort,
|
|
2450
|
+
dev: config.server.dev,
|
|
2451
|
+
dbPath: config.storage.readModel.url,
|
|
2452
|
+
drive: config.drive,
|
|
2453
|
+
packages: [...config.packages.list],
|
|
2454
|
+
remoteDrives: [...config.remoteDrives],
|
|
2455
|
+
https: config.server.https,
|
|
2456
|
+
identity: config.identity,
|
|
2457
|
+
attachmentServiceUrl: config.attachments.serviceUrl,
|
|
2458
|
+
mcp: config.features.mcp,
|
|
2459
|
+
inspection: config.inspection.enabled,
|
|
2460
|
+
pgliteWorkers: config.storage.pglite.workers,
|
|
2461
|
+
workflows: config.features.workflows === void 0 ? void 0 : { enabled: config.features.workflows },
|
|
2462
|
+
privacy: {
|
|
2463
|
+
enabled: config.features.privacy.enabled,
|
|
2464
|
+
deploymentSecret: config.features.privacy.deploymentSecret,
|
|
2465
|
+
intervalMs: config.features.privacy.intervalMs,
|
|
2466
|
+
deadlineMs: config.features.privacy.deadlineMs,
|
|
2467
|
+
markerGraceMs: config.features.privacy.markerGraceMs,
|
|
2468
|
+
purgeTimeoutMs: config.features.privacy.purgeTimeoutMs,
|
|
2469
|
+
signer: deps.privacySigner
|
|
2470
|
+
},
|
|
2471
|
+
processorConfig: config.processorConfig,
|
|
2472
|
+
disableLocalPackages: config.packages.disableLocal,
|
|
2473
|
+
enableDocumentModelSubgraphs: config.features.documentModelSubgraphs,
|
|
2474
|
+
dynamicModelLoading: config.packages.dynamic,
|
|
2475
|
+
migratePglite: config.storage.migratePglite,
|
|
2476
|
+
forcePgVersion: config.storage.forcePgVersion,
|
|
2477
|
+
workerPool: {
|
|
2478
|
+
numWorkers: executor.count,
|
|
2479
|
+
dbPoolSizePerWorker: executor.poolSize,
|
|
2480
|
+
acquireTimeoutMs: executor.acquireTimeoutMs
|
|
2481
|
+
},
|
|
2482
|
+
projectionWorker: {
|
|
2483
|
+
enabled: projection.enabled,
|
|
2484
|
+
dbPoolSize: projection.poolSize
|
|
2485
|
+
},
|
|
2486
|
+
unsupportedStoredDocuments: config.protocol.unsupportedStoredDocuments
|
|
2487
|
+
};
|
|
2488
|
+
}
|
|
2489
|
+
/** reactor-api's auth section; renown is resolved here, not there. */
|
|
2490
|
+
function authSectionOf(auth) {
|
|
2491
|
+
const { renown: _renown, ...section } = auth;
|
|
2492
|
+
return section;
|
|
2493
|
+
}
|
|
2494
|
+
if (import.meta.main) {
|
|
2495
|
+
const config = switchboardConfigFromEnv(process.env);
|
|
2496
|
+
initSwitchboardProcess(config);
|
|
2497
|
+
await startSwitchboard(config, { fatalErrorShutdown: true });
|
|
2498
|
+
}
|
|
2499
|
+
/**
|
|
2500
|
+
* Feeds the priority this server's request load and main-thread event-loop
|
|
2501
|
+
* delay, and ticks its controller every second. Returns the stop.
|
|
2502
|
+
*/
|
|
2503
|
+
function feedCatchUpPriority(priority, server) {
|
|
2504
|
+
const recorder = new RequestLoadRecorder({ eventLoopDelay: new NodeEventLoopDelay() });
|
|
2505
|
+
recorder.attach(server);
|
|
2506
|
+
priority.setLoadSource(recorder);
|
|
2507
|
+
const stopTicking = priority.startTicking();
|
|
2508
|
+
return () => {
|
|
2509
|
+
stopTicking();
|
|
2510
|
+
priority.setLoadSource(void 0);
|
|
2511
|
+
recorder.stop();
|
|
2512
|
+
};
|
|
2513
|
+
}
|
|
2514
|
+
//#endregion
|
|
2515
|
+
export { resolvePgliteStorageDirs as a, attachmentsPluginConfigSchema as c, isPortAvailable as i, applySwitchboardReactorDefaults as l, deriveAttachmentServiceConfig as n, startSwitchboard as o, initSwitchboardProcess as r, attachmentsPlugin as s, createReactorKysely as t, initProfilerFromEnv as u };
|
|
2516
|
+
|
|
2517
|
+
//# sourceMappingURL=server-cE1BWLQu.mjs.map
|
|
2518
|
+
//# debugId=4a0fe5f4-e71e-59f2-8cbd-cc08a5334040
|