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
//! Google Search backend — HTTP scraper (default) + headless Chromium (--features headless).
//!
//! ## Default mode (no extra flags)
//! Uses `reqwest` with browser-realistic headers to scrape Google's standard
//! search endpoint. Works without any API keys or browser downloads. Google
//! occasionally serves CAPTCHA pages — the backend detects them and returns
//! empty results gracefully so the orchestrator falls back to other backends.
//!
//! ## Headless mode (`--features headless`)
//! Uses `chromiumoxide` BrowserPool for full JS rendering. Higher fidelity
//! but requires compiling Chromium bindings (~5 min) and a Chrome binary.
//!
//! ## Anti-detection
//! Chrome/121 User-Agent, Accept-Language, Referer headers; 500ms inter-page
//! delay; CAPTCHA detection on first-page empty or block-page markers.

use crate::error::FetchiumResult;
use crate::search::{SearchBackend, SearchContext, TimeRange};
use crate::types::{BackendId, ResultItem};
use async_trait::async_trait;
use tracing::debug;
#[cfg(not(feature = "headless"))]
use tracing::info;
#[cfg(feature = "headless")]
use tracing::warn;

/// Max IP-rotation retries on CAPTCHA/block detection (2 = 1 cached + 1 fresh IP).
#[cfg(not(feature = "headless"))]
const MAX_IP_RETRIES: usize = 2;

/// Browser User-Agent matching Chrome 121 on Windows — reduces bot-detection.
#[cfg(not(feature = "headless"))]
const BROWSER_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
    AppleWebKit/537.36 (KHTML, like Gecko) \
    Chrome/121.0.0.0 Safari/537.36";

/// Google SERP scraper.
///
/// Without `--features headless`: lightweight HTTP scraper, no extra setup.
/// With `--features headless`: headless Chromium for JS-rendered results.
pub struct GoogleBackend {
    #[cfg(feature = "headless")]
    pool: std::sync::Arc<crate::browser::pool::BrowserPool>,
    #[cfg(not(feature = "headless"))]
    http: crate::http::HttpClient,
}

impl GoogleBackend {
    /// Create a headless-Chromium backend (requires `--features headless`).
    #[cfg(feature = "headless")]
    pub fn new(pool: std::sync::Arc<crate::browser::pool::BrowserPool>) -> Self {
        Self { pool }
    }

    /// Create an HTTP-scraper backend (default, no extra features required).
    #[cfg(not(feature = "headless"))]
    pub fn new_http(http: crate::http::HttpClient) -> Self {
        Self { http }
    }

    /// Build a Google search URL for the given query and page (0-indexed).
    fn build_url(query: &str, page: usize) -> String {
        Self::build_url_with_tbs(query, page, "")
    }

    fn build_url_with_tbs(query: &str, page: usize, tbs: &str) -> String {
        let start = page * 10;
        let encoded = url::form_urlencoded::Serializer::new(String::new())
            .append_key_only(query)
            .finish();
        let tbs_param = if tbs.is_empty() {
            String::new()
        } else {
            format!("&tbs={tbs}")
        };
        // pws=0  — disable personalised results for consistent scraping
        format!("https://www.google.com/search?q={encoded}&start={start}&hl=en&num=10&gl=us&pws=0{tbs_param}")
    }

    fn time_range_to_tbs(tr: Option<TimeRange>) -> &'static str {
        match tr {
            Some(TimeRange::Day) => "qdr:d",
            Some(TimeRange::Week) => "qdr:w",
            Some(TimeRange::Month) => "qdr:m",
            Some(TimeRange::Year) => "qdr:y",
            None => "",
        }
    }

    /// Fetch a Google SERP page with automatic IP rotation on block/CAPTCHA.
    ///
    /// Attempt 0 uses the cached residential client (fast path).
    /// Attempts 1+ use a fresh client (new residential IP via DataImpulse pool_max_idle=0).
    /// Returns `None` if all retries are exhausted with no results.
    #[cfg(not(feature = "headless"))]
    async fn fetch_page_with_retry(
        &self,
        url: &str,
        page: usize,
        locale: Option<&str>,
    ) -> Option<Vec<ResultItem>> {
        for attempt in 0..MAX_IP_RETRIES {
            let client = if attempt == 0 {
                self.http
                    .client_for_domain_with_locale("google.com", locale)
            } else {
                info!(
                    "Google: IP block detected — rotating to new residential IP (attempt {}/{})",
                    attempt + 1,
                    MAX_IP_RETRIES
                );
                // Brief pause before IP rotation to avoid hammering
                tokio::time::sleep(std::time::Duration::from_millis(300 * attempt as u64)).await;
                self.http
                    .fresh_client_for_domain_with_locale("google.com", locale)
            };

            let result = client
                .get(url)
                .header("User-Agent", BROWSER_UA)
                .header(
                    "Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                )
                .header("Accept-Language", "en-US,en;q=0.9")
                .header("Referer", "https://www.google.com/")
                .header("Cache-Control", "no-cache")
                .send()
                .await;

            match result {
                Ok(resp) if resp.status().is_success() => match resp.text().await {
                    Ok(html) => {
                        let results = Self::parse_serp(&html, page);
                        if !results.is_empty() {
                            return Some(results);
                        }
                        // Empty results = CAPTCHA/block → rotate IP
                        debug!("Google: empty SERP page {page} (attempt {attempt}) — rotating IP");
                    }
                    Err(e) => {
                        debug!("Google: body read error attempt {attempt}: {e}");
                    }
                },
                Ok(resp) if resp.status().as_u16() == 429 || resp.status().as_u16() == 403 => {
                    debug!(
                        "Google: HTTP {} attempt {attempt} — rotating IP",
                        resp.status()
                    );
                }
                Ok(resp) => {
                    debug!("Google: HTTP {} for page {page}", resp.status());
                    return None; // Non-retryable error
                }
                Err(e) => {
                    debug!("Google: request error attempt {attempt}: {e}");
                }
            }
        }

        debug!("Google: all {MAX_IP_RETRIES} IP rotation attempts exhausted for page {page}");
        None
    }

    /// Parse a Google SERP HTML page into [`ResultItem`]s.
    ///
    /// Returns an empty vec on CAPTCHA / block pages — the caller should warn
    /// and return early rather than trying subsequent pages.
    fn parse_serp(html: &str, page: usize) -> Vec<ResultItem> {
        use scraper::{Html, Selector};

        // ── CAPTCHA / block detection ────────────────────────────────────────
        // Google serves several kinds of block pages:
        // 1. Redirects to `accounts.google.com` (sign-in wall)
        // 2. Inline CAPTCHA challenge with text "detected unusual traffic"
        // 3. "please enable cookies" / JS-only pages
        if html.contains("accounts.google.com")
            || html.contains("detected unusual traffic")
            || html.contains("please enable cookies")
            || (html.len() < 5_000 && html.to_lowercase().contains("captcha"))
        {
            return vec![];
        }

        let document = Html::parse_document(html);
        let mut results = Vec::new();

        // Google's SERP DOM (stable across most Google updates):
        //  <div class="g">                   ← organic result wrapper
        //    <div class="yuRUbf">
        //      <a href="https://...">
        //        <h3 class="LC20lb">Title</h3>
        //      </a>
        //    </div>
        //    <div class="VwiC3b">Snippet</div>
        //  </div>
        let container_sel = Selector::parse("div.g, div[data-hveid]").unwrap();
        let title_sel = Selector::parse("h3").unwrap();
        let link_sel = Selector::parse("a[href]").unwrap();
        let snippet_sel = Selector::parse("div.VwiC3b, span.aCOpRe, div[data-sncf]").unwrap();

        let mut rank = (page * 10 + 1) as u32;

        for container in document.select(&container_sel) {
            let title = container
                .select(&title_sel)
                .next()
                .map(|e| e.text().collect::<String>().trim().to_string())
                .unwrap_or_default();

            if title.is_empty() {
                continue;
            }

            let url = container
                .select(&link_sel)
                .next()
                .and_then(|e| e.value().attr("href"))
                .filter(|href| href.starts_with("http"))
                .filter(|href| !href.contains("google.com"))
                .map(|s| s.to_string())
                .unwrap_or_default();

            if url.is_empty() {
                continue;
            }

            let snippet = container
                .select(&snippet_sel)
                .next()
                .map(|e| e.text().collect::<String>().trim().to_string())
                .unwrap_or_default();

            results.push(ResultItem {
                title,
                url,
                snippet,
                rank,
                backend: BackendId::Google,
                score: None,
                published_date: None,
            });
            rank += 1;
        }

        debug!(
            "Google parse_serp: {} results from page {}",
            results.len(),
            page
        );

        results
    }
}

#[async_trait]
impl SearchBackend for GoogleBackend {
    fn id(&self) -> BackendId {
        BackendId::Google
    }

    fn requires_headless(&self) -> bool {
        cfg!(feature = "headless")
    }

    async fn search(&self, query: &str, max_results: u32) -> FetchiumResult<Vec<ResultItem>> {
        // ── Non-headless path: lightweight HTTP scraper ───────────────────────
        #[cfg(not(feature = "headless"))]
        {
            let pages = (max_results as usize).div_ceil(10).min(2);
            let mut all_results = Vec::new();

            for page in 0..pages {
                let url = Self::build_url(query, page);
                match self.fetch_page_with_retry(&url, page, None).await {
                    Some(results) => all_results.extend(results),
                    None => break, // CAPTCHA exhausted or non-retryable
                }
                if page + 1 < pages {
                    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                }
            }

            return Ok(all_results.into_iter().take(max_results as usize).collect());
        }

        // ── Headless path: chromiumoxide BrowserPool ─────────────────────────
        #[cfg(feature = "headless")]
        {
            let pages = (max_results as usize).div_ceil(10).min(3);
            let mut all_results = Vec::new();

            for page in 0..pages {
                let url = Self::build_url(query, page);

                match self.pool.acquire_tab().await {
                    Ok(tab) => {
                        if page > 0 {
                            let delay_ms = 200 + (rand_u64() % 600);
                            tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
                        }

                        // Wait for Google organic results to render (JS-heavy SERP)
                        match tab.navigate_and_wait(&url, "div.g", 15_000).await {
                            Ok(_) => match tab.content().await {
                                Ok(html) => {
                                    all_results.extend(Self::parse_serp(&html, page));
                                }
                                Err(e) => {
                                    warn!("Google content error page {page}: {e}");
                                }
                            },
                            Err(e) => {
                                warn!("Google navigate error page {page}: {e}");
                            }
                        }
                    }
                    Err(e) => {
                        warn!("Google tab acquire failed: {e}");
                        break;
                    }
                }
            }

            Ok(all_results.into_iter().take(max_results as usize).collect())
        }
    }

    async fn search_with_context(
        &self,
        query: &str,
        max_results: u32,
        ctx: &SearchContext,
    ) -> FetchiumResult<Vec<ResultItem>> {
        let tbs = Self::time_range_to_tbs(ctx.time_range);
        if tbs.is_empty() {
            return self.search(query, max_results).await;
        }

        // Non-headless path with tbs date filtering + IP rotation
        #[cfg(not(feature = "headless"))]
        {
            let pages = (max_results as usize).div_ceil(10).min(2);
            let mut all_results = Vec::new();
            let locale = ctx.locale.as_deref();

            for page in 0..pages {
                let url = Self::build_url_with_tbs(query, page, tbs);
                match self.fetch_page_with_retry(&url, page, locale).await {
                    Some(results) => all_results.extend(results),
                    None => break,
                }
                if page + 1 < pages {
                    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                }
            }

            return Ok(all_results.into_iter().take(max_results as usize).collect());
        }

        // Headless path — fallback to default search (tbs not easily injectable)
        #[cfg(feature = "headless")]
        self.search(query, max_results).await
    }
}

/// Xorshift pseudo-random for anti-detection delays (no heavy dep).
#[cfg(feature = "headless")]
fn rand_u64() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    let mut x = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .subsec_nanos() as u64;
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    x
}

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

    #[cfg(not(feature = "headless"))]
    fn make_backend() -> GoogleBackend {
        use crate::config::FetchiumConfig;
        use crate::http::HttpClient;
        GoogleBackend::new_http(HttpClient::new(&FetchiumConfig::default()).expect("http"))
    }

    #[cfg(not(feature = "headless"))]
    #[test]
    fn backend_id() {
        assert_eq!(make_backend().id(), BackendId::Google);
    }

    #[cfg(not(feature = "headless"))]
    #[test]
    fn parse_serp_empty_html() {
        let results = GoogleBackend::parse_serp("<html><body></body></html>", 0);
        assert!(results.is_empty());
    }

    #[cfg(not(feature = "headless"))]
    #[test]
    fn parse_serp_captcha_detected() {
        // Simulate a CAPTCHA page — should return empty, not panic.
        let captcha_html = r#"<html><body>
            <p>detected unusual traffic from your computer network</p>
        </body></html>"#;
        let results = GoogleBackend::parse_serp(captcha_html, 0);
        assert!(results.is_empty());
    }

    #[cfg(not(feature = "headless"))]
    #[test]
    fn parse_serp_filters_non_http_urls() {
        let html = r#"<html><body>
            <div class="g">
                <h3>Good Result</h3>
                <a href="https://example.com/page">link</a>
                <div class="VwiC3b">A useful snippet.</div>
            </div>
            <div class="g">
                <h3>Google Internal</h3>
                <a href="https://www.google.com/search?q=test">internal</a>
            </div>
        </body></html>"#;
        let results = GoogleBackend::parse_serp(html, 0);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].url, "https://example.com/page");
        assert_eq!(results[0].backend, BackendId::Google);
    }

    #[cfg(not(feature = "headless"))]
    #[test]
    fn build_url_page_0() {
        let url = GoogleBackend::build_url("rust programming", 0);
        assert!(url.contains("google.com/search"));
        assert!(url.contains("start=0"));
        assert!(url.contains("rust"));
    }

    #[cfg(not(feature = "headless"))]
    #[test]
    fn build_url_page_1() {
        let url = GoogleBackend::build_url("test", 1);
        assert!(url.contains("start=10"));
    }

    #[cfg(feature = "headless")]
    #[test]
    fn build_url_headless() {
        let url = GoogleBackend::build_url("rust async", 0);
        assert!(url.contains("google.com/search"));
        assert!(url.contains("start=0"));
    }

    #[cfg(feature = "headless")]
    #[test]
    fn parse_serp_empty_headless() {
        let results = GoogleBackend::parse_serp("<html><body></body></html>", 0);
        assert!(results.is_empty());
    }
}