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**: time to wait for response headers and each response body
17//!   chunk. The deadline resets on every chunk arrival.
18//! - **Total**: wall-clock cap across the entire request lifecycle.
19//!
20//! # Proxy timeout phases
21//!
22//! When a request is routed through a proxy, the connect phase splits
23//! into two sub-phases:
24//!
25//! 1. `ProxyConnect` — the TCP connection from the client to the proxy.
26//! 2. `ProxyTls` — the TLS handshake over the CONNECT tunnel (HTTPS
27//!    targets only).
28//!
29//! After the tunnel is established, regular `Connect`, `Send`, and
30//! `Receive` semantics apply to the destination.
31//!
32//! # Enforcement
33//!
34//! - **Pool** and **Total** are enforced with `tokio::time::timeout`.
35//! - **Read** is enforced by a per-chunk wrapper stream that fires
36//!   `Error::Timeout { phase: Read }` if no chunk arrives within the
37//!   configured duration. The deadline resets on every chunk.
38//! - **Write** is enforced by a per-chunk wrapper stream that fires
39//!   `Error::Timeout { phase: Write }` if the producer does not yield
40//!   the next chunk within the configured duration. The deadline resets
41//!   on every chunk.
42//! - **Connect** is enforced by wrapping the underlying connector with a
43//!   timeout that bounds the entire connection-establishment phase (DNS
44//!   resolution, TCP connect, and TLS handshake). Fires
45//!   `Error::Timeout { phase: Connect }` if the connection is not
46//!   established within the configured duration.
47//!
48//! When a scalar timeout is provided (e.g. `Timeout::from_secs(5)`), it
49//! applies to pool, connect, write, and read phases. The total timeout is
50//! not set by scalar constructors unless explicitly specified.
51//!
52//! Request-level timeout overrides client-level timeout on a per-field
53//! basis: only the fields present in the request-level timeout replace
54//! the corresponding client-level fields.
55
56use std::time::Duration;
57
58/// Identifies the phase of a request that timed out.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum TimeoutPhase {
61    /// Waiting for a connection slot from the pool.
62    Pool,
63    /// Establishing TCP connection and TLS handshake.
64    Connect,
65    /// TCP connection to the proxy server.
66    ProxyConnect,
67    /// TLS handshake over a CONNECT tunnel to the proxy.
68    ProxyTls,
69    /// Sending request headers and body.
70    Write,
71    /// Waiting for response headers or a response body chunk.
72    Read,
73    /// The overall wall-clock deadline was exceeded.
74    Total,
75}
76
77impl std::fmt::Display for TimeoutPhase {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Self::Pool => write!(f, "pool"),
81            Self::Connect => write!(f, "connect"),
82            Self::ProxyConnect => write!(f, "proxy connect"),
83            Self::ProxyTls => write!(f, "proxy TLS"),
84            Self::Read => write!(f, "read"),
85            Self::Write => write!(f, "write"),
86            Self::Total => write!(f, "total"),
87        }
88    }
89}
90
91/// Phase-aware timeout configuration for a request.
92///
93/// Each field is optional. When `None`, the corresponding phase has no
94/// timeout. When a field is `Some(duration)`, the phase will fail with
95/// [`crate::Error::Timeout`] if it exceeds the given duration.
96///
97/// # Enforcement
98///
99/// - `pool`: enforced via `tokio::time::timeout` around the pool acquire.
100/// - `read`: enforced per chunk by a wrapper stream that fires
101///   `Error::Timeout { phase: Read }` when no data arrives within the
102///   configured duration. Resets on every chunk arrival.
103/// - `write`: enforced per chunk by a wrapper stream that fires
104///   `Error::Timeout { phase: Write }` when the request body producer
105///   does not yield a chunk within the configured duration. Resets on
106///   every chunk delivery. Only applies to streamed request bodies;
107///   buffered bodies complete synchronously.
108/// - `total`: enforced via `tokio::time::timeout` around the full send.
109/// - `connect`: enforced by wrapping the underlying connector with a
110///   timeout that bounds DNS resolution, TCP connect, and TLS handshake.
111///   Fires `Error::Timeout { phase: Connect }` if the connection is not
112///   established within the configured duration.
113///
114/// # Default
115///
116/// The default `Timeout` has all phases disabled (all `None`).
117///
118/// # Examples
119///
120/// ```
121/// use std::time::Duration;
122/// use eggfetch_core::Timeout;
123///
124/// // All phases get 5 seconds.
125/// let t = Timeout::from_secs(5);
126///
127/// // Only read and total are configured.
128/// let t = Timeout {
129///     read: Some(Duration::from_secs(30)),
130///     total: Some(Duration::from_secs(60)),
131///     ..Timeout::default()
132/// };
133/// ```
134#[derive(Debug, Default, Clone, Copy)]
135pub struct Timeout {
136    /// Time allowed to wait for a connection slot from the pool.
137    pub pool: Option<Duration>,
138    /// Time allowed to establish TCP connection and TLS handshake.
139    /// Includes DNS resolution when performed as part of connect.
140    /// Enforced by wrapping the underlying connector with a deadline.
141    pub connect: Option<Duration>,
142    /// Time allowed for the request body producer to yield each frame.
143    /// Applies to high-level streamed request bodies and the native
144    /// `http_body::Body` execution surface.
145    pub write: Option<Duration>,
146    /// Time allowed between response body chunks. Resets on every chunk.
147    pub read: Option<Duration>,
148    /// Optional wall-clock cap across the entire request lifecycle.
149    pub total: Option<Duration>,
150}
151
152impl Timeout {
153    /// Create a timeout with all phases disabled.
154    ///
155    /// This is the same as `Timeout::default()`.
156    #[must_use]
157    pub fn disabled() -> Self {
158        Self::default()
159    }
160
161    /// Create a timeout where pool, connect, write, and read each get the
162    /// given duration.
163    ///
164    /// The total timeout is not set. Use [`Timeout::builder`] or the
165    /// struct literal syntax to set it explicitly.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use eggfetch_core::Timeout;
171    ///
172    /// let t = Timeout::from_secs(5);
173    /// assert_eq!(t.pool, Some(std::time::Duration::from_secs(5)));
174    /// assert_eq!(t.connect, Some(std::time::Duration::from_secs(5)));
175    /// assert_eq!(t.write, Some(std::time::Duration::from_secs(5)));
176    /// assert_eq!(t.read, Some(std::time::Duration::from_secs(5)));
177    /// assert!(t.total.is_none());
178    /// ```
179    #[must_use]
180    pub fn from_secs(secs: u64) -> Self {
181        let d = Duration::from_secs(secs);
182        Self {
183            pool: Some(d),
184            connect: Some(d),
185            write: Some(d),
186            read: Some(d),
187            total: None,
188        }
189    }
190
191    /// Create an HTTPX-compatible timeout configuration.
192    ///
193    /// HTTPX 0.28.1 uses 5 seconds for each operational phase. It does not
194    /// define a request-wide wall-clock timeout, so `total` remains unset.
195    /// Set `total` explicitly when an EggFetch-native outer deadline is
196    /// desired.
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use std::time::Duration;
202    /// use eggfetch_core::Timeout;
203    ///
204    /// let t = Timeout::compat();
205    /// assert_eq!(t.pool, Some(Duration::from_secs(5)));
206    /// assert_eq!(t.connect, Some(Duration::from_secs(5)));
207    /// assert_eq!(t.write, Some(Duration::from_secs(5)));
208    /// assert_eq!(t.read, Some(Duration::from_secs(5)));
209    /// assert!(t.total.is_none());
210    /// ```
211    #[must_use]
212    pub fn compat() -> Self {
213        let d = Duration::from_secs(5);
214        Self {
215            pool: Some(d),
216            connect: Some(d),
217            write: Some(d),
218            read: Some(d),
219            total: None,
220        }
221    }
222
223    /// Create eggfetch-native timeout defaults.
224    ///
225    /// Uses 30 seconds for pool, connect, write, and read phases with
226    /// no total timeout. This is appropriate for general-purpose use
227    /// where the caller controls overall deadlines.
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// use std::time::Duration;
233    /// use eggfetch_core::Timeout;
234    ///
235    /// let t = Timeout::native();
236    /// assert_eq!(t.pool, Some(Duration::from_secs(30)));
237    /// assert_eq!(t.connect, Some(Duration::from_secs(30)));
238    /// assert_eq!(t.write, Some(Duration::from_secs(30)));
239    /// assert_eq!(t.read, Some(Duration::from_secs(30)));
240    /// assert!(t.total.is_none());
241    /// ```
242    #[must_use]
243    pub fn native() -> Self {
244        let d = Duration::from_secs(30);
245        Self {
246            pool: Some(d),
247            connect: Some(d),
248            write: Some(d),
249            read: Some(d),
250            total: None,
251        }
252    }
253
254    /// Create a [`TimeoutBuilder`] for configuring individual phases.
255    #[must_use]
256    pub fn builder() -> TimeoutBuilder {
257        TimeoutBuilder {
258            pool: None,
259            connect: None,
260            write: None,
261            read: None,
262            total: None,
263        }
264    }
265
266    /// Merge request-level overrides into client-level defaults.
267    ///
268    /// For each phase, if the request-level value is `Some`, it replaces
269    /// the client-level value. If `None`, the client-level value is kept.
270    #[must_use]
271    pub(crate) fn merge(self, override_timeout: Option<Self>) -> Self {
272        match override_timeout {
273            Some(req) => Self {
274                pool: req.pool.or(self.pool),
275                connect: req.connect.or(self.connect),
276                write: req.write.or(self.write),
277                read: req.read.or(self.read),
278                total: req.total.or(self.total),
279            },
280            None => self,
281        }
282    }
283
284    /// Returns `true` if any phase has a timeout set.
285    #[must_use]
286    pub fn has_any(&self) -> bool {
287        self.pool.is_some()
288            || self.connect.is_some()
289            || self.write.is_some()
290            || self.read.is_some()
291            || self.total.is_some()
292    }
293}
294
295/// Builder for constructing a [`Timeout`] with individual phase durations.
296///
297/// Created by [`Timeout::builder()`].
298#[derive(Debug, Clone)]
299pub struct TimeoutBuilder {
300    pool: Option<Duration>,
301    connect: Option<Duration>,
302    write: Option<Duration>,
303    read: Option<Duration>,
304    total: Option<Duration>,
305}
306
307impl TimeoutBuilder {
308    /// Set the pool acquisition timeout.
309    #[must_use]
310    pub fn pool(mut self, timeout: Duration) -> Self {
311        self.pool = Some(timeout);
312        self
313    }
314
315    /// Set the connect timeout.
316    #[must_use]
317    pub fn connect(mut self, timeout: Duration) -> Self {
318        self.connect = Some(timeout);
319        self
320    }
321
322    /// Set the write timeout.
323    #[must_use]
324    pub fn write(mut self, timeout: Duration) -> Self {
325        self.write = Some(timeout);
326        self
327    }
328
329    /// Set the read timeout.
330    #[must_use]
331    pub fn read(mut self, timeout: Duration) -> Self {
332        self.read = Some(timeout);
333        self
334    }
335
336    /// Set the total request timeout.
337    #[must_use]
338    pub fn total(mut self, timeout: Duration) -> Self {
339        self.total = Some(timeout);
340        self
341    }
342
343    /// Build the [`Timeout`].
344    #[must_use]
345    pub fn build(self) -> Timeout {
346        Timeout {
347            pool: self.pool,
348            connect: self.connect,
349            write: self.write,
350            read: self.read,
351            total: self.total,
352        }
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use proptest::prelude::*;
360
361    #[test]
362    fn timeout_default_all_none() {
363        let t = Timeout::default();
364        assert!(t.pool.is_none());
365        assert!(t.connect.is_none());
366        assert!(t.write.is_none());
367        assert!(t.read.is_none());
368        assert!(t.total.is_none());
369    }
370
371    #[test]
372    fn timeout_disabled_same_as_default() {
373        let t = Timeout::disabled();
374        assert!(!t.has_any());
375    }
376
377    #[test]
378    fn timeout_from_secs_sets_phases() {
379        let t = Timeout::from_secs(10);
380        assert_eq!(t.pool, Some(Duration::from_secs(10)));
381        assert_eq!(t.connect, Some(Duration::from_secs(10)));
382        assert_eq!(t.write, Some(Duration::from_secs(10)));
383        assert_eq!(t.read, Some(Duration::from_secs(10)));
384        assert!(t.total.is_none());
385    }
386
387    #[test]
388    fn timeout_builder_sets_all() {
389        let t = Timeout::builder()
390            .pool(Duration::from_secs(1))
391            .connect(Duration::from_secs(2))
392            .write(Duration::from_secs(3))
393            .read(Duration::from_secs(4))
394            .total(Duration::from_secs(5))
395            .build();
396        assert_eq!(t.pool, Some(Duration::from_secs(1)));
397        assert_eq!(t.connect, Some(Duration::from_secs(2)));
398        assert_eq!(t.write, Some(Duration::from_secs(3)));
399        assert_eq!(t.read, Some(Duration::from_secs(4)));
400        assert_eq!(t.total, Some(Duration::from_secs(5)));
401    }
402
403    #[test]
404    fn timeout_merge_request_overrides_client() {
405        let client = Timeout::from_secs(10);
406        let request = Timeout {
407            read: Some(Duration::from_secs(30)),
408            ..Timeout::default()
409        };
410        let merged = client.merge(Some(request));
411        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
412        assert_eq!(merged.connect, Some(Duration::from_secs(10)));
413        assert_eq!(merged.write, Some(Duration::from_secs(10)));
414        assert_eq!(merged.read, Some(Duration::from_secs(30)));
415        assert!(merged.total.is_none());
416    }
417
418    #[test]
419    fn timeout_merge_no_override() {
420        let client = Timeout::from_secs(5);
421        let merged = client.merge(None);
422        assert_eq!(merged.pool, Some(Duration::from_secs(5)));
423        assert_eq!(merged.connect, Some(Duration::from_secs(5)));
424    }
425
426    #[test]
427    fn timeout_compat_sets_operational_phases_without_total() {
428        let t = Timeout::compat();
429        let d = Duration::from_secs(5);
430        assert_eq!(t.pool, Some(d));
431        assert_eq!(t.connect, Some(d));
432        assert_eq!(t.write, Some(d));
433        assert_eq!(t.read, Some(d));
434        assert!(t.total.is_none());
435    }
436
437    #[test]
438    fn timeout_native_sets_phases_without_total() {
439        let t = Timeout::native();
440        let d = Duration::from_secs(30);
441        assert_eq!(t.pool, Some(d));
442        assert_eq!(t.connect, Some(d));
443        assert_eq!(t.write, Some(d));
444        assert_eq!(t.read, Some(d));
445        assert!(t.total.is_none());
446    }
447
448    #[test]
449    fn timeout_has_any() {
450        assert!(!Timeout::default().has_any());
451        assert!(Timeout::from_secs(1).has_any());
452        assert!(Timeout {
453            total: Some(Duration::from_secs(1)),
454            ..Timeout::default()
455        }
456        .has_any());
457    }
458
459    #[test]
460    fn timeout_phase_display() {
461        assert_eq!(TimeoutPhase::Pool.to_string(), "pool");
462        assert_eq!(TimeoutPhase::Connect.to_string(), "connect");
463        assert_eq!(TimeoutPhase::ProxyConnect.to_string(), "proxy connect");
464        assert_eq!(TimeoutPhase::ProxyTls.to_string(), "proxy TLS");
465        assert_eq!(TimeoutPhase::Write.to_string(), "write");
466        assert_eq!(TimeoutPhase::Read.to_string(), "read");
467        assert_eq!(TimeoutPhase::Total.to_string(), "total");
468    }
469
470    #[test]
471    fn timeout_merge_empty_override_preserves_client() {
472        let client = Timeout {
473            pool: Some(Duration::from_secs(1)),
474            connect: Some(Duration::from_secs(2)),
475            write: Some(Duration::from_secs(3)),
476            read: Some(Duration::from_secs(4)),
477            total: Some(Duration::from_secs(5)),
478        };
479        let merged = client.merge(Some(Timeout::default()));
480        assert_eq!(merged.pool, Some(Duration::from_secs(1)));
481        assert_eq!(merged.connect, Some(Duration::from_secs(2)));
482        assert_eq!(merged.write, Some(Duration::from_secs(3)));
483        assert_eq!(merged.read, Some(Duration::from_secs(4)));
484        assert_eq!(merged.total, Some(Duration::from_secs(5)));
485    }
486
487    #[test]
488    fn timeout_builder_matches_from_secs_for_phases() {
489        let scalar = Timeout::from_secs(5);
490        let builder = Timeout::builder()
491            .pool(Duration::from_secs(5))
492            .connect(Duration::from_secs(5))
493            .write(Duration::from_secs(5))
494            .read(Duration::from_secs(5))
495            .build();
496        assert_eq!(scalar.pool, builder.pool);
497        assert_eq!(scalar.connect, builder.connect);
498        assert_eq!(scalar.write, builder.write);
499        assert_eq!(scalar.read, builder.read);
500        assert_eq!(scalar.total, builder.total);
501    }
502
503    #[test]
504    fn timeout_merge_request_overrides_total() {
505        let client = Timeout::from_secs(10);
506        let request = Timeout {
507            total: Some(Duration::from_secs(60)),
508            ..Timeout::default()
509        };
510        let merged = client.merge(Some(request));
511        assert_eq!(merged.total, Some(Duration::from_secs(60)));
512        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
513    }
514
515    #[test]
516    fn zero_duration_timeout_is_valid() {
517        // Zero is a valid Duration in Rust (unsigned). It produces an immediate
518        // timeout when used with tokio::time::timeout. This is documented
519        // behavior, not an error.
520        let t = Timeout::from_secs(0);
521        assert_eq!(t.pool, Some(Duration::ZERO));
522        assert_eq!(t.connect, Some(Duration::ZERO));
523        assert_eq!(t.write, Some(Duration::ZERO));
524        assert_eq!(t.read, Some(Duration::ZERO));
525        assert_eq!(t.total, None);
526    }
527
528    proptest::proptest! {
529        #[test]
530        fn from_secs_sets_correct_phases(secs in 0u64..86400) {
531            let t = Timeout::from_secs(secs);
532            let d = Duration::from_secs(secs);
533            prop_assert_eq!(t.pool, Some(d));
534            prop_assert_eq!(t.connect, Some(d));
535            prop_assert_eq!(t.write, Some(d));
536            prop_assert_eq!(t.read, Some(d));
537            prop_assert!(t.total.is_none());
538        }
539
540        #[test]
541        fn disabled_has_no_phases(_ in 0u64..100) {
542            let t = Timeout::disabled();
543            prop_assert!(!t.has_any());
544            prop_assert!(t.pool.is_none());
545            prop_assert!(t.connect.is_none());
546            prop_assert!(t.write.is_none());
547            prop_assert!(t.read.is_none());
548            prop_assert!(t.total.is_none());
549        }
550
551        #[test]
552        fn has_any_consistent_with_fields(
553            pool in proptest::option::of(0u64..3600),
554            connect in proptest::option::of(0u64..3600),
555            write in proptest::option::of(0u64..3600),
556            read in proptest::option::of(0u64..3600),
557            total in proptest::option::of(0u64..3600),
558        ) {
559            let t = Timeout {
560                pool: pool.map(Duration::from_secs),
561                connect: connect.map(Duration::from_secs),
562                write: write.map(Duration::from_secs),
563                read: read.map(Duration::from_secs),
564                total: total.map(Duration::from_secs),
565            };
566            let expected = t.pool.is_some() || t.connect.is_some() || t.write.is_some() || t.read.is_some() || t.total.is_some();
567            prop_assert_eq!(t.has_any(), expected);
568        }
569
570        #[test]
571        fn builder_round_trip(
572            pool in 0u64..3600,
573            connect in 0u64..3600,
574            write in 0u64..3600,
575            read in 0u64..3600,
576            total in 0u64..3600,
577        ) {
578            let t = Timeout::builder()
579                .pool(Duration::from_secs(pool))
580                .connect(Duration::from_secs(connect))
581                .write(Duration::from_secs(write))
582                .read(Duration::from_secs(read))
583                .total(Duration::from_secs(total))
584                .build();
585            prop_assert_eq!(t.pool, Some(Duration::from_secs(pool)));
586            prop_assert_eq!(t.connect, Some(Duration::from_secs(connect)));
587            prop_assert_eq!(t.write, Some(Duration::from_secs(write)));
588            prop_assert_eq!(t.read, Some(Duration::from_secs(read)));
589            prop_assert_eq!(t.total, Some(Duration::from_secs(total)));
590        }
591    }
592}