This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
/
reporter-proxy.js
82 lines (68 loc) · 2.46 KB
/
reporter-proxy.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
const pjson = require('../package.json');
export const FIVE_MINUTES_IN_MILLISECONDS = 1000 * 60 * 5;
// this class allows us to call reporter methods
// before the reporter is actually loaded, since we don't want to
// assume that the metrics package will load before the GitHub package.
class ReporterProxy {
constructor() {
this.reporter = null;
this.events = [];
this.timings = [];
this.counters = [];
this.gitHubPackageVersion = pjson.version;
// if for some reason a user disables the metrics package, we don't want to
// just keep accumulating events in memory until the heat death of the universe.
// Use a no-op class, clear all queues, move on with our lives.
setTimeout(FIVE_MINUTES_IN_MILLISECONDS, () => {
if (this.reporter === null) {
this.setReporter(new FakeReporter());
this.events = [];
this.timings = [];
this.counters = [];
}
});
}
// function that is called after the reporter is actually loaded, to
// set the reporter and send any data that have accumulated while it was loading.
setReporter(reporter) {
this.reporter = reporter;
this.events.forEach(customEvent => {
this.reporter.addCustomEvent(customEvent.eventType, customEvent.event);
});
this.timings.forEach(timing => {
this.reporter.addTiming(timing.eventType, timing.durationInMilliseconds, timing.metadata);
});
this.counters.forEach(counterName => {
this.reporter.incrementCounter(counterName);
});
}
}
export const reporterProxy = new ReporterProxy();
export class FakeReporter {
addCustomEvent() {}
addTiming() {}
incrementCounter() {}
}
export function incrementCounter(counterName) {
if (reporterProxy.reporter) {
reporterProxy.reporter.incrementCounter(counterName);
} else {
reporterProxy.counters.push(counterName);
}
}
export function addTiming(eventType, durationInMilliseconds, metadata = {}) {
metadata.gitHubPackageVersion = reporterProxy.gitHubPackageVersion;
if (reporterProxy.reporter) {
reporterProxy.reporter.addTiming(eventType, durationInMilliseconds, metadata);
} else {
reporterProxy.timings.push({eventType, durationInMilliseconds, metadata});
}
}
export function addEvent(eventType, event) {
event.gitHubPackageVersion = reporterProxy.gitHubPackageVersion;
if (reporterProxy.reporter) {
reporterProxy.reporter.addCustomEvent(eventType, event);
} else {
reporterProxy.events.push({eventType, event});
}
}