lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

connections.rs (6760B)


      1 //! Bounded connection registration and synchronous completion cleanup.
      2 
      3 use std::{
      4     collections::BTreeMap,
      5     fmt,
      6     sync::{
      7         Arc, Mutex,
      8         atomic::{AtomicBool, AtomicUsize, Ordering},
      9     },
     10 };
     11 
     12 pub(crate) struct Connections {
     13     closed: AtomicBool,
     14     active: AtomicUsize,
     15     maximum: usize,
     16     relays: Mutex<BTreeMap<String, nostr_sdk::relay::Relay>>,
     17 }
     18 
     19 impl Connections {
     20     pub(crate) fn new(maximum: usize) -> Self {
     21         Self {
     22             closed: AtomicBool::new(false),
     23             active: AtomicUsize::new(0),
     24             maximum,
     25             relays: Mutex::new(BTreeMap::new()),
     26         }
     27     }
     28 
     29     pub(crate) fn is_closed(&self) -> bool {
     30         self.closed.load(Ordering::Acquire)
     31     }
     32 
     33     pub(crate) fn has_active_calls(&self) -> bool {
     34         self.active.load(Ordering::Acquire) != 0
     35     }
     36 
     37     pub(crate) fn begin(self: &Arc<Self>) -> Result<Operation, radroots_transport::Error> {
     38         if self.is_closed() {
     39             return Err(radroots_transport::Error::TransportClosed);
     40         }
     41         self.active
     42             .try_update(Ordering::AcqRel, Ordering::Acquire, |count| {
     43                 count.checked_add(1)
     44             })
     45             .map_err(|_| radroots_transport::Error::TransportUnavailable)?;
     46         let operation = Operation(Arc::clone(self));
     47         if self.is_closed() {
     48             return Err(radroots_transport::Error::TransportClosed);
     49         }
     50         Ok(operation)
     51     }
     52 
     53     pub(crate) fn close(&self) {
     54         self.closed.store(true, Ordering::Release);
     55         if !self.has_active_calls() {
     56             self.disconnect();
     57         }
     58     }
     59 
     60     pub(crate) fn register(
     61         &self,
     62         relay: nostr_sdk::relay::Relay,
     63     ) -> Result<(), nostr_sdk::error::Error> {
     64         let mut relays = self.relays.lock().map_err(|_| {
     65             nostr_sdk::error::Error::with_static_message(
     66                 nostr_sdk::error::ErrorKind::State,
     67                 "connection registration is unavailable",
     68             )
     69         })?;
     70         let url = relay.url().to_string();
     71         if !relays.contains_key(&url) && relays.len() >= self.maximum {
     72             return Err(nostr_sdk::error::Error::with_static_message(
     73                 nostr_sdk::error::ErrorKind::LimitExceeded,
     74                 "connection registration limit reached",
     75             ));
     76         }
     77         relays.insert(url, relay);
     78         Ok(())
     79     }
     80 
     81     fn disconnect(&self) {
     82         // Disposal alone may recover poisoned state; it never authorizes work.
     83         let relays = self
     84             .relays
     85             .lock()
     86             .unwrap_or_else(std::sync::PoisonError::into_inner);
     87         for relay in relays.values() {
     88             relay.disconnect();
     89         }
     90     }
     91 }
     92 
     93 impl fmt::Debug for Connections {
     94     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     95         formatter
     96             .debug_struct("Connections")
     97             .field("admission_closed", &self.is_closed())
     98             .field("active_calls", &self.active.load(Ordering::Acquire))
     99             .finish_non_exhaustive()
    100     }
    101 }
    102 
    103 pub(crate) struct Operation(Arc<Connections>);
    104 
    105 impl Drop for Operation {
    106     fn drop(&mut self) {
    107         if self.0.active.fetch_sub(1, Ordering::AcqRel) == 1 && self.0.is_closed() {
    108             self.0.disconnect();
    109         }
    110     }
    111 }
    112 
    113 #[cfg(test)]
    114 mod tests {
    115     use super::*;
    116 
    117     #[test]
    118     fn admission_closes_without_discarding_active_calls() {
    119         let connections = Arc::new(Connections::new(2));
    120         assert!(!connections.has_active_calls());
    121         let first = connections.begin().unwrap();
    122         let second = connections.begin().unwrap();
    123         connections.close();
    124         assert!(connections.is_closed());
    125         assert!(matches!(
    126             connections.begin(),
    127             Err(radroots_transport::Error::TransportClosed)
    128         ));
    129         drop(first);
    130         assert!(connections.has_active_calls());
    131         drop(second);
    132         assert!(!connections.has_active_calls());
    133         connections.close();
    134     }
    135 
    136     #[test]
    137     fn an_open_completed_call_does_not_close_admission_and_overflow_is_explicit() {
    138         let connections = Arc::new(Connections::new(1));
    139         drop(connections.begin().unwrap());
    140         assert!(!connections.is_closed());
    141         assert!(!connections.has_active_calls());
    142         connections.active.store(usize::MAX, Ordering::Release);
    143         assert!(matches!(
    144             connections.begin(),
    145             Err(radroots_transport::Error::TransportUnavailable)
    146         ));
    147         assert_eq!(connections.active.load(Ordering::Acquire), usize::MAX);
    148         connections.active.store(0, Ordering::Release);
    149         connections.close();
    150     }
    151 
    152     #[tokio::test]
    153     async fn registration_is_deduplicated_bounded_and_safe_after_poison() {
    154         let client = nostr_sdk::client::Client::default();
    155         client.add_relay("ws://127.0.0.1:19001").await.unwrap();
    156         client.add_relay("ws://127.0.0.1:19002").await.unwrap();
    157         let first = client.relay("ws://127.0.0.1:19001").await.unwrap().unwrap();
    158         let second = client.relay("ws://127.0.0.1:19002").await.unwrap().unwrap();
    159         let connections = Arc::new(Connections::new(1));
    160         connections.register(first.clone()).unwrap();
    161         connections.register(first.clone()).unwrap();
    162         assert_eq!(connections.relays.lock().unwrap().len(), 1);
    163         assert_eq!(
    164             connections.register(second).unwrap_err().kind(),
    165             nostr_sdk::error::ErrorKind::LimitExceeded
    166         );
    167         let debug = format!("{connections:?}");
    168         assert!(!debug.contains("19001"));
    169         let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
    170             let _held = connections.relays.lock().unwrap();
    171             panic!("poison connection registration");
    172         }));
    173         assert_eq!(
    174             connections.register(first).unwrap_err().kind(),
    175             nostr_sdk::error::ErrorKind::State
    176         );
    177         connections.close();
    178         assert!(connections.is_closed());
    179         client.shutdown().await;
    180     }
    181 
    182     #[test]
    183     fn dropping_a_pending_call_releases_its_registration_without_an_await() {
    184         use std::{
    185             future::Future,
    186             task::{Context, Poll, Waker},
    187         };
    188         let connections = Arc::new(Connections::new(1));
    189         let copy = Arc::clone(&connections);
    190         let mut call = Box::pin(async move {
    191             let _operation = copy.begin().unwrap();
    192             std::future::pending::<()>().await;
    193         });
    194         assert_eq!(
    195             call.as_mut().poll(&mut Context::from_waker(Waker::noop())),
    196             Poll::Pending
    197         );
    198         assert!(connections.has_active_calls());
    199         connections.close();
    200         drop(call);
    201         assert!(!connections.has_active_calls());
    202     }
    203 }