-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.js
47 lines (38 loc) · 956 Bytes
/
buffer.js
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
const debug = require('debug')('apex-logs-winston')
// TODO: implement retries
/**
* Buffer is used to batch events for efficient ingestion.
*/
module.exports = class Buffer {
constructor({ onFlush, onError, maxEntries = 250, maxRetries = 3, flushInterval = 5000 }) {
this.values = []
this.maxEntries = maxEntries
this.maxRetries = maxRetries
this.onFlush = onFlush
this.onError = onError
this._id = setInterval(this.flush.bind(this), flushInterval)
}
push(value) {
this.values.push(value)
if (this.values.length >= this.maxEntries) {
this.flush()
}
}
async flush() {
const values = this.values
debug('flushing %d entries', values.length)
if (!values.length) {
return
}
try {
this.values = []
await this.onFlush(values)
} catch(err) {
this.onError(err)
}
}
async close() {
clearInterval(this._id)
await this.flush()
}
}