Skip to main content

rama_http/layer/trace/
on_eos.rs

1use super::{DEFAULT_MESSAGE_LEVEL, Latency};
2use crate::header::HeaderMap;
3use crate::layer::classify::grpc_errors_as_failures::ParsedGrpcStatus;
4use rama_core::telemetry::tracing::{Level, Span};
5use rama_utils::latency::LatencyUnit;
6use std::time::Duration;
7
8/// Trait used to tell [`Trace`] what to do when a stream closes.
9///
10/// See the [module docs](../trace/index.html#on_eos) for details on exactly when the `on_eos`
11/// callback is called.
12///
13/// [`Trace`]: super::Trace
14pub trait OnEos: Send + Sync + 'static {
15    /// Do the thing.
16    ///
17    /// `stream_duration` is the duration since the response was sent.
18    ///
19    /// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
20    /// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
21    /// that weren't known when the span was created.
22    ///
23    /// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
24    /// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
25    /// [`TraceLayer::make_span_with`]: crate::layer::trace::TraceLayer::make_span_with
26    fn on_eos(self, trailers: Option<&HeaderMap>, stream_duration: Duration, span: &Span);
27}
28
29impl OnEos for () {
30    #[inline]
31    fn on_eos(self, _: Option<&HeaderMap>, _: Duration, _: &Span) {}
32}
33
34impl<F> OnEos for F
35where
36    F: Fn(Option<&HeaderMap>, Duration, &Span) + Send + Sync + 'static,
37{
38    fn on_eos(self, trailers: Option<&HeaderMap>, stream_duration: Duration, span: &Span) {
39        self(trailers, stream_duration, span)
40    }
41}
42
43/// The default [`OnEos`] implementation used by [`Trace`].
44///
45/// [`Trace`]: super::Trace
46#[derive(Clone, Debug)]
47pub struct DefaultOnEos {
48    level: Level,
49    latency_unit: LatencyUnit,
50}
51
52impl Default for DefaultOnEos {
53    fn default() -> Self {
54        Self {
55            level: DEFAULT_MESSAGE_LEVEL,
56            latency_unit: LatencyUnit::Millis,
57        }
58    }
59}
60
61impl DefaultOnEos {
62    /// Create a new [`DefaultOnEos`].
63    #[must_use]
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    rama_utils::macros::generate_set_and_with! {
69        /// Set the [`Level`] used for [tracing events].
70        ///
71        /// Defaults to [`Level::DEBUG`].
72        ///
73        /// [tracing events]: https://docs.rs/tracing/latest/tracing/#events
74        /// [`Level::DEBUG`]: https://docs.rs/tracing/latest/tracing/struct.Level.html#associatedconstant.DEBUG
75        pub fn level(mut self, level: Level) -> Self {
76            self.level = level;
77            self
78        }
79    }
80
81    rama_utils::macros::generate_set_and_with! {
82        /// Set the [`LatencyUnit`] latencies will be reported in.
83        ///
84        /// Defaults to [`LatencyUnit::Millis`].
85        pub fn latency_unit(mut self, latency_unit: LatencyUnit) -> Self {
86            self.latency_unit = latency_unit;
87            self
88        }
89    }
90}
91
92impl OnEos for DefaultOnEos {
93    fn on_eos(self, trailers: Option<&HeaderMap>, stream_duration: Duration, span: &Span) {
94        let stream_duration = Latency {
95            unit: self.latency_unit,
96            duration: stream_duration,
97        };
98        let status = trailers.and_then(|trailers| {
99            match crate::layer::classify::grpc_errors_as_failures::classify_grpc_metadata(
100                trailers,
101                crate::layer::classify::GrpcCode::Ok.into_bitmask(),
102            ) {
103                ParsedGrpcStatus::Success | ParsedGrpcStatus::HeaderNotGrpcCode => Some(0),
104                ParsedGrpcStatus::NonSuccess(status) => Some(status.code_raw()),
105                ParsedGrpcStatus::GrpcStatusHeaderMissing => None,
106            }
107        });
108
109        event_dynamic_lvl!(parent: span, self.level, %stream_duration, status, "end of stream");
110    }
111}