-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
560 lines (389 loc) · 11.8 KB
/
index.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
function HttpServer(eventManager) {
var HttpRequest = require('mage-http-request.js');
this.transports = {
http: HttpRequest
};
this.cmdHooks = [];
this.queryId = 0;
this.commandSystemStarted = false;
this.cmdMode = 'free';
this.simulatedTransportError = null;
this.eventManager = eventManager;
}
// transport
HttpServer.prototype.createTransport = function (type, options) {
// check transport availability
var Transport = this.transports[type];
if (!Transport) {
throw new Error('No transport type "' + type + '" found.');
}
return new Transport(options);
};
// command center
HttpServer.prototype.setCmdMode = function (mode) {
if (mode !== 'free' && mode !== 'blocking') {
throw new Error('Unrecognized command mode "' + mode + '", use "free" or "blocking".');
}
this.cmdMode = mode;
};
HttpServer.prototype.registerCommandHook = function (name, fn) {
// replace the old command hook if there is one
for (var i = 0; i < this.cmdHooks.length; i++) {
var cmdHook = this.cmdHooks[i];
if (cmdHook.name === name) {
cmdHook.fn = fn;
return;
}
}
// else append to the end
this.cmdHooks.push({ name: name, fn: fn });
};
HttpServer.prototype.unregisterCommandHook = function (name) {
for (var i = 0; i < this.cmdHooks.length; i++) {
var cmdHook = this.cmdHooks[i];
if (cmdHook.name === name) {
this.cmdHooks.splice(i, 1);
return;
}
}
};
HttpServer.prototype.sendCommand = function () {
console.warn('httpServer#sendCommand: command system not yet set up.');
};
HttpServer.prototype.resend = function () {
console.warn('httpServer.resend: command system not yet set up.');
};
HttpServer.prototype.discard = function () {
console.warn('httpServer.discard: command system not yet set up.');
};
HttpServer.prototype.queue = function () {
console.warn('httpServer.queue: command system not yet set up.');
};
HttpServer.prototype.piggyback = function () {
console.warn('httpServer.piggyback: command system not yet set up.');
};
HttpServer.prototype.simulateTransportError = function (type) {
this.simulatedTransportError = type;
};
HttpServer.prototype.setupCommandSystem = function (config) {
if (this.commandSystemStarted) {
return;
}
var hr = this.createTransport('http', config.httpOptions);
var that = this;
// if this timer is active, we're about to send batches.current (which may still grow).
var timer = null;
// if "streaming" is true, we will send batches.current the moment the running request returns.
var streaming = false;
// placeholder for unlock function, to avoid circular refs and upset jslint
var unlock;
var batches = {
current: [], // the commands we're building that will be sent _very_ soon
sending: [] // the commands that are currently being sent
};
// "queueing" is true when user commands are to be stored in the current batch, and should be
// sent off asap (through httpServer.queue method)
var queueing = false;
// "piggybacking" is true when user commands are to be stored in the current batch (through
// httpServer.piggyback method)
var piggybacking = false;
// "locked" is true for as long as a queryId has not been successfully completed.
var locked = false;
function onCommandResponse(transportError, responses) {
// this is the response to the request that is now in the batches.sending array
// [
// [sysError] or:
// [null, userError] or:
// [null, null, response obj, events array] // where events may be left out
// ]
if (that.simulatedTransportError) {
transportError = that.simulatedTransportError;
that.simulatedTransportError = null;
}
if (transportError) {
// "network": network failure (offline or timeout), retry is the only correct option
// "busy": usually treat quietly
return that.eventManager.emitEvent('io.error.' + transportError, {
reason: transportError,
info: responses
});
}
// unlock the command system for the next user command(s)
var batch = batches.sending;
unlock();
// from here on, handle all responses and drop the queue that we just received answers to
that.eventManager.emitEvent('io.response');
// handle the command responses
for (var i = 0; i < responses.length; i += 1) {
var response = responses[i];
var cmd = batch[i];
if (!cmd) {
console.warn('No command found for response', response);
continue;
}
var errorCode = response[0];
var cmdResponse = response[1];
var events = response[2];
if (events) {
that.eventManager.emitEvents(events);
}
/*
cmd = {
name: cmdName,
params: params,
files: files,
cb: cb
};
*/
if (!errorCode) {
that.eventManager.emit('io.' + cmd.name, cmdResponse, cmd.params);
}
if (cmd.cb) {
if (errorCode) {
cmd.cb(errorCode);
} else {
cmd.cb(null, cmdResponse);
}
}
}
}
var nextFileId = 0;
function sendBatch(batch) {
// no need to check for locked here, since that is taken care of by the caller of sendBatch
locked = true;
timer = null;
nextFileId = 0;
var i, len;
// prepare data extraction
len = batch.length;
var cmdNames = new Array(len);
var cmdParams = new Array(len);
var hasCallbacks = false;
var header = [], data, files;
for (i = 0; i < len; i += 1) {
var cmd = batch[i];
cmdNames[i] = cmd.name;
cmdParams[i] = cmd.params;
if (cmd.files) {
if (!files) {
files = {};
}
for (var fileId in cmd.files) {
files[fileId] = cmd.files[fileId];
}
}
if (cmd.cb) {
hasCallbacks = true;
}
}
data = cmdParams.join('\n');
// execute all hooks
for (i = 0, len = that.cmdHooks.length; i < len; i++) {
var hook = that.cmdHooks[i];
var hookOutput = hook.fn(data);
if (hookOutput) {
hookOutput.name = hook.name;
header.push(hookOutput);
}
}
// emit io.send event with all command names as the argument
that.eventManager.emitEvent('io.send', cmdNames);
// create a request
var url = encodeURI(config.url + '/' + cmdNames.join(','));
var urlParams = {};
if (hasCallbacks) {
urlParams.queryId = that.queryId;
}
// prepend the header before the cmd parameter data
data = JSON.stringify(header) + '\n' + data;
// send request to server
if (files) {
var FormData = window.FormData;
if (!FormData) {
console.warn('window.FormData class not available, old browser?');
} else {
var form = new FormData();
form.append('cmddata', data);
for (var name in files) {
form.append(name, files[name]);
}
data = form;
}
}
hr.send('POST', url, urlParams, data, null, onCommandResponse);
}
function sendCurrentBatch() {
batches.sending = batches.current;
batches.current = [];
// set streaming to false, a next user command can turn it on again
streaming = false;
sendBatch(batches.sending);
}
function scheduleCurrentBatch() {
// - Set streaming to true, so nothing can pause us
// - If no timer has been set yet, create a query ID, start a timer and prepare to
// send a new batch.
streaming = true;
if (locked) {
// if the current stream is locked, the unlocking will trigger this function to be
// called again.
return;
}
if (timer === null) {
that.queryId += 1;
timer = window.setTimeout(sendCurrentBatch, 0);
that.eventManager.emitEvent('io.queued', that.queryId);
}
}
function resendBatch() {
sendBatch(batches.sending);
}
unlock = function () {
// discard the last sent batch
batches.sending = [];
locked = false;
// if there is a batch ready to be sent again, trigger the send
if (batches.current.length > 0 && streaming) {
scheduleCurrentBatch();
}
};
// file upload helpers
var uploads;
function Upload(file) {
this.file = file;
}
Upload.prototype.toJSON = function () {
// returns the ID of the file
var id = '__file' + nextFileId;
nextFileId += 1;
if (!uploads) {
uploads = {};
}
uploads[id] = this.file;
return id;
};
var Blob = window.Blob;
var File = window.File;
var FileList = window.FileList;
/**
* Use this method to transform a File, Blob or FileList object to an object type that httpServer
* can upload. The result of this function may safely be put in of any parameter of a user
* command call.
*
* @param {File|Blob|FileList} file
* @param {boolean} silent Set to true to suppress errors when the type doesn't match
* @returns {Upload|Upload[]} An Upload instance, or an array of Upload instances
*/
this.transformUpload = function (file, silent) {
if (file instanceof Blob || file instanceof File) {
return new Upload(file);
}
if (file instanceof FileList) {
var list = [];
for (var i = 0; i < file.length; i++) {
list.push(new Upload(file[i]));
}
return list;
}
if (!silent) {
throw new TypeError('Given argument is not a Blob, File or FileList');
}
};
/**
* This will deep-inspect any given object and transform File, Blob or FileList objects using
* the transformUpload method.
*
* @param {Object} obj
*/
this.transformEmbeddedUploads = function (obj) {
var keys = Object.keys(obj || {});
for (var i = 0; i < keys.length; i++) {
var value = obj[keys[i]];
if (value && typeof value === 'object') {
var upload = this.transformUpload(value, true);
if (upload) {
obj[keys[i]] = upload;
} else {
this.transformEmbeddedUploads(obj[keys[i]]);
}
}
}
};
this.sendCommand = function (cmdName, params, cb) {
if (typeof cmdName !== 'string') {
throw new TypeError('Command name is not a string: ' + cmdName);
}
if (params && typeof params !== 'object') {
throw new TypeError('Command params is not an object: ' + params);
}
if (cb && typeof cb !== 'function') {
throw new TypeError('Command callback is not a function: ' + cb);
}
// cmdName is dot notation "moduleName.commandName"
// Serialize the params instantly, so that they may be altered right after this call without
// affecting command execution. The uploads list should be reset before, and after
// stringification.
uploads = null;
params = JSON.stringify(params);
// create the command object
var cmd = {
name: cmdName,
params: params,
files: uploads,
cb: cb
};
uploads = null;
if (piggybacking) {
// Add the command to the current queue, but don't start sending anything just yet.
// The next batch that gets scheduled will take these along.
batches.current.push(cmd);
} else if (locked) {
// We're currently sending, but if the next batch is accessible, we can add the command
// to it. That way it will be sent when the open request returns.
if (queueing || that.cmdMode === 'free') {
// add to current batch and make sure it will be sent off
batches.current.push(cmd);
scheduleCurrentBatch();
} else {
console.warn('Could not execute user command: busy.', cmd);
that.eventManager.emitEvent('io.error.busy', {
reason: 'busy',
command: cmd,
blockedBy: batches.sending
});
}
} else {
// The command can be executed right now, so add to the current batch and make sure it
// will be sent off
batches.current.push(cmd);
scheduleCurrentBatch();
}
};
// the discard function can be called if after a transport error, when do not want to retry
// it will unlock the command center for the next user command
this.discard = function () {
unlock();
that.eventManager.emitEvent('io.discarded');
};
this.resend = function () {
if (!batches.sending.length) {
console.warn('No commands to retry. Discarding instead.');
that.discard();
return;
}
that.eventManager.emitEvent('io.resend');
resendBatch();
};
this.queue = function (fn) {
queueing = true;
fn();
queueing = false;
};
this.piggyback = function (fn) {
piggybacking = true;
fn();
piggybacking = false;
};
this.commandSystemStarted = true;
};
module.exports = HttpServer;