Skip to main content

saluki_core/data_model/event/trace_stats/
mod.rs

1//! Trace stats.
2
3use stringtheory::MetaString;
4
5use crate::data_model::tags::TagSet;
6
7/// Trace statistics output from the APM Stats transform.
8///
9/// Contains pre-aggregated trace statistics grouped by client/tracer. The encoder wraps this
10/// in a `StatsPayload` protobuf and adds agent-level metadata (`agentHostname`, `agentEnv`,
11/// `agentVersion`, `clientComputed`) from ADP configuration. `splitPayload` comes from this event, which records
12/// whether it is one of several events produced by splitting a flush.
13#[derive(Clone, Debug, PartialEq, Default)]
14pub struct TraceStats {
15    /// Multiple client payloads, one per PayloadAggregationKey (hostname/env/version/container).
16    stats: Vec<ClientStatsPayload>,
17    /// Whether this is one of several events produced by splitting a flush.
18    split_payload: bool,
19}
20
21impl TraceStats {
22    /// Creates a new `TraceStats` with the given client stats payloads.
23    pub fn new(stats: Vec<ClientStatsPayload>) -> Self {
24        Self {
25            stats,
26            split_payload: false,
27        }
28    }
29
30    /// Sets whether this is one of several events produced by splitting a flush.
31    pub fn with_split_payload(mut self, split_payload: bool) -> Self {
32        self.split_payload = split_payload;
33        self
34    }
35
36    /// Returns `true` if this is one of several events produced by splitting a flush.
37    pub fn is_split_payload(&self) -> bool {
38        self.split_payload
39    }
40
41    /// Returns a reference to the client stats payloads.
42    pub fn stats(&self) -> &[ClientStatsPayload] {
43        &self.stats
44    }
45
46    /// Returns a mutable reference to the client stats payloads.
47    pub fn stats_mut(&mut self) -> &mut Vec<ClientStatsPayload> {
48        &mut self.stats
49    }
50}
51
52/// Tracer-level stats payload.
53///
54/// Groups stats by tracer/container identity (hostname, env, version, `container_id`).
55#[derive(Clone, Debug, PartialEq, Default)]
56pub struct ClientStatsPayload {
57    hostname: MetaString,
58    env: MetaString,
59    version: MetaString,
60    stats: Vec<ClientStatsBucket>,
61    lang: MetaString,
62    tracer_version: MetaString,
63    runtime_id: MetaString,
64    sequence: u64,
65    agent_aggregation: MetaString,
66    service: MetaString,
67    container_id: MetaString,
68    tags: TagSet,
69    git_commit_sha: MetaString,
70    image_tag: MetaString,
71    process_tags_hash: u64,
72    process_tags: MetaString,
73}
74
75impl ClientStatsPayload {
76    /// Creates a new `ClientStatsPayload` with the required identity fields.
77    pub fn new(hostname: impl Into<MetaString>, env: impl Into<MetaString>, version: impl Into<MetaString>) -> Self {
78        Self {
79            hostname: hostname.into(),
80            env: env.into(),
81            version: version.into(),
82            ..Self::default()
83        }
84    }
85
86    /// Sets the stats buckets.
87    pub fn with_stats(mut self, stats: Vec<ClientStatsBucket>) -> Self {
88        self.stats = stats;
89        self
90    }
91
92    /// Sets the tracer language.
93    pub fn with_lang(mut self, lang: impl Into<MetaString>) -> Self {
94        self.lang = lang.into();
95        self
96    }
97
98    /// Sets the tracer version.
99    pub fn with_tracer_version(mut self, tracer_version: impl Into<MetaString>) -> Self {
100        self.tracer_version = tracer_version.into();
101        self
102    }
103
104    /// Sets the runtime identifier.
105    pub fn with_runtime_id(mut self, runtime_id: impl Into<MetaString>) -> Self {
106        self.runtime_id = runtime_id.into();
107        self
108    }
109
110    /// Sets the message sequence number.
111    pub fn with_sequence(mut self, sequence: u64) -> Self {
112        self.sequence = sequence;
113        self
114    }
115
116    /// Sets the agent aggregation key.
117    pub fn with_agent_aggregation(mut self, agent_aggregation: impl Into<MetaString>) -> Self {
118        self.agent_aggregation = agent_aggregation.into();
119        self
120    }
121
122    /// Sets the main service name.
123    pub fn with_service(mut self, service: impl Into<MetaString>) -> Self {
124        self.service = service.into();
125        self
126    }
127
128    /// Sets the container identifier.
129    pub fn with_container_id(mut self, container_id: impl Into<MetaString>) -> Self {
130        self.container_id = container_id.into();
131        self
132    }
133
134    /// Sets the orchestrator tags.
135    pub fn with_tags(mut self, tags: impl Into<TagSet>) -> Self {
136        self.tags = tags.into();
137        self
138    }
139
140    /// Sets the git commit SHA.
141    pub fn with_git_commit_sha(mut self, git_commit_sha: impl Into<MetaString>) -> Self {
142        self.git_commit_sha = git_commit_sha.into();
143        self
144    }
145
146    /// Sets the container image tag.
147    pub fn with_image_tag(mut self, image_tag: impl Into<MetaString>) -> Self {
148        self.image_tag = image_tag.into();
149        self
150    }
151
152    /// Sets the process tags hash.
153    pub fn with_process_tags_hash(mut self, process_tags_hash: u64) -> Self {
154        self.process_tags_hash = process_tags_hash;
155        self
156    }
157
158    /// Sets the process tags.
159    pub fn with_process_tags(mut self, process_tags: impl Into<MetaString>) -> Self {
160        self.process_tags = process_tags.into();
161        self
162    }
163
164    /// Returns the hostname.
165    pub fn hostname(&self) -> &str {
166        &self.hostname
167    }
168
169    /// Returns the environment.
170    pub fn env(&self) -> &str {
171        &self.env
172    }
173
174    /// Returns the version.
175    pub fn version(&self) -> &str {
176        &self.version
177    }
178
179    /// Returns the stats buckets.
180    pub fn stats(&self) -> &[ClientStatsBucket] {
181        &self.stats
182    }
183
184    /// Returns the tracer language.
185    pub fn lang(&self) -> &str {
186        &self.lang
187    }
188
189    /// Returns the tracer version.
190    pub fn tracer_version(&self) -> &str {
191        &self.tracer_version
192    }
193
194    /// Returns the runtime identifier.
195    pub fn runtime_id(&self) -> &str {
196        &self.runtime_id
197    }
198
199    /// Returns the message sequence number.
200    pub fn sequence(&self) -> u64 {
201        self.sequence
202    }
203
204    /// Returns the agent aggregation key.
205    pub fn agent_aggregation(&self) -> &str {
206        &self.agent_aggregation
207    }
208
209    /// Returns the main service name.
210    pub fn service(&self) -> &str {
211        &self.service
212    }
213
214    /// Returns the container identifier.
215    pub fn container_id(&self) -> &str {
216        &self.container_id
217    }
218
219    /// Returns the orchestrator tags.
220    pub fn tags(&self) -> &TagSet {
221        &self.tags
222    }
223
224    /// Returns the git commit SHA.
225    pub fn git_commit_sha(&self) -> &str {
226        &self.git_commit_sha
227    }
228
229    /// Returns the container image tag.
230    pub fn image_tag(&self) -> &str {
231        &self.image_tag
232    }
233
234    /// Returns the process tags hash.
235    pub fn process_tags_hash(&self) -> u64 {
236        self.process_tags_hash
237    }
238
239    /// Returns the process tags.
240    pub fn process_tags(&self) -> &str {
241        &self.process_tags
242    }
243
244    /// Adds a new client statistics bucket to this payload.
245    pub fn add_stats(&mut self, stats: ClientStatsBucket) {
246        self.stats.push(stats);
247    }
248
249    /// Consumes the statistics buckets and returns them.
250    ///
251    /// No statistics buckets will remain in `self`.
252    pub fn take_stats(&mut self) -> Vec<ClientStatsBucket> {
253        std::mem::take(&mut self.stats)
254    }
255}
256
257/// A time bucket containing aggregated stats.
258///
259/// Stats are grouped into fixed-duration buckets (typically 10 seconds).
260#[derive(Clone, Debug, PartialEq, Default)]
261pub struct ClientStatsBucket {
262    /// Bucket start timestamp in nanoseconds since Unix epoch.
263    start: u64,
264    /// Bucket duration in nanoseconds.
265    duration: u64,
266    /// Grouped stats within this bucket.
267    stats: Vec<ClientGroupedStats>,
268    /// Time shift applied by the agent.
269    agent_time_shift: i64,
270}
271
272impl ClientStatsBucket {
273    /// Creates a new `ClientStatsBucket` with the given time range and stats.
274    pub fn new(start: u64, duration: u64, stats: Vec<ClientGroupedStats>) -> Self {
275        Self {
276            start,
277            duration,
278            stats,
279            agent_time_shift: 0,
280        }
281    }
282
283    /// Sets the grouped stats.
284    pub fn with_stats(mut self, stats: Vec<ClientGroupedStats>) -> Self {
285        self.stats = stats;
286        self
287    }
288
289    /// Sets the agent time shift.
290    pub fn with_agent_time_shift(mut self, agent_time_shift: i64) -> Self {
291        self.agent_time_shift = agent_time_shift;
292        self
293    }
294
295    /// Returns the bucket start timestamp in nanoseconds.
296    pub fn start(&self) -> u64 {
297        self.start
298    }
299
300    /// Returns the bucket duration in nanoseconds.
301    pub fn duration(&self) -> u64 {
302        self.duration
303    }
304
305    /// Returns the grouped stats within this bucket.
306    pub fn stats(&self) -> &[ClientGroupedStats] {
307        &self.stats
308    }
309
310    /// Returns a mutable reference to the grouped stats within this bucket.
311    pub fn stats_mut(&mut self) -> &mut Vec<ClientGroupedStats> {
312        &mut self.stats
313    }
314
315    /// Returns the agent time shift.
316    pub fn agent_time_shift(&self) -> i64 {
317        self.agent_time_shift
318    }
319
320    /// Consumes the grouped statistics and returns them.
321    ///
322    /// No statistics groups will remain in `self`.
323    pub fn take_stats(&mut self) -> Vec<ClientGroupedStats> {
324        std::mem::take(&mut self.stats)
325    }
326}
327
328/// Aggregated stats for spans grouped by aggregation key.
329///
330/// Contains both the aggregation key fields (service, name, resource, etc.) and
331/// the aggregated values (hits, errors, duration, latency distributions).
332#[derive(Clone, Debug, PartialEq, Default)]
333pub struct ClientGroupedStats {
334    // Aggregation key fields
335    service: MetaString,
336    name: MetaString,
337    resource: MetaString,
338    http_status_code: u32,
339    span_type: MetaString,
340    db_type: MetaString,
341    span_kind: MetaString,
342    peer_tags: Vec<MetaString>,
343    is_trace_root: Option<bool>,
344    grpc_status_code: MetaString,
345    http_method: MetaString,
346    http_endpoint: MetaString,
347
348    // Aggregated values
349    hits: u64,
350    errors: u64,
351    duration: u64,
352    ok_summary: Vec<u8>,
353    error_summary: Vec<u8>,
354    synthetics: bool,
355    top_level_hits: u64,
356}
357
358impl ClientGroupedStats {
359    /// Creates a new `ClientGroupedStats` with the required aggregation key fields.
360    pub fn new(service: impl Into<MetaString>, name: impl Into<MetaString>, resource: impl Into<MetaString>) -> Self {
361        Self {
362            service: service.into(),
363            name: name.into(),
364            resource: resource.into(),
365            ..Self::default()
366        }
367    }
368
369    // Builder methods for aggregation key fields
370
371    /// Sets the HTTP status code.
372    pub fn with_http_status_code(mut self, http_status_code: u32) -> Self {
373        self.http_status_code = http_status_code;
374        self
375    }
376
377    /// Sets the span type.
378    pub fn with_span_type(mut self, span_type: impl Into<MetaString>) -> Self {
379        self.span_type = span_type.into();
380        self
381    }
382
383    /// Sets the database type.
384    pub fn with_db_type(mut self, db_type: impl Into<MetaString>) -> Self {
385        self.db_type = db_type.into();
386        self
387    }
388
389    /// Sets the span kind.
390    pub fn with_span_kind(mut self, span_kind: impl Into<MetaString>) -> Self {
391        self.span_kind = span_kind.into();
392        self
393    }
394
395    /// Sets the peer tags.
396    pub fn with_peer_tags(mut self, peer_tags: Vec<MetaString>) -> Self {
397        self.peer_tags = peer_tags;
398        self
399    }
400
401    /// Sets whether this is a trace root.
402    pub fn with_is_trace_root(mut self, is_trace_root: Option<bool>) -> Self {
403        self.is_trace_root = is_trace_root;
404        self
405    }
406
407    /// Sets the gRPC status code.
408    pub fn with_grpc_status_code(mut self, grpc_status_code: impl Into<MetaString>) -> Self {
409        self.grpc_status_code = grpc_status_code.into();
410        self
411    }
412
413    /// Sets the HTTP method.
414    pub fn with_http_method(mut self, http_method: impl Into<MetaString>) -> Self {
415        self.http_method = http_method.into();
416        self
417    }
418
419    /// Sets the HTTP endpoint.
420    pub fn with_http_endpoint(mut self, http_endpoint: impl Into<MetaString>) -> Self {
421        self.http_endpoint = http_endpoint.into();
422        self
423    }
424
425    // Builder methods for aggregated values
426
427    /// Sets the hit count.
428    pub fn with_hits(mut self, hits: u64) -> Self {
429        self.hits = hits;
430        self
431    }
432
433    /// Sets the error count.
434    pub fn with_errors(mut self, errors: u64) -> Self {
435        self.errors = errors;
436        self
437    }
438
439    /// Sets the total duration in nanoseconds.
440    pub fn with_duration(mut self, duration: u64) -> Self {
441        self.duration = duration;
442        self
443    }
444
445    /// Sets the DDSketch summary for successful spans.
446    pub fn with_ok_summary(mut self, ok_summary: Vec<u8>) -> Self {
447        self.ok_summary = ok_summary;
448        self
449    }
450
451    /// Sets the DDSketch summary for error spans.
452    pub fn with_error_summary(mut self, error_summary: Vec<u8>) -> Self {
453        self.error_summary = error_summary;
454        self
455    }
456
457    /// Sets the synthetics traffic flag.
458    pub fn with_synthetics(mut self, synthetics: bool) -> Self {
459        self.synthetics = synthetics;
460        self
461    }
462
463    /// Sets the top-level hit count.
464    pub fn with_top_level_hits(mut self, top_level_hits: u64) -> Self {
465        self.top_level_hits = top_level_hits;
466        self
467    }
468
469    // Getters for aggregation key fields
470
471    /// Returns the service name.
472    pub fn service(&self) -> &str {
473        &self.service
474    }
475
476    /// Returns the operation name.
477    pub fn name(&self) -> &str {
478        &self.name
479    }
480
481    /// Returns the resource name.
482    pub fn resource(&self) -> &str {
483        &self.resource
484    }
485
486    /// Returns the HTTP status code.
487    pub fn http_status_code(&self) -> u32 {
488        self.http_status_code
489    }
490
491    /// Returns the span type.
492    pub fn span_type(&self) -> &str {
493        &self.span_type
494    }
495
496    /// Returns the database type.
497    pub fn db_type(&self) -> &str {
498        &self.db_type
499    }
500
501    /// Returns the span kind.
502    pub fn span_kind(&self) -> &str {
503        &self.span_kind
504    }
505
506    /// Returns the peer tags.
507    pub fn peer_tags(&self) -> &[MetaString] {
508        &self.peer_tags
509    }
510
511    /// Returns whether this is a trace root.
512    pub fn is_trace_root(&self) -> Option<bool> {
513        self.is_trace_root
514    }
515
516    /// Returns the gRPC status code.
517    pub fn grpc_status_code(&self) -> &str {
518        &self.grpc_status_code
519    }
520
521    /// Returns the HTTP method.
522    pub fn http_method(&self) -> &str {
523        &self.http_method
524    }
525
526    /// Returns the HTTP endpoint.
527    pub fn http_endpoint(&self) -> &str {
528        &self.http_endpoint
529    }
530
531    // Getters for aggregated values
532
533    /// Returns the hit count.
534    pub fn hits(&self) -> u64 {
535        self.hits
536    }
537
538    /// Returns the error count.
539    pub fn errors(&self) -> u64 {
540        self.errors
541    }
542
543    /// Returns the total duration in nanoseconds.
544    pub fn duration(&self) -> u64 {
545        self.duration
546    }
547
548    /// Returns the DDSketch summary for successful spans.
549    pub fn ok_summary(&self) -> &[u8] {
550        &self.ok_summary
551    }
552
553    /// Returns the DDSketch summary for error spans.
554    pub fn error_summary(&self) -> &[u8] {
555        &self.error_summary
556    }
557
558    /// Returns the synthetics traffic flag.
559    pub fn synthetics(&self) -> bool {
560        self.synthetics
561    }
562
563    /// Returns the top-level hit count.
564    pub fn top_level_hits(&self) -> u64 {
565        self.top_level_hits
566    }
567}