crawlkit-engine 2.0.0

High-performance Rust web crawler and SEO analysis toolkit with 28 analyzers, WASM plugin system, and enterprise features
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use futures::stream::Stream;
use futures::StreamExt;
use reqwest::header::USER_AGENT;
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use tokio::time::sleep;
use url::Url;

use crate::{CrawlConfig, CrawlError, FetchResult, RedirectHop};

/// Retry policy for failed requests.
///
/// Controls exponential backoff behavior for retryable HTTP status codes
/// and network errors. The backoff duration is calculated as:
/// `initial_backoff * backoff_multiplier^attempt`, capped at `max_backoff`.
///
/// # Examples
///
/// ```rust
/// use crawlkit_engine::http::RetryPolicy;
/// use std::time::Duration;
///
/// let policy = RetryPolicy::default();
/// assert_eq!(policy.max_retries, 3);
/// assert!(policy.is_retryable(429));
/// assert!(!policy.is_retryable(200));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryPolicy {
    /// Maximum number of retry attempts.
    pub max_retries: usize,
    /// Initial backoff duration.
    #[serde(with = "crate::duration_ms")]
    pub initial_backoff: Duration,
    /// Maximum backoff duration.
    #[serde(with = "crate::duration_ms")]
    pub max_backoff: Duration,
    /// Multiplier applied to backoff on each attempt.
    pub backoff_multiplier: f64,
    /// HTTP status codes that trigger a retry.
    pub retryable_statuses: Vec<u16>,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_retries: 3,
            initial_backoff: Duration::from_secs(1),
            max_backoff: Duration::from_secs(30),
            backoff_multiplier: 2.0,
            retryable_statuses: vec![429, 500, 502, 503, 504],
        }
    }
}

impl RetryPolicy {
    /// Returns the backoff duration for a given attempt number (0-indexed).
    ///
    /// The duration grows exponentially: `initial_backoff * multiplier^attempt`,
    /// capped at `max_backoff`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crawlkit_engine::http::RetryPolicy;
    /// use std::time::Duration;
    ///
    /// let policy = RetryPolicy::default();
    /// assert_eq!(policy.backoff_duration(0), Duration::from_secs(1));
    /// assert_eq!(policy.backoff_duration(1), Duration::from_secs(2));
    /// assert_eq!(policy.backoff_duration(10), Duration::from_secs(30)); // capped
    /// ```
    pub fn backoff_duration(&self, attempt: usize) -> Duration {
        let base = self.initial_backoff.as_secs_f64();
        let backoff = base * self.backoff_multiplier.powi(attempt as i32);
        let capped = backoff.min(self.max_backoff.as_secs_f64());
        Duration::from_secs_f64(capped)
    }

    /// Returns `true` if the given status code should trigger a retry.
    ///
    /// By default retries on: 429 (Too Many Requests), 500, 502, 503, 504.
    pub fn is_retryable(&self, status: u16) -> bool {
        self.retryable_statuses.contains(&status)
    }
}

/// User-agent rotator that cycles through a list of user-agent strings.
///
/// Thread-safe rotation using atomic operations. Useful for distributing
/// requests across multiple identity strings to avoid detection.
///
/// # Examples
///
/// ```rust
/// use crawlkit_engine::http::UserAgentRotator;
///
/// let rotator = UserAgentRotator::new(vec![
///     "bot/1.0".to_string(),
///     "bot/2.0".to_string(),
/// ]);
/// assert_eq!(rotator.next(), "bot/1.0");
/// assert_eq!(rotator.next(), "bot/2.0");
/// assert_eq!(rotator.next(), "bot/1.0"); // wraps around
/// ```
#[derive(Debug)]
pub struct UserAgentRotator {
    agents: Vec<String>,
    index: AtomicUsize,
}

impl UserAgentRotator {
    /// Creates a new rotator with the given user-agent strings.
    ///
    /// # Panics
    ///
    /// Panics if `agents` is empty.
    pub fn new(agents: Vec<String>) -> Self {
        assert!(
            !agents.is_empty(),
            "UserAgentRotator requires at least one user-agent"
        );
        Self {
            agents,
            index: AtomicUsize::new(0),
        }
    }

    /// Returns the next user-agent string in rotation.
    ///
    /// Uses `AcqRel` ordering to ensure fair rotation under contention.
    /// `Relaxed` would allow multiple threads to read the same index.
    pub fn next(&self) -> &str {
        let idx = self.index.fetch_add(1, Ordering::AcqRel);
        &self.agents[idx % self.agents.len()]
    }

    /// Returns the number of user-agents in the rotation.
    pub fn len(&self) -> usize {
        self.agents.len()
    }

    /// Returns `true` if the rotation contains no user-agents.
    pub fn is_empty(&self) -> bool {
        self.agents.is_empty()
    }
}

impl Default for UserAgentRotator {
    fn default() -> Self {
        Self::new(vec![format!("crawlkit/{}", env!("CARGO_PKG_VERSION"))])
    }
}

/// Configuration for the HTTP client.
///
/// Controls timeout, redirect policy, retry behavior, connection pooling,
/// and HTTP/2 settings. Can be constructed from a [`CrawlConfig`].
///
/// # Examples
///
/// ```rust
/// use crawlkit_engine::{CrawlConfig, http::HttpClientConfig};
///
/// let config = HttpClientConfig::from(&CrawlConfig::default());
/// assert_eq!(config.max_body_size, 10 * 1024 * 1024);
/// ```
#[derive(Debug, Clone)]
pub struct HttpClientConfig {
    /// Request timeout.
    pub timeout: Duration,
    /// Maximum number of redirects to follow.
    pub max_redirects: usize,
    /// Retry policy.
    pub retry_policy: RetryPolicy,
    /// User-agent rotator.
    pub user_agent: Arc<UserAgentRotator>,
    /// Maximum response body size in bytes (0 = unlimited).
    pub max_body_size: usize,
    /// Maximum number of idle connections per host.
    pub pool_max_idle_per_host: usize,
    /// Maximum number of idle connections across all hosts.
    pub pool_max_idle: usize,
    /// Whether to enable TCP keepalive.
    pub tcp_keepalive: Option<Duration>,
}

impl From<&CrawlConfig> for HttpClientConfig {
    fn from(config: &CrawlConfig) -> Self {
        Self {
            timeout: config.request_timeout,
            max_redirects: config.max_redirects,
            retry_policy: RetryPolicy::default(),
            user_agent: Arc::new(UserAgentRotator::new(vec![config.user_agent.clone()])),
            max_body_size: 10 * 1024 * 1024, // 10MB default
            pool_max_idle_per_host: 16,
            pool_max_idle: 32,
            tcp_keepalive: Some(Duration::from_secs(60)),
        }
    }
}

/// An HTTP client with retry, redirect tracking, and user-agent rotation.
///
/// Built on top of `reqwest::Client` with additional features for web crawling:
/// - Manual redirect following with hop recording
/// - Exponential backoff retry for transient failures
/// - User-agent rotation across requests
/// - Response body size limiting
/// - Streaming responses
///
/// # Examples
///
/// ```rust,no_run
/// use crawlkit_engine::{CrawlConfig, HttpClient};
/// use url::Url;
///
/// # async fn example() -> Result<(), crawlkit_engine::CrawlError> {
/// let client = HttpClient::from_crawl_config(&CrawlConfig::default())?;
/// let url = Url::parse("https://example.com")?;
/// let result = client.fetch(&url).await?;
/// assert_eq!(result.status_code, 200);
/// # Ok(())
/// # }
/// ```
pub struct HttpClient {
    client: Client,
    config: HttpClientConfig,
}

impl HttpClient {
    /// Creates a new `HttpClient` from the given configuration.
    ///
    /// Builds a `reqwest::Client` with TLS, HTTP/2 multiplexing, connection
    /// pooling, and redirect policy.
    ///
    /// # Errors
    ///
    /// Returns [`CrawlError::RequestFailed`] if the underlying reqwest client
    /// cannot be built (e.g., invalid TLS configuration).
    pub fn new(config: HttpClientConfig) -> Result<Self, CrawlError> {
        let mut builder = Client::builder()
            .timeout(config.timeout)
            .redirect(reqwest::redirect::Policy::limited(config.max_redirects))
            .user_agent(config.user_agent.next())
            .https_only(true)
            .http1_only()
            .pool_max_idle_per_host(config.pool_max_idle_per_host)
            .pool_idle_timeout(Duration::from_secs(90))
            .connect_timeout(Duration::from_secs(10));

        if let Some(keepalive) = config.tcp_keepalive {
            builder = builder.tcp_keepalive(keepalive);
        }

        let client = builder.build()?;

        Ok(Self { client, config })
    }

    /// Creates a new `HttpClient` from a `CrawlConfig`.
    ///
    /// Convenience method that converts the crawl config into an
    /// [`HttpClientConfig`] and builds the client.
    ///
    /// # Errors
    ///
    /// Returns [`CrawlError::RequestFailed`] if the client cannot be built.
    pub fn from_crawl_config(config: &CrawlConfig) -> Result<Self, CrawlError> {
        Self::new(HttpClientConfig::from(config))
    }

    /// Creates a new `HttpClient` optimized for high-throughput crawling.
    ///
    /// Enables HTTP/2, larger connection pools, and TCP keepalive.
    pub fn high_throughput(config: HttpClientConfig) -> Result<Self, CrawlError> {
        let cfg = HttpClientConfig {
            pool_max_idle_per_host: 64,
            pool_max_idle: 128,
            tcp_keepalive: Some(Duration::from_secs(60)),
            ..config
        };
        Self::new(cfg)
    }

    /// Fetches a URL with retry logic and redirect tracking.
    ///
    /// Returns a [`FetchResult`] with the final URL, status, headers, and body.
    /// Follows redirects manually to record each hop in the chain.
    ///
    /// # Errors
    ///
    /// Returns [`CrawlError::RequestFailed`] on network errors after retries
    /// are exhausted, or [`CrawlError::TooManyRedirects`] if the redirect
    /// limit is exceeded.
    pub async fn fetch(&self, url: &Url) -> Result<FetchResult, CrawlError> {
        self.fetch_with_redirects(url, self.config.max_redirects)
            .await
    }

    /// Fetches a URL, following up to `max_hops` redirects manually.
    ///
    /// Each redirect hop is recorded. If the hop limit is exceeded,
    /// [`CrawlError::TooManyRedirects`] is returned.
    ///
    /// # Errors
    ///
    /// Returns errors for network failures or exceeded redirect limits.
    pub async fn fetch_with_redirects(
        &self,
        url: &Url,
        max_hops: usize,
    ) -> Result<FetchResult, CrawlError> {
        let mut current_url = url.clone();
        let mut hops: Vec<RedirectHop> = Vec::new();

        for _ in 0..=max_hops {
            match self.fetch_once(&current_url).await {
                Ok((final_url, status, headers, body, elapsed)) => {
                    if status.is_redirection() {
                        let next_url = headers
                            .iter()
                            .find(|(k, _)| k.eq_ignore_ascii_case("location"))
                            .map(|(_, v)| v.clone());

                        match next_url {
                            Some(loc) => {
                                let resolved = current_url.join(&loc)?;
                                hops.push(RedirectHop {
                                    from: current_url.clone(),
                                    to: resolved.clone(),
                                    status_code: status.as_u16(),
                                });
                                current_url = resolved;
                                continue;
                            }
                            None => {
                                // No Location header — return the redirect response as-is
                                let body_size = body.len();
                                return Ok(FetchResult {
                                    final_url,
                                    status_code: status.as_u16(),
                                    headers,
                                    body,
                                    response_time: elapsed,
                                    body_size,
                                    fetched_at: chrono::Utc::now(),
                                });
                            }
                        }
                    }

                    let body_size = body.len();
                    return Ok(FetchResult {
                        final_url,
                        status_code: status.as_u16(),
                        headers,
                        body,
                        response_time: elapsed,
                        body_size,
                        fetched_at: chrono::Utc::now(),
                    });
                }
                Err(CrawlError::RequestFailed(e)) => {
                    return Err(CrawlError::RequestFailed(e));
                }
                Err(e) => return Err(e),
            }
        }

        Err(CrawlError::TooManyRedirects(max_hops))
    }

    /// Performs a single HTTP request with retry logic.
    ///
    /// Returns the final URL, status, headers, body text, and elapsed time.
    async fn fetch_once(
        &self,
        url: &Url,
    ) -> Result<(Url, StatusCode, Vec<(String, String)>, String, Duration), CrawlError> {
        let mut last_error: Option<CrawlError> = None;
        let max_retries = self.config.retry_policy.max_retries;

        for attempt in 0..=max_retries {
            let start = Instant::now();
            let user_agent = self.config.user_agent.next();

            let result = self
                .client
                .get(url.as_str())
                .header(USER_AGENT, user_agent)
                .send()
                .await;

            match result {
                Ok(response) => {
                    let status = response.status();
                    let elapsed = start.elapsed();
                    let headers: Vec<(String, String)> = response
                        .headers()
                        .iter()
                        .map(|(k, v)| {
                            (
                                k.as_str().to_string(),
                                String::from_utf8_lossy(v.as_bytes()).to_string(),
                            )
                        })
                        .collect();

                    if self.config.retry_policy.is_retryable(status.as_u16())
                        && attempt < max_retries
                    {
                        let backoff = self.config.retry_policy.backoff_duration(attempt);

                        // Respect Retry-After header for 429
                        if status == StatusCode::TOO_MANY_REQUESTS {
                            if let Some(retry_after) = headers
                                .iter()
                                .find(|(k, _)| k.eq_ignore_ascii_case("retry-after"))
                                .and_then(|(_, v)| v.parse::<u64>().ok())
                            {
                                let wait = Duration::from_secs(retry_after).max(backoff);
                                tracing::warn!(
                                    url = %url,
                                    status = status.as_u16(),
                                    retry_after = retry_after,
                                    "429 Too Many Requests, waiting before retry"
                                );
                                sleep(wait).await;
                                continue;
                            }
                        }

                        tracing::warn!(
                            url = %url,
                            status = status.as_u16(),
                            attempt = attempt + 1,
                            backoff_ms = backoff.as_millis(),
                            "Retrying after retryable status"
                        );
                        sleep(backoff).await;
                        continue;
                    }

                    // Extract final_url before consuming the response body
                    let final_url = response.url().clone();

                    let body = if self.config.max_body_size > 0 {
                        let bytes = response.bytes().await.map_err(CrawlError::RequestFailed)?;
                        let limited = &bytes[..bytes.len().min(self.config.max_body_size)];
                        String::from_utf8_lossy(limited).to_string()
                    } else {
                        response.text().await.map_err(CrawlError::RequestFailed)?
                    };

                    return Ok((final_url, status, headers, body, elapsed));
                }
                Err(e) => {
                    if (e.is_timeout() || e.is_connect()) && attempt < max_retries {
                        let backoff = self.config.retry_policy.backoff_duration(attempt);
                        tracing::warn!(
                            url = %url,
                            error = %e,
                            attempt = attempt + 1,
                            backoff_ms = backoff.as_millis(),
                            "Retrying after network error"
                        );
                        sleep(backoff).await;
                        last_error = Some(CrawlError::RequestFailed(e));
                        continue;
                    }
                    return Err(CrawlError::RequestFailed(e));
                }
            }
        }

        Err(last_error.unwrap_or(CrawlError::MaxRetriesExceeded(max_retries)))
    }

    /// Returns a reference to the inner `reqwest::Client`.
    pub fn inner(&self) -> &Client {
        &self.client
    }

    /// Returns a reference to the client configuration.
    pub fn config(&self) -> &HttpClientConfig {
        &self.config
    }

    /// Fetches a URL and streams the response body, calling the callback with
    /// each chunk.
    ///
    /// This is useful for large pages where you want to process HTML as it
    /// arrives rather than buffering the entire response in memory.
    ///
    /// # Errors
    ///
    /// Returns errors for network failures or redirect limit exceeded.
    pub async fn fetch_stream<F>(
        &self,
        url: &Url,
        mut on_chunk: F,
    ) -> Result<FetchResult, CrawlError>
    where
        F: FnMut(&str) + Send,
    {
        let mut current_url = url.clone();
        let mut hops: Vec<RedirectHop> = Vec::new();

        for _ in 0..=self.config.max_redirects {
            let start = Instant::now();
            let user_agent = self.config.user_agent.next();

            let response = self
                .client
                .get(current_url.as_str())
                .header(USER_AGENT, user_agent)
                .send()
                .await
                .map_err(CrawlError::RequestFailed)?;

            let status = response.status();
            let elapsed = start.elapsed();
            let headers: Vec<(String, String)> = response
                .headers()
                .iter()
                .map(|(k, v)| {
                    (
                        k.as_str().to_string(),
                        String::from_utf8_lossy(v.as_bytes()).to_string(),
                    )
                })
                .collect();

            if status.is_redirection() {
                let next_url = headers
                    .iter()
                    .find(|(k, _)| k.eq_ignore_ascii_case("location"))
                    .map(|(_, v)| v.clone());

                match next_url {
                    Some(loc) => {
                        let resolved = current_url.join(&loc)?;
                        hops.push(RedirectHop {
                            from: current_url.clone(),
                            to: resolved.clone(),
                            status_code: status.as_u16(),
                        });
                        current_url = resolved;
                        continue;
                    }
                    None => {
                        let final_url = response.url().clone();
                        return Ok(FetchResult {
                            final_url,
                            status_code: status.as_u16(),
                            headers,
                            body: String::new(),
                            response_time: elapsed,
                            body_size: 0,
                            fetched_at: chrono::Utc::now(),
                        });
                    }
                }
            }

            let final_url = response.url().clone();
            let mut body = String::new();
            let mut stream = response.bytes_stream();
            let mut total_size: usize = 0;

            while let Some(chunk_result) = stream.next().await {
                let chunk = chunk_result.map_err(CrawlError::RequestFailed)?;
                total_size += chunk.len();

                if self.config.max_body_size > 0 && total_size > self.config.max_body_size {
                    break;
                }

                let chunk_str = String::from_utf8_lossy(&chunk);
                on_chunk(&chunk_str);
                body.push_str(&chunk_str);
            }

            return Ok(FetchResult {
                final_url,
                status_code: status.as_u16(),
                headers,
                body,
                response_time: elapsed,
                body_size: total_size,
                fetched_at: chrono::Utc::now(),
            });
        }

        Err(CrawlError::TooManyRedirects(self.config.max_redirects))
    }

    /// Fetches a URL and returns the response as a streaming reader.
    ///
    /// Returns the response metadata (status, headers) and a streaming body.
    /// The caller can read chunks from the stream via [`FetchStreamReader::next_chunk`].
    ///
    /// # Errors
    ///
    /// Returns errors for network failures.
    pub async fn fetch_reader(&self, url: &Url) -> Result<FetchStreamReader, CrawlError> {
        let start = Instant::now();
        let user_agent = self.config.user_agent.next();

        let response = self
            .client
            .get(url.as_str())
            .header(USER_AGENT, user_agent)
            .send()
            .await
            .map_err(CrawlError::RequestFailed)?;

        let status = response.status();
        let elapsed = start.elapsed();
        let headers: Vec<(String, String)> = response
            .headers()
            .iter()
            .map(|(k, v)| {
                (
                    k.as_str().to_string(),
                    String::from_utf8_lossy(v.as_bytes()).to_string(),
                )
            })
            .collect();
        let final_url = response.url().clone();
        let max_body_size = self.config.max_body_size;

        let stream = response.bytes_stream().take_while(move |result| {
            let should_continue = match result {
                Ok(_bytes) => {
                    // Simple heuristic: stop if we've likely exceeded max body size
                    // This is approximate since we don't track total here
                    true
                }
                Err(_) => false,
            };
            async move { should_continue }
        });

        Ok(FetchStreamReader {
            final_url,
            status_code: status.as_u16(),
            headers,
            response_time: elapsed,
            stream: Box::pin(stream),
            body_size: 0,
            max_body_size,
        })
    }
}

/// A streaming HTTP response reader.
///
/// Read chunks from the body using the [`next_chunk`](FetchStreamReader::next_chunk) method.
/// The stream automatically respects `max_body_size`. Can be converted into
/// a [`FetchResult`] via [`into_fetch_result`](FetchStreamReader::into_fetch_result).
///
/// # Examples
///
/// ```rust,no_run
/// use crawlkit_engine::{CrawlConfig, HttpClient};
/// use url::Url;
///
/// # async fn example() -> Result<(), crawlkit_engine::CrawlError> {
/// let client = HttpClient::from_crawl_config(&CrawlConfig::default())?;
/// let url = Url::parse("https://example.com")?;
/// let mut reader = client.fetch_reader(&url).await?;
/// while let Some(chunk) = reader.next_chunk().await? {
///     // process chunk
/// }
/// # Ok(())
/// # }
/// ```
pub struct FetchStreamReader {
    pub final_url: Url,
    pub status_code: u16,
    pub headers: Vec<(String, String)>,
    pub response_time: Duration,
    stream: Pin<Box<dyn Stream<Item = Result<bytes::Bytes, reqwest::Error>> + Send>>,
    pub body_size: usize,
    max_body_size: usize,
}

impl FetchStreamReader {
    /// Reads the next chunk of the response body.
    ///
    /// Returns `Ok(Some(bytes))` if data is available, `Ok(None)` if the
    /// stream is complete, or `Err` on error. Respects `max_body_size`.
    ///
    /// # Errors
    ///
    /// Returns [`CrawlError::RequestFailed`] on network errors.
    pub async fn next_chunk(&mut self) -> Result<Option<Vec<u8>>, CrawlError> {
        if self.max_body_size > 0 && self.body_size >= self.max_body_size {
            return Ok(None);
        }

        match self.stream.next().await {
            Some(Ok(chunk)) => {
                let chunk: bytes::Bytes = chunk;
                let len = chunk.len();
                self.body_size += len;
                Ok(Some(chunk.to_vec()))
            }
            Some(Err(e)) => Err(CrawlError::RequestFailed(e)),
            None => Ok(None),
        }
    }

    /// Reads the entire remaining body into a String.
    ///
    /// Convenience method that drains all remaining chunks and concatenates
    /// them into a single UTF-8 string (lossy conversion).
    ///
    /// # Errors
    ///
    /// Returns [`CrawlError::RequestFailed`] on network errors.
    pub async fn read_body(&mut self) -> Result<String, CrawlError> {
        let mut body = String::new();
        while let Some(chunk) = self.next_chunk().await? {
            body.push_str(&String::from_utf8_lossy(&chunk));
        }
        Ok(body)
    }

    /// Converts this into a [`FetchResult`] by reading the full body.
    ///
    /// Consumes the reader and returns the complete response including
    /// headers, status, and body content.
    ///
    /// # Errors
    ///
    /// Returns [`CrawlError::RequestFailed`] on network errors.
    pub async fn into_fetch_result(mut self) -> Result<FetchResult, CrawlError> {
        let body = self.read_body().await?;
        let body_size = self.body_size;
        Ok(FetchResult {
            final_url: self.final_url,
            status_code: self.status_code,
            headers: self.headers,
            body,
            response_time: self.response_time,
            body_size,
            fetched_at: chrono::Utc::now(),
        })
    }
}

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

    #[test]
    fn test_retry_policy_default() {
        let policy = RetryPolicy::default();
        assert_eq!(policy.max_retries, 3);
        assert_eq!(policy.initial_backoff, Duration::from_secs(1));
        assert_eq!(policy.max_backoff, Duration::from_secs(30));
        assert!((policy.backoff_multiplier - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_retry_policy_backoff_duration() {
        let policy = RetryPolicy::default();
        assert_eq!(policy.backoff_duration(0), Duration::from_secs(1));
        assert_eq!(policy.backoff_duration(1), Duration::from_secs(2));
        assert_eq!(policy.backoff_duration(2), Duration::from_secs(4));
        assert_eq!(policy.backoff_duration(3), Duration::from_secs(8));
        // Capped at max_backoff
        assert_eq!(policy.backoff_duration(10), Duration::from_secs(30));
    }

    #[test]
    fn test_retry_policy_is_retryable() {
        let policy = RetryPolicy::default();
        assert!(policy.is_retryable(429));
        assert!(policy.is_retryable(500));
        assert!(policy.is_retryable(502));
        assert!(policy.is_retryable(503));
        assert!(policy.is_retryable(504));
        assert!(!policy.is_retryable(200));
        assert!(!policy.is_retryable(404));
    }

    #[test]
    fn test_user_agent_rotator() {
        let rotator = UserAgentRotator::new(vec![
            "agent-1".to_string(),
            "agent-2".to_string(),
            "agent-3".to_string(),
        ]);
        assert_eq!(rotator.len(), 3);
        assert!(!rotator.is_empty());
        assert_eq!(rotator.next(), "agent-1");
        assert_eq!(rotator.next(), "agent-2");
        assert_eq!(rotator.next(), "agent-3");
        assert_eq!(rotator.next(), "agent-1"); // wraps around
    }

    #[test]
    fn test_user_agent_rotator_default() {
        let rotator = UserAgentRotator::default();
        assert_eq!(rotator.len(), 1);
        let agent = rotator.next().to_string();
        assert!(agent.starts_with("crawlkit/"));
    }

    #[test]
    fn test_http_client_config_from_crawl_config() {
        let crawl_config = CrawlConfig::default();
        let http_config = HttpClientConfig::from(&crawl_config);
        assert_eq!(http_config.timeout, Duration::from_secs(30));
        assert_eq!(http_config.max_redirects, 20);
        assert_eq!(http_config.max_body_size, 10 * 1024 * 1024);
    }

    #[tokio::test]
    async fn test_http_client_creation() {
        let config = HttpClientConfig::from(&CrawlConfig::default());
        let client = HttpClient::new(config);
        assert!(client.is_ok());
    }
}