deploy_pool.js 1.38 KB

'use strict';

class DeployPool {

    constructor() {
        this.poolSize = 5;
        this.pool = [];
        this.running = new Map();
    }

    deploy(de) {
        de.error = 0;
        this.pool.push(de);
        setTimeout(() => {
            this.run();
        }, 1);
    }

    async run() {
        if (this.running.size < this.poolSize) {
            let de = this.pool.shift();

            if (de) {
                let id = await de.deploy(function(err) {
                    if (err && this.running.has(de.id)) {
                        console.log(`deploy fail ${de.id} : ` + err);
                        de.error = (de.error + 1) || 1;

                        if (de.error < 3) {
                            this.pool.push(de);
                        }
                    }
                    this.running.delete(de.id);
                    setTimeout(function(){
                        this.run();
                    }.bind(this), 1000);
                }.bind(this));

                this.running.set(id, de);
            }
        }
    }

    stop() {
        this.pool = [];
        let iter = this.running.keys();
        let next = iter.next();

        while(!next.done) {
            this.running.get(next.value).stop();
            this.running.delete(next.value);
            next = iter.next();
        }
    }
}

const pool = new DeployPool();

module.exports = pool;