@terreno/test 0.22.1

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 (69) hide show
  1. package/bunfig.toml +3 -0
  2. package/dist/cache/mongoTestCache.d.ts +16 -0
  3. package/dist/cache/mongoTestCache.js +541 -0
  4. package/dist/env/setTerrenoTestEnv.d.ts +13 -0
  5. package/dist/env/setTerrenoTestEnv.js +89 -0
  6. package/dist/http/authAsUser.d.ts +17 -0
  7. package/dist/http/authAsUser.js +165 -0
  8. package/dist/http/authAsUser.test.d.ts +1 -0
  9. package/dist/http/authAsUser.test.js +93 -0
  10. package/dist/http/getBaseServer.d.ts +9 -0
  11. package/dist/http/getBaseServer.js +33 -0
  12. package/dist/http/getBaseServer.test.d.ts +1 -0
  13. package/dist/http/getBaseServer.test.js +76 -0
  14. package/dist/index.d.ts +14 -0
  15. package/dist/index.js +46 -0
  16. package/dist/logging/setupEnvironment.d.ts +2 -0
  17. package/dist/logging/setupEnvironment.js +19 -0
  18. package/dist/logging/silenceLogs.d.ts +20 -0
  19. package/dist/logging/silenceLogs.js +168 -0
  20. package/dist/logging/testLogger.d.ts +7 -0
  21. package/dist/logging/testLogger.js +22 -0
  22. package/dist/mocks/sentryBun.d.ts +2 -0
  23. package/dist/mocks/sentryBun.js +136 -0
  24. package/dist/mongo/connection.d.ts +16 -0
  25. package/dist/mongo/connection.js +134 -0
  26. package/dist/mongo/connection.test.d.ts +1 -0
  27. package/dist/mongo/connection.test.js +28 -0
  28. package/dist/mongo/ensureMongoBinary.d.ts +6 -0
  29. package/dist/mongo/ensureMongoBinary.js +104 -0
  30. package/dist/mongo/mongoServer.d.ts +26 -0
  31. package/dist/mongo/mongoServer.js +424 -0
  32. package/dist/preload/defaultBackendPreload.d.ts +1 -0
  33. package/dist/preload/defaultBackendPreload.js +8 -0
  34. package/dist/preload/memoryMongo.d.ts +0 -0
  35. package/dist/preload/memoryMongo.js +2 -0
  36. package/dist/preload/registerBackendPreload.d.ts +33 -0
  37. package/dist/preload/registerBackendPreload.js +302 -0
  38. package/dist/transaction/testTransaction.d.ts +91 -0
  39. package/dist/transaction/testTransaction.js +719 -0
  40. package/dist/utils/ensureAllIndexes.d.ts +2 -0
  41. package/dist/utils/ensureAllIndexes.js +84 -0
  42. package/dist/utils/timeout.d.ts +1 -0
  43. package/dist/utils/timeout.js +45 -0
  44. package/dist/utils/waitForDocuments.d.ts +13 -0
  45. package/dist/utils/waitForDocuments.js +127 -0
  46. package/package.json +65 -0
  47. package/src/cache/mongoTestCache.ts +311 -0
  48. package/src/env/setTerrenoTestEnv.ts +50 -0
  49. package/src/http/authAsUser.test.ts +40 -0
  50. package/src/http/authAsUser.ts +59 -0
  51. package/src/http/getBaseServer.test.ts +30 -0
  52. package/src/http/getBaseServer.ts +34 -0
  53. package/src/index.ts +53 -0
  54. package/src/logging/setupEnvironment.ts +15 -0
  55. package/src/logging/silenceLogs.ts +134 -0
  56. package/src/logging/testLogger.ts +19 -0
  57. package/src/mocks/sentryBun.ts +140 -0
  58. package/src/mongo/connection.test.ts +30 -0
  59. package/src/mongo/connection.ts +65 -0
  60. package/src/mongo/ensureMongoBinary.ts +25 -0
  61. package/src/mongo/mongoServer.ts +214 -0
  62. package/src/preload/defaultBackendPreload.ts +7 -0
  63. package/src/preload/memoryMongo.ts +1 -0
  64. package/src/preload/registerBackendPreload.ts +174 -0
  65. package/src/transaction/testTransaction.ts +524 -0
  66. package/src/utils/ensureAllIndexes.ts +11 -0
  67. package/src/utils/timeout.ts +3 -0
  68. package/src/utils/waitForDocuments.ts +50 -0
  69. package/tsconfig.json +31 -0
@@ -0,0 +1,719 @@
1
+ "use strict";
2
+ /**
3
+ * Transaction-based test isolation for MongoDB.
4
+ *
5
+ * Instead of clearing and reloading all collections before every test,
6
+ * this module wraps each test in a MongoDB transaction that is aborted
7
+ * after the test completes. This rolls back all changes made during the
8
+ * test, leaving the database in its original state for the next test.
9
+ *
10
+ * How it works:
11
+ * 1. Mongoose operations (Query.exec, Model.save, Aggregate.exec, etc.)
12
+ * are monkey-patched to inject the current test session when active.
13
+ * 2. Before each test, a session is started and a transaction is begun.
14
+ * 3. After each test, the transaction is aborted and the session is ended.
15
+ * 4. All DB operations during the test see the pre-test snapshot and any
16
+ * writes made within the transaction, but nothing is persisted.
17
+ *
18
+ * Session reuse: a single MongoDB session is reused across all tests within
19
+ * a worker to avoid transaction number mismatches caused by the MongoDB driver's
20
+ * server session pool. When sessions are ended and reacquired from the pool,
21
+ * in-flight operations from a previous test can arrive with a stale transaction
22
+ * number, causing NoSuchTransaction errors. Reusing one session avoids this.
23
+ *
24
+ * Operation serialization: MongoDB does not support concurrent operations on
25
+ * the same session within a transaction. When app code uses Promise.all() to
26
+ * run DB operations in parallel, concurrent operations on the same session
27
+ * cause TransientTransactionError / NoSuchTransaction. We solve this with a
28
+ * reentrant async mutex:
29
+ * - Top-level operations (the ones fired by Promise.all) are serialized
30
+ * - Nested operations (e.g. pre-save hooks that do queries) detect they're
31
+ * already inside a serialized block and skip the mutex, preventing deadlocks
32
+ * - AsyncLocalStorage tracks the serialization context across the async chain
33
+ *
34
+ * Limitations:
35
+ * - App code that creates its own sessions (e.g. explicit transactions in
36
+ * route handlers) will have those sessions' operations redirected through
37
+ * the test session. The app's own commit/abort calls become no-ops.
38
+ * - Native driver operations (mongoose.connection.db.collection(...)) are
39
+ * NOT patched. Only Mongoose-level operations are covered.
40
+ */
41
+ var __assign = (this && this.__assign) || function () {
42
+ __assign = Object.assign || function(t) {
43
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
44
+ s = arguments[i];
45
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
46
+ t[p] = s[p];
47
+ }
48
+ return t;
49
+ };
50
+ return __assign.apply(this, arguments);
51
+ };
52
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
53
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
54
+ return new (P || (P = Promise))(function (resolve, reject) {
55
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
56
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
57
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
58
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
59
+ });
60
+ };
61
+ var __generator = (this && this.__generator) || function (thisArg, body) {
62
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
63
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
64
+ function verb(n) { return function (v) { return step([n, v]); }; }
65
+ function step(op) {
66
+ if (f) throw new TypeError("Generator is already executing.");
67
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
68
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
69
+ if (y = 0, t) op = [op[0] & 2, t.value];
70
+ switch (op[0]) {
71
+ case 0: case 1: t = op; break;
72
+ case 4: _.label++; return { value: op[1], done: false };
73
+ case 5: _.label++; y = op[1]; op = [0]; continue;
74
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
75
+ default:
76
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
77
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
78
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
79
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
80
+ if (t[2]) _.ops.pop();
81
+ _.trys.pop(); continue;
82
+ }
83
+ op = body.call(thisArg, _);
84
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
85
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
86
+ }
87
+ };
88
+ var __read = (this && this.__read) || function (o, n) {
89
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
90
+ if (!m) return o;
91
+ var i = m.call(o), r, ar = [], e;
92
+ try {
93
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
94
+ }
95
+ catch (error) { e = { error: error }; }
96
+ finally {
97
+ try {
98
+ if (r && !r.done && (m = i["return"])) m.call(i);
99
+ }
100
+ finally { if (e) throw e.error; }
101
+ }
102
+ return ar;
103
+ };
104
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
105
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
106
+ if (ar || !(i in from)) {
107
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
108
+ ar[i] = from[i];
109
+ }
110
+ }
111
+ return to.concat(ar || Array.prototype.slice.call(from));
112
+ };
113
+ var __values = (this && this.__values) || function(o) {
114
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
115
+ if (m) return m.call(o);
116
+ if (o && typeof o.length === "number") return {
117
+ next: function () {
118
+ if (o && i >= o.length) o = void 0;
119
+ return { value: o && o[i++], done: !o };
120
+ }
121
+ };
122
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
123
+ };
124
+ var __importDefault = (this && this.__importDefault) || function (mod) {
125
+ return (mod && mod.__esModule) ? mod : { "default": mod };
126
+ };
127
+ Object.defineProperty(exports, "__esModule", { value: true });
128
+ exports.installTransactionPatches = exports.resetTestSessionAfterReconnect = exports.abortTestTransaction = exports.startTestTransaction = exports.getTestSession = void 0;
129
+ var async_hooks_1 = require("async_hooks");
130
+ var mongoose_1 = __importDefault(require("mongoose"));
131
+ var currentTestSession = null;
132
+ var patchesInstalled = false;
133
+ // ============================================================================
134
+ // Reentrant Async Mutex
135
+ // ============================================================================
136
+ /**
137
+ * Tracks whether the current async context is already inside a serialized
138
+ * DB operation. When true, nested operations skip the mutex to avoid deadlocks.
139
+ */
140
+ var serializationContext = new async_hooks_1.AsyncLocalStorage();
141
+ /**
142
+ * Async mutex that serializes access to the MongoDB session.
143
+ * Only one DB operation can be in-flight at a time when a test session is active.
144
+ */
145
+ var AsyncMutex = /** @class */ (function () {
146
+ function AsyncMutex() {
147
+ this.queue = [];
148
+ this.locked = false;
149
+ }
150
+ AsyncMutex.prototype.acquire = function () {
151
+ return __awaiter(this, void 0, void 0, function () {
152
+ var _this = this;
153
+ return __generator(this, function (_a) {
154
+ if (!this.locked) {
155
+ this.locked = true;
156
+ return [2 /*return*/];
157
+ }
158
+ return [2 /*return*/, new Promise(function (resolve) {
159
+ _this.queue.push(resolve);
160
+ })];
161
+ });
162
+ });
163
+ };
164
+ AsyncMutex.prototype.release = function () {
165
+ var next = this.queue.shift();
166
+ if (next) {
167
+ next();
168
+ }
169
+ else {
170
+ this.locked = false;
171
+ }
172
+ };
173
+ AsyncMutex.prototype.reset = function () {
174
+ this.locked = false;
175
+ this.queue = [];
176
+ };
177
+ return AsyncMutex;
178
+ }());
179
+ var sessionMutex = new AsyncMutex();
180
+ /**
181
+ * Returns whether the active test transaction session can be attached to DB
182
+ * operations on the given Mongoose connection. The Node driver's
183
+ * `ClientSession` must belong to the same `MongoClient` as the collection;
184
+ * otherwise operations throw `MongoInvalidArgumentError` (observed in CI when
185
+ * mixing connections).
186
+ *
187
+ * @param connection - Mongoose connection (`Model.db`), or undefined when unknown
188
+ * @returns True when the session should be passed into driver options / `.session()`
189
+ */
190
+ var shouldAttachTestSessionToConnection = function (connection) {
191
+ if (!currentTestSession) {
192
+ return false;
193
+ }
194
+ var sessionClient = currentTestSession.client;
195
+ if (!connection || typeof connection.getClient !== "function") {
196
+ return true;
197
+ }
198
+ var connClient = connection.getClient();
199
+ if (!sessionClient || !connClient) {
200
+ return true;
201
+ }
202
+ return sessionClient === connClient;
203
+ };
204
+ /**
205
+ * Waits until all serialized DB operations have completed before test teardown.
206
+ *
207
+ * This prevents operations that were queued near test completion from leaking
208
+ * into the next test's transaction window, which can surface as intermittent
209
+ * NoSuchTransaction / transaction-number mismatch errors.
210
+ */
211
+ var waitForSerializedOperationsToDrain = function () {
212
+ var args_1 = [];
213
+ for (var _i = 0; _i < arguments.length; _i++) {
214
+ args_1[_i] = arguments[_i];
215
+ }
216
+ return __awaiter(void 0, __spreadArray([], __read(args_1), false), void 0, function (timeoutMs) {
217
+ var timeoutId;
218
+ if (timeoutMs === void 0) { timeoutMs = 5000; }
219
+ return __generator(this, function (_a) {
220
+ switch (_a.label) {
221
+ case 0:
222
+ _a.trys.push([0, , 2, 3]);
223
+ return [4 /*yield*/, Promise.race([
224
+ (function () { return __awaiter(void 0, void 0, void 0, function () {
225
+ return __generator(this, function (_a) {
226
+ switch (_a.label) {
227
+ case 0: return [4 /*yield*/, sessionMutex.acquire()];
228
+ case 1:
229
+ _a.sent();
230
+ sessionMutex.release();
231
+ return [2 /*return*/];
232
+ }
233
+ });
234
+ }); })(),
235
+ new Promise(function (_, reject) {
236
+ timeoutId = setTimeout(function () {
237
+ reject(new Error("[testTransaction] Timed out waiting for serialized operations to drain"));
238
+ }, timeoutMs);
239
+ }),
240
+ ])];
241
+ case 1:
242
+ _a.sent();
243
+ return [3 /*break*/, 3];
244
+ case 2:
245
+ if (timeoutId) {
246
+ clearTimeout(timeoutId);
247
+ }
248
+ return [7 /*endfinally*/];
249
+ case 3: return [2 /*return*/];
250
+ }
251
+ });
252
+ });
253
+ };
254
+ /**
255
+ * Wraps an async DB operation with the session mutex. Reentrant: if the current
256
+ * async context is already inside a serialized block, the operation runs directly
257
+ * without acquiring the mutex (preventing deadlocks from nested operations like
258
+ * pre-save hooks that do queries).
259
+ */
260
+ var serialized = function (fn) {
261
+ // If no test session is active, skip serialization entirely
262
+ if (!currentTestSession) {
263
+ return fn();
264
+ }
265
+ // If we're already inside a serialized block (nested call), run directly
266
+ var store = serializationContext.getStore();
267
+ if (store === null || store === void 0 ? void 0 : store.active) {
268
+ return fn();
269
+ }
270
+ // Top-level call: acquire mutex, then run inside the serialization context
271
+ var run = function () { return __awaiter(void 0, void 0, void 0, function () {
272
+ var hasRetried, error_1, isTransactionAborted, _a;
273
+ var _b, _c;
274
+ return __generator(this, function (_d) {
275
+ switch (_d.label) {
276
+ case 0:
277
+ hasRetried = false;
278
+ _d.label = 1;
279
+ case 1:
280
+ if (!true) return [3 /*break*/, 13];
281
+ return [4 /*yield*/, sessionMutex.acquire()];
282
+ case 2:
283
+ _d.sent();
284
+ _d.label = 3;
285
+ case 3:
286
+ _d.trys.push([3, 5, 11, 12]);
287
+ return [4 /*yield*/, serializationContext.run({ active: true }, fn)];
288
+ case 4: return [2 /*return*/, _d.sent()];
289
+ case 5:
290
+ error_1 = _d.sent();
291
+ isTransactionAborted = ((_c = (_b = error_1 === null || error_1 === void 0 ? void 0 : error_1.errorLabels) === null || _b === void 0 ? void 0 : _b.includes) === null || _c === void 0 ? void 0 : _c.call(_b, "TransientTransactionError")) ||
292
+ (currentTestSession && !currentTestSession.inTransaction());
293
+ if (!(!hasRetried && isTransactionAborted && currentTestSession)) return [3 /*break*/, 10];
294
+ hasRetried = true;
295
+ _d.label = 6;
296
+ case 6:
297
+ _d.trys.push([6, 9, , 10]);
298
+ if (!currentTestSession.inTransaction()) return [3 /*break*/, 8];
299
+ return [4 /*yield*/, currentTestSession.abortTransaction()];
300
+ case 7:
301
+ _d.sent();
302
+ _d.label = 8;
303
+ case 8:
304
+ currentTestSession.startTransaction();
305
+ return [3 /*break*/, 1];
306
+ case 9:
307
+ _a = _d.sent();
308
+ return [3 /*break*/, 10];
309
+ case 10: throw error_1;
310
+ case 11:
311
+ sessionMutex.release();
312
+ return [7 /*endfinally*/];
313
+ case 12: return [3 /*break*/, 1];
314
+ case 13: return [2 /*return*/];
315
+ }
316
+ });
317
+ }); };
318
+ return run();
319
+ };
320
+ // ============================================================================
321
+ // Public API
322
+ // ============================================================================
323
+ /** Returns the current test session, or null if not in a test transaction. */
324
+ var getTestSession = function () { return currentTestSession; };
325
+ exports.getTestSession = getTestSession;
326
+ /**
327
+ * Starts a new test transaction. Call in beforeEach.
328
+ *
329
+ * Reuses the existing MongoDB session when possible. A new session is only
330
+ * created on the very first call or after the previous session has been
331
+ * explicitly ended (e.g., due to an error).
332
+ */
333
+ var startTestTransaction = function () { return __awaiter(void 0, void 0, void 0, function () {
334
+ var _a, _b;
335
+ return __generator(this, function (_c) {
336
+ switch (_c.label) {
337
+ case 0:
338
+ if (!currentTestSession) return [3 /*break*/, 9];
339
+ _c.label = 1;
340
+ case 1:
341
+ _c.trys.push([1, 4, , 9]);
342
+ if (!currentTestSession.inTransaction()) return [3 /*break*/, 3];
343
+ return [4 /*yield*/, currentTestSession.abortTransaction()];
344
+ case 2:
345
+ _c.sent();
346
+ _c.label = 3;
347
+ case 3: return [3 /*break*/, 9];
348
+ case 4:
349
+ _a = _c.sent();
350
+ _c.label = 5;
351
+ case 5:
352
+ _c.trys.push([5, 7, , 8]);
353
+ return [4 /*yield*/, currentTestSession.endSession()];
354
+ case 6:
355
+ _c.sent();
356
+ return [3 /*break*/, 8];
357
+ case 7:
358
+ _b = _c.sent();
359
+ return [3 /*break*/, 8];
360
+ case 8:
361
+ currentTestSession = null;
362
+ return [3 /*break*/, 9];
363
+ case 9:
364
+ if (!!currentTestSession) return [3 /*break*/, 11];
365
+ return [4 /*yield*/, mongoose_1.default.startSession()];
366
+ case 10:
367
+ currentTestSession = _c.sent();
368
+ _c.label = 11;
369
+ case 11:
370
+ sessionMutex.reset();
371
+ currentTestSession.startTransaction();
372
+ return [2 /*return*/];
373
+ }
374
+ });
375
+ }); };
376
+ exports.startTestTransaction = startTestTransaction;
377
+ /**
378
+ * Aborts the current test transaction. Call in afterEach.
379
+ *
380
+ * The session is intentionally kept alive (not ended) so it can be reused by
381
+ * the next test. This avoids returning the session to the driver's server
382
+ * session pool, which prevents transaction number mismatches when in-flight
383
+ * operations from a previous test complete after the session has been recycled.
384
+ */
385
+ var abortTestTransaction = function () { return __awaiter(void 0, void 0, void 0, function () {
386
+ var error_2, _a;
387
+ return __generator(this, function (_b) {
388
+ switch (_b.label) {
389
+ case 0:
390
+ if (!currentTestSession) {
391
+ return [2 /*return*/];
392
+ }
393
+ _b.label = 1;
394
+ case 1:
395
+ _b.trys.push([1, 5, 10, 11]);
396
+ // Ensure any in-flight/queued DB work from the current test has settled
397
+ // before aborting and starting the next transaction.
398
+ return [4 /*yield*/, waitForSerializedOperationsToDrain()];
399
+ case 2:
400
+ // Ensure any in-flight/queued DB work from the current test has settled
401
+ // before aborting and starting the next transaction.
402
+ _b.sent();
403
+ if (!currentTestSession.inTransaction()) return [3 /*break*/, 4];
404
+ return [4 /*yield*/, currentTestSession.abortTransaction()];
405
+ case 3:
406
+ _b.sent();
407
+ _b.label = 4;
408
+ case 4: return [3 /*break*/, 11];
409
+ case 5:
410
+ error_2 = _b.sent();
411
+ // biome-ignore lint/suspicious/noConsole: test harness diagnostic when abort fails
412
+ console.warn("[testTransaction] Error aborting transaction:", error_2);
413
+ _b.label = 6;
414
+ case 6:
415
+ _b.trys.push([6, 8, , 9]);
416
+ return [4 /*yield*/, currentTestSession.endSession()];
417
+ case 7:
418
+ _b.sent();
419
+ return [3 /*break*/, 9];
420
+ case 8:
421
+ _a = _b.sent();
422
+ return [3 /*break*/, 9];
423
+ case 9:
424
+ currentTestSession = null;
425
+ return [3 /*break*/, 11];
426
+ case 10:
427
+ // Clean slate for the next test transaction.
428
+ sessionMutex.reset();
429
+ return [7 /*endfinally*/];
430
+ case 11: return [2 /*return*/];
431
+ }
432
+ });
433
+ }); };
434
+ exports.abortTestTransaction = abortTestTransaction;
435
+ /**
436
+ * Drops the cached test session after an out-of-band mongoose reconnect.
437
+ *
438
+ * Reconnects can swap the underlying MongoClient, which invalidates any active
439
+ * ClientSession. Clearing here prevents subsequent tests from reusing a stale
440
+ * or expired session.
441
+ */
442
+ var resetTestSessionAfterReconnect = function () { return __awaiter(void 0, void 0, void 0, function () {
443
+ var _a;
444
+ return __generator(this, function (_b) {
445
+ switch (_b.label) {
446
+ case 0:
447
+ if (!currentTestSession) {
448
+ sessionMutex.reset();
449
+ return [2 /*return*/];
450
+ }
451
+ _b.label = 1;
452
+ case 1:
453
+ _b.trys.push([1, 5, 6, 7]);
454
+ if (!currentTestSession.inTransaction()) return [3 /*break*/, 3];
455
+ return [4 /*yield*/, currentTestSession.abortTransaction()];
456
+ case 2:
457
+ _b.sent();
458
+ _b.label = 3;
459
+ case 3: return [4 /*yield*/, currentTestSession.endSession()];
460
+ case 4:
461
+ _b.sent();
462
+ return [3 /*break*/, 7];
463
+ case 5:
464
+ _a = _b.sent();
465
+ return [3 /*break*/, 7];
466
+ case 6:
467
+ currentTestSession = null;
468
+ sessionMutex.reset();
469
+ return [7 /*endfinally*/];
470
+ case 7: return [2 /*return*/];
471
+ }
472
+ });
473
+ }); };
474
+ exports.resetTestSessionAfterReconnect = resetTestSessionAfterReconnect;
475
+ // ============================================================================
476
+ // Mongoose Monkey-Patches
477
+ // ============================================================================
478
+ /**
479
+ * Installs Mongoose monkey-patches that inject the test session into all DB operations.
480
+ *
481
+ * Patches are idempotent — calling this multiple times is safe.
482
+ * The patches only activate when currentTestSession is non-null (i.e., during a test).
483
+ * All operations are serialized through the async mutex to prevent concurrent
484
+ * operations on the same MongoDB session.
485
+ *
486
+ * Patched operations:
487
+ * - Query.prototype.exec — covers find, findOne, updateOne, deleteMany, countDocuments, etc.
488
+ * - Model.prototype.save and $save — covers save() and create() (Model.create calls $save)
489
+ * - Aggregate.prototype.exec — covers aggregation pipelines
490
+ * - Model.bulkWrite — covers bulk write operations
491
+ * - Model.insertMany — covers bulk inserts (uses native driver, not save)
492
+ * - Model.distinct — bypasses Query, calls native driver directly
493
+ * - Model.startSession — returns a no-op wrapper so app-level transactions don't conflict
494
+ * - Collection.prototype (insertOne, updateOne, deleteOne, etc.) — covers native driver
495
+ * operations used by tests that call Model.collection.insertOne() directly
496
+ *
497
+ * When a model or collection uses a different MongoClient than the one that
498
+ * created the test session, patches skip session injection for that operation
499
+ * so the driver does not reject mismatched clients.
500
+ */
501
+ var installTransactionPatches = function () {
502
+ var e_1, _a, e_2, _b;
503
+ if (patchesInstalled) {
504
+ return;
505
+ }
506
+ // --- Query.prototype.exec ---
507
+ var originalQueryExec = mongoose_1.default.Query.prototype.exec;
508
+ mongoose_1.default.Query.prototype.exec = function () {
509
+ var _this = this;
510
+ var _a;
511
+ if (currentTestSession) {
512
+ if (!shouldAttachTestSessionToConnection((_a = this.model) === null || _a === void 0 ? void 0 : _a.db)) {
513
+ return originalQueryExec.apply(this);
514
+ }
515
+ this.session(currentTestSession);
516
+ return serialized(function () { return originalQueryExec.apply(_this); });
517
+ }
518
+ return originalQueryExec.apply(this);
519
+ };
520
+ // --- Model.prototype.save and $save ---
521
+ // In Mongoose 8, Model.create() calls $save (not save). $save is assigned from
522
+ // save at module load time (Model.prototype.$save = Model.prototype.save), so we
523
+ // must patch both to ensure Model.create() goes through our session injection.
524
+ var patchSave = function (original) {
525
+ return function (options) {
526
+ var _this = this;
527
+ var _a;
528
+ if (currentTestSession) {
529
+ var connection = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a.db;
530
+ if (!shouldAttachTestSessionToConnection(connection)) {
531
+ return original.call(this, options);
532
+ }
533
+ if (typeof options === "function") {
534
+ this.$session(currentTestSession);
535
+ return serialized(function () { return original.call(_this, options); });
536
+ }
537
+ options = __assign(__assign({}, (options || {})), { session: currentTestSession });
538
+ return serialized(function () { return original.call(_this, options); });
539
+ }
540
+ return original.call(this, options);
541
+ };
542
+ };
543
+ var originalSave = mongoose_1.default.Model.prototype.save;
544
+ mongoose_1.default.Model.prototype.save = patchSave(originalSave);
545
+ // $save is what Model.create() actually calls
546
+ var original$Save = mongoose_1.default.Model.prototype.$save;
547
+ mongoose_1.default.Model.prototype.$save = patchSave(original$Save);
548
+ // --- Aggregate.prototype.exec ---
549
+ var originalAggExec = mongoose_1.default.Aggregate.prototype.exec;
550
+ mongoose_1.default.Aggregate.prototype.exec = function () {
551
+ var _this = this;
552
+ var _a, _b;
553
+ if (currentTestSession) {
554
+ var connection = (_b = (_a = this._model) === null || _a === void 0 ? void 0 : _a.db) !== null && _b !== void 0 ? _b : this._connection;
555
+ if (!shouldAttachTestSessionToConnection(connection)) {
556
+ return originalAggExec.apply(this);
557
+ }
558
+ this.session(currentTestSession);
559
+ return serialized(function () { return originalAggExec.apply(_this); });
560
+ }
561
+ return originalAggExec.apply(this);
562
+ };
563
+ // --- Model.bulkWrite (static) ---
564
+ var originalBulkWrite = mongoose_1.default.Model.bulkWrite;
565
+ mongoose_1.default.Model.bulkWrite = function (ops, options) {
566
+ var _this = this;
567
+ if (currentTestSession) {
568
+ if (!shouldAttachTestSessionToConnection(this.db)) {
569
+ return originalBulkWrite.call(this, ops, options);
570
+ }
571
+ options = __assign(__assign({}, (options || {})), { session: currentTestSession });
572
+ return serialized(function () { return originalBulkWrite.call(_this, ops, options); });
573
+ }
574
+ return originalBulkWrite.call(this, ops, options);
575
+ };
576
+ // --- Model.insertMany (static) ---
577
+ var originalInsertMany = mongoose_1.default.Model.insertMany;
578
+ mongoose_1.default.Model.insertMany = function (docs, options) {
579
+ var _this = this;
580
+ if (currentTestSession) {
581
+ if (!shouldAttachTestSessionToConnection(this.db)) {
582
+ return originalInsertMany.call(this, docs, options);
583
+ }
584
+ options = __assign(__assign({}, (options || {})), { session: currentTestSession });
585
+ return serialized(function () { return originalInsertMany.call(_this, docs, options); });
586
+ }
587
+ return originalInsertMany.call(this, docs, options);
588
+ };
589
+ // --- Model.create (static) ---
590
+ // Some code paths call Model.create() directly (including through
591
+ // mongoose.Model.create.call(...)), which can otherwise bypass our top-level
592
+ // serialization guard and race with other operations on the shared test
593
+ // session. Wrapping create ensures transient transaction aborts trigger the
594
+ // same auto-restart logic in serialized().
595
+ var originalCreate = mongoose_1.default.Model.create;
596
+ mongoose_1.default.Model.create = function () {
597
+ var _this = this;
598
+ var args = [];
599
+ for (var _i = 0; _i < arguments.length; _i++) {
600
+ args[_i] = arguments[_i];
601
+ }
602
+ if (currentTestSession) {
603
+ if (!shouldAttachTestSessionToConnection(this.db)) {
604
+ return originalCreate.apply(this, args);
605
+ }
606
+ return serialized(function () { return originalCreate.apply(_this, args); });
607
+ }
608
+ return originalCreate.apply(this, args);
609
+ };
610
+ // --- Model.startSession (static) ---
611
+ // When test session is active, return a wrapper that redirects operations
612
+ // through the test session. This ensures app code that creates its own
613
+ // transactions (e.g. userExplorerAcquisitionUpload.ts) doesn't bypass
614
+ // test isolation.
615
+ var originalStartSession = mongoose_1.default.Model.startSession;
616
+ mongoose_1.default.Model.startSession = function (options) {
617
+ return __awaiter(this, void 0, void 0, function () {
618
+ var _this = this;
619
+ return __generator(this, function (_a) {
620
+ if (currentTestSession) {
621
+ return [2 /*return*/, __assign(__assign({}, currentTestSession), { startTransaction: function () { }, commitTransaction: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
622
+ return [2 /*return*/];
623
+ }); }); }, abortTransaction: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
624
+ return [2 /*return*/];
625
+ }); }); }, endSession: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
626
+ return [2 /*return*/];
627
+ }); }); }, id: currentTestSession.id, inTransaction: function () { var _a; return (_a = currentTestSession === null || currentTestSession === void 0 ? void 0 : currentTestSession.inTransaction()) !== null && _a !== void 0 ? _a : false; } })];
628
+ }
629
+ return [2 /*return*/, originalStartSession.call(this, options)];
630
+ });
631
+ });
632
+ };
633
+ // --- Collection.prototype (native driver operations) ---
634
+ // Some test files call Model.collection.insertOne() etc. directly, bypassing
635
+ // Mongoose. We patch the Mongoose Collection wrapper to inject the session
636
+ // into these operations so they participate in the test transaction.
637
+ //
638
+ // Methods are grouped by their options argument position:
639
+ // - optionsAt1: (docOrFilter, options?) — insertOne, deleteOne, deleteMany, findOne, etc.
640
+ // - optionsAt2: (filter, update, options?) — updateOne, updateMany, findOneAndUpdate, etc.
641
+ var patchCollectionMethod = function (method, optionsIndex) {
642
+ var original = mongoose_1.default.Collection.prototype[method];
643
+ if (typeof original !== "function") {
644
+ return;
645
+ }
646
+ mongoose_1.default.Collection.prototype[method] = function () {
647
+ var _this = this;
648
+ var args = [];
649
+ for (var _i = 0; _i < arguments.length; _i++) {
650
+ args[_i] = arguments[_i];
651
+ }
652
+ if (!currentTestSession) {
653
+ return original.apply(this, args);
654
+ }
655
+ if (!shouldAttachTestSessionToConnection(this.conn)) {
656
+ return original.apply(this, args);
657
+ }
658
+ return serialized(function () {
659
+ // Inject session into the options argument at the correct position
660
+ if (args[optionsIndex] && typeof args[optionsIndex] === "object") {
661
+ args[optionsIndex] = __assign(__assign({}, args[optionsIndex]), { session: currentTestSession });
662
+ }
663
+ else {
664
+ args[optionsIndex] = { session: currentTestSession };
665
+ }
666
+ return original.apply(_this, args);
667
+ });
668
+ };
669
+ };
670
+ try {
671
+ // (docOrFilter, options?) — options at index 1
672
+ for (var _c = __values([
673
+ "insertOne",
674
+ "insertMany",
675
+ "deleteOne",
676
+ "deleteMany",
677
+ "findOne",
678
+ "findOneAndDelete",
679
+ "countDocuments",
680
+ "aggregate",
681
+ ]), _d = _c.next(); !_d.done; _d = _c.next()) {
682
+ var method = _d.value;
683
+ patchCollectionMethod(method, 1);
684
+ }
685
+ }
686
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
687
+ finally {
688
+ try {
689
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
690
+ }
691
+ finally { if (e_1) throw e_1.error; }
692
+ }
693
+ try {
694
+ // (filter, update/replacement, options?) — options at index 2
695
+ for (var _e = __values([
696
+ "updateOne",
697
+ "updateMany",
698
+ "findOneAndUpdate",
699
+ "findOneAndReplace",
700
+ "replaceOne",
701
+ ]), _f = _e.next(); !_f.done; _f = _e.next()) {
702
+ var method = _f.value;
703
+ patchCollectionMethod(method, 2);
704
+ }
705
+ }
706
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
707
+ finally {
708
+ try {
709
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
710
+ }
711
+ finally { if (e_2) throw e_2.error; }
712
+ }
713
+ patchesInstalled = true;
714
+ if (process.env.DEBUG_TEST_TRANSACTION === "true") {
715
+ // biome-ignore lint/suspicious/noConsole: optional debug for patch installation
716
+ console.debug("[testTransaction] Mongoose patches installed");
717
+ }
718
+ };
719
+ exports.installTransactionPatches = installTransactionPatches;