//! A Mycelium daemon's API as it behaves for the transport, and the transport's tests //! against it. Its node is behind one lock, which a request for the inbox holds for as long //! as it waits for a message, and which every other request waits for: Mycelium 0.7's API //! does so (`mycelium-api`, its long poll holding the node's lock through its wait). Messages //! come into the inbox beside that lock, as they come from the network. It is served by axum, //! as Mycelium's API is. use std::collections::VecDeque; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use axum::extract::{Query, State}; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::{Json, Router}; use serde::Deserialize; use serde_json::{Value, json}; use url::Url; use super::daemon::MyceliumRuntime; use super::{MyceliumSetup, MyceliumTransport, encode_message}; use crate::transport::{MessageHandler, ParsedMessage, Transport, is_probe, wire}; /// Our daemon's public key, and a peer's. const OURS: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const THEIRS: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; /// Long enough for anything the transport does at once, short against Mycelium's long poll. const SOON: Duration = Duration::from_secs(2); #[derive(Default)] struct Daemon { /// The node, behind its lock. node: tokio::sync::Mutex<()>, inbox: std::sync::Mutex>, came: tokio::sync::Notify, /// Requests for the inbox begun, and messages taken to send. polls: AtomicUsize, sent: AtomicUsize, } impl Daemon { /// A message from the network, into the inbox. fn comes(&self, message: Value) { self.inbox.lock().expect("the inbox").push_back(message); self.came.notify_waiters(); } fn polls(&self) -> usize { self.polls.load(Ordering::SeqCst) } } #[derive(Deserialize)] struct Asked { #[serde(default)] timeout: u64, #[serde(default)] peek: bool, } async fn admin() -> Json { Json(json!({"nodePubkey": OURS})) } /// The inbox's next message, popped or peeked at, waiting for one up to `timeout` seconds /// with the node's lock held. async fn inbox(State(daemon): State>, Query(asked): Query) -> Response { daemon.polls.fetch_add(1, Ordering::SeqCst); let _node = daemon.node.lock().await; let until = tokio::time::Instant::now() + Duration::from_secs(asked.timeout); loop { let came = daemon.came.notified(); tokio::pin!(came); came.as_mut().enable(); let taken = { let mut inbox = daemon.inbox.lock().expect("the inbox"); if asked.peek { inbox.front().cloned() } else { inbox.pop_front() } }; if let Some(message) = taken { return Json(message).into_response(); } if asked.timeout == 0 { return StatusCode::NO_CONTENT.into_response(); } tokio::select! { () = &mut came => {} () = tokio::time::sleep_until(until) => return StatusCode::NO_CONTENT.into_response(), } } } async fn push(State(daemon): State>) -> Response { let _node = daemon.node.lock().await; daemon.sent.fetch_add(1, Ordering::SeqCst); (StatusCode::CREATED, Json(json!({"id": "0123456789abcdef"}))).into_response() } /// A daemon serving its API, and where. async fn started() -> (Arc, Url) { let daemon = Arc::new(Daemon::default()); let app = Router::new() .route("/api/v1/admin", get(admin)) .route("/api/v1/messages", get(inbox).post(push)) .with_state(daemon.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("a port"); let url = Url::parse(&format!( "http://{}/", listener.local_addr().expect("bound") )) .expect("a URL"); tokio::spawn(async move { let _ = axum::serve(listener, app).await; }); (daemon, url) } /// A transport using the daemon at `url`, taking what comes in, and what it took. async fn taking( url: Url, ) -> ( Arc, tokio::sync::mpsc::UnboundedReceiver, ) { let transport = Arc::new( MyceliumTransport::connect(MyceliumSetup { runtime: MyceliumRuntime::External, rest_url: url, }) .await .expect("connected"), ); let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let handler: MessageHandler = Box::new(move |_, message, _| { let tx = tx.clone(); Box::pin(async move { let _ = tx.send(message); Ok(()) }) }); let consuming = transport.clone(); tokio::spawn(async move { consuming.start_consumer(handler).await }); (transport, rx) } /// Waits until `daemon` has had a request for its inbox: the transport's first, which /// waits there while nothing comes in. async fn polled(daemon: &Daemon) { tokio::time::timeout(SOON, async { while daemon.polls() == 0 { tokio::time::sleep(Duration::from_millis(10)).await; } }) .await .expect("the inbox polled"); } fn a_message() -> ParsedMessage { wire::samples() .into_iter() .find(|message| !is_probe(message)) .expect("a message other than a probe") } /// `message` as the daemon gives it from the inbox, from the peer. fn inbound(message: &ParsedMessage) -> Value { let encoded = encode_message(OURS, message, wire::VERSION).expect("encoded"); let outbound: Value = serde_json::from_slice(&encoded.body).expect("JSON"); json!({ "id": "fedcba9876543210", "srcPk": THEIRS, "topic": outbound["topic"], "payload": outbound["payload"], }) } /// A node with nothing coming in sends at once: no request for the inbox holds up its /// messages. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_node_with_nothing_coming_in_sends_at_once() { let (daemon, url) = started().await; let (transport, _taken) = taking(url).await; // The inbox is waited for in the daemon by now. polled(&daemon).await; tokio::time::sleep(Duration::from_millis(100)).await; let message = encode_message(THEIRS, &a_message(), wire::VERSION).expect("encoded"); for n in 1..=3 { let sent = tokio::time::timeout(SOON, transport.send_encoded(&message)).await; assert!( matches!(sent, Ok(Ok(()))), "send {n} held up while nothing comes in: {sent:?}" ); assert_eq!(daemon.sent.load(Ordering::SeqCst), n); } } /// A message coming in is taken as it comes. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_message_is_taken_as_it_comes() { let (daemon, url) = started().await; let (_transport, mut taken) = taking(url).await; polled(&daemon).await; for _ in 0..3 { tokio::time::sleep(Duration::from_millis(100)).await; daemon.comes(inbound(&a_message())); let got = tokio::time::timeout(SOON, taken.recv()).await; assert!(matches!(got, Ok(Some(_))), "not taken: {got:?}"); } } /// A node with nothing coming in, and nothing to send, asks its daemon for nothing again /// and again: what it asked waits there. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_idle_node_asks_its_daemon_nothing_again_and_again() { let (daemon, url) = started().await; let (_transport, _taken) = taking(url).await; let before = daemon.polls(); tokio::time::sleep(Duration::from_secs(1)).await; let asked = daemon.polls() - before; assert!( asked <= 2, "{asked} requests for the inbox in an idle second" ); } /// Messages coming in while the node sends all come in, and every send goes out. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn messages_coming_while_the_node_sends_all_come_in() { const MESSAGES: usize = 50; let (daemon, url) = started().await; let (transport, mut taken) = taking(url).await; polled(&daemon).await; let message = encode_message(THEIRS, &a_message(), wire::VERSION).expect("encoded"); let sending = tokio::spawn({ let transport = transport.clone(); async move { for _ in 0..MESSAGES { transport.send_encoded(&message).await?; tokio::time::sleep(Duration::from_millis(3)).await; } anyhow::Ok(()) } }); let coming = tokio::spawn({ let daemon = daemon.clone(); async move { for _ in 0..MESSAGES { daemon.comes(inbound(&a_message())); tokio::time::sleep(Duration::from_millis(2)).await; } } }); let all = Duration::from_secs(10); let sent = tokio::time::timeout(all, sending).await; assert!(matches!(sent, Ok(Ok(Ok(())))), "sends held up: {sent:?}"); coming.await.expect("all came"); for n in 0..MESSAGES { let got = tokio::time::timeout(all, taken.recv()).await; assert!( matches!(got, Ok(Some(_))), "{n} of {MESSAGES} messages taken" ); } assert_eq!(daemon.sent.load(Ordering::SeqCst), MESSAGES); }