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 chunk.
143    /// Only applies to streamed request bodies.
144    pub write: Option<Duration>,
145    /// Time allowed between response body chunks. Resets on every chunk.
146    pub read: Option<Duration>,
147    /// Optional wall-clock cap across the entire request lifecycle.
148    pub total: Option<Duration>,
149}
150
151impl Timeout {
152    /// Create a timeout with all phases disabled.
153    ///
154    /// This is the same as `Timeout::default()`.
155    #[must_use]
156    pub fn disabled() -> Self {
157        Self::default()
158    }
159
160    /// Create a timeout where pool, connect, write, and read each get the
161    /// given duration.
162    ///
163    /// The total timeout is not set. Use [`Timeout::builder`] or the
164    /// struct literal syntax to set it explicitly.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use eggfetch_core::Timeout;
170    ///
171    /// let t = Timeout::from_secs(5);
172    /// assert_eq!(t.pool, Some(std::time::Duration::from_secs(5)));
173    /// assert_eq!(t.connect, Some(std::time::Duration::from_secs(5)));
174    /// assert_eq!(t.write, Some(std::time::Duration::from_secs(5)));
175    /// assert_eq!(t.read, Some(std::time::Duration::from_secs(5)));
176    /// assert!(t.total.is_none());
177    /// ```
178    #[must_use]
179    pub fn from_secs(secs: u64) -> Self {
180        let d = Duration::from_secs(secs);
181        Self {
182            pool: Some(d),
183            connect: Some(d),
184            write: Some(d),
185            read: Some(d),
186            total: None,
187        }
188    }
189
190    /// Create an HTTPX-compatible timeout configuration.
191    ///
192    /// HTTPX 0.28.1 uses 5 seconds for each operational phase. It does not
193    /// define a request-wide wall-clock timeout, so `total` remains unset.
194    /// Set `total` explicitly when an EggFetch-native outer deadline is
195    /// desired.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use std::time::Duration;
201    /// use eggfetch_core::Timeout;
202    ///
203    /// let t = Timeout::compat();
204    /// assert_eq!(t.pool, Some(Duration::from_secs(5)));
205    /// assert_eq!(t.connect, Some(Duration::from_secs(5)));
206    /// assert_eq!(t.write, Some(Duration::from_secs(5)));
207    /// assert_eq!(t.read, Some(Duration::from_secs(5)));
208    /// assert!(t.total.is_none());
209    /// ```
210    #[must_use]
211    pub fn compat() -> Self {
212        let d = Duration::from_secs(5);
213        Self {
214            pool: Some(d),
215            connect: Some(d),
216            write: Some(d),
217            read: Some(d),
218            total: None,
219        }
220    }
221
222    /// Create eggfetch-native timeout defaults.
223    ///
224    /// Uses 30 seconds for pool, connect, write, and read phases with
225    /// no total timeout. This is appropriate for general-purpose use
226    /// where the caller controls overall deadlines.
227    ///
228    /// # Examples
229    ///
230    /// ```
231    /// use std::time::Duration;
232    /// use eggfetch_core::Timeout;
233    ///
234    /// let t = Timeout::native();
235    /// assert_eq!(t.pool, Some(Duration::from_secs(30)));
236    /// assert_eq!(t.connect, Some(Duration::from_secs(30)));
237    /// assert_eq!(t.write, Some(Duration::from_secs(30)));
238    /// assert_eq!(t.read, Some(Duration::from_secs(30)));
239    /// assert!(t.total.is_none());
240    /// ```
241    #[must_use]
242    pub fn native() -> Self {
243        let d = Duration::from_secs(30);
244        Self {
245            pool: Some(d),
246            connect: Some(d),
247            write: Some(d),
248            read: Some(d),
249            total: None,
250        }
251    }
252
253    /// Create a [`TimeoutBuilder`] for configuring individual phases.
254    #[must_use]
255    pub fn builder() -> TimeoutBuilder {
256        TimeoutBuilder {
257            pool: None,
258            connect: None,
259            write: None,
260            read: None,
261            total: None,
262        }
263    }
264
265    /// Merge request-level overrides into client-level defaults.
266    ///
267    /// For each phase, if the request-level value is `Some`, it replaces
268    /// the client-level value. If `None`, the client-level value is kept.
269    #[must_use]
270    pub(crate) fn merge(self, override_timeout: Option<Self>) -> Self {
271        match override_timeout {
272            Some(req) => Self {
273                pool: req.pool.or(self.pool),
274                connect: req.connect.or(self.connect),
275                write: req.write.or(self.write),
276                read: req.read.or(self.read),
277                total: req.total.or(self.total),
278            },
279            None => self,
280        }
281    }
282
283    /// Returns `true` if any phase has a timeout set.
284    #[must_use]
285    pub fn has_any(&self) -> bool {
286        self.pool.is_some()
287            || self.connect.is_some()
288            || self.write.is_some()
289            || self.read.is_some()
290            || self.total.is_some()
291    }
292}
293
294/// Builder for constructing a [`Timeout`] with individual phase durations.
295///
296/// Created by [`Timeout::builder()`].
297#[derive(Debug, Clone)]
298pub struct TimeoutBuilder {
299    pool: Option<Duration>,
300    connect: Option<Duration>,
301    write: Option<Duration>,
302    read: Option<Duration>,
303    total: Option<Duration>,
304}
305
306impl TimeoutBuilder {
307    /// Set the pool acquisition timeout.
308    #[must_use]
309    pub fn pool(mut self, timeout: Duration) -> Self {
310        self.pool = Some(timeout);
311        self
312    }
313
314    /// Set the connect timeout.
315    #[must_use]
316    pub fn connect(mut self, timeout: Duration) -> Self {
317        self.connect = Some(timeout);
318        self
319    }
320
321    /// Set the write timeout.
322    #[must_use]
323    pub fn write(mut self, timeout: Duration) -> Self {
324        self.write = Some(timeout);
325        self
326    }
327
328    /// Set the read timeout.
329    #[must_use]
330    pub fn read(mut self, timeout: Duration) -> Self {
331        self.read = Some(timeout);
332        self
333    }
334
335    /// Set the total request timeout.
336    #[must_use]
337    pub fn total(mut self, timeout: Duration) -> Self {
338        self.total = Some(timeout);
339        self
340    }
341
342    /// Build the [`Timeout`].
343    #[must_use]
344    pub fn build(self) -> Timeout {
345        Timeout {
346            pool: self.pool,
347            connect: self.connect,
348            write: self.write,
349            read: self.read,
350            total: self.total,
351        }
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use proptest::prelude::*;
359
360    #[test]
361    fn timeout_default_all_none() {
362        let t = Timeout::default();
363        assert!(t.pool.is_none());
364        assert!(t.connect.is_none());
365        assert!(t.write.is_none());
366        assert!(t.read.is_none());
367        assert!(t.total.is_none());
368    }
369
370    #[test]
371    fn timeout_disabled_same_as_default() {
372        let t = Timeout::disabled();
373        assert!(!t.has_any());
374    }
375
376    #[test]
377    fn timeout_from_secs_sets_phases() {
378        let t = Timeout::from_secs(10);
379        assert_eq!(t.pool, Some(Duration::from_secs(10)));
380        assert_eq!(t.connect, Some(Duration::from_secs(10)));
381        assert_eq!(t.write, Some(Duration::from_secs(10)));
382        assert_eq!(t.read, Some(Duration::from_secs(10)));
383        assert!(t.total.is_none());
384    }
385
386    #[test]
387    fn timeout_builder_sets_all() {
388        let t = Timeout::builder()
389            .pool(Duration::from_secs(1))
390            .connect(Duration::from_secs(2))
391            .write(Duration::from_secs(3))
392            .read(Duration::from_secs(4))
393            .total(Duration::from_secs(5))
394            .build();
395        assert_eq!(t.pool, Some(Duration::from_secs(1)));
396        assert_eq!(t.connect, Some(Duration::from_secs(2)));
397        assert_eq!(t.write, Some(Duration::from_secs(3)));
398        assert_eq!(t.read, Some(Duration::from_secs(4)));
399        assert_eq!(t.total, Some(Duration::from_secs(5)));
400    }
401
402    #[test]
403    fn timeout_merge_request_overrides_client() {
404        let client = Timeout::from_secs(10);
405        let request = Timeout {
406            read: Some(Duration::from_secs(30)),
407            ..Timeout::default()
408        };
409        let merged = client.merge(Some(request));
410        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
411        assert_eq!(merged.connect, Some(Duration::from_secs(10)));
412        assert_eq!(merged.write, Some(Duration::from_secs(10)));
413        assert_eq!(merged.read, Some(Duration::from_secs(30)));
414        assert!(merged.total.is_none());
415    }
416
417    #[test]
418    fn timeout_merge_no_override() {
419        let client = Timeout::from_secs(5);
420        let merged = client.merge(None);
421        assert_eq!(merged.pool, Some(Duration::from_secs(5)));
422        assert_eq!(merged.connect, Some(Duration::from_secs(5)));
423    }
424
425    #[test]
426    fn timeout_compat_sets_operational_phases_without_total() {
427        let t = Timeout::compat();
428        let d = Duration::from_secs(5);
429        assert_eq!(t.pool, Some(d));
430        assert_eq!(t.connect, Some(d));
431        assert_eq!(t.write, Some(d));
432        assert_eq!(t.read, Some(d));
433        assert!(t.total.is_none());
434    }
435
436    #[test]
437    fn timeout_native_sets_phases_without_total() {
438        let t = Timeout::native();
439        let d = Duration::from_secs(30);
440        assert_eq!(t.pool, Some(d));
441        assert_eq!(t.connect, Some(d));
442        assert_eq!(t.write, Some(d));
443        assert_eq!(t.read, Some(d));
444        assert!(t.total.is_none());
445    }
446
447    #[test]
448    fn timeout_has_any() {
449        assert!(!Timeout::default().has_any());
450        assert!(Timeout::from_secs(1).has_any());
451        assert!(Timeout {
452            total: Some(Duration::from_secs(1)),
453            ..Timeout::default()
454        }
455        .has_any());
456    }
457
458    #[test]
459    fn timeout_phase_display() {
460        assert_eq!(TimeoutPhase::Pool.to_string(), "pool");
461        assert_eq!(TimeoutPhase::Connect.to_string(), "connect");
462        assert_eq!(TimeoutPhase::ProxyConnect.to_string(), "proxy connect");
463        assert_eq!(TimeoutPhase::ProxyTls.to_string(), "proxy TLS");
464        assert_eq!(TimeoutPhase::Write.to_string(), "write");
465        assert_eq!(TimeoutPhase::Read.to_string(), "read");
466        assert_eq!(TimeoutPhase::Total.to_string(), "total");
467    }
468
469    #[test]
470    fn timeout_merge_empty_override_preserves_client() {
471        let client = Timeout {
472            pool: Some(Duration::from_secs(1)),
473            connect: Some(Duration::from_secs(2)),
474            write: Some(Duration::from_secs(3)),
475            read: Some(Duration::from_secs(4)),
476            total: Some(Duration::from_secs(5)),
477        };
478        let merged = client.merge(Some(Timeout::default()));
479        assert_eq!(merged.pool, Some(Duration::from_secs(1)));
480        assert_eq!(merged.connect, Some(Duration::from_secs(2)));
481        assert_eq!(merged.write, Some(Duration::from_secs(3)));
482        assert_eq!(merged.read, Some(Duration::from_secs(4)));
483        assert_eq!(merged.total, Some(Duration::from_secs(5)));
484    }
485
486    #[test]
487    fn timeout_builder_matches_from_secs_for_phases() {
488        let scalar = Timeout::from_secs(5);
489        let builder = Timeout::builder()
490            .pool(Duration::from_secs(5))
491            .connect(Duration::from_secs(5))
492            .write(Duration::from_secs(5))
493            .read(Duration::from_secs(5))
494            .build();
495        assert_eq!(scalar.pool, builder.pool);
496        assert_eq!(scalar.connect, builder.connect);
497        assert_eq!(scalar.write, builder.write);
498        assert_eq!(scalar.read, builder.read);
499        assert_eq!(scalar.total, builder.total);
500    }
501
502    #[test]
503    fn timeout_merge_request_overrides_total() {
504        let client = Timeout::from_secs(10);
505        let request = Timeout {
506            total: Some(Duration::from_secs(60)),
507            ..Timeout::default()
508        };
509        let merged = client.merge(Some(request));
510        assert_eq!(merged.total, Some(Duration::from_secs(60)));
511        assert_eq!(merged.pool, Some(Duration::from_secs(10)));
512    }
513
514    #[test]
515    fn zero_duration_timeout_is_valid() {
516        // Zero is a valid Duration in Rust (unsigned). It produces an immediate
517        // timeout when used with tokio::time::timeout. This is documented
518        // behavior, not an error.
519        let t = Timeout::from_secs(0);
520        assert_eq!(t.pool, Some(Duration::ZERO));
521        assert_eq!(t.connect, Some(Duration::ZERO));
522        assert_eq!(t.write, Some(Duration::ZERO));
523        assert_eq!(t.read, Some(Duration::ZERO));
524        assert_eq!(t.total, None);
525    }
526
527    proptest::proptest! {
528        #[test]
529        fn from_secs_sets_correct_phases(secs in 0u64..86400) {
530            let t = Timeout::from_secs(secs);
531            let d = Duration::from_secs(secs);
532            prop_assert_eq!(t.pool, Some(d));
533            prop_assert_eq!(t.connect, Some(d));
534            prop_assert_eq!(t.write, Some(d));
535            prop_assert_eq!(t.read, Some(d));
536            prop_assert!(t.total.is_none());
537        }
538
539        #[test]
540        fn disabled_has_no_phases(_ in 0u64..100) {
541            let t = Timeout::disabled();
542            prop_assert!(!t.has_any());
543            prop_assert!(t.pool.is_none());
544            prop_assert!(t.connect.is_none());
545            prop_assert!(t.write.is_none());
546            prop_assert!(t.read.is_none());
547            prop_assert!(t.total.is_none());
548        }
549
550        #[test]
551        fn has_any_consistent_with_fields(
552            pool in proptest::option::of(0u64..3600),
553            connect in proptest::option::of(0u64..3600),
554            write in proptest::option::of(0u64..3600),
555            read in proptest::option::of(0u64..3600),
556            total in proptest::option::of(0u64..3600),
557        ) {
558            let t = Timeout {
559                pool: pool.map(Duration::from_secs),
560                connect: connect.map(Duration::from_secs),
561                write: write.map(Duration::from_secs),
562                read: read.map(Duration::from_secs),
563                total: total.map(Duration::from_secs),
564            };
565            let expected = t.pool.is_some() || t.connect.is_some() || t.write.is_some() || t.read.is_some() || t.total.is_some();
566            prop_assert_eq!(t.has_any(), expected);
567        }
568
569        #[test]
570        fn builder_round_trip(
571            pool in 0u64..3600,
572            connect in 0u64..3600,
573            write in 0u64..3600,
574            read in 0u64..3600,
575            total in 0u64..3600,
576        ) {
577            let t = Timeout::builder()
578                .pool(Duration::from_secs(pool))
579                .connect(Duration::from_secs(connect))
580                .write(Duration::from_secs(write))
581                .read(Duration::from_secs(read))
582                .total(Duration::from_secs(total))
583                .build();
584            prop_assert_eq!(t.pool, Some(Duration::from_secs(pool)));
585            prop_assert_eq!(t.connect, Some(Duration::from_secs(connect)));
586            prop_assert_eq!(t.write, Some(Duration::from_secs(write)));
587            prop_assert_eq!(t.read, Some(Duration::from_secs(read)));
588            prop_assert_eq!(t.total, Some(Duration::from_secs(total)));
589        }
590    }
591}