/
HooksWorkerClient.js
390 lines (339 loc) · 13.1 KB
/
HooksWorkerClient.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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
const generateUuid = require('uuid/v4');
const net = require('net');
const path = require('path');
const spawnArgs = require('spawn-args');
const { EventEmitter } = require('events');
const getGoBinary = require('./getGoBinary');
const logger = require('./logger');
const which = require('./which');
const { spawn } = require('./childProcess');
class HooksWorkerClient {
constructor(runner) {
this.runner = runner;
const options = this.runner.hooks.configuration;
this.language = options.language;
this.timeout = options['hooks-worker-timeout'] || 5000;
this.connectTimeout = options['hooks-worker-connect-timeout'] || 1500;
this.connectRetry = options['hooks-worker-connect-retry'] || 500;
this.afterConnectWait = options['hooks-worker-after-connect-wait'] || 100;
this.termTimeout = options['hooks-worker-term-timeout'] || 5000;
this.termRetry = options['hooks-worker-term-retry'] || 500;
this.handlerHost = options['hooks-worker-handler-host'] || '127.0.0.1';
this.handlerPort = options['hooks-worker-handler-port'] || 61321;
this.handlerMessageDelimiter = '\n';
this.clientConnected = false;
this.connectError = false;
this.emitter = new EventEmitter();
}
start(callback) {
logger.debug('Looking up hooks handler implementation:', this.language);
this.setCommandAndCheckForExecutables((executablesError) => {
if (executablesError) { return callback(executablesError); }
logger.debug('Starting hooks handler.');
this.spawnHandler((spawnHandlerError) => {
if (spawnHandlerError) { return callback(spawnHandlerError); }
logger.debug('Connecting to hooks handler.');
this.connectToHandler((connectHandlerError) => {
if (connectHandlerError) {
this.terminateHandler(terminateError => callback(connectHandlerError || terminateError));
return;
}
logger.debug('Registering hooks.');
this.registerHooks((registerHooksError) => {
if (registerHooksError) { return callback(registerHooksError); }
callback();
});
});
});
});
}
stop(callback) {
this.disconnectFromHandler();
this.terminateHandler(callback);
}
terminateHandler(callback) {
logger.debug('Terminating hooks handler process, PID', this.handler.pid);
if (this.handler.terminated) {
logger.debug('The hooks handler process has already terminated');
return callback();
}
this.handler.terminate({ force: true, timeout: this.termTimeout, retryDelay: this.termRetry });
this.handler.on('close', () => callback());
}
disconnectFromHandler() {
this.handlerClient.destroy();
}
setCommandAndCheckForExecutables(callback) {
// Select handler based on option, use option string as command if not match anything
let msg;
if (this.language === 'ruby') {
this.handlerCommand = 'dredd-hooks-ruby';
this.handlerCommandArgs = [];
if (!which.which(this.handlerCommand)) {
msg = `
Ruby hooks handler command not found: ${this.handlerCommand}
Install ruby hooks handler by running:
$ gem install dredd_hooks
`;
callback(new Error(msg));
} else {
callback();
}
} else if (this.language === 'rust') {
this.handlerCommand = 'dredd-hooks-rust';
this.handlerCommandArgs = [];
if (!which.which(this.handlerCommand)) {
msg = `
Rust hooks handler command not found: ${this.handlerCommand}
Install rust hooks handler by running:
$ cargo install dredd-hooks
`;
callback(new Error(msg));
} else {
callback();
}
} else if (this.language === 'python') {
this.handlerCommand = 'dredd-hooks-python';
this.handlerCommandArgs = [];
if (!which.which(this.handlerCommand)) {
msg = `
Python hooks handler command not found: ${this.handlerCommand}
Install python hooks handler by running:
$ pip install dredd_hooks
`;
callback(new Error(msg));
} else {
callback();
}
} else if (this.language === 'php') {
this.handlerCommand = 'dredd-hooks-php';
this.handlerCommandArgs = [];
if (!which.which(this.handlerCommand)) {
msg = `
PHP hooks handler command not found: ${this.handlerCommand}
Install php hooks handler by running:
$ composer require ddelnano/dredd-hooks-php --dev
`;
callback(new Error(msg));
} else {
callback();
}
} else if (this.language === 'perl') {
this.handlerCommand = 'dredd-hooks-perl';
this.handlerCommandArgs = [];
if (!which.which(this.handlerCommand)) {
msg = `
Perl hooks handler command not found: ${this.handlerCommand}
Install perl hooks handler by running:
$ cpanm Dredd::Hooks
`;
callback(new Error(msg));
} else {
callback();
}
} else if (this.language === 'nodejs') {
msg = `
Hooks handler should not be used for Node.js.
Use Dredd's native Node.js hooks instead.
`;
callback(new Error(msg));
} else if (this.language === 'go') {
getGoBinary((err, goBin) => {
if (err) {
callback(new Error(`Go doesn't seem to be installed: ${err.message}`));
} else {
this.handlerCommand = path.join(goBin, 'goodman');
this.handlerCommandArgs = [];
if (which.which(this.handlerCommand)) {
callback();
} else {
msg = `
Go hooks handler command not found: ${this.handlerCommand}
Install go hooks handler by running:
$ go get github.com/snikch/goodman/cmd/goodman
`;
callback(new Error(msg));
}
}
});
} else {
const parsedArgs = spawnArgs(this.language);
this.handlerCommand = parsedArgs.shift();
this.handlerCommandArgs = parsedArgs;
logger.debug(`Using '${this.handlerCommand}' as a hooks handler command, '${this.handlerCommandArgs.join(' ')}' as arguments`);
if (!which.which(this.handlerCommand)) {
msg = `Hooks handler command not found: ${this.handlerCommand}`;
callback(new Error(msg));
} else {
callback();
}
}
}
spawnHandler(callback) {
const pathGlobs = this.runner.hooks.configuration.hookfiles;
const handlerCommandArgs = this.handlerCommandArgs.concat(pathGlobs);
logger.debug(`Spawning '${this.language}' hooks handler process.`);
this.handler = spawn(this.handlerCommand, handlerCommandArgs);
this.handler.stdout.on('data', data => logger.debug('Hooks handler stdout:', data.toString()));
this.handler.stderr.on('data', data => logger.debug('Hooks handler stderr:', data.toString()));
this.handler.on('signalTerm', () => logger.debug('Gracefully terminating the hooks handler process'));
this.handler.on('signalKill', () => logger.debug('Killing the hooks handler process'));
this.handler.on('crash', (exitStatus, killed) => {
let msg;
if (killed) {
msg = `Hooks handler process '${this.handlerCommand} ${handlerCommandArgs.join(' ')}' was killed.`;
} else {
msg = `Hooks handler process '${this.handlerCommand} ${handlerCommandArgs.join(' ')}' exited with status: ${exitStatus}`;
}
logger.error(msg);
this.runner.hookHandlerError = new Error(msg);
});
this.handler.on('error', (err) => {
this.runner.hookHandlerError = err;
});
callback();
}
connectToHandler(callback) {
let timeout;
const start = Date.now();
const waitForConnect = () => {
if ((Date.now() - start) < this.connectTimeout) {
clearTimeout(timeout);
if (this.connectError !== false) {
logger.warn('Error connecting to the hooks handler process. Is the handler running? Retrying.');
this.connectError = false;
}
if (this.clientConnected !== true) {
connectAndSetupClient();
timeout = setTimeout(waitForConnect, this.connectRetry);
}
} else {
clearTimeout(timeout);
if (!this.clientConnected) {
if (this.handlerClient) { this.handlerClient.destroy(); }
const msg = `Connection timeout ${this.connectTimeout / 1000}s to hooks handler `
+ `on ${this.handlerHost}:${this.handlerPort} exceeded. Try increasing the limit.`;
callback(new Error(msg));
}
}
};
const connectAndSetupClient = () => {
logger.debug('Starting TCP connection with hooks handler process.');
if (this.runner.hookHandlerError) {
callback(this.runner.hookHandlerError);
}
this.handlerClient = net.connect({ port: this.handlerPort, host: this.handlerHost });
this.handlerClient.on('connect', () => {
logger.debug(`Successfully connected to hooks handler. Waiting ${this.afterConnectWait / 1000}s to start testing.`);
this.clientConnected = true;
clearTimeout(timeout);
setTimeout(callback, this.afterConnectWait);
});
this.handlerClient.on('close', () => logger.debug('TCP communication with hooks handler closed.'));
this.handlerClient.on('error', (connectError) => {
logger.debug('TCP communication with hooks handler errored.', connectError);
this.connectError = connectError;
});
let handlerBuffer = '';
this.handlerClient.on('data', (data) => {
logger.debug('Dredd received some data from hooks handler.');
handlerBuffer += data.toString();
if (data.toString().indexOf(this.handlerMessageDelimiter) > -1) {
const splittedData = handlerBuffer.split(this.handlerMessageDelimiter);
// Add last chunk to the buffer
handlerBuffer = splittedData.pop();
const messages = [];
for (const message of splittedData) {
messages.push(JSON.parse(message));
}
const result = [];
for (const message of messages) {
if (message.uuid) {
logger.debug('Dredd received a valid message from hooks handler:', message.uuid);
result.push(this.emitter.emit(message.uuid, message));
} else {
result.push(logger.debug('UUID not present in hooks handler message, ignoring:', JSON.stringify(message, null, 2)));
}
}
return result;
}
});
};
timeout = setTimeout(waitForConnect, this.connectRetry);
}
registerHooks(callback) {
const eachHookNames = [
'beforeEach',
'beforeEachValidation',
'afterEach',
'beforeAll',
'afterAll',
];
for (const eventName of eachHookNames) {
this.runner.hooks[eventName]((data, hookCallback) => {
const uuid = generateUuid();
// Send transaction to the handler
const message = {
event: eventName,
uuid,
data,
};
logger.debug('Sending HTTP transaction data to hooks handler:', uuid);
this.handlerClient.write(JSON.stringify(message));
this.handlerClient.write(this.handlerMessageDelimiter);
// Register event for the sent transaction
function messageHandler(receivedMessage) {
let value;
logger.debug('Handling hook:', uuid);
clearTimeout(timeout);
// We are directly modifying the `data` argument here. Neither direct
// assignment (`data = receivedMessage.data`) nor `clone()` will work...
// *All hooks receive array of transactions
if (eventName.indexOf('All') > -1) {
for (let index = 0; index < receivedMessage.data.length; index++) {
value = receivedMessage.data[index];
data[index] = value;
}
// *Each hook receives single transaction
} else {
for (const key of Object.keys(receivedMessage.data || {})) {
value = receivedMessage.data[key];
data[key] = value;
}
}
hookCallback();
}
const handleTimeout = () => {
logger.warn('Hook handling timed out.');
if (eventName.indexOf('All') === -1) {
data.fail = 'Hook timed out.';
}
this.emitter.removeListener(uuid, messageHandler);
hookCallback();
};
// Set timeout for the hook
let timeout = setTimeout(handleTimeout, this.timeout);
this.emitter.on(uuid, messageHandler);
});
}
this.runner.hooks.afterAll((transactions, hookCallback) => {
// This is needed for transaction modification integration tests:
// https://github.com/apiaryio/dredd-hooks-template/blob/master/features/execution_order.feature
if (process.env.TEST_DREDD_HOOKS_HANDLER_ORDER === 'true') {
console.error('FOR TESTING ONLY');
const modifications = (transactions[0] && transactions[0].hooks_modifications) || [];
if (!modifications.length) {
throw new Error('Hooks must modify transaction.hooks_modifications');
}
for (let index = 0; index < modifications.length; index++) {
const modification = modifications[index];
console.error(`${index} ${modification}`);
}
console.error('FOR TESTING ONLY');
}
this.stop(hookCallback);
});
callback();
}
}
module.exports = HooksWorkerClient;