relay_server/managed/
envelope.rs1use std::fmt::Debug;
2use std::mem::size_of;
3use std::time::Duration;
4
5use chrono::{DateTime, Utc};
6use relay_quotas::{DataCategory, Scoping};
7use relay_system::Addr;
8
9use crate::envelope::Envelope;
10use crate::extractors::RequestMeta;
11use crate::managed::Counted as _;
12use crate::services::outcome::{DiscardReason, Outcome, TrackOutcome};
13use crate::statsd::{RelayCounters, RelayTimers};
14use crate::utils::EnvelopeSummary;
15
16#[derive(Clone, Copy, Debug)]
18enum Handling {
19 Success,
24 Failure,
26}
27
28impl Handling {
29 fn from_outcome(outcome: &Outcome) -> Self {
30 if outcome.is_unexpected() {
31 Self::Failure
32 } else {
33 Self::Success
34 }
35 }
36
37 fn as_str(&self) -> &str {
38 match self {
39 Handling::Success => "success",
40 Handling::Failure => "failure",
41 }
42 }
43}
44
45#[derive(Debug)]
46struct EnvelopeContext {
47 summary: EnvelopeSummary,
48 scoping: Scoping,
49 partition_key: Option<u32>,
50 done: bool,
51}
52
53#[derive(Debug)]
69pub struct ManagedEnvelope {
70 envelope: Box<Envelope>,
71 context: EnvelopeContext,
72 outcome_aggregator: Addr<TrackOutcome>,
73}
74
75impl ManagedEnvelope {
76 pub fn new(envelope: Box<Envelope>, outcome_aggregator: Addr<TrackOutcome>) -> Self {
80 let meta = &envelope.meta();
81 let summary = EnvelopeSummary::compute(envelope.as_ref());
82 let scoping = meta.get_partial_scoping().into_scoping();
83
84 Self {
85 envelope,
86 context: EnvelopeContext {
87 summary,
88 scoping,
89 partition_key: None,
90 done: false,
91 },
92 outcome_aggregator,
93 }
94 }
95
96 #[cfg(test)]
98 pub fn untracked(envelope: Box<Envelope>, outcome_aggregator: Addr<TrackOutcome>) -> Self {
99 let mut envelope = Self::new(envelope, outcome_aggregator);
100 envelope.context.done = true;
101 envelope
102 }
103
104 pub fn envelope(&self) -> &Envelope {
106 self.envelope.as_ref()
107 }
108
109 pub fn envelope_mut(&mut self) -> &mut Envelope {
111 self.envelope.as_mut()
112 }
113
114 pub fn into_envelope(mut self) -> Box<Envelope> {
116 self.context.done = true;
117 self.take_envelope()
118 }
119
120 pub(crate) fn take_envelope(&mut self) -> Box<Envelope> {
124 Box::new(self.envelope.take_items())
125 }
126
127 pub fn update(&mut self) -> &mut Self {
131 self.context.summary = EnvelopeSummary::compute(self.envelope());
132 self
133 }
134
135 pub fn scope(&mut self, scoping: Scoping) -> &mut Self {
137 self.context.scoping = scoping;
138 self
139 }
140
141 pub fn track_outcome(&self, outcome: Outcome, category: DataCategory, quantity: usize) {
146 self.outcome_aggregator.send(TrackOutcome {
147 timestamp: self.received_at(),
148 scoping: self.context.scoping,
149 outcome,
150 event_id: self.envelope.event_id(),
151 remote_addr: self.meta().remote_addr(),
152 category,
153 quantity: quantity as u64,
154 });
155 }
156
157 pub fn accept(mut self) {
163 if !self.context.done {
164 self.finish(RelayCounters::EnvelopeAccepted, Handling::Success);
165 }
166 }
167
168 pub fn reject(&mut self, outcome: Outcome) {
172 if self.context.done {
173 return;
174 }
175
176 let handling = Handling::from_outcome(&outcome);
179 match handling {
180 Handling::Success => relay_log::debug!("dropped envelope: {outcome}"),
181 Handling::Failure => {
182 let summary = &self.context.summary;
183
184 relay_log::error!(
185 tags.project_key = self.scoping().project_key.to_string(),
186 tags.has_attachments = summary.attachment_bytes > 0,
187 tags.has_sessions = summary.session_quantity > 0,
188 tags.has_profiles = summary.profile_quantity.total > 0,
189 tags.has_transactions = summary.secondary_transaction_quantity > 0,
190 tags.has_span_metrics = summary.secondary_span_quantity > 0,
191 tags.has_replays = summary.replay_quantity > 0,
192 tags.has_user_reports = summary.user_report_quantity > 0,
193 tags.has_trace_metrics = summary.trace_metric_quantity > 0,
194 tags.has_checkins = summary.monitor_quantity > 0,
195 tags.event_category = ?summary.event_category,
196 cached_summary = ?summary,
197 recomputed_summary = ?EnvelopeSummary::compute(self.envelope()),
198 "dropped envelope: {outcome}"
199 );
200 }
201 }
202
203 for (category, quantity) in self.context.summary.quantities() {
204 self.track_outcome(outcome.clone(), category, quantity);
205 }
206
207 self.finish(RelayCounters::EnvelopeRejected, handling);
208 }
209
210 pub fn scoping(&self) -> Scoping {
212 self.context.scoping
213 }
214
215 pub fn partition_key(&self) -> Option<u32> {
217 self.context.partition_key
218 }
219
220 pub fn set_partition_key(&mut self, partition_key: Option<u32>) -> &mut Self {
222 self.context.partition_key = partition_key;
223 self
224 }
225
226 pub fn meta(&self) -> &RequestMeta {
228 self.envelope().meta()
229 }
230
231 pub fn estimated_size(&self) -> usize {
240 (f64::ceil(
242 (self.context.summary.payload_size + size_of::<Self>() + size_of::<Envelope>()) as f64
243 / 1000.,
244 ) * 1000.) as usize
245 }
246
247 pub fn received_at(&self) -> DateTime<Utc> {
251 self.envelope.received_at()
252 }
253
254 pub fn age(&self) -> Duration {
258 self.envelope.age()
259 }
260
261 pub(super) fn outcome_aggregator(&self) -> &Addr<TrackOutcome> {
264 &self.outcome_aggregator
265 }
266
267 fn finish(&mut self, counter: RelayCounters, handling: Handling) {
269 relay_statsd::metric!(counter(counter) += 1, handling = handling.as_str());
270 relay_statsd::metric!(timer(RelayTimers::EnvelopeTotalTime) = self.age());
271
272 self.context.done = true;
273 }
274}
275
276impl Drop for ManagedEnvelope {
277 fn drop(&mut self) {
278 self.reject(Outcome::Invalid(DiscardReason::Internal));
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use bytes::Bytes;
286
287 #[test]
288 fn span_metrics_are_reported() {
289 let bytes =
290 Bytes::from(r#"{"dsn":"https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"}"#);
291 let envelope = Envelope::parse_bytes(bytes).unwrap();
292
293 let (outcome_aggregator, mut rx) = Addr::custom();
294 let mut env = ManagedEnvelope::new(envelope, outcome_aggregator);
295 env.context.summary.span_quantity = 123;
296 env.context.summary.secondary_span_quantity = 456;
297
298 env.reject(Outcome::Abuse);
299
300 rx.close();
301
302 let outcome = rx.blocking_recv().unwrap();
303 assert_eq!(outcome.category, DataCategory::Span);
304 assert_eq!(outcome.quantity, 123);
305 assert_eq!(outcome.outcome, Outcome::Abuse);
306
307 let outcome = rx.blocking_recv().unwrap();
308 assert_eq!(outcome.category, DataCategory::SpanIndexed);
309 assert_eq!(outcome.quantity, 123);
310 assert_eq!(outcome.outcome, Outcome::Abuse);
311
312 let outcome = rx.blocking_recv().unwrap();
313 assert_eq!(outcome.category, DataCategory::Span);
314 assert_eq!(outcome.quantity, 456);
315 assert_eq!(outcome.outcome, Outcome::Abuse);
316
317 assert!(rx.blocking_recv().is_none());
318 }
319}