@terreno/test 57.3.0 → 57.6.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.
Files changed (45) hide show
  1. package/README.md +2 -2
  2. package/bunfig.toml +13 -0
  3. package/dist/cache/mongoTestCache.js +175 -427
  4. package/dist/env/setTerrenoTestEnv.js +15 -65
  5. package/dist/http/authAsUser.js +28 -153
  6. package/dist/http/getBaseServer.js +6 -7
  7. package/dist/logging/setupEnvironment.js +1 -1
  8. package/dist/logging/silenceLogs.js +36 -93
  9. package/dist/logging/testLogger.js +4 -4
  10. package/dist/mocks/sentryBun.js +39 -39
  11. package/dist/mongo/connection.js +31 -115
  12. package/dist/mongo/ensureMongoBinary.js +12 -92
  13. package/dist/mongo/mongoServer.js +142 -390
  14. package/dist/preload/defaultBackendPreload.js +4 -2
  15. package/dist/preload/memoryMongo.d.ts +1 -0
  16. package/dist/preload/memoryMongo.js +1 -0
  17. package/dist/preload/registerBackendPreload.js +87 -262
  18. package/dist/transaction/testTransaction.js +224 -444
  19. package/dist/utils/ensureAllIndexes.js +9 -76
  20. package/dist/utils/timeout.js +3 -41
  21. package/dist/utils/waitForDocuments.js +18 -115
  22. package/package.json +13 -13
  23. package/src/cache/mongoTestCache.test.ts +103 -0
  24. package/src/http/getBaseServer.test.ts +20 -5
  25. package/src/logging/silenceLogs.test.ts +52 -0
  26. package/src/mocks/sentryBun.test.ts +230 -0
  27. package/src/mongo/connection.test.ts +14 -0
  28. package/src/mongo/mongoServer.test.ts +74 -0
  29. package/src/preload/defaultBackendPreload.ts +5 -2
  30. package/src/preload/registerBackendPreload.test.ts +10 -0
  31. package/src/transaction/testTransaction.test.ts +64 -0
  32. package/src/utils/helpers.test.ts +46 -0
  33. package/tsconfig.json +6 -22
  34. package/dist/env/setTerrenoTestEnv.test.d.ts +0 -1
  35. package/dist/env/setTerrenoTestEnv.test.js +0 -24
  36. package/dist/http/authAsUser.test.d.ts +0 -1
  37. package/dist/http/authAsUser.test.js +0 -93
  38. package/dist/http/getBaseServer.test.d.ts +0 -1
  39. package/dist/http/getBaseServer.test.js +0 -76
  40. package/dist/logging/setupEnvironment.test.d.ts +0 -1
  41. package/dist/logging/setupEnvironment.test.js +0 -23
  42. package/dist/logging/testLogger.test.d.ts +0 -1
  43. package/dist/logging/testLogger.test.js +0 -56
  44. package/dist/mongo/connection.test.d.ts +0 -1
  45. package/dist/mongo/connection.test.js +0 -28
@@ -32,180 +32,85 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
- var __generator = (this && this.__generator) || function (thisArg, body) {
45
- 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);
46
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
- function verb(n) { return function (v) { return step([n, v]); }; }
48
- function step(op) {
49
- if (f) throw new TypeError("Generator is already executing.");
50
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
- 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;
52
- if (y = 0, t) op = [op[0] & 2, t.value];
53
- switch (op[0]) {
54
- case 0: case 1: t = op; break;
55
- case 4: _.label++; return { value: op[1], done: false };
56
- case 5: _.label++; y = op[1]; op = [0]; continue;
57
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
- default:
59
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
- if (t[2]) _.ops.pop();
64
- _.trys.pop(); continue;
65
- }
66
- op = body.call(thisArg, _);
67
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
- }
70
- };
71
- var __values = (this && this.__values) || function(o) {
72
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
73
- if (m) return m.call(o);
74
- if (o && typeof o.length === "number") return {
75
- next: function () {
76
- if (o && i >= o.length) o = void 0;
77
- return { value: o && o[i++], done: !o };
78
- }
79
- };
80
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
81
- };
82
- var __read = (this && this.__read) || function (o, n) {
83
- var m = typeof Symbol === "function" && o[Symbol.iterator];
84
- if (!m) return o;
85
- var i = m.call(o), r, ar = [], e;
86
- try {
87
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
88
- }
89
- catch (error) { e = { error: error }; }
90
- finally {
91
- try {
92
- if (r && !r.done && (m = i["return"])) m.call(i);
93
- }
94
- finally { if (e) throw e.error; }
95
- }
96
- return ar;
97
- };
98
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
99
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
100
- if (ar || !(i in from)) {
101
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
102
- ar[i] = from[i];
103
- }
104
- }
105
- return to.concat(ar || Array.prototype.slice.call(from));
106
- };
107
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
108
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
109
37
  };
110
38
  Object.defineProperty(exports, "__esModule", { value: true });
111
39
  exports.createMongoTestCache = void 0;
112
- var crypto = __importStar(require("node:crypto"));
113
- var fs = __importStar(require("node:fs"));
114
- var path = __importStar(require("node:path"));
115
- var luxon_1 = require("luxon");
116
- var mongoose_1 = __importDefault(require("mongoose"));
117
- var testLogger_1 = require("../logging/testLogger");
118
- var connection_1 = require("../mongo/connection");
119
- var mongoServer_1 = require("../mongo/mongoServer");
120
- var testTransaction_1 = require("../transaction/testTransaction");
121
- var ensureAllIndexes_1 = require("../utils/ensureAllIndexes");
122
- var HASH_FILE = "source-hash.txt";
123
- var CACHED_DATA_FILE = "cached-data.json";
124
- var CACHED_COLLECTIONS_FILE = "cached-collections.json";
125
- var MAX_CACHE_AGE_MS = 60 * 60 * 1000;
126
- var getAllTsFiles = function (dir) {
127
- var e_1, _a;
128
- var files = [];
40
+ const crypto = __importStar(require("node:crypto"));
41
+ const fs = __importStar(require("node:fs"));
42
+ const path = __importStar(require("node:path"));
43
+ const luxon_1 = require("luxon");
44
+ const mongoose_1 = __importDefault(require("mongoose"));
45
+ const testLogger_1 = require("../logging/testLogger");
46
+ const connection_1 = require("../mongo/connection");
47
+ const mongoServer_1 = require("../mongo/mongoServer");
48
+ const testTransaction_1 = require("../transaction/testTransaction");
49
+ const ensureAllIndexes_1 = require("../utils/ensureAllIndexes");
50
+ const HASH_FILE = "source-hash.txt";
51
+ const CACHED_DATA_FILE = "cached-data.json";
52
+ const CACHED_COLLECTIONS_FILE = "cached-collections.json";
53
+ const MAX_CACHE_AGE_MS = 60 * 60 * 1000;
54
+ const getAllTsFiles = (dir) => {
55
+ const files = [];
129
56
  if (!fs.existsSync(dir)) {
130
57
  return files;
131
58
  }
132
- var entries = fs.readdirSync(dir, { withFileTypes: true });
133
- try {
134
- for (var entries_1 = __values(entries), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
135
- var entry = entries_1_1.value;
136
- var fullPath = path.join(dir, entry.name);
137
- if (entry.isDirectory()) {
138
- files.push.apply(files, __spreadArray([], __read(getAllTsFiles(fullPath)), false));
139
- }
140
- else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
141
- files.push(fullPath);
142
- }
59
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
60
+ for (const entry of entries) {
61
+ const fullPath = path.join(dir, entry.name);
62
+ if (entry.isDirectory()) {
63
+ files.push(...getAllTsFiles(fullPath));
143
64
  }
144
- }
145
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
146
- finally {
147
- try {
148
- if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1);
65
+ else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
66
+ files.push(fullPath);
149
67
  }
150
- finally { if (e_1) throw e_1.error; }
151
68
  }
152
69
  return files;
153
70
  };
154
- var calculateSourceFilesHash = function (sourceDirs) {
155
- var e_2, _a;
156
- var tsFiles = sourceDirs.flatMap(function (dir) { return getAllTsFiles(dir); }).sort();
157
- var hash = crypto.createHash("sha256");
158
- try {
159
- for (var tsFiles_1 = __values(tsFiles), tsFiles_1_1 = tsFiles_1.next(); !tsFiles_1_1.done; tsFiles_1_1 = tsFiles_1.next()) {
160
- var file = tsFiles_1_1.value;
161
- hash.update(file);
162
- hash.update(fs.readFileSync(file, "utf-8"));
163
- }
164
- }
165
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
166
- finally {
167
- try {
168
- if (tsFiles_1_1 && !tsFiles_1_1.done && (_a = tsFiles_1.return)) _a.call(tsFiles_1);
169
- }
170
- finally { if (e_2) throw e_2.error; }
71
+ const calculateSourceFilesHash = (sourceDirs) => {
72
+ const tsFiles = sourceDirs.flatMap((dir) => getAllTsFiles(dir)).sort();
73
+ const hash = crypto.createHash("sha256");
74
+ for (const file of tsFiles) {
75
+ hash.update(file);
76
+ hash.update(fs.readFileSync(file, "utf-8"));
171
77
  }
172
78
  return hash.digest("hex");
173
79
  };
174
- var getSavedHash = function (cacheDir) {
175
- var hashFilePath = path.join(cacheDir, HASH_FILE);
80
+ const getSavedHash = (cacheDir) => {
81
+ const hashFilePath = path.join(cacheDir, HASH_FILE);
176
82
  if (!fs.existsSync(hashFilePath)) {
177
83
  return null;
178
84
  }
179
85
  try {
180
86
  return fs.readFileSync(hashFilePath, "utf-8").trim();
181
87
  }
182
- catch (_a) {
88
+ catch {
183
89
  return null;
184
90
  }
185
91
  };
186
- var saveHash = function (cacheDir, hash) {
92
+ const saveHash = (cacheDir, hash) => {
187
93
  fs.mkdirSync(cacheDir, { recursive: true });
188
94
  fs.writeFileSync(path.join(cacheDir, HASH_FILE), hash);
189
95
  };
190
- var cacheFilesExist = function (cacheDir) {
191
- var dataFilePath = path.join(cacheDir, CACHED_DATA_FILE);
192
- var collectionsFilePath = path.join(cacheDir, CACHED_COLLECTIONS_FILE);
193
- var hashFilePath = path.join(cacheDir, HASH_FILE);
96
+ const cacheFilesExist = (cacheDir) => {
97
+ const dataFilePath = path.join(cacheDir, CACHED_DATA_FILE);
98
+ const collectionsFilePath = path.join(cacheDir, CACHED_COLLECTIONS_FILE);
99
+ const hashFilePath = path.join(cacheDir, HASH_FILE);
194
100
  if (!fs.existsSync(dataFilePath) ||
195
101
  !fs.existsSync(collectionsFilePath) ||
196
102
  !fs.existsSync(hashFilePath)) {
197
103
  return false;
198
104
  }
199
105
  if (!process.env.CI) {
200
- var cacheAge = luxon_1.DateTime.now().toMillis() - fs.statSync(dataFilePath).mtimeMs;
106
+ const cacheAge = luxon_1.DateTime.now().toMillis() - fs.statSync(dataFilePath).mtimeMs;
201
107
  if (cacheAge > MAX_CACHE_AGE_MS) {
202
108
  return false;
203
109
  }
204
110
  }
205
111
  return true;
206
112
  };
207
- var convertValue = function (value) {
208
- var e_3, _a;
113
+ const convertValue = (value) => {
209
114
  if (value === null || value === undefined) {
210
115
  return value;
211
116
  }
@@ -219,334 +124,177 @@ var convertValue = function (value) {
219
124
  return value;
220
125
  }
221
126
  if (Array.isArray(value)) {
222
- return value.map(function (item) { return convertValue(item); });
127
+ return value.map((item) => convertValue(item));
223
128
  }
224
129
  if (typeof value === "object") {
225
- var converted = {};
226
- try {
227
- for (var _b = __values(Object.entries(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
228
- var _d = __read(_c.value, 2), key = _d[0], nested = _d[1];
229
- converted[key] = convertValue(nested);
230
- }
231
- }
232
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
233
- finally {
234
- try {
235
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
236
- }
237
- finally { if (e_3) throw e_3.error; }
130
+ const converted = {};
131
+ for (const [key, nested] of Object.entries(value)) {
132
+ converted[key] = convertValue(nested);
238
133
  }
239
134
  return converted;
240
135
  }
241
136
  return value;
242
137
  };
243
- var getReconnectUri = function (publishedUriEnvVar, baseDatabaseName) {
244
- var uri = process.env[publishedUriEnvVar];
138
+ const getReconnectUri = (publishedUriEnvVar, baseDatabaseName) => {
139
+ const uri = process.env[publishedUriEnvVar];
245
140
  if (!uri) {
246
- throw new Error("[mongoTestCache] ".concat(publishedUriEnvVar, " is not set"));
141
+ throw new Error(`[mongoTestCache] ${publishedUriEnvVar} is not set`);
247
142
  }
248
- return (0, connection_1.buildDatabaseUri)({ databaseName: mongoose_1.default.connection.name || baseDatabaseName, uri: uri });
143
+ return (0, connection_1.buildDatabaseUri)({ databaseName: mongoose_1.default.connection.name || baseDatabaseName, uri });
249
144
  };
250
145
  /** Throws when the driver has no database handle, so callers treat it like a failed ping. */
251
- var requireDb = function () {
252
- var db = mongoose_1.default.connection.db;
146
+ const requireDb = () => {
147
+ const { db } = mongoose_1.default.connection;
253
148
  if (!db) {
254
149
  throw new Error("[mongoTestCache] mongoose connection has no database handle");
255
150
  }
256
151
  return db;
257
152
  };
258
- var ensureConnectionReady = function (publishedUriEnvVar, baseDatabaseName) { return __awaiter(void 0, void 0, void 0, function () {
259
- var maxQuickAttempts, delayMs, attempt, state, _a, _b;
260
- return __generator(this, function (_c) {
261
- switch (_c.label) {
262
- case 0:
263
- maxQuickAttempts = 3;
264
- delayMs = 200;
265
- attempt = 1;
266
- _c.label = 1;
267
- case 1:
268
- if (!(attempt <= maxQuickAttempts)) return [3 /*break*/, 16];
269
- state = mongoose_1.default.connection.readyState;
270
- if (!(state === 1)) return [3 /*break*/, 5];
271
- _c.label = 2;
272
- case 2:
273
- _c.trys.push([2, 4, , 5]);
274
- return [4 /*yield*/, requireDb().admin().command({ ping: 1 })];
275
- case 3:
276
- _c.sent();
277
- return [2 /*return*/];
278
- case 4:
279
- _a = _c.sent();
280
- return [3 /*break*/, 5];
281
- case 5:
282
- if (!(state === 0 || state === 3)) return [3 /*break*/, 13];
283
- _c.label = 6;
284
- case 6:
285
- _c.trys.push([6, 12, , 13]);
286
- if (!(state === 3)) return [3 /*break*/, 8];
287
- return [4 /*yield*/, mongoose_1.default.disconnect().catch(function () { })];
288
- case 7:
289
- _c.sent();
290
- _c.label = 8;
291
- case 8: return [4 /*yield*/, mongoose_1.default.connect(getReconnectUri(publishedUriEnvVar, baseDatabaseName), {
153
+ const ensureConnectionReady = async (publishedUriEnvVar, baseDatabaseName) => {
154
+ const maxQuickAttempts = 3;
155
+ const delayMs = 200;
156
+ for (let attempt = 1; attempt <= maxQuickAttempts; attempt++) {
157
+ const state = mongoose_1.default.connection.readyState;
158
+ if (state === 1) {
159
+ try {
160
+ await requireDb().admin().command({ ping: 1 });
161
+ return;
162
+ }
163
+ catch {
164
+ // stale connection
165
+ }
166
+ }
167
+ if (state === 0 || state === 3) {
168
+ try {
169
+ if (state === 3) {
170
+ await mongoose_1.default.disconnect().catch(() => { });
171
+ }
172
+ await mongoose_1.default.connect(getReconnectUri(publishedUriEnvVar, baseDatabaseName), {
292
173
  connectTimeoutMS: 2000,
293
174
  serverSelectionTimeoutMS: 2000,
294
175
  socketTimeoutMS: 2000,
295
- })];
296
- case 9:
297
- _c.sent();
298
- return [4 /*yield*/, requireDb().admin().command({ ping: 1 })];
299
- case 10:
300
- _c.sent();
301
- return [4 /*yield*/, (0, testTransaction_1.resetTestSessionAfterReconnect)()];
302
- case 11:
303
- _c.sent();
304
- return [2 /*return*/];
305
- case 12:
306
- _b = _c.sent();
307
- return [3 /*break*/, 13];
308
- case 13:
309
- if (!(attempt < maxQuickAttempts)) return [3 /*break*/, 15];
310
- return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, delayMs); })];
311
- case 14:
312
- _c.sent();
313
- _c.label = 15;
314
- case 15:
315
- attempt++;
316
- return [3 /*break*/, 1];
317
- case 16: return [4 /*yield*/, (0, mongoServer_1.restartMongoServer)({ baseDatabaseName: baseDatabaseName, publishedUriEnvVar: publishedUriEnvVar })];
318
- case 17:
319
- _c.sent();
320
- return [4 /*yield*/, (0, testTransaction_1.resetTestSessionAfterReconnect)()];
321
- case 18:
322
- _c.sent();
323
- return [2 /*return*/];
176
+ });
177
+ await requireDb().admin().command({ ping: 1 });
178
+ await (0, testTransaction_1.resetTestSessionAfterReconnect)();
179
+ return;
180
+ }
181
+ catch {
182
+ // retry
183
+ }
324
184
  }
325
- });
326
- }); };
327
- var loadTestDataIntoDb = function (cachedCollections) { return __awaiter(void 0, void 0, void 0, function () {
328
- var clearPromises, _a, _b, collectionName, restorePromises, _c, _d, collectionName, docs, convertedDocs, restoreResults, restoreResults_1, restoreResults_1_1, result, error, isDuplicateKey;
329
- var e_4, _e, e_5, _f, e_6, _g;
330
- var _h;
331
- return __generator(this, function (_j) {
332
- switch (_j.label) {
333
- case 0:
334
- clearPromises = [];
335
- try {
336
- for (_a = __values(Object.keys(cachedCollections)), _b = _a.next(); !_b.done; _b = _a.next()) {
337
- collectionName = _b.value;
338
- clearPromises.push(requireDb().collection(collectionName).deleteMany({}));
339
- }
340
- }
341
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
342
- finally {
343
- try {
344
- if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
345
- }
346
- finally { if (e_4) throw e_4.error; }
347
- }
348
- return [4 /*yield*/, Promise.all(clearPromises)];
349
- case 1:
350
- _j.sent();
351
- restorePromises = [];
352
- try {
353
- for (_c = __values(Object.keys(cachedCollections)), _d = _c.next(); !_d.done; _d = _c.next()) {
354
- collectionName = _d.value;
355
- docs = cachedCollections[collectionName];
356
- if (!docs || docs.length === 0) {
357
- continue;
358
- }
359
- convertedDocs = docs.map(function (doc) { return convertValue(doc); });
360
- restorePromises.push(mongoose_1.default.connection
361
- .db.collection(collectionName)
362
- .insertMany(convertedDocs, { ordered: false }));
363
- }
364
- }
365
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
366
- finally {
367
- try {
368
- if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
369
- }
370
- finally { if (e_5) throw e_5.error; }
371
- }
372
- return [4 /*yield*/, Promise.allSettled(restorePromises)];
373
- case 2:
374
- restoreResults = _j.sent();
375
- try {
376
- for (restoreResults_1 = __values(restoreResults), restoreResults_1_1 = restoreResults_1.next(); !restoreResults_1_1.done; restoreResults_1_1 = restoreResults_1.next()) {
377
- result = restoreResults_1_1.value;
378
- if (result.status === "rejected") {
379
- error = result.reason;
380
- isDuplicateKey = (error === null || error === void 0 ? void 0 : error.code) === 11000 ||
381
- ((_h = error === null || error === void 0 ? void 0 : error.writeErrors) === null || _h === void 0 ? void 0 : _h.every(function (writeError) { return writeError.code === 11000; }));
382
- if (!isDuplicateKey) {
383
- throw result.reason;
384
- }
385
- }
386
- }
387
- }
388
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
389
- finally {
390
- try {
391
- if (restoreResults_1_1 && !restoreResults_1_1.done && (_g = restoreResults_1.return)) _g.call(restoreResults_1);
392
- }
393
- finally { if (e_6) throw e_6.error; }
394
- }
395
- return [4 /*yield*/, (0, ensureAllIndexes_1.ensureAllIndexes)()];
396
- case 3:
397
- _j.sent();
398
- return [2 /*return*/];
185
+ if (attempt < maxQuickAttempts) {
186
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
187
+ }
188
+ }
189
+ await (0, mongoServer_1.restartMongoServer)({ baseDatabaseName, publishedUriEnvVar });
190
+ await (0, testTransaction_1.resetTestSessionAfterReconnect)();
191
+ };
192
+ const loadTestDataIntoDb = async (cachedCollections) => {
193
+ const clearPromises = [];
194
+ for (const collectionName of Object.keys(cachedCollections)) {
195
+ clearPromises.push(requireDb().collection(collectionName).deleteMany({}));
196
+ }
197
+ await Promise.all(clearPromises);
198
+ const restorePromises = [];
199
+ for (const collectionName of Object.keys(cachedCollections)) {
200
+ const docs = cachedCollections[collectionName];
201
+ if (!docs || docs.length === 0) {
202
+ continue;
203
+ }
204
+ const convertedDocs = docs.map((doc) => convertValue(doc));
205
+ restorePromises.push(mongoose_1.default.connection
206
+ .db.collection(collectionName)
207
+ .insertMany(convertedDocs, { ordered: false }));
208
+ }
209
+ const restoreResults = await Promise.allSettled(restorePromises);
210
+ for (const result of restoreResults) {
211
+ if (result.status === "rejected") {
212
+ const error = result.reason;
213
+ const isDuplicateKey = error?.code === 11000 ||
214
+ error?.writeErrors?.every((writeError) => writeError.code === 11000);
215
+ if (!isDuplicateKey) {
216
+ throw result.reason;
217
+ }
399
218
  }
400
- });
401
- }); };
402
- var createMongoTestCache = function (options) {
403
- var _a, _b;
404
- var publishedUriEnvVar = (_a = options.publishedUriEnvVar) !== null && _a !== void 0 ? _a : "TERRENO_TEST_MONGO_URI";
405
- var baseDatabaseName = (_b = options.baseDatabaseName) !== null && _b !== void 0 ? _b : "terrenoTest_base";
406
- var cachedSourceHash = null;
407
- var cachedCollectionsInMemory = null;
408
- var inflightSetupTestCache = null;
409
- var getSourceHash = function () {
219
+ }
220
+ await (0, ensureAllIndexes_1.ensureAllIndexes)();
221
+ };
222
+ const createMongoTestCache = (options) => {
223
+ const publishedUriEnvVar = options.publishedUriEnvVar ?? "TERRENO_TEST_MONGO_URI";
224
+ const baseDatabaseName = options.baseDatabaseName ?? "terrenoTest_base";
225
+ let cachedSourceHash = null;
226
+ let cachedCollectionsInMemory = null;
227
+ let inflightSetupTestCache = null;
228
+ const getSourceHash = () => {
410
229
  if (!cachedSourceHash) {
411
230
  cachedSourceHash = calculateSourceFilesHash(options.sourceDirs);
412
231
  }
413
232
  return cachedSourceHash;
414
233
  };
415
- var cleanCache = function () {
416
- var e_7, _a;
417
- try {
418
- for (var _b = __values([CACHED_DATA_FILE, CACHED_COLLECTIONS_FILE, HASH_FILE]), _c = _b.next(); !_c.done; _c = _b.next()) {
419
- var file = _c.value;
420
- var filePath = path.join(options.cacheDir, file);
421
- if (fs.existsSync(filePath)) {
422
- fs.unlinkSync(filePath);
423
- }
424
- }
425
- }
426
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
427
- finally {
428
- try {
429
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
234
+ const cleanCache = () => {
235
+ for (const file of [CACHED_DATA_FILE, CACHED_COLLECTIONS_FILE, HASH_FILE]) {
236
+ const filePath = path.join(options.cacheDir, file);
237
+ if (fs.existsSync(filePath)) {
238
+ fs.unlinkSync(filePath);
430
239
  }
431
- finally { if (e_7) throw e_7.error; }
432
240
  }
433
241
  cachedCollectionsInMemory = null;
434
242
  cachedSourceHash = null;
435
243
  };
436
- var setupTestCache = function () {
437
- var args_1 = [];
438
- for (var _i = 0; _i < arguments.length; _i++) {
439
- args_1[_i] = arguments[_i];
244
+ const setupTestCache = async ({ force = false } = {}) => {
245
+ const currentHash = calculateSourceFilesHash(options.sourceDirs);
246
+ const savedHash = getSavedHash(options.cacheDir);
247
+ if (!force && savedHash === currentHash && cacheFilesExist(options.cacheDir)) {
248
+ return;
440
249
  }
441
- return __awaiter(void 0, __spreadArray([], __read(args_1), false), void 0, function (_a) {
442
- var currentHash, savedHash, isAlreadyConnected, cachedData, cachedCollections, _b, _c, collectionName, collection, docs, e_8_1;
443
- var e_8, _d;
444
- var _e = _a === void 0 ? {} : _a, _f = _e.force, force = _f === void 0 ? false : _f;
445
- return __generator(this, function (_g) {
446
- switch (_g.label) {
447
- case 0:
448
- currentHash = calculateSourceFilesHash(options.sourceDirs);
449
- savedHash = getSavedHash(options.cacheDir);
450
- if (!force && savedHash === currentHash && cacheFilesExist(options.cacheDir)) {
451
- return [2 /*return*/];
452
- }
453
- isAlreadyConnected = mongoose_1.default.connection.readyState === 1;
454
- if (!!isAlreadyConnected) return [3 /*break*/, 3];
455
- return [4 /*yield*/, (0, mongoServer_1.startMongoServer)({ baseDatabaseName: baseDatabaseName, publishedUriEnvVar: publishedUriEnvVar, useReplSet: true })];
456
- case 1:
457
- _g.sent();
458
- return [4 /*yield*/, (0, mongoServer_1.waitForDatabaseReady)()];
459
- case 2:
460
- _g.sent();
461
- _g.label = 3;
462
- case 3: return [4 /*yield*/, options.createTestData()];
463
- case 4:
464
- cachedData = _g.sent();
465
- cachedCollections = {};
466
- _g.label = 5;
467
- case 5:
468
- _g.trys.push([5, 10, 11, 12]);
469
- _b = __values(Object.keys(mongoose_1.default.connection.collections)), _c = _b.next();
470
- _g.label = 6;
471
- case 6:
472
- if (!!_c.done) return [3 /*break*/, 9];
473
- collectionName = _c.value;
474
- collection = mongoose_1.default.connection.collections[collectionName];
475
- return [4 /*yield*/, collection.find({}).toArray()];
476
- case 7:
477
- docs = _g.sent();
478
- cachedCollections[collectionName] = docs.map(function (doc) { return JSON.parse(JSON.stringify(doc)); });
479
- _g.label = 8;
480
- case 8:
481
- _c = _b.next();
482
- return [3 /*break*/, 6];
483
- case 9: return [3 /*break*/, 12];
484
- case 10:
485
- e_8_1 = _g.sent();
486
- e_8 = { error: e_8_1 };
487
- return [3 /*break*/, 12];
488
- case 11:
489
- try {
490
- if (_c && !_c.done && (_d = _b.return)) _d.call(_b);
491
- }
492
- finally { if (e_8) throw e_8.error; }
493
- return [7 /*endfinally*/];
494
- case 12:
495
- fs.mkdirSync(options.cacheDir, { recursive: true });
496
- fs.writeFileSync(path.join(options.cacheDir, CACHED_DATA_FILE), JSON.stringify(cachedData));
497
- fs.writeFileSync(path.join(options.cacheDir, CACHED_COLLECTIONS_FILE), JSON.stringify(cachedCollections));
498
- saveHash(options.cacheDir, currentHash);
499
- cachedCollectionsInMemory = cachedCollections;
500
- testLogger_1.testLogger.info("[mongoTestCache] Test data cached to ".concat(options.cacheDir));
501
- return [2 /*return*/];
502
- }
503
- });
504
- });
250
+ const isAlreadyConnected = mongoose_1.default.connection.readyState === 1;
251
+ if (!isAlreadyConnected) {
252
+ await (0, mongoServer_1.startMongoServer)({ baseDatabaseName, publishedUriEnvVar, useReplSet: true });
253
+ await (0, mongoServer_1.waitForDatabaseReady)();
254
+ }
255
+ const cachedData = await options.createTestData();
256
+ const cachedCollections = {};
257
+ for (const collectionName of Object.keys(mongoose_1.default.connection.collections)) {
258
+ const collection = mongoose_1.default.connection.collections[collectionName];
259
+ const docs = await collection.find({}).toArray();
260
+ cachedCollections[collectionName] = docs.map((doc) => JSON.parse(JSON.stringify(doc)));
261
+ }
262
+ fs.mkdirSync(options.cacheDir, { recursive: true });
263
+ fs.writeFileSync(path.join(options.cacheDir, CACHED_DATA_FILE), JSON.stringify(cachedData));
264
+ fs.writeFileSync(path.join(options.cacheDir, CACHED_COLLECTIONS_FILE), JSON.stringify(cachedCollections));
265
+ saveHash(options.cacheDir, currentHash);
266
+ cachedCollectionsInMemory = cachedCollections;
267
+ testLogger_1.testLogger.info(`[mongoTestCache] Test data cached to ${options.cacheDir}`);
505
268
  };
506
- var loadTestDataFromCache = function () { return __awaiter(void 0, void 0, void 0, function () {
507
- var cachedFilePath, currentHash, savedHash, cacheValid;
508
- return __generator(this, function (_a) {
509
- switch (_a.label) {
510
- case 0:
511
- fs.mkdirSync(options.cacheDir, { recursive: true });
512
- cachedFilePath = path.join(options.cacheDir, CACHED_COLLECTIONS_FILE);
513
- currentHash = getSourceHash();
514
- savedHash = getSavedHash(options.cacheDir);
515
- cacheValid = cacheFilesExist(options.cacheDir) && savedHash === currentHash;
516
- if (!!cacheValid) return [3 /*break*/, 2];
517
- if (!inflightSetupTestCache) {
518
- inflightSetupTestCache = setupTestCache().finally(function () {
519
- inflightSetupTestCache = null;
520
- });
521
- }
522
- // Wrapped because the `finally` above clears the shared slot once it settles.
523
- return [4 /*yield*/, Promise.resolve(inflightSetupTestCache)];
524
- case 1:
525
- // Wrapped because the `finally` above clears the shared slot once it settles.
526
- _a.sent();
527
- _a.label = 2;
528
- case 2:
529
- if (!cachedCollectionsInMemory) {
530
- cachedCollectionsInMemory = JSON.parse(fs.readFileSync(cachedFilePath, "utf-8"));
531
- }
532
- if (!cachedCollectionsInMemory) {
533
- throw new Error("[mongoTestCache] Cached collections were not loaded");
534
- }
535
- return [4 /*yield*/, ensureConnectionReady(publishedUriEnvVar, baseDatabaseName)];
536
- case 3:
537
- _a.sent();
538
- return [4 /*yield*/, loadTestDataIntoDb(cachedCollectionsInMemory)];
539
- case 4:
540
- _a.sent();
541
- return [2 /*return*/];
269
+ const loadTestDataFromCache = async () => {
270
+ fs.mkdirSync(options.cacheDir, { recursive: true });
271
+ const cachedFilePath = path.join(options.cacheDir, CACHED_COLLECTIONS_FILE);
272
+ const currentHash = getSourceHash();
273
+ const savedHash = getSavedHash(options.cacheDir);
274
+ const cacheValid = cacheFilesExist(options.cacheDir) && savedHash === currentHash;
275
+ if (!cacheValid) {
276
+ if (!inflightSetupTestCache) {
277
+ inflightSetupTestCache = setupTestCache().finally(() => {
278
+ inflightSetupTestCache = null;
279
+ });
542
280
  }
543
- });
544
- }); };
281
+ // Wrapped because the `finally` above clears the shared slot once it settles.
282
+ await Promise.resolve(inflightSetupTestCache);
283
+ }
284
+ if (!cachedCollectionsInMemory) {
285
+ cachedCollectionsInMemory = JSON.parse(fs.readFileSync(cachedFilePath, "utf-8"));
286
+ }
287
+ if (!cachedCollectionsInMemory) {
288
+ throw new Error("[mongoTestCache] Cached collections were not loaded");
289
+ }
290
+ await ensureConnectionReady(publishedUriEnvVar, baseDatabaseName);
291
+ await loadTestDataIntoDb(cachedCollectionsInMemory);
292
+ };
545
293
  return {
546
- cacheFilesExist: function () { return cacheFilesExist(options.cacheDir); },
547
- cleanCache: cleanCache,
548
- loadTestDataFromCache: loadTestDataFromCache,
549
- setupTestCache: setupTestCache,
294
+ cacheFilesExist: () => cacheFilesExist(options.cacheDir),
295
+ cleanCache,
296
+ loadTestDataFromCache,
297
+ setupTestCache,
550
298
  };
551
299
  };
552
300
  exports.createMongoTestCache = createMongoTestCache;