vouchington-tooling 0.62.0 → 0.64.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.
- package/README.md +147 -0
- package/dist/cli/commands/cloc.d.mts +7 -0
- package/dist/cli/commands/cloc.mjs +47 -0
- package/dist/cli/commands/storybook-browser-runner.d.mts +7 -0
- package/dist/cli/commands/storybook-browser-runner.mjs +29 -0
- package/dist/cli/index.mjs +4 -0
- package/dist/cli/parse-forwarded-commands.d.mts +6 -0
- package/dist/cli/parse-forwarded-commands.mjs +4 -0
- package/dist/cli/parse.d.mts +6 -0
- package/dist/cli/usage-text.d.mts +1 -1
- package/dist/cli/usage-text.mjs +18 -0
- package/dist/cloc/child-process.d.mts +3 -0
- package/dist/cloc/child-process.mjs +14 -0
- package/dist/cloc/classify.d.mts +8 -0
- package/dist/cloc/classify.mjs +20 -0
- package/dist/cloc/config-load.d.mts +7 -0
- package/dist/cloc/config-load.mjs +26 -0
- package/dist/cloc/config.d.mts +55 -0
- package/dist/cloc/config.mjs +109 -0
- package/dist/cloc/count.d.mts +9 -0
- package/dist/cloc/count.mjs +33 -0
- package/dist/cloc/index.d.mts +12 -0
- package/dist/cloc/index.mjs +7 -0
- package/dist/cloc/layout.test-helpers.d.mts +8 -0
- package/dist/cloc/layout.test-helpers.mjs +42 -0
- package/dist/cloc/paths.d.mts +7 -0
- package/dist/cloc/paths.mjs +29 -0
- package/dist/cloc/patterns.d.mts +10 -0
- package/dist/cloc/patterns.mjs +25 -0
- package/dist/cloc/rows.d.mts +13 -0
- package/dist/cloc/rows.mjs +42 -0
- package/dist/cloc/scc.d.mts +10 -0
- package/dist/cloc/scc.mjs +55 -0
- package/dist/cloc/tracked.d.mts +4 -0
- package/dist/cloc/tracked.mjs +40 -0
- package/dist/postgres-test-faults/fault-support.d.mts +11 -0
- package/dist/postgres-test-faults/fault-support.mjs +61 -0
- package/dist/postgres-test-faults/fault-types.d.mts +43 -0
- package/dist/postgres-test-faults/fault-types.mjs +1 -0
- package/dist/postgres-test-faults/index.d.mts +5 -0
- package/dist/postgres-test-faults/index.mjs +4 -0
- package/dist/postgres-test-faults/lock-observers.d.mts +20 -0
- package/dist/postgres-test-faults/lock-observers.mjs +14 -0
- package/dist/postgres-test-faults/lock-wait.d.mts +13 -0
- package/dist/postgres-test-faults/lock-wait.mjs +62 -0
- package/dist/postgres-test-faults/lock-waiter.d.mts +19 -0
- package/dist/postgres-test-faults/lock-waiter.mjs +95 -0
- package/dist/postgres-test-faults/observation-queue.d.mts +2 -0
- package/dist/postgres-test-faults/observation-queue.mjs +22 -0
- package/dist/postgres-test-faults/polling.d.mts +6 -0
- package/dist/postgres-test-faults/polling.mjs +33 -0
- package/dist/postgres-test-faults/pool-query-failure.d.mts +8 -0
- package/dist/postgres-test-faults/pool-query-failure.mjs +136 -0
- package/dist/postgres-test-faults/query-failure.d.mts +8 -0
- package/dist/postgres-test-faults/query-failure.mjs +108 -0
- package/dist/postgres-test-faults/test-cluster.test-helpers.d.mts +13 -0
- package/dist/postgres-test-faults/test-cluster.test-helpers.mjs +84 -0
- package/dist/provider-replay/abort-listeners.d.mts +4 -0
- package/dist/provider-replay/abort-listeners.mjs +19 -0
- package/dist/provider-replay/aws-replay-abort-signal.d.mts +5 -0
- package/dist/provider-replay/aws-replay-abort-signal.mjs +63 -0
- package/dist/provider-replay/aws-replay-request-handler.d.mts +38 -0
- package/dist/provider-replay/aws-replay-request-handler.mjs +66 -0
- package/dist/provider-replay/force-client-option.d.mts +6 -0
- package/dist/provider-replay/force-client-option.mjs +13 -0
- package/dist/provider-replay/index.d.mts +6 -0
- package/dist/provider-replay/index.mjs +6 -0
- package/dist/provider-replay/provider-replay.d.mts +32 -0
- package/dist/provider-replay/provider-replay.mjs +54 -0
- package/dist/provider-replay/recorded-response.d.mts +17 -0
- package/dist/provider-replay/recorded-response.mjs +42 -0
- package/dist/provider-replay/replay-response.d.mts +8 -0
- package/dist/provider-replay/replay-response.mjs +38 -0
- package/dist/storybook-browser-runner/args.d.mts +8 -0
- package/dist/storybook-browser-runner/args.mjs +52 -0
- package/dist/storybook-browser-runner/attempt-result.d.mts +41 -0
- package/dist/storybook-browser-runner/attempt-result.mjs +108 -0
- package/dist/storybook-browser-runner/bootstrap-telemetry.d.mts +35 -0
- package/dist/storybook-browser-runner/bootstrap-telemetry.mjs +138 -0
- package/dist/storybook-browser-runner/cache-plan.d.mts +22 -0
- package/dist/storybook-browser-runner/cache-plan.mjs +53 -0
- package/dist/storybook-browser-runner/diagnostics.d.mts +8 -0
- package/dist/storybook-browser-runner/diagnostics.mjs +29 -0
- package/dist/storybook-browser-runner/env.d.mts +2 -0
- package/dist/storybook-browser-runner/env.mjs +59 -0
- package/dist/storybook-browser-runner/fixtures.test-helpers.d.mts +49 -0
- package/dist/storybook-browser-runner/fixtures.test-helpers.mjs +95 -0
- package/dist/storybook-browser-runner/index.d.mts +15 -0
- package/dist/storybook-browser-runner/index.mjs +70 -0
- package/dist/storybook-browser-runner/observer-state.d.mts +22 -0
- package/dist/storybook-browser-runner/observer-state.mjs +21 -0
- package/dist/storybook-browser-runner/options.d.mts +18 -0
- package/dist/storybook-browser-runner/options.mjs +49 -0
- package/dist/storybook-browser-runner/output-observer.d.mts +37 -0
- package/dist/storybook-browser-runner/output-observer.mjs +130 -0
- package/dist/storybook-browser-runner/output-patterns.d.mts +14 -0
- package/dist/storybook-browser-runner/output-patterns.mjs +26 -0
- package/dist/storybook-browser-runner/quiet-output.d.mts +16 -0
- package/dist/storybook-browser-runner/quiet-output.mjs +79 -0
- package/dist/storybook-browser-runner/run-attempt.d.mts +14 -0
- package/dist/storybook-browser-runner/run-attempt.mjs +111 -0
- package/dist/storybook-browser-runner/runtime-metadata.d.mts +12 -0
- package/dist/storybook-browser-runner/runtime-metadata.mjs +50 -0
- package/dist/storybook-browser-runner/session-deps.d.mts +11 -0
- package/dist/storybook-browser-runner/session-deps.mjs +70 -0
- package/dist/storybook-browser-runner/types.d.mts +49 -0
- package/dist/storybook-browser-runner/types.mjs +1 -0
- package/dist/storybook-browser-runner/vite-detectors.d.mts +6 -0
- package/dist/storybook-browser-runner/vite-detectors.mjs +20 -0
- package/dist/storybook-browser-runner/watchdog.d.mts +23 -0
- package/dist/storybook-browser-runner/watchdog.mjs +55 -0
- package/package.json +27 -1
- package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { LockObserverConfig, ObserverPool, QueryExecutor } from './fault-types.mts';
|
|
2
|
+
/** Returns the PostgreSQL backend PID serving `query`'s current connection. */
|
|
3
|
+
export declare function getTestPostgresBackendProcessId(query: QueryExecutor): Promise<number>;
|
|
4
|
+
/** Runs `text` on the executor chosen by `observerPool`. */
|
|
5
|
+
export declare function runObservation<Row extends object>(config: LockObserverConfig, observerPool: ObserverPool, text: string, values: unknown[]): Promise<{
|
|
6
|
+
rows: Row[];
|
|
7
|
+
}>;
|
|
8
|
+
/** Returns the backend PID holding an exact session advisory lock owned by this test. */
|
|
9
|
+
export declare function getAdvisoryLockHolderProcessId(config: LockObserverConfig, input: {
|
|
10
|
+
key: string;
|
|
11
|
+
mode?: 'exclusive' | 'shared';
|
|
12
|
+
namespace?: number;
|
|
13
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** Returns the PostgreSQL backend PID serving `query`'s current connection. */
|
|
2
|
+
export async function getTestPostgresBackendProcessId(query) {
|
|
3
|
+
const { rows } = await query({
|
|
4
|
+
text: `
|
|
5
|
+
/* getTestPostgresBackendProcessId */
|
|
6
|
+
SELECT pg_backend_pid()::integer AS process_id
|
|
7
|
+
`,
|
|
8
|
+
});
|
|
9
|
+
const processId = rows[0]?.process_id;
|
|
10
|
+
if (processId === undefined)
|
|
11
|
+
throw new Error('PostgreSQL did not return a backend process ID');
|
|
12
|
+
return processId;
|
|
13
|
+
}
|
|
14
|
+
/** Runs `text` on the executor chosen by `observerPool`. */
|
|
15
|
+
export function runObservation(config, observerPool, text, values) {
|
|
16
|
+
if (typeof observerPool === 'function')
|
|
17
|
+
return observerPool({ text, values });
|
|
18
|
+
if (observerPool === 'write')
|
|
19
|
+
return config.write({ text, values });
|
|
20
|
+
if (!config.advisoryLockPool)
|
|
21
|
+
throw new Error("The 'advisoryLock' observer requires an advisoryLockPool executor");
|
|
22
|
+
return config.advisoryLockPool({ text, values });
|
|
23
|
+
}
|
|
24
|
+
/** Returns the backend PID holding an exact session advisory lock owned by this test. */
|
|
25
|
+
export async function getAdvisoryLockHolderProcessId(config, input) {
|
|
26
|
+
const lockMode = input.mode === 'shared' ? 'ShareLock' : 'ExclusiveLock';
|
|
27
|
+
const result = input.namespace === undefined
|
|
28
|
+
? await config.write({
|
|
29
|
+
text: `
|
|
30
|
+
/* getTestPostgresAdvisoryLockHolderProcessId:oneInt */
|
|
31
|
+
SELECT pid::integer AS process_id
|
|
32
|
+
FROM pg_locks
|
|
33
|
+
WHERE locktype = 'advisory'
|
|
34
|
+
AND database = (SELECT oid FROM pg_database WHERE datname = current_database())
|
|
35
|
+
AND mode = $1
|
|
36
|
+
AND granted
|
|
37
|
+
AND objsubid = 1
|
|
38
|
+
AND classid::bigint = ((hashtextextended($2::text, 0) >> 32) & 4294967295)
|
|
39
|
+
AND objid::bigint = (hashtextextended($2::text, 0) & 4294967295)
|
|
40
|
+
`,
|
|
41
|
+
values: [lockMode, input.key],
|
|
42
|
+
})
|
|
43
|
+
: await config.write({
|
|
44
|
+
text: `
|
|
45
|
+
/* getTestPostgresAdvisoryLockHolderProcessId:twoInt */
|
|
46
|
+
SELECT pid::integer AS process_id
|
|
47
|
+
FROM pg_locks
|
|
48
|
+
WHERE locktype = 'advisory'
|
|
49
|
+
AND database = (SELECT oid FROM pg_database WHERE datname = current_database())
|
|
50
|
+
AND mode = $1
|
|
51
|
+
AND granted
|
|
52
|
+
AND objsubid = 2
|
|
53
|
+
AND classid = $2::integer::oid
|
|
54
|
+
AND objid = hashtext($3::text)::oid
|
|
55
|
+
`,
|
|
56
|
+
values: [lockMode, input.namespace, input.key],
|
|
57
|
+
});
|
|
58
|
+
const processId = result.rows[0]?.process_id;
|
|
59
|
+
if (processId === undefined)
|
|
60
|
+
throw new Error('PostgreSQL did not report the test advisory-lock holder');
|
|
61
|
+
return processId;
|
|
62
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { LockObserverConfig, LockWaiterDiagnostic, ObserverPool } from './fault-types.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Waits until a query bearing `queryMarker` is blocked by this test's lock-holding backend.
|
|
4
|
+
* Use a dedicated advisory executor when the held lock and blocked operations can occupy every
|
|
5
|
+
* write connection; the observer must run before the holder is released. Passing a previously
|
|
6
|
+
* acquired transaction executor reserves the observer connection before the holder or blocked
|
|
7
|
+
* operation starts, and its transaction-local activity snapshot is discarded before each
|
|
8
|
+
* observation. Supply `waiterProcessId` to distinguish this operation from other matching waiters.
|
|
9
|
+
*/
|
|
10
|
+
export declare function waitForLockWaiter(config: LockObserverConfig, holderProcessId: number, queryMarker: string, observerPool?: ObserverPool, onDiagnostic?: (diagnostic: LockWaiterDiagnostic) => void, signal?: AbortSignal, waiterProcessId?: number): Promise<void>;
|
|
11
|
+
/**
|
|
12
|
+
* Waits until one backend is blocked by `holderProcessId` on `directQueryMarker` and a second
|
|
13
|
+
* backend is blocked by that first backend on one of `blockedByDirectQueryMarkers`.
|
|
14
|
+
*
|
|
15
|
+
* Use this when the second operation cannot reach the holder's lock because the first operation
|
|
16
|
+
* already holds a conflicting row lock. `pg_blocking_pids` reports only the direct blocker, so
|
|
17
|
+
* the second wait is the transitive link.
|
|
18
|
+
*/
|
|
19
|
+
export declare function waitForBlockedLockChain(config: LockObserverConfig, holderProcessId: number, directQueryMarker: string, blockedByDirectQueryMarkers: readonly string[], observerPool?: ObserverPool): Promise<void>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { runObservation } from "./lock-wait.mjs";
|
|
2
|
+
import { pollUntilNotNull } from "./polling.mjs";
|
|
3
|
+
/** A LIKE pattern matching `text` literally anywhere, so `%`, `_` and `\` in markers are not wildcards. */
|
|
4
|
+
function likeContains(text) {
|
|
5
|
+
return `%${text.replace(/[\\%_]/g, '\\$&')}%`;
|
|
6
|
+
}
|
|
7
|
+
const CLEAR_SNAPSHOT = 'SELECT pg_stat_clear_snapshot()';
|
|
8
|
+
const WAITER_SQL = `
|
|
9
|
+
/* waitForTestPostgresLockWaiter */
|
|
10
|
+
SELECT EXISTS (
|
|
11
|
+
SELECT 1
|
|
12
|
+
FROM pg_stat_activity activity
|
|
13
|
+
WHERE activity.pid <> pg_backend_pid()
|
|
14
|
+
AND ($1::integer IS NULL OR activity.pid = $1::integer)
|
|
15
|
+
AND activity.state = 'active'
|
|
16
|
+
AND activity.wait_event_type = 'Lock'
|
|
17
|
+
AND activity.query LIKE $2::text
|
|
18
|
+
AND $3::integer = ANY(pg_blocking_pids(activity.pid))
|
|
19
|
+
) AS waiting
|
|
20
|
+
`;
|
|
21
|
+
const CHAIN_SQL = `
|
|
22
|
+
/* waitForTestPostgresBlockedLockChain */
|
|
23
|
+
SELECT EXISTS (
|
|
24
|
+
SELECT 1
|
|
25
|
+
FROM pg_stat_activity direct_waiter
|
|
26
|
+
JOIN pg_stat_activity indirect_waiter
|
|
27
|
+
ON direct_waiter.pid = ANY(pg_blocking_pids(indirect_waiter.pid))
|
|
28
|
+
WHERE direct_waiter.pid <> pg_backend_pid()
|
|
29
|
+
AND indirect_waiter.pid <> pg_backend_pid()
|
|
30
|
+
AND direct_waiter.state = 'active'
|
|
31
|
+
AND indirect_waiter.state = 'active'
|
|
32
|
+
AND direct_waiter.wait_event_type = 'Lock'
|
|
33
|
+
AND indirect_waiter.wait_event_type = 'Lock'
|
|
34
|
+
AND direct_waiter.query LIKE $1::text
|
|
35
|
+
AND $2::integer = ANY(pg_blocking_pids(direct_waiter.pid))
|
|
36
|
+
AND indirect_waiter.query LIKE ANY($3::text[])
|
|
37
|
+
) AS waiting
|
|
38
|
+
`;
|
|
39
|
+
/**
|
|
40
|
+
* Waits until a query bearing `queryMarker` is blocked by this test's lock-holding backend.
|
|
41
|
+
* Use a dedicated advisory executor when the held lock and blocked operations can occupy every
|
|
42
|
+
* write connection; the observer must run before the holder is released. Passing a previously
|
|
43
|
+
* acquired transaction executor reserves the observer connection before the holder or blocked
|
|
44
|
+
* operation starts, and its transaction-local activity snapshot is discarded before each
|
|
45
|
+
* observation. Supply `waiterProcessId` to distinguish this operation from other matching waiters.
|
|
46
|
+
*/
|
|
47
|
+
export async function waitForLockWaiter(config, holderProcessId, queryMarker, observerPool = 'write', onDiagnostic, signal, waiterProcessId) {
|
|
48
|
+
await pollUntilNotNull(async () => {
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
if (typeof observerPool === 'function') {
|
|
51
|
+
onDiagnostic?.({ phase: 'snapshot-clear-start', waiting: false });
|
|
52
|
+
signal?.throwIfAborted();
|
|
53
|
+
await observerPool({
|
|
54
|
+
text: `/* waitForTestPostgresLockWaiter.refresh */ ${CLEAR_SNAPSHOT}`,
|
|
55
|
+
});
|
|
56
|
+
signal?.throwIfAborted();
|
|
57
|
+
onDiagnostic?.({ phase: 'snapshot-cleared', waiting: false });
|
|
58
|
+
}
|
|
59
|
+
onDiagnostic?.({ phase: 'waiter-query-start', waiting: false });
|
|
60
|
+
signal?.throwIfAborted();
|
|
61
|
+
const { rows } = await runObservation(config, observerPool, WAITER_SQL, [waiterProcessId ?? null, likeContains(queryMarker), holderProcessId]);
|
|
62
|
+
signal?.throwIfAborted();
|
|
63
|
+
onDiagnostic?.({ phase: 'waiter-query', waiting: rows[0]?.waiting ?? false });
|
|
64
|
+
return rows[0]?.waiting ? true : null;
|
|
65
|
+
}, config.timeoutMs ?? 5_000, config.intervalMs ?? 10).catch((err) => {
|
|
66
|
+
const cause = signal?.aborted && err !== signal.reason
|
|
67
|
+
? new SuppressedError(err, signal.reason, 'Lock observation failed during cancellation')
|
|
68
|
+
: err;
|
|
69
|
+
throw new Error(`Operation did not wait for the test lock: ${queryMarker}`, { cause });
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Waits until one backend is blocked by `holderProcessId` on `directQueryMarker` and a second
|
|
74
|
+
* backend is blocked by that first backend on one of `blockedByDirectQueryMarkers`.
|
|
75
|
+
*
|
|
76
|
+
* Use this when the second operation cannot reach the holder's lock because the first operation
|
|
77
|
+
* already holds a conflicting row lock. `pg_blocking_pids` reports only the direct blocker, so
|
|
78
|
+
* the second wait is the transitive link.
|
|
79
|
+
*/
|
|
80
|
+
export async function waitForBlockedLockChain(config, holderProcessId, directQueryMarker, blockedByDirectQueryMarkers, observerPool = 'advisoryLock') {
|
|
81
|
+
await pollUntilNotNull(async () => {
|
|
82
|
+
if (typeof observerPool === 'function')
|
|
83
|
+
await observerPool({
|
|
84
|
+
text: `/* waitForTestPostgresBlockedLockChain.refresh */ ${CLEAR_SNAPSHOT}`,
|
|
85
|
+
});
|
|
86
|
+
const { rows } = await runObservation(config, observerPool, CHAIN_SQL, [
|
|
87
|
+
likeContains(directQueryMarker),
|
|
88
|
+
holderProcessId,
|
|
89
|
+
blockedByDirectQueryMarkers.map(likeContains),
|
|
90
|
+
]);
|
|
91
|
+
return rows[0]?.waiting ? true : null;
|
|
92
|
+
}, config.timeoutMs ?? 5_000, config.intervalMs ?? 10).catch((err) => {
|
|
93
|
+
throw new Error(`Operations did not form a lock chain behind the test holder: ${directQueryMarker}`, { cause: err });
|
|
94
|
+
});
|
|
95
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
const observationScope = new AsyncLocalStorage();
|
|
3
|
+
const poolObservationQueue = { tail: Promise.resolve() };
|
|
4
|
+
/** Serializes pool instrumentation so two fault scopes never wrap the same pool at once. */
|
|
5
|
+
export async function runPoolObservationExclusively(operation) {
|
|
6
|
+
if (observationScope.getStore()?.active)
|
|
7
|
+
throw new Error('PostgreSQL pool instrumentation cannot be nested');
|
|
8
|
+
const previousObservation = poolObservationQueue.tail;
|
|
9
|
+
let releaseObservation;
|
|
10
|
+
poolObservationQueue.tail = new Promise((resolve) => {
|
|
11
|
+
releaseObservation = resolve;
|
|
12
|
+
});
|
|
13
|
+
await previousObservation;
|
|
14
|
+
const context = { active: true };
|
|
15
|
+
try {
|
|
16
|
+
return await observationScope.run(context, operation);
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
context.active = false;
|
|
20
|
+
releaseObservation();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Polls `fn` until it returns a non-null value, then returns it. Throws once `maxMs` elapses, even
|
|
3
|
+
* when a reading never settles, so a value that never appears fails at the wait instead of letting
|
|
4
|
+
* a later assertion pass vacuously.
|
|
5
|
+
*/
|
|
6
|
+
export declare function pollUntilNotNull<T>(fn: () => Promise<T | null | undefined>, maxMs?: number, intervalMs?: number, description?: string): Promise<T>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** How long the final reading after the deadline may take before the wait gives up. */
|
|
2
|
+
const FINAL_READING_GRACE_MS = 250;
|
|
3
|
+
async function within(reading, ms, timeoutError) {
|
|
4
|
+
let timer;
|
|
5
|
+
const timeout = new Promise((_, reject) => {
|
|
6
|
+
timer = setTimeout(() => reject(timeoutError), ms);
|
|
7
|
+
});
|
|
8
|
+
try {
|
|
9
|
+
return await Promise.race([reading, timeout]);
|
|
10
|
+
}
|
|
11
|
+
finally {
|
|
12
|
+
clearTimeout(timer);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Polls `fn` until it returns a non-null value, then returns it. Throws once `maxMs` elapses, even
|
|
17
|
+
* when a reading never settles, so a value that never appears fails at the wait instead of letting
|
|
18
|
+
* a later assertion pass vacuously.
|
|
19
|
+
*/
|
|
20
|
+
export async function pollUntilNotNull(fn, maxMs = 2000, intervalMs = 25, description = 'a non-null value') {
|
|
21
|
+
const timeoutError = new Error(`Timed out waiting for ${description} (after ${maxMs}ms)`);
|
|
22
|
+
const deadline = Date.now() + maxMs;
|
|
23
|
+
while (Date.now() < deadline) {
|
|
24
|
+
const result = await within(fn(), Math.max(deadline - Date.now(), 1), timeoutError);
|
|
25
|
+
if (result != null)
|
|
26
|
+
return result;
|
|
27
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
28
|
+
}
|
|
29
|
+
const last = await within(fn(), FINAL_READING_GRACE_MS, timeoutError);
|
|
30
|
+
if (last != null)
|
|
31
|
+
return last;
|
|
32
|
+
throw timeoutError;
|
|
33
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PostgresFaultOptions, PostgresFaultResult } from './fault-types.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Lets the unchanged `pg.Pool#query` core execute its original SQL on an actual aborted client.
|
|
4
|
+
* The statement whose text starts with `queryMarker` (for example a leading block comment naming
|
|
5
|
+
* the statement) is run after a real division by zero aborts the leased transaction, so
|
|
6
|
+
* PostgreSQL answers it with `25P02`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function withPostgresPoolQueryFailureForTest<Result>(queryMarker: string, operation: () => Promise<Result>, options: PostgresFaultOptions): Promise<PostgresFaultResult<Result>>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { assertFaultOptions, hasErrorCode, installProperty, isPlainTextConfig, ownsRequest, queryText, restoreProperty, targetsStatement, } from "./fault-support.mjs";
|
|
4
|
+
import { runPoolObservationExclusively } from "./observation-queue.mjs";
|
|
5
|
+
const leaseContext = new AsyncLocalStorage();
|
|
6
|
+
const failureContext = new AsyncLocalStorage();
|
|
7
|
+
/**
|
|
8
|
+
* Lets the unchanged `pg.Pool#query` core execute its original SQL on an actual aborted client.
|
|
9
|
+
* The statement whose text starts with `queryMarker` (for example a leading block comment naming
|
|
10
|
+
* the statement) is run after a real division by zero aborts the leased transaction, so
|
|
11
|
+
* PostgreSQL answers it with `25P02`.
|
|
12
|
+
*/
|
|
13
|
+
export async function withPostgresPoolQueryFailureForTest(queryMarker, operation, options) {
|
|
14
|
+
assertFaultOptions(queryMarker, options);
|
|
15
|
+
const endTimeoutMs = options.endTimeoutMs ?? 5_000;
|
|
16
|
+
return runPoolObservationExclusively(async () => {
|
|
17
|
+
const context = { active: true };
|
|
18
|
+
let fired = false;
|
|
19
|
+
let targetError;
|
|
20
|
+
let cleanupFailure;
|
|
21
|
+
const originals = options.pools.map((pool) => ({
|
|
22
|
+
pool,
|
|
23
|
+
query: pool.query,
|
|
24
|
+
connect: pool.connect,
|
|
25
|
+
queryDescriptor: Object.getOwnPropertyDescriptor(pool, 'query'),
|
|
26
|
+
connectDescriptor: Object.getOwnPropertyDescriptor(pool, 'connect'),
|
|
27
|
+
}));
|
|
28
|
+
function requireFailure(result) {
|
|
29
|
+
if (cleanupFailure)
|
|
30
|
+
throw cleanupFailure;
|
|
31
|
+
if (!targetError)
|
|
32
|
+
throw new Error('The operation did not execute the targeted failed SQL');
|
|
33
|
+
return { result, error: targetError };
|
|
34
|
+
}
|
|
35
|
+
async function executeFault(pool, query, connect, args) {
|
|
36
|
+
const client = await Reflect.apply(connect, pool, []);
|
|
37
|
+
const lease = { pool, client, active: true, handedOff: false };
|
|
38
|
+
// Register before release: pg-pool destroys errored clients without awaiting their end.
|
|
39
|
+
const ended = once(client, 'end', { signal: AbortSignal.timeout(endTimeoutMs) });
|
|
40
|
+
// Observe rejection immediately even if SQL fails before cleanup awaits this promise.
|
|
41
|
+
const settledEnd = ended.then(() => undefined, (err) => err);
|
|
42
|
+
let result;
|
|
43
|
+
let failure;
|
|
44
|
+
try {
|
|
45
|
+
// The lease transfers release to the unchanged pg-pool core; destroying that client owns rollback.
|
|
46
|
+
await client.query('BEGIN');
|
|
47
|
+
try {
|
|
48
|
+
await client.query('/* withPostgresPoolQueryFailureForTest */ SELECT 1 / 0');
|
|
49
|
+
throw new Error('PostgreSQL unexpectedly accepted division by zero');
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
if (!hasErrorCode(err, '22012'))
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
result = await leaseContext.run(lease, () => Reflect.apply(query, pool, args));
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
if (!hasErrorCode(err, '25P02'))
|
|
60
|
+
throw err;
|
|
61
|
+
if (!lease.handedOff)
|
|
62
|
+
throw new Error('The original pool core did not acquire the lease', { cause: err });
|
|
63
|
+
targetError = err;
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
failure = err;
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
lease.active = false;
|
|
72
|
+
if (!lease.handedOff)
|
|
73
|
+
client.release(true);
|
|
74
|
+
}
|
|
75
|
+
const endError = await settledEnd;
|
|
76
|
+
if (endError) {
|
|
77
|
+
cleanupFailure = new AggregateError([endError, failure], 'The failed pool client did not finish closing');
|
|
78
|
+
throw cleanupFailure;
|
|
79
|
+
}
|
|
80
|
+
if (failure instanceof Error)
|
|
81
|
+
throw failure;
|
|
82
|
+
if (failure)
|
|
83
|
+
throw new Error('Pool query failed with a non-Error rejection', { cause: failure });
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
function wrapPoolQuery(pool, query, connect) {
|
|
87
|
+
return ((...args) => {
|
|
88
|
+
const text = queryText(args[0]);
|
|
89
|
+
const ownsContext = failureContext.getStore() === context || ownsRequest(options);
|
|
90
|
+
if (!ownsContext ||
|
|
91
|
+
!context.active ||
|
|
92
|
+
fired ||
|
|
93
|
+
!targetsStatement(text, queryMarker, options.command))
|
|
94
|
+
return Reflect.apply(query, pool, args);
|
|
95
|
+
if (!isPlainTextConfig(args))
|
|
96
|
+
throw new Error('Target fault requires the adapter plain-config Promise pool query');
|
|
97
|
+
fired = true;
|
|
98
|
+
return executeFault(pool, query, connect, args);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function wrapPoolConnect(pool, connect) {
|
|
102
|
+
return ((...args) => {
|
|
103
|
+
const lease = leaseContext.getStore();
|
|
104
|
+
if (lease?.active &&
|
|
105
|
+
lease.pool === pool &&
|
|
106
|
+
!lease.handedOff &&
|
|
107
|
+
args.length === 1 &&
|
|
108
|
+
typeof args[0] === 'function') {
|
|
109
|
+
const callback = args[0];
|
|
110
|
+
queueMicrotask(() => {
|
|
111
|
+
if (!lease.active)
|
|
112
|
+
return;
|
|
113
|
+
lease.handedOff = true;
|
|
114
|
+
callback(null, lease.client, lease.client.release);
|
|
115
|
+
});
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
return Reflect.apply(connect, pool, args);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
for (const { pool, query, connect } of originals) {
|
|
123
|
+
installProperty(pool, 'connect', wrapPoolConnect(pool, connect));
|
|
124
|
+
installProperty(pool, 'query', wrapPoolQuery(pool, query, connect));
|
|
125
|
+
}
|
|
126
|
+
return await failureContext.run(context, async () => requireFailure(await operation()));
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
context.active = false;
|
|
130
|
+
for (const { pool, queryDescriptor, connectDescriptor } of originals) {
|
|
131
|
+
restoreProperty(pool, 'query', queryDescriptor);
|
|
132
|
+
restoreProperty(pool, 'connect', connectDescriptor);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PostgresFaultOptions, PostgresFaultResult } from './fault-types.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Fails one actual SQL statement after its owner has begun a real transaction. The statement whose
|
|
4
|
+
* text starts with `queryMarker` runs after a real division by zero aborts that transaction, so
|
|
5
|
+
* PostgreSQL answers it with `25P02`. The statement must be issued on a client leased from one of
|
|
6
|
+
* `options.pools`, after a `BEGIN` sent through the same client.
|
|
7
|
+
*/
|
|
8
|
+
export declare function withPostgresQueryFailureForTest<Result>(queryMarker: string, operation: () => Promise<Result>, options: PostgresFaultOptions): Promise<PostgresFaultResult<Result>>;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { assertFaultOptions, hasErrorCode, installProperty, isPlainTextConfig, ownsRequest, queryText, restoreProperty, targetsStatement, } from "./fault-support.mjs";
|
|
3
|
+
import { runPoolObservationExclusively } from "./observation-queue.mjs";
|
|
4
|
+
/** COMMIT, END, ABORT and ROLLBACK end the transaction; ROLLBACK TO SAVEPOINT and AND CHAIN keep one open. */
|
|
5
|
+
function endsTransaction(command) {
|
|
6
|
+
return (/^(?:COMMIT|ROLLBACK|END|ABORT)\b/i.test(command) &&
|
|
7
|
+
!/^ROLLBACK\s+(?:(?:WORK|TRANSACTION)\s+)?TO\b/i.test(command) &&
|
|
8
|
+
!/\bAND\s+CHAIN\b/i.test(command));
|
|
9
|
+
}
|
|
10
|
+
const queryFailureContext = new AsyncLocalStorage();
|
|
11
|
+
/**
|
|
12
|
+
* Fails one actual SQL statement after its owner has begun a real transaction. The statement whose
|
|
13
|
+
* text starts with `queryMarker` runs after a real division by zero aborts that transaction, so
|
|
14
|
+
* PostgreSQL answers it with `25P02`. The statement must be issued on a client leased from one of
|
|
15
|
+
* `options.pools`, after a `BEGIN` sent through the same client.
|
|
16
|
+
*/
|
|
17
|
+
export async function withPostgresQueryFailureForTest(queryMarker, operation, options) {
|
|
18
|
+
assertFaultOptions(queryMarker, options);
|
|
19
|
+
return runPoolObservationExclusively(async () => {
|
|
20
|
+
const context = { active: true };
|
|
21
|
+
const ownsContext = () => context.active && (queryFailureContext.getStore() === context || ownsRequest(options));
|
|
22
|
+
let fired = false;
|
|
23
|
+
let targetError;
|
|
24
|
+
const restorations = new Set();
|
|
25
|
+
const poolDescriptors = options.pools.map((pool) => ({
|
|
26
|
+
pool,
|
|
27
|
+
descriptor: Object.getOwnPropertyDescriptor(pool, 'connect'),
|
|
28
|
+
connect: pool.connect,
|
|
29
|
+
}));
|
|
30
|
+
function observeClient(client) {
|
|
31
|
+
const queryDescriptor = Object.getOwnPropertyDescriptor(client, 'query');
|
|
32
|
+
const releaseDescriptor = Object.getOwnPropertyDescriptor(client, 'release');
|
|
33
|
+
const originalQuery = client.query;
|
|
34
|
+
const originalRelease = client.release;
|
|
35
|
+
let began = false;
|
|
36
|
+
const restore = () => {
|
|
37
|
+
restoreProperty(client, 'query', queryDescriptor);
|
|
38
|
+
restoreProperty(client, 'release', releaseDescriptor);
|
|
39
|
+
restorations.delete(restore);
|
|
40
|
+
};
|
|
41
|
+
restorations.add(restore);
|
|
42
|
+
async function failActualStatement(args) {
|
|
43
|
+
try {
|
|
44
|
+
await Reflect.apply(originalQuery, client, [
|
|
45
|
+
'/* withPostgresQueryFailureForTest */ SELECT 1 / 0',
|
|
46
|
+
]);
|
|
47
|
+
throw new Error('PostgreSQL unexpectedly accepted division by zero');
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
if (!hasErrorCode(err, '22012'))
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
return await Reflect.apply(originalQuery, client, args);
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
if (!hasErrorCode(err, '25P02'))
|
|
58
|
+
throw err;
|
|
59
|
+
targetError = err;
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
installProperty(client, 'query', (...args) => {
|
|
64
|
+
const text = queryText(args[0]);
|
|
65
|
+
const command = text.trimStart().replace(/^\/\*[\s\S]*?\*\/\s*/, '');
|
|
66
|
+
const owned = ownsContext();
|
|
67
|
+
if (owned && /^(?:BEGIN|START\s+TRANSACTION)\b/i.test(command))
|
|
68
|
+
began = true;
|
|
69
|
+
if (owned && endsTransaction(command))
|
|
70
|
+
began = false;
|
|
71
|
+
if (!owned || fired || !targetsStatement(text, queryMarker, options.command))
|
|
72
|
+
return Reflect.apply(originalQuery, client, args);
|
|
73
|
+
if (!began || !isPlainTextConfig(args))
|
|
74
|
+
throw new Error('Target fault requires the owned transaction adapter Promise query');
|
|
75
|
+
fired = true;
|
|
76
|
+
return failActualStatement(args);
|
|
77
|
+
});
|
|
78
|
+
installProperty(client, 'release', (...args) => {
|
|
79
|
+
restore();
|
|
80
|
+
return Reflect.apply(originalRelease, client, args);
|
|
81
|
+
});
|
|
82
|
+
return client;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
for (const { pool, connect } of poolDescriptors) {
|
|
86
|
+
installProperty(pool, 'connect', (...args) => {
|
|
87
|
+
// Pool.query uses a callback; preserve that overload and every other context exactly.
|
|
88
|
+
if (args.length || !ownsContext())
|
|
89
|
+
return Reflect.apply(connect, pool, args);
|
|
90
|
+
return Reflect.apply(connect, pool, args).then((client) => context.active ? observeClient(client) : client);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return await queryFailureContext.run(context, async () => {
|
|
94
|
+
const result = await operation();
|
|
95
|
+
if (!targetError)
|
|
96
|
+
throw new Error('The operation did not execute the targeted failed SQL');
|
|
97
|
+
return { result, error: targetError };
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
context.active = false;
|
|
102
|
+
for (const restore of restorations)
|
|
103
|
+
restore();
|
|
104
|
+
for (const { pool, descriptor } of poolDescriptors)
|
|
105
|
+
restoreProperty(pool, 'connect', descriptor);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
export type TestCluster = {
|
|
3
|
+
/** Opens a pool against the throwaway cluster. */
|
|
4
|
+
createPool: (max?: number) => pg.Pool;
|
|
5
|
+
stop: () => Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Starts a throwaway PostgreSQL cluster (binaries from `POSTGRES_BIN_DIR`, `PATH` or a standard
|
|
9
|
+
* install location). Returns undefined when no server can run here, for example inside a sandbox
|
|
10
|
+
* that forbids shared memory, so the real-database suites skip. Under CI that is a failure
|
|
11
|
+
* instead, so the real-database tests cannot be silently skipped there.
|
|
12
|
+
*/
|
|
13
|
+
export declare function tryStartTestCluster(): Promise<TestCluster | undefined>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, globSync, mkdtempSync, rmSync } from 'node:fs';
|
|
3
|
+
import { createServer } from 'node:net';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { delimiter, join } from 'node:path';
|
|
6
|
+
import pg from 'pg';
|
|
7
|
+
function findPostgresBinDir() {
|
|
8
|
+
return [
|
|
9
|
+
process.env.POSTGRES_BIN_DIR ?? '',
|
|
10
|
+
...(process.env.PATH ?? '').split(delimiter),
|
|
11
|
+
...globSync('/usr/lib/postgresql/*/bin'),
|
|
12
|
+
...globSync('/opt/homebrew/opt/postgresql@*/bin'),
|
|
13
|
+
...globSync('/usr/local/opt/postgresql@*/bin'),
|
|
14
|
+
].find((dir) => dir && existsSync(join(dir, 'initdb')) && existsSync(join(dir, 'pg_ctl')));
|
|
15
|
+
}
|
|
16
|
+
async function freePort() {
|
|
17
|
+
const server = createServer();
|
|
18
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
19
|
+
const address = server.address();
|
|
20
|
+
const port = typeof address === 'object' && address ? address.port : 0;
|
|
21
|
+
await new Promise((resolve) => server.close(resolve));
|
|
22
|
+
return port;
|
|
23
|
+
}
|
|
24
|
+
async function startTestCluster(binDir) {
|
|
25
|
+
const dir = mkdtempSync(join(tmpdir(), 'pg-faults-'));
|
|
26
|
+
const run = (bin, args) => execFileSync(join(binDir, bin), args, { stdio: 'pipe' });
|
|
27
|
+
try {
|
|
28
|
+
const port = await freePort();
|
|
29
|
+
run('initdb', ['-D', dir, '-U', 'postgres', '--auth=trust', '--no-sync']);
|
|
30
|
+
run('pg_ctl', [
|
|
31
|
+
'-D',
|
|
32
|
+
dir,
|
|
33
|
+
'-w',
|
|
34
|
+
'-o',
|
|
35
|
+
`-p ${port} -h 127.0.0.1 -c fsync=off -c unix_socket_directories=${dir}`,
|
|
36
|
+
'-l',
|
|
37
|
+
join(dir, 'server.log'),
|
|
38
|
+
'start',
|
|
39
|
+
]);
|
|
40
|
+
const pools = new Set();
|
|
41
|
+
return {
|
|
42
|
+
createPool: (max = 4) => {
|
|
43
|
+
const pool = new pg.Pool({
|
|
44
|
+
host: '127.0.0.1',
|
|
45
|
+
port,
|
|
46
|
+
user: 'postgres',
|
|
47
|
+
database: 'postgres',
|
|
48
|
+
max,
|
|
49
|
+
});
|
|
50
|
+
pools.add(pool);
|
|
51
|
+
return pool;
|
|
52
|
+
},
|
|
53
|
+
stop: async () => {
|
|
54
|
+
await Promise.allSettled([...pools].map((pool) => pool.end()));
|
|
55
|
+
run('pg_ctl', ['-D', dir, '-m', 'immediate', '-w', 'stop']);
|
|
56
|
+
rmSync(dir, { recursive: true, force: true });
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
rmSync(dir, { recursive: true, force: true });
|
|
62
|
+
throw err;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Starts a throwaway PostgreSQL cluster (binaries from `POSTGRES_BIN_DIR`, `PATH` or a standard
|
|
67
|
+
* install location). Returns undefined when no server can run here, for example inside a sandbox
|
|
68
|
+
* that forbids shared memory, so the real-database suites skip. Under CI that is a failure
|
|
69
|
+
* instead, so the real-database tests cannot be silently skipped there.
|
|
70
|
+
*/
|
|
71
|
+
export async function tryStartTestCluster() {
|
|
72
|
+
try {
|
|
73
|
+
const binDir = findPostgresBinDir();
|
|
74
|
+
if (!binDir)
|
|
75
|
+
throw new Error('PostgreSQL binaries (initdb, pg_ctl) were not found');
|
|
76
|
+
return await startTestCluster(binDir);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
if (process.env.CI)
|
|
80
|
+
throw err;
|
|
81
|
+
console.warn(`Skipping real PostgreSQL tests: ${err.message.split('\n')[0]}`);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Runs `handler` once if `signal` aborts; the returned function detaches it. */
|
|
2
|
+
export declare function onAbort(signal: AbortSignal | null | undefined, handler: () => void): () => void;
|
|
3
|
+
/** Reads the request body, rejecting with the signal's reason if it aborts before the body ends. */
|
|
4
|
+
export declare function readUntilAborted(request: Request, signal: AbortSignal): Promise<Buffer>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Runs `handler` once if `signal` aborts; the returned function detaches it. */
|
|
2
|
+
export function onAbort(signal, handler) {
|
|
3
|
+
signal?.addEventListener('abort', handler, { once: true });
|
|
4
|
+
return () => signal?.removeEventListener('abort', handler);
|
|
5
|
+
}
|
|
6
|
+
/** Reads the request body, rejecting with the signal's reason if it aborts before the body ends. */
|
|
7
|
+
export async function readUntilAborted(request, signal) {
|
|
8
|
+
signal.throwIfAborted();
|
|
9
|
+
let detach;
|
|
10
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
11
|
+
detach = onAbort(signal, () => reject(signal.reason));
|
|
12
|
+
});
|
|
13
|
+
try {
|
|
14
|
+
return Buffer.from(await Promise.race([request.arrayBuffer(), aborted]));
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
detach();
|
|
18
|
+
}
|
|
19
|
+
}
|