relay_server/managed/
counted.rs

1use std::collections::BTreeMap;
2
3use itertools::Either;
4use relay_event_schema::protocol::{
5    OurLog, SessionAggregateItem, SessionAggregates, SessionUpdate, Span, SpanV2, TraceMetric,
6};
7use relay_protocol::Annotated;
8use relay_quotas::DataCategory;
9use smallvec::SmallVec;
10
11use crate::envelope::{Item, SourceQuantities, WithHeader};
12use crate::metrics_extraction::transactions::ExtractedMetrics;
13use crate::utils::EnvelopeSummary;
14use crate::{Envelope, metrics, processing};
15
16/// A list of data categories and amounts.
17pub type Quantities = SmallVec<[(DataCategory, usize); 2]>;
18
19/// A counted item.
20///
21/// An item may represent multiple categories with different counts at once.
22pub trait Counted {
23    /// Returns the contained item quantities.
24    ///
25    /// Implementation are expected to be pure.
26    fn quantities(&self) -> Quantities;
27}
28
29impl Counted for () {
30    fn quantities(&self) -> Quantities {
31        Quantities::new()
32    }
33}
34
35impl<T: Counted> Counted for Option<T> {
36    fn quantities(&self) -> Quantities {
37        match self {
38            Some(inner) => inner.quantities(),
39            None => Quantities::new(),
40        }
41    }
42}
43
44impl<L, R> Counted for Either<L, R>
45where
46    L: Counted,
47    R: Counted,
48{
49    fn quantities(&self) -> Quantities {
50        match self {
51            Either::Left(value) => value.quantities(),
52            Either::Right(value) => value.quantities(),
53        }
54    }
55}
56
57impl Counted for (DataCategory, usize) {
58    fn quantities(&self) -> Quantities {
59        smallvec::smallvec![*self]
60    }
61}
62
63impl<const N: usize> Counted for [(DataCategory, usize); N] {
64    fn quantities(&self) -> Quantities {
65        smallvec::SmallVec::from_slice(self)
66    }
67}
68
69impl Counted for Item {
70    fn quantities(&self) -> Quantities {
71        self.quantities()
72    }
73}
74
75impl Counted for Box<Envelope> {
76    fn quantities(&self) -> Quantities {
77        EnvelopeSummary::compute(self).quantities()
78    }
79}
80
81impl Counted for EnvelopeSummary {
82    fn quantities(&self) -> Quantities {
83        let mut quantities = Quantities::new();
84
85        if let Some(category) = self.event_category {
86            quantities.push((category, 1));
87            if let Some(category) = category.index_category() {
88                quantities.push((category, 1));
89            }
90        }
91
92        let data = [
93            (DataCategory::Attachment, self.attachment_quantities.bytes()),
94            (
95                DataCategory::AttachmentItem,
96                self.attachment_quantities.count(),
97            ),
98            (DataCategory::Profile, self.profile_quantity.total),
99            (DataCategory::ProfileBackend, self.profile_quantity.backend),
100            (DataCategory::ProfileUi, self.profile_quantity.ui),
101            (DataCategory::ProfileIndexed, self.profile_quantity.total),
102            (DataCategory::Span, self.span_quantity),
103            (DataCategory::SpanIndexed, self.span_quantity),
104            (
105                DataCategory::Transaction,
106                self.secondary_transaction_quantity,
107            ),
108            (DataCategory::Span, self.secondary_span_quantity),
109            (DataCategory::Replay, self.replay_quantity),
110            (DataCategory::ProfileChunk, self.profile_chunk_quantity),
111            (DataCategory::ProfileChunkUi, self.profile_chunk_ui_quantity),
112            (DataCategory::UserReportV2, self.user_report_quantity),
113            (DataCategory::TraceMetric, self.trace_metric_quantity),
114            (DataCategory::LogItem, self.log_item_quantity),
115            (DataCategory::LogByte, self.log_byte_quantity),
116            (DataCategory::Monitor, self.monitor_quantity),
117            (DataCategory::Session, self.session_quantity),
118        ];
119
120        for (category, quantity) in data {
121            if quantity > 0 {
122                quantities.push((category, quantity));
123            }
124        }
125
126        quantities
127    }
128}
129
130impl Counted for WithHeader<OurLog> {
131    fn quantities(&self) -> Quantities {
132        smallvec::smallvec![
133            (DataCategory::LogItem, 1),
134            (
135                DataCategory::LogByte,
136                processing::logs::get_calculated_byte_size(self)
137            )
138        ]
139    }
140}
141
142impl Counted for WithHeader<TraceMetric> {
143    fn quantities(&self) -> Quantities {
144        smallvec::smallvec![(DataCategory::TraceMetric, 1)]
145    }
146}
147
148impl Counted for WithHeader<SpanV2> {
149    fn quantities(&self) -> Quantities {
150        smallvec::smallvec![(DataCategory::Span, 1), (DataCategory::SpanIndexed, 1)]
151    }
152}
153
154impl Counted for Annotated<Span> {
155    fn quantities(&self) -> Quantities {
156        smallvec::smallvec![(DataCategory::Span, 1), (DataCategory::SpanIndexed, 1)]
157    }
158}
159
160impl Counted for ExtractedMetrics {
161    fn quantities(&self) -> Quantities {
162        // We only consider project metrics, sampling project metrics should never carry outcomes,
163        // as they would be for a *different* project.
164        let SourceQuantities {
165            transactions,
166            spans,
167            buckets,
168        } = metrics::extract_quantities(&self.project_metrics);
169
170        [
171            (DataCategory::Transaction, transactions),
172            (DataCategory::Span, spans),
173            (DataCategory::MetricBucket, buckets),
174        ]
175        .into_iter()
176        .filter(|(_, q)| *q > 0)
177        .collect()
178    }
179}
180
181impl Counted for SessionUpdate {
182    fn quantities(&self) -> Quantities {
183        smallvec::smallvec![(DataCategory::Session, 1)]
184    }
185}
186
187impl Counted for SessionAggregates {
188    fn quantities(&self) -> Quantities {
189        smallvec::smallvec![(DataCategory::Session, self.aggregates.len())]
190    }
191}
192impl Counted for SessionAggregateItem {
193    fn quantities(&self) -> Quantities {
194        smallvec::smallvec![(DataCategory::Session, 1)]
195    }
196}
197
198#[cfg(feature = "processing")]
199impl Counted for sentry_protos::snuba::v1::Outcomes {
200    fn quantities(&self) -> Quantities {
201        self.category_count
202            .iter()
203            .inspect(|cc| {
204                debug_assert!(DataCategory::try_from(cc.data_category).is_ok());
205                debug_assert!(usize::try_from(cc.quantity).is_ok());
206            })
207            .filter_map(|cc| {
208                Some((
209                    DataCategory::try_from(cc.data_category).ok()?,
210                    usize::try_from(cc.quantity).ok()?,
211                ))
212            })
213            .collect()
214    }
215}
216
217#[cfg(feature = "processing")]
218impl Counted for sentry_protos::snuba::v1::TraceItem {
219    fn quantities(&self) -> Quantities {
220        self.outcomes.quantities()
221    }
222}
223
224impl<T> Counted for &T
225where
226    T: Counted,
227{
228    fn quantities(&self) -> Quantities {
229        (*self).quantities()
230    }
231}
232
233impl<T> Counted for Box<T>
234where
235    T: Counted,
236{
237    fn quantities(&self) -> Quantities {
238        self.as_ref().quantities()
239    }
240}
241
242impl<T: Counted> Counted for [T] {
243    fn quantities(&self) -> Quantities {
244        let mut quantities = BTreeMap::new();
245        for element in self {
246            for (category, size) in element.quantities() {
247                *quantities.entry(category).or_default() += size;
248            }
249        }
250        quantities.into_iter().collect()
251    }
252}
253
254impl<T: Counted> Counted for Vec<T> {
255    fn quantities(&self) -> Quantities {
256        self.as_slice().quantities()
257    }
258}
259
260impl<T: Counted, const N: usize> Counted for SmallVec<[T; N]> {
261    fn quantities(&self) -> Quantities {
262        self.as_slice().quantities()
263    }
264}