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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
//! synchronous function as middleware.

use core::mem;

use std::sync::mpsc::Receiver;

use tokio::sync::mpsc::UnboundedSender;

use crate::{
    context::WebContext,
    http::{Request, RequestExt, Response},
    service::Service,
};

/// experimental type for sync function as middleware.
pub struct SyncMiddleware<F>(F);

impl<F> SyncMiddleware<F> {
    /// *. Sync middleware does not have access to request/response body.
    ///
    /// construct a new middleware with given sync function.
    /// the function must be actively calling [Next::call] and finish it to drive inner services to completion.
    /// panic in sync function middleware would result in a panic at task level and it's client connection would
    /// be terminated immediately.
    pub fn new<C, E>(func: F) -> Self
    where
        F: Fn(&mut Next<E>, WebContext<'_, C>) -> Result<Response<()>, E> + Send + Sync + 'static,
        C: Clone + Send + 'static,
        E: Send + 'static,
    {
        Self(func)
    }
}

/// next/inner services of a middleware function. [Next::call] must run to complete in order to drive
/// services.
pub struct Next<E> {
    tx: UnboundedSender<Request<RequestExt<()>>>,
    rx: Receiver<Result<Response<()>, E>>,
}

impl<E> Next<E> {
    /// call next/inner services to complete where they would produce either a http response or an error.
    pub fn call<C>(&mut self, mut ctx: WebContext<'_, C>) -> Result<Response<()>, E> {
        let req = mem::take(ctx.req_mut());
        self.tx.send(req).unwrap();
        self.rx.recv().unwrap()
    }
}

impl<F, S, E> Service<Result<S, E>> for SyncMiddleware<F>
where
    F: Clone,
{
    type Response = service::SyncService<F, S>;
    type Error = E;

    async fn call(&self, res: Result<S, E>) -> Result<Self::Response, Self::Error> {
        res.map(|service| service::SyncService {
            func: self.0.clone(),
            service,
        })
    }
}

mod service {
    use core::cell::RefCell;

    use std::sync::mpsc::sync_channel;

    use tokio::sync::mpsc::unbounded_channel;

    use crate::{body::RequestBody, http::WebResponse, service::ready::ReadyService};

    use super::*;

    pub struct SyncService<F, S> {
        pub(super) func: F,
        pub(super) service: S,
    }

    impl<'r, F, C, S, B, ResB, Err> Service<WebContext<'r, C, B>> for SyncService<F, S>
    where
        F: Fn(&mut Next<Err>, WebContext<'_, C>) -> Result<Response<()>, Err> + Send + Clone + 'static,
        C: Clone + Send + 'static,
        S: for<'r2> Service<WebContext<'r, C, B>, Response = WebResponse<ResB>, Error = Err>,
        Err: Send + 'static,
    {
        type Response = WebResponse<ResB>;
        type Error = Err;

        async fn call(&self, mut ctx: WebContext<'r, C, B>) -> Result<Self::Response, Self::Error> {
            let func = self.func.clone();
            let state = ctx.state().clone();
            let mut req = mem::take(ctx.req_mut());

            let (tx, mut rx) = unbounded_channel();
            let (tx2, rx2) = sync_channel(1);

            let mut next = Next { tx, rx: rx2 };
            let handle = tokio::task::spawn_blocking(move || {
                let mut body = RefCell::new(RequestBody::None);
                let ctx = WebContext::new(&mut req, &mut body, &state);
                func(&mut next, ctx)
            });

            *ctx.req_mut() = match rx.recv().await {
                Some(req) => req,
                None => {
                    // tx is dropped which means spawned thread exited already. join it and panic if necessary.
                    match handle.await.unwrap() {
                        Ok(_) => todo!("there is no support for body type yet"),
                        Err(e) => return Err(e),
                    }
                }
            };

            match self.service.call(ctx).await {
                Ok(res) => {
                    let (parts, body) = res.into_parts();
                    let _ = tx2.send(Ok(Response::from_parts(parts, ())));
                    let res = handle.await.unwrap()?;
                    Ok(res.map(|_| body))
                }
                Err(e) => {
                    let _ = tx2.send(Err(e));
                    let res = handle.await.unwrap()?;
                    Ok(res.map(|_| todo!("there is no support for body type yet")))
                }
            }
        }
    }

    impl<F, S> ReadyService for SyncService<F, S>
    where
        S: ReadyService,
    {
        type Ready = S::Ready;

        #[inline]
        async fn ready(&self) -> Self::Ready {
            self.service.ready().await
        }
    }
}

#[cfg(test)]
mod test {
    use core::convert::Infallible;

    use crate::{
        body::ResponseBody,
        http::{StatusCode, WebResponse},
        service::fn_service,
        App,
    };

    use super::*;

    async fn handler(req: WebContext<'_, &'static str>) -> Result<WebResponse, Infallible> {
        assert_eq!(*req.state(), "996");
        Ok(req.into_response(ResponseBody::empty()))
    }

    fn middleware<E>(next: &mut Next<E>, ctx: WebContext<'_, &'static str>) -> Result<Response<()>, E> {
        next.call(ctx)
    }

    #[tokio::test]
    async fn sync_middleware() {
        let res = App::new()
            .with_state("996")
            .at("/", fn_service(handler))
            .enclosed(SyncMiddleware::new(middleware))
            .finish()
            .call(())
            .await
            .unwrap()
            .call(Request::default())
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::OK);
    }
}