rama_http/layer/trace/on_body_chunk.rs
1use rama_core::telemetry::tracing::Span;
2use std::time::Duration;
3
4/// Trait used to tell [`Trace`] what to do when a body chunk has been sent.
5///
6/// See the [module docs](../trace/index.html#on_body_chunk) for details on exactly when the
7/// `on_body_chunk` callback is called.
8///
9/// [`Trace`]: super::Trace
10pub trait OnBodyChunk<B>: Send + Sync + 'static {
11 /// Do the thing.
12 ///
13 /// `latency` is the duration since the response was sent or since the last body chunk as sent.
14 ///
15 /// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
16 /// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
17 /// that weren't known when the span was created.
18 ///
19 /// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
20 /// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
21 /// [`TraceLayer::make_span_with`]: crate::layer::trace::TraceLayer::make_span_with
22 fn on_body_chunk(&mut self, chunk: &B, latency: Duration, span: &Span);
23}
24
25impl<B, F> OnBodyChunk<B> for F
26where
27 F: Fn(&B, Duration, &Span) + Send + Sync + 'static,
28{
29 fn on_body_chunk(&mut self, chunk: &B, latency: Duration, span: &Span) {
30 self(chunk, latency, span)
31 }
32}
33
34impl<B> OnBodyChunk<B> for () {
35 #[inline]
36 fn on_body_chunk(&mut self, _: &B, _: Duration, _: &Span) {}
37}
38
39/// The default [`OnBodyChunk`] implementation used by [`Trace`].
40///
41/// Simply does nothing.
42///
43/// [`Trace`]: super::Trace
44#[derive(Debug, Default, Clone)]
45pub struct DefaultOnBodyChunk {
46 _priv: (),
47}
48
49impl DefaultOnBodyChunk {
50 /// Create a new `DefaultOnBodyChunk`.
51 #[must_use]
52 pub const fn new() -> Self {
53 Self { _priv: () }
54 }
55}
56
57impl<B> OnBodyChunk<B> for DefaultOnBodyChunk {
58 #[inline]
59 fn on_body_chunk(&mut self, _: &B, _: Duration, _: &Span) {}
60}