Skip to main content

relay_server/managed/
envelope.rs

1use 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/// Denotes the success of handling an envelope.
17#[derive(Clone, Copy, Debug)]
18enum Handling {
19    /// The envelope was handled successfully.
20    ///
21    /// This can be the case even if the envelpoe was dropped. For example, if a rate limit is in
22    /// effect or if the corresponding project is disabled.
23    Success,
24    /// Handling the envelope failed due to an error or bug.
25    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/// Tracks the lifetime of an [`Envelope`] in Relay.
54///
55/// The managed envelope accompanies envelopes through the processing pipeline in Relay and ensures
56/// that outcomes are recorded when the Envelope is dropped. They can be dropped in one of three
57/// ways:
58///
59///  - By calling [`accept`](Self::accept). Responsibility of the envelope has been transferred to
60///    another service, and no further outcomes need to be recorded.
61///  - By calling [`reject`](Self::reject). The entire envelope was dropped, and the outcome
62///    specifies the reason.
63///  - By dropping the managed envelope. This indicates an issue or a bug and raises the
64///    `"internal"` outcome. There should be additional error handling to report an error to Sentry.
65///
66/// The managed envelope also holds a processing queue permit which is used for backpressure
67/// management. It is automatically reclaimed when the context is dropped along with the envelope.
68#[derive(Debug)]
69pub struct ManagedEnvelope {
70    envelope: Box<Envelope>,
71    context: EnvelopeContext,
72    outcome_aggregator: Addr<TrackOutcome>,
73}
74
75impl ManagedEnvelope {
76    /// Computes a managed envelope from the given envelope and binds it to the processing queue.
77    ///
78    /// To provide additional scoping, use [`ManagedEnvelope::scope`].
79    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    /// An untracked instance which does not emit outcomes, useful for testing.
97    #[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    /// Returns a reference to the contained [`Envelope`].
105    pub fn envelope(&self) -> &Envelope {
106        self.envelope.as_ref()
107    }
108
109    /// Returns a mutable reference to the contained [`Envelope`].
110    pub fn envelope_mut(&mut self) -> &mut Envelope {
111        self.envelope.as_mut()
112    }
113
114    /// Consumes itself returning the managed envelope.
115    pub fn into_envelope(mut self) -> Box<Envelope> {
116        self.context.done = true;
117        self.take_envelope()
118    }
119
120    /// Take the envelope out of the context and replace it with a dummy.
121    ///
122    /// Note that after taking out the envelope, the envelope summary is incorrect.
123    pub(crate) fn take_envelope(&mut self) -> Box<Envelope> {
124        Box::new(self.envelope.take_items())
125    }
126
127    /// Update the context with envelope information.
128    ///
129    /// This updates the item summary as well as the event id.
130    pub fn update(&mut self) -> &mut Self {
131        self.context.summary = EnvelopeSummary::compute(self.envelope());
132        self
133    }
134
135    /// Re-scopes this context to the given scoping.
136    pub fn scope(&mut self, scoping: Scoping) -> &mut Self {
137        self.context.scoping = scoping;
138        self
139    }
140
141    /// Records an outcome scoped to this envelope's context.
142    ///
143    /// This managed envelope should be updated using [`update`](Self::update) soon after this
144    /// operation to ensure that subsequent outcomes are consistent.
145    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    /// Accepts the envelope and drops the context.
158    ///
159    /// This should be called if the envelope has been accepted by the upstream, which means that
160    /// the responsibility for logging outcomes has been moved. This function will not log any
161    /// outcomes.
162    pub fn accept(mut self) {
163        if !self.context.done {
164            self.finish(RelayCounters::EnvelopeAccepted, Handling::Success);
165        }
166    }
167
168    /// Records rejection outcomes for all items stored in this context.
169    ///
170    /// This does not send outcomes for empty envelopes or request-only contexts.
171    pub fn reject(&mut self, outcome: Outcome) {
172        if self.context.done {
173            return;
174        }
175
176        // Errors are only logged for what we consider failed request handling. In other cases, we
177        // "expect" errors and log them as debug level.
178        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    /// Returns scoping stored in this context.
211    pub fn scoping(&self) -> Scoping {
212        self.context.scoping
213    }
214
215    /// Returns the partition key, which is set on upstream requests in the `X-Sentry-Relay-Shard` header.
216    pub fn partition_key(&self) -> Option<u32> {
217        self.context.partition_key
218    }
219
220    /// Sets a new [`Self::partition_key`].
221    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    /// Returns the contained original request meta.
227    pub fn meta(&self) -> &RequestMeta {
228        self.envelope().meta()
229    }
230
231    /// Returns estimated size of this envelope.
232    ///
233    /// This is just an estimated size, which in reality can be somewhat bigger, depending on the
234    /// list of additional attributes allocated on all of the inner types.
235    ///
236    /// NOTE: Current implementation counts in only the size of the items payload and stack
237    /// allocated parts of [`Envelope`] and [`ManagedEnvelope`]. All the heap allocated fields
238    /// within early mentioned types are skipped.
239    pub fn estimated_size(&self) -> usize {
240        // Always round it up to next 1KB.
241        (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    /// Returns the time at which the envelope was received at this Relay.
248    ///
249    /// This is the date time equivalent to [`start_time`](Self::received_at).
250    pub fn received_at(&self) -> DateTime<Utc> {
251        self.envelope.received_at()
252    }
253
254    /// Returns the time elapsed in seconds since the envelope was received by this Relay.
255    ///
256    /// In case the elapsed time is negative, it is assumed that no time elapsed.
257    pub fn age(&self) -> Duration {
258        self.envelope.age()
259    }
260
261    /// Escape hatch for the [`super::Managed`] type, to make it possible to construct
262    /// from a managed envelope.
263    pub(super) fn outcome_aggregator(&self) -> &Addr<TrackOutcome> {
264        &self.outcome_aggregator
265    }
266
267    /// Resets inner state to ensure there's no more logging.
268    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}