1 | const got = require('got')
|
2 |
|
3 | module.exports = class Batcher {
|
4 | constructor (options) {
|
5 | this.options = options
|
6 | this.interval = this.options.interval
|
7 | ? Number(this.options.interval) * 1000
|
8 | : 5000
|
9 | this.circuitBreakerInterval = 60000
|
10 | this.batch = {
|
11 | streams: []
|
12 | }
|
13 | }
|
14 | wait (duration) {
|
15 | return new Promise(resolve => {
|
16 | setTimeout(resolve, duration)
|
17 | })
|
18 | }
|
19 | pushLogEntry (logEntry) {
|
20 | this.batch.streams.push(logEntry)
|
21 | }
|
22 | clearBatch () {
|
23 | this.batch.streams = []
|
24 | }
|
25 | sendBatchToLoki () {
|
26 | return new Promise((resolve, reject) => {
|
27 | if (this.batch.streams.length === 0) {
|
28 | resolve()
|
29 | } else {
|
30 | got
|
31 | .post(this.options.host + '/api/prom/push', {
|
32 | body: JSON.stringify(this.batch),
|
33 | headers: {
|
34 | 'content-type': 'application/json'
|
35 | }
|
36 | })
|
37 | .then(res => {
|
38 | this.clearBatch()
|
39 | resolve()
|
40 | })
|
41 | .catch(err => {
|
42 | reject(err)
|
43 | })
|
44 | }
|
45 | })
|
46 | }
|
47 | async run () {
|
48 | while (true) {
|
49 | try {
|
50 | await this.sendBatchToLoki()
|
51 | if (this.interval === this.circuitBreakerInterval) {
|
52 | this.interval = Number(this.options.interval) * 1000
|
53 | }
|
54 | } catch (e) {
|
55 | this.interval = this.circuitBreakerInterval
|
56 | }
|
57 | await this.wait(this.interval)
|
58 | }
|
59 | }
|
60 | }
|