@terreno/test 57.18.0 → 57.20.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/CHANGELOG.md +2074 -0
- package/README.md +6 -0
- package/dist/assertions/expectAPIError.d.ts +18 -0
- package/dist/assertions/expectAPIError.js +33 -0
- package/dist/assertions/strictResponseProperties.d.ts +14 -0
- package/dist/assertions/strictResponseProperties.js +37 -0
- package/dist/cache/mongoTestCache.js +2 -2
- package/dist/cli/collectFiles.d.ts +38 -0
- package/dist/cli/collectFiles.js +73 -0
- package/dist/cli/testHygiene.d.ts +134 -0
- package/dist/cli/testHygiene.js +357 -0
- package/dist/cli/testHygieneCli.d.ts +2 -0
- package/dist/cli/testHygieneCli.js +5 -0
- package/dist/cli/testHygieneRules.d.ts +58 -0
- package/dist/cli/testHygieneRules.js +517 -0
- package/dist/cli/testShard.d.ts +155 -0
- package/dist/cli/testShard.js +377 -0
- package/dist/cli/testShardCli.d.ts +2 -0
- package/dist/cli/testShardCli.js +5 -0
- package/dist/expo/authTokenStorage.d.ts +76 -0
- package/dist/expo/authTokenStorage.js +160 -0
- package/dist/expo/expoModuleMocks.d.ts +24 -0
- package/dist/expo/expoModuleMocks.js +456 -0
- package/dist/expo/libraryModuleMocks.d.ts +17 -0
- package/dist/expo/libraryModuleMocks.js +347 -0
- package/dist/expo/mockHelpers.d.ts +39 -0
- package/dist/expo/mockHelpers.js +45 -0
- package/dist/expo/mockModuleAliases.d.ts +50 -0
- package/dist/expo/mockModuleAliases.js +174 -0
- package/dist/expo/reactNativeMock.d.ts +39 -0
- package/dist/expo/reactNativeMock.js +421 -0
- package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
- package/dist/expo/registerExpoTestEnvironment.js +165 -0
- package/dist/expo/renderWithTerreno.d.ts +47 -0
- package/dist/expo/renderWithTerreno.js +47 -0
- package/dist/http/authWithToken.d.ts +20 -0
- package/dist/http/authWithToken.js +30 -0
- package/dist/index.d.ts +14 -1
- package/dist/index.js +33 -1
- package/dist/logging/silenceLogs.js +0 -2
- package/dist/mocks/aiSdk.d.ts +77 -0
- package/dist/mocks/aiSdk.js +102 -0
- package/dist/mocks/cloudTasks.d.ts +91 -0
- package/dist/mocks/cloudTasks.js +197 -0
- package/dist/mocks/expoPush.d.ts +53 -0
- package/dist/mocks/expoPush.js +57 -0
- package/dist/mocks/gcs.d.ts +101 -0
- package/dist/mocks/gcs.js +162 -0
- package/dist/mocks/googleAuth.d.ts +69 -0
- package/dist/mocks/googleAuth.js +55 -0
- package/dist/mocks/mockGroup.d.ts +11 -0
- package/dist/mocks/mockGroup.js +21 -0
- package/dist/mocks/notifiers.d.ts +21 -0
- package/dist/mocks/notifiers.js +26 -0
- package/dist/mocks/sendgrid.d.ts +22 -0
- package/dist/mocks/sendgrid.js +32 -0
- package/dist/mocks/twilio.d.ts +72 -0
- package/dist/mocks/twilio.js +64 -0
- package/dist/preload/registerBackendPreload.js +4 -1
- package/dist/time/freezeTime.d.ts +16 -0
- package/dist/time/freezeTime.js +49 -0
- package/dist/transaction/testTransaction.d.ts +43 -6
- package/dist/transaction/testTransaction.js +371 -92
- package/dist/utils/waitUntil.d.ts +22 -0
- package/dist/utils/waitUntil.js +34 -0
- package/package.json +53 -8
- package/src/assertions/expectAPIError.ts +51 -0
- package/src/assertions/strictResponseProperties.ts +42 -0
- package/src/cache/mongoTestCache.ts +2 -2
- package/src/cli/collectFiles.ts +115 -0
- package/src/cli/testHygiene.ts +539 -0
- package/src/cli/testHygieneCli.ts +4 -0
- package/src/cli/testHygieneRules.ts +719 -0
- package/src/cli/testShard.ts +532 -0
- package/src/cli/testShardCli.ts +4 -0
- package/src/expo/authTokenStorage.ts +198 -0
- package/src/expo/expoModuleMocks.ts +503 -0
- package/src/expo/libraryModuleMocks.ts +411 -0
- package/src/expo/mockHelpers.ts +73 -0
- package/src/expo/mockModuleAliases.ts +252 -0
- package/src/expo/reactNativeMock.ts +534 -0
- package/src/expo/registerExpoTestEnvironment.ts +262 -0
- package/src/expo/renderWithTerreno.ts +79 -0
- package/src/http/authWithToken.ts +38 -0
- package/src/index.ts +82 -1
- package/src/logging/silenceLogs.ts +0 -2
- package/src/mocks/aiSdk.ts +199 -0
- package/src/mocks/cloudTasks.ts +323 -0
- package/src/mocks/expoPush.ts +134 -0
- package/src/mocks/gcs.ts +305 -0
- package/src/mocks/googleAuth.ts +136 -0
- package/src/mocks/mockGroup.ts +32 -0
- package/src/mocks/notifiers.ts +36 -0
- package/src/mocks/sendgrid.ts +57 -0
- package/src/mocks/twilio.ts +143 -0
- package/src/preload/registerBackendPreload.ts +4 -1
- package/src/time/freezeTime.ts +61 -0
- package/src/transaction/testTransaction.ts +456 -124
- package/src/utils/waitUntil.ts +47 -0
- package/biome.jsonc +0 -20
- package/bunfig.toml +0 -16
- package/src/cache/mongoTestCache.test.ts +0 -103
- package/src/env/setTerrenoTestEnv.test.ts +0 -26
- package/src/http/authAsUser.test.ts +0 -40
- package/src/http/getBaseServer.test.ts +0 -45
- package/src/logging/setupEnvironment.test.ts +0 -24
- package/src/logging/silenceLogs.test.ts +0 -52
- package/src/logging/testLogger.test.ts +0 -58
- package/src/mocks/sentryBun.test.ts +0 -230
- package/src/mongo/connection.test.ts +0 -43
- package/src/mongo/mongoServer.test.ts +0 -99
- package/src/preload/registerBackendPreload.test.ts +0 -10
- package/src/transaction/testTransaction.test.ts +0 -64
- package/src/utils/helpers.test.ts +0 -46
- package/tsconfig.json +0 -18
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// noExplicitAny: Mongoose prototype patches require dynamic signatures
|
|
3
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: Mongoose prototype patches require dynamic signatures
|
|
4
2
|
/**
|
|
5
3
|
* Transaction-based test isolation for MongoDB.
|
|
6
4
|
*
|
|
@@ -29,9 +27,22 @@
|
|
|
29
27
|
* cause TransientTransactionError / NoSuchTransaction. We solve this with a
|
|
30
28
|
* reentrant async mutex:
|
|
31
29
|
* - Top-level operations (the ones fired by Promise.all) are serialized
|
|
32
|
-
* - Nested operations (e.g. pre-save hooks that do queries)
|
|
33
|
-
*
|
|
34
|
-
*
|
|
30
|
+
* - Nested operations (e.g. pre-save hooks that do queries) run without taking
|
|
31
|
+
* the mutex while the ancestor that owns it is still inside its critical
|
|
32
|
+
* section, preventing deadlocks
|
|
33
|
+
* - AsyncLocalStorage tracks which critical section owns the current async chain
|
|
34
|
+
*
|
|
35
|
+
* Teardown drain: every operation is counted while in flight, and teardown waits
|
|
36
|
+
* for that count to reach zero before aborting. Work a test leaves behind — a
|
|
37
|
+
* fire-and-forget `void AuditLog.create(...)` write, follow-up writes spawned by
|
|
38
|
+
* post-save hooks — would otherwise still be queued when the transaction is
|
|
39
|
+
* aborted, then run against the aborted transaction or, once the session is no
|
|
40
|
+
* longer transactional, commit for real.
|
|
41
|
+
*
|
|
42
|
+
* Test-boundary cancellation: operations still queued on the mutex when the
|
|
43
|
+
* session is discarded reject with {@link TestTransactionOperationCancelledError}
|
|
44
|
+
* instead of running. Use {@link isTestTransactionOperationCancelled} to
|
|
45
|
+
* recognize that error (including when wrapped through `cause`).
|
|
35
46
|
*
|
|
36
47
|
* Limitations:
|
|
37
48
|
* - App code that creates its own sessions (e.g. explicit transactions in
|
|
@@ -44,17 +55,55 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
44
55
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
45
56
|
};
|
|
46
57
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
47
|
-
exports.installTransactionPatches = exports.resetTestSessionAfterReconnect = exports.abortTestTransaction = exports.startTestTransaction = exports.getTestSession = void 0;
|
|
58
|
+
exports.installTransactionPatches = exports.resetTestSessionAfterReconnect = exports.abortTestTransaction = exports.startTestTransaction = exports.getTestSession = exports.isTestTransactionOperationCancelled = exports.TestTransactionOperationCancelledError = void 0;
|
|
48
59
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
49
60
|
const mongoose_1 = __importDefault(require("mongoose"));
|
|
50
61
|
let currentTestSession = null;
|
|
51
62
|
let patchesInstalled = false;
|
|
63
|
+
/** How deep {@link isTestTransactionOperationCancelled} follows `cause` chains. */
|
|
64
|
+
const MAX_CAUSE_DEPTH = 5;
|
|
65
|
+
/** Default budget for in-flight operations to settle before teardown gives up. */
|
|
66
|
+
// Below Bun's default 5s hook timeout, so a quarantine after a timed-out drain finishes
|
|
67
|
+
// inside the same afterEach instead of spilling into the next test.
|
|
68
|
+
const DEFAULT_DRAIN_TIMEOUT_MS = 3000;
|
|
69
|
+
// ============================================================================
|
|
70
|
+
// Cancellation Error
|
|
71
|
+
// ============================================================================
|
|
72
|
+
/**
|
|
73
|
+
* Thrown when a queued DB operation is discarded at a test boundary.
|
|
74
|
+
*
|
|
75
|
+
* Rejecting stops the operation's `await` chain so later writes cannot run
|
|
76
|
+
* after the test session is gone. `bun test` reports an unawaited rejection
|
|
77
|
+
* itself (it does not call `process.on("unhandledRejection")` listeners), so a
|
|
78
|
+
* fire-and-forget write that hits this error shows up as a test failure; await
|
|
79
|
+
* the write, or check `isTestTransactionOperationCancelled` where it is caught.
|
|
80
|
+
*/
|
|
81
|
+
class TestTransactionOperationCancelledError extends Error {
|
|
82
|
+
constructor() {
|
|
83
|
+
super("[testTransaction] Cancelled a queued operation at a test boundary");
|
|
84
|
+
this.name = "TestTransactionOperationCancelledError";
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
exports.TestTransactionOperationCancelledError = TestTransactionOperationCancelledError;
|
|
88
|
+
/** True when `error` is a test-boundary cancellation, including wrapped `cause` chains. */
|
|
89
|
+
const isTestTransactionOperationCancelled = (error) => {
|
|
90
|
+
let current = error;
|
|
91
|
+
for (let depth = 0; depth < MAX_CAUSE_DEPTH && current; depth++) {
|
|
92
|
+
if (current instanceof TestTransactionOperationCancelledError) {
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
current = current.cause;
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
};
|
|
99
|
+
exports.isTestTransactionOperationCancelled = isTestTransactionOperationCancelled;
|
|
52
100
|
// ============================================================================
|
|
53
101
|
// Reentrant Async Mutex
|
|
54
102
|
// ============================================================================
|
|
55
103
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
104
|
+
* Identifies the critical section that the current async context belongs to.
|
|
105
|
+
* A nested operation skips the mutex only while that section still holds it,
|
|
106
|
+
* which avoids deadlocks without letting detached work bypass serialization.
|
|
58
107
|
*/
|
|
59
108
|
const serializationContext = new node_async_hooks_1.AsyncLocalStorage();
|
|
60
109
|
/**
|
|
@@ -64,30 +113,125 @@ const serializationContext = new node_async_hooks_1.AsyncLocalStorage();
|
|
|
64
113
|
class AsyncMutex {
|
|
65
114
|
queue = [];
|
|
66
115
|
locked = false;
|
|
116
|
+
/**
|
|
117
|
+
* Bumped by {@link reset}. A holder releases with the generation it acquired
|
|
118
|
+
* in, so a holder stranded by a reset cannot unlock (or hand off) a mutex that
|
|
119
|
+
* a later test now owns.
|
|
120
|
+
*/
|
|
121
|
+
generation = 0;
|
|
122
|
+
/** Resolves with the generation the lock was granted in; pass it to {@link release}. */
|
|
67
123
|
async acquire() {
|
|
68
124
|
if (!this.locked) {
|
|
69
125
|
this.locked = true;
|
|
70
|
-
return;
|
|
126
|
+
return this.generation;
|
|
71
127
|
}
|
|
72
|
-
return new Promise((resolve) => {
|
|
73
|
-
this.queue.push(resolve);
|
|
128
|
+
return new Promise((resolve, reject) => {
|
|
129
|
+
this.queue.push({ reject, resolve });
|
|
74
130
|
});
|
|
75
131
|
}
|
|
76
|
-
release() {
|
|
132
|
+
release(generation) {
|
|
133
|
+
if (generation !== this.generation) {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
77
136
|
const next = this.queue.shift();
|
|
78
137
|
if (next) {
|
|
79
|
-
next();
|
|
138
|
+
next.resolve(this.generation);
|
|
80
139
|
}
|
|
81
140
|
else {
|
|
82
141
|
this.locked = false;
|
|
83
142
|
}
|
|
84
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Cancels queued work when the owning test session is discarded.
|
|
146
|
+
*
|
|
147
|
+
* Resolving every waiter as though it owned the lock would let them all
|
|
148
|
+
* proceed concurrently on the shared session. Rejecting with
|
|
149
|
+
* {@link TestTransactionOperationCancelledError} instead stops `await`
|
|
150
|
+
* chains so later writes cannot run after the session is reset.
|
|
151
|
+
*/
|
|
85
152
|
reset() {
|
|
86
|
-
|
|
153
|
+
const stranded = this.queue;
|
|
87
154
|
this.queue = [];
|
|
155
|
+
this.locked = false;
|
|
156
|
+
this.generation++;
|
|
157
|
+
for (const waiter of stranded) {
|
|
158
|
+
waiter.reject(new TestTransactionOperationCancelledError());
|
|
159
|
+
}
|
|
88
160
|
}
|
|
89
161
|
}
|
|
90
162
|
const sessionMutex = new AsyncMutex();
|
|
163
|
+
/**
|
|
164
|
+
* Identity of the critical section that currently holds {@link sessionMutex}.
|
|
165
|
+
* A nested operation may only skip the mutex while its own ancestor still holds
|
|
166
|
+
* it; see {@link serialized}.
|
|
167
|
+
*/
|
|
168
|
+
let currentMutexOwner = null;
|
|
169
|
+
/** Clears the mutex and its holder identity between tests. */
|
|
170
|
+
const resetSessionMutex = () => {
|
|
171
|
+
currentMutexOwner = null;
|
|
172
|
+
sessionMutex.reset();
|
|
173
|
+
};
|
|
174
|
+
// ============================================================================
|
|
175
|
+
// In-Flight Operation Tracking
|
|
176
|
+
// ============================================================================
|
|
177
|
+
/**
|
|
178
|
+
* DB operations issued through {@link serialized} that have not settled yet.
|
|
179
|
+
*
|
|
180
|
+
* This counts queued operations as well as running ones, because a test can
|
|
181
|
+
* leave work behind after its body returns — fire-and-forget writes, and
|
|
182
|
+
* follow-up writes spawned by post-save hooks. Teardown must wait for all of it.
|
|
183
|
+
*/
|
|
184
|
+
let pendingOperationCount = 0;
|
|
185
|
+
/**
|
|
186
|
+
* Incremented when tracking is abandoned so that late `finally` blocks from a
|
|
187
|
+
* previous epoch cannot drive {@link pendingOperationCount} negative.
|
|
188
|
+
*/
|
|
189
|
+
let operationEpoch = 0;
|
|
190
|
+
/** Resolvers waiting for {@link pendingOperationCount} to reach zero. */
|
|
191
|
+
let drainWaiters = [];
|
|
192
|
+
const notifyDrained = () => {
|
|
193
|
+
const waiters = drainWaiters;
|
|
194
|
+
drainWaiters = [];
|
|
195
|
+
for (const resolve of waiters) {
|
|
196
|
+
resolve();
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
/** Runs an operation while counting it as in-flight. */
|
|
200
|
+
const trackOperation = async (operation) => {
|
|
201
|
+
const epoch = operationEpoch;
|
|
202
|
+
pendingOperationCount++;
|
|
203
|
+
try {
|
|
204
|
+
return await operation();
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
if (epoch === operationEpoch) {
|
|
208
|
+
pendingOperationCount--;
|
|
209
|
+
if (pendingOperationCount === 0) {
|
|
210
|
+
notifyDrained();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
/** Resolves once no tracked operation is in flight. */
|
|
216
|
+
const whenNoOperationsInFlight = () => {
|
|
217
|
+
if (pendingOperationCount === 0) {
|
|
218
|
+
return Promise.resolve();
|
|
219
|
+
}
|
|
220
|
+
return new Promise((resolve) => {
|
|
221
|
+
drainWaiters.push(resolve);
|
|
222
|
+
});
|
|
223
|
+
};
|
|
224
|
+
/**
|
|
225
|
+
* Clears operation accounting after the session that owns it is quarantined.
|
|
226
|
+
*
|
|
227
|
+
* Late `finally` blocks from the discarded session belong to the previous
|
|
228
|
+
* epoch, so they cannot affect accounting for the next test.
|
|
229
|
+
*/
|
|
230
|
+
const abandonOperationTracking = () => {
|
|
231
|
+
operationEpoch++;
|
|
232
|
+
pendingOperationCount = 0;
|
|
233
|
+
notifyDrained();
|
|
234
|
+
};
|
|
91
235
|
/**
|
|
92
236
|
* Returns whether the active test transaction session can be attached to DB
|
|
93
237
|
* operations on the given Mongoose connection. The Node driver's
|
|
@@ -112,63 +256,146 @@ const shouldAttachTestSessionToConnection = (connection) => {
|
|
|
112
256
|
}
|
|
113
257
|
return sessionClient === connClient;
|
|
114
258
|
};
|
|
259
|
+
const drainTimeoutError = () => new Error(`[testTransaction] Timed out waiting for ${pendingOperationCount} serialized operation(s) to drain`);
|
|
115
260
|
/**
|
|
116
|
-
* Waits until
|
|
261
|
+
* Waits until every serialized DB operation has settled before test teardown.
|
|
117
262
|
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
263
|
+
* Taking one turn on the mutex is not enough: the mutex is FIFO, so a turn only
|
|
264
|
+
* proves that operations queued *before* teardown have finished. Work the test
|
|
265
|
+
* left behind — a fire-and-forget write, a follow-up write spawned by a
|
|
266
|
+
* post-save hook — queues after teardown and would still be pending. Those
|
|
267
|
+
* operations then execute against a transaction that has already been aborted,
|
|
268
|
+
* which surfaces as a NoSuchTransaction error, or worse, land after
|
|
269
|
+
* {@link serialized} has given up on the transaction and get committed for real.
|
|
270
|
+
*
|
|
271
|
+
* Waiting on the in-flight count instead covers both queued and running work,
|
|
272
|
+
* and re-checks after yielding because settling one operation can enqueue the
|
|
273
|
+
* next one in its chain. Uses the monotonic clock so `setSystemTime` in a test
|
|
274
|
+
* cannot stretch or shrink the budget.
|
|
121
275
|
*/
|
|
122
|
-
const waitForSerializedOperationsToDrain = async (timeoutMs
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
276
|
+
const waitForSerializedOperationsToDrain = async (timeoutMs) => {
|
|
277
|
+
const deadline = performance.now() + timeoutMs;
|
|
278
|
+
while (pendingOperationCount > 0) {
|
|
279
|
+
const remainingMs = deadline - performance.now();
|
|
280
|
+
if (remainingMs <= 0) {
|
|
281
|
+
throw drainTimeoutError();
|
|
282
|
+
}
|
|
283
|
+
let timeoutId;
|
|
284
|
+
try {
|
|
285
|
+
await Promise.race([
|
|
286
|
+
whenNoOperationsInFlight(),
|
|
287
|
+
new Promise((_, reject) => {
|
|
288
|
+
timeoutId = setTimeout(() => {
|
|
289
|
+
reject(drainTimeoutError());
|
|
290
|
+
}, remainingMs);
|
|
291
|
+
}),
|
|
292
|
+
]);
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
if (timeoutId) {
|
|
296
|
+
clearTimeout(timeoutId);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
// Yield a macrotask so any operation chained onto the ones that just settled
|
|
300
|
+
// is registered before we conclude the queue is empty.
|
|
301
|
+
await new Promise((resolve) => {
|
|
302
|
+
setTimeout(resolve, 0);
|
|
303
|
+
});
|
|
136
304
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
305
|
+
};
|
|
306
|
+
/**
|
|
307
|
+
* Guarantees the reused session has an open transaction before an operation runs.
|
|
308
|
+
*
|
|
309
|
+
* When the server aborts the transaction mid-test, the session stays usable but
|
|
310
|
+
* is no longer transactional. Every subsequent write would then execute as an
|
|
311
|
+
* ordinary write and be committed, permanently leaking the test's fixtures into
|
|
312
|
+
* the shared database and corrupting every test file that runs after it.
|
|
313
|
+
* Reopening a transaction keeps those writes rollback-able.
|
|
314
|
+
*/
|
|
315
|
+
const ensureTransactionOpen = () => {
|
|
316
|
+
if (currentTestSession && !currentTestSession.inTransaction()) {
|
|
317
|
+
currentTestSession.startTransaction();
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* Discards a session whose operations did not settle before teardown.
|
|
322
|
+
*
|
|
323
|
+
* A drain timeout means the session can no longer safely isolate the following
|
|
324
|
+
* test. Aborting and ending it makes the old operations fail instead of letting
|
|
325
|
+
* them attach to a new transaction; clearing the global lets the next test
|
|
326
|
+
* obtain a fresh session.
|
|
327
|
+
*/
|
|
328
|
+
const quarantineTestSession = async () => {
|
|
329
|
+
const session = currentTestSession;
|
|
330
|
+
if (!session) {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
currentTestSession = null;
|
|
334
|
+
try {
|
|
335
|
+
if (session.inTransaction()) {
|
|
336
|
+
await session.abortTransaction();
|
|
140
337
|
}
|
|
141
338
|
}
|
|
339
|
+
catch {
|
|
340
|
+
// The session is being discarded after a teardown failure.
|
|
341
|
+
}
|
|
342
|
+
try {
|
|
343
|
+
await session.endSession();
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
// The session is being discarded after a teardown failure.
|
|
347
|
+
}
|
|
142
348
|
};
|
|
143
349
|
/**
|
|
144
|
-
* Wraps an async DB operation with the session mutex. Reentrant:
|
|
145
|
-
*
|
|
146
|
-
* without acquiring the mutex
|
|
147
|
-
*
|
|
350
|
+
* Wraps an async DB operation with the session mutex. Reentrant: while the
|
|
351
|
+
* critical section that owns the mutex is still running, operations it spawns
|
|
352
|
+
* run directly without acquiring the mutex, so nested work like a pre-save hook
|
|
353
|
+
* issuing its own query cannot deadlock against its caller.
|
|
354
|
+
*
|
|
355
|
+
* Restart caveat: when a `TransientTransactionError` is hit mid-test, this
|
|
356
|
+
* function restarts the transaction and retries only the *failing* operation.
|
|
357
|
+
* The restart discards the transaction's snapshot, so writes the test made
|
|
358
|
+
* earlier are silently rolled back and a later assertion can fail against a DB
|
|
359
|
+
* state the test doesn't expect. The restart path is a last resort — the drain
|
|
360
|
+
* and reentrancy rules above exist to keep operations from arriving on an
|
|
361
|
+
* already-aborted transaction in the first place.
|
|
148
362
|
*/
|
|
149
363
|
const serialized = (fn) => {
|
|
150
364
|
// If no test session is active, skip serialization entirely
|
|
151
365
|
if (!currentTestSession) {
|
|
152
366
|
return fn();
|
|
153
367
|
}
|
|
154
|
-
//
|
|
368
|
+
// Nested call whose ancestor still holds the mutex: acquiring it again would
|
|
369
|
+
// deadlock, so run directly. The ancestor check is deliberately by identity
|
|
370
|
+
// rather than a plain "am I inside a serialized block" flag — the async
|
|
371
|
+
// context is inherited by fire-and-forget work too, and such an operation can
|
|
372
|
+
// resume long after its ancestor released the mutex. Treating that as nested
|
|
373
|
+
// would let it run concurrently with another operation on the same session,
|
|
374
|
+
// which MongoDB rejects.
|
|
155
375
|
const store = serializationContext.getStore();
|
|
156
|
-
if (store
|
|
157
|
-
return fn
|
|
376
|
+
if (store && store.owner === currentMutexOwner) {
|
|
377
|
+
return trackOperation(fn);
|
|
158
378
|
}
|
|
159
379
|
// Top-level call: acquire mutex, then run inside the serialization context
|
|
160
380
|
const run = async () => {
|
|
161
381
|
let hasRetried = false;
|
|
162
382
|
while (true) {
|
|
163
|
-
await sessionMutex.acquire();
|
|
383
|
+
const generation = await sessionMutex.acquire();
|
|
384
|
+
const owner = {};
|
|
385
|
+
currentMutexOwner = owner;
|
|
164
386
|
try {
|
|
165
|
-
|
|
387
|
+
ensureTransactionOpen();
|
|
388
|
+
return await serializationContext.run({ owner }, fn);
|
|
166
389
|
}
|
|
167
390
|
catch (error) {
|
|
391
|
+
if ((0, exports.isTestTransactionOperationCancelled)(error)) {
|
|
392
|
+
throw error;
|
|
393
|
+
}
|
|
168
394
|
// If this error aborted the transaction (e.g. E11000 duplicate key),
|
|
169
395
|
// restart it and retry once so transient transaction-number mismatches
|
|
170
396
|
// don't fail the test immediately.
|
|
171
|
-
const
|
|
397
|
+
const transactionError = error;
|
|
398
|
+
const isTransactionAborted = transactionError?.errorLabels?.includes?.("TransientTransactionError") ||
|
|
172
399
|
(currentTestSession && !currentTestSession.inTransaction());
|
|
173
400
|
if (!hasRetried && isTransactionAborted && currentTestSession) {
|
|
174
401
|
hasRetried = true;
|
|
@@ -187,11 +414,14 @@ const serialized = (fn) => {
|
|
|
187
414
|
throw error;
|
|
188
415
|
}
|
|
189
416
|
finally {
|
|
190
|
-
|
|
417
|
+
if (currentMutexOwner === owner) {
|
|
418
|
+
currentMutexOwner = null;
|
|
419
|
+
}
|
|
420
|
+
sessionMutex.release(generation);
|
|
191
421
|
}
|
|
192
422
|
}
|
|
193
423
|
};
|
|
194
|
-
return run
|
|
424
|
+
return trackOperation(run);
|
|
195
425
|
};
|
|
196
426
|
// ============================================================================
|
|
197
427
|
// Public API
|
|
@@ -228,32 +458,44 @@ const startTestTransaction = async () => {
|
|
|
228
458
|
if (!currentTestSession) {
|
|
229
459
|
currentTestSession = await mongoose_1.default.startSession();
|
|
230
460
|
}
|
|
231
|
-
|
|
461
|
+
resetSessionMutex();
|
|
232
462
|
currentTestSession.startTransaction();
|
|
233
463
|
};
|
|
234
464
|
exports.startTestTransaction = startTestTransaction;
|
|
235
465
|
/**
|
|
236
466
|
* Aborts the current test transaction. Call in afterEach.
|
|
237
467
|
*
|
|
238
|
-
*
|
|
468
|
+
* Waits for in-flight and queued operations to settle first. If they do not
|
|
469
|
+
* settle within the drain budget, the session is quarantined (aborted and
|
|
470
|
+
* ended), queued operations reject with {@link TestTransactionOperationCancelledError},
|
|
471
|
+
* and the drain timeout error is rethrown so the offending test fails.
|
|
472
|
+
*
|
|
473
|
+
* The session is otherwise kept alive (not ended) so it can be reused by
|
|
239
474
|
* the next test. This avoids returning the session to the driver's server
|
|
240
475
|
* session pool, which prevents transaction number mismatches when in-flight
|
|
241
476
|
* operations from a previous test complete after the session has been recycled.
|
|
242
477
|
*/
|
|
243
|
-
const abortTestTransaction = async () => {
|
|
478
|
+
const abortTestTransaction = async ({ drainTimeoutMs = DEFAULT_DRAIN_TIMEOUT_MS, } = {}) => {
|
|
244
479
|
if (!currentTestSession) {
|
|
245
480
|
return;
|
|
246
481
|
}
|
|
482
|
+
// Ensure any in-flight/queued DB work from the current test has settled
|
|
483
|
+
// before aborting, so it cannot land on the next test's transaction.
|
|
484
|
+
try {
|
|
485
|
+
await waitForSerializedOperationsToDrain(drainTimeoutMs);
|
|
486
|
+
}
|
|
487
|
+
catch (error) {
|
|
488
|
+
await quarantineTestSession();
|
|
489
|
+
abandonOperationTracking();
|
|
490
|
+
resetSessionMutex();
|
|
491
|
+
throw error;
|
|
492
|
+
}
|
|
247
493
|
try {
|
|
248
|
-
// Ensure any in-flight/queued DB work from the current test has settled
|
|
249
|
-
// before aborting and starting the next transaction.
|
|
250
|
-
await waitForSerializedOperationsToDrain();
|
|
251
494
|
if (currentTestSession.inTransaction()) {
|
|
252
495
|
await currentTestSession.abortTransaction();
|
|
253
496
|
}
|
|
254
497
|
}
|
|
255
498
|
catch (error) {
|
|
256
|
-
// biome-ignore lint/suspicious/noConsole: test harness diagnostic when abort fails
|
|
257
499
|
console.warn("[testTransaction] Error aborting transaction:", error);
|
|
258
500
|
// If the abort failed, the session may be in a bad state. End it so
|
|
259
501
|
// startTestTransaction creates a fresh one.
|
|
@@ -267,7 +509,7 @@ const abortTestTransaction = async () => {
|
|
|
267
509
|
}
|
|
268
510
|
finally {
|
|
269
511
|
// Clean slate for the next test transaction.
|
|
270
|
-
|
|
512
|
+
resetSessionMutex();
|
|
271
513
|
}
|
|
272
514
|
};
|
|
273
515
|
exports.abortTestTransaction = abortTestTransaction;
|
|
@@ -280,7 +522,7 @@ exports.abortTestTransaction = abortTestTransaction;
|
|
|
280
522
|
*/
|
|
281
523
|
const resetTestSessionAfterReconnect = async () => {
|
|
282
524
|
if (!currentTestSession) {
|
|
283
|
-
|
|
525
|
+
resetSessionMutex();
|
|
284
526
|
return;
|
|
285
527
|
}
|
|
286
528
|
try {
|
|
@@ -294,7 +536,7 @@ const resetTestSessionAfterReconnect = async () => {
|
|
|
294
536
|
}
|
|
295
537
|
finally {
|
|
296
538
|
currentTestSession = null;
|
|
297
|
-
|
|
539
|
+
resetSessionMutex();
|
|
298
540
|
}
|
|
299
541
|
};
|
|
300
542
|
exports.resetTestSessionAfterReconnect = resetTestSessionAfterReconnect;
|
|
@@ -315,7 +557,8 @@ exports.resetTestSessionAfterReconnect = resetTestSessionAfterReconnect;
|
|
|
315
557
|
* - Aggregate.prototype.exec — covers aggregation pipelines
|
|
316
558
|
* - Model.bulkWrite — covers bulk write operations
|
|
317
559
|
* - Model.insertMany — covers bulk inserts (uses native driver, not save)
|
|
318
|
-
* - Model.
|
|
560
|
+
* - Model.create — serializes multi-document creates (forces `ordered: true`) so
|
|
561
|
+
* their saves cannot race each other on the shared session
|
|
319
562
|
* - Model.startSession — returns a no-op wrapper so app-level transactions don't conflict
|
|
320
563
|
* - Collection.prototype (insertOne, updateOne, deleteOne, etc.) — covers native driver
|
|
321
564
|
* operations used by tests that call Model.collection.insertOne() directly
|
|
@@ -335,18 +578,27 @@ const installTransactionPatches = () => {
|
|
|
335
578
|
if (!shouldAttachTestSessionToConnection(this.model?.db)) {
|
|
336
579
|
return originalQueryExec.apply(this);
|
|
337
580
|
}
|
|
338
|
-
|
|
339
|
-
return serialized(() =>
|
|
581
|
+
let attempt = 0;
|
|
582
|
+
return serialized(() => {
|
|
583
|
+
// Query instances are single-use in Mongoose, so when serialized() retries
|
|
584
|
+
// after restarting a transaction it must execute a fresh clone. The first
|
|
585
|
+
// attempt runs the original: `clone()` drops per-instance hooks such as the
|
|
586
|
+
// ones `doc.deleteOne()` registers to run document middleware.
|
|
587
|
+
const queryForExecution = attempt === 0 ? this : this.clone();
|
|
588
|
+
attempt++;
|
|
589
|
+
queryForExecution.session(currentTestSession);
|
|
590
|
+
return originalQueryExec.apply(queryForExecution);
|
|
591
|
+
});
|
|
340
592
|
}
|
|
341
593
|
return originalQueryExec.apply(this);
|
|
342
594
|
};
|
|
343
595
|
// --- Model.prototype.save and $save ---
|
|
344
|
-
//
|
|
345
|
-
//
|
|
346
|
-
//
|
|
596
|
+
// Model.create() calls $save (not save). $save is assigned from save at module
|
|
597
|
+
// load time (Model.prototype.$save = Model.prototype.save), so we must patch
|
|
598
|
+
// both to ensure Model.create() goes through our session injection.
|
|
347
599
|
const patchSave = (original) => function (options) {
|
|
348
600
|
if (currentTestSession) {
|
|
349
|
-
const connection = this.constructor
|
|
601
|
+
const connection = this.constructor.db;
|
|
350
602
|
if (!shouldAttachTestSessionToConnection(connection)) {
|
|
351
603
|
return original.call(this, options);
|
|
352
604
|
}
|
|
@@ -354,8 +606,8 @@ const installTransactionPatches = () => {
|
|
|
354
606
|
this.$session(currentTestSession);
|
|
355
607
|
return serialized(() => original.call(this, options));
|
|
356
608
|
}
|
|
357
|
-
|
|
358
|
-
return serialized(() => original.call(this,
|
|
609
|
+
const optionsWithSession = { ...(options ?? {}), session: currentTestSession };
|
|
610
|
+
return serialized(() => original.call(this, optionsWithSession));
|
|
359
611
|
}
|
|
360
612
|
return original.call(this, options);
|
|
361
613
|
};
|
|
@@ -368,7 +620,8 @@ const installTransactionPatches = () => {
|
|
|
368
620
|
const originalAggExec = mongoose_1.default.Aggregate.prototype.exec;
|
|
369
621
|
mongoose_1.default.Aggregate.prototype.exec = function () {
|
|
370
622
|
if (currentTestSession) {
|
|
371
|
-
const
|
|
623
|
+
const aggregateInternals = this;
|
|
624
|
+
const connection = aggregateInternals._model?.db ?? aggregateInternals._connection;
|
|
372
625
|
if (!shouldAttachTestSessionToConnection(connection)) {
|
|
373
626
|
return originalAggExec.apply(this);
|
|
374
627
|
}
|
|
@@ -379,27 +632,29 @@ const installTransactionPatches = () => {
|
|
|
379
632
|
};
|
|
380
633
|
// --- Model.bulkWrite (static) ---
|
|
381
634
|
const originalBulkWrite = mongoose_1.default.Model.bulkWrite;
|
|
382
|
-
mongoose_1.default.Model.bulkWrite = function (
|
|
635
|
+
mongoose_1.default.Model.bulkWrite = function (...args) {
|
|
383
636
|
if (currentTestSession) {
|
|
384
637
|
if (!shouldAttachTestSessionToConnection(this.db)) {
|
|
385
|
-
return originalBulkWrite.
|
|
638
|
+
return originalBulkWrite.apply(this, args);
|
|
386
639
|
}
|
|
387
|
-
|
|
388
|
-
|
|
640
|
+
const [ops, options] = args;
|
|
641
|
+
const optionsWithSession = { ...(options ?? {}), session: currentTestSession };
|
|
642
|
+
return serialized(() => originalBulkWrite.apply(this, [ops, optionsWithSession]));
|
|
389
643
|
}
|
|
390
|
-
return originalBulkWrite.
|
|
644
|
+
return originalBulkWrite.apply(this, args);
|
|
391
645
|
};
|
|
392
646
|
// --- Model.insertMany (static) ---
|
|
393
647
|
const originalInsertMany = mongoose_1.default.Model.insertMany;
|
|
394
|
-
mongoose_1.default.Model.insertMany = function (
|
|
648
|
+
mongoose_1.default.Model.insertMany = function (...args) {
|
|
395
649
|
if (currentTestSession) {
|
|
396
650
|
if (!shouldAttachTestSessionToConnection(this.db)) {
|
|
397
|
-
return originalInsertMany.
|
|
651
|
+
return originalInsertMany.apply(this, args);
|
|
398
652
|
}
|
|
399
|
-
|
|
400
|
-
|
|
653
|
+
const [docs, options] = args;
|
|
654
|
+
const optionsWithSession = { ...(options ?? {}), session: currentTestSession };
|
|
655
|
+
return serialized(() => originalInsertMany.apply(this, [docs, optionsWithSession]));
|
|
401
656
|
}
|
|
402
|
-
return originalInsertMany.
|
|
657
|
+
return originalInsertMany.apply(this, args);
|
|
403
658
|
};
|
|
404
659
|
// --- Model.create (static) ---
|
|
405
660
|
// Some code paths call Model.create() directly (including through
|
|
@@ -407,35 +662,57 @@ const installTransactionPatches = () => {
|
|
|
407
662
|
// serialization guard and race with other operations on the shared test
|
|
408
663
|
// session. Wrapping create ensures transient transaction aborts trigger the
|
|
409
664
|
// same auto-restart logic in serialized().
|
|
665
|
+
//
|
|
666
|
+
// Multi-document creates are additionally forced to `ordered: true`. Mongoose
|
|
667
|
+
// saves an array of documents with `Promise.all` unless ordered, and those
|
|
668
|
+
// nested saves are reentrant children of this critical section, so they skip
|
|
669
|
+
// the mutex and hit the shared session concurrently. When such a create is the
|
|
670
|
+
// first operation of a transaction, only one of the racing inserts carries
|
|
671
|
+
// `startTransaction: true`; if a sibling reaches the server first, the server
|
|
672
|
+
// rejects it with NoSuchTransaction ("Given transaction number N ... does not
|
|
673
|
+
// match any in-progress transactions"). Mongoose enforces the same constraint
|
|
674
|
+
// itself for explicitly-passed sessions — our session is injected lower down,
|
|
675
|
+
// at `$save`, so that guard never sees it.
|
|
676
|
+
// Varargs (`create(doc1, doc2)`) cannot carry options, so multi-document
|
|
677
|
+
// calls are rewritten to the equivalent array form, which also returns an array.
|
|
678
|
+
const toOrderedCreateArgs = (args) => {
|
|
679
|
+
if (Array.isArray(args[0])) {
|
|
680
|
+
return [args[0], { ...(args[1] ?? {}), ordered: true }, ...args.slice(2)];
|
|
681
|
+
}
|
|
682
|
+
// Mongoose drops a trailing falsy argument from varargs creates.
|
|
683
|
+
const docs = args.length > 1 && !args[args.length - 1] ? args.slice(0, -1) : args;
|
|
684
|
+
return docs.length > 1 ? [docs, { ordered: true }] : args;
|
|
685
|
+
};
|
|
410
686
|
const originalCreate = mongoose_1.default.Model.create;
|
|
411
687
|
mongoose_1.default.Model.create = function (...args) {
|
|
412
688
|
if (currentTestSession) {
|
|
413
689
|
if (!shouldAttachTestSessionToConnection(this.db)) {
|
|
414
690
|
return originalCreate.apply(this, args);
|
|
415
691
|
}
|
|
416
|
-
return serialized(() => originalCreate.apply(this, args));
|
|
692
|
+
return serialized(() => originalCreate.apply(this, toOrderedCreateArgs(args)));
|
|
417
693
|
}
|
|
418
694
|
return originalCreate.apply(this, args);
|
|
419
695
|
};
|
|
420
696
|
// --- Model.startSession (static) ---
|
|
421
697
|
// When test session is active, return a wrapper that redirects operations
|
|
422
698
|
// through the test session. This ensures app code that creates its own
|
|
423
|
-
// transactions
|
|
424
|
-
// test isolation.
|
|
699
|
+
// transactions doesn't bypass test isolation.
|
|
425
700
|
const originalStartSession = mongoose_1.default.Model.startSession;
|
|
426
|
-
mongoose_1.default.Model.startSession = async function (
|
|
701
|
+
mongoose_1.default.Model.startSession = async function (...args) {
|
|
427
702
|
if (currentTestSession) {
|
|
703
|
+
const testSession = currentTestSession;
|
|
428
704
|
return {
|
|
429
|
-
...
|
|
705
|
+
...testSession,
|
|
430
706
|
abortTransaction: async () => { },
|
|
431
707
|
commitTransaction: async () => { },
|
|
432
708
|
endSession: async () => { },
|
|
433
|
-
id:
|
|
709
|
+
id: testSession.id,
|
|
434
710
|
inTransaction: () => currentTestSession?.inTransaction() ?? false,
|
|
435
711
|
startTransaction: () => { },
|
|
712
|
+
withTransaction: async (callback) => callback(testSession),
|
|
436
713
|
};
|
|
437
714
|
}
|
|
438
|
-
return originalStartSession.
|
|
715
|
+
return originalStartSession.apply(this, args);
|
|
439
716
|
};
|
|
440
717
|
// --- Collection.prototype (native driver operations) ---
|
|
441
718
|
// Some test files call Model.collection.insertOne() etc. directly, bypassing
|
|
@@ -446,26 +723,29 @@ const installTransactionPatches = () => {
|
|
|
446
723
|
// - optionsAt1: (docOrFilter, options?) — insertOne, deleteOne, deleteMany, findOne, etc.
|
|
447
724
|
// - optionsAt2: (filter, update, options?) — updateOne, updateMany, findOneAndUpdate, etc.
|
|
448
725
|
const patchCollectionMethod = (method, optionsIndex) => {
|
|
449
|
-
const
|
|
726
|
+
const collectionPrototype = mongoose_1.default.Collection.prototype;
|
|
727
|
+
const original = collectionPrototype[method];
|
|
450
728
|
if (typeof original !== "function") {
|
|
451
729
|
return;
|
|
452
730
|
}
|
|
453
|
-
|
|
731
|
+
const originalMethod = original;
|
|
732
|
+
collectionPrototype[method] = function (...args) {
|
|
454
733
|
if (!currentTestSession) {
|
|
455
|
-
return
|
|
734
|
+
return originalMethod.apply(this, args);
|
|
456
735
|
}
|
|
457
736
|
if (!shouldAttachTestSessionToConnection(this.conn)) {
|
|
458
|
-
return
|
|
737
|
+
return originalMethod.apply(this, args);
|
|
459
738
|
}
|
|
460
739
|
return serialized(() => {
|
|
461
740
|
// Inject session into the options argument at the correct position
|
|
462
|
-
|
|
463
|
-
|
|
741
|
+
const existingOptions = args[optionsIndex];
|
|
742
|
+
if (existingOptions && typeof existingOptions === "object") {
|
|
743
|
+
args[optionsIndex] = { ...existingOptions, session: currentTestSession };
|
|
464
744
|
}
|
|
465
745
|
else {
|
|
466
746
|
args[optionsIndex] = { session: currentTestSession };
|
|
467
747
|
}
|
|
468
|
-
return
|
|
748
|
+
return originalMethod.apply(this, args);
|
|
469
749
|
});
|
|
470
750
|
};
|
|
471
751
|
};
|
|
@@ -494,7 +774,6 @@ const installTransactionPatches = () => {
|
|
|
494
774
|
}
|
|
495
775
|
patchesInstalled = true;
|
|
496
776
|
if (process.env.DEBUG_TEST_TRANSACTION === "true") {
|
|
497
|
-
// biome-ignore lint/suspicious/noConsole: optional debug for patch installation
|
|
498
777
|
console.debug("[testTransaction] Mongoose patches installed");
|
|
499
778
|
}
|
|
500
779
|
};
|