lib

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

nostr_retirement_tests.rs (6451B)


      1 use super::*;
      2 use radroots_transport::{EventSource, FetchPage, FetchRequest, source::FetchBounds};
      3 use std::{
      4     future::Future,
      5     task::{Context, Poll, Waker},
      6     time::Duration,
      7 };
      8 use tokio::{io::AsyncReadExt, net::TcpListener, sync::oneshot, task::JoinHandle};
      9 
     10 fn profile(base: &str, count: usize) -> RelayProfile {
     11     RelayProfile::explicit(
     12         RelayProfileKind::Simulator,
     13         (0..count).map(|index| {
     14             RelayEndpoint::new(
     15                 format!("{base}/{index}"),
     16                 RelayUrlPolicy::Local,
     17                 RelayAccess::ReadWrite,
     18             )
     19             .unwrap()
     20         }),
     21     )
     22     .unwrap()
     23 }
     24 
     25 struct HeldFetch {
     26     slot: NostrSlot,
     27     previous: NostrState,
     28     base: String,
     29     fetch: JoinHandle<Result<FetchPage, radroots_transport::Error>>,
     30     server: JoinHandle<()>,
     31 }
     32 
     33 async fn held_fetch(relays: usize) -> HeldFetch {
     34     let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
     35     let base = format!("ws://{}", listener.local_addr().unwrap());
     36     let (connected, ready) = oneshot::channel();
     37     let server = tokio::spawn(async move {
     38         let (mut stream, _) = listener.accept().await.unwrap();
     39         let mut bytes = [0; 4096];
     40         assert!(stream.read(&mut bytes).await.unwrap() > 0);
     41         connected.send(()).unwrap();
     42         // An admitted connection is held before upgrade. Only the exact /0
     43         // target is requested; the remaining profile reservations do no I/O.
     44         loop {
     45             match stream.read(&mut bytes).await {
     46                 Ok(0) | Err(_) => break,
     47                 Ok(_) => {}
     48             }
     49         }
     50     });
     51     let slot = NostrSlot::new();
     52     slot.configure(profile(&base, relays)).await.unwrap();
     53     let previous = slot.cleanup_snapshot().unwrap();
     54     let target = RelayEndpoint::new(
     55         format!("{base}/0"),
     56         RelayUrlPolicy::Local,
     57         RelayAccess::ReadWrite,
     58     )
     59     .unwrap()
     60     .url()
     61     .to_target()
     62     .unwrap();
     63     let request = FetchRequest::new(
     64         "retirement-resource-check",
     65         TargetSet::new(vec![target]).unwrap(),
     66         FetchBounds::new(1, u64::MAX).unwrap(),
     67     )
     68     .unwrap();
     69     let copy = slot.clone();
     70     let fetch = tokio::spawn(async move { copy.fetch(request).await });
     71     tokio::time::timeout(Duration::from_secs(2), ready)
     72         .await
     73         .unwrap()
     74         .unwrap();
     75     assert!(previous.transport.has_in_flight_operations());
     76     HeldFetch {
     77         slot,
     78         previous,
     79         base,
     80         fetch,
     81         server,
     82     }
     83 }
     84 
     85 #[tokio::test]
     86 async fn an_oversized_new_profile_is_refused_before_changing_the_selection() {
     87     let slot = NostrSlot::new();
     88     let base = "ws://127.0.0.1:19991";
     89     slot.configure(profile(base, NOSTR_SESSION_RELAY_LIMIT))
     90         .await
     91         .unwrap();
     92     assert_eq!(
     93         slot.read_targets().unwrap().len(),
     94         NOSTR_SESSION_RELAY_LIMIT
     95     );
     96     assert_eq!(
     97         slot.configure(profile(base, NOSTR_SESSION_RELAY_LIMIT + 1))
     98             .await
     99             .unwrap_err()
    100             .kind(),
    101         crate::error::ErrorKind::InvalidHostConfiguration
    102     );
    103     assert_eq!(
    104         slot.read_targets().unwrap().len(),
    105         NOSTR_SESSION_RELAY_LIMIT
    106     );
    107     slot.shutdown().await;
    108 }
    109 
    110 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    111 async fn the_aggregate_budget_retains_a_busy_pool_and_refuses_an_extra_reservation() {
    112     let HeldFetch {
    113         slot,
    114         previous,
    115         base,
    116         fetch,
    117         server,
    118     } = held_fetch(16).await;
    119     assert_eq!(
    120         slot.configure(profile(&base, 1)).await.unwrap_err().kind(),
    121         crate::error::ErrorKind::SharedOperationUnavailable
    122     );
    123     assert!(previous.transport.admission_is_closed());
    124     assert!(previous.transport.has_in_flight_operations());
    125     assert!(slot.read_targets().is_none());
    126     assert!(slot.state.read().unwrap().retired.is_empty());
    127     slot.shutdown().await;
    128     tokio::time::timeout(Duration::from_secs(2), server)
    129         .await
    130         .unwrap()
    131         .unwrap();
    132     let _obtained = tokio::time::timeout(Duration::from_secs(5), fetch)
    133         .await
    134         .unwrap()
    135         .unwrap();
    136 }
    137 
    138 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    139 async fn cancelled_shutdown_retains_current_and_retired_pools_for_explicit_retry() {
    140     let HeldFetch {
    141         slot,
    142         previous,
    143         base,
    144         fetch,
    145         server,
    146     } = held_fetch(1).await;
    147     slot.configure(profile(&base, 15)).await.unwrap();
    148     assert_eq!(slot.read_targets().unwrap().len(), 15);
    149     assert_eq!(slot.state.read().unwrap().retired.len(), 1);
    150     assert!(previous.transport.has_in_flight_operations());
    151     assert_eq!(
    152         slot.configure(profile(&base, 16)).await.unwrap_err().kind(),
    153         crate::error::ErrorKind::SharedOperationUnavailable
    154     );
    155     let held = slot.transition.lock().await;
    156     let mut close = Box::pin(slot.shutdown());
    157     assert_eq!(
    158         close.as_mut().poll(&mut Context::from_waker(Waker::noop())),
    159         Poll::Pending
    160     );
    161     drop(close);
    162     assert_eq!(slot.state.read().unwrap().retired.len(), 1);
    163     assert_eq!(
    164         slot.configure(profile(&base, 1)).await.unwrap_err().kind(),
    165         crate::error::ErrorKind::ClientClosed
    166     );
    167     drop(held);
    168     slot.shutdown().await;
    169     assert!(slot.state.read().unwrap().retired.is_empty());
    170     assert!(slot.read_targets().is_none());
    171     tokio::time::timeout(Duration::from_secs(2), server)
    172         .await
    173         .unwrap()
    174         .unwrap();
    175     let _obtained = tokio::time::timeout(Duration::from_secs(5), fetch)
    176         .await
    177         .unwrap()
    178         .unwrap();
    179     slot.shutdown().await;
    180 }
    181 
    182 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    183 async fn a_cancelled_call_disconnects_before_idle_retirement_is_reclaimed() {
    184     let HeldFetch {
    185         slot,
    186         previous,
    187         base,
    188         fetch,
    189         server,
    190     } = held_fetch(1).await;
    191     slot.configure(profile(&base, 15)).await.unwrap();
    192     assert_eq!(slot.state.read().unwrap().retired.len(), 1);
    193     fetch.abort();
    194     assert!(fetch.await.unwrap_err().is_cancelled());
    195     tokio::time::timeout(Duration::from_secs(2), server)
    196         .await
    197         .unwrap()
    198         .unwrap();
    199     assert!(!previous.transport.has_in_flight_operations());
    200     slot.configure(profile(&base, 1)).await.unwrap();
    201     assert!(slot.state.read().unwrap().retired.is_empty());
    202     assert_eq!(slot.read_targets().unwrap().len(), 1);
    203     slot.shutdown().await;
    204 }