Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@fbinhouse/devops-job-queue / src / logWriter.js
Size: Mime:

class LogWriter {
    constructor(db, jobId) {
        this.db = db;
        this.jobId = jobId;

        this.logItems = [];
        this.interval = null;
    }

    start() {
        this.interval = setInterval(() => {
            if (!this.running) {
                this.running = true;
                this.cycle().then(() => {
                    this.running = false;
                }).catch(e => {
                    console.error(e);
                    this.running = false;
                });
            }
        }, 5000);
    }

    stop() {
        console.log('*** Job has finished', this.jobId, 'and log queue is empty, stopping job writer');
        clearInterval(this.interval);
        this.interval = null;
    }

    addLogItem(logData) {
        this.logItems.push(logData);
    }

    async cycle() {
        // Push all log items that are available now
        let items = this.logItems.splice(0, this.logItems.length);
        if (items.length === 0) {
            // console.log('*** No items to add, check this job is still running by querying the database');
            await this.checkJobFinished();
        } else {
            await this.db.addManyJobLogItems(this.jobId, items);
        }
    }

    async checkJobFinished() {
        let job = await this.db.getJobById(this.jobId);
        // console.log('*** JOB STATUS IS', job.status, 'for jobId', this.jobId);
        if (job.status === 3 || job.status === 4) {
            this.stop();
        }
    }
}

module.exports = LogWriter;