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    #[must_use]
141    pub fn with_auth_token_source(mut self, source: impl TokenSource) -> Self {
142        self.auth_token_source = Some(Arc::new(source));
143        self
144    }
145
146    /// Sets the preferred underlay, applied to whatever endhost API discovery
147    /// returns (default: UDP).
148    #[must_use]
149    pub fn with_preferred_underlay(mut self, underlay: PreferredUnderlay) -> Self {
150        self.preferred_underlay = Some(underlay);
151        self
152    }
153
154    /// Customizes the [`ScionStackBuilder`] used to build connectivity, for
155    /// settings this configuration does not expose directly (underlay-specific
156    /// configuration, discovery tuning, token sources).
157    ///
158    /// The hook runs every time connectivity is (re)built: on first use and
159    /// after every [`reset`](crate::Client::reset). It runs after the settings
160    /// above are applied, so it can override them.
161    // XXX(shitz): This hook exists because `SnapUnderlayConfig`/`UdpUnderlayConfig`
162    // are single-use (not `Clone`) while every rebuild needs a fresh
163    // `ScionStackBuilder` from the same settings. Once they are made `Clone`
164    // in scion-stack, replace this with direct `with_snap_underlay_config` and
165    // `with_udp_underlay_config` setters.
166    #[must_use]
167    pub fn with_stack_customizer(
168        mut self,
169        customizer: impl Fn(ScionStackBuilder) -> ScionStackBuilder + Send + Sync + 'static,
170    ) -> Self {
171        self.stack_customizer = Some(Arc::new(customizer));
172        self
173    }
174
175    /// Sets the timeout for establishing a connection to an origin, covering
176    /// name resolution and all staggered connection attempts.
177    #[must_use]
178    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
179        self.connect_timeout = timeout;
180        self
181    }
182
183    /// Sets the default timeout for a whole request: connectivity build,
184    /// establishment, response head, and body collection. Overridable per
185    /// request with
186    /// [`RequestBuilder::request_timeout`](crate::RequestBuilder::request_timeout).
187    ///
188    /// It is one deadline across all of those phases, and it keeps running while
189    /// the caller holds the [`Response`](crate::Response) — see there for what
190    /// that means for body collection.
191    #[must_use]
192    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
193        self.request_timeout = timeout;
194        self
195    }
196
197    /// Sets how long an origin's pooled connection may sit unused before an
198    /// opportunistic sweep reclaims it (and its socket).
199    #[must_use]
200    pub fn with_idle_connection_timeout(mut self, timeout: Duration) -> Self {
201        self.idle_connection_timeout = timeout;
202        self
203    }
204
205    /// Bounds the number of distinct origins with pooled connections. Each
206    /// pooled connection holds a socket, and therefore a file descriptor;
207    /// when the bound is hit, the least recently used origin is evicted (and
208    /// the eviction logged).
209    #[must_use]
210    pub fn with_max_origins(mut self, max_origins: usize) -> Self {
211        self.max_origins = max_origins;
212        self
213    }
214
215    /// Sets the stagger between connection attempts to an origin's candidate
216    /// addresses: the next candidate is only tried this long after the
217    /// previous one, unless it already failed (RFC 8305, Happy Eyeballs).
218    #[must_use]
219    pub fn with_connection_attempt_delay(mut self, delay: Duration) -> Self {
220        self.connection_attempt_delay = delay;
221        self
222    }
223
224    /// Sets the QUIC configuration used for every connection: trust anchors
225    /// (`ca_certs_file` / `ca_certs_dir` / `ca_certs_pem`) or a certificate
226    /// verifier (`with_cert_verifier` / `with_platform_verifier`), peer
227    /// verification, handshake and idle timeouts, and transport tuning. The application
228    /// protocol list must contain `h3` (the default).
229    #[must_use]
230    pub fn with_quic_config(mut self, quic: QuicConfig) -> Self {
231        self.quic = quic;
232        self
233    }
234
235    /// Replaces the default DNS resolver
236    /// ([`ScionTxtDnsResolver`](scion_stack::resolver::txt::ScionTxtDnsResolver))
237    /// with a caller-supplied one.
238    ///
239    /// The default resolver is constructed fresh on every connectivity
240    /// rebuild, because system DNS configuration is a property of the current
241    /// network. An injected resolver is reused across rebuilds as-is;
242    /// reacting to network changes is then its responsibility.
243    #[must_use]
244    pub fn with_resolver(mut self, resolver: Arc<dyn ScionDnsResolver>) -> Self {
245        self.resolver = Some(resolver);
246        self
247    }
248
249    /// Resolves `host` to `addrs` instead of looking it up, for a host that
250    /// has no TSAR records. Applies to URLs and to `CONNECT` authorities
251    /// alike.
252    ///
253    /// Only the default resolver applies overrides. A resolver injected with
254    /// [`with_resolver`](Self::with_resolver) does its own resolution.
255    #[must_use]
256    pub fn with_dns_override(mut self, host: impl Into<String>, addrs: Vec<ScionIpAddr>) -> Self {
257        self.dns_overrides
258            .push((host.into().to_ascii_lowercase(), addrs));
259        self
260    }
261}
262
263impl fmt::Debug for Config {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        f.debug_struct("Config")
266            .field("endhost_api", &self.endhost_api)
267            .field(
268                "auth_token_source",
269                &self.auth_token_source.as_ref().map(|_| "<redacted>"),
270            )
271            .field("preferred_underlay", &self.preferred_underlay)
272            .field(
273                "stack_customizer",
274                &self.stack_customizer.as_ref().map(|_| "<fn>"),
275            )
276            .field("connect_timeout", &self.connect_timeout)
277            .field("request_timeout", &self.request_timeout)
278            .field("idle_connection_timeout", &self.idle_connection_timeout)
279            .field("max_origins", &self.max_origins)
280            .field("connection_attempt_delay", &self.connection_attempt_delay)
281            .field("quic", &self.quic)
282            .field("resolver", &self.resolver.as_ref().map(|_| "<custom>"))
283            .field("dns_overrides", &self.dns_overrides)
284            .finish()
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    fn config() -> Config {
293        Config::new("https://endhost-api.example.org".parse().unwrap())
294    }
295
296    #[test]
297    fn new_applies_defaults() {
298        let config = config();
299        assert_eq!(config.connect_timeout, DEFAULT_CONNECT_TIMEOUT);
300        assert_eq!(config.request_timeout, DEFAULT_REQUEST_TIMEOUT);
301        assert_eq!(
302            config.idle_connection_timeout,
303            DEFAULT_IDLE_CONNECTION_TIMEOUT
304        );
305        assert_eq!(config.max_origins, DEFAULT_MAX_ORIGINS);
306        assert_eq!(
307            config.connection_attempt_delay,
308            DEFAULT_CONNECTION_ATTEMPT_DELAY
309        );
310    }
311
312    #[test]
313    fn default_idle_sweep_precedes_quic_idle_timeout() {
314        let config = config();
315        assert!(config.idle_connection_timeout < config.quic.idle_timeout);
316    }
317
318    #[test]
319    fn debug_redacts_the_auth_token() {
320        let config = config().with_auth_token("super-secret-token");
321        let debug = format!("{config:?}");
322        assert!(!debug.contains("super-secret-token"));
323        assert!(debug.contains("<redacted>"));
324    }
325}