|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | +import type { Link, Attributes, SpanKind, Context } from "@opentelemetry/api"; |
| 4 | +import type { Sampler, SamplingResult } from "@opentelemetry/sdk-trace-base"; |
| 5 | +import { SamplingDecision } from "@opentelemetry/sdk-trace-base"; |
| 6 | +import { roundDownToNearest, shouldSample } from "./samplingUtils.js"; |
| 7 | + |
| 8 | +type RateLimitedSamplerState = { |
| 9 | + effectiveWindowCount: number; |
| 10 | + effectiveWindowNanos: number; |
| 11 | + lastNanoTime: number; |
| 12 | +}; |
| 13 | + |
| 14 | +/** |
| 15 | + * RateLimitedSampler is responsible for the following: |
| 16 | + * - Implements a rate-limiting sampling strategy based on a specified number of requests per second. |
| 17 | + * - Dynamically adjusts the sampling rate based on the time elapsed since the last sample. |
| 18 | + * - Provides a sampling rate that can be used to determine whether a span should be recorded. |
| 19 | + * @param requestsPerSecond - |
| 20 | + */ |
| 21 | +export class RateLimitedSampler implements Sampler { |
| 22 | + private readonly nanoTimeSupplier: () => number; |
| 23 | + private readonly inverseAdaptationTimeNanos: number; |
| 24 | + private readonly targetSpansPerNanosecondLimit: number; |
| 25 | + private state: RateLimitedSamplerState; |
| 26 | + private readonly roundToNearest: boolean; |
| 27 | + private readonly tracesPerSecond: number; |
| 28 | + |
| 29 | + /** |
| 30 | + * Initializes a new instance of the RateLimitedSampler class. |
| 31 | + * @param tracesPerSecond - The maximum number of traces to sample per second. |
| 32 | + * @throws Error if tracesPerSecond is negative. |
| 33 | + */ |
| 34 | + constructor(tracesPerSecond: number) { |
| 35 | + this.tracesPerSecond = tracesPerSecond; |
| 36 | + if (this.tracesPerSecond < 0.0) { |
| 37 | + throw new Error("Limit for sampled traces per second must be nonnegative"); |
| 38 | + } |
| 39 | + const adaptationTimeSeconds = 0.1; |
| 40 | + this.nanoTimeSupplier = () => Number(process.hrtime.bigint()); |
| 41 | + this.inverseAdaptationTimeNanos = 1e-9 / adaptationTimeSeconds; |
| 42 | + this.targetSpansPerNanosecondLimit = 1e-9 * this.tracesPerSecond; |
| 43 | + const now = this.nanoTimeSupplier(); |
| 44 | + this.state = { |
| 45 | + effectiveWindowCount: 0, |
| 46 | + effectiveWindowNanos: 0, |
| 47 | + lastNanoTime: now, |
| 48 | + }; |
| 49 | + this.roundToNearest = true; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Updates the state of the sampler based on the current time. |
| 54 | + * This method calculates the effective window count and nanos based on the time elapsed since the last sample. |
| 55 | + * @param oldState - The previous state of the sampler. |
| 56 | + * @param currentNanoTime - The current time in nanoseconds. |
| 57 | + * @returns The updated state of the sampler. |
| 58 | + */ |
| 59 | + private updateState( |
| 60 | + oldState: RateLimitedSamplerState, |
| 61 | + currentNanoTime: number, |
| 62 | + ): RateLimitedSamplerState { |
| 63 | + if (currentNanoTime <= oldState.lastNanoTime) { |
| 64 | + return { |
| 65 | + effectiveWindowCount: oldState.effectiveWindowCount + 1, |
| 66 | + effectiveWindowNanos: oldState.effectiveWindowNanos, |
| 67 | + lastNanoTime: oldState.lastNanoTime, |
| 68 | + }; |
| 69 | + } |
| 70 | + const nanoTimeDelta = currentNanoTime - oldState.lastNanoTime; |
| 71 | + const decayFactor = Math.exp(-nanoTimeDelta * this.inverseAdaptationTimeNanos); |
| 72 | + const currentEffectiveWindowCount = oldState.effectiveWindowCount * decayFactor + 1; |
| 73 | + const currentEffectiveWindowNanos = oldState.effectiveWindowNanos * decayFactor + nanoTimeDelta; |
| 74 | + return { |
| 75 | + effectiveWindowCount: currentEffectiveWindowCount, |
| 76 | + effectiveWindowNanos: currentEffectiveWindowNanos, |
| 77 | + lastNanoTime: currentNanoTime, |
| 78 | + }; |
| 79 | + } |
| 80 | + |
| 81 | + /** |
| 82 | + * Gets the current sample rate based on the effective window count and nanos. |
| 83 | + * This method calculates the sampling probability and returns it as a percentage. |
| 84 | + * If `roundToNearest` is true, it rounds down the sampling percentage to the nearest whole number. |
| 85 | + * @returns The current sample rate as a percentage. |
| 86 | + */ |
| 87 | + public getSampleRate(): number { |
| 88 | + const currentNanoTime = this.nanoTimeSupplier(); |
| 89 | + this.state = this.updateState(this.state, currentNanoTime); |
| 90 | + |
| 91 | + const samplingProbability = |
| 92 | + (this.state.effectiveWindowNanos * this.targetSpansPerNanosecondLimit) / |
| 93 | + this.state.effectiveWindowCount; |
| 94 | + let samplingPercentage = 100 * Math.min(samplingProbability, 1); |
| 95 | + |
| 96 | + if (this.roundToNearest) { |
| 97 | + samplingPercentage = roundDownToNearest(samplingPercentage); |
| 98 | + } |
| 99 | + return samplingPercentage; |
| 100 | + } |
| 101 | + |
| 102 | + /** |
| 103 | + * Checks whether span needs to be created and tracked. |
| 104 | + * |
| 105 | + * @param context - Parent Context which may contain a span. |
| 106 | + * @param traceId - traceId of the span to be created. It can be different from the |
| 107 | + * traceId in the {@link SpanContext}. Typically in situations when the |
| 108 | + * span to be created starts a new trace. |
| 109 | + * @param spanName - Name of the span to be created. |
| 110 | + * @param spanKind - Kind of the span to be created. |
| 111 | + * @param attributes - Initial set of SpanAttributes for the Span being constructed. |
| 112 | + * @param links - Collection of links that will be associated with the Span to |
| 113 | + * be created. Typically useful for batch operations. |
| 114 | + * @returns a {@link SamplingResult}. |
| 115 | + */ |
| 116 | + public shouldSample( |
| 117 | + context: Context, |
| 118 | + traceId: string, |
| 119 | + // @ts-expect-error unused argument |
| 120 | + spanName: string, |
| 121 | + // @ts-expect-error unused argument |
| 122 | + spanKind: SpanKind, |
| 123 | + attributes: Attributes, |
| 124 | + // @ts-expect-error unused argument |
| 125 | + links: Link[], |
| 126 | + ): SamplingResult { |
| 127 | + const sampleRate = this.getSampleRate(); |
| 128 | + return shouldSample(sampleRate, context, traceId, attributes) |
| 129 | + ? { decision: SamplingDecision.RECORD_AND_SAMPLED, attributes: attributes } |
| 130 | + : { decision: SamplingDecision.NOT_RECORD, attributes: attributes }; |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * Return Sampler description |
| 135 | + */ |
| 136 | + public toString(): string { |
| 137 | + return `RateLimitedSampler{${this.tracesPerSecond}}`; |
| 138 | + } |
| 139 | +} |
0 commit comments