forked from zhoutony/html5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.js
More file actions
71 lines (56 loc) · 1.21 KB
/
queue.js
File metadata and controls
71 lines (56 loc) · 1.21 KB
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
/**
* Module dependencies.
*/
var debug = require('debug')('axon:queue');
/**
* Queue plugin.
*
* Provides an `.enqueue()` method to the `sock`. Messages
* passed to `enqueue` will be buffered until the next
* `connect` event is emitted.
*
* Emits:
*
* - `drop` (msg) when a message is dropped
* - `flush` (msgs) when the queue is flushed
*
* @param {Object} options
* @api private
*/
module.exports = function(options){
options = options || {};
return function(sock){
/**
* Message buffer.
*/
sock.queue = [];
/**
* Flush `buf` on `connect`.
*/
sock.on('connect', function(){
var prev = sock.queue;
var len = prev.length;
sock.queue = [];
debug('flush %d messages', len);
for (var i = 0; i < len; ++i) {
this.send.apply(this, prev[i]);
}
sock.emit('flush', prev);
});
/**
* Pushes `msg` into `buf`.
*/
sock.enqueue = function(msg){
var hwm = sock.settings.hwm;
if (sock.queue.length >= hwm) return drop(msg);
sock.queue.push(msg);
};
/**
* Drop the given `msg`.
*/
function drop(msg) {
debug('drop');
sock.emit('drop', msg);
}
};
};