tower_http/trace/on_body_chunk.rs
1use std::time::Duration;
2use tracing::Span;
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> {
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 ///
22 /// If you're using [hyper] as your server `B` will most likely be [`Bytes`].
23 ///
24 /// [hyper]: https://hyper.rs
25 /// [`Bytes`]: https://docs.rs/bytes/latest/bytes/struct.Bytes.html
26 /// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
27 fn on_body_chunk(&mut self, chunk: &B, latency: Duration, span: &Span);
28}
29
30impl<B, F> OnBodyChunk<B> for F
31where
32 F: FnMut(&B, Duration, &Span),
33{
34 fn on_body_chunk(&mut self, chunk: &B, latency: Duration, span: &Span) {
35 self(chunk, latency, span)
36 }
37}
38
39impl<B> OnBodyChunk<B> for () {
40 #[inline]
41 fn on_body_chunk(&mut self, _: &B, _: Duration, _: &Span) {}
42}
43
44/// The default [`OnBodyChunk`] implementation used by [`Trace`].
45///
46/// Simply does nothing.
47///
48/// [`Trace`]: super::Trace
49#[derive(Debug, Default, Clone)]
50pub struct DefaultOnBodyChunk {
51 _priv: (),
52}
53
54impl DefaultOnBodyChunk {
55 /// Create a new `DefaultOnBodyChunk`.
56 pub fn new() -> Self {
57 Self { _priv: () }
58 }
59}
60
61impl<B> OnBodyChunk<B> for DefaultOnBodyChunk {
62 #[inline]
63 fn on_body_chunk(&mut self, _: &B, _: Duration, _: &Span) {}
64}