tor_multipath_voip/bench/bench1/worker.js

56 lines
1.3 KiB
JavaScript

"use strict"
const worker = function(sim_limit, start_delay) {
this.sim_limit = sim_limit
this.start_delay = start_delay
this.last_started = 0
this.count = 0
this.wait = []
this.success_cb = []
this.error_cb = []
}
worker.prototype.__schedule = function() {
if (this.count >= this.sim_limit) {
console.debug(`Worker is full, ${this.wait.length} jobs in the queue`)
return
}
if (this.wait.length <= 0) return
const now = Date.now()
let will_start_in = 0
if (this.last_started + this.start_delay > now) {
will_start_in = this.last_started + this.start_delay - now
console.debug(`Too many jobs started at once, throttle job of ${will_start_in}ms`)
}
this.last_started = now + will_start_in
this.count++
setTimeout(((refw, job) => () => {
console.debug("A job has been started")
job()
.then(v => {
refw.count--
refw.__schedule()
refw.success_cb.forEach(cb => cb(v))
})
.catch(e => {
refw.count--
refw.__schedule()
refw.error_cb.forEach(cb => cb(e))
})
})(this,this.wait.pop()), will_start_in)
}
worker.prototype.add = function(prom) {
this.wait.push(prom)
this.__schedule()
}
worker.prototype.on = function(evt, cb) {
if (evt == 'success') this.success_cb.push(cb)
else if (evt == 'error') this.error_cb.push(cb)
}
module.exports = worker