Skip to main content

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::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<T: Counted, S: Counted> Counted for (T, S) {
45    fn quantities(&self) -> Quantities {
46        let mut quantities = self.0.quantities();
47        quantities.extend(self.1.quantities());
48        quantities
49    }
50}
51
52impl<L, R> Counted for Either<L, R>
53where
54    L: Counted,
55    R: Counted,
56{
57    fn quantities(&self) -> Quantities {
58        match self {
59            Either::Left(value) => value.quantities(),
60            Either::Right(value) => value.quantities(),
61        }
62    }
63}
64
65impl Counted for (DataCategory, usize) {
66    fn quantities(&self) -> Quantities {
67        smallvec::smallvec![*self]
68    }
69}
70
71impl<const N: usize> Counted for [(DataCategory, usize); N] {
72    fn quantities(&self) -> Quantities {
73        smallvec::SmallVec::from_slice(self)
74    }
75}
76
77impl Counted for Item {
78    fn quantities(&self) -> Quantities {
79        self.quantities()
80    }
81}
82
83impl Counted for Box<Envelope> {
84    fn quantities(&self) -> Quantities {
85        EnvelopeSummary::compute(self).quantities()
86    }
87}
88
89impl Counted for EnvelopeSummary {
90    fn quantities(&self) -> Quantities {
91        let mut quantities = Quantities::new();
92
93        if let Some(category) = self.event_category {
94            quantities.push((category, 1));
95            if let Some(category) = category.index_category() {
96                quantities.push((category, 1));
97            }
98        }
99
100        let data = [
101            (DataCategory::Attachment, self.attachment_bytes),
102            (DataCategory::AttachmentItem, self.attachment_count),
103            (DataCategory::Profile, self.profile_quantity.total),
104            (DataCategory::ProfileBackend, self.profile_quantity.backend),
105            (DataCategory::ProfileUi, self.profile_quantity.ui),
106            (DataCategory::ProfileIndexed, self.profile_quantity.total),
107            (DataCategory::Span, self.span_quantity),
108            (DataCategory::SpanIndexed, self.span_quantity),
109            (
110                DataCategory::Transaction,
111                self.secondary_transaction_quantity,
112            ),
113            (DataCategory::Span, self.secondary_span_quantity),
114            (DataCategory::Replay, self.replay_quantity),
115            (DataCategory::ProfileChunk, self.profile_chunk_quantity),
116            (DataCategory::ProfileChunkUi, self.profile_chunk_ui_quantity),
117            (DataCategory::UserReportV2, self.user_report_quantity),
118            (DataCategory::TraceMetric, self.trace_metric_quantity),
119            (
120                DataCategory::TraceMetricByte,
121                self.trace_metric_byte_quantity,
122            ),
123            (DataCategory::LogItem, self.log_item_quantity),
124            (DataCategory::LogByte, self.log_byte_quantity),
125            (DataCategory::Monitor, self.monitor_quantity),
126            (DataCategory::Session, self.session_quantity),
127        ];
128
129        for (category, quantity) in data {
130            if quantity > 0 {
131                quantities.push((category, quantity));
132            }
133        }
134
135        quantities
136    }
137}
138
139impl Counted for WithHeader<OurLog> {
140    fn quantities(&self) -> Quantities {
141        smallvec::smallvec![
142            (DataCategory::LogItem, 1),
143            (
144                DataCategory::LogByte,
145                processing::logs::get_calculated_byte_size(self)
146            )
147        ]
148    }
149}
150
151impl Counted for WithHeader<TraceMetric> {
152    fn quantities(&self) -> Quantities {
153        smallvec::smallvec![
154            (DataCategory::TraceMetric, 1),
155            (
156                DataCategory::TraceMetricByte,
157                processing::trace_metrics::get_calculated_byte_size(self)
158            )
159        ]
160    }
161}
162
163impl Counted for WithHeader<SpanV2> {
164    fn quantities(&self) -> Quantities {
165        smallvec::smallvec![(DataCategory::Span, 1), (DataCategory::SpanIndexed, 1)]
166    }
167}
168
169impl Counted for Annotated<Span> {
170    fn quantities(&self) -> Quantities {
171        smallvec::smallvec![(DataCategory::Span, 1), (DataCategory::SpanIndexed, 1)]
172    }
173}
174
175impl Counted for ExtractedMetrics {
176    fn quantities(&self) -> Quantities {
177        // We only consider project metrics, sampling project metrics should never carry outcomes,
178        // as they would be for a *different* project.
179        let SourceQuantities {
180            transactions,
181            spans,
182            buckets,
183        } = metrics::extract_quantities(&self.0);
184
185        [
186            (DataCategory::Transaction, transactions),
187            (DataCategory::Span, spans),
188            (DataCategory::MetricBucket, buckets),
189        ]
190        .into_iter()
191        .filter(|(_, q)| *q > 0)
192        .collect()
193    }
194}
195
196impl Counted for SessionUpdate {
197    fn quantities(&self) -> Quantities {
198        smallvec::smallvec![(DataCategory::Session, 1)]
199    }
200}
201
202impl Counted for SessionAggregates {
203    fn quantities(&self) -> Quantities {
204        smallvec::smallvec![(DataCategory::Session, self.aggregates.len())]
205    }
206}
207impl Counted for SessionAggregateItem {
208    fn quantities(&self) -> Quantities {
209        smallvec::smallvec![(DataCategory::Session, 1)]
210    }
211}
212
213#[cfg(feature = "processing")]
214impl Counted for sentry_protos::snuba::v1::Outcomes {
215    fn quantities(&self) -> Quantities {
216        self.category_count
217            .iter()
218            .inspect(|cc| {
219                debug_assert!(DataCategory::try_from(cc.data_category).is_ok());
220                debug_assert!(usize::try_from(cc.quantity).is_ok());
221            })
222            .filter_map(|cc| {
223                Some((
224                    DataCategory::try_from(cc.data_category).ok()?,
225                    usize::try_from(cc.quantity).ok()?,
226                ))
227            })
228            .collect()
229    }
230}
231
232#[cfg(feature = "processing")]
233impl Counted for sentry_protos::snuba::v1::TraceItem {
234    fn quantities(&self) -> Quantities {
235        self.outcomes.quantities()
236    }
237}
238
239impl<T> Counted for &T
240where
241    T: Counted,
242{
243    fn quantities(&self) -> Quantities {
244        (*self).quantities()
245    }
246}
247
248impl<T> Counted for Box<T>
249where
250    T: Counted,
251{
252    fn quantities(&self) -> Quantities {
253        self.as_ref().quantities()
254    }
255}
256
257impl<T: Counted> Counted for [T] {
258    fn quantities(&self) -> Quantities {
259        let mut quantities = BTreeMap::new();
260        for element in self {
261            for (category, size) in element.quantities() {
262                *quantities.entry(category).or_default() += size;
263            }
264        }
265        quantities.into_iter().collect()
266    }
267}
268
269impl<T: Counted> Counted for Vec<T> {
270    fn quantities(&self) -> Quantities {
271        self.as_slice().quantities()
272    }
273}
274
275impl<T: Counted, const N: usize> Counted for SmallVec<[T; N]> {
276    fn quantities(&self) -> Quantities {
277        self.as_slice().quantities()
278    }
279}