1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright (c) Mysten Labs, Inc.
// Modifications Copyright (c) 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::task::{Context, Poll};

use http::{Request, Response};
use tower::Service;

use super::{CallbackLayer, MakeCallbackHandler, ResponseFuture};

/// Middleware that adds callbacks to a [`Service`].
///
/// See the [module docs](crate::callback) for an example.
///
/// [`Service`]: tower::Service
#[derive(Debug, Clone, Copy)]
pub struct Callback<S, M> {
    pub(crate) inner: S,
    pub(crate) make_callback_handler: M,
}

impl<S, M> Callback<S, M> {
    /// Create a new [`Callback`].
    pub fn new(inner: S, make_callback_handler: M) -> Self {
        Self {
            inner,
            make_callback_handler,
        }
    }

    /// Returns a new [`Layer`] that wraps services with a [`CallbackLayer`]
    /// middleware.
    ///
    /// [`Layer`]: tower::layer::Layer
    pub fn layer(make_handler: M) -> CallbackLayer<M>
    where
        M: MakeCallbackHandler,
    {
        CallbackLayer::new(make_handler)
    }

    /// Gets a reference to the underlying service.
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Gets a mutable reference to the underlying service.
    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    /// Consumes `self`, returning the underlying service.
    pub fn into_inner(self) -> S {
        self.inner
    }
}

impl<S, M, RequestBody, ResponseBody> Service<Request<RequestBody>> for Callback<S, M>
where
    S: Service<Request<RequestBody>, Response = Response<ResponseBody>>,
    M: MakeCallbackHandler,
{
    type Response = Response<ResponseBody>;
    type Error = S::Error;
    type Future = ResponseFuture<S::Future, M::Handler>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request<RequestBody>) -> Self::Future {
        let (head, body) = request.into_parts();
        let handler = self.make_callback_handler.make_handler(&head);
        let request = Request::from_parts(head, body);

        ResponseFuture {
            inner: self.inner.call(request),
            handler: Some(handler),
        }
    }
}