diff --git a/quest/a1/node-idle/README.md b/quest/a1/node-idle/README.md index bcbc5141..f3e97be7 100644 --- a/quest/a1/node-idle/README.md +++ b/quest/a1/node-idle/README.md @@ -10,5 +10,4 @@ The native configuration and Node option quests are independently reviewable. Th ## Required -- [Native transport configuration](/quest/a1/node-idle/native-transport-config.md) - typed reusable builder input - [Node options](/quest/a1/node-idle/options.md) - explicit millisecond options and runtime behavior diff --git a/quest/a1/node-idle/native-transport-config.md b/quest/a1/node-idle/native-transport-config.md deleted file mode 100644 index 0bed32db..00000000 --- a/quest/a1/node-idle/native-transport-config.md +++ /dev/null @@ -1,11 +0,0 @@ -# [M] Accept typed native transport configuration - -## Goal - -Quinn client and server builders accept caller-provided TransportConfig without duplicating endpoint or TLS construction. - -## Plan - -Add a composable typed configuration input and retain the current defaults when omitted. Apply configuration across roots, certificate-hash and disabled-verification client construction, and server construction. Keep the existing explicit congestion-controller option as an overlay on the supplied configuration so unrelated options survive; document that precedence. - -Test preservation of timeout, keepalive and congestion-control settings through each construction path. Read the existing builder transport regression before extending it. This is a shared native API prerequisite for Node options, not a new cross-platform configuration abstraction. diff --git a/quest/a1/node-idle/options.md b/quest/a1/node-idle/options.md index 25f260c2..981c4850 100644 --- a/quest/a1/node-idle/options.md +++ b/quest/a1/node-idle/options.md @@ -10,10 +10,6 @@ Expose explicit millisecond options, validate finite representable values, and d Keep the default idle timeout and absent keepalive behavior. Test configured expiry, preserved default configuration, disabled behavior, keepalive maintaining an otherwise idle connection and invalid input rejection. Use deterministic configuration/unit coverage where possible; exercise actual Node runtime sessions for the integration behavior. Update generated declarations through the normal generation path, wrapper options and examples in the same PR. -## Required - -- [Native transport configuration](/quest/a1/node-idle/native-transport-config.md) - supply options consistently through existing construction paths - ## Closes - [#219](https://github.com/moq-dev/web-transport/issues/219) - the implementation completes this report diff --git a/rs/web-transport-quinn/README.md b/rs/web-transport-quinn/README.md index e17180b3..2ab5b96c 100644 --- a/rs/web-transport-quinn/README.md +++ b/rs/web-transport-quinn/README.md @@ -57,6 +57,31 @@ Both are spawned on the runtime that [quinn::default_runtime](https://docs.rs/qu Tokio works out of the box. To run on async-std or smol instead, enable quinn's `runtime-async-std` or `runtime-smol` feature in your own `Cargo.toml`. Resolving a hostname in `Client::connect` still uses tokio, so outside a tokio runtime connect to an IP address or resolve the name yourself. +## Transport configuration + +`ClientBuilder::with_transport_config` and `ServerBuilder::with_transport_config` take an owned `quinn::TransportConfig`. When omitted, the builders use Quinn's defaults: a 30-second maximum idle timeout, no keepalive, and CUBIC congestion control. The transport configuration applies to every client certificate-verification path and to server connections. + +```rust,no_run +use std::time::Duration; +use web_transport_quinn::{quinn, ClientBuilder, CongestionControl}; + +# fn main() -> Result<(), Box> { +let mut transport = quinn::TransportConfig::default(); +transport.max_idle_timeout(Some(Duration::from_secs(60).try_into()?)); +transport.keep_alive_interval(Some(Duration::from_secs(10))); + +let client = ClientBuilder::new() + .with_transport_config(transport) + .with_congestion_control(CongestionControl::LowLatency) + .with_system_roots()?; +# Ok(()) +# } +``` + +An explicit `LowLatency` or `Throughput` congestion choice overrides only the configuration's congestion controller, regardless of builder call order. `Default` removes that override and preserves the supplied controller. Calling `with_transport_config` again replaces the supplied configuration; other settings survive the congestion override. + +Quinn's `TransportConfig` is not cloneable, so `ClientBuilder` owns it and does not implement `Clone`. Construct a builder for each configuration, then clone the finished `Client` to share its endpoint and settings across connections. + ## API The `web-transport-quinn` API is almost identical to the Quinn API, except that [Connection](https://docs.rs/quinn/latest/quinn/struct.Connection.html) is called [Session](https://docs.rs/web-transport-quinn/latest/web_transport_quinn/struct.Session.html). diff --git a/rs/web-transport-quinn/src/client.rs b/rs/web-transport-quinn/src/client.rs index 9edeef04..eab00450 100644 --- a/rs/web-transport-quinn/src/client.rs +++ b/rs/web-transport-quinn/src/client.rs @@ -17,7 +17,7 @@ use crate::{ClientError, Session}; /// /// Different algorithms make different tradeoffs between throughput and latency. pub enum CongestionControl { - /// Use the default congestion control algorithm (typically CUBIC). + /// Keep the transport configuration's controller (Quinn defaults to CUBIC). Default, /// Optimize for throughput (typically CUBIC). Throughput, @@ -44,9 +44,9 @@ pub(crate) fn controller_factory(algorithm: CongestionControl) -> Option, ) -> Arc { - let mut transport = quinn::TransportConfig::default(); if let Some(cc) = congestion_controller { transport.congestion_controller_factory(cc.clone()); } @@ -58,9 +58,10 @@ pub(crate) fn transport_config( /// Construct a WebTransport [Client] using sane defaults. /// /// This is optional; advanced users may use [Client::new] directly. -#[derive(Clone)] +/// Build a client before cloning it to share its endpoint and configuration. pub struct ClientBuilder { provider: crypto::Provider, + transport: quinn::TransportConfig, congestion_controller: Option, } @@ -70,11 +71,24 @@ impl ClientBuilder { pub fn new() -> Self { Self { provider: crypto::default_provider(), + transport: quinn::TransportConfig::default(), congestion_controller: None, } } - /// Enable the specified congestion controller. + /// Use the supplied QUIC transport configuration instead of Quinn's defaults. + /// + /// An explicit [`Self::with_congestion_control`] choice overrides only its + /// congestion controller, regardless of the order these methods are called. + pub fn with_transport_config(mut self, transport: quinn::TransportConfig) -> Self { + self.transport = transport; + self + } + + /// Override the transport configuration's congestion controller. + /// + /// [`CongestionControl::Default`] preserves the supplied configuration's + /// controller, or Quinn's default when no configuration is supplied. pub fn with_congestion_control(mut self, algorithm: CongestionControl) -> Self { self.congestion_controller = controller_factory(algorithm); self @@ -160,7 +174,10 @@ impl ClientBuilder { let client_config = QuicClientConfig::try_from(crypto).unwrap(); let mut client_config = quinn::ClientConfig::new(Arc::new(client_config)); - client_config.transport_config(transport_config(self.congestion_controller.as_ref())); + client_config.transport_config(transport_config( + self.transport, + self.congestion_controller.as_ref(), + )); let client = quinn::Endpoint::client("[::]:0".parse().unwrap()).unwrap(); Ok(Client { @@ -390,3 +407,139 @@ impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification { self.0.signature_verification_algorithms.supported_schemes() } } + +#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +pub(crate) mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + pub(crate) fn builder() -> ClientBuilder { + // Avoid a process-wide provider when both features are enabled. + #[cfg(feature = "aws-lc-rs")] + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] + let provider = Arc::new(rustls::crypto::ring::default_provider()); + + ClientBuilder { + provider, + transport: quinn::TransportConfig::default(), + congestion_controller: None, + } + } + + struct CountingController(Arc); + + impl quinn::congestion::ControllerFactory for CountingController { + fn build( + self: Arc, + now: std::time::Instant, + mtu: u16, + ) -> Box { + self.0.fetch_add(1, Ordering::SeqCst); + Arc::new(quinn::congestion::NewRenoConfig::default()).build(now, mtu) + } + } + + pub(crate) fn custom_transport() -> (quinn::TransportConfig, Arc) { + let built = Arc::new(AtomicUsize::new(0)); + let mut transport = quinn::TransportConfig::default(); + transport + .max_idle_timeout(Some(Duration::from_secs(12).try_into().unwrap())) + .keep_alive_interval(Some(Duration::from_secs(3))) + .congestion_controller_factory(Arc::new(CountingController(built.clone()))); + (transport, built) + } + + pub(crate) fn assert_transport(config: &impl std::fmt::Debug, custom: bool) { + // Quinn exposes these settings only through Debug. + let expected = if custom { + custom_transport().0 + } else { + quinn::TransportConfig::default() + }; + let expected = format!("{expected:?}"); + let config = format!("{config:?}"); + assert!(config.contains(&expected), "{config}"); + } + + fn finish(builder: ClientBuilder, path: u8) -> Client { + match path { + 0 => builder.with_system_roots(), + 1 => builder.with_server_certificate_hashes(vec![]), + 2 => builder.with_server_certificates(vec![]), + 3 => builder.dangerous().with_no_certificate_verification(), + _ => unreachable!(), + } + .unwrap() + } + + #[tokio::test] + async fn builder_transport_reaches_every_client_config() { + for path in 0..4 { + let client = finish(builder(), path); + assert_transport(&client.config, false); + + for transport_first in [false, true] { + for algorithm in [ + CongestionControl::Default, + CongestionControl::LowLatency, + CongestionControl::Throughput, + ] { + let overridden = !matches!(algorithm, CongestionControl::Default); + let (transport, built) = custom_transport(); + let builder = builder(); + let builder = if transport_first { + builder + .with_transport_config(transport) + .with_congestion_control(algorithm) + } else { + builder + .with_congestion_control(algorithm) + .with_transport_config(transport) + }; + let client = finish(builder, path); + assert_transport(&client.config, true); + + // Controller construction happens before any network/TLS result, + // so the system-root path needs no publicly trusted test server. + let connecting = client + .endpoint + .connect_with( + client.config.clone(), + "[::1]:9".parse().unwrap(), + "localhost", + ) + .unwrap(); + assert_eq!(built.load(Ordering::SeqCst), usize::from(!overridden)); + drop(connecting); + client.endpoint.close(0u32.into(), b"done"); + } + } + } + } + + #[tokio::test] + async fn default_congestion_control_removes_only_the_overlay() { + let (transport, built) = custom_transport(); + let client = builder() + .with_transport_config(transport) + .with_congestion_control(CongestionControl::LowLatency) + .with_congestion_control(CongestionControl::Default) + .dangerous() + .with_no_certificate_verification() + .unwrap(); + assert_transport(&client.config, true); + let connecting = client + .endpoint + .connect_with( + client.config.clone(), + "[::1]:9".parse().unwrap(), + "localhost", + ) + .unwrap(); + assert_eq!(built.load(Ordering::SeqCst), 1); + drop(connecting); + client.endpoint.close(0u32.into(), b"done"); + } +} diff --git a/rs/web-transport-quinn/src/server.rs b/rs/web-transport-quinn/src/server.rs index 715ab26e..2decf9ed 100644 --- a/rs/web-transport-quinn/src/server.rs +++ b/rs/web-transport-quinn/src/server.rs @@ -26,6 +26,7 @@ use crate::{ pub struct ServerBuilder { provider: crypto::Provider, addr: std::net::SocketAddr, + transport: quinn::TransportConfig, congestion_controller: Option, } @@ -43,6 +44,7 @@ impl ServerBuilder { Self { provider: crypto::default_provider(), addr: "[::]:443".parse().unwrap(), + transport: quinn::TransportConfig::default(), congestion_controller: None, } } @@ -52,7 +54,19 @@ impl ServerBuilder { Self { addr, ..self } } - /// Enable the specified congestion controller. + /// Use the supplied QUIC transport configuration instead of Quinn's defaults. + /// + /// An explicit [`Self::with_congestion_control`] choice overrides only its + /// congestion controller, regardless of the order these methods are called. + pub fn with_transport_config(mut self, transport: quinn::TransportConfig) -> Self { + self.transport = transport; + self + } + + /// Override the transport configuration's congestion controller. + /// + /// [`CongestionControl::Default`] preserves the supplied configuration's + /// controller, or Quinn's default when no configuration is supplied. pub fn with_congestion_control(mut self, algorithm: CongestionControl) -> Self { self.congestion_controller = controller_factory(algorithm); self @@ -65,22 +79,19 @@ impl ServerBuilder { chain: Vec>, key: PrivateKeyDer<'static>, ) -> Result { - let transport = transport_config(self.congestion_controller.as_ref()); - let config = self.config(chain, key, transport)?; + let addr = self.addr; + let config = self.config(chain, key)?; - let server = quinn::Endpoint::server(config, self.addr) - .map_err(|e| ServerError::IoError(e.into()))?; + let server = + quinn::Endpoint::server(config, addr).map_err(|e| ServerError::IoError(e.into()))?; Ok(Server::new(server)) } - /// Build the quinn config, taking the transport separately so the caller (and the - /// tests) can tell which one ends up attached. fn config( - &self, + self, chain: Vec>, key: PrivateKeyDer<'static>, - transport: Arc, ) -> Result { // Standard Quinn setup let mut config = rustls::ServerConfig::builder_with_provider(self.provider.clone()) @@ -92,7 +103,10 @@ impl ServerBuilder { let config: quinn::crypto::rustls::QuicServerConfig = config.try_into().unwrap(); let mut config = quinn::ServerConfig::with_crypto(Arc::new(config)); - config.transport_config(transport); + config.transport_config(transport_config( + self.transport, + self.congestion_controller.as_ref(), + )); Ok(config) } @@ -241,6 +255,7 @@ impl core::ops::Deref for Request { #[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] mod tests { use super::*; + use crate::client::tests::{assert_transport, custom_transport}; use rustls::pki_types::PrivatePkcs8KeyDer; fn self_signed() -> (Vec>, PrivateKeyDer<'static>) { @@ -263,22 +278,97 @@ mod tests { ServerBuilder { provider, addr: "[::]:0".parse().unwrap(), + transport: quinn::TransportConfig::default(), congestion_controller: None, } } /// quinn installs its own default transport config, so the builder's has to be - /// attached explicitly or every server knob (congestion control) silently no-ops. + /// attached explicitly or every server knob silently no-ops. #[test] fn builder_transport_reaches_the_config() { let (chain, key) = self_signed(); - let builder = builder().with_congestion_control(CongestionControl::LowLatency); - assert!(builder.congestion_controller.is_some()); - - let transport = transport_config(builder.congestion_controller.as_ref()); - let config = builder.config(chain, key, transport.clone()).unwrap(); + let config = builder().config(chain, key).unwrap(); + assert_transport(&config.transport, false); + + for transport_first in [false, true] { + let (chain, key) = self_signed(); + let (transport, _) = custom_transport(); + let builder = if transport_first { + builder() + .with_transport_config(transport) + .with_congestion_control(CongestionControl::LowLatency) + } else { + builder() + .with_congestion_control(CongestionControl::LowLatency) + .with_transport_config(transport) + }; + let config = builder.config(chain, key).unwrap(); + assert_transport(&config.transport, true); + } + } - assert!(Arc::ptr_eq(&config.transport, &transport)); + #[tokio::test] + async fn builder_transport_reaches_the_server_endpoint() { + use std::sync::atomic::Ordering; + use std::time::Duration; + + tokio::time::timeout(Duration::from_secs(10), async { + for transport_first in [false, true] { + for algorithm in [ + CongestionControl::Default, + CongestionControl::LowLatency, + CongestionControl::Throughput, + ] { + let (chain, key) = self_signed(); + let (transport, built) = custom_transport(); + let expected = match algorithm { + CongestionControl::Default => { + std::any::TypeId::of::() + } + CongestionControl::LowLatency => { + std::any::TypeId::of::() + } + CongestionControl::Throughput => { + std::any::TypeId::of::() + } + }; + let builder = if transport_first { + builder() + .with_transport_config(transport) + .with_congestion_control(algorithm) + } else { + builder() + .with_congestion_control(algorithm) + .with_transport_config(transport) + }; + let mut server = builder.with_certificate(chain, key).unwrap(); + let client = crate::client::tests::builder() + .dangerous() + .with_no_certificate_verification() + .unwrap(); + let url = format!("https://[::1]:{}/", server.local_addr().unwrap().port()) + .parse::() + .unwrap(); + let (client_session, server_session) = + tokio::join!(client.connect(url), async { + server.accept().await.unwrap().ok().await.unwrap() + }); + let client_session = client_session.unwrap(); + let controller = server_session.congestion_state().into_any(); + assert_eq!(controller.as_ref().type_id(), expected); + assert_eq!( + built.load(Ordering::SeqCst), + usize::from(controller.is::()) + ); + server.close(0u32.into(), b"done"); + client_session.closed().await; + server.wait_idle().await; + } + } + }) + .await + .unwrap(); } } diff --git a/rs/web-transport/README.md b/rs/web-transport/README.md index 0720376f..6a9ab0f8 100644 --- a/rs/web-transport/README.md +++ b/rs/web-transport/README.md @@ -15,6 +15,10 @@ This crate provides a generic WebTransport implementation depending on the platf WASM builds additionally require `--cfg=web_sys_unstable_apis`; see [web-transport-wasm](../web-transport-wasm/README.md#requirements). +The native `ClientBuilder::with_transport_config` accepts Quinn's owned `TransportConfig`, available through `web_transport::quinn::quinn::TransportConfig`. Explicit congestion control overrides only its controller, regardless of setter order; see the [Quinn configuration documentation](../web-transport-quinn/README.md#transport-configuration) for defaults and examples. + +The native `ClientBuilder` does not implement `Clone`. Construct a builder for each configuration, then clone the finished `Client` when sharing its endpoint and settings. + ## Why no trait? diff --git a/rs/web-transport/src/quinn.rs b/rs/web-transport/src/quinn.rs index 9c90a05d..3ff5b046 100644 --- a/rs/web-transport/src/quinn.rs +++ b/rs/web-transport/src/quinn.rs @@ -7,7 +7,8 @@ pub use web_transport_quinn as quinn; pub use web_transport_quinn::CongestionControl; /// Create a [Client] that can be used to dial multiple [Session]s. -#[derive(Default, Clone)] +/// Build a client before cloning it to share its endpoint and configuration. +#[derive(Default)] pub struct ClientBuilder { inner: quinn::ClientBuilder, protocols: Vec, @@ -18,6 +19,17 @@ impl ClientBuilder { Self::default() } + /// Use the supplied QUIC transport configuration instead of Quinn's defaults. + /// + /// Explicit congestion control overrides only its controller, regardless of + /// the order this method and [`Self::with_congestion_control`] are called. + pub fn with_transport_config(self, transport: quinn::quinn::TransportConfig) -> Self { + Self { + inner: self.inner.with_transport_config(transport), + ..self + } + } + /// Allow a lower latency congestion controller. pub fn with_congestion_control(self, cc: CongestionControl) -> Self { Self {