mongodb-memory-server-core 8.15.0 → 9.0.0-beta.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 (51) hide show
  1. package/lib/MongoMemoryReplSet.d.ts +3 -19
  2. package/lib/MongoMemoryReplSet.d.ts.map +1 -1
  3. package/lib/MongoMemoryReplSet.js +283 -294
  4. package/lib/MongoMemoryReplSet.js.map +1 -1
  5. package/lib/MongoMemoryServer.d.ts +13 -26
  6. package/lib/MongoMemoryServer.d.ts.map +1 -1
  7. package/lib/MongoMemoryServer.js +323 -333
  8. package/lib/MongoMemoryServer.js.map +1 -1
  9. package/lib/util/DryMongoBinary.d.ts +1 -1
  10. package/lib/util/DryMongoBinary.d.ts.map +1 -1
  11. package/lib/util/DryMongoBinary.js +158 -172
  12. package/lib/util/DryMongoBinary.js.map +1 -1
  13. package/lib/util/MongoBinary.js +85 -85
  14. package/lib/util/MongoBinary.js.map +1 -1
  15. package/lib/util/MongoBinaryDownload.d.ts +2 -11
  16. package/lib/util/MongoBinaryDownload.d.ts.map +1 -1
  17. package/lib/util/MongoBinaryDownload.js +210 -262
  18. package/lib/util/MongoBinaryDownload.js.map +1 -1
  19. package/lib/util/MongoBinaryDownloadUrl.d.ts +3 -5
  20. package/lib/util/MongoBinaryDownloadUrl.d.ts.map +1 -1
  21. package/lib/util/MongoBinaryDownloadUrl.js +67 -94
  22. package/lib/util/MongoBinaryDownloadUrl.js.map +1 -1
  23. package/lib/util/MongoInstance.d.ts +3 -1
  24. package/lib/util/MongoInstance.d.ts.map +1 -1
  25. package/lib/util/MongoInstance.js +125 -126
  26. package/lib/util/MongoInstance.js.map +1 -1
  27. package/lib/util/errors.d.ts +10 -9
  28. package/lib/util/errors.d.ts.map +1 -1
  29. package/lib/util/errors.js +16 -27
  30. package/lib/util/errors.js.map +1 -1
  31. package/lib/util/getos/index.d.ts +1 -1
  32. package/lib/util/getos/index.d.ts.map +1 -1
  33. package/lib/util/getos/index.js +53 -59
  34. package/lib/util/getos/index.js.map +1 -1
  35. package/lib/util/getport/index.d.ts +34 -0
  36. package/lib/util/getport/index.d.ts.map +1 -0
  37. package/lib/util/getport/index.js +108 -0
  38. package/lib/util/getport/index.js.map +1 -0
  39. package/lib/util/lockfile.d.ts.map +1 -1
  40. package/lib/util/lockfile.js +155 -169
  41. package/lib/util/lockfile.js.map +1 -1
  42. package/lib/util/postinstallHelper.js +15 -18
  43. package/lib/util/postinstallHelper.js.map +1 -1
  44. package/lib/util/resolveConfig.d.ts.map +1 -1
  45. package/lib/util/resolveConfig.js +9 -8
  46. package/lib/util/resolveConfig.js.map +1 -1
  47. package/lib/util/utils.d.ts +20 -4
  48. package/lib/util/utils.d.ts.map +1 -1
  49. package/lib/util/utils.js +135 -118
  50. package/lib/util/utils.js.map +1 -1
  51. package/package.json +8 -12
@@ -5,7 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const events_1 = require("events");
6
6
  const MongoMemoryServer_1 = require("./MongoMemoryServer");
7
7
  const utils_1 = require("./util/utils");
8
- const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
8
+ const debug_1 = tslib_1.__importDefault(require("debug"));
9
9
  const mongodb_1 = require("mongodb");
10
10
  const MongoInstance_1 = require("./util/MongoInstance");
11
11
  const errors_1 = require("./util/errors");
@@ -33,7 +33,6 @@ var MongoMemoryReplSetEvents;
33
33
  */
34
34
  class MongoMemoryReplSet extends events_1.EventEmitter {
35
35
  constructor(opts = {}) {
36
- var _a;
37
36
  super();
38
37
  /**
39
38
  * All servers this ReplSet instance manages
@@ -41,9 +40,9 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
41
40
  this.servers = [];
42
41
  this._state = MongoMemoryReplSetStates.stopped;
43
42
  this._ranCreateAuth = false;
44
- this.binaryOpts = Object.assign({}, opts.binary);
45
- this.instanceOpts = (_a = opts.instanceOpts) !== null && _a !== void 0 ? _a : [];
46
- this.replSetOpts = Object.assign({}, opts.replSet);
43
+ this.binaryOpts = { ...opts.binary };
44
+ this.instanceOpts = opts.instanceOpts ?? [];
45
+ this.replSetOpts = { ...opts.replSet };
47
46
  }
48
47
  /**
49
48
  * Change "this._state" to "newState" and emit "newState"
@@ -57,13 +56,11 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
57
56
  * Create an instance of "MongoMemoryReplSet" and call start
58
57
  * @param opts Options for the ReplSet
59
58
  */
60
- static create(opts) {
61
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
62
- log('create: Called .create() method');
63
- const replSet = new this(Object.assign({}, opts));
64
- yield replSet.start();
65
- return replSet;
66
- });
59
+ static async create(opts) {
60
+ log('create: Called .create() method');
61
+ const replSet = new this({ ...opts });
62
+ await replSet.start();
63
+ return replSet;
67
64
  }
68
65
  /**
69
66
  * Get Current state of this class
@@ -104,7 +101,7 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
104
101
  set replSetOpts(val) {
105
102
  assertionIsMMSRSState(MongoMemoryReplSetStates.stopped, this._state);
106
103
  const defaults = {
107
- auth: false,
104
+ auth: { enable: false },
108
105
  args: [],
109
106
  name: 'testset',
110
107
  count: 1,
@@ -114,14 +111,10 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
114
111
  storageEngine: 'ephemeralForTest',
115
112
  configSettings: {},
116
113
  };
117
- this._replSetOpts = Object.assign(Object.assign({}, defaults), val);
114
+ this._replSetOpts = { ...defaults, ...val };
118
115
  (0, utils_1.assertion)(this._replSetOpts.count > 0, new errors_1.ReplsetCountLowError(this._replSetOpts.count));
119
- // setting this for sanity
120
- if (typeof this._replSetOpts.auth === 'boolean') {
121
- this._replSetOpts.auth = { disable: !this._replSetOpts.auth };
122
- }
123
- // do not set default when "disable" is "true" to save execution and memory
124
- if (!this._replSetOpts.auth.disable) {
116
+ // only set default is enabled
117
+ if (this._replSetOpts.auth.enable) {
125
118
  this._replSetOpts.auth = (0, utils_1.authDefault)(this._replSetOpts.auth);
126
119
  }
127
120
  }
@@ -135,9 +128,9 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
135
128
  return false;
136
129
  }
137
130
  (0, utils_1.assertion)(typeof this._replSetOpts.auth === 'object', new errors_1.AuthNotObjectError());
138
- return typeof this._replSetOpts.auth.disable === 'boolean' // if "this._replSetOpts.auth.disable" is defined, use that
139
- ? !this._replSetOpts.auth.disable // invert the disable boolean, because "auth" should only be disabled if "disabled = true"
140
- : true; // if "this._replSetOpts.auth.disable" is not defined, default to true because "this._replSetOpts.auth" is defined
131
+ return typeof this._replSetOpts.auth.enable === 'boolean' // if "this._replSetOpts.auth.enable" is defined, use that
132
+ ? this._replSetOpts.auth.enable
133
+ : false; // if "this._replSetOpts.auth.enable" is not defined, default to false
141
134
  }
142
135
  /**
143
136
  * Returns instance options suitable for a MongoMemoryServer.
@@ -198,8 +191,7 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
198
191
  }
199
192
  const hosts = this.servers
200
193
  .map((s) => {
201
- var _a;
202
- const port = (_a = s.instanceInfo) === null || _a === void 0 ? void 0 : _a.port;
194
+ const port = s.instanceInfo?.port;
203
195
  (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(port), new Error('Instance Port is undefined!'));
204
196
  const ip = otherIp || '127.0.0.1';
205
197
  return `${ip}:${port}`;
@@ -213,205 +205,201 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
213
205
  * Start underlying `mongod` instances.
214
206
  * @throws if state is already "running"
215
207
  */
216
- start() {
217
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
218
- log('start:', this.state);
219
- switch (this.state) {
220
- case MongoMemoryReplSetStates.stopped:
221
- break;
222
- case MongoMemoryReplSetStates.running:
223
- default:
224
- throw new errors_1.StateError([MongoMemoryReplSetStates.stopped], this.state);
208
+ async start() {
209
+ log('start:', this.state);
210
+ switch (this.state) {
211
+ case MongoMemoryReplSetStates.stopped:
212
+ break;
213
+ case MongoMemoryReplSetStates.running:
214
+ default:
215
+ throw new errors_1.StateError([MongoMemoryReplSetStates.stopped], this.state);
216
+ }
217
+ this.stateChange(MongoMemoryReplSetStates.init); // this needs to be executed before "setImmediate"
218
+ await (0, utils_1.ensureAsync)()
219
+ .then(() => this.initAllServers())
220
+ .then(() => this._initReplSet())
221
+ .catch(async (err) => {
222
+ if (!debug_1.default.enabled('MongoMS:MongoMemoryReplSet')) {
223
+ console.warn('Starting the MongoMemoryReplSet Instance failed, enable debug log for more information. Error:\n', err);
225
224
  }
226
- this.stateChange(MongoMemoryReplSetStates.init); // this needs to be executed before "setImmediate"
227
- yield (0, utils_1.ensureAsync)()
228
- .then(() => this.initAllServers())
229
- .then(() => this._initReplSet())
230
- .catch((err) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
231
- if (!debug_1.default.enabled('MongoMS:MongoMemoryReplSet')) {
232
- console.warn('Starting the MongoMemoryReplSet Instance failed, enable debug log for more information. Error:\n', err);
233
- }
234
- log('ensureAsync chain threw a Error: ', err);
235
- yield this.stop({ doCleanup: false, force: false }); // still try to close the instance that was spawned, without cleanup for investigation
236
- this.stateChange(MongoMemoryReplSetStates.stopped);
237
- throw err;
238
- }));
225
+ log('ensureAsync chain threw a Error: ', err);
226
+ await this.stop({ doCleanup: false, force: false }); // still try to close the instance that was spawned, without cleanup for investigation
227
+ this.stateChange(MongoMemoryReplSetStates.stopped);
228
+ throw err;
239
229
  });
240
230
  }
241
231
  /**
242
232
  * Initialize & start all servers in the replSet
243
233
  */
244
- initAllServers() {
245
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
246
- log('initAllServers');
247
- this.stateChange(MongoMemoryReplSetStates.init);
248
- if (this.servers.length > 0) {
249
- log('initAllServers: lenght of "servers" is higher than 0, starting existing servers');
250
- if (this._ranCreateAuth) {
251
- log('initAllServers: "_ranCreateAuth" is true, re-using auth');
252
- const keyfilepath = (0, path_1.resolve)(yield this.ensureKeyFile(), 'keyfile');
253
- for (const server of this.servers) {
254
- (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(server.instanceInfo), new errors_1.InstanceInfoError('MongoMemoryReplSet.initAllServers'));
255
- (0, utils_1.assertion)(typeof this._replSetOpts.auth === 'object', new errors_1.AuthNotObjectError());
256
- server.instanceInfo.instance.instanceOpts.auth = true;
257
- server.instanceInfo.instance.instanceOpts.keyfileLocation = keyfilepath;
258
- server.instanceInfo.instance.extraConnectionOptions = {
259
- authSource: 'admin',
260
- authMechanism: 'SCRAM-SHA-256',
261
- auth: {
262
- username: this._replSetOpts.auth.customRootName,
263
- password: this._replSetOpts.auth.customRootPwd,
264
- },
265
- };
266
- }
234
+ async initAllServers() {
235
+ log('initAllServers');
236
+ this.stateChange(MongoMemoryReplSetStates.init);
237
+ if (this.servers.length > 0) {
238
+ log('initAllServers: lenght of "servers" is higher than 0, starting existing servers');
239
+ if (this._ranCreateAuth) {
240
+ log('initAllServers: "_ranCreateAuth" is true, re-using auth');
241
+ const keyfilepath = (0, path_1.resolve)(await this.ensureKeyFile(), 'keyfile');
242
+ for (const server of this.servers) {
243
+ (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(server.instanceInfo), new errors_1.InstanceInfoError('MongoMemoryReplSet.initAllServers'));
244
+ (0, utils_1.assertion)(typeof this._replSetOpts.auth === 'object', new errors_1.AuthNotObjectError());
245
+ server.instanceInfo.instance.instanceOpts.auth = true;
246
+ server.instanceInfo.instance.instanceOpts.keyfileLocation = keyfilepath;
247
+ server.instanceInfo.instance.extraConnectionOptions = {
248
+ authSource: 'admin',
249
+ authMechanism: 'SCRAM-SHA-256',
250
+ auth: {
251
+ username: this._replSetOpts.auth.customRootName,
252
+ password: this._replSetOpts.auth.customRootPwd,
253
+ },
254
+ };
267
255
  }
268
- yield Promise.all(this.servers.map((s) => s.start(true)));
269
- log('initAllServers: finished starting existing instances again');
270
- return;
271
256
  }
272
- let keyfilePath = undefined;
273
- if (this.enableAuth()) {
274
- keyfilePath = (0, path_1.resolve)(yield this.ensureKeyFile(), 'keyfile');
275
- }
276
- // Any servers defined within `_instanceOpts` should be started first as
277
- // the user could have specified a `dbPath` in which case we would want to perform
278
- // the `replSetInitiate` command against that server.
279
- this._instanceOpts.forEach((opts, index) => {
280
- log(`initAllServers: starting special server "${index + 1}" of "${this._instanceOpts.length}" from instanceOpts (count: ${this.servers.length + 1}):`, opts);
281
- this.servers.push(this._initServer(this.getInstanceOpts(opts, keyfilePath)));
282
- });
283
- while (this.servers.length < this._replSetOpts.count) {
284
- log(`initAllServers: starting extra server "${this.servers.length + 1}" of "${this._replSetOpts.count}" (count: ${this.servers.length + 1})`);
285
- this.servers.push(this._initServer(this.getInstanceOpts(undefined, keyfilePath)));
286
- }
287
- log('initAllServers: waiting for all servers to finish starting');
288
- // ensures all servers are listening for connection
289
- yield Promise.all(this.servers.map((s) => s.start()));
290
- log('initAllServers: finished starting all servers initially');
257
+ await Promise.all(this.servers.map((s) => s.start(true)));
258
+ log('initAllServers: finished starting existing instances again');
259
+ return;
260
+ }
261
+ let keyfilePath = undefined;
262
+ if (this.enableAuth()) {
263
+ keyfilePath = (0, path_1.resolve)(await this.ensureKeyFile(), 'keyfile');
264
+ }
265
+ // Any servers defined within `_instanceOpts` should be started first as
266
+ // the user could have specified a `dbPath` in which case we would want to perform
267
+ // the `replSetInitiate` command against that server.
268
+ this._instanceOpts.forEach((opts, index) => {
269
+ log(`initAllServers: starting special server "${index + 1}" of "${this._instanceOpts.length}" from instanceOpts (count: ${this.servers.length + 1}):`, opts);
270
+ this.servers.push(this._initServer(this.getInstanceOpts(opts, keyfilePath)));
291
271
  });
272
+ while (this.servers.length < this._replSetOpts.count) {
273
+ log(`initAllServers: starting extra server "${this.servers.length + 1}" of "${this._replSetOpts.count}" (count: ${this.servers.length + 1})`);
274
+ this.servers.push(this._initServer(this.getInstanceOpts(undefined, keyfilePath)));
275
+ }
276
+ log('initAllServers: waiting for all servers to finish starting');
277
+ // ensures all servers are listening for connection
278
+ await Promise.all(this.servers.map((s) => s.start()));
279
+ log('initAllServers: finished starting all servers initially');
292
280
  }
293
281
  /**
294
282
  * Ensure "_keyfiletmp" is defined
295
283
  * @returns the ensured "_keyfiletmp" value
296
284
  */
297
- ensureKeyFile() {
298
- var _a;
299
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
300
- log('ensureKeyFile');
301
- if ((0, utils_1.isNullOrUndefined)(this._keyfiletmp)) {
302
- this._keyfiletmp = yield (0, utils_1.createTmpDir)('mongo-mem-keyfile-');
303
- }
304
- const keyfilepath = (0, path_1.resolve)(this._keyfiletmp, 'keyfile');
305
- // if path does not exist or have no access, create it (or fail)
306
- if (!(yield (0, utils_1.statPath)(keyfilepath))) {
307
- log('ensureKeyFile: creating Keyfile');
308
- (0, utils_1.assertion)(typeof this._replSetOpts.auth === 'object', new errors_1.AuthNotObjectError());
309
- yield fs_1.promises.writeFile((0, path_1.resolve)(this._keyfiletmp, 'keyfile'), (_a = this._replSetOpts.auth.keyfileContent) !== null && _a !== void 0 ? _a : '0123456789', { mode: 0o700 } // this is because otherwise mongodb errors with "permissions are too open" on unix systems
310
- );
311
- }
312
- return this._keyfiletmp;
313
- });
285
+ async ensureKeyFile() {
286
+ log('ensureKeyFile');
287
+ if ((0, utils_1.isNullOrUndefined)(this._keyfiletmp)) {
288
+ this._keyfiletmp = await (0, utils_1.createTmpDir)('mongo-mem-keyfile-');
289
+ }
290
+ const keyfilepath = (0, path_1.resolve)(this._keyfiletmp, 'keyfile');
291
+ // if path does not exist or have no access, create it (or fail)
292
+ if (!(await (0, utils_1.statPath)(keyfilepath))) {
293
+ log('ensureKeyFile: creating Keyfile');
294
+ (0, utils_1.assertion)(typeof this._replSetOpts.auth === 'object', new errors_1.AuthNotObjectError());
295
+ await fs_1.promises.writeFile((0, path_1.resolve)(this._keyfiletmp, 'keyfile'), this._replSetOpts.auth.keyfileContent ?? '0123456789', { mode: 0o700 } // this is because otherwise mongodb errors with "permissions are too open" on unix systems
296
+ );
297
+ }
298
+ return this._keyfiletmp;
314
299
  }
315
- stop(cleanupOptions) {
316
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
317
- log(`stop: called by ${(0, utils_1.isNullOrUndefined)(process.exitCode) ? 'manual' : 'process exit'}`);
318
- /** Default to cleanup temporary, but not custom dbpaths */
319
- let cleanup = { doCleanup: true, force: false };
320
- // handle the old way of setting wheter to cleanup or not
321
- // TODO: for next major release (9.0), this should be removed
322
- if (typeof cleanupOptions === 'boolean') {
323
- cleanup.doCleanup = cleanupOptions;
324
- }
325
- // handle the new way of setting what and how to cleanup
326
- if (typeof cleanupOptions === 'object') {
327
- cleanup = cleanupOptions;
328
- }
329
- if (this._state === MongoMemoryReplSetStates.stopped) {
330
- log('stop: state is "stopped", trying to stop / kill anyway');
331
- }
332
- const successfullyStopped = yield Promise.all(this.servers.map((s) => s.stop({ doCleanup: false, force: false })))
333
- .then(() => {
334
- this.stateChange(MongoMemoryReplSetStates.stopped);
335
- return true;
336
- })
337
- .catch((err) => {
338
- log('stop:', err);
339
- this.stateChange(MongoMemoryReplSetStates.stopped, err);
340
- return false;
341
- });
342
- // return early if the instances failed to stop
343
- if (!successfullyStopped) {
344
- return false;
345
- }
346
- if (cleanup.doCleanup) {
347
- yield this.cleanup(cleanup);
348
- }
300
+ /**
301
+ * Stop the underlying `mongod` instance(s).
302
+ * @param cleanupOptions Set how to run ".cleanup", by default only `{ doCleanup: true }` is used
303
+ */
304
+ async stop(cleanupOptions) {
305
+ log(`stop: called by ${(0, utils_1.isNullOrUndefined)(process.exitCode) ? 'manual' : 'process exit'}`);
306
+ /** Default to cleanup temporary, but not custom dbpaths */
307
+ let cleanup = { doCleanup: true, force: false };
308
+ // TODO: for next major release (10.0), this should be removed
309
+ if (typeof cleanupOptions === 'boolean') {
310
+ throw new Error('Unsupported argument type: boolean');
311
+ }
312
+ // handle the new way of setting what and how to cleanup
313
+ if (typeof cleanupOptions === 'object') {
314
+ cleanup = cleanupOptions;
315
+ }
316
+ if (this._state === MongoMemoryReplSetStates.stopped) {
317
+ log('stop: state is "stopped", trying to stop / kill anyway');
318
+ }
319
+ const successfullyStopped = await Promise.all(this.servers.map((s) => s.stop({ doCleanup: false, force: false })))
320
+ .then(() => {
321
+ this.stateChange(MongoMemoryReplSetStates.stopped);
349
322
  return true;
323
+ })
324
+ .catch((err) => {
325
+ log('stop:', err);
326
+ this.stateChange(MongoMemoryReplSetStates.stopped, err);
327
+ return false;
350
328
  });
329
+ // return early if the instances failed to stop
330
+ if (!successfullyStopped) {
331
+ return false;
332
+ }
333
+ if (cleanup.doCleanup) {
334
+ await this.cleanup(cleanup);
335
+ }
336
+ return true;
351
337
  }
352
- cleanup(options) {
353
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
354
- assertionIsMMSRSState(MongoMemoryReplSetStates.stopped, this._state);
355
- log(`cleanup for "${this.servers.length}" servers`);
356
- /** Default to doing cleanup, but not forcing it */
357
- let cleanup = { doCleanup: true, force: false };
358
- // handle the old way of setting wheter to cleanup or not
359
- // TODO: for next major release (9.0), this should be removed
360
- if (typeof options === 'boolean') {
361
- cleanup.force = options;
362
- }
363
- // handle the new way of setting what and how to cleanup
364
- if (typeof options === 'object') {
365
- cleanup = options;
366
- }
367
- log(`cleanup:`, cleanup);
368
- // dont do cleanup, if "doCleanup" is false
369
- if (!cleanup.doCleanup) {
370
- log('cleanup: "doCleanup" is set to false');
371
- return;
372
- }
373
- yield Promise.all(this.servers.map((s) => s.cleanup(cleanup)));
374
- // cleanup the keyfile tmpdir
375
- if (!(0, utils_1.isNullOrUndefined)(this._keyfiletmp)) {
376
- yield (0, utils_1.removeDir)(this._keyfiletmp);
377
- this._keyfiletmp = undefined;
378
- }
379
- this.servers = [];
380
- this._ranCreateAuth = false;
338
+ /**
339
+ * Remove the defined dbPath's
340
+ * @param options Set how to run a cleanup, by default `{ doCleanup: true }` is used
341
+ * @throws If "state" is not "stopped"
342
+ * @throws If "instanceInfo" is not defined
343
+ * @throws If an fs error occured
344
+ */
345
+ async cleanup(options) {
346
+ assertionIsMMSRSState(MongoMemoryReplSetStates.stopped, this._state);
347
+ log(`cleanup for "${this.servers.length}" servers`);
348
+ /** Default to doing cleanup, but not forcing it */
349
+ let cleanup = { doCleanup: true, force: false };
350
+ // TODO: for next major release (10.0), this should be removed
351
+ if (typeof options === 'boolean') {
352
+ throw new Error('Unsupported argument type: boolean');
353
+ }
354
+ // handle the new way of setting what and how to cleanup
355
+ if (typeof options === 'object') {
356
+ cleanup = options;
357
+ }
358
+ log(`cleanup:`, cleanup);
359
+ // dont do cleanup, if "doCleanup" is false
360
+ if (!cleanup.doCleanup) {
361
+ log('cleanup: "doCleanup" is set to false');
381
362
  return;
382
- });
363
+ }
364
+ await Promise.all(this.servers.map((s) => s.cleanup(cleanup)));
365
+ // cleanup the keyfile tmpdir
366
+ if (!(0, utils_1.isNullOrUndefined)(this._keyfiletmp)) {
367
+ await (0, utils_1.removeDir)(this._keyfiletmp);
368
+ this._keyfiletmp = undefined;
369
+ }
370
+ this.servers = [];
371
+ this._ranCreateAuth = false;
372
+ return;
383
373
  }
384
374
  /**
385
375
  * Wait until all instances are running
386
376
  * @throws if state is "stopped" (cannot wait on something that dosnt start)
387
377
  */
388
- waitUntilRunning() {
389
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
390
- yield (0, utils_1.ensureAsync)();
391
- log('waitUntilRunning:', this._state);
392
- switch (this._state) {
393
- case MongoMemoryReplSetStates.running:
394
- // just return immediatly if the replSet is already running
395
- return;
396
- case MongoMemoryReplSetStates.init:
397
- // wait for event "running"
398
- yield new Promise((res) => {
399
- // the use of "this" here can be done because "on" either binds "this" or uses an arrow function
400
- function waitRunning(state) {
401
- // this is because other states can be emitted multiple times (like stopped & init for auth creation)
402
- if (state === MongoMemoryReplSetStates.running) {
403
- this.removeListener(MongoMemoryReplSetEvents.stateChange, waitRunning);
404
- res();
405
- }
378
+ async waitUntilRunning() {
379
+ await (0, utils_1.ensureAsync)();
380
+ log('waitUntilRunning:', this._state);
381
+ switch (this._state) {
382
+ case MongoMemoryReplSetStates.running:
383
+ // just return immediatly if the replSet is already running
384
+ return;
385
+ case MongoMemoryReplSetStates.init:
386
+ // wait for event "running"
387
+ await new Promise((res) => {
388
+ // the use of "this" here can be done because "on" either binds "this" or uses an arrow function
389
+ function waitRunning(state) {
390
+ // this is because other states can be emitted multiple times (like stopped & init for auth creation)
391
+ if (state === MongoMemoryReplSetStates.running) {
392
+ this.removeListener(MongoMemoryReplSetEvents.stateChange, waitRunning);
393
+ res();
406
394
  }
407
- this.on(MongoMemoryReplSetEvents.stateChange, waitRunning);
408
- });
409
- return;
410
- case MongoMemoryReplSetStates.stopped:
411
- default:
412
- throw new errors_1.StateError([MongoMemoryReplSetStates.running, MongoMemoryReplSetStates.init], this.state);
413
- }
414
- });
395
+ }
396
+ this.on(MongoMemoryReplSetEvents.stateChange, waitRunning);
397
+ });
398
+ return;
399
+ case MongoMemoryReplSetStates.stopped:
400
+ default:
401
+ throw new errors_1.StateError([MongoMemoryReplSetStates.running, MongoMemoryReplSetStates.init], this.state);
402
+ }
415
403
  }
416
404
  /**
417
405
  * Connects to the first server from the list of servers and issues the `replSetInitiate`
@@ -420,75 +408,78 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
420
408
  * @throws if "servers.length" is not 1 or above
421
409
  * @throws if package "mongodb" is not installed
422
410
  */
423
- _initReplSet() {
424
- var _a, _b, _c;
425
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
426
- log('_initReplSet');
427
- assertionIsMMSRSState(MongoMemoryReplSetStates.init, this._state);
428
- (0, utils_1.assertion)(this.servers.length > 0, new Error('One or more servers are required.'));
429
- const uris = this.servers.map((server) => server.getUri());
430
- const isInMemory = ((_a = this.servers[0].instanceInfo) === null || _a === void 0 ? void 0 : _a.storageEngine) === 'ephemeralForTest';
431
- const extraOptions = this._ranCreateAuth
432
- ? (_c = (_b = this.servers[0].instanceInfo) === null || _b === void 0 ? void 0 : _b.instance.extraConnectionOptions) !== null && _c !== void 0 ? _c : {}
433
- : {};
434
- const con = yield mongodb_1.MongoClient.connect(uris[0], Object.assign({
435
- // somehow since mongodb-nodejs 4.0, this option is needed when the server is set to be in a replset
436
- directConnection: true }, extraOptions));
437
- log('_initReplSet: connected');
438
- // try-finally to close connection in any case
411
+ async _initReplSet() {
412
+ log('_initReplSet');
413
+ assertionIsMMSRSState(MongoMemoryReplSetStates.init, this._state);
414
+ (0, utils_1.assertion)(this.servers.length > 0, new Error('One or more servers are required.'));
415
+ const uris = this.servers.map((server) => server.getUri());
416
+ const isInMemory = this.servers[0].instanceInfo?.storageEngine === 'ephemeralForTest';
417
+ const extraOptions = this._ranCreateAuth
418
+ ? this.servers[0].instanceInfo?.instance.extraConnectionOptions ?? {}
419
+ : {};
420
+ const con = await mongodb_1.MongoClient.connect(uris[0], {
421
+ // somehow since mongodb-nodejs 4.0, this option is needed when the server is set to be in a replset
422
+ directConnection: true,
423
+ ...extraOptions,
424
+ });
425
+ log('_initReplSet: connected');
426
+ // try-finally to close connection in any case
427
+ try {
428
+ const adminDb = con.db('admin');
429
+ const members = uris.map((uri, index) => ({
430
+ _id: index,
431
+ host: (0, utils_1.getHost)(uri),
432
+ ...(this.servers[index].opts.instance?.replicaMemberConfig || {}), // Overwrite replica member config
433
+ }));
434
+ const rsConfig = {
435
+ _id: this._replSetOpts.name,
436
+ members,
437
+ writeConcernMajorityJournalDefault: !isInMemory,
438
+ settings: {
439
+ electionTimeoutMillis: 500,
440
+ ...this._replSetOpts.configSettings,
441
+ },
442
+ };
443
+ // try-catch because the first "command" can fail
439
444
  try {
440
- const adminDb = con.db('admin');
441
- const members = uris.map((uri, index) => {
442
- var _a;
443
- return (Object.assign({ _id: index, host: (0, utils_1.getHost)(uri) }, (((_a = this.servers[index].opts.instance) === null || _a === void 0 ? void 0 : _a.replicaMemberConfig) || {})));
444
- });
445
- const rsConfig = {
446
- _id: this._replSetOpts.name,
447
- members,
448
- writeConcernMajorityJournalDefault: !isInMemory,
449
- settings: Object.assign({ electionTimeoutMillis: 500 }, this._replSetOpts.configSettings),
450
- };
451
- // try-catch because the first "command" can fail
452
- try {
453
- log('_initReplSet: trying "replSetInitiate"');
454
- yield adminDb.command({ replSetInitiate: rsConfig });
455
- if (this.enableAuth()) {
456
- log('_initReplSet: "enableAuth" returned "true"');
457
- yield this._waitForPrimary(undefined, '_initReplSet authIsObject');
458
- // find the primary instance to run createAuth on
459
- const primary = this.servers.find((server) => { var _a; return (_a = server.instanceInfo) === null || _a === void 0 ? void 0 : _a.instance.isInstancePrimary; });
460
- (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(primary), new Error('No Primary found'));
461
- // this should be defined at this point, but is checked anyway (thanks to types)
462
- (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(primary.instanceInfo), new errors_1.InstanceInfoError('_initReplSet authIsObject primary'));
463
- yield con.close(); // just ensuring that no timeouts happen or conflicts happen
464
- yield primary.createAuth(primary.instanceInfo);
465
- this._ranCreateAuth = true;
466
- }
467
- }
468
- catch (err) {
469
- if (err instanceof mongodb_1.MongoError && err.errmsg == 'already initialized') {
470
- log(`_initReplSet: "${err.errmsg}": trying to set old config`);
471
- const { config: oldConfig } = yield adminDb.command({ replSetGetConfig: 1 });
472
- log('_initReplSet: got old config:\n', oldConfig);
473
- yield adminDb.command({
474
- replSetReconfig: oldConfig,
475
- force: true,
476
- });
477
- }
478
- else {
479
- throw err;
480
- }
445
+ log('_initReplSet: trying "replSetInitiate"');
446
+ await adminDb.command({ replSetInitiate: rsConfig });
447
+ if (this.enableAuth()) {
448
+ log('_initReplSet: "enableAuth" returned "true"');
449
+ await this._waitForPrimary(undefined, '_initReplSet authIsObject');
450
+ // find the primary instance to run createAuth on
451
+ const primary = this.servers.find((server) => server.instanceInfo?.instance.isInstancePrimary);
452
+ (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(primary), new Error('No Primary found'));
453
+ // this should be defined at this point, but is checked anyway (thanks to types)
454
+ (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(primary.instanceInfo), new errors_1.InstanceInfoError('_initReplSet authIsObject primary'));
455
+ await con.close(); // just ensuring that no timeouts happen or conflicts happen
456
+ await primary.createAuth(primary.instanceInfo);
457
+ this._ranCreateAuth = true;
481
458
  }
482
- log('_initReplSet: ReplSet-reconfig finished');
483
- yield this._waitForPrimary(undefined, '_initReplSet beforeRunning');
484
- this.stateChange(MongoMemoryReplSetStates.running);
485
- log('_initReplSet: running');
486
459
  }
487
- finally {
488
- log('_initReplSet: finally closing connection');
489
- yield con.close();
460
+ catch (err) {
461
+ if (err instanceof mongodb_1.MongoError && err.errmsg == 'already initialized') {
462
+ log(`_initReplSet: "${err.errmsg}": trying to set old config`);
463
+ const { config: oldConfig } = await adminDb.command({ replSetGetConfig: 1 });
464
+ log('_initReplSet: got old config:\n', oldConfig);
465
+ await adminDb.command({
466
+ replSetReconfig: oldConfig,
467
+ force: true,
468
+ });
469
+ }
470
+ else {
471
+ throw err;
472
+ }
490
473
  }
491
- });
474
+ log('_initReplSet: ReplSet-reconfig finished');
475
+ await this._waitForPrimary(undefined, '_initReplSet beforeRunning');
476
+ this.stateChange(MongoMemoryReplSetStates.running);
477
+ log('_initReplSet: running');
478
+ }
479
+ finally {
480
+ log('_initReplSet: finally closing connection');
481
+ await con.close();
482
+ }
492
483
  }
493
484
  /**
494
485
  * Create the one Instance (without starting them)
@@ -510,36 +501,34 @@ class MongoMemoryReplSet extends events_1.EventEmitter {
510
501
  * @param where Extra Parameter for logging to know where this function was called
511
502
  * @throws if timeout is reached
512
503
  */
513
- _waitForPrimary(timeout = 1000 * 30, where) {
514
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
515
- log('_waitForPrimary: Waiting for a Primary');
516
- let timeoutId;
517
- // "race" because not all servers will be a primary
518
- yield Promise.race([
519
- ...this.servers.map((server) => new Promise((res, rej) => {
520
- const instanceInfo = server.instanceInfo;
521
- // this should be defined at this point, but is checked anyway (thanks to types)
522
- if ((0, utils_1.isNullOrUndefined)(instanceInfo)) {
523
- return rej(new errors_1.InstanceInfoError('_waitForPrimary Primary race'));
524
- }
525
- instanceInfo.instance.once(MongoInstance_1.MongoInstanceEvents.instancePrimary, res);
526
- if (instanceInfo.instance.isInstancePrimary) {
527
- log('_waitForPrimary: found instance being already primary');
528
- res();
529
- }
530
- })),
531
- new Promise((_res, rej) => {
532
- timeoutId = setTimeout(() => {
533
- Promise.all([...this.servers.map((v) => v.stop())]); // this is not chained with "rej", this is here just so things like jest can exit at some point
534
- rej(new errors_1.WaitForPrimaryTimeoutError(timeout, where));
535
- }, timeout);
536
- }),
537
- ]);
538
- if (!(0, utils_1.isNullOrUndefined)(timeoutId)) {
539
- clearTimeout(timeoutId);
540
- }
541
- log('_waitForPrimary: detected one primary instance ');
542
- });
504
+ async _waitForPrimary(timeout = 1000 * 30, where) {
505
+ log('_waitForPrimary: Waiting for a Primary');
506
+ let timeoutId;
507
+ // "race" because not all servers will be a primary
508
+ await Promise.race([
509
+ ...this.servers.map((server) => new Promise((res, rej) => {
510
+ const instanceInfo = server.instanceInfo;
511
+ // this should be defined at this point, but is checked anyway (thanks to types)
512
+ if ((0, utils_1.isNullOrUndefined)(instanceInfo)) {
513
+ return rej(new errors_1.InstanceInfoError('_waitForPrimary Primary race'));
514
+ }
515
+ instanceInfo.instance.once(MongoInstance_1.MongoInstanceEvents.instancePrimary, res);
516
+ if (instanceInfo.instance.isInstancePrimary) {
517
+ log('_waitForPrimary: found instance being already primary');
518
+ res();
519
+ }
520
+ })),
521
+ new Promise((_res, rej) => {
522
+ timeoutId = setTimeout(() => {
523
+ Promise.all([...this.servers.map((v) => v.stop())]); // this is not chained with "rej", this is here just so things like jest can exit at some point
524
+ rej(new errors_1.WaitForPrimaryTimeoutError(timeout, where));
525
+ }, timeout);
526
+ }),
527
+ ]);
528
+ if (!(0, utils_1.isNullOrUndefined)(timeoutId)) {
529
+ clearTimeout(timeoutId);
530
+ }
531
+ log('_waitForPrimary: detected one primary instance ');
543
532
  }
544
533
  }
545
534
  exports.MongoMemoryReplSet = MongoMemoryReplSet;