-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcongestion.js
60 lines (52 loc) · 1.21 KB
/
congestion.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
/*
* congestion v0.1.0
* Generator-based congestion control
*
* Copyright 2016, Ali Farhadi
* Released under the MIT license.
*/
'use strict';
var Emitter = require('events').EventEmitter,
Promise = require('pinkie-promise'),
inherits = require('util').inherits;
function Congestion(capacity) {
Emitter.call(this);
this.capacity = capacity || 100;
this.current = 0;
this.full = false;
}
inherits(Congestion, Emitter);
Congestion.prototype.inc = function(value) {
if (value && typeof value.then == 'function') {
this.current++;
value.then(this.dec.bind(this), this.dec.bind(this));
} else {
this.current += value || 1;
}
if (this.current >= this.capacity && !this.full) {
this.full = true;
this.emit('full');
}
}
Congestion.prototype.dec = function(value) {
this.current -= value || 1;
if (this.current < this.capacity && this.full) {
this.full = false;
this.emit('free');
}
}
Congestion.prototype.wait = function(value) {
if (value) {
this.inc(value);
}
if (!this.full) {
return Promise.resolve();
}
return new Promise(function(resolve) {
this.once('free', resolve);
}.bind(this));
}
module.exports = function(i) {
return new Congestion(i);
};
module.exports.Congestion = Congestion;