prosa-hyper 0.3.0

ProSA Hyper processor for HTTP client/server
Documentation
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::{
    convert::Infallible,
    io,
    os::fd::AsRawFd,
    sync::Arc,
    time::{Duration, Instant},
};

use bytes::Bytes;
use http_body_util::combinators::BoxBody;
use hyper::{
    Request,
    client::conn::{http1, http2},
};
use hyper_util::rt::{TokioExecutor, TokioIo};
use opentelemetry::{KeyValue, metrics::Histogram};
use prosa::{
    core::{
        adaptor::Adaptor,
        msg::{InternalMsg, Msg as _, RequestMsg},
        proc::{ProcBusParam as _, ProcParam},
        service::ServiceError,
    },
    io::{
        SslConfig,
        stream::{Stream, TargetSetting},
        url_is_ssl,
    },
};
use tokio::{
    task::JoinSet,
    time::{self, timeout},
};
use tracing::{debug, info, warn};

use crate::{H2, HyperProcError, client::adaptor::HyperClientAdaptor, hyper_version_str};

/// Type alias for HTTP request pair to reduce type complexity
type HttpRequestPair<M> = (RequestMsg<M>, Request<BoxBody<Bytes, Infallible>>);

/// Hyper client socket
#[derive(Debug, Clone)]
pub struct HyperClientSocket {
    /// Target of the socket
    target: TargetSetting,
    /// Whether the socket is using HTTP/2
    is_http2: bool,
    /// HTTP message timeout duration
    http_timeout: Duration,
}

macro_rules! close_socket {
    ($self:ident, $proc:ident, $socket_id:ident, $msg_queue:ident, $service_name:ident, $return:expr) => {
        $proc.remove_proc_queue($socket_id as u32).await?;
        while let Ok(msg) = $msg_queue.try_recv() {
            if let InternalMsg::Request(req_msg) = msg {
                let _ = req_msg.return_error_to_sender(
                    None,
                    ServiceError::UnableToReachService($service_name.clone()),
                );
            }
        }
        return $return;
    };
}

impl HyperClientSocket {
    pub fn new(mut target: TargetSetting, http_timeout: u64) -> Self {
        // Set default protocol to HTTP2 if target enabled SSL
        if let Some(ssl) = target.ssl.as_mut() {
            info!(
                "Target {} enable SSL, set ALPN to support HTTP/2 and HTTP/1.1",
                target.url
            );
            ssl.set_alpn(vec!["h2".into(), "http/1.1".into()]);
        } else if url_is_ssl(&target.url) {
            let mut ssl = SslConfig::default();
            ssl.set_alpn(vec!["h2".into(), "http/1.1".into()]);
            target.ssl = Some(ssl);
        }

        HyperClientSocket {
            target,
            is_http2: false,
            http_timeout: Duration::from_millis(http_timeout),
        }
    }

    /// Helper to setup socket queue and service registration
    async fn setup_socket_queue<M>(
        proc: &Arc<ProcParam<M>>,
        socket_id: u32,
        service_name: &str,
    ) -> Result<tokio::sync::mpsc::Receiver<InternalMsg<M>>, HyperProcError>
    where
        M: 'static
            + std::marker::Send
            + std::marker::Sync
            + std::marker::Sized
            + std::clone::Clone
            + std::fmt::Debug
            + prosa::core::msg::Tvf
            + std::default::Default,
    {
        let (tx_queue, rx_queue) = tokio::sync::mpsc::channel(2048);
        proc.add_proc_queue(tx_queue, socket_id).await?;
        proc.add_service(vec![service_name.to_string()], socket_id)
            .await?;
        Ok(rx_queue)
    }

    /// Helper to process a service request into an HTTP request
    fn process_request<M, A>(
        adaptor: &Arc<A>,
        mut msg: RequestMsg<M>,
        target_url: &url::Url,
        service_name: &str,
    ) -> Option<HttpRequestPair<M>>
    where
        M: 'static
            + std::marker::Send
            + std::marker::Sync
            + std::marker::Sized
            + std::clone::Clone
            + std::fmt::Debug
            + prosa::core::msg::Tvf
            + std::default::Default,
        A: 'static + HyperClientAdaptor<M> + std::marker::Send + std::marker::Sync,
    {
        if let Some(data) = msg.take_data() {
            match adaptor.process_srv_request(data, target_url) {
                Ok(http_request) => Some((msg, http_request)),
                Err(e) => {
                    let _ = msg.return_error_to_sender(None, e);
                    None
                }
            }
        } else {
            let _ = msg.return_error_to_sender(
                None,
                ServiceError::UnableToReachService(service_name.to_string()),
            );
            None
        }
    }

    /// Helper to handle handshake timeout errors
    fn handle_handshake_timeout(
        socket_id: i32,
        target_addr: &str,
        timeout_ms: u64,
        protocol: &str,
    ) -> HyperProcError {
        warn!(
            socket_id = socket_id,
            addr = target_addr,
            "{protocol} handshake timeout after {timeout_ms} ms"
        );
        HyperProcError::Io(io::Error::new(
            io::ErrorKind::TimedOut,
            format!("{protocol} handshake timeout after {timeout_ms} ms"),
        ))
    }

    /// Helper to handle handshake errors
    fn handle_handshake_error(
        socket_id: i32,
        target_addr: &str,
        error: hyper::Error,
        protocol: &str,
    ) -> HyperProcError {
        warn!(
            socket_id = socket_id,
            addr = target_addr,
            "{protocol} handshake error: {error}"
        );
        HyperProcError::Hyper(error, target_addr.to_string())
    }

    /// Method to spawn a task that handle the Hyper client socket with HTTP/1.1
    async fn spawn_http1<M, A>(
        self,
        io: TokioIo<Stream>,
        proc: Arc<ProcParam<M>>,
        adaptor: Arc<A>,
        service_name: String,
        message_histogram: Histogram<u64>,
    ) -> Result<HyperClientSocket, HyperProcError>
    where
        M: 'static
            + std::marker::Send
            + std::marker::Sync
            + std::marker::Sized
            + std::clone::Clone
            + std::fmt::Debug
            + prosa::core::msg::Tvf
            + std::default::Default,
        A: 'static + Adaptor + HyperClientAdaptor<M> + std::marker::Send + std::marker::Sync,
    {
        let socket_id = io.inner().as_raw_fd();
        let target_addr = self.target.to_string();
        match time::timeout(
            Duration::from_millis(self.target.connect_timeout),
            http1::handshake(io),
        )
        .await
        {
            Ok(Ok((mut sender, mut connection))) => {
                debug!(
                    socket_id = socket_id,
                    addr = target_addr,
                    "Connected to HTTP1 remote"
                );
                let mut rx_queue =
                    Self::setup_socket_queue(&proc, socket_id as u32, &service_name).await?;
                debug!(
                    socket_id = socket_id,
                    addr = target_addr,
                    "HTTP client expose service name: {}",
                    service_name
                );
                let mut msg_to_send: Option<HttpRequestPair<M>> = None;
                let mut req_instant = Instant::now();

                loop {
                    if let Some((msg, http_request)) = msg_to_send.take() {
                        let http_log = http_request.uri().to_string();
                        tokio::select! {
                            // Closed the socket
                            Err(_) = &mut connection => {
                                debug!(socket_id = socket_id, addr = target_addr, "Remote HTTP1 close the socket");
                                close_socket!(self, proc, socket_id, rx_queue, service_name, Ok(self));
                            }
                            // Send an HTTP request
                            response_sent = timeout(self.http_timeout, sender.send_request(http_request)) => {
                                match response_sent {
                                    Ok(response) => {
                                        let (code, version) = response.as_ref().map_or((500, "HTTP/1"), |r| (r.status().as_u16() as i64, hyper_version_str(r.version())));
                                        message_histogram.record(
                                            req_instant.elapsed().as_millis() as u64,
                                            &[
                                                KeyValue::new("target", target_addr.clone()),
                                                KeyValue::new("code", code),
                                                KeyValue::new("version", version),
                                            ],
                                        );

                                        match adaptor.process_http_response(response).await {
                                            Ok(r) => {
                                                let _ = msg.return_to_sender(r);
                                            },
                                            Err(e) => {
                                                let _ = msg.return_error_to_sender(None, e);
                                            }
                                        }
                                    },
                                    Err(elapsed) => {
                                        info!(socket_id = socket_id, addr = target_addr, "Message timeout after {} ms: {:?} - {}", elapsed, msg, http_log);
                                        let _ = msg.return_error_to_sender(None, ServiceError::Timeout(service_name.clone(), self.http_timeout.as_millis() as u64));
                                        // Need to drop the connection because it's HTTP1
                                        close_socket!(self, proc, socket_id, rx_queue, service_name, Ok(self));
                                    },
                                };
                            }
                        }
                    } else {
                        tokio::select! {
                            // Closed the socket
                            Err(_) = &mut connection => {
                                debug!(socket_id = socket_id, addr = target_addr, "Remote close the socket");
                                close_socket!(self, proc, socket_id, rx_queue, service_name, Ok(self));
                            }
                            // Receive a message to send from the queue
                            Some(msg) = rx_queue.recv() => {
                                debug!(socket_id = socket_id, addr = target_addr, "HTTP client receive a message to send: {:?}", msg);
                                match msg {
                                    InternalMsg::Request(req_msg) => {
                                        if let Some(result) = Self::process_request(&adaptor, req_msg, &self.target.url, &service_name) {
                                            msg_to_send = Some(result);
                                            req_instant = Instant::now();
                                        }
                                    },
                                    InternalMsg::Response(msg) => panic!(
                                        "The HTTP1 hyper client socket {}/{socket_id} receive a response {:?}",
                                        proc.get_proc_id(),
                                        msg
                                    ),
                                    InternalMsg::Error(err_msg) => panic!(
                                        "The HTTP1 hyper client socket {}/{socket_id} receive an error {:?}",
                                        proc.get_proc_id(),
                                        err_msg
                                    ),
                                    InternalMsg::Command(_) | InternalMsg::Config => {
                                        // TODO: Implement Command/Config handling or document as unsupported
                                    },
                                    InternalMsg::Service(_table) => {/* Will not use service table */},
                                    InternalMsg::Shutdown => {
                                        // Remove the socket queue and wait message to finish
                                        close_socket!(self, proc, socket_id, rx_queue, service_name, Ok(self));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Ok(Err(e)) => Err(Self::handle_handshake_error(
                socket_id,
                &target_addr,
                e,
                "HTTP1",
            )),
            Err(_) => Err(Self::handle_handshake_timeout(
                socket_id,
                &target_addr,
                self.target.connect_timeout,
                "HTTP1",
            )),
        }
    }

    /// Method to spawn a task that handle the Hyper client socket with HTTP/2
    async fn spawn_h2<M, A>(
        mut self,
        io: TokioIo<Stream>,
        proc: Arc<ProcParam<M>>,
        adaptor: Arc<A>,
        service_name: String,
        message_histogram: Histogram<u64>,
    ) -> Result<HyperClientSocket, HyperProcError>
    where
        M: 'static
            + std::marker::Send
            + std::marker::Sync
            + std::marker::Sized
            + std::clone::Clone
            + std::fmt::Debug
            + prosa::core::msg::Tvf
            + std::default::Default,
        A: 'static + Adaptor + HyperClientAdaptor<M> + std::marker::Send + std::marker::Sync,
    {
        let socket_id = io.inner().as_raw_fd();
        let target_addr = self.target.to_string();
        self.is_http2 = true;
        match time::timeout(
            Duration::from_millis(self.target.connect_timeout),
            http2::handshake(TokioExecutor::new(), io),
        )
        .await
        {
            Ok(Ok((sender, mut connection))) => {
                debug!(
                    socket_id = socket_id,
                    addr = target_addr,
                    "Connected to HTTP2 remote"
                );
                let mut rx_queue =
                    Self::setup_socket_queue(&proc, socket_id as u32, &service_name).await?;

                loop {
                    tokio::select! {
                        // Closed the socket
                        Err(_) = &mut connection => {
                            debug!(socket_id = socket_id, addr = target_addr, "Remote HTTP2 close the socket");
                            close_socket!(self, proc, socket_id, rx_queue, service_name, Ok(self));
                        }
                        // Receive a message to send from the queue
                        Some(msg) = rx_queue.recv() => {
                            match msg {
                                InternalMsg::Request(mut req_msg) => {
                                    if let Some(data) = req_msg.take_data() {
                                        let req_instant = Instant::now();
                                        let mut sender = sender.clone();
                                        let adaptor = adaptor.clone();
                                        let target_url = self.target.url.clone();
                                        let message_histogram = message_histogram.clone();
                                        let http_timeout = self.http_timeout;
                                        let service_name_clone = service_name.clone();

                                        tokio::spawn(async move {
                                            match adaptor.process_srv_request(data, &target_url) {
                                                Ok(http_request) => {
                                                    match timeout(http_timeout, sender.send_request(http_request)).await {
                                                        Ok(http_response) => {
                                                            let (code, version) = http_response.as_ref().map_or((500, "HTTP/2"), |r| (r.status().as_u16() as i64, hyper_version_str(r.version())));
                                                            message_histogram.record(
                                                                req_instant.elapsed().as_millis() as u64,
                                                                &[
                                                                    KeyValue::new("target", target_url.to_string()),
                                                                    KeyValue::new("code", code),
                                                                    KeyValue::new("version", version),
                                                                ],
                                                            );

                                                            match adaptor.process_http_response(http_response).await {
                                                                Ok(response) => {
                                                                    let _ = req_msg.return_to_sender(response);
                                                                },
                                                                Err(e) => { let _ = req_msg.return_error_to_sender(None, e); },
                                                            }
                                                        },
                                                        Err(_) => { let _ = req_msg.return_error_to_sender(None, ServiceError::Timeout(service_name_clone, http_timeout.as_millis() as u64)); },
                                                    };
                                                },
                                                Err(e) => {
                                                    let _ = req_msg.return_error_to_sender(None, e);
                                                },
                                            }
                                        });
                                    } else {
                                        let _ = req_msg.return_error_to_sender(None, ServiceError::UnableToReachService(service_name.clone()));
                                    }
                                },
                                InternalMsg::Response(msg) => panic!(
                                    "The H2 hyper client socket {}/{socket_id} receive a response {:?}",
                                    proc.get_proc_id(),
                                    msg
                                ),
                                InternalMsg::Error(err_msg) => panic!(
                                    "The H2 hyper client socket {}/{socket_id} receive an error {:?}",
                                    proc.get_proc_id(),
                                    err_msg
                                ),
                                InternalMsg::Command(_) | InternalMsg::Config => {
                                    // TODO: Implement Command/Config handling or document as unsupported
                                },
                                InternalMsg::Service(_table) => {/* Will not use service table */},
                                InternalMsg::Shutdown => {
                                    // Remove the socket queue and wait message to finish
                                    close_socket!(self, proc, socket_id, rx_queue, service_name, Ok(self));
                                }
                            }
                        }
                    }
                }
            }
            Ok(Err(e)) => Err(Self::handle_handshake_error(
                socket_id,
                &target_addr,
                e,
                "HTTP2",
            )),
            Err(_) => Err(Self::handle_handshake_timeout(
                socket_id,
                &target_addr,
                self.target.connect_timeout,
                "HTTP2",
            )),
        }
    }

    /// Method to spawn a task to handle the Hyper client socket
    pub fn spawn<M, A>(
        self,
        join_set: &mut JoinSet<Result<Self, HyperProcError>>,
        proc: Arc<ProcParam<M>>,
        adaptor: Arc<A>,
        service_name: String,
        message_histogram: Histogram<u64>,
    ) where
        M: 'static
            + std::marker::Send
            + std::marker::Sync
            + std::marker::Sized
            + std::clone::Clone
            + std::fmt::Debug
            + prosa::core::msg::Tvf
            + std::default::Default,
        A: 'static + Adaptor + HyperClientAdaptor<M> + std::marker::Send + std::marker::Sync,
    {
        join_set.spawn(async move {
            let io = TokioIo::new(self.target.connect().await?);
            if io.inner().selected_alpn_check(|alpn| alpn == H2) {
                self.spawn_h2::<M, A>(io, proc, adaptor, service_name, message_histogram)
                    .await
            } else {
                self.spawn_http1::<M, A>(io, proc, adaptor, service_name, message_histogram)
                    .await
            }
        });
    }
}