xref: /aosp_15_r20/external/grpc-grpc/src/python/grpcio_observability/grpc_observability/sampler.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2023 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "sampler.h"
16 
17 #include <cmath>
18 #include <cstdint>
19 
20 #include "absl/strings/escaping.h"
21 
22 namespace grpc_observability {
23 
24 namespace {
25 
26 // Converts a probability in [0, 1] to a threshold in [0, UINT64_MAX].
CalculateThreshold(double probability)27 uint64_t CalculateThreshold(double probability) {
28   if (probability <= 0.0) return 0;
29   if (probability >= 1.0) return UINT64_MAX;
30   // We can't directly return probability * UINT64_MAX.
31   //
32   // UINT64_MAX is (2^64)-1, but as a double rounds up to 2^64.
33   // For probabilities >= 1-(2^-54), the product wraps to zero!
34   // Instead, calculate the high and low 32 bits separately.
35   const double product = UINT32_MAX * probability;
36   double hi_bits, lo_bits = ldexp(modf(product, &hi_bits), 32) + product;
37   return (static_cast<uint64_t>(hi_bits) << 32) +
38          static_cast<uint64_t>(lo_bits);
39 }
40 
CalculateThresholdFromBuffer(const std::string & trace_id)41 uint64_t CalculateThresholdFromBuffer(const std::string& trace_id) {
42   const std::string trace_id_bytes = absl::HexStringToBytes(trace_id);
43   const uint8_t* buf = reinterpret_cast<const uint8_t*>(trace_id_bytes.c_str());
44   uint64_t res = 0;
45   for (int i = 0; i < 8; ++i) {
46     res |= (static_cast<uint64_t>(buf[i]) << (i * 8));
47   }
48   return res;
49 }
50 }  // namespace
51 
Get()52 ProbabilitySampler& ProbabilitySampler::Get() {
53   static ProbabilitySampler* sampler = new ProbabilitySampler;
54   return *sampler;
55 }
56 
SetThreshold(double probability)57 void ProbabilitySampler::SetThreshold(double probability) {
58   uint64_t threshold = CalculateThreshold(probability);
59   threshold_ = threshold;
60 }
61 
ShouldSample(const std::string & trace_id)62 bool ProbabilitySampler::ShouldSample(const std::string& trace_id) {
63   if (threshold_ == 0 || trace_id.length() < 32) return false;
64   // All Spans within the same Trace will get the same sampling decision, so
65   // full trees of Spans will be sampled.
66   return CalculateThresholdFromBuffer(trace_id) <= threshold_;
67 }
68 
69 }  // namespace grpc_observability
70