-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
423 lines (381 loc) · 16.3 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
var util = require( 'util' )
, assert = require( 'assert' )
, Stream = require( 'stream' )
;
/* AmqpStream ( options, callback )
*
*/
var AmqpStream = function ( options, callback ) {
if ( typeof options == 'function' && typeof callback != 'function' ) {
callback = options;
}
var callback = callback || function (){};
// Validate arguments
if ( typeof options != 'object' || options.constructor != Object ) {
callback( Error( 'AmqpStream requires the first argument to an options object.' ) );
return false;
}
// If module was called as a function, return a new AmqpStream object
if ( !(this instanceof AmqpStream) )
return new AmqpStream( options, callback );
// Variables / Properties
var stream = this;
var err = null;
// Make sure we have a valid connection
if ( !(amqpObjectType(options.connection)=='Connection') && !(amqpObjectType(options.exchange)=='Exchange') && !(amqpObjectType(options.queue)=='Queue') ) {
callback( Error( 'AmqpStream requires at least one amqp object (Connection, Exchange, or Queue).' ) );
return false;
}
// Determine connection bearing object
var connection = amqpObjectType(options.connection)=='Connection' ? options.connection :
amqpObjectType(options.exchange)=='Exchange' ? options.exchange.connection :
amqpObjectType(options.queue)=='Queue' ? options.queue.connection : null;
// AMQP related configuration properties
this.connection = null;
this.exchange = null;
this.queue = null;
this.routingKey = options.routingKey || '#';
this.ctag = null;
this.originId = uniqueIdentifier();
this.autoBind = typeof options.autoBind != 'undefined' ? options.autoBind : true;
this.correlations = [];
//this.correlationId = (options.correlationId && options.correlationId === true) ? uniqueIdentifier() : (options.correlationId || null);
this.publishOptions = options.publishOptions || {};
this.publishOptions.headers = this.publishOptions.headers || {};
this.publishOptions.headers['x-stream-origin'] = this.originId;
// Stream interface properties
this.writable = false; // Enabled once exchange is set
this.readable = false;
this.paused = false; // Start in an un-paused state
this.ended = false;
this.destroyed = false;
this.buffer = [];
this.initializing = true;
var connectionReady = false;
var exchangeReady = false;
var queueReady = false;
var onReady = function () {
if ( stream.initializing && connectionReady && (exchangeReady || !options.exchange) && (queueReady || (typeof options.queue != 'undefined' && options.queue === false) ) ) {
stream.initializing = false;
callback( err, stream );
process.nextTick( function () { stream.emit( 'ready' ); } );
}
}
var configureStream = function ( connection, options ) {
var connectionReady = function () {
setConnection( connection );
if ( amqpObjectType(options.exchange) == 'Exchange' ) setExchange( options.exchange );
else if ( options.exchange && typeof options.exchange == 'string' ) {
connection.exchange( options.exchange, options.exchangeOptions||{durable:false,autoDelete:true}, function (exchange) {
setExchange( exchange );
});
}
if ( amqpObjectType(options.queue) == 'Queue' ) {
if ( !options.exchange && options.queue.exchange ) {
options.exchange = options.queue.exchange;
setExchange( options.exchange );
}
setQueue( options.queue );
}
else if ( options.queue && typeof options.queue == 'string' ) {
connection.queue( options.queue, options.queueOptions||{durable:false,autoDelete:true}, function (queue) {
setQueue( queue );
});
}
// Skip binding to a queue if queue:false, will create write-only stream
else if ( typeof options.queue != 'undefined' && options.queue === false ) {
options.queue = null;
}
else {
options.queue = buildQueue();
}
}
if ( !connection._connecting && connection.channels && Object.keys(connection.channels).length > 0 ) {
connectionReady();
}
else {
connection.on( 'ready', connectionReady );
}
}
var setConnection = function ( connection ) {
stream.connection = connection;
stream.emit( 'connectionReady' );
connectionReady = true;
onReady();
}
var setExchange = function ( exchange ) {
if ( stream.exchange )
return;
assert.equal( amqpObjectType(exchange), 'Exchange', 'setExchange expected an Exchange object' );
stream.exchange = exchange;
stream.writable = true;
stream.emit( 'exchangeReady' );
stream.exchange.on( 'error', function (err) { stream.emit( 'error', err); });
exchangeReady = true;
onReady();
}
var setQueue = function ( queue ) {
if ( stream.queue )
return;
assert.equal( amqpObjectType(queue), 'Queue', 'setQueue expected a Queue object' );
stream.queue = queue;
stream.readable = true;
stream.emit( 'queueReady' );
queue.on( 'error', function (err) { stream.emit( 'error', err); });
queue.subscribe( messageHandler ).addCallback( function(ok) {
stream.ctag = ok.consumerTag;
});
// if ( stream.correlationId ) {
// stream.publishOptions.replyTo = queue.name;
// stream.publishOptions.correlationId = stream.correlationId;
// }
queueReady = true;
onReady();
}
var buildQueue = function ( ) {
var queue = stream.connection.queue( '', {durable: false, exclusive: true, autoDelete: true}, function () {
if ( stream.autoBind )
queue.bind( stream.exchange, stream.routingKey );
queue.bind( stream.exchange, queue.name );
queue.on( 'queueBindOk', function () { setQueue(queue); });
});
return queue;
}
var onEnd = function () {
stream.writable = stream.readable = false;
stream.ended = true;
stream.emit( 'end' );
}
var messageHandler = function ( message, headers, deliveryInfo ) {
if ( 'x-stream-origin' in headers && headers['x-stream-origin'] == stream.originId )
return; // Do not emit our own writes ( this is for duplex streams )
if ( deliveryInfo.correlationId ) {
if ( deliveryInfo.correlationId in stream.correlations ) {
var emitter = stream.correlations[ deliveryInfo.correlationId ];
}
else {
var emitter = stream.createCorrelatedResponse( deliveryInfo.replyTo, deliveryInfo.correlationId, function ( err, emitter ) {
stream.emit( 'correlatedRequest', emitter );
});
}
if ( 'x-stream-event' in headers && headers['x-stream-event'] == 'end') {
if ( message.data && message.data.toString().trim() != '' )
emitter.emit( 'data', message.data );
emitter.emit( 'end' );
process.nextTick( function () { delete stream.correlations[deliveryInfo.correlationId] } );
}
}
else {
var emitter = stream;
if ( 'x-stream-event' in headers && headers['x-stream-event'] == 'end' ) {
if ( message.data && message.data.toString().trim() != '' )
emitter.emit( 'data', message.data );
if( !( emitter.paused || emitter.buffer.length ) )
return onEnd();
else
emitter.once( 'drain', onEnd );
emitter.drain();
}
}
if ( 'x-stream-event' in headers && headers['x-stream-event'] == 'error') {
if ( message.data && message.data.toString().trim() != '' )
emitter.emit( 'data', message.data );
emitter.emit( 'error' );
}
else if ( ( !('x-stream-event' in headers) || ('x-stream-event' in headers && headers['x-stream-event'] == 'data') ) &&
message.data && message.data.toString().trim() != ''
) {
if ( emitter.paused ) {
emitter.buffer.push( message.data );
}
else {
emitter.emit( 'data', message.data );
}
}
}
// Configure the stream
configureStream( connection, options );
}
util.inherits( AmqpStream, Stream );
// TODO: Can we sanely support back-pressure here (return false, emit drain), does it even matter w/ amqp?
AmqpStream.prototype.write = function ( buf, enc, routingKey, _addOpts ) {
if ( routingKey && !_addOpts )
var _addOpts = routingKey, routingKey = null;
if ( !this.writable )
this.emit( 'error', Error( 'Non-writable amqp stream.' ) );
else {
if ( typeof buf == 'string' ) {
var buf = new Buffer( buf, enc );
}
var options = {};
for (var opt in this.publishOptions) options[opt] = this.publishOptions[opt];
if (_addOpts) for ( opt in _addOpts ) options[opt] = _addOpts[opt];
options.headers['x-stream-event'] = 'data';
this.exchange.publish( routingKey || this.routingKey, buf || ' ', options );
}
}
AmqpStream.prototype.end = function ( buf, enc, _addOpts ) {
if ( routingKey && !_addOpts )
var _addOpts = routingKey, routingKey = null;
if ( !this.writable && !this.ended )
this.emit( 'error', Error( 'Non-writable amqp stream.' ) );
else {
if ( typeof buf == 'string' ) {
var buf = new Buffer( buf, enc );
}
var options = {};
for (var opt in this.publishOptions) options[opt] = this.publishOptions[opt];
if (_addOpts) for ( opt in _addOpts ) options[opt] = _addOpts[opt];
options.headers['x-stream-event'] = 'end';
this.exchange.publish( this.routingKey, buf || ' ', options );
this.ended = true;
if ( this.ctag && this.queue )
this.queue.unsubscribe( this.ctag );
process.nextTick( this.destroy.bind(this) );
}
}
AmqpStream.prototype.endCorrelation = function ( buf, enc, routingKey, _addOpts ) {
if ( routingKey && !_addOpts )
var _addOpts = routingKey, routingKey = null;
if ( typeof buf == 'string' ) {
var buf = new Buffer( buf, enc );
}
var options = {};
for (var opt in this.publishOptions) options[opt] = this.publishOptions[opt];
if (_addOpts) for ( opt in _addOpts ) options[opt] = _addOpts[opt];
options.headers['x-stream-event'] = 'end';
this.exchange.publish( routingKey || this.routingKey, buf || ' ', options );
}
AmqpStream.prototype.error = function ( buf, enc, routingKey, _addOpts ) {
if ( routingKey && !_addOpts )
var _addOpts = routingKey, routingKey = null;
if ( typeof buf == 'string' ) {
var buf = new Buffer( buf, enc );
}
var options = {};
for (var opt in this.publishOptions) options[opt] = this.publishOptions[opt];
if (_addOpts) for ( opt in _addOpts ) options[opt] = _addOpts[opt];
options.headers['x-stream-event'] = 'error';
this.exchange.publish( routingKey || this.routingKey, buf || ' ', options );
}
// TODO: I feel like we can do better at unbinding/unsubscribing here. but may not be needed
// due to autoDelete
AmqpStream.prototype.destroy = function ( ) {
this.writable = this.readable = false;
this.destroyed = this.ended = true;
this.buffer.length = 0;
this.emit( 'close' );
}
/* Pause/Resume support for read-side of stream
* Thanks to dominictarr for this logic, it just buffers in memory like pause-stream
*/
// TODO: We should be able to pause data coming in from amqp here instead of buffering in memory
// but I took the easy way out for now
AmqpStream.prototype.pause = function () {
this.paused = true;
}
AmqpStream.prototype.resume = function () {
this.paused = false;
this.drain();
}
AmqpStream.prototype.drain = function () {
while( !this.paused && this.buffer.length )
this.emit( 'data', this.buffer.shift() );
}
/* createCorrelatedRequest
* This function returns a "sub stream" on duplex streams where writes are published with a correlation
* ID, and emits only occur when incoming messages contain a matching correlation ID
*/
AmqpStream.prototype.createCorrelatedRequest = function ( correlationId, callback ) {
if ( typeof correlationId == 'function' )
var callback = correlationId, correlationId = null;
var stream = this
, err = null
;
if ( !stream.queue )
callback( Error('Cannot create correlated request on non-readable amqp stream.') );
var correlationId = correlationId || uniqueIdentifier();
var substream = new Stream;
substream.readable = true;
substream.writable = true;
substream.paused = false;
substream.write = function ( buf, enc ) {
stream.write( buf, enc, {replyTo:stream.queue.name, correlationId:correlationId} );
}
substream.error = function ( buf, enc ) {
stream.error( buf, enc, {replyTo:stream.queue.name, correlationId:correlationId} );
}
substream.end = function ( buf, enc ) {
stream.endCorrelation( buf, enc, {replyTo:stream.queue.name, correlationId:correlationId} );
process.nextTick( function () {
substream.emit( 'end' );
delete stream.correlations[ correlationId ];
});
}
// TODO: Implement pause/resume on correlated streams
substream.pause = function () {}
substream.pause = function () {}
stream.correlations[correlationId] = substream;
callback( err, substream );
return substream;
}
AmqpStream.prototype.createCorrelatedResponse = function ( routingKey, correlationId, callback ) {
if ( typeof correlationId == 'function' )
var callback = correlationId, correlationId = true;
var stream = this
, err = null
;
if ( !stream.queue )
callback( Error('Cannot create correlated request on non-readable amqp stream.') );
var substream = new Stream;
substream.readable = true;
substream.writable = true;
substream.paused = false;
substream.write = function ( buf, enc ) {
stream.write( buf, enc, routingKey, {correlationId:correlationId} );
}
substream.error = function ( buf, enc ) {
stream.error( buf, enc, routingKey, {correlationId:correlationId} );
}
substream.end = function ( buf, enc ) {
stream.endCorrelation( buf, enc, routingKey, {correlationId:correlationId} );
process.nextTick( function () {
substream.emit( 'end' );
delete stream.correlations[ correlationId ];
});
}
// TODO: Implement pause/resume on correlated streams
substream.pause = function () {}
substream.pause = function () {}
stream.correlations[correlationId] = substream;
callback( err, substream );
return substream;
}
/* createStream
* Convenience function that matches some node conventions, same as: new AmqpStream, or just AmqpStream
*/
AmqpStream.createStream = function () {
return AmqpStream.apply( null, arguments );
}
module.exports = AmqpStream;
/* amqpObjectType
* Helper function that identifies object types from the node amqp module
* Could probably do better, but do not want to require amqp locally so trying to avoid
* instanceof.
*/
function amqpObjectType( instance ) {
if ( instance && instance.subscribeRaw )
return 'Queue';
if ( instance && instance.cleanup )
return 'Exchange';
if ( instance && instance.addListener )
return 'Connection';
return null;
}
/* uniqueIdentifier
* Used to create a unique identifiers for use in x-stream-origin header value, so that in a duplex
* amqp stream, write will not emit messages locally, and for correlation ID's.
*/
function uniqueIdentifier( ) {
return Math.floor(Math.random() * 1000000).toString(36).toUpperCase() + (new Date).getTime().toString(36).toUpperCase();
}