vouchington-tooling 0.62.0 → 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 +59 -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/package.json +17 -1
- package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
|
@@ -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;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { readUntilAborted } from "./abort-listeners.mjs";
|
|
2
|
+
import { forceClientOption } from "./force-client-option.mjs";
|
|
3
|
+
import { toReplayResponse } from "./replay-response.mjs";
|
|
4
|
+
export function createProviderReplay(options = {}) {
|
|
5
|
+
const requests = [];
|
|
6
|
+
const queue = [];
|
|
7
|
+
// `new Request(...)` applies fetch semantics to the SDK's arguments: the effective URL, method,
|
|
8
|
+
// and headers (a form body brings its own `content-type`), the body bytes, and an abort signal
|
|
9
|
+
// that follows `init.signal`.
|
|
10
|
+
const replayRequest = async (request, url = request.url, headers = request.headers) => {
|
|
11
|
+
const { signal } = request;
|
|
12
|
+
signal.throwIfAborted();
|
|
13
|
+
// Reserve the request's position and its response before awaiting the body, so concurrent
|
|
14
|
+
// calls keep the order in which they started.
|
|
15
|
+
const sent = {
|
|
16
|
+
method: request.method,
|
|
17
|
+
url,
|
|
18
|
+
headers: Object.fromEntries(headers.entries()),
|
|
19
|
+
body: undefined,
|
|
20
|
+
json: () => JSON.parse(sent.body?.toString('utf8') ?? 'null'),
|
|
21
|
+
};
|
|
22
|
+
requests.push(sent);
|
|
23
|
+
const next = queue.shift();
|
|
24
|
+
if (!next) {
|
|
25
|
+
throw new Error(`Provider replay has no recorded response for request ${requests.length}: ${sent.method} ${sent.url}`);
|
|
26
|
+
}
|
|
27
|
+
const bytes = await readUntilAborted(request, signal);
|
|
28
|
+
sent.body = bytes.length === 0 ? undefined : bytes;
|
|
29
|
+
return toReplayResponse(next, options.chunkBytes, signal);
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
fetch: async (input, init) => replayRequest(new Request(input, init)),
|
|
33
|
+
sendHttpRequest: async (url, init) => replayRequest(new Request(url, init), url, new Headers(init?.headers)),
|
|
34
|
+
requests,
|
|
35
|
+
respondWith: (...responses) => void queue.push(...responses),
|
|
36
|
+
assertDrained: () => {
|
|
37
|
+
if (queue.length > 0) {
|
|
38
|
+
throw new Error(`Provider replay left ${queue.length} recorded response(s) unrequested`);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
reset: () => {
|
|
42
|
+
requests.length = 0;
|
|
43
|
+
queue.length = 0;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Subclasses an SDK client so every instance sends through the replay, whatever `fetch` production
|
|
49
|
+
* code configured. Use it inside a `vi.mock` of the SDK package for a client that production builds
|
|
50
|
+
* itself, so the test never edits production code.
|
|
51
|
+
*/
|
|
52
|
+
export function replayClient(Constructor, replay) {
|
|
53
|
+
return forceClientOption(Constructor, 'fetch', replay.fetch);
|
|
54
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** A provider response as it arrived on the wire: status, headers and the raw body bytes. */
|
|
2
|
+
export type RecordedResponse = {
|
|
3
|
+
status: number;
|
|
4
|
+
statusText: string;
|
|
5
|
+
headers: Array<[name: string, value: string]>;
|
|
6
|
+
body: Buffer;
|
|
7
|
+
};
|
|
8
|
+
export type LoadRecordedResponseOptions = {
|
|
9
|
+
/** Directory (path or `file:` URL) that holds the raw `.http` fixtures. */
|
|
10
|
+
fixtureRoot: string | URL;
|
|
11
|
+
/** Literal tokens swapped in the whole file, for ids a test must keep unique. */
|
|
12
|
+
replace?: Record<string, string>;
|
|
13
|
+
};
|
|
14
|
+
/** Loads the raw `.http` fixture `<fixtureRoot>/<name>` and parses it. */
|
|
15
|
+
export declare function loadRecordedResponse(name: string, options: LoadRecordedResponseOptions): RecordedResponse;
|
|
16
|
+
/** Parses raw HTTP response text: a status line, headers, a blank line, then the body bytes. */
|
|
17
|
+
export declare function parseRecordedResponse(raw: Buffer): RecordedResponse;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/** Headers describing the original transfer framing; the replay serves the decoded body instead. */
|
|
5
|
+
const FRAMING_HEADERS = new Set([
|
|
6
|
+
'connection',
|
|
7
|
+
'content-encoding',
|
|
8
|
+
'content-length',
|
|
9
|
+
'keep-alive',
|
|
10
|
+
'transfer-encoding',
|
|
11
|
+
]);
|
|
12
|
+
/** Loads the raw `.http` fixture `<fixtureRoot>/<name>` and parses it. */
|
|
13
|
+
export function loadRecordedResponse(name, options) {
|
|
14
|
+
const { fixtureRoot } = options;
|
|
15
|
+
const root = typeof fixtureRoot === 'string' ? fixtureRoot : fileURLToPath(fixtureRoot);
|
|
16
|
+
let raw = readFileSync(resolve(root, name)).toString('latin1');
|
|
17
|
+
for (const [token, value] of Object.entries(options.replace ?? {})) {
|
|
18
|
+
raw = raw.replaceAll(token, value);
|
|
19
|
+
}
|
|
20
|
+
return parseRecordedResponse(Buffer.from(raw, 'latin1'));
|
|
21
|
+
}
|
|
22
|
+
/** Parses raw HTTP response text: a status line, headers, a blank line, then the body bytes. */
|
|
23
|
+
export function parseRecordedResponse(raw) {
|
|
24
|
+
const crlf = raw.indexOf('\r\n\r\n');
|
|
25
|
+
const lf = raw.indexOf('\n\n');
|
|
26
|
+
const useCrlf = crlf !== -1 && (lf === -1 || crlf < lf);
|
|
27
|
+
const headEnd = useCrlf ? crlf : lf;
|
|
28
|
+
const head = headEnd === -1 ? raw : raw.subarray(0, headEnd);
|
|
29
|
+
const body = headEnd === -1 ? Buffer.alloc(0) : raw.subarray(headEnd + (useCrlf ? 4 : 2));
|
|
30
|
+
const [statusLine = '', ...headerLines] = head.toString('latin1').split(/\r?\n/);
|
|
31
|
+
const status = /^HTTP\/\S+ (\d{3})(?: (.*))?$/.exec(statusLine);
|
|
32
|
+
if (!status)
|
|
33
|
+
throw new Error(`Recorded response has no HTTP status line: ${statusLine}`);
|
|
34
|
+
const headers = headerLines.flatMap((line) => {
|
|
35
|
+
const colon = line.indexOf(':');
|
|
36
|
+
const name = line.slice(0, colon).trim().toLowerCase();
|
|
37
|
+
if (colon < 1 || FRAMING_HEADERS.has(name))
|
|
38
|
+
return [];
|
|
39
|
+
return [[name, line.slice(colon + 1).trim()]];
|
|
40
|
+
});
|
|
41
|
+
return { status: Number(status[1]), statusText: status[2] ?? '', headers, body };
|
|
42
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RecordedResponse } from './recorded-response.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Builds the `Response` an SDK reads. The body streams in `chunkBytes` pieces (default: one), so a
|
|
4
|
+
* small value proves the consumer does not depend on events arriving aligned to chunk boundaries.
|
|
5
|
+
* When the request's `signal` aborts while the body is being read, the stream errors with the
|
|
6
|
+
* signal's reason, as a real transport does.
|
|
7
|
+
*/
|
|
8
|
+
export declare function toReplayResponse(recorded: RecordedResponse, chunkBytes?: number, signal?: AbortSignal | null): Response;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { onAbort } from "./abort-listeners.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* Builds the `Response` an SDK reads. The body streams in `chunkBytes` pieces (default: one), so a
|
|
4
|
+
* small value proves the consumer does not depend on events arriving aligned to chunk boundaries.
|
|
5
|
+
* When the request's `signal` aborts while the body is being read, the stream errors with the
|
|
6
|
+
* signal's reason, as a real transport does.
|
|
7
|
+
*/
|
|
8
|
+
export function toReplayResponse(recorded, chunkBytes, signal) {
|
|
9
|
+
const size = chunkBytes ?? Math.max(recorded.body.length, 1);
|
|
10
|
+
if (!Number.isSafeInteger(size) || size < 1) {
|
|
11
|
+
throw new RangeError(`chunkBytes must be a positive integer, received ${chunkBytes}`);
|
|
12
|
+
}
|
|
13
|
+
let offset = 0;
|
|
14
|
+
let detach;
|
|
15
|
+
const body = recorded.body.length === 0
|
|
16
|
+
? null
|
|
17
|
+
: new ReadableStream({
|
|
18
|
+
start(controller) {
|
|
19
|
+
detach = onAbort(signal, () => controller.error(signal?.reason));
|
|
20
|
+
},
|
|
21
|
+
pull(controller) {
|
|
22
|
+
if (signal?.aborted)
|
|
23
|
+
return controller.error(signal.reason);
|
|
24
|
+
if (offset >= recorded.body.length) {
|
|
25
|
+
detach();
|
|
26
|
+
return controller.close();
|
|
27
|
+
}
|
|
28
|
+
controller.enqueue(recorded.body.subarray(offset, offset + size));
|
|
29
|
+
offset += size;
|
|
30
|
+
},
|
|
31
|
+
cancel: detach,
|
|
32
|
+
});
|
|
33
|
+
return new Response(body, {
|
|
34
|
+
status: recorded.status,
|
|
35
|
+
statusText: recorded.statusText,
|
|
36
|
+
headers: recorded.headers,
|
|
37
|
+
});
|
|
38
|
+
}
|