-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprom.js
65 lines (57 loc) · 1.82 KB
/
prom.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
import * as Prom from 'prom-client'
/**
* @typedef {{
* requestsTotal: Prom.Counter
* cachedRequestsTotal: Prom.Counter
* firewallBlocked: Prom.Counter
* requestsByContentTypeTotal: Prom.Counter<'type'>
* }} Metrics
*/
export function createRegistry (ns = 'cfanalytics') {
return {
registry: Prom.register,
metrics: {
requestsTotal: new Prom.Counter({
name: `${ns}_requests_total`,
help: 'Number of requests.'
}),
cachedRequestsTotal: new Prom.Counter({
name: `${ns}_cached_requests_total`,
help: 'Number of cached requests.'
}),
firewallBlocked: new Prom.Counter({
name: `${ns}_firewall_blocked_requests_total`,
help: 'Number of firewall blocked requests.'
}),
requestsByContentTypeTotal: new Prom.Counter({
name: `${ns}_requests_content_type_total`,
help: 'Number of requests per content type delivered.',
labelNames: ['type']
})
}
}
}
/**
* @param {Metrics} metrics
*/
export function recordMetrics(metrics) {
/**
* @param {AsyncIterable<import('./analytics').Analytics>} source
*/
return async function* (source) {
for await (const analytics of source) {
const { requests, cachedRequests, firewallBlockedRequests, contentTypeRequests } = analytics
// Increment requests
metrics.requestsTotal.inc(requests)
// Increment cached requests
metrics.cachedRequestsTotal.inc(cachedRequests)
// Increment firewall blocked requests
metrics.firewallBlocked.inc(firewallBlockedRequests)
// Increment request counts for each content type
contentTypeRequests && Object.keys(contentTypeRequests).forEach(type => {
metrics.requestsByContentTypeTotal.inc({ type }, contentTypeRequests[type])
})
yield analytics
}
}
}