sui_http/
connection_info.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::HashMap;
5use std::sync::Arc;
6use std::sync::RwLock;
7use tokio_rustls::rustls::pki_types::CertificateDer;
8
9pub(crate) type ActiveConnections<A = std::net::SocketAddr> =
10    Arc<RwLock<HashMap<ConnectionId, ConnectionInfo<A>>>>;
11
12pub type ConnectionId = usize;
13
14#[derive(Debug)]
15pub struct ConnectionInfo<A>(Arc<Inner<A>>);
16
17#[derive(Clone, Debug)]
18pub struct PeerCertificates(Arc<Vec<tokio_rustls::rustls::pki_types::CertificateDer<'static>>>);
19
20impl PeerCertificates {
21    pub fn peer_certs(&self) -> &[tokio_rustls::rustls::pki_types::CertificateDer<'static>] {
22        self.0.as_ref()
23    }
24}
25
26impl<A> ConnectionInfo<A> {
27    pub(crate) fn new(
28        address: A,
29        peer_certificates: Option<Arc<Vec<CertificateDer<'static>>>>,
30        graceful_shutdown_token: tokio_util::sync::CancellationToken,
31    ) -> Self {
32        Self(Arc::new(Inner {
33            address,
34            time_established: std::time::Instant::now(),
35            peer_certificates: peer_certificates.map(PeerCertificates),
36            graceful_shutdown_token,
37        }))
38    }
39
40    /// The peer's remote address
41    pub fn remote_address(&self) -> &A {
42        &self.0.address
43    }
44
45    /// Time the Connection was established
46    pub fn time_established(&self) -> std::time::Instant {
47        self.0.time_established
48    }
49
50    pub fn peer_certificates(&self) -> Option<&PeerCertificates> {
51        self.0.peer_certificates.as_ref()
52    }
53
54    /// A stable identifier for this connection
55    pub fn id(&self) -> ConnectionId {
56        &*self.0 as *const _ as usize
57    }
58
59    /// Trigger a graceful shutdown of this connection
60    pub fn close(&self) {
61        self.0.graceful_shutdown_token.cancel()
62    }
63}
64
65#[derive(Debug)]
66struct Inner<A = std::net::SocketAddr> {
67    address: A,
68
69    // Time that the connection was established
70    time_established: std::time::Instant,
71
72    peer_certificates: Option<PeerCertificates>,
73    graceful_shutdown_token: tokio_util::sync::CancellationToken,
74}
75
76#[derive(Debug, Clone)]
77pub struct ConnectInfo<A = std::net::SocketAddr> {
78    /// Returns the local address of this connection.
79    pub local_addr: A,
80    /// Returns the remote (peer) address of this connection.
81    pub remote_addr: A,
82}
83
84impl<A> ConnectInfo<A> {
85    /// Return the local address the IO resource is connected.
86    pub fn local_addr(&self) -> &A {
87        &self.local_addr
88    }
89
90    /// Return the remote address the IO resource is connected too.
91    pub fn remote_addr(&self) -> &A {
92        &self.remote_addr
93    }
94}