aboutsummaryrefslogtreecommitdiffstats
path: root/src/transport/mycelium
diff options
context:
space:
mode:
Diffstat (limited to 'src/transport/mycelium')
-rw-r--r--src/transport/mycelium/mod.rs214
1 files changed, 143 insertions, 71 deletions
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<crate::transport::Admission>,
+ /// 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<usize>,
+}
+
+/// A request to the daemon besides the inbox's, under way while this lives (`others`).
+struct Turn<'a>(&'a tokio::sync::watch::Sender<usize>);
+
+impl<'a> Turn<'a> {
+ fn taken(others: &'a tokio::sync::watch::Sender<usize>) -> 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<HandlerFn> = 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<usize>,
tx: tokio::sync::mpsc::Sender<InboundMessage>,
) {
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<reqwest::Response> {
+ 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::<InboundMessage>(&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<InboundMessage> {
+ 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::<InboundMessage>(&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(