@powerhousedao/switchboard 6.2.3-dev.9 → 6.2.3-dev.90
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/ai-gateway.test.d.ts +2 -0
- package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
- 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-desktop-auth.test.d.ts +2 -0
- package/.tsbuild/test/boot-desktop-auth.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-ready-drives.test.d.ts +2 -0
- package/.tsbuild/test/boot-ready-drives.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/delegated-publish.test.d.ts +2 -0
- package/.tsbuild/test/delegated-publish.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/keyframe-reclaim-store.test.d.ts +2 -0
- package/.tsbuild/test/keyframe-reclaim-store.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/processor-timing-log.test.d.ts +2 -0
- package/.tsbuild/test/processor-timing-log.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-apps-config.test.d.ts +2 -0
- package/.tsbuild/test/workflow/oauth-apps-config.test.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/waitpoint-routes.test.d.ts +2 -0
- package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
- package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
- package/.tsbuild/test/workflow/waitpoint-runtime.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 +1206 -0
- package/README.md +88 -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-DJ4iQ3QZ.mjs +473 -0
- package/dist/from-env-DJ4iQ3QZ.mjs.map +1 -0
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +84 -84
- 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-BHEUSn9G.d.mts +46 -0
- package/dist/plugin-host-BHEUSn9G.d.mts.map +1 -0
- package/dist/plugins/ai.d.mts +37 -0
- package/dist/plugins/ai.d.mts.map +1 -0
- package/dist/plugins/ai.mjs +400 -0
- package/dist/plugins/ai.mjs.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-1yj85yQD.mjs +326 -0
- package/dist/schema-1yj85yQD.mjs.map +1 -0
- package/dist/schema-ugrJupVH.d.mts +246 -0
- package/dist/schema-ugrJupVH.d.mts.map +1 -0
- package/dist/server-CgDvrUqE.mjs +2729 -0
- package/dist/server-CgDvrUqE.mjs.map +1 -0
- package/dist/server.d.mts +129 -189
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +5 -5
- package/dist/types-DzO3_320.d.mts +308 -0
- package/dist/types-DzO3_320.d.mts.map +1 -0
- package/dist/utils-Cm0TE6dP.mjs +148 -0
- package/dist/utils-Cm0TE6dP.mjs.map +1 -0
- package/dist/utils.d.mts +30 -5
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +5 -4
- package/dist/worker-pool-gyxJnCxA.mjs +304 -0
- package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
- package/dist/workflow-runtime-CF5pc8mt.d.mts +33 -0
- package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
- package/dist/workflows-C9BQlyT0.mjs +1943 -0
- package/dist/workflows-C9BQlyT0.mjs.map +1 -0
- package/package.json +85 -24
- package/scripts/install-packages.sh +0 -0
- package/test/ai-gateway.test.ts +612 -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-desktop-auth.test.ts +278 -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 +213 -0
- package/test/boot-privacy.test.ts +232 -0
- package/test/boot-ready-drives.test.ts +141 -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 +942 -0
- package/test/config-merge.test.ts +226 -0
- package/test/config-schema.test.ts +156 -0
- package/test/create-signature-policy.test.ts +69 -0
- package/test/default-drive-protocol-versions.test.ts +79 -0
- package/test/default-drive-slug.test.ts +265 -0
- package/test/delegated-publish.test.ts +435 -0
- package/test/durable-node-fs-pg16.test.ts +80 -0
- package/test/fatal-shutdown.test.ts +205 -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 +327 -0
- package/test/goldens/supergraph.graphql +5918 -0
- package/test/goldens/workflow-runtime.graphql +1548 -0
- package/test/inspection-throttle.test.ts +23 -0
- package/test/keyframe-reclaim-store.test.ts +156 -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 +441 -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/processor-timing-log.test.ts +109 -0
- package/test/redact-webhook-path.test.ts +9 -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-apps-config.test.ts +66 -0
- package/test/workflow/oauth.test.ts +286 -0
- package/test/workflow/resolvers.test.ts +488 -0
- package/test/workflow/runtime-host.test.ts +19 -0
- package/test/workflow/waitpoint-routes.test.ts +306 -0
- package/test/workflow/waitpoint-runtime.test.ts +204 -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 +1254 -0
- package/test/workflows-plugin-config.test.ts +77 -0
- package/tsconfig.json +11 -2
- package/tsdown.config.ts +13 -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
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!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]="
|
|
4
|
-
import {
|
|
5
|
-
import "./
|
|
3
|
+
!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]="7918c19e-39da-5020-b8b3-e72a02c33357")}catch(e){}}();
|
|
4
|
+
import { n as StoredDocumentsRefusedError, t as switchboardConfigFromEnv } from "./from-env-DJ4iQ3QZ.mjs";
|
|
5
|
+
import { a as callerOverEnv, o as mergeSwitchboardConfig } from "./schema-1yj85yQD.mjs";
|
|
6
|
+
import { d as initProfilerFromEnv, r as initSwitchboardProcess, s as startSwitchboard } from "./server-CgDvrUqE.mjs";
|
|
6
7
|
import { metrics } from "@opentelemetry/api";
|
|
7
8
|
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
8
9
|
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
|
|
@@ -20,8 +21,8 @@ import { SentryPropagator, SentrySpanProcessor } from "@sentry/opentelemetry";
|
|
|
20
21
|
import { childLogger } from "document-model";
|
|
21
22
|
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
|
|
22
23
|
import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
23
|
-
import dotenv from "dotenv";
|
|
24
24
|
import { getConfig } from "@powerhousedao/config/node";
|
|
25
|
+
import { DEFAULT_DRIVE_ICON } from "@powerhousedao/shared/clis";
|
|
25
26
|
//#region src/metrics.ts
|
|
26
27
|
const logger$2 = childLogger(["switchboard", "metrics"]);
|
|
27
28
|
function createMeterProviderFromEnv(env) {
|
|
@@ -44,8 +45,46 @@ function createMeterProviderFromEnv(env) {
|
|
|
44
45
|
return meterProvider;
|
|
45
46
|
}
|
|
46
47
|
//#endregion
|
|
48
|
+
//#region src/observability-signals.mts
|
|
49
|
+
/**
|
|
50
|
+
* Flushes telemetry on SIGINT/SIGTERM, then exits only when no other module
|
|
51
|
+
* has claimed a failing exit.
|
|
52
|
+
*
|
|
53
|
+
* Exit ownership, decided here on purpose:
|
|
54
|
+
*
|
|
55
|
+
* - Ordinary signal (process.exitCode unset or 0): this handler exits with
|
|
56
|
+
* the current exit code after the flush settles (the flush bounds itself,
|
|
57
|
+
* see shutdown() in observability.mts). When the reactor builder's drain
|
|
58
|
+
* handler is also attached it runs first (prependListener) and swaps
|
|
59
|
+
* process.exit for a recording shim before this handler's exit call, so
|
|
60
|
+
* the drain still finishes and performs the real exit; when the builder is
|
|
61
|
+
* not attached (startup, signalHandlers: false), this exit is what
|
|
62
|
+
* terminates the process, with code 0.
|
|
63
|
+
*
|
|
64
|
+
* - Fatal shutdown in progress (process.exitCode already non-zero):
|
|
65
|
+
* fatal-shutdown.mts sets exitCode = 1 and arms a 15s forced exit BEFORE
|
|
66
|
+
* raising SIGTERM, precisely so the builder's drain can flush the PGlite
|
|
67
|
+
* snapshots. Calling exit here would lower that code to 0 (supervisors
|
|
68
|
+
* would see a crash as success) and, whenever the builder's shim is not in
|
|
69
|
+
* place, cut the drain off at this handler's shorter flush budget. So this
|
|
70
|
+
* handler never exits once a non-zero code is set: the exit belongs to the
|
|
71
|
+
* builder's drain, or failing that to fatal-shutdown's 15s backstop, both
|
|
72
|
+
* of which preserve code 1.
|
|
73
|
+
*/
|
|
74
|
+
function installObservabilitySignalHandlers(flush, proc = process) {
|
|
75
|
+
const onSignal = () => {
|
|
76
|
+
flush().finally(() => {
|
|
77
|
+
const code = proc.exitCode;
|
|
78
|
+
if (code !== void 0 && code !== 0) return;
|
|
79
|
+
proc.exit(code ?? 0);
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
proc.on("SIGINT", onSignal);
|
|
83
|
+
proc.on("SIGTERM", onSignal);
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
47
86
|
//#region src/redact-webhook-path.ts
|
|
48
|
-
const
|
|
87
|
+
const TOKEN_SEGMENTS = ["/webhooks/", "/waitpoints/"];
|
|
49
88
|
/**
|
|
50
89
|
* Strips a webhook's delivery token out of a request path.
|
|
51
90
|
*
|
|
@@ -56,10 +95,13 @@ const WEBHOOK_SEGMENT = "/webhooks/";
|
|
|
56
95
|
function redactWebhookPath(url) {
|
|
57
96
|
if (!url) return "";
|
|
58
97
|
const path = url.split("?")[0] ?? url;
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
98
|
+
for (const segment of TOKEN_SEGMENTS) {
|
|
99
|
+
const at = path.indexOf(segment);
|
|
100
|
+
if (at === -1) continue;
|
|
101
|
+
if (path.length === at + segment.length) return url;
|
|
102
|
+
return `${path.slice(0, at)}${segment}[redacted]`;
|
|
103
|
+
}
|
|
104
|
+
return url;
|
|
63
105
|
}
|
|
64
106
|
//#endregion
|
|
65
107
|
//#region src/observability.mts
|
|
@@ -149,79 +191,34 @@ async function shutdown() {
|
|
|
149
191
|
eventLoopInstrumentation?.stop();
|
|
150
192
|
await Promise.race([Promise.all([meterProvider?.shutdown().catch(() => void 0), sdk?.shutdown().catch(() => void 0)]), new Promise((resolve) => setTimeout(resolve, 5e3))]);
|
|
151
193
|
}
|
|
152
|
-
|
|
153
|
-
shutdown().finally(() => process.exit(0));
|
|
154
|
-
});
|
|
155
|
-
process.on("SIGTERM", () => {
|
|
156
|
-
shutdown().finally(() => process.exit(0));
|
|
157
|
-
});
|
|
194
|
+
installObservabilitySignalHandlers(shutdown);
|
|
158
195
|
//#endregion
|
|
159
|
-
//#region src/config.ts
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
forcePgVersion: parseForcePgVersion(process.env.PH_FORCE_PG_VERSION),
|
|
173
|
-
drive: {
|
|
174
|
-
id: "powerhouse",
|
|
175
|
-
slug: "powerhouse",
|
|
176
|
-
documentType: parseDriveType(process.env.PH_DEFAULT_DRIVE_TYPE),
|
|
177
|
-
global: {
|
|
178
|
-
name: "Powerhouse",
|
|
179
|
-
icon: "https://ipfs.io/ipfs/QmcaTDBYn8X2psGaXe7iQ6qd8q6oqHLgxvMX9yXf7f9uP7"
|
|
180
|
-
},
|
|
181
|
-
local: {
|
|
182
|
-
availableOffline: true,
|
|
183
|
-
listeners: [],
|
|
184
|
-
sharingType: "public",
|
|
185
|
-
triggers: []
|
|
186
|
-
}
|
|
196
|
+
//#region src/config/bin.ts
|
|
197
|
+
const BIN_DRIVE = {
|
|
198
|
+
id: "powerhouse",
|
|
199
|
+
slug: "powerhouse",
|
|
200
|
+
global: {
|
|
201
|
+
name: "Powerhouse",
|
|
202
|
+
icon: DEFAULT_DRIVE_ICON
|
|
203
|
+
},
|
|
204
|
+
local: {
|
|
205
|
+
availableOffline: true,
|
|
206
|
+
listeners: [],
|
|
207
|
+
sharingType: "public",
|
|
208
|
+
triggers: []
|
|
187
209
|
}
|
|
188
210
|
};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
wall: {
|
|
199
|
-
samplingDurationMs: 1e4,
|
|
200
|
-
samplingIntervalMicros: 1e4,
|
|
201
|
-
collectCpuTime: true
|
|
202
|
-
},
|
|
203
|
-
heap: {
|
|
204
|
-
samplingIntervalBytes: 512 * 1024,
|
|
205
|
-
stackDepth: 64
|
|
206
|
-
}
|
|
207
|
-
}, {
|
|
208
|
-
wallEnabled: wallEnabled !== "false",
|
|
209
|
-
heapEnabled: heapEnabled === "true"
|
|
211
|
+
/** The bin's config: the config file's port, then the env, then the bin's own options. */
|
|
212
|
+
function binSwitchboardConfig(env, options) {
|
|
213
|
+
return callerOverEnv(mergeSwitchboardConfig({ server: { port: options.filePort } }, switchboardConfigFromEnv(env, {
|
|
214
|
+
bin: true,
|
|
215
|
+
logger: options.logger
|
|
216
|
+
})), {
|
|
217
|
+
features: { mcp: true },
|
|
218
|
+
drive: BIN_DRIVE,
|
|
219
|
+
storage: { migratePglite: options.migratePglite || void 0 }
|
|
210
220
|
});
|
|
211
221
|
}
|
|
212
|
-
async function initProfiler(options, flags = {
|
|
213
|
-
wallEnabled: true,
|
|
214
|
-
heapEnabled: false
|
|
215
|
-
}) {
|
|
216
|
-
console.log("Initializing Pyroscope profiler at:", options?.serverAddress);
|
|
217
|
-
console.log(" Wall profiling:", flags.wallEnabled ? "enabled" : "disabled");
|
|
218
|
-
console.log(" Heap profiling:", flags.heapEnabled ? "enabled" : "disabled");
|
|
219
|
-
const { default: Pyroscope } = await import("@pyroscope/nodejs");
|
|
220
|
-
Pyroscope.init(options);
|
|
221
|
-
if (flags.wallEnabled) Pyroscope.startWallProfiling();
|
|
222
|
-
Pyroscope.startCpuProfiling();
|
|
223
|
-
if (flags.heapEnabled) Pyroscope.startHeapProfiling();
|
|
224
|
-
}
|
|
225
222
|
//#endregion
|
|
226
223
|
//#region src/index.mts
|
|
227
224
|
const logger = childLogger(["switchboard"]);
|
|
@@ -243,14 +240,17 @@ if (process.env.PYROSCOPE_SERVER_ADDRESS) try {
|
|
|
243
240
|
}
|
|
244
241
|
const cliMigratePglite = process.argv.slice(2).includes("--migrate-pglite");
|
|
245
242
|
try {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
migratePglite: cliMigratePglite
|
|
249
|
-
forcePgVersion: config.forcePgVersion ?? void 0
|
|
243
|
+
const config = binSwitchboardConfig(process.env, {
|
|
244
|
+
filePort: getConfig().switchboard?.port,
|
|
245
|
+
migratePglite: cliMigratePglite
|
|
250
246
|
});
|
|
247
|
+
initSwitchboardProcess(config);
|
|
248
|
+
await startSwitchboard(config, { fatalErrorShutdown: true });
|
|
251
249
|
} catch (e) {
|
|
252
|
-
|
|
253
|
-
|
|
250
|
+
if (!StoredDocumentsRefusedError.isError(e)) {
|
|
251
|
+
Sentry.captureException(e);
|
|
252
|
+
logger.error("Switchboard failed to start: @error", e);
|
|
253
|
+
}
|
|
254
254
|
await Sentry.flush(2e3).catch(() => void 0);
|
|
255
255
|
process.exit(1);
|
|
256
256
|
}
|
|
@@ -258,4 +258,4 @@ try {
|
|
|
258
258
|
export {};
|
|
259
259
|
|
|
260
260
|
//# sourceMappingURL=index.mjs.map
|
|
261
|
-
//# debugId=
|
|
261
|
+
//# debugId=7918c19e-39da-5020-b8b3-e72a02c33357
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/metrics.ts","../src/redact-webhook-path.ts","../src/observability.mts","../src/config.ts","../src/profiler.ts","../src/index.mts"],"sourcesContent":["import { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-http\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport {\n MeterProvider,\n PeriodicExportingMetricReader,\n} from \"@opentelemetry/sdk-metrics\";\nimport { childLogger } from \"document-model\";\n\nconst logger = childLogger([\"switchboard\", \"metrics\"]);\n\nexport function createMeterProviderFromEnv(env: {\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_METRIC_EXPORT_INTERVAL?: string;\n OTEL_SERVICE_NAME?: string;\n}): MeterProvider | undefined {\n const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;\n if (!endpoint) return undefined;\n\n const parsed = parseInt(env.OTEL_METRIC_EXPORT_INTERVAL ?? \"\", 10);\n const exportIntervalMillis =\n Number.isFinite(parsed) && parsed > 0 ? parsed : 5_000;\n\n const base = endpoint.replace(/\\/$/, \"\");\n const exporterUrl = base.endsWith(\"/v1/metrics\")\n ? base\n : `${base}/v1/metrics`;\n\n logger.info(`Initializing OpenTelemetry metrics exporter at: ${endpoint}`);\n const meterProvider = new MeterProvider({\n resource: resourceFromAttributes({\n \"service.name\": env.OTEL_SERVICE_NAME ?? \"switchboard\",\n }),\n readers: [\n new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: exporterUrl,\n }),\n exportIntervalMillis,\n exportTimeoutMillis: Math.max(exportIntervalMillis - 250, 1),\n }),\n ],\n });\n logger.info(`Metrics export enabled (interval: ${exportIntervalMillis}ms)`);\n return meterProvider;\n}\n","const WEBHOOK_SEGMENT = \"/webhooks/\";\n\n/**\n * Strips a webhook's delivery token out of a request path.\n *\n * The token is the endpoint's whole credential and it sits in the path, so it\n * must not reach a log line or a span attribute that ships off-box. The family\n * mounts under the host's base path, so the segment can sit at any depth.\n */\nexport function redactWebhookPath(url: string | undefined): string {\n if (!url) return \"\";\n // Dropped with the token: `http.route` is meant to be a template, and a\n // query string is another place a sender can put a credential.\n const path = url.split(\"?\")[0] ?? url;\n const at = path.indexOf(WEBHOOK_SEGMENT);\n if (at === -1) return url;\n // Nothing after the segment is nothing to redact.\n if (path.length === at + WEBHOOK_SEGMENT.length) return url;\n return `${path.slice(0, at)}${WEBHOOK_SEGMENT}[redacted]`;\n}\n","// Single observability bootstrap: Sentry + OpenTelemetry (tracing + metrics).\n//\n// MUST be imported as the very first module in apps/switchboard/src/index.mts.\n// OpenTelemetry instrumentations register require-time hooks at module load,\n// so http/express/pg/graphql must not be imported (transitively) before this\n// file runs.\n//\n// Replaces three legacy bootstrap sites:\n// - apps/switchboard/src/server.mts top-level Sentry.init\n// - apps/switchboard/src/metrics.ts standalone MeterProvider (still exported\n// here via createMeterProviderFromEnv so its tests keep passing)\n// - packages/reactor-api/src/tracing.ts side-effect NodeSDK\nimport { metrics } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { ExpressInstrumentation } from \"@opentelemetry/instrumentation-express\";\nimport { GraphQLInstrumentation } from \"@opentelemetry/instrumentation-graphql\";\nimport { HttpInstrumentation } from \"@opentelemetry/instrumentation-http\";\nimport { PgInstrumentation } from \"@opentelemetry/instrumentation-pg\";\nimport { UndiciInstrumentation } from \"@opentelemetry/instrumentation-undici\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport type { MeterProvider } from \"@opentelemetry/sdk-metrics\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n BatchSpanProcessor,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n registerEventLoopInstrumentation,\n type EventLoopInstrumentation,\n} from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport * as Sentry from \"@sentry/node\";\nimport { SentryPropagator, SentrySpanProcessor } from \"@sentry/opentelemetry\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage } from \"node:http\";\nimport { createMeterProviderFromEnv } from \"./metrics.js\";\nimport { redactWebhookPath } from \"./redact-webhook-path.js\";\n\nconst logger = childLogger([\"switchboard\", \"observability\"]);\n\nconst SERVICE_NAME = process.env.OTEL_SERVICE_NAME || \"switchboard\";\nconst SERVICE_VERSION = process.env.npm_package_version || \"unknown\";\nconst TENANT_ID = process.env.TENANT_ID || \"default\";\nconst DEPLOY_ENV = process.env.NODE_ENV || \"development\";\n\nconst TEMPO_ENDPOINT = process.env.TEMPO_ENDPOINT;\nconst SENTRY_DSN = process.env.SENTRY_DSN;\n\n// Whether to forward TRANSACTIONS (spans) to Sentry. Errors are always sent\n// when SENTRY_DSN is set — this flag only gates APM/tracing into Sentry.\n// Default on (back-compat). Set SENTRY_TRACING_ENABLED=false for an\n// \"errors-only\" deployment: errors still go to Sentry, traces still go to\n// Tempo, but no transactions hit Sentry (no Kafka/ClickHouse/nodestore\n// cost). This is the recommended mode for tenant workloads at scale —\n// Sentry's value there is error grouping; traces live in Tempo.\nconst SENTRY_TRACING_TO_SENTRY =\n Boolean(SENTRY_DSN) && process.env.SENTRY_TRACING_ENABLED !== \"false\";\n\nconst TRACING_REQUESTED =\n process.env.ENABLE_TRACING === \"true\" ||\n process.env.NODE_ENV === \"production\";\nconst HAS_TRACE_DESTINATION = Boolean(TEMPO_ENDPOINT) || Boolean(SENTRY_DSN);\nconst TRACING_ENABLED = TRACING_REQUESTED && HAS_TRACE_DESTINATION;\n\nif (TRACING_REQUESTED && !HAS_TRACE_DESTINATION) {\n logger.warn(\n \"Tracing was requested (NODE_ENV=production or ENABLE_TRACING=true) but \" +\n \"no destination is configured — instrumentation will not run. Set \" +\n \"TEMPO_ENDPOINT (e.g. http://tempo.monitoring.svc.cluster.local:4318/v1/traces) \" +\n \"to export OTLP spans, and/or SENTRY_DSN to forward spans to Sentry.\",\n );\n}\n\n// APM sampling for the Sentry-SDK-managed path (i.e. when TRACING is OFF and\n// @sentry/node runs its own bundled OTel — see skipOpenTelemetrySetup below).\n//\n// IMPORTANT: when TRACING_ENABLED, this value does NOT govern span volume.\n// Our NodeSDK (below) owns the pipeline and is constructed with no explicit\n// `sampler`, so @opentelemetry/sdk-node falls back to buildSamplerFromEnv()\n// and the REAL head-sampling knob is the standard OTEL_TRACES_SAMPLER /\n// OTEL_TRACES_SAMPLER_ARG env (set per-deploy in the k8s chart). That head\n// decision gates spans before any processor runs, so it bounds BOTH the\n// SentrySpanProcessor (→ Sentry transactions) and the Tempo OTLP export.\n// (Wiring @sentry/opentelemetry's SentrySampler here would let this rate\n// drive both backends and make DSC/sample_rand propagation spec-correct, but\n// that only matters for Sentry server-side dynamic sampling — a SaaS feature\n// our self-hosted install doesn't run — so it's intentionally deferred.)\nconst SENTRY_TRACES_SAMPLE_RATE = parseFloat(\n process.env.SENTRY_TRACES_SAMPLE_RATE ?? \"0.1\",\n);\n\nif (SENTRY_DSN) {\n logger.info(\"Initialized Sentry with env: @env\", process.env.SENTRY_ENV);\n Sentry.init({\n dsn: SENTRY_DSN,\n environment: process.env.SENTRY_ENV,\n // Match the version tag uploaded by release-branch.yml so source maps\n // resolve. Populated by the CI (WORKSPACE_VERSION) or npm at runtime.\n release:\n process.env.SENTRY_RELEASE ||\n (process.env.npm_package_version\n ? `v${process.env.npm_package_version}`\n : undefined),\n // 0 in errors-only mode so even @sentry/node's bundled auto-OTel path\n // (used when TRACING_ENABLED is false) produces no transactions.\n tracesSampleRate: SENTRY_TRACING_TO_SENTRY ? SENTRY_TRACES_SAMPLE_RATE : 0,\n // When tracing is on, our NodeSDK below owns the OTel globals and Sentry\n // receives spans via SentrySpanProcessor. Skipping Sentry's bundled OTel\n // setup avoids two TracerProviders fighting over setGlobalTracerProvider.\n // When tracing is off, leave the flag unset so @sentry/node's default\n // auto-OTel still records HTTP transactions for the APM dashboard.\n skipOpenTelemetrySetup: TRACING_ENABLED,\n });\n}\n\nconst meterProvider: MeterProvider | undefined = createMeterProviderFromEnv({\n OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,\n OTEL_METRIC_EXPORT_INTERVAL: process.env.OTEL_METRIC_EXPORT_INTERVAL,\n OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,\n});\nlet eventLoopInstrumentation: EventLoopInstrumentation | undefined;\nif (meterProvider) {\n // One-way door: must register before any code calls metrics.getMeter() —\n // most notably ReactorInstrumentation inside the reactor module.\n metrics.setGlobalMeterProvider(meterProvider);\n // Host event-loop and CPU gauges (reactor.host.eventloop.*,\n // reactor.host.cpu.utilization). The bench sweep identified the host event\n // loop, not the executor, as the binding constraint on write throughput\n // (bench/test/integration/BASELINE.md, Run 10) — these are the production\n // counterpart of the metrics that finding was made from. Must come after\n // setGlobalMeterProvider or the gauges bind to a no-op meter.\n eventLoopInstrumentation = registerEventLoopInstrumentation();\n}\n\nlet sdk: NodeSDK | undefined;\n\nif (TRACING_ENABLED) {\n logger.info(`Initializing OpenTelemetry tracing for ${SERVICE_NAME}`);\n if (TEMPO_ENDPOINT) logger.info(` Tempo endpoint: ${TEMPO_ENDPOINT}`);\n if (SENTRY_DSN) logger.info(` Sentry span forwarding: enabled`);\n logger.info(` Tenant: ${TENANT_ID}`);\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: SERVICE_NAME,\n [ATTR_SERVICE_VERSION]: SERVICE_VERSION,\n \"tenant.id\": TENANT_ID,\n \"deployment.environment\": DEPLOY_ENV,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n if (TEMPO_ENDPOINT) {\n spanProcessors.push(\n new BatchSpanProcessor(new OTLPTraceExporter({ url: TEMPO_ENDPOINT })),\n );\n }\n if (SENTRY_TRACING_TO_SENTRY) {\n // Fan the same OTel spans into Sentry — same trace IDs as Tempo, so\n // Sentry transactions cross-link to traces in Grafana. Skipped in\n // errors-only mode (SENTRY_TRACING_ENABLED=false): spans still flow to\n // Tempo via the BatchSpanProcessor above, just not to Sentry.\n spanProcessors.push(new SentrySpanProcessor());\n }\n\n sdk = new NodeSDK({\n resource,\n spanProcessors,\n textMapPropagator: SENTRY_TRACING_TO_SENTRY\n ? new SentryPropagator()\n : undefined,\n instrumentations: [\n new HttpInstrumentation({\n ignoreIncomingRequestHook: (req) =>\n req.url === \"/health\" || req.url === \"/ready\",\n requireParentforIncomingSpans: false,\n requireParentforOutgoingSpans: false,\n requestHook: (span, request) => {\n span.setAttribute(\n \"http.route\",\n redactWebhookPath((request as IncomingMessage).url),\n );\n },\n responseHook: (span, response) => {\n if (response.statusCode) {\n span.setAttribute(\"http.status_code\", response.statusCode);\n }\n },\n }),\n new ExpressInstrumentation({\n requestHook: (span, info) => {\n if (info.route) span.setAttribute(\"http.route\", info.route);\n },\n }),\n // HttpInstrumentation only patches node:http/https; outbound global\n // fetch() goes through undici and is otherwise untraced — e.g. the\n // per-request Renown credential check in AuthService.verifyCredentialExists.\n new UndiciInstrumentation(),\n new GraphQLInstrumentation({ mergeItems: true, allowValues: true }),\n // requireParentSpan: only trace DB queries that run inside a request\n // (HTTP/GraphQL) span. Parentless queries — the management\n // switchboard's background polling loops (vetra-cloud-observability\n // reconcile @60s + clint pull-worker @15s, each writing\n // environment_pods / clint_runtime_endpoints) — would otherwise each\n // become a standalone root transaction. That volume scales O(tenant\n // count) and was ~70% of all Sentry transactions before this change.\n // Dropping it at the instrumentation layer (no span created at all) is\n // cheaper and cleaner than sampling it away downstream.\n new PgInstrumentation({\n enhancedDatabaseReporting: true,\n requireParentSpan: true,\n }),\n ],\n });\n sdk.start();\n if (\n SENTRY_TRACING_TO_SENTRY &&\n typeof Sentry.validateOpenTelemetrySetup === \"function\"\n ) {\n Sentry.validateOpenTelemetrySetup();\n }\n logger.info(\"OpenTelemetry tracing initialized\");\n}\n\nasync function shutdown() {\n // Detach the observable callback before the provider drains, so the final\n // export does not fire a gauge callback against a shutting-down meter.\n eventLoopInstrumentation?.stop();\n await Promise.race([\n Promise.all([\n meterProvider?.shutdown().catch(() => undefined),\n sdk?.shutdown().catch(() => undefined),\n ]),\n new Promise<void>((resolve) => setTimeout(resolve, 5_000)),\n ]);\n}\n\nprocess.on(\"SIGINT\", () => {\n void shutdown().finally(() => process.exit(0));\n});\nprocess.on(\"SIGTERM\", () => {\n void shutdown().finally(() => process.exit(0));\n});\n\nexport { meterProvider, sdk };\n","import dotenv from \"dotenv\";\ndotenv.config();\n\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { parseForcePgVersion } from \"./pglite-version.js\";\nimport type {\n SwitchboardDriveDocumentType,\n SwitchboardDriveInput,\n} from \"./types.js\";\nconst phConfig = getConfig();\nconst { switchboard } = phConfig;\ninterface Config {\n database: {\n url: string;\n };\n port: number;\n mcp: boolean;\n migratePglite: boolean;\n forcePgVersion: 16 | 17 | null;\n drive: SwitchboardDriveInput;\n}\n\nfunction parseDriveType(\n raw: string | undefined,\n): SwitchboardDriveDocumentType | undefined {\n if (!raw) return undefined;\n if (raw === \"powerhouse/document-drive\" || raw === \"powerhouse/reactor-drive\")\n return raw;\n throw new Error(\n `Invalid PH_DEFAULT_DRIVE_TYPE: ${raw}. Expected \"powerhouse/document-drive\" or \"powerhouse/reactor-drive\".`,\n );\n}\n\nexport const config: Config = {\n database: {\n // url: process.env.PH_SWITCHBOARD_DATABASE_URL ?? switchboard?.database?.url ?? \"dev.db\",\n url:\n process.env.PH_SWITCHBOARD_DATABASE_URL ??\n switchboard?.database?.url ??\n \"dev.db\",\n },\n port:\n process.env.PH_SWITCHBOARD_PORT &&\n !isNaN(Number(process.env.PH_SWITCHBOARD_PORT))\n ? Number(process.env.PH_SWITCHBOARD_PORT)\n : (switchboard?.port ?? 4001),\n mcp: true,\n migratePglite: process.env.PH_MIGRATE_PGLITE === \"true\",\n forcePgVersion: parseForcePgVersion(process.env.PH_FORCE_PG_VERSION),\n drive: {\n id: \"powerhouse\",\n slug: \"powerhouse\",\n documentType: parseDriveType(process.env.PH_DEFAULT_DRIVE_TYPE),\n global: {\n name: \"Powerhouse\",\n icon: \"https://ipfs.io/ipfs/QmcaTDBYn8X2psGaXe7iQ6qd8q6oqHLgxvMX9yXf7f9uP7\",\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n};\n","import type { PyroscopeConfig } from \"@pyroscope/nodejs\";\n\nexport async function initProfilerFromEnv(env: typeof process.env) {\n const {\n PYROSCOPE_SERVER_ADDRESS: serverAddress,\n PYROSCOPE_APPLICATION_NAME: appName,\n PYROSCOPE_USER: basicAuthUser,\n PYROSCOPE_PASSWORD: basicAuthPassword,\n PYROSCOPE_WALL_ENABLED: wallEnabled,\n PYROSCOPE_HEAP_ENABLED: heapEnabled,\n } = env;\n\n const options: PyroscopeConfig = {\n serverAddress,\n appName,\n basicAuthUser,\n basicAuthPassword,\n // Wall profiling captures wall-clock time (includes async I/O waits)\n // This shows GraphQL resolvers even when waiting for database\n wall: {\n samplingDurationMs: 10000, // 10 second sampling windows\n samplingIntervalMicros: 10000, // 10ms sampling interval (100 samples/sec)\n collectCpuTime: true, // Also collect CPU time alongside wall time\n },\n // Heap profiling for memory allocation tracking\n heap: {\n samplingIntervalBytes: 512 * 1024, // Sample every 512KB allocated\n stackDepth: 64, // Capture deeper stacks for better context\n },\n };\n return initProfiler(options, {\n wallEnabled: wallEnabled !== \"false\",\n heapEnabled: heapEnabled === \"true\",\n });\n}\n\ninterface ProfilerFlags {\n wallEnabled?: boolean;\n heapEnabled?: boolean;\n}\n\nexport async function initProfiler(\n options?: PyroscopeConfig,\n flags: ProfilerFlags = { wallEnabled: true, heapEnabled: false },\n) {\n console.log(\"Initializing Pyroscope profiler at:\", options?.serverAddress);\n console.log(\" Wall profiling:\", flags.wallEnabled ? \"enabled\" : \"disabled\");\n console.log(\" Heap profiling:\", flags.heapEnabled ? \"enabled\" : \"disabled\");\n\n const { default: Pyroscope } = await import(\"@pyroscope/nodejs\");\n Pyroscope.init(options);\n\n // Start wall profiling (captures async I/O time - shows resolvers)\n if (flags.wallEnabled) {\n Pyroscope.startWallProfiling();\n }\n\n // Start CPU profiling (captures CPU-bound work)\n Pyroscope.startCpuProfiling();\n\n // Optionally start heap profiling (memory allocations)\n if (flags.heapEnabled) {\n Pyroscope.startHeapProfiling();\n }\n}\n","#!/usr/bin/env node\n// Observability MUST load before any module that imports http/express/pg/graphql\n// so OpenTelemetry's require-time hooks can patch them. It also owns Sentry\n// init and the SIGINT/SIGTERM flush.\nimport \"./observability.mjs\";\n\nimport * as Sentry from \"@sentry/node\";\nimport { childLogger } from \"document-model\";\nimport { config } from \"./config.js\";\nimport { initProfilerFromEnv } from \"./profiler.js\";\nimport { startSwitchboard } from \"./server.mjs\";\n\nconst logger = childLogger([\"switchboard\"]);\n\nfunction ensureNodeVersion(minVersion = \"24\") {\n const version = process.versions.node;\n if (!version) {\n return;\n }\n\n if (version < minVersion) {\n console.error(\n `Node version ${minVersion} or higher is required. Current version: ${version}`,\n );\n process.exit(1);\n }\n}\n// Ensure minimum Node.js version\nensureNodeVersion(\"24\");\n\n// Each subgraph registers its own SIGINT/SIGTERM listeners, and the count\n// scales with dynamically-loaded document models beyond the default cap of 10.\nprocess.setMaxListeners(0);\n\nif (process.env.PYROSCOPE_SERVER_ADDRESS) {\n try {\n await initProfilerFromEnv(process.env);\n } catch (e) {\n Sentry.captureException(e);\n logger.error(\"Error starting profiler: @error\", e);\n }\n}\n\nconst cliMigratePglite = process.argv.slice(2).includes(\"--migrate-pglite\");\n\n// A boot failure leaves no serving process behind, so it must exit non-zero:\n// logging and continuing hides a dead switchboard from the supervisor, which\n// would otherwise never restart it.\ntry {\n await startSwitchboard({\n ...config,\n migratePglite: cliMigratePglite || config.migratePglite,\n forcePgVersion: config.forcePgVersion ?? undefined,\n });\n} catch (e) {\n Sentry.captureException(e);\n logger.error(\"Switchboard failed to start: @error\", e);\n await Sentry.flush(2000).catch(() => undefined);\n process.exit(1);\n}\n"],"names":["logger","logger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAMA,WAAS,YAAY,CAAC,eAAe,UAAU,CAAC;AAEtD,SAAgB,2BAA2B,KAIb;CAC5B,MAAM,WAAW,IAAI;AACrB,KAAI,CAAC,SAAU,QAAO,KAAA;CAEtB,MAAM,SAAS,SAAS,IAAI,+BAA+B,IAAI,GAAG;CAClE,MAAM,uBACJ,OAAO,SAAS,OAAO,IAAI,SAAS,IAAI,SAAS;CAEnD,MAAM,OAAO,SAAS,QAAQ,OAAO,GAAG;CACxC,MAAM,cAAc,KAAK,SAAS,cAAc,GAC5C,OACA,GAAG,KAAK;AAEZ,UAAO,KAAK,mDAAmD,WAAW;CAC1E,MAAM,gBAAgB,IAAI,cAAc;EACtC,UAAU,uBAAuB,EAC/B,gBAAgB,IAAI,qBAAqB,eAC1C,CAAC;EACF,SAAS,CACP,IAAI,8BAA8B;GAChC,UAAU,IAAI,mBAAmB,EAC/B,KAAK,aACN,CAAC;GACF;GACA,qBAAqB,KAAK,IAAI,uBAAuB,KAAK,EAAE;GAC7D,CAAC,CACH;EACF,CAAC;AACF,UAAO,KAAK,qCAAqC,qBAAqB,KAAK;AAC3E,QAAO;;;;AC3CT,MAAM,kBAAkB;;;;;;;;AASxB,SAAgB,kBAAkB,KAAiC;AACjE,KAAI,CAAC,IAAK,QAAO;CAGjB,MAAM,OAAO,IAAI,MAAM,IAAI,CAAC,MAAM;CAClC,MAAM,KAAK,KAAK,QAAQ,gBAAgB;AACxC,KAAI,OAAO,GAAI,QAAO;AAEtB,KAAI,KAAK,WAAW,KAAK,GAAwB,QAAO;AACxD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;AAC/C,SAAQ,KAAK,EAAE","debug_id":"c6c10af1-f4cc-56a5-abf6-fa35cf0de956"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/metrics.ts","../src/observability-signals.mts","../src/redact-webhook-path.ts","../src/observability.mts","../src/config/bin.ts","../src/index.mts"],"sourcesContent":["import { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-http\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport {\n MeterProvider,\n PeriodicExportingMetricReader,\n} from \"@opentelemetry/sdk-metrics\";\nimport { childLogger } from \"document-model\";\n\nconst logger = childLogger([\"switchboard\", \"metrics\"]);\n\nexport function createMeterProviderFromEnv(env: {\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_METRIC_EXPORT_INTERVAL?: string;\n OTEL_SERVICE_NAME?: string;\n}): MeterProvider | undefined {\n const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;\n if (!endpoint) return undefined;\n\n const parsed = parseInt(env.OTEL_METRIC_EXPORT_INTERVAL ?? \"\", 10);\n const exportIntervalMillis =\n Number.isFinite(parsed) && parsed > 0 ? parsed : 5_000;\n\n const base = endpoint.replace(/\\/$/, \"\");\n const exporterUrl = base.endsWith(\"/v1/metrics\")\n ? base\n : `${base}/v1/metrics`;\n\n logger.info(`Initializing OpenTelemetry metrics exporter at: ${endpoint}`);\n const meterProvider = new MeterProvider({\n resource: resourceFromAttributes({\n \"service.name\": env.OTEL_SERVICE_NAME ?? \"switchboard\",\n }),\n readers: [\n new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: exporterUrl,\n }),\n exportIntervalMillis,\n exportTimeoutMillis: Math.max(exportIntervalMillis - 250, 1),\n }),\n ],\n });\n logger.info(`Metrics export enabled (interval: ${exportIntervalMillis}ms)`);\n return meterProvider;\n}\n","// Signal handling for the observability bootstrap, split out of\n// observability.mts so tests can exercise it without importing the module\n// whose load-time side effects start Sentry and OpenTelemetry.\n\ntype SignalProcess = Pick<NodeJS.Process, \"on\" | \"exit\"> & {\n exitCode?: NodeJS.Process[\"exitCode\"];\n};\n\n/**\n * Flushes telemetry on SIGINT/SIGTERM, then exits only when no other module\n * has claimed a failing exit.\n *\n * Exit ownership, decided here on purpose:\n *\n * - Ordinary signal (process.exitCode unset or 0): this handler exits with\n * the current exit code after the flush settles (the flush bounds itself,\n * see shutdown() in observability.mts). When the reactor builder's drain\n * handler is also attached it runs first (prependListener) and swaps\n * process.exit for a recording shim before this handler's exit call, so\n * the drain still finishes and performs the real exit; when the builder is\n * not attached (startup, signalHandlers: false), this exit is what\n * terminates the process, with code 0.\n *\n * - Fatal shutdown in progress (process.exitCode already non-zero):\n * fatal-shutdown.mts sets exitCode = 1 and arms a 15s forced exit BEFORE\n * raising SIGTERM, precisely so the builder's drain can flush the PGlite\n * snapshots. Calling exit here would lower that code to 0 (supervisors\n * would see a crash as success) and, whenever the builder's shim is not in\n * place, cut the drain off at this handler's shorter flush budget. So this\n * handler never exits once a non-zero code is set: the exit belongs to the\n * builder's drain, or failing that to fatal-shutdown's 15s backstop, both\n * of which preserve code 1.\n */\nexport function installObservabilitySignalHandlers(\n flush: () => Promise<void>,\n proc: SignalProcess = process,\n): void {\n const onSignal = () => {\n void flush().finally(() => {\n const code = proc.exitCode;\n if (code !== undefined && code !== 0) {\n return;\n }\n proc.exit(code ?? 0);\n });\n };\n proc.on(\"SIGINT\", onSignal);\n proc.on(\"SIGTERM\", onSignal);\n}\n","// Segments followed by a token that is the request's whole credential:\n// a webhook's delivery token, a waitpoint's resume token.\nconst TOKEN_SEGMENTS = [\"/webhooks/\", \"/waitpoints/\"];\n\n/**\n * Strips a webhook's delivery token out of a request path.\n *\n * The token is the endpoint's whole credential and it sits in the path, so it\n * must not reach a log line or a span attribute that ships off-box. The family\n * mounts under the host's base path, so the segment can sit at any depth.\n */\nexport function redactWebhookPath(url: string | undefined): string {\n if (!url) return \"\";\n // Dropped with the token: `http.route` is meant to be a template, and a\n // query string is another place a sender can put a credential.\n const path = url.split(\"?\")[0] ?? url;\n for (const segment of TOKEN_SEGMENTS) {\n const at = path.indexOf(segment);\n if (at === -1) continue;\n // Nothing after the segment is nothing to redact.\n if (path.length === at + segment.length) return url;\n return `${path.slice(0, at)}${segment}[redacted]`;\n }\n return url;\n}\n","// Single observability bootstrap: Sentry + OpenTelemetry (tracing + metrics).\n//\n// MUST be imported as the very first module in apps/switchboard/src/index.mts.\n// OpenTelemetry instrumentations register require-time hooks at module load,\n// so http/express/pg/graphql must not be imported (transitively) before this\n// file runs.\n//\n// Replaces three legacy bootstrap sites:\n// - apps/switchboard/src/server.mts top-level Sentry.init\n// - apps/switchboard/src/metrics.ts standalone MeterProvider (still exported\n// here via createMeterProviderFromEnv so its tests keep passing)\n// - packages/reactor-api/src/tracing.ts side-effect NodeSDK\nimport { metrics } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { ExpressInstrumentation } from \"@opentelemetry/instrumentation-express\";\nimport { GraphQLInstrumentation } from \"@opentelemetry/instrumentation-graphql\";\nimport { HttpInstrumentation } from \"@opentelemetry/instrumentation-http\";\nimport { PgInstrumentation } from \"@opentelemetry/instrumentation-pg\";\nimport { UndiciInstrumentation } from \"@opentelemetry/instrumentation-undici\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport type { MeterProvider } from \"@opentelemetry/sdk-metrics\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n BatchSpanProcessor,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n registerEventLoopInstrumentation,\n type EventLoopInstrumentation,\n} from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport * as Sentry from \"@sentry/node\";\nimport { SentryPropagator, SentrySpanProcessor } from \"@sentry/opentelemetry\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage } from \"node:http\";\nimport { createMeterProviderFromEnv } from \"./metrics.js\";\nimport { installObservabilitySignalHandlers } from \"./observability-signals.mjs\";\nimport { redactWebhookPath } from \"./redact-webhook-path.js\";\n\nconst logger = childLogger([\"switchboard\", \"observability\"]);\n\nconst SERVICE_NAME = process.env.OTEL_SERVICE_NAME || \"switchboard\";\nconst SERVICE_VERSION = process.env.npm_package_version || \"unknown\";\nconst TENANT_ID = process.env.TENANT_ID || \"default\";\nconst DEPLOY_ENV = process.env.NODE_ENV || \"development\";\n\nconst TEMPO_ENDPOINT = process.env.TEMPO_ENDPOINT;\nconst SENTRY_DSN = process.env.SENTRY_DSN;\n\n// Whether to forward TRANSACTIONS (spans) to Sentry. Errors are always sent\n// when SENTRY_DSN is set — this flag only gates APM/tracing into Sentry.\n// Default on (back-compat). Set SENTRY_TRACING_ENABLED=false for an\n// \"errors-only\" deployment: errors still go to Sentry, traces still go to\n// Tempo, but no transactions hit Sentry (no Kafka/ClickHouse/nodestore\n// cost). This is the recommended mode for tenant workloads at scale —\n// Sentry's value there is error grouping; traces live in Tempo.\nconst SENTRY_TRACING_TO_SENTRY =\n Boolean(SENTRY_DSN) && process.env.SENTRY_TRACING_ENABLED !== \"false\";\n\nconst TRACING_REQUESTED =\n process.env.ENABLE_TRACING === \"true\" ||\n process.env.NODE_ENV === \"production\";\nconst HAS_TRACE_DESTINATION = Boolean(TEMPO_ENDPOINT) || Boolean(SENTRY_DSN);\nconst TRACING_ENABLED = TRACING_REQUESTED && HAS_TRACE_DESTINATION;\n\nif (TRACING_REQUESTED && !HAS_TRACE_DESTINATION) {\n logger.warn(\n \"Tracing was requested (NODE_ENV=production or ENABLE_TRACING=true) but \" +\n \"no destination is configured — instrumentation will not run. Set \" +\n \"TEMPO_ENDPOINT (e.g. http://tempo.monitoring.svc.cluster.local:4318/v1/traces) \" +\n \"to export OTLP spans, and/or SENTRY_DSN to forward spans to Sentry.\",\n );\n}\n\n// APM sampling for the Sentry-SDK-managed path (i.e. when TRACING is OFF and\n// @sentry/node runs its own bundled OTel — see skipOpenTelemetrySetup below).\n//\n// IMPORTANT: when TRACING_ENABLED, this value does NOT govern span volume.\n// Our NodeSDK (below) owns the pipeline and is constructed with no explicit\n// `sampler`, so @opentelemetry/sdk-node falls back to buildSamplerFromEnv()\n// and the REAL head-sampling knob is the standard OTEL_TRACES_SAMPLER /\n// OTEL_TRACES_SAMPLER_ARG env (set per-deploy in the k8s chart). That head\n// decision gates spans before any processor runs, so it bounds BOTH the\n// SentrySpanProcessor (→ Sentry transactions) and the Tempo OTLP export.\n// (Wiring @sentry/opentelemetry's SentrySampler here would let this rate\n// drive both backends and make DSC/sample_rand propagation spec-correct, but\n// that only matters for Sentry server-side dynamic sampling — a SaaS feature\n// our self-hosted install doesn't run — so it's intentionally deferred.)\nconst SENTRY_TRACES_SAMPLE_RATE = parseFloat(\n process.env.SENTRY_TRACES_SAMPLE_RATE ?? \"0.1\",\n);\n\nif (SENTRY_DSN) {\n logger.info(\"Initialized Sentry with env: @env\", process.env.SENTRY_ENV);\n Sentry.init({\n dsn: SENTRY_DSN,\n environment: process.env.SENTRY_ENV,\n // Match the version tag uploaded by release-branch.yml so source maps\n // resolve. Populated by the CI (WORKSPACE_VERSION) or npm at runtime.\n release:\n process.env.SENTRY_RELEASE ||\n (process.env.npm_package_version\n ? `v${process.env.npm_package_version}`\n : undefined),\n // 0 in errors-only mode so even @sentry/node's bundled auto-OTel path\n // (used when TRACING_ENABLED is false) produces no transactions.\n tracesSampleRate: SENTRY_TRACING_TO_SENTRY ? SENTRY_TRACES_SAMPLE_RATE : 0,\n // When tracing is on, our NodeSDK below owns the OTel globals and Sentry\n // receives spans via SentrySpanProcessor. Skipping Sentry's bundled OTel\n // setup avoids two TracerProviders fighting over setGlobalTracerProvider.\n // When tracing is off, leave the flag unset so @sentry/node's default\n // auto-OTel still records HTTP transactions for the APM dashboard.\n skipOpenTelemetrySetup: TRACING_ENABLED,\n });\n}\n\nconst meterProvider: MeterProvider | undefined = createMeterProviderFromEnv({\n OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,\n OTEL_METRIC_EXPORT_INTERVAL: process.env.OTEL_METRIC_EXPORT_INTERVAL,\n OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,\n});\nlet eventLoopInstrumentation: EventLoopInstrumentation | undefined;\nif (meterProvider) {\n // One-way door: must register before any code calls metrics.getMeter() —\n // most notably ReactorInstrumentation inside the reactor module.\n metrics.setGlobalMeterProvider(meterProvider);\n // Host event-loop and CPU gauges (reactor.host.eventloop.*,\n // reactor.host.cpu.utilization). The bench sweep identified the host event\n // loop, not the executor, as the binding constraint on write throughput\n // (bench/test/integration/BASELINE.md, Run 10) — these are the production\n // counterpart of the metrics that finding was made from. Must come after\n // setGlobalMeterProvider or the gauges bind to a no-op meter.\n eventLoopInstrumentation = registerEventLoopInstrumentation();\n}\n\nlet sdk: NodeSDK | undefined;\n\nif (TRACING_ENABLED) {\n logger.info(`Initializing OpenTelemetry tracing for ${SERVICE_NAME}`);\n if (TEMPO_ENDPOINT) logger.info(` Tempo endpoint: ${TEMPO_ENDPOINT}`);\n if (SENTRY_DSN) logger.info(` Sentry span forwarding: enabled`);\n logger.info(` Tenant: ${TENANT_ID}`);\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: SERVICE_NAME,\n [ATTR_SERVICE_VERSION]: SERVICE_VERSION,\n \"tenant.id\": TENANT_ID,\n \"deployment.environment\": DEPLOY_ENV,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n if (TEMPO_ENDPOINT) {\n spanProcessors.push(\n new BatchSpanProcessor(new OTLPTraceExporter({ url: TEMPO_ENDPOINT })),\n );\n }\n if (SENTRY_TRACING_TO_SENTRY) {\n // Fan the same OTel spans into Sentry — same trace IDs as Tempo, so\n // Sentry transactions cross-link to traces in Grafana. Skipped in\n // errors-only mode (SENTRY_TRACING_ENABLED=false): spans still flow to\n // Tempo via the BatchSpanProcessor above, just not to Sentry.\n spanProcessors.push(new SentrySpanProcessor());\n }\n\n sdk = new NodeSDK({\n resource,\n spanProcessors,\n textMapPropagator: SENTRY_TRACING_TO_SENTRY\n ? new SentryPropagator()\n : undefined,\n instrumentations: [\n new HttpInstrumentation({\n ignoreIncomingRequestHook: (req) =>\n req.url === \"/health\" || req.url === \"/ready\",\n requireParentforIncomingSpans: false,\n requireParentforOutgoingSpans: false,\n requestHook: (span, request) => {\n span.setAttribute(\n \"http.route\",\n redactWebhookPath((request as IncomingMessage).url),\n );\n },\n responseHook: (span, response) => {\n if (response.statusCode) {\n span.setAttribute(\"http.status_code\", response.statusCode);\n }\n },\n }),\n new ExpressInstrumentation({\n requestHook: (span, info) => {\n if (info.route) span.setAttribute(\"http.route\", info.route);\n },\n }),\n // HttpInstrumentation only patches node:http/https; outbound global\n // fetch() goes through undici and is otherwise untraced — e.g. the\n // per-request Renown credential check in AuthService.verifyCredentialExists.\n new UndiciInstrumentation(),\n new GraphQLInstrumentation({ mergeItems: true, allowValues: true }),\n // requireParentSpan: only trace DB queries that run inside a request\n // (HTTP/GraphQL) span. Parentless queries — the management\n // switchboard's background polling loops (vetra-cloud-observability\n // reconcile @60s + clint pull-worker @15s, each writing\n // environment_pods / clint_runtime_endpoints) — would otherwise each\n // become a standalone root transaction. That volume scales O(tenant\n // count) and was ~70% of all Sentry transactions before this change.\n // Dropping it at the instrumentation layer (no span created at all) is\n // cheaper and cleaner than sampling it away downstream.\n new PgInstrumentation({\n enhancedDatabaseReporting: true,\n requireParentSpan: true,\n }),\n ],\n });\n sdk.start();\n if (\n SENTRY_TRACING_TO_SENTRY &&\n typeof Sentry.validateOpenTelemetrySetup === \"function\"\n ) {\n Sentry.validateOpenTelemetrySetup();\n }\n logger.info(\"OpenTelemetry tracing initialized\");\n}\n\nasync function shutdown() {\n // Detach the observable callback before the provider drains, so the final\n // export does not fire a gauge callback against a shutting-down meter.\n eventLoopInstrumentation?.stop();\n await Promise.race([\n Promise.all([\n meterProvider?.shutdown().catch(() => undefined),\n sdk?.shutdown().catch(() => undefined),\n ]),\n new Promise<void>((resolve) => setTimeout(resolve, 5_000)),\n ]);\n}\n\n// Exit-code and drain coordination with fatal-shutdown.mts and the reactor\n// builder lives in observability-signals.mts; the earlier inline handlers\n// exited with a literal 0, which turned a fatal crash (exitCode = 1) into a\n// success in the supervisor's eyes and could cut the snapshot drain short.\ninstallObservabilitySignalHandlers(shutdown);\n\nexport { meterProvider, sdk };\n","import { DEFAULT_DRIVE_ICON } from \"@powerhousedao/shared/clis\";\nimport type { ILogger } from \"document-model\";\nimport { switchboardConfigFromEnv } from \"./from-env.js\";\nimport { callerOverEnv, mergeSwitchboardConfig } from \"./merge.js\";\nimport type { SwitchboardConfigInput } from \"./schema.js\";\n\nconst BIN_DRIVE = {\n id: \"powerhouse\",\n slug: \"powerhouse\",\n global: { name: \"Powerhouse\", icon: DEFAULT_DRIVE_ICON },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n};\n\n/** The bin's config: the config file's port, then the env, then the bin's own options. */\nexport function binSwitchboardConfig(\n env: Readonly<Record<string, string | undefined>>,\n options: {\n /** powerhouse.config.json `switchboard.port`. */\n filePort?: number;\n /** The `--migrate-pglite` flag. */\n migratePglite: boolean;\n logger?: ILogger;\n },\n): SwitchboardConfigInput {\n return callerOverEnv(\n mergeSwitchboardConfig(\n { server: { port: options.filePort } },\n switchboardConfigFromEnv(env, { bin: true, logger: options.logger }),\n ),\n {\n features: { mcp: true },\n drive: BIN_DRIVE,\n storage: { migratePglite: options.migratePglite || undefined },\n },\n );\n}\n","#!/usr/bin/env node\n// Observability MUST load before any module that imports http/express/pg/graphql\n// so OpenTelemetry's require-time hooks can patch them. It also owns Sentry\n// init and the SIGINT/SIGTERM flush.\nimport \"./observability.mjs\";\n\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport * as Sentry from \"@sentry/node\";\nimport { childLogger } from \"document-model\";\nimport { binSwitchboardConfig } from \"./config/bin.js\";\nimport { initProfilerFromEnv } from \"./profiler.js\";\nimport { initSwitchboardProcess, startSwitchboard } from \"./server.mjs\";\nimport { StoredDocumentsRefusedError } from \"./unsupported-stored-documents.mjs\";\n\nconst logger = childLogger([\"switchboard\"]);\n\nfunction ensureNodeVersion(minVersion = \"24\") {\n const version = process.versions.node;\n if (!version) {\n return;\n }\n\n if (version < minVersion) {\n console.error(\n `Node version ${minVersion} or higher is required. Current version: ${version}`,\n );\n process.exit(1);\n }\n}\n// Ensure minimum Node.js version\nensureNodeVersion(\"24\");\n\n// Each subgraph registers its own SIGINT/SIGTERM listeners, and the count\n// scales with dynamically-loaded document models beyond the default cap of 10.\nprocess.setMaxListeners(0);\n\nif (process.env.PYROSCOPE_SERVER_ADDRESS) {\n try {\n await initProfilerFromEnv(process.env);\n } catch (e) {\n Sentry.captureException(e);\n logger.error(\"Error starting profiler: @error\", e);\n }\n}\n\nconst cliMigratePglite = process.argv.slice(2).includes(\"--migrate-pglite\");\n\n// A boot failure leaves no serving process behind, so it must exit non-zero:\n// logging and continuing hides a dead switchboard from the supervisor, which\n// would otherwise never restart it.\ntry {\n const config = binSwitchboardConfig(process.env, {\n filePort: getConfig().switchboard?.port,\n migratePglite: cliMigratePglite,\n });\n initSwitchboardProcess(config);\n await startSwitchboard(config, { fatalErrorShutdown: true });\n} catch (e) {\n // startSwitchboard already reported a refusal to the operator.\n if (!StoredDocumentsRefusedError.isError(e)) {\n Sentry.captureException(e);\n logger.error(\"Switchboard failed to start: @error\", e);\n }\n await Sentry.flush(2000).catch(() => undefined);\n process.exit(1);\n}\n"],"names":["logger","logger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAMA,WAAS,YAAY,CAAC,eAAe,SAAS,CAAC;AAErD,SAAgB,2BAA2B,KAIb;CAC5B,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,UAAU,OAAO,KAAA;CAEtB,MAAM,SAAS,SAAS,IAAI,+BAA+B,IAAI,EAA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K,CAAC;AAC7D,SAAS,GAAG;CAEV,IAAI,CAAC,4BAA4B,QAAQ,CAAC,GAAG;EAC3C,OAAO,iBAAiB,CAAC;EACzB,OAAO,MAAM,uCAAuC,CAAC;CACvD;CACA,MAAM,OAAO,MAAM,GAAI,CAAC,CAAC,YAAY,KAAA,CAAS;CAC9C,QAAQ,KAAK,CAAC;AAChB","debug_id":"7918c19e-39da-5020-b8b3-e72a02c33357"}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
|
2
|
+
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="58dbe86a-e88c-57d1-9ab1-54f06a068229")}catch(e){}}();
|
|
3
3
|
import path from "path";
|
|
4
4
|
import { execSync } from "child_process";
|
|
5
5
|
import fs from "fs";
|
|
@@ -31,4 +31,4 @@ try {
|
|
|
31
31
|
export {};
|
|
32
32
|
|
|
33
33
|
//# sourceMappingURL=install-packages.mjs.map
|
|
34
|
-
//# debugId=
|
|
34
|
+
//# debugId=58dbe86a-e88c-57d1-9ab1-54f06a068229
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"install-packages.mjs","sources":["../src/install-packages.mts"],"sourcesContent":["import { execSync } from \"child_process\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n// Define interface for package.json\ninterface PackageJson {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\n// Get the list of packages to install from the environment variable\nconst pkgs = process.env.PH_PACKAGES?.split(\",\") || [];\n\n// Skip if no packages to install\nif (pkgs.length === 0 || (pkgs.length === 1 && pkgs[0] === \"\")) {\n process.exit(0);\n}\n\ntry {\n // Read the package.json file to check existing dependencies\n const packageJsonPath = path.join(process.cwd(), \"package.json\");\n const packageJsonContent = fs.readFileSync(packageJsonPath, \"utf-8\");\n const packageJson = JSON.parse(packageJsonContent) as PackageJson;\n\n // Get all installed dependencies\n const installedDependencies: Record<string, string> = {\n ...(packageJson.dependencies || {}),\n ...(packageJson.devDependencies || {}),\n };\n\n for (const pkg of pkgs) {\n if (pkg === \"\") continue;\n\n // Check if the package is already installed\n if (installedDependencies[pkg]) {\n console.log(`> Package ${pkg} is already installed, skipping`);\n continue;\n }\n\n console.log(`> Installing ${pkg}`);\n execSync(`pnpm add ${pkg}@latest`, { stdio: \"inherit\" });\n }\n} catch (error) {\n console.error(\"Error in package installation:\", error);\n process.exit(1);\n}\n"],"names":[],"mappings":";;;;;;AAWA,MAAM,OAAO,QAAQ,IAAI,aAAa,MAAM,
|
|
1
|
+
{"version":3,"file":"install-packages.mjs","sources":["../src/install-packages.mts"],"sourcesContent":["import { execSync } from \"child_process\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n// Define interface for package.json\ninterface PackageJson {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\n// Get the list of packages to install from the environment variable\nconst pkgs = process.env.PH_PACKAGES?.split(\",\") || [];\n\n// Skip if no packages to install\nif (pkgs.length === 0 || (pkgs.length === 1 && pkgs[0] === \"\")) {\n process.exit(0);\n}\n\ntry {\n // Read the package.json file to check existing dependencies\n const packageJsonPath = path.join(process.cwd(), \"package.json\");\n const packageJsonContent = fs.readFileSync(packageJsonPath, \"utf-8\");\n const packageJson = JSON.parse(packageJsonContent) as PackageJson;\n\n // Get all installed dependencies\n const installedDependencies: Record<string, string> = {\n ...(packageJson.dependencies || {}),\n ...(packageJson.devDependencies || {}),\n };\n\n for (const pkg of pkgs) {\n if (pkg === \"\") continue;\n\n // Check if the package is already installed\n if (installedDependencies[pkg]) {\n console.log(`> Package ${pkg} is already installed, skipping`);\n continue;\n }\n\n console.log(`> Installing ${pkg}`);\n execSync(`pnpm add ${pkg}@latest`, { stdio: \"inherit\" });\n }\n} catch (error) {\n console.error(\"Error in package installation:\", error);\n process.exit(1);\n}\n"],"names":[],"mappings":";;;;;;AAWA,MAAM,OAAO,QAAQ,IAAI,aAAa,MAAM,GAAG,KAAK,CAAC;AAGrD,IAAI,KAAK,WAAW,KAAM,KAAK,WAAW,KAAK,KAAK,OAAO,IACzD,QAAQ,KAAK,CAAC;AAGhB,IAAI;CAEF,MAAM,kBAAkB,KAAK,KAAK,QAAQ,IAAI,GAAG,cAAc;CAC/D,MAAM,qBAAqB,GAAG,aAAa,iBAAiB,OAAO;CACnE,MAAM,cAAc,KAAK,MAAM,kBAAkB;CAGjD,MAAM,wBAAgD;EACpD,GAAI,YAAY,gBAAgB,CAAC;EACjC,GAAI,YAAY,mBAAmB,CAAC;CACtC;CAEA,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,QAAQ,IAAI;EAGhB,IAAI,sBAAsB,MAAM;GAC9B,QAAQ,IAAI,aAAa,IAAI,gCAAgC;GAC7D;EACF;EAEA,QAAQ,IAAI,gBAAgB,KAAK;EACjC,SAAS,YAAY,IAAI,UAAU,EAAE,OAAO,UAAU,CAAC;CACzD;AACF,SAAS,OAAO;CACd,QAAQ,MAAM,kCAAkC,KAAK;CACrD,QAAQ,KAAK,CAAC;AAChB","debug_id":"58dbe86a-e88c-57d1-9ab1-54f06a068229"}
|
|
@@ -0,0 +1,32 @@
|
|
|
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]="54d61ec8-8bfa-5067-b1a5-2ae8c4b8fd6d")}catch(e){}}();
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region src/plugins/mcp.mts
|
|
5
|
+
/** No entry config: presence is the whole activation. A typo'd config key
|
|
6
|
+
* fails at resolution instead of being silently ignored. */
|
|
7
|
+
const mcpPluginConfigSchema = z.strictObject({});
|
|
8
|
+
/**
|
|
9
|
+
* R2.2 — the MCP subsystem as a built-in plugin. Flag-on semantics: PRESENCE
|
|
10
|
+
* IS ACTIVATION — listed (built-in default) means the /mcp endpoint mounts;
|
|
11
|
+
* removed from the composition means it does not exist. The MCP_ENABLED env
|
|
12
|
+
* flag governs the classic/flag-off path only (resolveMcpEnabled, which
|
|
13
|
+
* still runs and whose result this transform overrides flag-on).
|
|
14
|
+
*
|
|
15
|
+
* The mount itself lives inside reactor-api's initializeAndStartAPI (carve
|
|
16
|
+
* map: reactor-api server.ts:1282-1294) and is driven by options.mcp — the
|
|
17
|
+
* plugin's whole job is owning that option.
|
|
18
|
+
*/
|
|
19
|
+
const mcpPlugin = {
|
|
20
|
+
name: "switchboard-mcp",
|
|
21
|
+
appliesTo: "switchboard",
|
|
22
|
+
configSchema: mcpPluginConfigSchema,
|
|
23
|
+
hooks: { transformServerOptions: (options) => options.mcp === false ? options : {
|
|
24
|
+
...options,
|
|
25
|
+
mcp: true
|
|
26
|
+
} }
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { mcpPluginConfigSchema as n, mcpPlugin as t };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=mcp-SsBK14Jm.mjs.map
|
|
32
|
+
//# debugId=54d61ec8-8bfa-5067-b1a5-2ae8c4b8fd6d
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-SsBK14Jm.mjs","sources":["../src/plugins/mcp.mts"],"sourcesContent":["import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\nimport { z } from \"zod\";\n\n/** No entry config: presence is the whole activation. A typo'd config key\n * fails at resolution instead of being silently ignored. */\nexport const mcpPluginConfigSchema = z.strictObject({});\n\nexport type McpPluginConfig = z.input<typeof mcpPluginConfigSchema>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/mcp\": McpPluginConfig;\n }\n}\n\n/**\n * R2.2 — the MCP subsystem as a built-in plugin. Flag-on semantics: PRESENCE\n * IS ACTIVATION — listed (built-in default) means the /mcp endpoint mounts;\n * removed from the composition means it does not exist. The MCP_ENABLED env\n * flag governs the classic/flag-off path only (resolveMcpEnabled, which\n * still runs and whose result this transform overrides flag-on).\n *\n * The mount itself lives inside reactor-api's initializeAndStartAPI (carve\n * map: reactor-api server.ts:1282-1294) and is driven by options.mcp — the\n * plugin's whole job is owning that option.\n */\nexport const mcpPlugin: HostPlugin<{\n transformServerOptions: (\n options: Record<string, unknown>,\n ctx: SwitchboardHostContext,\n ) => Record<string, unknown>;\n}> = {\n name: \"switchboard-mcp\",\n appliesTo: \"switchboard\",\n configSchema: mcpPluginConfigSchema,\n hooks: {\n // An explicit caller/host `mcp: false` option keeps winning (the same\n // short-circuit resolveMcpEnabled has); only the ENV flag loses its\n // meaning flag-on — presence in the composition is the switch.\n transformServerOptions: (options) =>\n options.mcp === false ? options : { ...options, mcp: true },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default mcpPlugin;\n"],"names":[],"mappings":";;;;;;AAMA,MAAa,wBAAwB,EAAE,aAAa,CAAC,CAAC;;;;;;;;;;;;AAqBtD,MAAa,YAKR;CACH,MAAM;CACN,WAAW;CACX,cAAc;CACd,OAAO,EAIL,yBAAyB,YACvB,QAAQ,QAAQ,QAAQ,UAAU;EAAE,GAAG;EAAS,KAAK;CAAK,EAC9D;AACF","debug_id":"54d61ec8-8bfa-5067-b1a5-2ae8c4b8fd6d"}
|
package/dist/migrate.d.mts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
|
2
|
+
export {};
|
package/dist/migrate.mjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!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]="
|
|
4
|
-
import dotenv from "dotenv";
|
|
3
|
+
!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]="be192444-eb57-5f26-a00c-ffbb35edea43")}catch(e){}}();
|
|
5
4
|
import { getConfig } from "@powerhousedao/config/node";
|
|
6
5
|
import { REACTOR_SCHEMA, getMigrationStatus, runMigrations } from "@powerhousedao/reactor";
|
|
7
6
|
import { getReactorDriveMigrationStatus, runReactorDriveMigrations } from "@powerhousedao/reactor-drive";
|
|
7
|
+
import dotenv from "dotenv";
|
|
8
8
|
import { Kysely, PostgresDialect } from "kysely";
|
|
9
9
|
import { Pool } from "pg";
|
|
10
|
+
import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
10
11
|
//#region src/migrate.mts
|
|
11
|
-
dotenv.config();
|
|
12
|
+
if (!isDotenvDisabled()) dotenv.config();
|
|
12
13
|
function isPostgresUrl(url) {
|
|
13
14
|
return url.startsWith("postgresql://") || url.startsWith("postgres://");
|
|
14
15
|
}
|
|
@@ -22,7 +23,8 @@ async function main() {
|
|
|
22
23
|
return;
|
|
23
24
|
}
|
|
24
25
|
console.log(`Database: ${dbPath}`);
|
|
25
|
-
const
|
|
26
|
+
const pool = new Pool({ connectionString: dbPath });
|
|
27
|
+
const db = new Kysely({ dialect: new PostgresDialect({ pool }) });
|
|
26
28
|
try {
|
|
27
29
|
if (command === "status") {
|
|
28
30
|
console.log("\nChecking migration status...");
|
|
@@ -76,4 +78,4 @@ main();
|
|
|
76
78
|
export {};
|
|
77
79
|
|
|
78
80
|
//# sourceMappingURL=migrate.mjs.map
|
|
79
|
-
//# debugId=
|
|
81
|
+
//# debugId=be192444-eb57-5f26-a00c-ffbb35edea43
|
package/dist/migrate.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate.mjs","sources":["../src/migrate.mts"],"sourcesContent":["#!/usr/bin/env node\nimport dotenv from \"dotenv\";\
|
|
1
|
+
{"version":3,"file":"migrate.mjs","sources":["../src/migrate.mts"],"sourcesContent":["#!/usr/bin/env node\nimport dotenv from \"dotenv\";\nimport { isDotenvDisabled } from \"@powerhousedao/shared/clis/project-env\";\nif (!isDotenvDisabled()) dotenv.config();\n\nimport { Kysely, PostgresDialect } from \"kysely\";\nimport { Pool } from \"pg\";\nimport {\n runMigrations,\n getMigrationStatus,\n REACTOR_SCHEMA,\n} from \"@powerhousedao/reactor\";\nimport {\n getReactorDriveMigrationStatus,\n runReactorDriveMigrations,\n} from \"@powerhousedao/reactor-drive\";\nimport { getConfig } from \"@powerhousedao/config/node\";\n\nfunction isPostgresUrl(url: string): boolean {\n return url.startsWith(\"postgresql://\") || url.startsWith(\"postgres://\");\n}\n\nasync function main() {\n const command = process.argv[2];\n const config = getConfig();\n\n const dbPath =\n process.env.PH_SWITCHBOARD_DATABASE_URL ??\n process.env.PH_REACTOR_DATABASE_URL ??\n process.env.DATABASE_URL ??\n config.switchboard?.database?.url;\n\n if (!dbPath || !isPostgresUrl(dbPath)) {\n console.log(\"No PostgreSQL URL configured. Skipping migrations.\");\n console.log(\"(PGlite migrations are handled automatically on startup)\");\n return;\n }\n\n console.log(`Database: ${dbPath}`);\n\n const pool = new Pool({ connectionString: dbPath });\n\n const db = new Kysely<any>({\n dialect: new PostgresDialect({ pool }),\n });\n\n try {\n if (command === \"status\") {\n console.log(\"\\nChecking migration status...\");\n const migrations = await getMigrationStatus(db, REACTOR_SCHEMA);\n\n console.log(\"\\nReactor Migration Status:\");\n console.log(\"=========================\");\n\n for (const migration of migrations) {\n const status = migration.executedAt\n ? `[OK] Executed at ${migration.executedAt.toISOString()}`\n : \"[--] Pending\";\n console.log(`${status} - ${migration.name}`);\n }\n\n const driveMigrations = await getReactorDriveMigrationStatus(\n db,\n REACTOR_SCHEMA,\n );\n\n console.log(\"\\nReactor-Drive Migration Status:\");\n console.log(\"===============================\");\n\n for (const migration of driveMigrations) {\n const status = migration.executedAt\n ? `[OK] Executed at ${migration.executedAt.toISOString()}`\n : \"[--] Pending\";\n console.log(`${status} - ${migration.name}`);\n }\n } else {\n console.log(\"\\nRunning reactor migrations...\");\n const result = await runMigrations(db, REACTOR_SCHEMA);\n\n if (!result.success) {\n console.error(\"Migration failed:\", result.error?.message);\n process.exit(1);\n }\n\n if (result.migrationsExecuted.length === 0) {\n console.log(\"No reactor migrations to run - database is up to date\");\n } else {\n console.log(\n `Successfully executed ${result.migrationsExecuted.length} reactor migration(s):`,\n );\n for (const name of result.migrationsExecuted) {\n console.log(` - ${name}`);\n }\n }\n\n console.log(\"\\nRunning reactor-drive migrations...\");\n const driveResult = await runReactorDriveMigrations(db, REACTOR_SCHEMA);\n\n if (!driveResult.success) {\n console.error(\n \"Reactor-drive migration failed:\",\n driveResult.error?.message,\n );\n process.exit(1);\n }\n\n if (driveResult.migrationsExecuted.length === 0) {\n console.log(\n \"No reactor-drive migrations to run - database is up to date\",\n );\n } else {\n console.log(\n `Successfully executed ${driveResult.migrationsExecuted.length} reactor-drive migration(s):`,\n );\n for (const name of driveResult.migrationsExecuted) {\n console.log(` - ${name}`);\n }\n }\n }\n } catch (error) {\n console.error(\n \"Error:\",\n error instanceof Error ? error.message : String(error),\n );\n process.exit(1);\n } finally {\n await db.destroy();\n }\n}\n\nvoid main();\n"],"names":[],"mappings":";;;;;;;;;;;AAGA,IAAI,CAAC,iBAAiB,GAAG,OAAO,OAAO;AAevC,SAAS,cAAc,KAAsB;CA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AAO,OAAO,OAAO;IACxD,QAAQ,KAAK,CAAC;GAChB;GAEA,IAAI,OAAO,mBAAmB,WAAW,GACvC,QAAQ,IAAI,uDAAuD;QAC9D;IACL,QAAQ,IACN,yBAAyB,OAAO,mBAAmB,OAAO,uBAC5D;IACA,KAAK,MAAM,QAAQ,OAAO,oBACxB,QAAQ,IAAI,OAAO,MAAM;GAE7B;GAEA,QAAQ,IAAI,uCAAuC;GACnD,MAAM,cAAc,MAAM,0BAA0B,IAAI,cAAc;GAEtE,IAAI,CAAC,YAAY,SAAS;IACxB,QAAQ,MACN,mCACA,YAAY,OAAO,OACrB;IACA,QAAQ,KAAK,CAAC;GAChB;GAEA,IAAI,YAAY,mBAAmB,WAAW,GAC5C,QAAQ,IACN,6DACF;QACK;IACL,QAAQ,IACN,yBAAyB,YAAY,mBAAmB,OAAO,6BACjE;IACA,KAAK,MAAM,QAAQ,YAAY,oBAC7B,QAAQ,IAAI,OAAO,MAAM;GAE7B;EACF;CACF,SAAS,OAAO;EACd,QAAQ,MACN,UACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CACvD;EACA,QAAQ,KAAK,CAAC;CAChB,UAAU;EACR,MAAM,GAAG,QAAQ;CACnB;AACF;AAEK,KAAK","debug_id":"be192444-eb57-5f26-a00c-ffbb35edea43"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { i as SwitchboardConfig } from "./schema-ugrJupVH.mjs";
|
|
2
|
+
import { HostPlugin, MergedContribution, ResolvedPlugin } from "@powerhousedao/host-core";
|
|
3
|
+
//#region src/plugin-host.d.mts
|
|
4
|
+
/**
|
|
5
|
+
* The context plugins receive. Fields are populated as the boot spine reaches
|
|
6
|
+
* them (api/client/graphqlManager are undefined before stage 17); concrete
|
|
7
|
+
* types stay in server.mts — subsystem carves tighten their own slices.
|
|
8
|
+
*/
|
|
9
|
+
interface SwitchboardHostContext {
|
|
10
|
+
/** The switchboard's ILogger; typed loosely here to avoid pinning the
|
|
11
|
+
* logger package in the scaffold — subsystem carves use it as-is. */
|
|
12
|
+
logger: unknown;
|
|
13
|
+
options: Record<string, unknown>;
|
|
14
|
+
/** The parsed config the switchboard booted with. */
|
|
15
|
+
config?: SwitchboardConfig;
|
|
16
|
+
renown: unknown;
|
|
17
|
+
serverPort?: number;
|
|
18
|
+
/** Set by the attachments plugin at onHttpMounting; the boot reads it for
|
|
19
|
+
* the returned handle. */
|
|
20
|
+
attachmentService?: unknown;
|
|
21
|
+
/** Privacy plugin state: config resolved at transformServerOptions
|
|
22
|
+
* (fail-fast), the running subsystem set at onSubgraphsRegistering. */
|
|
23
|
+
privacyConfig?: unknown;
|
|
24
|
+
privacy?: unknown;
|
|
25
|
+
/** Workflows plugin: wiring closures handed in by server.mts, runtime +
|
|
26
|
+
* retry handles stored by the plugin. */
|
|
27
|
+
workflowsOrchestration?: unknown;
|
|
28
|
+
workflows?: unknown;
|
|
29
|
+
workflowsRetry?: unknown;
|
|
30
|
+
api?: unknown;
|
|
31
|
+
/** @deprecated The facade; plugins that have moved take `read` and `write`. */
|
|
32
|
+
client?: unknown;
|
|
33
|
+
/** The reactor's read half (IReactorReadClient), set at onReactorReady. */
|
|
34
|
+
read?: unknown;
|
|
35
|
+
/** The reactor's write half (IReactorWriteClient), set at onReactorReady. */
|
|
36
|
+
write?: unknown;
|
|
37
|
+
graphqlManager?: unknown;
|
|
38
|
+
reactorClientModule?: unknown;
|
|
39
|
+
/** Late subgraph registrations drain before the readiness router update. */
|
|
40
|
+
lateSubgraphs?: Promise<unknown>[];
|
|
41
|
+
contributions: Record<string, MergedContribution[]>;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { SwitchboardHostContext as t };
|
|
45
|
+
export {};
|
|
46
|
+
//# sourceMappingURL=plugin-host-BHEUSn9G.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-host-BHEUSn9G.d.mts","names":[],"sources":["../src/plugin-host.mts"],"mappings":";;;;;;;;UA0CiB;;;EAGf;EACA,SAAS;;EAET,SAAS;EACT;EACA;;;EAGA;;;EAGA;EACA;;;EAGA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB;EAChB,eAAe,eAAe"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { t as SwitchboardHostContext } from "../plugin-host-BHEUSn9G.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { HostPlugin } from "@powerhousedao/host-core";
|
|
4
|
+
//#region src/plugins/ai.d.mts
|
|
5
|
+
export declare const DEFAULT_AI_UPSTREAM_URL = "https://openrouter.ai/api/v1";
|
|
6
|
+
export declare const aiPluginConfigSchema: z.ZodObject<{
|
|
7
|
+
defaultModel: z.ZodString;
|
|
8
|
+
maxOutputTokens: z.ZodDefault<z.ZodNumber>;
|
|
9
|
+
upstreamUrl: z.ZodDefault<z.ZodURL>;
|
|
10
|
+
appTitle: z.ZodDefault<z.ZodString>;
|
|
11
|
+
appUrl: z.ZodDefault<z.ZodURL>;
|
|
12
|
+
allowWithoutAuth: z.ZodDefault<z.ZodBoolean>;
|
|
13
|
+
}, z.core.$strict>;
|
|
14
|
+
export type AiPluginConfig = z.infer<typeof aiPluginConfigSchema>;
|
|
15
|
+
/** What a host.js entry writes (typed-host-configs 1.4). */
|
|
16
|
+
export type AiPluginConfigInput = z.input<typeof aiPluginConfigSchema>;
|
|
17
|
+
declare global {
|
|
18
|
+
interface PHPluginConfigs {
|
|
19
|
+
"@powerhousedao/switchboard/plugins/ai": AiPluginConfigInput;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export type AiPlugin = HostPlugin<{
|
|
23
|
+
onHttpMounting: (ctx: SwitchboardHostContext) => void;
|
|
24
|
+
}, AiPluginConfig>;
|
|
25
|
+
/**
|
|
26
|
+
* The AI gateway: an OpenAI-compatible endpoint for this host's admins that
|
|
27
|
+
* holds the provider key server side, so the browser's agent runs without
|
|
28
|
+
* one. The key is a host secret in the workflow runtime's encrypted store,
|
|
29
|
+
* reached per request through `ctx.workflows`: the runtime can arrive after
|
|
30
|
+
* boot, and a second opener of the store could race the first over the key
|
|
31
|
+
* file. Without the runtime the routes answer 503.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createAiPlugin(rawConfig: unknown): AiPlugin;
|
|
34
|
+
//#endregion
|
|
35
|
+
export { createAiPlugin as default };
|
|
36
|
+
export {};
|
|
37
|
+
//# sourceMappingURL=ai.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ai.d.mts","names":[],"sources":["../../src/plugins/ai.mts"],"mappings":";;;;qBAUa;qBAEA,sBAAoB,EAAA;;;;;;;GAgB/B,EAAA,KAAA;YAEU,iBAAiB,EAAE,aAAa;;YAGhC,sBAAsB,EAAE,aAAa;QAEzC;YACI;IACR,yCAAyC;;;YAIjC,WAAW;EACnB,iBAAiB,KAAK;GACxB;;;;;;;;;wBAWc,eAAe,qBAAqB"}
|