Skip to main content

stele/traces/
stats.rs

1// serde_with's DeserializeFromStr macro generates code that calls core::str::from_utf8 internally,
2// which we otherwise disallow in favor of simdutf8::basic::from_utf8.
3#![allow(clippy::disallowed_methods)]
4
5use std::{
6    collections::hash_map::Entry,
7    fmt,
8    hash::{Hash as _, Hasher as _},
9    num::ParseIntError,
10    str::FromStr,
11};
12
13use base64::Engine as _;
14use datadog_protos::{
15    sketches::DDSketch as ProtoDDSketch,
16    traces::{self as proto, Trilean},
17};
18use ddsketch::canonical::{mapping::LogarithmicMapping, DDSketch};
19use protobuf::Message as _;
20use saluki_common::{collections::FastHashMap, hash::StableHasher};
21use saluki_error::{generic_error, ErrorContext as _, GenericError};
22use serde::{Deserialize, Serialize};
23use serde_with::{DeserializeFromStr, SerializeDisplay};
24use stringtheory::MetaString;
25
26/// An ergonomic wrapper around `DDSketch` for APM stats.
27///
28/// This wrapper holds an APM stats-specific `DDSketch`, which ensures the relevant DDSketch parameters (relative
29/// accuracy, max bins, etc) are matched to that of the DDSketch configuration used in the Trace Agent. Further, this
30/// wrapper provides ergonomic conversions to/from a string representation based on a base64-encoded wrapper around the
31/// canonical Protobuf representation.
32///
33/// This makes it safe to transport over JSON for use in `datadog-intake` and `panoramic`.
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35#[serde(try_from = "String", into = "String")]
36pub struct EncodedApmStatsDDSketch {
37    inner: DDSketch,
38}
39
40impl EncodedApmStatsDDSketch {
41    /// Returns a reference to the inner `DDSketch`.
42    pub fn inner(&self) -> &DDSketch {
43        &self.inner
44    }
45
46    /// Returns a mutable reference to the inner `DDSketch`.
47    pub fn inner_mut(&mut self) -> &mut DDSketch {
48        &mut self.inner
49    }
50}
51
52impl TryFrom<ProtoDDSketch> for EncodedApmStatsDDSketch {
53    type Error = GenericError;
54
55    fn try_from(value: ProtoDDSketch) -> Result<Self, Self::Error> {
56        // TODO: It'd be good to avoid having to reconstitute the mapping manually, somehow.
57        let mapping = LogarithmicMapping::new(0.01).expect("Relative accuracy should be valid (0 <= 0.01 <= 1)");
58        let inner = DDSketch::from_proto(&value, mapping)
59            .error_context("Failed to convert DDSketch from canonical Protocol Buffers representation.")?;
60
61        Ok(Self { inner })
62    }
63}
64
65impl TryFrom<String> for EncodedApmStatsDDSketch {
66    type Error = GenericError;
67
68    fn try_from(value: String) -> Result<Self, Self::Error> {
69        // We expect the sketch to be encoded in its canonical Protocol Buffers form, additionally wrapped
70        // in a base64 encoding to make it safe for JSON transport.
71        let sketch_raw_proto = base64::engine::general_purpose::STANDARD
72            .decode(value)
73            .error_context("Failed to decode base64-encoded DDSketch.")?;
74
75        let sketch_proto = ProtoDDSketch::parse_from_bytes(&sketch_raw_proto[..])
76            .error_context("Failed to decode DDSketch from canonical Protocol Buffers representation.")?;
77
78        Self::try_from(sketch_proto)
79    }
80}
81
82impl From<EncodedApmStatsDDSketch> for ProtoDDSketch {
83    fn from(value: EncodedApmStatsDDSketch) -> Self {
84        value.inner.to_proto()
85    }
86}
87
88impl From<EncodedApmStatsDDSketch> for String {
89    fn from(value: EncodedApmStatsDDSketch) -> Self {
90        let sketch_proto = ProtoDDSketch::from(value);
91        let sketch_raw_proto = sketch_proto
92            .write_to_bytes()
93            .expect("Should not fail to encode DDSketch to serialized Protocol Buffers representation.");
94
95        base64::engine::general_purpose::STANDARD.encode(sketch_raw_proto)
96    }
97}
98
99#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
100struct AgentMetadata {
101    hostname: MetaString,
102    env: MetaString,
103    agent_version: MetaString,
104    client_computed: bool,
105}
106
107impl From<&proto::StatsPayload> for AgentMetadata {
108    fn from(payload: &proto::StatsPayload) -> Self {
109        Self {
110            hostname: (*payload.agentHostname).into(),
111            env: (*payload.agentEnv).into(),
112            agent_version: (*payload.agentVersion).into(),
113            client_computed: payload.clientComputed,
114        }
115    }
116}
117
118#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
119struct TracerMetadata {
120    hostname: MetaString,
121    env: MetaString,
122    version: MetaString,
123    service: MetaString,
124    language: MetaString,
125    tracer_version: MetaString,
126    runtime_id: MetaString,
127    sequence: u64,
128    agent_aggregation: MetaString,
129    container_id: MetaString,
130    tags: Vec<MetaString>,
131    git_commit_sha: MetaString,
132    image_tag: MetaString,
133    process_tags_hash: u64,
134    process_tags: MetaString,
135}
136
137impl From<&proto::ClientStatsPayload> for TracerMetadata {
138    fn from(payload: &proto::ClientStatsPayload) -> Self {
139        Self {
140            hostname: (*payload.hostname).into(),
141            env: (*payload.env).into(),
142            version: (*payload.version).into(),
143            service: (*payload.service).into(),
144            language: (*payload.lang).into(),
145            tracer_version: (*payload.tracerVersion).into(),
146            runtime_id: (*payload.runtimeID).into(),
147            sequence: payload.sequence,
148            agent_aggregation: (*payload.agentAggregation).into(),
149            container_id: (*payload.containerID).into(),
150            tags: payload.tags.iter().map(|t| MetaString::from(&**t)).collect(),
151            git_commit_sha: (*payload.git_commit_sha).into(),
152            image_tag: (*payload.image_tag).into(),
153            process_tags_hash: payload.process_tags_hash,
154            process_tags: (*payload.process_tags).into(),
155        }
156    }
157}
158
159/// Time frame covered by a bucket.
160#[derive(Clone, Copy, Debug, DeserializeFromStr, Hash, Eq, PartialEq, SerializeDisplay)]
161pub struct BucketTimeframe {
162    /// Start time of the bucket, in nanoseconds.
163    pub start_time_ns: u64,
164
165    /// Width of the bucket, in nanoseconds.
166    pub duration_ns: u64,
167}
168
169impl fmt::Display for BucketTimeframe {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        write!(f, "[{},{}]", self.start_time_ns, self.duration_ns)
172    }
173}
174
175impl FromStr for BucketTimeframe {
176    type Err = String;
177
178    fn from_str(s: &str) -> Result<Self, Self::Err> {
179        let parts: Vec<&str> = s.trim_matches(['[', ']']).split(',').collect();
180        if parts.len() != 2 {
181            return Err(format!("expected two elements, found {}", parts.len()));
182        }
183        let start_time_ns = parts[0].parse::<u64>().map_err(|e| e.to_string())?;
184        let duration_ns = parts[1].parse::<u64>().map_err(|e| e.to_string())?;
185        Ok(Self {
186            start_time_ns,
187            duration_ns,
188        })
189    }
190}
191
192impl From<&proto::ClientStatsBucket> for BucketTimeframe {
193    fn from(bucket: &proto::ClientStatsBucket) -> Self {
194        Self {
195            start_time_ns: bucket.start,
196            duration_ns: bucket.duration,
197        }
198    }
199}
200
201/// Client statistics grouped by time frame.
202#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
203pub struct BucketedClientStatistics {
204    agent_metadata: AgentMetadata,
205    tracer_metadata: TracerMetadata,
206    buckets: FastHashMap<BucketTimeframe, ClientStatistics>,
207}
208
209impl BucketedClientStatistics {
210    /// Merge the given stats into the given bucket, creating the bucket if it doesn't already exist.
211    pub fn merge(&mut self, bucket_timeframe: BucketTimeframe, stats: ClientStatistics) -> Result<(), GenericError> {
212        match self.buckets.entry(bucket_timeframe) {
213            Entry::Occupied(mut entry) => {
214                let existing_stats = entry.get_mut();
215                existing_stats.merge(stats)
216            }
217            Entry::Vacant(entry) => {
218                entry.insert(stats);
219                Ok(())
220            }
221        }
222    }
223
224    /// Returns a merged `ClientStatistics` representing all buckets.
225    ///
226    /// If no buckets are present, `Ok(None)` is returned. Otherwise, `Ok(Some)` is returned containing the merged
227    /// client statistics.
228    ///
229    /// # Errors
230    ///
231    /// If the buckets can't be merged for any reason, an error is returned.
232    pub fn merged(&self) -> Result<Option<ClientStatistics>, GenericError> {
233        let mut bucket_stats = self.buckets.values().cloned();
234
235        let mut merged_stats = match bucket_stats.next() {
236            Some(bucket) => bucket,
237            None => return Ok(None),
238        };
239
240        for other in bucket_stats {
241            merged_stats.merge(other)?;
242        }
243
244        Ok(Some(merged_stats))
245    }
246
247    /// Returns an iterator over each bucket.
248    pub fn buckets(&self) -> impl Iterator<Item = (&BucketTimeframe, &ClientStatistics)> {
249        self.buckets.iter()
250    }
251}
252
253/// Client statistics for a given span.
254#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
255pub struct ClientStatistics {
256    service: MetaString,
257    name: MetaString,
258    resource: MetaString,
259    type_: MetaString,
260    hits: u64,
261    errors: u64,
262    duration_ns: u64,
263    ok_summary: EncodedApmStatsDDSketch,
264    error_summary: EncodedApmStatsDDSketch,
265    synthetics: bool,
266    top_level_hits: u64,
267    span_kind: MetaString,
268    peer_tags: Vec<MetaString>,
269    is_trace_root: Option<bool>,
270    db_type: MetaString,
271    grpc_status_code: MetaString,
272    http_status_code: u32,
273    http_method: MetaString,
274    http_endpoint: MetaString,
275}
276
277impl ClientStatistics {
278    /// Returns the name of the service whose spans these statistics cover.
279    pub fn service(&self) -> &str {
280        &self.service
281    }
282
283    /// Merges `other` into `self`.
284    ///
285    /// If `other` doesn't have the same aggregation key as `self` (essentially: if any of the string fields differ),
286    /// an error is returned.
287    pub fn merge(&mut self, other: Self) -> Result<(), GenericError> {
288        // Check all "fixed" fields and ensure they're identical.
289        if self.service != other.service {
290            return Err(generic_error!("failed to merge client statistics: service mismatch"));
291        }
292        if self.name != other.name {
293            return Err(generic_error!("failed to merge client statistics: name mismatch"));
294        }
295        if self.resource != other.resource {
296            return Err(generic_error!("failed to merge client statistics: resource mismatch"));
297        }
298        if self.type_ != other.type_ {
299            return Err(generic_error!("failed to merge client statistics: type mismatch"));
300        }
301        if self.span_kind != other.span_kind {
302            return Err(generic_error!("failed to merge client statistics: span kind mismatch"));
303        }
304        if self.peer_tags != other.peer_tags {
305            return Err(generic_error!("failed to merge client statistics: peer tags mismatch"));
306        }
307        if self.db_type != other.db_type {
308            return Err(generic_error!("failed to merge client statistics: db type mismatch"));
309        }
310        if self.grpc_status_code != other.grpc_status_code {
311            return Err(generic_error!(
312                "failed to merge client statistics: grpc status code mismatch"
313            ));
314        }
315        if self.http_status_code != other.http_status_code {
316            return Err(generic_error!(
317                "failed to merge client statistics: http status code mismatch"
318            ));
319        }
320        if self.http_method != other.http_method {
321            return Err(generic_error!(
322                "failed to merge client statistics: http method mismatch"
323            ));
324        }
325        if self.http_endpoint != other.http_endpoint {
326            return Err(generic_error!(
327                "failed to merge client statistics: http endpoint mismatch"
328            ));
329        }
330
331        // Merge together the things we can actually merge.
332        //
333        // The counters wrap on overflow, as the `uint64` fields that the trace-agent sums them into do. Generated spans
334        // can have durations close to `i64::MAX`, so summing a few of them overflows `u64`: wrapping keeps both sides
335        // of a comparison equal where checked addition would panic.
336        self.hits = self.hits.wrapping_add(other.hits);
337        self.errors = self.errors.wrapping_add(other.errors);
338        self.duration_ns = self.duration_ns.wrapping_add(other.duration_ns);
339        self.synthetics |= other.synthetics;
340        self.top_level_hits = self.top_level_hits.wrapping_add(other.top_level_hits);
341
342        self.ok_summary.inner_mut().merge(other.ok_summary.inner());
343        self.error_summary.inner_mut().merge(other.error_summary.inner());
344
345        Ok(())
346    }
347}
348
349impl From<&proto::ClientGroupedStats> for ClientStatistics {
350    fn from(payload: &proto::ClientGroupedStats) -> Self {
351        let is_trace_root = match payload.is_trace_root.enum_value() {
352            Ok(Trilean::NOT_SET) => None,
353            Ok(Trilean::TRUE) => Some(true),
354            Ok(Trilean::FALSE) => Some(false),
355            Err(_) => None,
356        };
357
358        // Decode the DDSketch entries from their canonial Protocol Buffers representation.
359        let ok_summary_proto = ProtoDDSketch::parse_from_bytes(payload.okSummary())
360            .expect("Should not fail to decode DDSketch from serialized Protocol Buffers representation.");
361        let ok_summary = EncodedApmStatsDDSketch::try_from(ok_summary_proto)
362            .expect("Should not fail to convert DDSketch from canonical Protocol Buffers representation.");
363        let error_summary_proto = ProtoDDSketch::parse_from_bytes(payload.errorSummary())
364            .expect("Should not fail to decode DDSketch from serialized Protocol Buffers representation.");
365        let error_summary = EncodedApmStatsDDSketch::try_from(error_summary_proto)
366            .expect("Should not fail to convert DDSketch from canonical Protocol Buffers representation.");
367
368        Self {
369            service: (*payload.service).into(),
370            name: (*payload.name).into(),
371            resource: (*payload.resource).into(),
372            type_: (*payload.type_).into(),
373            hits: payload.hits,
374            errors: payload.errors,
375            duration_ns: payload.duration,
376            ok_summary,
377            error_summary,
378            synthetics: payload.synthetics,
379            top_level_hits: payload.topLevelHits,
380            span_kind: (*payload.span_kind).into(),
381            peer_tags: payload.peer_tags.iter().map(|t| MetaString::from(&**t)).collect(),
382            is_trace_root,
383            db_type: (*payload.DB_type).into(),
384            grpc_status_code: (*payload.GRPC_status_code).into(),
385            http_status_code: payload.HTTP_status_code,
386            http_method: (*payload.HTTP_method).into(),
387            http_endpoint: (*payload.HTTP_endpoint).into(),
388        }
389    }
390}
391
392/// Aggregation key for client statistics.
393#[derive(Clone, Debug, DeserializeFromStr, Eq, Hash, PartialEq, SerializeDisplay)]
394pub struct AggregationKey(u64);
395
396impl fmt::Display for AggregationKey {
397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398        write!(f, "{}", self.0)
399    }
400}
401
402impl FromStr for AggregationKey {
403    type Err = ParseIntError;
404
405    fn from_str(s: &str) -> Result<Self, Self::Err> {
406        Ok(Self(s.parse()?))
407    }
408}
409
410impl From<&proto::ClientGroupedStats> for AggregationKey {
411    fn from(payload: &proto::ClientGroupedStats) -> Self {
412        // We manually hash the various fields to come up with our aggregation key.
413        //
414        // TODO: This follows the logic in `libdd-trace-stats` and it would be nice to eventually converge on using
415        // that code directly, but there's a number of changes that would need to be made upstream in order to make
416        // doing so possible.
417        let mut hasher = StableHasher::default();
418
419        payload.resource.hash(&mut hasher);
420        payload.service.hash(&mut hasher);
421        payload.name.hash(&mut hasher);
422        payload.type_.hash(&mut hasher);
423        payload.span_kind.hash(&mut hasher);
424        payload.HTTP_status_code.hash(&mut hasher);
425        payload.synthetics.hash(&mut hasher);
426
427        // TODO: technically, peer tags should only be included if they match the _configured_ peer keys to aggregate on
428        // so we're doing this wrong but we can iterate on it later
429        payload.peer_tags.hash(&mut hasher);
430
431        payload.is_trace_root.value().hash(&mut hasher);
432        payload.HTTP_method.hash(&mut hasher);
433        payload.HTTP_endpoint.hash(&mut hasher);
434        payload.GRPC_status_code.hash(&mut hasher);
435        payload.DB_type.hash(&mut hasher);
436
437        Self(hasher.finish())
438    }
439}
440
441/// Aggregator for client statistics.
442///
443/// Client statistics are represented by generating an "aggregation key" for a given span, and then grouping statistics
444/// by that key. The aggregation key includes fields like service, span name, span operation, response code, and more.
445/// This is meant to group like spans together,
446#[derive(Clone, Debug, Default, Deserialize, Serialize)]
447pub struct ClientStatisticsAggregator {
448    groups: FastHashMap<AggregationKey, BucketedClientStatistics>,
449}
450
451impl ClientStatisticsAggregator {
452    /// Merges the given payload into the aggregator.
453    pub fn merge_payload(&mut self, payload: &proto::StatsPayload) -> Result<(), GenericError> {
454        let agent_metadata = AgentMetadata::from(payload);
455        for client_stats_payload in payload.stats() {
456            let tracer_metadata = TracerMetadata::from(client_stats_payload);
457
458            for stats_bucket in client_stats_payload.stats() {
459                let bucket_timeframe = BucketTimeframe::from(stats_bucket);
460
461                for grouped_stat in stats_bucket.stats() {
462                    let aggregation_key = AggregationKey::from(grouped_stat);
463                    let stats_group = self
464                        .groups
465                        .entry(aggregation_key)
466                        .or_insert_with(|| BucketedClientStatistics {
467                            agent_metadata: agent_metadata.clone(),
468                            tracer_metadata: tracer_metadata.clone(),
469                            buckets: FastHashMap::default(),
470                        });
471
472                    if stats_group.agent_metadata != agent_metadata {
473                        return Err(generic_error!("agent metadata mismatch"));
474                    }
475                    if stats_group.tracer_metadata != tracer_metadata {
476                        return Err(generic_error!("tracer metadata mismatch"));
477                    }
478
479                    stats_group.merge(bucket_timeframe, ClientStatistics::from(grouped_stat))?;
480                }
481            }
482        }
483
484        Ok(())
485    }
486
487    /// Returns a reference to the aggregated statistics groups.
488    pub fn groups(&self) -> &FastHashMap<AggregationKey, BucketedClientStatistics> {
489        &self.groups
490    }
491}
492
493#[cfg(test)]
494mod tests {
495    use protobuf::Message as _;
496
497    use super::{proto, ClientStatistics, ClientStatisticsAggregator, DDSketch};
498
499    fn sketch_bytes() -> Vec<u8> {
500        let mut sketch = DDSketch::with_relative_accuracy(0.01).expect("relative accuracy should be valid");
501        sketch.add(1.0);
502        sketch.to_proto().write_to_bytes().expect("sketch should serialize")
503    }
504
505    fn stats_payload(split_payload: bool) -> proto::StatsPayload {
506        let mut grouped = proto::ClientGroupedStats::new();
507        grouped.set_service("svc".to_string());
508        grouped.set_name("op".to_string());
509        grouped.set_resource("res".to_string());
510        grouped.set_hits(1);
511        grouped.set_okSummary(sketch_bytes());
512        grouped.set_errorSummary(sketch_bytes());
513
514        let mut bucket = proto::ClientStatsBucket::new();
515        bucket.set_start(0);
516        bucket.set_duration(10);
517        bucket.set_stats(vec![grouped]);
518
519        let mut client = proto::ClientStatsPayload::new();
520        client.set_hostname("host".to_string());
521        client.set_stats(vec![bucket]);
522
523        let mut payload = proto::StatsPayload::new();
524        payload.set_agentHostname("agent".to_string());
525        payload.set_splitPayload(split_payload);
526        payload.set_stats(vec![client]);
527        payload
528    }
529
530    #[test]
531    fn split_payload_flag_does_not_have_to_match_across_payloads() {
532        let mut aggregator = ClientStatisticsAggregator::default();
533
534        aggregator.merge_payload(&stats_payload(false)).unwrap();
535        aggregator.merge_payload(&stats_payload(true)).unwrap();
536    }
537
538    fn client_stats(hits: u64, errors: u64, duration_ns: u64, top_level_hits: u64) -> ClientStatistics {
539        let empty_sketch: DDSketch =
540            DDSketch::with_relative_accuracy(0.01).expect("Relative accuracy should be valid (0 <= 0.01 <= 1)");
541        let empty_sketch = empty_sketch
542            .to_proto()
543            .write_to_bytes()
544            .expect("Should not fail to encode an empty DDSketch.");
545
546        let mut payload = proto::ClientGroupedStats::new();
547        payload.service = "service".into();
548        payload.name = "name".into();
549        payload.hits = hits;
550        payload.errors = errors;
551        payload.duration = duration_ns;
552        payload.topLevelHits = top_level_hits;
553        payload.okSummary = empty_sketch.clone();
554        payload.errorSummary = empty_sketch;
555
556        ClientStatistics::from(&payload)
557    }
558
559    #[test]
560    fn merge_wraps_counters_on_overflow() {
561        // Generated spans can have durations close to `i64::MAX`, and three of them overflow `u64` when summed.
562        let large = i64::MAX as u64;
563        let mut merged = client_stats(1, 1, large, 1);
564        merged.merge(client_stats(1, 1, large, 1)).unwrap();
565        merged.merge(client_stats(1, 1, large, 1)).unwrap();
566        assert_eq!(merged.duration_ns, large.wrapping_mul(3));
567        assert_eq!(merged.hits, 3);
568        assert_eq!(merged.errors, 3);
569        assert_eq!(merged.top_level_hits, 3);
570
571        let mut merged = client_stats(u64::MAX, u64::MAX, 0, u64::MAX);
572        merged.merge(client_stats(1, 1, 0, 1)).unwrap();
573        assert_eq!(merged.hits, 0);
574        assert_eq!(merged.errors, 0);
575        assert_eq!(merged.top_level_hits, 0);
576    }
577}