All files / winston-loki/src batcher.js

83.33% Statements 20/24
66.67% Branches 4/6
80% Functions 8/10
83.33% Lines 20/24
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 612x   2x   5x 5x     5x 5x         7x 7x       10x     5x     6x 6x 5x   1x                                   5x 6x 6x 5x       1x   6x        
const got = require('got')
 
module.exports = class Batcher {
  constructor (options) {
    this.options = options
    this.interval = this.options.interval
      ? Number(this.options.interval) * 1000
      : 5000
    this.circuitBreakerInterval = 60000
    this.batch = {
      streams: []
    }
  }
  wait (duration) {
    return new Promise(resolve => {
      setTimeout(resolve, duration)
    })
  }
  pushLogEntry (logEntry) {
    this.batch.streams.push(logEntry)
  }
  clearBatch () {
    this.batch.streams = []
  }
  sendBatchToLoki () {
    return new Promise((resolve, reject) => {
      if (this.batch.streams.length === 0) {
        resolve()
      } else {
        got
          .post(this.options.host + '/api/prom/push', {
            body: JSON.stringify(this.batch),
            headers: {
              'content-type': 'application/json'
            }
          })
          .then(res => {
            this.clearBatch()
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      }
    })
  }
  async run () {
    while (true) {
      try {
        await this.sendBatchToLoki()
        Iif (this.interval === this.circuitBreakerInterval) {
          this.interval = Number(this.options.interval) * 1000
        }
      } catch (e) {
        this.interval = this.circuitBreakerInterval
      }
      await this.wait(this.interval)
    }
  }
}