searchwala 8.3.0

Meta-search engine and zero-dependency MCP server in Rust: cross-engine consensus ranking, trafilatura + Readability extraction, domain controls, scholarly sources, and mode-specific synthesis with optional BYOK LLM
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
// ══════════════════════════════════════════════════════════════════════════════
// SearchWala v8.0 — URL Utilities
//
// v8.0 changes:
//   * ONE canonicalization function (`canonical_key`). v7.0 had the same
//     normalization logic copy-pasted verbatim into `normalize_url` and
//     `deduplicate`, two implementations that had to agree with nothing
//     enforcing it.
//   * Query parameters are SORTED, so `?a=1&b=2` and `?b=2&a=1` are one page.
//   * www / m. / amp. / mobile. host prefixes and /amp, /index.html path
//     suffixes are unified. On news sites — the Amar Ujala class — these are
//     the dominant duplicate form and v7.0 scraped each variant separately.
//   * `should_skip` matches on the HOST, not a substring of the whole URL.
//     v7.0's `lower_url.contains("amazon.com")` dropped
//     `https://news.site.com/why-amazon.com-won` — a legitimate article.
//   * `ref` / `source` / `src` / `amp` / `campaign` / `partner` removed from
//     TRACKING_PARAMS: they are load-bearing on many sites and stripping them
//     produced 404s.
// ══════════════════════════════════════════════════════════════════════════════

use std::collections::HashSet;
use url::Url;

use crate::config;

/// Host prefixes that denote the same content as the bare host.
const HOST_PREFIXES: &[&str] = &["www.", "m.", "amp.", "mobile.", "www2.", "en."];

/// Two-level public suffixes we must not over-trim.
const TWO_LEVEL_SUFFIXES: &[&str] = &[
    "co.uk", "co.in", "co.jp", "co.kr", "co.nz", "co.za", "co.il", "com.br", "com.au", "com.mx",
    "com.tr", "com.cn", "com.sg", "com.hk", "or.jp", "ne.jp", "ac.uk", "gov.uk", "org.uk",
    "net.au", "org.au", "gov.in", "ac.in", "nic.in",
];

/// Path suffixes that are the same document as the parent path.
const PATH_SUFFIXES: &[&str] = &[
    "/amp",
    "/amp/",
    "/index.html",
    "/index.htm",
    "/index.php",
    "/index.asp",
    "/default.html",
    "/default.htm",
];

/// Canonical identity of a page: the single source of truth for
/// "are these the same document?".
///
/// Deliberately *not* a valid URL — it is a comparison key. Use
/// [`normalize_url`] when you need something fetchable.
pub fn canonical_key(raw: &str) -> String {
    let trimmed = raw.trim();
    let Ok(mut u) = Url::parse(trimmed) else {
        return trimmed.to_lowercase();
    };
    if !matches!(u.scheme(), "http" | "https") {
        return trimmed.to_lowercase();
    }
    u.set_fragment(None);

    // ── Host: lowercase, strip content-equivalent prefixes ──
    let mut host = u.host_str().unwrap_or_default().to_lowercase();
    host = host.trim_end_matches('.').to_string();
    loop {
        let mut stripped = false;
        for p in HOST_PREFIXES {
            if let Some(rest) = host.strip_prefix(*p) {
                // Never strip down to a bare public suffix.
                if rest.contains('.') {
                    host = rest.to_string();
                    stripped = true;
                    break;
                }
            }
        }
        if !stripped {
            break;
        }
    }

    // ── Path: drop AMP/index suffixes and the trailing slash ──
    let mut path = u.path().to_string();
    loop {
        let mut changed = false;
        for suf in PATH_SUFFIXES {
            if path.len() > suf.len() && path.ends_with(suf) {
                path.truncate(path.len() - suf.len());
                changed = true;
                break;
            }
        }
        if !changed {
            break;
        }
    }
    while path.len() > 1 && path.ends_with('/') {
        path.pop();
    }
    // Paths are case-sensitive on most servers — preserve case.

    // ── Query: drop tracking params, then SORT ──
    let mut pairs: Vec<(String, String)> = u
        .query_pairs()
        .filter(|(k, _)| {
            let kl = k.to_lowercase();
            !config::TRACKING_PARAMS.contains(&kl.as_str())
        })
        .map(|(k, v)| (k.into_owned(), v.into_owned()))
        .collect();
    pairs.sort();

    if pairs.is_empty() {
        format!("{host}{path}")
    } else {
        let q: Vec<String> = pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
        format!("{host}{path}?{}", q.join("&"))
    }
}

/// Registrable root of a host, respecting common two-level suffixes.
pub fn registrable_domain(host: &str) -> String {
    let h = host.trim_end_matches('.').to_lowercase();
    let parts: Vec<&str> = h.split('.').collect();
    if parts.len() <= 2 {
        return h;
    }
    let last_two = parts[parts.len() - 2..].join(".");
    if TWO_LEVEL_SUFFIXES.contains(&last_two.as_str()) && parts.len() >= 3 {
        return parts[parts.len() - 3..].join(".");
    }
    last_two
}

/// Normalize a caller-supplied domain filter (e.g. `"docs.rs"`, `"https://www.GitHub.com/foo"`,
/// `".arxiv.org"`) into a clean lowercase bare hostname (`"docs.rs"`, `"github.com"`, `"arxiv.org"`).
/// Returns `None` for invalid, empty, or non-domain strings.
pub fn normalize_domain_filter(raw: &str) -> Option<String> {
    let s = raw.trim();
    if s.is_empty() || s.len() > 2048 {
        return None;
    }

    let candidate_host = if s.contains("://") {
        let u = Url::parse(s).ok()?;
        u.host_str()?.to_ascii_lowercase()
    } else {
        // Strip path/query/fragment/port from bare host strings like "docs.rs/tokio" or "docs.rs:443".
        let host_port = s.split(['/', '?', '#']).next().unwrap_or("");
        let host_only = host_port.split(':').next().unwrap_or("");
        host_only.to_ascii_lowercase()
    };

    let mut host = candidate_host.trim_matches('.').to_string();
    while let Some(rest) = host.strip_prefix("www.") {
        if rest.contains('.') {
            host = rest.to_string();
        } else {
            break;
        }
    }

    if host.is_empty() || host.len() > 253 || !host.contains('.') {
        return None;
    }

    for label in host.split('.') {
        if label.is_empty()
            || label.len() > 63
            || label.starts_with('-')
            || label.ends_with('-')
            || !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
        {
            return None;
        }
    }

    Some(host)
}

/// True if `url`'s host is `domain` or a subdomain of `domain` (never substring matching).
/// Also treats `youtu.be` as matching `youtube.com`.
pub fn host_matches_domain(url: &str, domain: &str) -> bool {
    let Ok(u) = Url::parse(url.trim()) else {
        return false;
    };
    let Some(raw_host) = u.host_str() else {
        return false;
    };
    let host = raw_host.trim_end_matches('.').to_ascii_lowercase();
    let d = domain.trim_matches('.').to_ascii_lowercase();
    if d.is_empty() || host.is_empty() {
        return false;
    }
    if d == "youtube.com" && host == "youtu.be" {
        return true;
    }
    host == d || host.ends_with(&format!(".{d}"))
}

/// Subdomain-preserving display domain for grouping discovered sources
/// (strips `www.`, `m.`, `amp.`, `mobile.`, `www2.` while preserving meaningful
/// subdomains like `docs.python.org` or `en.wikipedia.org`).
pub fn display_domain(url: &str) -> String {
    let Ok(u) = Url::parse(url.trim()) else {
        return String::new();
    };
    let mut host = u
        .host_str()
        .unwrap_or_default()
        .trim_end_matches('.')
        .to_ascii_lowercase();
    const DISPLAY_PREFIXES: &[&str] = &["www.", "m.", "amp.", "mobile.", "www2."];
    loop {
        let mut stripped = false;
        for p in DISPLAY_PREFIXES {
            if let Some(rest) = host.strip_prefix(*p) {
                if rest.contains('.') {
                    host = rest.to_string();
                    stripped = true;
                    break;
                }
            }
        }
        if !stripped {
            break;
        }
    }
    host
}

/// A fetchable, tracking-stripped URL (scheme preserved).
pub fn normalize_url(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    let mut u = Url::parse(trimmed).ok()?;
    if !matches!(u.scheme(), "http" | "https") {
        return None;
    }
    u.set_fragment(None);

    let mut pairs: Vec<(String, String)> = u
        .query_pairs()
        .filter(|(k, _)| {
            let kl = k.to_lowercase();
            !config::TRACKING_PARAMS.contains(&kl.as_str())
        })
        .map(|(k, v)| (k.into_owned(), v.into_owned()))
        .collect();
    pairs.sort();

    if pairs.is_empty() {
        u.set_query(None);
    } else {
        let q: Vec<String> = pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
        u.set_query(Some(&q.join("&")));
    }
    Some(u.to_string())
}

/// Should this URL be skipped entirely?
///
/// Matches the blocklist against the HOST (exact or subdomain), never against
/// a substring of the full URL.
pub fn should_skip(url: &str) -> bool {
    let Ok(u) = Url::parse(url.trim()) else {
        return true;
    };
    if !matches!(u.scheme(), "http" | "https") {
        return true;
    }
    let host = u.host_str().unwrap_or_default().to_lowercase();
    if host.is_empty() {
        return true;
    }
    for d in config::SKIP_DOMAINS {
        let d = d.to_lowercase();
        if host == d || host.ends_with(&format!(".{d}")) {
            return true;
        }
    }
    let path = u.path().to_lowercase();
    config::SKIP_EXTENSIONS.iter().any(|e| path.ends_with(e))
}

/// Legacy alias — `canonical_key` is the real implementation now.
/// Kept as public API surface for callers outside this crate.
#[allow(dead_code)]
pub fn dedup_key(url: &str) -> String {
    canonical_key(url)
}

/// Deduplicate URLs preserving order, capped at `max_count`.
///
/// NOTE: callers that care about RANKING should not rely on this ordering.
/// v7.0 chose which URLs to scrape here, in arrival order, which meant the
/// scrape set was decided by whichever engine happened to finish first —
/// discarding the RRF consensus it had just computed. See `search.rs`.
pub fn deduplicate(urls: Vec<String>, max_count: usize, focus_mode: Option<&str>) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut unique = Vec::with_capacity(max_count.min(urls.len()));
    let focus_lower = focus_mode.map(|m| m.to_lowercase());

    for raw in urls {
        let Some(normalized) = normalize_url(&raw) else {
            continue;
        };

        let host = Url::parse(&normalized)
            .ok()
            .and_then(|u| u.host_str().map(|h| h.to_lowercase()))
            .unwrap_or_default();

        let bypass = match focus_lower.as_deref() {
            Some("reddit") => host.ends_with("reddit.com"),
            Some("youtube") => host.ends_with("youtube.com") || host.ends_with("youtu.be"),
            _ => false,
        };
        if !bypass && should_skip(&normalized) {
            continue;
        }
        if !seen.insert(canonical_key(&normalized)) {
            continue;
        }
        unique.push(normalized);
        if unique.len() >= max_count {
            break;
        }
    }
    unique
}

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

    #[test]
    fn canonical_key_unifies_www_amp_mobile_and_param_order() {
        let variants = [
            "https://example.com/article",
            "https://www.example.com/article",
            "https://m.example.com/article",
            "https://amp.example.com/article",
            "https://www.example.com/article/",
            "https://www.example.com/article/amp",
            "https://www.example.com/article/index.html",
            "https://www.example.com/article#section-2",
            "https://www.example.com/article?utm_source=fb&fbclid=xyz",
        ];
        let keys: HashSet<String> = variants.iter().map(|v| canonical_key(v)).collect();
        assert_eq!(
            keys.len(),
            1,
            "all variants must collapse to one key, got {keys:?}"
        );
    }

    #[test]
    fn canonical_key_sorts_query_params() {
        // v7.0 treated these as two different pages and scraped both.
        assert_eq!(
            canonical_key("https://x.test/p?b=2&a=1"),
            canonical_key("https://x.test/p?a=1&b=2")
        );
    }

    #[test]
    fn canonical_key_keeps_meaningfully_different_pages_apart() {
        let a = canonical_key("https://x.test/p?id=1");
        let b = canonical_key("https://x.test/p?id=2");
        assert_ne!(a, b);
        assert_ne!(
            canonical_key("https://x.test/a"),
            canonical_key("https://x.test/b")
        );
        // Case-sensitive paths stay distinct.
        assert_ne!(
            canonical_key("https://x.test/Foo"),
            canonical_key("https://x.test/foo")
        );
    }

    #[test]
    fn canonical_key_does_not_strip_host_to_a_public_suffix() {
        // "en." is a strippable prefix, but "en.wikipedia.org" must not become
        // "wikipedia.org" if that would change identity... it should, actually:
        // en.wikipedia.org/wiki/X and wikipedia.org/wiki/X are the same doc.
        // What must NOT happen is stripping to something without a dot.
        assert!(
            canonical_key("https://m.co/x").contains("m.co")
                || canonical_key("https://m.co/x").contains("co")
        );
        // Never produce an empty host.
        assert!(!canonical_key("https://www.com/x").starts_with('/'));
    }

    #[test]
    fn should_skip_matches_host_not_substring() {
        // THE v7.0 BUG: a legitimate article whose PATH mentions a blocked
        // domain was dropped.
        assert!(
            !should_skip("https://news.site.com/why-amazon.com-lost-the-race"),
            "legitimate article must not be skipped"
        );
        assert!(
            !should_skip("https://blog.test/review?q=facebook.com"),
            "blocked domain in a query value must not skip"
        );
        // Real blocks still work, including subdomains.
        assert!(should_skip("https://twitter.com/user/status/1"));
        assert!(should_skip("https://www.facebook.com/page"));
        assert!(should_skip("https://m.tiktok.com/v/1"));
    }

    #[test]
    fn should_skip_rejects_binary_extensions_and_bad_schemes() {
        assert!(should_skip("https://x.test/file.zip"));
        assert!(should_skip("https://x.test/video.mp4"));
        assert!(should_skip("ftp://x.test/a"));
        assert!(should_skip("javascript:alert(1)"));
        assert!(should_skip("not a url"));
        assert!(!should_skip("https://x.test/article.html"));
    }

    #[test]
    fn tracking_params_stripped_but_load_bearing_ones_kept() {
        let k = canonical_key("https://x.test/p?utm_source=a&gclid=b&id=42&ref=partner");
        assert!(k.contains("id=42"), "load-bearing param dropped: {k}");
        assert!(!k.contains("utm_source"), "utm_source not stripped: {k}");
        assert!(!k.contains("gclid"), "gclid not stripped: {k}");
        // `ref` is load-bearing on many sites (GitHub, docs portals) and must
        // survive — v7.0 stripped it and produced 404s.
        assert!(k.contains("ref=partner"), "ref must be preserved: {k}");
    }

    #[test]
    fn registrable_domain_handles_two_level_suffixes() {
        assert_eq!(registrable_domain("www.bbc.co.uk"), "bbc.co.uk");
        assert_eq!(registrable_domain("news.amarujala.com"), "amarujala.com");
        assert_eq!(registrable_domain("a.b.c.example.com"), "example.com");
        assert_eq!(registrable_domain("times.of.india.co.in"), "india.co.in");
        assert_eq!(registrable_domain("example.com"), "example.com");
    }

    #[test]
    fn deduplicate_collapses_variants_and_respects_cap() {
        let urls = vec![
            "https://a.test/x".to_string(),
            "https://www.a.test/x/".to_string(), // dup of the above
            "https://a.test/x?utm_source=q".to_string(), // dup
            "https://b.test/y".to_string(),
            "https://twitter.com/z".to_string(), // blocked
            "https://c.test/w".to_string(),
        ];
        let out = deduplicate(urls, 10, None);
        assert_eq!(out.len(), 3, "got {out:?}");
        let out2 = deduplicate(
            vec![
                "https://a.test/1".into(),
                "https://b.test/2".into(),
                "https://c.test/3".into(),
            ],
            2,
            None,
        );
        assert_eq!(out2.len(), 2);
    }

    #[test]
    fn normalize_url_stays_fetchable() {
        let n = normalize_url("https://Example.COM/Path?b=2&utm_medium=x&a=1#frag").unwrap();
        assert!(n.starts_with("https://"), "{n}");
        assert!(!n.contains("utm_medium"), "{n}");
        assert!(!n.contains('#'), "{n}");
        // Must still parse as a URL.
        assert!(Url::parse(&n).is_ok());
    }

    #[test]
    fn canonical_key_is_utf8_safe() {
        // Devanagari path + query must not panic.
        let k = canonical_key("https://www.amarujala.com/क्रिकेट/विश्व-कप?utm_source=fb");
        assert!(!k.is_empty());
        assert!(!k.contains("utm_source"));
    }

    #[test]
    fn normalize_domain_filter_handles_urls_subdomains_and_rejects_invalid() {
        assert_eq!(
            normalize_domain_filter("docs.rs").as_deref(),
            Some("docs.rs")
        );
        assert_eq!(
            normalize_domain_filter("https://www.GitHub.com/tokio-rs/tokio?tab=1").as_deref(),
            Some("github.com")
        );
        assert_eq!(
            normalize_domain_filter(" .arxiv.org. ").as_deref(),
            Some("arxiv.org")
        );
        assert_eq!(
            normalize_domain_filter("blog.rust-lang.org:443/2026").as_deref(),
            Some("blog.rust-lang.org")
        );
        for bad in [
            "",
            "   ",
            "localhost",
            "not a domain",
            "foo..bar",
            "-bad.com",
            "bad-.com",
        ] {
            assert_eq!(normalize_domain_filter(bad), None, "should reject {bad:?}");
        }
    }

    #[test]
    fn host_matches_domain_is_exact_or_subdomain_never_substring() {
        assert!(host_matches_domain("https://docs.rs/tokio", "docs.rs"));
        assert!(host_matches_domain("https://beta.docs.rs/tokio", "docs.rs"));
        assert!(!host_matches_domain(
            "https://evil-docs.rs/tokio",
            "docs.rs"
        ));
        assert!(!host_matches_domain(
            "https://docs.rs.evil.test/",
            "docs.rs"
        ));
        assert!(host_matches_domain("https://youtu.be/abc", "youtube.com"));
        assert!(!host_matches_domain("not a url", "docs.rs"));
    }

    #[test]
    fn display_domain_strips_www_mobile_amp_but_keeps_meaningful_subdomains() {
        assert_eq!(display_domain("https://www.github.com/a/b"), "github.com");
        assert_eq!(display_domain("https://m.amp.example.com/x"), "example.com");
        assert_eq!(
            display_domain("https://docs.python.org/3/"),
            "docs.python.org"
        );
        assert_eq!(
            display_domain("https://en.wikipedia.org/wiki/Rust"),
            "en.wikipedia.org"
        );
    }
}