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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::{
    pin::Pin,
    task::{Context, Poll},
};

use futures_util::{Future, FutureExt};
use http::StatusCode;
use pin_project_lite::pin_project;
use tower::{Layer, Service};

use crate::{proto::Error as HrpcError, request::BoxRequest, response::BoxResponse};

/// Layer for layering services with [`ErrorIdentifierToStatus`].
#[derive(Clone)]
pub struct ErrorIdentifierToStatusLayer<ToStatus> {
    to_status: ToStatus,
}

impl<ToStatus> ErrorIdentifierToStatusLayer<ToStatus>
where
    ToStatus: Fn(&str) -> Option<StatusCode>,
{
    /// Create a new layer using the provided [`ToStatus`] function.
    pub fn new(to_status: ToStatus) -> Self {
        Self { to_status }
    }
}

impl<ToStatus, S> Layer<S> for ErrorIdentifierToStatusLayer<ToStatus>
where
    ToStatus: Clone,
{
    type Service = ErrorIdentifierToStatus<ToStatus, S>;

    fn layer(&self, inner: S) -> Self::Service {
        ErrorIdentifierToStatus::new(self.to_status.clone(), inner)
    }
}

/// Service to set response status from possible errors.
#[derive(Clone)]
pub struct ErrorIdentifierToStatus<ToStatus, S> {
    inner: S,
    to_status: ToStatus,
}

impl<ToStatus, S> ErrorIdentifierToStatus<ToStatus, S> {
    /// Create a new service by wrapping another service, and converting to
    /// status using the provided function.
    pub fn new(to_status: ToStatus, inner: S) -> Self {
        Self { inner, to_status }
    }
}

impl<ToStatus, S> Service<BoxRequest> for ErrorIdentifierToStatus<ToStatus, S>
where
    S: Service<BoxRequest, Response = BoxResponse>,
    ToStatus: Fn(&str) -> Option<StatusCode> + Clone,
{
    type Response = BoxResponse;

    type Error = S::Error;

    type Future = ErrorIdentifierToStatusFuture<ToStatus, S::Future>;

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

    fn call(&mut self, req: BoxRequest) -> Self::Future {
        ErrorIdentifierToStatusFuture {
            resp_fut: Service::call(&mut self.inner, req),
            to_status: self.to_status.clone(),
        }
    }
}

pin_project! {
    /// Future for [`ErrorIdentifierToStatus`].
    pub struct ErrorIdentifierToStatusFuture<ToStatus, Fut> {
        #[pin]
        resp_fut: Fut,
        to_status: ToStatus,
    }
}

impl<ToStatus, Fut, Err> Future for ErrorIdentifierToStatusFuture<ToStatus, Fut>
where
    Fut: Future<Output = Result<BoxResponse, Err>>,
    ToStatus: Fn(&str) -> Option<StatusCode>,
{
    type Output = Result<BoxResponse, Err>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        this.resp_fut.poll_unpin(cx).map_ok(|mut resp| {
            if let Some(status) = resp
                .extensions()
                .get::<HrpcError>()
                .and_then(|err| (this.to_status)(&err.identifier))
            {
                resp.extensions_mut().insert(status);
            }
            resp
        })
    }
}