|
| 1 | +/* eslint-disable no-bitwise */ |
| 2 | +import type { Attributes, Context, SpanContext } from '@opentelemetry/api'; |
| 3 | +import { isSpanContextValid, trace, TraceFlags } from '@opentelemetry/api'; |
| 4 | +import type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace-base'; |
| 5 | +import { SamplingDecision } from '@opentelemetry/sdk-trace-base'; |
| 6 | +import { hasTracingEnabled } from '@sentry/core'; |
| 7 | +import { _INTERNAL_SENTRY_TRACE_PARENT_CONTEXT_KEY } from '@sentry/opentelemetry-node'; |
| 8 | +import type { Client, ClientOptions, SamplingContext, TraceparentData } from '@sentry/types'; |
| 9 | +import { isNaN, logger } from '@sentry/utils'; |
| 10 | + |
| 11 | +import { OTEL_ATTR_PARENT_SAMPLED, OTEL_ATTR_SENTRY_SAMPLE_RATE } from '../constants'; |
| 12 | + |
| 13 | +/** |
| 14 | + * A custom OTEL sampler that uses Sentry sampling rates to make it's decision |
| 15 | + */ |
| 16 | +export class SentrySampler implements Sampler { |
| 17 | + private _client: Client; |
| 18 | + |
| 19 | + public constructor(client: Client) { |
| 20 | + this._client = client; |
| 21 | + } |
| 22 | + |
| 23 | + /** @inheritDoc */ |
| 24 | + public shouldSample( |
| 25 | + context: Context, |
| 26 | + traceId: string, |
| 27 | + spanName: string, |
| 28 | + _spanKind: unknown, |
| 29 | + _attributes: unknown, |
| 30 | + _links: unknown, |
| 31 | + ): SamplingResult { |
| 32 | + const options = this._client.getOptions(); |
| 33 | + |
| 34 | + if (!hasTracingEnabled(options)) { |
| 35 | + return { decision: SamplingDecision.NOT_RECORD }; |
| 36 | + } |
| 37 | + |
| 38 | + const parentContext = trace.getSpanContext(context); |
| 39 | + |
| 40 | + let parentSampled: boolean | undefined = undefined; |
| 41 | + |
| 42 | + // Only inherit sample rate if `traceId` is the same |
| 43 | + // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones |
| 44 | + if (parentContext && isSpanContextValid(parentContext) && parentContext.traceId === traceId) { |
| 45 | + if (parentContext.isRemote) { |
| 46 | + parentSampled = getParentRemoteSampled(parentContext, context); |
| 47 | + __DEBUG_BUILD__ && |
| 48 | + logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`); |
| 49 | + } else { |
| 50 | + parentSampled = Boolean(parentContext.traceFlags & TraceFlags.SAMPLED); |
| 51 | + __DEBUG_BUILD__ && |
| 52 | + logger.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + const sampleRate = getSampleRate(options, { |
| 57 | + transactionContext: { |
| 58 | + name: spanName, |
| 59 | + parentSampled, |
| 60 | + }, |
| 61 | + parentSampled, |
| 62 | + }); |
| 63 | + |
| 64 | + const attributes: Attributes = { |
| 65 | + [OTEL_ATTR_SENTRY_SAMPLE_RATE]: Number(sampleRate), |
| 66 | + }; |
| 67 | + |
| 68 | + if (typeof parentSampled === 'boolean') { |
| 69 | + attributes[OTEL_ATTR_PARENT_SAMPLED] = parentSampled; |
| 70 | + } |
| 71 | + |
| 72 | + // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The |
| 73 | + // only valid values are booleans or numbers between 0 and 1.) |
| 74 | + if (!isValidSampleRate(sampleRate)) { |
| 75 | + __DEBUG_BUILD__ && logger.warn('[Tracing] Discarding span because of invalid sample rate.'); |
| 76 | + |
| 77 | + return { |
| 78 | + decision: SamplingDecision.NOT_RECORD, |
| 79 | + attributes, |
| 80 | + }; |
| 81 | + } |
| 82 | + |
| 83 | + // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped |
| 84 | + if (!sampleRate) { |
| 85 | + __DEBUG_BUILD__ && |
| 86 | + logger.log( |
| 87 | + `[Tracing] Discarding span because ${ |
| 88 | + typeof options.tracesSampler === 'function' |
| 89 | + ? 'tracesSampler returned 0 or false' |
| 90 | + : 'a negative sampling decision was inherited or tracesSampleRate is set to 0' |
| 91 | + }`, |
| 92 | + ); |
| 93 | + |
| 94 | + return { |
| 95 | + decision: SamplingDecision.NOT_RECORD, |
| 96 | + attributes, |
| 97 | + }; |
| 98 | + } |
| 99 | + |
| 100 | + // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is |
| 101 | + // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. |
| 102 | + const isSampled = Math.random() < (sampleRate as number | boolean); |
| 103 | + |
| 104 | + // if we're not going to keep it, we're done |
| 105 | + if (!isSampled) { |
| 106 | + __DEBUG_BUILD__ && |
| 107 | + logger.log( |
| 108 | + `[Tracing] Discarding span because it's not included in the random sample (sampling rate = ${Number( |
| 109 | + sampleRate, |
| 110 | + )})`, |
| 111 | + ); |
| 112 | + |
| 113 | + return { |
| 114 | + decision: SamplingDecision.NOT_RECORD, |
| 115 | + attributes, |
| 116 | + }; |
| 117 | + } |
| 118 | + |
| 119 | + return { |
| 120 | + decision: SamplingDecision.RECORD_AND_SAMPLED, |
| 121 | + attributes, |
| 122 | + }; |
| 123 | + } |
| 124 | + |
| 125 | + /** Returns the sampler name or short description with the configuration. */ |
| 126 | + public toString(): string { |
| 127 | + return 'SentrySampler'; |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +function getSampleRate( |
| 132 | + options: Pick<ClientOptions, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'>, |
| 133 | + samplingContext: SamplingContext, |
| 134 | +): number | boolean { |
| 135 | + if (typeof options.tracesSampler === 'function') { |
| 136 | + return options.tracesSampler(samplingContext); |
| 137 | + } |
| 138 | + |
| 139 | + if (samplingContext.parentSampled !== undefined) { |
| 140 | + return samplingContext.parentSampled; |
| 141 | + } |
| 142 | + |
| 143 | + if (typeof options.tracesSampleRate !== 'undefined') { |
| 144 | + return options.tracesSampleRate; |
| 145 | + } |
| 146 | + |
| 147 | + // When `enableTracing === true`, we use a sample rate of 100% |
| 148 | + if (options.enableTracing) { |
| 149 | + return 1; |
| 150 | + } |
| 151 | + |
| 152 | + return 0; |
| 153 | +} |
| 154 | + |
| 155 | +/** |
| 156 | + * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). |
| 157 | + */ |
| 158 | +function isValidSampleRate(rate: unknown): boolean { |
| 159 | + // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck |
| 160 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 161 | + if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { |
| 162 | + __DEBUG_BUILD__ && |
| 163 | + logger.warn( |
| 164 | + `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( |
| 165 | + rate, |
| 166 | + )} of type ${JSON.stringify(typeof rate)}.`, |
| 167 | + ); |
| 168 | + return false; |
| 169 | + } |
| 170 | + |
| 171 | + // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false |
| 172 | + if (rate < 0 || rate > 1) { |
| 173 | + __DEBUG_BUILD__ && |
| 174 | + logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`); |
| 175 | + return false; |
| 176 | + } |
| 177 | + return true; |
| 178 | +} |
| 179 | + |
| 180 | +function getTraceParentData(parentContext: Context): TraceparentData | undefined { |
| 181 | + return parentContext.getValue(_INTERNAL_SENTRY_TRACE_PARENT_CONTEXT_KEY) as TraceparentData | undefined; |
| 182 | +} |
| 183 | + |
| 184 | +function getParentRemoteSampled(spanContext: SpanContext, context: Context): boolean | undefined { |
| 185 | + const traceId = spanContext.traceId; |
| 186 | + const traceparentData = getTraceParentData(context); |
| 187 | + |
| 188 | + // Only inherit sample rate if `traceId` is the same |
| 189 | + return traceparentData && traceId === traceparentData.traceId ? traceparentData.parentSampled : undefined; |
| 190 | +} |
0 commit comments