@terreno/test 57.18.0 → 57.19.2

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