eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! Phase-aware timeout configuration.
//!
//! Timeouts are applied per-phase during the request lifecycle. Each phase
//! measures a specific segment of the request:
//!
//! - **Pool**: time waiting for a connection slot from the pool.
//! - **Connect**: time to establish the TCP connection and TLS handshake
//!   (including DNS resolution).
//! - **`ProxyConnect`**: TCP connection to the proxy server. Only applies
//!   when a proxy is configured.
//! - **`ProxyTls`**: TLS handshake over a CONNECT tunnel to the proxy.
//!   Only applies to HTTPS targets routed through an HTTP proxy.
//! - **Write**: time for the request body producer to yield each chunk.
//!   Only applies to streamed request bodies; buffered bodies complete
//!   synchronously.
//! - **Read**: after the request body producer completes, time to wait for
//!   response headers, then each response body chunk. The deadline resets on
//!   each chunk. Early responses do not charge upload time to the read budget.
//! - **Total**: absolute wall-clock deadline across the entire request
//!   lifecycle, from logical request start through response-body EOF (or
//!   terminal body error), including pool acquisition, transport setup,
//!   response headers, body chunks, decompression, and trailers. It never
//!   resets on chunk arrival, decoding selection, or first body poll. A body
//!   that is first polled after the deadline reports `Total` without
//!   accepting a ready inner chunk.
//!
//! # Proxy timeout phases
//!
//! When a request is routed through a proxy, the connect phase splits
//! into two sub-phases:
//!
//! 1. `ProxyConnect` — the TCP connection from the client to the proxy.
//! 2. `ProxyTls` — the TLS handshake over the CONNECT tunnel (HTTPS
//!    targets only).
//!
//! After the tunnel is established, regular `Connect`, `Send`, and
//! `Receive` semantics apply to the destination.
//!
//! # Enforcement
//!
//! - **Pool** and **Total** are enforced with `tokio::time::timeout`.
//! - **Read** is enforced while waiting for response headers after request
//!   body completion on Hyper and UDS routes, then by a per-chunk wrapper
//!   stream. The body deadline starts on first body poll and resets on every
//!   chunk. Experimental HTTP/3 currently applies this field to response-body
//!   progress only; its header wait remains total-bounded.
//! - **Total** is enforced in two stages: `tokio::time::timeout` bounds the
//!   transport future up to response headers, and a crate-private absolute
//!   response-body deadline (`ResponseDeadline`) bounds body streaming
//!   through EOF/trailers. The absolute instant never resets; an
//!   already-expired deadline wins before polling the inner body, and when
//!   both read and total are observably expired at the same poll boundary
//!   `Total` is preferred as the outer lifecycle cap.
//! - **Write** is enforced by a per-chunk wrapper stream that fires
//!   `Error::Timeout { phase: Write }` if the producer does not yield
//!   the next chunk within the configured duration. The deadline resets
//!   on every chunk.
//! - **Connect** is enforced by wrapping the underlying connector with a
//!   timeout that bounds the entire connection-establishment phase (DNS
//!   resolution, TCP connect, and TLS handshake). Fires
//!   `Error::Timeout { phase: Connect }` if the connection is not
//!   established within the configured duration.
//!
//! When a scalar timeout is provided (e.g. `Timeout::from_secs(5)`), it
//! applies to pool, connect, write, and read phases. The total timeout is
//! not set by scalar constructors unless explicitly specified.
//!
//! Request-level timeout overrides client-level timeout on a per-field
//! basis: only the fields present in the request-level timeout replace
//! the corresponding client-level fields.

use std::time::Duration;

/// Identifies the phase of a request that timed out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimeoutPhase {
    /// Waiting for a connection slot from the pool.
    Pool,
    /// Establishing TCP connection and TLS handshake.
    Connect,
    /// TCP connection to the proxy server.
    ProxyConnect,
    /// TLS handshake over a CONNECT tunnel to the proxy.
    ProxyTls,
    /// Sending request headers and body.
    Write,
    /// Waiting for response headers or a response body chunk.
    Read,
    /// The overall wall-clock deadline was exceeded.
    Total,
}

impl std::fmt::Display for TimeoutPhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pool => write!(f, "pool"),
            Self::Connect => write!(f, "connect"),
            Self::ProxyConnect => write!(f, "proxy connect"),
            Self::ProxyTls => write!(f, "proxy TLS"),
            Self::Read => write!(f, "read"),
            Self::Write => write!(f, "write"),
            Self::Total => write!(f, "total"),
        }
    }
}

/// Phase-aware timeout configuration for a request.
///
/// Each field is optional. When `None`, the corresponding phase has no
/// timeout. When a field is `Some(duration)`, the phase will fail with
/// [`crate::Error::Timeout`] if it exceeds the given duration.
///
/// # Enforcement
///
/// - `pool`: enforced via `tokio::time::timeout` around the pool acquire.
/// - `read`: on Hyper/UDS routes, response-header waiting is bounded after
///   request-body completion; response-body progress is enforced per chunk by
///   a wrapper stream and resets on each arrival. Experimental HTTP/3 currently
///   applies this field to response-body chunks only.
/// - `write`: enforced per chunk by a wrapper stream that fires
///   `Error::Timeout { phase: Write }` when the request body producer
///   does not yield a chunk within the configured duration. Resets on
///   every chunk delivery. Only applies to streamed request bodies;
///   buffered bodies complete synchronously.
/// - `total`: absolute wall-clock deadline from logical request start
///   through response-body EOF/trailers. Enforced around the transport
///   future and retained on the response body; never restarted per chunk,
///   decode selection, redirect hop, retry attempt, or first body poll.
/// - `connect`: enforced by wrapping the underlying connector with a
///   timeout that bounds DNS resolution, TCP connect, and TLS handshake.
///   Fires `Error::Timeout { phase: Connect }` if the connection is not
///   established within the configured duration.
///
/// # Default
///
/// The default `Timeout` has all phases disabled (all `None`).
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use eggfetch_core::Timeout;
///
/// // All phases get 5 seconds.
/// let t = Timeout::from_secs(5);
///
/// // Only read and total are configured.
/// let t = Timeout {
///     read: Some(Duration::from_secs(30)),
///     total: Some(Duration::from_secs(60)),
///     ..Timeout::default()
/// };
/// ```
#[derive(Debug, Default, Clone, Copy)]
pub struct Timeout {
    /// Time allowed to wait for a connection slot from the pool.
    pub pool: Option<Duration>,
    /// Time allowed to establish TCP connection and TLS handshake.
    /// Includes DNS resolution when performed as part of connect.
    /// Enforced by wrapping the underlying connector with a deadline.
    pub connect: Option<Duration>,
    /// Time allowed for the request body producer to yield each frame.
    /// Applies to high-level streamed request bodies and the native
    /// `http_body::Body` execution surface.
    pub write: Option<Duration>,
    /// Time allowed for response headers after request-body completion and
    /// between response-body chunks. The body timer starts on first body poll
    /// and resets on every chunk. Experimental HTTP/3 currently applies this
    /// field to response-body progress only.
    pub read: Option<Duration>,
    /// Optional wall-clock cap across the entire request lifecycle.
    pub total: Option<Duration>,
}

impl Timeout {
    /// Create a timeout with all phases disabled.
    ///
    /// This is the same as `Timeout::default()`.
    #[must_use]
    pub fn disabled() -> Self {
        Self::default()
    }

    /// Create a timeout where pool, connect, write, and read each get the
    /// given duration.
    ///
    /// The total timeout is not set. Use [`Timeout::builder`] or the
    /// struct literal syntax to set it explicitly.
    ///
    /// # Examples
    ///
    /// ```
    /// use eggfetch_core::Timeout;
    ///
    /// let t = Timeout::from_secs(5);
    /// assert_eq!(t.pool, Some(std::time::Duration::from_secs(5)));
    /// assert_eq!(t.connect, Some(std::time::Duration::from_secs(5)));
    /// assert_eq!(t.write, Some(std::time::Duration::from_secs(5)));
    /// assert_eq!(t.read, Some(std::time::Duration::from_secs(5)));
    /// assert!(t.total.is_none());
    /// ```
    #[must_use]
    pub fn from_secs(secs: u64) -> Self {
        let d = Duration::from_secs(secs);
        Self {
            pool: Some(d),
            connect: Some(d),
            write: Some(d),
            read: Some(d),
            total: None,
        }
    }

    /// Create an HTTPX-compatible timeout configuration.
    ///
    /// HTTPX 0.28.1 uses 5 seconds for each operational phase. It does not
    /// define a request-wide wall-clock timeout, so `total` remains unset.
    /// Set `total` explicitly when an EggFetch-native outer deadline is
    /// desired.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use eggfetch_core::Timeout;
    ///
    /// let t = Timeout::compat();
    /// assert_eq!(t.pool, Some(Duration::from_secs(5)));
    /// assert_eq!(t.connect, Some(Duration::from_secs(5)));
    /// assert_eq!(t.write, Some(Duration::from_secs(5)));
    /// assert_eq!(t.read, Some(Duration::from_secs(5)));
    /// assert!(t.total.is_none());
    /// ```
    #[must_use]
    pub fn compat() -> Self {
        let d = Duration::from_secs(5);
        Self {
            pool: Some(d),
            connect: Some(d),
            write: Some(d),
            read: Some(d),
            total: None,
        }
    }

    /// Create eggfetch-native timeout defaults.
    ///
    /// Uses 30 seconds for pool, connect, write, and read phases with
    /// no total timeout. This is appropriate for general-purpose use
    /// where the caller controls overall deadlines.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use eggfetch_core::Timeout;
    ///
    /// let t = Timeout::native();
    /// assert_eq!(t.pool, Some(Duration::from_secs(30)));
    /// assert_eq!(t.connect, Some(Duration::from_secs(30)));
    /// assert_eq!(t.write, Some(Duration::from_secs(30)));
    /// assert_eq!(t.read, Some(Duration::from_secs(30)));
    /// assert!(t.total.is_none());
    /// ```
    #[must_use]
    pub fn native() -> Self {
        let d = Duration::from_secs(30);
        Self {
            pool: Some(d),
            connect: Some(d),
            write: Some(d),
            read: Some(d),
            total: None,
        }
    }

    /// Create a [`TimeoutBuilder`] for configuring individual phases.
    #[must_use]
    pub fn builder() -> TimeoutBuilder {
        TimeoutBuilder {
            pool: None,
            connect: None,
            write: None,
            read: None,
            total: None,
        }
    }

    /// Merge request-level overrides into client-level defaults.
    ///
    /// For each phase, if the request-level value is `Some`, it replaces
    /// the client-level value. If `None`, the client-level value is kept.
    ///
    /// Note: there is intentionally no way to *clear* a client-level timeout
    /// for a single request (`None` means "inherit"). Callers needing no
    /// timeout for one phase must set an explicit large value or use a
    /// client without that phase configured.
    #[must_use]
    pub(crate) fn merge(self, override_timeout: Option<Self>) -> Self {
        match override_timeout {
            Some(req) => Self {
                pool: req.pool.or(self.pool),
                connect: req.connect.or(self.connect),
                write: req.write.or(self.write),
                read: req.read.or(self.read),
                total: req.total.or(self.total),
            },
            None => self,
        }
    }

    /// Returns `true` if any phase has a timeout set.
    #[must_use]
    pub fn has_any(&self) -> bool {
        self.pool.is_some()
            || self.connect.is_some()
            || self.write.is_some()
            || self.read.is_some()
            || self.total.is_some()
    }
}

/// Crate-private absolute response-body deadline for the native `total`
/// timeout.
///
/// The instant is computed once during request preparation
/// (`started + total`) and never changes afterwards: it does not start on
/// first body poll, reset on chunk/frame arrival, restart on decode
/// selection, or restart across redirect/retry hops. The owning stream
/// retains only this `std::time::Instant` plus the hop total used for
/// `Error::Timeout` elapsed reporting; Tokio timers are created lazily on
/// first body poll in the consuming runtime so a response handed to another
/// runtime (e.g. the synchronous Python adapter) never carries a
/// runtime-bound sleep across the boundary.
///
/// Dropping a response before EOF remains ordinary cancellation and never
/// manufactures a timeout; the deadline only surfaces as
/// `TimeoutPhase::Total` when the body is polled at or after expiry.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ResponseDeadline {
    deadline: std::time::Instant,
    total: Duration,
}

impl ResponseDeadline {
    /// Capture the absolute deadline with the hop total used for elapsed
    /// reporting.
    #[must_use]
    pub(crate) fn new(deadline: std::time::Instant, total: Duration) -> Self {
        Self { deadline, total }
    }

    /// The absolute instant the logical request expires.
    #[must_use]
    pub(crate) fn deadline(&self) -> std::time::Instant {
        self.deadline
    }

    /// Returns `true` when the wall-clock deadline has passed.
    #[must_use]
    pub(crate) fn is_expired(&self) -> bool {
        std::time::Instant::now() >= self.deadline
    }

    /// Elapsed time for `Error::Timeout` reporting: time since the hop
    /// started (`deadline - total`), matching the transport-stage total
    /// convention of reporting hop-local elapsed rather than a bare
    /// zero-duration expiry.
    #[must_use]
    pub(crate) fn elapsed(&self) -> Duration {
        let started = self
            .deadline
            .checked_sub(self.total)
            .unwrap_or(self.deadline);
        // `started` may be in the future when the deadline was saturated
        // (e.g. `Duration::MAX` total); never panic on `duration_since`.
        // Recompute as now - started saturating: Instant::elapsed() panics
        // when `started` is in the future, so use the saturating form.
        std::time::Instant::now().saturating_duration_since(started)
    }
}

/// Saturating `Instant + Duration`: on overflow (e.g. `Duration::MAX` as a
/// total timeout) fall back to ~10 years out instead of panicking.
#[must_use]
pub(crate) fn saturating_add_instant(
    base: std::time::Instant,
    duration: Duration,
) -> std::time::Instant {
    base.checked_add(duration).unwrap_or_else(|| {
        base.checked_add(Duration::from_secs(86400 * 365 * 10))
            .unwrap_or(base)
    })
}

/// Saturating `tokio::time::Instant::now() + duration`: on overflow (e.g.
/// absurd per-chunk budgets) fall back to ~10 years out instead of
/// panicking. The ultimate fallback is `now` (immediate expiry,
/// fail-closed), which cannot overflow.
#[must_use]
pub(crate) fn saturating_tokio_now_plus(duration: Duration) -> tokio::time::Instant {
    let now = tokio::time::Instant::now();
    now.checked_add(duration).unwrap_or_else(|| {
        now.checked_add(Duration::from_secs(86400 * 365 * 10))
            .unwrap_or(now)
    })
}
/// Builder for constructing a [`Timeout`] with individual phase durations.
///
/// Created by [`Timeout::builder()`].
#[derive(Debug, Clone)]
pub struct TimeoutBuilder {
    pool: Option<Duration>,
    connect: Option<Duration>,
    write: Option<Duration>,
    read: Option<Duration>,
    total: Option<Duration>,
}

impl TimeoutBuilder {
    /// Set the pool acquisition timeout.
    #[must_use]
    pub fn pool(mut self, timeout: Duration) -> Self {
        self.pool = Some(timeout);
        self
    }

    /// Set the connect timeout.
    #[must_use]
    pub fn connect(mut self, timeout: Duration) -> Self {
        self.connect = Some(timeout);
        self
    }

    /// Set the write timeout.
    #[must_use]
    pub fn write(mut self, timeout: Duration) -> Self {
        self.write = Some(timeout);
        self
    }

    /// Set the read timeout.
    #[must_use]
    pub fn read(mut self, timeout: Duration) -> Self {
        self.read = Some(timeout);
        self
    }

    /// Set the total request timeout.
    #[must_use]
    pub fn total(mut self, timeout: Duration) -> Self {
        self.total = Some(timeout);
        self
    }

    /// Build the [`Timeout`].
    #[must_use]
    pub fn build(self) -> Timeout {
        Timeout {
            pool: self.pool,
            connect: self.connect,
            write: self.write,
            read: self.read,
            total: self.total,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[test]
    fn timeout_default_all_none() {
        let t = Timeout::default();
        assert!(t.pool.is_none());
        assert!(t.connect.is_none());
        assert!(t.write.is_none());
        assert!(t.read.is_none());
        assert!(t.total.is_none());
    }

    #[test]
    fn saturating_add_instant_absorbs_duration_max() {
        // `started + Duration::MAX` panics on overflow; the saturating
        // helper must return a usable future deadline instead.
        let started = std::time::Instant::now();
        let deadline = saturating_add_instant(started, Duration::MAX);
        assert!(deadline >= started);
    }

    #[test]
    fn response_deadline_elapsed_never_panics_on_saturated_deadline() {
        // A saturated far-future deadline (e.g. from `Duration::MAX`)
        // must report zero elapsed rather than panicking in
        // `duration_since`.
        let saturated = saturating_add_instant(std::time::Instant::now(), Duration::MAX);
        let deadline = ResponseDeadline::new(saturated, Duration::MAX);
        assert_eq!(deadline.elapsed(), Duration::ZERO);
    }

    #[test]
    fn timeout_disabled_same_as_default() {
        let t = Timeout::disabled();
        assert!(!t.has_any());
    }

    #[test]
    fn timeout_from_secs_sets_phases() {
        let t = Timeout::from_secs(10);
        assert_eq!(t.pool, Some(Duration::from_secs(10)));
        assert_eq!(t.connect, Some(Duration::from_secs(10)));
        assert_eq!(t.write, Some(Duration::from_secs(10)));
        assert_eq!(t.read, Some(Duration::from_secs(10)));
        assert!(t.total.is_none());
    }

    #[test]
    fn timeout_builder_sets_all() {
        let t = Timeout::builder()
            .pool(Duration::from_secs(1))
            .connect(Duration::from_secs(2))
            .write(Duration::from_secs(3))
            .read(Duration::from_secs(4))
            .total(Duration::from_secs(5))
            .build();
        assert_eq!(t.pool, Some(Duration::from_secs(1)));
        assert_eq!(t.connect, Some(Duration::from_secs(2)));
        assert_eq!(t.write, Some(Duration::from_secs(3)));
        assert_eq!(t.read, Some(Duration::from_secs(4)));
        assert_eq!(t.total, Some(Duration::from_secs(5)));
    }

    #[test]
    fn timeout_merge_request_overrides_client() {
        let client = Timeout::from_secs(10);
        let request = Timeout {
            read: Some(Duration::from_secs(30)),
            ..Timeout::default()
        };
        let merged = client.merge(Some(request));
        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
        assert_eq!(merged.connect, Some(Duration::from_secs(10)));
        assert_eq!(merged.write, Some(Duration::from_secs(10)));
        assert_eq!(merged.read, Some(Duration::from_secs(30)));
        assert!(merged.total.is_none());
    }

    #[test]
    fn timeout_merge_no_override() {
        let client = Timeout::from_secs(5);
        let merged = client.merge(None);
        assert_eq!(merged.pool, Some(Duration::from_secs(5)));
        assert_eq!(merged.connect, Some(Duration::from_secs(5)));
    }

    #[test]
    fn timeout_compat_sets_operational_phases_without_total() {
        let t = Timeout::compat();
        let d = Duration::from_secs(5);
        assert_eq!(t.pool, Some(d));
        assert_eq!(t.connect, Some(d));
        assert_eq!(t.write, Some(d));
        assert_eq!(t.read, Some(d));
        assert!(t.total.is_none());
    }

    #[test]
    fn timeout_native_sets_phases_without_total() {
        let t = Timeout::native();
        let d = Duration::from_secs(30);
        assert_eq!(t.pool, Some(d));
        assert_eq!(t.connect, Some(d));
        assert_eq!(t.write, Some(d));
        assert_eq!(t.read, Some(d));
        assert!(t.total.is_none());
    }

    #[test]
    fn timeout_has_any() {
        assert!(!Timeout::default().has_any());
        assert!(Timeout::from_secs(1).has_any());
        assert!(Timeout {
            total: Some(Duration::from_secs(1)),
            ..Timeout::default()
        }
        .has_any());
    }

    #[test]
    fn timeout_phase_display() {
        assert_eq!(TimeoutPhase::Pool.to_string(), "pool");
        assert_eq!(TimeoutPhase::Connect.to_string(), "connect");
        assert_eq!(TimeoutPhase::ProxyConnect.to_string(), "proxy connect");
        assert_eq!(TimeoutPhase::ProxyTls.to_string(), "proxy TLS");
        assert_eq!(TimeoutPhase::Write.to_string(), "write");
        assert_eq!(TimeoutPhase::Read.to_string(), "read");
        assert_eq!(TimeoutPhase::Total.to_string(), "total");
    }

    #[test]
    fn timeout_merge_empty_override_preserves_client() {
        let client = Timeout {
            pool: Some(Duration::from_secs(1)),
            connect: Some(Duration::from_secs(2)),
            write: Some(Duration::from_secs(3)),
            read: Some(Duration::from_secs(4)),
            total: Some(Duration::from_secs(5)),
        };
        let merged = client.merge(Some(Timeout::default()));
        assert_eq!(merged.pool, Some(Duration::from_secs(1)));
        assert_eq!(merged.connect, Some(Duration::from_secs(2)));
        assert_eq!(merged.write, Some(Duration::from_secs(3)));
        assert_eq!(merged.read, Some(Duration::from_secs(4)));
        assert_eq!(merged.total, Some(Duration::from_secs(5)));
    }

    #[test]
    fn timeout_builder_matches_from_secs_for_phases() {
        let scalar = Timeout::from_secs(5);
        let builder = Timeout::builder()
            .pool(Duration::from_secs(5))
            .connect(Duration::from_secs(5))
            .write(Duration::from_secs(5))
            .read(Duration::from_secs(5))
            .build();
        assert_eq!(scalar.pool, builder.pool);
        assert_eq!(scalar.connect, builder.connect);
        assert_eq!(scalar.write, builder.write);
        assert_eq!(scalar.read, builder.read);
        assert_eq!(scalar.total, builder.total);
    }

    #[test]
    fn timeout_merge_request_overrides_total() {
        let client = Timeout::from_secs(10);
        let request = Timeout {
            total: Some(Duration::from_secs(60)),
            ..Timeout::default()
        };
        let merged = client.merge(Some(request));
        assert_eq!(merged.total, Some(Duration::from_secs(60)));
        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
    }

    #[test]
    fn zero_duration_timeout_is_valid() {
        // Zero is a valid Duration in Rust (unsigned). It produces an immediate
        // timeout when used with tokio::time::timeout. This is documented
        // behavior, not an error.
        let t = Timeout::from_secs(0);
        assert_eq!(t.pool, Some(Duration::ZERO));
        assert_eq!(t.connect, Some(Duration::ZERO));
        assert_eq!(t.write, Some(Duration::ZERO));
        assert_eq!(t.read, Some(Duration::ZERO));
        assert_eq!(t.total, None);
    }

    proptest::proptest! {
        #[test]
        fn from_secs_sets_correct_phases(secs in 0u64..86400) {
            let t = Timeout::from_secs(secs);
            let d = Duration::from_secs(secs);
            prop_assert_eq!(t.pool, Some(d));
            prop_assert_eq!(t.connect, Some(d));
            prop_assert_eq!(t.write, Some(d));
            prop_assert_eq!(t.read, Some(d));
            prop_assert!(t.total.is_none());
        }

        #[test]
        fn disabled_has_no_phases(_ in 0u64..100) {
            let t = Timeout::disabled();
            prop_assert!(!t.has_any());
            prop_assert!(t.pool.is_none());
            prop_assert!(t.connect.is_none());
            prop_assert!(t.write.is_none());
            prop_assert!(t.read.is_none());
            prop_assert!(t.total.is_none());
        }

        #[test]
        fn has_any_consistent_with_fields(
            pool in proptest::option::of(0u64..3600),
            connect in proptest::option::of(0u64..3600),
            write in proptest::option::of(0u64..3600),
            read in proptest::option::of(0u64..3600),
            total in proptest::option::of(0u64..3600),
        ) {
            let t = Timeout {
                pool: pool.map(Duration::from_secs),
                connect: connect.map(Duration::from_secs),
                write: write.map(Duration::from_secs),
                read: read.map(Duration::from_secs),
                total: total.map(Duration::from_secs),
            };
            let expected = t.pool.is_some() || t.connect.is_some() || t.write.is_some() || t.read.is_some() || t.total.is_some();
            prop_assert_eq!(t.has_any(), expected);
        }

        #[test]
        fn builder_round_trip(
            pool in 0u64..3600,
            connect in 0u64..3600,
            write in 0u64..3600,
            read in 0u64..3600,
            total in 0u64..3600,
        ) {
            let t = Timeout::builder()
                .pool(Duration::from_secs(pool))
                .connect(Duration::from_secs(connect))
                .write(Duration::from_secs(write))
                .read(Duration::from_secs(read))
                .total(Duration::from_secs(total))
                .build();
            prop_assert_eq!(t.pool, Some(Duration::from_secs(pool)));
            prop_assert_eq!(t.connect, Some(Duration::from_secs(connect)));
            prop_assert_eq!(t.write, Some(Duration::from_secs(write)));
            prop_assert_eq!(t.read, Some(Duration::from_secs(read)));
            prop_assert_eq!(t.total, Some(Duration::from_secs(total)));
        }
    }
}