Skip to main content

rama_http/layer/upgrade/mitm/
layer.rs

1use std::fmt;
2use std::sync::Arc;
3
4use rama_core::{
5    Layer,
6    error_sink::{ErrorSink, TracingErrorSink},
7    rt::Executor,
8};
9
10use super::HttpUpgradeMitmRelay;
11
12#[derive(Clone)]
13/// Layer used to create the middleware [`HttpUpgradeMitmRelay`] service.
14pub struct HttpUpgradeMitmRelayLayer<M> {
15    exec: Executor,
16    nested_matcher_svc: M,
17    error_sink: Arc<dyn ErrorSink>,
18}
19
20impl<U> HttpUpgradeMitmRelayLayer<U> {
21    #[inline(always)]
22    #[must_use]
23    /// Create a new [`HttpUpgradeMitmRelayLayer`] used to produce
24    /// the middleware [`HttpUpgradeMitmRelay`] service.
25    pub fn new(exec: Executor, nested_matcher_svc: U) -> Self {
26        Self {
27            exec,
28            nested_matcher_svc,
29            error_sink: Arc::new(TracingErrorSink::default()),
30        }
31    }
32
33    /// Set a custom [`ErrorSink`] used to observe errors from the detached
34    /// relay task. Defaults to [`TracingErrorSink::default`] (traces at DEBUG).
35    #[must_use]
36    pub fn with_error_sink(mut self, sink: impl ErrorSink) -> Self {
37        self.error_sink = Arc::new(sink);
38        self
39    }
40}
41
42impl<M: fmt::Debug> fmt::Debug for HttpUpgradeMitmRelayLayer<M> {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.debug_struct("HttpUpgradeMitmRelayLayer")
45            .field("exec", &self.exec)
46            .field("nested_matcher_svc", &self.nested_matcher_svc)
47            .finish()
48    }
49}
50
51impl<M: Clone, S> Layer<S> for HttpUpgradeMitmRelayLayer<M> {
52    type Service = HttpUpgradeMitmRelay<M, S>;
53
54    #[inline(always)]
55    fn layer(&self, inner_svc: S) -> Self::Service {
56        HttpUpgradeMitmRelay::new(
57            self.exec.clone(),
58            self.nested_matcher_svc.clone(),
59            inner_svc,
60        )
61        .with_error_sink(self.error_sink.clone())
62    }
63
64    #[inline(always)]
65    fn into_layer(self, inner_svc: S) -> Self::Service {
66        HttpUpgradeMitmRelay::new(self.exec, self.nested_matcher_svc, inner_svc)
67            .with_error_sink(self.error_sink)
68    }
69}