vouchington-tooling 0.61.1 → 0.63.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 +80 -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/runner-port-policy/index.d.mts +9 -0
- package/dist/runner-port-policy/index.mjs +32 -0
- package/dist/vitest-diagnostics/index.d.mts +8 -0
- package/dist/vitest-diagnostics/index.mjs +4 -0
- package/dist/vitest-diagnostics/vitest-ci-reporters.d.mts +40 -0
- package/dist/vitest-diagnostics/vitest-ci-reporters.mjs +70 -0
- package/dist/vitest-diagnostics/vitest-file-progress-reporter.d.mts +24 -0
- package/dist/vitest-diagnostics/vitest-file-progress-reporter.mjs +49 -0
- package/dist/vitest-diagnostics/vitest-github-actions-reporter.d.mts +13 -0
- package/dist/vitest-diagnostics/vitest-github-actions-reporter.mjs +35 -0
- package/dist/vitest-diagnostics/vitest-storybook-progress-reporter.d.mts +24 -0
- package/dist/vitest-diagnostics/vitest-storybook-progress-reporter.mjs +53 -0
- package/package.json +17 -1
- package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
function assertAwsAbortSignal(source) {
|
|
2
|
+
if (typeof source !== 'object' || !('aborted' in source) || typeof source.aborted !== 'boolean')
|
|
3
|
+
throw new TypeError('Invalid AWS request abort signal');
|
|
4
|
+
}
|
|
5
|
+
/** Smithy accepts native, cross-realm EventTarget, and legacy onabort signals. */
|
|
6
|
+
export function observeAwsReplayAbort(source) {
|
|
7
|
+
if (source == null)
|
|
8
|
+
return { signal: undefined, detach: () => { } };
|
|
9
|
+
if (source instanceof AbortSignal)
|
|
10
|
+
return { signal: source, detach: () => { } };
|
|
11
|
+
assertAwsAbortSignal(source);
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const abort = () => controller.abort(source.reason);
|
|
14
|
+
if (source.aborted) {
|
|
15
|
+
abort();
|
|
16
|
+
return { signal: controller.signal, detach: () => { } };
|
|
17
|
+
}
|
|
18
|
+
let detach;
|
|
19
|
+
if (typeof source.addEventListener === 'function' &&
|
|
20
|
+
typeof source.removeEventListener === 'function') {
|
|
21
|
+
source.addEventListener('abort', abort, { once: true });
|
|
22
|
+
detach = () => source.removeEventListener('abort', abort);
|
|
23
|
+
}
|
|
24
|
+
else if ('onabort' in source) {
|
|
25
|
+
detach = observeLegacyAbort(source, abort);
|
|
26
|
+
}
|
|
27
|
+
else
|
|
28
|
+
throw new TypeError('AWS request abort signal has no notification API');
|
|
29
|
+
// Cancellation can race with installing the observer.
|
|
30
|
+
if (source.aborted)
|
|
31
|
+
abort();
|
|
32
|
+
return { signal: controller.signal, detach };
|
|
33
|
+
}
|
|
34
|
+
const legacyObservers = new WeakMap();
|
|
35
|
+
function legacyState(source) {
|
|
36
|
+
const existing = legacyObservers.get(source);
|
|
37
|
+
if (existing && source.onabort === existing.listener)
|
|
38
|
+
return existing;
|
|
39
|
+
const previous = source.onabort;
|
|
40
|
+
const callbacks = new Set();
|
|
41
|
+
const listener = (event) => {
|
|
42
|
+
for (const callback of callbacks)
|
|
43
|
+
callback();
|
|
44
|
+
previous?.call(source, event);
|
|
45
|
+
};
|
|
46
|
+
const state = { callbacks, previous, listener };
|
|
47
|
+
legacyObservers.set(source, state);
|
|
48
|
+
source.onabort = listener;
|
|
49
|
+
return state;
|
|
50
|
+
}
|
|
51
|
+
function observeLegacyAbort(source, abort) {
|
|
52
|
+
const observed = legacyState(source);
|
|
53
|
+
observed.callbacks.add(abort);
|
|
54
|
+
return () => {
|
|
55
|
+
observed.callbacks.delete(abort);
|
|
56
|
+
if (observed.callbacks.size > 0)
|
|
57
|
+
return;
|
|
58
|
+
if (source.onabort === observed.listener)
|
|
59
|
+
source.onabort = observed.previous;
|
|
60
|
+
if (legacyObservers.get(source) === observed)
|
|
61
|
+
legacyObservers.delete(source);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import type { ProviderReplay } from './provider-replay.mts';
|
|
3
|
+
/** The parts of smithy's `HttpRequest` this handler reads. */
|
|
4
|
+
type AwsReplayHttpRequest = {
|
|
5
|
+
method: string;
|
|
6
|
+
protocol: string;
|
|
7
|
+
hostname: string;
|
|
8
|
+
port?: number;
|
|
9
|
+
path: string;
|
|
10
|
+
query?: Record<string, string | string[] | null>;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
body?: RequestInit['body'];
|
|
13
|
+
};
|
|
14
|
+
type AwsReplayHandlerOptions = {
|
|
15
|
+
abortSignal?: unknown;
|
|
16
|
+
};
|
|
17
|
+
/** Smithy treats any object with a `handle` function as an `HttpHandler`. */
|
|
18
|
+
export type AwsReplayRequestHandler = {
|
|
19
|
+
handle: (request: AwsReplayHttpRequest, options?: AwsReplayHandlerOptions) => Promise<{
|
|
20
|
+
response: {
|
|
21
|
+
statusCode: number;
|
|
22
|
+
reason: string;
|
|
23
|
+
headers: Record<string, string>;
|
|
24
|
+
body: Readable;
|
|
25
|
+
};
|
|
26
|
+
}>;
|
|
27
|
+
destroy: () => void;
|
|
28
|
+
updateHttpClientConfig: () => void;
|
|
29
|
+
httpHandlerConfigs: () => Record<string, never>;
|
|
30
|
+
};
|
|
31
|
+
export declare function createAwsReplayRequestHandler(replay: ProviderReplay): AwsReplayRequestHandler;
|
|
32
|
+
/**
|
|
33
|
+
* Subclasses an AWS SDK client so every instance sends through the replay, whatever
|
|
34
|
+
* `requestHandler` production code configured. Use it inside a `vi.mock` of the SDK package for a
|
|
35
|
+
* client that production builds itself, so the test never edits production code.
|
|
36
|
+
*/
|
|
37
|
+
export declare function replayAwsClient<Client extends abstract new (config: never) => object>(Constructor: Client, replay: ProviderReplay): Client;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { observeAwsReplayAbort } from "./aws-replay-abort-signal.mjs";
|
|
3
|
+
import { forceClientOption } from "./force-client-option.mjs";
|
|
4
|
+
export function createAwsReplayRequestHandler(replay) {
|
|
5
|
+
return {
|
|
6
|
+
async handle(request, options) {
|
|
7
|
+
const origin = new URL(`${request.protocol}//${request.hostname}`);
|
|
8
|
+
if (request.port)
|
|
9
|
+
origin.port = String(request.port);
|
|
10
|
+
const query = serializeAwsReplayQuery(request.query ?? {});
|
|
11
|
+
const url = `${origin.origin}${request.path}${query ? `?${query}` : ''}`;
|
|
12
|
+
const { signal, detach } = observeAwsReplayAbort(options?.abortSignal);
|
|
13
|
+
try {
|
|
14
|
+
const response = await replay.sendHttpRequest(url, {
|
|
15
|
+
method: request.method,
|
|
16
|
+
headers: request.headers,
|
|
17
|
+
body: request.body ?? null,
|
|
18
|
+
duplex: 'half',
|
|
19
|
+
signal: signal ?? null,
|
|
20
|
+
});
|
|
21
|
+
const body = response.body ? Readable.fromWeb(response.body) : Readable.from([]);
|
|
22
|
+
if (response.body)
|
|
23
|
+
body.once('close', detach);
|
|
24
|
+
else
|
|
25
|
+
detach();
|
|
26
|
+
return {
|
|
27
|
+
response: {
|
|
28
|
+
statusCode: response.status,
|
|
29
|
+
reason: response.statusText,
|
|
30
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
31
|
+
body,
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
detach();
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
destroy: () => { },
|
|
41
|
+
updateHttpClientConfig: () => { },
|
|
42
|
+
httpHandlerConfigs: () => ({}),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Smithy's wire query order and RFC3986 escaping, including bare null keys. */
|
|
46
|
+
function serializeAwsReplayQuery(query) {
|
|
47
|
+
const escape = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
48
|
+
return Object.keys(query)
|
|
49
|
+
.toSorted()
|
|
50
|
+
.flatMap((name) => {
|
|
51
|
+
const key = escape(name);
|
|
52
|
+
const value = query[name];
|
|
53
|
+
if (value == null)
|
|
54
|
+
return key;
|
|
55
|
+
return [value].flat().map((part) => `${key}=${escape(part)}`);
|
|
56
|
+
})
|
|
57
|
+
.join('&');
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Subclasses an AWS SDK client so every instance sends through the replay, whatever
|
|
61
|
+
* `requestHandler` production code configured. Use it inside a `vi.mock` of the SDK package for a
|
|
62
|
+
* client that production builds itself, so the test never edits production code.
|
|
63
|
+
*/
|
|
64
|
+
export function replayAwsClient(Constructor, replay) {
|
|
65
|
+
return forceClientOption(Constructor, 'requestHandler', createAwsReplayRequestHandler(replay));
|
|
66
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subclasses an SDK client constructor so every instance is built with `options[name] = value`,
|
|
3
|
+
* whatever the caller configured for that option. The options object is the first constructor
|
|
4
|
+
* argument; any further arguments are forwarded untouched.
|
|
5
|
+
*/
|
|
6
|
+
export declare function forceClientOption<Client extends abstract new (...args: never[]) => object>(Constructor: Client, name: string, value: unknown): Client;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subclasses an SDK client constructor so every instance is built with `options[name] = value`,
|
|
3
|
+
* whatever the caller configured for that option. The options object is the first constructor
|
|
4
|
+
* argument; any further arguments are forwarded untouched.
|
|
5
|
+
*/
|
|
6
|
+
export function forceClientOption(Constructor, name, value) {
|
|
7
|
+
class ForcedOptionClient extends Constructor {
|
|
8
|
+
constructor(options, ...rest) {
|
|
9
|
+
super({ ...options, [name]: value }, ...rest);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
return ForcedOptionClient;
|
|
13
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { onAbort, readUntilAborted } from './abort-listeners.mts';
|
|
2
|
+
export { observeAwsReplayAbort } from './aws-replay-abort-signal.mts';
|
|
3
|
+
export { createAwsReplayRequestHandler, replayAwsClient, type AwsReplayRequestHandler, } from './aws-replay-request-handler.mts';
|
|
4
|
+
export { createProviderReplay, replayClient, type ProviderReplay, type ReplayedRequest, } from './provider-replay.mts';
|
|
5
|
+
export { loadRecordedResponse, parseRecordedResponse, type LoadRecordedResponseOptions, type RecordedResponse, } from './recorded-response.mts';
|
|
6
|
+
export { toReplayResponse } from './replay-response.mts';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { onAbort, readUntilAborted } from "./abort-listeners.mjs";
|
|
2
|
+
export { observeAwsReplayAbort } from "./aws-replay-abort-signal.mjs";
|
|
3
|
+
export { createAwsReplayRequestHandler, replayAwsClient, } from "./aws-replay-request-handler.mjs";
|
|
4
|
+
export { createProviderReplay, replayClient, } from "./provider-replay.mjs";
|
|
5
|
+
export { loadRecordedResponse, parseRecordedResponse, } from "./recorded-response.mjs";
|
|
6
|
+
export { toReplayResponse } from "./replay-response.mjs";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { RecordedResponse } from './recorded-response.mts';
|
|
2
|
+
/** What the code under test sent. Header names are lower-cased. */
|
|
3
|
+
export type ReplayedRequest = {
|
|
4
|
+
method: string;
|
|
5
|
+
url: string;
|
|
6
|
+
headers: Record<string, string>;
|
|
7
|
+
body: Buffer | undefined;
|
|
8
|
+
json: <T = unknown>() => T;
|
|
9
|
+
};
|
|
10
|
+
export type ProviderReplay = {
|
|
11
|
+
/** Pass this as the SDK's `fetch` option. It answers each request with the next queued response. */
|
|
12
|
+
fetch: typeof fetch;
|
|
13
|
+
/** Raw HTTP transport: preserve serialized URL bytes instead of fetch URL normalization. */
|
|
14
|
+
sendHttpRequest: (url: string, init?: RequestInit) => Promise<Response>;
|
|
15
|
+
/** Every request the SDK sent, in order. */
|
|
16
|
+
requests: ReplayedRequest[];
|
|
17
|
+
/** Queue responses; the SDK receives them in request order. */
|
|
18
|
+
respondWith: (...responses: RecordedResponse[]) => void;
|
|
19
|
+
/** Fail when a queued response was never requested, so a skipped call cannot pass silently. */
|
|
20
|
+
assertDrained: () => void;
|
|
21
|
+
/** Forget the queue and the captured requests, for a client shared across the tests of a file. */
|
|
22
|
+
reset: () => void;
|
|
23
|
+
};
|
|
24
|
+
export declare function createProviderReplay(options?: {
|
|
25
|
+
chunkBytes?: number;
|
|
26
|
+
}): ProviderReplay;
|
|
27
|
+
/**
|
|
28
|
+
* Subclasses an SDK client so every instance sends through the replay, whatever `fetch` production
|
|
29
|
+
* code configured. Use it inside a `vi.mock` of the SDK package for a client that production builds
|
|
30
|
+
* itself, so the test never edits production code.
|
|
31
|
+
*/
|
|
32
|
+
export declare function replayClient<Client extends abstract new (...args: never[]) => object>(Constructor: Client, replay: ProviderReplay): Client;
|