eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
#![allow(
    missing_docs,
    dead_code,
    unused_mut,
    clippy::large_futures,
    clippy::missing_panics_doc,
    clippy::redundant_closure_for_method_calls,
    clippy::inefficient_to_string,
    clippy::manual_let_else,
    clippy::single_char_pattern,
    clippy::match_same_arms,
    clippy::needless_borrow,
    clippy::trim_split_whitespace,
    clippy::too_many_lines,
    clippy::unused_self,
    clippy::items_after_statements,
    clippy::expect_fun_call,
    clippy::len_zero,
    clippy::unnecessary_debug_formatting,
    clippy::format_push_string,
    clippy::new_without_default,
    clippy::map_unwrap_or
)]
#![cfg(feature = "high-level-url")]
//! Timeout integration tests for eggfetch-core.

mod test_server;

use std::time::Duration;

use bytes::Bytes;
use eggfetch_core::{Client, Error, RequestBody, Timeout, TimeoutPhase};
use futures_util::StreamExt;
use test_server::{TestServer, TestServerConfig};

/// Pool timeout fires when `max_connections=1` saturates and the wait exceeds
/// the configured pool timeout.
#[tokio::test]
async fn test_pool_timeout_with_saturated_pool() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 300,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .max_connections(1)
        .timeout(Timeout {
            pool: Some(Duration::from_millis(200)),
            ..Timeout::default()
        })
        .build();

    let client2 = client.clone();
    let url2 = url.clone();

    // First request holds the only slot.
    let h1 = tokio::spawn(async move { client.get(&url).unwrap().send().await });

    // Give the first request time to acquire the slot.
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Second request should fail with pool timeout.
    let h2 = tokio::spawn(async move { client2.get(&url2).unwrap().send().await });

    let r2 = h2.await.unwrap();
    assert!(
        matches!(
            r2,
            Err(Error::Timeout {
                phase: TimeoutPhase::Pool,
                ..
            })
        ),
        "expected pool timeout, got: {r2:?}"
    );

    // First request may still be in flight; wait for it to complete.
    let _ = h1.await;

    server.shutdown();
}

/// Connect timeout fires when connecting to an unroutable IP.
#[tokio::test]
async fn test_connect_timeout() {
    // 192.0.2.1 is TEST-NET-1 (RFC 5737) — unroutable on any real network.
    let client = Client::builder()
        .timeout(Timeout {
            connect: Some(Duration::from_millis(100)),
            read: Some(Duration::from_millis(10)),
            ..Timeout::default()
        })
        .build();

    let result = client.get("http://192.0.2.1:80/").unwrap().send().await;

    assert!(
        result.is_err(),
        "expected error connecting to unroutable IP"
    );
    // The error could be a timeout, connect error, or hyper error depending
    // on OS behavior with TEST-NET addresses.
    match &result {
        Err(
            Error::Timeout {
                phase: TimeoutPhase::Connect,
                ..
            }
            | Error::Connect(_)
            | Error::HyperClient(_)
            | Error::Hyper(_)
            | Error::Io(_),
        ) => { /* acceptable */ }
        other => panic!("unexpected error: {other:?}"),
    }
}

/// Total timeout fires when the request takes longer than the total deadline.
#[tokio::test]
async fn test_total_timeout() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 500,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .timeout(Timeout {
            total: Some(Duration::from_millis(100)),
            ..Timeout::default()
        })
        .build();

    let result = client.get(&url).unwrap().send().await;

    assert!(
        matches!(
            result,
            Err(Error::Timeout {
                phase: TimeoutPhase::Total,
                ..
            })
        ),
        "expected total timeout, got: {result:?}"
    );

    server.shutdown();
}

/// Fast requests succeed even with generous timeouts.
#[tokio::test]
async fn test_no_timeout_when_fast_enough() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 0,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().timeout(Timeout::from_secs(5)).build();

    let result = client.get(&url).unwrap().send().await;
    assert!(
        result.is_ok(),
        "expected success for fast request, got: {result:?}"
    );

    server.shutdown();
}

/// Request-level timeout overrides client-level timeout.
#[tokio::test]
async fn test_request_level_timeout_overrides_client() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 300,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().timeout(Timeout::from_secs(5)).build();

    // Request-level total timeout overrides the generous client timeout.
    let result = client
        .get(&url)
        .unwrap()
        .timeout(Timeout {
            total: Some(Duration::from_millis(100)),
            ..Timeout::default()
        })
        .send()
        .await;

    assert!(
        matches!(
            result,
            Err(Error::Timeout {
                phase: TimeoutPhase::Total,
                ..
            })
        ),
        "expected total timeout from request-level override, got: {result:?}"
    );

    server.shutdown();
}

/// Disabled timeouts (all None) allow slow requests to succeed.
#[tokio::test]
async fn test_disabled_timeout_does_not_fail() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 200,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().timeout(Timeout::disabled()).build();

    let result = client.get(&url).unwrap().send().await;
    assert!(
        result.is_ok(),
        "expected success with disabled timeout, got: {result:?}"
    );

    server.shutdown();
}

/// Pool timeout errors report `TimeoutPhase::Pool`; total timeout errors
/// report `TimeoutPhase::Total`.
#[tokio::test]
async fn test_timeout_error_reports_correct_phase() {
    // --- Pool phase ---
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 300,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .max_connections(1)
        .timeout(Timeout {
            pool: Some(Duration::from_millis(200)),
            ..Timeout::default()
        })
        .build();

    let client2 = client.clone();
    let url2 = url.clone();

    let h1 = tokio::spawn(async move {
        let _ = client.get(&url).unwrap().send().await;
    });
    tokio::time::sleep(Duration::from_millis(50)).await;

    let h2 = tokio::spawn(async move { client2.get(&url2).unwrap().send().await });

    let pool_err = h2.await.unwrap();
    assert!(
        matches!(
            pool_err,
            Err(Error::Timeout {
                phase: TimeoutPhase::Pool,
                ..
            })
        ),
        "expected TimeoutPhase::Pool, got: {pool_err:?}"
    );

    let _ = h1.await;
    server.shutdown();

    // --- Total phase ---
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 500,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .timeout(Timeout {
            total: Some(Duration::from_millis(100)),
            ..Timeout::default()
        })
        .build();

    let total_err = client.get(&url).unwrap().send().await;
    assert!(
        matches!(
            total_err,
            Err(Error::Timeout {
                phase: TimeoutPhase::Total,
                ..
            })
        ),
        "expected TimeoutPhase::Total, got: {total_err:?}"
    );

    server.shutdown();
}

/// Client builder accepts timeout configuration and compiles.
#[test]
fn test_client_builder_timeout_config() {
    let client = Client::builder().timeout(Timeout::from_secs(5)).build();

    let req = client.get("https://example.com").unwrap().build().unwrap();
    assert_eq!(*req.method(), http::Method::GET);
}

/// Request builder accepts timeout configuration and compiles.
#[test]
fn test_request_builder_timeout_config() {
    let client = Client::new();
    let req = client
        .get("https://example.com")
        .unwrap()
        .timeout(Timeout::from_secs(5))
        .build()
        .unwrap();

    assert!(req.timeout().is_some());
    let t = req.timeout().unwrap();
    assert_eq!(t.pool, Some(Duration::from_secs(5)));
    assert_eq!(t.connect, Some(Duration::from_secs(5)));
    assert_eq!(t.write, Some(Duration::from_secs(5)));
    assert_eq!(t.read, Some(Duration::from_secs(5)));
    assert!(t.total.is_none());
}

/// Cancelling a waiting acquisition does not cause deadlock. The third
/// request succeeds after the first completes.
#[tokio::test]
async fn test_pool_timeout_cancellation_safety() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 100,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .max_connections(1)
        .timeout(Timeout {
            pool: Some(Duration::from_millis(200)),
            ..Timeout::default()
        })
        .build();

    // First request holds the only slot.
    let h1 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };

    // Give first request time to acquire the slot.
    tokio::time::sleep(Duration::from_millis(30)).await;

    // Second request starts waiting, then we cancel it by aborting.
    let h2 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };

    // Give the waiter time to start blocking on the semaphore.
    tokio::time::sleep(Duration::from_millis(30)).await;

    // Cancel the waiter.
    h2.abort();
    tokio::time::sleep(Duration::from_millis(10)).await;

    // First request completes; consume and drop it so the streaming body
    // releases the pooled connection before we issue the next request.
    {
        let mut r1 = h1.await.unwrap().expect("first request should succeed");
        let _ = r1.bytes().await;
    }

    // Third request should succeed without deadlock.
    let resp = client.get(&url).unwrap().send().await;
    assert!(
        resp.is_ok(),
        "third request should succeed after cancellation"
    );

    server.shutdown();
}

/// Read timeout fires when a chunked response stalls between chunks.
#[tokio::test]
async fn test_read_timeout_on_chunked_response_stall() {
    // Server sends 2 chunks quickly, then stalls 500ms before the 3rd.
    let mut server = TestServer::start(&TestServerConfig {
        chunked: true,
        response_body: Some(b"abcdefghij".to_vec()),
        chunk_stall_after: Some(2),
        chunk_stall_ms: 500,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .timeout(Timeout {
            read: Some(Duration::from_millis(150)),
            ..Timeout::default()
        })
        .build();

    let mut resp = client.get(&url).unwrap().send().await.unwrap();
    let mut stream = resp.bytes_stream().unwrap();

    // First two chunks arrive well within the read timeout.
    for _ in 0..2 {
        let next = tokio::time::timeout(Duration::from_millis(400), stream.next())
            .await
            .expect("early chunks should arrive within the read timeout")
            .expect("stream should yield chunk")
            .expect("chunk should be Ok");
        assert!(!next.is_empty(), "chunk should have data");
    }

    // The server now stalls before the next chunk; read timeout fires.
    let next = stream.next().await;
    match next {
        Some(Err(Error::Timeout {
            phase: TimeoutPhase::Read,
            ..
        })) => {}
        other => panic!("expected read timeout error, got: {other:?}"),
    }

    server.shutdown();
}

/// Read timeout also bounds the wait for response headers after the request
/// body has been sent; it does not consume the connect or upload budget.
#[tokio::test]
async fn test_read_timeout_on_delayed_response_headers() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 350,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .timeout(Timeout {
            connect: Some(Duration::from_secs(1)),
            write: Some(Duration::from_secs(1)),
            read: Some(Duration::from_millis(80)),
            ..Timeout::default()
        })
        .build();

    let started = tokio::time::Instant::now();
    let result = client.post(&url).unwrap().body("request").send().await;
    assert!(
        matches!(
            result,
            Err(Error::Timeout {
                phase: TimeoutPhase::Read,
                ..
            })
        ),
        "expected a response-header read timeout, got: {result:?}"
    );
    assert!(started.elapsed() < Duration::from_millis(250));

    server.shutdown();
}

#[tokio::test]
async fn test_early_response_during_request_body_is_not_a_read_timeout() {
    // This fixture responds as soon as it receives request headers instead of
    // waiting for the streamed upload. The response must win while the body
    // producer is still pending; upload time is not response-read time.
    let mut server = TestServer::start(&TestServerConfig {
        consume_body: false,
        ..Default::default()
    });
    let url = server.url();
    let client = Client::builder()
        .timeout(Timeout {
            write: Some(Duration::from_secs(1)),
            read: Some(Duration::from_millis(50)),
            ..Timeout::default()
        })
        .build();
    let producer = futures_util::stream::unfold(0_u8, |state| async move {
        match state {
            0 => Some((Ok(Bytes::from_static(b"first")), 1)),
            1 => {
                tokio::time::sleep(Duration::from_millis(300)).await;
                Some((Ok(Bytes::from_static(b"second")), 2))
            }
            _ => None,
        }
    });

    let response = tokio::time::timeout(
        Duration::from_millis(250),
        client
            .post(&url)
            .unwrap()
            .body(RequestBody::Stream {
                stream: Box::pin(producer),
                length: None,
            })
            .send(),
    )
    .await
    .expect("an early response should not wait for the stalled upload")
    .expect("early response should succeed");
    assert_eq!(response.status(), 200);
    server.shutdown();
}

#[tokio::test]
async fn test_total_timeout_wins_over_response_header_read_timeout() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 350,
        ..Default::default()
    });
    let url = server.url();
    let client = Client::builder()
        .timeout(Timeout {
            connect: Some(Duration::from_secs(1)),
            write: Some(Duration::from_secs(1)),
            read: Some(Duration::from_millis(80)),
            total: Some(Duration::from_millis(80)),
            ..Timeout::default()
        })
        .build();

    let result = client.post(&url).unwrap().body("request").send().await;
    assert!(
        matches!(
            result,
            Err(Error::Timeout {
                phase: TimeoutPhase::Total,
                ..
            })
        ),
        "expected total timeout to win, got: {result:?}"
    );
    server.shutdown();
}

/// Write timeout fires when a streaming request body's producer stalls
/// between chunks.
#[tokio::test]
async fn test_write_timeout_on_request_body_stall() {
    let mut server = TestServer::start(&TestServerConfig {
        consume_body: true,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder()
        .timeout(Timeout {
            write: Some(Duration::from_millis(100)),
            // The first body producer delay is longer than this read budget.
            // It must stay classified as request-body Write inactivity.
            read: Some(Duration::from_millis(20)),
            ..Timeout::default()
        })
        .build();

    // Producer yields one chunk quickly, then stalls BEFORE yielding a
    // second chunk. The server reads the request body, so hyper must
    // drive the body stream — which gives the write timeout a chance
    // to fire.
    let producer = futures_util::stream::unfold(0u32, |i| async move {
        if i == 0 {
            tokio::time::sleep(Duration::from_millis(50)).await;
            Some((Ok(Bytes::from("chunk0")), 1))
        } else if i == 1 {
            // Stall past the write timeout.
            tokio::time::sleep(Duration::from_secs(2)).await;
            Some((Ok(Bytes::from("chunk1")), 2))
        } else {
            Some((Ok(Bytes::from("chunk2")), 3))
        }
    });
    let stream = Box::pin(producer);
    // With a known Content-Length (17 bytes), hyper MUST read that many
    // bytes from the body before the server will respond.
    let body = RequestBody::from_stream(stream, Some(17));

    let result = tokio::time::timeout(
        Duration::from_secs(3),
        client.post(&url).unwrap().body(body).send(),
    )
    .await
    .expect("overall send should complete (likely with write timeout)");

    match result {
        Err(Error::Timeout {
            phase: TimeoutPhase::Write,
            ..
        }) => {}
        other => panic!("expected write timeout error, got: {other:?}"),
    }

    server.shutdown();
}