mof-bottleneck
Version:
A middleware wrapped Bottleneckp module for floodesh
42 lines (31 loc) • 1.54 kB
JavaScript
const Bottleneck = require('bottleneckp')
module.exports = (options) => {
return function* ( ctx, next ) {
if(!ctx.app.scheduler){
let scheduler = ctx.app.scheduler = Object.create(null);
Object.keys(options).forEach(cfg => scheduler[cfg] = new Bottleneck.Cluster(options[cfg].concurrent, options[cfg].rate,options[cfg].priorityRange,options[cfg].defaultPriority, options[cfg].homogenous) );
}
yield new Promise((resolve) => {
let clusterCfg = ctx.func;
if( !(clusterCfg in ctx.app.scheduler) )
clusterCfg = "defaultCfg";
ctx.opt.clusterCfg = clusterCfg;
let cluster = ctx.app.scheduler[clusterCfg];
if( ! ctx.opt.hasOwnProperty("limiter") )
ctx.opt.limiter = "default";
ctx.app.logger.verbose("Bottleneck submit, cluster: %s, limiter: %s", clusterCfg,ctx.opt.limiter);
ctx.app.logger.verbose("Bottleneck cluster: %s, status: %s", clusterCfg, cluster.status);
if(ctx.scounter) ctx.scounter('bottleneck');// for metrics collecting
cluster.key(ctx.opt.limiter).submit( ctx.opt.priority||1 ,done => {
ctx.app.logger.verbose("Bottleneck callback, cluster: %s, limiter: %s",ctx.opt.clusterCfg, ctx.opt.limiter);
ctx.resourceList.bottleneck = done;
resolve();
});
});
yield next();
ctx.resourceList.bottleneck();// release bottleneck resource here
delete ctx.resourceList.bottleneck;
ctx.app.logger.verbose("Bottleneck released, cluster: %s, limiter: %s",ctx.opt.clusterCfg, ctx.opt.limiter);
}
}