Skip to main content

scion_http3/
config.rs

1// Copyright 2026 Anapaya Systems
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//   http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Client configuration.
16
17use std::{fmt, sync::Arc, time::Duration};
18
19use async_trait::async_trait;
20use scion_quic::quic::config::QuicConfig;
21use scion_stack::{
22    ScionStackBuilder,
23    reqwest_connect_rpc::token_source::{
24        TokenSource, TokenSourceError, TokenSourceWatch, static_token::StaticTokenSource,
25    },
26    resolver::ScionDnsResolver,
27    stack::builder::PreferredUnderlay,
28};
29use sciparse::address::ip_addr::ScionIpAddr;
30use url::Url;
31
32/// Default timeout for establishing a connection to an origin.
33pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
34/// Default timeout for a request (response head plus body collection).
35pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
36/// Default idle time after which an origin's connection is swept.
37///
38/// Deliberately below the default QUIC idle timeout (30 seconds,
39/// [`scion_quic::quic::config::QuicConfig`]): QUIC kills an idle connection
40/// after that and keep-alives are off, so sweeping later would pool
41/// connections that are already dead.
42pub const DEFAULT_IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(25);
43/// Default bound on the number of distinct origins with pooled connections.
44pub const DEFAULT_MAX_ORIGINS: usize = 8;
45/// Default stagger between connection attempts to an origin's candidate
46/// addresses (RFC 8305, Happy Eyeballs).
47pub const DEFAULT_CONNECTION_ATTEMPT_DELAY: Duration = Duration::from_millis(250);
48
49/// The type of the [`ScionStackBuilder`] customization hook, see
50/// [`Config::with_stack_customizer`].
51pub(crate) type StackCustomizer =
52    dyn Fn(ScionStackBuilder) -> ScionStackBuilder + Send + Sync + 'static;
53
54/// Adapts a shared [`TokenSource`] to the by-value `impl TokenSource` the stack
55/// builder takes.
56///
57/// A [`Config`] is cloneable and outlives every stack built from it, so it holds
58/// the source behind an `Arc` and hands the builder one of these on each
59/// rebuild. Both methods delegate, so a refreshing source keeps refreshing.
60pub(crate) struct SharedTokenSource(pub(crate) Arc<dyn TokenSource>);
61
62#[async_trait]
63impl TokenSource for SharedTokenSource {
64    fn watch(&self) -> TokenSourceWatch {
65        self.0.watch()
66    }
67
68    async fn get_token(&self) -> Result<String, TokenSourceError> {
69        self.0.get_token().await
70    }
71}
72
73/// Configuration for a [`Client`](crate::Client).
74///
75/// Construct with [`Config::new`] and customize with the consuming `with_*`
76/// methods. The endhost API URL is the only required setting: it is how the
77/// client discovers the data planes available to it, and the same single
78/// setting reaches a real SCION network or a local `PocketSCION` topology.
79#[derive(Clone)]
80pub struct Config {
81    pub(crate) endhost_api: Url,
82    pub(crate) auth_token_source: Option<Arc<dyn TokenSource>>,
83    pub(crate) preferred_underlay: Option<PreferredUnderlay>,
84    pub(crate) stack_customizer: Option<Arc<StackCustomizer>>,
85    pub(crate) connect_timeout: Duration,
86    pub(crate) request_timeout: Duration,
87    pub(crate) idle_connection_timeout: Duration,
88    pub(crate) max_origins: usize,
89    pub(crate) connection_attempt_delay: Duration,
90    pub(crate) quic: QuicConfig,
91    pub(crate) resolver: Option<Arc<dyn ScionDnsResolver>>,
92    pub(crate) dns_overrides: Vec<(String, Vec<ScionIpAddr>)>,
93}
94
95impl Config {
96    /// Creates a configuration that discovers connectivity through the given
97    /// endhost API.
98    #[must_use]
99    pub fn new(endhost_api: Url) -> Self {
100        Config {
101            endhost_api,
102            auth_token_source: None,
103            preferred_underlay: None,
104            stack_customizer: None,
105            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
106            request_timeout: DEFAULT_REQUEST_TIMEOUT,
107            idle_connection_timeout: DEFAULT_IDLE_CONNECTION_TIMEOUT,
108            max_origins: DEFAULT_MAX_ORIGINS,
109            connection_attempt_delay: DEFAULT_CONNECTION_ATTEMPT_DELAY,
110            quic: QuicConfig::default(),
111            resolver: None,
112            dns_overrides: Vec::new(),
113        }
114    }
115
116    /// Sets a fixed token to authenticate with the endhost API and the SNAP
117    /// control plane.
118    ///
119    /// Use [`with_auth_token_source`](Self::with_auth_token_source) instead when
120    /// the token expires: connectivity is rebuilt on every
121    /// [`reset`](crate::Client::reset), and a token captured here is reused
122    /// verbatim each time.
123    #[must_use]
124    pub fn with_auth_token(self, token: impl Into<String>) -> Self {
125        self.with_auth_token_source(StaticTokenSource::from(token.into()))
126    }
127
128    /// Sets the token *source* used to authenticate with the endhost API and
129    /// the SNAP control plane.
130    ///
131    /// The source is shared, not rebuilt: the same one is handed to every stack
132    /// this configuration builds, so a refreshing source keeps its schedule and
133    /// its cached token across a [`reset`](crate::Client::reset). Implement
134    /// [`TokenSource`](scion_stack::reqwest_connect_rpc::token_source::TokenSource)
135    /// to supply tokens that expire.
136    ///
137    /// For a source scoped to the endhost API alone, reach the builder's
138    /// `with_endhost_api_auth_token_source` through
139    /// [`with_stack_customizer`](Self::with_stack_customizer).
140    ///
141    /// A failing source fails the request with
142    /// [`Error::StackBuild`](crate::Error::StackBuild), which is retryable if
143    /// the source error is transient.
144    #[must_use]
145    pub fn with_auth_token_source(mut self, source: impl TokenSource) -> Self {
146        self.auth_token_source = Some(Arc::new(source));
147        self
148    }
149
150    /// Sets the preferred underlay, applied to whatever endhost API discovery
151    /// returns (default: UDP).
152    #[must_use]
153    pub fn with_preferred_underlay(mut self, underlay: PreferredUnderlay) -> Self {
154        self.preferred_underlay = Some(underlay);
155        self
156    }
157
158    /// Customizes the [`ScionStackBuilder`] used to build connectivity, for
159    /// settings this configuration does not expose directly (underlay-specific
160    /// configuration, discovery tuning, token sources).
161    ///
162    /// The hook runs every time connectivity is (re)built: on first use and
163    /// after every [`reset`](crate::Client::reset). It runs after the settings
164    /// above are applied, so it can override them.
165    // XXX(shitz): This hook exists because `SnapUnderlayConfig`/`UdpUnderlayConfig`
166    // are single-use (not `Clone`) while every rebuild needs a fresh
167    // `ScionStackBuilder` from the same settings. Once they are made `Clone`
168    // in scion-stack, replace this with direct `with_snap_underlay_config` and
169    // `with_udp_underlay_config` setters.
170    #[must_use]
171    pub fn with_stack_customizer(
172        mut self,
173        customizer: impl Fn(ScionStackBuilder) -> ScionStackBuilder + Send + Sync + 'static,
174    ) -> Self {
175        self.stack_customizer = Some(Arc::new(customizer));
176        self
177    }
178
179    /// Sets the timeout for establishing a connection to an origin, covering
180    /// name resolution and all staggered connection attempts.
181    #[must_use]
182    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
183        self.connect_timeout = timeout;
184        self
185    }
186
187    /// Sets the default timeout for a whole request: connectivity build,
188    /// establishment, response head, and body collection. Overridable per
189    /// request with
190    /// [`RequestBuilder::request_timeout`](crate::RequestBuilder::request_timeout).
191    ///
192    /// It is one deadline across all of those phases, and it keeps running while
193    /// the caller holds the [`Response`](crate::Response) — see there for what
194    /// that means for body collection.
195    #[must_use]
196    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
197        self.request_timeout = timeout;
198        self
199    }
200
201    /// Sets how long an origin's pooled connection may sit unused before an
202    /// opportunistic sweep reclaims it (and its socket).
203    #[must_use]
204    pub fn with_idle_connection_timeout(mut self, timeout: Duration) -> Self {
205        self.idle_connection_timeout = timeout;
206        self
207    }
208
209    /// Bounds the number of distinct origins with pooled connections. Each
210    /// pooled connection holds a socket, and therefore a file descriptor;
211    /// when the bound is hit, the least recently used origin is evicted (and
212    /// the eviction logged).
213    #[must_use]
214    pub fn with_max_origins(mut self, max_origins: usize) -> Self {
215        self.max_origins = max_origins;
216        self
217    }
218
219    /// Sets the stagger between connection attempts to an origin's candidate
220    /// addresses: the next candidate is only tried this long after the
221    /// previous one, unless it already failed (RFC 8305, Happy Eyeballs).
222    #[must_use]
223    pub fn with_connection_attempt_delay(mut self, delay: Duration) -> Self {
224        self.connection_attempt_delay = delay;
225        self
226    }
227
228    /// Sets the QUIC configuration used for every connection: trust anchors
229    /// (`ca_certs_file` / `ca_certs_dir` / `ca_certs_pem`) or a certificate
230    /// verifier (`with_cert_verifier` / `with_platform_verifier`), peer
231    /// verification, handshake and idle timeouts, and transport tuning. The application
232    /// protocol list must contain `h3` (the default).
233    #[must_use]
234    pub fn with_quic_config(mut self, quic: QuicConfig) -> Self {
235        self.quic = quic;
236        self
237    }
238
239    /// Replaces the default DNS resolver
240    /// ([`ScionTxtDnsResolver`](scion_stack::resolver::txt::ScionTxtDnsResolver))
241    /// with a caller-supplied one.
242    ///
243    /// The default resolver is constructed fresh on every connectivity
244    /// rebuild, because system DNS configuration is a property of the current
245    /// network. An injected resolver is reused across rebuilds as-is;
246    /// reacting to network changes is then its responsibility.
247    #[must_use]
248    pub fn with_resolver(mut self, resolver: Arc<dyn ScionDnsResolver>) -> Self {
249        self.resolver = Some(resolver);
250        self
251    }
252
253    /// Resolves `host` to `addrs` instead of looking it up, for a host that
254    /// has no TSAR records. Applies to URLs and to `CONNECT` authorities
255    /// alike.
256    ///
257    /// Only the default resolver applies overrides. A resolver injected with
258    /// [`with_resolver`](Self::with_resolver) does its own resolution.
259    #[must_use]
260    pub fn with_dns_override(mut self, host: impl Into<String>, addrs: Vec<ScionIpAddr>) -> Self {
261        self.dns_overrides
262            .push((host.into().to_ascii_lowercase(), addrs));
263        self
264    }
265}
266
267impl fmt::Debug for Config {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        f.debug_struct("Config")
270            .field("endhost_api", &self.endhost_api)
271            .field(
272                "auth_token_source",
273                &self.auth_token_source.as_ref().map(|_| "<redacted>"),
274            )
275            .field("preferred_underlay", &self.preferred_underlay)
276            .field(
277                "stack_customizer",
278                &self.stack_customizer.as_ref().map(|_| "<fn>"),
279            )
280            .field("connect_timeout", &self.connect_timeout)
281            .field("request_timeout", &self.request_timeout)
282            .field("idle_connection_timeout", &self.idle_connection_timeout)
283            .field("max_origins", &self.max_origins)
284            .field("connection_attempt_delay", &self.connection_attempt_delay)
285            .field("quic", &self.quic)
286            .field("resolver", &self.resolver.as_ref().map(|_| "<custom>"))
287            .field("dns_overrides", &self.dns_overrides)
288            .finish()
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    fn config() -> Config {
297        Config::new("https://endhost-api.example.org".parse().unwrap())
298    }
299
300    #[test]
301    fn new_applies_defaults() {
302        let config = config();
303        assert_eq!(config.connect_timeout, DEFAULT_CONNECT_TIMEOUT);
304        assert_eq!(config.request_timeout, DEFAULT_REQUEST_TIMEOUT);
305        assert_eq!(
306            config.idle_connection_timeout,
307            DEFAULT_IDLE_CONNECTION_TIMEOUT
308        );
309        assert_eq!(config.max_origins, DEFAULT_MAX_ORIGINS);
310        assert_eq!(
311            config.connection_attempt_delay,
312            DEFAULT_CONNECTION_ATTEMPT_DELAY
313        );
314    }
315
316    #[test]
317    fn default_idle_sweep_precedes_quic_idle_timeout() {
318        let config = config();
319        assert!(config.idle_connection_timeout < config.quic.idle_timeout);
320    }
321
322    #[test]
323    fn debug_redacts_the_auth_token() {
324        let config = config().with_auth_token("super-secret-token");
325        let debug = format!("{config:?}");
326        assert!(!debug.contains("super-secret-token"));
327        assert!(debug.contains("<redacted>"));
328    }
329}