Skip to main content

relay_server/managed/
managed.rs

1#[cfg(debug_assertions)]
2use std::collections::BTreeMap;
3use std::convert::Infallible;
4use std::fmt;
5use std::iter::FusedIterator;
6use std::mem::ManuallyDrop;
7use std::net::IpAddr;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, Ordering};
10
11use chrono::{DateTime, Utc};
12use itertools::Either;
13use relay_quotas::{DataCategory, Scoping};
14use relay_system::Addr;
15use smallvec::SmallVec;
16
17use crate::Envelope;
18use crate::endpoints::common::BadStoreRequest;
19use crate::extractors::RequestMeta;
20use crate::managed::{Counted, ManagedEnvelope, Quantities};
21use crate::services::outcome::{DiscardReason, Outcome, TrackOutcome};
22use crate::services::processor::ProcessingError;
23
24#[cfg(debug_assertions)]
25mod debug;
26#[cfg(test)]
27mod test;
28
29#[cfg(test)]
30pub use self::test::*;
31
32/// An error which can be extracted into an outcome.
33pub trait OutcomeError {
34    /// Produced error, without attached outcome.
35    type Error;
36
37    /// Consumes the error and returns an outcome and [`Self::Error`].
38    ///
39    /// Returning a `None` outcome should discard the item(s) silently.
40    fn consume(self) -> (Option<Outcome>, Self::Error);
41}
42
43impl OutcomeError for Outcome {
44    type Error = ();
45
46    fn consume(self) -> (Option<Outcome>, Self::Error) {
47        (self, ()).consume()
48    }
49}
50
51impl OutcomeError for Option<Outcome> {
52    type Error = ();
53
54    fn consume(self) -> (Option<Outcome>, Self::Error) {
55        (self, ()).consume()
56    }
57}
58
59impl<E> OutcomeError for (Outcome, E) {
60    type Error = E;
61
62    fn consume(self) -> (Option<Outcome>, Self::Error) {
63        (Some(self.0), self.1)
64    }
65}
66
67impl<E> OutcomeError for (Option<Outcome>, E) {
68    type Error = E;
69
70    fn consume(self) -> (Option<Outcome>, Self::Error) {
71        self
72    }
73}
74
75impl OutcomeError for ProcessingError {
76    type Error = Self;
77
78    fn consume(self) -> (Option<Outcome>, Self::Error) {
79        (self.to_outcome(), self)
80    }
81}
82
83impl OutcomeError for Infallible {
84    type Error = Self;
85
86    fn consume(self) -> (Option<Outcome>, Self::Error) {
87        match self {}
88    }
89}
90
91impl OutcomeError for BadStoreRequest {
92    type Error = Self;
93
94    fn consume(self) -> (Option<Outcome>, Self) {
95        (self.to_outcome(), self)
96    }
97}
98
99/// A wrapper type which ensures outcomes have been emitted for an error.
100///
101/// [`Managed`] wraps an error in [`Rejected`] once outcomes for have been emitted for the managed
102/// item.
103#[derive(Debug, Clone, Copy)]
104#[must_use = "a rejection must be propagated"]
105pub struct Rejected<T>(T);
106
107impl<T> Rejected<T> {
108    /// Extracts the underlying error.
109    pub fn into_inner(self) -> T {
110        self.0
111    }
112
113    /// Maps the rejected error to a different error.
114    pub fn map<F, S>(self, f: F) -> Rejected<S>
115    where
116        F: FnOnce(T) -> S,
117    {
118        Rejected(f(self.0))
119    }
120}
121
122impl<T> std::error::Error for Rejected<T>
123where
124    T: std::error::Error,
125{
126    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
127        self.0.source()
128    }
129}
130
131impl<T> std::fmt::Display for Rejected<T>
132where
133    T: std::fmt::Display,
134{
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        self.0.fmt(f)
137    }
138}
139
140impl<T> axum::response::IntoResponse for Rejected<T>
141where
142    T: axum::response::IntoResponse,
143{
144    fn into_response(self) -> axum::response::Response {
145        self.0.into_response()
146    }
147}
148
149/// The [`Managed`] wrapper ensures outcomes are correctly emitted for the contained item.
150pub struct Managed<T: Counted> {
151    value: T,
152    meta: Arc<Meta>,
153    done: AtomicBool,
154}
155
156impl Managed<Box<Envelope>> {
157    /// Creates a managed instance from an unmanaged envelope.
158    pub fn from_envelope(envelope: Box<Envelope>, outcome_aggregator: Addr<TrackOutcome>) -> Self {
159        let meta = Arc::new(Meta {
160            outcome_aggregator,
161            received_at: envelope.received_at(),
162            scoping: envelope.meta().get_partial_scoping().into_scoping(),
163            remote_addr: envelope.meta().remote_addr(),
164        });
165
166        Self::from_parts(envelope, meta)
167    }
168}
169
170/// Helper trait to abstract over `Vec` and `SmallVec` in [`Managed::retain`].
171pub trait RetainMut<I> {
172    /// Retains only the elements specified by the predicate.
173    fn retain_mut(&mut self, f: impl FnMut(&mut I) -> bool);
174}
175
176impl<I> RetainMut<I> for Vec<I> {
177    fn retain_mut(&mut self, f: impl FnMut(&mut I) -> bool) {
178        Vec::retain_mut(self, f)
179    }
180}
181impl<I, const N: usize> RetainMut<I> for SmallVec<[I; N]> {
182    fn retain_mut(&mut self, f: impl FnMut(&mut I) -> bool) {
183        SmallVec::retain_mut(self, f)
184    }
185}
186
187impl<T: Counted> Managed<T> {
188    /// Creates new [`Managed`] instance with the provided `value` and metadata from a [`ManagedEnvelope`].
189    ///
190    /// The [`Managed`] instance, inherits all metadata from the passed [`ManagedEnvelope`],
191    /// like received time or scoping.
192    pub fn with_meta_from_managed_envelope(envelope: &ManagedEnvelope, value: T) -> Self {
193        Self::from_parts(
194            value,
195            Arc::new(Meta {
196                outcome_aggregator: envelope.outcome_aggregator().clone(),
197                received_at: envelope.received_at(),
198                scoping: envelope.scoping(),
199                remote_addr: envelope.meta().remote_addr(),
200            }),
201        )
202    }
203
204    /// Creates new [`Managed`] instance with the provided `value` and metadata from `request_meta`.
205    pub fn with_meta_from_request_meta(
206        request_meta: &RequestMeta,
207        outcome_aggregator: &Addr<TrackOutcome>,
208        value: T,
209    ) -> Self {
210        Self::from_parts(
211            value,
212            Arc::new(Meta {
213                outcome_aggregator: outcome_aggregator.clone(),
214                received_at: request_meta.received_at(),
215                scoping: request_meta.get_partial_scoping().into_scoping(),
216                remote_addr: request_meta.remote_addr(),
217            }),
218        )
219    }
220
221    /// Creates another [`Managed`] instance, with a new value but shared metadata.
222    pub fn wrap<S>(&self, other: S) -> Managed<S>
223    where
224        S: Counted,
225    {
226        Managed::from_parts(other, Arc::clone(&self.meta))
227    }
228
229    /// Boxes the contained value.
230    pub fn boxed(self) -> Managed<Box<T>> {
231        self.map(|value, _| Box::new(value))
232    }
233
234    /// Original received timestamp.
235    pub fn received_at(&self) -> DateTime<Utc> {
236        self.meta.received_at
237    }
238
239    /// Scoping information stored in this context.
240    pub fn scoping(&self) -> Scoping {
241        self.meta.scoping
242    }
243
244    /// Optional remote addr from where the data was received.
245    pub fn remote_addr(&self) -> Option<IpAddr> {
246        self.meta.remote_addr
247    }
248
249    /// Updates the scoping stored in this context.
250    ///
251    /// Special care has to be taken when items contained in the managed instance also store a
252    /// scoping. Such a scoping will **not** be updated.
253    ///
254    /// Conversions between `Managed<Box<Envelope>>` and `ManagedEnvelope` transfer the scoping
255    /// correctly.
256    ///
257    /// See also: [`ManagedEnvelope::scope`].
258    pub fn scope(&mut self, scoping: Scoping) {
259        let meta = Arc::make_mut(&mut self.meta);
260        meta.scoping = scoping;
261    }
262
263    /// Merge [`Self`] with another [`Managed`] instance using a mapping function.
264    ///
265    /// The caller's closure is expected to merge `other`'s inner value into `self`'s inner value.
266    /// The outcome records of `self` are automatically offset by the records of `other`.
267    pub fn merge_with<S, F>(&mut self, other: Managed<S>, f: F)
268    where
269        S: Counted,
270        F: FnOnce(&mut T, S, &mut RecordKeeper),
271    {
272        self.modify(|s, records| {
273            records.add(other.as_ref());
274            other.accept(|o| f(s, o, records));
275        })
276    }
277    /// Zips two managed instances into one managed tuple.
278    ///
279    /// The returned instance uses the metadata from `first`. `second` is accepted, transferring
280    /// outcome responsibility to the merged instance.
281    pub fn zip<S>(first: Self, second: Managed<S>) -> Managed<(T, S)>
282    where
283        S: Counted,
284    {
285        debug_assert_eq!(
286            first.scoping(),
287            second.scoping(),
288            "cannot zip Managed values with different metadata"
289        );
290        first.map(|first, records| {
291            records.add(second.as_ref());
292            let second = second.accept(|second| second);
293            (first, second)
294        })
295    }
296
297    /// Splits [`Self`] into two other [`Managed`] items.
298    ///
299    /// The two resulting managed instances together are expected to have the same outcomes as the original instance..
300    /// Since splitting may introduce a new type of item, which some of the original
301    /// quantities are transferred to, there may be new additional data categories created.
302    pub fn split_once<F, S, U>(self, f: F) -> (Managed<S>, Managed<U>)
303    where
304        F: FnOnce(T, &mut RecordKeeper) -> (S, U),
305        S: Counted,
306        U: Counted,
307    {
308        debug_assert!(!self.is_done());
309
310        let (value, meta) = self.destructure();
311        let quantities = value.quantities();
312
313        let mut records = RecordKeeper::new(&meta, quantities);
314
315        let (a, b) = f(value, &mut records);
316
317        let mut quantities = a.quantities();
318        quantities.extend(b.quantities());
319        records.success(quantities);
320
321        (
322            Managed::from_parts(a, Arc::clone(&meta)),
323            Managed::from_parts(b, meta),
324        )
325    }
326
327    /// Splits [`Self`] into a variable amount if individual items.
328    ///
329    /// Useful when the current instance contains multiple items of the same type
330    /// and must be split into individually managed items.
331    pub fn split<F, I, S>(self, f: F) -> Split<I::IntoIter, I::Item>
332    where
333        F: FnOnce(T) -> I,
334        I: IntoIterator<Item = S>,
335        S: Counted,
336    {
337        self.split_with_context(|value| (f(value), ())).0
338    }
339
340    /// Splits [`Self`] into a variable amount if individual items.
341    ///
342    /// Like [`Self::split`] but also allows returning an untracked context,
343    /// a way of returning additional data when deconstructing the original item.
344    pub fn split_with_context<F, I, S, C>(self, f: F) -> (Split<I::IntoIter, I::Item>, C)
345    where
346        F: FnOnce(T) -> (I, C),
347        I: IntoIterator<Item = S>,
348        S: Counted,
349    {
350        debug_assert!(!self.is_done());
351
352        let (value, meta) = self.destructure();
353        #[cfg(debug_assertions)]
354        let quantities = value.quantities();
355
356        let (items, context) = f(value);
357
358        (
359            Split {
360                #[cfg(debug_assertions)]
361                quantities,
362                items: items.into_iter(),
363                meta,
364                exhausted: false,
365            },
366            context,
367        )
368    }
369
370    /// Filters individual items and emits outcomes for them if they are removed.
371    ///
372    /// This is particularly useful when the managed instance is a container of individual items,
373    /// which need to be processed or filtered on a case by case basis.
374    ///
375    /// # Examples:
376    ///
377    /// ```
378    /// # use relay_server::managed::{Counted, Managed, Quantities};
379    /// # #[derive(Copy, Clone)]
380    /// # struct Context<'a>(&'a u32);
381    /// # struct Item;
382    /// struct Items {
383    ///     items: Vec<Item>,
384    /// }
385    /// # impl Counted for Items {
386    /// #   fn quantities(&self) -> Quantities {
387    /// #       todo!()
388    /// #   }
389    /// # }
390    /// # impl Counted for Item {
391    /// #   fn quantities(&self) -> Quantities {
392    /// #       todo!()
393    /// #   }
394    /// # }
395    /// # type Error = std::convert::Infallible;
396    ///
397    /// fn process_items(items: &mut Managed<Items>, ctx: Context<'_>) {
398    ///     items.retain(|items| &mut items.items, |item, _| process(item, ctx));
399    /// }
400    ///
401    /// fn process(item: &mut Item, ctx: Context<'_>) -> Result<(), Error> {
402    ///     todo!()
403    /// }
404    /// ```
405    pub fn retain<S, I, U, E, V>(&mut self, select: S, mut retain: U)
406    where
407        S: FnOnce(&mut T) -> &mut V,
408        I: Counted,
409        U: FnMut(&mut I, &mut RecordKeeper<'_>) -> Result<(), E>,
410        E: OutcomeError,
411        V: RetainMut<I>,
412    {
413        self.retain_with_context(
414            |inner| (select(inner), &()),
415            |item, _, records| retain(item, records),
416        );
417    }
418
419    /// Filters individual items and emits outcomes for them if they are removed.
420    ///
421    /// Like [`Self::retain`], but it allows for an additional context extracted from the managed
422    /// object passed to the retain function.
423    ///
424    /// # Examples:
425    ///
426    /// ```
427    /// # use relay_server::managed::{Counted, Managed, Quantities};
428    /// # #[derive(Copy, Clone)]
429    /// # struct Context<'a>(&'a u32);
430    /// # struct Item;
431    /// struct Items {
432    ///     ty: String,
433    ///     items: Vec<Item>,
434    /// }
435    /// # impl Counted for Items {
436    /// #   fn quantities(&self) -> Quantities {
437    /// #       todo!()
438    /// #   }
439    /// # }
440    /// # impl Counted for Item {
441    /// #   fn quantities(&self) -> Quantities {
442    /// #       todo!()
443    /// #   }
444    /// # }
445    /// # type Error = std::convert::Infallible;
446    ///
447    /// fn process_items(items: &mut Managed<Items>, ctx: Context<'_>) {
448    ///     items.retain_with_context(|items| (&mut items.items, &items.ty), |item, ty, _| process(item, ty, ctx));
449    /// }
450    ///
451    /// fn process(item: &mut Item, ty: &str, ctx: Context<'_>) -> Result<(), Error> {
452    ///     todo!()
453    /// }
454    /// ```
455    pub fn retain_with_context<S, C, I, U, E, V>(&mut self, select: S, mut retain: U)
456    where
457        // Returning `&'a C` here is not optimal, ideally we return C here and express the correct
458        // bound of `C: 'a` but this is, to my knowledge, currently not possible to express in stable Rust.
459        //
460        // This is unfortunately a bit limiting but for most of our purposes it is enough.
461        for<'a> S: FnOnce(&'a mut T) -> (&'a mut V, &'a C),
462        I: Counted,
463        U: FnMut(&mut I, &C, &mut RecordKeeper<'_>) -> Result<(), E>,
464        E: OutcomeError,
465        V: RetainMut<I>,
466    {
467        self.modify(|inner, records| {
468            let (items, ctx) = select(inner);
469            items.retain_mut(|item| match retain(item, ctx, records) {
470                Ok(()) => true,
471                Err(err) => {
472                    records.reject_err(err, &*item);
473                    false
474                }
475            })
476        });
477    }
478
479    /// Maps a [`Managed<T>`] to [`Managed<S>`] by applying the mapping function `f`.
480    ///
481    /// Like [`Self::try_map`] but not fallible.
482    pub fn map<S, F>(self, f: F) -> Managed<S>
483    where
484        F: FnOnce(T, &mut RecordKeeper) -> S,
485        S: Counted,
486    {
487        self.try_map(move |inner, records| Ok::<_, Infallible>(f(inner, records)))
488            .unwrap_or_else(|e| match e.0 {})
489    }
490
491    /// Maps a [`Managed<T>`] to [`Managed<S>`] by applying the mapping function `f`.
492    ///
493    /// The mapping function gets access to a [`RecordKeeper`], to emit outcomes for partial
494    /// discards.
495    ///
496    /// If the mapping function returns an error, the entire (original) [`Self`] is rejected,
497    /// no partial outcomes are emitted.
498    pub fn try_map<S, F, E>(self, f: F) -> Result<Managed<S>, Rejected<E::Error>>
499    where
500        F: FnOnce(T, &mut RecordKeeper) -> Result<S, E>,
501        S: Counted,
502        E: OutcomeError,
503    {
504        debug_assert!(!self.is_done());
505
506        let (value, meta) = self.destructure();
507        let quantities = value.quantities();
508
509        let mut records = RecordKeeper::new(&meta, quantities);
510
511        match f(value, &mut records) {
512            Ok(value) => {
513                records.success(value.quantities());
514                Ok(Managed::from_parts(value, meta))
515            }
516            Err(err) => Err(records.failure(err)),
517        }
518    }
519
520    /// Gives mutable access to the contained value to modify it.
521    ///
522    /// Like [`Self::try_modify`] but not fallible.
523    pub fn modify<F>(&mut self, f: F)
524    where
525        F: FnOnce(&mut T, &mut RecordKeeper),
526    {
527        self.try_modify(move |inner, records| {
528            f(inner, records);
529            Ok::<_, Infallible>(())
530        })
531        .unwrap_or_else(|e| match e {})
532    }
533
534    /// Gives mutable access to the contained value to modify it.
535    ///
536    /// The modifying function gets access to a [`RecordKeeper`], to emit outcomes for partial
537    /// discards.
538    ///
539    /// If the modifying function returns an error, the entire (original) [`Self`] is rejected,
540    /// no partial outcomes are emitted.
541    pub fn try_modify<F, E>(&mut self, f: F) -> Result<(), Rejected<E::Error>>
542    where
543        F: FnOnce(&mut T, &mut RecordKeeper) -> Result<(), E>,
544        E: OutcomeError,
545    {
546        debug_assert!(!self.is_done());
547
548        let quantities = self.value.quantities();
549        let mut records = RecordKeeper::new(&self.meta, quantities);
550
551        match f(&mut self.value, &mut records) {
552            Ok(()) => {
553                records.success(self.value.quantities());
554                Ok(())
555            }
556            Err(err) => {
557                let err = records.failure(err);
558                self.done.store(true, Ordering::Relaxed);
559                Err(err)
560            }
561        }
562    }
563
564    /// Accepts the item of this managed instance.
565    ///
566    /// This should be called if the item has been or is about to be accepted by the upstream, which means that
567    /// the responsibility for logging outcomes has been moved. This function will not log any
568    /// outcomes.
569    ///
570    /// Like [`Self::try_accept`], but infallible.
571    pub fn accept<F, S>(self, f: F) -> S
572    where
573        F: FnOnce(T) -> S,
574    {
575        self.try_accept(|item| Ok::<_, Infallible>(f(item)))
576            .unwrap_or_else(|err| match err.0 {})
577    }
578
579    /// Accepts the item of this managed instance.
580    ///
581    /// This should be called if the item has been or is about to be accepted by the upstream.
582    ///
583    /// Outcomes are only emitted when the accepting closure returns an error, which means that
584    /// in the success case the responsibility for logging outcomes has been moved to the
585    /// caller/upstream.
586    pub fn try_accept<F, S, E>(self, f: F) -> Result<S, Rejected<E::Error>>
587    where
588        F: FnOnce(T) -> Result<S, E>,
589        E: OutcomeError,
590    {
591        debug_assert!(!self.is_done());
592
593        let (value, meta) = self.destructure();
594        let records = RecordKeeper::new(&meta, value.quantities());
595
596        match f(value) {
597            Ok(value) => {
598                records.accept();
599                Ok(value)
600            }
601            Err(err) => Err(records.failure(err)),
602        }
603    }
604
605    /// Rejects the entire [`Managed`] instance with an internal error.
606    ///
607    /// Internal errors should be reserved for uses where logical invariants are violated.
608    /// Cases which should never happen and always indicate a logical bug.
609    ///
610    /// This function will panic in debug builds, but discard the item
611    /// with an internal discard reason in release builds.
612    #[track_caller]
613    pub fn internal_error(&self, reason: &'static str) -> Rejected<()> {
614        relay_log::error!("internal error: {reason}");
615        debug_assert!(false, "internal error: {reason}");
616        self.reject_err((Outcome::Invalid(DiscardReason::Internal), ()))
617    }
618
619    /// Rejects the entire [`Managed`] instance.
620    pub fn reject_err<E>(&self, error: E) -> Rejected<E::Error>
621    where
622        E: OutcomeError,
623    {
624        debug_assert!(!self.is_done());
625
626        let (outcome, error) = error.consume();
627        self.do_reject(outcome);
628        Rejected(error)
629    }
630
631    fn do_reject(&self, outcome: Option<Outcome>) {
632        // Always set the internal state to `done`, even if there is no outcome to be emitted.
633        // All bookkeeping has been done.
634        let is_done = self.done.fetch_or(true, Ordering::Relaxed);
635
636        // No outcome to emit, we're done.
637        let Some(outcome) = outcome else {
638            return;
639        };
640
641        // Only emit outcomes if we were not yet done.
642        //
643        // Callers should guard against accidentally calling `do_reject` when the `is_done` flag is
644        // already set, but internal uses (like `Drop`) can rely on this double emission
645        // prevention.
646        if !is_done {
647            for (category, quantity) in self.value.quantities() {
648                self.meta.track_outcome(outcome.clone(), category, quantity);
649            }
650        }
651    }
652
653    /// De-structures this managed instance into its own parts.
654    ///
655    /// While de-structured no outcomes will be emitted on drop.
656    ///
657    /// Currently no `Managed`, which already has outcomes emitted, should be de-structured
658    /// as this status is lost.
659    fn destructure(self) -> (T, Arc<Meta>) {
660        // SAFETY: this follows an approach mentioned in the RFC
661        // <https://github.com/rust-lang/rfcs/pull/3466> to move fields out of
662        // a type with a drop implementation.
663        //
664        // The original type is wrapped in a manual drop to prevent running the
665        // drop handler, afterwards all fields are moved out of the type.
666        //
667        // And the original type is forgotten, de-structuring the original type
668        // without running its drop implementation.
669        let this = ManuallyDrop::new(self);
670        let Managed { value, meta, done } = &*this;
671
672        let value = unsafe { std::ptr::read(value) };
673        let meta = unsafe { std::ptr::read(meta) };
674        let done = unsafe { std::ptr::read(done) };
675        // This is a current invariant, if we ever need to change the invariant,
676        // the done status should be preserved and returned instead.
677        debug_assert!(
678            !done.load(Ordering::Relaxed),
679            "a `done` managed should never be destructured"
680        );
681
682        (value, meta)
683    }
684
685    fn from_parts(value: T, meta: Arc<Meta>) -> Self {
686        Self {
687            value,
688            meta,
689            done: AtomicBool::new(false),
690        }
691    }
692
693    fn is_done(&self) -> bool {
694        self.done.load(Ordering::Relaxed)
695    }
696}
697
698impl<T: Counted> Drop for Managed<T> {
699    fn drop(&mut self) {
700        self.do_reject(Some(Outcome::Invalid(DiscardReason::Internal)));
701    }
702}
703
704impl<T: Counted + fmt::Debug> fmt::Debug for Managed<T> {
705    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
706        write!(f, "Managed<{}>[", std::any::type_name::<T>())?;
707        for (i, (category, quantity)) in self.value.quantities().iter().enumerate() {
708            if i > 0 {
709                write!(f, ",")?;
710            }
711            write!(f, "{category}:{quantity}")?;
712        }
713        write!(f, "](")?;
714        self.value.fmt(f)?;
715        write!(f, ")")
716    }
717}
718
719impl<T: Counted> Managed<Option<T>> {
720    /// Turns a managed option into an optional [`Managed`].
721    pub fn transpose(self) -> Option<Managed<T>> {
722        let (o, meta) = self.destructure();
723        o.map(|t| Managed::from_parts(t, meta))
724    }
725}
726
727impl<L: Counted, R: Counted> Managed<Either<L, R>> {
728    /// Turns a managed [`Either`] into an [`Either`] of [`Managed`].
729    pub fn transpose(self) -> Either<Managed<L>, Managed<R>> {
730        let (either, meta) = self.destructure();
731        match either {
732            Either::Left(value) => Either::Left(Managed::from_parts(value, meta)),
733            Either::Right(value) => Either::Right(Managed::from_parts(value, meta)),
734        }
735    }
736}
737
738impl From<Managed<Box<Envelope>>> for ManagedEnvelope {
739    fn from(value: Managed<Box<Envelope>>) -> Self {
740        let (value, meta) = value.destructure();
741        let mut envelope = ManagedEnvelope::new(value, meta.outcome_aggregator.clone());
742        envelope.scope(meta.scoping);
743        envelope
744    }
745}
746
747impl<T: Counted> AsRef<T> for Managed<T> {
748    fn as_ref(&self) -> &T {
749        &self.value
750    }
751}
752
753impl<T: Counted> std::ops::Deref for Managed<T> {
754    type Target = T;
755
756    fn deref(&self) -> &Self::Target {
757        &self.value
758    }
759}
760
761/// Internal metadata attached with a [`Managed`] instance.
762#[derive(Debug, Clone)]
763struct Meta {
764    /// Outcome aggregator service.
765    outcome_aggregator: Addr<TrackOutcome>,
766    /// Received timestamp, when the contained payload/information was received.
767    ///
768    /// See also: [`crate::extractors::RequestMeta::received_at`].
769    received_at: DateTime<Utc>,
770    /// Data scoping information of the contained item.
771    scoping: Scoping,
772    /// Optional remote addr from where the data was received.
773    remote_addr: Option<IpAddr>,
774}
775
776impl Meta {
777    pub fn track_outcome(&self, outcome: Outcome, category: DataCategory, quantity: usize) {
778        self.outcome_aggregator.send(TrackOutcome {
779            timestamp: self.received_at,
780            scoping: self.scoping,
781            outcome,
782            event_id: None,
783            remote_addr: self.remote_addr,
784            category,
785            quantity: quantity as _,
786        });
787    }
788}
789
790/// A record keeper makes sure modifications done on a [`Managed`] item are all accounted for
791/// correctly.
792pub struct RecordKeeper<'a> {
793    meta: &'a Meta,
794    on_drop: Quantities,
795    #[cfg(debug_assertions)]
796    lenient: SmallVec<[DataCategory; 1]>,
797    #[cfg(debug_assertions)]
798    modifications: BTreeMap<DataCategory, isize>,
799    in_flight: SmallVec<[(DataCategory, usize, Option<Outcome>); 2]>,
800}
801
802impl<'a> RecordKeeper<'a> {
803    fn new(meta: &'a Meta, quantities: Quantities) -> Self {
804        Self {
805            meta,
806            on_drop: quantities,
807            #[cfg(debug_assertions)]
808            lenient: Default::default(),
809            #[cfg(debug_assertions)]
810            modifications: Default::default(),
811            in_flight: Default::default(),
812        }
813    }
814
815    /// Marking a data category as lenient exempts this category from outcome quantity validations.
816    ///
817    /// Consider using [`Self::modify_by`] instead.
818    ///
819    /// This can be used in cases where the quantity is knowingly modified, which is quite common
820    /// for data categories which count bytes.
821    pub fn lenient(&mut self, category: DataCategory) {
822        let _category = category;
823        #[cfg(debug_assertions)]
824        self.lenient.push(_category);
825    }
826
827    /// Modifies the expected count for a category.
828    ///
829    /// When extracting payloads category counts may expectedly change, these changes can be
830    /// tracked using this function.
831    ///
832    /// Prefer using [`Self::modify_by`] over [`Self::lenient`] as lenient completely disables
833    /// validation for the entire category.
834    pub fn modify_by(&mut self, category: DataCategory, offset: isize) {
835        let _category = category;
836        let _offset = offset;
837        #[cfg(debug_assertions)]
838        {
839            *self.modifications.entry(_category).or_default() += offset;
840        }
841    }
842
843    /// Adds the `item` quantities to the expected count.
844    ///
845    /// See also: [`Self::modify_by`].
846    pub fn add<T: Counted>(&mut self, item: T) {
847        for (category, quantities) in item.quantities() {
848            self.modify_by(category, quantities as isize);
849        }
850    }
851
852    /// Removes the `item` quantities from the expected count.
853    ///
854    /// See also: [`Self::modify_by`].
855    pub fn remove<T: Counted>(&mut self, item: &T) {
856        for (category, quantities) in item.quantities() {
857            self.modify_by(category, -(quantities as isize));
858        }
859    }
860
861    /// Finalizes all records and emits the necessary outcomes.
862    ///
863    /// This uses the quantities of the original item.
864    fn failure<E>(mut self, error: E) -> Rejected<E::Error>
865    where
866        E: OutcomeError,
867    {
868        let (outcome, error) = error.consume();
869
870        if let Some(outcome) = outcome {
871            for (category, quantity) in std::mem::take(&mut self.on_drop) {
872                self.meta.track_outcome(outcome.clone(), category, quantity);
873            }
874        }
875
876        Rejected(error)
877    }
878
879    /// Finalizes all records and asserts that no additional outcomes have been tracked.
880    ///
881    /// Unlike [`Self::success`], this method does not allow for intermediate or partial outcomes,
882    /// it also does not verify any outcomes.
883    ///
884    /// This method is useful for using the record keeper to track failure outcomes, either
885    /// explicit failures or panics.
886    fn accept(mut self) {
887        debug_assert!(
888            self.in_flight.is_empty(),
889            "records accepted, but intermediate outcomes tracked"
890        );
891        self.on_drop.clear();
892    }
893
894    /// Finalizes all records and emits the created outcomes.
895    ///
896    /// This only emits the outcomes that have been explicitly registered.
897    /// In a debug build, the function also ensure no outcomes have been missed by comparing
898    /// quantities of the item before and after.
899    fn success(mut self, new: Quantities) {
900        let original = std::mem::take(&mut self.on_drop);
901        self.assert_quantities(original, new);
902
903        self.on_drop.clear();
904        for (category, quantity, outcome) in std::mem::take(&mut self.in_flight) {
905            if let Some(outcome) = outcome {
906                self.meta.track_outcome(outcome, category, quantity);
907            }
908        }
909    }
910
911    /// Asserts that there have been no quantities lost.
912    ///
913    /// The original amount of quantities should match the new amount of quantities + all emitted
914    /// outcomes.
915    #[cfg(debug_assertions)]
916    fn assert_quantities(&self, original: Quantities, new: Quantities) {
917        macro_rules! emit {
918            ($category:expr, $($tt:tt)*) => {{
919                match self.lenient.contains(&$category) {
920                    // Certain categories are known to be not always correct,
921                    // they are logged instead.
922                    true => relay_log::debug!($($tt)*),
923                    false  => {
924                        relay_log::error!("Original: {original:?}");
925                        relay_log::error!("New: {new:?}");
926                        relay_log::error!("Modifications: {:?}", self.modifications);
927                        relay_log::error!("In Flight: {:?}", self.in_flight);
928                        panic!($($tt)*)
929                    }
930                }
931            }};
932        }
933
934        let mut sums = debug::Quantities::from(&original).0;
935        for (category, offset) in &self.modifications {
936            let v = sums.entry(*category).or_default();
937            match v.checked_add_signed(*offset) {
938                Some(result) => *v = result,
939                None => emit!(
940                    category,
941                    "Attempted to modify original quantity {v} into the negative ({offset})"
942                ),
943            }
944        }
945
946        for (category, quantity, outcome) in &self.in_flight {
947            match sums.get_mut(category) {
948                Some(c) if *c >= *quantity => *c -= *quantity,
949                Some(c) => emit!(
950                    category,
951                    "Emitted {quantity} outcomes ({outcome:?}) for {category}, but there were only {c} items in the category originally"
952                ),
953                None => emit!(
954                    category,
955                    "Emitted {quantity} outcomes ({outcome:?}) for {category}, but there never was an item in this category"
956                ),
957            }
958        }
959
960        for (category, quantity) in &new {
961            match sums.get_mut(category) {
962                Some(c) if *c >= *quantity => *c -= *quantity,
963                Some(c) => emit!(
964                    category,
965                    "New item has {quantity} items in category '{category}', but original (after emitted outcomes) only has {c} left"
966                ),
967                None => emit!(
968                    category,
969                    "New item has {quantity} items in category '{category}', but after emitted outcomes there are none left"
970                ),
971            }
972        }
973
974        for (category, quantity) in sums {
975            if quantity > 0 {
976                emit!(
977                    category,
978                    "Missing outcomes or mismatched quantity in category '{category}', off by {quantity}"
979                );
980            }
981        }
982    }
983
984    #[cfg(not(debug_assertions))]
985    fn assert_quantities(&self, _: Quantities, _: Quantities) {}
986}
987
988impl<'a> Drop for RecordKeeper<'a> {
989    fn drop(&mut self) {
990        for (category, quantity) in std::mem::take(&mut self.on_drop) {
991            self.meta.track_outcome(
992                Outcome::Invalid(DiscardReason::Internal),
993                category,
994                quantity,
995            );
996        }
997    }
998}
999
1000impl RecordKeeper<'_> {
1001    /// Rejects an item if the passed result is an error and returns a default value.
1002    ///
1003    /// Similar to [`Self::reject_err`], this emits the necessary outcomes for an
1004    /// item, if there is an error.
1005    pub fn or_default<T, E, Q>(&mut self, r: Result<T, E>, q: Q) -> T
1006    where
1007        T: Default,
1008        E: OutcomeError,
1009        Q: Counted,
1010    {
1011        match r {
1012            Ok(result) => result,
1013            Err(err) => {
1014                self.reject_err(err, q);
1015                T::default()
1016            }
1017        }
1018    }
1019
1020    /// Rejects an item with an error.
1021    ///
1022    /// Makes sure the correct outcomes are tracked for the item, that is discarded due to an
1023    /// error.
1024    pub fn reject_err<E, Q>(&mut self, err: E, q: Q) -> E::Error
1025    where
1026        E: OutcomeError,
1027        Q: Counted,
1028    {
1029        let (outcome, err) = err.consume();
1030        for (category, quantity) in q.quantities() {
1031            self.in_flight.push((category, quantity, outcome.clone()))
1032        }
1033        err
1034    }
1035
1036    /// Rejects an item with an internal error.
1037    ///
1038    /// See also: [`Managed::internal_error`].
1039    #[track_caller]
1040    pub fn internal_error<E, Q>(&mut self, error: E, q: Q)
1041    where
1042        E: std::error::Error + 'static,
1043        Q: Counted,
1044    {
1045        relay_log::error!(error = &error as &dyn std::error::Error, "internal error");
1046        debug_assert!(false, "internal error: {error}");
1047        self.reject_err((Outcome::Invalid(DiscardReason::Internal), ()), q);
1048    }
1049}
1050
1051/// Iterator returned by [`Managed::split`].
1052pub struct Split<I, S>
1053where
1054    I: Iterator<Item = S>,
1055    S: Counted,
1056{
1057    #[cfg(debug_assertions)]
1058    quantities: Quantities,
1059    items: I,
1060    meta: Arc<Meta>,
1061    exhausted: bool,
1062}
1063
1064impl<I, S> Split<I, S>
1065where
1066    I: Iterator<Item = S>,
1067    S: Counted,
1068{
1069    /// Subtracts passed quantities from the total quantities to verify total quantity counts are
1070    /// matching.
1071    #[cfg(debug_assertions)]
1072    fn subtract(&mut self, q: Quantities) {
1073        for (category, quantities) in q {
1074            let Some(orig_quantities) = self
1075                .quantities
1076                .iter_mut()
1077                .find_map(|(c, q)| (*c == category).then_some(q))
1078            else {
1079                debug_assert!(
1080                    false,
1081                    "mismatching quantities, item split into category {category}, \
1082                    which originally was not present"
1083                );
1084                continue;
1085            };
1086
1087            if *orig_quantities >= quantities {
1088                *orig_quantities -= quantities;
1089            } else {
1090                debug_assert!(
1091                    false,
1092                    "in total more items produced in category {category} than originally available"
1093                );
1094            }
1095        }
1096    }
1097}
1098
1099impl<I, S> Iterator for Split<I, S>
1100where
1101    I: Iterator<Item = S>,
1102    S: Counted,
1103{
1104    type Item = Managed<S>;
1105
1106    fn next(&mut self) -> Option<Self::Item> {
1107        let next = match self.items.next() {
1108            Some(next) => next,
1109            None => {
1110                self.exhausted = true;
1111                return None;
1112            }
1113        };
1114
1115        #[cfg(debug_assertions)]
1116        self.subtract(next.quantities());
1117
1118        Some(Managed::from_parts(next, Arc::clone(&self.meta)))
1119    }
1120}
1121
1122impl<I, S> Drop for Split<I, S>
1123where
1124    I: Iterator<Item = S>,
1125    S: Counted,
1126{
1127    fn drop(&mut self) {
1128        // If the inner iterator was exhausted, no items should be remaining.
1129        #[cfg(debug_assertions)]
1130        if self.exhausted {
1131            for (category, quantities) in &self.quantities {
1132                debug_assert!(
1133                    *quantities == 0,
1134                    "items split, but still {quantities} remaining in category {category}"
1135                );
1136            }
1137        }
1138
1139        if self.exhausted {
1140            return;
1141        }
1142
1143        // There may be items remaining in the iterator for multiple reasons:
1144        // - there was a panic
1145        // - the iterator was never fully consumed
1146        //
1147        // In any case, outcomes must be emitted for the remaining items.
1148        for item in &mut self.items {
1149            for (category, quantity) in item.quantities() {
1150                self.meta.track_outcome(
1151                    Outcome::Invalid(DiscardReason::Internal),
1152                    category,
1153                    quantity,
1154                );
1155            }
1156        }
1157    }
1158}
1159
1160impl<I, S> FusedIterator for Split<I, S>
1161where
1162    I: Iterator<Item = S> + FusedIterator,
1163    S: Counted,
1164{
1165}
1166
1167#[cfg(test)]
1168mod tests {
1169    use super::*;
1170
1171    use relay_base_schema::project::ProjectId;
1172
1173    struct CountedVec(Vec<u32>);
1174
1175    impl Counted for CountedVec {
1176        fn quantities(&self) -> Quantities {
1177            smallvec::smallvec![(DataCategory::Error, self.0.len())]
1178        }
1179    }
1180
1181    struct CountedValue(u32);
1182
1183    impl Counted for CountedValue {
1184        fn quantities(&self) -> Quantities {
1185            smallvec::smallvec![(DataCategory::Error, 1)]
1186        }
1187    }
1188
1189    #[test]
1190    fn test_reject_err_no_outcome() {
1191        let value = CountedVec(vec![0, 1, 2, 3, 4, 5]);
1192        let (managed, mut handle) = Managed::for_test(value).build();
1193
1194        // Rejecting with no outcome, should not emit any outcomes.
1195        let _ = managed.reject_err((None, ()));
1196        handle.assert_no_outcomes();
1197
1198        // Now dropping the manged instance, should not record any (internal) outcomes either.
1199        drop(managed);
1200        handle.assert_no_outcomes();
1201    }
1202
1203    #[test]
1204    fn test_merge() {
1205        let (mut a, mut handle_a) = Managed::for_test(CountedVec(vec![1, 2])).build();
1206        let (b, mut handle_b) = Managed::for_test(CountedVec(vec![3, 4])).build();
1207
1208        a.merge_with(b, |a, b, _| a.0.extend(b.0));
1209
1210        assert_eq!(a.0, vec![1, 2, 3, 4]);
1211        drop(a);
1212        handle_a.assert_internal_outcome(DataCategory::Error, 4);
1213        handle_b.assert_no_outcomes();
1214    }
1215
1216    #[test]
1217    fn test_zip_into_tuple() {
1218        let (a, mut handle_a) = Managed::for_test(CountedVec(vec![1, 2])).build();
1219        let (b, mut handle_b) = Managed::for_test(CountedValue(3)).build();
1220
1221        let z = Managed::zip(a, b);
1222
1223        assert_eq!((z.as_ref().0).0, vec![1, 2]);
1224        assert_eq!((z.as_ref().1).0, 3);
1225        drop(z);
1226        handle_a.assert_internal_outcome(DataCategory::Error, 2);
1227        handle_a.assert_internal_outcome(DataCategory::Error, 1);
1228        handle_b.assert_no_outcomes();
1229    }
1230
1231    #[test]
1232    fn test_zip_rejects_different_metadata() {
1233        let (a, mut handle_a) = Managed::for_test(CountedVec(vec![1, 2])).build();
1234        let (b, mut handle_b) = Managed::for_test(CountedValue(3))
1235            .scoping(Scoping {
1236                project_id: ProjectId::new(45),
1237                ..a.scoping()
1238            })
1239            .build();
1240
1241        let result = std::panic::catch_unwind(move || {
1242            Managed::zip(a, b);
1243        });
1244
1245        assert!(
1246            result.is_err(),
1247            "cannot zip Managed values with different metadata"
1248        );
1249        handle_a.assert_internal_outcome(DataCategory::Error, 2);
1250        handle_b.assert_internal_outcome(DataCategory::Error, 1);
1251    }
1252
1253    #[test]
1254    fn test_merge_mismatched_records_should_panic() {
1255        let (mut a, mut handle_a) = Managed::for_test(CountedVec(vec![1, 2])).build();
1256        let (b, _handle_b) = Managed::for_test(CountedVec(vec![3, 4])).build();
1257
1258        let r = std::panic::catch_unwind(move || {
1259            a.merge_with(b, |_a, _b, _| {});
1260        });
1261
1262        assert!(
1263            r.is_err(),
1264            "expected merge to panic because of mismatched outcome records"
1265        );
1266        handle_a.assert_internal_outcome(DataCategory::Error, 2);
1267    }
1268
1269    #[test]
1270    fn test_split_fully_consumed() {
1271        let value = CountedVec(vec![0, 1, 2, 3, 4, 5]);
1272        let (managed, mut handle) = Managed::for_test(value).build();
1273
1274        let s = managed
1275            .split(|value| value.0.into_iter().map(CountedValue))
1276            // Fully consume the iterator to make sure there aren't any outcomes emitted on drop.
1277            .collect::<Vec<_>>();
1278
1279        handle.assert_no_outcomes();
1280
1281        for (i, s) in s.into_iter().enumerate() {
1282            assert_eq!(s.as_ref().0, i as u32);
1283            let outcome = Outcome::Invalid(DiscardReason::Cors);
1284            let _ = s.reject_err((outcome.clone(), ()));
1285            handle.assert_outcome(&outcome, DataCategory::Error, 1);
1286        }
1287    }
1288
1289    #[test]
1290    fn test_split_partially_consumed_emits_remaining() {
1291        let value = CountedVec(vec![0, 1, 2, 3, 4, 5]);
1292        let (managed, mut handle) = Managed::for_test(value).build();
1293
1294        let mut s = managed.split(|value| value.0.into_iter().map(CountedValue));
1295        handle.assert_no_outcomes();
1296
1297        drop(s.next());
1298        handle.assert_internal_outcome(DataCategory::Error, 1);
1299        drop(s.next());
1300        handle.assert_internal_outcome(DataCategory::Error, 1);
1301        drop(s.next());
1302        handle.assert_internal_outcome(DataCategory::Error, 1);
1303        handle.assert_no_outcomes();
1304
1305        drop(s);
1306
1307        handle.assert_internal_outcome(DataCategory::Error, 1);
1308        handle.assert_internal_outcome(DataCategory::Error, 1);
1309        handle.assert_internal_outcome(DataCategory::Error, 1);
1310    }
1311
1312    #[test]
1313    fn test_split_changing_quantities_should_panic() {
1314        let value = CountedVec(vec![0, 1, 2, 3, 4, 5]);
1315        let (managed, mut handle) = Managed::for_test(value).build();
1316
1317        let mut s = managed.split(|_| std::iter::once(CountedValue(0)));
1318
1319        s.next().unwrap().accept(|_| {});
1320        handle.assert_no_outcomes();
1321
1322        assert!(s.next().is_none());
1323
1324        let r = std::panic::catch_unwind(move || {
1325            drop(s);
1326        });
1327
1328        assert!(
1329            r.is_err(),
1330            "expected split to panic because of mismatched (not enough) outcomes"
1331        );
1332    }
1333
1334    #[test]
1335    fn test_split_more_outcomes_than_before_should_panic() {
1336        let value = CountedVec(vec![0]);
1337        let (managed, mut handle) = Managed::for_test(value).build();
1338
1339        let mut s = managed.split(|_| vec![CountedValue(0), CountedValue(2)].into_iter());
1340
1341        s.next().unwrap().accept(|_| {});
1342        handle.assert_no_outcomes();
1343
1344        let r = std::panic::catch_unwind(move || {
1345            s.next();
1346        });
1347
1348        assert!(
1349            r.is_err(),
1350            "expected split to panic because of mismatched (too many) outcomes"
1351        );
1352    }
1353
1354    #[test]
1355    fn test_split_changing_categories_should_panic() {
1356        struct Special;
1357        impl Counted for Special {
1358            fn quantities(&self) -> Quantities {
1359                smallvec::smallvec![(DataCategory::Error, 1), (DataCategory::Transaction, 1)]
1360            }
1361        }
1362
1363        let value = CountedVec(vec![0]);
1364        let (managed, _handle) = Managed::for_test(value).build();
1365
1366        let mut s = managed.split(|value| value.0.into_iter().map(|_| Special));
1367
1368        let r = std::panic::catch_unwind(move || {
1369            let _ = s.next();
1370        });
1371
1372        assert!(
1373            r.is_err(),
1374            "expected split to panic because of mismatched outcome categories"
1375        );
1376    }
1377
1378    #[test]
1379    fn test_split_assert_fused() {
1380        fn only_fused<T: FusedIterator>(_: T) {}
1381
1382        let (managed, mut handle) = Managed::for_test(CountedVec(vec![0])).build();
1383        only_fused(managed.split(|value| value.0.into_iter().map(CountedValue)));
1384        handle.assert_internal_outcome(DataCategory::Error, 1);
1385    }
1386}