@artilleryio/int-core 1.0.0

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.
@@ -0,0 +1,376 @@
1
+ /* This Source Code Form is subject to the terms of the Mozilla Public
2
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
+
5
+ 'use strict';
6
+
7
+ const async = require('async');
8
+ const _ = require('lodash');
9
+
10
+ const io = require('socket.io-client');
11
+
12
+ const deepEqual = require('fast-deep-equal');
13
+ const debug = require('debug')('socketio');
14
+ const engineUtil = require('@artilleryio/int-commons').engine_util;
15
+ const EngineHttp = require('./engine_http');
16
+ const template = engineUtil.template;
17
+
18
+ module.exports = SocketIoEngine;
19
+
20
+ function SocketIoEngine(script) {
21
+ this.config = script.config;
22
+
23
+ this.socketioOpts = this.config.socketio || {};
24
+ this.httpDelegate = new EngineHttp(script);
25
+ }
26
+
27
+ SocketIoEngine.prototype.createScenario = function (scenarioSpec, ee) {
28
+ const self = this;
29
+ // Adds scenario overridden configuration into the static config
30
+ this.socketioOpts = { ...this.socketioOpts, ...scenarioSpec.socketio };
31
+
32
+ const tasks = _.map(scenarioSpec.flow, function (rs) {
33
+ if (typeof rs.think !== 'undefined') {
34
+ return engineUtil.createThink(
35
+ rs,
36
+ _.get(self.config, 'defaults.think', {})
37
+ );
38
+ }
39
+
40
+ return self.step(rs, ee);
41
+ });
42
+
43
+ return self.compile(tasks, scenarioSpec.flow, ee);
44
+ };
45
+
46
+ function markEndTime(ee, _, startedAt) {
47
+ const endedAt = process.hrtime(startedAt);
48
+ const delta = endedAt[0] * 1e9 + endedAt[1];
49
+
50
+ ee.emit('histogram', 'socketio.response_time', delta / 1e6);
51
+ }
52
+
53
+ function isResponseRequired(spec) {
54
+ return spec.emit && spec.response && spec.response.channel;
55
+ }
56
+
57
+ function isAcknowledgeRequired(spec) {
58
+ return spec.emit && spec.acknowledge;
59
+ }
60
+
61
+ function processResponse(ee, data, response, context, callback) {
62
+ // Do we have supplied data to validate?
63
+ if (response.data && !deepEqual(data, response.data)) {
64
+ debug('data is not valid:');
65
+ debug(data);
66
+ debug(response);
67
+
68
+ const err = 'data is not valid';
69
+ ee.emit('error', err);
70
+
71
+ return callback(err, context);
72
+ }
73
+
74
+ // If no capture or match specified, then we consider it a success at this point...
75
+ if (!response.capture && !response.match) {
76
+ return callback(null, context);
77
+ }
78
+
79
+ // Construct the (HTTP) response...
80
+ const fauxResponse = { body: JSON.stringify(data) };
81
+
82
+ // Handle the capture or match clauses...
83
+ engineUtil.captureOrMatch(
84
+ response,
85
+ fauxResponse,
86
+ context,
87
+ function (err, result) {
88
+ // Were we unable to invoke captureOrMatch?
89
+ if (err) {
90
+ debug(data);
91
+ ee.emit('error', err);
92
+
93
+ return callback(err, context);
94
+ }
95
+
96
+ if (result !== null) {
97
+ // Do we have any failed matches?
98
+ const failedMatches = _.filter(result.matches, (v) => {
99
+ return !v.success;
100
+ });
101
+
102
+ // How to handle failed matches?
103
+ if (failedMatches.length > 0) {
104
+ debug(failedMatches);
105
+ // TODO: Should log the details of the match somewhere
106
+ ee.emit('error', 'Failed match');
107
+ return callback(new Error('Failed match'), context);
108
+ } else {
109
+ // Populate the context with captured values
110
+ _.each(result.captures, function (v, k) {
111
+ context.vars[k] = v.value;
112
+ });
113
+ }
114
+
115
+ // Replace the base object context
116
+ // Question: Should this be JSON object or String?
117
+ context.vars.$ = fauxResponse.body;
118
+
119
+ // Increment the success count...
120
+ context._successCount++;
121
+
122
+ return callback(null, context);
123
+ }
124
+ }
125
+ );
126
+ }
127
+
128
+ SocketIoEngine.prototype.step = function (requestSpec, ee) {
129
+ const self = this;
130
+
131
+ if (requestSpec.loop) {
132
+ const steps = _.map(requestSpec.loop, function (rs) {
133
+ if (!rs.emit && !rs.loop) {
134
+ return self.httpDelegate.step(rs, ee);
135
+ }
136
+ return self.step(rs, ee);
137
+ });
138
+
139
+ return engineUtil.createLoopWithCount(requestSpec.count || -1, steps, {
140
+ loopValue: requestSpec.loopValue,
141
+ loopElement: requestSpec.loopElement || '$loopElement',
142
+ overValues: requestSpec.over,
143
+ whileTrue: self.config.processor
144
+ ? self.config.processor[requestSpec.whileTrue]
145
+ : undefined
146
+ });
147
+ }
148
+
149
+ const f = function (context, callback) {
150
+ // Only process emit requests; delegate the rest to the HTTP engine (or think utility)
151
+ if (requestSpec.think) {
152
+ return engineUtil.createThink(
153
+ requestSpec,
154
+ _.get(self.config, 'defaults.think', {})
155
+ );
156
+ }
157
+ if (!requestSpec.emit) {
158
+ const delegateFunc = self.httpDelegate.step(requestSpec, ee);
159
+ return delegateFunc(context, callback);
160
+ }
161
+
162
+ ee.emit('counter', 'socketio.emit', 1);
163
+ ee.emit('rate', 'socketio.emit_rate');
164
+
165
+ const startedAt = process.hrtime();
166
+ const socketio = context.sockets[requestSpec.namespace] || null;
167
+ if (!(requestSpec.emit && socketio)) {
168
+ debug('invalid arguments');
169
+ ee.emit('error', 'invalid arguments');
170
+
171
+ // TODO: Provide a more helpful message
172
+ callback(new Error('socketio: invalid arguments'));
173
+ }
174
+
175
+ const outgoing = requestSpec.emit.channel
176
+ ? [
177
+ template(requestSpec.emit.channel, context),
178
+ template(requestSpec.emit.data, context)
179
+ ]
180
+ : Array.from(requestSpec.emit).map((arg) => template(arg, context));
181
+
182
+ const endCallback = function (err, context, needEmit) {
183
+ if (err) {
184
+ debug(err);
185
+ }
186
+
187
+ if (isAcknowledgeRequired(requestSpec)) {
188
+ const ackCallback = function () {
189
+ const response = {
190
+ data: template(requestSpec.acknowledge.data, context),
191
+ capture: template(requestSpec.acknowledge.capture, context),
192
+ match: template(requestSpec.acknowledge.match, context)
193
+ };
194
+ // Make sure data, capture or match has a default json spec for parsing socketio responses
195
+ _.each(response, function (r) {
196
+ if (_.isPlainObject(r) && !('json' in r)) {
197
+ r.json = '$.0'; // Default to the first callback argument
198
+ }
199
+ });
200
+ // Acknowledge data can take up multiple arguments of the emit callback
201
+ processResponse(ee, arguments, response, context, function (err) {
202
+ if (!err) {
203
+ markEndTime(ee, context, startedAt);
204
+ }
205
+ return callback(err, context);
206
+ });
207
+ };
208
+
209
+ // Acknowledge required so add callback to emit
210
+ if (needEmit) {
211
+ socketio.emit(...outgoing, ackCallback);
212
+ } else {
213
+ ackCallback();
214
+ }
215
+ } else {
216
+ // No acknowledge data is expected, so emit without a listener
217
+ if (needEmit) {
218
+ socketio.emit(...outgoing);
219
+ }
220
+ markEndTime(ee, context, startedAt);
221
+ return callback(null, context);
222
+ }
223
+ }; // endCallback
224
+
225
+ if (isResponseRequired(requestSpec)) {
226
+ const response = {
227
+ channel: template(requestSpec.response.channel, context),
228
+ data: template(requestSpec.response.data, context),
229
+ capture: template(requestSpec.response.capture, context),
230
+ match: template(requestSpec.response.match, context)
231
+ };
232
+
233
+ // Listen for the socket.io response on the specified channel
234
+ let done = false;
235
+
236
+ socketio.on(response.channel, function receive(data) {
237
+ done = true;
238
+ processResponse(ee, data, response, context, function (err) {
239
+ if (!err) {
240
+ markEndTime(ee, context, startedAt);
241
+ }
242
+ // Stop listening on the response channel
243
+ socketio.off(response.channel);
244
+
245
+ return endCallback(err, context, false);
246
+ });
247
+ });
248
+
249
+ // Send the data on the specified socket.io channel
250
+ socketio.emit(...outgoing);
251
+ // If we don't get a response within the timeout, fire an error
252
+ const waitTime = (self.config.timeout || 10) * 1000;
253
+
254
+ setTimeout(function responseTimeout() {
255
+ if (!done) {
256
+ const err = 'response timeout';
257
+ ee.emit('error', err);
258
+ return callback(err, context);
259
+ }
260
+ }, waitTime);
261
+ } else {
262
+ endCallback(null, context, true);
263
+ }
264
+ };
265
+
266
+ function preStep(context, callback) {
267
+ // Set default namespace in emit action
268
+ requestSpec.namespace = template(requestSpec.namespace, context) || '';
269
+
270
+ self.loadContextSocket(requestSpec.namespace, context, function (err) {
271
+ if (err) {
272
+ debug(err);
273
+ ee.emit('error', err.message);
274
+ return callback(err, context);
275
+ }
276
+
277
+ return f(context, callback);
278
+ });
279
+ }
280
+
281
+ if (requestSpec.emit) {
282
+ return preStep;
283
+ } else {
284
+ return f;
285
+ }
286
+ };
287
+
288
+ SocketIoEngine.prototype.loadContextSocket = function (namespace, context, cb) {
289
+ context.sockets = context.sockets || {};
290
+
291
+ if (!context.sockets[namespace]) {
292
+ const target = this.config.target + namespace;
293
+ const tls = this.config.tls || {};
294
+
295
+ const socketioOpts = template(this.socketioOpts, context);
296
+ const options = _.extend(
297
+ {},
298
+ socketioOpts, // templated
299
+ tls
300
+ );
301
+
302
+ const socket = io(target, options);
303
+ context.sockets[namespace] = socket;
304
+
305
+ socket.onAny(() => {
306
+ context.__receivedMessageCount++;
307
+ });
308
+
309
+ socket.once('connect', function () {
310
+ cb(null, socket);
311
+ });
312
+ socket.once('connect_error', function (err) {
313
+ cb(err, null);
314
+ });
315
+ } else {
316
+ return cb(null, context.sockets[namespace]);
317
+ }
318
+ };
319
+
320
+ SocketIoEngine.prototype.closeContextSockets = function (context) {
321
+ if (context.sockets && Object.keys(context.sockets).length > 0) {
322
+ const namespaces = Object.keys(context.sockets);
323
+
324
+ namespaces.forEach(function (namespace) {
325
+ context.sockets[namespace].disconnect();
326
+ });
327
+ }
328
+ };
329
+
330
+ SocketIoEngine.prototype.compile = function (tasks, scenarioSpec, ee) {
331
+ const self = this;
332
+
333
+ function zero(callback, context) {
334
+ context.__receivedMessageCount = 0;
335
+ ee.emit('started');
336
+
337
+ self.loadContextSocket('', context, function done(err) {
338
+ if (err) {
339
+ ee.emit('error', err);
340
+
341
+ return callback(err, context);
342
+ }
343
+
344
+ return callback(null, context);
345
+ });
346
+ }
347
+
348
+ return function scenario(initialContext, callback) {
349
+ initialContext = self.httpDelegate.setInitialContext(initialContext);
350
+
351
+ initialContext._pendingRequests = _.size(
352
+ _.reject(scenarioSpec, function (rs) {
353
+ return typeof rs.think === 'number';
354
+ })
355
+ );
356
+
357
+ const steps = _.flatten([
358
+ function z(cb) {
359
+ return zero(cb, initialContext);
360
+ },
361
+ tasks
362
+ ]);
363
+
364
+ async.waterfall(steps, function scenarioWaterfallCb(err, context) {
365
+ if (err) {
366
+ debug(err);
367
+ }
368
+
369
+ if (context) {
370
+ self.closeContextSockets(context);
371
+ }
372
+
373
+ return callback(err, context);
374
+ });
375
+ };
376
+ };