-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (68 loc) · 1.75 KB
/
index.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
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
84
85
86
'use strict'
const EventEmitter = require('events').EventEmitter
const singleMetric = require('@telemetry-js/metric').single
module.exports = function (name, options) {
if (typeof name !== 'string' || name === '') {
throw new TypeError('The first argument "name" must be a non-empty string')
} else if (options != null && typeof options !== 'object') {
throw new TypeError('The second argument "options" must be an object')
}
const metricOptions = Object.assign({}, options, { unit: 'milliseconds' })
const queues = []
const stops = new Set()
const pluginFn = function () {
const queue = []
queues.push(queue)
return new StopwatchCollector(queue)
}
const record = function (startTime) {
const date = new Date()
const endTime = date.getTime()
const duration = endTime - startTime
for (const queue of queues) {
const metric = singleMetric(name, metricOptions)
metric.record(duration, date)
queue.push(metric)
}
}
pluginFn.start = function () {
const stop = record.bind(null, Date.now())
stops.add(stop)
return stop
}
pluginFn.stop = function () {
for (const stop of stops) {
stop()
}
stops.clear()
}
if (options && options.start) {
pluginFn.start()
}
return pluginFn
}
class StopwatchCollector extends EventEmitter {
constructor (queue) {
super()
this._queue = queue
}
start (callback) {
this._queue.length = 0
process.nextTick(callback)
}
ping (callback) {
this._flush()
// No need to dezalgo ping()
callback()
}
stop (callback) {
this._flush()
process.nextTick(callback)
}
_flush () {
for (const metric of this._queue) {
this.emit('metric', metric)
}
this._queue.length = 0
}
}