From 00cac6466057c2a8a92dae9e4cd46369e72bcad9 Mon Sep 17 00:00:00 2001 From: tv Date: Fri, 20 Nov 2026 02:12:15 +0000 Subject: mycelium: wait in the daemon only while nothing else is asked of it Mycelium holds its node's lock for as long as a request for the inbox waits for a message, and every other request waits for that lock, the messages we send among them: with two polls of up to five minutes, a node with nothing coming in sent nothing until a message came in (each send timing out after ten seconds), so two idle nodes never reached each other, a node joining a federation whose only node was its founder's among them. The inbox is waited for by one request, and only while nothing else is asked of the daemon: a send, or a seed's lookup, takes a turn (`Turn`), which drops the waiting request, freeing the daemon's lock as its API drops a request whose client went away. While turns are under way, the poller takes what is there without waiting, again as each begins or ends; then it waits again. It waits peeking, the message left in the inbox, and pops it after without waiting, so a request dropped while it waited takes nothing with it. Nothing is asked of the daemon again and again: an idle node has one request waiting there, for up to five minutes. The warnings about the daemon's API name the error's causes, not only which request failed. --- src/transport/mycelium/mod.rs | 214 ++++++++++++++++++++++++++++-------------- 1 file changed, 143 insertions(+), 71 deletions(-) (limited to 'src') diff --git a/src/transport/mycelium/mod.rs b/src/transport/mycelium/mod.rs index fd5beef..7ba7df7 100644 --- a/src/transport/mycelium/mod.rs +++ b/src/transport/mycelium/mod.rs @@ -22,6 +22,7 @@ pub(crate) use daemon::{MyceliumSetup, MyceliumSpawnConfig}; /// The scheme of this transport's addresses (`transport::paths`). pub(crate) const SCHEME: &str = "mycelium"; +/// How long a request for the inbox waits in the daemon for a message (`poll_inbox`). const MYCELIUM_POLL_TIMEOUT_SECS: u64 = 300; /// How long Mycelium tries to deliver a message before dropping it. const DELIVERY_LIMIT: Duration = Duration::from_secs(300); @@ -30,8 +31,6 @@ const DELIVERY_LIMIT: Duration = Duration::from_secs(300); /// is even parsed. Generous, because a sync message can carry a whole history until /// large deltas travel as blobs. const MAX_INBOUND_BYTES: usize = 256 << 20; -/// Polls of the inbox in progress at once. -const INBOX_POLLS: usize = 2; /// How long a request to our Mycelium may take, before what its body adds /// (`post_timeout`). const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); @@ -44,8 +43,6 @@ const POST_MIN_RATE: u64 = 1 << 20; /// payload says (`wire`). const TOPIC: &str = "continuum"; -const EMPTY_QUEUE_DELAY: Duration = Duration::from_millis(25); - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct InboundMessage { @@ -91,6 +88,25 @@ pub(crate) struct MyceliumTransport { local_id: String, /// Whose messages may be large (`transport::Admission`). admission: std::sync::OnceLock, + /// Requests to the daemon under way besides the inbox's (`Turn`): while any is, the + /// inbox's poller doesn't wait in the daemon (`poll_inbox`). + others: tokio::sync::watch::Sender, +} + +/// A request to the daemon besides the inbox's, under way while this lives (`others`). +struct Turn<'a>(&'a tokio::sync::watch::Sender); + +impl<'a> Turn<'a> { + fn taken(others: &'a tokio::sync::watch::Sender) -> Self { + others.send_modify(|n| *n += 1); + Turn(others) + } +} + +impl Drop for Turn<'_> { + fn drop(&mut self) { + self.0.send_modify(|n| *n -= 1); + } } /// This transport's options, checked when the configuration is loaded @@ -250,6 +266,7 @@ impl MyceliumTransport { pubkey_basepath: rest_url.join("/api/v1/pubkey/")?, local_id: admin.node_pubkey, admission: std::sync::OnceLock::new(), + others: tokio::sync::watch::channel(0).0, }; transport.discard_backlog().await; Ok(transport) @@ -286,7 +303,7 @@ impl MyceliumTransport { break; } Err(error) => { - tracing::warn!(error = %error, "Couldn't drain the inbox"); + tracing::warn!(error = %with_causes(error), "Couldn't drain the inbox"); break; } } @@ -306,6 +323,7 @@ impl MyceliumTransport { public_key: String, } + let _turn = Turn::taken(&self.others); let response: PublicKeyResponse = self .client .get(self.pubkey_basepath.join(&ip.to_string())?) @@ -368,6 +386,7 @@ impl Transport for MyceliumTransport { async fn send_encoded(&self, message: &EncodedMessage) -> Result<()> { tracing::trace!(payload_bytes = message.body.len(), "Sending message"); + let _turn = Turn::taken(&self.others); let response = self .client .post(self.messages_endpoint.clone()) @@ -409,17 +428,14 @@ impl Transport for MyceliumTransport { "Starting the consumer" ); - // Several polls at once, so one message's HTTP round trip overlaps the next one's - // and handling them: the messages still go to the handler one at a time. - let (tx, mut rx) = tokio::sync::mpsc::channel(INBOX_POLLS * 4); - for _ in 0..INBOX_POLLS { - tokio::spawn(poll_inbox( - self.poll_client.clone(), - self.messages_endpoint.clone(), - tx.clone(), - )); - } - drop(tx); + // The poller takes the next message while the handler takes the one before. + let (tx, mut rx) = tokio::sync::mpsc::channel(8); + tokio::spawn(poll_inbox( + self.poll_client.clone(), + self.messages_endpoint.clone(), + self.others.subscribe(), + tx, + )); // PINGs and PONGs aren't handled after the message before them (`is_probe`). let handler: std::sync::Arc = std::sync::Arc::from(handler); @@ -483,79 +499,135 @@ impl Transport for MyceliumTransport { } } -/// Long-polls the inbox and passes what it pops to `tx` (`start_consumer`). +/// Takes what comes into the inbox and passes it to `tx` (`start_consumer`). Mycelium holds +/// its node's lock for as long as a request for the inbox waits for a message, and every +/// other request waits for that lock, the messages we send among them. So the poller waits +/// there only while nothing else is asked of the daemon (`others`): a request that begins +/// drops the waiting one, which frees the lock, as the daemon's API drops a request whose +/// client went away. While others are under way, it takes what is there without waiting, +/// again as each begins or ends. It waits peeking (`peek`), leaving the message in the +/// inbox, and pops it after without waiting: a request dropped while it waited takes +/// nothing with it. async fn poll_inbox( client: reqwest::Client, endpoint: Url, + mut others: tokio::sync::watch::Receiver, tx: tokio::sync::mpsc::Sender, ) { loop { - tracing::trace!("Polling the inbox"); - - let response = match client - .get(endpoint.clone()) - .query(&[("timeout", MYCELIUM_POLL_TIMEOUT_SECS)]) - .query(&[("topic", encode_topic(TOPIC))]) - .send() - .await - { - Ok(resp) => resp, - Err(error) => { - tracing::warn!(error = %error, "Polling the inbox failed"); - tokio::time::sleep(Duration::from_millis(250)).await; - continue; + let popped = if *others.borrow() == 0 { + tokio::select! { + biased; + begun = others.wait_for(|n| *n > 0) => { + if begun.is_err() { + return; // the transport is gone + } + continue; + } + peeked = ask(&client, &endpoint, MYCELIUM_POLL_TIMEOUT_SECS, true) => { + if peeked.is_none() { + continue; + } + } + } + ask(&client, &endpoint, 0, false).await + } else { + match ask(&client, &endpoint, 0, false).await { + Some(response) => Some(response), + None => { + if others.changed().await.is_err() { + return; + } + continue; + } } }; - - let status = response.status(); - - if status == StatusCode::NO_CONTENT { - tracing::trace!("The inbox is empty"); - tokio::time::sleep(EMPTY_QUEUE_DELAY).await; + let Some(response) = popped else { + continue; + }; + let Some(message) = message_of(response).await else { continue; + }; + if tx.send(message).await.is_err() { + return; // the consumer stopped } + } +} - if !status.is_success() { - tracing::warn!(status = %status, "Polling the inbox failed"); +/// Asks the daemon for the inbox's next message, waiting up to `timeout` seconds for one, +/// and leaving it there with `peek`: the answer carrying it, where one came; none where +/// none did, or where the request failed, which is said, and waited a moment after. +async fn ask( + client: &reqwest::Client, + endpoint: &Url, + timeout: u64, + peek: bool, +) -> Option { + tracing::trace!(timeout, peek, "Asking for the inbox"); + let mut request = client + .get(endpoint.clone()) + .query(&[("timeout", timeout)]) + .query(&[("topic", encode_topic(TOPIC))]); + if peek { + request = request.query(&[("peek", true)]); + } + match request.send().await { + Ok(response) if response.status() == StatusCode::NO_CONTENT => { + tracing::trace!("The inbox is empty"); + None + } + Ok(response) if response.status().is_success() => Some(response), + Ok(response) => { + tracing::warn!(status = %response.status(), "Polling the inbox failed"); tokio::time::sleep(Duration::from_millis(500)).await; - continue; + None } + Err(error) => { + tracing::warn!(error = %with_causes(error), "Polling the inbox failed"); + tokio::time::sleep(Duration::from_millis(250)).await; + None + } + } +} - let raw_bytes = match read_capped(response, MAX_INBOUND_BYTES).await { - Ok(Some(bytes)) => bytes, - Ok(None) => { - tracing::warn!( - limit_bytes = MAX_INBOUND_BYTES, - "Dropping an inbound message larger than the limit" - ); - continue; - } - Err(error) => { - tracing::warn!(error = %error, "Couldn't read a message from the inbox"); - tokio::time::sleep(Duration::from_millis(100)).await; - continue; - } - }; - - let inbound_message = match serde_json::from_slice::(&raw_bytes) { - Ok(msg) => msg, - Err(error) => { - tracing::error!( - error = %error, - raw_payload = %String::from_utf8_lossy(&raw_bytes), - "Dropping a message that doesn't decode" - ); - tokio::time::sleep(Duration::from_millis(500)).await; - continue; - } - }; - - if tx.send(inbound_message).await.is_err() { - return; // the consumer stopped +/// The message `response` carries, where it is no larger than `MAX_INBOUND_BYTES` and +/// decodes; else none, said. +async fn message_of(response: reqwest::Response) -> Option { + let raw_bytes = match read_capped(response, MAX_INBOUND_BYTES).await { + Ok(Some(bytes)) => bytes, + Ok(None) => { + tracing::warn!( + limit_bytes = MAX_INBOUND_BYTES, + "Dropping an inbound message larger than the limit" + ); + return None; + } + Err(error) => { + tracing::warn!(error = %with_causes(error), "Couldn't read a message from the inbox"); + tokio::time::sleep(Duration::from_millis(100)).await; + return None; + } + }; + match serde_json::from_slice::(&raw_bytes) { + Ok(message) => Some(message), + Err(error) => { + tracing::error!( + error = %error, + raw_payload = %String::from_utf8_lossy(&raw_bytes), + "Dropping a message that doesn't decode" + ); + tokio::time::sleep(Duration::from_millis(500)).await; + None } } } +/// A request's error and its causes, as people read them: reqwest's own says only which +/// request failed, its causes why. +fn with_causes(error: reqwest::Error) -> String { + format!("{:#}", anyhow::Error::from(error)) +} + /// The body of `response`, unless it is larger than `limit` bytes (None): read no /// further than that, whatever the sender claims. async fn read_capped( -- cgit v1.3.1