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
186
use std::io;
use std::mem::transmute;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Poll, Context};

use futures::future::BoxFuture;
use http::request::Parts;
use tokio::io::{AsyncRead, ReadBuf};

use crate::data::{Data, IoHandler, RawStream};
use crate::{Request, Response, Rocket, Orbit};

// TODO: Magic with trait async fn to get rid of the box pin.
// TODO: Write safety proofs.

macro_rules! static_assert_covariance {
    ($($T:tt)*) => (
        const _: () = {
            fn _assert_covariance<'x: 'y, 'y>(x: &'y $($T)*<'x>) -> &'y $($T)*<'y> { x }
        };
    )
}

#[derive(Debug)]
pub struct ErasedRequest {
    // XXX: SAFETY: This (dependent) field must come first due to drop order!
    request: Request<'static>,
    _rocket: Arc<Rocket<Orbit>>,
    _parts: Box<Parts>,
}

impl Drop for ErasedRequest {
    fn drop(&mut self) { }
}

#[derive(Debug)]
pub struct ErasedResponse {
    // XXX: SAFETY: This (dependent) field must come first due to drop order!
    response: Response<'static>,
    _request: Arc<ErasedRequest>,
}

impl Drop for ErasedResponse {
    fn drop(&mut self) { }
}

pub struct ErasedIoHandler {
    // XXX: SAFETY: This (dependent) field must come first due to drop order!
    io: Box<dyn IoHandler + 'static>,
    _request: Arc<ErasedRequest>,
}

impl Drop for ErasedIoHandler {
    fn drop(&mut self) { }
}

impl ErasedRequest {
    pub fn new(
        rocket: Arc<Rocket<Orbit>>,
        parts: Parts,
        constructor: impl for<'r> FnOnce(
            &'r Rocket<Orbit>,
            &'r Parts
        ) -> Request<'r>,
    ) -> ErasedRequest {
        let rocket: Arc<Rocket<Orbit>> = rocket;
        let parts: Box<Parts> = Box::new(parts);
        let request: Request<'_> = {
            let rocket: &Rocket<Orbit> = &rocket;
            let rocket: &'static Rocket<Orbit> = unsafe { transmute(rocket) };
            let parts: &Parts = &parts;
            let parts: &'static Parts = unsafe { transmute(parts) };
            constructor(rocket, parts)
        };

        ErasedRequest { _rocket: rocket, _parts: parts, request, }
    }

    pub async fn into_response<T, D>(
        self,
        raw_stream: D,
        preprocess: impl for<'r, 'x> FnOnce(
            &'r Rocket<Orbit>,
            &'r mut Request<'x>,
            &'r mut Data<'x>
        ) -> BoxFuture<'r, T>,
        dispatch: impl for<'r> FnOnce(
            T,
            &'r Rocket<Orbit>,
            &'r Request<'r>,
            Data<'r>
        ) -> BoxFuture<'r, Response<'r>>,
    ) -> ErasedResponse
        where T: Send + Sync + 'static,
              D: for<'r> Into<RawStream<'r>>
    {
        let mut data: Data<'_> = Data::from(raw_stream);
        let mut parent = Arc::new(self);
        let token: T = {
            let parent: &mut ErasedRequest = Arc::get_mut(&mut parent).unwrap();
            let rocket: &Rocket<Orbit> = &parent._rocket;
            let request: &mut Request<'_> = &mut parent.request;
            let data: &mut Data<'_> = &mut data;
            preprocess(rocket, request, data).await
        };

        let parent = parent;
        let response: Response<'_> = {
            let parent: &ErasedRequest = &parent;
            let parent: &'static ErasedRequest = unsafe { transmute(parent) };
            let rocket: &Rocket<Orbit> = &parent._rocket;
            let request: &Request<'_> = &parent.request;
            dispatch(token, rocket, request, data).await
        };

        ErasedResponse {
            _request: parent,
            response,
        }
    }
}

impl ErasedResponse {
    pub fn inner(&self) -> &Response<'_> {
        static_assert_covariance!(Response);
        &self.response
    }

    pub fn with_inner_mut<'a, T>(
        &'a mut self,
        f: impl for<'r> FnOnce(&'a mut Response<'r>) -> T
    ) -> T {
        static_assert_covariance!(Response);
        f(&mut self.response)
    }

    pub fn make_io_handler<'a>(
        &'a mut self,
        constructor: impl for<'r> FnOnce(
            &'r Request<'r>,
            &'a mut Response<'r>,
        ) -> Option<Box<dyn IoHandler + 'r>>
    ) -> Option<ErasedIoHandler> {
        let parent: Arc<ErasedRequest> = self._request.clone();
        let io: Option<Box<dyn IoHandler + '_>> = {
            let parent: &ErasedRequest = &parent;
            let parent: &'static ErasedRequest = unsafe { transmute(parent) };
            let request: &Request<'_> = &parent.request;
            constructor(request, &mut self.response)
        };

        io.map(|io| ErasedIoHandler { _request: parent, io })
    }
}

impl ErasedIoHandler {
    pub fn with_inner_mut<'a, T: 'a>(
        &'a mut self,
        f: impl for<'r> FnOnce(&'a mut Box<dyn IoHandler + 'r>) -> T
    ) -> T {
        fn _assert_covariance<'x: 'y, 'y>(
            x: &'y Box<dyn IoHandler + 'x>
        ) -> &'y Box<dyn IoHandler + 'y> { x }

        f(&mut self.io)
    }

    pub fn take<'a>(&'a mut self) -> Box<dyn IoHandler + 'a> {
        fn _assert_covariance<'x: 'y, 'y>(
            x: &'y Box<dyn IoHandler + 'x>
        ) -> &'y Box<dyn IoHandler + 'y> { x }

        self.with_inner_mut(|handler| std::mem::replace(handler, Box::new(())))
    }
}

impl AsyncRead for ErasedResponse {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        self.get_mut().with_inner_mut(|r| Pin::new(r.body_mut()).poll_read(cx, buf))
    }
}