aria2-core 0.3.5

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
//! HTTP connection manager
//!
//! Provides connection pool reuse, Keep-Alive management, LRU eviction,
//! idle timeout, and redirect following.
//!
//! # LRU Eviction
//!
//! Per-key idle connections live in a `VecDeque`: front = oldest (evicted
//! first), back = newest. Mirrors C++ `socketPool_` multimap ordering.

use std::collections::{HashMap, HashSet, VecDeque};
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;

use tokio::net::TcpStream;
use tokio::time::timeout;
use url::Url;

use aria2_protocol::http::response::is_redirect_status;

use crate::error::{Aria2Error, RecoverableError, Result};
use crate::http::cookie_storage::{CookieJar, CookieStorage};

use super::active_connection::{ActiveConnection, ConnectionPoolKey, ProxyInfo};
use super::types::{HttpConfig, HttpResponse};
use crate::network::ConnectionContext;

/// HTTP connection manager
///
/// Provides connection acquisition, release, pool management, and redirect
/// following. Supports Keep-Alive reuse, LRU eviction, per-key idle limits,
/// and circular redirect detection.
pub struct HttpConnectionManager {
    config: HttpConfig,
    /// Idle connection pool: conn_id -> ActiveConnection.
    /// Only contains connections that are idle (released back via `put_back`).
    pool: HashMap<u64, ActiveConnection>,
    /// Per-key LRU index of idle connections.
    /// VecDeque front = oldest idle, back = newest idle.
    /// Only contains conn_ids for connections currently in `pool`.
    key_connections: HashMap<ConnectionPoolKey, VecDeque<u64>>,
    /// Total live connection count (idle in pool + in-use by callers)
    active_count: usize,
    /// Connection ID generator
    id_counter: AtomicU64,
    /// Maximum redirect hops
    max_redirects: u32,
    /// Shared canonical cookie storage used by production download paths.
    cookie_storage: Option<std::sync::Arc<CookieStorage>>,
    /// Legacy URL/API adapter retained for compatibility.
    cookie_jar: Option<CookieJar>,
}

impl HttpConnectionManager {
    /// Create a new HTTP connection manager
    pub fn new(config: &HttpConfig) -> Self {
        Self {
            config: config.clone(),
            pool: HashMap::new(),
            key_connections: HashMap::new(),
            active_count: 0,
            id_counter: AtomicU64::new(1),
            max_redirects: crate::constants::HTTP_DEFAULT_MAX_REDIRECTS as u32,
            cookie_storage: None,
            cookie_jar: None,
        }
    }

    // ==================== Accessors ====================

    /// Maximum concurrent connections configuration
    pub fn max_connections(&self) -> usize {
        self.config.max_connections
    }

    /// Current total live connection count (idle + in-use)
    pub fn active_count(&self) -> usize {
        self.active_count
    }

    /// Current idle connection pool size
    pub fn pool_size(&self) -> usize {
        self.pool.len()
    }

    /// Number of idle connections for a specific pool key
    pub fn idle_count_for_key(&self, key: &ConnectionPoolKey) -> usize {
        self.key_connections.get(key).map_or(0, |dq| dq.len())
    }

    /// Maximum idle connections per host configuration
    pub fn max_idle_per_host(&self) -> usize {
        self.config.max_idle_per_host
    }

    // ==================== Pool Operations (mirrors C++ API) ====================

    /// Acquire a connection — reuse idle or create new.
    ///
    /// Mirrors C++ `popPooledSocket()` + new connection creation.
    /// On reuse, the oldest valid idle connection is returned (LRU front).
    pub async fn acquire(
        &mut self,
        url: &Url,
        proxy: Option<&ProxyInfo>,
    ) -> Result<ActiveConnection> {
        let host = Self::extract_host(url);
        let pool_key = ConnectionPoolKey {
            target: format!(
                "{scheme}://{host}:{port}",
                scheme = url.scheme(),
                host = host,
                port = url.port_or_known_default().unwrap_or(80)
            ),
            proxy: proxy.cloned(),
        };

        // Try to reuse an idle connection from the pool
        if let Some(conn) = self.pop_pooled_connection(&pool_key)? {
            tracing::debug!("Reused connection: id={}, key={:?}", conn.id, pool_key);
            return Ok(conn);
        }

        // Check if max connection limit has been reached
        if self.active_count >= self.config.max_connections {
            // Try to evict expired connections to free slots
            self.check_timeout();

            if self.active_count >= self.config.max_connections {
                return Err(Aria2Error::Recoverable(
                    RecoverableError::TemporaryNetworkFailure {
                        message: format!(
                            "Max connection limit reached: {} (key={:?})",
                            self.config.max_connections, pool_key
                        ),
                    },
                ));
            }
        }

        // Create a new connection
        self.create_new_connection(url, &host, pool_key).await
    }

    /// Return a connection to the idle pool (mirrors C++ `putBack()`).
    ///
    /// Takes ownership of the connection. It goes to the back of the LRU
    /// deque (newest). If per-key idle count exceeds `max_idle_per_host`,
    /// the oldest is evicted first. Invalid connections are discarded.
    pub async fn put_back(&mut self, mut conn: ActiveConnection) {
        if !conn.is_valid() {
            tracing::debug!("Connection no longer valid on put_back: id={}", conn.id);
            self.active_count = self.active_count.saturating_sub(1);
            return;
        }

        let conn_id = conn.id;
        let pool_key = conn.pool_key.clone();

        // Mark as idle and place in pool
        conn.mark_pooled();
        self.pool.insert(conn_id, conn);

        // Add to back of LRU deque (newest idle)
        self.key_connections
            .entry(pool_key.clone())
            .or_default()
            .push_back(conn_id);

        // Enforce per-key idle limit (evict oldest = front of deque)
        self.enforce_idle_limit(&pool_key).await;

        tracing::debug!(
            "Put back connection to pool: id={}, key={:?}",
            conn_id,
            pool_key
        );
    }

    /// Legacy alias for `put_back()`.
    pub async fn release(&mut self, conn: ActiveConnection) {
        self.put_back(conn).await
    }

    /// Drop an in-use connection after a network failure.
    ///
    /// This deliberately does not evict DNS state: the caller must decide
    /// whether the peer was an origin address or a proxy address.
    pub async fn discard(&mut self, mut conn: ActiveConnection) {
        self.active_count = self.active_count.saturating_sub(1);
        let _ = conn.shutdown().await;
    }

    /// Evict idle origin connections matching a concrete connection context.
    /// Proxy connections are not matched because their peer is the proxy.
    pub async fn evict_peer(&mut self, context: &ConnectionContext) -> usize {
        let ids: Vec<u64> = self
            .pool
            .iter()
            .filter_map(|(id, conn)| {
                (!conn.is_proxied() && conn.connection_context() == context).then_some(*id)
            })
            .collect();
        let mut evicted = 0;
        for id in ids {
            if let Some(mut conn) = self.pool.remove(&id) {
                self.remove_from_key_deque(&conn.pool_key, id);
                let _ = conn.shutdown().await;
                self.active_count = self.active_count.saturating_sub(1);
                evicted += 1;
            }
        }
        evicted
    }

    /// Retrieve a pooled idle connection for a specific key without creating new.
    ///
    /// Mirrors C++ `popPooledSocket()`. Returns `None` if no valid idle
    /// connection exists for the given key.
    pub fn get_connection(
        &mut self,
        pool_key: &ConnectionPoolKey,
    ) -> Result<Option<ActiveConnection>> {
        self.pop_pooled_connection(pool_key)
    }

    /// Evict all idle connections that exceeded the idle timeout.
    ///
    /// Mirrors C++ `evictSocketPool()`. Call periodically.
    /// Returns the number of connections evicted.
    pub fn check_timeout(&mut self) -> usize {
        if self.pool.is_empty() {
            return 0;
        }

        let idle_timeout = self.config.idle_timeout;
        let mut evicted_keys: Vec<(u64, ConnectionPoolKey)> = Vec::new();

        for (&conn_id, conn) in &self.pool {
            if conn.is_idle_timeout(idle_timeout) {
                evicted_keys.push((conn_id, conn.pool_key.clone()));
            }
        }

        let count = evicted_keys.len();
        for (conn_id, pool_key) in evicted_keys {
            if let Some(mut conn) = self.pool.remove(&conn_id) {
                tracing::debug!(
                    "Evicted idle-timeout connection: id={}, idle={:.2}s",
                    conn_id,
                    conn.pooled_at.map_or(0.0, |t| t.elapsed().as_secs_f64())
                );
                std::mem::drop(conn.shutdown());
                self.active_count = self.active_count.saturating_sub(1);
                self.remove_from_key_deque(&pool_key, conn_id);
            }
        }

        if count > 0 {
            tracing::info!("Evicted {} idle-timeout connections", count);
        }
        count
    }

    /// Close all idle connections (mirrors C++ `releaseAll()`).
    ///
    /// Active (in-use) connections are NOT affected.
    pub async fn release_all(&mut self) {
        let count = self.pool.len();
        for (_, mut conn) in self.pool.drain() {
            let _ = conn.shutdown().await;
        }
        self.key_connections.clear();
        self.active_count = self.active_count.saturating_sub(count);

        if count > 0 {
            tracing::info!("Released all {} idle connections", count);
        }
    }

    /// Full cleanup — close all connections and reset state.
    pub async fn cleanup(&mut self) {
        for (_, mut conn) in self.pool.drain() {
            let _ = conn.shutdown().await;
        }
        self.key_connections.clear();
        self.active_count = 0;
        tracing::info!("Connection pool cleaned up");
    }

    /// Force close a specific connection by ID.
    pub async fn close_connection(&mut self, conn_id: u64) {
        if let Some(mut conn) = self.pool.remove(&conn_id) {
            let pool_key = conn.pool_key.clone();
            let _ = conn.shutdown().await;
            self.active_count = self.active_count.saturating_sub(1);
            self.remove_from_key_deque(&pool_key, conn_id);
            tracing::debug!("Force closed connection: id={}", conn_id);
        }
    }

    // ==================== Redirect Following ====================

    /// Follow HTTP redirects with circular detection.
    pub fn follow_redirects(
        &self,
        response: &HttpResponse,
        current_url: &Url,
        redirect_chain: &HashSet<Url>,
        redirect_count: u32,
    ) -> Result<Url> {
        if !is_redirect_status(response.status_code) {
            return Err(Aria2Error::Parse(format!(
                "Non-redirect response code: {}",
                response.status_code
            )));
        }
        if redirect_count >= self.max_redirects {
            return Err(Aria2Error::Network(format!(
                "Max redirect count exceeded: {}",
                self.max_redirects
            )));
        }
        let location = response
            .location()
            .ok_or_else(|| Aria2Error::Parse("Missing Location header".to_string()))?;
        let new_url = current_url
            .join(location)
            .map_err(|e| Aria2Error::Parse(format!("Failed to parse redirect URL: {}", e)))?;
        if redirect_chain.contains(&new_url) {
            return Err(Aria2Error::Network(format!(
                "Circular redirect detected: {}",
                new_url
            )));
        }
        tracing::info!(
            "Following redirect: {} -> {} ({}/{})",
            current_url,
            new_url,
            redirect_count + 1,
            self.max_redirects
        );
        Ok(new_url)
    }

    /// Iteratively follow HTTP redirects with loop detection.
    pub async fn follow_redirects_iterative<F, Fut>(
        &self,
        initial_url: &Url,
        mut get_response: F,
    ) -> Result<HttpResponse>
    where
        F: FnMut(&Url) -> Fut,
        Fut: std::future::Future<Output = Result<HttpResponse>>,
    {
        const MAX_REDIRECTS: u8 = crate::constants::HTTP_DEFAULT_MAX_REDIRECTS as u8;
        let mut current_url = initial_url.clone();
        let mut seen_urls = HashSet::<String>::new();

        for iteration in 0..MAX_REDIRECTS {
            let url_str = current_url.to_string();
            if !seen_urls.insert(url_str.clone()) {
                return Err(Aria2Error::Network(format!(
                    "Redirect loop detected: {}",
                    url_str
                )));
            }
            let resp = get_response(&current_url).await?;
            if !is_redirect_status(resp.status_code) {
                return Ok(resp);
            }
            let location = resp.location().ok_or_else(|| {
                Aria2Error::Network("Missing Location header in redirect response".into())
            })?;
            current_url = current_url
                .join(location)
                .map_err(|e| Aria2Error::Parse(format!("Failed to parse redirect URL: {}", e)))?;
            tracing::info!(
                "Following redirect: iteration {}/{}",
                iteration + 1,
                MAX_REDIRECTS
            );
        }

        Err(Aria2Error::Network(format!(
            "Too many redirects (>{}), last URL: {}",
            MAX_REDIRECTS, current_url
        )))
    }

    // ==================== Range Headers ====================

    /// Build a Range request header per RFC 7233.
    pub fn build_range_header(&self, start: u64, end: Option<u64>) -> String {
        match end {
            Some(e) => format!("bytes={}-{}", start, e),
            None => format!("bytes={}-", start),
        }
    }

    /// Parse Content-Range response header. Returns `(start, end, total)`.
    pub fn parse_content_range(&self, header: &str) -> Option<(u64, u64, u64)> {
        let header = header.trim();
        let range = header
            .strip_prefix("bytes ")
            .or_else(|| header.strip_prefix("bytes="))
            .unwrap_or(header);
        let (range, total) = range.split_once('/')?;
        let (start, end) = range.split_once('-')?;
        let start = start.trim().parse::<u64>().ok()?;
        let end = end.trim().parse::<u64>().ok()?;
        if start > end {
            return None;
        }
        let total = match total.trim() {
            "*" => u64::MAX,
            value => value.parse().ok()?,
        };
        if total != u64::MAX && end >= total {
            return None;
        }
        Some((start, end, total))
    }

    // ==================== Cookie Jar Integration ====================

    /// Set the canonical shared cookie storage for automatic HTTP handling.
    pub fn set_cookie_storage(&mut self, storage: Option<std::sync::Arc<CookieStorage>>) {
        self.cookie_storage = storage;
    }

    /// Construct a manager already bound to the process-wide cookie storage.
    pub fn with_shared_cookie_storage(config: &HttpConfig) -> Self {
        let mut manager = Self::new(config);
        manager.set_cookie_storage(Some(CookieStorage::shared()));
        manager
    }

    /// Set the cookie jar for automatic cookie management.
    pub fn set_cookie_jar(&mut self, jar: Option<CookieJar>) {
        self.cookie_jar = jar;
    }

    /// Get a reference to the current cookie jar.
    pub fn cookie_jar(&self) -> &Option<CookieJar> {
        &self.cookie_jar
    }

    /// Get a mutable reference to the current cookie jar.
    pub fn cookie_jar_mut(&mut self) -> &mut Option<CookieJar> {
        &mut self.cookie_jar
    }

    /// Attach matching cookies from the jar to an HTTP request.
    pub fn attach_cookies_to_request(&self, url: &Url) -> Option<String> {
        let is_https = url.scheme() == "https";
        if let Some(storage) = &self.cookie_storage {
            let header =
                storage.to_header_string(url.host_str().unwrap_or_default(), url.path(), is_https);
            if !header.is_empty() {
                return Some(header);
            }
        }
        let jar = self.cookie_jar.as_ref()?;
        jar.cookie_header_for_url(url.as_str(), is_https)
    }

    /// Extract cookies from response Set-Cookie headers and store in the jar.
    pub fn extract_cookies_from_response(
        &mut self,
        response_headers: &[(String, String)],
        _request_url: &Url,
    ) -> usize {
        let mut stored = 0;
        if let Some(storage) = &self.cookie_storage {
            for (name, value) in response_headers {
                if name.eq_ignore_ascii_case("set-cookie")
                    && storage.parse_and_store(
                        value,
                        _request_url.host_str().unwrap_or_default(),
                        _request_url.path(),
                    )
                {
                    stored += 1;
                }
            }
            return stored;
        }
        let jar = match &mut self.cookie_jar {
            Some(j) => j,
            None => return 0,
        };
        for (name, value) in response_headers {
            if name.eq_ignore_ascii_case("set-cookie")
                && let Some(cookie) = crate::http::cookie::JarCookie::parse_set_cookie(value)
            {
                jar.store(cookie);
                stored += 1;
                tracing::debug!(
                    "Extracted cookie from Set-Cookie: {}",
                    &value[..value.len().min(80)]
                );
            }
        }
        stored
    }

    // ==================== Private Helpers ====================

    /// Extract host identifier from URL (host:port)
    pub(super) fn extract_host(url: &Url) -> String {
        match url.port_or_known_default() {
            Some(port) => format!(
                "{}:{}",
                url.host_str().unwrap_or(crate::constants::DEFAULT_HOST),
                port
            ),
            None => url
                .host_str()
                .unwrap_or(crate::constants::DEFAULT_HOST)
                .to_string(),
        }
    }

    /// Pop the oldest valid idle connection for the key.
    /// Matches C++ `findSocketPoolEntry()`. Skips timed-out/invalid.
    fn pop_pooled_connection(
        &mut self,
        pool_key: &ConnectionPoolKey,
    ) -> Result<Option<ActiveConnection>> {
        let deque = match self.key_connections.get_mut(pool_key) {
            Some(dq) => dq,
            None => return Ok(None),
        };

        // Walk from front (oldest) to find first valid, non-expired connection
        let mut candidate_ids: Vec<u64> = Vec::new();
        while let Some(&conn_id) = deque.front() {
            candidate_ids.push(conn_id);
            deque.pop_front();

            if let Some(mut conn) = self.pool.remove(&conn_id) {
                if conn.is_valid() && !conn.is_idle_timeout(self.config.idle_timeout) {
                    // Valid connection — mark as in-use and return
                    conn.mark_in_use();
                    conn.touch();

                    tracing::debug!(
                        "Reused idle connection: id={}, idle={:.2}s",
                        conn_id,
                        conn.pooled_at.map_or(0.0, |t| t.elapsed().as_secs_f64())
                    );
                    return Ok(Some(conn));
                } else {
                    // Expired or invalid — discard
                    let reason = if !conn.is_valid() {
                        "invalid"
                    } else {
                        "timed-out"
                    };
                    tracing::debug!("Discarded {} idle connection: id={}", reason, conn_id);
                    std::mem::drop(conn.shutdown());
                    self.active_count = self.active_count.saturating_sub(1);
                }
            }
            // Connection not in pool (shouldn't happen) — just skip
        }

        // All candidates were invalid/expired; deque is now empty
        if deque.is_empty() {
            self.key_connections.remove(pool_key);
        }

        Ok(None)
    }

    /// Create a new TCP connection.
    async fn create_new_connection(
        &mut self,
        url: &Url,
        host: &str,
        pool_key: ConnectionPoolKey,
    ) -> Result<ActiveConnection> {
        let addresses = Self::resolve_addresses(url).await?;
        let mut last_error = None;
        let mut connected = None;
        for addr in &addresses {
            match timeout(self.config.connect_timeout, TcpStream::connect(addr)).await {
                Ok(Ok(stream)) => {
                    connected = Some((stream, *addr));
                    break;
                }
                Ok(Err(error)) => last_error = Some(format!("{}: {}", addr, error)),
                Err(_) => last_error = Some(format!("{}: connection timeout", addr)),
            }
        }
        let (stream, _addr) = connected.ok_or_else(|| {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!(
                    "TCP connection failed for {}: {}",
                    host,
                    last_error.unwrap_or_else(|| "no addresses".to_string())
                ),
            })
        })?;

        if let Err(e) = stream.set_nodelay(true) {
            tracing::warn!("Failed to set nodelay: {}", e);
        }

        let conn_id = self.id_counter.fetch_add(1, Ordering::SeqCst);

        let conn = ActiveConnection {
            id: conn_id,
            connection: ConnectionContext::new(
                host,
                url.port_or_known_default().unwrap_or(80),
                stream.peer_addr().map_err(|e| {
                    Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                        message: format!("peer address unavailable: {e}"),
                    })
                })?,
            ),
            stream,
            host: host.to_string(),
            last_used: Instant::now(),
            pooled_at: None, // In use, not idle
            pool_key: pool_key.clone(),
        };

        self.active_count += 1;
        // Do NOT add to key_connections — connection is in use, not idle

        tracing::info!(
            "Created new connection: id={}, host={}, active={}/{}",
            conn_id,
            host,
            self.active_count,
            self.config.max_connections
        );

        Ok(conn)
    }

    /// Resolve a URL to all currently available socket addresses.
    async fn resolve_addresses(url: &Url) -> Result<Vec<SocketAddr>> {
        let host = url
            .host_str()
            .ok_or_else(|| Aria2Error::Parse("URL missing hostname".to_string()))?;
        let port = url
            .port_or_known_default()
            .ok_or_else(|| Aria2Error::Parse("Unable to determine port number".to_string()))?;
        let host_port = format!("{}:{}", host, port);
        tokio::net::lookup_host(&host_port)
            .await
            .map(|addresses| addresses.collect())
            .map_err(|error| Aria2Error::Parse(format!("Failed to resolve address: {}", error)))
    }

    /// Enforce per-key idle limit by evicting oldest (front of deque).
    async fn enforce_idle_limit(&mut self, pool_key: &ConnectionPoolKey) {
        let max_idle = self.config.max_idle_per_host;
        if max_idle == 0 {
            return; // 0 = unlimited
        }

        while self.idle_count_for_key(pool_key) > max_idle {
            let evict_id = match self.key_connections.get_mut(pool_key) {
                Some(dq) => match dq.pop_front() {
                    Some(id) => id,
                    None => break,
                },
                None => break,
            };

            if let Some(mut conn) = self.pool.remove(&evict_id) {
                tracing::debug!(
                    "LRU evicted oldest idle connection: id={}, key={:?} (limit={})",
                    evict_id,
                    pool_key,
                    max_idle
                );
                let _ = conn.shutdown().await;
                self.active_count = self.active_count.saturating_sub(1);
            }
        }

        // Clean up empty deque entry
        if self.idle_count_for_key(pool_key) == 0 {
            self.key_connections.remove(pool_key);
        }
    }

    /// Remove a conn_id from the key's LRU deque. O(n) but deque is small.
    fn remove_from_key_deque(&mut self, pool_key: &ConnectionPoolKey, conn_id: u64) {
        if let Some(dq) = self.key_connections.get_mut(pool_key) {
            dq.retain(|&id| id != conn_id);
            if dq.is_empty() {
                self.key_connections.remove(pool_key);
            }
        }
    }
}

impl Drop for HttpConnectionManager {
    fn drop(&mut self) {
        for (_, conn) in self.pool.drain() {
            drop(conn);
        }
        self.key_connections.clear();
    }
}

impl std::fmt::Debug for HttpConnectionManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpConnectionManager")
            .field("max_connections", &self.config.max_connections)
            .field("connect_timeout", &self.config.connect_timeout)
            .field("read_timeout", &self.config.read_timeout)
            .field("write_timeout", &self.config.write_timeout)
            .field("idle_timeout", &self.config.idle_timeout)
            .field("max_idle_per_host", &self.config.max_idle_per_host)
            .field("active_count", &self.active_count)
            .field("pool_size", &self.pool.len())
            .field("cookie_storage_set", &self.cookie_storage.is_some())
            .field("cookie_jar_set", &self.cookie_jar.is_some())
            .finish()
    }
}