Skip to main content

toolkit_contract/runtime/
config.rs

1//! Client, retry, and credential configuration consumed by generated clients.
2//!
3//! [`ClientConfig`] is shared by both the generated REST client and the
4//! generated gRPC client; [`InternalTokenProvider`] is the runtime source of the
5//! platform-plane credential those clients attach on `PlatformSecurityContext`
6//! methods.
7
8use std::borrow::Cow;
9use std::sync::Arc;
10use std::time::Duration;
11
12use secrecy::SecretString;
13
14/// Outcome of resolving the process's platform-plane credential on one outbound
15/// call.
16///
17/// Three-state (rather than `Option<SecretString>`) so an attach site can tell
18/// an intentionally unauthenticated deployment (Profile 1) apart from a broken
19/// credential source — e.g. the projected token file is transiently empty.
20/// Attach helpers stay silent on [`Self::NotConfigured`] and `warn!` on
21/// [`Self::Unavailable`], never emitting the token.
22#[derive(Debug)]
23pub enum CredentialState {
24    /// No credential configured (Profile 1 / `InternalCredential::None`). Attach
25    /// nothing, silently — a legitimate deployment.
26    NotConfigured,
27    /// A credential is configured and currently available; attach it.
28    Available(SecretString),
29    /// Configured but currently unavailable (empty token file, or the background
30    /// refresh has not run yet). Attach nothing but **warn** — a broken source,
31    /// not an intentional opt-out. Carries the reason (never the token).
32    Unavailable(Cow<'static, str>),
33}
34
35/// Source of the process's **platform-plane** internal credential.
36///
37/// Generated clients attach it — as the `X-ToolKit-Internal-Token` header /
38/// metadata, **never** `Authorization` — on methods whose plane marker is
39/// `PlatformSecurityContext` (`cpt-cf-adr-two-plane-auth`). The credential comes
40/// from the runtime (the bootstrap-selected `InternalCredential`), never the
41/// contract argument.
42///
43/// Invoked on every call so a rotating credential (e.g. a projected Kubernetes
44/// `ServiceAccount` token) is always attached in its current form; it returns a
45/// [`CredentialState`] to distinguish not-configured (silent) from unavailable
46/// (warn). Because it runs per-request on an async path, the closure **must not
47/// block, do I/O, or take a contended lock** (see [`InternalTokenProvider::new`]).
48#[derive(Clone)]
49pub struct InternalTokenProvider(Arc<dyn Fn() -> CredentialState + Send + Sync>);
50
51impl InternalTokenProvider {
52    /// Build a provider whose credential is resolved by `provider` on each call
53    /// (supports rotation).
54    ///
55    /// The closure **must not block, do I/O, or take a contended lock** — it is
56    /// called on every outbound platform-plane request from an async path. See
57    /// [`InternalTokenProvider`] and use `ServiceAccountTokenReader::token_provider`
58    /// as the reference pattern for a rotating credential.
59    #[must_use]
60    pub fn new(provider: impl Fn() -> CredentialState + Send + Sync + 'static) -> Self {
61        Self(Arc::new(provider))
62    }
63
64    /// Build a provider that always yields the given static `token`.
65    ///
66    /// Suitable for a non-rotating credential (e.g. a shared secret); prefer
67    /// [`InternalTokenProvider::new`] for rotating tokens.
68    #[must_use]
69    pub fn from_token(token: SecretString) -> Self {
70        Self::new(move || CredentialState::Available(token.clone()))
71    }
72
73    /// Resolve the current credential state.
74    #[must_use]
75    pub fn current(&self) -> CredentialState {
76        (self.0)()
77    }
78
79    /// Resolve the token to attach on an outbound platform-plane call, applying
80    /// the shared attach policy so the REST and gRPC helpers behave identically:
81    /// `None`/[`NotConfigured`](CredentialState::NotConfigured) → `None` (silent),
82    /// [`Available`](CredentialState::Available) → `Some`, and
83    /// [`Unavailable`](CredentialState::Unavailable) → `None` plus a `warn!`
84    /// naming the plane and `rpc` (never the token).
85    #[must_use]
86    pub fn resolve_for_attach(provider: Option<&Self>, rpc: &str) -> Option<SecretString> {
87        match provider.map(Self::current) {
88            None | Some(CredentialState::NotConfigured) => None,
89            Some(CredentialState::Available(token)) => Some(token),
90            Some(CredentialState::Unavailable(reason)) => {
91                tracing::warn!(
92                    plane = "platform",
93                    rpc,
94                    reason = %reason,
95                    "platform-plane credential configured but currently unavailable; \
96                     sending request without the internal token",
97                );
98                None
99            }
100        }
101    }
102}
103
104impl std::fmt::Debug for InternalTokenProvider {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        // Never render the credential (or even hint at its presence beyond the
107        // opaque marker) so it cannot leak through a `{:?}` sink.
108        f.write_str("InternalTokenProvider(<fn>)")
109    }
110}
111
112/// Base configuration for a generated REST client.
113///
114/// `#[non_exhaustive]`: construct via [`ClientConfig::new`] and the `with_*`
115/// chain rather than a struct literal, so future transport knobs can be added
116/// without a breaking change.
117#[derive(Debug, Clone)]
118#[non_exhaustive]
119pub struct ClientConfig {
120    /// Base URL prefix (e.g., `https://billing.internal`).
121    /// Combined with the base path declared in the projection trait.
122    pub base_url: String,
123    /// Deadline applied to a **single** unary attempt — NOT to the whole logical
124    /// call. A `#[retryable]` method may make up to `retry.max_attempts` attempts,
125    /// so the worst-case wall-clock for a logical call is bounded by
126    /// `max_attempts × (timeout + retry.max_delay)` (the per-retry backoff is
127    /// itself clamped to [`RetryConfig::max_delay`], including a server-advised
128    /// `Retry-After`). There is deliberately no separate whole-call budget field.
129    pub timeout: Duration,
130    /// Per-**item** idle deadline for streams of any framing: the maximum gap
131    /// between two received wire chunks before the stream is treated as timed
132    /// out. A long-lived stream is NOT bounded by [`timeout`](Self::timeout)
133    /// (which would kill a healthy slow stream); it is bounded by this larger
134    /// idle deadline instead. Defaults to 60s (> the unary default).
135    ///
136    /// This is *idle*, not *quiet*: any wire chunk resets it, including ones
137    /// that dispatch no item (an SSE keepalive comment, a multipart part header
138    /// block arriving on its own).
139    pub stream_idle_timeout: Duration,
140    /// Retry policy applied to methods marked `#[retryable]`.
141    pub retry: RetryConfig,
142    /// Reconnect policy for streams of any framing. By default
143    /// `max_attempts: 0` — stream failures bubble up unchanged. Set explicitly
144    /// to opt into transparent re-open on a transient failure.
145    ///
146    /// Two limits are deliberate rather than accidental:
147    ///
148    /// - **It applies only to a method whose open is immediate**
149    ///   (`#[streaming] fn`). A fallible open (`#[streaming] async fn`) carries
150    ///   domain semantics the client must not blindly repeat — a re-open can
151    ///   collide with an exclusion lease the first open acquired, and its
152    ///   failure would land as a stream item, past the caller's open-time error
153    ///   handling. Generated code therefore passes
154    ///   [`ReconnectConfig::disabled`] for a fallible open regardless of this
155    ///   value.
156    /// - **Resume via `Last-Event-ID` is SSE-only.** A reconnected
157    ///   `multipart/mixed` stream re-issues the original request with no resume
158    ///   token, because the framing has none. The transport still reopens it,
159    ///   but that is a blind restart, not a resume: the server replays the body
160    ///   from its first part, so any items already delivered before the failure
161    ///   are **delivered again** (at-least-once, with no marker for the
162    ///   restart). Enable reconnect for a multipart stream only where the
163    ///   consumer tolerates duplicates; one needing exactly-once must instead
164    ///   leave reconnect disabled and run its own reopen loop with
165    ///   application-level dedup.
166    pub stream_reconnect: ReconnectConfig,
167    /// When `true`, the generated client refuses plaintext `http://` and
168    /// requires TLS (`toolkit_http::TransportSecurity::TlsOnly`) for every
169    /// request — including the bearer-carrying `Authorization` header, which
170    /// otherwise would ride whatever scheme `base_url` uses. Defaults to
171    /// `false`, preserving the platform's existing in-mesh service-to-service
172    /// convention where plaintext HTTP inside a secured network boundary is an
173    /// accepted, deliberate choice (see
174    /// [`build_default_http_client`](crate::runtime::client::build_default_http_client)).
175    /// In a build where `toolkit-http/fips` is enabled the default is `true`
176    /// (it follows `toolkit_http::TransportSecurity::default()`); there an
177    /// explicit `false` is the opt-in to plaintext and a warning is logged
178    /// when the client is built (by `toolkit-http` for REST, by the generated
179    /// `connect` for gRPC).
180    /// Set this when a resolved endpoint may cross an untrusted network. Read by
181    /// both the REST and gRPC transports.
182    pub require_tls: bool,
183    /// Maximum *idle* keep-alive connections retained **per upstream host**
184    /// (active in-flight requests are not capped). Defaults to 128; raise via
185    /// [`ClientTuning`](crate::wiring::ClientTuning) for higher concurrency.
186    /// **REST transport only.**
187    ///
188    /// Keep it at or above the expected per-upstream concurrency: below that,
189    /// hyper closes excess connections as they idle and reopens them per
190    /// request, producing a `connect(2)` storm that dominates CPU. The 128
191    /// default clears the ~100-concurrent gear-to-gear traffic that motivated it
192    /// (the old `toolkit-http` default of 32 did not).
193    pub pool_max_idle_per_host: usize,
194    /// How long an idle keep-alive connection is retained before it is closed —
195    /// the companion of [`pool_max_idle_per_host`](Self::pool_max_idle_per_host)
196    /// (which bounds *how many*). Keep it above the gap between bursts to an
197    /// upstream so connections stay warm. Defaults to 90s. **REST transport only.**
198    ///
199    /// `None` does **not** mean "kept indefinitely": it leaves the hyper-util
200    /// setter unset, so hyper-util's own default (~90s) applies. The default is
201    /// an explicit `Some(90s)` for that reason.
202    pub pool_idle_timeout: Option<Duration>,
203    /// Maximum in-flight requests through this client at once (across all
204    /// upstream hosts). `None` disables the limiter; `Some(n)` caps at `n`, with
205    /// `Some(0)` clamped to 1 by the transport so the client can't wedge
206    /// shedding everything. Defaults to `Some(128)`, aligned with
207    /// [`pool_max_idle_per_host`](Self::pool_max_idle_per_host) so the idle pool
208    /// is fully reusable before load is shed. **REST transport only.**
209    ///
210    /// The cap bounds requests *waiting on response headers* — the tower permit
211    /// is released once headers arrive, so a long-lived SSE/multipart body holds
212    /// no slot while it streams; size it against in-flight requests, not open
213    /// streams. A shed request surfaces as
214    /// [`TransportError::Overloaded`](crate::runtime::transport_error::TransportError::Overloaded),
215    /// which is **not** transient, so a saturated client fails fast rather than
216    /// retrying into its own overload.
217    pub max_concurrent_requests: Option<usize>,
218    /// Source of the platform-plane internal credential attached to methods
219    /// whose plane marker is `PlatformSecurityContext` (carried as
220    /// `X-ToolKit-Internal-Token`). `None` (the default) attaches nothing —
221    /// legitimate for Profile 1 / in-process (`InternalCredential::None`);
222    /// the requirement is enforced server-side. The bootstrap layer populates
223    /// this from the process's selected `InternalCredential`. Tenant-plane
224    /// methods (`SecurityContext`) never consult it; they forward the caller's
225    /// bearer token from the argument.
226    pub internal_token_provider: Option<InternalTokenProvider>,
227}
228
229impl ClientConfig {
230    /// Create a new config with sensible defaults.
231    #[must_use]
232    pub fn new(base_url: impl Into<String>) -> Self {
233        Self {
234            base_url: base_url.into(),
235            timeout: Duration::from_secs(30),
236            stream_idle_timeout: Duration::from_mins(1),
237            retry: RetryConfig::default(),
238            stream_reconnect: ReconnectConfig::default(),
239            require_tls: default_require_tls(),
240            // `build_default_http_client` always sets these on the builder, so
241            // toolkit-http's own defaults (32/90s/100) never apply here.
242            pool_max_idle_per_host: 128,
243            pool_idle_timeout: Some(Duration::from_secs(90)),
244            max_concurrent_requests: Some(128),
245            internal_token_provider: None,
246        }
247    }
248
249    /// Override the per-call (unary) timeout.
250    #[must_use]
251    pub fn with_timeout(mut self, timeout: Duration) -> Self {
252        self.timeout = timeout;
253        self
254    }
255
256    /// Override the per-item stream idle deadline (max gap between wire
257    /// chunks). See [`Self::stream_idle_timeout`].
258    #[must_use]
259    pub fn with_stream_idle_timeout(mut self, idle: Duration) -> Self {
260        self.stream_idle_timeout = idle;
261        self
262    }
263
264    /// Override the retry policy.
265    #[must_use]
266    pub fn with_retry(mut self, retry: RetryConfig) -> Self {
267        self.retry = retry;
268        self
269    }
270
271    /// Override the stream reconnect policy. Use
272    /// [`ReconnectConfig::disabled()`] to disable (the default) or
273    /// [`ReconnectConfig::enabled()`] to opt in. See
274    /// [`Self::stream_reconnect`] for what it does and does not govern.
275    #[must_use]
276    pub fn with_stream_reconnect(mut self, stream_reconnect: ReconnectConfig) -> Self {
277        self.stream_reconnect = stream_reconnect;
278        self
279    }
280
281    /// Require TLS (reject plaintext `http://`) for this client. See
282    /// [`Self::require_tls`].
283    #[must_use]
284    pub fn with_require_tls(mut self, require_tls: bool) -> Self {
285        self.require_tls = require_tls;
286        self
287    }
288
289    /// Error message when [`Self::require_tls`] is set but `base_url` is not
290    /// `https://`. Transports call this when the client is constructed, so a
291    /// plaintext endpoint fails once there instead of on every call.
292    #[must_use]
293    pub(crate) fn tls_scheme_violation(&self) -> Option<String> {
294        if !self.require_tls || is_https(&self.base_url) {
295            return None;
296        }
297        let why = if default_require_tls() {
298            "require_tls is on (the default in FIPS builds); set `require_tls: false` \
299             to opt in to plaintext"
300        } else {
301            "require_tls is set"
302        };
303        Some(format!(
304            "{why}, but the endpoint scheme is not https: {}",
305            self.base_url
306        ))
307    }
308
309    /// Check `base_url` against [`Self::require_tls`], for a transport that
310    /// does not go through `toolkit-http` (the generated gRPC `connect`).
311    ///
312    /// In a FIPS build, a plaintext endpoint allowed by `require_tls: false`
313    /// passes, and the first one in the process is logged as a warning.
314    ///
315    /// # Errors
316    /// TLS is required and the endpoint is not `https://`; the message says why.
317    pub fn check_tls_scheme(&self) -> Result<(), String> {
318        if let Some(reason) = self.tls_scheme_violation() {
319            return Err(reason);
320        }
321        if default_require_tls() && !self.require_tls && !is_https(&self.base_url) {
322            static WARNED: std::sync::Once = std::sync::Once::new();
323            WARNED.call_once(|| {
324                tracing::warn!(
325                    target: "toolkit_http::security",
326                    endpoint = %self.base_url,
327                    "plaintext endpoint used in a FIPS build (require_tls: false): \
328                     requests to it are not encrypted (logged once per process)"
329                );
330            });
331        }
332        Ok(())
333    }
334
335    /// Override the max idle keep-alive connections per upstream host. See
336    /// [`Self::pool_max_idle_per_host`].
337    #[must_use]
338    pub fn with_pool_max_idle_per_host(mut self, max: usize) -> Self {
339        self.pool_max_idle_per_host = max;
340        self
341    }
342
343    /// Override how long idle keep-alive connections are retained (`None` uses
344    /// hyper-util's default). See [`Self::pool_idle_timeout`].
345    #[must_use]
346    pub fn with_pool_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
347        self.pool_idle_timeout = timeout;
348        self
349    }
350
351    /// Override the max concurrent in-flight requests (`None` disables the
352    /// limiter). See [`Self::max_concurrent_requests`].
353    #[must_use]
354    pub fn with_max_concurrent_requests(mut self, max: Option<usize>) -> Self {
355        self.max_concurrent_requests = max;
356        self
357    }
358
359    /// Set (or clear) the platform-plane internal-credential provider. See
360    /// [`Self::internal_token_provider`]. Accepts either an
361    /// [`InternalTokenProvider`] or an `Option<InternalTokenProvider>`, so the
362    /// bootstrap layer can pass through whatever the process selected without a
363    /// branch.
364    #[must_use]
365    pub fn with_internal_token_provider(
366        mut self,
367        provider: impl Into<Option<InternalTokenProvider>>,
368    ) -> Self {
369        self.internal_token_provider = provider.into();
370        self
371    }
372}
373
374/// Bounded exponential-backoff retry policy with full jitter.
375#[derive(Debug, Clone)]
376pub struct RetryConfig {
377    /// Maximum number of attempts (must be at least 1).
378    pub max_attempts: u32,
379    /// Base delay before the first retry.
380    pub base_delay: Duration,
381    /// Hard cap on the delay between retries.
382    pub max_delay: Duration,
383    /// Multiplier applied between consecutive retries.
384    pub multiplier: f64,
385}
386
387impl RetryConfig {
388    /// Disable retries entirely (single attempt).
389    #[must_use]
390    pub const fn off() -> Self {
391        Self {
392            max_attempts: 1,
393            base_delay: Duration::ZERO,
394            max_delay: Duration::ZERO,
395            multiplier: 1.0,
396        }
397    }
398}
399
400impl Default for RetryConfig {
401    fn default() -> Self {
402        Self {
403            max_attempts: 3,
404            base_delay: Duration::from_millis(100),
405            max_delay: Duration::from_secs(2),
406            multiplier: 2.0,
407        }
408    }
409}
410
411/// SSE reconnect policy. The streaming client tracks the latest `id:`
412/// field seen on the wire and, on transient stream failures, re-issues
413/// the request with a `Last-Event-ID: <stored>` header so the server can
414/// resume the event sequence (per HTML5 `EventSource` spec).
415///
416/// Default is **opt-in disabled** (`max_attempts: 0`) so existing SDKs see
417/// no behaviour change.
418#[derive(Debug, Clone)]
419pub struct ReconnectConfig {
420    /// Maximum number of *consecutive* reconnect attempts with no healthy
421    /// connection in between (the burst budget). `0` (default) disables
422    /// reconnect entirely — stream errors bubble up. The budget is reset by a
423    /// connection that both delivers an item and stays up at least
424    /// [`min_healthy_uptime`](Self::min_healthy_uptime).
425    pub max_attempts: u32,
426    /// Initial delay before the first reconnect attempt.
427    pub base_delay: Duration,
428    /// Hard cap on delay between reconnect attempts.
429    pub max_delay: Duration,
430    /// Minimum time a connection must stay up — *in addition to* delivering at
431    /// least one item — before its end resets the burst budget. Delivering a
432    /// single item is too weak a health signal on its own: a peer that emits
433    /// one item and immediately drops would reset the budget on every cycle and
434    /// reopen forever, re-sending the auth token each time (#4740). A connection
435    /// shorter than this counts against `max_attempts` like any other failed
436    /// attempt.
437    pub min_healthy_uptime: Duration,
438    /// Absolute lifetime ceiling on reopens, independent of budget resets. It
439    /// bounds the pathological peer that stays up *just past*
440    /// `min_healthy_uptime`, delivers an item, and drops on a loop — which would
441    /// otherwise reset the burst budget indefinitely. Set high enough that a
442    /// genuinely healthy long-lived subscription (which reconnects rarely) never
443    /// approaches it; `0` refuses reopen outright.
444    pub max_total_reopens: u32,
445}
446
447impl Default for ReconnectConfig {
448    fn default() -> Self {
449        Self {
450            max_attempts: 0,
451            base_delay: Duration::from_millis(500),
452            max_delay: Duration::from_secs(10),
453            min_healthy_uptime: Duration::from_secs(5),
454            max_total_reopens: 10_000,
455        }
456    }
457}
458
459impl ReconnectConfig {
460    /// Build a reconnect policy with up to `max_attempts` retries and the
461    /// supplied initial delay (capped by `max_delay`, default 10s).
462    #[must_use]
463    pub fn enabled(max_attempts: u32, base_delay: Duration) -> Self {
464        Self {
465            max_attempts,
466            base_delay,
467            ..Self::default()
468        }
469    }
470
471    /// A policy that never reconnects: the stream's first transport failure
472    /// ends it.
473    ///
474    /// The counterpart to [`ReconnectConfig::enabled`]. [`Default`] already
475    /// yields `max_attempts: 0`, so this is behaviourally the same value — it
476    /// exists so a call site that *must* not reconnect reads as a deliberate
477    /// choice rather than an accepted default.
478    ///
479    /// Generated clients pass this for a method whose open is fallible
480    /// (`#[streaming] async fn`). Such an open carries domain semantics the
481    /// client must not blindly repeat: any exclusion lease it acquired is owned
482    /// by the returned stream's lifetime, resume may be specified through the
483    /// contract's own cursor rather than `Last-Event-ID`, and a reconnect-time
484    /// failure would arrive as a stream *item* — past the caller's open-time
485    /// error handling, which is the whole reason the fallible shape exists.
486    #[must_use]
487    pub const fn disabled() -> Self {
488        // Every field is named explicitly (rather than `..Self::default()`) so a
489        // future field with an *enabling* default can't silently leak into a
490        // constructor documented as never reconnecting — matching
491        // [`RetryConfig::off`]. These are the same values as [`Default`].
492        Self {
493            max_attempts: 0,
494            base_delay: Duration::from_millis(500),
495            max_delay: Duration::from_secs(10),
496            min_healthy_uptime: Duration::from_secs(5),
497            max_total_reopens: 10_000,
498        }
499    }
500
501    /// Override the maximum delay between reconnect attempts.
502    #[must_use]
503    pub fn with_max_delay(mut self, max_delay: Duration) -> Self {
504        self.max_delay = max_delay;
505        self
506    }
507
508    /// Override the minimum healthy connection uptime that resets the burst
509    /// budget. See [`min_healthy_uptime`](Self::min_healthy_uptime).
510    #[must_use]
511    pub fn with_min_healthy_uptime(mut self, min_healthy_uptime: Duration) -> Self {
512        self.min_healthy_uptime = min_healthy_uptime;
513        self
514    }
515
516    /// Override the absolute lifetime cap on reopens. See
517    /// [`max_total_reopens`](Self::max_total_reopens).
518    #[must_use]
519    pub fn with_max_total_reopens(mut self, max_total_reopens: u32) -> Self {
520        self.max_total_reopens = max_total_reopens;
521        self
522    }
523}
524
525/// `true` when `toolkit-http` defaults to `TlsOnly`, i.e. under its `fips`
526/// feature. Read from `toolkit-http` rather than a feature of this crate so it
527/// follows Cargo feature unification.
528pub(crate) fn default_require_tls() -> bool {
529    toolkit_http::TransportSecurity::default() == toolkit_http::TransportSecurity::TlsOnly
530}
531
532fn is_https(url: &str) -> bool {
533    url.trim_start()
534        .get(..8)
535        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://"))
536}
537
538#[cfg(test)]
539#[cfg_attr(coverage_nightly, coverage(off))]
540mod tests {
541    use super::*;
542
543    /// Run with `--features fips` in `make test-fips`. The default follows
544    /// `toolkit-http`'s transport default, which feature unification can turn
545    /// to `TlsOnly` without this crate's `fips` feature; this crate's `fips`
546    /// always turns it on.
547    #[test]
548    fn require_tls_defaults_to_true_only_in_fips_builds() {
549        let require_tls = ClientConfig::new("http://svc").require_tls;
550        assert_eq!(
551            require_tls,
552            toolkit_http::TransportSecurity::default() == toolkit_http::TransportSecurity::TlsOnly
553        );
554        if cfg!(feature = "fips") {
555            assert!(
556                require_tls,
557                "require_tls must default to true in a FIPS build"
558            );
559        }
560    }
561
562    #[test]
563    fn tls_scheme_violation_only_for_required_tls_over_plaintext() {
564        let plain = ClientConfig::new("http://svc:8080");
565        assert!(
566            plain
567                .clone()
568                .with_require_tls(false)
569                .tls_scheme_violation()
570                .is_none()
571        );
572        let message = plain
573            .with_require_tls(true)
574            .tls_scheme_violation()
575            .expect("require_tls over http:// must be reported");
576        assert!(message.contains("http://svc:8080"), "{message}");
577        if cfg!(feature = "fips") {
578            assert!(message.contains("require_tls: false"), "{message}");
579        }
580
581        for url in ["https://svc", "HTTPS://svc", " https://svc"] {
582            let tls = ClientConfig::new(url).with_require_tls(true);
583            assert!(tls.tls_scheme_violation().is_none(), "{url}");
584        }
585    }
586
587    #[test]
588    fn check_tls_scheme_fails_only_on_violation() {
589        for (url, require_tls) in [
590            ("http://svc", false),
591            ("http://svc", true),
592            ("https://svc", false),
593            ("https://svc", true),
594        ] {
595            let config = ClientConfig::new(url).with_require_tls(require_tls);
596            assert_eq!(
597                config.check_tls_scheme().err(),
598                config.tls_scheme_violation(),
599                "{url} require_tls={require_tls}"
600            );
601        }
602    }
603
604    #[test]
605    fn default_retry_has_three_attempts() {
606        let r = RetryConfig::default();
607        assert_eq!(r.max_attempts, 3);
608        assert!(r.base_delay > Duration::ZERO);
609    }
610
611    #[test]
612    fn off_yields_single_attempt() {
613        let r = RetryConfig::off();
614        assert_eq!(r.max_attempts, 1);
615    }
616
617    // The "never a second attempt" guarantee that `disabled()` carries is
618    // pinned behaviourally by `reconnect_is_derived_from_the_open_shape_not_from_client_config`
619    // (tests/rest_client_codegen.rs), which counts real server connections on
620    // the fallible-open path and asserts exactly one. A unit test that merely
621    // read back `disabled()`'s fields couldn't fail unless struct construction
622    // itself broke, so it isn't restated here.
623
624    #[test]
625    fn client_config_chains_overrides() {
626        let cfg = ClientConfig::new("https://x.example")
627            .with_timeout(Duration::from_secs(5))
628            .with_retry(RetryConfig::off());
629        assert_eq!(cfg.base_url, "https://x.example");
630        assert_eq!(cfg.timeout, Duration::from_secs(5));
631        assert_eq!(cfg.retry.max_attempts, 1);
632    }
633}