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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
#![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")]
//! Connection pool and concurrency lifecycle tests.

mod test_server;

use std::sync::atomic::Ordering;
use std::time::Duration;

use eggfetch_core::Client;
use test_server::{TestServer, TestServerConfig};

/// Sequential requests to the same host reuse connections.
#[tokio::test]
async fn test_reuse_connections() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder().build();

    for _ in 0..5 {
        let resp = client.get(&url).unwrap().send().await.unwrap();
        assert!(resp.is_success());
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    }
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    let accepted = server.connections_accepted();

    // Hyper should reuse the connection; we should see at most 3 TCP
    // connections (initial + possible idle reconnection during warm-up).
    assert!(
        accepted <= 3,
        "expected at most 3 TCP connections for sequential reuse, got {accepted}"
    );

    server.shutdown();
}

/// Connections are not reused when the server sends `Connection: close`.
#[tokio::test]
async fn test_connection_close_not_reused() {
    let mut server = TestServer::start(&TestServerConfig {
        close_connection: true,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().max_connections(8).build();

    for _ in 0..5 {
        let resp = client.get(&url).unwrap().send().await.unwrap();
        assert!(resp.is_success());
        tokio::task::yield_now().await;
    }

    // Each request should have opened a new TCP connection.
    let accepted = server.connections_accepted();
    assert!(
        accepted >= 5,
        "expected at least 5 TCP connections with Connection: close, got {accepted}"
    );

    server.shutdown();
}

/// Global `max_connections` limits concurrent in-flight requests.
///
/// Uses timing-based verification: with `max_connections=2` and a 200ms
/// server delay, 6 requests should take at least 400ms if the limit works.
#[tokio::test]
async fn test_max_connections_limits() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 200,
        ..Default::default()
    });
    let url = server.url();

    let max_conn: usize = 2;
    let client = Client::builder().max_connections(max_conn).build();

    let start = std::time::Instant::now();

    // Fire 6 concurrent requests.
    let mut handles = Vec::new();
    for _ in 0..6 {
        let client = client.clone();
        let url = url.clone();
        handles.push(tokio::spawn(async move {
            client.get(&url).unwrap().send().await.unwrap();
        }));
    }

    for h in handles {
        h.await.unwrap();
    }

    let elapsed = start.elapsed();

    // With max_connections=2 and 200ms delay, 6 requests need 3 batches
    // of 2 = 600ms minimum. Allow generous margin for timing jitter.
    // Without the limit, all 6 would complete in ~200ms.
    let min_expected = Duration::from_millis(350);
    assert!(
        elapsed >= min_expected,
        "expected at least {min_expected:?} with max_connections={max_conn}, elapsed {elapsed:?}"
    );

    // The pool limits logical in-flight requests. Hyper owns TCP connection
    // reuse, so the number of accepted sockets is not a reliable assertion
    // for this abstraction.
    server.shutdown();
}

/// Per-host `max_connections` limits concurrent requests to one host.
#[tokio::test]
async fn test_max_connections_per_host() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 200,
        ..Default::default()
    });
    let url = server.url();

    let max_per_host: usize = 2;
    let client = Client::builder()
        .max_connections(8)
        .max_connections_per_host(max_per_host)
        .build();

    let start = std::time::Instant::now();

    let mut handles = Vec::new();
    for _ in 0..6 {
        let client = client.clone();
        let url = url.clone();
        handles.push(tokio::spawn(async move {
            client.get(&url).unwrap().send().await.unwrap();
        }));
    }

    for h in handles {
        h.await.unwrap();
    }

    let elapsed = start.elapsed();

    // Same timing logic: max_per_host=2 means 3 batches of 2 = ~600ms.
    let min_expected = Duration::from_millis(350);
    assert!(
        elapsed >= min_expected,
        "expected at least {min_expected:?} with max_connections_per_host={max_per_host}, elapsed {elapsed:?}"
    );

    server.shutdown();
}

/// Pool metrics counters are updated after requests.
#[tokio::test]
async fn test_pool_metrics_tracking() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder().build();

    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert!(resp.is_success());

    // At this point, the pool's acquisition_waits should be 0 (no limits
    // configured, so no waiting needed).
    let metrics = client.pool_metrics();
    assert_eq!(
        metrics.acquisition_waits.load(Ordering::Relaxed),
        0,
        "no waits expected without limits"
    );
    assert_eq!(
        metrics.acquisition_cancellations.load(Ordering::Relaxed),
        0,
        "no cancellations expected"
    );

    server.shutdown();
}

/// A cloned client shares the same pool as the original.
#[tokio::test]
async fn test_clone_shares_pool() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder().max_connections(4).build();

    let client2 = client.clone();

    // Both should work and share the pool.
    let r1 = client.get(&url).unwrap().send().await.unwrap();
    let r2 = client2.get(&url).unwrap().send().await.unwrap();
    assert!(r1.is_success());
    assert!(r2.is_success());
    tokio::task::yield_now().await;

    // Total connections should still be small (pool reuse).
    let accepted = server.connections_accepted();
    assert!(
        accepted <= 3,
        "cloned clients should share pool, expected <= 3 connections, got {accepted}"
    );

    server.shutdown();
}

/// Client builder methods configure pool correctly.
#[test]
fn test_client_builder_pool_config() {
    let _client = Client::builder()
        .max_connections(10)
        .max_connections_per_host(5)
        .max_idle_connections(20)
        .max_idle_connections_per_host(10)
        .idle_timeout(Duration::from_secs(30))
        .user_agent("test-agent")
        .build();
}

/// Idle timeout configuration is accepted by the builder.
#[test]
fn test_idle_timeout_config() {
    let _client = Client::builder()
        .idle_timeout(Duration::from_secs(60))
        .build();
}

/// A configured idle timeout does not prevent connection reuse while the
/// connection is still fresh (control case for the eviction tests below).
#[tokio::test]
async fn test_idle_timeout_allows_reuse_within_timeout() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder()
        .idle_timeout(Duration::from_secs(30))
        .build();

    for _ in 0..3 {
        let resp = client.get(&url).unwrap().send().await.unwrap();
        assert!(resp.is_success());
    }

    // All three rapid sequential requests must share pooled connections:
    // without reuse this would be 3 accepted connections.
    assert!(
        server.connections_accepted() <= 2,
        "expected connection reuse within the idle timeout, got {} accepted",
        server.connections_accepted()
    );

    server.shutdown();
}

/// The Hyper pool timer evicts idle connections in the background, without
/// waiting for the next checkout.
///
/// `pool_idle_timeout` alone only discards expired entries lazily when the
/// next request checks one out; the installed `pool_timer` is what closes an
/// idle socket proactively. This test issues a single request and then polls
/// the server-side open-connection gauge: it must drop to zero with no
/// second request involved.
#[tokio::test]
async fn test_idle_timer_evicts_connection_in_background() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder()
        .idle_timeout(Duration::from_millis(100))
        .build();

    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert!(resp.is_success());
    drop(resp);
    assert_eq!(server.connections_accepted(), 1);
    assert_eq!(server.open_connections(), 1);

    // Hyper clamps its proactive idle check to at least ~90 ms, so poll
    // with a generous deadline rather than asserting an exact schedule.
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    loop {
        if server.open_connections() == 0 {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "idle connection was not evicted in the background; still open"
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    server.shutdown();
}

/// Multiple sequential requests to the same server reuse connections.
#[tokio::test]
async fn test_connection_reuse_same_host() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder().build();

    // First request establishes the connection.
    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert!(resp.is_success());
    tokio::task::yield_now().await;

    let after_first = server.connections_accepted();
    assert!(
        after_first >= 1,
        "at least 1 connection after first request"
    );

    // Subsequent requests should reuse the connection.
    for _ in 0..5 {
        let resp = client.get(&url).unwrap().send().await.unwrap();
        assert!(resp.is_success());
        tokio::task::yield_now().await;
    }

    let after_all = server.connections_accepted();
    // Connections may increase during initial setup on CI due to timing.
    // Allow up to 6 new connections (1 original + 5 requests could each
    // potentially open a new connection under heavy CI load).
    assert!(
        after_all <= after_first + 6,
        "expected reuse: {after_first} -> {after_all}"
    );

    server.shutdown();
}

/// With `max_connections=1`, the second request must wait for the first.
#[tokio::test]
async fn test_acquisition_wait() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 150,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().max_connections(1).build();

    let start = std::time::Instant::now();

    let h1 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };
    let h2 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };

    let mut r1 = h1.await.unwrap().unwrap();
    assert!(r1.is_success());
    // Consume the body so the pool permit is released; the lease on the
    // response body holds the permit until the body is consumed or
    // dropped. After consuming, the second request can acquire it.
    let _ = r1.bytes().await;
    drop(r1);

    let mut r2 = h2.await.unwrap().unwrap();
    assert!(r2.is_success());
    let _ = r2.bytes().await;
    drop(r2);

    // With max_connections=1 and a 150ms delay per request, two sequential
    // requests should take at least 250ms (accounting for timing jitter).
    let elapsed = start.elapsed();
    assert!(
        elapsed >= Duration::from_millis(250),
        "expected serialization delay, elapsed {elapsed:?}"
    );

    // The pool should have recorded at least one acquisition wait.
    let metrics = client.pool_metrics();
    assert!(
        metrics.acquisition_waits.load(Ordering::SeqCst) >= 1,
        "expected at least 1 acquisition wait"
    );

    server.shutdown();
}

/// With `max_connections=2`, three concurrent requests show bounded concurrency.
#[tokio::test]
async fn test_max_connections_bounds_three() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 300,
        ..Default::default()
    });
    let url = server.url();

    let max_conn: usize = 2;
    let client = Client::builder().max_connections(max_conn).build();

    let start = std::time::Instant::now();

    let mut handles = Vec::new();
    for _ in 0..3 {
        let client = client.clone();
        let url = url.clone();
        handles.push(tokio::spawn(async move {
            client.get(&url).unwrap().send().await.unwrap();
        }));
    }

    for h in handles {
        h.await.unwrap();
    }

    let elapsed = start.elapsed();

    // With max_connections=2 and 300ms delay, 3 requests need 2 batches:
    // 2 concurrent + 1 sequential = ~600ms minimum.
    let min_expected = Duration::from_millis(450);
    assert!(
        elapsed >= min_expected,
        "expected at least {min_expected:?} with max_connections={max_conn}, elapsed {elapsed:?}"
    );

    server.shutdown();
}

/// Test that requests fail gracefully when the server is not running.
#[tokio::test]
async fn test_connection_refused() {
    let client = Client::builder().build();
    let result = client.get("http://127.0.0.1:1").unwrap().send().await;
    assert!(result.is_err());
}

/// Test sending a POST request with a body to the test server.
#[tokio::test]
async fn test_post_with_body() {
    let mut server = TestServer::start(&TestServerConfig {
        consume_body: true,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().build();
    let resp = client
        .post(&url)
        .unwrap()
        .header("Content-Type", "text/plain")
        .body("hello")
        .send()
        .await
        .unwrap();
    assert!(resp.is_success());

    server.shutdown();
}

/// Pool metrics track acquisition waits correctly.
#[tokio::test]
async fn test_pool_metrics_waits() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 100,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().max_connections(1).build();

    let start = std::time::Instant::now();

    // Fire two concurrent requests with max_connections=1.
    let h1 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };
    let h2 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };

    let mut r1 = h1.await.unwrap().unwrap();
    assert!(r1.is_success());
    // Consume r1's body to release the pool permit; the lease holds
    // the permit until the body is dropped or consumed.
    let _ = r1.bytes().await;
    drop(r1);

    let mut r2 = h2.await.unwrap().unwrap();
    assert!(r2.is_success());
    let _ = r2.bytes().await;
    drop(r2);

    let elapsed = start.elapsed();
    assert!(
        elapsed >= Duration::from_millis(150),
        "expected serialization, elapsed {elapsed:?}"
    );

    let metrics = client.pool_metrics();
    assert!(
        metrics.acquisition_waits.load(Ordering::SeqCst) >= 1,
        "expected at least 1 acquisition wait"
    );

    server.shutdown();
}

/// Idle connections are closed after the configured idle timeout.
///
/// After the first request completes, the connection goes idle. If we wait
/// longer than `idle_timeout`, the pool should close it, and the next request
/// opens a fresh connection.
#[tokio::test]
async fn test_idle_timeout_closes_stale_connection() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder()
        .idle_timeout(Duration::from_millis(100))
        .build();

    // First request opens a connection.
    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert!(resp.is_success());
    assert_eq!(server.connections_accepted(), 1);

    // Wait for the idle timeout to expire.
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Second request: the old connection should have been evicted by the pool,
    // so a new TCP connection is accepted.
    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert!(resp.is_success());
    assert!(
        server.connections_accepted() >= 2,
        "expected at least 2 connections after idle timeout, got {}",
        server.connections_accepted()
    );

    server.shutdown();
}

/// A cached route-specific client (SNI override) obeys the same idle policy
/// as the standard path.
///
/// The SNI route previously received the idle timeout but no per-host cap;
/// both now resolve from the same `Pool` helpers. Two SNI requests separated
/// by more than the idle timeout must open a second server-side connection
/// while still succeeding through the one cached route client.
#[tokio::test]
async fn test_sni_cached_client_obeys_idle_policy() {
    use eggfetch_core::TransportHints;

    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder()
        .idle_timeout(Duration::from_millis(100))
        .build();

    let sni_hints = || TransportHints {
        sni_hostname: Some("sni-idle.test".to_owned()),
        ..Default::default()
    };

    let resp = client
        .get(&url)
        .unwrap()
        .transport_hints(sni_hints())
        .send()
        .await
        .unwrap();
    assert!(resp.is_success());
    drop(resp);
    assert_eq!(server.connections_accepted(), 1);

    // Materially beyond the configured idle timeout (Hyper clamps its
    // proactive check to ~90 ms, so 300 ms leaves generous margin).
    tokio::time::sleep(Duration::from_millis(300)).await;

    let resp = client
        .get(&url)
        .unwrap()
        .transport_hints(sni_hints())
        .send()
        .await
        .unwrap();
    assert!(resp.is_success());
    assert!(
        server.connections_accepted() >= 2,
        "expected the SNI route to reconnect after idle timeout, got {}",
        server.connections_accepted()
    );

    server.shutdown();
}

/// The effective per-host idle cap reaches Hyper: a zero cap disables idle
/// retention, so sequential requests each open a fresh connection.
///
/// Both the per-host name and its `max_idle_connections` fallback feed the
/// same resolved policy (`Pool::max_idle_per_host`), so both spellings are
/// exercised at the wire level; precedence itself is pinned by unit tests in
/// `src/pool.rs`.
#[tokio::test]
async fn test_idle_per_host_cap_zero_disables_reuse() {
    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder().max_idle_connections_per_host(0).build();
    for _ in 0..3 {
        let resp = client.get(&url).unwrap().send().await.unwrap();
        assert!(resp.is_success());
    }
    assert_eq!(
        server.connections_accepted(),
        3,
        "zero per-host idle cap must prevent reuse, got {}",
        server.connections_accepted()
    );
    server.shutdown();

    let mut server = TestServer::start(&TestServerConfig::default());
    let url = server.url();

    let client = Client::builder().max_idle_connections(0).build();
    for _ in 0..2 {
        let resp = client.get(&url).unwrap().send().await.unwrap();
        assert!(resp.is_success());
    }
    assert_eq!(
        server.connections_accepted(),
        2,
        "zero fallback idle cap must prevent reuse, got {}",
        server.connections_accepted()
    );
    server.shutdown();
}

/// Cancelling a waiting acquisition is safe and releases the waiter cleanly.
///
/// With `max_connections=1`, the first request holds the slot. A second request
/// starts waiting. We cancel it, then drop the first. The third request
/// should succeed without deadlock.
#[tokio::test]
async fn test_cancelled_waiter_releases_cleanly() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 50,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().max_connections(1).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(20)).await;

    // Second request starts waiting for the slot.
    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(20)).await;

    // Cancel the waiter by aborting the task.
    h2.abort();
    // Wait for abort to propagate.
    tokio::time::sleep(Duration::from_millis(10)).await;

    // First request completes; consume its body to release the lease,
    // then drop the response so the pool permit is freed.
    let mut r1 = h1.await.unwrap().unwrap();
    assert!(r1.is_success());
    let _ = r1.bytes().await;
    drop(r1);

    // Third request should succeed — no deadlock from the cancelled waiter.
    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert!(resp.is_success());

    server.shutdown();
}

/// The pool permit must be held by the response body until the body is
/// fully consumed or dropped. A streaming response that is held but not
/// consumed must block subsequent requests that need the same slot.
#[tokio::test]
async fn test_streaming_response_holds_permit_until_consumed() {
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 100,
        ..Default::default()
    });
    let url = server.url();

    let client = Client::builder().max_connections(1).build();

    // First request: hold the response body without consuming it.
    let mut resp1 = client.get(&url).unwrap().send().await.unwrap();
    let body_stream = resp1.bytes_stream().unwrap();

    // Second request with same slot count must wait until the first
    // body is consumed or dropped.
    let start = std::time::Instant::now();
    let h2 = {
        let client = client.clone();
        let url = url.clone();
        tokio::spawn(async move { client.get(&url).unwrap().send().await })
    };
    // Allow the waiter to actually start blocking.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    assert!(
        !h2.is_finished(),
        "second request should be waiting for the permit"
    );

    // Drop the streaming body, releasing the permit.
    drop(body_stream);
    drop(resp1);

    let resp2 = h2.await.unwrap().unwrap();
    let elapsed = start.elapsed();
    assert!(
        elapsed >= std::time::Duration::from_millis(40),
        "second request should have waited, only {elapsed:?}"
    );
    assert!(resp2.is_success());

    server.shutdown();
}

/// When a waiter is queued for a per-host permit and another task
/// releases its permit, the per-origin semaphore entry must not be
/// evicted while the waiter is still in the acquire queue.  Previously
/// the entry's `available_permits() == max` predicate could fire during
/// the wait, evicting the entry and orphaning the waiter's `Arc`.  The
/// orphan's permit returns to a semaphore no longer in the table,
/// silently leaking capacity and (under churn) eventually bypassing the
/// per-host limit.  The fix adds an `Arc::strong_count > 1` guard to
/// `retain` so the entry stays as long as the waiter holds a clone.
#[tokio::test]
async fn per_origin_eviction_skips_entries_with_active_waiter() {
    use eggfetch_core::{Client, Limits};

    // `max_connections_per_host = 1` bounds the per-host semaphore so
    // the second in-flight request to the same origin must wait.
    let client = Client::builder()
        .limits(Limits {
            max_connections_per_host: Some(1),
            ..Default::default()
        })
        .build();

    // A slow server that delays the response keeps the first permit
    // held long enough for the second request to queue.
    let mut server = TestServer::start(&TestServerConfig {
        response_delay_ms: 100,
        ..Default::default()
    });

    // First request acquires the (only) per-host permit.
    let url = server.url();
    let req1 = client.get(&url).unwrap().send();
    // Let the first request reach the server and acquire the permit.
    tokio::time::sleep(Duration::from_millis(20)).await;
    let req2 = client.get(&url).unwrap().send();

    // Both requests resolve; if the per-host entry was evicted while
    // `req2` was queued on the orphaned semaphore, the orphan's permit
    // would return to a removed entry and `req2` would either hang or
    // fail.  With the fix, req2 completes normally.
    let resp1 = req1.await.unwrap();
    // Drop resp1 (and its body) to release the per-host permit, then
    // await req2 which has been waiting in the per-host queue.
    drop(resp1);
    let resp2 = req2.await.unwrap();
    assert!(resp2.is_success());

    server.shutdown();
}