iota_http/
connection_info.rs

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