|
|
@ -2,25 +2,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
const Promise = require("bluebird");
|
|
|
|
const Promise = require("bluebird");
|
|
|
|
const ms = require("ms");
|
|
|
|
const ms = require("ms");
|
|
|
|
const promiseDelaySince = require("@joepie91/promise-delay-every");
|
|
|
|
const promiseDelayEvery = require("@joepie91/promise-delay-every");
|
|
|
|
const propagateAbort = require("@ppstreams/propagate-abort");
|
|
|
|
const propagateAbort = require("@promistream/propagate-abort");
|
|
|
|
|
|
|
|
const propagatePeek = require("@promistream/propagate-peek");
|
|
|
|
|
|
|
|
const debug = require("debug")("promistream:rate-limit");
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = function rateLimitedStream(interval) {
|
|
|
|
function makeClonableInstance(interval) {
|
|
|
|
let intervalInMilliseconds = (typeof interval === "number")
|
|
|
|
let intervalInMilliseconds = (typeof interval === "number")
|
|
|
|
? interval
|
|
|
|
? interval
|
|
|
|
: ms(interval);
|
|
|
|
: ms(interval);
|
|
|
|
|
|
|
|
|
|
|
|
let delayer = promiseDelaySince(intervalInMilliseconds);
|
|
|
|
debug(`Creating clonable with interval of ${intervalInMilliseconds}ms`);
|
|
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
let delayer = promiseDelayEvery(intervalInMilliseconds);
|
|
|
|
description: `rate-limited stream (1 per ${interval})`,
|
|
|
|
|
|
|
|
read: (source) => {
|
|
|
|
return function createClone () {
|
|
|
|
return Promise.try(() => {
|
|
|
|
debug("Creating clone");
|
|
|
|
return delayer();
|
|
|
|
|
|
|
|
}).then(() => {
|
|
|
|
return {
|
|
|
|
return source.read();
|
|
|
|
_promistreamVersion: 0,
|
|
|
|
});
|
|
|
|
description: `rate-limited stream (1 per ${interval})`,
|
|
|
|
},
|
|
|
|
read: (source) => {
|
|
|
|
abort: propagateAbort
|
|
|
|
return Promise.try(() => {
|
|
|
|
}
|
|
|
|
debug("Attempted read");
|
|
|
|
};
|
|
|
|
return delayer();
|
|
|
|
|
|
|
|
}).then(() => {
|
|
|
|
|
|
|
|
debug("Delay passed, completing read");
|
|
|
|
|
|
|
|
return source.read();
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
peek: propagatePeek,
|
|
|
|
|
|
|
|
abort: propagateAbort
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = function rateLimitedStream(... args) {
|
|
|
|
|
|
|
|
// Internally, we treat a non-clonable stream as a clonable stream that will only ever have one clone - this makes implementation much simpler
|
|
|
|
|
|
|
|
let createClone = makeClonableInstance(... args);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return createClone();
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
module.exports.clonable = makeClonableInstance;
|
|
|
|