-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalve.js
46 lines (36 loc) · 1.05 KB
/
valve.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
'use strict';
/**
* Ensure that the stream disconnects if it goes over `maxBytes` `perSeconds`
* @param {Stream} stream
* @param {Number} maxBytes number of bytes
* @param {Number} perSeconds number of seconds
* @return {Stream} [description]
*/
function valve(stream, maxBytes, perSeconds) {
var lastTime = Date.now();
var bytesReceived = 0;
var lastBytesRead = 0;
stream._read = _wrap(stream._read, function (_read, n) {
var now = Date.now();
var totalMs = now - lastTime;
if (totalMs / 1000 > perSeconds) {
bytesReceived = 0;
lastTime = now;
}
bytesReceived += this.bytesRead - lastBytesRead;
lastBytesRead = this.bytesRead;
if (bytesReceived > maxBytes) {
var err = new Error('ESOCKETOVERFLOW');
this.destroy(err);
return false;
}
return _read.call(this, n);
});
return stream;
}
function _wrap(f, wrapper) {
return function wrappedFunc() {
return wrapper.apply(this, [f].concat(Array.prototype.slice.call(arguments)));
};
}
module.exports = valve;