specters 4.2.2

Rust HTTP client with browser-like Chrome and Firefox fingerprints across TLS, HTTP/1.1, HTTP/2, HTTP/3, and WebSockets
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
//! Connection pool for HTTP/2 and HTTP/3 multiplexing
//!
//! This module provides connection pooling with support for:
//! - HTTP/1.1: One connection per request (no pooling)
//! - HTTP/2: Connection reuse with stream multiplexing
//! - HTTP/3: QUIC connection reuse with stream multiplexing

use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing;

use crate::error::Result;
use crate::fingerprint::FingerprintProfile;
use crate::transport::connector::MaybeHttpsStream;
use crate::transport::h2::PseudoHeaderOrder;
use crate::version::HttpVersion;

/// Connection pool key identifying a unique host/port combination with fingerprint settings
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct PoolKey {
    pub host: String,
    pub port: u16,
    pub is_https: bool,
    pub fingerprint: FingerprintProfile,
    pub pseudo_order: PseudoHeaderOrder,
}

impl PoolKey {
    /// Create a new pool key
    pub fn new(
        host: String,
        port: u16,
        is_https: bool,
        fingerprint: FingerprintProfile,
        pseudo_order: PseudoHeaderOrder,
    ) -> Self {
        Self {
            host,
            port,
            is_https,
            fingerprint,
            pseudo_order,
        }
    }

    pub fn origin_key(&self) -> OriginKey {
        OriginKey {
            host: self.host.clone(),
            port: self.port,
            is_https: self.is_https,
        }
    }
}

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct OriginKey {
    pub host: String,
    pub port: u16,
    pub is_https: bool,
}

#[derive(Debug, Clone)]
pub struct OriginFairQueue<K = PoolKey> {
    order: VecDeque<OriginKey>,
    queues: HashMap<OriginKey, VecDeque<K>>,
    len: usize,
}

impl<K> Default for OriginFairQueue<K> {
    fn default() -> Self {
        Self {
            order: VecDeque::new(),
            queues: HashMap::new(),
            len: 0,
        }
    }
}

impl<K> OriginFairQueue<K> {
    pub fn push_with_origin(&mut self, origin: OriginKey, key: K) {
        let queue = self.queues.entry(origin.clone()).or_default();
        if queue.is_empty() {
            self.order.push_back(origin);
        }
        queue.push_back(key);
        self.len += 1;
    }

    pub fn pop_next(&mut self) -> Option<K> {
        while let Some(origin) = self.order.pop_front() {
            let Some((key, has_more)) = self.pop_origin_front(&origin) else {
                continue;
            };
            if has_more {
                self.order.push_back(origin);
            } else {
                self.queues.remove(&origin);
            }
            self.len = self.len.saturating_sub(1);
            return Some(key);
        }
        None
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    fn pop_origin_front(&mut self, origin: &OriginKey) -> Option<(K, bool)> {
        let queue = self.queues.get_mut(origin)?;
        let key = queue.pop_front()?;
        Some((key, !queue.is_empty()))
    }
}

impl OriginFairQueue<PoolKey> {
    pub fn push(&mut self, key: PoolKey) {
        let origin = key.origin_key();
        self.push_with_origin(origin, key);
    }
}

/// Pool entry for HTTP/1.1 connections
#[derive(Debug)]
pub struct H1PoolEntry {
    pub stream: MaybeHttpsStream,
    pub last_used: Instant,
}

impl H1PoolEntry {
    pub fn new(stream: MaybeHttpsStream) -> Self {
        Self {
            stream,
            last_used: Instant::now(),
        }
    }

    pub fn is_expired(&self, max_idle: Duration) -> bool {
        self.last_used.elapsed() >= max_idle
    }
}

/// Pool entry tracking connection state and stream usage
#[derive(Debug, Clone)]
pub struct PoolEntry {
    pub version: HttpVersion,
    pub established_at: Instant,
    pub last_used: Instant,
    /// Number of active streams (for HTTP/2 and HTTP/3)
    pub active_streams: u32,
    /// Maximum concurrent streams (from SETTINGS for HTTP/2)
    pub max_streams: u32,
    /// Connection is still valid
    pub is_valid: bool,
}

impl PoolEntry {
    /// Create a new pool entry
    pub fn new(version: HttpVersion, max_streams: u32) -> Self {
        let now = Instant::now();
        Self {
            version,
            established_at: now,
            last_used: now,
            active_streams: 0,
            max_streams,
            is_valid: true,
        }
    }

    /// Check if this connection can handle another multiplexed stream
    pub fn can_multiplex(&self) -> bool {
        matches!(
            self.version,
            HttpVersion::Http2 | HttpVersion::Http3 | HttpVersion::Http3Only
        ) && self.active_streams < self.max_streams
            && self.is_valid
    }

    /// Attempt to acquire a stream slot
    pub fn acquire_stream(&mut self) -> bool {
        if self.can_multiplex() {
            self.active_streams += 1;
            self.last_used = Instant::now();
            true
        } else {
            false
        }
    }

    /// Release a stream slot
    pub fn release_stream(&mut self) {
        if self.active_streams > 0 {
            self.active_streams -= 1;
            self.last_used = Instant::now();
        }
    }

    /// Mark connection as invalid (connection error, GOAWAY frame, etc.)
    pub fn invalidate(&mut self) {
        self.is_valid = false;
    }

    /// Check if connection is expired based on idle time
    pub fn is_expired(&self, max_idle: Duration) -> bool {
        let age = Instant::now().duration_since(self.last_used);
        age >= max_idle
    }
}

/// Connection pool for reusing HTTP/1.1, HTTP/2, and HTTP/3 connections
pub struct ConnectionPool {
    entries: Arc<RwLock<HashMap<PoolKey, PoolEntry>>>,
    h1_idle: Arc<RwLock<HashMap<PoolKey, Vec<H1PoolEntry>>>>,
    max_idle_duration: Duration,
    #[allow(dead_code)] // Reserved for future connection limiting per host
    max_connections_per_host: usize,
    default_max_streams: u32,
}

impl ConnectionPool {
    /// Default maximum idle duration (30 seconds)
    const DEFAULT_MAX_IDLE: Duration = Duration::from_secs(30);

    /// Default maximum connections per host
    const DEFAULT_MAX_PER_HOST: usize = 6;

    /// Default maximum concurrent streams for HTTP/2 and HTTP/3
    const DEFAULT_MAX_STREAMS: u32 = 100;

    /// Create a new connection pool with default settings
    pub fn new() -> Self {
        Self {
            entries: Arc::new(RwLock::new(HashMap::new())),
            h1_idle: Arc::new(RwLock::new(HashMap::new())),
            max_idle_duration: Self::DEFAULT_MAX_IDLE,
            max_connections_per_host: Self::DEFAULT_MAX_PER_HOST,
            default_max_streams: Self::DEFAULT_MAX_STREAMS,
        }
    }

    /// Create a connection pool with custom configuration
    pub fn with_config(max_idle: Duration, max_per_host: usize, max_streams: u32) -> Self {
        Self {
            entries: Arc::new(RwLock::new(HashMap::new())),
            h1_idle: Arc::new(RwLock::new(HashMap::new())),
            max_idle_duration: max_idle,
            max_connections_per_host: max_per_host,
            default_max_streams: max_streams,
        }
    }

    /// Get an idle HTTP/1.1 connection from the pool
    pub async fn get_h1(&self, key: &PoolKey) -> Option<MaybeHttpsStream> {
        let start = Instant::now();
        let mut pool = self.h1_idle.write().await;
        if let Some(entries) = pool.get_mut(key) {
            tracing::debug!("H1 Pool: {} entries for key {:?}", entries.len(), key);
            let initial_count = entries.len();
            while let Some(entry) = entries.pop() {
                if !entry.is_expired(self.max_idle_duration) {
                    tracing::debug!(
                        "H1 Pool: Reusing connection for {:?} (checked {} entries, took {:?})",
                        key,
                        initial_count - entries.len(),
                        start.elapsed()
                    );
                    return Some(entry.stream);
                }
                tracing::debug!(
                    "H1 Pool: Connection expired for {:?} (age: {:?})",
                    key,
                    entry.last_used.elapsed()
                );
            }
        } else {
            tracing::debug!("H1 Pool: No entries for key {:?}", key);
        }
        tracing::debug!(
            "H1 Pool: No reusable connection found for {:?} (took {:?})",
            key,
            start.elapsed()
        );
        None
    }

    /// Return an HTTP/1.1 connection to the pool
    pub async fn put_h1(&self, key: PoolKey, stream: MaybeHttpsStream) {
        if self.max_connections_per_host == 0 {
            return;
        }
        let start = Instant::now();
        tracing::debug!("H1 Pool: Returning connection for {:?}", key);
        let mut pool = self.h1_idle.write().await;
        let entries = pool.entry(key.clone()).or_default();
        let count_before = entries.len();
        while entries.len() >= self.max_connections_per_host {
            entries.remove(0);
        }
        entries.push(H1PoolEntry::new(stream));
        tracing::debug!(
            "H1 Pool: Returned connection for {:?} (pool size: {} -> {}, took {:?})",
            key,
            count_before,
            entries.len(),
            start.elapsed()
        );
    }

    /// Try to return an HTTP/1.1 connection to the pool without awaiting.
    ///
    /// This is used by poll-based response bodies, where parking the caller on
    /// an async pool lock would couple body EOF to an unrelated task wake. If
    /// the pool lock is temporarily unavailable, the connection is safely
    /// discarded instead of being returned late or through a spawned shim.
    pub fn try_put_h1(&self, key: PoolKey, stream: MaybeHttpsStream) -> bool {
        if self.max_connections_per_host == 0 {
            return false;
        }
        let Ok(mut pool) = self.h1_idle.try_write() else {
            return false;
        };
        let entries = pool.entry(key).or_default();
        while entries.len() >= self.max_connections_per_host {
            entries.remove(0);
        }
        entries.push(H1PoolEntry::new(stream));
        true
    }

    /// Get an existing connection or signal that a new one should be created
    ///
    /// Returns:
    /// - `Ok(Some(entry))`: Reusable connection found (HTTP/2 or HTTP/3)
    /// - `Ok(None)`: No reusable connection, create new one
    pub async fn get_or_create(
        &self,
        key: &PoolKey,
        version: HttpVersion,
    ) -> Result<Option<PoolEntry>> {
        let start = Instant::now();
        let mut entries = self.entries.write().await;

        // HTTP/1.1 doesn't support multiplexing in this map - managed via get_h1/put_h1
        if version == HttpVersion::Http1_1 {
            return Ok(None);
        }

        // Check for existing valid connection with available stream slots
        if let Some(entry) = entries.get_mut(key) {
            let active_before = entry.active_streams;
            if entry.acquire_stream() {
                tracing::debug!(
                    "H2/H3 Pool: Reusing connection for {:?} (active streams: {} -> {}, took {:?})",
                    key,
                    active_before,
                    entry.active_streams,
                    start.elapsed()
                );
                return Ok(Some(entry.clone()));
            } else {
                tracing::debug!(
                    "H2/H3 Pool: Connection exists for {:?} but cannot multiplex (active: {}/{}, valid: {}, took {:?})",
                    key,
                    active_before,
                    entry.max_streams,
                    entry.is_valid,
                    start.elapsed()
                );
            }
        } else {
            tracing::debug!("H2/H3 Pool: No existing connection for {:?}", key);
        }

        // No reusable connection found - create new entry
        tracing::debug!(
            "H2/H3 Pool: Creating new connection entry for {:?} (took {:?})",
            key,
            start.elapsed()
        );
        let entry = PoolEntry::new(version, self.default_max_streams);
        entries.insert(key.clone(), entry.clone());

        Ok(Some(entry))
    }

    /// Release a stream slot back to the pool
    pub async fn release(&self, key: &PoolKey) {
        let mut entries = self.entries.write().await;
        if let Some(entry) = entries.get_mut(key) {
            let active_before = entry.active_streams;
            entry.release_stream();
            tracing::debug!(
                "H2/H3 Pool: Released stream for {:?} (active streams: {} -> {})",
                key,
                active_before,
                entry.active_streams
            );
        } else {
            tracing::warn!(
                "H2/H3 Pool: Attempted to release stream for non-existent connection {:?}",
                key
            );
        }
    }

    /// Invalidate a connection (due to error, GOAWAY, etc.)
    pub async fn invalidate(&self, key: &PoolKey) {
        let mut entries = self.entries.write().await;
        if let Some(entry) = entries.get_mut(key) {
            entry.invalidate();
        }
    }

    /// Remove expired and invalid connections
    pub async fn cleanup(&self) {
        // Cleanup H2/H3 entries
        {
            let mut entries = self.entries.write().await;
            entries
                .retain(|_key, entry| entry.is_valid && !entry.is_expired(self.max_idle_duration));
        }

        // Cleanup H1 entries
        {
            let mut h1_pool = self.h1_idle.write().await;
            for entries in h1_pool.values_mut() {
                entries.retain(|e| !e.is_expired(self.max_idle_duration));
            }
            h1_pool.retain(|_, entries| !entries.is_empty());
        }
    }

    /// Spawn a background cleanup task that runs periodically
    ///
    /// Returns a handle to the spawned task
    pub fn spawn_cleanup_task(self: Arc<Self>, interval: Duration) -> tokio::task::JoinHandle<()> {
        tokio::spawn(async move {
            let mut interval_timer = tokio::time::interval(interval);
            loop {
                interval_timer.tick().await;
                self.cleanup().await;
            }
        })
    }

    /// Get current pool statistics (for debugging/monitoring)
    pub async fn stats(&self) -> PoolStats {
        let entries = self.entries.read().await;
        let h1_pool = self.h1_idle.read().await;

        let h1_idle_count = h1_pool.values().map(|v| v.len()).sum();

        PoolStats {
            total_connections: entries.len() + h1_idle_count,
            active_streams: entries.values().map(|e| e.active_streams).sum(),
            http2_connections: entries
                .values()
                .filter(|e| matches!(e.version, HttpVersion::Http2))
                .count(),
            http3_connections: entries
                .values()
                .filter(|e| matches!(e.version, HttpVersion::Http3 | HttpVersion::Http3Only))
                .count(),
            http1_idle_connections: h1_idle_count,
        }
    }
}

impl Default for ConnectionPool {
    fn default() -> Self {
        Self::new()
    }
}

/// Pool statistics for monitoring
#[derive(Debug, Clone)]
pub struct PoolStats {
    pub total_connections: usize,
    pub active_streams: u32,
    pub http2_connections: usize,
    pub http3_connections: usize,
    pub http1_idle_connections: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pool_key_equality() {
        let key1 = PoolKey::new(
            "example.com".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );
        let key2 = PoolKey::new(
            "example.com".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );
        let key3 = PoolKey::new(
            "example.com".to_string(),
            80,
            false,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );

        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_pool_entry_multiplexing() {
        let mut entry = PoolEntry::new(HttpVersion::Http2, 100);

        // Should be able to acquire streams
        assert!(entry.can_multiplex());
        assert!(entry.acquire_stream());
        assert_eq!(entry.active_streams, 1);

        // Release stream
        entry.release_stream();
        assert_eq!(entry.active_streams, 0);
    }

    #[test]
    fn test_pool_entry_max_streams() {
        let mut entry = PoolEntry::new(HttpVersion::Http2, 2);

        assert!(entry.acquire_stream());
        assert!(entry.acquire_stream());
        assert!(!entry.acquire_stream()); // Max reached
        assert_eq!(entry.active_streams, 2);
    }

    #[test]
    fn test_pool_entry_invalidation() {
        let mut entry = PoolEntry::new(HttpVersion::Http2, 100);

        assert!(entry.can_multiplex());
        entry.invalidate();
        assert!(!entry.can_multiplex());
    }

    #[test]
    fn test_pool_entry_expiration() {
        let entry = PoolEntry::new(HttpVersion::Http2, 100);

        // Should not be expired immediately
        assert!(!entry.is_expired(Duration::from_secs(30)));

        // Test with zero duration (always expired)
        assert!(entry.is_expired(Duration::from_secs(0)));
    }

    #[tokio::test]
    async fn test_connection_pool_http11() {
        let pool = ConnectionPool::new();
        let key = PoolKey::new(
            "example.com".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );

        // HTTP/1.1 should always return None (no pooling)
        let result = pool
            .get_or_create(&key, HttpVersion::Http1_1)
            .await
            .unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_connection_pool_http2_multiplexing() {
        let pool = ConnectionPool::new();
        let key = PoolKey::new(
            "example.com".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );

        // First request creates connection
        let entry1 = pool.get_or_create(&key, HttpVersion::Http2).await.unwrap();
        assert!(entry1.is_some());

        // Second request should reuse connection
        let entry2 = pool.get_or_create(&key, HttpVersion::Http2).await.unwrap();
        assert!(entry2.is_some());

        // Verify stats
        let stats = pool.stats().await;
        assert_eq!(stats.total_connections, 1);
        assert_eq!(stats.http2_connections, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_release() {
        let pool = ConnectionPool::new();
        let key = PoolKey::new(
            "example.com".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );

        let _entry = pool.get_or_create(&key, HttpVersion::Http2).await.unwrap();

        // Release stream
        pool.release(&key).await;

        let stats = pool.stats().await;
        assert_eq!(stats.total_connections, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_invalidation() {
        let pool = ConnectionPool::new();
        let key = PoolKey::new(
            "example.com".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );

        let _entry = pool.get_or_create(&key, HttpVersion::Http2).await.unwrap();

        // Invalidate connection
        pool.invalidate(&key).await;

        // Cleanup should remove invalid connection
        pool.cleanup().await;

        let stats = pool.stats().await;
        assert_eq!(stats.total_connections, 0);
    }

    #[test]
    fn origin_fair_queue_rotates_ready_origins_before_same_origin_reuse() {
        let alpha_chrome = PoolKey::new(
            "alpha.example".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );
        let alpha_firefox = PoolKey::new(
            "alpha.example".to_string(),
            443,
            true,
            FingerprintProfile::Firefox142,
            PseudoHeaderOrder::Firefox,
        );
        let beta_chrome = PoolKey::new(
            "beta.example".to_string(),
            443,
            true,
            FingerprintProfile::Chrome142,
            PseudoHeaderOrder::Chrome,
        );
        let mut queue = OriginFairQueue::default();

        queue.push(alpha_chrome.clone());
        queue.push(alpha_firefox.clone());
        queue.push(beta_chrome.clone());

        assert_eq!(queue.pop_next(), Some(alpha_chrome));
        assert_eq!(
            queue.pop_next(),
            Some(beta_chrome),
            "pool-level scheduling must give another ready origin a turn before reusing alpha"
        );
        assert_eq!(queue.pop_next(), Some(alpha_firefox));
        assert!(queue.is_empty());
    }
}