From 43911615c80d27396242a22688607716e1fe6dcf Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 13 Oct 2026 18:15:59 -0700 Subject: [PATCH 1/4] chore: claim CLI duration defaults quest From f4afe45d5b930bec13a53f662e56113756a97843 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 13 Oct 2026 18:30:09 -0700 Subject: [PATCH 2/4] fix(tokio): honor durations set on parsed configs Co-Authored-By: Codex --- doc/setup/upgrade.md | 9 ++ quest/m1/README.md | 1 - quest/m1/cli-duration-defaults.md | 52 ------- rs/moq-c/src/api.rs | 4 +- rs/moq-c/src/client.rs | 16 +- rs/moq-c/src/test.rs | 20 ++- rs/moq-ffi/src/session.rs | 6 +- rs/moq-gst/src/sink/session.rs | 4 +- rs/moq-relay/src/config.rs | 2 +- rs/moq-relay/src/shutdown.rs | 2 +- rs/moq-relay/tests/auth_lifetime.rs | 4 +- rs/moq-relay/tests/cluster_unknown.rs | 2 +- rs/moq-relay/tests/drills.rs | 10 +- rs/moq-relay/tests/goaway_cluster.rs | 14 +- rs/moq-relay/tests/public_rules.rs | 2 +- rs/moq-relay/tests/runtime_uring.rs | 2 +- rs/moq-relay/tests/session_revalidate.rs | 2 +- rs/moq-relay/tests/shutdown_signal.rs | 4 +- rs/moq-relay/tests/smoke.rs | 2 +- rs/moq-tokio/src/cli/duration.rs | 85 ++++++----- rs/moq-tokio/src/client.rs | 18 +-- rs/moq-tokio/src/connect.rs | 84 ++++++++--- rs/moq-tokio/src/connection.rs | 177 ++++++++++++----------- rs/moq-tokio/src/listen.rs | 34 ++++- rs/moq-tokio/src/quic.rs | 71 ++++++--- rs/moq-tokio/src/websocket.rs | 28 +++- rs/moq-tokio/tests/backend.rs | 6 +- rs/moq-tokio/tests/broadcast.rs | 16 +- rs/moq-tokio/tests/reconnect.rs | 16 +- 29 files changed, 398 insertions(+), 295 deletions(-) delete mode 100644 quest/m1/cli-duration-defaults.md diff --git a/doc/setup/upgrade.md b/doc/setup/upgrade.md index 7513e46d881..4036a14a658 100644 --- a/doc/setup/upgrade.md +++ b/doc/setup/upgrade.md @@ -19,6 +19,15 @@ error lists and rerun. These land with the next breaking release, not the 2026-09-23 train. +- **moq-tokio config durations are optional.** Wrap durations in `Some(...)` for + connect `race`, `resolution_delay`, and `timeout`; listen `timeout`; QUIC + `idle_timeout` and `keep_alive`; backoff `initial`, `max`, and `timeout`; + GOAWAY `handover`; and WebSocket `delay`. `None` uses the default, while + `Some(Duration::ZERO)` keeps each knob's zero behavior. Values set in code + now take effect on parsed and merged configs unless the flag or environment + variable was actually given. TOML keys, C ABI, binding records, and wire + formats are unchanged. + - **A QUIC load-balancer nonce needs its server id.** `listen.lb_nonce`, `--listen-quic-lb-nonce`, and `MOQ_LISTEN_QUIC_LB_NONCE` without `lb_id` stop startup. Setting `lb_id` (or `lb_nonce`) and `load_balancer` together also diff --git a/quest/m1/README.md b/quest/m1/README.md index 80e8c0927c2..ed269022bc9 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -146,7 +146,6 @@ above them. - [Plan: watch worker](/quest/m1/plan-watch-worker.md) - prototype an invisible page worker against app-spawned workers, and land the jank harness that decides - [Watch worker](/quest/m1/watch-worker.md) - watch playback runs in a worker onto an OffscreenCanvas, so main-thread jank never stalls video or audio - [Rust papercuts](/quest/m1/papercuts-rs.md) - HTTP refusals are counted, and a `u64::MAX` resume is unbounded -- [Duration parser defaults](/quest/m1/cli-duration-defaults.md) - a moq-tokio duration set in code beats the parser default on a parsed or merged config, zero included, after #5350 - [Publish channel count](/quest/m1/publish-audio-channel-count.md) - forcing a channel count on an Audio.Capture stops costing the subscriber gaps of silence - [JS request deadline](/quest/m1/js-request-deadline.md) - each JS request, PUBLISH_NAMESPACE included, has one fatal 10 s timer from create to answer and fails fast without stream credit, so nothing queues or retries - [Handshake deadline covers admission](/quest/m1/handshake-admission-deadline.md) - `listen.timeout` bounds a connection through auth admission on both listeners, replacing the hardcoded admission timeout diff --git a/quest/m1/cli-duration-defaults.md b/quest/m1/cli-duration-defaults.md deleted file mode 100644 index d5d17810364..00000000000 --- a/quest/m1/cli-duration-defaults.md +++ /dev/null @@ -1,52 +0,0 @@ -# [M] A duration set in code beats the parser default - -## Goal - -On a moq-tokio config built by the command line or merged from settings, a -duration a caller sets in code takes effect, zero included, unless its flag or -env var was actually given. #5350 fixes this for `connect.backoff.timeout`. -The rest still ignore the code: connect `race`, `resolution_delay`, and -`timeout`; `listen.timeout`; QUIC `idle_timeout` and `keep_alive`; backoff -`initial` and `max`; GOAWAY `handover`; and WebSocket `delay`. - -## Plan - -The cause, from #5350: usage builds `default_value_t` by formatting and -reparsing it, so `CliDuration::fallback` reaches the struct as an explicit -value and `CliDuration::resolve` prefers it over the typed field. And a parse -leaves each `#[usage(skip)]` typed field at `Duration::ZERO`, which `resolve` -reads as unset, so a zero set afterwards looks like no value. Zero is a real -setting for most of these fields: wait forever, disable keep-alive, dial every -address at once, or give WebSocket no head start. - -These aren't one-line fixes. Each field's public type changes, and its callers -in moq-c, moq-ffi, moq-gst, moq-relay, and the moq-tokio tests (about 70 -sites) follow. - -Decided 2026-10-13: give all ten fields #5350's shape. The typed field becomes -`Option` (`None` is unset, and `Default` holds the default), the -`*_arg` field loses its parser default, and each field resolves the flag, then -the typed field, then the default. `fallback`, `resolve`, and the `explicit` -bit then have no callers, so delete them (also decided) and leave `CliDuration` as the -humantime parser. - -Rejected: fixing usage (jdx/usage, an outside party) to assign -`default_value_t` without the string round-trip. It fixes only the first -half; skipped fields still start at zero, so the zero ambiguity stays. - -Start after #5350 merges, since this reuses its `serde_duration::option` and -shape. Like #5350, help no longer prints these flags' defaults, because -usage's `default` sets a parser value; each doc comment states its default. -Use a help-only default instead if usage offers one. - -Extend #5350's `a_timeout_set_in_code_beats_the_parser_default` to every field: -a parsed config, a merged round-trip with zero and nonzero values, a given -flag still winning, and a config built in code. It must fail on main. - -Public API: breaking, each listed `moq_tokio` field goes from `Duration` to -`Option`. The C ABI and FFI records keep their `has_*` flags and -don't change. Wire: none. - -## Related - -- [#5350](https://github.com/moq-dev/moq/pull/5350) - the backoff timeout fix this generalizes diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 13d08eaadfc..ea76d27838f 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -1110,11 +1110,11 @@ pub extern "C" fn moq_client_defaults() -> moq_client_config { dst.websocket_delay_us = micros(websocket.delay); dst.has_websocket_delay = true; - dst.backoff_initial_us = micros(config.connect.backoff.initial); + dst.backoff_initial_us = micros(config.connect.backoff.initial.unwrap()); dst.has_backoff_initial = true; dst.backoff_multiplier = config.connect.backoff.multiplier; dst.has_backoff_multiplier = true; - dst.backoff_max_us = micros(config.connect.backoff.max); + dst.backoff_max_us = micros(config.connect.backoff.max.unwrap()); dst.has_backoff_max = true; if let Some(timeout) = config.connect.backoff.timeout { dst.backoff_timeout_us = micros(timeout); diff --git a/rs/moq-c/src/client.rs b/rs/moq-c/src/client.rs index 48e4dcad540..948fd8953a5 100644 --- a/rs/moq-c/src/client.rs +++ b/rs/moq-c/src/client.rs @@ -50,19 +50,19 @@ pub unsafe fn parse_client(config: Option<&moq_client_config>) -> Result) -> Result) -> Result moq_tokio::quic::Confi // The properties are optional and the config fields are not: an unset property // leaves the library default rather than overriding it with one of its own. if let Some(idle_timeout) = settings.quic_idle_timeout { - config.idle_timeout = idle_timeout; + config.idle_timeout = Some(idle_timeout); } if let Some(keep_alive) = settings.quic_keep_alive { - config.keep_alive = keep_alive; + config.keep_alive = Some(keep_alive); } config } diff --git a/rs/moq-relay/src/config.rs b/rs/moq-relay/src/config.rs index e2087e66f71..2b82a948de8 100644 --- a/rs/moq-relay/src/config.rs +++ b/rs/moq-relay/src/config.rs @@ -920,7 +920,7 @@ timeout = "2m" let args = vec![std::ffi::OsString::from("moq-relay"), std::ffi::OsString::from(&path)]; let config = Config::parse_and_merge(args).expect("config load"); - assert_eq!(config.connect.timeout, std::time::Duration::from_secs(120)); + assert_eq!(config.connect.timeout, Some(std::time::Duration::from_secs(120))); } #[test] diff --git a/rs/moq-relay/src/shutdown.rs b/rs/moq-relay/src/shutdown.rs index 67e43e8708b..12476d1453a 100644 --- a/rs/moq-relay/src/shutdown.rs +++ b/rs/moq-relay/src/shutdown.rs @@ -290,7 +290,7 @@ mod tests { async fn withheld_websocket_setup_ends_at_the_deadline() { let window = Duration::from_secs(1); let mut config = crate::Config::default(); - config.listen.timeout = Duration::ZERO; + config.listen.timeout = Some(Duration::ZERO); config.listen.bind = Some("127.0.0.1:0".parse().unwrap()); config.listen.tls.generate = vec!["localhost".into()]; config.web.ws = true; diff --git a/rs/moq-relay/tests/auth_lifetime.rs b/rs/moq-relay/tests/auth_lifetime.rs index c98836b49c4..2987f58869d 100644 --- a/rs/moq-relay/tests/auth_lifetime.rs +++ b/rs/moq-relay/tests/auth_lifetime.rs @@ -207,7 +207,7 @@ fn client() -> moq_tokio::Client { let mut config = moq_tokio::connect::Config::default(); config.tls.insecure = Some(true); config.once = Some(true); - config.websocket.delay = Duration::ZERO; + config.websocket.delay = Some(Duration::ZERO); config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); config.init(Default::default()).expect("client init") } @@ -1399,7 +1399,7 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { let mut config = moq_tokio::connect::Config::default(); config.once = Some(true); config.version = vec!["moq-transport-22".parse().unwrap()]; - config.websocket.delay = Duration::ZERO; + config.websocket.delay = Some(Duration::ZERO); config.init(Default::default()).unwrap() }; let origin = moq_tokio::origin::spawn(); diff --git a/rs/moq-relay/tests/cluster_unknown.rs b/rs/moq-relay/tests/cluster_unknown.rs index a4d9bce682a..8449d478718 100644 --- a/rs/moq-relay/tests/cluster_unknown.rs +++ b/rs/moq-relay/tests/cluster_unknown.rs @@ -47,7 +47,7 @@ async fn spawn_relay( fn client(version: Option) -> moq_tokio::Client { let mut config = moq_tokio::connect::Config::default(); config.tls.insecure = Some(true); - config.websocket.delay = Duration::ZERO; + config.websocket.delay = Some(Duration::ZERO); config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); config.version.extend(version); config.init(Default::default()).expect("client init") diff --git a/rs/moq-relay/tests/drills.rs b/rs/moq-relay/tests/drills.rs index f3a6e0e9643..ea3621ed202 100644 --- a/rs/moq-relay/tests/drills.rs +++ b/rs/moq-relay/tests/drills.rs @@ -305,8 +305,8 @@ fn quic() -> moq_tokio::quic::Config { // busy runner has to stall eight times over before a live session is mistaken // for a dead one. let mut quic = moq_tokio::quic::Config::default(); - quic.idle_timeout = Duration::from_secs(2); - quic.keep_alive = Duration::from_millis(250); + quic.idle_timeout = Some(Duration::from_secs(2)); + quic.keep_alive = Some(Duration::from_millis(250)); quic } @@ -327,8 +327,8 @@ fn dial() -> moq_tokio::connect::Config { // Fast enough to keep a relay bounce or a link flap inside the drill's // budget, paced enough that the loop is still a backoff. - config.backoff.initial = Duration::from_millis(50); - config.backoff.max = Duration::from_millis(200); + config.backoff.initial = Some(Duration::from_millis(50)); + config.backoff.max = Some(Duration::from_millis(200)); config.backoff.timeout = Some(Duration::from_secs(5)); config } @@ -981,7 +981,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { // idles out only after `relay_idle`, which the flap's waits allow for. let mut config = relay_config(); config.quic = credit(lane, config.quic); - let relay_idle = config.quic.idle_timeout; + let relay_idle = config.quic.resolve().idle_timeout; let origin = RelayHost::start(config).await; let seed = seed(lane); let peer = match (link, lane) { diff --git a/rs/moq-relay/tests/goaway_cluster.rs b/rs/moq-relay/tests/goaway_cluster.rs index fbe07c143c4..27a5135a4e1 100644 --- a/rs/moq-relay/tests/goaway_cluster.rs +++ b/rs/moq-relay/tests/goaway_cluster.rs @@ -149,7 +149,7 @@ async fn cluster_continues_a_group_split_by_goaway_inner() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); - client_config.goaway.handover = Duration::from_secs(2); + client_config.goaway.handover = Some(Duration::from_secs(2)); let client = client_config.init(Default::default()).expect("client init"); let mut cluster_config = cluster::Config::default(); @@ -294,7 +294,7 @@ async fn cluster_migrates_on_upstream_goaway_inner() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. - client_config.goaway.handover = Duration::from_secs(2); + client_config.goaway.handover = Some(Duration::from_secs(2)); let client = client_config.init(Default::default()).expect("client init"); let mut cluster_config = cluster::Config::default(); @@ -419,7 +419,7 @@ async fn spawn_relay_with_upstream( let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. - client_config.goaway.handover = Duration::from_secs(2); + client_config.goaway.handover = Some(Duration::from_secs(2)); // Only lite-07 carries the epoch that lets a failover resume the subscription. client_config.version = vec![LITE_07.parse().unwrap()]; let client = client_config.init(Default::default()).expect("client init"); @@ -503,7 +503,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. - client_config.goaway.handover = Duration::from_secs(2); + client_config.goaway.handover = Some(Duration::from_secs(2)); client_config.version = vec![LITE_07.parse().unwrap()]; let mid_a_client = client_config.init(Default::default()).expect("mid-a client init"); let (_mid_a_upstream_client, mid_a_upstream) = within( @@ -768,7 +768,7 @@ async fn cluster_reconnects_on_empty_uri_goaway_inner() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. - client_config.goaway.handover = Duration::from_secs(2); + client_config.goaway.handover = Some(Duration::from_secs(2)); // Only lite-07 carries the epoch that lets the redial resume the subscription. client_config.version = vec![LITE_07.parse().unwrap()]; let client = client_config.init(Default::default()).expect("client init"); @@ -895,11 +895,11 @@ async fn goaway_handover_is_enforced_while_the_replacement_dial_hangs_inner() { let handover = Duration::from_millis(200); let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); - client_config.goaway.handover = handover; + client_config.goaway.handover = Some(handover); // The GOAWAY has to land on a *healthy* session, which is the path that goes // straight into the replacement dial. Below this bar it takes the immediate // redirect path instead, whose sleep polls the drain either way. - client_config.backoff.initial = Duration::from_millis(50); + client_config.backoff.initial = Some(Duration::from_millis(50)); let client = client_config.init(Default::default()).expect("client init"); let url: Url = format!("tcp://127.0.0.1:{port}/").parse().expect("parse url"); diff --git a/rs/moq-relay/tests/public_rules.rs b/rs/moq-relay/tests/public_rules.rs index 64bcb361477..ef40c21a2b9 100644 --- a/rs/moq-relay/tests/public_rules.rs +++ b/rs/moq-relay/tests/public_rules.rs @@ -22,7 +22,7 @@ const TIMEOUT: Duration = Duration::from_secs(10); fn client() -> moq_tokio::Client { let mut config = moq_tokio::connect::Config::default(); config.once = Some(true); - config.websocket.delay = Duration::ZERO; + config.websocket.delay = Some(Duration::ZERO); config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); config.init(Default::default()).expect("client init") } diff --git a/rs/moq-relay/tests/runtime_uring.rs b/rs/moq-relay/tests/runtime_uring.rs index c542abbf1c1..424d004a7ad 100644 --- a/rs/moq-relay/tests/runtime_uring.rs +++ b/rs/moq-relay/tests/runtime_uring.rs @@ -776,7 +776,7 @@ async fn uring_workers_bound_stalled_handshakes() { let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); let mut config = uring_config(&cert, &key); - config.listen.timeout = Duration::from_millis(200); + config.listen.timeout = Some(Duration::from_millis(200)); let relay = Relay::load(config).await.expect("load relay"); let port = relay.addr().expect("workers bound an address").port(); let addr = SocketAddr::from(([127, 0, 0, 1], port)); diff --git a/rs/moq-relay/tests/session_revalidate.rs b/rs/moq-relay/tests/session_revalidate.rs index c6a42a575c9..ce96bd0b5cf 100644 --- a/rs/moq-relay/tests/session_revalidate.rs +++ b/rs/moq-relay/tests/session_revalidate.rs @@ -240,7 +240,7 @@ fn client_at(bind: &str) -> moq_tokio::Client { let mut config = moq_tokio::connect::Config::default(); config.tls.insecure = Some(true); config.once = Some(true); - config.websocket.delay = Duration::ZERO; + config.websocket.delay = Some(Duration::ZERO); config.bind = Some(bind.parse().expect("parse bind")); config.init(Default::default()).expect("client init") } diff --git a/rs/moq-relay/tests/shutdown_signal.rs b/rs/moq-relay/tests/shutdown_signal.rs index b295cee1899..ca763c62775 100644 --- a/rs/moq-relay/tests/shutdown_signal.rs +++ b/rs/moq-relay/tests/shutdown_signal.rs @@ -343,8 +343,8 @@ async fn a_reconnecting_client_rides_out_a_restart_inner() { broadcast.announce(Default::default()).expect("announce"); let mut publisher = moq_tokio::connect::Config::default(); // Redials paced well inside the drain, under a window that ends long before it. - publisher.backoff.initial = Duration::from_millis(200); - publisher.backoff.max = Duration::from_millis(200); + publisher.backoff.initial = Some(Duration::from_millis(200)); + publisher.backoff.max = Some(Duration::from_millis(200)); publisher.backoff.timeout = Some(DRAIN_TIMEOUT / 3); let publisher = publisher .init(Default::default()) diff --git a/rs/moq-relay/tests/smoke.rs b/rs/moq-relay/tests/smoke.rs index 4c94eb74d6c..fd1b50f975c 100644 --- a/rs/moq-relay/tests/smoke.rs +++ b/rs/moq-relay/tests/smoke.rs @@ -117,7 +117,7 @@ fn client_version(version: Option) -> moq_tokio::Client { // redial would re-register with the relay behind the assertions' back. config.once = Some(true); // Zero head start so the WebSocket path runs immediately. - config.websocket.delay = std::time::Duration::ZERO; + config.websocket.delay = Some(std::time::Duration::ZERO); // Every relay in this file listens on IPv4 loopback, so bind the same family // rather than egressing a QUIC dial from a dual-stack IPv6 socket. config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); diff --git a/rs/moq-tokio/src/cli/duration.rs b/rs/moq-tokio/src/cli/duration.rs index 2ba6ce2b3ab..094baf9afed 100644 --- a/rs/moq-tokio/src/cli/duration.rs +++ b/rs/moq-tokio/src/cli/duration.rs @@ -11,7 +11,6 @@ use ::serde::{Deserialize, Deserializer, Serialize, Serializer}; #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Duration { value: StdDuration, - explicit: bool, } impl Duration { @@ -19,19 +18,6 @@ impl Duration { pub const fn into_std(self) -> StdDuration { self.value } - - /// A parser default, which yields to a standing typed value during an update. - pub(crate) const fn fallback(value: StdDuration) -> Self { - Self { value, explicit: false } - } - - /// Resolve an optional parser value against the public typed field. - pub(crate) fn resolve(value: Option, configured: StdDuration) -> StdDuration { - match value { - Some(value) if value.explicit || configured.is_zero() => value.value, - _ => configured, - } - } } impl Deref for Duration { @@ -44,7 +30,7 @@ impl Deref for Duration { impl From for Duration { fn from(value: StdDuration) -> Self { - Self { value, explicit: true } + Self { value } } } @@ -94,25 +80,7 @@ impl<'de> Deserialize<'de> for Duration { } pub(crate) mod serde_duration { - use ::serde::{Deserialize, Deserializer, Serializer}; - use std::time::Duration; - - pub fn serialize(value: &Duration, serializer: S) -> Result - where - S: Serializer, - { - serializer.collect_str(&humantime::format_duration(*value)) - } - - pub fn deserialize<'de, D>(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let value = String::deserialize(deserializer)?; - humantime::parse_duration(&value).map_err(::serde::de::Error::custom) - } - - /// The same format for an optional duration. + /// Human-readable serialization for an optional duration. pub mod option { use ::serde::{Deserialize, Deserializer, Serializer}; use std::time::Duration; @@ -122,7 +90,7 @@ pub(crate) mod serde_duration { S: Serializer, { match value { - Some(value) => super::serialize(value, serializer), + Some(value) => serializer.collect_str(&humantime::format_duration(*value)), None => serializer.serialize_none(), } } @@ -137,3 +105,50 @@ pub(crate) mod serde_duration { } } } + +// Exercise the same precedence contract for each duration config, including its +// own interpretation of zero (disabled, unlimited, or a minimum pacing floor). +#[cfg(test)] +macro_rules! test_config_duration { + ($name:ident, $config:ty, $field:ident, $flag:literal, $resolve:expr, $expected:expr) => { + #[test] + fn $name() { + #[derive(usage::Cli)] + #[usage(unknown_flags = "error", args_override_self = false)] + #[usage(settings)] + struct Wrapper { + #[usage(flatten)] + config: $config, + } + let parse = |args: &[&str]| { + let args = args.iter().map(std::ffi::OsStr::new).collect::>(); + Wrapper::parse_from(&args).unwrap().config + }; + let merged = |config: &$config| -> $config { toml::Value::try_from(config).unwrap().try_into().unwrap() }; + let resolve = $resolve; + let expected = $expected; + let default = resolve(&<$config>::default()); + assert_eq!(resolve(&parse(&[])), default, "parsed default"); + assert_eq!(resolve(&merged(&parse(&[]))), default, "merged default"); + let mut unset = <$config>::default(); + unset.$field = None; + assert_eq!(resolve(&unset), default, "unset uses the default"); + assert_eq!(resolve(&merged(&unset)), default, "unset round-trip"); + for value in [std::time::Duration::ZERO, std::time::Duration::from_secs(3)] { + for mut config in [parse(&[]), merged(&parse(&[])), <$config>::default()] { + config.$field = value.into(); + assert_eq!(resolve(&config), expected(value), "typed {value:?}"); + assert_eq!(resolve(&merged(&config)), expected(value), "round-trip {value:?}"); + } + let flag_value = if value.is_zero() { "3s" } else { "0s" }; + let flag_duration = humantime::parse_duration(flag_value).unwrap(); + for mut config in [parse(&[$flag, flag_value]), merged(&parse(&[$flag, flag_value]))] { + config.$field = value.into(); + assert_eq!(resolve(&config), expected(flag_duration), "explicit flag"); + } + } + } + }; +} +#[cfg(test)] +pub(crate) use test_config_duration; diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index 4bb2d0ab335..1da920fe7f9 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -1258,7 +1258,7 @@ mod tests { "#; let config: crate::connect::Config = toml::from_str(toml).unwrap(); - assert_eq!(config.race, crate::connect::DEFAULT_RACE); + assert_eq!(config.resolve().race, crate::connect::DEFAULT_RACE); assert!( config.deprecated().to_string().contains("failover_delay -> race"), "{}", @@ -1279,18 +1279,18 @@ mod tests { "#; let config: crate::connect::Config = toml::from_str(toml).unwrap(); - assert_eq!(config.resolution_delay, std::time::Duration::from_millis(10)); + assert_eq!(config.resolution_delay, Some(std::time::Duration::from_millis(10))); // Simulate: TOML loaded, then CLI args re-applied (no --connect-resolution-delay flag). let mut cli = Cli { config }; cli.update_from(&[]); - assert_eq!(cli.config.resolution_delay, std::time::Duration::from_millis(10)); + assert_eq!(cli.config.resolution_delay, Some(std::time::Duration::from_millis(10))); } #[test] fn test_cli_resolution_delay() { let config = Cli::config_from(["test", "--connect-resolution-delay", "0s"]); - assert_eq!(config.resolution_delay, std::time::Duration::ZERO); + assert_eq!(config.resolution_delay, None); assert_eq!(config.resolve().resolution_delay, std::time::Duration::ZERO); } @@ -1608,7 +1608,7 @@ mod tests { let mut config = crate::connect::Config::default(); config.tls.insecure = Some(true); // No head start, so the fallback dials while QUIC waits on the 403. - config.websocket.delay = std::time::Duration::ZERO; + config.websocket.delay = Some(std::time::Duration::ZERO); let client = config.init(Default::default()).unwrap(); // The same race `connect_inner` runs, except the fallback dials its own port, @@ -1685,7 +1685,7 @@ mod tests { let mut client_config = crate::connect::Config::default(); client_config.tls.insecure = Some(true); // Dial both arms immediately; the fallback handshake is gated by QUIC. - client_config.websocket.delay = std::time::Duration::ZERO; + client_config.websocket.delay = Some(std::time::Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let quic_addr: crate::connect::Addr = Url::parse(&format!("https://localhost:{quic_port}")).unwrap().into(); @@ -1841,7 +1841,7 @@ mod tests { #[test] fn race_defaults_to_the_rfc_8305_stagger() { let config = crate::connect::Config::default(); - assert_eq!(config.race, std::time::Duration::from_millis(250)); + assert_eq!(config.race, Some(std::time::Duration::from_millis(250))); assert_eq!(config.resolve().race, std::time::Duration::from_millis(250)); } @@ -1874,10 +1874,10 @@ mod tests { let timeout = crate::connect::DEFAULT_TIMEOUT; let mut config = crate::connect::Config { - timeout, + timeout: Some(timeout), ..Default::default() }; - config.websocket.delay = std::time::Duration::ZERO; + config.websocket.delay = Some(std::time::Duration::ZERO); let client = config.init(Default::default()).unwrap(); // Nothing is listening on UDP, so the QUIC arm fails and leaves the WebSocket diff --git a/rs/moq-tokio/src/connect.rs b/rs/moq-tokio/src/connect.rs index 9689ddb6540..8d4d83d8559 100644 --- a/rs/moq-tokio/src/connect.rs +++ b/rs/moq-tokio/src/connect.rs @@ -394,7 +394,7 @@ failover_delay = "1s" ) .expect("parse"); assert!(config.url.is_none()); - assert_eq!(config.race, DEFAULT_RACE); + assert_eq!(config.resolve().race, DEFAULT_RACE); let reported = config.deprecated().to_string(); assert!(reported.contains("connect -> url"), "{reported}"); assert!(reported.contains("failover_delay -> race"), "{reported}"); @@ -531,16 +531,19 @@ pub struct Config { /// /// This staggers the attempts within one [`crate::Client::connect`]; [`Self::timeout`] /// bounds that call as a whole. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub race: std::time::Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub race: Option, #[usage( name = "connect-race", long = "connect-race", env = "MOQ_CONNECT_RACE", - default_value_t = crate::cli::Duration::fallback(DEFAULT_RACE), - default = "250ms", setting = "connect.race" )] #[serde(default, rename = "__cli_race", skip_serializing_if = "Option::is_none")] @@ -558,16 +561,19 @@ pub struct Config { /// The full answer is authoritative, including which family to try first, so /// this is how long the IPv4-only one waits for it before going ahead alone. /// Defaults to 50ms; `0s` dials as soon as any address resolves. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub resolution_delay: std::time::Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub resolution_delay: Option, #[usage( name = "connect-resolution-delay", long = "connect-resolution-delay", env = "MOQ_CONNECT_RESOLUTION_DELAY", - default_value_t = crate::cli::Duration::fallback(DEFAULT_RESOLUTION_DELAY), - default = "50ms", setting = "connect.resolution_delay" )] #[serde(default, rename = "__cli_resolution_delay", skip_serializing_if = "Option::is_none")] @@ -582,16 +588,19 @@ pub struct Config { /// never speaks would hang the whole connect. [`crate::Connection`] only re-arms /// its backoff between attempts, so an attempt that never returns stalls the /// retry loop indefinitely. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub timeout: std::time::Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub timeout: Option, #[usage( name = "connect-timeout", long = "connect-timeout", env = "MOQ_CONNECT_TIMEOUT", - default_value_t = crate::cli::Duration::fallback(DEFAULT_TIMEOUT), - default = "30s", setting = "connect.timeout" )] #[serde(default, rename = "__cli_timeout", skip_serializing_if = "Option::is_none")] @@ -704,12 +713,12 @@ impl Default for Config { url: None, connect: None, bind: None, - race: DEFAULT_RACE, + race: Some(DEFAULT_RACE), race_arg: None, failover_delay: None, - resolution_delay: DEFAULT_RESOLUTION_DELAY, + resolution_delay: Some(DEFAULT_RESOLUTION_DELAY), resolution_delay_arg: None, - timeout: DEFAULT_TIMEOUT, + timeout: Some(DEFAULT_TIMEOUT), timeout_arg: None, version: Vec::new(), extensions: Default::default(), @@ -781,9 +790,17 @@ impl Config { pub fn resolve(&self) -> Resolved { Resolved { bind: self.bind.unwrap_or_else(default_bind), - race: crate::cli::Duration::resolve(self.race_arg, self.race), - resolution_delay: crate::cli::Duration::resolve(self.resolution_delay_arg, self.resolution_delay), - timeout: crate::cli::Duration::resolve(self.timeout_arg, self.timeout), + race: self.race_arg.map(Into::into).or(self.race).unwrap_or(DEFAULT_RACE), + resolution_delay: self + .resolution_delay_arg + .map(Into::into) + .or(self.resolution_delay) + .unwrap_or(DEFAULT_RESOLUTION_DELAY), + timeout: self + .timeout_arg + .map(Into::into) + .or(self.timeout) + .unwrap_or(DEFAULT_TIMEOUT), } } } @@ -828,3 +845,32 @@ mod addr_tests { assert_eq!(Addr::new(url).addresses(), None); } } + +#[cfg(test)] +mod duration_tests { + use super::*; + crate::cli::duration::test_config_duration!( + race_set_in_code_beats_parser_default, + Config, + race, + "--connect-race", + |c: &Config| c.resolve().race, + |d| d + ); + crate::cli::duration::test_config_duration!( + resolution_delay_set_in_code_beats_parser_default, + Config, + resolution_delay, + "--connect-resolution-delay", + |c: &Config| c.resolve().resolution_delay, + |d| d + ); + crate::cli::duration::test_config_duration!( + timeout_set_in_code_beats_parser_default, + Config, + timeout, + "--connect-timeout", + |c: &Config| c.resolve().timeout, + |d| d + ); +} diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 1d25f25a2e9..f0770114df1 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -66,16 +66,19 @@ pub struct Backoff { /// Doubles as the bar a session must stay up to count as healthy, so it is /// floored at 50ms: at zero every session would look healthy and the retry /// pacing would collapse. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub initial: Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub initial: Option, #[usage( name = "backoff-initial", long, env = "MOQ_BACKOFF_INITIAL", - default_value_t = CliDuration::fallback(DEFAULT_INITIAL), - default = "1s", setting = "connect.backoff.initial" )] #[serde(default, rename = "__cli_initial", skip_serializing_if = "Option::is_none")] @@ -92,18 +95,16 @@ pub struct Backoff { pub multiplier: u32, /// Maximum delay between reconnect attempts. Defaults to 5s. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub max: Duration, - - #[usage( - name = "backoff-max", - long, - env = "MOQ_BACKOFF_MAX", - default_value_t = CliDuration::fallback(DEFAULT_MAX), - default = "5s", - setting = "connect.backoff.max" + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" )] + pub max: Option, + + #[usage(name = "backoff-max", long, env = "MOQ_BACKOFF_MAX", setting = "connect.backoff.max")] #[serde(default, rename = "__cli_max", skip_serializing_if = "Option::is_none")] max_arg: Option, @@ -144,10 +145,10 @@ pub struct Backoff { impl Default for Backoff { fn default() -> Self { Self { - initial: DEFAULT_INITIAL, + initial: Some(DEFAULT_INITIAL), initial_arg: None, multiplier: DEFAULT_MULTIPLIER, - max: DEFAULT_MAX, + max: Some(DEFAULT_MAX), max_arg: None, timeout: Some(DEFAULT_TIMEOUT), timeout_arg: None, @@ -345,16 +346,19 @@ pub struct Goaway { /// "10s" or "500ms". This is a cap: a GOAWAY naming a shorter deadline wins, /// since the peer force-closes at its own deadline regardless, but a longer one /// does not extend it. Defaults to 10 seconds. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub handover: Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub handover: Option, #[usage( name = "goaway-handover", long, env = "MOQ_GOAWAY_HANDOVER", - default_value_t = CliDuration::fallback(DEFAULT_HANDOVER), - default = "10s", setting = "connect.goaway.handover" )] #[serde(default, rename = "__cli_handover", skip_serializing_if = "Option::is_none")] @@ -365,7 +369,7 @@ impl Default for Goaway { fn default() -> Self { Self { redirect: Redirect::SameHost, - handover: DEFAULT_HANDOVER, + handover: Some(DEFAULT_HANDOVER), handover_arg: None, } } @@ -403,8 +407,13 @@ struct Pacing { impl Pacing { fn new(backoff: &Backoff) -> Self { - let initial = CliDuration::resolve(backoff.initial_arg, backoff.initial).max(MIN_BACKOFF); - let max = CliDuration::resolve(backoff.max_arg, backoff.max); + let initial = backoff + .initial_arg + .map(Into::into) + .or(backoff.initial) + .unwrap_or(DEFAULT_INITIAL) + .max(MIN_BACKOFF); + let max = backoff.max_arg.map(Into::into).or(backoff.max).unwrap_or(DEFAULT_MAX); Self { initial, max: max.max(initial), @@ -426,7 +435,11 @@ impl Goaway { fn resolve(&self) -> Resolved { Resolved { redirect: self.redirect, - handover: CliDuration::resolve(self.handover_arg, self.handover), + handover: self + .handover_arg + .map(Into::into) + .or(self.handover) + .unwrap_or(DEFAULT_HANDOVER), } } } @@ -1658,15 +1671,15 @@ mod tests { // Stand in for the TOML layer, then re-apply the CLI with none of the flags set. let mut parsed = Wrapper::parse_from(&[]).unwrap(); - parsed.backoff.initial = Duration::from_secs(7); + parsed.backoff.initial = Some(Duration::from_secs(7)); parsed.backoff.multiplier = 5; - parsed.backoff.max = Duration::from_secs(11); + parsed.backoff.max = Some(Duration::from_secs(11)); parsed.backoff.timeout = Some(Duration::ZERO); parsed.update_from(&[]); - assert_eq!(parsed.backoff.initial, Duration::from_secs(7)); + assert_eq!(parsed.backoff.initial, Some(Duration::from_secs(7))); assert_eq!(parsed.backoff.multiplier, 5); - assert_eq!(parsed.backoff.max, Duration::from_secs(11)); + assert_eq!(parsed.backoff.max, Some(Duration::from_secs(11))); assert_eq!(parsed.backoff.window(), Duration::ZERO, "0 means retry forever"); // With no flags, the parser defaults resolve to the typed defaults. @@ -1683,47 +1696,6 @@ mod tests { assert_eq!(Pacing::new(&parsed.backoff).initial, Duration::from_secs(3)); } - /// A window set in code wins on a config the command line built, including zero. - /// - /// The parser stored its 10s default exactly as if `--backoff-timeout 10s` had been given, so - /// it beat the typed field, and a zero there was indistinguishable from the field left unset. - #[test] - fn a_timeout_set_in_code_beats_the_parser_default() { - #[derive(usage::Cli)] - #[usage(unknown_flags = "error", args_override_self = false)] - #[usage(settings)] - struct Wrapper { - #[usage(flatten)] - backoff: Backoff, - } - - let mut parsed = Wrapper::parse_from(&[]).unwrap().backoff; - assert_eq!(parsed.window(), DEFAULT_TIMEOUT); - parsed.timeout = Some(Duration::ZERO); - assert_eq!(parsed.window(), Duration::ZERO, "a parsed config"); - - let merged = |backoff: &Backoff| -> Backoff { toml::Value::try_from(backoff).unwrap().try_into().unwrap() }; - let mut config = merged(&Wrapper::parse_from(&[]).unwrap().backoff); - assert_eq!(config.window(), DEFAULT_TIMEOUT, "the default survives the round-trip"); - config.timeout = Some(Duration::ZERO); - assert_eq!(config.window(), Duration::ZERO, "a merged config"); - config.timeout = Some(Duration::from_secs(3)); - assert_eq!(config.window(), Duration::from_secs(3), "a merged config, nonzero"); - - // An explicit flag still wins, through the round-trip too. - let flag = [std::ffi::OsStr::new("--backoff-timeout"), std::ffi::OsStr::new("0s")]; - let mut config = merged(&Wrapper::parse_from(&flag).unwrap().backoff); - config.timeout = Some(Duration::from_secs(3)); - assert_eq!(config.window(), Duration::ZERO, "the flag beats the field"); - - // A config built in code was never affected. - let config = Backoff { - timeout: Some(Duration::ZERO), - ..Default::default() - }; - assert_eq!(config.window(), Duration::ZERO); - } - /// GOAWAY typed defaults remain overrideable by a standing TOML layer. #[test] fn cli_does_not_clobber_toml_goaway() { @@ -1760,7 +1732,7 @@ mod tests { #[test] fn handover_takes_the_earlier_deadline() { let config = Goaway { - handover: Duration::from_secs(10), + handover: Some(Duration::from_secs(10)), ..Default::default() }; @@ -2036,7 +2008,7 @@ mod tests { // A zero initial would also make every session look healthy, resetting the // give-up window forever. let pacing = Pacing::new(&Backoff { - initial: Duration::ZERO, + initial: Some(Duration::ZERO), ..Default::default() }); assert_eq!(pacing.initial, MIN_BACKOFF); @@ -2044,7 +2016,7 @@ mod tests { // A cap below the floor would clamp the delay straight back down. let pacing = Pacing::new(&Backoff { - max: Duration::ZERO, + max: Some(Duration::ZERO), ..Default::default() }); assert_eq!(pacing.max, pacing.initial); @@ -2059,8 +2031,8 @@ mod tests { // All at once: still paced. let pacing = Pacing::new(&Backoff { - initial: Duration::ZERO, - max: Duration::ZERO, + initial: Some(Duration::ZERO), + max: Some(Duration::ZERO), multiplier: 0, ..Default::default() }); @@ -2075,9 +2047,9 @@ mod tests { #[test] fn pacing_grows_to_the_cap() { let pacing = Pacing::new(&Backoff { - initial: Duration::from_millis(100), + initial: Some(Duration::from_millis(100)), multiplier: 2, - max: Duration::from_millis(400), + max: Some(Duration::from_millis(400)), ..Default::default() }); @@ -2128,9 +2100,9 @@ mod tests { #[test] fn test_backoff_default() { let backoff = Backoff::default(); - assert_eq!(backoff.initial, Duration::from_secs(1)); + assert_eq!(backoff.initial, Some(Duration::from_secs(1))); assert_eq!(backoff.multiplier, 2); - assert_eq!(backoff.max, Duration::from_secs(5)); + assert_eq!(backoff.max, Some(Duration::from_secs(5))); assert_eq!(backoff.timeout, Some(Duration::from_secs(10))); } @@ -2363,8 +2335,8 @@ mod tests { url(&format!("tcp://{}/", listener.local_addr().expect("local addr"))) }; let mut client = client(); - client.backoff.initial = Duration::from_millis(50); - client.backoff.max = Duration::from_millis(50); + client.backoff.initial = Some(Duration::from_millis(50)); + client.backoff.max = Some(Duration::from_millis(50)); client.backoff.timeout = Some(Duration::from_millis(200)); let started = tokio::time::Instant::now(); let connection = client.connect(target); @@ -2769,7 +2741,7 @@ mod tests { let subscriber = crate::origin::spawn(); let mut config = crate::connect::Config::default(); config.tls.insecure = Some(true); - config.goaway.handover = HANDOVER; + config.goaway.handover = Some(HANDOVER); let client = config .init(Default::default()) .unwrap() @@ -3124,7 +3096,7 @@ mod tests { config.tls.insecure = Some(true); // Both dials start now; the fixture holds the fallback handshake so load // cannot decide which transport this test exercises. - config.websocket.delay = Duration::ZERO; + config.websocket.delay = Some(Duration::ZERO); let client = config .init(Default::default()) .unwrap() @@ -3208,10 +3180,10 @@ mod tests { let subscriber = crate::origin::spawn(); let mut config = crate::connect::Config::default(); - config.goaway.handover = HANDOVER; + config.goaway.handover = Some(HANDOVER); // A session younger than the initial delay counts as redirected immediately and // waits out a backoff, which this test is not about. - config.backoff.initial = MIN_BACKOFF; + config.backoff.initial = Some(MIN_BACKOFF); let client = config .init(Default::default()) .unwrap() @@ -3275,3 +3247,40 @@ mod tests { ); } } + +#[cfg(test)] +mod duration_tests { + use super::*; + crate::cli::duration::test_config_duration!( + initial_set_in_code_beats_parser_default, + Backoff, + initial, + "--backoff-initial", + |c: &Backoff| Pacing::new(c).initial, + |d: Duration| d.max(MIN_BACKOFF) + ); + crate::cli::duration::test_config_duration!( + max_set_in_code_beats_parser_default, + Backoff, + max, + "--backoff-max", + |c: &Backoff| Pacing::new(c).max, + |d: Duration| d.max(DEFAULT_INITIAL) + ); + crate::cli::duration::test_config_duration!( + timeout_set_in_code_beats_parser_default, + Backoff, + timeout, + "--backoff-timeout", + |c: &Backoff| c.window(), + |d| d + ); + crate::cli::duration::test_config_duration!( + handover_set_in_code_beats_parser_default, + Goaway, + handover, + "--goaway-handover", + |c: &Goaway| c.resolve().handover, + |d| d + ); +} diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index ee2d5fb7910..67229671d07 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -159,16 +159,19 @@ pub struct Config { /// connection open indefinitely, since keep-alives count as activity. The /// connection is closed with a timeout code once this passes. See /// [`resolved_timeout`](Self::resolved_timeout) for the value in effect. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub timeout: std::time::Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub timeout: Option, #[usage( name = "listen-timeout", long = "listen-timeout", env = "MOQ_LISTEN_TIMEOUT", - default_value_t = crate::cli::Duration::fallback(DEFAULT_TIMEOUT), - default = "10s", setting = "listen.timeout" )] #[serde(default, rename = "__cli_timeout", skip_serializing_if = "Option::is_none")] @@ -274,7 +277,7 @@ impl Default for Config { unix: Default::default(), version: Vec::new(), extensions: Default::default(), - timeout: DEFAULT_TIMEOUT, + timeout: Some(DEFAULT_TIMEOUT), timeout_arg: None, tls: Default::default(), preferred_v4: None, @@ -515,7 +518,11 @@ impl Config { /// How long an accepted connection has to finish its handshake, or `None` to wait /// forever: for zero, and for a timeout too long for the clock to reach. pub fn resolved_timeout(&self) -> Option { - let timeout = crate::cli::Duration::resolve(self.timeout_arg, self.timeout); + let timeout = self + .timeout_arg + .map(Into::into) + .or(self.timeout) + .unwrap_or(DEFAULT_TIMEOUT); (!timeout.is_zero() && std::time::Instant::now().checked_add(timeout).is_some()).then_some(timeout) } @@ -846,7 +853,7 @@ load_balancer = { id = "ab", nonce = 8 } // Past the clock's range is forever, not a panic on the first accept. let config = Config { - timeout: std::time::Duration::MAX, + timeout: Some(std::time::Duration::MAX), ..Default::default() }; assert_eq!(config.resolved_timeout(), None); @@ -863,3 +870,16 @@ load_balancer = { id = "ab", nonce = 8 } assert_eq!(config.version, vec!["moq-lite-03".parse::().unwrap()]); } } + +#[cfg(test)] +mod duration_tests { + use super::*; + crate::cli::duration::test_config_duration!( + timeout_set_in_code_beats_parser_default, + Config, + timeout, + "--listen-timeout", + |c: &Config| c.resolved_timeout(), + |d: std::time::Duration| (!d.is_zero()).then_some(d) + ); +} diff --git a/rs/moq-tokio/src/quic.rs b/rs/moq-tokio/src/quic.rs index 256ba1d8693..0fcef593cd8 100644 --- a/rs/moq-tokio/src/quic.rs +++ b/rs/moq-tokio/src/quic.rs @@ -140,16 +140,19 @@ pub struct Config { /// Idle timeout before an inactive connection is dropped. Defaults to 10s. /// /// QUIC uses the smaller of both ends' timeouts, so either side can shorten it. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub idle_timeout: Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub idle_timeout: Option, #[usage( name = "quic-idle-timeout", long = "quic-idle-timeout", env = "MOQ_QUIC_IDLE_TIMEOUT", - default_value_t = CliDuration::fallback(DEFAULT_IDLE_TIMEOUT), - default = "10s", setting = "quic.idle_timeout" )] #[serde(default, rename = "__cli_idle_timeout", skip_serializing_if = "Option::is_none")] @@ -160,16 +163,19 @@ pub struct Config { /// The iroh backend applies this to its connection keep-alive. It also keeps /// a 5s per-path heartbeat that its builder will not raise or clear, so any /// interval above 5s still sends those path pings, and `0s` leaves both at 5s. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub keep_alive: Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub keep_alive: Option, #[usage( name = "quic-keep-alive", long = "quic-keep-alive", env = "MOQ_QUIC_KEEP_ALIVE", - default_value_t = CliDuration::fallback(DEFAULT_KEEP_ALIVE), - default = "3s", setting = "quic.keep_alive" )] #[serde(default, rename = "__cli_keep_alive", skip_serializing_if = "Option::is_none")] @@ -264,9 +270,9 @@ impl Default for Config { Self { max_streams: None, gso: None, - idle_timeout: DEFAULT_IDLE_TIMEOUT, + idle_timeout: Some(DEFAULT_IDLE_TIMEOUT), idle_timeout_arg: None, - keep_alive: DEFAULT_KEEP_ALIVE, + keep_alive: Some(DEFAULT_KEEP_ALIVE), keep_alive_arg: None, mtu_discovery: None, congestion_control: None, @@ -510,7 +516,7 @@ impl Config { Some(_) if cfg!(not(feature = "qlog")) => Err(crate::Error::QlogUnsupported), _ => Ok(()), }?; - validate_idle_timeout(Some(CliDuration::resolve(self.idle_timeout_arg, self.idle_timeout)))?; + validate_idle_timeout(Some(self.resolve().idle_timeout))?; validate_windows(self) } @@ -522,8 +528,16 @@ impl Config { pub fn resolve(&self) -> Resolved { // A zero keep-alive means "disabled"; anything else (including unset) keeps // the connection warm, defaulting to 3s. - let idle_timeout = CliDuration::resolve(self.idle_timeout_arg, self.idle_timeout); - let keep_alive = CliDuration::resolve(self.keep_alive_arg, self.keep_alive); + let idle_timeout = self + .idle_timeout_arg + .map(Into::into) + .or(self.idle_timeout) + .unwrap_or(DEFAULT_IDLE_TIMEOUT); + let keep_alive = self + .keep_alive_arg + .map(Into::into) + .or(self.keep_alive) + .unwrap_or(DEFAULT_KEEP_ALIVE); let keep_alive = (!keep_alive.is_zero()).then_some(keep_alive); Resolved { @@ -690,13 +704,13 @@ mod tests { #[test] fn zero_keep_alive_disables_it() { let disabled = Config { - keep_alive: Duration::ZERO, + keep_alive: Some(Duration::ZERO), ..Default::default() }; assert_eq!(disabled.resolve().keep_alive, None); let explicit = Config { - keep_alive: Duration::from_secs(2), + keep_alive: Some(Duration::from_secs(2)), ..Default::default() }; assert_eq!(explicit.resolve().keep_alive, Some(Duration::from_secs(2))); @@ -838,19 +852,19 @@ mod tests { #[test] fn idle_timeout_beyond_the_varint_is_rejected() { let over = Config { - idle_timeout: (MAX_IDLE_TIMEOUT + Duration::from_millis(1)), + idle_timeout: Some(MAX_IDLE_TIMEOUT + Duration::from_millis(1)), ..Default::default() }; assert!(matches!(over.validate(), Err(crate::Error::IdleTimeoutRange))); let saturated = Config { - idle_timeout: Duration::from_millis(u64::MAX), + idle_timeout: Some(Duration::from_millis(u64::MAX)), ..Default::default() }; assert!(matches!(saturated.validate(), Err(crate::Error::IdleTimeoutRange))); let at_limit = Config { - idle_timeout: MAX_IDLE_TIMEOUT, + idle_timeout: Some(MAX_IDLE_TIMEOUT), ..Default::default() }; assert!(at_limit.validate().is_ok()); @@ -978,3 +992,24 @@ mod tests { assert_eq!(quic.qlog.as_deref(), Some(std::path::Path::new("/tmp/qlog"))); } } + +#[cfg(test)] +mod duration_tests { + use super::*; + crate::cli::duration::test_config_duration!( + idle_timeout_set_in_code_beats_parser_default, + Config, + idle_timeout, + "--quic-idle-timeout", + |c: &Config| c.resolve().idle_timeout, + |d| d + ); + crate::cli::duration::test_config_duration!( + keep_alive_set_in_code_beats_parser_default, + Config, + keep_alive, + "--quic-keep-alive", + |c: &Config| c.resolve().keep_alive, + |d: Duration| (!d.is_zero()).then_some(d) + ); +} diff --git a/rs/moq-tokio/src/websocket.rs b/rs/moq-tokio/src/websocket.rs index 7bcc7efa711..531055f094b 100644 --- a/rs/moq-tokio/src/websocket.rs +++ b/rs/moq-tokio/src/websocket.rs @@ -160,16 +160,19 @@ pub struct Config { /// Head start given to the QUIC dial before the WebSocket fallback joins the /// race. Defaults to 200ms, and drops to zero for a server WebSocket already won. + /// `None` uses the default; an explicit command-line flag or environment variable wins. #[usage(skip)] - #[serde(with = "crate::cli::duration::serde_duration")] - pub delay: time::Duration, + #[serde( + default, + with = "crate::cli::duration::serde_duration::option", + skip_serializing_if = "Option::is_none" + )] + pub delay: Option, #[usage( name = "connect-websocket-delay", long = "connect-websocket-delay", env = "MOQ_CONNECT_WEBSOCKET_DELAY", - default_value_t = CliDuration::fallback(DEFAULT_DELAY), - default = "200ms", setting = "connect.websocket.delay" )] #[serde(default, rename = "__cli_delay", skip_serializing_if = "Option::is_none")] @@ -185,7 +188,7 @@ impl Default for Config { fn default() -> Self { Self { enabled: None, - delay: DEFAULT_DELAY, + delay: Some(DEFAULT_DELAY), delay_arg: None, legacy: Default::default(), } @@ -249,7 +252,7 @@ impl Config { pub fn resolve(&self) -> Resolved { Resolved { enabled: self.enabled.unwrap_or(true), - delay: CliDuration::resolve(self.delay_arg, self.delay), + delay: self.delay_arg.map(Into::into).or(self.delay).unwrap_or(DEFAULT_DELAY), } } } @@ -955,3 +958,16 @@ mod legacy_tests { assert_eq!(config.resolve().delay, DEFAULT_DELAY); } } + +#[cfg(test)] +mod duration_tests { + use super::*; + crate::cli::duration::test_config_duration!( + delay_set_in_code_beats_parser_default, + Config, + delay, + "--connect-websocket-delay", + |c: &Config| c.resolve().delay, + |d| d + ); +} diff --git a/rs/moq-tokio/tests/backend.rs b/rs/moq-tokio/tests/backend.rs index ced057c9986..a00b153ef66 100644 --- a/rs/moq-tokio/tests/backend.rs +++ b/rs/moq-tokio/tests/backend.rs @@ -461,7 +461,7 @@ async fn mtls_test(scheme: &str, reject: bool) { // One shared tuning, handed to both roles the way a binary would. let mut quic = moq_tokio::quic::Config::default(); quic.gso = Some(false); - quic.keep_alive = Duration::from_secs(1); + quic.keep_alive = Some(Duration::from_secs(1)); let server = server_config.init(quic.clone()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); @@ -746,7 +746,7 @@ async fn iroh_connect_test(version: Option<&str>) { async fn noq_client_close_reaches_server() { // An idle timeout inside TIMEOUT would hide a lost close. let mut quic = moq_tokio::quic::Config::default(); - quic.idle_timeout = TIMEOUT * 3; + quic.idle_timeout = Some(TIMEOUT * 3); let mut server_config = moq_tokio::listen::Config::default(); server_config.bind = Some("127.0.0.1:0".parse().unwrap()); @@ -1091,7 +1091,7 @@ async fn noq_client_close_keeps_predecessor_handover() { config.tls.insecure = Some(true); config.bind = Some("127.0.0.1:0".parse().unwrap()); // Well under the one second close window. - config.goaway.handover = Duration::from_millis(500); + config.goaway.handover = Some(Duration::from_millis(500)); let client = config .init(quic) .expect("failed to init client") diff --git a/rs/moq-tokio/tests/broadcast.rs b/rs/moq-tokio/tests/broadcast.rs index f21f3f1303c..7cb70653e90 100644 --- a/rs/moq-tokio/tests/broadcast.rs +++ b/rs/moq-tokio/tests/broadcast.rs @@ -2099,7 +2099,7 @@ async fn broadcast_websocket() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Disable WebSocket delay so client connects immediately via ws:// - client_config.websocket.delay = Duration::ZERO; + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://localhost:{}", ws_addr.port()).parse().unwrap(); @@ -2218,7 +2218,7 @@ async fn broadcast_websocket_fallback() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // No delay. Race QUIC and WebSocket simultaneously. - client_config.websocket.delay = Duration::ZERO; + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); @@ -2341,7 +2341,7 @@ async fn broadcast_websocket_uses_newest_version() { let sub_origin = moq_tokio::origin::spawn(); let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); - client_config.websocket.delay = Duration::ZERO; + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://localhost:{}", ws_addr.port()).parse().unwrap(); @@ -2773,7 +2773,7 @@ async fn websocket_unauthorized_handshake_is_explicit() { }); let mut client_config = moq_tokio::connect::Config::default(); - client_config.websocket.delay = Duration::ZERO; + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://{addr}").parse().unwrap(); @@ -2810,7 +2810,7 @@ async fn reconnect_stops_on_websocket_unauthorized() { }); let mut client_config = moq_tokio::connect::Config::default(); - client_config.websocket.delay = Duration::ZERO; + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://{addr}").parse().unwrap(); @@ -2900,7 +2900,7 @@ async fn one_shot_connect_surfaces_the_session_close() { client_config.tls.insecure = Some(true); client_config.once = Some(true); // A tiny backoff so a buggy redial happens well within the sleep below. - client_config.backoff.initial = Duration::from_millis(10); + client_config.backoff.initial = Some(Duration::from_millis(10)); let client = client_config.init(Default::default()).expect("failed to init client"); let connection = tokio::time::timeout(TIMEOUT, client.connect(url).established()) @@ -2962,7 +2962,7 @@ async fn a_dead_session_unannounces_while_the_reconnect_retries() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Retry forever with a fast cadence: the worst case for a stale announce. - client_config.backoff.initial = Duration::from_millis(10); + client_config.backoff.initial = Some(Duration::from_millis(10)); client_config.backoff.timeout = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); @@ -3638,7 +3638,7 @@ async fn zero_initial_backoff_still_gives_up_on_a_flapping_peer() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); - client_config.backoff.initial = Duration::ZERO; + client_config.backoff.initial = Some(Duration::ZERO); client_config.backoff.timeout = Some(Duration::from_millis(500)); let client = client_config.init(Default::default()).expect("failed to init client"); diff --git a/rs/moq-tokio/tests/reconnect.rs b/rs/moq-tokio/tests/reconnect.rs index 51a96c48343..d86a8eba3a4 100644 --- a/rs/moq-tokio/tests/reconnect.rs +++ b/rs/moq-tokio/tests/reconnect.rs @@ -22,8 +22,8 @@ fn client(backoff: moq_tokio::Backoff) -> moq_tokio::Client { #[tokio::test] async fn a_transient_failure_retries_until_the_budget_runs_out() { let mut backoff = moq_tokio::Backoff::default(); - backoff.initial = Duration::from_millis(20); - backoff.max = Duration::from_millis(40); + backoff.initial = Some(Duration::from_millis(20)); + backoff.max = Some(Duration::from_millis(40)); backoff.timeout = Some(Duration::from_millis(200)); // Nothing listens on port 1, so every attempt is refused: transient as far as this layer knows. @@ -201,8 +201,8 @@ async fn spawn_server() -> ( /// A client that redials fast, so a migration lands inside the test's patience. fn quick_client(redirect: moq_tokio::Redirect) -> moq_tokio::Client { let mut config = moq_tokio::connect::Config::default(); - config.backoff.initial = Duration::from_millis(20); - config.backoff.max = Duration::from_millis(40); + config.backoff.initial = Some(Duration::from_millis(20)); + config.backoff.max = Some(Duration::from_millis(40)); config.backoff.timeout = Some(Duration::ZERO); config.goaway.redirect = redirect; config.init(Default::default()).expect("failed to init client") @@ -336,8 +336,8 @@ async fn a_draining_peer_does_not_exhaust_the_retry_window() { // more than twice the window. A GOAWAY arriving inside the 200ms health bar is what makes a // session count as drained at once rather than as a healthy session that later migrated. let mut backoff = moq_tokio::Backoff::default(); - backoff.initial = Duration::from_millis(200); - backoff.max = Duration::from_millis(200); + backoff.initial = Some(Duration::from_millis(200)); + backoff.max = Some(Duration::from_millis(200)); backoff.timeout = Some(Duration::from_millis(500)); rides_out_a_drain(backoff, 12).await; } @@ -348,8 +348,8 @@ async fn a_draining_peer_does_not_exhaust_the_retry_window() { async fn a_drain_backoff_longer_than_the_retry_window_still_redials() { // From the second drained session on, the delay is 400ms against a 100ms window. let mut backoff = moq_tokio::Backoff::default(); - backoff.initial = Duration::from_millis(200); - backoff.max = Duration::from_millis(400); + backoff.initial = Some(Duration::from_millis(200)); + backoff.max = Some(Duration::from_millis(400)); backoff.timeout = Some(Duration::from_millis(100)); rides_out_a_drain(backoff, 4).await; } From e7e3eb1c440073c5b43df1fbe2aaad534f4e2f46 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 13 Oct 2026 19:09:29 -0700 Subject: [PATCH 3/4] docs: keep duration upgrade note in the existing list Co-Authored-By: Codex --- doc/setup/upgrade.md | 1 - 1 file changed, 1 deletion(-) diff --git a/doc/setup/upgrade.md b/doc/setup/upgrade.md index 4036a14a658..f17d39aba1f 100644 --- a/doc/setup/upgrade.md +++ b/doc/setup/upgrade.md @@ -27,7 +27,6 @@ These land with the next breaking release, not the 2026-09-23 train. now take effect on parsed and merged configs unless the flag or environment variable was actually given. TOML keys, C ABI, binding records, and wire formats are unchanged. - - **A QUIC load-balancer nonce needs its server id.** `listen.lb_nonce`, `--listen-quic-lb-nonce`, and `MOQ_LISTEN_QUIC_LB_NONCE` without `lb_id` stop startup. Setting `lb_id` (or `lb_nonce`) and `load_balancer` together also From e9cb3ceb294f7725c669218eee079253648a5cc9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 14 Oct 2026 09:50:02 -0700 Subject: [PATCH 4/4] fix(tokio): state each duration flag's default in --help The flags lost their parser defaults, and with them the [default: X] line. Co-Authored-By: Claude Opus 5.5 --- rs/moq-tokio/src/connect.rs | 3 +++ rs/moq-tokio/src/connection.rs | 4 ++++ rs/moq-tokio/src/listen.rs | 1 + rs/moq-tokio/src/quic.rs | 2 ++ rs/moq-tokio/src/websocket.rs | 1 + 5 files changed, 11 insertions(+) diff --git a/rs/moq-tokio/src/connect.rs b/rs/moq-tokio/src/connect.rs index 8d4d83d8559..789efcb0df5 100644 --- a/rs/moq-tokio/src/connect.rs +++ b/rs/moq-tokio/src/connect.rs @@ -540,6 +540,7 @@ pub struct Config { )] pub race: Option, + /// Delay before also dialing the next resolved address. Defaults to 250ms; 0s dials every address at once. #[usage( name = "connect-race", long = "connect-race", @@ -570,6 +571,7 @@ pub struct Config { )] pub resolution_delay: Option, + /// Delay before dialing IPv4 while the full DNS answer is outstanding. Defaults to 50ms. #[usage( name = "connect-resolution-delay", long = "connect-resolution-delay", @@ -597,6 +599,7 @@ pub struct Config { )] pub timeout: Option, + /// Maximum time for one connect, covering the dial and the MoQ handshake. Defaults to 30s; 0s waits forever. #[usage( name = "connect-timeout", long = "connect-timeout", diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 95ac57da1cb..352ea806d05 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -75,6 +75,7 @@ pub struct Backoff { )] pub initial: Option, + /// Initial delay before the first reconnect attempt. Defaults to 1s, floored at 50ms. #[usage( name = "backoff-initial", long, @@ -104,6 +105,7 @@ pub struct Backoff { )] pub max: Option, + /// Maximum delay between reconnect attempts. Defaults to 5s. #[usage(name = "backoff-max", long, env = "MOQ_BACKOFF_MAX", setting = "connect.backoff.max")] #[serde(default, rename = "__cli_max", skip_serializing_if = "Option::is_none")] max_arg: Option, @@ -132,6 +134,7 @@ pub struct Backoff { // No parser default: the parser stores one as if it were given, and it would then beat a // window set in code. The default lives in [`Backoff::window`] instead. + /// Maximum time to spend retrying before giving up. Defaults to 10s; 0s retries forever. #[usage( name = "backoff-timeout", long, @@ -355,6 +358,7 @@ pub struct Goaway { )] pub handover: Option, + /// How long the old session keeps serving after its replacement connects. Defaults to 10s. #[usage( name = "goaway-handover", long, diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index 67229671d07..20e6fa4f7ab 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -168,6 +168,7 @@ pub struct Config { )] pub timeout: Option, + /// Maximum time for an accepted connection to finish its handshake. Defaults to 10s; 0s waits forever. #[usage( name = "listen-timeout", long = "listen-timeout", diff --git a/rs/moq-tokio/src/quic.rs b/rs/moq-tokio/src/quic.rs index 0fcef593cd8..4935765246d 100644 --- a/rs/moq-tokio/src/quic.rs +++ b/rs/moq-tokio/src/quic.rs @@ -149,6 +149,7 @@ pub struct Config { )] pub idle_timeout: Option, + /// Idle timeout before an inactive connection is dropped. Defaults to 10s. #[usage( name = "quic-idle-timeout", long = "quic-idle-timeout", @@ -172,6 +173,7 @@ pub struct Config { )] pub keep_alive: Option, + /// Keep-alive ping interval. Defaults to 3s; 0s disables it. #[usage( name = "quic-keep-alive", long = "quic-keep-alive", diff --git a/rs/moq-tokio/src/websocket.rs b/rs/moq-tokio/src/websocket.rs index 09057a91148..e7a4d7a6a1c 100644 --- a/rs/moq-tokio/src/websocket.rs +++ b/rs/moq-tokio/src/websocket.rs @@ -177,6 +177,7 @@ pub struct Config { )] pub delay: Option, + /// Head start given to the QUIC dial before the WebSocket fallback joins the race. Defaults to 200ms. #[usage( name = "connect-websocket-delay", long = "connect-websocket-delay",