/
MongoMemoryServer.ts
330 lines (284 loc) · 9.71 KB
/
MongoMemoryServer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import { SpawnOptions } from 'child_process';
import * as tmp from 'tmp';
import getPort from 'get-port';
import { assertion, generateDbName, getUriBase, isNullOrUndefined } from './util/db_util';
import MongoInstance from './util/MongoInstance';
import { MongoBinaryOpts } from './util/MongoBinary';
import { MongoMemoryInstancePropT, StorageEngineT } from './types';
import debug from 'debug';
import { EventEmitter } from 'events';
const log = debug('MongoMS:MongoMemoryServer');
tmp.setGracefulCleanup();
/**
* MongoMemoryServer Stored Options
*/
export interface MongoMemoryServerOptsT {
instance?: MongoMemoryInstancePropT;
binary?: MongoBinaryOpts;
spawn?: SpawnOptions;
}
/**
* Data used by _startUpInstance's "data" variable
*/
export interface StartupInstanceData {
port: number;
dbPath?: string;
dbName: string;
ip: string;
storageEngine: StorageEngineT;
replSet?: string;
tmpDir?: tmp.DirResult;
}
/**
* Information about the currently running instance
*/
export interface MongoInstanceDataT extends StartupInstanceData {
dbPath: string; // re-declare, because in this interface it is *not* optional
instance: MongoInstance;
}
/**
* All Events for "MongoMemoryServer"
*/
export enum MongoMemoryServerEventEnum {
stateChange = 'stateChange',
}
/**
* All States for "MongoMemoryServer._state"
*/
export enum MongoMemoryServerStateEnum {
new = 'new',
starting = 'starting',
running = 'running',
stopped = 'stopped',
}
export interface MongoMemoryServer extends EventEmitter {
// Overwrite EventEmitter's definitions (to provide at least the event names)
emit(event: MongoMemoryServerEventEnum, ...args: any[]): boolean;
on(event: MongoMemoryServerEventEnum, listener: (...args: any[]) => void): this;
once(event: MongoMemoryServerEventEnum, listener: (...args: any[]) => void): this;
}
export class MongoMemoryServer extends EventEmitter {
protected instanceInfo?: MongoInstanceDataT;
opts: MongoMemoryServerOptsT;
_state: MongoMemoryServerStateEnum = MongoMemoryServerStateEnum.new;
/**
* Create an Mongo-Memory-Sever Instance
*
* Note: because of JavaScript limitations, autoStart cannot be awaited here, use ".create" for async/await ability
* @param opts Mongo-Memory-Sever Options
*/
constructor(opts?: MongoMemoryServerOptsT) {
super();
this.opts = { ...opts };
}
/**
* Create an Mongo-Memory-Sever Instance that can be awaited
* @param opts Mongo-Memory-Sever Options
*/
static async create(opts?: MongoMemoryServerOptsT): Promise<MongoMemoryServer> {
log('Called MongoMemoryServer.create() method');
const instance = new MongoMemoryServer({ ...opts });
await instance.start();
return instance;
}
/**
* Change "this._state" to "newState" and emit "stateChange" with "newState"
* @param newState The new State to set & emit
*/
protected stateChange(newState: MongoMemoryServerStateEnum): void {
this._state = newState;
this.emit(MongoMemoryServerEventEnum.stateChange, newState);
}
/**
* Start the in-memory Instance
*/
async start(): Promise<boolean> {
log('Called MongoMemoryServer.start() method');
if (this.instanceInfo) {
throw new Error(
'MongoDB instance already in status startup/running/error. Use debug for more info.'
);
}
this.stateChange(MongoMemoryServerStateEnum.starting);
this.instanceInfo = await this._startUpInstance().catch((err) => {
if (!debug.enabled('MongoMS:MongoMemoryServer')) {
console.warn('Starting the instance failed, enable debug for more infomation');
}
throw err;
});
this.stateChange(MongoMemoryServerStateEnum.running);
return true;
}
/**
* Internal Function to start an instance
* @private
*/
async _startUpInstance(): Promise<MongoInstanceDataT> {
log('Called MongoMemoryServer._startUpInstance() method');
/** Shortcut to this.opts.instance */
const instOpts = this.opts.instance ?? {};
const data: StartupInstanceData = {
port: await getPort({ port: instOpts.port ?? undefined }), // do (null or undefined) to undefined
dbName: generateDbName(instOpts.dbName),
ip: instOpts.ip ?? '127.0.0.1',
storageEngine: instOpts.storageEngine ?? 'ephemeralForTest',
replSet: instOpts.replSet,
dbPath: instOpts.dbPath,
tmpDir: undefined,
};
if (instOpts.port != data.port) {
log(`starting with port ${data.port}, since ${instOpts.port} was locked:`, data.port);
}
if (!data.dbPath) {
data.tmpDir = tmp.dirSync({
mode: 0o755,
prefix: 'mongo-mem-',
unsafeCleanup: true,
});
data.dbPath = data.tmpDir.name;
}
log(`Starting MongoDB instance with options: ${JSON.stringify(data)}`);
// After that startup MongoDB instance
const instance = await MongoInstance.run({
instance: {
dbPath: data.dbPath,
ip: data.ip,
port: data.port,
storageEngine: data.storageEngine,
replSet: data.replSet,
args: instOpts.args,
auth: instOpts.auth,
},
binary: this.opts.binary,
spawn: this.opts.spawn,
});
return {
...data,
dbPath: data.dbPath as string, // because otherwise the types would be incompatible
instance: instance,
};
}
/**
* Stop the current In-Memory Instance
*/
async stop(): Promise<boolean> {
log('Called MongoMemoryServer.stop() method');
// just return "true" if the instance is already running / defined
if (isNullOrUndefined(this.instanceInfo)) {
log('Instance is already stopped, returning true');
return true;
}
// assert here, just to be sure
assertion(
!isNullOrUndefined(this.instanceInfo.instance),
new Error('"instanceInfo.instance" is undefined!')
);
log(
`Shutdown MongoDB server on port ${
this.instanceInfo.port
} with pid ${this.instanceInfo.instance.getPid()}` // "undefined" would say more than ""
);
await this.instanceInfo.instance.kill();
const tmpDir = this.instanceInfo.tmpDir;
if (tmpDir) {
log(`Removing tmpDir ${tmpDir.name}`);
tmpDir.removeCallback();
}
this.instanceInfo = undefined;
this.stateChange(MongoMemoryServerStateEnum.stopped);
return true;
}
/**
* Get Information about the currently running instance, if it is not running it returns "undefined"
*/
getInstanceInfo(): MongoInstanceDataT | undefined {
return this.instanceInfo;
}
/**
* Ensure that the instance is running
* -> throws if instance cannot be started
*/
async ensureInstance(): Promise<MongoInstanceDataT> {
log('Called MongoMemoryServer.ensureInstance() method');
if (this.instanceInfo) {
return this.instanceInfo;
}
switch (this._state) {
case MongoMemoryServerStateEnum.running:
throw new Error('MongoMemoryServer "_state" is "running" but "instanceInfo" is undefined!');
case MongoMemoryServerStateEnum.new:
case MongoMemoryServerStateEnum.stopped:
break;
case MongoMemoryServerStateEnum.starting:
return new Promise((res, rej) =>
this.once(MongoMemoryServerEventEnum.stateChange, (state) => {
if (state != MongoMemoryServerStateEnum.running) {
rej(
new Error(
`"ensureInstance" waited for "running" but got an different state: "${state}"`
)
);
}
res(this.instanceInfo);
})
);
default:
throw new Error(`"ensureInstance" does not have an case for "${this._state}"`);
}
log(' - no running instance, call `start()` command');
await this.start();
log(' - `start()` command was succesfully resolved');
// check again for 1. Typescript-type reasons and 2. if .start failed to throw an error
if (!this.instanceInfo) {
throw new Error('Ensure-Instance failed to start an instance!');
}
return this.instanceInfo;
}
/**
* Generate the Connection string used by mongodb
* @param otherDbName Set an custom Database name, or set this to "true" to generate an different name
*/
getUri(otherDbName?: string | boolean): string {
assertionInstanceInfo(this.instanceInfo);
let dbName: string = this.instanceInfo.dbName;
// using "if" instead of nested "?:"
if (!isNullOrUndefined(otherDbName)) {
// use "otherDbName" if string, otherwise generate an db-name
dbName = typeof otherDbName === 'string' ? otherDbName : generateDbName();
}
return getUriBase(this.instanceInfo.ip, this.instanceInfo.port, dbName);
}
/**
* Get the Port of the currently running Instance
*/
getPort(): number {
assertionInstanceInfo(this.instanceInfo);
assertion(!isNullOrUndefined(this.instanceInfo.port), new Error('"port" is undefined'));
return this.instanceInfo.port;
}
/**
* Get the DB-Path of the currently running Instance
*/
getDbPath(): string {
assertionInstanceInfo(this.instanceInfo);
assertion(!isNullOrUndefined(this.instanceInfo.dbPath), new Error('"dbPath" is undefined'));
return this.instanceInfo.dbPath;
}
/**
* Get the DB-Name of the currently running Instance
*/
getDbName(): string {
assertionInstanceInfo(this.instanceInfo);
assertion(!isNullOrUndefined(this.instanceInfo.dbName), new Error('"dbName" is undefined'));
return this.instanceInfo.dbName;
}
}
export default MongoMemoryServer;
/**
* This function is to de-duplicate code
* -> this couldnt be included in the class, because "asserts this.instanceInfo" is not allowed
* @param val this.instanceInfo
*/
function assertionInstanceInfo(val: unknown): asserts val is MongoInstanceDataT {
assertion(!isNullOrUndefined(val), new Error('"instanceInfo" is undefined'));
}