|
| 1 | +/** |
| 2 | + * Copyright 2019, OpenCensus Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { SpanContext } from '@opencensus/web-types'; |
| 18 | + |
| 19 | +const IS_SAMPLED_BIT = 0x1; |
| 20 | + |
| 21 | +/** |
| 22 | + * Returns whether sampling hint bit of the intial load span context `options` |
| 23 | + * is set. |
| 24 | + */ |
| 25 | +export function isSampled(spanContext: SpanContext) { |
| 26 | + const options = spanContext.options; |
| 27 | + if (!options) return false; |
| 28 | + return !!(options & IS_SAMPLED_BIT); |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Random sampling decision using `Math.random`. |
| 33 | + */ |
| 34 | +export function makeRandomSamplingDecision(sampleRate: number): number { |
| 35 | + // Math.random returns a number in the 0-1 range (inclusive of 0 but not 1). |
| 36 | + // That means we should use the strict `<` operator to compare it to the |
| 37 | + // sample rate. A value of 1 for `options` indicates trace sampling. |
| 38 | + return Math.random() < sampleRate ? 1 : 0; |
| 39 | +} |
0 commit comments