From f7663f14ec302cb4c078aafa3d7b5c44df0dbfc1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 05:59:15 -0800 Subject: [PATCH 1/5] chore(quest): claim quest/m2/webrtc-bind.md Quest-Claim: 7f502abc4005a894 From 820265b90d92e8329b6887bd14cd03d317ef56e7 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 06:04:02 -0800 Subject: [PATCH 2/5] wip: moq-webrtc's server binds at startup --- doc/bin/rtc.md | 7 +- quest/m2/README.md | 1 - quest/m2/gateway-align.md | 1 - quest/m2/str0m-upstream.md | 1 - quest/m2/webrtc-bind.md | 84 --------------------- quest/m3/one-port/rtc-feed.md | 19 +++-- rs/moq-cli/src/rtc.rs | 19 +++-- rs/moq-webrtc/MIGRATE.md | 15 ++++ rs/moq-webrtc/src/client/mod.rs | 18 ++--- rs/moq-webrtc/src/client/whep.rs | 2 +- rs/moq-webrtc/src/client/whip.rs | 2 +- rs/moq-webrtc/src/lib.rs | 16 +++- rs/moq-webrtc/src/server/mod.rs | 121 +++++++++++++++++-------------- rs/moq-webrtc/src/server/mux.rs | 40 +++++++--- rs/moq-webrtc/src/server/whep.rs | 5 +- rs/moq-webrtc/src/server/whip.rs | 38 +++++++++- rs/moq-webrtc/src/session.rs | 25 ++++--- 17 files changed, 211 insertions(+), 203 deletions(-) delete mode 100644 quest/m2/webrtc-bind.md diff --git a/doc/bin/rtc.md b/doc/bin/rtc.md index c72365778df..290b407f799 100644 --- a/doc/bin/rtc.md +++ b/doc/bin/rtc.md @@ -29,8 +29,11 @@ the highest-bitrate enabled Opus rendition (then sample rate, then channels). It follows the catalog: a peer whose rendition is disabled moves to the next best at that rendition's first keyframe, a better one that re-enables wins the peer back, and with none enabled the peer receives nothing until one is. `--cors-origin` -opens the endpoint to browsers on other origins, and `--udp-bind` plus -`--public-addr` pin one media port for firewalls. The listener is plain HTTP; +opens the endpoint to browsers on other origins. Every session shares one UDP +media port, `--udp-bind` (OS-picked by default), bound at startup so a taken port +fails before the listener reports ready. Behind NAT, `--public-addr` advertises +the public address as written, so `--public-addr 203.0.113.1:5000` reaches a port +the NAT forwards to `--udp-bind`; port 0 advertises the bound port. The listener is plain HTTP; put a TLS-terminating proxy in front for WHIP clients that require HTTPS. A fresh WHEP peer joins at the current group, so it starts at a keyframe without waiting for the next one. `DELETE` on the resource URL tears a session down per the RFC. Each WHIP session publishes diff --git a/quest/m2/README.md b/quest/m2/README.md index 42df4d4cfa6..2bf4d8292db 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -66,7 +66,6 @@ removal, a rename, or a wire, catalog, or format change that is free until [device and cursor](/quest/m2/native-media-config.md), [sink names](/quest/m2/audio-sink-names.md), [moq-vaapi's exports](/quest/m2/vaapi-exports.md), - [the WebRTC bind](/quest/m2/webrtc-bind.md), [gateway admission](/quest/m2/gateway-align.md), and [upstream str0m](/quest/m2/str0m-upstream.md), which reverses the 2026-10-30 vendoring. diff --git a/quest/m2/gateway-align.md b/quest/m2/gateway-align.md index 2eb39fa42b5..f6cf688e7e3 100644 --- a/quest/m2/gateway-align.md +++ b/quest/m2/gateway-align.md @@ -93,7 +93,6 @@ unpublished. CLI: the `rtc` endpoint is renamed. Wire: none. ## Related -- [moq-webrtc's server binds at startup](/quest/m2/webrtc-bind.md) - changes the same crate's server constructor and the same CLI file - [TS import reports its outcomes as values](/quest/m2/ts-typed-outcomes.md) - removes the CLI's downcasts of moq-srt and moq-rtsp errors - [moq-srt per-connection rate handle](/quest/m3/srt-rate-handle.md) - enforces the ingest cap this gives a home, and adds the egress cap as a request field - [moq-webrtc paces WHEP viewers](/quest/m3/rtc-pacing.md) - adds `rate` to `whep::Request` diff --git a/quest/m2/str0m-upstream.md b/quest/m2/str0m-upstream.md index 37927fb7966..b2ac29321d9 100644 --- a/quest/m2/str0m-upstream.md +++ b/quest/m2/str0m-upstream.md @@ -102,5 +102,4 @@ toward browsers; record any change step 1 finds. ## Related - [MoQ builds against rind 0.4](/quest/m0/rind-adapters.md) - moves the rind pin the adapters must match, and edits vendored files this deletes -- [moq-webrtc's server binds at startup](/quest/m2/webrtc-bind.md) - changes the same crate's server - [The gateways admit a session the same way](/quest/m2/gateway-align.md) - changes the same crate's request types diff --git a/quest/m2/webrtc-bind.md b/quest/m2/webrtc-bind.md deleted file mode 100644 index 2fcb6ad4877..00000000000 --- a/quest/m2/webrtc-bind.md +++ /dev/null @@ -1,84 +0,0 @@ -# [M] moq-webrtc's server binds its UDP socket at startup - -## Goal - -`moq_webrtc::Server::bind(config).await` binds the shared UDP socket and -fails if it cannot, so `moq import|export webrtc --listen` reports a taken -or unbindable `--udp-bind` port at startup, before it says it is ready. -`--public-addr 203.0.113.1:5000` advertises port 5000, as written. The -server's socket shape can take the planned shared-port feed without another -break, and the client config carries no field nothing sets. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - -- ✅ `Server::bind(config)` binds at construction (rejected: land the m3 - shared-port feed before the cut so the two-variant socket ships; keep the - lazy bind and take a break in the release after). It matches - `moq_rtmp::Server::bind` and `moq_srt::Server::bind`, and a gateway that - logs "serving" with no socket bound fails late, in front of a browser. -- ✅ `--public-addr` honors the port it is given (rejected: change the type - to an IP and rename the flag `--public-ip`; keep and document). The type - is `SocketAddr`, and a mapped port behind a NAT is what the port is for. -- ✅ `client::Config::ice_candidates` is deleted until a caller sets it. - -Facts found by the audit: - -- `Server::new(config) -> Self` binds nothing - (`rs/moq-webrtc/src/server/mod.rs:181`). The socket binds inside `mux()` - on the first accept (`:170`, `:192`-`:196`), "so `Server::new` can stay - synchronous". -- The CLI logs "serving WebRTC" and calls `notify_ready()` with no UDP - socket bound (`rs/moq-cli/src/rtc.rs:144`-`:147`), so a bad `--udp-bind` - surfaces as an HTTP error on the first WHIP or WHEP request. -- `server::Config` and `server::Socket` derive `Clone` - (`rs/moq-webrtc/src/server/mod.rs:129`, `:149`), and `Socket` has one - variant, `Bind(SocketAddr)` (`:153`). The second is the m3 - [shared-port feed](/quest/m3/one-port/rtc-feed.md), which holds a channel - receiver and cannot be `Clone`; that quest already notes the fed socket - "may belong in the server's constructor rather than the config". Either - answer is a break once the crate is published. -- The session keeps only the IP of each advertised address: - `advertise.iter().map(|addr| SocketAddr::new(addr.ip(), port))` with the - bound port (`rs/moq-webrtc/src/session.rs:715`). -- `client::Config::ice_candidates` - (`rs/moq-webrtc/src/client/mod.rs:21`) is read at - `client/whip.rs:28` and `client/whep.rs:27` and set by nothing: both CLI - call sites pass `client::Config::default()` - (`rs/moq-cli/src/rtc.rs:103`, `:125`). -- `moq-webrtc` has never been published under this name (the API diff marks - it new), so all of this is free until the cut. - -For the PR: - -- Settle where the socket lives so the feed is additive. Recommended: the - socket is an argument of the constructor, not a field of a `Clone` - config, and the single-variant `Socket` enum is deleted until the feed - adds its own constructor. The alternative, dropping `Clone` from `Config` - and `Socket`, keeps one constructor but freezes a config that cannot be - copied. Write the choice into [the feed quest](/quest/m3/one-port/rtc-feed.md). -- `Server::bind` is async and returns the bind error. Reproduce the late - failure first: a test that binds the UDP port, starts the server on it, - and expects the constructor to fail. -- An advertised candidate is sent exactly as given. Keep the existing - default for an unspecified bind address (loopback with the bound port). - Test that a `--public-addr` with its own port reaches the SDP answer. -- Fix the flag's `requires = "rtc-listen"` - (`rs/moq-cli/src/rtc.rs:34`), which names no flag. -- Recommended, not decided by the maintainer: record the crate's version - line in the PR. The manifest reads `0.3.12` - (`rs/moq-webrtc/Cargo.toml:8`), so `just version 0.22.0` moves it onto the - shared line; that is right, since published moq-cli depends on it. -- Update `doc/bin/rtc.md` (renamed by [the gateway alignment](/quest/m2/gateway-align.md)) - and `rs/moq-webrtc/MIGRATE.md`. - -Public API: moq-webrtc breaks (`Server::new` becomes `Server::bind`, the -socket's place, `client::Config::ice_candidates`), free while unpublished. -CLI: `--public-addr` now advertises its port. Wire: none. - -## Related - -- [The gateways admit a session the same way](/quest/m2/gateway-align.md) - changes the same crate's request and client names, and renames the CLI endpoint -- [moq-webrtc runs on upstream str0m](/quest/m2/str0m-upstream.md) - swaps the stack under the same session code -- [A WebRTC feed on the shared port](/quest/m3/one-port/rtc-feed.md) - adds the second socket source this leaves room for diff --git a/quest/m3/one-port/rtc-feed.md b/quest/m3/one-port/rtc-feed.md index 36473bd16f6..777aa64c79f 100644 --- a/quest/m3/one-port/rtc-feed.md +++ b/quest/m3/one-port/rtc-feed.md @@ -56,7 +56,8 @@ read loop: moq-webrtc's `ice::Socket`'s `udp: Arc` becomes implements it, so the bound case behaves as today), and a fed mux routes datagrams from the demux hook instead of reading a bound socket. Adapt the sketch above to that: `advertised` is `ice_candidates`, and `recv` feeds -the mux's existing router. Address-family mapping follows the real socket, +the mux's existing router; the `Socket` enum is replaced by a second +constructor (below). Address-family mapping follows the real socket, not the advertisement: a dual-stack socket bound to `[::]` may advertise a public IPv4 address, so the `Transmit` impl owns the IPv4-mapped conversion moq-webrtc's ICE module applies today. Received and pinned addresses use the same @@ -78,13 +79,15 @@ returns a guard that releases the pin on drop. So the fed `Socket` takes a selected pair, dropped when its session ends or ICE moves. A feed's `recv` returns `None` once the listener is gone. -Things to watch: the server config is `Clone` today and a receiver is not, so -the fed socket may belong in the server's constructor rather than the -config. Since 2026-11-16 (maintainer, /quest-plan of the pre-cut audit) -[the bind at startup](/quest/m2/webrtc-bind.md) settles this before the cut: -the server becomes `Server::bind(config)`, and that PR picks where the -socket lives and writes it here, so the feed is an addition, not a break. The fed mux has nothing to bind lazily, and a dropped feed should -fail the server loudly rather than idle. +Settled 2026-11-16 by the bind at startup: the socket is the constructor's, +not the config's. `Server::bind(addr, config).await` binds its own socket, and +`server::Config` holds only `ice_candidates` and stays `Clone`; there is no +`Socket` enum. The feed adds a second constructor, such as +`Server::feed(webrtc, config)`, taking the `WebRtc` handle by value, so it is +an addition, not a break. Its `ice_candidates` are the shared address to +advertise, sent as given (port 0 takes the socket's port). The fed mux has +nothing to bind, and a dropped feed should fail the server loudly rather than +idle. Noted 2026-10-31 from [moq-dev/moq#7095](https://github.com/moq-dev/moq/pull/7095): its demux `Datagram` carries no ECN marks or kernel receive timestamp. If diff --git a/rs/moq-cli/src/rtc.rs b/rs/moq-cli/src/rtc.rs index ebadfaeeba0..b05497bb706 100644 --- a/rs/moq-cli/src/rtc.rs +++ b/rs/moq-cli/src/rtc.rs @@ -26,12 +26,13 @@ pub struct Args { #[usage(name = "rtc-listen", long = "listen", value_name = "ADDR", group = "rtc-mode")] pub listen: Option, - /// Shared UDP socket for ICE/media (one port for all sessions). + /// Shared UDP socket for ICE/media (one port for all sessions), bound at startup. #[usage(long, requires = "--listen", default = "[::]:0")] pub udp_bind: SocketAddr, - /// Public UDP address(es) advertised as ICE host candidates (repeatable). - #[usage(long, requires = "rtc-listen")] + /// Public UDP address(es) advertised as ICE host candidates, as given (repeatable). + /// Port 0 advertises the `--udp-bind` port. + #[usage(long, requires = "--listen")] pub public_addr: Vec, /// Browser CORS policy for the WHIP/WHEP listener. @@ -57,7 +58,7 @@ pub struct Listen { /// WHIP server: accept incoming WebRTC publishes into the Origin as `target.name` (import). pub async fn listen_import(target: ImportTarget, listen: Listen) -> anyhow::Result<()> { let publisher = scope_producer(&target.origin, &target.name)?; - let server = moq_webrtc::Server::new(server_config(&listen)); + let server = bind(&listen).await?; serve(server.publish_router(publisher, target.ingest), "WHIP", listen).await } @@ -69,7 +70,7 @@ pub async fn listen_export(origin: moq_net::origin::Consumer, name: String, list let subscriber = origin .scope("", &scope) .with_context(|| format!("failed to scope origin to broadcast `{name}`"))?; - let server = moq_webrtc::Server::new(server_config(&listen)); + let server = bind(&listen).await?; serve(server.subscribe_router(subscriber), "WHEP", listen).await } @@ -127,11 +128,13 @@ pub async fn connect_export(origin: moq_net::origin::Consumer, url: Url, name: S Ok(()) } -fn server_config(listen: &Listen) -> moq_webrtc::server::Config { +/// Bind the shared media socket, so a bad `--udp-bind` fails startup. +async fn bind(listen: &Listen) -> anyhow::Result { let mut config = moq_webrtc::server::Config::default(); - config.socket = moq_webrtc::server::Socket::Bind(listen.udp_bind); config.ice_candidates.clone_from(&listen.public_addr); - config + moq_webrtc::Server::bind(listen.udp_bind, config) + .await + .with_context(|| format!("failed to bind --udp-bind {}", listen.udp_bind)) } async fn serve(router: axum::Router, role: &str, listen: Listen) -> anyhow::Result<()> { diff --git a/rs/moq-webrtc/MIGRATE.md b/rs/moq-webrtc/MIGRATE.md index 424cf864612..54e6358dd6d 100644 --- a/rs/moq-webrtc/MIGRATE.md +++ b/rs/moq-webrtc/MIGRATE.md @@ -4,6 +4,21 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `Server::bind` binds the media socket + +`Server::new(config)` is `Server::bind(addr, config).await?`: it binds the shared UDP socket at `addr` and fails if it cannot, instead of on the first accept. +`server::Socket` and `server::Config::socket` are gone; pass the address you set as `Socket::Bind(addr)`, or `"0.0.0.0:0"` for the old default. +`Server::local_addr` reports the bound address. + +### Advertised candidates keep their port + +`server::Config::ice_candidates` are advertised as given, port included, instead of with the bound port. +Write the public port you forward to the bound one, or port 0 to keep advertising the bound port. + +### `client::Config::ice_candidates` is gone + +Nothing read a client's advertised candidates usefully: the server learns a client's address from its ICE checks. Drop the field; `client::Config` has no options yet. + ### `Config::max_age` of `None` is unlimited ([#7729](https://github.com/moq-dev/moq/pull/7729)) `server::Config::max_age` and `client::Config::max_age` default to `Some(hang::container::MAX_AGE)` (30 s), and `None` now sets no publisher limit instead of keeping that default. diff --git a/rs/moq-webrtc/src/client/mod.rs b/rs/moq-webrtc/src/client/mod.rs index a7300daedd4..eed348cd5e2 100644 --- a/rs/moq-webrtc/src/client/mod.rs +++ b/rs/moq-webrtc/src/client/mod.rs @@ -8,18 +8,15 @@ mod whep; mod whip; -use std::net::SocketAddr; - use url::Url; /// Configuration shared by both `client publish` and `client subscribe`. +/// +/// No options yet; it is where a later one, such as a dial policy, goes without +/// changing [`Client::new`]. #[derive(Clone, Debug, Default)] #[non_exhaustive] -pub struct Config { - /// Public UDP socket addresses to advertise as ICE host candidates in - /// our outbound offer. Same semantics as [`crate::server::Config::ice_candidates`]. - pub ice_candidates: Vec, -} +pub struct Config {} /// Outbound WHIP/WHEP dialer. /// @@ -27,7 +24,6 @@ pub struct Config { /// rustls config survive between resources. #[derive(Clone)] pub struct Client { - config: Config, http: reqwest::Client, } @@ -40,19 +36,15 @@ impl Client { /// Fails with [`Error::UnsupportedCpu`](crate::Error::UnsupportedCpu) on a CPU /// rind can't run on. pub fn new(config: Config) -> crate::Result { + let Config {} = config; // reqwest reads rustls's process default and panics without one, so install rind's // unless the host already chose a provider. moq_crypto::provider::install_default()?; Ok(Self { - config, http: reqwest::Client::builder().build()?, }) } - pub(crate) fn config(&self) -> &Config { - &self.config - } - pub(crate) fn http(&self) -> &reqwest::Client { &self.http } diff --git a/rs/moq-webrtc/src/client/whep.rs b/rs/moq-webrtc/src/client/whep.rs index 94104e30e8b..03883508e85 100644 --- a/rs/moq-webrtc/src/client/whep.rs +++ b/rs/moq-webrtc/src/client/whep.rs @@ -24,7 +24,7 @@ pub(crate) async fn dial( ) -> Result<()> { let sink = Box::new(IngestSink::new(broadcast, catalog)?); - let socket = session::bind_udp(&client.config().ice_candidates).await?; + let socket = session::bind_udp().await?; let mut rtc = session::rtc_config()?.build(kio::clock::now().into_std()); for addr in socket.locals() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; diff --git a/rs/moq-webrtc/src/client/whip.rs b/rs/moq-webrtc/src/client/whip.rs index adad3d92a35..b63a14d8c2d 100644 --- a/rs/moq-webrtc/src/client/whip.rs +++ b/rs/moq-webrtc/src/client/whip.rs @@ -25,7 +25,7 @@ pub(crate) async fn dial(client: &Client, url: Url, source: moq_mux::Source) -> return Err(Error::NoRenditions); } - let socket = session::bind_udp(&client.config().ice_candidates).await?; + let socket = session::bind_udp().await?; // Restrict to codecs the catalog can actually source so the remote // answer doesn't pick a codec we have no rendition for. let mut rtc = session::rtc_with_codecs(&codecs)?; diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index 9099a876637..6f0c3376942 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -194,7 +194,9 @@ mod tests { let (old_route, mut old, old_catalog) = publish_opus(&origin, moq_net::Instance::random()); push(&mut *old, 20_000, OPUS_PACKET); - let server = Server::new(server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + .await + .unwrap(); let whep_origin = origin.consume(); let (sessions_tx, mut sessions) = tokio::sync::mpsc::channel(1); let app = Router::new().route( @@ -260,7 +262,9 @@ mod tests { let (old_route, mut old, old_catalog) = publish_opus(&origin, moq_net::Instance::random()); push(&mut *old, 20_000, OPUS_PACKET); - let server = Server::new(server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + .await + .unwrap(); let ingest_origin = moq_tokio::origin::spawn(); let whip_origin = ingest_origin.clone(); let app = Router::new().route( @@ -325,7 +329,9 @@ mod tests { tokio::task::JoinHandle<()>, tokio::sync::mpsc::Receiver>>, ) { - let server = Server::new(server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let (sessions_tx, sessions) = tokio::sync::mpsc::channel(1); let app = Router::new().route( @@ -468,7 +474,9 @@ mod tests { drop(announcements); let server_origin = moq_tokio::origin::spawn(); - let server = Server::new(server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + .await + .unwrap(); let (sources_tx, mut sources_rx) = tokio::sync::mpsc::channel(2); let whip_server = server.clone(); let whip_origin = server_origin.clone(); diff --git a/rs/moq-webrtc/src/server/mod.rs b/rs/moq-webrtc/src/server/mod.rs index 54a85e81bd3..8f83f361756 100644 --- a/rs/moq-webrtc/src/server/mod.rs +++ b/rs/moq-webrtc/src/server/mod.rs @@ -20,7 +20,7 @@ use std::time::Duration; use axum::Router; #[cfg(feature = "server")] use axum::http::{HeaderValue, StatusCode, Uri}; -use tokio::sync::{OnceCell, oneshot}; +use tokio::sync::oneshot; use crate::Result; use mux::Mux; @@ -129,34 +129,14 @@ pub(crate) fn session_location(uri: &Uri, resource_id: &str) -> Option, - - /// The shared WebRTC media socket. Every WHIP/WHEP session shares this one UDP port - /// (demuxed by ICE ufrag), so a deployment opens exactly one media port in its firewall. - /// Defaults to binding `0.0.0.0:0`, letting the OS pick a port, which is fine for - /// dev/loopback; production pins it. - pub socket: Socket, -} - -/// Where the shared WebRTC media socket comes from. -#[derive(Clone, Debug)] -#[non_exhaustive] -pub enum Socket { - /// Bind a UDP socket at this address on the first accept. - Bind(SocketAddr), -} - -impl Default for Socket { - fn default() -> Self { - Self::Bind(SocketAddr::from(([0, 0, 0, 0], 0))) - } } /// Shared WebRTC media state: the UDP mux and live sessions behind [`whip::accept`] and [`whep::accept`]. @@ -166,10 +146,9 @@ pub struct Server { } struct Inner { - config: Config, - /// The shared media socket + demux, bound lazily on the first accept so - /// `Server::new` can stay synchronous (and an idle server binds no port). - mux: OnceCell, + /// The shared media socket and its demux. Every WHIP/WHEP session shares + /// this one UDP port, demuxed by ICE ufrag. + mux: Mux, /// Live sessions keyed by resource id, each holding a cancel sender the /// session task selects on. Lets [`Server::terminate`] (and the bundled /// `DELETE` route) end a session by its `Location` id. @@ -177,25 +156,30 @@ struct Inner { } impl Server { - /// Build a server with shared ICE and media settings. - pub fn new(config: Config) -> Self { - Self { + /// Bind the shared media socket at `addr` and serve WHIP and WHEP sessions on it. + /// + /// Every session shares this one UDP port, so a deployment opens exactly one + /// media port in its firewall; port 0 lets the OS pick one. Fails if the + /// socket cannot be bound, or an advertised candidate is invalid. Dropping + /// the last clone, and every session it accepted, releases the port. + pub async fn bind(addr: SocketAddr, config: Config) -> Result { + let mux = Mux::bind(addr, &config.ice_candidates).await?; + Ok(Self { inner: Arc::new(Inner { - config, - mux: OnceCell::new(), + mux, sessions: Mutex::new(HashMap::new()), }), - } + }) } - /// The shared media mux, bound (and its demux task spawned) on first use. - pub(crate) async fn mux(&self) -> Result<&Mux> { - self.inner - .mux - .get_or_try_init(|| match self.inner.config.socket { - Socket::Bind(addr) => Mux::bind(addr, &self.inner.config.ice_candidates), - }) - .await + /// The shared media mux. + pub(crate) fn mux(&self) -> &Mux { + &self.inner.mux + } + + /// The address the shared media socket is bound to. + pub fn local_addr(&self) -> SocketAddr { + self.inner.mux.local_addr() } /// Router for `server publish` (WHIP), publishing each session as `ingest` says. Mount @@ -267,27 +251,56 @@ pub(crate) fn delete(server: &Server, path: &str) -> StatusCode { mod tests { use super::*; - fn server() -> Server { - Server::new(Config::default()) + const LOOPBACK: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 0); + + async fn server() -> Server { + Server::bind(LOOPBACK, Config::default()).await.unwrap() } - #[test] - fn terminate_unknown_session_is_false() { - assert!(!server().terminate("00000000-0000-0000-0000-000000000000")); + /// A port something else holds fails the constructor, before anything reports + /// the server ready, rather than the first WHIP or WHEP request. + #[tokio::test] + async fn bind_fails_on_a_taken_port() { + let taken = std::net::UdpSocket::bind(LOOPBACK).unwrap(); + let err = Server::bind(taken.local_addr().unwrap(), Config::default()) + .await + .err() + .expect("bound a taken port"); + assert!(matches!(err, crate::Error::Io(_)), "{err}"); } - #[test] - fn terminate_registered_session_once() { - let server = server(); + /// The last clone of a server that accepted nothing releases its port. + #[tokio::test] + async fn dropping_the_server_releases_its_port() { + let server = server().await; + let addr = server.local_addr(); + let clone = server.clone(); + drop(server); + std::net::UdpSocket::bind(addr).expect_err("a live clone keeps the port"); + + drop(clone); + // Let the aborted demux task drop its socket. + tokio::task::yield_now().await; + std::net::UdpSocket::bind(addr).expect("the dropped server kept its port"); + } + + #[tokio::test] + async fn terminate_unknown_session_is_false() { + assert!(!server().await.terminate("00000000-0000-0000-0000-000000000000")); + } + + #[tokio::test] + async fn terminate_registered_session_once() { + let server = server().await; let id = "11111111-1111-1111-1111-111111111111"; let _cancel = server.register_session(id.to_string()); assert!(server.terminate(id), "first terminate finds the session"); assert!(!server.terminate(id), "second terminate is a no-op"); } - #[test] - fn unregister_drops_the_entry() { - let server = server(); + #[tokio::test] + async fn unregister_drops_the_entry() { + let server = server().await; let id = "22222222-2222-2222-2222-222222222222"; let _cancel = server.register_session(id.to_string()); server.unregister_session(id); diff --git a/rs/moq-webrtc/src/server/mux.rs b/rs/moq-webrtc/src/server/mux.rs index af9e98c572f..e83154c0368 100644 --- a/rs/moq-webrtc/src/server/mux.rs +++ b/rs/moq-webrtc/src/server/mux.rs @@ -50,14 +50,24 @@ struct Entry { /// The shared media socket plus its demux routing table. /// -/// One per [`Server`](crate::server::Server), bound lazily on the first -/// WHIP/WHEP accept so `Server::new` can stay synchronous. +/// One per [`Server`](crate::server::Server), bound when the server is. pub(crate) struct Mux { socket: Arc, + /// The address `socket` is bound to. + local: SocketAddr, registry: Arc>, - /// ICE host candidates to advertise: the configured public IP(s) (or the - /// bound address if none) paired with the shared socket's actual port. + /// ICE host candidates to advertise: the configured addresses (or the + /// bound address if none). candidates: Vec, + /// The task reading `socket`, which holds it open until aborted. + demux: tokio::task::JoinHandle<()>, +} + +impl Drop for Mux { + fn drop(&mut self) { + // Release the port once the server and every session it accepted are gone. + self.demux.abort(); + } } /// Removes a session's ufrag entry (and sweeps any dead address entries) when @@ -98,24 +108,32 @@ impl Registry { impl Mux { /// Bind the shared socket to `udp_bind` and spawn the demux task. The - /// advertised candidates are `ice_candidates` (each reusing the socket's - /// real port), or the bound address when none are configured. An unspecified - /// bind falls back to loopback for local testing. + /// advertised candidates are `ice_candidates` as given (a port of 0 taking + /// the bound port), or the bound address when none are configured. An + /// unspecified bind falls back to loopback for local testing. pub(crate) async fn bind(udp_bind: SocketAddr, ice_candidates: &[SocketAddr]) -> Result { let socket = Arc::new(UdpSocket::bind(udp_bind).await?); - let candidates = advertised_candidates(ice_candidates, socket.local_addr()?)?; + let local = socket.local_addr()?; + let candidates = advertised_candidates(ice_candidates, local)?; let registry = Arc::new(Mutex::new(Registry::default())); - tokio::spawn(demux(socket.clone(), registry.clone())); + let demux = tokio::spawn(demux(socket.clone(), registry.clone())); - tracing::info!(?candidates, bound = %socket.local_addr()?, "webrtc media mux listening"); + tracing::info!(?candidates, bound = %local, "webrtc media mux listening"); Ok(Self { socket, + local, registry, candidates, + demux, }) } + /// The address the shared socket is bound to. + pub(crate) fn local_addr(&self) -> SocketAddr { + self.local + } + /// Mint ICE credentials for a new session and register its inbox. Returns /// the credentials (set on the session's [`Rtc`](str0m::Rtc) so the demux's /// ufrag lookup matches), the inbox receiver the session reads from, and a @@ -292,7 +310,7 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0), ]; let mux = Mux::bind(bind, &advertise).await.expect("dual-stack bind"); - let port = mux.socket.local_addr().unwrap().port(); + let port = mux.local_addr().port(); let (creds, mut rx, registration) = mux.register(); // Dial the mux over IPv4, which a dual-stack socket accepts as v4-mapped. diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index 0d7b49de17c..34540120fae 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -343,7 +343,10 @@ mod tests { .expect("create broadcast"); let (sub_origin, _connection, accept) = lazy_client(pub_origin).await; - let _router = super::router(crate::server::Server::new(Default::default()), sub_origin.consume()); + let server = crate::server::Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), Default::default()) + .await + .unwrap(); + let _router = super::router(server, sub_origin.consume()); let missing = kio::clock::timeout(TIMEOUT, sub_origin.consume().request("missing", None)) .await .expect("sync timed out"); diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index 9a642355ee4..49e7cc33050 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -270,7 +270,9 @@ mod tests { /// a description str0m still parses, and an uncapped one carries no bandwidth line. #[tokio::test] async fn a_capped_answer_carries_tias() { - let server = Server::new(crate::server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), crate::server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let cap = moq_net::bandwidth::Cap::new(moq_net::bandwidth::Rate::from_mbps(1)); let offer = offer(); @@ -286,12 +288,40 @@ mod tests { assert!(!uncapped.answer.contains("\r\nb="), "{}", uncapped.answer); } + /// An advertised address reaches the answer as given, its port included, so a NAT can + /// forward another public port to the bound one; a port of 0 takes the bound port. + #[tokio::test] + async fn an_advertised_candidate_keeps_its_port() { + let config = crate::server::Config { + ice_candidates: vec![ + "203.0.113.1:5000".parse().unwrap(), + "[2001:db8::1]:0".parse().unwrap(), + ], + }; + let server = Server::bind("127.0.0.1:0".parse().unwrap(), config).await.unwrap(); + let bound = server.local_addr().port(); + let origin = moq_tokio::origin::spawn(); + let offer = offer(); + let path = moq_net::Path::from_static("live/nat"); + let response = accept(&server, Request::new(&origin, path, &offer)).await.unwrap(); + + let hosts: Vec<_> = response + .answer + .lines() + .filter(|line| line.starts_with("a=candidate:")) + .map(|line| line.split(' ').skip(4).take(2).collect::>().join(" ")) + .collect(); + assert_eq!(hosts, ["203.0.113.1 5000".to_string(), format!("2001:db8::1 {bound}")]); + } + /// A session that ends without a DELETE, here one that never connects, ends its tracks /// with the transport cause, so a reader sees the publisher go rather than a producer /// dropped unfinished. #[tokio::test(start_paused = true)] async fn a_session_ending_without_a_delete_ends_its_tracks() { - let server = Server::new(crate::server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), crate::server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); let session = accept( @@ -325,7 +355,9 @@ mod tests { /// it leaves. #[tokio::test] async fn a_reconnect_replaces_the_stale_session() { - let server = Server::new(crate::server::Config::default()); + let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), crate::server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); let _stale_session = accept( diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index 51eab73941a..1d20ebdee8a 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -682,19 +682,18 @@ pub fn rtc_with_codecs(codecs: &[str0m::format::Codec]) -> Result { } /// Bind an ephemeral UDP socket for a single client session, read by its own -/// [`crate::ice::reader`], with the ICE candidates to advertise. +/// [`crate::ice::reader`], advertising the bound address (loopback when it is +/// unspecified). /// /// The client paths are 1:1 (one socket per dialed session, no demux); the -/// server paths share one socket via `crate::server::mux` instead. `advertise` -/// IPs are used verbatim (reusing the bound port); empty falls back to the -/// bound address, substituting loopback when that address is unspecified. -pub async fn bind_udp(advertise: &[SocketAddr]) -> Result { +/// server paths share one socket via `crate::server::mux` instead. +pub async fn bind_udp() -> Result { let udp = Arc::new(UdpSocket::bind(("0.0.0.0", 0)).await?); - let locals = advertised_candidates(advertise, udp.local_addr()?)?; + let locals = advertised_candidates(&[], udp.local_addr()?)?; Ok(crate::ice::Socket::new(udp.clone(), locals, crate::ice::reader(udp))?) } -/// Pair configured ICE candidates with the bound UDP port and validate them. +/// The ICE host candidates to advertise for a socket bound at `local`, validated. pub(crate) fn advertised_candidates(advertise: &[SocketAddr], local: SocketAddr) -> Result> { let port = local.port(); let candidates = if advertise.is_empty() { @@ -710,9 +709,15 @@ pub(crate) fn advertised_candidates(advertise: &[SocketAddr], local: SocketAddr) } vec![candidate] } else { - // Reuse the bound port across each advertised IP, since str0m's ICE agent - // picks the destination port from the candidate it's pairing against. - advertise.iter().map(|addr| SocketAddr::new(addr.ip(), port)).collect() + // Sent as given: a NAT or load balancer may forward another public port to + // the bound one. Port 0 asks for the bound port. + advertise + .iter() + .map(|addr| match addr.port() { + 0 => SocketAddr::new(addr.ip(), port), + _ => *addr, + }) + .collect() }; for addr in &candidates { From 2a2b448a61109cf7ef72f63d7aca385de18419b9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 06:19:53 -0800 Subject: [PATCH 3/5] moq-webrtc's server binds its UDP socket at startup Server::new becomes Server::bind(addr, config).await, binding the shared media socket and failing if it cannot, so the CLI reports a bad --udp-bind before it says it is ready. The last clone releases the port. Advertised ICE candidates keep their port (0 takes the bound one), and client::Config::ice_candidates, which nothing set, is gone. Co-Authored-By: Claude Opus 5.5 --- rs/moq-cli/src/args.rs | 12 ++++++++++++ rs/moq-webrtc/MIGRATE.md | 15 --------------- rs/moq-webrtc/src/lib.rs | 8 ++++---- rs/moq-webrtc/src/server/whep.rs | 4 ++-- rs/moq-webrtc/src/server/whip.rs | 13 +++++-------- rs/moq-webrtc/src/session.rs | 11 ----------- 6 files changed, 23 insertions(+), 40 deletions(-) diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index 41aab58a0c5..8995db60cee 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -1797,6 +1797,18 @@ mod tests { } } + /// The WebRTC media socket flags configure the listener, so a dialer refuses them. + #[test] + fn rtc_media_flags_need_the_listener() { + for flag in [["--udp-bind", "[::]:5000"], ["--public-addr", "203.0.113.1:5000"]] { + let listen = [&["rtc", "--listen", "127.0.0.1:8443"][..], &flag].concat(); + export(&listen).unwrap().validate().unwrap(); + let connect = [&["rtc", "--connect", "http://remote/whip"][..], &flag].concat(); + let err = export(&connect).err().expect("a dialer took a listener flag"); + assert!(err.to_string().contains("--listen"), "{flag:?}: {err}"); + } + } + /// `--report` and `--echo-path` go where the CLI builds the one catalog they add a section to. #[test] fn catalog_sections_need_a_catalog_the_cli_builds() { diff --git a/rs/moq-webrtc/MIGRATE.md b/rs/moq-webrtc/MIGRATE.md index 54e6358dd6d..424cf864612 100644 --- a/rs/moq-webrtc/MIGRATE.md +++ b/rs/moq-webrtc/MIGRATE.md @@ -4,21 +4,6 @@ How to update your code for each breaking change, newest first. ## Unreleased -### `Server::bind` binds the media socket - -`Server::new(config)` is `Server::bind(addr, config).await?`: it binds the shared UDP socket at `addr` and fails if it cannot, instead of on the first accept. -`server::Socket` and `server::Config::socket` are gone; pass the address you set as `Socket::Bind(addr)`, or `"0.0.0.0:0"` for the old default. -`Server::local_addr` reports the bound address. - -### Advertised candidates keep their port - -`server::Config::ice_candidates` are advertised as given, port included, instead of with the bound port. -Write the public port you forward to the bound one, or port 0 to keep advertising the bound port. - -### `client::Config::ice_candidates` is gone - -Nothing read a client's advertised candidates usefully: the server learns a client's address from its ICE checks. Drop the field; `client::Config` has no options yet. - ### `Config::max_age` of `None` is unlimited ([#7729](https://github.com/moq-dev/moq/pull/7729)) `server::Config::max_age` and `client::Config::max_age` default to `Some(hang::container::MAX_AGE)` (30 s), and `None` now sets no publisher limit instead of keeping that default. diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index 6f0c3376942..6dc7c385c89 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -194,7 +194,7 @@ mod tests { let (old_route, mut old, old_catalog) = publish_opus(&origin, moq_net::Instance::random()); push(&mut *old, 20_000, OPUS_PACKET); - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) .await .unwrap(); let whep_origin = origin.consume(); @@ -262,7 +262,7 @@ mod tests { let (old_route, mut old, old_catalog) = publish_opus(&origin, moq_net::Instance::random()); push(&mut *old, 20_000, OPUS_PACKET); - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) .await .unwrap(); let ingest_origin = moq_tokio::origin::spawn(); @@ -329,7 +329,7 @@ mod tests { tokio::task::JoinHandle<()>, tokio::sync::mpsc::Receiver>>, ) { - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) .await .unwrap(); let origin = moq_tokio::origin::spawn(); @@ -474,7 +474,7 @@ mod tests { drop(announcements); let server_origin = moq_tokio::origin::spawn(); - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) .await .unwrap(); let (sources_tx, mut sources_rx) = tokio::sync::mpsc::channel(2); diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index 34540120fae..5b497c36d10 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -170,7 +170,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { // CodecConfig before accept_offer so the answer intersects the peer's offer // with what the catalog actually has, instead of agreeing to a codec we can't // fulfil; set the mux's known ICE credentials on the same config. - let mux = server.mux().await?; + let mux = server.mux(); let (creds, inbound, registration) = mux.register(); let mut rtc = session::rtc_config_with_codecs(&codecs)? .set_local_ice_credentials(creds) @@ -343,7 +343,7 @@ mod tests { .expect("create broadcast"); let (sub_origin, _connection, accept) = lazy_client(pub_origin).await; - let server = crate::server::Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), Default::default()) + let server = crate::server::Server::bind("127.0.0.1:0".parse().unwrap(), Default::default()) .await .unwrap(); let _router = super::router(server, sub_origin.consume()); diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index 49e7cc33050..1df4f25ee69 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -176,7 +176,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { // Register a session on the shared media mux: known ICE credentials (so the // demux routes this peer's STUN by ufrag), an inbox to read datagrams from, // and a guard the session task holds for its lifetime (unregisters on exit). - let mux = server.mux().await?; + let mux = server.mux(); let (creds, inbound, registration) = mux.register(); let mut rtc = session::rtc_config()? .set_local_ice_credentials(creds) @@ -270,7 +270,7 @@ mod tests { /// a description str0m still parses, and an uncapped one carries no bandwidth line. #[tokio::test] async fn a_capped_answer_carries_tias() { - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), crate::server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), crate::server::Config::default()) .await .unwrap(); let origin = moq_tokio::origin::spawn(); @@ -293,10 +293,7 @@ mod tests { #[tokio::test] async fn an_advertised_candidate_keeps_its_port() { let config = crate::server::Config { - ice_candidates: vec![ - "203.0.113.1:5000".parse().unwrap(), - "[2001:db8::1]:0".parse().unwrap(), - ], + ice_candidates: vec!["203.0.113.1:5000".parse().unwrap(), "[2001:db8::1]:0".parse().unwrap()], }; let server = Server::bind("127.0.0.1:0".parse().unwrap(), config).await.unwrap(); let bound = server.local_addr().port(); @@ -319,7 +316,7 @@ mod tests { /// dropped unfinished. #[tokio::test(start_paused = true)] async fn a_session_ending_without_a_delete_ends_its_tracks() { - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), crate::server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), crate::server::Config::default()) .await .unwrap(); let origin = moq_tokio::origin::spawn(); @@ -355,7 +352,7 @@ mod tests { /// it leaves. #[tokio::test] async fn a_reconnect_replaces_the_stale_session() { - let server = Server::bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0)), crate::server::Config::default()) + let server = Server::bind("127.0.0.1:0".parse().unwrap(), crate::server::Config::default()) .await .unwrap(); let origin = moq_tokio::origin::spawn(); diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index 1d20ebdee8a..ed17814e385 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -804,17 +804,6 @@ mod tests { assert_eq!(advertised_candidates(&[], local).unwrap(), vec![local]); } - #[test] - fn advertised_candidates_reuse_bound_port_for_configured_addresses() { - let local: SocketAddr = "0.0.0.0:4444".parse().unwrap(); - let advertised = vec!["127.0.0.1:1000".parse().unwrap(), "[::1]:2000".parse().unwrap()]; - - assert_eq!( - advertised_candidates(&advertised, local).unwrap(), - vec!["127.0.0.1:4444".parse().unwrap(), "[::1]:4444".parse().unwrap()] - ); - } - #[test] fn advertised_candidates_reject_configured_unspecified_addresses() { let local: SocketAddr = "127.0.0.1:4444".parse().unwrap(); From a31e2681d04475c5ffd145237e9d247e3a622d66 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 06:21:11 -0800 Subject: [PATCH 4/5] moq-webrtc: say why the client destructures its config Co-Authored-By: Claude Opus 5.5 --- rs/moq-webrtc/src/client/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rs/moq-webrtc/src/client/mod.rs b/rs/moq-webrtc/src/client/mod.rs index eed348cd5e2..e8ab1f37d4a 100644 --- a/rs/moq-webrtc/src/client/mod.rs +++ b/rs/moq-webrtc/src/client/mod.rs @@ -36,6 +36,7 @@ impl Client { /// Fails with [`Error::UnsupportedCpu`](crate::Error::UnsupportedCpu) on a CPU /// rind can't run on. pub fn new(config: Config) -> crate::Result { + // Destructured so a new option cannot compile without being used. let Config {} = config; // reqwest reads rustls's process default and panics without one, so install rind's // unless the host already chose a provider. From 35b19090da1a38c1a263eb59557dfe4c363e72e4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 17 Nov 2026 00:45:01 -0800 Subject: [PATCH 5/5] Follow the rtc to webrtc rename in a test; yield instead of retrying for the port Co-Authored-By: Claude Sonnet 5.5 --- rs/moq-cli/src/args.rs | 6 +++--- rs/moq-webrtc/src/server/mod.rs | 16 ++++------------ 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index 5a09eac7c83..7c84c985263 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -1816,11 +1816,11 @@ mod tests { /// The WebRTC media socket flags configure the listener, so a dialer refuses them. #[test] - fn rtc_media_flags_need_the_listener() { + fn webrtc_media_flags_need_the_listener() { for flag in [["--udp-bind", "[::]:5000"], ["--public-addr", "203.0.113.1:5000"]] { - let listen = [&["rtc", "--listen", "127.0.0.1:8443"][..], &flag].concat(); + let listen = [&["webrtc", "--listen", "127.0.0.1:8443"][..], &flag].concat(); export(&listen).unwrap().validate().unwrap(); - let connect = [&["rtc", "--connect", "http://remote/whip"][..], &flag].concat(); + let connect = [&["webrtc", "--connect", "http://remote/whip"][..], &flag].concat(); let err = export(&connect).err().expect("a dialer took a listener flag"); assert!(err.to_string().contains("--listen"), "{flag:?}: {err}"); } diff --git a/rs/moq-webrtc/src/server/mod.rs b/rs/moq-webrtc/src/server/mod.rs index d0d66c6dc79..c243d01e492 100644 --- a/rs/moq-webrtc/src/server/mod.rs +++ b/rs/moq-webrtc/src/server/mod.rs @@ -279,18 +279,10 @@ mod tests { std::net::UdpSocket::bind(addr).expect_err("a live clone keeps the port"); drop(clone); - // The abort only requests cancellation: the demux task drops its socket once the - // runtime next polls it, which a single yield does not guarantee. Retry until a deadline. - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); - loop { - match std::net::UdpSocket::bind(addr) { - Ok(_) => break, - Err(err) if tokio::time::Instant::now() >= deadline => { - panic!("the dropped server kept its port: {err}") - } - Err(_) => tokio::time::sleep(std::time::Duration::from_millis(10)).await, - } - } + // The abort only schedules the demux task to be dropped; yielding lets this + // current-thread runtime run it, which drops its socket handle. + tokio::task::yield_now().await; + std::net::UdpSocket::bind(addr).expect("the dropped server kept its port"); } #[tokio::test]