@powerhousedao/switchboard 6.2.3 → 6.3.0-dev.2

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 (271) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  5. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  6. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  7. package/.tsbuild/test/boot-desktop-auth.test.d.ts +2 -0
  8. package/.tsbuild/test/boot-desktop-auth.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  12. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-ready-drives.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-ready-drives.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-undo-v3-flag.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-undo-v3-flag.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  31. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  32. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  33. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  34. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  35. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  36. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  37. package/.tsbuild/test/default-composition.test.d.ts +2 -0
  38. package/.tsbuild/test/default-composition.test.d.ts.map +1 -0
  39. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  40. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  41. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  42. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  43. package/.tsbuild/test/delegated-publish.test.d.ts +2 -0
  44. package/.tsbuild/test/delegated-publish.test.d.ts.map +1 -0
  45. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  46. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  47. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/greetings/index.d.ts +13 -0
  48. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/greetings/index.d.ts.map +1 -0
  49. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/index.d.ts +3 -0
  50. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/index.d.ts.map +1 -0
  51. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/tally/index.d.ts +7 -0
  52. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/tally/index.d.ts.map +1 -0
  53. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  54. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  55. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  56. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  57. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  58. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  59. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  60. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  61. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  62. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  63. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  64. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  65. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  66. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  67. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  68. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  69. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  70. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  71. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  72. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  73. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  74. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  75. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  76. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  77. package/.tsbuild/test/served-schemas-mixed-package.test.d.ts +2 -0
  78. package/.tsbuild/test/served-schemas-mixed-package.test.d.ts.map +1 -0
  79. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  80. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  81. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  82. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  83. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  84. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  85. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  86. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  87. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  88. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  89. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts +2 -0
  90. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts.map +1 -0
  91. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  92. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  93. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  94. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  95. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  96. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  97. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  98. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  99. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  100. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  101. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  102. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  103. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  104. package/Auth.md +108 -2
  105. package/CHANGELOG.md +1066 -2
  106. package/README.md +69 -24
  107. package/dist/boot.d.mts +46 -0
  108. package/dist/boot.d.mts.map +1 -0
  109. package/dist/boot.mjs +67 -0
  110. package/dist/boot.mjs.map +1 -0
  111. package/dist/config/from-env.d.mts +15 -0
  112. package/dist/config/from-env.d.mts.map +1 -0
  113. package/dist/config/from-env.mjs +4 -0
  114. package/dist/config/schema.d.mts +3 -0
  115. package/dist/config/schema.mjs +4 -0
  116. package/dist/from-env-DKK_wPrO.mjs +497 -0
  117. package/dist/from-env-DKK_wPrO.mjs.map +1 -0
  118. package/dist/index.d.mts +1 -2
  119. package/dist/index.mjs +40 -219
  120. package/dist/index.mjs.map +1 -1
  121. package/dist/mcp-VW52B8KD.mjs +32 -0
  122. package/dist/mcp-VW52B8KD.mjs.map +1 -0
  123. package/dist/migrate.mjs +5 -4
  124. package/dist/migrate.mjs.map +1 -1
  125. package/dist/observability-CldagyT_.mjs +224 -0
  126. package/dist/observability-CldagyT_.mjs.map +1 -0
  127. package/dist/observability.d.mts +30 -0
  128. package/dist/observability.d.mts.map +1 -0
  129. package/dist/observability.mjs +4 -0
  130. package/dist/plugin-host-tTjDTNz0.d.mts +46 -0
  131. package/dist/plugin-host-tTjDTNz0.d.mts.map +1 -0
  132. package/dist/plugins/ai.d.mts +37 -0
  133. package/dist/plugins/ai.d.mts.map +1 -0
  134. package/dist/plugins/ai.mjs +400 -0
  135. package/dist/plugins/ai.mjs.map +1 -0
  136. package/dist/plugins/attachments.d.mts +33 -0
  137. package/dist/plugins/attachments.d.mts.map +1 -0
  138. package/dist/plugins/attachments.mjs +4 -0
  139. package/dist/plugins/mcp.d.mts +31 -0
  140. package/dist/plugins/mcp.d.mts.map +1 -0
  141. package/dist/plugins/mcp.mjs +4 -0
  142. package/dist/plugins/privacy.d.mts +22 -0
  143. package/dist/plugins/privacy.d.mts.map +1 -0
  144. package/dist/plugins/privacy.mjs +4 -0
  145. package/dist/plugins/workflows.d.mts +80 -0
  146. package/dist/plugins/workflows.d.mts.map +1 -0
  147. package/dist/plugins/workflows.mjs +4 -0
  148. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  149. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  150. package/dist/privacy-HQnhqf2H.mjs +91 -0
  151. package/dist/privacy-HQnhqf2H.mjs.map +1 -0
  152. package/dist/privacy-UodgY0i_.mjs +44 -0
  153. package/dist/privacy-UodgY0i_.mjs.map +1 -0
  154. package/dist/renown-layers-DmbWLt46.mjs +42 -0
  155. package/dist/renown-layers-DmbWLt46.mjs.map +1 -0
  156. package/dist/schema-BJ-OFAox.mjs +359 -0
  157. package/dist/schema-BJ-OFAox.mjs.map +1 -0
  158. package/dist/schema-w1lShimw.d.mts +258 -0
  159. package/dist/schema-w1lShimw.d.mts.map +1 -0
  160. package/dist/server-BS-PFzoK.mjs +2752 -0
  161. package/dist/server-BS-PFzoK.mjs.map +1 -0
  162. package/dist/server.d.mts +94 -228
  163. package/dist/server.d.mts.map +1 -1
  164. package/dist/server.mjs +5 -4
  165. package/dist/types-Bk4T4D9F.d.mts +318 -0
  166. package/dist/types-Bk4T4D9F.d.mts.map +1 -0
  167. package/dist/utils-Cm0TE6dP.mjs +148 -0
  168. package/dist/utils-Cm0TE6dP.mjs.map +1 -0
  169. package/dist/utils.d.mts +29 -3
  170. package/dist/utils.d.mts.map +1 -1
  171. package/dist/utils.mjs +5 -4
  172. package/dist/worker-pool-gyxJnCxA.mjs +304 -0
  173. package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
  174. package/dist/workflow-runtime-CF5pc8mt.d.mts +33 -0
  175. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  176. package/dist/workflows-mdYUh3Us.mjs +1947 -0
  177. package/dist/workflows-mdYUh3Us.mjs.map +1 -0
  178. package/package.json +86 -24
  179. package/scripts/install-packages.sh +0 -0
  180. package/test/ai-gateway.test.ts +612 -0
  181. package/test/attachment-reference-read-model.test.ts +28 -20
  182. package/test/attachments/byte-grants.test.ts +4 -1
  183. package/test/attachments/download-target.test.ts +36 -20
  184. package/test/attachments/index.test.ts +13 -1
  185. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  186. package/test/attachments/routes-integration.test.ts +1 -0
  187. package/test/attachments/routes.test.ts +132 -12
  188. package/test/attachments/service-config.test.ts +28 -16
  189. package/test/boot-auth-config.test.ts +146 -0
  190. package/test/boot-create-signature-policy.test.ts +15 -13
  191. package/test/boot-desktop-auth.test.ts +278 -0
  192. package/test/boot-env-isolation.test.ts +26 -0
  193. package/test/boot-helpers.ts +19 -0
  194. package/test/boot-inspection-enabled.test.ts +140 -0
  195. package/test/boot-mcp-auth.test.ts +449 -0
  196. package/test/boot-mcp-enabled.test.ts +27 -27
  197. package/test/boot-port-zero.test.ts +101 -0
  198. package/test/boot-preconditions.test.ts +213 -0
  199. package/test/boot-privacy.test.ts +232 -0
  200. package/test/boot-ready-drives.test.ts +141 -0
  201. package/test/boot-undo-v3-flag.test.ts +120 -0
  202. package/test/boot-unsupported-stored-documents.test.ts +23 -19
  203. package/test/boot-without-renown.test.ts +11 -9
  204. package/test/boot-without-require-signatures.test.ts +12 -10
  205. package/test/boot-worker-trust-policy.test.ts +11 -10
  206. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  207. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  208. package/test/config-from-env.test.ts +968 -0
  209. package/test/config-merge.test.ts +351 -0
  210. package/test/config-schema.test.ts +183 -0
  211. package/test/default-composition.test.ts +290 -0
  212. package/test/default-drive-protocol-versions.test.ts +79 -0
  213. package/test/default-drive-slug.test.ts +265 -0
  214. package/test/delegated-publish.test.ts +435 -0
  215. package/test/durable-node-fs-pg16.test.ts +80 -0
  216. package/test/fatal-shutdown.test.ts +104 -1
  217. package/test/fixtures/mixed-subgraphs/subgraphs/greetings/index.ts +16 -0
  218. package/test/fixtures/mixed-subgraphs/subgraphs/index.ts +3 -0
  219. package/test/fixtures/mixed-subgraphs/subgraphs/tally/index.ts +73 -0
  220. package/test/goldens/packages.graphql +797 -0
  221. package/test/goldens/privacy.graphql +853 -0
  222. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  223. package/test/goldens/resolvers.json +327 -0
  224. package/test/goldens/supergraph.graphql +5918 -0
  225. package/test/goldens/workflow-runtime.graphql +1548 -0
  226. package/test/inspection-throttle.test.ts +23 -0
  227. package/test/keyframe-reclaim-store.test.ts +156 -0
  228. package/test/observability-signals.test.ts +131 -0
  229. package/test/permissions-backfill.test.ts +486 -0
  230. package/test/pglite-dialect.test.ts +237 -2
  231. package/test/pglite-preflight.test.ts +313 -0
  232. package/test/pglite-storage-dirs.test.ts +113 -0
  233. package/test/pglite-store.test.ts +441 -0
  234. package/test/pglite-version.test.ts +9 -1
  235. package/test/plugin-config-schemas.test.ts +83 -0
  236. package/test/plugin-presence.test.ts +262 -0
  237. package/test/port-probe.test.ts +45 -0
  238. package/test/processor-timing-log.test.ts +109 -0
  239. package/test/reactor-feature-flags.test.ts +20 -0
  240. package/test/redact-webhook-path.test.ts +9 -0
  241. package/test/renown-storage-path.test.ts +40 -0
  242. package/test/renown-trust-policy.test.ts +7 -9
  243. package/test/served-schemas-mixed-package.test.ts +251 -0
  244. package/test/served-schemas.test.ts +134 -0
  245. package/test/shutdown.test.ts +278 -0
  246. package/test/snapshot-writer.ts +94 -0
  247. package/test/store-lock.test.ts +65 -0
  248. package/test/two-switchboards.test.ts +146 -0
  249. package/test/worker-pool.test.ts +27 -1
  250. package/test/workflow/oauth-apps-config.test.ts +66 -0
  251. package/test/workflow/oauth.test.ts +82 -10
  252. package/test/workflow/resolvers.test.ts +230 -38
  253. package/test/workflow/runtime-host.test.ts +19 -0
  254. package/test/workflow/waitpoint-routes.test.ts +306 -0
  255. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  256. package/test/workflow/webhook-trigger-test.test.ts +8 -0
  257. package/test/workflow-reactor-access.test.ts +384 -0
  258. package/test/workflow-reactor-enforcement.test.ts +808 -0
  259. package/test/workflow-read-gate.test.ts +128 -60
  260. package/test/workflow-runtime.test.ts +1005 -237
  261. package/test/workflows-plugin-config.test.ts +77 -0
  262. package/tsconfig.json +5 -2
  263. package/tsdown.config.ts +12 -0
  264. package/vitest.config.ts +66 -1
  265. package/.tsbuild/test/mcp-flag.test.d.ts +0 -2
  266. package/.tsbuild/test/mcp-flag.test.d.ts.map +0 -1
  267. package/dist/server-sQoWp21G.mjs +0 -2939
  268. package/dist/server-sQoWp21G.mjs.map +0 -1
  269. package/dist/utils-uaBlzyjS.mjs +0 -86
  270. package/dist/utils-uaBlzyjS.mjs.map +0 -1
  271. package/test/mcp-flag.test.ts +0 -56
@@ -0,0 +1,251 @@
1
+ /**
2
+ * One package whose subgraphs index exports a BaseSubgraph subclass and a
3
+ * code-first Subgraph subclass, loaded from `packages.list` the way a local
4
+ * project is. Both serve through the switchboard supergraph: the schema-first
5
+ * query, the code-first query and mutation, the code-first subscription
6
+ * beside the built-in `r` subgraph's on the supergraph's SSE stream, and
7
+ * `r`'s over the WebSocket endpoint.
8
+ */
9
+ import { documentModelDocumentModelModule, type ILogger } from "document-model";
10
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import {
15
+ afterAll,
16
+ afterEach,
17
+ beforeAll,
18
+ describe,
19
+ expect,
20
+ it,
21
+ vi,
22
+ } from "vitest";
23
+ import type { startSwitchboard } from "../src/server.mjs";
24
+ import { bootSwitchboard } from "./boot-helpers.js";
25
+
26
+ const FIXTURE = fileURLToPath(
27
+ new URL("./fixtures/mixed-subgraphs", import.meta.url),
28
+ );
29
+
30
+ function stubLogger(): ILogger {
31
+ const logger = {
32
+ verbose: vi.fn(),
33
+ debug: vi.fn(),
34
+ info: vi.fn(),
35
+ warn: vi.fn(),
36
+ error: vi.fn(),
37
+ child: vi.fn(),
38
+ };
39
+ logger.child.mockReturnValue(logger);
40
+ return logger as unknown as ILogger;
41
+ }
42
+
43
+ let tempRoot: string;
44
+ let switchboard: Awaited<ReturnType<typeof startSwitchboard>> | undefined;
45
+ let origin: string;
46
+ const cleanups: (() => void)[] = [];
47
+
48
+ beforeAll(async () => {
49
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-mixed-package-"));
50
+ const configFile = join(tempRoot, "powerhouse.config.json");
51
+ await writeFile(configFile, "{}");
52
+ switchboard = await bootSwitchboard(
53
+ {
54
+ server: { port: 0 },
55
+ storage: {
56
+ reactor: { url: join(tempRoot, "reactor") },
57
+ readModel: { url: join(tempRoot, "read-model") },
58
+ userDataDir: tempRoot,
59
+ },
60
+ features: { workflows: false, mcp: false },
61
+ packages: { disableLocal: true, list: [FIXTURE] },
62
+ identity: { keypairPath: join(tempRoot, "identity.json") },
63
+ configFile,
64
+ },
65
+ { logger: stubLogger() },
66
+ {},
67
+ );
68
+ origin = `http://127.0.0.1:${switchboard.port}`;
69
+ }, 120_000);
70
+
71
+ afterEach(() => {
72
+ for (const cleanup of cleanups.splice(0)) cleanup();
73
+ });
74
+
75
+ afterAll(async () => {
76
+ try {
77
+ await switchboard?.shutdown();
78
+ } finally {
79
+ await rm(tempRoot, { recursive: true, force: true });
80
+ }
81
+ });
82
+
83
+ async function post(query: string): Promise<unknown> {
84
+ const response = await fetch(`${origin}/graphql`, {
85
+ method: "POST",
86
+ headers: { "content-type": "application/json" },
87
+ body: JSON.stringify({ query }),
88
+ });
89
+ return response.json();
90
+ }
91
+
92
+ /** Every `next` payload of a subscription over the graphql-transport-ws endpoint. */
93
+ function overWebSocket(query: string): unknown[] {
94
+ const events: unknown[] = [];
95
+ const socket = new WebSocket(
96
+ `ws://127.0.0.1:${switchboard!.port}/graphql/subscriptions`,
97
+ "graphql-transport-ws",
98
+ );
99
+ socket.onopen = () =>
100
+ socket.send(JSON.stringify({ type: "connection_init", payload: {} }));
101
+ socket.onmessage = ({ data }) => {
102
+ const message = JSON.parse(String(data)) as {
103
+ type: string;
104
+ payload?: unknown;
105
+ };
106
+ if (message.type === "connection_ack") {
107
+ socket.send(
108
+ JSON.stringify({ id: "1", type: "subscribe", payload: { query } }),
109
+ );
110
+ } else if (message.type === "next") {
111
+ events.push(message.payload);
112
+ } else if (message.type === "error") {
113
+ events.push({ error: message.payload });
114
+ }
115
+ };
116
+ cleanups.push(() => socket.close());
117
+ return events;
118
+ }
119
+
120
+ /** Every `next` payload of a subscription over the supergraph's SSE stream. */
121
+ function overSse(query: string): unknown[] {
122
+ const events: unknown[] = [];
123
+ const controller = new AbortController();
124
+ cleanups.push(() => controller.abort());
125
+ void (async () => {
126
+ const response = await fetch(`${origin}/graphql/stream`, {
127
+ method: "POST",
128
+ headers: {
129
+ "content-type": "application/json",
130
+ accept: "text/event-stream",
131
+ },
132
+ body: JSON.stringify({ query }),
133
+ signal: controller.signal,
134
+ });
135
+ const decoder = new TextDecoder();
136
+ let text = "";
137
+ for await (const chunk of response.body!) {
138
+ text += decoder.decode(chunk as Uint8Array, { stream: true });
139
+ const frames = text.split("\n\n");
140
+ text = frames.pop() ?? "";
141
+ for (const frame of frames) {
142
+ const data = /^data: (.*)$/m.exec(frame)?.[1];
143
+ if (frame.startsWith("event: next") && data !== undefined) {
144
+ events.push(JSON.parse(data));
145
+ }
146
+ }
147
+ }
148
+ })().catch(() => undefined);
149
+ return events;
150
+ }
151
+
152
+ const until = (events: unknown[], count: number) =>
153
+ vi.waitFor(() => expect(events.length).toBeGreaterThanOrEqual(count), {
154
+ timeout: 15_000,
155
+ interval: 50,
156
+ });
157
+
158
+ const DOCUMENT_CHANGES = `subscription {
159
+ documentChanges(search: { type: "powerhouse/document-model" }) {
160
+ type
161
+ documents { id name documentType }
162
+ }
163
+ }`;
164
+
165
+ /** Creates documents named `<prefix>-<n>` until `events` holds one, and checks it is that creation. */
166
+ async function expectDocumentCreation(events: unknown[], prefix: string) {
167
+ const created = new Map<string, string>();
168
+ // A subscription is live some time after it is sent, and nothing tells
169
+ // the client when, so create a document until one arrives.
170
+ let n = 0;
171
+ await vi.waitFor(
172
+ async () => {
173
+ if (events.length === 0) {
174
+ const document =
175
+ documentModelDocumentModelModule.utils.createDocument();
176
+ document.header.name = `${prefix}-${n++}`;
177
+ const stored = await switchboard!.reactor.create(document);
178
+ created.set(document.header.name, stored.header.id);
179
+ }
180
+ expect(events.length).toBeGreaterThan(0);
181
+ },
182
+ { timeout: 15_000, interval: 200 },
183
+ );
184
+ const event = events[0] as {
185
+ data: { documentChanges: { documents: { name: string }[] } };
186
+ };
187
+ const name = event.data.documentChanges.documents[0]?.name ?? "";
188
+ expect(name).toMatch(new RegExp(`^${prefix}-\\d+$`));
189
+ expect(event).toEqual({
190
+ data: {
191
+ documentChanges: {
192
+ type: "CREATED",
193
+ documents: [
194
+ {
195
+ id: created.get(name),
196
+ name,
197
+ documentType: "powerhouse/document-model",
198
+ },
199
+ ],
200
+ },
201
+ },
202
+ });
203
+ }
204
+
205
+ describe("a package with a schema-first and a code-first subgraph", () => {
206
+ it("answers the schema-first query through the supergraph", async () => {
207
+ expect(await post('{ greeting(to: "Ada") }')).toEqual({
208
+ data: { greeting: "Hello, Ada" },
209
+ });
210
+ });
211
+
212
+ it("answers the code-first query and mutation through the supergraph", async () => {
213
+ expect(await post('{ tally(id: "q") { id count doubled } }')).toEqual({
214
+ data: { tally: { id: "q", count: 0, doubled: 0 } },
215
+ });
216
+ expect(
217
+ await post(
218
+ 'mutation { incrementTally(id: "q", by: 3) { id count doubled } }',
219
+ ),
220
+ ).toEqual({
221
+ data: { incrementTally: { id: "q", count: 3, doubled: 6 } },
222
+ });
223
+ expect(await post('{ tally(id: "q") { id count doubled } }')).toEqual({
224
+ data: { tally: { id: "q", count: 3, doubled: 6 } },
225
+ });
226
+ });
227
+ });
228
+
229
+ describe("subscriptions through the supergraph", () => {
230
+ it("delivers the tally, its change and an r document creation over SSE", async () => {
231
+ const id = "sub-SSE";
232
+ const tally = overSse(
233
+ `subscription { tallyChanged(id: "${id}") { id count doubled } }`,
234
+ );
235
+ const documents = overSse(DOCUMENT_CHANGES);
236
+ await until(tally, 1);
237
+ expect(
238
+ await post(`mutation { incrementTally(id: "${id}", by: 2) { count } }`),
239
+ ).toEqual({ data: { incrementTally: { count: 2 } } });
240
+ await until(tally, 2);
241
+ expect(tally).toEqual([
242
+ { data: { tallyChanged: { id, count: 0, doubled: 0 } } },
243
+ { data: { tallyChanged: { id, count: 2, doubled: 4 } } },
244
+ ]);
245
+ await expectDocumentCreation(documents, "SSE");
246
+ }, 30_000);
247
+
248
+ it("delivers an r document creation over WebSocket", async () => {
249
+ await expectDocumentCreation(overWebSocket(DOCUMENT_CHANGES), "WebSocket");
250
+ }, 30_000);
251
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Regenerate after an intended change, from the repository root. Removing the
3
+ * goldens first drops those of endpoints no longer served:
4
+ *
5
+ * rm -rf packages/reactor-api/test/graphql/goldens apps/switchboard/test/goldens && \
6
+ * UPDATE_GOLDENS=1 pnpm --workspace-concurrency=1 \
7
+ * --filter @powerhousedao/reactor-api --filter @powerhousedao/switchboard \
8
+ * exec vitest run served-schemas && pnpm exec oxfmt \
9
+ * packages/reactor-api/test/graphql/goldens apps/switchboard/test/goldens
10
+ */
11
+ import {
12
+ expectSchemaGolden,
13
+ jsonGolden,
14
+ recordServedSchemas,
15
+ type ServedEndpoints,
16
+ } from "@powerhousedao/reactor-api/test";
17
+ import type { ILogger } from "document-model";
18
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
19
+ import { tmpdir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
23
+ import type { startSwitchboard } from "../src/server.mjs";
24
+ import { bootSwitchboard } from "./boot-helpers.js";
25
+
26
+ const goldens = (file: string) =>
27
+ fileURLToPath(new URL(`./goldens/${file}`, import.meta.url));
28
+
29
+ const SUBGRAPHS = [
30
+ "packages",
31
+ "privacy",
32
+ "reactor-drive-nodes",
33
+ "workflow-runtime",
34
+ ];
35
+
36
+ const ADMIN = "0xadad00000000000000000000000000000000adad";
37
+ const SECRET = "switchboard-served-schemas-deployment-secret";
38
+
39
+ function stubLogger(): ILogger {
40
+ const logger = {
41
+ verbose: vi.fn(),
42
+ debug: vi.fn(),
43
+ info: vi.fn(),
44
+ warn: vi.fn(),
45
+ error: vi.fn(),
46
+ child: vi.fn(),
47
+ };
48
+ logger.child.mockReturnValue(logger);
49
+ return logger as unknown as ILogger;
50
+ }
51
+
52
+ const realFetch = globalThis.fetch;
53
+ let tempRoot: string;
54
+ let recorder: ReturnType<typeof recordServedSchemas> | undefined;
55
+ let switchboard: Awaited<ReturnType<typeof startSwitchboard>> | undefined;
56
+ let served: ServedEndpoints;
57
+
58
+ beforeAll(async () => {
59
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-served-schemas-"));
60
+ const configFile = join(tempRoot, "powerhouse.config.json");
61
+ await writeFile(configFile, "{}");
62
+ // The workflow runtime reads a hard-coded cloud piece catalog at boot.
63
+ vi.stubGlobal(
64
+ "fetch",
65
+ (input: string | URL | Request, init?: RequestInit) => {
66
+ const url = new URL(input instanceof Request ? input.url : String(input));
67
+ return url.hostname === "127.0.0.1"
68
+ ? realFetch(input, init)
69
+ : Promise.reject(new Error(`${url.host} is off limits to this test`));
70
+ },
71
+ );
72
+ recorder = recordServedSchemas();
73
+ // Every switchboard subgraph on, from this config alone: no inherited env,
74
+ // config file or user data. The registry URL only turns the packages
75
+ // subgraph on, and the Renown URL keeps discovery off the network.
76
+ switchboard = await bootSwitchboard(
77
+ {
78
+ server: { port: 0 },
79
+ storage: {
80
+ reactor: { url: join(tempRoot, "reactor") },
81
+ readModel: { url: join(tempRoot, "read-model") },
82
+ userDataDir: tempRoot,
83
+ },
84
+ auth: {
85
+ enabled: true,
86
+ admins: [ADMIN],
87
+ renown: { url: "http://127.0.0.1:9" },
88
+ },
89
+ features: {
90
+ workflows: true,
91
+ mcp: false,
92
+ privacy: { enabled: true, deploymentSecret: SECRET },
93
+ },
94
+ packages: { disableLocal: true, registryUrl: "http://127.0.0.1:9" },
95
+ identity: { keypairPath: join(tempRoot, "identity.json") },
96
+ configFile,
97
+ },
98
+ { logger: stubLogger() },
99
+ {},
100
+ );
101
+ served = await recorder.read(
102
+ (request) => realFetch(request),
103
+ `http://127.0.0.1:${switchboard.port}`,
104
+ SUBGRAPHS,
105
+ );
106
+ }, 120_000);
107
+
108
+ afterAll(async () => {
109
+ try {
110
+ await switchboard?.shutdown();
111
+ } finally {
112
+ recorder?.restore();
113
+ vi.unstubAllGlobals();
114
+ await rm(tempRoot, { recursive: true, force: true });
115
+ }
116
+ });
117
+
118
+ describe("switchboard served schemas", () => {
119
+ it.each(SUBGRAPHS)("serves /graphql/%s as its golden", async (name) => {
120
+ const schema = served.subgraphs.get(name);
121
+ expect(schema, `/graphql/${name} is not served`).toBeDefined();
122
+ await expectSchemaGolden(schema!, goldens(`${name}.graphql`));
123
+ });
124
+
125
+ it("serves /graphql as supergraph.graphql", async () => {
126
+ await expectSchemaGolden(served.supergraph, goldens("supergraph.graphql"));
127
+ });
128
+
129
+ it("binds the resolvers in resolvers.json", async () => {
130
+ expect(served.resolvers).toEqual(
131
+ await jsonGolden(goldens("resolvers.json"), served.resolvers),
132
+ );
133
+ });
134
+ });
@@ -0,0 +1,278 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ import {
3
+ ReactorBuilder,
4
+ ReactorClientBuilder,
5
+ type Database,
6
+ type InProcessReactorClientModule,
7
+ } from "@powerhousedao/reactor";
8
+ import type { ILogger } from "document-model";
9
+ import { Kysely } from "kysely";
10
+ import { PGliteDialect } from "kysely-pglite-dialect";
11
+ import { mkdtemp, rm } from "node:fs/promises";
12
+ import { createServer } from "node:net";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ afterEach,
17
+ beforeEach,
18
+ describe,
19
+ expect,
20
+ it,
21
+ vi,
22
+ type MockInstance,
23
+ } from "vitest";
24
+ import { applySwitchboardReactorDefaults } from "../src/builder-defaults.mjs";
25
+ import type { startSwitchboard } from "../src/server.mjs";
26
+ import { bootSwitchboard } from "./boot-helpers.js";
27
+
28
+ type Switchboard = Awaited<ReturnType<typeof startSwitchboard>>;
29
+
30
+ async function freePort(): Promise<number> {
31
+ const server = createServer();
32
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
33
+ const address = server.address();
34
+ await new Promise<void>((resolve) => server.close(() => resolve()));
35
+ if (!address || typeof address === "string") throw new Error("no port");
36
+ return address.port;
37
+ }
38
+
39
+ /** True when nothing holds `port` any more. */
40
+ async function portIsFree(port: number): Promise<boolean> {
41
+ const server = createServer();
42
+ return new Promise((resolve) => {
43
+ server.once("error", () => resolve(false));
44
+ server.listen(port, () => server.close(() => resolve(true)));
45
+ });
46
+ }
47
+
48
+ /** initServer returns the reactor-api handle too; SwitchboardReactor does not
49
+ * type it. Spying on its dispose shows how often the api was drained. */
50
+ function apiOf(sb: object): { dispose: () => Promise<void> } {
51
+ const api: unknown = Reflect.get(sb, "api");
52
+ if (
53
+ typeof api !== "object" ||
54
+ api === null ||
55
+ typeof Reflect.get(api, "dispose") !== "function"
56
+ ) {
57
+ throw new Error("switchboard returned no api handle");
58
+ }
59
+ return api as { dispose: () => Promise<void> };
60
+ }
61
+
62
+ function stubLogger(): ILogger {
63
+ const logger = {
64
+ verbose: vi.fn(),
65
+ debug: vi.fn(),
66
+ info: vi.fn(),
67
+ warn: vi.fn(),
68
+ error: vi.fn(),
69
+ child: vi.fn(),
70
+ };
71
+ logger.child.mockReturnValue(logger);
72
+ return logger as unknown as ILogger;
73
+ }
74
+
75
+ describe("SwitchboardReactor.shutdown", () => {
76
+ let tempRoot: string;
77
+ let previousReactorDb: string | undefined;
78
+ let switchboard: Switchboard | undefined;
79
+ const signalsBefore = {
80
+ SIGINT: new Set<NodeJS.SignalsListener>(),
81
+ SIGTERM: new Set<NodeJS.SignalsListener>(),
82
+ };
83
+ const addedListeners = (signal: "SIGINT" | "SIGTERM") =>
84
+ (process.listeners(signal) as NodeJS.SignalsListener[]).filter(
85
+ (listener) => !signalsBefore[signal].has(listener),
86
+ );
87
+
88
+ beforeEach(async () => {
89
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-shutdown-"));
90
+ previousReactorDb = process.env.PH_REACTOR_DATABASE_URL;
91
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
92
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
93
+ signalsBefore[signal] = new Set(
94
+ process.listeners(signal) as NodeJS.SignalsListener[],
95
+ );
96
+ }
97
+ });
98
+
99
+ afterEach(async () => {
100
+ await switchboard?.shutdown().catch(() => undefined);
101
+ switchboard = undefined;
102
+ vi.restoreAllMocks();
103
+ // The owned reactor's withSignalHandlers() listeners outlive the test.
104
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
105
+ for (const listener of addedListeners(signal)) {
106
+ process.removeListener(signal, listener);
107
+ }
108
+ }
109
+ if (previousReactorDb === undefined) {
110
+ delete process.env.PH_REACTOR_DATABASE_URL;
111
+ } else {
112
+ process.env.PH_REACTOR_DATABASE_URL = previousReactorDb;
113
+ }
114
+ await rm(tempRoot, { recursive: true, force: true });
115
+ });
116
+
117
+ async function start(
118
+ reactor?: InProcessReactorClientModule,
119
+ ): Promise<Switchboard> {
120
+ switchboard = await bootSwitchboard(
121
+ {
122
+ server: { port: 0 },
123
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
124
+ features: { workflows: false, mcp: false },
125
+ packages: { disableLocal: true },
126
+ identity: { keypairPath: join(tempRoot, "identity.json") },
127
+ },
128
+ { reactor, logger: stubLogger() },
129
+ );
130
+ return switchboard;
131
+ }
132
+
133
+ /**
134
+ * Spies on the reactor module the switchboard builds for itself, from the
135
+ * moment it is built (an aborted boot tears it down before returning).
136
+ */
137
+ function watchOwnedReactor() {
138
+ const realBuild = Object.getOwnPropertyDescriptor(
139
+ ReactorClientBuilder.prototype,
140
+ "buildModule",
141
+ )?.value as (
142
+ this: ReactorClientBuilder,
143
+ ) => Promise<InProcessReactorClientModule>;
144
+ const watched: {
145
+ kill?: MockInstance<() => unknown>;
146
+ destroy?: MockInstance<() => Promise<void>>;
147
+ } = {};
148
+ vi.spyOn(ReactorClientBuilder.prototype, "buildModule").mockImplementation(
149
+ async function (this: ReactorClientBuilder) {
150
+ const built = await realBuild.call(this);
151
+ if (!built.reactorModule) throw new Error("no reactor module built");
152
+ watched.kill = vi.spyOn(built.reactorModule.reactor, "kill");
153
+ watched.destroy = vi.spyOn(built.reactorModule.database, "destroy");
154
+ return built;
155
+ },
156
+ );
157
+ return watched;
158
+ }
159
+
160
+ /** Stubbed before boot: the signal handler binds process.exit when the
161
+ * reactor is built. */
162
+ function stubExit() {
163
+ const codes: Array<number | undefined> = [];
164
+ let resolveExit: (code: number | undefined) => void = () => undefined;
165
+ const exited = new Promise<number | undefined>((resolve) => {
166
+ resolveExit = resolve;
167
+ });
168
+ vi.spyOn(process, "exit").mockImplementation((code) => {
169
+ const value = code === undefined ? undefined : Number(code);
170
+ codes.push(value);
171
+ resolveExit(value);
172
+ return undefined as never;
173
+ });
174
+ return { codes, exited };
175
+ }
176
+
177
+ function raiseSigint(): void {
178
+ const sigint = addedListeners("SIGINT");
179
+ expect(sigint).toHaveLength(1);
180
+ sigint[0]!("SIGINT");
181
+ }
182
+
183
+ it("stops an owned reactor and frees the port once, however often it is called", async () => {
184
+ const reactor = watchOwnedReactor();
185
+ const exit = stubExit();
186
+
187
+ const sb = await start();
188
+ const dispose = vi.spyOn(apiOf(sb), "dispose");
189
+ expect(await portIsFree(sb.port)).toBe(false);
190
+
191
+ await Promise.all([sb.shutdown(), sb.shutdown()]);
192
+ await sb.shutdown();
193
+
194
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
195
+ expect(dispose).toHaveBeenCalledTimes(1);
196
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
197
+ expect(await portIsFree(sb.port)).toBe(true);
198
+ expect(exit.codes).toEqual([]);
199
+
200
+ // A later SIGINT joins the finished teardown and only exits.
201
+ raiseSigint();
202
+ expect(await exit.exited).toBe(0);
203
+ expect(exit.codes).toEqual([0]);
204
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
205
+ expect(dispose).toHaveBeenCalledTimes(1);
206
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
207
+ }, 60_000);
208
+
209
+ it("an aborted boot tears the owned reactor down once, through its shutdown", async () => {
210
+ const reactor = watchOwnedReactor();
211
+ const exit = stubExit();
212
+ const previousSource = process.env.RENOWN_SOURCE;
213
+ // No loaded package serves the renown read model: the boot aborts after
214
+ // the reactor and the api are up.
215
+ process.env.RENOWN_SOURCE = "self";
216
+ const port = await freePort();
217
+
218
+ try {
219
+ await expect(
220
+ bootSwitchboard(
221
+ {
222
+ server: { port: port, strictPort: true },
223
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
224
+ features: { workflows: false, mcp: false },
225
+ packages: { disableLocal: true },
226
+ identity: { keypairPath: join(tempRoot, "identity.json") },
227
+ },
228
+ { logger: stubLogger() },
229
+ ),
230
+ ).rejects.toThrow(/no loaded package serves/);
231
+ } finally {
232
+ if (previousSource === undefined) {
233
+ delete process.env.RENOWN_SOURCE;
234
+ } else {
235
+ process.env.RENOWN_SOURCE = previousSource;
236
+ }
237
+ }
238
+
239
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
240
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
241
+ expect(await portIsFree(port)).toBe(true);
242
+
243
+ raiseSigint();
244
+ expect(await exit.exited).toBe(0);
245
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
246
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
247
+ }, 60_000);
248
+
249
+ it("drains the api once and leaves a caller-provided reactor running", async () => {
250
+ const database = new Kysely<Database>({
251
+ dialect: new PGliteDialect(new PGlite()),
252
+ });
253
+ const reactorBuilder = new ReactorBuilder().withKysely(database);
254
+ const clientBuilder = new ReactorClientBuilder().withReactorBuilder(
255
+ reactorBuilder,
256
+ );
257
+ applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
258
+ signalHandlers: false,
259
+ });
260
+ const caller = await clientBuilder.buildModule();
261
+ const callerModule = caller.reactorModule;
262
+ if (!callerModule) throw new Error("caller built no reactor module");
263
+
264
+ try {
265
+ const sb = await start(caller);
266
+ const kill = vi.spyOn(callerModule.reactor, "kill");
267
+ const dispose = vi.spyOn(apiOf(sb), "dispose");
268
+
269
+ await Promise.all([sb.shutdown(), sb.shutdown()]);
270
+
271
+ expect(dispose).toHaveBeenCalledTimes(1);
272
+ expect(kill).not.toHaveBeenCalled();
273
+ expect(await portIsFree(sb.port)).toBe(true);
274
+ } finally {
275
+ await callerModule.shutdown();
276
+ }
277
+ }, 60_000);
278
+ });