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