@powerhousedao/switchboard 6.2.3-dev.7 → 6.2.3-dev.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  2. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  29. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  30. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  31. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  32. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  34. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  35. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  36. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  37. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  38. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  39. package/.tsbuild/test/inspection-flag.test.d.ts +2 -0
  40. package/.tsbuild/test/inspection-flag.test.d.ts.map +1 -0
  41. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  42. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  43. package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
  44. package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
  45. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  46. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  47. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  48. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  49. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  50. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  51. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  52. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  53. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  54. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  55. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  56. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  57. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  58. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  59. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  60. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  61. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  62. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  63. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  64. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  65. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  66. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  67. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  68. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  69. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  70. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  71. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  72. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  73. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  74. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  75. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  76. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  77. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  78. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  79. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  80. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  81. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  82. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  83. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  84. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  85. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  86. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  87. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  88. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  89. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  90. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  91. package/.tsbuild/vitest.config.d.ts.map +1 -1
  92. package/Auth.md +144 -2
  93. package/CHANGELOG.md +869 -0
  94. package/README.md +47 -10
  95. package/dist/index.d.mts +2 -1
  96. package/dist/index.mjs +50 -50
  97. package/dist/index.mjs.map +1 -1
  98. package/dist/install-packages.d.mts +2 -1
  99. package/dist/install-packages.mjs +2 -2
  100. package/dist/install-packages.mjs.map +1 -1
  101. package/dist/mcp-SsBK14Jm.mjs +32 -0
  102. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  103. package/dist/migrate.d.mts +2 -1
  104. package/dist/migrate.mjs +4 -3
  105. package/dist/migrate.mjs.map +1 -1
  106. package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
  107. package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
  108. package/dist/plugins/attachments.d.mts +33 -0
  109. package/dist/plugins/attachments.d.mts.map +1 -0
  110. package/dist/plugins/attachments.mjs +4 -0
  111. package/dist/plugins/mcp.d.mts +31 -0
  112. package/dist/plugins/mcp.d.mts.map +1 -0
  113. package/dist/plugins/mcp.mjs +4 -0
  114. package/dist/plugins/privacy.d.mts +22 -0
  115. package/dist/plugins/privacy.d.mts.map +1 -0
  116. package/dist/plugins/privacy.mjs +4 -0
  117. package/dist/plugins/workflows.d.mts +79 -0
  118. package/dist/plugins/workflows.d.mts.map +1 -0
  119. package/dist/plugins/workflows.mjs +4 -0
  120. package/dist/privacy-BsFl7GzK.mjs +118 -0
  121. package/dist/privacy-BsFl7GzK.mjs.map +1 -0
  122. package/dist/{server-CiKkVE6g.mjs → server-Be1vmpxu.mjs} +1213 -244
  123. package/dist/server-Be1vmpxu.mjs.map +1 -0
  124. package/dist/server.d.mts +208 -45
  125. package/dist/server.d.mts.map +1 -1
  126. package/dist/server.mjs +4 -5
  127. package/dist/{utils-Baw7rThP.mjs → utils-Dh845exv.mjs} +48 -9
  128. package/dist/utils-Dh845exv.mjs.map +1 -0
  129. package/dist/utils.d.mts +10 -5
  130. package/dist/utils.d.mts.map +1 -1
  131. package/dist/utils.mjs +3 -3
  132. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  133. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  134. package/dist/workflows-fsBcElEi.mjs +1382 -0
  135. package/dist/workflows-fsBcElEi.mjs.map +1 -0
  136. package/package.json +50 -20
  137. package/scripts/install-packages.sh +0 -0
  138. package/test/attachment-reference-read-model.test.ts +6 -1
  139. package/test/attachments/auth.test.ts +85 -0
  140. package/test/attachments/byte-grants.test.ts +290 -0
  141. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  142. package/test/attachments/download-target.test.ts +201 -32
  143. package/test/attachments/index.test.ts +47 -4
  144. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  145. package/test/attachments/routes-integration.test.ts +60 -4
  146. package/test/attachments/routes.test.ts +271 -24
  147. package/test/attachments/service-config.test.ts +13 -3
  148. package/test/attachments/url-signer.test.ts +105 -0
  149. package/test/boot-create-signature-policy.test.ts +108 -0
  150. package/test/boot-inspection-enabled.test.ts +150 -0
  151. package/test/boot-mcp-enabled.test.ts +130 -0
  152. package/test/boot-privacy.test.ts +243 -0
  153. package/test/boot-unsupported-stored-documents.test.ts +213 -0
  154. package/test/boot-without-renown.test.ts +81 -0
  155. package/test/boot-without-require-signatures.test.ts +74 -0
  156. package/test/boot-worker-trust-policy.test.ts +90 -0
  157. package/test/boot-workflow-singleton-conflict.test.ts +107 -0
  158. package/test/boot-workflow-singleton-retry.test.ts +133 -0
  159. package/test/builder-defaults.test.ts +80 -0
  160. package/test/create-signature-policy.test.ts +69 -0
  161. package/test/default-drive-slug.test.ts +97 -0
  162. package/test/durable-node-fs-pg16.test.ts +80 -0
  163. package/test/fatal-shutdown.test.ts +165 -0
  164. package/test/inspection-flag.test.ts +62 -0
  165. package/test/inspection-throttle.test.ts +23 -0
  166. package/test/mcp-flag.test.ts +56 -0
  167. package/test/observability-signals.test.ts +131 -0
  168. package/test/pglite-dialect.test.ts +217 -2
  169. package/test/pglite-preflight.test.ts +313 -0
  170. package/test/pglite-storage-dirs.test.ts +103 -0
  171. package/test/pglite-version.test.ts +9 -1
  172. package/test/plugin-config-schemas.test.ts +83 -0
  173. package/test/plugin-presence.test.ts +269 -0
  174. package/test/port-probe.test.ts +45 -0
  175. package/test/renown-trust-policy.test.ts +315 -0
  176. package/test/shutdown.test.ts +278 -0
  177. package/test/snapshot-writer.ts +94 -0
  178. package/test/unsupported-stored-documents.test.ts +72 -0
  179. package/test/worker-pool.test.ts +27 -1
  180. package/test/workflow/harness.ts +289 -0
  181. package/test/workflow/oauth.test.ts +214 -0
  182. package/test/workflow/resolvers.test.ts +357 -0
  183. package/test/workflow/webhook-dedupe.test.ts +295 -0
  184. package/test/workflow/webhook-signed.test.ts +509 -0
  185. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  186. package/test/workflow/webhook-unsigned.test.ts +345 -0
  187. package/test/workflow-reactor-access.test.ts +384 -0
  188. package/test/workflow-reactor-enforcement.test.ts +808 -0
  189. package/test/workflow-read-gate.test.ts +213 -0
  190. package/test/workflow-runtime.test.ts +1122 -0
  191. package/test/workflows-plugin-config.test.ts +77 -0
  192. package/tsconfig.json +11 -2
  193. package/tsdown.config.ts +9 -1
  194. package/dist/server-CiKkVE6g.mjs.map +0 -1
  195. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -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 { startSwitchboard } from "../src/server.mjs";
26
+
27
+ type Switchboard = Awaited<ReturnType<typeof startSwitchboard>>;
28
+
29
+ async function freePort(): Promise<number> {
30
+ const server = createServer();
31
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
32
+ const address = server.address();
33
+ await new Promise<void>((resolve) => server.close(() => resolve()));
34
+ if (!address || typeof address === "string") throw new Error("no port");
35
+ return address.port;
36
+ }
37
+
38
+ /** True when nothing holds `port` any more. */
39
+ async function portIsFree(port: number): Promise<boolean> {
40
+ const server = createServer();
41
+ return new Promise((resolve) => {
42
+ server.once("error", () => resolve(false));
43
+ server.listen(port, () => server.close(() => resolve(true)));
44
+ });
45
+ }
46
+
47
+ /** initServer returns the reactor-api handle too; SwitchboardReactor does not
48
+ * type it. Spying on its dispose shows how often the api was drained. */
49
+ function apiOf(sb: object): { dispose: () => Promise<void> } {
50
+ const api: unknown = Reflect.get(sb, "api");
51
+ if (
52
+ typeof api !== "object" ||
53
+ api === null ||
54
+ typeof Reflect.get(api, "dispose") !== "function"
55
+ ) {
56
+ throw new Error("switchboard returned no api handle");
57
+ }
58
+ return api as { dispose: () => Promise<void> };
59
+ }
60
+
61
+ function stubLogger(): ILogger {
62
+ const logger = {
63
+ verbose: vi.fn(),
64
+ debug: vi.fn(),
65
+ info: vi.fn(),
66
+ warn: vi.fn(),
67
+ error: vi.fn(),
68
+ child: vi.fn(),
69
+ };
70
+ logger.child.mockReturnValue(logger);
71
+ return logger as unknown as ILogger;
72
+ }
73
+
74
+ describe("SwitchboardReactor.shutdown", () => {
75
+ let tempRoot: string;
76
+ let previousReactorDb: string | undefined;
77
+ let switchboard: Switchboard | undefined;
78
+ const signalsBefore = {
79
+ SIGINT: new Set<NodeJS.SignalsListener>(),
80
+ SIGTERM: new Set<NodeJS.SignalsListener>(),
81
+ };
82
+ const addedListeners = (signal: "SIGINT" | "SIGTERM") =>
83
+ (process.listeners(signal) as NodeJS.SignalsListener[]).filter(
84
+ (listener) => !signalsBefore[signal].has(listener),
85
+ );
86
+
87
+ beforeEach(async () => {
88
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-shutdown-"));
89
+ previousReactorDb = process.env.PH_REACTOR_DATABASE_URL;
90
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
91
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
92
+ signalsBefore[signal] = new Set(
93
+ process.listeners(signal) as NodeJS.SignalsListener[],
94
+ );
95
+ }
96
+ });
97
+
98
+ afterEach(async () => {
99
+ await switchboard?.shutdown().catch(() => undefined);
100
+ switchboard = undefined;
101
+ vi.restoreAllMocks();
102
+ // The owned reactor's withSignalHandlers() listeners outlive the test.
103
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
104
+ for (const listener of addedListeners(signal)) {
105
+ process.removeListener(signal, listener);
106
+ }
107
+ }
108
+ if (previousReactorDb === undefined) {
109
+ delete process.env.PH_REACTOR_DATABASE_URL;
110
+ } else {
111
+ process.env.PH_REACTOR_DATABASE_URL = previousReactorDb;
112
+ }
113
+ await rm(tempRoot, { recursive: true, force: true });
114
+ });
115
+
116
+ async function start(
117
+ reactor?: InProcessReactorClientModule,
118
+ ): Promise<Switchboard> {
119
+ switchboard = await startSwitchboard({
120
+ reactor,
121
+ workflows: { enabled: false },
122
+ dbPath: join(tempRoot, "read-model"),
123
+ port: await freePort(),
124
+ strictPort: true,
125
+ mcp: false,
126
+ disableLocalPackages: true,
127
+ identity: { keypairPath: join(tempRoot, "identity.json") },
128
+ 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
+ startSwitchboard({
221
+ workflows: { enabled: false },
222
+ dbPath: join(tempRoot, "read-model"),
223
+ port,
224
+ strictPort: true,
225
+ mcp: false,
226
+ disableLocalPackages: true,
227
+ identity: { keypairPath: join(tempRoot, "identity.json") },
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
+ });
@@ -0,0 +1,94 @@
1
+ // Test-only v1 snapshot.bin writer over a loose on-disk tree.
2
+ import { promises as fs } from "node:fs";
3
+ import type { FileHandle } from "node:fs/promises";
4
+ import path from "node:path";
5
+
6
+ const MAGIC = new Uint8Array([0x50, 0x47, 0x4c, 0x41]);
7
+ const FORMAT_VERSION = 1;
8
+ const HEADER_SIZE = 12;
9
+ const ENTRY_PREFIX_SIZE = 9;
10
+ const DEFAULT_SKIP = ["snapshot.bin", "snapshot.bin.tmp"];
11
+
12
+ export interface SnapshotEntry {
13
+ type: 0 | 1;
14
+ mode: number;
15
+ relPath: string;
16
+ data?: Buffer;
17
+ }
18
+
19
+ export interface WriteSnapshotOptions {
20
+ /** Root-level names to leave out. Defaults to the snapshot files. */
21
+ skip?: string[];
22
+ }
23
+
24
+ export async function collectDiskEntries(
25
+ dataDir: string,
26
+ options: WriteSnapshotOptions = {},
27
+ ): Promise<SnapshotEntry[]> {
28
+ const skip = new Set(options.skip ?? DEFAULT_SKIP);
29
+ const entries: SnapshotEntry[] = [];
30
+ const walk = async (dir: string, rel: string) => {
31
+ const names = (await fs.readdir(dir)).sort();
32
+ for (const name of names) {
33
+ if (rel === "" && skip.has(name)) continue;
34
+ const full = path.join(dir, name);
35
+ const relPath = rel === "" ? name : `${rel}/${name}`;
36
+ const stat = await fs.lstat(full);
37
+ if (stat.isDirectory()) {
38
+ entries.push({ type: 0, mode: stat.mode & 0o7777, relPath });
39
+ await walk(full, relPath);
40
+ } else if (stat.isFile()) {
41
+ entries.push({
42
+ type: 1,
43
+ mode: stat.mode & 0o7777,
44
+ relPath,
45
+ data: await fs.readFile(full),
46
+ });
47
+ }
48
+ }
49
+ };
50
+ await walk(dataDir, "");
51
+ return entries;
52
+ }
53
+
54
+ export function encodeSnapshot(entries: SnapshotEntry[]): Buffer {
55
+ const encoder = new TextEncoder();
56
+ const parts: Buffer[] = [];
57
+ const header = Buffer.alloc(HEADER_SIZE);
58
+ header.set(MAGIC, 0);
59
+ header.writeUInt32LE(FORMAT_VERSION, 4);
60
+ header.writeUInt32LE(entries.length, 8);
61
+ parts.push(header);
62
+ for (const entry of entries) {
63
+ const pathBytes = encoder.encode(entry.relPath);
64
+ const dataLen = entry.data?.byteLength ?? 0;
65
+ const prefix = Buffer.alloc(ENTRY_PREFIX_SIZE + pathBytes.byteLength + 4);
66
+ prefix.writeUInt8(entry.type, 0);
67
+ prefix.writeUInt32LE(entry.mode, 1);
68
+ prefix.writeUInt32LE(pathBytes.byteLength, 5);
69
+ prefix.set(pathBytes, ENTRY_PREFIX_SIZE);
70
+ prefix.writeUInt32LE(dataLen, ENTRY_PREFIX_SIZE + pathBytes.byteLength);
71
+ parts.push(prefix);
72
+ if (entry.data && dataLen > 0) parts.push(entry.data);
73
+ }
74
+ return Buffer.concat(parts);
75
+ }
76
+
77
+ /** Serializes `dataDir` into `snapshotPath`. Returns the entry count and size. */
78
+ export async function writeSnapshotFromDir(
79
+ dataDir: string,
80
+ snapshotPath: string,
81
+ options: WriteSnapshotOptions = {},
82
+ ): Promise<{ entries: number; bytes: number }> {
83
+ const entries = await collectDiskEntries(dataDir, options);
84
+ const bytes = encodeSnapshot(entries);
85
+ let fh: FileHandle | undefined;
86
+ try {
87
+ fh = await fs.open(snapshotPath, "w");
88
+ await fh.writeFile(bytes);
89
+ await fh.sync();
90
+ } finally {
91
+ await fh?.close();
92
+ }
93
+ return { entries: entries.length, bytes: bytes.byteLength };
94
+ }
@@ -0,0 +1,72 @@
1
+ import { UnsupportedStoredProtocolError } from "@powerhousedao/reactor";
2
+ import { describe, expect, it } from "vitest";
3
+ import {
4
+ StoredDocumentsRefusedError,
5
+ resolveUnsupportedStoredDocuments,
6
+ } from "../src/unsupported-stored-documents.mjs";
7
+
8
+ describe("resolveUnsupportedStoredDocuments", () => {
9
+ it("refuses by default", () => {
10
+ expect(resolveUnsupportedStoredDocuments(undefined, {})).toBe("refuse");
11
+ expect(
12
+ resolveUnsupportedStoredDocuments(undefined, {
13
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: " ",
14
+ }),
15
+ ).toBe("refuse");
16
+ });
17
+
18
+ it("reads REACTOR_UNSUPPORTED_STORED_DOCUMENTS", () => {
19
+ expect(
20
+ resolveUnsupportedStoredDocuments(undefined, {
21
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: " read-only ",
22
+ }),
23
+ ).toBe("read-only");
24
+ expect(
25
+ resolveUnsupportedStoredDocuments(undefined, {
26
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: "refuse",
27
+ }),
28
+ ).toBe("refuse");
29
+ });
30
+
31
+ it("lets the option win over the env var", () => {
32
+ expect(
33
+ resolveUnsupportedStoredDocuments("refuse", {
34
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: "read-only",
35
+ }),
36
+ ).toBe("refuse");
37
+ });
38
+
39
+ it("refuses an unknown value", () => {
40
+ expect(() =>
41
+ resolveUnsupportedStoredDocuments(undefined, {
42
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: "readonly",
43
+ }),
44
+ ).toThrow(
45
+ 'REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "readonly"',
46
+ );
47
+ });
48
+ });
49
+
50
+ describe("StoredDocumentsRefusedError", () => {
51
+ it("names the versions, the count and both ways forward", () => {
52
+ const cause = new UnsupportedStoredProtocolError(
53
+ [
54
+ { protocol: "base-reducer", version: 3 },
55
+ { protocol: "base-reducer", version: 7 },
56
+ ],
57
+ 4,
58
+ );
59
+
60
+ const error = new StoredDocumentsRefusedError(cause);
61
+
62
+ expect(error.message).toBe(
63
+ "Refusing to start: 4 stored document(s) require base-reducer 3, base-reducer 7, which this switchboard does not run. " +
64
+ "Either start a switchboard build that runs base-reducer 3, base-reducer 7, or set REACTOR_UNSUPPORTED_STORED_DOCUMENTS=read-only to start with those documents read-only.",
65
+ );
66
+ expect(error.documents).toBe(4);
67
+ expect(error.versions).toBe(cause.versions);
68
+ expect(error.cause).toBe(cause);
69
+ expect(StoredDocumentsRefusedError.isError(error)).toBe(true);
70
+ expect(StoredDocumentsRefusedError.isError(cause)).toBe(false);
71
+ });
72
+ });
@@ -1,9 +1,12 @@
1
1
  import type { ILogger } from "document-model";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
3
5
  import { describe, expect, it, vi } from "vitest";
4
6
  import {
5
7
  autoWorkerCount,
6
8
  buildWorkerDbConfig,
9
+ keepImportableSources,
7
10
  resolveHostPoolSize,
8
11
  resolveWorkerModelSources,
9
12
  resolveWorkerPoolOptions,
@@ -264,3 +267,26 @@ describe("resolveWorkerModelSources", () => {
264
267
  expect(logger.warn).toHaveBeenCalledTimes(1);
265
268
  });
266
269
  });
270
+
271
+ describe("keepImportableSources", () => {
272
+ it("keeps sources that export a model and drops one that throws or has none", async () => {
273
+ const dir = mkdtempSync(path.join(tmpdir(), "ph-model-sources-"));
274
+ const good = path.join(dir, "good.mjs");
275
+ const broken = path.join(dir, "broken.mjs");
276
+ const empty = path.join(dir, "empty.mjs");
277
+ writeFileSync(
278
+ good,
279
+ 'export const Model = { reducer: () => ({}), documentModel: { global: { id: "test/model" } } };',
280
+ );
281
+ writeFileSync(broken, 'throw new Error("stale dist");');
282
+ // What `ph init` builds for a project with no models yet.
283
+ writeFileSync(empty, "export {};");
284
+
285
+ const kept = await keepImportableSources(
286
+ [{ filePath: broken }, { filePath: good }, { filePath: empty }],
287
+ stubLogger(),
288
+ );
289
+
290
+ expect(kept).toEqual([{ filePath: good }]);
291
+ });
292
+ });