/usr/lib/nodejs/call-limit/call-limit.js is in node-call-limit 1.1.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | "use strict"
var defaultMaxRunning = 50
var limit = module.exports = function (func, maxRunning) {
var running = 0
var queue = []
if (!maxRunning) maxRunning = defaultMaxRunning
return function limited () {
var self = this
var args = Array.prototype.slice.call(arguments)
if (running >= maxRunning) {
queue.push({self: this, args: args})
return
}
var cb = typeof args[args.length-1] === 'function' && args.pop()
++ running
args.push(function () {
var cbargs = arguments
-- running
cb && process.nextTick(function () {
cb.apply(self, cbargs)
})
if (queue.length) {
var next = queue.shift()
limited.apply(next.self, next.args)
}
})
func.apply(self, args)
}
}
module.exports.method = function (classOrObj, method, maxRunning) {
if (typeof classOrObj === 'function') {
var func = classOrObj.prototype[method]
classOrObj.prototype[method] = limit(func, maxRunning)
} else {
var func = classOrObj[method]
classOrObj[method] = limit(func, maxRunning)
}
}
module.exports.promise = function (func, maxRunning) {
var running = 0
var queue = []
if (!maxRunning) maxRunning = defaultMaxRunning
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve) {
if (running >= maxRunning) {
queue.push({self: self, args: args, resolve: resolve})
return
} else {
runNext(self, args, resolve)
}
function runNext (self, args, resolve) {
++ running
resolve(
func.apply(self, args)
.then(finish, function (err) {
finish(err)
throw err
}))
}
function finish () {
-- running
if (queue.length) {
var next = queue.shift()
process.nextTick(runNext, next.self, next.args, next.resolve)
}
}
})
}
}
module.exports.promise.method = function (classOrObj, method, maxRunning) {
if (typeof classOrObj === 'function') {
var func = classOrObj.prototype[method]
classOrObj.prototype[method] = limit.promise(func, maxRunning)
} else {
var func = classOrObj[method]
classOrObj[method] = limit.promise(func, maxRunning)
}
}
|