credence_lib/middleware/
socket.rs

1use {axum::extract::*, bytestring::*, compris::normal::*};
2
3//
4// SocketMiddleware
5//
6
7/// Axum middleware that attaches [Socket] information as an extension to requests.
8///
9/// Unfortunately, this information is normally stripped from requests (by Hyper?) by the time
10/// it reaches axum routers. This workaround is provided without commentary on that upstream design
11/// decision.
12#[derive(Clone, Debug)]
13pub struct SocketMiddleware {
14    /// Socket.
15    pub socket: Socket,
16}
17
18impl SocketMiddleware {
19    /// Constructor.
20    pub fn new(socket: Socket) -> Self {
21        Self { socket }
22    }
23
24    /// To be used with [map_request_with_state].
25    pub async fn function(State(state_self): State<Self>, mut request: Request) -> Request {
26        request.extensions_mut().insert(state_self.socket.clone());
27        request
28    }
29}
30
31//
32// Socket
33//
34
35/// Socket.
36#[derive(Clone, Debug)]
37pub struct Socket {
38    /// TCP port.
39    pub port: u16,
40
41    /// Whether TLS is enabled ("https").
42    pub tls: bool,
43
44    /// Host.
45    pub host: ByteString,
46}
47
48impl Socket {
49    /// Constructor.
50    pub fn new(port: u16, tls: bool, host: ByteString) -> Self {
51        Self { port, tls, host }
52    }
53}
54
55impl Into<Value> for &Socket {
56    fn into(self) -> Value {
57        let mut socket_map = Map::new();
58        socket_map.value.insert("port".into(), self.port.into());
59        socket_map.value.insert("tls".into(), self.tls.into());
60        socket_map.value.insert("host".into(), self.host.clone().into());
61        socket_map.into()
62    }
63}