diff --git a/doc/bin/cli.md b/doc/bin/cli.md index 5a46af26322..d5b2aa87f78 100644 --- a/doc/bin/cli.md +++ b/doc/bin/cli.md @@ -29,7 +29,7 @@ prebuilt CLI artifacts for 32-bit boards are not yet available. | `import` | `archive ` | Replay a recording from an object store. | | `export` | `fmp4`, `mkv`, `ts`, `flv`, `h264`, `h265` | Write a container to stdout. | | `export` | `mp4 --output ` | Record a regular MP4 that stays playable if the recording is cut short. | -| `export` | `hls --listen`, `hls --output ` | Serve the broadcast as HLS over HTTP, record it to a directory, or both. | +| `export` | `hls --hls-listen`, `hls --output ` | Serve the broadcast as HLS over HTTP, record it to a directory, or both. | | `export` | `rtmp`, `srt`, `rtc` | Serve plays (`--listen`) or push to a remote (`--connect`). | | `export` | `archive ` | Record every broadcast under the prefix into an object store. | | `play` | | Decode and play in a native window with sound. | @@ -365,7 +365,7 @@ over one connection: ```bash moq --connect https://relay.example.com/anon \ import --broadcast event.hang srt --listen 0.0.0.0:9000 \ - -- export --broadcast event.hang hls --listen 0.0.0.0:8080 \ + -- export --broadcast event.hang hls --hls-listen 0.0.0.0:8080 \ -- export --broadcast event.hang archive file:///recordings ``` diff --git a/doc/bin/hls.md b/doc/bin/hls.md index 1a7361018f2..4db658a73a3 100644 --- a/doc/bin/hls.md +++ b/doc/bin/hls.md @@ -13,7 +13,7 @@ a remote HLS master or media playlist into a broadcast. # Publish, then serve. Players open # http://localhost:8089/my-stream.hang/master.m3u8 (or manifest.mpd for DASH) ffmpeg -re -i input.mp4 -c copy -f mp4 -movflags cmaf+separate_moof+delay_moov+skip_trailer -frag_duration 1000 - | moq --connect https://relay.example.com/anon --broadcast my-stream.hang import fmp4 -moq --connect https://relay.example.com/anon --broadcast my-stream.hang export hls --listen '[::]:8089' +moq --connect https://relay.example.com/anon --broadcast my-stream.hang export hls --hls-listen '[::]:8089' # Record into ./recording, ending once the broadcast finishes moq --connect https://relay.example.com/anon --broadcast my-stream.hang export hls --output ./recording @@ -83,7 +83,7 @@ recording needs moq-lite 07 on every network hop for track discovery; see ```bash moq --connect https://relay.example.com/anon --connect-version moq-lite-07-wip --broadcast event export archive s3://recordings moq --connect https://relay.example.com/anon --broadcast event-replay.hang import archive s3://recordings/event/@ -moq --connect https://relay.example.com/anon --broadcast event-replay.hang export hls --listen '[::]:8089' +moq --connect https://relay.example.com/anon --broadcast event-replay.hang export hls --hls-listen '[::]:8089' ``` The archived catalog and media replay as recorded, so the export lists the same @@ -94,7 +94,7 @@ window as a live broadcast. `--output ` writes `master.m3u8` and each rendition's `{video,audio}/{name}/media.m3u8`, init, and `.m4s` segments into an empty or absent directory as each segment completes. Recording alone binds no HTTP port; -add `--listen` to serve and record from one stage, in which case serving goes on +add `--hls-listen` to serve and record from one stage, in which case serving goes on after the recording completes. The recording starts at the oldest segment in the `--window` and gets @@ -111,7 +111,7 @@ removed and re-added with another target, which logs a warning. A GOP longer than the target is still recorded, with a warning, so keep keyframe intervals within the declared interval. -`--listen-tls-cert`/`--listen-tls-key` or `--listen-tls-generate` serve HTTPS, +`--hls-tls-cert`/`--hls-tls-key` or `--hls-tls-generate` serve HTTPS, and `--cors-origin` opens it to browsers. HLS TLS reads `MOQ_HLS_TLS_*`; `MOQ_LISTEN_TLS_*` configures only the MoQ listener. See `moq export hls --help`. diff --git a/doc/bin/relay/index.md b/doc/bin/relay/index.md index fe2ce4f07e1..6578bc5c63c 100644 --- a/doc/bin/relay/index.md +++ b/doc/bin/relay/index.md @@ -110,13 +110,13 @@ relay.with_web(web).run().await?; ICE, DTLS, and RTP arrive on it, and its `send` answers from the same port. On a wildcard bind with several local addresses, set the reply's `Transmit.src_ip` to the `Datagram.local` it answers; left `None`, the kernel - picks the source address, which the peer may not accept. It fails unless the - tokio runtime serves QUIC: on a stream-only relay, and with `runtime.io_uring`, - whose workers do not split the port yet. -- To serve RTMP on the web ports, take `relay.rtmp()` and pass each accepted - stream to `moq_rtmp::accept_stream`. The HTTP and HTTPS listeners hand it - plaintext RTMP, and RTMPS (TLS with no ALPN) already decrypted; untaken, the - relay closes them. + picks the source address, which the peer may not accept. It is `None` once + taken, and unless the tokio runtime serves QUIC: on a stream-only relay, and + with `runtime.io_uring`, whose workers do not split the port yet. +- To serve RTMP on the web ports, take `relay.rtmp()` (`None` once taken) and + pass each accepted stream to `moq_rtmp::accept_stream`. The HTTP and HTTPS + listeners hand it plaintext RTMP, and RTMPS (TLS with no ALPN) already + decrypted; untaken, the relay closes them. See [docs.rs/moq-relay](https://docs.rs/moq-relay) and [`rs/moq-relay/examples/embed.rs`](https://github.com/moq-dev/moq/blob/main/rs/moq-relay/examples/embed.rs). diff --git a/quest/m2/api-shape/README.md b/quest/m2/api-shape/README.md index bb612304b5f..0d12fbe06e0 100644 --- a/quest/m2/api-shape/README.md +++ b/quest/m2/api-shape/README.md @@ -58,6 +58,5 @@ Rejected in planning: - [Transports take shared types](/quest/m2/api-shape/transport.md) - moq-uring takes a congestion factory and rustls configs, and the tokio server request stops exposing its QUIC internals - [Crates re-export no whole crate](/quest/m2/api-shape/reexports.md) - no moq crate re-exports a whole crate, moq's own included, so a dependency bump is no moq break, and moq-mux's container `Guard` gets a name - [Media crates' small surface fixes](/quest/m2/api-shape/media.md) - exporters, the container consumer, catalog color range, rate grant, moq-stats, JSON, and MSF each have one path and one name -- [Apps' small surface fixes](/quest/m2/api-shape/apps.md) - the relay, gateways, moq-hls, moq-cli, and moq-boy drop dead or unreachable surface and gain role names - [JS packages' small surface fixes](/quest/m2/api-shape/js.md) - track info, connection, qmux, watch, publish, ui, video, boy, and auth exports each have one path and one name - [Bindings' small surface fixes](/quest/m2/api-shape/bindings.md) - Go's read cancel, JSON producer construction, and the Python wheel's test module diff --git a/quest/m2/api-shape/apps.md b/quest/m2/api-shape/apps.md deleted file mode 100644 index 64ffd89b20a..00000000000 --- a/quest/m2/api-shape/apps.md +++ /dev/null @@ -1,41 +0,0 @@ -# [M] Apps' small surface fixes - -## Goal - -- moq-relay: - - `Internal::with_uring` becomes crate-private; it takes a type nobody - outside can build since `uring` went private. - - The hidden refusals for config keys and flags `release` never shipped - (`[session]`, `[peer]`, `--peer-*`, `--limits-*-requests`, - `auth.verifications`) are deleted. - - `cluster::Options.session` becomes `client`, matching its type and the - `[limits.client]` key. - - `Relay::{rtmp, webrtc}` become take-once `&mut self -> Option<_>`, like - `admissions()`. - - `session::View` and `shutdown::{Tally, Drained}` get - `#[non_exhaustive]`. -- moq-webrtc drops the dead `Error::{SessionNotFound, SessionClosed}` and - hides `p2p` (`#[doc(hidden)]`, as on release) until the - [m4 p2p work](/quest/m4/p2p/README.md) has a caller. -- moq-srt's `dial` module becomes private; `Client` keeps one path. -- moq-hls gains `Error::is_denied()`, so embedders stop matching nested - errors. -- `moq export hls`'s listener flags become `--hls-listen` and - `--hls-tls-{cert,key,generate,root}`, matching the `MOQ_HLS_*` - environment, with named refusals for the old flags, which shipped. -- moq-boy's Rust crate stops exporting its internals (the JS half is in - [the JS child](/quest/m2/api-shape/js.md)). -- moq-relay's `cluster::Options.network`, a `moq_tokio::sim::Network` test - hook added by [moq-dev/moq#8139](https://github.com/moq-dev/moq/pull/8139), - is `#[doc(hidden)]` test support, so the published config names no - simulator type. If an embedder needs injected dials, the shape is a - take-once `Cluster::dials()` handle, not a config field (added - 2026-11-07, maintainer, /quest-plan from the 2026-11-07 API sweep of open PRs and remaining quests). - -## Plan - -Found by the 2026-11-07 API shape audit (apps); see the -[epic](/quest/m2/api-shape/README.md). Decided 2026-11-07 (maintainer): -✅ hide `p2p` until m4 (rejected: keep it public; delete it). Gateway ingest -is [gateway-ingest](/quest/m2/gateway-ingest.md). Downstream code that -matches the deleted webrtc variants loses only dead arms. diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index 3f79060000d..da966a9c8c5 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -1079,7 +1079,7 @@ impl Export { ExportSink::Flv(args) => found.extend(args.deprecated()), ExportSink::H264(args) | ExportSink::H265(args) => found.extend(args.deprecated()), ExportSink::Rtmp(rtmp) => found.extend(rtmp.deprecated()), - ExportSink::Hls(hls) => found.extend(hls.tls.deprecated()), + ExportSink::Hls(hls) => found.extend(hls.deprecated()), _ => {} } found @@ -1792,7 +1792,7 @@ mod tests { fn sinks_without_selection_refuse_it() { let sinks = [ ["ts"].as_slice(), - &["hls", "--listen", "127.0.0.1:8080"], + &["hls", "--hls-listen", "127.0.0.1:8080"], &["rtmp", "--listen", "127.0.0.1:1935"], &["srt", "--listen", "127.0.0.1:9000"], &["rtc", "--listen", "127.0.0.1:8443"], @@ -1899,7 +1899,11 @@ mod tests { for sink in ["ts", "fmp4", "mkv", "flv", "h264", "h265"] { export(&["--echo", "alice", sink]).unwrap().validate().unwrap(); } - for sink in [["hls", "--listen", "127.0.0.1:8080"].as_slice(), &["report"], &["echo"]] { + for sink in [ + ["hls", "--hls-listen", "127.0.0.1:8080"].as_slice(), + &["report"], + &["echo"], + ] { let err = export(&[["--echo", "alice"].as_slice(), sink].concat()) .unwrap() .validate() @@ -2119,8 +2123,37 @@ mod tests { let reported = err.to_string(); assert!(reported.contains("--tls-cert"), "{reported}"); - assert!(reported.contains("--listen-tls-cert"), "{reported}"); - assert!(reported.contains("--listen-tls-root"), "{reported}"); + assert!(reported.contains("--hls-tls-cert"), "{reported}"); + assert!(reported.contains("--hls-tls-root"), "{reported}"); + } + + /// The released `export hls --listen*` spellings name their `--hls-*` replacements + /// rather than reach the MoQ listener's flags of the same name. + #[test] + fn released_hls_listener_flags_are_refused() { + for (old, value, new) in [ + ("--listen", "127.0.0.1:8080", "--hls-listen"), + ("--listen-tls-cert", "cert.pem", "--hls-tls-cert"), + ("--listen-tls-key", "key.pem", "--hls-tls-key"), + ("--listen-tls-generate", "localhost", "--hls-tls-generate"), + ("--listen-tls-root", "ca.pem", "--hls-tls-root"), + ] { + let Err(err) = Invocation::try_parse_from([ + "moq", + "--connect", + "http://relay/anon", + "--broadcast", + "room", + "export", + "hls", + old, + value, + ]) else { + panic!("{old} on export hls must not start a run"); + }; + let reported = err.to_string(); + assert!(reported.contains(old) && reported.contains(new), "{reported}"); + } } /// One released spelling stops the run even when the rest of the command line is @@ -2309,7 +2342,7 @@ mod tests { "--broadcast", "cam1.hang", "hls", - "--listen", + "--hls-listen", "0.0.0.0:8080", ]) .unwrap(); diff --git a/rs/moq-cli/src/hls.rs b/rs/moq-cli/src/hls.rs index fee57d0b649..510bab1aca5 100644 --- a/rs/moq-cli/src/hls.rs +++ b/rs/moq-cli/src/hls.rs @@ -14,7 +14,7 @@ use crate::moq::{ImportTarget, notify_ready}; mod record; -/// Where `export hls` serves when neither `--listen` nor `--output` is given. +/// Where `export hls` serves when neither `--hls-listen` nor `--output` is given. const LISTEN: SocketAddr = SocketAddr::new(std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED), 8089); /// HLS import (pull a remote playlist) args. @@ -37,9 +37,13 @@ pub struct ImportArgs { pub struct ExportArgs { /// HTTP listener for the HLS endpoints. Defaults to `[::]:8089` unless `--output` records /// without serving. - #[usage(long, value_name = "ADDR")] + #[usage(long = "hls-listen", value_name = "ADDR")] pub listen: Option, + /// The released `--listen`, refused by name: the MoQ side's `--listen` is another listener. + #[usage(name = "hls-legacy-listen", long = "listen", hide = true)] + legacy_listen: Option, + /// Record the broadcast's playlists and segments into this directory, which must be empty /// or absent. Fails if the recording ends abruptly or misses a segment. #[usage(long, value_name = "DIR", value_hint = usage_rs::ValueHint::DirPath)] @@ -61,25 +65,28 @@ pub struct ExportArgs { } /// TLS for the HLS HTTP listener, independent of the MoQ listener's environment. -#[derive(usage_rs::Args, Clone)] +#[derive(usage_rs::Args, Clone, Default)] #[usage(unknown_flags = "error", args_override_self = false)] pub struct Tls { /// Load the HLS listener's PEM certificate. - #[usage(long = "listen-tls-cert", env = "MOQ_HLS_TLS_CERT", value_hint = usage_rs::ValueHint::FilePath)] + #[usage(long = "hls-tls-cert", env = "MOQ_HLS_TLS_CERT", value_hint = usage_rs::ValueHint::FilePath)] pub cert: Vec, /// Load the HLS listener's PEM private key. - #[usage(long = "listen-tls-key", env = "MOQ_HLS_TLS_KEY", value_hint = usage_rs::ValueHint::FilePath)] + #[usage(long = "hls-tls-key", env = "MOQ_HLS_TLS_KEY", value_hint = usage_rs::ValueHint::FilePath)] pub key: Vec, /// Generate the HLS listener's self-signed certificate for these hostnames. - #[usage(long = "listen-tls-generate", env = "MOQ_HLS_TLS_GENERATE", delimiter = ',')] + #[usage(long = "hls-tls-generate", env = "MOQ_HLS_TLS_GENERATE", delimiter = ',')] pub generate: Vec, /// Trust these PEM roots for optional HLS client certificates. - #[usage(long = "listen-tls-root", env = "MOQ_HLS_TLS_ROOT", delimiter = ',', value_hint = usage_rs::ValueHint::FilePath)] + #[usage(long = "hls-tls-root", env = "MOQ_HLS_TLS_ROOT", delimiter = ',', value_hint = usage_rs::ValueHint::FilePath)] pub root: Vec, + + // Every released spelling of each listener TLS setting. `MOQ_LISTEN_TLS_*` stay + // out: they configure the MoQ listener now. #[usage( name = "hls-legacy-cert", long = "tls-cert", - alias = "server-tls-cert", + aliases("server-tls-cert", "listen-tls-cert"), env = "MOQ_SERVER_TLS_CERT", hide = true )] @@ -88,7 +95,7 @@ pub struct Tls { #[usage( name = "hls-legacy-key", long = "tls-key", - alias = "server-tls-key", + aliases("server-tls-key", "listen-tls-key"), env = "MOQ_SERVER_TLS_KEY", hide = true )] @@ -97,7 +104,7 @@ pub struct Tls { #[usage( name = "hls-legacy-generate", long = "tls-generate", - alias = "server-tls-generate", + aliases("server-tls-generate", "listen-tls-generate"), env = "MOQ_SERVER_TLS_GENERATE", delimiter = ',', hide = true @@ -107,6 +114,7 @@ pub struct Tls { #[usage( name = "hls-legacy-root", long = "server-tls-root", + alias = "listen-tls-root", env = "MOQ_SERVER_TLS_ROOT", delimiter = ',', hide = true @@ -114,35 +122,46 @@ pub struct Tls { legacy_root: Vec, } -impl Tls { +impl ExportArgs { + /// The released spellings in use, each paired with what replaced it. pub(super) fn deprecated(&self) -> moq_tokio::cli::Deprecated { + let mut found = self.tls.deprecated(); + if self.legacy_listen.is_some() { + found.flag("--listen", None, "--hls-listen"); + } + found + } +} + +impl Tls { + fn deprecated(&self) -> moq_tokio::cli::Deprecated { let mut found = moq_tokio::cli::Deprecated::default(); if !self.legacy_cert.is_empty() { found.flag( - "--tls-cert", + "--listen-tls-cert, --tls-cert, --server-tls-cert", Some("MOQ_SERVER_TLS_CERT"), - "--listen-tls-cert / MOQ_HLS_TLS_CERT", + "--hls-tls-cert / MOQ_HLS_TLS_CERT", ); } if !self.legacy_key.is_empty() { found.flag( - "--tls-key", + "--listen-tls-key, --tls-key, --server-tls-key", Some("MOQ_SERVER_TLS_KEY"), - "--listen-tls-key / MOQ_HLS_TLS_KEY", + "--hls-tls-key / MOQ_HLS_TLS_KEY", ); } if !self.legacy_generate.is_empty() { found.flag( - "--tls-generate", + "--listen-tls-generate, --tls-generate, --server-tls-generate", Some("MOQ_SERVER_TLS_GENERATE"), - "--listen-tls-generate / MOQ_HLS_TLS_GENERATE", + "--hls-tls-generate / MOQ_HLS_TLS_GENERATE", ); } if !self.legacy_root.is_empty() { found.flag( - "--server-tls-root", + "--listen-tls-root, --server-tls-root", Some("MOQ_SERVER_TLS_ROOT"), - "--listen-tls-root / MOQ_HLS_TLS_ROOT", + "--hls-tls-root / MOQ_HLS_TLS_ROOT", ); } found @@ -287,11 +306,11 @@ pub async fn export(origin: moq_net::origin::Consumer, args: ExportArgs, name: S None => { anyhow::ensure!( tls.cert.is_empty() && tls.key.is_empty() && tls.generate.is_empty() && tls.root.is_empty(), - "the HLS listener's TLS flags only apply with `export hls --listen`" + "the HLS listener's TLS flags only apply with `export hls --hls-listen`" ); anyhow::ensure!( args.cors.origin.is_empty(), - "`--cors-origin` only applies to `export hls --listen`" + "`--cors-origin` only applies to `export hls --hls-listen`" ); None } @@ -454,16 +473,8 @@ mod test { let args = ExportArgs { listen: None, output: Some(dir.path().join("recording")), - tls: Tls { - cert: Vec::new(), - key: Vec::new(), - generate: Vec::new(), - root: Vec::new(), - legacy_cert: Vec::new(), - legacy_key: Vec::new(), - legacy_generate: Vec::new(), - legacy_root: Vec::new(), - }, + legacy_listen: None, + tls: Tls::default(), window: std::time::Duration::from_secs(16).into(), cors: Default::default(), }; diff --git a/rs/moq-hls/src/error.rs b/rs/moq-hls/src/error.rs index a3c84220db8..4f1f5ca7808 100644 --- a/rs/moq-hls/src/error.rs +++ b/rs/moq-hls/src/error.rs @@ -196,6 +196,17 @@ impl Error { } } + /// Whether the source denied access to a broadcast or track, which a server answers with `403`. + pub fn is_denied(&self) -> bool { + match self { + Self::Moq(moq_net::Error::Unauthorized) | Self::Mux(moq_mux::Error::Moq(moq_net::Error::Unauthorized)) => { + true + } + Self::CatalogFailed { source } | Self::MediaFailed { source, .. } => source.is_denied(), + _ => false, + } + } + /// Whether this is the source's settled answer, which another import pass cannot change. /// /// A response that arrived is the server's answer, and only a narrow set of statuses invites @@ -249,6 +260,20 @@ pub type Result = std::result::Result; mod tests { use super::*; + /// A denial stays one however the export wraps it. + #[test] + fn denial_survives_wrapping() { + let denied = Error::Mux(moq_mux::Error::Moq(moq_net::Error::Unauthorized)); + let wrapped = Error::CatalogFailed { + source: Box::new(Error::MediaFailed { + track: "video".into(), + source: Box::new(denied), + }), + }; + assert!(wrapped.is_denied()); + assert!(!Error::Moq(moq_net::Error::NotFound).is_denied()); + } + #[tokio::test] async fn http_error_redacts_url() { // A freed port refuses the connection, so reqwest fails with the dialed URL attached. diff --git a/rs/moq-hls/src/server/routes.rs b/rs/moq-hls/src/server/routes.rs index 7089bb8d7fd..4f653399656 100644 --- a/rs/moq-hls/src/server/routes.rs +++ b/rs/moq-hls/src/server/routes.rs @@ -272,14 +272,9 @@ fn not_found() -> Response { fn server_error(err: crate::Error) -> Response { tracing::warn!(%err, "hls request failed"); // A catalog denied mid-stream still answers as a denial. - let denied = match &err { - crate::Error::CatalogFailed { source } => source.as_ref(), - err => err, - }; - let status = match denied { - crate::Error::Moq(moq_net::Error::Unauthorized) - | crate::Error::Mux(moq_mux::Error::Moq(moq_net::Error::Unauthorized)) => StatusCode::FORBIDDEN, - _ => StatusCode::INTERNAL_SERVER_ERROR, + let status = match err.is_denied() { + true => StatusCode::FORBIDDEN, + false => StatusCode::INTERNAL_SERVER_ERROR, }; (status, [(header::CACHE_CONTROL, "no-store")]).into_response() } diff --git a/rs/moq-relay/benches/session.rs b/rs/moq-relay/benches/session.rs index c8a7e0923de..9cfe86ac852 100644 --- a/rs/moq-relay/benches/session.rs +++ b/rs/moq-relay/benches/session.rs @@ -77,7 +77,7 @@ impl Backend for Relay { let pool = cache.pool.clone(); let mut options = cluster::Options::default(); // The shared sweeps include more announcements than a default ordinary client. - options.session.announces = options.peer.announces; + options.client.announces = options.peer.announces; let mut stats = stats::Config::default(); stats.enabled = true; stats.node = Some(id.to_string()); diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index 5f14055fe81..64c8a60b3b9 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -31,7 +31,7 @@ const ATTACH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); #[serde_as] #[derive(usage_rs::Args, Clone, Default, Serialize, Deserialize)] #[usage(unknown_flags = "error", args_override_self = false)] -#[serde(default)] +#[serde(default, deny_unknown_fields)] #[non_exhaustive] pub struct Config { /// The auth server asked once per session event: `connect`, `attach`, `revalidate`, and @@ -84,10 +84,6 @@ pub struct Config { #[serde_as(as = "OneOrMany<_>")] pub public_publish: Vec, - #[usage(skip)] - #[serde(rename = "verifications", skip_serializing)] - pub(crate) removed_verifications: Option, - /// The 0.14 flags and env vars #3688 removed, kept parsing but hidden. Never /// read as settings: [`deprecated`](Self::deprecated) names what replaced each. #[usage(flatten)] @@ -139,9 +135,6 @@ const VERIFICATIONS: usize = 128; #[derive(Clone, Debug, Default, usage_rs::Args)] #[usage(unknown_flags = "error", args_override_self = false)] pub(crate) struct Legacy { - #[usage(long = "auth-verifications", env = "MOQ_AUTH_VERIFICATIONS", hide = true)] - verifications: Option, - #[usage(name = "auth-key", long = "auth-key", env = "MOQ_AUTH_KEY", hide = true)] key: Option, #[usage(name = "auth-key-dir", long = "auth-key-dir", env = "MOQ_AUTH_KEY_DIR", hide = true)] @@ -208,22 +201,6 @@ impl Config { /// ignored. pub fn deprecated(&self) -> moq_tokio::cli::Deprecated { let mut found = moq_tokio::cli::Deprecated::default(); - if self.legacy.verifications.is_some() { - found.changed( - "--auth-verifications", - Some("MOQ_AUTH_VERIFICATIONS"), - "the fixed per-session verification policy", - "the configurable verification window is removed", - ); - } - if self.removed_verifications.is_some() { - found.toml( - "[auth] verifications", - "the fixed per-session verification policy", - None, - ); - } - let legacy = &self.legacy; for (set, flag, env, toml, new) in [ ( @@ -1673,15 +1650,11 @@ mod tests { assert!(grant.publish.is_empty()); } - /// Removed explicit window values, including zero, are refused by name. + /// An unknown `[auth]` key, such as the never-released `verifications`, fails to parse. #[test] - fn configurable_verifications_are_refused() { - for value in [0, 4] { - let parsed: Config = - toml::from_str(&format!("url = \"http://127.0.0.1:4440/\"\nverifications = {value}\n")).unwrap(); - let error = parsed.validate(false).unwrap_err(); - assert!(error.to_string().contains("verifications"), "{error}"); - } + fn unknown_keys_are_refused() { + let error = toml::from_str::("url = \"http://127.0.0.1:4440/\"\nverifications = 4\n").unwrap_err(); + assert!(error.to_string().contains("verifications"), "{error}"); } /// Public rules grant a certificate what they grant anyone, so a client CA diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs index 45c6959b97f..7679eb41816 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -1022,7 +1022,7 @@ struct LanAuth { #[non_exhaustive] pub struct Options { /// Session limits for ordinary client sessions. - pub session: crate::limits::Client, + pub client: crate::limits::Client, /// Session and QUIC limits for authenticated peers and outbound cluster links. pub peer: crate::limits::Peer, /// Cluster identity, peers, and discovery. @@ -1305,7 +1305,7 @@ fn dialer<'a>(cluster: &'a Cluster, token: &'a ClusterToken) -> impl FnMut(DialT /// remote peers. #[derive(Clone)] pub struct Cluster { - session_limits: moq_net::session::Limits, + client_limits: moq_net::session::Limits, peer_limits: moq_net::session::Limits, peer_quic: crate::limits::Quic, config: Config, @@ -1387,7 +1387,7 @@ impl Cluster { if lease.token().peer { self.peer_limits } else { - self.session_limits + self.client_limits } } @@ -1434,7 +1434,7 @@ impl Cluster { let Options { config, cache, - session, + client, peer, stats, #[cfg(feature = "test-support")] @@ -1488,7 +1488,7 @@ impl Cluster { let nodes = crate::nodes::Nodes::default(); tracing::info!(hop_id = %origin.hop(), "cluster initialized"); let cluster = Cluster { - session_limits: session.resolve(), + client_limits: client.resolve(), peer_limits: peer.resolve(), peer_quic: peer.quic, config, @@ -2578,7 +2578,7 @@ mod tests { #[tokio::test] async fn session_limits_follow_the_admitted_grant() { let mut options = Options::default(); - options.session.announces = 2; + options.client.announces = 2; options.peer.announces = 20; let cluster = Cluster::spawn(options).unwrap(); for (peer, upstream, expected) in [(false, false, 2), (true, false, 20), (true, true, 20)] { diff --git a/rs/moq-relay/src/config.rs b/rs/moq-relay/src/config.rs index de1b5e184c8..0154b9e5a0a 100644 --- a/rs/moq-relay/src/config.rs +++ b/rs/moq-relay/src/config.rs @@ -26,13 +26,6 @@ pub struct Config { #[usage(flatten)] pub limits: crate::limits::Config, - #[usage(skip)] - #[serde(rename = "session", skip_serializing)] - legacy_session: Option, - #[usage(skip)] - #[serde(rename = "peer", skip_serializing)] - legacy_peer: Option, - /// The QUIC/TLS configuration for the server. #[usage(flatten)] #[serde(default)] @@ -306,13 +299,6 @@ impl Config { /// replaced it. fn deprecated(&self) -> moq_tokio::cli::Deprecated { let mut deprecated = self.quic.deprecated(); - deprecated.extend(self.limits.legacy.deprecated()); - if self.legacy_session.is_some() { - deprecated.toml("[session]", "[limits.client]", None); - } - if self.legacy_peer.is_some() { - deprecated.toml("[peer]", "[limits.peer]", None); - } deprecated.extend(self.listen.deprecated()); deprecated.extend(self.connect.deprecated()); deprecated.extend(self.cluster.deprecated()); @@ -445,19 +431,7 @@ mod tests { /// Each renamed setting: its old flag, old variable, a value equal to the old default, /// and the replacement its refusal names. - const OBSOLETE_ROLE_SOURCES: [(&str, &str, &str, &str); 5] = [ - ( - "--session-announces", - "MOQ_SESSION_ANNOUNCES", - "1000", - "--limits-client-announces", - ), - ( - "--peer-announces", - "MOQ_PEER_ANNOUNCES", - "100000", - "--limits-peer-announces", - ), + const OBSOLETE_ROLE_SOURCES: [(&str, &str, &str, &str); 2] = [ ( "--cluster-connect-api", "MOQ_CLUSTER_CONNECT_API", @@ -470,12 +444,6 @@ mod tests { "api.pem", "--cluster-api-tls-root", ), - ( - "--auth-verifications", - "MOQ_AUTH_VERIFICATIONS", - "128", - "fixed per-session verification policy", - ), ]; /// Renames refuse an explicit variable even when its value equals the old default. @@ -508,11 +476,8 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("obsolete.toml"); for (body, replacement) in [ - ("[session]\nannounces = 1000", "[limits.client]"), - ("[peer]\nannounces = 100000", "[limits.peer]"), ("[cluster]\nconnect_api = 'peers.json'", "[cluster.api] url"), ("[cluster]\nconnect_api_tls_root = []", "[cluster.api.tls] root"), - ("[auth]\nverifications = 128", "fixed per-session verification policy"), ] { std::fs::write(&path, body).unwrap(); let error = @@ -601,22 +566,6 @@ mod tests { assert_eq!(config.limits.peer.resolve().announces, 90); } - /// Sizing the removed request window refuses to start rather than run without the - /// setting. - #[test] - fn removed_request_limits_are_refused() { - if !test_env::Env::without(&["MOQ_LIMITS_CLIENT_REQUESTS", "MOQ_LIMITS_PEER_REQUESTS"]).isolate() { - return; - } - let error = Config::parse_and_merge(["moq-relay", "--limits-peer-requests=1000"]).unwrap_err(); - assert!(error.to_string().contains("--limits-peer-requests"), "{error}"); - - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("limits.toml"); - std::fs::write(&path, "[limits.client]\nrequests = 8\n").unwrap(); - assert!(Config::parse_and_merge([std::ffi::OsString::from("moq-relay"), path.into()]).is_err()); - } - /// `[limits.peer.quic]` mirrors `[quic]`'s keys without touching `[quic]` itself. #[test] fn peer_quic_table_merges_with_flags() { diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index 955c562be14..32c4974e61a 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -9,7 +9,7 @@ //! - `/metrics` - this node's own traffic counters as OpenMetrics text //! exposition, plus the accept-loop health of its TCP listeners //! ([`with_listeners`](Internal::with_listeners)) and the per-worker health of -//! its io_uring runtime ([`with_uring`](Internal::with_uring)), and the +//! its io_uring runtime, and the //! progress of a shutdown drain ([`with_shutdown`](Internal::with_shutdown)). A distinct plane //! from both the customer `web` surface and the MoQ `.stats` broadcast: the same //! atomics, but a different transport and audience (an ops scraper, not a @@ -50,13 +50,12 @@ use prometheus_client::{ metrics::{MetricType, counter::ConstCounter, gauge::ConstGauge}, }; -/// One io_uring worker's counters, as [`with_uring`](Internal::with_uring) takes -/// them. +/// One io_uring worker's counters, as `Internal::with_uring` takes them. /// /// Uninhabited when the relay is built without the io_uring listener, so the /// list is always empty there and the renderer skips itself, rather than -/// `cfg`-ing the two fields, the two struct literals that fill them, the -/// builder and the renderer's signature separately. +/// `cfg`-ing the two fields, the two struct literals that fill them, and the +/// renderer's signature separately. #[cfg(all(target_os = "linux", feature = "_uring"))] type UringWorker = moq_uring::metrics::Metrics; @@ -235,10 +234,8 @@ impl Internal { /// Register them before the threads start, so a worker that never came up /// (or has died) still has a series that has stopped moving rather than no /// series at all. - /// - /// Off the io_uring build the item type is uninhabited, so there is nothing - /// to register and nothing is rendered. - pub fn with_uring(mut self, workers: impl IntoIterator) -> Self { + #[cfg(all(target_os = "linux", feature = "_uring"))] + pub(crate) fn with_uring(mut self, workers: impl IntoIterator) -> Self { self.uring.extend(workers); self } diff --git a/rs/moq-relay/src/limits.rs b/rs/moq-relay/src/limits.rs index 561825c0ef8..e6d50f324b2 100644 --- a/rs/moq-relay/src/limits.rs +++ b/rs/moq-relay/src/limits.rs @@ -14,9 +14,6 @@ pub struct Config { /// Session and QUIC limits for authenticated cluster peers. #[usage(flatten)] pub peer: Peer, - #[usage(flatten)] - #[serde(skip)] - pub(crate) legacy: Legacy, } /// Session limits for ordinary client sessions. @@ -160,70 +157,3 @@ fn resolve(announces: usize) -> moq_net::session::Limits { limits.announces = announces; limits } - -#[derive(usage_rs::Args, Clone, Debug, Default)] -pub(crate) struct Legacy { - #[usage(long = "session-announces", env = "MOQ_SESSION_ANNOUNCES", hide = true)] - session_announces: Option, - #[usage(long = "peer-announces", env = "MOQ_PEER_ANNOUNCES", hide = true)] - peer_announces: Option, - #[usage(long = "peer-quic-max-streams", env = "MOQ_PEER_QUIC_MAX_STREAMS", hide = true)] - peer_quic_max_streams: Option, - #[usage(long = "peer-quic-receive-window", env = "MOQ_PEER_QUIC_RECEIVE_WINDOW", hide = true)] - peer_quic_receive_window: Option, - #[usage(long = "peer-quic-send-window", env = "MOQ_PEER_QUIC_SEND_WINDOW", hide = true)] - peer_quic_send_window: Option, - #[usage(long = "limits-client-requests", env = "MOQ_LIMITS_CLIENT_REQUESTS", hide = true)] - client_requests: Option, - #[usage(long = "limits-peer-requests", env = "MOQ_LIMITS_PEER_REQUESTS", hide = true)] - peer_requests: Option, -} - -impl Legacy { - pub(crate) fn deprecated(&self) -> moq_tokio::cli::Deprecated { - let mut found = moq_tokio::cli::Deprecated::default(); - if self.session_announces.is_some() { - found.flag( - "--session-announces", - Some("MOQ_SESSION_ANNOUNCES"), - "--limits-client-announces", - ); - } - if self.peer_announces.is_some() { - found.flag( - "--peer-announces", - Some("MOQ_PEER_ANNOUNCES"), - "--limits-peer-announces", - ); - } - if self.peer_quic_max_streams.is_some() { - found.flag( - "--peer-quic-max-streams", - Some("MOQ_PEER_QUIC_MAX_STREAMS"), - "--limits-peer-quic-max-streams", - ); - } - if self.peer_quic_receive_window.is_some() { - found.flag( - "--peer-quic-receive-window", - Some("MOQ_PEER_QUIC_RECEIVE_WINDOW"), - "--limits-peer-quic-receive-window", - ); - } - if self.peer_quic_send_window.is_some() { - found.flag( - "--peer-quic-send-window", - Some("MOQ_PEER_QUIC_SEND_WINDOW"), - "--limits-peer-quic-send-window", - ); - } - const REQUESTS: &str = "stream flow control bounds requests"; - if self.client_requests.is_some() { - found.removed("--limits-client-requests", Some("MOQ_LIMITS_CLIENT_REQUESTS"), REQUESTS); - } - if self.peer_requests.is_some() { - found.removed("--limits-peer-requests", Some("MOQ_LIMITS_PEER_REQUESTS"), REQUESTS); - } - found - } -} diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index b5fe4b74765..71cd873acd9 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -294,7 +294,7 @@ impl Relay { let mut cluster_options = cluster::Options::new(config.cluster) .with_cache(cache) .with_stats(config.stats); - cluster_options.session = config.limits.client; + cluster_options.client = config.limits.client; cluster_options.peer = config.limits.peer; let (cluster, driver) = cluster::Cluster::new(cluster_options)?; let mut cluster = cluster.with_connect(config.connect.clone(), config.quic.clone()); @@ -429,21 +429,19 @@ impl Relay { /// The WebRTC media path (ICE, DTLS, and RTP) arriving on the QUIC port, /// for an embedder's WebRTC stack to serve and answer through the same port. /// - /// Until a feed is taken, and once every feed is dropped, that traffic is - /// dropped and counted. Fails when no tokio listener serves QUIC: a stream-only - /// relay, or one on the io_uring workers, which do not split the port yet. + /// Until it is taken, and once it is dropped, that traffic is + /// dropped and counted. `None` once taken, or when no tokio listener serves + /// QUIC: a stream-only relay, or one on the io_uring workers, which do not + /// split the port yet. #[cfg(feature = "_quic")] - pub fn webrtc(&self) -> anyhow::Result { - let demux = self - .demux - .as_ref() - .context("the WebRTC media path needs QUIC served by the tokio runtime")?; - Ok(demux.webrtc()) + pub fn webrtc(&mut self) -> Option { + self.demux.take().map(|demux| demux.webrtc()) } /// The RTMP and RTMPS connections the public web listeners classify, for the /// embedder to serve; see [`web::Web::rtmp`]. Untaken, they are logged and closed. - pub fn rtmp(&mut self) -> web::rtmp::Incoming { + /// `None` once taken. + pub fn rtmp(&mut self) -> Option { self.web.rtmp() } diff --git a/rs/moq-relay/src/session.rs b/rs/moq-relay/src/session.rs index 7537fdc8cc3..2bfaea4841a 100644 --- a/rs/moq-relay/src/session.rs +++ b/rs/moq-relay/src/session.rs @@ -453,6 +453,7 @@ impl IntoResponse for Error { #[serde_as] #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[non_exhaustive] pub struct View { /// Random 128-bit hex, unique per session. pub id: String, diff --git a/rs/moq-relay/src/shutdown.rs b/rs/moq-relay/src/shutdown.rs index ccd0f94017e..53bb37e6d30 100644 --- a/rs/moq-relay/src/shutdown.rs +++ b/rs/moq-relay/src/shutdown.rs @@ -118,6 +118,7 @@ impl Signals { /// The sessions a drain is waiting on. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] pub struct Tally { /// Served sessions whose closure has not yet been observed by supervision. pub open: usize, @@ -127,6 +128,7 @@ pub struct Tally { /// How the drain ended, including sessions cut by its deadline. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub struct Drained { /// Sessions still open at the deadline that were force-closed. pub forced: usize, diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index b86f6a33334..cbafb369f80 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -278,11 +278,9 @@ impl Web { /// RTMP opens with a byte no HTTP request or TLS ClientHello starts with, and an /// RTMPS client negotiates no ALPN, so both share the web ports. Until this is /// called, or once the returned consumer is dropped, they are logged and closed. - /// A later call replaces the earlier consumer. - pub fn rtmp(&mut self) -> rtmp::Incoming { - let (handoff, incoming) = rtmp::Handoff::new(); - self.rtmp = handoff; - incoming + /// `None` once taken. + pub fn rtmp(&mut self) -> Option { + self.rtmp.incoming() } /// Serve `tls://` on the HTTPS listener with `acceptor`, usually @@ -2231,7 +2229,7 @@ mod tests { .with_listen(&listen(None)) .bind() .unwrap(); - let incoming = rtmp.then(|| web.rtmp()); + let incoming = rtmp.then(|| web.rtmp().expect("taken once")); let Addrs { http: Some(http), https: Some(https), diff --git a/rs/moq-relay/src/web/rtmp.rs b/rs/moq-relay/src/web/rtmp.rs index b0a6e5da99d..49c60c5a52c 100644 --- a/rs/moq-relay/src/web/rtmp.rs +++ b/rs/moq-relay/src/web/rtmp.rs @@ -60,13 +60,18 @@ impl AsyncWrite for Stream { pub(crate) struct Handoff(Arc>>>); impl Handoff { - /// A handoff and the consumer it feeds. + /// The consumer this handoff feeds, or `None` once one was taken. /// /// One slot: each connection waits on its own task for the embedder to take it, /// which the listener's idle deadline bounds like any other stalled handshake. - pub(crate) fn new() -> (Self, Incoming) { + pub(crate) fn incoming(&self) -> Option { + let mut slot = self.0.lock().unwrap_or_else(PoisonError::into_inner); + if slot.is_some() { + return None; + } let (tx, rx) = mpsc::channel(1); - (Self(Arc::new(Mutex::new(Some(tx)))), Incoming(rx)) + *slot = Some(tx); + Some(Incoming(rx)) } /// Refuse every later connection once the returned guard drops. diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index 67d24faf858..d17510bd7eb 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -1221,10 +1221,8 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { Some(registration), ))); } - assert_eq!( - observer.changed().await, - moq_relay::shutdown::Tally { open: 2, ending: 0 } - ); + let tally = observer.changed().await; + assert_eq!((tally.open, tally.ending), (2, 0)); for view in registry.list(&Default::default()) { assert_eq!(view.closed, None); assert!(serde_json::to_value(view).unwrap().get("closed").is_none()); @@ -1242,10 +1240,8 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { let closed = kio::clock::wall(); clients[0].abort(moq_net::Error::Cancel); script.ends_at_least(1, "first end").await; - assert_eq!( - observer.changed().await, - moq_relay::shutdown::Tally { open: 1, ending: 1 } - ); + let tally = observer.changed().await; + assert_eq!((tally.open, tally.ending), (1, 1)); let views = registry.list(&Default::default()); assert_eq!(views.iter().filter(|view| view.closed == Some(closed)).count(), 1); let view = views.iter().find(|view| view.closed.is_some()).unwrap(); @@ -1259,10 +1255,8 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { }); clock.advance(drain_timeout - Duration::from_secs(1)); script.ends_at_least(2, "deadline end").await; - assert_eq!( - observer.changed().await, - moq_relay::shutdown::Tally { open: 0, ending: 2 } - ); + let tally = observer.changed().await; + assert_eq!((tally.open, tally.ending), (0, 2)); assert!( !drained.is_finished(), "drain ended before the server answered the ends" @@ -1280,12 +1274,8 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { supervised.await.expect("supervisor task").expect("drained session"); } assert_eq!( - summary, - moq_relay::shutdown::Drained { - forced: 1, - ending: 1, - elapsed: Duration::from_secs(6), - } + (summary.forced, summary.ending, summary.elapsed), + (1, 1, Duration::from_secs(6)) ); assert_eq!(observer.tally(), Default::default()); assert!(registry.list(&Default::default()).is_empty()); @@ -1696,7 +1686,8 @@ async fn closes_at_expires(clock: &kio::clock::Installed, consumer: moq_auth::le )] let parked = tokio::time::timeout(Duration::from_secs(1), client.closed()).await; assert!(parked.is_err(), "the paused driver closed the transport"); - assert_eq!(observer.tally(), moq_relay::shutdown::Tally { open: 1, ending: 0 }); + let tally = observer.tally(); + assert_eq!((tally.open, tally.ending), (1, 0)); let views = registry.list(&Default::default()); assert_eq!(views.len(), 1, "registration left before its transport closed"); assert_eq!(views[0].closed, None); @@ -2114,7 +2105,7 @@ async fn relay_request_limits_distinguish_clients_and_peers() { let script = Script::new(grant); let auth = build_auth(script.spawn().await); let mut options = cluster::Options::default(); - options.session.announces = 1; + options.client.announces = 1; options.peer.announces = 2; let cluster = crate::spawn_cluster(options); let consumer = cluster.origin.consume(); diff --git a/rs/moq-relay/tests/integration/embed.rs b/rs/moq-relay/tests/integration/embed.rs index 3a688783325..f9038df7a6d 100644 --- a/rs/moq-relay/tests/integration/embed.rs +++ b/rs/moq-relay/tests/integration/embed.rs @@ -450,7 +450,7 @@ async fn uring_custom_route_and_quic() { async fn webrtc_feed(mut config: Config) { let _ = rind_rustls::default_provider().unwrap().install_default(); config.drain_timeout = Some((Duration::ZERO).into()); - let relay = Relay::load(config).await.expect("load relay").with_signals(false); + let mut relay = Relay::load(config).await.expect("load relay").with_signals(false); let quic = relay.quic_addr().expect("quic listener bound"); let feed = relay.webrtc().expect("tokio serves QUIC"); let trigger = relay.shutdown_trigger().clone(); diff --git a/rs/moq-srt/src/lib.rs b/rs/moq-srt/src/lib.rs index a5749eb8e9b..0cd1adb2eb3 100644 --- a/rs/moq-srt/src/lib.rs +++ b/rs/moq-srt/src/lib.rs @@ -31,7 +31,7 @@ #![warn(missing_docs)] -pub mod dial; +mod dial; mod error; mod server; mod ts; diff --git a/rs/moq-webrtc/src/error.rs b/rs/moq-webrtc/src/error.rs index 029987b3b23..6bdbdf52238 100644 --- a/rs/moq-webrtc/src/error.rs +++ b/rs/moq-webrtc/src/error.rs @@ -10,14 +10,6 @@ pub enum Error { #[error("unsupported codec: {0}")] UnsupportedCodec(String), - /// No live session matched the resource id (e.g. a DELETE for an unknown id). - #[error("session not found")] - SessionNotFound, - - /// The peer closed the session; the media session ended without a failure. - #[error("session closed")] - SessionClosed, - /// ICE never connected before the establishment deadline, or before the DTLS /// handshake gave up waiting for it. #[error("ICE did not connect in time")] diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index bd576e7a46a..b211bd8241b 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -1,5 +1,4 @@ -//! WebRTC for MoQ: a WHIP/WHEP gateway, and with the `p2p` feature, MoQ sessions over a -//! data channel with a browser peer (the `p2p` module). +//! WebRTC for MoQ: a WHIP/WHEP gateway. //! //! The gateway bridges WHIP (RFC 9725) and WHEP between WebRTC peers and //! [`moq_net`] broadcasts. The crate is split along two orthogonal axes @@ -41,6 +40,7 @@ pub mod client; #[cfg(feature = "p2p")] +#[doc(hidden)] pub mod p2p; pub mod rate; pub mod server; diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index 9ebe397464d..bb4e838ddbb 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -219,7 +219,6 @@ fn status_for(err: &Error) -> StatusCode { match err { Error::InvalidSdp(_) | Error::InvalidPath(_) => StatusCode::BAD_REQUEST, Error::UnsupportedCodec(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE, - Error::SessionNotFound => StatusCode::NOT_FOUND, Error::Moq(moq_net::Error::Unauthorized) => StatusCode::UNAUTHORIZED, Error::Moq(moq_net::Error::NotFound | moq_net::Error::Unroutable) => StatusCode::NOT_FOUND, _ => StatusCode::INTERNAL_SERVER_ERROR, diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index a9da35fdeb8..3ae82542171 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -231,7 +231,6 @@ fn status_for(err: &Error) -> StatusCode { match err { Error::InvalidSdp(_) | Error::InvalidPath(_) => StatusCode::BAD_REQUEST, Error::UnsupportedCodec(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE, - Error::SessionNotFound => StatusCode::NOT_FOUND, Error::Moq(moq_net::Error::Unauthorized) => StatusCode::UNAUTHORIZED, _ => StatusCode::INTERNAL_SERVER_ERROR, } diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index 385472754b5..7d18a7cb8c0 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -180,19 +180,23 @@ impl Session { } } + /// Drive the media session until it fails or the peer disconnects, which is `Ok`. pub async fn run(&mut self) -> Result<()> { let result = self.run_loop().await; // Any end but the peer's DELETE, a disconnect or an offer that never connected // included, ends the sink's tracks with its cause, so subscribers see the publisher // go rather than its tracks dropped unfinished. - if let Err(err) = &result - && let MediaRole::Ingest(sink) = &mut self.role - { - sink.abort(moq_net::Error::Transport(err.to_string())); + if let MediaRole::Ingest(sink) = &mut self.role { + let cause = match &result { + Ok(()) => "session closed".to_string(), + Err(err) => err.to_string(), + }; + sink.abort(moq_net::Error::Transport(cause)); } result } + /// Returns `Ok` only when the peer disconnects. async fn run_loop(&mut self) -> Result<()> { loop { let remb_at = self.rate.as_ref().and_then(IngestRate::remb_at); @@ -257,7 +261,7 @@ impl Session { Ok(crate::ice::Event::Rtc(event)) => self.handle_event(event)?, // No STUN servers are configured, so there is nothing to trickle. Ok(_) => {} - Err(crate::ice::Error::Closed) => return Err(Error::SessionClosed), + Err(crate::ice::Error::Closed) => return Ok(()), Err(crate::ice::Error::Timeout) => return Err(Error::IceTimeout), Err(crate::ice::Error::Rtc(err)) => return Err(Error::Rtc(err)), }, @@ -570,21 +574,17 @@ fn to_u64(value: i128) -> u64 { value.clamp(0, u64::MAX as i128) as u64 } -/// Log a finished session at the right level, then fold an ordinary peer disconnect -/// ([`Error::SessionClosed`]) into `Ok` so only genuine failures error. Keeps normal -/// WebRTC churn out of the warning stream. `role` labels the path (e.g. `"whip server"`). +/// Log a finished session at the right level, keeping normal WebRTC churn out of the +/// warning stream. `role` labels the path (e.g. `"whip server"`). pub(crate) fn end(role: &str, result: Result<()>) -> Result<()> { match &result { - Ok(()) | Err(Error::SessionClosed) => tracing::debug!(role, "session ended"), + Ok(()) => tracing::debug!(role, "session ended"), // An abandoned offer (peer answered but never connected) is normal churn, not // a failure: keep it out of the warning stream. Err(Error::IceTimeout) => tracing::debug!(role, "session ended: ICE never connected"), Err(err) => tracing::warn!(%err, role, "session ended"), } - match result { - Ok(()) | Err(Error::SessionClosed) => Ok(()), - Err(err) => Err(err), - } + result } /// Convert a str0m [`MediaTime`](str0m::media::MediaTime) to microseconds.