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