@powerhousedao/switchboard 6.2.3-dev.70 → 6.2.3-dev.72

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.
Files changed (54) hide show
  1. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  2. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  3. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  4. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  5. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  6. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  7. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  8. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  9. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  10. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  11. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  12. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  13. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  14. package/CHANGELOG.md +44 -0
  15. package/dist/index.mjs +1 -1
  16. package/dist/{mcp-cNWW82NH.mjs → mcp-SsBK14Jm.mjs} +10 -5
  17. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  18. package/dist/plugins/attachments.d.mts +10 -0
  19. package/dist/plugins/attachments.d.mts.map +1 -1
  20. package/dist/plugins/attachments.mjs +4 -4
  21. package/dist/plugins/mcp.d.mts +10 -0
  22. package/dist/plugins/mcp.d.mts.map +1 -1
  23. package/dist/plugins/mcp.mjs +4 -4
  24. package/dist/plugins/privacy.d.mts +10 -0
  25. package/dist/plugins/privacy.d.mts.map +1 -1
  26. package/dist/plugins/privacy.mjs +4 -4
  27. package/dist/plugins/workflows.d.mts +46 -3
  28. package/dist/plugins/workflows.d.mts.map +1 -1
  29. package/dist/plugins/workflows.mjs +4 -4
  30. package/dist/{privacy-C8KVimKF.mjs → privacy-BsFl7GzK.mjs} +9 -4
  31. package/dist/{privacy-C8KVimKF.mjs.map → privacy-BsFl7GzK.mjs.map} +1 -1
  32. package/dist/{server-CF_mjyJi.mjs → server-CrWPtMG6.mjs} +114 -29
  33. package/dist/server-CrWPtMG6.mjs.map +1 -0
  34. package/dist/server.d.mts +18 -15
  35. package/dist/server.d.mts.map +1 -1
  36. package/dist/server.mjs +3 -3
  37. package/dist/{utils-uaBlzyjS.mjs → utils-Dh845exv.mjs} +42 -9
  38. package/dist/utils-Dh845exv.mjs.map +1 -0
  39. package/dist/utils.d.mts +8 -2
  40. package/dist/utils.d.mts.map +1 -1
  41. package/dist/utils.mjs +3 -3
  42. package/dist/{workflows-qKtqZhn3.mjs → workflows-fsBcElEi.mjs} +111 -67
  43. package/dist/{workflows-qKtqZhn3.mjs.map → workflows-fsBcElEi.mjs.map} +1 -1
  44. package/package.json +18 -17
  45. package/test/attachments/routes.test.ts +26 -11
  46. package/test/default-drive-slug.test.ts +97 -0
  47. package/test/plugin-config-schemas.test.ts +83 -0
  48. package/test/port-probe.test.ts +45 -0
  49. package/test/shutdown.test.ts +278 -0
  50. package/test/store-lock.test.ts +65 -0
  51. package/test/workflows-plugin-config.test.ts +77 -0
  52. package/dist/mcp-cNWW82NH.mjs.map +0 -1
  53. package/dist/server-CF_mjyJi.mjs.map +0 -1
  54. package/dist/utils-uaBlzyjS.mjs.map +0 -1
@@ -1,9 +1,9 @@
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]="c7a0fd97-c4f8-5b06-a939-44b23fae01c3")}catch(e){}}();
3
- import { a as composeWorkflowRuntime, c as resolveWorkflowsEnabled, d as installFatalErrorShutdown, f as triggerFatalShutdown, i as assertWorkflowPackageLoadable, l as retryWorkflowSingleton, n as WORKFLOW_PACKAGE_NAME, o as isWorkflowSingletonConflict, r as WORKFLOW_TELEMETRY_SCOPE, s as modelManifestSource, t as workflowsPlugin, u as workflowSingletonLossHandler } from "./workflows-qKtqZhn3.mjs";
4
- import { n as resolvePrivacy, r as startPrivacy, t as privacyPlugin } from "./privacy-C8KVimKF.mjs";
5
- import { t as mcpPlugin } from "./mcp-cNWW82NH.mjs";
6
- import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-uaBlzyjS.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="290090f1-e3b3-5338-a8cc-2072903fbb2a")}catch(e){}}();
3
+ import { _ as triggerFatalShutdown, a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as installFatalErrorShutdown, h as workflowSingletonLossHandler, l as assertWorkflowPackageLoadable, m as retryWorkflowSingleton, p as resolveWorkflowsEnabled, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-fsBcElEi.mjs";
4
+ import { i as startPrivacy, r as resolvePrivacy, t as privacyPlugin } from "./privacy-BsFl7GzK.mjs";
5
+ import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
6
+ import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-Dh845exv.mjs";
7
7
  import { createRequire, register } from "node:module";
8
8
  import { metrics, trace } from "@opentelemetry/api";
9
9
  import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
@@ -11,7 +11,7 @@ import * as Sentry from "@sentry/node";
11
11
  import { childLogger, setLogLevel } from "document-model";
12
12
  import dotenv from "dotenv";
13
13
  import { getConfig } from "@powerhousedao/config/node";
14
- import { existsSync, promises, realpathSync } from "node:fs";
14
+ import fs, { existsSync, promises, realpathSync } from "node:fs";
15
15
  import path, { resolve } from "node:path";
16
16
  import { createDurableNodeFs, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, syncTree } from "@powerhousedao/reactor-api/pglite-node";
17
17
  import { ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
@@ -28,6 +28,7 @@ import path$1 from "path";
28
28
  import { Pool } from "pg";
29
29
  import { Readable } from "node:stream";
30
30
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
31
+ import { z } from "zod";
31
32
  import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
32
33
  import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
33
34
  import { readFile } from "node:fs/promises";
@@ -258,7 +259,7 @@ function parseReserveOptions(input) {
258
259
  if (extension !== null && typeof extension !== "string") return null;
259
260
  if (obj.clientHash !== void 0) {
260
261
  if (typeof obj.clientHash !== "string" || !HASH_PATTERN.test(obj.clientHash)) return null;
261
- if (typeof obj.sizeBytes !== "number" || !Number.isInteger(obj.sizeBytes) || obj.sizeBytes <= 0 || !Number.isSafeInteger(obj.sizeBytes)) return null;
262
+ if (typeof obj.sizeBytes !== "number" || !Number.isSafeInteger(obj.sizeBytes) || obj.sizeBytes < 0) return null;
262
263
  return {
263
264
  mimeType,
264
265
  fileName,
@@ -903,6 +904,9 @@ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options
903
904
  }
904
905
  //#endregion
905
906
  //#region src/plugins/attachments.mts
907
+ /** No entry config: presence is the whole activation. A typo'd config key
908
+ * fails at resolution instead of being silently ignored. */
909
+ const attachmentsPluginConfigSchema = z.strictObject({});
906
910
  /**
907
911
  * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
908
912
  * routes mount at onHttpMounting and the remote attachment service is created
@@ -919,6 +923,7 @@ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options
919
923
  const attachmentsPlugin = {
920
924
  name: "switchboard-attachments",
921
925
  appliesTo: "switchboard",
926
+ configSchema: attachmentsPluginConfigSchema,
922
927
  hooks: { onHttpMounting: (ctx) => {
923
928
  registerAttachmentRoutes(ctx.api);
924
929
  ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
@@ -1714,6 +1719,63 @@ var StoredDocumentsRefusedError = class extends Error {
1714
1719
  }
1715
1720
  };
1716
1721
  //#endregion
1722
+ //#region src/store-lock.mts
1723
+ var StoreInUseError = class extends Error {
1724
+ dir;
1725
+ owner;
1726
+ constructor(dir, owner) {
1727
+ 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.`);
1728
+ this.dir = dir;
1729
+ this.owner = owner;
1730
+ this.name = "StoreInUseError";
1731
+ }
1732
+ };
1733
+ const lockPathOf = (dir) => `${path.resolve(dir)}.lock`;
1734
+ function isAlive(pid) {
1735
+ try {
1736
+ process.kill(pid, 0);
1737
+ return true;
1738
+ } catch (error) {
1739
+ return error.code === "EPERM";
1740
+ }
1741
+ }
1742
+ function readOwner(file) {
1743
+ try {
1744
+ return JSON.parse(fs.readFileSync(file, "utf8"));
1745
+ } catch {
1746
+ return;
1747
+ }
1748
+ }
1749
+ const held = /* @__PURE__ */ new Set();
1750
+ let exitHookInstalled = false;
1751
+ function releaseAll() {
1752
+ for (const file of held) if (readOwner(file)?.pid === process.pid) try {
1753
+ fs.rmSync(file);
1754
+ } catch {}
1755
+ held.clear();
1756
+ }
1757
+ /** Take the lock for each store dir, or throw StoreInUseError naming the
1758
+ * live owner. Idempotent within one process. */
1759
+ function acquireStoreLocks(dirs, isPidAlive = isAlive) {
1760
+ const mine = {
1761
+ pid: process.pid,
1762
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1763
+ command: process.argv.slice(1).join(" ").slice(0, 200)
1764
+ };
1765
+ for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {
1766
+ const file = lockPathOf(dir);
1767
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1768
+ const owner = readOwner(file);
1769
+ if (owner && owner.pid !== process.pid && isPidAlive(owner.pid)) throw new StoreInUseError(dir, owner);
1770
+ fs.writeFileSync(file, `${JSON.stringify(mine)}\n`);
1771
+ held.add(file);
1772
+ }
1773
+ if (!exitHookInstalled) {
1774
+ exitHookInstalled = true;
1775
+ process.on("exit", releaseAll);
1776
+ }
1777
+ }
1778
+ //#endregion
1717
1779
  //#region src/server.mts
1718
1780
  const defaultLogger = childLogger(["switchboard"]);
1719
1781
  const LogLevel = process.env.LOG_LEVEL || "info";
@@ -1753,7 +1815,21 @@ const PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === "1";
1753
1815
  * the port is free, false if the OS reports it in use. Any other error is
1754
1816
  * surfaced so we don't silently mask real issues (permissions, bad host, …).
1755
1817
  */
1756
- function isPortAvailable(port) {
1818
+ async function isPortAvailable(port) {
1819
+ try {
1820
+ return await probePort(port, "::");
1821
+ } catch (error) {
1822
+ if (!isNoIpv6Error(error)) throw portProbeError(port, error);
1823
+ try {
1824
+ return await probePort(port, "0.0.0.0");
1825
+ } catch (ipv4Error) {
1826
+ throw portProbeError(port, ipv4Error);
1827
+ }
1828
+ }
1829
+ }
1830
+ const isNoIpv6Error = (error) => ["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(error.code ?? "");
1831
+ const portProbeError = (port, error) => new Error(`Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1832
+ function probePort(port, host) {
1757
1833
  return new Promise((resolve, reject) => {
1758
1834
  const tester = net.createServer();
1759
1835
  tester.once("error", (err) => {
@@ -1765,7 +1841,7 @@ function isPortAvailable(port) {
1765
1841
  });
1766
1842
  tester.listen({
1767
1843
  port,
1768
- host: "::"
1844
+ host
1769
1845
  });
1770
1846
  });
1771
1847
  }
@@ -1878,6 +1954,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1878
1954
  callerReactor: options.reactor !== void 0
1879
1955
  });
1880
1956
  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.`);
1957
+ if (!PGLITE_IN_MEMORY) acquireStoreLocks(pgliteDirs);
1881
1958
  warnIgnoredFlushInterval(logger);
1882
1959
  const detectedMajors = await runPglitePreflight({
1883
1960
  dirs: pgliteDirs,
@@ -1985,6 +2062,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1985
2062
  const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
1986
2063
  const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
1987
2064
  applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
2065
+ signalHandlers: options.signalHandlers,
1988
2066
  documentModels: [...documentModels, ...vetraDocumentModels],
1989
2067
  upgradeManifests,
1990
2068
  executorConfig: hasSkipThreshold || enabledFeatureFlags.length > 0 ? {
@@ -2080,22 +2158,25 @@ async function initServer(serverPort, options, renown, renownConfig) {
2080
2158
  };
2081
2159
  };
2082
2160
  const abortBoot = async (api) => {
2161
+ let disposed;
2162
+ const disposeApi = () => disposed ??= api.dispose();
2163
+ apiRef.current = { dispose: disposeApi };
2083
2164
  const owned = ownedReactorModule;
2084
- if (owned) try {
2165
+ if (owned?.reactorModule) try {
2166
+ await owned.reactorModule.shutdown();
2167
+ } catch (error) {
2168
+ logger.error("Aborting boot: reactor shutdown failed: @error", error);
2169
+ }
2170
+ else if (owned) try {
2085
2171
  await owned.reactor.kill().completed;
2086
2172
  } catch (error) {
2087
2173
  logger.error("Aborting boot: reactor shutdown failed: @error", error);
2088
2174
  }
2089
2175
  try {
2090
- await api.dispose();
2176
+ await disposeApi();
2091
2177
  } catch (error) {
2092
2178
  logger.error("Aborting boot: api dispose failed: @error", error);
2093
2179
  }
2094
- if (owned?.reactorModule) try {
2095
- await owned.reactorModule.database.destroy();
2096
- } catch (error) {
2097
- logger.error("Aborting boot: database destroy failed: @error", error);
2098
- }
2099
2180
  };
2100
2181
  let localCredentialCheck;
2101
2182
  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;
@@ -2306,14 +2387,17 @@ async function initServer(serverPort, options, renown, renownConfig) {
2306
2387
  throw error;
2307
2388
  }
2308
2389
  }
2309
- const shutdown = async () => {
2390
+ let apiDrained;
2391
+ const drainApi = () => apiDrained ??= (async () => {
2310
2392
  if (pluginHost) await pluginHost.observe("onShutdown");
2311
2393
  await privacy?.stop();
2312
2394
  await workflowsRetry?.stop();
2313
2395
  await workflows?.stop();
2314
2396
  await api.dispose();
2315
- };
2316
- apiRef.current = { dispose: shutdown };
2397
+ })();
2398
+ apiRef.current = { dispose: drainApi };
2399
+ const ownedReactor = ownedReactorModule?.reactorModule;
2400
+ const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;
2317
2401
  if (httpLoader) {
2318
2402
  const packageManagementService = new PackageManagementService({
2319
2403
  defaultRegistryUrl: registryUrl,
@@ -2372,8 +2456,8 @@ async function initServer(serverPort, options, renown, renownConfig) {
2372
2456
  }, reporting);
2373
2457
  if (options.drive) {
2374
2458
  if (!renown) throw new Error("Cannot create default drive without Renown identity");
2375
- if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort);
2376
- else defaultDriveUrl = await addDefaultDrive(client, options.drive, serverPort);
2459
+ if ((options.drive.documentType ?? "powerhouse/document-drive") === "powerhouse/reactor-drive") defaultDriveUrl = await addDefaultReactorDrive(client, options.drive, serverPort, logger);
2460
+ else defaultDriveUrl = await addDefaultDrive(client, options.drive, serverPort, logger);
2377
2461
  }
2378
2462
  if (vite) api.httpAdapter.mountRawMiddleware(vite.middlewares);
2379
2463
  if (remoteDrives.length > 0) for (const remoteDriveUrl of remoteDrives) {
@@ -2431,11 +2515,12 @@ async function initServer(serverPort, options, renown, renownConfig) {
2431
2515
  * dangling until the process exits.
2432
2516
  *
2433
2517
  * When `options.reactor` is omitted, the switchboard builds and owns the
2434
- * reactor. `shutdown()` on the returned handle only drains the api (HTTP
2435
- * server, GraphQL, MCP, attachments); the reactor itself is torn down by
2436
- * its own signal handlers (`withSignalHandlers`), which call `kill()` and
2437
- * trigger the `withShutdownHook` chain that disposes the api. Programmatic
2438
- * full teardown isn't currently exposed — wire it via SIGINT/SIGTERM.
2518
+ * reactor. `shutdown()` on the returned handle then runs the reactor
2519
+ * module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains
2520
+ * the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the
2521
+ * reactor database. It does not exit the process. It is the same memoized
2522
+ * teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling
2523
+ * it twice, or receiving a signal around it, tears down once.
2439
2524
  */
2440
2525
  const startSwitchboard = async (options = {}) => {
2441
2526
  const requestedPort = options.port ?? DEFAULT_PORT;
@@ -2491,7 +2576,7 @@ const startSwitchboard = async (options = {}) => {
2491
2576
  };
2492
2577
  if (import.meta.main) await startSwitchboard({ fatalErrorShutdown: true });
2493
2578
  //#endregion
2494
- export { startSwitchboard as a, attachmentsPlugin as c, parseForcePgVersion as d, resolvePgliteStorageDirs as i, applySwitchboardReactorDefaults as l, deriveAttachmentServiceConfig as n, StoredDocumentsRefusedError as o, isPortAvailable as r, resolveUnsupportedStoredDocuments as s, createReactorKysely as t, initProfilerFromEnv as u };
2579
+ export { startSwitchboard as a, attachmentsPlugin as c, initProfilerFromEnv as d, parseForcePgVersion as f, resolvePgliteStorageDirs as i, attachmentsPluginConfigSchema as l, deriveAttachmentServiceConfig as n, StoredDocumentsRefusedError as o, isPortAvailable as r, resolveUnsupportedStoredDocuments as s, createReactorKysely as t, applySwitchboardReactorDefaults as u };
2495
2580
 
2496
- //# sourceMappingURL=server-CF_mjyJi.mjs.map
2497
- //# debugId=c7a0fd97-c4f8-5b06-a939-44b23fae01c3
2581
+ //# sourceMappingURL=server-CrWPtMG6.mjs.map
2582
+ //# debugId=290090f1-e3b3-5338-a8cc-2072903fbb2a