-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (69 loc) · 1.98 KB
/
index.js
File metadata and controls
83 lines (69 loc) · 1.98 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict'
const RequestBuilder = require('./lib/req-builder')
const EventEmitter = require('events').EventEmitter
module.exports = function plugin (options) {
return new CloudWatchPublisher(options)
}
class CloudWatchPublisher extends EventEmitter {
constructor (options) {
super()
if (!options) options = {}
// To avoid allocating many objects, this plugin does not use `aws-sdk`,
// but a string builder to build HTTP requests made to CloudWatch.
this._builder = new RequestBuilder(options)
this._backgroundFlushCallback = this._backgroundFlushCallback.bind(this)
this._backgroundFlushing = false
}
publish (metric) {
if (metric.isSingle()) {
this._builder.addSingleMetric(metric)
} else if (metric.isSummary()) {
this._builder.addSummaryMetric(metric)
}
}
ping (callback) {
if (!this._builder.hasData()) {
// No need to dezalgo ping()
return callback()
}
// Perform HTTP requests in background, to not delay other plugins.
if (!this._backgroundFlushing) {
this._backgroundFlush()
}
callback()
}
_backgroundFlush () {
this._backgroundFlushing = true
this.flush(this._backgroundFlushCallback)
}
_backgroundFlushCallback (err) {
this._backgroundFlushing = false
if (err) this.emit('error', err)
this.emit('_flush')
}
stop (callback) {
if (this._backgroundFlushing) {
this.once('_flush', this.stop.bind(this, callback))
} else {
this.once('_flush', callback)
this._backgroundFlush()
}
}
// Exposed for standalone usage
flush (options, callback) {
let promise
if (typeof options === 'function') {
callback = options
options = null
} else if (callback === undefined) {
promise = new Promise((resolve, reject) => {
callback = function (err, result) {
if (err) reject(err)
else resolve(result)
}
})
}
this._builder.send(options, callback)
return promise
}
}