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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use std::{convert::Infallible, pin::Pin};

use async_stream::stream;
use axum::{
    body::{HttpBody, StreamBody},
    http::{header, Request, StatusCode},
    response::{IntoResponse, Response},
    BoxError,
};
use futures::{Future, Stream, StreamExt};
use prost::Message;
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    error::RpcIntoError,
    parts::RpcFromRequestParts,
    prelude::{RpcError, RpcErrorCode},
    response::RpcIntoResponse,
};

use super::codec::{
    decode_check_headers, decode_request_payload, encode_error, encode_error_response, ReqResInto,
};

pub trait RpcHandlerStream<TMReq, TMRes, TUid, TState, TBody>:
    Clone + Send + Sized + 'static
{
    type Future: Future<Output = Response> + Send + 'static;

    fn call(self, req: Request<TBody>, state: TState) -> Self::Future;
}

// TODO: Get "connect-timeout-ms" (number as string) and apply timeout.
// TODO: Parse request metadata from:
//      - [0-9a-z]*!"-bin" ASCII value
//      - [0-9a-z]*-bin" (base64 encoded binary)
// TODO: Allow response to send back both leading and trailing metadata.
// This is here because writing Rust macros sucks a**. So I uncomment this when I'm trying to modify
// the below macro.
// #[allow(unused_parens, non_snake_case, unused_mut)]
// impl<TMReq, TMRes, TInto, TFnItem, TFnFut, TFn, TState, TBody, T1>
//     RpcHandlerStream<TMReq, TMRes, (T1, TMReq), TState, TBody> for TFn
// where
//     TMReq: Message + DeserializeOwned + Default + Send + 'static,
//     TMRes: Message + Serialize + Send + 'static,
//     TInto: RpcIntoResponse<TMRes>,
//     TFnItem: Stream<Item = TInto> + Send + Sized + 'static,
//     TFnFut: Future<Output = TFnItem> + Send + Sync,
//     TFn: FnOnce(T1, TMReq) -> TFnFut + Clone + Send + Sync + 'static,
//     TBody: HttpBody + Send + Sync + 'static,
//     TBody::Data: Send,
//     TBody::Error: Into<BoxError>,
//     TState: Send + Sync + 'static,
//     T1: RpcFromRequestParts<TMRes, TState> + Send,
// {
//     type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

//     fn call(self, req: Request<TBody>, state: TState) -> Self::Future {
//         Box::pin(async move {
//             let (mut parts, body) = req.into_parts();

//             let ReqResInto { binary } = match decode_check_headers(&mut parts, true) {
//                 Ok(binary) => binary,
//                 Err(e) => return e,
//             };

//             let state = &state;

//             let t1 = match T1::rpc_from_request_parts(&mut parts, state).await {
//                 Ok(value) => value,
//                 Err(e) => {
//                     let e = e.rpc_into_error();
//                     return encode_error_response(&e, binary, true);
//                 }
//             };

//             let req = Request::from_parts(parts, body);

//             let proto_req: TMReq = match decode_request_payload(req, state, binary, true).await {
//                 Ok(value) => value,
//                 Err(e) => return e,
//             };

//             let mut res = Box::pin(self(t1, proto_req).await);

//             let res = stream! {
//                 while let Some(item) = res.next().await {
//                     let rpc_item = item.rpc_into_response();
//                     match rpc_item {
//                         Ok(rpc_item) => {
//                             if binary {
//                                 let mut res = vec![0x2, 0, 0, 0, 0];
//                                 if let Err(e) = rpc_item.encode(&mut res) {
//                                     let e = RpcError::new(RpcErrorCode::Internal, e.to_string());
//                                     yield Result::<Vec<u8>, Infallible>::Ok(encode_error(&e, true));
//                                     break;
//                                 }
//                                 let size = ((res.len() - 5) as u32).to_be_bytes();
//                                 res[1..5].copy_from_slice(&size);
//                                 yield Ok(res);
//                             } else {
//                                 let mut res = vec![0x2, 0, 0, 0, 0];
//                                 if let Err(e) = serde_json::to_writer(&mut res, &rpc_item) {
//                                     let e = RpcError::new(RpcErrorCode::Internal, e.to_string());
//                                     yield Ok(encode_error(&e, true));
//                                     break;
//                                 }
//                                 let size = ((res.len() - 5) as u32).to_be_bytes();
//                                 res[1..5].copy_from_slice(&size);
//                                 yield Ok(res);
//                             }
//                         },
//                         Err(e) => {
//                             yield Ok(encode_error(&e, binary));
//                             break;
//                         }
//                     }
//                 }

//                 // EndStreamResponse, see: https://connect.build/docs/protocol/#error-end-stream
//                 // TODO: Support returning trailers (they would need to bundle in the error type).
//                 if binary {
//                     yield Result::<Vec<u8>, Infallible>::Ok(vec![0x2, 0, 0, 0, 0]);
//                 } else {
//                     yield Result::<Vec<u8>, Infallible>::Ok(vec![0x2, 0, 0, 0, 2, b'{', b'}']);
//                 }
//             };

//             (
//                 StatusCode::OK,
//                 [(
//                     header::CONTENT_TYPE,
//                     if binary {
//                         "application/connect+proto"
//                     } else {
//                         "application/connect+json"
//                     },
//                 )],
//                 StreamBody::new(res),
//             )
//                 .into_response()
//         })
//     }
// }

macro_rules! impl_handler {
    (
        [$($ty:ident),*]
    ) => {
        #[allow(unused_parens, non_snake_case, unused_mut)]
        impl<TMReq, TMRes, TInto, TFnItem, TFnFut, TFn, TState, TBody, $($ty,)*>
            RpcHandlerStream<TMReq, TMRes, ($($ty,)* TMReq), TState, TBody> for TFn
        where
            TMReq: Message + DeserializeOwned + Default + Send + 'static,
            TMRes: Message + Serialize + Send + 'static,
            TInto: RpcIntoResponse<TMRes>,
            TFnItem: Stream<Item = TInto> + Send + Sized + 'static,
            TFnFut: Future<Output = TFnItem> + Send + Sync,
            TFn: FnOnce($($ty,)* TMReq) -> TFnFut + Clone + Send + Sync + 'static,
            TBody: HttpBody + Send + Sync + 'static,
            TBody::Data: Send,
            TBody::Error: Into<BoxError>,
            TState: Send + Sync + 'static,
            $( $ty: RpcFromRequestParts<TMRes, TState> + Send, )*
        {

            type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

            fn call(self, req: Request<TBody>, state: TState) -> Self::Future {
                Box::pin(async move {
                    let (mut parts, body) = req.into_parts();

                    let ReqResInto { binary } = match decode_check_headers(&mut parts, true) {
                        Ok(binary) => binary,
                        Err(e) => return e,
                    };

                    let state = &state;

                    $(
                    let $ty = match $ty::rpc_from_request_parts(&mut parts, state).await {
                        Ok(value) => value,
                        Err(e) => {
                            let e = e.rpc_into_error();
                            return encode_error_response(&e, binary, true);
                        }
                    };
                    )*

                    let req = Request::from_parts(parts, body);

                    let proto_req: TMReq = match decode_request_payload(req, state, binary, true).await {
                        Ok(value) => value,
                        Err(e) => return e,
                    };

                    let mut res = Box::pin(self($($ty,)* proto_req).await);

                    let res = stream! {
                        while let Some(item) = res.next().await {
                            let rpc_item = item.rpc_into_response();
                            match rpc_item {
                                Ok(rpc_item) => {
                                    if binary {
                                        let mut res = vec![0x2, 0, 0, 0, 0];
                                        if let Err(e) = rpc_item.encode(&mut res) {
                                            let e = RpcError::new(RpcErrorCode::Internal, e.to_string());
                                            yield Result::<Vec<u8>, Infallible>::Ok(encode_error(&e, true));
                                            break;
                                        }
                                        let size = ((res.len() - 5) as u32).to_be_bytes();
                                        res[1..5].copy_from_slice(&size);
                                        yield Ok(res);
                                    } else {
                                        let mut res = vec![0x2, 0, 0, 0, 0];
                                        if let Err(e) = serde_json::to_writer(&mut res, &rpc_item) {
                                            let e = RpcError::new(RpcErrorCode::Internal, e.to_string());
                                            yield Ok(encode_error(&e, true));
                                            break;
                                        }
                                        let size = ((res.len() - 5) as u32).to_be_bytes();
                                        res[1..5].copy_from_slice(&size);
                                        yield Ok(res);
                                    }
                                },
                                Err(e) => {
                                    yield Ok(encode_error(&e, binary));
                                    break;
                                }
                            }
                        }

                        // EndStreamResponse, see: https://connect.build/docs/protocol/#error-end-stream
                        // TODO: Support returning trailers (they would need to bundle in the error type).
                        if binary {
                            yield Result::<Vec<u8>, Infallible>::Ok(vec![0x2, 0, 0, 0, 0]);
                        } else {
                            yield Result::<Vec<u8>, Infallible>::Ok(vec![0x2, 0, 0, 0, 2, b'{', b'}']);
                        }
                    };

                    (
                        StatusCode::OK,
                        [(
                            header::CONTENT_TYPE,
                            if binary {
                                "application/connect+proto"
                            } else {
                                "application/connect+json"
                            },
                        )],
                        StreamBody::new(res),
                    )
                        .into_response()
                })
            }
        }
    };
}

impl_handler!([]);
impl_handler!([T1]);
impl_handler!([T1, T2]);
impl_handler!([T1, T2, T3]);
impl_handler!([T1, T2, T3, T4]);
impl_handler!([T1, T2, T3, T4, T5]);
impl_handler!([T1, T2, T3, T4, T5, T6]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]);