Skip to main content

eggfetch_core/
timeout.rs

1//! Phase-aware timeout configuration.
2//!
3//! Timeouts are applied per-phase during the request lifecycle. Each phase
4//! measures a specific segment of the request:
5//!
6//! - **Pool**: time waiting for a connection slot from the pool.
7//! - **Connect**: time to establish the TCP connection and TLS handshake
8//!   (including DNS resolution).
9//! - **`ProxyConnect`**: TCP connection to the proxy server. Only applies
10//!   when a proxy is configured.
11//! - **`ProxyTls`**: TLS handshake over a CONNECT tunnel to the proxy.
12//!   Only applies to HTTPS targets routed through an HTTP proxy.
13//! - **Write**: time for the request body producer to yield each chunk.
14//!   Only applies to streamed request bodies; buffered bodies complete
15//!   synchronously.
16//! - **Read**: after the request body producer completes, time to wait for
17//!   response headers, then each response body chunk. The deadline resets on
18//!   each chunk. Early responses do not charge upload time to the read budget.
19//! - **Total**: absolute wall-clock deadline across the entire request
20//!   lifecycle, from logical request start through response-body EOF (or
21//!   terminal body error), including pool acquisition, transport setup,
22//!   response headers, body chunks, decompression, and trailers. It never
23//!   resets on chunk arrival, decoding selection, or first body poll. A body
24//!   that is first polled after the deadline reports `Total` without
25//!   accepting a ready inner chunk.
26//!
27//! # Proxy timeout phases
28//!
29//! When a request is routed through a proxy, the connect phase splits
30//! into two sub-phases:
31//!
32//! 1. `ProxyConnect` — the TCP connection from the client to the proxy.
33//! 2. `ProxyTls` — the TLS handshake over the CONNECT tunnel (HTTPS
34//!    targets only).
35//!
36//! After the tunnel is established, regular `Connect`, `Send`, and
37//! `Receive` semantics apply to the destination.
38//!
39//! # Enforcement
40//!
41//! - **Pool** and **Total** are enforced with `tokio::time::timeout`.
42//! - **Read** is enforced while waiting for response headers after request
43//!   body completion on Hyper and UDS routes, then by a per-chunk wrapper
44//!   stream. The body deadline starts on first body poll and resets on every
45//!   chunk. Experimental HTTP/3 currently applies this field to response-body
46//!   progress only; its header wait remains total-bounded.
47//! - **Total** is enforced in two stages: `tokio::time::timeout` bounds the
48//!   transport future up to response headers, and a crate-private absolute
49//!   response-body deadline (`ResponseDeadline`) bounds body streaming
50//!   through EOF/trailers. The absolute instant never resets; an
51//!   already-expired deadline wins before polling the inner body, and when
52//!   both read and total are observably expired at the same poll boundary
53//!   `Total` is preferred as the outer lifecycle cap.
54//! - **Write** is enforced by a per-chunk wrapper stream that fires
55//!   `Error::Timeout { phase: Write }` if the producer does not yield
56//!   the next chunk within the configured duration. The deadline resets
57//!   on every chunk.
58//! - **Connect** is enforced by wrapping the underlying connector with a
59//!   timeout that bounds the entire connection-establishment phase (DNS
60//!   resolution, TCP connect, and TLS handshake). Fires
61//!   `Error::Timeout { phase: Connect }` if the connection is not
62//!   established within the configured duration.
63//!
64//! When a scalar timeout is provided (e.g. `Timeout::from_secs(5)`), it
65//! applies to pool, connect, write, and read phases. The total timeout is
66//! not set by scalar constructors unless explicitly specified.
67//!
68//! Request-level timeout overrides client-level timeout on a per-field
69//! basis: only the fields present in the request-level timeout replace
70//! the corresponding client-level fields.
71
72use std::time::Duration;
73
74/// Identifies the phase of a request that timed out.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum TimeoutPhase {
77    /// Waiting for a connection slot from the pool.
78    Pool,
79    /// Establishing TCP connection and TLS handshake.
80    Connect,
81    /// TCP connection to the proxy server.
82    ProxyConnect,
83    /// TLS handshake over a CONNECT tunnel to the proxy.
84    ProxyTls,
85    /// Sending request headers and body.
86    Write,
87    /// Waiting for response headers or a response body chunk.
88    Read,
89    /// The overall wall-clock deadline was exceeded.
90    Total,
91}
92
93impl std::fmt::Display for TimeoutPhase {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        match self {
96            Self::Pool => write!(f, "pool"),
97            Self::Connect => write!(f, "connect"),
98            Self::ProxyConnect => write!(f, "proxy connect"),
99            Self::ProxyTls => write!(f, "proxy TLS"),
100            Self::Read => write!(f, "read"),
101            Self::Write => write!(f, "write"),
102            Self::Total => write!(f, "total"),
103        }
104    }
105}
106
107/// Phase-aware timeout configuration for a request.
108///
109/// Each field is optional. When `None`, the corresponding phase has no
110/// timeout. When a field is `Some(duration)`, the phase will fail with
111/// [`crate::Error::Timeout`] if it exceeds the given duration.
112///
113/// # Enforcement
114///
115/// - `pool`: enforced via `tokio::time::timeout` around the pool acquire.
116/// - `read`: on Hyper/UDS routes, response-header waiting is bounded after
117///   request-body completion; response-body progress is enforced per chunk by
118///   a wrapper stream and resets on each arrival. Experimental HTTP/3 currently
119///   applies this field to response-body chunks only.
120/// - `write`: enforced per chunk by a wrapper stream that fires
121///   `Error::Timeout { phase: Write }` when the request body producer
122///   does not yield a chunk within the configured duration. Resets on
123///   every chunk delivery. Only applies to streamed request bodies;
124///   buffered bodies complete synchronously.
125/// - `total`: absolute wall-clock deadline from logical request start
126///   through response-body EOF/trailers. Enforced around the transport
127///   future and retained on the response body; never restarted per chunk,
128///   decode selection, redirect hop, retry attempt, or first body poll.
129/// - `connect`: enforced by wrapping the underlying connector with a
130///   timeout that bounds DNS resolution, TCP connect, and TLS handshake.
131///   Fires `Error::Timeout { phase: Connect }` if the connection is not
132///   established within the configured duration.
133///
134/// # Default
135///
136/// The default `Timeout` has all phases disabled (all `None`).
137///
138/// # Examples
139///
140/// ```
141/// use std::time::Duration;
142/// use eggfetch_core::Timeout;
143///
144/// // All phases get 5 seconds.
145/// let t = Timeout::from_secs(5);
146///
147/// // Only read and total are configured.
148/// let t = Timeout {
149///     read: Some(Duration::from_secs(30)),
150///     total: Some(Duration::from_secs(60)),
151///     ..Timeout::default()
152/// };
153/// ```
154#[derive(Debug, Default, Clone, Copy)]
155pub struct Timeout {
156    /// Time allowed to wait for a connection slot from the pool.
157    pub pool: Option<Duration>,
158    /// Time allowed to establish TCP connection and TLS handshake.
159    /// Includes DNS resolution when performed as part of connect.
160    /// Enforced by wrapping the underlying connector with a deadline.
161    pub connect: Option<Duration>,
162    /// Time allowed for the request body producer to yield each frame.
163    /// Applies to high-level streamed request bodies and the native
164    /// `http_body::Body` execution surface.
165    pub write: Option<Duration>,
166    /// Time allowed for response headers after request-body completion and
167    /// between response-body chunks. The body timer starts on first body poll
168    /// and resets on every chunk. Experimental HTTP/3 currently applies this
169    /// field to response-body progress only.
170    pub read: Option<Duration>,
171    /// Optional wall-clock cap across the entire request lifecycle.
172    pub total: Option<Duration>,
173}
174
175impl Timeout {
176    /// Create a timeout with all phases disabled.
177    ///
178    /// This is the same as `Timeout::default()`.
179    #[must_use]
180    pub fn disabled() -> Self {
181        Self::default()
182    }
183
184    /// Create a timeout where pool, connect, write, and read each get the
185    /// given duration.
186    ///
187    /// The total timeout is not set. Use [`Timeout::builder`] or the
188    /// struct literal syntax to set it explicitly.
189    ///
190    /// # Examples
191    ///
192    /// ```
193    /// use eggfetch_core::Timeout;
194    ///
195    /// let t = Timeout::from_secs(5);
196    /// assert_eq!(t.pool, Some(std::time::Duration::from_secs(5)));
197    /// assert_eq!(t.connect, Some(std::time::Duration::from_secs(5)));
198    /// assert_eq!(t.write, Some(std::time::Duration::from_secs(5)));
199    /// assert_eq!(t.read, Some(std::time::Duration::from_secs(5)));
200    /// assert!(t.total.is_none());
201    /// ```
202    #[must_use]
203    pub fn from_secs(secs: u64) -> Self {
204        let d = Duration::from_secs(secs);
205        Self {
206            pool: Some(d),
207            connect: Some(d),
208            write: Some(d),
209            read: Some(d),
210            total: None,
211        }
212    }
213
214    /// Create an HTTPX-compatible timeout configuration.
215    ///
216    /// HTTPX 0.28.1 uses 5 seconds for each operational phase. It does not
217    /// define a request-wide wall-clock timeout, so `total` remains unset.
218    /// Set `total` explicitly when an EggFetch-native outer deadline is
219    /// desired.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use std::time::Duration;
225    /// use eggfetch_core::Timeout;
226    ///
227    /// let t = Timeout::compat();
228    /// assert_eq!(t.pool, Some(Duration::from_secs(5)));
229    /// assert_eq!(t.connect, Some(Duration::from_secs(5)));
230    /// assert_eq!(t.write, Some(Duration::from_secs(5)));
231    /// assert_eq!(t.read, Some(Duration::from_secs(5)));
232    /// assert!(t.total.is_none());
233    /// ```
234    #[must_use]
235    pub fn compat() -> Self {
236        let d = Duration::from_secs(5);
237        Self {
238            pool: Some(d),
239            connect: Some(d),
240            write: Some(d),
241            read: Some(d),
242            total: None,
243        }
244    }
245
246    /// Create eggfetch-native timeout defaults.
247    ///
248    /// Uses 30 seconds for pool, connect, write, and read phases with
249    /// no total timeout. This is appropriate for general-purpose use
250    /// where the caller controls overall deadlines.
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// use std::time::Duration;
256    /// use eggfetch_core::Timeout;
257    ///
258    /// let t = Timeout::native();
259    /// assert_eq!(t.pool, Some(Duration::from_secs(30)));
260    /// assert_eq!(t.connect, Some(Duration::from_secs(30)));
261    /// assert_eq!(t.write, Some(Duration::from_secs(30)));
262    /// assert_eq!(t.read, Some(Duration::from_secs(30)));
263    /// assert!(t.total.is_none());
264    /// ```
265    #[must_use]
266    pub fn native() -> Self {
267        let d = Duration::from_secs(30);
268        Self {
269            pool: Some(d),
270            connect: Some(d),
271            write: Some(d),
272            read: Some(d),
273            total: None,
274        }
275    }
276
277    /// Create a [`TimeoutBuilder`] for configuring individual phases.
278    #[must_use]
279    pub fn builder() -> TimeoutBuilder {
280        TimeoutBuilder {
281            pool: None,
282            connect: None,
283            write: None,
284            read: None,
285            total: None,
286        }
287    }
288
289    /// Merge request-level overrides into client-level defaults.
290    ///
291    /// For each phase, if the request-level value is `Some`, it replaces
292    /// the client-level value. If `None`, the client-level value is kept.
293    ///
294    /// Note: there is intentionally no way to *clear* a client-level timeout
295    /// for a single request (`None` means "inherit"). Callers needing no
296    /// timeout for one phase must set an explicit large value or use a
297    /// client without that phase configured.
298    #[must_use]
299    pub(crate) fn merge(self, override_timeout: Option<Self>) -> Self {
300        match override_timeout {
301            Some(req) => Self {
302                pool: req.pool.or(self.pool),
303                connect: req.connect.or(self.connect),
304                write: req.write.or(self.write),
305                read: req.read.or(self.read),
306                total: req.total.or(self.total),
307            },
308            None => self,
309        }
310    }
311
312    /// Returns `true` if any phase has a timeout set.
313    #[must_use]
314    pub fn has_any(&self) -> bool {
315        self.pool.is_some()
316            || self.connect.is_some()
317            || self.write.is_some()
318            || self.read.is_some()
319            || self.total.is_some()
320    }
321}
322
323/// Crate-private absolute response-body deadline for the native `total`
324/// timeout.
325///
326/// The instant is computed once during request preparation
327/// (`started + total`) and never changes afterwards: it does not start on
328/// first body poll, reset on chunk/frame arrival, restart on decode
329/// selection, or restart across redirect/retry hops. The owning stream
330/// retains only this `std::time::Instant` plus the hop total used for
331/// `Error::Timeout` elapsed reporting; Tokio timers are created lazily on
332/// first body poll in the consuming runtime so a response handed to another
333/// runtime (e.g. the synchronous Python adapter) never carries a
334/// runtime-bound sleep across the boundary.
335///
336/// Dropping a response before EOF remains ordinary cancellation and never
337/// manufactures a timeout; the deadline only surfaces as
338/// `TimeoutPhase::Total` when the body is polled at or after expiry.
339#[derive(Debug, Clone, Copy)]
340pub(crate) struct ResponseDeadline {
341    deadline: std::time::Instant,
342    total: Duration,
343}
344
345impl ResponseDeadline {
346    /// Capture the absolute deadline with the hop total used for elapsed
347    /// reporting.
348    #[must_use]
349    pub(crate) fn new(deadline: std::time::Instant, total: Duration) -> Self {
350        Self { deadline, total }
351    }
352
353    /// The absolute instant the logical request expires.
354    #[must_use]
355    pub(crate) fn deadline(&self) -> std::time::Instant {
356        self.deadline
357    }
358
359    /// Returns `true` when the wall-clock deadline has passed.
360    #[must_use]
361    pub(crate) fn is_expired(&self) -> bool {
362        std::time::Instant::now() >= self.deadline
363    }
364
365    /// Elapsed time for `Error::Timeout` reporting: time since the hop
366    /// started (`deadline - total`), matching the transport-stage total
367    /// convention of reporting hop-local elapsed rather than a bare
368    /// zero-duration expiry.
369    #[must_use]
370    pub(crate) fn elapsed(&self) -> Duration {
371        let started = self
372            .deadline
373            .checked_sub(self.total)
374            .unwrap_or(self.deadline);
375        // `started` may be in the future when the deadline was saturated
376        // (e.g. `Duration::MAX` total); never panic on `duration_since`.
377        // Recompute as now - started saturating: Instant::elapsed() panics
378        // when `started` is in the future, so use the saturating form.
379        std::time::Instant::now().saturating_duration_since(started)
380    }
381}
382
383/// Saturating `Instant + Duration`: on overflow (e.g. `Duration::MAX` as a
384/// total timeout) fall back to ~10 years out instead of panicking.
385#[must_use]
386pub(crate) fn saturating_add_instant(
387    base: std::time::Instant,
388    duration: Duration,
389) -> std::time::Instant {
390    base.checked_add(duration).unwrap_or_else(|| {
391        base.checked_add(Duration::from_secs(86400 * 365 * 10))
392            .unwrap_or(base)
393    })
394}
395
396/// Saturating `tokio::time::Instant::now() + duration`: on overflow (e.g.
397/// absurd per-chunk budgets) fall back to ~10 years out instead of
398/// panicking. The ultimate fallback is `now` (immediate expiry,
399/// fail-closed), which cannot overflow.
400#[must_use]
401pub(crate) fn saturating_tokio_now_plus(duration: Duration) -> tokio::time::Instant {
402    let now = tokio::time::Instant::now();
403    now.checked_add(duration).unwrap_or_else(|| {
404        now.checked_add(Duration::from_secs(86400 * 365 * 10))
405            .unwrap_or(now)
406    })
407}
408/// Builder for constructing a [`Timeout`] with individual phase durations.
409///
410/// Created by [`Timeout::builder()`].
411#[derive(Debug, Clone)]
412pub struct TimeoutBuilder {
413    pool: Option<Duration>,
414    connect: Option<Duration>,
415    write: Option<Duration>,
416    read: Option<Duration>,
417    total: Option<Duration>,
418}
419
420impl TimeoutBuilder {
421    /// Set the pool acquisition timeout.
422    #[must_use]
423    pub fn pool(mut self, timeout: Duration) -> Self {
424        self.pool = Some(timeout);
425        self
426    }
427
428    /// Set the connect timeout.
429    #[must_use]
430    pub fn connect(mut self, timeout: Duration) -> Self {
431        self.connect = Some(timeout);
432        self
433    }
434
435    /// Set the write timeout.
436    #[must_use]
437    pub fn write(mut self, timeout: Duration) -> Self {
438        self.write = Some(timeout);
439        self
440    }
441
442    /// Set the read timeout.
443    #[must_use]
444    pub fn read(mut self, timeout: Duration) -> Self {
445        self.read = Some(timeout);
446        self
447    }
448
449    /// Set the total request timeout.
450    #[must_use]
451    pub fn total(mut self, timeout: Duration) -> Self {
452        self.total = Some(timeout);
453        self
454    }
455
456    /// Build the [`Timeout`].
457    #[must_use]
458    pub fn build(self) -> Timeout {
459        Timeout {
460            pool: self.pool,
461            connect: self.connect,
462            write: self.write,
463            read: self.read,
464            total: self.total,
465        }
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472    use proptest::prelude::*;
473
474    #[test]
475    fn timeout_default_all_none() {
476        let t = Timeout::default();
477        assert!(t.pool.is_none());
478        assert!(t.connect.is_none());
479        assert!(t.write.is_none());
480        assert!(t.read.is_none());
481        assert!(t.total.is_none());
482    }
483
484    #[test]
485    fn saturating_add_instant_absorbs_duration_max() {
486        // `started + Duration::MAX` panics on overflow; the saturating
487        // helper must return a usable future deadline instead.
488        let started = std::time::Instant::now();
489        let deadline = saturating_add_instant(started, Duration::MAX);
490        assert!(deadline >= started);
491    }
492
493    #[test]
494    fn response_deadline_elapsed_never_panics_on_saturated_deadline() {
495        // A saturated far-future deadline (e.g. from `Duration::MAX`)
496        // must report zero elapsed rather than panicking in
497        // `duration_since`.
498        let saturated = saturating_add_instant(std::time::Instant::now(), Duration::MAX);
499        let deadline = ResponseDeadline::new(saturated, Duration::MAX);
500        assert_eq!(deadline.elapsed(), Duration::ZERO);
501    }
502
503    #[test]
504    fn timeout_disabled_same_as_default() {
505        let t = Timeout::disabled();
506        assert!(!t.has_any());
507    }
508
509    #[test]
510    fn timeout_from_secs_sets_phases() {
511        let t = Timeout::from_secs(10);
512        assert_eq!(t.pool, Some(Duration::from_secs(10)));
513        assert_eq!(t.connect, Some(Duration::from_secs(10)));
514        assert_eq!(t.write, Some(Duration::from_secs(10)));
515        assert_eq!(t.read, Some(Duration::from_secs(10)));
516        assert!(t.total.is_none());
517    }
518
519    #[test]
520    fn timeout_builder_sets_all() {
521        let t = Timeout::builder()
522            .pool(Duration::from_secs(1))
523            .connect(Duration::from_secs(2))
524            .write(Duration::from_secs(3))
525            .read(Duration::from_secs(4))
526            .total(Duration::from_secs(5))
527            .build();
528        assert_eq!(t.pool, Some(Duration::from_secs(1)));
529        assert_eq!(t.connect, Some(Duration::from_secs(2)));
530        assert_eq!(t.write, Some(Duration::from_secs(3)));
531        assert_eq!(t.read, Some(Duration::from_secs(4)));
532        assert_eq!(t.total, Some(Duration::from_secs(5)));
533    }
534
535    #[test]
536    fn timeout_merge_request_overrides_client() {
537        let client = Timeout::from_secs(10);
538        let request = Timeout {
539            read: Some(Duration::from_secs(30)),
540            ..Timeout::default()
541        };
542        let merged = client.merge(Some(request));
543        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
544        assert_eq!(merged.connect, Some(Duration::from_secs(10)));
545        assert_eq!(merged.write, Some(Duration::from_secs(10)));
546        assert_eq!(merged.read, Some(Duration::from_secs(30)));
547        assert!(merged.total.is_none());
548    }
549
550    #[test]
551    fn timeout_merge_no_override() {
552        let client = Timeout::from_secs(5);
553        let merged = client.merge(None);
554        assert_eq!(merged.pool, Some(Duration::from_secs(5)));
555        assert_eq!(merged.connect, Some(Duration::from_secs(5)));
556    }
557
558    #[test]
559    fn timeout_compat_sets_operational_phases_without_total() {
560        let t = Timeout::compat();
561        let d = Duration::from_secs(5);
562        assert_eq!(t.pool, Some(d));
563        assert_eq!(t.connect, Some(d));
564        assert_eq!(t.write, Some(d));
565        assert_eq!(t.read, Some(d));
566        assert!(t.total.is_none());
567    }
568
569    #[test]
570    fn timeout_native_sets_phases_without_total() {
571        let t = Timeout::native();
572        let d = Duration::from_secs(30);
573        assert_eq!(t.pool, Some(d));
574        assert_eq!(t.connect, Some(d));
575        assert_eq!(t.write, Some(d));
576        assert_eq!(t.read, Some(d));
577        assert!(t.total.is_none());
578    }
579
580    #[test]
581    fn timeout_has_any() {
582        assert!(!Timeout::default().has_any());
583        assert!(Timeout::from_secs(1).has_any());
584        assert!(Timeout {
585            total: Some(Duration::from_secs(1)),
586            ..Timeout::default()
587        }
588        .has_any());
589    }
590
591    #[test]
592    fn timeout_phase_display() {
593        assert_eq!(TimeoutPhase::Pool.to_string(), "pool");
594        assert_eq!(TimeoutPhase::Connect.to_string(), "connect");
595        assert_eq!(TimeoutPhase::ProxyConnect.to_string(), "proxy connect");
596        assert_eq!(TimeoutPhase::ProxyTls.to_string(), "proxy TLS");
597        assert_eq!(TimeoutPhase::Write.to_string(), "write");
598        assert_eq!(TimeoutPhase::Read.to_string(), "read");
599        assert_eq!(TimeoutPhase::Total.to_string(), "total");
600    }
601
602    #[test]
603    fn timeout_merge_empty_override_preserves_client() {
604        let client = Timeout {
605            pool: Some(Duration::from_secs(1)),
606            connect: Some(Duration::from_secs(2)),
607            write: Some(Duration::from_secs(3)),
608            read: Some(Duration::from_secs(4)),
609            total: Some(Duration::from_secs(5)),
610        };
611        let merged = client.merge(Some(Timeout::default()));
612        assert_eq!(merged.pool, Some(Duration::from_secs(1)));
613        assert_eq!(merged.connect, Some(Duration::from_secs(2)));
614        assert_eq!(merged.write, Some(Duration::from_secs(3)));
615        assert_eq!(merged.read, Some(Duration::from_secs(4)));
616        assert_eq!(merged.total, Some(Duration::from_secs(5)));
617    }
618
619    #[test]
620    fn timeout_builder_matches_from_secs_for_phases() {
621        let scalar = Timeout::from_secs(5);
622        let builder = Timeout::builder()
623            .pool(Duration::from_secs(5))
624            .connect(Duration::from_secs(5))
625            .write(Duration::from_secs(5))
626            .read(Duration::from_secs(5))
627            .build();
628        assert_eq!(scalar.pool, builder.pool);
629        assert_eq!(scalar.connect, builder.connect);
630        assert_eq!(scalar.write, builder.write);
631        assert_eq!(scalar.read, builder.read);
632        assert_eq!(scalar.total, builder.total);
633    }
634
635    #[test]
636    fn timeout_merge_request_overrides_total() {
637        let client = Timeout::from_secs(10);
638        let request = Timeout {
639            total: Some(Duration::from_secs(60)),
640            ..Timeout::default()
641        };
642        let merged = client.merge(Some(request));
643        assert_eq!(merged.total, Some(Duration::from_secs(60)));
644        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
645    }
646
647    #[test]
648    fn zero_duration_timeout_is_valid() {
649        // Zero is a valid Duration in Rust (unsigned). It produces an immediate
650        // timeout when used with tokio::time::timeout. This is documented
651        // behavior, not an error.
652        let t = Timeout::from_secs(0);
653        assert_eq!(t.pool, Some(Duration::ZERO));
654        assert_eq!(t.connect, Some(Duration::ZERO));
655        assert_eq!(t.write, Some(Duration::ZERO));
656        assert_eq!(t.read, Some(Duration::ZERO));
657        assert_eq!(t.total, None);
658    }
659
660    proptest::proptest! {
661        #[test]
662        fn from_secs_sets_correct_phases(secs in 0u64..86400) {
663            let t = Timeout::from_secs(secs);
664            let d = Duration::from_secs(secs);
665            prop_assert_eq!(t.pool, Some(d));
666            prop_assert_eq!(t.connect, Some(d));
667            prop_assert_eq!(t.write, Some(d));
668            prop_assert_eq!(t.read, Some(d));
669            prop_assert!(t.total.is_none());
670        }
671
672        #[test]
673        fn disabled_has_no_phases(_ in 0u64..100) {
674            let t = Timeout::disabled();
675            prop_assert!(!t.has_any());
676            prop_assert!(t.pool.is_none());
677            prop_assert!(t.connect.is_none());
678            prop_assert!(t.write.is_none());
679            prop_assert!(t.read.is_none());
680            prop_assert!(t.total.is_none());
681        }
682
683        #[test]
684        fn has_any_consistent_with_fields(
685            pool in proptest::option::of(0u64..3600),
686            connect in proptest::option::of(0u64..3600),
687            write in proptest::option::of(0u64..3600),
688            read in proptest::option::of(0u64..3600),
689            total in proptest::option::of(0u64..3600),
690        ) {
691            let t = Timeout {
692                pool: pool.map(Duration::from_secs),
693                connect: connect.map(Duration::from_secs),
694                write: write.map(Duration::from_secs),
695                read: read.map(Duration::from_secs),
696                total: total.map(Duration::from_secs),
697            };
698            let expected = t.pool.is_some() || t.connect.is_some() || t.write.is_some() || t.read.is_some() || t.total.is_some();
699            prop_assert_eq!(t.has_any(), expected);
700        }
701
702        #[test]
703        fn builder_round_trip(
704            pool in 0u64..3600,
705            connect in 0u64..3600,
706            write in 0u64..3600,
707            read in 0u64..3600,
708            total in 0u64..3600,
709        ) {
710            let t = Timeout::builder()
711                .pool(Duration::from_secs(pool))
712                .connect(Duration::from_secs(connect))
713                .write(Duration::from_secs(write))
714                .read(Duration::from_secs(read))
715                .total(Duration::from_secs(total))
716                .build();
717            prop_assert_eq!(t.pool, Some(Duration::from_secs(pool)));
718            prop_assert_eq!(t.connect, Some(Duration::from_secs(connect)));
719            prop_assert_eq!(t.write, Some(Duration::from_secs(write)));
720            prop_assert_eq!(t.read, Some(Duration::from_secs(read)));
721            prop_assert_eq!(t.total, Some(Duration::from_secs(total)));
722        }
723    }
724}