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
// Copyright (c) Mysten Labs, Inc.
// Modifications Copyright (c) 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use http::Response;
use pin_project_lite::pin_project;

use super::ResponseHandler;

pin_project! {
    /// Response future for [`Callback`].
    ///
    /// [`Callback`]: super::Callback
    pub struct ResponseFuture<F, ResponseHandler> {
        #[pin]
        pub(crate) inner: F,
        pub(crate) handler: Option<ResponseHandler>,
    }
}

impl<Fut, B, E, ResponseHandlerT> Future for ResponseFuture<Fut, ResponseHandlerT>
where
    Fut: Future<Output = Result<Response<B>, E>>,
    ResponseHandlerT: ResponseHandler,
{
    type Output = Result<Response<B>, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let result = futures::ready!(this.inner.poll(cx));
        let handler = this.handler.take().unwrap();

        let result = match result {
            Ok(response) => {
                let (head, body) = response.into_parts();
                handler.on_response(&head);
                Ok(Response::from_parts(head, body))
            }
            Err(error) => {
                handler.on_error(&error);
                Err(error)
            }
        };

        Poll::Ready(result)
    }
}