generated from honeycombio/.github
-
Notifications
You must be signed in to change notification settings - Fork 7
/
deterministic-sampler.ts
66 lines (61 loc) · 1.49 KB
/
deterministic-sampler.ts
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
import { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
import {
AlwaysOffSampler,
AlwaysOnSampler,
Sampler,
SamplingResult,
TraceIdRatioBasedSampler,
} from '@opentelemetry/sdk-trace-base';
import { DEFAULT_SAMPLE_RATE } from './honeycomb-options';
export function configureDeterministicSampler(sampleRate?: number) {
return new DeterministicSampler(
sampleRate === undefined ? DEFAULT_SAMPLE_RATE : sampleRate,
);
}
export class DeterministicSampler implements Sampler {
private _sampleRate: number;
private _sampler: Sampler;
constructor(sampleRate: number) {
this._sampleRate = sampleRate;
switch (sampleRate) {
case 0:
this._sampler = new AlwaysOffSampler();
break;
case 1:
this._sampler = new AlwaysOnSampler();
break;
default: {
const ratio = 1.0 / sampleRate;
this._sampler = new TraceIdRatioBasedSampler(ratio);
break;
}
}
}
shouldSample(
context: Context,
traceId: string,
spanName: string,
spanKind: SpanKind,
attributes: Attributes,
links: Link[],
): SamplingResult {
const result = this._sampler.shouldSample(
context,
traceId,
spanName,
spanKind,
attributes,
links,
);
return {
...result,
attributes: {
...result.attributes,
SampleRate: this._sampleRate,
},
};
}
toString(): string {
return `DeterministicSampler(${this._sampler.toString()})`;
}
}