-
Notifications
You must be signed in to change notification settings - Fork 309
/
priority_sampler.js
74 lines (55 loc) · 1.64 KB
/
priority_sampler.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
'use strict'
const Sampler = require('./sampler')
const ext = require('../ext')
const SERVICE_NAME = ext.tags.SERVICE_NAME
const SAMPLING_PRIORITY = ext.tags.SAMPLING_PRIORITY
const USER_REJECT = ext.priority.USER_REJECT
const AUTO_REJECT = ext.priority.AUTO_REJECT
const AUTO_KEEP = ext.priority.AUTO_KEEP
const USER_KEEP = ext.priority.USER_KEEP
const DEFAULT_KEY = 'service:,env:'
const priorities = [
USER_REJECT,
AUTO_REJECT,
AUTO_KEEP,
USER_KEEP
]
class PrioritySampler {
constructor (env) {
this._env = env
this.update({})
}
isSampled (span) {
const context = this._getContext(span)
const key = `service:${context.tags[SERVICE_NAME]},env:${this._env}`
const sampler = this._samplers[key] || this._samplers[DEFAULT_KEY]
return sampler.isSampled(span)
}
sample (span) {
const context = this._getContext(span)
if (context.sampling.priority !== undefined) return
const tag = parseInt(context.tags[SAMPLING_PRIORITY], 10)
if (this.validate(tag)) {
context.sampling.priority = tag
return
}
context.sampling.priority = this.isSampled(span) ? AUTO_KEEP : AUTO_REJECT
}
update (rates) {
const samplers = {}
for (const key in rates) {
const rate = rates[key]
const sampler = new Sampler(rate)
samplers[key] = sampler
}
samplers[DEFAULT_KEY] = samplers[DEFAULT_KEY] || new Sampler(AUTO_KEEP)
this._samplers = samplers
}
validate (samplingPriority) {
return priorities.indexOf(samplingPriority) !== -1
}
_getContext (span) {
return typeof span.context === 'function' ? span.context() : span
}
}
module.exports = PrioritySampler