lib

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

native_backend_tests.rs (7940B)


      1 use futures::{SinkExt, StreamExt};
      2 use nostr_sdk::{
      3     client::{Client, ClientNotification},
      4     prelude::RelayMessage,
      5     relay::RelayNotification,
      6 };
      7 use std::{num::NonZeroUsize, time::Duration};
      8 use tokio_tungstenite::{accept_async, tungstenite::Message};
      9 
     10 const WATCHDOG: Duration = Duration::from_secs(5);
     11 
     12 #[tokio::test]
     13 async fn queued_subscription_is_sent_once_after_a_real_socket_reconnect() {
     14     use nostr_sdk::prelude::{ClientMessage, Filter, Kind, SubscriptionId};
     15     tokio::time::timeout(WATCHDOG, async {
     16         let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
     17         let url = format!("ws://{}", listener.local_addr().unwrap());
     18         let endpoint = crate::RelayEndpoint::new(
     19             &url,
     20             crate::RelayUrlPolicy::Local,
     21             crate::RelayAccess::ReadOnly,
     22         )
     23         .unwrap();
     24         let connector = crate::session_socket::SessionWebsocketTransport::new(
     25             &[endpoint],
     26             Duration::from_secs(1),
     27             std::sync::Arc::new(crate::test_host::LoopbackConnector),
     28         );
     29         let client = Client::builder().websocket_transport(connector).build();
     30         client.add_relay(&url).await.unwrap();
     31         let (closed, closure) = tokio::sync::oneshot::channel();
     32         let (observed, frames) = tokio::sync::oneshot::channel();
     33         let server = tokio::spawn(async move {
     34             let (tcp, _) = listener.accept().await.unwrap();
     35             let mut first = accept_async(tcp).await.unwrap();
     36             while let Some(message) = first.next().await {
     37                 match message {
     38                     Ok(Message::Close(_)) | Err(_) => break,
     39                     _ => first.flush().await.unwrap(),
     40                 }
     41             }
     42             closed.send(()).unwrap();
     43             let (tcp, _) = listener.accept().await.unwrap();
     44             let mut second = accept_async(tcp).await.unwrap();
     45             let mut requests = Vec::new();
     46             while let Some(message) = second.next().await {
     47                 match message.unwrap() {
     48                     Message::Text(text) => {
     49                         let value: serde_json::Value = serde_json::from_str(&text).unwrap();
     50                         if value[0] == "CLOSE" && value[1] == "sent-barrier" {
     51                             observed.send(requests).unwrap();
     52                             break;
     53                         }
     54                         requests.push(value);
     55                     }
     56                     _ => second.flush().await.unwrap(),
     57                 }
     58             }
     59             // Keep the second connection alive until explicit shutdown.
     60             while let Some(message) = second.next().await {
     61                 if matches!(message, Ok(Message::Close(_)) | Err(_)) {
     62                     break;
     63                 }
     64                 second.flush().await.unwrap();
     65             }
     66         });
     67         let relay = super::connect_relay(&client, &url, Duration::from_secs(1))
     68             .await
     69             .unwrap();
     70         relay.disconnect();
     71         closure.await.unwrap();
     72         let id = SubscriptionId::new("retained-live");
     73         let filter = Filter::new().kind(Kind::TextNote);
     74         relay
     75             .subscribe(filter.clone())
     76             .with_id(id.clone())
     77             .await
     78             .unwrap();
     79         super::connect_relay(&client, &url, Duration::from_secs(1))
     80             .await
     81             .unwrap();
     82         relay
     83             .send_msg(ClientMessage::close(SubscriptionId::new("sent-barrier")))
     84             .wait_until_sent(Duration::from_secs(1))
     85             .await
     86             .unwrap();
     87         let frames = frames.await.unwrap();
     88         assert_eq!(
     89             frames,
     90             vec![
     91                 serde_json::from_str::<serde_json::Value>(
     92                     &ClientMessage::req(id, filter).as_json()
     93                 )
     94                 .unwrap()
     95             ]
     96         );
     97         client.shutdown().await;
     98         server.await.unwrap();
     99     })
    100     .await
    101     .unwrap();
    102 }
    103 
    104 #[tokio::test]
    105 async fn actual_native_receivers_report_local_repeated_gaps_and_continue() {
    106     tokio::time::timeout(WATCHDOG, async {
    107         let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    108         let url = format!("ws://{}", listener.local_addr().unwrap());
    109         let endpoint = crate::RelayEndpoint::new(
    110             &url,
    111             crate::RelayUrlPolicy::Local,
    112             crate::RelayAccess::ReadOnly,
    113         )
    114         .unwrap();
    115         let connector = crate::session_socket::SessionWebsocketTransport::new(
    116             &[endpoint],
    117             Duration::from_secs(1),
    118             std::sync::Arc::new(crate::test_host::LoopbackConnector),
    119         );
    120         let client = Client::builder()
    121             .websocket_transport(connector)
    122             .notification_channel_size(NonZeroUsize::new(2).unwrap())
    123             .build();
    124         client
    125             .add_relay(&url)
    126             .notification_channel_size(2)
    127             .await
    128             .unwrap();
    129         let (send, mut receive) = tokio::sync::mpsc::channel::<usize>(1);
    130         let server = tokio::spawn(async move {
    131             let (tcp, _) = listener.accept().await.unwrap();
    132             let mut socket = accept_async(tcp).await.unwrap();
    133             while let Some(sequence) = receive.recv().await {
    134                 let frame = serde_json::json!(["NOTICE", sequence.to_string()]).to_string();
    135                 socket.send(Message::Text(frame.into())).await.unwrap();
    136             }
    137             socket.close(None).await.unwrap();
    138         });
    139         let relay = super::connect_relay(&client, &url, Duration::from_secs(1))
    140             .await
    141             .unwrap();
    142         let mut fast_relay = relay.notifications().with_gaps();
    143         let mut slow_relay = relay.notifications().with_gaps();
    144         let mut fast_client = client.notifications().with_gaps();
    145         let mut slow_client = client.notifications().with_gaps();
    146 
    147         for round in 0..2 {
    148             for sequence in round * 8..(round + 1) * 8 {
    149                 send.send(sequence).await.unwrap();
    150                 let RelayNotification::Message { message } =
    151                     fast_relay.next().await.unwrap().unwrap()
    152                 else {
    153                     panic!("relay message")
    154                 };
    155                 assert!(
    156                     matches!(*message, RelayMessage::Notice(value) if value == sequence.to_string())
    157                 );
    158                 let ClientNotification::Message { relay_url, message } =
    159                     fast_client.next().await.unwrap().unwrap()
    160                 else {
    161                     panic!("client message")
    162                 };
    163                 assert_eq!(relay_url.as_str(), url);
    164                 assert!(
    165                     matches!(*message, RelayMessage::Notice(value) if value == sequence.to_string())
    166                 );
    167             }
    168             assert_eq!(slow_relay.next().await.unwrap().unwrap_err().skipped, 6);
    169             assert_eq!(slow_client.next().await.unwrap().unwrap_err().skipped, 6);
    170             for sequence in (round + 1) * 8 - 2..(round + 1) * 8 {
    171                 let RelayNotification::Message { message } =
    172                     slow_relay.next().await.unwrap().unwrap()
    173                 else {
    174                     panic!("retained relay message")
    175                 };
    176                 assert!(
    177                     matches!(*message, RelayMessage::Notice(value) if value == sequence.to_string())
    178                 );
    179                 let ClientNotification::Message { message, .. } =
    180                     slow_client.next().await.unwrap().unwrap()
    181                 else {
    182                     panic!("retained client message")
    183                 };
    184                 assert!(
    185                     matches!(*message, RelayMessage::Notice(value) if value == sequence.to_string())
    186                 );
    187             }
    188         }
    189         drop(send);
    190         server.await.unwrap();
    191         client.shutdown().await;
    192     })
    193     .await
    194     .unwrap();
    195 }