@xlinklight/testkit 7.0.0-rc.0 → 7.0.0

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 (59) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +169 -169
  3. package/package.json +4 -4
  4. package/src/architecture-database.d.mts +36 -36
  5. package/src/architecture-database.mjs +64 -64
  6. package/src/artifact-observation.mjs +50 -50
  7. package/src/browser-lifecycle.mjs +45 -45
  8. package/src/cloudflare-browser.mjs +41 -41
  9. package/src/cloudflare-pages.d.mts +34 -34
  10. package/src/cloudflare-pages.mjs +170 -170
  11. package/src/cloudflare-provider-http.mjs +32 -32
  12. package/src/cluster-directory.d.mts +16 -16
  13. package/src/cluster-directory.mjs +90 -90
  14. package/src/core-publishing.d.mts +75 -75
  15. package/src/core-publishing.mjs +214 -214
  16. package/src/dev-command-runner.mjs +97 -97
  17. package/src/fixture-path.mjs +19 -19
  18. package/src/function-admission.d.mts +1 -1
  19. package/src/function-admission.mjs +58 -58
  20. package/src/host-artifact.mjs +32 -32
  21. package/src/host-stop.mjs +15 -15
  22. package/src/lifecycle-trace.mjs +32 -32
  23. package/src/managed-native-fixture.d.mts +84 -84
  24. package/src/managed-native-fixture.mjs +209 -209
  25. package/src/native-fixture.mjs +125 -125
  26. package/src/native-platform.mjs +56 -56
  27. package/src/operator-accounts.mjs +103 -103
  28. package/src/owned-process.mjs +75 -75
  29. package/src/owner-database.mjs +215 -215
  30. package/src/owner-operator-build.mjs +33 -33
  31. package/src/owner-production-browser.mjs +215 -215
  32. package/src/owner-production-instances.mjs +41 -41
  33. package/src/owner-production.d.mts +104 -104
  34. package/src/owner-production.mjs +338 -338
  35. package/src/owner-worker-build.mjs +83 -83
  36. package/src/prebuilt-output.d.mts +2 -2
  37. package/src/prebuilt-output.mjs +104 -104
  38. package/src/production-hosts.mjs +38 -38
  39. package/src/release-build.mjs +71 -71
  40. package/src/release-control.mjs +45 -45
  41. package/src/release-coordinator.d.mts +9 -9
  42. package/src/release-coordinator.mjs +222 -222
  43. package/src/release-credentials.d.mts +8 -8
  44. package/src/release-credentials.mjs +97 -97
  45. package/src/release-mutex.mjs +38 -38
  46. package/src/release-operator.d.mts +6 -6
  47. package/src/release-operator.mjs +59 -59
  48. package/src/release-supabase.d.mts +7 -7
  49. package/src/release-supabase.mjs +37 -37
  50. package/src/release-vercel.d.mts +22 -22
  51. package/src/release-vercel.mjs +51 -51
  52. package/src/release-writer.d.mts +6 -6
  53. package/src/release-writer.mjs +172 -172
  54. package/src/retained-postgres-shutdown.d.mts +51 -51
  55. package/src/retained-postgres-shutdown.mjs +262 -262
  56. package/src/temporary-acquisition.mjs +62 -62
  57. package/src/temporary-scope.d.mts +47 -47
  58. package/src/temporary-scope.mjs +268 -268
  59. package/src/worker-artifact.mjs +214 -214
@@ -1,262 +1,262 @@
1
- import { spawn } from "node:child_process";
2
- import { lstat, readFile } from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- const NORMAL_SHUTDOWN_LIMIT_MS = 60000;
6
-
7
- function failure(code, message, cause) {
8
- return Object.assign(new Error(message, cause === undefined ? undefined : { cause }), { code });
9
- }
10
-
11
- function validateOptions({ dataDirectory, pgCtl, terminationGraceMs = NORMAL_SHUTDOWN_LIMIT_MS }) {
12
- if (!path.isAbsolute(dataDirectory ?? "") || !path.isAbsolute(pgCtl ?? "")) {
13
- throw failure("PG_SHUTDOWN_PATH_REJECTED", "PostgreSQL shutdown requires absolute owned data and pg_ctl paths");
14
- }
15
- if (!Number.isInteger(terminationGraceMs) || terminationGraceMs < 1 || terminationGraceMs > NORMAL_SHUTDOWN_LIMIT_MS) {
16
- throw failure("PG_SHUTDOWN_BOUND_REJECTED", "PostgreSQL termination grace must be 1..60000 ms");
17
- }
18
- return { dataDirectory: path.resolve(dataDirectory), pgCtl, terminationGraceMs };
19
- }
20
-
21
- function observeChild(child, state, onError = () => {}) {
22
- let resolve;
23
- const completion = new Promise(done => { resolve = done; });
24
- function closed(code, signal) {
25
- if (state.closed) return;
26
- state.closed = true;
27
- state.exitCode = code;
28
- state.signalCode = signal ?? null;
29
- resolve(state);
30
- }
31
- child.once("error", error => { onError(error); state.error = String(error); });
32
- child.once("close", closed);
33
- // An EmbeddedPostgres start can finish before this adapter sees its child.
34
- // Exit without pipe closure is deliberately insufficient.
35
- if ((child.exitCode !== null || child.signalCode !== null)
36
- && [child.stdout, child.stderr].every(stream => !stream || stream.closed)) {
37
- closed(child.exitCode, child.signalCode);
38
- }
39
- return { child, state, completion };
40
- }
41
-
42
- function createShutdownGate(getChild, startPending, options, clearChild = () => {}) {
43
- const { dataDirectory, pgCtl, terminationGraceMs } = validateOptions(options);
44
- const state = {
45
- pid: undefined, closed: false, exitCode: null, signalCode: null,
46
- stopMethod: "owned-postgres-pg-ctl-fast", stopError: null, stopErrors: [],
47
- normalPostgresStopped: false, pendingStart: false,
48
- controlPid: undefined, controlClosed: false, controlExitCode: null,
49
- };
50
- let producer, stopPromise, closing = false, finished = false, pollTimer;
51
- let primaryFailure, diagnostic = "";
52
- const originals = [];
53
- const retain = (stage, error) => originals.push(Object.freeze({ stage, error }));
54
- const getOriginalFailures = () => Object.freeze([...originals]);
55
- const remember = error => {
56
- retain("shutdown", error);
57
- primaryFailure ??= error;
58
- state.stopError ??= String(error);
59
- state.stopErrors.push(String(error));
60
- return error;
61
- };
62
- function capture() {
63
- const child = getChild();
64
- if (!child) return producer;
65
- if (producer && producer.child !== child) {
66
- throw failure("PG_SHUTDOWN_IDENTITY_CHANGED", "Owned PostgreSQL producer changed during shutdown");
67
- }
68
- if (!producer) {
69
- state.pid = child.pid;
70
- producer = observeChild(child, state, error => retain("producer error", error));
71
- producer.completion.then(() => {
72
- if (!closing) options.signal?.removeEventListener("abort", abort);
73
- });
74
- }
75
- return producer;
76
- }
77
- function delay() {
78
- return new Promise(resolve => {
79
- pollTimer = setTimeout(() => { pollTimer = undefined; resolve(); }, 25);
80
- });
81
- }
82
- function assertActive() {
83
- if (finished) throw primaryFailure ?? failure("PG_SHUTDOWN_CLOSED_GATE", "PostgreSQL shutdown boundary has ended");
84
- }
85
- async function normalStop() {
86
- while (!capture()) {
87
- state.pendingStart = startPending();
88
- if (!state.pendingStart) {
89
- state.closed = true;
90
- state.normalPostgresStopped = true;
91
- return;
92
- }
93
- await delay();
94
- assertActive();
95
- }
96
- state.pendingStart = startPending();
97
- if (!Number.isSafeInteger(producer.child.pid) || producer.child.pid < 1) {
98
- // A failed spawn still owns a ChildProcess close event. Do not lose that
99
- // lifetime by throwing out of the factory after spawn returned.
100
- await producer.completion;
101
- assertActive();
102
- state.normalPostgresStopped = true;
103
- clearChild(producer.child);
104
- return;
105
- }
106
- try { await options.beforeStop?.(producer.child); }
107
- catch (error) { remember(error); }
108
- assertActive();
109
- if (!producer.state.closed && producer.child.exitCode === null && producer.child.signalCode === null) {
110
- // A cancellation can arrive in onSpawn, before PostgreSQL publishes its
111
- // pid file. Never let pg_ctl target an unverified directory in that gap.
112
- for (;;) {
113
- assertActive();
114
- if (producer.state.closed || producer.child.exitCode !== null || producer.child.signalCode !== null) break;
115
- let pidFile;
116
- try {
117
- const filename = path.join(dataDirectory, "postmaster.pid");
118
- const metadata = await lstat(filename);
119
- if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 4096) {
120
- throw failure("PG_SHUTDOWN_PID_FILE_REJECTED", "Owned postmaster pid file is not a bounded ordinary file");
121
- }
122
- pidFile = await readFile(filename, "utf8");
123
- }
124
- catch (error) {
125
- if (error.code !== "ENOENT") throw failure("PG_SHUTDOWN_PID_FILE_UNKNOWN", "Cannot read owned postmaster pid file", error);
126
- await delay();
127
- continue;
128
- }
129
- assertActive();
130
- const lines = pidFile.split(/\r?\n/);
131
- if (!/^[1-9][0-9]*$/.test(lines[0] ?? "") || Number(lines[0]) !== producer.child.pid
132
- || !lines[1] || path.resolve(lines[1]) !== dataDirectory) {
133
- throw failure("PG_SHUTDOWN_PID_FILE_MISMATCH", "Postmaster pid file does not identify this owned producer and data directory");
134
- }
135
- if (producer.state.closed || producer.child.exitCode !== null || producer.child.signalCode !== null) break;
136
- const controller = spawn(pgCtl, [
137
- "-D", dataDirectory, "stop", "-m", "fast", "-w", "-t", String(Math.ceil(terminationGraceMs / 1000)),
138
- ], { windowsHide: true, shell: false, stdio: ["ignore", "pipe", "pipe"] });
139
- const controlState = { closed: false, exitCode: null, signalCode: null };
140
- state.controlPid = controller.pid;
141
- const control = observeChild(controller, controlState, error => retain("controller error", error));
142
- // Draining output prevents pipe backpressure; pg_ctl diagnostics are
143
- // bounded separately from the producer's caller-owned log streams.
144
- const drain = chunk => { if (diagnostic.length < 2048) diagnostic += String(chunk).slice(0, 2048 - diagnostic.length); };
145
- controller.stdout?.on("data", drain);
146
- controller.stderr?.on("data", drain);
147
- controller.once("error", error => remember(failure("PG_NORMAL_STOP_CONTROL_ERROR", "Owned pg_ctl could not complete", error)));
148
- const controlled = control.completion.then(result => {
149
- state.controlClosed = true;
150
- state.controlExitCode = result.exitCode;
151
- if (result.error || result.exitCode !== 0 || result.signalCode) {
152
- remember(failure("PG_NORMAL_STOP_CONTROL_FAILED", "Owned pg_ctl fast stop failed: "
153
- + String(result.exitCode) + (diagnostic ? " " + diagnostic : "")));
154
- }
155
- });
156
- // Both close events include stdio EOF. A controller error must not
157
- // short-circuit waiting for the still-owned producer.
158
- await Promise.all([controlled, producer.completion]);
159
- if (primaryFailure) throw primaryFailure;
160
- break;
161
- }
162
- }
163
- await producer.completion;
164
- assertActive();
165
- if (primaryFailure) throw primaryFailure;
166
- state.normalPostgresStopped = true;
167
- clearChild(producer.child);
168
- }
169
- function stop() {
170
- if (stopPromise) return stopPromise;
171
- closing = true;
172
- stopPromise = (async () => {
173
- let boundaryTimer;
174
- const boundary = new Promise((_, reject) => {
175
- boundaryTimer = setTimeout(() => {
176
- const error = failure("PG_NORMAL_STOP_TIMEOUT", "Owned PostgreSQL normal shutdown did not close within "
177
- + String(terminationGraceMs) + " ms; ownership remains unknown" + (diagnostic ? ": " + diagnostic : ""));
178
- remember(error);
179
- reject(primaryFailure);
180
- }, terminationGraceMs);
181
- });
182
- try {
183
- await Promise.race([normalStop(), boundary]);
184
- } catch (error) {
185
- if (!state.stopErrors.includes(String(error))) remember(error);
186
- throw primaryFailure ?? error;
187
- } finally {
188
- finished = true;
189
- clearTimeout(boundaryTimer);
190
- clearTimeout(pollTimer);
191
- pollTimer = undefined;
192
- options.signal?.removeEventListener("abort", abort);
193
- }
194
- })();
195
- // Preserve the public promise while making automatic cancellation safe
196
- // when its caller only inspects state later.
197
- void stopPromise.catch(() => {});
198
- return stopPromise;
199
- }
200
- function abort() { void stop().catch(() => {}); }
201
- options.signal?.addEventListener("abort", abort, { once: true });
202
- return { state, stop, capture, fail: remember, getOriginalFailures, get closing() { return closing; } };
203
- }
204
-
205
- /**
206
- * A retained PostgreSQL producer uses pg_ctl fast stop, including cancellation.
207
- * This proves direct producer/controller closure, not a whole job lifetime.
208
- */
209
- export function startRetainedPostgres(executable, args, options = {}) {
210
- const { dataDirectory, pgCtl, signal, onSpawn, beforeStop, terminationGraceMs = NORMAL_SHUTDOWN_LIMIT_MS, ...spawnOptions } = options;
211
- validateOptions({ dataDirectory, pgCtl, terminationGraceMs });
212
- signal?.throwIfAborted();
213
- const child = spawn(executable, args, {
214
- windowsHide: true, stdio: ["ignore", "pipe", "pipe"], ...spawnOptions, shell: false,
215
- });
216
- const gate = createShutdownGate(() => child, () => false, { dataDirectory, pgCtl, signal, beforeStop, terminationGraceMs });
217
- const producer = gate.capture();
218
- function abort() { void gate.stop().catch(() => {}); }
219
- // The gate installs cancellation before the spawn callback is delivered.
220
- child.once("spawn", () => {
221
- try { onSpawn?.(); }
222
- catch (error) {
223
- gate.state.error = String(error);
224
- gate.fail(error);
225
- void gate.stop().catch(() => {});
226
- }
227
- });
228
- if (signal?.aborted) abort();
229
- return { child, state: gate.state, completion: producer.completion, stop: gate.stop, getOriginalFailures: gate.getOriginalFailures };
230
- }
231
-
232
- /**
233
- * Installed embedded-postgres 16.11 stores its child in an ordinary JS field.
234
- * Its automatic exit hook dynamically calls public stop(), so binding before
235
- * start routes explicit stop, abort and that hook through one normal close.
236
- */
237
- export function bindEmbeddedPostgresShutdown(instance, options = {}) {
238
- if (!instance || typeof instance.start !== "function" || typeof instance.stop !== "function") {
239
- throw failure("PG_SHUTDOWN_INSTANCE_REJECTED", "Expected the installed EmbeddedPostgres start/stop interface");
240
- }
241
- options.signal?.throwIfAborted();
242
- const originalStart = instance.start.bind(instance);
243
- let pending = false, started = false, startPromise;
244
- const gate = createShutdownGate(() => instance.process, () => pending, options, child => {
245
- if (instance.process === child) instance.process = undefined;
246
- });
247
- instance.start = function start() {
248
- if (gate.closing) return Promise.reject(failure("PG_START_AFTER_SHUTDOWN", "PostgreSQL start is closed by its shared shutdown gate"));
249
- if (started) return startPromise;
250
- started = true;
251
- pending = true;
252
- startPromise = Promise.resolve().then(originalStart).finally(() => {
253
- pending = false;
254
- gate.state.pendingStart = false;
255
- try { gate.capture(); } catch (error) { gate.state.error ??= String(error); }
256
- });
257
- return startPromise;
258
- };
259
- instance.stop = gate.stop;
260
- if (options.signal?.aborted) void gate.stop().catch(() => {});
261
- return { state: gate.state, stop: gate.stop, getOriginalFailures: gate.getOriginalFailures };
262
- }
1
+ import { spawn } from "node:child_process";
2
+ import { lstat, readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ const NORMAL_SHUTDOWN_LIMIT_MS = 60000;
6
+
7
+ function failure(code, message, cause) {
8
+ return Object.assign(new Error(message, cause === undefined ? undefined : { cause }), { code });
9
+ }
10
+
11
+ function validateOptions({ dataDirectory, pgCtl, terminationGraceMs = NORMAL_SHUTDOWN_LIMIT_MS }) {
12
+ if (!path.isAbsolute(dataDirectory ?? "") || !path.isAbsolute(pgCtl ?? "")) {
13
+ throw failure("PG_SHUTDOWN_PATH_REJECTED", "PostgreSQL shutdown requires absolute owned data and pg_ctl paths");
14
+ }
15
+ if (!Number.isInteger(terminationGraceMs) || terminationGraceMs < 1 || terminationGraceMs > NORMAL_SHUTDOWN_LIMIT_MS) {
16
+ throw failure("PG_SHUTDOWN_BOUND_REJECTED", "PostgreSQL termination grace must be 1..60000 ms");
17
+ }
18
+ return { dataDirectory: path.resolve(dataDirectory), pgCtl, terminationGraceMs };
19
+ }
20
+
21
+ function observeChild(child, state, onError = () => {}) {
22
+ let resolve;
23
+ const completion = new Promise(done => { resolve = done; });
24
+ function closed(code, signal) {
25
+ if (state.closed) return;
26
+ state.closed = true;
27
+ state.exitCode = code;
28
+ state.signalCode = signal ?? null;
29
+ resolve(state);
30
+ }
31
+ child.once("error", error => { onError(error); state.error = String(error); });
32
+ child.once("close", closed);
33
+ // An EmbeddedPostgres start can finish before this adapter sees its child.
34
+ // Exit without pipe closure is deliberately insufficient.
35
+ if ((child.exitCode !== null || child.signalCode !== null)
36
+ && [child.stdout, child.stderr].every(stream => !stream || stream.closed)) {
37
+ closed(child.exitCode, child.signalCode);
38
+ }
39
+ return { child, state, completion };
40
+ }
41
+
42
+ function createShutdownGate(getChild, startPending, options, clearChild = () => {}) {
43
+ const { dataDirectory, pgCtl, terminationGraceMs } = validateOptions(options);
44
+ const state = {
45
+ pid: undefined, closed: false, exitCode: null, signalCode: null,
46
+ stopMethod: "owned-postgres-pg-ctl-fast", stopError: null, stopErrors: [],
47
+ normalPostgresStopped: false, pendingStart: false,
48
+ controlPid: undefined, controlClosed: false, controlExitCode: null,
49
+ };
50
+ let producer, stopPromise, closing = false, finished = false, pollTimer;
51
+ let primaryFailure, diagnostic = "";
52
+ const originals = [];
53
+ const retain = (stage, error) => originals.push(Object.freeze({ stage, error }));
54
+ const getOriginalFailures = () => Object.freeze([...originals]);
55
+ const remember = error => {
56
+ retain("shutdown", error);
57
+ primaryFailure ??= error;
58
+ state.stopError ??= String(error);
59
+ state.stopErrors.push(String(error));
60
+ return error;
61
+ };
62
+ function capture() {
63
+ const child = getChild();
64
+ if (!child) return producer;
65
+ if (producer && producer.child !== child) {
66
+ throw failure("PG_SHUTDOWN_IDENTITY_CHANGED", "Owned PostgreSQL producer changed during shutdown");
67
+ }
68
+ if (!producer) {
69
+ state.pid = child.pid;
70
+ producer = observeChild(child, state, error => retain("producer error", error));
71
+ producer.completion.then(() => {
72
+ if (!closing) options.signal?.removeEventListener("abort", abort);
73
+ });
74
+ }
75
+ return producer;
76
+ }
77
+ function delay() {
78
+ return new Promise(resolve => {
79
+ pollTimer = setTimeout(() => { pollTimer = undefined; resolve(); }, 25);
80
+ });
81
+ }
82
+ function assertActive() {
83
+ if (finished) throw primaryFailure ?? failure("PG_SHUTDOWN_CLOSED_GATE", "PostgreSQL shutdown boundary has ended");
84
+ }
85
+ async function normalStop() {
86
+ while (!capture()) {
87
+ state.pendingStart = startPending();
88
+ if (!state.pendingStart) {
89
+ state.closed = true;
90
+ state.normalPostgresStopped = true;
91
+ return;
92
+ }
93
+ await delay();
94
+ assertActive();
95
+ }
96
+ state.pendingStart = startPending();
97
+ if (!Number.isSafeInteger(producer.child.pid) || producer.child.pid < 1) {
98
+ // A failed spawn still owns a ChildProcess close event. Do not lose that
99
+ // lifetime by throwing out of the factory after spawn returned.
100
+ await producer.completion;
101
+ assertActive();
102
+ state.normalPostgresStopped = true;
103
+ clearChild(producer.child);
104
+ return;
105
+ }
106
+ try { await options.beforeStop?.(producer.child); }
107
+ catch (error) { remember(error); }
108
+ assertActive();
109
+ if (!producer.state.closed && producer.child.exitCode === null && producer.child.signalCode === null) {
110
+ // A cancellation can arrive in onSpawn, before PostgreSQL publishes its
111
+ // pid file. Never let pg_ctl target an unverified directory in that gap.
112
+ for (;;) {
113
+ assertActive();
114
+ if (producer.state.closed || producer.child.exitCode !== null || producer.child.signalCode !== null) break;
115
+ let pidFile;
116
+ try {
117
+ const filename = path.join(dataDirectory, "postmaster.pid");
118
+ const metadata = await lstat(filename);
119
+ if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 4096) {
120
+ throw failure("PG_SHUTDOWN_PID_FILE_REJECTED", "Owned postmaster pid file is not a bounded ordinary file");
121
+ }
122
+ pidFile = await readFile(filename, "utf8");
123
+ }
124
+ catch (error) {
125
+ if (error.code !== "ENOENT") throw failure("PG_SHUTDOWN_PID_FILE_UNKNOWN", "Cannot read owned postmaster pid file", error);
126
+ await delay();
127
+ continue;
128
+ }
129
+ assertActive();
130
+ const lines = pidFile.split(/\r?\n/);
131
+ if (!/^[1-9][0-9]*$/.test(lines[0] ?? "") || Number(lines[0]) !== producer.child.pid
132
+ || !lines[1] || path.resolve(lines[1]) !== dataDirectory) {
133
+ throw failure("PG_SHUTDOWN_PID_FILE_MISMATCH", "Postmaster pid file does not identify this owned producer and data directory");
134
+ }
135
+ if (producer.state.closed || producer.child.exitCode !== null || producer.child.signalCode !== null) break;
136
+ const controller = spawn(pgCtl, [
137
+ "-D", dataDirectory, "stop", "-m", "fast", "-w", "-t", String(Math.ceil(terminationGraceMs / 1000)),
138
+ ], { windowsHide: true, shell: false, stdio: ["ignore", "pipe", "pipe"] });
139
+ const controlState = { closed: false, exitCode: null, signalCode: null };
140
+ state.controlPid = controller.pid;
141
+ const control = observeChild(controller, controlState, error => retain("controller error", error));
142
+ // Draining output prevents pipe backpressure; pg_ctl diagnostics are
143
+ // bounded separately from the producer's caller-owned log streams.
144
+ const drain = chunk => { if (diagnostic.length < 2048) diagnostic += String(chunk).slice(0, 2048 - diagnostic.length); };
145
+ controller.stdout?.on("data", drain);
146
+ controller.stderr?.on("data", drain);
147
+ controller.once("error", error => remember(failure("PG_NORMAL_STOP_CONTROL_ERROR", "Owned pg_ctl could not complete", error)));
148
+ const controlled = control.completion.then(result => {
149
+ state.controlClosed = true;
150
+ state.controlExitCode = result.exitCode;
151
+ if (result.error || result.exitCode !== 0 || result.signalCode) {
152
+ remember(failure("PG_NORMAL_STOP_CONTROL_FAILED", "Owned pg_ctl fast stop failed: "
153
+ + String(result.exitCode) + (diagnostic ? " " + diagnostic : "")));
154
+ }
155
+ });
156
+ // Both close events include stdio EOF. A controller error must not
157
+ // short-circuit waiting for the still-owned producer.
158
+ await Promise.all([controlled, producer.completion]);
159
+ if (primaryFailure) throw primaryFailure;
160
+ break;
161
+ }
162
+ }
163
+ await producer.completion;
164
+ assertActive();
165
+ if (primaryFailure) throw primaryFailure;
166
+ state.normalPostgresStopped = true;
167
+ clearChild(producer.child);
168
+ }
169
+ function stop() {
170
+ if (stopPromise) return stopPromise;
171
+ closing = true;
172
+ stopPromise = (async () => {
173
+ let boundaryTimer;
174
+ const boundary = new Promise((_, reject) => {
175
+ boundaryTimer = setTimeout(() => {
176
+ const error = failure("PG_NORMAL_STOP_TIMEOUT", "Owned PostgreSQL normal shutdown did not close within "
177
+ + String(terminationGraceMs) + " ms; ownership remains unknown" + (diagnostic ? ": " + diagnostic : ""));
178
+ remember(error);
179
+ reject(primaryFailure);
180
+ }, terminationGraceMs);
181
+ });
182
+ try {
183
+ await Promise.race([normalStop(), boundary]);
184
+ } catch (error) {
185
+ if (!state.stopErrors.includes(String(error))) remember(error);
186
+ throw primaryFailure ?? error;
187
+ } finally {
188
+ finished = true;
189
+ clearTimeout(boundaryTimer);
190
+ clearTimeout(pollTimer);
191
+ pollTimer = undefined;
192
+ options.signal?.removeEventListener("abort", abort);
193
+ }
194
+ })();
195
+ // Preserve the public promise while making automatic cancellation safe
196
+ // when its caller only inspects state later.
197
+ void stopPromise.catch(() => {});
198
+ return stopPromise;
199
+ }
200
+ function abort() { void stop().catch(() => {}); }
201
+ options.signal?.addEventListener("abort", abort, { once: true });
202
+ return { state, stop, capture, fail: remember, getOriginalFailures, get closing() { return closing; } };
203
+ }
204
+
205
+ /**
206
+ * A retained PostgreSQL producer uses pg_ctl fast stop, including cancellation.
207
+ * This proves direct producer/controller closure, not a whole job lifetime.
208
+ */
209
+ export function startRetainedPostgres(executable, args, options = {}) {
210
+ const { dataDirectory, pgCtl, signal, onSpawn, beforeStop, terminationGraceMs = NORMAL_SHUTDOWN_LIMIT_MS, ...spawnOptions } = options;
211
+ validateOptions({ dataDirectory, pgCtl, terminationGraceMs });
212
+ signal?.throwIfAborted();
213
+ const child = spawn(executable, args, {
214
+ windowsHide: true, stdio: ["ignore", "pipe", "pipe"], ...spawnOptions, shell: false,
215
+ });
216
+ const gate = createShutdownGate(() => child, () => false, { dataDirectory, pgCtl, signal, beforeStop, terminationGraceMs });
217
+ const producer = gate.capture();
218
+ function abort() { void gate.stop().catch(() => {}); }
219
+ // The gate installs cancellation before the spawn callback is delivered.
220
+ child.once("spawn", () => {
221
+ try { onSpawn?.(); }
222
+ catch (error) {
223
+ gate.state.error = String(error);
224
+ gate.fail(error);
225
+ void gate.stop().catch(() => {});
226
+ }
227
+ });
228
+ if (signal?.aborted) abort();
229
+ return { child, state: gate.state, completion: producer.completion, stop: gate.stop, getOriginalFailures: gate.getOriginalFailures };
230
+ }
231
+
232
+ /**
233
+ * Installed embedded-postgres 16.11 stores its child in an ordinary JS field.
234
+ * Its automatic exit hook dynamically calls public stop(), so binding before
235
+ * start routes explicit stop, abort and that hook through one normal close.
236
+ */
237
+ export function bindEmbeddedPostgresShutdown(instance, options = {}) {
238
+ if (!instance || typeof instance.start !== "function" || typeof instance.stop !== "function") {
239
+ throw failure("PG_SHUTDOWN_INSTANCE_REJECTED", "Expected the installed EmbeddedPostgres start/stop interface");
240
+ }
241
+ options.signal?.throwIfAborted();
242
+ const originalStart = instance.start.bind(instance);
243
+ let pending = false, started = false, startPromise;
244
+ const gate = createShutdownGate(() => instance.process, () => pending, options, child => {
245
+ if (instance.process === child) instance.process = undefined;
246
+ });
247
+ instance.start = function start() {
248
+ if (gate.closing) return Promise.reject(failure("PG_START_AFTER_SHUTDOWN", "PostgreSQL start is closed by its shared shutdown gate"));
249
+ if (started) return startPromise;
250
+ started = true;
251
+ pending = true;
252
+ startPromise = Promise.resolve().then(originalStart).finally(() => {
253
+ pending = false;
254
+ gate.state.pendingStart = false;
255
+ try { gate.capture(); } catch (error) { gate.state.error ??= String(error); }
256
+ });
257
+ return startPromise;
258
+ };
259
+ instance.stop = gate.stop;
260
+ if (options.signal?.aborted) void gate.stop().catch(() => {});
261
+ return { state: gate.state, stop: gate.stop, getOriginalFailures: gate.getOriginalFailures };
262
+ }
@@ -1,62 +1,62 @@
1
- import path from 'node:path';
2
- import {randomUUID} from 'node:crypto';
3
-
4
- // A bounded, non-waiting bakery doorway. Unique intent files avoid deleting a
5
- // replacement lock while retiring an interrupted contender. No heartbeat or
6
- // age-based lease can expire a live owner.
7
- export function acquireTemporaryScope({io, directory, label, probeOwner, verifyScope}) {
8
- const prefix = '.' + label + '-acquire-', token = randomUUID(), file = path.join(directory, prefix + token + '.json');
9
- const intent = {version: 1, token, ownerPid: process.pid, sequence: 0};
10
- let created = false;
11
- const fail = () => { throw Error('TEMPORARY_ACQUISITION_BUSY'); };
12
- const read = name => {
13
- verifyScope();
14
- try {
15
- const target = path.join(directory, name), before = io.lstatSync(target);
16
- if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > 8192) return fail();
17
- const bytes = io.readFileSync(target), after = io.lstatSync(target), value = JSON.parse(bytes.toString('utf8'));
18
- if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || bytes.length !== after.size
19
- || value.version !== 1 || name !== prefix + value.token + '.json' || !/^[a-f0-9-]{36}$/.test(value.token ?? '')
20
- || !Number.isSafeInteger(value.ownerPid) || value.ownerPid < 1 || !Number.isSafeInteger(value.sequence) || value.sequence < 0) return fail();
21
- return {name, target, value, identity: {dev: after.dev, ino: after.ino}};
22
- } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
23
- };
24
- const list = () => {
25
- verifyScope();
26
- const names = io.readdirSync(directory).filter(name => name.startsWith(prefix));
27
- if (names.length > 64) return fail();
28
- return names.map(read).filter(Boolean);
29
- };
30
- const retired = candidate => candidate.value.ownerPid !== process.pid && probeOwner(candidate.value.ownerPid) === 'dead';
31
- const remove = candidate => {
32
- const current = read(candidate.name);
33
- if (!current) return;
34
- if (current.identity.dev !== candidate.identity.dev || current.identity.ino !== candidate.identity.ino
35
- || JSON.stringify(current.value) !== JSON.stringify(candidate.value)) return fail();
36
- verifyScope(); io.unlinkSync(candidate.target);
37
- };
38
- const release = () => {
39
- if (!created) return;
40
- const own = read(path.basename(file));
41
- if (!own || JSON.stringify(own.value) !== JSON.stringify(intent)) return fail();
42
- remove(own); created = false;
43
- };
44
- try {
45
- verifyScope(); io.writeFileSync(file, JSON.stringify(intent) + '\n', {flag: 'wx', mode: 0o600}); created = true;
46
- const others = list().filter(candidate => candidate.value.token !== token && !retired(candidate));
47
- intent.sequence = 1 + Math.max(0, ...others.map(candidate => candidate.value.sequence));
48
- if (!Number.isSafeInteger(intent.sequence)) return fail();
49
- verifyScope(); io.writeFileSync(file, JSON.stringify(intent) + '\n');
50
- const contenders = list().filter(candidate => candidate.value.token !== token);
51
- for (const candidate of contenders) {
52
- if (retired(candidate)) continue;
53
- const other = candidate.value;
54
- if (other.sequence === 0 || other.sequence < intent.sequence || (other.sequence === intent.sequence && other.token < token)) return fail();
55
- }
56
- for (const candidate of contenders) if (retired(candidate)) remove(candidate);
57
- return release;
58
- } catch (error) {
59
- try { release(); } catch (releaseError) { error.releaseError = releaseError; }
60
- throw error;
61
- }
62
- }
1
+ import path from 'node:path';
2
+ import {randomUUID} from 'node:crypto';
3
+
4
+ // A bounded, non-waiting bakery doorway. Unique intent files avoid deleting a
5
+ // replacement lock while retiring an interrupted contender. No heartbeat or
6
+ // age-based lease can expire a live owner.
7
+ export function acquireTemporaryScope({io, directory, label, probeOwner, verifyScope}) {
8
+ const prefix = '.' + label + '-acquire-', token = randomUUID(), file = path.join(directory, prefix + token + '.json');
9
+ const intent = {version: 1, token, ownerPid: process.pid, sequence: 0};
10
+ let created = false;
11
+ const fail = () => { throw Error('TEMPORARY_ACQUISITION_BUSY'); };
12
+ const read = name => {
13
+ verifyScope();
14
+ try {
15
+ const target = path.join(directory, name), before = io.lstatSync(target);
16
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > 8192) return fail();
17
+ const bytes = io.readFileSync(target), after = io.lstatSync(target), value = JSON.parse(bytes.toString('utf8'));
18
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || bytes.length !== after.size
19
+ || value.version !== 1 || name !== prefix + value.token + '.json' || !/^[a-f0-9-]{36}$/.test(value.token ?? '')
20
+ || !Number.isSafeInteger(value.ownerPid) || value.ownerPid < 1 || !Number.isSafeInteger(value.sequence) || value.sequence < 0) return fail();
21
+ return {name, target, value, identity: {dev: after.dev, ino: after.ino}};
22
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
23
+ };
24
+ const list = () => {
25
+ verifyScope();
26
+ const names = io.readdirSync(directory).filter(name => name.startsWith(prefix));
27
+ if (names.length > 64) return fail();
28
+ return names.map(read).filter(Boolean);
29
+ };
30
+ const retired = candidate => candidate.value.ownerPid !== process.pid && probeOwner(candidate.value.ownerPid) === 'dead';
31
+ const remove = candidate => {
32
+ const current = read(candidate.name);
33
+ if (!current) return;
34
+ if (current.identity.dev !== candidate.identity.dev || current.identity.ino !== candidate.identity.ino
35
+ || JSON.stringify(current.value) !== JSON.stringify(candidate.value)) return fail();
36
+ verifyScope(); io.unlinkSync(candidate.target);
37
+ };
38
+ const release = () => {
39
+ if (!created) return;
40
+ const own = read(path.basename(file));
41
+ if (!own || JSON.stringify(own.value) !== JSON.stringify(intent)) return fail();
42
+ remove(own); created = false;
43
+ };
44
+ try {
45
+ verifyScope(); io.writeFileSync(file, JSON.stringify(intent) + '\n', {flag: 'wx', mode: 0o600}); created = true;
46
+ const others = list().filter(candidate => candidate.value.token !== token && !retired(candidate));
47
+ intent.sequence = 1 + Math.max(0, ...others.map(candidate => candidate.value.sequence));
48
+ if (!Number.isSafeInteger(intent.sequence)) return fail();
49
+ verifyScope(); io.writeFileSync(file, JSON.stringify(intent) + '\n');
50
+ const contenders = list().filter(candidate => candidate.value.token !== token);
51
+ for (const candidate of contenders) {
52
+ if (retired(candidate)) continue;
53
+ const other = candidate.value;
54
+ if (other.sequence === 0 || other.sequence < intent.sequence || (other.sequence === intent.sequence && other.token < token)) return fail();
55
+ }
56
+ for (const candidate of contenders) if (retired(candidate)) remove(candidate);
57
+ return release;
58
+ } catch (error) {
59
+ try { release(); } catch (releaseError) { error.releaseError = releaseError; }
60
+ throw error;
61
+ }
62
+ }