forked from postwait/node-amqp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amqp.js
2344 lines (1942 loc) · 66.1 KB
/
amqp.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var events = require('events'),
util = require('util'),
net = require('net'),
protocol,
jspack = require('./jspack').jspack,
Buffer = require('buffer').Buffer,
Promise = require('./promise').Promise,
URL = require('url'),
AMQPTypes = require('./constants').AMQPTypes,
Indicators = require('./constants').Indicators,
FrameType = require('./constants').FrameType;
function mixin () {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, source;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !(typeof target === 'function') )
target = {};
// mixin process itself if only one argument is passed
if ( length == i ) {
target = GLOBAL;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (source = arguments[i]) != null ) {
// Extend the base object
Object.getOwnPropertyNames(source).forEach(function(k){
var d = Object.getOwnPropertyDescriptor(source, k) || {value: source[k]};
if (d.get) {
target.__defineGetter__(k, d.get);
if (d.set) {
target.__defineSetter__(k, d.set);
}
}
else {
// Prevent never-ending loop
if (target === d.value) {
return;
}
if (deep && d.value && typeof d.value === "object") {
target[k] = mixin(deep,
// Never move original objects, clone them
source[k] || (d.value.length != null ? [] : {})
, d.value);
}
else {
target[k] = d.value;
}
}
});
}
}
// Return the modified object
return target;
}
var debugLevel = process.env['NODE_DEBUG_AMQP'] ? 1 : 0;
function debug (x) {
if (debugLevel > 0) console.error(x + '\n');
}
// a look up table for methods recieved
// indexed on class id, method id
var methodTable = {};
// methods keyed on their name
var methods = {};
// classes keyed on their index
var classes = {};
(function () { // anon scope for init
//debug("initializing amqp methods...");
protocol = require('./amqp-definitions-0-9-1');
for (var i = 0; i < protocol.classes.length; i++) {
var classInfo = protocol.classes[i];
classes[classInfo.index] = classInfo;
for (var j = 0; j < classInfo.methods.length; j++) {
var methodInfo = classInfo.methods[j];
var name = classInfo.name
+ methodInfo.name[0].toUpperCase()
+ methodInfo.name.slice(1);
//debug(name);
var method = { name: name
, fields: methodInfo.fields
, methodIndex: methodInfo.index
, classIndex: classInfo.index
};
if (!methodTable[classInfo.index]) methodTable[classInfo.index] = {};
methodTable[classInfo.index][methodInfo.index] = method;
methods[name] = method;
}
}
})(); // end anon scope
// parser
var maxFrameBuffer = 131072; // 128k, same as rabbitmq (which was
// copying qpid)
// An interruptible AMQP parser.
//
// type is either 'server' or 'client'
// version is '0-9-1'.
//
// Instances of this class have several callbacks
// - onMethod(channel, method, args);
// - onHeartBeat()
// - onContent(channel, buffer);
// - onContentHeader(channel, class, weight, properties, size);
//
// This class does not subclass EventEmitter, in order to reduce the speed
// of emitting the callbacks. Since this is an internal class, that should
// be fine.
function AMQPParser (version, type) {
this.isClient = (type == 'client');
this.state = this.isClient ? 'frameHeader' : 'protocolHeader';
if (version != '0-9-1') this.throwError("Unsupported protocol version");
var frameHeader = new Buffer(7);
frameHeader.used = 0;
var frameBuffer, frameType, frameChannel;
var self = this;
function header(data) {
var fh = frameHeader;
var needed = fh.length - fh.used;
data.copy(fh, fh.used, 0, data.length);
fh.used += data.length; // sloppy
if (fh.used >= fh.length) {
fh.read = 0;
frameType = fh[fh.read++];
frameChannel = parseInt(fh, 2);
var frameSize = parseInt(fh, 4);
fh.used = 0; // for reuse
if (frameSize > maxFrameBuffer) {
self.throwError("Oversized frame " + frameSize);
}
frameBuffer = new Buffer(frameSize);
frameBuffer.used = 0;
return frame(data.slice(needed));
}
else { // need more!
return header;
}
}
function frame(data) {
var fb = frameBuffer;
var needed = fb.length - fb.used;
var sourceEnd = (fb.length > data.length) ? data.length : fb.length;
data.copy(fb, fb.used, 0, sourceEnd);
fb.used += data.length;
if (data.length > needed) {
return frameEnd(data.slice(needed));
}
else if (data.length == needed) {
return frameEnd;
}
else {
return frame;
}
}
function frameEnd(data) {
if (data.length > 0) {
if (data[0] === Indicators.FRAME_END) {
switch (frameType) {
case FrameType.METHOD:
self._parseMethodFrame(frameChannel, frameBuffer);
break;
case FrameType.HEADER:
self._parseHeaderFrame(frameChannel, frameBuffer);
break;
case FrameType.BODY:
if (self.onContent) {
self.onContent(frameChannel, frameBuffer);
}
break;
case FrameType.HEARTBEAT:
debug("heartbeat");
if (self.onHeartBeat) self.onHeartBeat();
break;
default:
self.throwError("Unhandled frame type " + frameType);
break;
}
return header(data.slice(1));
}
else {
self.throwError("Missing frame end marker");
}
}
else {
return frameEnd;
}
}
self.parse = header;
}
// If there's an error in the parser, call the onError handler or throw
AMQPParser.prototype.throwError = function (error) {
if(this.onError) this.onError(error);
else throw new Error(error);
};
// Everytime data is recieved on the socket, pass it to this function for
// parsing.
AMQPParser.prototype.execute = function (data) {
// This function only deals with dismantling and buffering the frames.
// It delegates to other functions for parsing the frame-body.
debug('execute: ' + data.toString());
this.parse = this.parse(data);
};
// parse Network Byte Order integers. size can be 1,2,4,8
function parseInt (buffer, size) {
switch (size) {
case 1:
return buffer[buffer.read++];
case 2:
return (buffer[buffer.read++] << 8) + buffer[buffer.read++];
case 4:
return (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) +
(buffer[buffer.read++] << 8) + buffer[buffer.read++];
case 8:
return (buffer[buffer.read++] << 56) + (buffer[buffer.read++] << 48) +
(buffer[buffer.read++] << 40) + (buffer[buffer.read++] << 32) +
(buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) +
(buffer[buffer.read++] << 8) + buffer[buffer.read++];
default:
throw new Error("cannot parse ints of that size");
}
}
function parseShortString (buffer) {
var length = buffer[buffer.read++];
var s = buffer.toString('utf8', buffer.read, buffer.read+length);
buffer.read += length;
return s;
}
function parseLongString (buffer) {
var length = parseInt(buffer, 4);
var s = buffer.slice(buffer.read, buffer.read + length);
buffer.read += length;
return s.toString();
}
function parseSignedInteger (buffer) {
var int = parseInt(buffer, 4);
if (int & 0x80000000) {
int |= 0xEFFFFFFF;
int = -int;
}
return int;
}
function parseValue (buffer) {
switch (buffer[buffer.read++]) {
case AMQPTypes.STRING:
return parseLongString(buffer);
case AMQPTypes.INTEGER:
return parseInt(buffer, 4);
case AMQPTypes.DECIMAL:
var dec = parseInt(buffer, 1);
var num = parseInt(buffer, 4);
return num / (dec * 10);
case AMQPTypes._64BIT_FLOAT:
var b = [];
for (var i = 0; i < 8; ++i)
b[i] = buffer[buffer.read++];
return (new jspack(true)).Unpack('d', b);
case AMQPTypes._32BIT_FLOAT:
var b = [];
for (var i = 0; i < 4; ++i)
b[i] = buffer[buffer.read++];
return (new jspack(true)).Unpack('f', b);
case AMQPTypes.TIME:
var int = parseInt(buffer, 8);
return (new Date()).setTime(int * 1000);
case AMQPTypes.HASH:
return parseTable(buffer);
case AMQPTypes.SIGNED_64BIT:
return parseInt(buffer, 8);
case AMQPTypes.BOOLEAN:
return (parseInt(buffer, 1) > 0);
case AMQPTypes.BYTE_ARRAY:
var len = parseInt(buffer, 4);
var buf = new Buffer(len);
buffer.copy(buf, 0, buffer.read, buffer.read + len);
buffer.read += len;
return buf;
case AMQPTypes.ARRAY:
var len = parseInt(buffer, 4);
var end = buffer.read + len;
var arr = [];
while (buffer.read < end) {
arr.push(parseValue(buffer));
}
return arr;
default:
throw new Error("Unknown field value type " + buffer[buffer.read-1]);
}
}
function parseTable (buffer) {
var length = buffer.read + parseInt(buffer, 4);
var table = {};
while (buffer.read < length) {
table[parseShortString(buffer)] = parseValue(buffer);
}
return table;
}
function parseFields (buffer, fields) {
var args = {};
var bitIndex = 0;
var value;
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
//debug("parsing field " + field.name + " of type " + field.domain);
switch (field.domain) {
case 'bit':
// 8 bits can be packed into one octet.
// XXX check if bitIndex greater than 7?
value = (buffer[buffer.read] & (1 << bitIndex)) ? true : false;
if (fields[i+1] && fields[i+1].domain == 'bit') {
bitIndex++;
} else {
bitIndex = 0;
buffer.read++;
}
break;
case 'octet':
value = buffer[buffer.read++];
break;
case 'short':
value = parseInt(buffer, 2);
break;
case 'long':
value = parseInt(buffer, 4);
break;
case 'timestamp':
case 'longlong':
value = parseInt(buffer, 8);
break;
case 'shortstr':
value = parseShortString(buffer);
break;
case 'longstr':
value = parseLongString(buffer);
break;
case 'table':
value = parseTable(buffer);
break;
default:
throw new Error("Unhandled parameter type " + field.domain);
}
//debug("got " + value);
args[field.name] = value;
}
return args;
}
AMQPParser.prototype._parseMethodFrame = function (channel, buffer) {
buffer.read = 0;
var classId = parseInt(buffer, 2),
methodId = parseInt(buffer, 2);
// Make sure that this is a method that we understand.
if (!methodTable[classId] || !methodTable[classId][methodId]) {
this.throwError("Received unknown [classId, methodId] pair [" +
classId + ", " + methodId + "]");
}
var method = methodTable[classId][methodId];
if (!method) this.throwError("bad method?");
var args = parseFields(buffer, method.fields);
if (this.onMethod) {
this.onMethod(channel, method, args);
}
};
AMQPParser.prototype._parseHeaderFrame = function (channel, buffer) {
buffer.read = 0;
var classIndex = parseInt(buffer, 2);
var weight = parseInt(buffer, 2);
var size = parseInt(buffer, 8);
var classInfo = classes[classIndex];
if (classInfo.fields.length > 15) {
this.throwError("TODO: support more than 15 properties");
}
var propertyFlags = parseInt(buffer, 2);
var fields = [];
for (var i = 0; i < classInfo.fields.length; i++) {
var field = classInfo.fields[i];
// groan.
if (propertyFlags & (1 << (15-i))) fields.push(field);
}
var properties = parseFields(buffer, fields);
if (this.onContentHeader) {
this.onContentHeader(channel, classInfo, weight, properties, size);
}
};
function serializeFloat(b, size, value, bigEndian) {
var jp = new jspack(bigEndian);
switch(size) {
case 4:
var x = jp.Pack('f', [value]);
for (var i = 0; i < x.length; ++i)
b[b.used++] = x[i];
break;
case 8:
var x = jp.Pack('d', [value]);
for (var i = 0; i < x.length; ++i)
b[b.used++] = x[i];
break;
default:
throw new Error("Unknown floating point size");
}
}
function serializeInt (b, size, int) {
if (b.used + size > b.length) {
throw new Error("write out of bounds");
}
// Only 4 cases - just going to be explicit instead of looping.
switch (size) {
// octet
case 1:
b[b.used++] = int;
break;
// short
case 2:
b[b.used++] = (int & 0xFF00) >> 8;
b[b.used++] = (int & 0x00FF) >> 0;
break;
// long
case 4:
b[b.used++] = (int & 0xFF000000) >> 24;
b[b.used++] = (int & 0x00FF0000) >> 16;
b[b.used++] = (int & 0x0000FF00) >> 8;
b[b.used++] = (int & 0x000000FF) >> 0;
break;
// long long
case 8:
b[b.used++] = (int & 0xFF00000000000000) >> 56;
b[b.used++] = (int & 0x00FF000000000000) >> 48;
b[b.used++] = (int & 0x0000FF0000000000) >> 40;
b[b.used++] = (int & 0x000000FF00000000) >> 32;
b[b.used++] = (int & 0x00000000FF000000) >> 24;
b[b.used++] = (int & 0x0000000000FF0000) >> 16;
b[b.used++] = (int & 0x000000000000FF00) >> 8;
b[b.used++] = (int & 0x00000000000000FF) >> 0;
break;
default:
throw new Error("Bad size");
}
}
function serializeShortString (b, string) {
if (typeof(string) != "string") {
throw new Error("param must be a string");
}
var byteLength = Buffer.byteLength(string, 'utf8');
if (byteLength > 0xFF) {
throw new Error("String too long for 'shortstr' parameter");
}
if (1 + byteLength + b.used >= b.length) {
throw new Error("Not enough space in buffer for 'shortstr'");
}
b[b.used++] = byteLength;
b.write(string, b.used, 'utf8');
b.used += byteLength;
}
function serializeLongString (b, string) {
// we accept string, object, or buffer for this parameter.
// in the case of string we serialize it to utf8.
if (typeof(string) == 'string') {
var byteLength = Buffer.byteLength(string, 'utf8');
serializeInt(b, 4, byteLength);
b.write(string, b.used, 'utf8');
b.used += byteLength;
} else if (typeof(string) == 'object') {
serializeTable(b, string);
} else {
// data is Buffer
var byteLength = string.length;
serializeInt(b, 4, byteLength);
b.write(string, b.used); // memcpy
b.used += byteLength;
}
}
function serializeDate(b, date) {
serializeInt(b, 8, date.valueOf() / 1000);
}
function serializeBuffer(b, buffer) {
serializeInt(b, 4, buffer.length);
buffer.copy(b, b.used, 0);
b.used += buffer.length;
}
function serializeBase64(b, buffer) {
serializeLongString(b, buffer.toString('base64'));
}
function isBigInt(value) {
return value > 0xffffffff;
}
function getCode(dec) {
var hexArray = "0123456789ABCDEF".split('');
var code1 = Math.floor(dec / 16);
var code2 = dec - code1 * 16;
return hexArray[code2];
}
function isFloat(value)
{
return value === +value && value !== (value|0);
}
function serializeValue (b, value) {
switch (typeof(value)) {
case 'string':
b[b.used++] = 'S'.charCodeAt(0);
serializeLongString(b, value);
break;
case 'number':
if (!isFloat(value)) {
if (isBigInt(value)) {
// 64-bit uint
b[b.used++] = 'l'.charCodeAt(0);
serializeInt(b, 8, value);
} else {
//32-bit uint
b[b.used++] = 'I'.charCodeAt(0);
serializeInt(b, 4, value);
}
} else {
//64-bit float
b[b.used++] = 'd'.charCodeAt(0);
serializeFloat(b, 8, value);
}
break;
case 'boolean':
b[b.used++] = 't'.charCodeAt(0);
b[b.used++] = value;
break;
default:
if (value instanceof Date) {
b[b.used++] = 'T'.charCodeAt(0);
serializeDate(b, value);
} else if (value instanceof Buffer) {
b[b.used++] = 'x'.charCodeAt(0);
serializeBuffer(b, value);
} else if (util.isArray(value)) {
b[b.used++] = 'A'.charCodeAt(0);
serializeArray(b, value);
} else if (typeof(value) === 'object') {
b[b.used++] = 'F'.charCodeAt(0);
serializeTable(b, value);
} else {
this.throwError("unsupported type in amqp table: " + typeof(value));
}
}
}
function serializeTable (b, object) {
if (typeof(object) != "object") {
throw new Error("param must be an object");
}
// Save our position so that we can go back and write the length of this table
// at the beginning of the packet (once we know how many entries there are).
var lengthIndex = b.used;
b.used += 4; // sizeof long
var startIndex = b.used;
for (var key in object) {
if (!object.hasOwnProperty(key)) continue;
serializeShortString(b, key);
serializeValue(b, object[key]);
}
var endIndex = b.used;
b.used = lengthIndex;
serializeInt(b, 4, endIndex - startIndex);
b.used = endIndex;
}
function serializeArray (b, arr) {
// Save our position so that we can go back and write the byte length of this array
// at the beginning of the packet (once we have serialized all elements).
var lengthIndex = b.used;
b.used += 4; // sizeof long
var startIndex = b.used;
var len = arr.length;
for (var i = 0; i < len; i++) {
serializeValue(b, arr[i]);
}
var endIndex = b.used;
b.used = lengthIndex;
serializeInt(b, 4, endIndex - startIndex);
b.used = endIndex;
}
function serializeFields (buffer, fields, args, strict) {
var bitField = 0;
var bitIndex = 0;
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var domain = field.domain;
if (!(field.name in args)) {
if (strict) {
throw new Error("Missing field '" + field.name + "' of type '" + domain + "' while executing AMQP method '" + arguments.callee.caller.arguments[1].name + "'");
}
continue;
}
var param = args[field.name];
//debug("domain: " + domain + " param: " + param);
switch (domain) {
case 'bit':
if (typeof(param) != "boolean") {
throw new Error("Unmatched field " + JSON.stringify(field));
}
if (param) bitField |= (1 << bitIndex);
bitIndex++;
if (!fields[i+1] || fields[i+1].domain != 'bit') {
debug('SET bit field ' + field.name + ' 0x' + bitField.toString(16));
buffer[buffer.used++] = bitField;
bitField = 0;
bitIndex = 0;
}
break;
case 'octet':
if (typeof(param) != "number" || param > 0xFF) {
throw new Error("Unmatched field " + JSON.stringify(field));
}
buffer[buffer.used++] = param;
break;
case 'short':
if (typeof(param) != "number" || param > 0xFFFF) {
throw new Error("Unmatched field " + JSON.stringify(field));
}
serializeInt(buffer, 2, param);
break;
case 'long':
if (typeof(param) != "number" || param > 0xFFFFFFFF) {
throw new Error("Unmatched field " + JSON.stringify(field));
}
serializeInt(buffer, 4, param);
break;
case 'timestamp':
case 'longlong':
serializeInt(buffer, 8, param);
break;
case 'shortstr':
if (typeof(param) != "string" || param.length > 0xFF) {
throw new Error("Unmatched field " + JSON.stringify(field));
}
serializeShortString(buffer, param);
break;
case 'longstr':
serializeLongString(buffer, param);
break;
case 'table':
if (typeof(param) != "object") {
throw new Error("Unmatched field " + JSON.stringify(field));
}
serializeTable(buffer, param);
break;
default:
throw new Error("Unknown domain value type " + domain);
}
}
}
function Connection (connectionArgs, options, readyCallback) {
net.Stream.call(this);
var self = this;
this.setOptions(connectionArgs);
this.setImplOptions(options);
if (typeof readyCallback === 'function') {
this._readyCallback = readyCallback;
}
var parser;
var backoffTime = null;
this.connectionAttemptScheduled = false;
var backoff = function () {
if (self._inboundHeartbeatTimer !== null) {
clearTimeout(self._inboundHeartbeatTimer);
self._inboundHeartbeatTimer = null;
}
if (self._outboundHeartbeatTimer !== null) {
clearTimeout(self._outboundHeartbeatTimer);
self._outboundHeartbeatTimer = null;
}
if (!self.connectionAttemptScheduled) {
// Set to true, as we are presently in the process of scheduling one.
self.connectionAttemptScheduled = true;
// Kill the socket, if it hasn't been killed already.
self.end();
// Reset parser state
parser = null;
// In order for our reconnection to be seamless, we have to notify the
// channels that they are no longer connected so that nobody attempts
// to send messages which would be doomed to fail.
for (var channel in self.channels) {
if (channel != 0) {
self.channels[channel].state = 'closed';
}
}
// Queues are channels (so we have already marked them as closed), but
// queues have special needs, since the subscriptions will no longer
// be known to the server when we reconnect. Mark the subscriptions as
// closed so that we can resubscribe them once we are reconnected.
for (var queue in self.queues) {
for (var index in self.queues[queue].consumerTagOptions) {
self.queues[queue].consumerTagOptions[index]['state'] = 'closed';
}
}
// Begin reconnection attempts
if (self.implOptions.reconnect) {
// Don't thrash, use a backoff strategy.
if (backoffTime === null) {
// This is the first time we've failed since a successful connection,
// so use the configured backoff time without any modification.
backoffTime = self.implOptions.reconnectBackoffTime;
} else if (self.implOptions.reconnectBackoffStrategy === 'exponential') {
// If you've configured exponential backoff, we'll double the
// backoff time each subsequent attempt until success.
backoffTime *= 2;
// limit the maxium timeout, to avoid potentially unlimited stalls
if(backoffTime > self.implOptions.reconnectExponentialLimit){
backoffTime = self.implOptions.reconnectExponentialLimit;
}
} else if (self.implOptions.reconnectBackoffStrategy === 'linear') {
// Linear strategy is the default. In this case, we will retry at a
// constant interval, so there's no need to change the backoff time
// between attempts.
} else {
// TODO should we warn people if they picked a nonexistent strategy?
}
setTimeout(function () {
// Set to false, so that if we fail in the reconnect attempt, we can
// schedule another one.
self.connectionAttemptScheduled = false;
self.reconnect();
}, backoffTime);
}
}
};
this._defaultExchange = null;
this.channelCounter = 0;
this._sendBuffer = new Buffer(maxFrameBuffer);
self.addListener('connect', function () {
// In the case where this is a reconnection, do not trample on the existing
// channels.
// For your reference, channel 0 is the control channel.
self.channels = (self.implOptions.reconnect ? self.channels : undefined) || {0:self};
self.queues = (self.implOptions.reconnect ? self.queues : undefined) || {};
self.exchanges = (self.implOptions.reconnect ? self.exchanges : undefined) || {};
parser = new AMQPParser('0-9-1', 'client');
parser.onMethod = function (channel, method, args) {
self._onMethod(channel, method, args);
};
parser.onContent = function (channel, data) {
debug(channel + " > content " + data.length);
if (self.channels[channel] && self.channels[channel]._onContent) {
self.channels[channel]._onContent(channel, data);
} else {
debug("unhandled content: " + data);
}
};
parser.onContentHeader = function (channel, classInfo, weight, properties, size) {
debug(channel + " > content header " + JSON.stringify([classInfo.name, weight, properties, size]));
if (self.channels[channel] && self.channels[channel]._onContentHeader) {
self.channels[channel]._onContentHeader(channel, classInfo, weight, properties, size);
} else {
debug("unhandled content header");
}
};
parser.onHeartBeat = function () {
self.emit("heartbeat");
debug("heartbeat");
};
parser.onError = function (e) {
self.emit("error", e);
self.emit("close");
};
//debug("connected...");
// Time to start the AMQP 7-way connection initialization handshake!
// 1. The client sends the server a version string
self.write("AMQP" + String.fromCharCode(0,0,9,1));
});
self.addListener('data', function (data) {
if(parser != null){
parser.execute(data);
}
self._inboundHeartbeatTimerReset();
});
self.addListener('error', function () {
backoff();
});
self.addListener('ready', function () {
// Reset the backoff time since we have successfully connected.
backoffTime = null;
if (self.implOptions.reconnect) {
// Reconnect any channels which were open.
for (var channel in self.channels) {
if (channel != 0) {
self.channels[channel].reconnect();
}
}
}
// Restart the heartbeat to the server
self._outboundHeartbeatTimerReset();
});
}
util.inherits(Connection, net.Stream);
exports.Connection = Connection;
var defaultPorts = { 'amqp': 5672, 'amqps': 5671 };
var defaultOptions = { host: 'localhost'
, port: defaultPorts['amqp']
, login: 'guest'
, password: 'guest'
, vhost: '/'
};
// If the "reconnect" option is true, then the driver will attempt to
// reconnect using the configured strategy *any time* the connection
// becomes unavailable.
// If this is not appropriate for your application, do not set this option.
// If you would like this option, you can set parameters controlling how
// aggressively the reconnections will be attempted.
// Valid strategies are "linear" and "exponential".
// Backoff times are in milliseconds. Under the "linear" strategy, the driver
// will pause <reconnectBackoffTime> ms before the first attempt, and between
// each subsequent attempt. Under the "exponential" strategy, the driver will
// pause <reconnectBackoffTime> ms before the first attempt, and will double
// the previous pause between each subsequent attempt until a connection is
// reestablished.
var defaultImplOptions = { defaultExchangeName: '', reconnect: true , reconnectBackoffStrategy: 'linear' , reconnectExponentialLimit: 120000, reconnectBackoffTime: 1000 };
function urlOptions(connectionString) {
var opts = {};
var url = URL.parse(connectionString);
var scheme = url.protocol.substring(0, url.protocol.lastIndexOf(':'));
if (scheme != 'amqp' && scheme != 'amqps') {
throw new Error('Connection URI must use amqp or amqps scheme. ' +
'For example, "amqp://bus.megacorp.internal:5766".');
}
opts.ssl = ('amqps' === scheme);
opts.host = url.hostname;
opts.port = url.port || defaultPorts[scheme];
if (url.auth) {
var auth = url.auth.split(':');
auth[0] && (opts.login = auth[0]);
auth[1] && (opts.password = auth[1]);