Skip to main content

tower_http/on_early_drop/
layer.rs

1//! Tower [`Layer`] for the on-early-drop middleware.
2
3use crate::on_early_drop::service::OnEarlyDropService;
4use tower_layer::Layer;
5
6/// [`Layer`] that applies [`OnEarlyDropService`].
7///
8/// See the [module docs](super) for details and examples.
9#[derive(Clone, Copy)]
10pub struct OnEarlyDropLayer<OFD, OBD> {
11    on_future_drop: OFD,
12    on_body_drop: OBD,
13}
14
15impl<OFD, OBD> std::fmt::Debug for OnEarlyDropLayer<OFD, OBD> {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        f.debug_struct("OnEarlyDropLayer")
18            .field("on_future_drop", &format_args!(".."))
19            .field("on_body_drop", &format_args!(".."))
20            .finish()
21    }
22}
23
24impl OnEarlyDropLayer<(), ()> {
25    /// Start with both slots set to no-op. Chain
26    /// [`on_future_drop`](Self::on_future_drop) and
27    /// [`on_body_drop`](Self::on_body_drop) to install hooks.
28    pub fn builder() -> Self {
29        Self {
30            on_future_drop: (),
31            on_body_drop: (),
32        }
33    }
34}
35
36impl<H: Clone> OnEarlyDropLayer<H, H> {
37    /// Install the same hook in both slots.
38    ///
39    /// Typical choice is
40    /// [`EarlyDropsAsFailures`](crate::on_early_drop::EarlyDropsAsFailures);
41    /// see the [module docs](super) for the example.
42    pub fn new(hook: H) -> Self {
43        Self {
44            on_future_drop: hook.clone(),
45            on_body_drop: hook,
46        }
47    }
48}
49
50impl<OFD, OBD> OnEarlyDropLayer<OFD, OBD> {
51    /// Replace the future-drop slot.
52    pub fn on_future_drop<T>(self, hook: T) -> OnEarlyDropLayer<T, OBD> {
53        OnEarlyDropLayer {
54            on_future_drop: hook,
55            on_body_drop: self.on_body_drop,
56        }
57    }
58
59    /// Replace the body-drop slot.
60    pub fn on_body_drop<T>(self, hook: T) -> OnEarlyDropLayer<OFD, T> {
61        OnEarlyDropLayer {
62            on_future_drop: self.on_future_drop,
63            on_body_drop: hook,
64        }
65    }
66}
67
68impl<S, OFD, OBD> Layer<S> for OnEarlyDropLayer<OFD, OBD>
69where
70    OFD: Clone,
71    OBD: Clone,
72{
73    type Service = OnEarlyDropService<S, OFD, OBD>;
74
75    fn layer(&self, inner: S) -> Self::Service {
76        OnEarlyDropService::new(
77            inner,
78            self.on_future_drop.clone(),
79            self.on_body_drop.clone(),
80        )
81    }
82}