-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
190 lines (172 loc) · 5.02 KB
/
index.js
File metadata and controls
190 lines (172 loc) · 5.02 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
'use strict';
const fp = require('fastify-plugin');
const { default: Client } = require('@immobiliarelabs/dats');
const doc = require('@dnlup/doc');
const {
hrtime2ns,
hrtime2us,
hrtime2ms,
hrtime2s,
} = require('@dnlup/hrtime-utils');
const { gte16 } = require('./lib/utils');
const timerifyNotSupported = () => {
throw new Error('Timerify is supported only on Node version 16 and newer.');
};
const timerifyWrap = gte16
? require('./lib/timerifyWrap').timerifyWrap
: () => timerifyNotSupported;
function clientMock() {
const mock = {
socket: {
onError: /* istanbul ignore next */ () => {},
},
};
for (const method of ['on', 'counter', 'timing', 'gauge', 'set']) {
mock[method] = () => {};
}
mock.close = (done) => {
return setImmediate(done);
};
return mock;
}
function sendHealthData(
{ eventLoopUtilization, eventLoopDelay, memory, cpu },
stats
) {
stats.gauge('process.mem.external', memory.external);
stats.gauge('process.mem.rss', memory.rss);
stats.gauge('process.mem.heapUsed', memory.heapUsed);
stats.gauge('process.mem.heapTotal', memory.heapTotal);
stats.gauge('process.eventLoopDelay', eventLoopDelay);
stats.gauge('process.eventLoopUtilization', eventLoopUtilization);
stats.gauge('process.cpu', cpu);
}
function onClose(instance, done) {
instance.stats.close(done);
}
function hitsCounter(request, reply, next) {
this.stats.counter(`api.${request.metrics.id}.requests`);
next();
}
function responseTiming(request, reply, next) {
this.stats.timing(
`api.${request.metrics.id}.response_time`,
reply.getResponseTime()
);
next();
}
function errorsCounter(request, reply, error, done) {
this.stats.counter(`api.${request.metrics.id}.errors.${reply.statusCode}`);
done();
}
/**
* Default metrics that are enabled
*/
const COLLECT = {
/**
* Response time
*/
timing: true,
/**
* Route hit counter
*/
hits: true,
/**
* Route errors counter
*/
errors: true,
/**
* Health data
*/
health: true,
};
module.exports = fp(
function (
fastify,
{
host,
namespace,
bufferSize,
bufferFlushTimeout,
sampleInterval,
udpDnsCache,
udpDnsCacheTTL,
collect = {},
onError = (error) => void fastify.log.error(error),
},
next
) {
const enabledMetrics = Object.assign({}, COLLECT, collect);
for (const key of ['timing', 'hits', 'errors', 'health']) {
if (typeof enabledMetrics[key] !== 'boolean') {
return next(new Error(`"${key}" must be a Boolean.`));
}
}
const stats = host
? new Client({
host,
namespace,
bufferSize,
bufferFlushTimeout,
udpDnsCache,
udpDnsCacheTTL,
onError,
})
: clientMock();
fastify.decorate('stats', stats);
fastify.decorate('timerify', timerifyWrap(fastify));
fastify.decorate('hrtime2ns', hrtime2ns);
fastify.decorate('hrtime2us', hrtime2us);
fastify.decorate('hrtime2ms', hrtime2ms);
fastify.decorate('hrtime2s', hrtime2s);
if (enabledMetrics.health) {
const sampler = doc({ sampleInterval });
fastify.decorate('doc', sampler);
const onSample = function () {
sendHealthData(
{
eventLoopUtilization:
sampler.eventLoopUtilization.raw.utilization,
eventLoopDelay: sampler.eventLoopDelay.computed,
memory: sampler.memory,
cpu: sampler.cpu.usage,
},
stats
);
};
sampler.on('sample', onSample);
}
if (
enabledMetrics.timing ||
enabledMetrics.errors ||
enabledMetrics.hits
) {
/**
* Assign a default route id if not defined in the reply
* config options.
* @see https://www.fastify.io/docs/latest/Routes/#config
*/
fastify.addHook('onRequest', function (request, reply, next) {
request.metrics = {
id: reply.context.config.routeId || 'noId',
};
next();
});
}
fastify.addHook('onClose', onClose);
if (enabledMetrics.hits) {
fastify.addHook('onRequest', hitsCounter);
}
if (enabledMetrics.timing) {
fastify.addHook('onResponse', responseTiming);
}
if (enabledMetrics.errors) {
fastify.addHook('onError', errorsCounter);
}
next();
},
{
name: '@immobiliarelabs/fastify-metrics',
fastify: '3.x',
}
);