-
Notifications
You must be signed in to change notification settings - Fork 36
/
Client.js
485 lines (351 loc) · 10.6 KB
/
Client.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
/*jslint node: true, indent: 2, unused: true, maxlen: 80, camelcase: true, esversion: 9 */
const Socket = require('./Socket');
const Transaction = require('./client/Transaction');
const Subscription = require('./client/Subscription');
const BufferWritable = require('./util/buffer/BufferWritable');
const ERROR_MAX_CONTENT_LENGTH = 4096;
class Client extends Socket {
constructor(transportSocket, options = {}) {
options = {
commandHandlers: {},
unknownCommand: onUnknownCommand,
resetDisconnect: true,
...options
};
super(transportSocket, options);
this._options = options;
this._receipts = {};
this._nextReceiptId = 1;
this._subscriptions = {};
this._nextSubcriptionId = 1;
this._nextTransactionId = 1;
this._disconnecting = false;
this._hasDisconnectReceipt = false;
this._resetDisconnect = options.resetDisconnect === true;
}
_onInputEnd() {
if (this._hasDisconnectReceipt) {
this.destroy();
}
else {
const errorMessage = this.hasFinishedOutput() ?
'connection ended without disconnect receipt' :
'connection ended unexpectedly';
this.destroy(this.createProtocolError(errorMessage));
}
}
_beforeSendResponse() {
// No interception of outgoing frame
}
_onDestroyed(exception) {
if (!exception) {
return;
}
for (let key in this._subscriptions) {
this._subscriptions[key].processMessageFrame(exception);
}
}
/*
* Create frame to send to the server. This method returns a Writable stream
* object for sending the frame body content.
*/
sendFrame(command, headers, options) {
if (options) {
let onReceipt = options.onReceipt;
if (typeof options.onError === 'function') {
const originalOnReceipt = onReceipt || function(){};
const onError = options.onError;
this.on('error', onError);
onReceipt = () => {
this.removeListener('error', onError);
originalOnReceipt();
};
}
if (typeof onReceipt === 'function') {
const id = this._nextReceiptId++;
this._receipts[id] = onReceipt;
headers.receipt = id;
}
}
return Socket.prototype.sendFrame.apply(this, arguments);
}
/*
* Send CONNECT frame to the server.
*/
connect(headers, callback) {
if (typeof headers === 'string') {
headers = {'host': headers};
}
headers = Object.assign({
'accept-version': '1.0,1.1,1.2'
}, headers);
let heartbeat = this.getHeartbeat();
if (typeof headers['heart-beat'] === "string") {
const match = headers['heart-beat'].match(/^(\d+) *, *(\d+)$/);
if (match) {
heartbeat = [parseInt(match[1], 10), parseInt(match[2], 10)];
this.setHeartbeat(heartbeat);
}
}
headers['heart-beat'] = heartbeat[0] + "," + heartbeat[1];
this.setCommandHandlers({
'CONNECTED': onConnected,
'ERROR': onError
});
if (typeof callback === 'function') {
const self = this;
(function() {
const onConnected = function(client) {
cleanup();
callback(null, client);
};
const onError = function(error) {
cleanup();
callback(error);
};
const cleanup = function() {
self.removeListener('error', onError);
self.removeListener('connect', onConnected);
};
self.on('error', onError);
self.on('connect', onConnected);
})();
}
const frame = this.sendFrame('CONNECT', headers);
frame.end();
}
/*
* Send a message to the server. This method returns a Writable stream object
* for sending the frame body content.
*/
send(headers, options) {
if (typeof headers === 'string') {
headers = {destination: headers};
}
return this.sendFrame('SEND', headers, options);
}
/*
* Send a message with the specified body to the server.
*/
sendString(headers, body, options, callback) {
const frame = this.send(headers, options);
frame.write(body);
frame.end(callback);
}
begin(headers) {
if (typeof headers !== 'object') {
if (typeof headers !== 'undefined') {
headers = {transaction: headers};
}
else {
headers = {};
}
}
if (!('transaction' in headers)) {
headers.transaction = this._nextTransactionId++;
}
const transaction = new Transaction(headers.transaction, this);
this.sendFrame('BEGIN', headers).end();
return transaction;
}
subscribe(headers, messageListener) {
if (typeof headers === 'string') {
headers = {destination: headers};
}
let id = headers.id !== undefined ?
headers.id : this._nextSubcriptionId++;
while (this._subscriptions[id] !== undefined) {
id = this._nextSubcriptionId++;
}
headers.id = id;
const ack = headers.ack || 'auto';
ensureValidAckMode(ack);
const subscription = new Subscription(id, ack, messageListener, this);
this._subscriptions[id] = subscription;
this.sendFrame('SUBSCRIBE', headers).end();
return subscription;
}
_getAckHeaders(message, userHeaders) {
return Object.assign({}, userHeaders, {
'subscription': message.headers.subscription,
'message-id': message.headers['message-id'],
'id': message.headers.ack
});
}
ack(message, headers, sendOptions, callback) {
const frame = this.sendFrame('ACK',
this._getAckHeaders(message, headers), sendOptions);
frameHandler(frame, callback);
}
nack (message, headers, sendOptions, callback) {
const frame = this.sendFrame('NACK',
this._getAckHeaders(message, headers), sendOptions);
frameHandler(frame, callback);
}
getSubscription(id) {
return this._subscriptions[id];
}
setImplicitSubscription(id, ack, messageListener) {
if (this._subscriptions.hasOwnProperty(id)) {
throw new Error('subscription id \'' + id + '\' already in use');
}
if (ack === void 0 || ack === null){
ack = 'auto';
}
ensureValidAckMode(ack);
const subscription = new Subscription(id, ack, messageListener, this);
this._subscriptions[id] = subscription;
return subscription;
}
/*
* Perform graceful disconnect from server. This operation does not complete
* until all messages are acknowledged.
*/
disconnect(callback) {
if (typeof callback === 'function') {
const self = this;
(function() {
const onEnd = function(client) {
cleanup();
callback(null, client);
};
const onError = function(error) {
cleanup();
callback(error);
};
const cleanup = function() {
self.removeListener('end', onEnd);
self.removeListener('error', onError);
};
self.on('end', onEnd);
self.on('error', onError);
})();
}
this.sendFrame('DISCONNECT', {}, {
onReceipt: () => {
this._hasDisconnectReceipt = true;
const transport = this.getTransportSocket();
if (this._resetDisconnect) {
this.destroy();
}
else{
transport.end();
}
}
}).end(this._finishOutput.bind(this));
// Keep the transport output open until the receipt is processed just in
// case the transport is not configured to handle half-open connections.
this._disconnecting = true;
}
readEmptyBody(frame, callback) {
frame.readEmptyBody((isEmpty) => {
if (isEmpty) {
if (typeof callback === 'function') {
callback.call(this);
}
}
else {
this.destroy(this.createProtocolError('expected empty body frame'));
}
});
}
/*
* Get the connection options that the client was initialized with.
*/
getOptions() {
return this._options;
}
}
function ensureValidAckMode(mode) {
const validAckModes = [
'auto', 'client', 'client-individual'
];
if (validAckModes.indexOf(mode) === -1) {
throw new Error('invalid ack mode: \'' + mode + '\'');
}
}
function frameHandler(frame, callback) {
const cb = function (err) {
if (typeof callback === 'function') {
callback(err || new Error('The frame failed but no error was provided'));
}
};
frame.on('error', cb);
frame.end(function (err) {
frame.removeListener('error', cb);
if (typeof callback === 'function') {
callback(err);
}
});
}
function onConnected(frame, beforeSendResponse) {
// If no version header is present then assume the server is running stomp 1.0
// protocol
this.setVersion(frame.headers.version || '1.0');
this.setCommandHandlers({
'MESSAGE': onMessage,
'RECEIPT': onReceipt,
'ERROR': onError
});
this.readEmptyBody(frame, () => {
if (frame.headers['heart-beat'] !== undefined) {
const heartbeat = frame.headers['heart-beat']
.split(',').map(function(x) {
return parseInt(x, 10);
});
if ( heartbeat.length > 1 &&
!isNaN(heartbeat[0]) &&
!isNaN(heartbeat[1]) ) {
this._runHeartbeat(heartbeat[0], heartbeat[1]);
}
}
this.headers = frame.headers;
this.emit('connect', this);
beforeSendResponse();
});
}
function onError(frame) {
const message = frame.headers.message ? frame.headers.message :
'server sent ERROR frame';
const error = this.createApplicationError(message);
if ( frame.headers['content-type'] === 'text/plain' &&
frame.headers['content-length'] <= ERROR_MAX_CONTENT_LENGTH) {
const content = new BufferWritable(Buffer.alloc(ERROR_MAX_CONTENT_LENGTH));
frame.on('end', function() {
error.longMessage = content.getWrittenSlice().toString();
this.destroy(error);
});
frame.pipe(content);
}
else {
this.destroy(error);
}
}
function onMessage(frame, beforeSendResponse) {
const subId = frame.headers.subscription;
const subscription = this._subscriptions[subId];
if (subscription === void 0) {
this.destroy(this.createProtocolError('invalid subscription id ' + subId));
return;
}
subscription.processMessageFrame(null, frame);
beforeSendResponse();
}
function onReceipt(frame, beforeSendResponse) {
const id = frame.headers['receipt-id'];
if (id === undefined || this._receipts[id] === undefined) {
this.destroy(this.createProtocolError('invalid receipt'));
return;
}
this.readEmptyBody(frame, function() {
this._receipts[id].call(this);
delete this._receipts[id];
beforeSendResponse();
});
}
function onUnknownCommand(frame) {
this.destroy(this.createProtocolError(
'unknown command \'' + frame.command + '\''
));
}
module.exports = Client;