fetchium-core 1.0.0

Fetchium core library — search, extract, rank, validate, cache
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
//! HTTP client with connection pooling, retries, rate limiting, and size limits.
//!
//! PRD SS14: Domain-aware scheduler with per-domain concurrency caps.
//! PRD SS44: Structured errors with retry info.

use crate::config::FetchiumConfig;
use crate::error::{ErrorKind, FetchiumError, FetchiumResult, StructuredError};
use crate::proxy::{DataImpulseClient, ProxyPool};
use dashmap::DashMap;
use reqwest::{Client, StatusCode};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::time::sleep;
use tracing::{debug, info};
use url::Url;

/// Maximum retry attempts for transient errors.
const MAX_RETRIES: u32 = 3;
/// Base delay for exponential backoff (milliseconds).
const BASE_DELAY_MS: u64 = 500;
/// Maximum backoff delay cap (30 seconds) to prevent excessive waits.
const MAX_BACKOFF_MS: u64 = 30_000;
/// Maximum response body size (10 MB).
const _MAX_BODY_SIZE: u64 = 10 * 1024 * 1024;

/// Per-domain rate limit state.
#[derive(Debug)]
struct DomainState {
    last_request: Instant,
    min_delay: Duration,
}

/// Domains that are blocked hard enough to justify the expensive residential path.
/// API-based backends (Serper, Exa, Tavily, Gemini) are NOT in this list.
/// Everything else should use the cheaper fixed proxy pool or direct traffic.
const RESIDENTIAL_REQUIRED_DOMAINS: &[&str] = &["google.com", "www.google.com"];

/// Shared HTTP client with connection pooling, retries, and rate limiting.
#[derive(Clone)]
pub struct HttpClient {
    inner: Client,
    config: Arc<FetchiumConfig>,
    /// Per-domain rate limiting state.
    domain_delays: Arc<DashMap<String, DomainState>>,
    /// Optional Webshare proxy pool (datacenter — legacy fallback).
    proxy_pool: Option<ProxyPool>,
    /// DataImpulse residential proxy client (country-targeted, pay-per-GB).
    dataimpulse: Option<DataImpulseClient>,
}

/// Fetch result with metadata about the request.
#[derive(Debug)]
pub struct FetchResult {
    pub body: String,
    pub status: u16,
    pub content_type: String,
    pub content_length: Option<u64>,
    pub url: String,
    pub elapsed_ms: u64,
    pub retries: u32,
}

impl HttpClient {
    /// Create a new HTTP client from config.
    pub fn new(config: &FetchiumConfig) -> FetchiumResult<Self> {
        let client = Client::builder()
            .user_agent(&config.fetch.user_agent)
            .timeout(Duration::from_secs(config.fetch.timeout_secs))
            .connect_timeout(Duration::from_secs(10))
            .redirect(reqwest::redirect::Policy::limited(
                config.fetch.max_redirects as usize,
            ))
            .gzip(true)
            .brotli(true)
            .pool_max_idle_per_host(100)
            .pool_idle_timeout(Duration::from_secs(90))
            .build()
            .map_err(FetchiumError::Network)?;

        // Load proxy pool if configured
        let proxy_pool = if config.proxy.enabled {
            let proxy_file = config
                .proxy
                .proxy_file
                .clone()
                .unwrap_or_else(|| config.data_dir().join("proxies.txt"));
            if proxy_file.exists() {
                match ProxyPool::load_from_file(&proxy_file) {
                    Ok(pool) if !pool.is_empty() => {
                        info!(
                            "Proxy pool loaded: {} proxies from {}",
                            pool.len(),
                            proxy_file.display()
                        );
                        Some(pool)
                    }
                    Ok(_) => {
                        tracing::warn!("Proxy file is empty: {}", proxy_file.display());
                        None
                    }
                    Err(e) => {
                        tracing::warn!("Failed to load proxy file {}: {e}", proxy_file.display());
                        None
                    }
                }
            } else {
                tracing::warn!("Proxy file not found: {}", proxy_file.display());
                None
            }
        } else {
            None
        };

        // Build DataImpulse residential proxy client if configured
        let dataimpulse = if config.dataimpulse.enabled && !config.dataimpulse.username.is_empty() {
            let di = DataImpulseClient::new(
                &config.dataimpulse.username,
                &config.dataimpulse.password,
                &config.dataimpulse.host,
                config.dataimpulse.port,
                &config.fetch.user_agent,
                Duration::from_secs(config.fetch.timeout_secs),
            );
            info!(
                "DataImpulse residential proxy enabled ({}:{})",
                config.dataimpulse.host, config.dataimpulse.port
            );
            Some(di)
        } else {
            None
        };

        Ok(Self {
            inner: client,
            config: Arc::new(config.clone()),
            domain_delays: Arc::new(DashMap::new()),
            proxy_pool,
            dataimpulse,
        })
    }

    /// Get the inner reqwest client for direct use.
    pub fn client(&self) -> &Client {
        &self.inner
    }

    /// Get a reqwest client for a specific domain.
    ///
    /// Priority order:
    /// 1. DataImpulse residential proxy (country-targeted) — Google only
    /// 2. Direct connection — default path for everything else
    ///
    /// Cheap path by default: non-Google traffic stays direct until a backend
    /// explicitly asks for proxy escalation.
    pub fn client_for_domain_with_locale(&self, domain: &str, locale: Option<&str>) -> Client {
        let needs_residential = self.needs_residential_proxy(domain);

        // Google uses residential immediately.
        if needs_residential {
            if let Some(ref di) = self.dataimpulse {
                if di.is_configured() {
                    debug!("DataImpulse residential proxy for {domain} locale={locale:?}");
                    return di.client(locale);
                }
            }
        }

        // Everyone else uses the cheapest path first.
        self.inner.clone()
    }

    /// Backwards-compatible wrapper — no locale hint.
    pub fn client_for_domain(&self, domain: &str) -> Client {
        self.client_for_domain_with_locale(domain, None)
    }

    /// Direct client — bypasses ALL proxy routing (residential and datacenter).
    ///
    /// Use for first-attempt requests where proxy is not yet needed.
    /// If the direct attempt fails, escalate to `client_for_domain_with_locale`.
    /// Saves DataImpulse GB when direct connections succeed (majority of requests).
    pub fn client_direct(&self) -> Client {
        self.inner.clone()
    }

    /// Get a forced proxy client for a domain.
    ///
    /// Google uses residential. All other proxy-eligible domains use the fixed
    /// proxy pool. Falls back to direct when no proxy is available.
    pub fn proxy_client_for_domain_with_locale(
        &self,
        domain: &str,
        locale: Option<&str>,
    ) -> Client {
        if self.needs_residential_proxy(domain) {
            if let Some(ref di) = self.dataimpulse {
                if di.is_configured() {
                    return di.client(locale);
                }
            }
            return self.inner.clone();
        }

        if let Some(ref pool) = self.proxy_pool {
            if self.should_proxy_domain(domain) {
                if let Some(proxy) = pool.proxy_for_domain(domain) {
                    if let Ok(client) = ProxyPool::build_client_with_proxy(
                        &proxy,
                        &self.config.fetch.user_agent,
                        Duration::from_secs(self.config.fetch.timeout_secs),
                    ) {
                        return client;
                    }
                }
            }
        }

        self.inner.clone()
    }

    /// Get a **fresh** client that forces a new residential IP on the next request.
    ///
    /// Use when a previous request was blocked (CAPTCHA, 403, empty SERP).
    /// The fresh client has no connection pool, so DataImpulse assigns a new
    /// residential IP. Falls back to `client_for_domain_with_locale` if not residential.
    pub fn fresh_client_for_domain_with_locale(
        &self,
        domain: &str,
        locale: Option<&str>,
    ) -> Client {
        if self.needs_residential_proxy(domain) {
            if let Some(ref di) = self.dataimpulse {
                if di.is_configured() {
                    return di.fresh_client(locale);
                }
            }
        }
        // Non-residential: force a new datacenter proxy assignment on retry if possible.
        if let Some(ref pool) = self.proxy_pool {
            if self.should_proxy_domain(domain) {
                if let Some(proxy) = pool.fresh_proxy_for_domain(domain) {
                    if let Ok(client) = ProxyPool::build_client_with_proxy(
                        &proxy,
                        &self.config.fetch.user_agent,
                        Duration::from_secs(self.config.fetch.timeout_secs),
                    ) {
                        return client;
                    }
                }
            }
        }

        // Fall back to the normal path (direct).
        self.client_for_domain_with_locale(domain, locale)
    }

    /// Whether a domain requires residential IPs to avoid blocks.
    fn needs_residential_proxy(&self, domain: &str) -> bool {
        // Check user-configured override list first
        if !self.config.dataimpulse.proxy_domains.is_empty() {
            return self
                .config
                .dataimpulse
                .proxy_domains
                .iter()
                .any(|d| domain.ends_with(d.as_str()) || domain == d.as_str());
        }
        // Built-in list of search engines blocked by datacenter IPs
        RESIDENTIAL_REQUIRED_DOMAINS
            .iter()
            .any(|&d| domain == d || domain.ends_with(&format!(".{d}")))
    }

    /// Get the config reference.
    pub fn config(&self) -> &FetchiumConfig {
        &self.config
    }

    /// Extract domain from a URL for rate limiting.
    pub fn extract_domain(url: &str) -> String {
        Url::parse(url)
            .map(|u| u.host_str().unwrap_or("unknown").to_string())
            .unwrap_or_else(|_| "unknown".to_string())
    }

    /// Wait if needed to respect per-domain rate limits.
    async fn enforce_rate_limit(&self, domain: &str) {
        let min_delay = Duration::from_millis(200);
        if let Some(state) = self.domain_delays.get(domain) {
            let elapsed = state.last_request.elapsed();
            if elapsed < state.min_delay {
                let wait = state.min_delay - elapsed;
                debug!("Rate limiting {domain}: waiting {wait:?}");
                sleep(wait).await;
            }
        }
        self.domain_delays.insert(
            domain.to_string(),
            DomainState {
                last_request: Instant::now(),
                min_delay,
            },
        );
    }

    /// Calculate backoff delay with jitter for retry attempt.
    /// Capped at MAX_BACKOFF_MS to prevent excessive waits on high retry counts.
    fn backoff_delay(attempt: u32) -> Duration {
        let base = BASE_DELAY_MS.saturating_mul(2u64.saturating_pow(attempt));
        let jitter = (std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .subsec_nanos()
            % 500) as u64;
        Duration::from_millis(base.saturating_add(jitter).min(MAX_BACKOFF_MS))
    }

    /// Whether a status code is retryable.
    fn is_retryable_status(status: StatusCode) -> bool {
        matches!(
            status,
            StatusCode::TOO_MANY_REQUESTS
                | StatusCode::INTERNAL_SERVER_ERROR
                | StatusCode::BAD_GATEWAY
                | StatusCode::SERVICE_UNAVAILABLE
                | StatusCode::GATEWAY_TIMEOUT
        )
    }

    /// Map an HTTP status to a structured error kind.
    fn status_to_error_kind(status: StatusCode) -> ErrorKind {
        match status {
            StatusCode::FORBIDDEN => ErrorKind::Http403,
            StatusCode::TOO_MANY_REQUESTS => ErrorKind::Http429,
            s if s.is_server_error() => ErrorKind::Http5xx,
            _ => ErrorKind::Unknown,
        }
    }

    /// Fetch a URL with retries, rate limiting, and size enforcement.
    /// Returns the response body as a string along with metadata.
    pub async fn fetch(&self, url: &str) -> FetchiumResult<FetchResult> {
        let domain = Self::extract_domain(url);
        let start = Instant::now();
        let max_size = self.config.fetch.max_page_size;
        let mut last_err: Option<FetchiumError> = None;

        for attempt in 0..=MAX_RETRIES {
            if attempt > 0 {
                let delay = Self::backoff_delay(attempt - 1);
                debug!("Retry {attempt}/{MAX_RETRIES} for {url} after {delay:?}");
                sleep(delay).await;
            }

            self.enforce_rate_limit(&domain).await;

            let result = self.inner.get(url).send().await;

            match result {
                Ok(resp) => {
                    let status = resp.status();

                    if !status.is_success() {
                        if Self::is_retryable_status(status) && attempt < MAX_RETRIES {
                            debug!("Retryable status {status} for {url} (attempt {attempt}/{MAX_RETRIES})");
                            last_err = Some(FetchiumError::Structured(StructuredError {
                                kind: Self::status_to_error_kind(status),
                                retryable: true,
                                message: format!("HTTP {status} from {url}"),
                                source_url: Some(url.to_string()),
                                suggested_action: "Retry with backoff".into(),
                                alternatives: vec![],
                            }));
                            continue;
                        }

                        return Err(FetchiumError::Structured(StructuredError {
                            kind: Self::status_to_error_kind(status),
                            retryable: false,
                            message: format!("HTTP {status} from {url}"),
                            source_url: Some(url.to_string()),
                            suggested_action: match status {
                                StatusCode::FORBIDDEN => "Site blocks automated access".into(),
                                StatusCode::TOO_MANY_REQUESTS => "Rate limited, try later".into(),
                                _ => "Check URL and try again".into(),
                            },
                            alternatives: vec![],
                        }));
                    }

                    let content_length = resp.content_length();
                    if let Some(len) = content_length {
                        if len > max_size {
                            return Err(FetchiumError::Structured(StructuredError {
                                kind: ErrorKind::ExtractionFailed,
                                retryable: false,
                                message: format!(
                                    "Response too large: {len} bytes (max {max_size})"
                                ),
                                source_url: Some(url.to_string()),
                                suggested_action: "Increase max_page_size in config".into(),
                                alternatives: vec![],
                            }));
                        }
                    }

                    let content_type = resp
                        .headers()
                        .get("content-type")
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or("text/html")
                        .to_string();

                    let final_url = resp.url().to_string();

                    let body = resp.text().await.map_err(FetchiumError::Network)?;

                    if body.len() as u64 > max_size {
                        return Err(FetchiumError::Structured(StructuredError {
                            kind: ErrorKind::ExtractionFailed,
                            retryable: false,
                            message: format!("Body too large: {} bytes", body.len()),
                            source_url: Some(url.to_string()),
                            suggested_action: "Increase max_page_size".into(),
                            alternatives: vec![],
                        }));
                    }

                    return Ok(FetchResult {
                        body,
                        status: status.as_u16(),
                        content_type,
                        content_length,
                        url: final_url,
                        elapsed_ms: start.elapsed().as_millis() as u64,
                        retries: attempt,
                    });
                }
                Err(e) => {
                    if (e.is_timeout() || e.is_connect()) && attempt < MAX_RETRIES {
                        debug!("Transient error for {url}: {e}");
                        last_err = Some(FetchiumError::Network(e));
                        continue;
                    }
                    return Err(FetchiumError::Network(e));
                }
            }
        }

        Err(last_err.unwrap_or_else(|| {
            FetchiumError::Structured(StructuredError {
                kind: ErrorKind::NetworkTimeout,
                retryable: false,
                message: format!("All {MAX_RETRIES} retries exhausted for {url}"),
                source_url: Some(url.to_string()),
                suggested_action: "Check network connectivity".into(),
                alternatives: vec![],
            })
        }))
    }

    /// Convenience: fetch a URL and return just the body text.
    pub async fn fetch_text(&self, url: &str) -> FetchiumResult<String> {
        let result = self.fetch(url).await?;
        Ok(result.body)
    }

    /// Get the proxy pool (if configured).
    pub fn proxy_pool(&self) -> Option<&ProxyPool> {
        self.proxy_pool.as_ref()
    }

    /// Check if a domain should use proxies.
    fn should_proxy_domain(&self, domain: &str) -> bool {
        // Never proxy bypass domains
        if self
            .config
            .proxy
            .bypass_domains
            .iter()
            .any(|d| domain.contains(d.as_str()))
        {
            return false;
        }
        // If proxy_domains is specified, only proxy those
        if !self.config.proxy.proxy_domains.is_empty() {
            return self
                .config
                .proxy
                .proxy_domains
                .iter()
                .any(|d| domain.contains(d.as_str()));
        }
        // Default: proxy everything
        true
    }

    /// Fetch a URL through a rotating proxy. Falls back to direct if no proxy available.
    pub async fn fetch_via_proxy(&self, url: &str) -> FetchiumResult<FetchResult> {
        let domain = Self::extract_domain(url);

        let pool = match &self.proxy_pool {
            Some(p) if !p.is_empty() && self.should_proxy_domain(&domain) => p,
            _ => return self.fetch(url).await,
        };

        let proxy = match pool.proxy_for_domain(&domain) {
            Some(p) => p,
            None => {
                debug!("No available proxy for {domain}, falling back to direct");
                return self.fetch(url).await;
            }
        };

        let start = Instant::now();
        let client = ProxyPool::build_client_with_proxy(
            &proxy,
            &self.config.fetch.user_agent,
            Duration::from_secs(self.config.fetch.timeout_secs),
        )
        .map_err(FetchiumError::Network)?;

        match client.get(url).send().await {
            Ok(resp) => {
                let status = resp.status();
                let latency = start.elapsed().as_millis() as u64;

                if status.is_success() {
                    proxy.record_success(latency);
                    let content_type = resp
                        .headers()
                        .get("content-type")
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or("text/html")
                        .to_string();
                    let content_length = resp.content_length();
                    let final_url = resp.url().to_string();
                    let body = resp.text().await.map_err(FetchiumError::Network)?;

                    Ok(FetchResult {
                        body,
                        status: status.as_u16(),
                        content_type,
                        content_length,
                        url: final_url,
                        elapsed_ms: latency,
                        retries: 0,
                    })
                } else if status == StatusCode::FORBIDDEN || status == StatusCode::TOO_MANY_REQUESTS
                {
                    // Proxy got blocked — record failure and retry with next proxy
                    proxy.record_failure();
                    debug!(
                        "Proxy {}:{} blocked (HTTP {}) for {domain}, trying next",
                        proxy.host, proxy.port, status
                    );
                    // One retry with a different proxy
                    if let Some(next_proxy) = pool.next_proxy() {
                        let client2 = ProxyPool::build_client_with_proxy(
                            &next_proxy,
                            &self.config.fetch.user_agent,
                            Duration::from_secs(self.config.fetch.timeout_secs),
                        )
                        .map_err(FetchiumError::Network)?;

                        let start2 = Instant::now();
                        match client2.get(url).send().await {
                            Ok(resp2) if resp2.status().is_success() => {
                                next_proxy.record_success(start2.elapsed().as_millis() as u64);
                                let body = resp2.text().await.map_err(FetchiumError::Network)?;
                                Ok(FetchResult {
                                    body,
                                    status: 200,
                                    content_type: "text/html".into(),
                                    content_length: None,
                                    url: url.to_string(),
                                    elapsed_ms: start.elapsed().as_millis() as u64,
                                    retries: 1,
                                })
                            }
                            _ => {
                                next_proxy.record_failure();
                                self.fetch(url).await // fall back to direct
                            }
                        }
                    } else {
                        self.fetch(url).await
                    }
                } else {
                    proxy.record_failure();
                    Err(FetchiumError::Structured(StructuredError {
                        kind: Self::status_to_error_kind(status),
                        retryable: false,
                        message: format!("HTTP {status} via proxy for {url}"),
                        source_url: Some(url.to_string()),
                        suggested_action: "Try different proxy or direct".into(),
                        alternatives: vec![],
                    }))
                }
            }
            Err(e) => {
                proxy.record_failure();
                debug!(
                    "Proxy {}:{} connection failed for {domain}: {e}",
                    proxy.host, proxy.port
                );
                // Fall back to direct connection
                self.fetch(url).await
            }
        }
    }

    /// Convenience: fetch text through a proxy.
    pub async fn fetch_text_via_proxy(&self, url: &str) -> FetchiumResult<String> {
        let result = self.fetch_via_proxy(url).await?;
        Ok(result.body)
    }

    /// Single-shot fetch — no retries, no rate limiting.
    ///
    /// Use this for sources where connection errors are *expected* (e.g. third-party
    /// Piped/Invidious instances that may be down). A single fast attempt is better
    /// than burning 3.5s on retry sleeps when we're racing many sources in parallel.
    pub async fn fetch_text_once(&self, url: &str) -> FetchiumResult<String> {
        let resp = self
            .inner
            .get(url)
            .send()
            .await
            .map_err(FetchiumError::Network)?;

        if !resp.status().is_success() {
            return Err(FetchiumError::Structured(crate::error::StructuredError {
                kind: Self::status_to_error_kind(resp.status()),
                retryable: false,
                message: format!("HTTP {} from {url}", resp.status()),
                source_url: Some(url.to_string()),
                suggested_action: "Source unavailable".into(),
                alternatives: vec![],
            }));
        }

        resp.text().await.map_err(FetchiumError::Network)
    }

    /// Single-shot POST — no retries, no rate limiting.
    ///
    /// Like `fetch_text_once` but sends a JSON POST body. Used for YouTube Innertube
    /// API calls where each call is time-sensitive and retries are not desired.
    pub async fn post_json_once(&self, url: &str, body: String) -> FetchiumResult<String> {
        let resp = self
            .inner
            .post(url)
            .header("Content-Type", "application/json")
            .body(body)
            .send()
            .await
            .map_err(FetchiumError::Network)?;

        if !resp.status().is_success() {
            return Err(FetchiumError::Structured(crate::error::StructuredError {
                kind: Self::status_to_error_kind(resp.status()),
                retryable: false,
                message: format!("HTTP {} from {url}", resp.status()),
                source_url: Some(url.to_string()),
                suggested_action: "Source unavailable".into(),
                alternatives: vec![],
            }));
        }

        resp.text().await.map_err(FetchiumError::Network)
    }

    /// POST JSON with retry support (uses the standard retry/rate-limit pipeline).
    pub async fn post_json(&self, url: &str, body: &str) -> FetchiumResult<String> {
        let resp = self
            .inner
            .post(url)
            .header("Content-Type", "application/json")
            .body(body.to_string())
            .send()
            .await
            .map_err(FetchiumError::Network)?;

        if !resp.status().is_success() {
            return Err(FetchiumError::Structured(crate::error::StructuredError {
                kind: Self::status_to_error_kind(resp.status()),
                retryable: resp.status().is_server_error(),
                message: format!("HTTP {} from {url}", resp.status()),
                source_url: Some(url.to_string()),
                suggested_action: "Check API key and request format".into(),
                alternatives: vec![],
            }));
        }

        resp.text().await.map_err(FetchiumError::Network)
    }

    /// POST JSON with a custom header (e.g., API key in non-standard header).
    pub async fn post_json_with_header(
        &self,
        url: &str,
        body: &str,
        header_name: &str,
        header_value: &str,
    ) -> FetchiumResult<String> {
        let resp = self
            .inner
            .post(url)
            .header("Content-Type", "application/json")
            .header(header_name, header_value)
            .body(body.to_string())
            .send()
            .await
            .map_err(FetchiumError::Network)?;

        if !resp.status().is_success() {
            return Err(FetchiumError::Structured(crate::error::StructuredError {
                kind: Self::status_to_error_kind(resp.status()),
                retryable: resp.status().is_server_error(),
                message: format!("HTTP {} from {url}", resp.status()),
                source_url: Some(url.to_string()),
                suggested_action: "Check API key and request format".into(),
                alternatives: vec![],
            }));
        }

        resp.text().await.map_err(FetchiumError::Network)
    }
}

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

    #[test]
    fn client_creation() {
        let config = FetchiumConfig::default();
        let client = HttpClient::new(&config);
        assert!(client.is_ok());
    }

    #[test]
    fn domain_extraction() {
        assert_eq!(
            HttpClient::extract_domain("https://www.example.com/page"),
            "www.example.com"
        );
        assert_eq!(
            HttpClient::extract_domain("http://localhost:8080/api"),
            "localhost"
        );
        assert_eq!(HttpClient::extract_domain("not-a-url"), "unknown");
    }

    #[test]
    fn backoff_delay_increases() {
        let d0 = HttpClient::backoff_delay(0);
        let d1 = HttpClient::backoff_delay(1);
        let d2 = HttpClient::backoff_delay(2);
        assert!(d0.as_millis() >= 500 && d0.as_millis() < 1000);
        assert!(d1.as_millis() >= 1000 && d1.as_millis() < 1500);
        assert!(d2.as_millis() >= 2000 && d2.as_millis() < 2500);
    }

    #[test]
    fn retryable_status_codes() {
        assert!(HttpClient::is_retryable_status(
            StatusCode::TOO_MANY_REQUESTS
        ));
        assert!(HttpClient::is_retryable_status(StatusCode::BAD_GATEWAY));
        assert!(HttpClient::is_retryable_status(
            StatusCode::SERVICE_UNAVAILABLE
        ));
        assert!(!HttpClient::is_retryable_status(StatusCode::NOT_FOUND));
        assert!(!HttpClient::is_retryable_status(StatusCode::FORBIDDEN));
    }

    #[test]
    fn residential_proxy_is_google_only_by_default() {
        let client = HttpClient::new(&FetchiumConfig::default()).unwrap();
        assert!(client.needs_residential_proxy("google.com"));
        assert!(client.needs_residential_proxy("www.google.com"));
        assert!(!client.needs_residential_proxy("duckduckgo.com"));
        assert!(!client.needs_residential_proxy("html.duckduckgo.com"));
        assert!(!client.needs_residential_proxy("bing.com"));
    }

    #[test]
    fn explicit_residential_domain_override_wins() {
        let mut config = FetchiumConfig::default();
        config.dataimpulse.proxy_domains = vec!["example.com".into()];
        let client = HttpClient::new(&config).unwrap();
        assert!(client.needs_residential_proxy("www.example.com"));
        assert!(!client.needs_residential_proxy("google.com"));
    }
}