credence_lib/middleware/
socket.rs

1use {axum::extract::*, compris::normal::*, kutil::std::immutable::*};
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](axum::middleware::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<AnnotatedT> Into<Variant<AnnotatedT>> for &Socket
56where
57    AnnotatedT: Default,
58{
59    fn into(self) -> Variant<AnnotatedT> {
60        let mut socket_map = Map::default();
61        socket_map.into_insert("port", self.port);
62        socket_map.into_insert("tls", self.tls);
63        socket_map.into_insert("host", self.host.clone());
64        socket_map.into()
65    }
66}