@powerhousedao/switchboard 6.2.3-dev.6 → 6.2.3-dev.60

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 (177) 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/durable-node-fs-pg16.test.d.ts +2 -0
  34. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  35. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  36. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  37. package/.tsbuild/test/inspection-flag.test.d.ts +2 -0
  38. package/.tsbuild/test/inspection-flag.test.d.ts.map +1 -0
  39. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  40. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  41. package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
  42. package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
  43. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  44. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  45. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  46. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  47. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  48. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  49. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  50. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  51. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  52. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  53. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  54. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  55. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  56. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  57. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  58. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  59. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  60. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  61. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  62. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  63. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  64. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  65. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  66. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  67. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  68. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  69. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  70. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  71. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  72. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  73. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  74. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  75. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  76. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  77. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  78. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  79. package/.tsbuild/vitest.config.d.ts.map +1 -1
  80. package/Auth.md +144 -2
  81. package/CHANGELOG.md +736 -0
  82. package/README.md +47 -10
  83. package/dist/index.d.mts +2 -1
  84. package/dist/index.mjs +50 -50
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/install-packages.d.mts +2 -1
  87. package/dist/install-packages.mjs +2 -2
  88. package/dist/install-packages.mjs.map +1 -1
  89. package/dist/mcp-cNWW82NH.mjs +27 -0
  90. package/dist/mcp-cNWW82NH.mjs.map +1 -0
  91. package/dist/migrate.d.mts +2 -1
  92. package/dist/migrate.mjs +4 -3
  93. package/dist/migrate.mjs.map +1 -1
  94. package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
  95. package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
  96. package/dist/plugins/attachments.d.mts +23 -0
  97. package/dist/plugins/attachments.d.mts.map +1 -0
  98. package/dist/plugins/attachments.mjs +4 -0
  99. package/dist/plugins/mcp.d.mts +21 -0
  100. package/dist/plugins/mcp.d.mts.map +1 -0
  101. package/dist/plugins/mcp.mjs +4 -0
  102. package/dist/plugins/privacy.d.mts +12 -0
  103. package/dist/plugins/privacy.d.mts.map +1 -0
  104. package/dist/plugins/privacy.mjs +4 -0
  105. package/dist/plugins/workflows.d.mts +36 -0
  106. package/dist/plugins/workflows.d.mts.map +1 -0
  107. package/dist/plugins/workflows.mjs +4 -0
  108. package/dist/privacy-C8KVimKF.mjs +113 -0
  109. package/dist/privacy-C8KVimKF.mjs.map +1 -0
  110. package/dist/{server-CiKkVE6g.mjs → server-C9RQTWTA.mjs} +1132 -222
  111. package/dist/server-C9RQTWTA.mjs.map +1 -0
  112. package/dist/server.d.mts +158 -30
  113. package/dist/server.d.mts.map +1 -1
  114. package/dist/server.mjs +4 -5
  115. package/dist/{utils-Baw7rThP.mjs → utils-uaBlzyjS.mjs} +15 -9
  116. package/dist/utils-uaBlzyjS.mjs.map +1 -0
  117. package/dist/utils.d.mts +4 -5
  118. package/dist/utils.d.mts.map +1 -1
  119. package/dist/utils.mjs +3 -3
  120. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  121. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  122. package/dist/workflows-qKtqZhn3.mjs +1338 -0
  123. package/dist/workflows-qKtqZhn3.mjs.map +1 -0
  124. package/package.json +49 -20
  125. package/scripts/install-packages.sh +0 -0
  126. package/test/attachment-reference-read-model.test.ts +6 -1
  127. package/test/attachments/auth.test.ts +85 -0
  128. package/test/attachments/byte-grants.test.ts +290 -0
  129. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  130. package/test/attachments/download-target.test.ts +201 -32
  131. package/test/attachments/index.test.ts +47 -4
  132. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  133. package/test/attachments/routes-integration.test.ts +60 -4
  134. package/test/attachments/routes.test.ts +271 -24
  135. package/test/attachments/service-config.test.ts +13 -3
  136. package/test/attachments/url-signer.test.ts +105 -0
  137. package/test/boot-create-signature-policy.test.ts +108 -0
  138. package/test/boot-inspection-enabled.test.ts +150 -0
  139. package/test/boot-mcp-enabled.test.ts +130 -0
  140. package/test/boot-privacy.test.ts +243 -0
  141. package/test/boot-unsupported-stored-documents.test.ts +213 -0
  142. package/test/boot-without-renown.test.ts +81 -0
  143. package/test/boot-without-require-signatures.test.ts +74 -0
  144. package/test/boot-worker-trust-policy.test.ts +90 -0
  145. package/test/boot-workflow-singleton-conflict.test.ts +107 -0
  146. package/test/boot-workflow-singleton-retry.test.ts +133 -0
  147. package/test/builder-defaults.test.ts +80 -0
  148. package/test/create-signature-policy.test.ts +69 -0
  149. package/test/durable-node-fs-pg16.test.ts +80 -0
  150. package/test/fatal-shutdown.test.ts +165 -0
  151. package/test/inspection-flag.test.ts +62 -0
  152. package/test/inspection-throttle.test.ts +23 -0
  153. package/test/mcp-flag.test.ts +56 -0
  154. package/test/observability-signals.test.ts +131 -0
  155. package/test/pglite-dialect.test.ts +217 -2
  156. package/test/pglite-preflight.test.ts +313 -0
  157. package/test/pglite-version.test.ts +9 -1
  158. package/test/plugin-presence.test.ts +269 -0
  159. package/test/renown-trust-policy.test.ts +315 -0
  160. package/test/snapshot-writer.ts +94 -0
  161. package/test/unsupported-stored-documents.test.ts +72 -0
  162. package/test/worker-pool.test.ts +27 -1
  163. package/test/workflow/harness.ts +289 -0
  164. package/test/workflow/oauth.test.ts +214 -0
  165. package/test/workflow/resolvers.test.ts +357 -0
  166. package/test/workflow/webhook-dedupe.test.ts +295 -0
  167. package/test/workflow/webhook-signed.test.ts +509 -0
  168. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  169. package/test/workflow/webhook-unsigned.test.ts +345 -0
  170. package/test/workflow-reactor-access.test.ts +384 -0
  171. package/test/workflow-reactor-enforcement.test.ts +808 -0
  172. package/test/workflow-read-gate.test.ts +213 -0
  173. package/test/workflow-runtime.test.ts +1122 -0
  174. package/tsconfig.json +11 -2
  175. package/tsdown.config.ts +9 -1
  176. package/dist/server-CiKkVE6g.mjs.map +0 -1
  177. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { inspectionThrottleFromEnv } from "../src/inspection-throttle.mjs";
3
+
4
+ describe("inspectionThrottleFromEnv", () => {
5
+ it("keeps the default when unset or blank", () => {
6
+ expect(inspectionThrottleFromEnv({})).toEqual({});
7
+ expect(
8
+ inspectionThrottleFromEnv({ PH_INSPECTION_CALLS_PER_MINUTE: " " }),
9
+ ).toEqual({});
10
+ });
11
+
12
+ it("reads PH_INSPECTION_CALLS_PER_MINUTE", () => {
13
+ expect(
14
+ inspectionThrottleFromEnv({ PH_INSPECTION_CALLS_PER_MINUTE: " 30 " }),
15
+ ).toEqual({ callsPerMinute: 30 });
16
+ });
17
+
18
+ it.each(["abc", "-1", "1.5", "0", "1O"])("throws on %s", (raw) => {
19
+ expect(() =>
20
+ inspectionThrottleFromEnv({ PH_INSPECTION_CALLS_PER_MINUTE: raw }),
21
+ ).toThrow(/PH_INSPECTION_CALLS_PER_MINUTE/);
22
+ });
23
+ });
@@ -0,0 +1,56 @@
1
+ import { afterEach, beforeAll, describe, expect, it } from "vitest";
2
+ import { initFeatureFlags } from "../src/feature-flags.js";
3
+ import { MCP_ENABLED, resolveMcpEnabled } from "../src/mcp-flag.mjs";
4
+ import type { BooleanFlagSource } from "../src/workflow-runtime.mjs";
5
+
6
+ describe("resolveMcpEnabled", () => {
7
+ let featureFlags: BooleanFlagSource;
8
+
9
+ beforeAll(async () => {
10
+ featureFlags = await initFeatureFlags();
11
+ });
12
+
13
+ afterEach(() => {
14
+ delete process.env[MCP_ENABLED];
15
+ });
16
+
17
+ it("defaults to on", async () => {
18
+ await expect(resolveMcpEnabled({ featureFlags })).resolves.toBe(true);
19
+ await expect(
20
+ resolveMcpEnabled({ featureFlags, option: true }),
21
+ ).resolves.toBe(true);
22
+ });
23
+
24
+ it('is turned off by MCP_ENABLED="false"', async () => {
25
+ process.env[MCP_ENABLED] = "false";
26
+
27
+ await expect(resolveMcpEnabled({ featureFlags })).resolves.toBe(false);
28
+ });
29
+
30
+ // `ph vetra` passes `mcp: true` explicitly; the env var still wins.
31
+ it("turns off a host that asked for MCP", async () => {
32
+ process.env[MCP_ENABLED] = "false";
33
+
34
+ await expect(
35
+ resolveMcpEnabled({ featureFlags, option: true }),
36
+ ).resolves.toBe(false);
37
+ });
38
+
39
+ it("never turns on a host that switched MCP off", async () => {
40
+ process.env[MCP_ENABLED] = "true";
41
+
42
+ await expect(
43
+ resolveMcpEnabled({ featureFlags, option: false }),
44
+ ).resolves.toBe(false);
45
+ });
46
+
47
+ it("leaves MCP on for any value but the string false", async () => {
48
+ for (const raw of ["true", "0", "no", ""]) {
49
+ process.env[MCP_ENABLED] = raw;
50
+ await expect(
51
+ resolveMcpEnabled({ featureFlags }),
52
+ `MCP_ENABLED=${JSON.stringify(raw)}`,
53
+ ).resolves.toBe(true);
54
+ }
55
+ });
56
+ });
@@ -0,0 +1,131 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+ import { installFatalErrorShutdown } from "../src/fatal-shutdown.mjs";
4
+ import { installObservabilitySignalHandlers } from "../src/observability-signals.mjs";
5
+
6
+ function makeProc() {
7
+ const emitter = new EventEmitter();
8
+ const proc = Object.assign(emitter, {
9
+ pid: 1234,
10
+ exitCode: undefined as number | undefined,
11
+ kill: vi.fn((_pid: number, signal: string) => {
12
+ emitter.emit(signal);
13
+ return true;
14
+ }),
15
+ exit: vi.fn(),
16
+ });
17
+ return proc;
18
+ }
19
+
20
+ const logger = {
21
+ error: vi.fn(),
22
+ } as unknown as Parameters<typeof installFatalErrorShutdown>[0];
23
+
24
+ /** Lets the finally callback behind the flush promise run. */
25
+ async function settleMicrotasks(): Promise<void> {
26
+ await Promise.resolve();
27
+ await Promise.resolve();
28
+ await Promise.resolve();
29
+ }
30
+
31
+ describe("installObservabilitySignalHandlers", () => {
32
+ afterEach(() => {
33
+ vi.useRealTimers();
34
+ });
35
+
36
+ it.each(["SIGINT", "SIGTERM"])(
37
+ "exits 0 after the flush on an ordinary %s",
38
+ async (signal) => {
39
+ const proc = makeProc();
40
+ const flush = vi.fn(() => Promise.resolve());
41
+ installObservabilitySignalHandlers(flush, proc as never);
42
+
43
+ proc.emit(signal);
44
+ await settleMicrotasks();
45
+
46
+ expect(flush).toHaveBeenCalledOnce();
47
+ expect(proc.exit).toHaveBeenCalledExactlyOnceWith(0);
48
+ },
49
+ );
50
+
51
+ it("does not exit before the flush settles", async () => {
52
+ const proc = makeProc();
53
+ let finish: () => void = () => undefined;
54
+ const flush = vi.fn(
55
+ () => new Promise<void>((resolve) => (finish = resolve)),
56
+ );
57
+ installObservabilitySignalHandlers(flush, proc as never);
58
+
59
+ proc.emit("SIGTERM");
60
+ await settleMicrotasks();
61
+ expect(proc.exit).not.toHaveBeenCalled();
62
+
63
+ finish();
64
+ await settleMicrotasks();
65
+ expect(proc.exit).toHaveBeenCalledExactlyOnceWith(0);
66
+ });
67
+
68
+ it("keeps exit code 1 when a fatal error raised the SIGTERM", async () => {
69
+ vi.useFakeTimers();
70
+ const proc = makeProc();
71
+ const flush = vi.fn(() => Promise.resolve());
72
+ // Production order: observability's handlers install at module load,
73
+ // before the fatal handlers.
74
+ installObservabilitySignalHandlers(flush, proc as never);
75
+ installFatalErrorShutdown(logger, proc as never);
76
+
77
+ proc.emit("uncaughtException", new Error("boom"));
78
+ expect(proc.exitCode).toBe(1);
79
+ await settleMicrotasks();
80
+
81
+ // The flush ran, but observability never lowered the code to 0; the
82
+ // process is still alive inside the fatal path's drain budget.
83
+ expect(flush).toHaveBeenCalledOnce();
84
+ expect(proc.exit).not.toHaveBeenCalled();
85
+
86
+ // Fatal-shutdown's backstop owns the exit and preserves code 1.
87
+ vi.advanceTimersByTime(15_000);
88
+ expect(proc.exit).toHaveBeenCalledExactlyOnceWith(1);
89
+ expect(proc.exit).not.toHaveBeenCalledWith(0);
90
+ expect(proc.exitCode).toBe(1);
91
+ });
92
+
93
+ it("leaves the fatal drain budget intact even when the flush is slow", async () => {
94
+ vi.useFakeTimers();
95
+ const proc = makeProc();
96
+ let finish: () => void = () => undefined;
97
+ const flush = vi.fn(
98
+ () => new Promise<void>((resolve) => (finish = resolve)),
99
+ );
100
+ installObservabilitySignalHandlers(flush, proc as never);
101
+ installFatalErrorShutdown(logger, proc as never);
102
+
103
+ proc.emit("uncaughtException", new Error("boom"));
104
+
105
+ // The flush gives up at its own ~5s budget (simulated by resolving it
106
+ // here); that settling must not force an exit ahead of the drain.
107
+ vi.advanceTimersByTime(5_000);
108
+ finish();
109
+ await settleMicrotasks();
110
+ expect(proc.exit).not.toHaveBeenCalled();
111
+
112
+ // Only the 15s fatal backstop ends the process, with code 1.
113
+ vi.advanceTimersByTime(9_999);
114
+ expect(proc.exit).not.toHaveBeenCalled();
115
+ vi.advanceTimersByTime(1);
116
+ expect(proc.exit).toHaveBeenCalledExactlyOnceWith(1);
117
+ });
118
+
119
+ it("respects a non-zero exit code set by any other module", async () => {
120
+ const proc = makeProc();
121
+ proc.exitCode = 1;
122
+ const flush = vi.fn(() => Promise.resolve());
123
+ installObservabilitySignalHandlers(flush, proc as never);
124
+
125
+ proc.emit("SIGTERM");
126
+ await settleMicrotasks();
127
+
128
+ expect(flush).toHaveBeenCalledOnce();
129
+ expect(proc.exit).not.toHaveBeenCalled();
130
+ });
131
+ });
@@ -1,7 +1,62 @@
1
1
  import { PGlite } from "@electric-sql/pglite";
2
2
  import { Kysely, sql } from "kysely";
3
- import { afterEach, describe, expect, it } from "vitest";
4
- import { ClosablePGliteDialect } from "../src/pglite-dialect.js";
3
+ import type { ILogger } from "document-model";
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
5
+ import {
6
+ IN_MEMORY_PGLITE_STORAGE_FACTS,
7
+ PGLITE_PATH_STORAGE_FACTS,
8
+ POSTGRES_STORAGE_FACTS,
9
+ } from "@powerhousedao/reactor";
10
+ import { mkdtemp, rm } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { createReactorKysely } from "../src/server.mjs";
14
+ import { EventEmitter } from "node:events";
15
+ import { installFatalErrorShutdown } from "../src/fatal-shutdown.mjs";
16
+ import {
17
+ ClosablePGliteDialect,
18
+ reactorPgliteDialectOptions,
19
+ } from "../src/pglite-dialect.js";
20
+
21
+ type Row = { id: number };
22
+ type Schema = { t: Row };
23
+
24
+ function stubLogger(): ILogger {
25
+ const logger = {
26
+ verbose: vi.fn(),
27
+ debug: vi.fn(),
28
+ info: vi.fn(),
29
+ warn: vi.fn(),
30
+ error: vi.fn(),
31
+ child: vi.fn(),
32
+ };
33
+ logger.child.mockReturnValue(logger);
34
+ return logger as unknown as ILogger;
35
+ }
36
+
37
+ /** COMMIT on an aborted transaction silently rolls back unless the dialect guards it. */
38
+ async function commitOfAnAbortedTransaction(
39
+ db: Kysely<Schema>,
40
+ ): Promise<{ outcome: unknown; rows: Row[] }> {
41
+ await sql`create table t (id int primary key)`.execute(db);
42
+ const outcome = await db
43
+ .transaction()
44
+ .execute(async (trx) => {
45
+ await sql`insert into t (id) values (1)`.execute(trx);
46
+ try {
47
+ await sql`select 1 / 0`.execute(trx);
48
+ } catch {
49
+ /* swallowed, exactly as an unrelated caller would */
50
+ }
51
+ return "JOB-SUCCEEDED";
52
+ })
53
+ .then(
54
+ (value: unknown) => value,
55
+ (error: Error) => ({ error: error.message }),
56
+ );
57
+ const rows = await sql<Row>`select id from t`.execute(db);
58
+ return { outcome, rows: rows.rows };
59
+ }
5
60
 
6
61
  describe("ClosablePGliteDialect", () => {
7
62
  const created: PGlite[] = [];
@@ -26,6 +81,34 @@ describe("ClosablePGliteDialect", () => {
26
81
  expect(pglite.closed).toBe(true);
27
82
  });
28
83
 
84
+ it("tolerates a close that rejects because the runtime aborted", async () => {
85
+ const pglite = new PGlite();
86
+ created.push(pglite);
87
+ const db = new Kysely({ dialect: new ClosablePGliteDialect(pglite) });
88
+ await sql`select 1`.execute(db);
89
+ const realClose = pglite.close.bind(pglite);
90
+ pglite.close = () => {
91
+ pglite.close = realClose;
92
+ return Promise.reject(new Error("PGlite aborted: ENOSPC"));
93
+ };
94
+
95
+ await expect(db.destroy()).resolves.toBeUndefined();
96
+ });
97
+
98
+ it("rethrows a close that fails for any other reason", async () => {
99
+ const pglite = new PGlite();
100
+ created.push(pglite);
101
+ const db = new Kysely({ dialect: new ClosablePGliteDialect(pglite) });
102
+ await sql`select 1`.execute(db);
103
+ const realClose = pglite.close.bind(pglite);
104
+ pglite.close = () => {
105
+ pglite.close = realClose;
106
+ return Promise.reject(new Error("disk gone"));
107
+ };
108
+
109
+ await expect(db.destroy()).rejects.toThrow("disk gone");
110
+ });
111
+
29
112
  it("is idempotent if the PGlite is already closed", async () => {
30
113
  const pglite = new PGlite();
31
114
  created.push(pglite);
@@ -37,4 +120,136 @@ describe("ClosablePGliteDialect", () => {
37
120
 
38
121
  await expect(db.destroy()).resolves.toBeUndefined();
39
122
  });
123
+
124
+ it("refuses to report a commit for an aborted transaction", async () => {
125
+ const pglite = new PGlite();
126
+ created.push(pglite);
127
+ const db = new Kysely<Schema>({
128
+ dialect: new ClosablePGliteDialect(pglite, {
129
+ onDiagnostic: () => undefined,
130
+ }),
131
+ });
132
+
133
+ const { outcome, rows } = await commitOfAnAbortedTransaction(db);
134
+ expect(outcome).not.toBe("JOB-SUCCEEDED");
135
+ expect(rows).toEqual([]);
136
+
137
+ await db.destroy();
138
+ });
139
+ });
140
+
141
+ describe("switchboard's reactor storage factory", () => {
142
+ it("builds a PGlite kysely with the commit guard", async () => {
143
+ const storage = await createReactorKysely({
144
+ reactorDbUrl: undefined,
145
+ reactorPgliteDir: ".ph/unused-by-the-in-memory-branch",
146
+ reactorPgliteMajor: 17,
147
+ inMemory: true,
148
+ hostPoolSize: () => {
149
+ throw new Error("the PGlite branch must not read the host pool size");
150
+ },
151
+ logger: stubLogger(),
152
+ });
153
+
154
+ const { outcome, rows } = await commitOfAnAbortedTransaction(
155
+ storage.kysely as unknown as Kysely<Schema>,
156
+ );
157
+ expect(outcome).not.toBe("JOB-SUCCEEDED");
158
+ expect(rows).toEqual([]);
159
+ expect(storage.poolInstrumentation).toBeUndefined();
160
+
161
+ await storage.kysely.destroy();
162
+ });
163
+
164
+ describe("storage facts", () => {
165
+ let dataDir: string | undefined;
166
+
167
+ afterEach(async () => {
168
+ if (dataDir) await rm(dataDir, { recursive: true, force: true });
169
+ dataDir = undefined;
170
+ });
171
+
172
+ const open = (opts: Partial<Parameters<typeof createReactorKysely>[0]>) =>
173
+ createReactorKysely({
174
+ reactorDbUrl: undefined,
175
+ reactorPgliteDir: ".ph/unused-by-the-in-memory-branch",
176
+ reactorPgliteMajor: 17,
177
+ inMemory: false,
178
+ hostPoolSize: () => 1,
179
+ logger: stubLogger(),
180
+ ...opts,
181
+ });
182
+
183
+ // Kysely closes only a driver that has run a query; an unopened PGlite
184
+ // would still be initialising its data dir when afterEach removes it.
185
+ const openAndDestroy = async (
186
+ kysely: Awaited<ReturnType<typeof createReactorKysely>>["kysely"],
187
+ ) => {
188
+ await sql`select 1`.execute(kysely);
189
+ await kysely.destroy();
190
+ };
191
+
192
+ it("reports in-memory PGlite as not durable", async () => {
193
+ const storage = await open({ inMemory: true });
194
+ expect(storage.storageFacts).toEqual(IN_MEMORY_PGLITE_STORAGE_FACTS);
195
+ await openAndDestroy(storage.kysely);
196
+ });
197
+
198
+ it("reports a PGlite data directory as durable on a path", async () => {
199
+ dataDir = await mkdtemp(join(tmpdir(), "sb-facts-"));
200
+ const storage = await open({ reactorPgliteDir: dataDir });
201
+ expect(storage.storageFacts).toEqual(PGLITE_PATH_STORAGE_FACTS);
202
+ await openAndDestroy(storage.kysely);
203
+ }, 30_000);
204
+
205
+ it("reports a Postgres url as a durable server", async () => {
206
+ const storage = await open({
207
+ reactorDbUrl: "postgres://postgres:postgres@127.0.0.1:1/never-dialed",
208
+ });
209
+ expect(storage.storageFacts).toEqual(POSTGRES_STORAGE_FACTS);
210
+ await storage.kysely.destroy();
211
+ });
212
+ });
213
+ });
214
+
215
+ describe("a poisoned reactor PGlite session", () => {
216
+ it("takes the fatal shutdown path", async () => {
217
+ const emitter = new EventEmitter();
218
+ const proc = Object.assign(emitter, {
219
+ pid: 1234,
220
+ exitCode: undefined as number | undefined,
221
+ kill: vi.fn(() => true),
222
+ exit: vi.fn(),
223
+ });
224
+ const logger = stubLogger();
225
+ installFatalErrorShutdown(logger, proc as never);
226
+
227
+ const pglite = new PGlite();
228
+ const dead = new Proxy(pglite, {
229
+ get(target, prop, receiver) {
230
+ if (prop === "query") {
231
+ return (text: string, params?: unknown[]) =>
232
+ /dead_call/.test(text)
233
+ ? new Promise(() => undefined)
234
+ : target.query(text, params);
235
+ }
236
+ const value = Reflect.get(target, prop, receiver) as unknown;
237
+ return typeof value === "function"
238
+ ? (value as (...args: unknown[]) => unknown).bind(target)
239
+ : value;
240
+ },
241
+ });
242
+ const db = new Kysely<Schema>({
243
+ dialect: new ClosablePGliteDialect(dead, {
244
+ ...reactorPgliteDialectOptions(logger, proc as never),
245
+ statementTimeoutMs: 50,
246
+ }),
247
+ });
248
+
249
+ await expect(sql`select 1 as dead_call`.execute(db)).rejects.toThrow();
250
+
251
+ expect(proc.kill).toHaveBeenCalledWith(1234, "SIGTERM");
252
+ expect(proc.exitCode).toBe(1);
253
+ await pglite.close();
254
+ });
40
255
  });