/
utils.ts
308 lines (273 loc) · 9.31 KB
/
utils.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
import debug from 'debug';
import { ChildProcess } from 'child_process';
import { AutomaticAuth } from '../MongoMemoryServer';
import { promises as fspromises, Stats, constants } from 'fs';
import { LinuxOS } from './getos';
import {
AssertionFallbackError,
BinaryNotFoundError,
InsufficientPermissionsError,
} from './errors';
const log = debug('MongoMS:utils');
/**
* This is here, because NodeJS does not have a FSError type
*/
interface ErrorWithCode extends Error {
code: string;
}
/**
* This is here, because NodeJS does not have a FSError type
* @param err Value to check agains
* @returns `true` if it is a error with code, `false` if not
*/
export function errorWithCode(err: unknown): err is ErrorWithCode {
return err instanceof Error && 'code' in err;
}
/**
* Return input or default database
* @param {string} dbName
*/
export function generateDbName(dbName?: string): string {
// this is ""(empty) to make it compatible with mongodb's uri format and mongoose's uri format
// (in mongodb its the auth database, in mongoose its the default database for models)
return dbName || '';
}
/**
* Extracts the host and port information from a mongodb URI string.
* @param {string} uri mongodb URI
*/
export function getHost(uri: string): string {
// this will turn "mongodb://user:pass@localhost:port/authdb?queryoptions=1" to "localhost:port"
return uri.replace(/(?:^mongodb:\/{2})|(?:\/.*$)|(?:.*@)/gim, '');
}
/**
* Basic MongoDB Connection string
* @param host the host ip or an list of hosts
* @param port the host port or undefined if "host" is an list of hosts
* @param dbName the database to add to the uri (in mongodb its the auth database, in mongoose its the default database for models)
* @param query extra uri-query options (joined with "&")
*/
export function uriTemplate(
host: string,
port: number | undefined,
dbName: string,
query?: string[]
): string {
const hosts = !isNullOrUndefined(port) ? `${host}:${port}` : host;
return `mongodb://${hosts}/${dbName}` + (!isNullOrUndefined(query) ? `?${query.join('&')}` : '');
}
/**
* Because since node 4.0.0 the internal util.is* functions got deprecated
* @param val Any value to test if null or undefined
*/
export function isNullOrUndefined(val: unknown): val is null | undefined {
return val === null || val === undefined;
}
/**
* Assert an condition, if "false" throw error
* Note: it is not named "assert" to differentiate between node and jest types
* @param cond The Condition to throw
* @param error An Custom Error to throw
*/
export function assertion(cond: unknown, error?: Error): asserts cond {
if (!cond) {
throw error ?? new AssertionFallbackError();
}
}
/**
* Kill an ChildProcess
* @param childprocess The Process to kill
* @param name the name used in the logs
* @param mongodPort the port for the mongod process (for easier logging)
*/
export async function killProcess(
childprocess: ChildProcess,
name: string,
mongodPort?: number
): Promise<void> {
function ilog(msg: string) {
log(`Mongo[${mongodPort || 'unknown'}] killProcess: ${msg}`);
}
// this case can somehow happen, see https://github.com/nodkz/mongodb-memory-server/issues/666
if (isNullOrUndefined(childprocess)) {
ilog('childprocess was somehow undefined');
return;
}
// check if the childProcess (via PID) is still alive (found thanks to https://github.com/nodkz/mongodb-memory-server/issues/411)
if (!isAlive(childprocess.pid)) {
ilog("given childProcess's PID was not alive anymore");
return;
}
/**
* Timeout before using SIGKILL
*/
const timeoutTime = 1000 * 10;
await new Promise<void>((res, rej) => {
let timeout = setTimeout(() => {
ilog('killProcess: timeout triggered, trying SIGKILL');
if (!debug.enabled('MongoMS:utils')) {
console.warn(
'An Process didnt exit with signal "SIGINT" within 10 seconds, using "SIGKILL"!\n' +
'Enable debug logs for more information'
);
}
childprocess.kill('SIGKILL');
timeout = setTimeout(() => {
ilog('killProcess: timeout triggered again, rejecting');
rej(new Error(`Process "${name}" didnt exit, enable debug for more information.`));
}, timeoutTime);
}, timeoutTime);
childprocess.once(`exit`, (code, signal) => {
ilog(`killProcess: ${name}: got exit signal, Code: ${code}, Signal: ${signal}`);
clearTimeout(timeout);
res();
});
ilog(`killProcess: ${name}: sending "SIGINT"`);
childprocess.kill('SIGINT');
});
}
/**
* Check if the given Process is still alive
* @param {number} pid The Process PID
*/
export function isAlive(pid?: number): boolean {
// This test (and allow to be undefined) is here because somewhere between nodejs 12 and 16 the types for "childprocess.pid" changed to include "| undefined"
if (isNullOrUndefined(pid)) {
return false;
}
try {
process.kill(pid, 0); // code "0" dosnt actually kill anything (on all supported systems)
return true;
} catch (err) {
return false;
}
}
/**
* Call "process.nextTick" to ensure an function is exectued directly after all code surrounding it
* look at the following link to get to know on why this needed: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick (read full documentation)
*/
export async function ensureAsync(): Promise<void> {
return new Promise((res) => process.nextTick(res));
}
/**
* Convert Partitial input into full-defaulted output
* @param opts Partitial input options
*/
export function authDefault(opts: AutomaticAuth): Required<AutomaticAuth> {
return {
force: false,
disable: false,
customRootName: 'mongodb-memory-server-root',
customRootPwd: 'rootuser',
extraUsers: [],
keyfileContent: '0123456789',
...opts,
};
}
/**
* Run "fs.promises.stat", but return "undefined" if error is "ENOENT" or "EACCES"
* follows symlinks
* @param path The Path to Stat
* @throws if the error is not "ENOENT" or "EACCES"
*/
export async function statPath(path: string): Promise<Stats | undefined> {
return fspromises.stat(path).catch((err) => {
// catch the error if the directory doesn't exist or permission is denied, without throwing an error
if (['ENOENT', 'EACCES'].includes(err.code)) {
return undefined;
}
throw err;
});
}
/**
* Like "fs.existsSync" but async
* uses "utils.statPath"
* follows symlinks
* @param path The Path to check for
*/
export async function pathExists(path: string): Promise<boolean> {
return !isNullOrUndefined(await statPath(path));
}
/**
* Try to read an release file path and apply an parser to the output
* @param path The Path to read for an release file
* @param parser An function to parse the output of the file
*/
export async function tryReleaseFile(
path: string,
parser: (output: string) => LinuxOS | undefined
): Promise<LinuxOS | undefined> {
try {
const output = await fspromises.readFile(path);
return parser(output.toString());
} catch (err) {
if (errorWithCode(err) && !['ENOENT', 'EACCES'].includes(err.code)) {
throw err;
}
log(`tryReleaseFile: "${path}" does not exist`);
return undefined;
}
}
/**
* Cleanup interface to provide easy to understand arguments for clean-up
*/
export interface Cleanup {
/**
* Setting this to `true` will activate cleanup
* @default true
*/
doCleanup?: boolean;
/**
* Setting this to `true` will cleanup the directory even if it is *not* a temporary directory
* @default false
*/
force?: boolean;
}
/**
* This Class is used to have unified types for base-manager functions
*/
export abstract class ManagerBase {
// this cannot be done yet, https://github.com/microsoft/TypeScript/issues/34516
// abstract static create(opts: Record<string, any>): Promise<new (...args: any) => any>;
abstract start(forceSamePort: boolean): Promise<void>;
abstract start(): Promise<void>;
/** @deprecated replace argument with `Cleanup` interface object */
abstract stop(cleanup: boolean): Promise<boolean>; // TODO: for next major release (9.0), this should be removed
abstract stop(cleanup: Cleanup): Promise<boolean>;
}
/**
* This Class is used to have unified types for advanced-manager functions
*/
export abstract class ManagerAdvanced extends ManagerBase {
abstract getUri(otherDB?: string | boolean): string;
/** @deprecated replace argument with `Cleanup` interface object */
abstract cleanup(force: boolean): Promise<void>; // TODO: for next major release (9.0), this should be removed
abstract cleanup(cleanup: Cleanup): Promise<void>;
}
/**
* Check that the Binary has sufficient Permissions to be executed
* @param path The Path to check
*/
export async function checkBinaryPermissions(path: string): Promise<void> {
try {
await fspromises.access(path, constants.X_OK); // check if the provided path exists and has the execute bit for current user
} catch (err) {
if (errorWithCode(err)) {
if (err.code === 'EACCES') {
throw new InsufficientPermissionsError(path);
}
if (err.code === 'ENOENT') {
throw new BinaryNotFoundError(path);
}
}
throw err;
}
}
/**
* Make Directory, wrapper for native mkdir with recursive true
* @param path The Path to create
* @returns Nothing
*/
export async function mkdir(path: string): Promise<void> {
await fspromises.mkdir(path, { recursive: true });
}