From cb7cbd49410e13ffcd70ef0c4f1877141e2612af Mon Sep 17 00:00:00 2001 From: mnovak Date: Thu, 3 Dec 2026 09:20:13 +0100 Subject: [PATCH] [relay] Calls: rustfmt the long-poll and TURN code of v0.2.0 (no change in behaviour) --- crates/relay/src/arrivals.rs | 17 ++- crates/relay/src/http.rs | 14 +- crates/relay/src/lib.rs | 10 +- crates/relay/src/main.rs | 5 +- crates/relay/src/turn.rs | 16 ++- crates/relay/tests/calls.rs | 242 +++++++++++++++++++++++++++++------ crates/relay/tests/relay.rs | 5 +- 7 files changed, 257 insertions(+), 52 deletions(-) diff --git a/crates/relay/src/arrivals.rs b/crates/relay/src/arrivals.rs index 1db5935..d82bd15 100644 --- a/crates/relay/src/arrivals.rs +++ b/crates/relay/src/arrivals.rs @@ -23,7 +23,10 @@ pub struct Place<'a> { impl Arrivals { pub fn new(max: usize) -> Self { - Self { waiting: Mutex::new(HashMap::new()), max } + Self { + waiting: Mutex::new(HashMap::new()), + max, + } } /// A place to wait for `id`, or `None` when the relay already holds `max` waiters. @@ -35,7 +38,11 @@ impl Arrivals { } let entry = w.entry(id).or_insert_with(|| (Arc::new(Notify::new()), 0)); entry.1 += 1; - Some(Place { arrivals: self, id, notify: Arc::clone(&entry.0) }) + Some(Place { + arrivals: self, + id, + notify: Arc::clone(&entry.0), + }) } /// A blob arrived for `id`: everyone waiting for it is answered. @@ -49,7 +56,11 @@ impl Arrivals { impl Drop for Place<'_> { fn drop(&mut self) { - let mut w = self.arrivals.waiting.lock().unwrap_or_else(|e| e.into_inner()); + let mut w = self + .arrivals + .waiting + .lock() + .unwrap_or_else(|e| e.into_inner()); if let Some(entry) = w.get_mut(&self.id) { entry.1 -= 1; if entry.1 == 0 { diff --git a/crates/relay/src/http.rs b/crates/relay/src/http.rs index 07cda07..c069937 100644 --- a/crates/relay/src/http.rs +++ b/crates/relay/src/http.rs @@ -194,9 +194,15 @@ async fn fetch_blobs( let id = mailbox(&id)?; let token = bearer(&headers)?; let wait = clamp_wait(q.wait); - let place = if wait.is_zero() { None } else { s.arrivals.enter(id) }; + let place = if wait.is_zero() { + None + } else { + s.arrivals.enter(id) + }; let Some(place) = place else { - return Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? })); + return Ok(Json(FetchedBlobs { + blobs: s.store.fetch(&id, &token)?, + })); }; let notified = place.notify.notified(); tokio::pin!(notified); @@ -207,7 +213,9 @@ async fn fetch_blobs( } let _ = tokio::time::timeout(wait, notified).await; // The place is left when this returns. - Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? })) + Ok(Json(FetchedBlobs { + blobs: s.store.fetch(&id, &token)?, + })) } /// `POST …/turn` with the fetch token: a TURN REST pair (`calls-relay.md`). 404 without a TURN secret or with a diff --git a/crates/relay/src/lib.rs b/crates/relay/src/lib.rs index 5999ad6..aa43bf3 100644 --- a/crates/relay/src/lib.rs +++ b/crates/relay/src/lib.rs @@ -55,10 +55,16 @@ pub fn parse_args>(args: I) -> Result limits.file_bytes = positive(it.next())?, "--push-loopback" => push_loopback = true, "--turn-secret-file" => { - turn_secret_file = Some(it.next().map(PathBuf::from).ok_or_else(|| usage.to_string())?) + turn_secret_file = Some( + it.next() + .map(PathBuf::from) + .ok_or_else(|| usage.to_string())?, + ) } "--turn-url" => { - let url = it.next().filter(|u| u.starts_with("turn:") || u.starts_with("turns:")); + let url = it + .next() + .filter(|u| u.starts_with("turn:") || u.starts_with("turns:")); turn_urls.push(url.ok_or_else(|| usage.to_string())?); } "--listen" => { diff --git a/crates/relay/src/main.rs b/crates/relay/src/main.rs index 0fcf7e2..002bd47 100644 --- a/crates/relay/src/main.rs +++ b/crates/relay/src/main.rs @@ -75,7 +75,10 @@ async fn main() { std::process::exit(2); } }; - state = state.with_turn(tabellarius_relay::turn::Turn::new(secret, args.turn_urls.clone())); + state = state.with_turn(tabellarius_relay::turn::Turn::new( + secret, + args.turn_urls.clone(), + )); } let app = router(state); let shutdown = async { diff --git a/crates/relay/src/turn.rs b/crates/relay/src/turn.rs index 03e13b0..9aa962d 100644 --- a/crates/relay/src/turn.rs +++ b/crates/relay/src/turn.rs @@ -20,7 +20,11 @@ pub struct Turn { impl Turn { pub fn new(secret: Vec, urls: Vec) -> Self { - Self { secret, urls, counts: Mutex::new(HashMap::new()) } + Self { + secret, + urls, + counts: Mutex::new(HashMap::new()), + } } /// A fresh pair for `id` at `now`, or `None` when it had [`TURN_PER_HOUR`] this hour. @@ -48,7 +52,13 @@ impl Turn { ); let mut mac = Hmac::::new_from_slice(&self.secret).ok()?; mac.update(username.as_bytes()); - let password = base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()); - Some(TurnCredentials { username, password, ttl: TURN_TTL_SECS, urls: self.urls.clone() }) + let password = + base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()); + Some(TurnCredentials { + username, + password, + ttl: TURN_TTL_SECS, + urls: self.urls.clone(), + }) } } diff --git a/crates/relay/tests/calls.rs b/crates/relay/tests/calls.rs index b15263f..b4464e3 100644 --- a/crates/relay/tests/calls.rs +++ b/crates/relay/tests/calls.rs @@ -46,35 +46,95 @@ impl Relay { if let Some(t) = turn { state = state.with_turn(t); } - Self { app: router(state), _store: store, now } + Self { + app: router(state), + _store: store, + now, + } } - async fn call(&self, method: Method, path: &str, auth: Option<&Token>, body: Vec) -> (StatusCode, Vec) { + async fn call( + &self, + method: Method, + path: &str, + auth: Option<&Token>, + body: Vec, + ) -> (StatusCode, Vec) { let mut req = Request::builder().method(method).uri(path); if let Some(t) = auth { req = req.header(header::AUTHORIZATION, t.to_bearer()); } - let resp = self.app.clone().oneshot(req.body(Body::from(body)).expect("request")).await.expect("infallible"); + let resp = self + .app + .clone() + .oneshot(req.body(Body::from(body)).expect("request")) + .await + .expect("infallible"); let status = resp.status(); - let bytes = resp.into_body().collect().await.expect("body").to_bytes().to_vec(); + let bytes = resp + .into_body() + .collect() + .await + .expect("body") + .to_bytes() + .to_vec(); (status, bytes) } async fn mailbox(&self) -> Mailbox { - let m = Mailbox { id: MailboxId::from_bytes(random()), post: Token::from_bytes(random()), fetch: Token::from_bytes(random()) }; - let body = serde_json::to_vec(&CreateMailbox { id: m.id, post_token_hash: m.post.hash(), fetch_token_hash: m.fetch.hash() }).expect("json"); - assert_eq!(self.call(Method::POST, "/v0/mailboxes", None, body).await.0, StatusCode::CREATED); + let m = Mailbox { + id: MailboxId::from_bytes(random()), + post: Token::from_bytes(random()), + fetch: Token::from_bytes(random()), + }; + let body = serde_json::to_vec(&CreateMailbox { + id: m.id, + post_token_hash: m.post.hash(), + fetch_token_hash: m.fetch.hash(), + }) + .expect("json"); + assert_eq!( + self.call(Method::POST, "/v0/mailboxes", None, body).await.0, + StatusCode::CREATED + ); m } async fn post(&self, m: &Mailbox, bytes: &[u8]) -> StatusCode { - self.call(Method::POST, &format!("/v0/mailboxes/{}/blobs", m.id.to_wire()), Some(&m.post), bytes.to_vec()).await.0 + self.call( + Method::POST, + &format!("/v0/mailboxes/{}/blobs", m.id.to_wire()), + Some(&m.post), + bytes.to_vec(), + ) + .await + .0 } async fn fetch(&self, m: &Mailbox, token: &Token, wait: Option) -> (StatusCode, usize) { let q = wait.map(|w| format!("?wait={w}")).unwrap_or_default(); - let (status, body) = self.call(Method::GET, &format!("/v0/mailboxes/{}/blobs{q}", m.id.to_wire()), Some(token), vec![]).await; - let n = if status == StatusCode::OK { serde_json::from_slice::(&body).expect("json").blobs.len() } else { 0 }; + let (status, body) = self + .call( + Method::GET, + &format!("/v0/mailboxes/{}/blobs{q}", m.id.to_wire()), + Some(token), + vec![], + ) + .await; + let n = if status == StatusCode::OK { + serde_json::from_slice::(&body) + .expect("json") + .blobs + .len() + } else { + 0 + }; (status, n) } async fn turn(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec) { - self.call(Method::POST, &format!("/v0/mailboxes/{}/turn", m.id.to_wire()), Some(token), vec![]).await + self.call( + Method::POST, + &format!("/v0/mailboxes/{}/turn", m.id.to_wire()), + Some(token), + vec![], + ) + .await } } @@ -88,11 +148,18 @@ async fn a_long_poll_answers_as_soon_as_a_blob_arrives() { let started = Instant::now(); let waiting = tokio::spawn(async move { r.fetch(&mm, &mm.fetch, Some(25)).await }); tokio::time::sleep(Duration::from_millis(300)).await; - assert!(!waiting.is_finished(), "nothing waiting, so the request is held"); + assert!( + !waiting.is_finished(), + "nothing waiting, so the request is held" + ); assert_eq!(relay.post(&m, b"ring").await, StatusCode::CREATED); let (status, n) = waiting.await.expect("task"); assert_eq!((status, n), (StatusCode::OK, 1)); - assert!(started.elapsed() < Duration::from_secs(2), "answered on arrival, not after the wait: {:?}", started.elapsed()); + assert!( + started.elapsed() < Duration::from_secs(2), + "answered on arrival, not after the wait: {:?}", + started.elapsed() + ); } #[tokio::test(flavor = "multi_thread")] @@ -100,9 +167,15 @@ async fn a_long_poll_with_nothing_arriving_answers_empty_after_the_wait() { let relay = Relay::new(None, 1024); let m = relay.mailbox().await; let started = Instant::now(); - assert_eq!(relay.fetch(&m, &m.fetch, Some(1)).await, (StatusCode::OK, 0)); + assert_eq!( + relay.fetch(&m, &m.fetch, Some(1)).await, + (StatusCode::OK, 0) + ); let took = started.elapsed(); - assert!(took >= Duration::from_millis(900) && took < Duration::from_secs(3), "held about a second: {took:?}"); + assert!( + took >= Duration::from_millis(900) && took < Duration::from_secs(3), + "held about a second: {took:?}" + ); } #[tokio::test(flavor = "multi_thread")] @@ -124,16 +197,32 @@ async fn a_waiting_blob_is_answered_at_once_and_a_wrong_token_is_never_held() { let m = relay.mailbox().await; relay.post(&m, b"already here").await; let started = Instant::now(); - assert_eq!(relay.fetch(&m, &m.fetch, Some(25)).await, (StatusCode::OK, 1)); - assert_eq!(relay.fetch(&m, &m.post, Some(25)).await.0, StatusCode::NOT_FOUND, "the post token cannot fetch"); - assert!(started.elapsed() < Duration::from_secs(1), "neither was held"); + assert_eq!( + relay.fetch(&m, &m.fetch, Some(25)).await, + (StatusCode::OK, 1) + ); + assert_eq!( + relay.fetch(&m, &m.post, Some(25)).await.0, + StatusCode::NOT_FOUND, + "the post token cannot fetch" + ); + assert!( + started.elapsed() < Duration::from_secs(1), + "neither was held" + ); } #[tokio::test(flavor = "multi_thread")] async fn a_wait_longer_than_the_limit_is_held_the_limit_at_most() { assert_eq!(MAX_WAIT_SECS, 25); - assert_eq!(tabellarius_relay::http::clamp_wait(Some(3600)), Duration::from_secs(25)); - assert_eq!(tabellarius_relay::http::clamp_wait(Some(5)), Duration::from_secs(5)); + assert_eq!( + tabellarius_relay::http::clamp_wait(Some(3600)), + Duration::from_secs(25) + ); + assert_eq!( + tabellarius_relay::http::clamp_wait(Some(5)), + Duration::from_secs(5) + ); assert_eq!(tabellarius_relay::http::clamp_wait(None), Duration::ZERO); } @@ -145,8 +234,14 @@ async fn over_the_cap_a_long_poll_is_answered_at_once() { let first = tokio::spawn(async move { r.fetch(&mm, &mm.fetch, Some(2)).await }); tokio::time::sleep(Duration::from_millis(200)).await; let started = Instant::now(); - assert_eq!(relay.fetch(&m, &m.fetch, Some(25)).await, (StatusCode::OK, 0)); - assert!(started.elapsed() < Duration::from_millis(500), "the second waiter is over the cap"); + assert_eq!( + relay.fetch(&m, &m.fetch, Some(25)).await, + (StatusCode::OK, 0) + ); + assert!( + started.elapsed() < Duration::from_millis(500), + "the second waiter is over the cap" + ); assert_eq!(first.await.expect("task"), (StatusCode::OK, 0)); } @@ -154,7 +249,16 @@ async fn over_the_cap_a_long_poll_is_answered_at_once() { fn turn() -> (Turn, Vec) { let secret = random::<32>().to_vec(); - (Turn::new(secret.clone(), vec!["turn:turn.test:3478?transport=udp".into(), "turn:turn.test:3478?transport=tcp".into()]), secret) + ( + Turn::new( + secret.clone(), + vec![ + "turn:turn.test:3478?transport=udp".into(), + "turn:turn.test:3478?transport=tcp".into(), + ], + ), + secret, + ) } #[tokio::test(flavor = "multi_thread")] @@ -173,16 +277,26 @@ async fn turn_credentials_are_coturns_rest_pair_valid_ten_minutes() { assert_eq!(status, StatusCode::OK); let c: TurnCredentials = serde_json::from_slice(&body).expect("json"); let (expiry, rand) = c.username.split_once(':').expect("expiry:random"); - assert_eq!(expiry.parse::().expect("number"), T0 + TURN_TTL_SECS as i64); + assert_eq!( + expiry.parse::().expect("number"), + T0 + TURN_TTL_SECS as i64 + ); assert!(rand.len() >= 16, "a random part, no mailbox in it"); - assert!(!c.username.contains(&m.id.to_wire()) && !String::from_utf8_lossy(&body).contains(&m.id.to_wire())); + assert!( + !c.username.contains(&m.id.to_wire()) + && !String::from_utf8_lossy(&body).contains(&m.id.to_wire()) + ); let mut mac = Hmac::::new_from_slice(&secret).expect("key"); mac.update(c.username.as_bytes()); - assert_eq!(c.password, base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())); + assert_eq!( + c.password, + base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()) + ); assert_eq!(c.ttl, TURN_TTL_SECS); assert_eq!(c.urls.len(), 2); // Two requests give two different usernames. - let again: TurnCredentials = serde_json::from_slice(&relay.turn(&m, &m.fetch).await.1).expect("json"); + let again: TurnCredentials = + serde_json::from_slice(&relay.turn(&m, &m.fetch).await.1).expect("json"); assert_ne!(again.username, c.username); } @@ -192,13 +306,27 @@ async fn only_the_fetch_token_gets_turn_credentials_and_only_thirty_an_hour() { let relay = Relay::new(Some(t), 1024); let m = relay.mailbox().await; assert_eq!(relay.turn(&m, &m.post).await.0, StatusCode::NOT_FOUND); - assert_eq!(relay.turn(&m, &Token::from_bytes(random())).await.0, StatusCode::NOT_FOUND); + assert_eq!( + relay.turn(&m, &Token::from_bytes(random())).await.0, + StatusCode::NOT_FOUND + ); for i in 0..TURN_PER_HOUR { - assert_eq!(relay.turn(&m, &m.fetch).await.0, StatusCode::OK, "credential {i}"); + assert_eq!( + relay.turn(&m, &m.fetch).await.0, + StatusCode::OK, + "credential {i}" + ); } - assert_eq!(relay.turn(&m, &m.fetch).await.0, StatusCode::TOO_MANY_REQUESTS); + assert_eq!( + relay.turn(&m, &m.fetch).await.0, + StatusCode::TOO_MANY_REQUESTS + ); relay.now.fetch_add(3600, Ordering::SeqCst); - assert_eq!(relay.turn(&m, &m.fetch).await.0, StatusCode::OK, "a new hour"); + assert_eq!( + relay.turn(&m, &m.fetch).await.0, + StatusCode::OK, + "a new hour" + ); // Another mailbox has its own count. let other = relay.mailbox().await; assert_eq!(relay.turn(&other, &other.fetch).await.0, StatusCode::OK); @@ -212,7 +340,11 @@ async fn turn_credentials_and_long_polls_store_nothing() { let store = Arc::new(Store::open(&path).expect("store")); let clock: Clock = Arc::new(|| T0); let app = router(AppState::new(Arc::clone(&store), clock).with_turn(t)); - let relay = Relay { app, _store: store, now: Arc::new(AtomicI64::new(T0)) }; + let relay = Relay { + app, + _store: store, + now: Arc::new(AtomicI64::new(T0)), + }; let m = relay.mailbox().await; let before = std::fs::read(&path).expect("db"); let (_, body) = relay.turn(&m, &m.fetch).await; @@ -222,7 +354,10 @@ async fn turn_credentials_and_long_polls_store_nothing() { let after = std::fs::read(&path).expect("db"); assert_eq!(before, after, "the database did not change"); for needle in [c.username.as_bytes(), c.password.as_bytes(), &secret[..]] { - assert!(!after.windows(needle.len()).any(|w| w == needle), "nothing of the TURN pair or the secret on disk"); + assert!( + !after.windows(needle.len()).any(|w| w == needle), + "nothing of the TURN pair or the secret on disk" + ); } } @@ -230,11 +365,40 @@ async fn turn_credentials_and_long_polls_store_nothing() { fn the_turn_flags_come_together_or_not_at_all() { use tabellarius_relay::parse_args; let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); - let a = parse_args(s(&["--turn-secret-file", "/run/turn", "--turn-url", "turn:t.test:3478?transport=udp", "--turn-url", "turn:t.test:3478?transport=tcp"])).expect("valid"); - assert_eq!(a.turn_secret_file.as_deref(), Some(std::path::Path::new("/run/turn"))); + let a = parse_args(s(&[ + "--turn-secret-file", + "/run/turn", + "--turn-url", + "turn:t.test:3478?transport=udp", + "--turn-url", + "turn:t.test:3478?transport=tcp", + ])) + .expect("valid"); + assert_eq!( + a.turn_secret_file.as_deref(), + Some(std::path::Path::new("/run/turn")) + ); assert_eq!(a.turn_urls.len(), 2); - assert!(parse_args(s(&["--turn-secret-file", "/run/turn"])).is_err(), "a secret without a URL"); - assert!(parse_args(s(&["--turn-url", "turn:t.test:3478"])).is_err(), "a URL without a secret"); - assert!(parse_args(s(&["--turn-secret-file", "/run/turn", "--turn-url", "https://t.test"])).is_err(), "not a TURN URL"); - assert!(parse_args(s(&[])).expect("defaults").turn_secret_file.is_none()); + assert!( + parse_args(s(&["--turn-secret-file", "/run/turn"])).is_err(), + "a secret without a URL" + ); + assert!( + parse_args(s(&["--turn-url", "turn:t.test:3478"])).is_err(), + "a URL without a secret" + ); + assert!( + parse_args(s(&[ + "--turn-secret-file", + "/run/turn", + "--turn-url", + "https://t.test" + ])) + .is_err(), + "not a TURN URL" + ); + assert!(parse_args(s(&[])) + .expect("defaults") + .turn_secret_file + .is_none()); } diff --git a/crates/relay/tests/relay.rs b/crates/relay/tests/relay.rs index 01efd96..65d10ef 100644 --- a/crates/relay/tests/relay.rs +++ b/crates/relay/tests/relay.rs @@ -861,7 +861,10 @@ async fn the_join_page_is_static_and_loads_nothing_from_elsewhere() { "Copyright (c) 2026 Marek Novák", "Source (CPAL-1.0): gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius", ] { - assert!(body.contains(credit), "the page lacks the credit {credit:?}"); + assert!( + body.contains(credit), + "the page lacks the credit {credit:?}" + ); } }