-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathutils.js
270 lines (226 loc) · 7 KB
/
utils.js
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
'use strict';
const { Logger } = require('../../src/logger');
const { deprecateOptions, arrayStrictEqual, errorStrictEqual } = require('../../src/utils');
const chalk = require('chalk');
const util = require('util');
const chai = require('chai');
const expect = chai.expect;
const sinonChai = require('sinon-chai');
chai.use(sinonChai);
function makeTestFunction(config) {
const fn = options => {
if (options) options = null;
};
return deprecateOptions(config, fn);
}
function ensureCalledWith(stub, args) {
args.forEach(m => expect(stub).to.have.been.calledWith(m));
}
// creation of class with a logger
function ClassWithLogger() {
this.logger = new Logger('ClassWithLogger');
}
ClassWithLogger.prototype.f = makeTestFunction({
name: 'f',
deprecatedOptions: ['maxScan', 'snapshot', 'fields'],
optionsIndex: 0
});
ClassWithLogger.prototype.getLogger = function () {
return this.logger;
};
// creation of class without a logger
function ClassWithoutLogger() {}
ClassWithoutLogger.prototype.f = makeTestFunction({
name: 'f',
deprecatedOptions: ['maxScan', 'snapshot', 'fields'],
optionsIndex: 0
});
// creation of class where getLogger returns undefined
function ClassWithUndefinedLogger() {}
ClassWithUndefinedLogger.prototype.f = makeTestFunction({
name: 'f',
deprecatedOptions: ['maxScan', 'snapshot', 'fields'],
optionsIndex: 0
});
ClassWithUndefinedLogger.prototype.getLogger = function () {
return undefined;
};
function diff(lhs, rhs, fields, comparator) {
return fields.reduce((diff, field) => {
if ((lhs[field] == null || rhs[field] == null) && field !== 'error') {
return diff;
}
if (!comparator(lhs[field], rhs[field])) {
diff.push(
` ${field}: ${chalk.green(`${util.inspect(lhs[field])}`)} => ${chalk.green(
`${util.inspect(rhs[field])}`
)}`
);
}
return diff;
}, []);
}
function serverDescriptionDiff(lhs, rhs) {
const objectIdFields = ['electionId'];
const arrayFields = ['hosts', 'tags'];
const simpleFields = [
'type',
'minWireVersion',
'me',
'setName',
'setVersion',
'electionId',
'primary',
'logicalSessionTimeoutMinutes'
];
return diff(lhs, rhs, simpleFields, (x, y) => x === y)
.concat(diff(lhs, rhs, ['error'], (x, y) => errorStrictEqual(x, y)))
.concat(diff(lhs, rhs, arrayFields, (x, y) => arrayStrictEqual(x, y)))
.concat(diff(lhs, rhs, objectIdFields, (x, y) => x.equals(y)))
.join(',\n');
}
function topologyDescriptionDiff(lhs, rhs) {
const simpleFields = [
'type',
'setName',
'maxSetVersion',
'stale',
'compatible',
'compatibilityError',
'logicalSessionTimeoutMinutes',
'error',
'commonWireVersion'
];
return diff(lhs, rhs, simpleFields, (x, y) => x === y).join(',\n');
}
function visualizeMonitoringEvents(client) {
function print(msg) {
console.error(`${chalk.white(new Date().toISOString())} ${msg}`);
}
client.on('serverHeartbeatStarted', event =>
print(`${chalk.yellow('heartbeat')} ${chalk.bold('started')} host: '${event.connectionId}`)
);
client.on('serverHeartbeatSucceeded', event =>
print(
`${chalk.yellow('heartbeat')} ${chalk.green('succeeded')} host: '${
event.connectionId
}' ${chalk.gray(`(${event.duration} ms)`)}`
)
);
client.on('serverHeartbeatFailed', event =>
print(
`${chalk.yellow('heartbeat')} ${chalk.red('failed')} host: '${
event.connectionId
}' ${chalk.gray(`(${event.duration} ms)`)}`
)
);
// server information
client.on('serverOpening', event => {
print(
`${chalk.cyan('server')} [${event.address}] ${chalk.bold('opening')} in topology#${
event.topologyId
}`
);
});
client.on('serverClosed', event => {
print(
`${chalk.cyan('server')} [${event.address}] ${chalk.bold('closed')} in topology#${
event.topologyId
}`
);
});
client.on('serverDescriptionChanged', event => {
print(`${chalk.cyan('server')} [${event.address}] changed:`);
console.error(serverDescriptionDiff(event.previousDescription, event.newDescription));
});
// topology information
client.on('topologyOpening', event => {
print(`${chalk.magenta('topology')} adding topology#${event.topologyId}`);
});
client.on('topologyClosed', event => {
print(`${chalk.magenta('topology')} removing topology#${event.topologyId}`);
});
client.on('topologyDescriptionChanged', event => {
const diff = topologyDescriptionDiff(event.previousDescription, event.newDescription);
if (diff !== '') {
print(`${chalk.magenta('topology')} [topology#${event.topologyId}] changed:`);
console.error(diff);
}
});
}
class EventCollector {
constructor(obj, events, options) {
this._events = Object.create(null);
this._timeout = options ? options.timeout : 5000;
events.forEach(eventName => {
this._events[eventName] = [];
obj.on(eventName, event => this._events[eventName].push(event));
});
}
waitForEvent(eventName, count, callback) {
if (typeof count === 'function') {
callback = count;
count = 1;
}
this.waitForEventImpl(this, Date.now(), eventName, count, callback);
}
/**
* Will only return one event at a time from the front of the list
* Useful for iterating over the events in the order they occurred
*
* @param {string} eventName
* @returns {Promise<Record<string, any>>}
*/
waitAndShiftEvent(eventName) {
return new Promise((resolve, reject) => {
if (this._events[eventName].length > 0) {
return resolve(this._events[eventName].shift());
}
this.waitForEventImpl(this, Date.now(), eventName, 1, error => {
if (error) return reject(error);
resolve(this._events[eventName].shift());
});
});
}
reset(eventName) {
if (eventName == null) {
Object.keys(this._events).forEach(eventName => {
this._events[eventName] = [];
});
return;
}
if (this._events[eventName] == null) {
throw new TypeError(`invalid event name "${eventName}" specified for reset`);
}
this._events[eventName] = [];
}
waitForEventImpl(collector, start, eventName, count, callback) {
const events = collector._events[eventName];
if (events.length >= count) {
return callback(undefined, events);
}
if (Date.now() - start >= collector._timeout) {
return callback(new Error(`timed out waiting for event "${eventName}"`));
}
setTimeout(() => this.waitForEventImpl(collector, start, eventName, count, callback), 10);
}
}
function getSymbolFrom(target, symbolName, assertExists = true) {
const symbol = Object.getOwnPropertySymbols(target).filter(
s => s.toString() === `Symbol(${symbolName})`
)[0];
if (assertExists && !symbol) {
throw new Error(`Did not find Symbol(${symbolName}) on ${target}`);
}
return symbol;
}
module.exports = {
EventCollector,
makeTestFunction,
ensureCalledWith,
ClassWithLogger,
ClassWithoutLogger,
ClassWithUndefinedLogger,
visualizeMonitoringEvents,
getSymbolFrom
};