Skip to main content

fats/
provider.rs

1//! PROVIDERS: how a URL becomes bytes. `plain` = a direct GET with Safari 26's TLS, HTTP/2 and header profile;
2//! `bd` = Bright Data Web Unlocker; `oxy` / `oxyjs` = Oxylabs Web API `/v1/scrape` without / with JavaScript
3//! rendering (one key, two prices, two timeouts); `decodo` / `decodojs` = Decodo Web Data API `/v1/scrape` the same
4//! way. One table holds names, keys, timeouts and list prices; the router (fetch.rs) decides which to call.
5
6use serde_json::{Value, json};
7use std::time::{Duration, Instant};
8use std::{net::ToSocketAddrs, sync::LazyLock};
9
10#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
11pub enum Tier {
12    #[default]
13    Plain,
14    Bd,
15    Oxy,
16    OxyJs,
17    Decodo,
18    DecodoJs,
19}
20
21#[derive(serde::Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct Spec {
24    /// meta.json / stats name (`brightdata`); `short` is the `provider:` value and the tier-path name (`bd`).
25    pub name: &'static str,
26    pub short: &'static str,
27    pub env: &'static str,
28    pub timeout: Duration,
29    /// USD per request at list price (no API returns a cost).
30    pub price: f64,
31    /// THE capability row the router builds every ladder from (`fetch::Plan::ladder`): `page` (fetches a page),
32    /// `js` (renders JavaScript), `search`, `pdf` (a file's exact bytes), `gov` (government hosts served),
33    /// `auto_geo` (its unset exit country is the best for the target: `sent` names none by default).
34    can: Vec<&'static str>,
35    /// The provider bills a finished job that relays the site's own 5xx (`charged`): Oxylabs' "Not
36    /// charged" is its own API error (`500 REQUEST_FAILED_AFTER_TOO_MANY_RETRIES`, an error envelope, never a
37    /// `results` answer); Bright Data's inner 5xx is an unlock failure (zone counter +0).
38    pub bills_site_5xx: bool,
39    /// What a call adds, for the `no_key` row (`unblock+JS`).
40    pub buys: &'static str,
41    /// A search's typical answer time, s: the default `wait:` of a search this tier leads (`fetch::Plan::search`).
42    pub search_s: u64,
43}
44
45/// The provider table (`src/data/providers.json`): `specs` indexed by `Tier as usize`, `apis` by `Api as usize`,
46/// `links` per account, `cctld` = TLD → `"<exit country> <its page languages>"` (`fetch::langs`).
47/// Prices: Oxylabs Web API $1.00/1k, $1.50/1k with `run_js` (smallest paid plan); Bright Data Web Unlocker
48/// ~$1.50/1k; Decodo $1.00/1k, $1.50/1k with JS. Timeouts: plain 10 s, Oxylabs without JS 10 s (its wins took
49/// 1.4–5.6 s on 40 hard pages, 6 s cut 2 of 3 Reddit threads; a page rung after plain's captcha with both keys and
50/// on every rung with one key, also files, prefetch, `provider:oxy`), Decodo without JS 15 s, BD, Oxylabs and
51/// Decodo with JS 40 s each (`timeout:` sets the renders; of 131 renders that served, 8 took 40–60 s and none
52/// longer; Decodo's measured renders took 35.5 and 38.9 s).
53#[derive(serde::Deserialize)]
54#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
55pub struct Providers {
56    pub specs: Vec<Spec>,
57    pub apis: Vec<ApiRow>,
58    pub links: Vec<Links>,
59    pub cctld: std::collections::HashMap<&'static str, &'static str>,
60}
61
62pub static PROVIDERS: LazyLock<Providers> = LazyLock::new(|| crate::settings::table("providers"));
63
64impl Tier {
65    pub const ALL: [Tier; 6] = [Tier::Plain, Tier::Bd, Tier::Oxy, Tier::OxyJs, Tier::Decodo, Tier::DecodoJs];
66
67    pub fn spec(self) -> &'static Spec {
68        &PROVIDERS.specs[self as usize]
69    }
70
71    /// A tier's short or stored name (`oxyjs`, `oxylabs-js`) → tier; the `provider:` mod refuses `oxyjs`.
72    pub fn parse(s: &str) -> Option<Tier> {
73        Tier::ALL.into_iter().find(|t| t.spec().short == s || t.spec().name == s)
74    }
75
76    /// The tier whose key this one sends, as `fats config` lists it (`oxyjs` → `oxy`): the first with its env.
77    pub fn owner(self) -> Tier {
78        Tier::ALL.into_iter().find(|t| t.spec().env == self.spec().env).unwrap_or(self)
79    }
80
81    /// The JS rung of a provider whose key also fetches without JS (oxyjs, decodojs): the call asks for a render
82    /// (`Ask::js`) and the copy drops `<noscript>` (`clean::build_doc`); bd renders on its own.
83    pub fn renders(self) -> bool {
84        self.owner() != self
85    }
86
87    /// The tier's row says it does `job` (`Spec::can`).
88    pub fn can(self, job: &str) -> bool {
89        self.spec().can.contains(&job)
90    }
91
92    /// The name `fats setup <name> on|off` switches: the key's owner, `free` for plain.
93    pub fn switch(self) -> &'static str {
94        if self == Tier::Plain { "free" } else { self.owner().spec().short }
95    }
96
97    /// The key this tier sends (`saved_key`; Bright Data's needs the zone too); None = not configured, or
98    /// switched off (`settings::on`). Plain needs none: an empty key.
99    pub fn key(self) -> Option<String> {
100        match self {
101            Tier::Plain => crate::settings::on(self.switch()).then(String::new),
102            Tier::Bd => crate::settings::zone().and_then(|_| self.saved_key()),
103            _ => self.saved_key(),
104        }
105    }
106
107    /// Its owner's saved key as `setup`, `account` and `config` read it (`settings::key`): switched off = none;
108    /// Bright Data's needs no zone here.
109    pub fn saved_key(self) -> Option<String> {
110        crate::settings::on(self.switch()).then(|| crate::settings::key(self.switch())).flatten()
111    }
112}
113
114/// Short name for a stored provider name (`brightdata` → `bd`); unknown names pass through.
115pub fn short(name: &str) -> &str {
116    PROVIDERS.specs.iter().find(|s| s.name == name).map_or(name, |s| s.short)
117}
118
119/// What to fetch and how.
120#[derive(Clone, Default)]
121pub struct Ask {
122    pub url: String,
123    /// A render (`Tier::renders`): Oxylabs `run_js`, Decodo `headless`.
124    pub js: bool,
125    /// `country:` as given, ISO 3166-1 alpha-2, lower case (`fr`); see `country` for what each tier sends.
126    pub country: Option<String>,
127    pub timeout: Option<Duration>,
128    /// Body cap in bytes (`max_bytes:`).
129    pub max_bytes: u64,
130    /// `device:mobile`: Oxylabs emulates a phone's user agent and viewport; Bright Data has no such setting.
131    pub mobile: bool,
132    /// A PDF run (fetch `pdf_run`): Bright Data sends the file's bytes (`format: raw`), not a JSON string.
133    pub doc: bool,
134    /// Plain sends the browser's own `Accept`, without `MD_ACCEPT`: `fetch::run`'s second call after a weak Markdown
135    /// answer, and a picture download (`cli::download`).
136    pub html: bool,
137}
138
139/// Plain's `Accept` (`FATS_ACCEPT_MD`, not in a PDF run): Markdown first, then Safari's own list, so a server that
140/// converts its pages (Cloudflare's Markdown for Agents, `text/markdown`) skips our CONVERT and any other server
141/// answers as it does a browser.
142pub const MD_ACCEPT: &str = "text/markdown;q=1.0, text/html;q=0.9, application/xhtml+xml;q=0.9, */*;q=0.8";
143
144/// A target's answer, whoever carried it. `headers` = lowercase `name: value` lines (bot-wall vendors live there).
145#[derive(Default)]
146pub struct Raw {
147    pub status: u16,
148    pub final_url: String,
149    pub ctype: String,
150    pub headers: String,
151    pub body: Vec<u8>,
152    /// What the body was decoded from (`windows-1250`; "" = UTF-8, as provider APIs return JSON strings).
153    pub charset: &'static str,
154    /// The provider's request budget, when its answer said (`Limit`).
155    pub limit: Option<Limit>,
156    /// The page whose meta refresh plain followed (`refresh`) to this one (`Meta::refreshed_from`): kept to be
157    /// seen, never a base, never what `outline::lost_page` judges (the target is, as any landing).
158    pub refreshed_from: Option<String>,
159    /// Plain's https failure an http copy stands in for (`plain`): `tls:wrong-version-number+http:200`.
160    pub why: String,
161}
162
163/// A provider's own request budget from its answer: the two numbers only. Oxylabs Web API sends
164/// `x-ratelimit-<bucket>-<account number>-limit` and `-remaining` (search 10, scrape 250; undocumented, window
165/// unknown; observed, not documented). The header names carry the account number, so they are never kept.
166#[derive(Clone, Copy, Debug, Default, PartialEq)]
167pub struct Limit {
168    pub limit: u32,
169    pub remaining: u32,
170}
171
172/// Seconds before a rate-limited call is worth retrying when the answer gives none (`retry-after`).
173pub const RETRY_AFTER: u64 = 5;
174
175/// A failed call: the stable code, and the provider's own answer when it sent one (HTTP status, body). The body
176/// is never printed: it is masked here and kept only as the snapshot's `error.txt` (a provider may echo the
177/// key in it: ScrapingBee's 401 does).
178#[derive(Debug, Default, PartialEq)]
179pub struct Fail {
180    pub code: &'static str,
181    pub status: u16,
182    pub body: Vec<u8>,
183    /// What the `!` row may add to the code: a short token read from the answer (`proxy_error`), never raw text.
184    pub why: String,
185    pub limit: Option<Limit>,
186}
187
188impl From<&'static str> for Fail {
189    fn from(code: &'static str) -> Fail {
190        Fail { code, ..Fail::default() }
191    }
192}
193
194/// One call. Err = a stable code. `billed` = the provider charges for it (`charged`).
195pub async fn get(t: Tier, ask: &Ask, key: &str) -> (Result<Raw, Fail>, bool) {
196    let wait = ask.timeout.unwrap_or(t.spec().timeout);
197    let r = match t {
198        Tier::Plain => plain(ask, wait).await,
199        Tier::Bd => brightdata(ask, key, wait).await,
200        Tier::Oxy | Tier::OxyJs => oxylabs(ask, key, wait).await,
201        Tier::Decodo | Tier::DecodoJs => decodo(ask, key, wait).await,
202    };
203    let billed = charged(t, r.as_ref().map(|raw| raw.status));
204    (r.and_then(|raw| if raw.body.len() as u64 > ask.max_bytes { Err("too_big".into()) } else { Ok(raw) }), billed)
205}
206
207/// Run `f` to its end on a fresh single-thread runtime: the one bridge from the blocking CLI to async calls.
208/// None = no runtime could be built (the caller's `net_error`).
209pub fn block<F: Future>(f: F) -> Option<F::Output> {
210    Some(tokio::runtime::Builder::new_current_thread().enable_all().build().ok()?.block_on(f))
211}
212
213/// A command answers by `wait:`: `calls` run side by side on one runtime, each answer in order;
214/// None = still running at `wait` (given up, the row says `late`).
215pub fn all_within<F>(calls: Vec<F>, wait: Duration) -> Vec<Option<F::Output>>
216where
217    F: Future<Output: Send> + Send + 'static,
218{
219    let mut got: Vec<Option<F::Output>> = calls.iter().map(|_| None).collect();
220    block(async {
221        let mut set = tokio::task::JoinSet::new();
222        for (i, call) in calls.into_iter().enumerate() {
223            set.spawn(async move { (i, call.await) });
224        }
225        let end = tokio::time::Instant::now() + wait;
226        while let Ok(Some(Ok((i, answer)))) = tokio::time::timeout_at(end, set.join_next()).await {
227            got[i] = Some(answer);
228        }
229    });
230    got
231}
232
233/// A call given up at the command's `wait:` (`all_within`, a search's deadline): `provider_timeout wait:5s`.
234pub fn late(wait: Duration) -> Fail {
235    Fail { why: format!("wait:{}s", wait.as_secs()), ..Fail::from("provider_timeout") }
236}
237
238/// The second resolver, asked only when the system resolver found no address: Cloudflare's DNS over HTTPS (JSON,
239/// developers.cloudflare.com 1.1.1.1 dns-json: GET `name` + `type`, `accept: application/dns-json`; `Status` = the
240/// DNS RCODE, `Answer` the records, `type` 1 = A, 28 = AAAA). Some(true) = an address (A, else AAAA: asked only
241/// on no A), Some(false) = none: NXDOMAIN (RCODE 3) or NODATA (NOERROR, no address: a dead name in a signed zone
242/// answers so), None = no verdict (unreachable, SERVFAIL).
243pub async fn exists(host: &str) -> Option<bool> {
244    for (ty, code) in [("A", 1), ("AAAA", 28)] {
245        let (body, ..) = api(Api::Doh, "", json!({"name": host, "type": ty}), 64 << 10, DOH_WAIT).await.ok()?;
246        let j = serde_json::from_slice::<Value>(&body).ok()?;
247        let records = j["Answer"].as_array().into_iter().flatten();
248        match j["Status"].as_u64()? {
249            0 if records.into_iter().any(|r| r["type"] == code) => return Some(true),
250            0 => {}
251            3 => return Some(false),
252            _ => return None,
253        }
254    }
255    Some(false)
256}
257
258/// A keyless call to fats's own endpoint (`telemetry`): the 200's body, else what failed (the HTTP status, or the
259/// code when no reply came), never a row.
260pub async fn ours(to: Api, req: Value, wait: Duration) -> Result<Vec<u8>, String> {
261    let fail = |f: Fail| if f.status > 0 { f.status.to_string() } else { f.code.to_string() };
262    api(to, "", req, 64 << 10, wait).await.map(|a| a.0).map_err(fail)
263}
264
265pub const DOH_WAIT: Duration = Duration::from_millis(1500);
266
267/// THE host check, before any tier runs (`js:true` skips plain too): the system resolver, and on no address the second
268/// resolver (`exists`, asked on that failure only). A host with no address from both (NXDOMAIN or NODATA alike) is a
269/// plain hop `no_host`, one whose every address is private `private_address`: final, $0, no provider call. No paid call
270/// before a verdict on the address: none within `dns_wait` seconds is a final `dns_timeout` (when the providers ran at
271/// a shorter wait, a name of 127.0.0.1 billed a render of the provider's own loopback); worst case `dns_wait` + the
272/// second resolver's two calls (A, then AAAA on no A), `DOH_WAIT` 1.5 s each: ≤ 3 s. One lookup: the system resolver
273/// retries on its own, and a second one for the same name only joins the first (macOS mDNSResponder: an unanswered
274/// query is sent again at ≥ 1 s, doubling, uDNS.c `UDNSBackOffMultiplier`; the same question is a `DuplicateOf` the
275/// first, mDNS.c; glibc: `attempts:2` × `timeout:5`, resolv.conf(5)). Within the agent's `timeout:` (`agent_left`) when
276/// shorter: the lookup is no part of a call, the wall holds it all the same. None = the host resolves public, or the
277/// URL names an IP address; else the hop's code and why (`fetch::host_hop`). A real run's only: `dry:true` looks
278/// nothing up (`lang::real_host`, its shape rule `askable` here too).
279pub fn host_check(url: &str, wall: Option<Duration>) -> Option<(&'static str, String)> {
280    let url::Host::Domain(host) = url::Url::parse(url).ok()?.host()?.to_owned() else { return None };
281    let (t0, (tx, rx), name) = (Instant::now(), std::sync::mpsc::channel(), host.clone());
282    // a name no resolver can ask for (`lang::askable`: an empty or 64-char label, a hyphen at a label's end) is
283    // looked up by neither resolver: `no_host` at once, $0, never the network's fault
284    let ask = crate::lang::askable(&host);
285    ask.then(|| std::thread::spawn(move || tx.send(lookup(&name))));
286    let all = rx
287        .recv_timeout(Duration::from_secs(crate::settings::limit("dns_wait")).min(wall.unwrap_or(Duration::MAX)))
288        .ok();
289    let fast = t0.elapsed() < Duration::from_millis(crate::settings::limit("dns_fast_ms"));
290    // Ok = the system resolver's word (true: every address private); on no address, Err = the second resolver's
291    // (Some(true): it holds an address the system's did not give; Some(false): none, NXDOMAIN or NODATA) and the
292    // system resolver's error
293    let second = || block(exists(&host)).flatten();
294    let got = all.map(|all| match all {
295        Ok(all) if !all.is_empty() => Ok(all_private(&all)),
296        all => Err((second(), all.err())),
297    });
298    // an error back under `dns_fast_ms` was no wait cut short: `dns_wait:` cures nothing there
299    let (code, why) = match got {
300        _ if !ask => ("no_host", None),
301        Some(Ok(true)) if !crate::settings::get().allow_private.value => ("private_address", None),
302        Some(Ok(_) | Err((Some(true), _))) => return None,
303        Some(Err((Some(false), _))) => ("no_host", None),
304        Some(Err((None, why))) if fast => ("dns_failed", why),
305        _ => ("dns_timeout", None),
306    };
307    Some((code, why.unwrap_or_default()))
308}
309
310/// Some addresses, every one private (`host_check`, a redirect hop's `follow`).
311fn all_private(all: &[std::net::SocketAddr]) -> bool {
312    !all.is_empty() && all.iter().all(|a| private_ip(a.ip()))
313}
314
315/// The system resolver's addresses for `host`, or its own error (getaddrinfo's words, `said_short`: `nodename nor
316/// servname provided, or not known`). Under a test's fake transport and in unit tests, the whole network: that
317/// error, a `lag.*` name's after 2 s (`host_check`'s wait), 10.0.0.1 for a `lan.*` name.
318pub fn lookup(host: &str) -> Result<Vec<std::net::SocketAddr>, String> {
319    if in_process() {
320        std::thread::sleep(Duration::from_secs(if host.starts_with("lag.") { 2 } else { 0 }));
321        let lan = host.starts_with("lan.").then(|| vec![([10, 0, 0, 1], 443).into()]);
322        return lan.ok_or_else(|| said_short("nodename nor servname provided, or not known"));
323    }
324    let said = |e: std::io::Error| said_short(&e.to_string().rsplit(": ").next().unwrap_or_default().to_lowercase());
325    (host, 443).to_socket_addrs().map(Iterator::collect).map_err(said)
326}
327
328/// THE billing rule, one for both providers: an answer below 500 is billed; a refusal, a 5xx or a timeout is not,
329/// but a site's 5xx relayed in a finished job is where `bills_site_5xx` (Oxylabs, printed `(assumed)` until one is
330/// reconciled). Oxylabs: "All upstream engines failed. Not charged." (developers.oxylabs.io/products/web-api/
331/// troubleshooting, its own error envelope, a `provider_error` here); its no-JS and 60 s cuts end in that 500 (10 of
332/// 11 re-run at 60 s, measured 2026-10-14). Bright Data: the zone counter moved +20 for ~28 calls, its 3 `http_502` and
333/// 6 timeouts unbilled. A search answer with no result list is not (bd: +0
334/// for 2 such `provider_error`s). A call WE cut has no answer: its price is unverified (`fetch::billed`:
335/// bd billed 15 s search cuts; "a cut is free" held for 1-s cuts only).
336pub fn charged(t: Tier, status: Result<u16, &Fail>) -> bool {
337    t != Tier::Plain && status.is_ok_and(|s| s < 500 || t.spec().bills_site_5xx)
338}
339
340/// The codes that carry the provider's own reason (`reason`: its error envelope, its refusal of the URL): a 4xx of
341/// one settles its tier (`fetch::settled`), `stats` and a failed row print that reason.
342pub const OWN_REASON: [&str; 2] = ["provider_error", "provider_refused"];
343
344/// THE list of the provider's own refusals (`OWN_REASON`, bd's `x-brd-error`, a rate limit): no answer, so never
345/// billed (`charged` gets them as an `Err`); a tried path says `$0 (not charged)`, a priced retry after one
346/// ` · last try not charged`.
347pub const REFUSED: &[&str] = &[OWN_REASON[0], OWN_REASON[1], "rate_limited"];
348
349/// THE money total: from +0.0, so nothing spent prints `$0.0000` (`sum::<f64>()` of nothing is −0.0 → `$-0.0000`).
350pub fn spend(costs: impl IntoIterator<Item = f64>) -> f64 {
351    costs.into_iter().fold(0.0, |total, cost| total + cost)
352}
353
354/// A transport error's code; a TLS handshake that failed says so in `why`: `tls:<reason>` from BoringSSL's error
355/// stack, whose text is `[REASON] …` (btls 0.5.6 `ErrorStack`'s Display: `tls:certificate-verify-failed`).
356fn net(e: &wreq::Error) -> Fail {
357    let mut src: Option<&(dyn std::error::Error + 'static)> = Some(e);
358    let mut tls = String::new();
359    while let Some(s) = src {
360        if s.is::<Private>() {
361            return Fail::from("private_address");
362        }
363        if let Some(r) = s.to_string().strip_prefix('[').and_then(|r| r.split(']').next()) {
364            tls = format!("tls:{}", r.to_lowercase().replace('_', "-"));
365        }
366        src = s.source();
367    }
368    let code = match () {
369        _ if e.is_timeout() => "provider_timeout",
370        _ if e.is_connect() || e.is_dns() || e.is_tls() => "connect_failed",
371        _ => "net_error",
372    };
373    Fail { why: said_short(&tls), ..Fail::from(code) }
374}
375
376/// A header map as (name, value) pairs; names are lower case already.
377fn pairs(h: &wreq::header::HeaderMap) -> Vec<(String, String)> {
378    h.iter().map(|(k, v)| (k.as_str().to_string(), String::from_utf8_lossy(v.as_bytes()).into())).collect()
379}
380
381/// Headers as `Raw::headers` keeps them: `name: value` lines, all lower case (wall vendors are matched on them; the
382/// HTTP stack hands names in lower case anyway), never one that carries a credential (words.json
383/// `secret_headers`: the site's session cookie, an auth challenge; `fats u1 headers` prints them to a model).
384fn header_lines<'a>(h: impl Iterator<Item = (&'a String, &'a str)>) -> String {
385    let safe = |(k, _): &(&String, &str)| !crate::lang::WORDS.secret_headers.contains(&k.to_lowercase().as_str());
386    h.filter(safe).map(|(k, v)| format!("{}: {}\n", k.to_lowercase(), v.to_lowercase())).collect()
387}
388
389/// Plain is your own connection, so its client takes no proxy (`no_proxy`): through one, the proxy resolves the
390/// name and `Fence` never runs. wreq 0.16.3 takes `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` (either case) by
391/// default and, without its `system-proxy` feature, nothing else (proxy/matcher.rs `Builder::from_env`). Some =
392/// one is set: the one line status and `config` print.
393pub fn proxy_note() -> Option<&'static str> {
394    let vars = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].map(|k| [k.to_string(), k.to_lowercase()]);
395    let set = vars.as_flattened().iter().any(|k| crate::settings::env(k).is_some());
396    set.then_some("proxy env ignored on plain (your own connection); paid tiers are the proxies")
397}
398
399async fn plain(ask: &Ask, wait: Duration) -> Result<Raw, Fail> {
400    let client = wreq::Client::builder()
401        .emulation(browser())
402        .no_proxy()
403        .redirect(wreq::redirect::Policy::none())
404        .dns_resolver(Fence)
405        .timeout(wait)
406        .build()
407        .map_err(|_| "net_error")?;
408    let send = |u: String| {
409        let req = client.get(&u);
410        let md = crate::settings::get().accept_md.value && !ask.doc && !ask.html;
411        let req = if md { req.header(wreq::header::ACCEPT, MD_ACCEPT) } else { req };
412        async move {
413            let r = req.send().await.map_err(|e| net(&e))?;
414            let to = r.headers().get("location").map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned());
415            Ok::<_, Fail>((r.status().as_u16(), to, r))
416        }
417    };
418    let read = |at: String| {
419        let send = &send;
420        async move {
421            let (final_url, r) = follow(&at, send).await?;
422            let (status, headers) =
423                (r.status().as_u16(), header_lines(pairs(r.headers()).iter().map(|h| (&h.0, h.1.as_str()))));
424            let ctype = r.headers().get("content-type").map(|v| String::from_utf8_lossy(v.as_bytes()).to_lowercase());
425            let ctype = ctype.unwrap_or_default();
426            let body = capped(r, ask.max_bytes).await?;
427            let declared =
428                ctype.split("charset=").nth(1).map(|c| c.split(';').next().unwrap_or(c).trim_matches(['"', ' ']));
429            // a picture's bytes are never text (`cli::asset`)
430            let (body, charset) = if ctype.starts_with("image/") { (body, "") } else { decode_body(body, declared) };
431            Ok::<Raw, Fail>(Raw { status, final_url, ctype, headers, body, charset, ..Raw::default() })
432        }
433    };
434    // https the host's listener would not take (`connect_failed`: TLS, reset, refused; the host resolved,
435    // `host_check`) is no wall: every tier meets the same listener. The same URL over http, once, in the same turn
436    // of the brake (a redirect's way). Its why keeps the https cause first, then what http answered
437    // (`tls:wrong-version-number+http:200`); a 2xx copy goes through the content check as any plain body
438    // (`fetch::judge`), any other answer leaves the https failure. A certificate's refusal (expired, wrong host,
439    // untrusted: `tls:certificate-*`) under it is the site's answer (`tls_failed`, final): every tier meets the same
440    // certificate, a paid one only when asked (expired.badssl.com: http 301 back to https, then oxy + oxyjs, $0.0025)
441    let mut first = read(ask.url.clone()).await;
442    if let Err(f) = &mut first
443        && f.code == "connect_failed"
444        && let Some(r) = ask.url.strip_prefix("https:")
445    {
446        let cause = if f.why.is_empty() { String::new() } else { format!("{}+", f.why) };
447        match read(format!("http:{r}")).await {
448            Ok(raw) if (200..300).contains(&raw.status) => {
449                first = Ok(Raw { why: format!("{cause}http:{}", raw.status), ..raw })
450            }
451            h => {
452                f.why = format!("{cause}http:{}", h.map_or_else(|h| h.code.into(), |r| r.status.to_string()));
453                f.code = if f.why.starts_with("tls:certificate-") { "tls_failed" } else { f.code };
454            }
455        }
456    }
457    let first = first?;
458    let Some(to) = refresh(&first) else { return Ok(first) };
459    // the site's own move in its HTML is followed once, as a `Location` is; a target that errs or answers no 2xx
460    // leaves the refreshing page the page (its host was reached: never thrown away for the target's failure)
461    match read(to).await {
462        Ok(raw) if (200..300).contains(&raw.status) => Ok(Raw { refreshed_from: Some(first.final_url), ..raw }),
463        _ => Ok(first),
464    }
465}
466
467/// The site's own redirect in its HTML (`plain` follows it once, $0): a 2xx HTML page that shows under
468/// `page_chars`, loads no script and holds `<meta http-equiv=refresh content="0; url=…">` to its own origin
469/// (scheme, host and port; http → https the one scheme change) (the content parsed as the WHATWG "shared
470/// declarative refresh steps": a time of digits, `;` or `,`, an optional `url=`, the URL, quotes off). A delay,
471/// a sign, another origin, a script beside it or no URL (`url=` empty reloads the page) is no redirect: a
472/// challenge's 360 s `<noscript>` refresh (no URL), a scripted page's no-JS fallback (an "enable JavaScript"
473/// page). Only a body holding the bytes `http-equiv` is parsed. Some = the target.
474fn refresh(raw: &Raw) -> Option<String> {
475    let html = raw.status < 300 && crate::clean::kind_of(&raw.ctype, &raw.body) == "html";
476    let marked = html && raw.body.windows(10).any(|w| w.eq_ignore_ascii_case(b"http-equiv"));
477    let tree = crate::html::parse(&String::from_utf8_lossy(marked.then_some(&raw.body[..])?));
478    let tag = |n: &&crate::html::Node| n.attr("http-equiv").is_some_and(|v| v.eq_ignore_ascii_case("refresh"));
479    let (delay, rest) = tree.nodes.iter().find(tag)?.attr("content")?.split_once([';', ','])?;
480    let rest = rest.split_once('=').filter(|(k, _)| k.trim().eq_ignore_ascii_case("url")).map_or(rest, |(_, v)| v);
481    // both quote marks, the double one escaped: a bare one would pair this file's literals off (`lang` error_table)
482    let target = rest.trim().trim_matches(['\x22', '\'']);
483    let at = url::Url::parse(&raw.final_url).ok()?;
484    let delay = delay.trim();
485    let to = at.join(target).ok().filter(|_| !target.is_empty())?;
486    let scheme = at.scheme() == to.scheme() || (at.scheme(), to.scheme()) == ("http", "https");
487    let origin = scheme && (at.host_str(), at.port()) == (to.host_str(), to.port());
488    let alone = !tree.nodes.iter().any(|n| n.tag == "script") && origin;
489    let small = crate::fetch::visible(&tree).0.chars().count() < crate::settings::limit("page_chars");
490    (!delay.is_empty() && delay.bytes().all(|b| b == b'0') && alone && small).then(|| to.into())
491}
492
493/// Text is kept as UTF-8: a body with no file magic is decoded from what the header or page declares (else
494/// sniffed); a file (PDF, zip) stays bytes. The one rule for every carrier of a page's bytes (plain, Bright Data
495/// raw, a local file).
496pub fn decode_body(body: Vec<u8>, declared: Option<&str>) -> (Vec<u8>, &'static str) {
497    if crate::clean::sniff(&body).is_some() { (body, "") } else { crate::clean::decode(body, declared) }
498}
499
500// ---------------------------------------------------------------- private-address fence
501
502/// Not a public unicast address: inside a block of `sites.json` `fence`; IPv4 inside IPv6 (mapped, NAT64,
503/// compatible, 6to4) is judged as the IPv4 it carries.
504pub fn private_ip(ip: std::net::IpAddr) -> bool {
505    use std::net::IpAddr::{V4, V6};
506    let bits = |ip| match ip {
507        V4(a) => (u128::from(a.to_bits()), 32),
508        V6(a) => (a.to_bits(), 128),
509    };
510    let block = |(net, n): (&str, &str)| Some((bits(net.parse().ok()?), n.parse::<u32>().ok()?));
511    let (at, width) = bits(ip);
512    // inside a block: the same family, and the address's first `n` bits are the block's
513    let blocks = crate::fetch::SITES.fence.iter().filter_map(|b| block(b.split_once('/')?));
514    let within = || blocks.clone().any(|((net, w), n)| w == width && (at ^ net).checked_shr(w - n.min(w)) == Some(0));
515    let V6(a) = ip else { return within() };
516    let s = a.segments();
517    // an IPv4 inside: mapped `::ffff:a.b.c.d`, NAT64 `64:ff9b::/96`, compatible `::/96`, 6to4 `2002::/16`
518    let v4 = |hi: u16, lo: u16| Some(std::net::Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo)));
519    let v4 = a.to_ipv4_mapped().or(match s {
520        [0x64, 0xff9b, 0, 0, 0, 0, ..] | [0, 0, 0, 0, 0, 0, ..] => v4(s[6], s[7]),
521        [0x2002, ..] => v4(s[1], s[2]),
522        _ => None,
523    });
524    v4.map_or_else(within, |v4| private_ip(V4(v4)))
525}
526
527/// The URL's own host is private (an IP literal in any WHATWG spelling, or `localhost`); DNS names are judged
528/// by `Fence` when they resolve. Always false with `FATS_ALLOW_PRIVATE=1`.
529pub fn private_host(url: &str) -> bool {
530    !crate::settings::get().allow_private.value && private_name(url)
531}
532
533fn private_name(url: &str) -> bool {
534    match url::Url::parse(url).ok().as_ref().and_then(url::Url::host) {
535        Some(url::Host::Ipv4(a)) => private_ip(a.into()),
536        Some(url::Host::Ipv6(a)) => private_ip(a.into()),
537        Some(url::Host::Domain(d)) => {
538            let d = d.trim_end_matches('.');
539            d == "localhost" || d.ends_with(".localhost")
540        }
541        None => true,
542    }
543}
544
545/// THE home-IP brake (plain only, never a provider: they are the other IPs): one plain call to a host at a time
546/// and one start per `plain_host_pace_ms`, across processes (a lock file per host under the cache, `pace/<host>`,
547/// holding the last start, epoch seconds). A plain call WAITS its turn, keys or not: the brake protects the home IP,
548/// it never buys a provider call for a page plain serves free (12 JSON pages of one host: $0 waiting, $0.015
549/// skipping). 0 = no brake. It blocks before the call starts, so the wait is no part of the call's ms. Returns (the
550/// turn, held while the file is open; the ms waited, `Hop::waited`); a file that will not open or lock = no turn, no
551/// wait: the call runs unbraked rather than not at all.
552pub fn pace(url: &str) -> (Option<std::fs::File>, u64) {
553    use std::io::{Seek, Write};
554    let (gap, t0) = (Duration::from_millis(crate::settings::limit("plain_host_pace_ms")), Instant::now());
555    let at = crate::settings::get().cache.value.join("pace").join(crate::clean::host_of(url));
556    let open = || std::fs::OpenOptions::new().create(true).truncate(false).read(true).write(true).open(&at);
557    let file = at.parent().map(std::fs::create_dir_all).and_then(Result::ok).and_then(|()| open().ok());
558    let Some(mut f) = file.filter(|f| !gap.is_zero() && f.lock().is_ok()) else { return (None, 0) };
559    // the start is read and written under the lock (a new host = an empty file: lanes that opened it before the
560    // first start still wait), never the file's mtime (another clock, which a copy or a sync moves); 20 bytes wide,
561    // so each write covers the last whole and a crash mid-write leaves no shorter mix (an older, longer file's
562    // tail is never read)
563    let last = std::io::read_to_string(&f).ok().and_then(|s| s.get(..20)?.parse::<f64>().ok());
564    // a clock stepped back counts as no time gone
565    let since = last.and_then(|t| Duration::try_from_secs_f64((crate::cache::now() - t).max(0.0)).ok());
566    std::thread::sleep(since.and_then(|s| gap.checked_sub(s)).unwrap_or_default());
567    f.rewind().and_then(|()| write!(f, "{:020.6}", crate::cache::now())).ok();
568    (Some(f), t0.elapsed().as_millis() as u64)
569}
570
571/// The resolver for plain fetches: the system's answer minus private addresses, so a name that resolves (or
572/// re-resolves, DNS rebinding) to one never gets a connection.
573struct Fence;
574
575#[derive(Debug)]
576struct Private;
577
578impl std::fmt::Display for Private {
579    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
580        f.write_str("resolves to a private address")
581    }
582}
583
584impl std::error::Error for Private {}
585
586impl wreq::dns::Resolve for Fence {
587    fn resolve(&self, name: wreq::dns::Name) -> wreq::dns::Resolving {
588        Box::pin(async move {
589            let all = tokio::task::spawn_blocking(move || (name.as_str(), 0).to_socket_addrs());
590            let open = crate::settings::get().allow_private.value;
591            let keep: Vec<_> = all.await??.filter(|a| open || !private_ip(a.ip())).collect();
592            if keep.is_empty() {
593                return Err(Box::new(Private) as Box<dyn std::error::Error + Send + Sync>);
594            }
595            Ok(Box::new(keep.into_iter()) as wreq::dns::Addrs)
596        })
597    }
598}
599
600/// Redirects, followed here rather than by the client so every hop's host passes `private_host` (an IP literal
601/// in a `Location` never reaches the resolver) and every redirect's name `hop_private`. The first URL's name is
602/// `host_check`'s for a page; a picture (`cli::download`), a meta-refresh target and the http fallback have only
603/// `Fence` at connect, so a private name there ends `net_error`, never `private_address`. `send` = one request → (status, Location, response). Ok = (final URL, response); at most 10
604/// redirects.
605async fn follow<R, E: From<&'static str>, F>(url: &str, send: impl Fn(String) -> F) -> Result<(String, R), E>
606where
607    F: Future<Output = Result<(u16, Option<String>, R), E>>,
608{
609    let mut at = url.to_string();
610    for hop in 0..=10 {
611        if private_host(&at) || hop > 0 && hop_private(&at).await == Some(true) {
612            return Err("private_address".into());
613        }
614        match send(at.clone()).await? {
615            (301 | 302 | 303 | 307 | 308, Some(to), _) => {
616                at = url::Url::parse(&at).and_then(|u| u.join(&to)).map_err(|_| "net_error")?.into();
617            }
618            (_, _, r) => return Ok((at, r)),
619        }
620    }
621    Err("redirect_loop".into())
622}
623
624/// A redirect's name resolves to private addresses only (the system resolver, `lookup`, within `dns_wait`), checked
625/// before its request, as `host_check` checks the first URL's: `Fence` judges the connect too, this keeps the rule
626/// whatever carries the request. None = an IP literal (`private_host`'s) or no answer in time: the connect's
627/// `Fence` still judges.
628async fn hop_private(url: &str) -> Option<bool> {
629    let url::Host::Domain(host) = url::Url::parse(url).ok()?.host()?.to_owned() else { return None };
630    let wait = Duration::from_secs(crate::settings::limit("dns_wait"));
631    let all = tokio::time::timeout(wait, tokio::task::spawn_blocking(move || lookup(&host))).await.ok()?.ok()?.ok()?;
632    Some(all_private(&all) && !crate::settings::get().allow_private.value)
633}
634
635/// The body, frame by frame, refused as soon as it passes `cap` bytes: a chunked or lying server never fills
636/// memory (Content-Length, when sent, refuses it before the first frame, its size the why).
637async fn capped(mut r: wreq::Response, cap: u64) -> Result<Vec<u8>, Fail> {
638    use http_body::Body;
639    if let Some(n) = r.content_length().filter(|&n| n > cap) {
640        return Err(Fail { why: format!("{}B", crate::lang::ksize(n as usize)), ..Fail::from("too_big") });
641    }
642    let mut v = Vec::new();
643    while let Some(f) = std::future::poll_fn(|cx| std::pin::Pin::new(&mut r).poll_frame(cx)).await {
644        let Ok(d) = f.map_err(|e| net(&e))?.into_data() else { continue };
645        if (v.len() + d.len()) as u64 > cap {
646            return Err("too_big".into());
647        }
648        v.extend_from_slice(&d);
649    }
650    Ok(v)
651}
652
653// ---------------------------------------------------------------- provider APIs: the one table, the one sender
654
655/// Every provider API this binary sends a key to. A call names an `Api`, never a URL string, so a key can only
656/// go to a URL in `Providers::apis`: scrape, search, and the account reads `fats account` makes. Account endpoints that
657/// return secrets are never listed (Bright Data `GET /zone` and `/zone/passwords` return zone passwords,
658/// Webshare `/proxy/list` returns proxy passwords).
659#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
660pub enum Api {
661    BdRequest,
662    OxyScrape,
663    OxySearch,
664    /// Account reads (`fats account`): Oxylabs has no balance or usage API for the Web API key; the scraper list
665    /// answers 200 or 401, so it is the key check (developers.oxylabs.io products/web-api).
666    OxyScrapers,
667    /// Bright Data Account Management API (docs.brightdata.com api-reference/account-management-api): balance in
668    /// USD, active zones `[{name, type}]`, the cost export (a read, documented as POST), one zone's month.
669    BdBalance,
670    BdZones,
671    BdCosts,
672    BdZoneCost,
673    /// DNS over HTTPS (`exists`): no key.
674    Doh,
675    /// GitHub repository search and one account's repositories (`gh_repos`): the GitHub token, or none.
676    GhRepos,
677    GhUser,
678    /// Decodo Web Data API (github.com/Decodo/sdk-ts `src/client.ts`, `Authorization: Bearer <api key>`): pages,
679    /// and the key check (`check_call`).
680    DecodoScrape,
681    /// fats's own endpoints (`telemetry`): the daily update check and the weekly counts; no key.
682    Telemetry,
683    TelemetryL2,
684}
685
686/// A row of `Providers::apis`: the method, the URL, and what an account read gets (`account dry:true`, `{from}`
687/// `{to}` = the month). A GET sends the request's fields as the query string.
688#[derive(serde::Deserialize)]
689#[serde(deny_unknown_fields)]
690pub struct ApiRow {
691    pub api: Api,
692    pub method: &'static str,
693    pub url: &'static str,
694    pub what: &'static str,
695    /// The `accept` header the API asks for (DoH: `application/dns-json`); empty = none.
696    #[serde(default)]
697    pub accept: &'static str,
698}
699
700impl Api {
701    pub fn row(self) -> &'static ApiRow {
702        &PROVIDERS.apis[self as usize]
703    }
704
705    /// The URL a call to `self` goes to: a GET's `req` string fields as the query (`send`, `account dry:true`).
706    pub fn url(self, req: &Value) -> String {
707        let get = req.as_object().into_iter().flatten().filter(|_| self.row().method == "GET");
708        let pairs = get.map(|(k, v)| (k, v.as_str().unwrap_or_default()));
709        let q = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
710        // a path's `{q}` (GhUser's login, `[A-Za-z0-9-]` only) is the request's `q`, also sent in the query
711        let url = crate::lang::draw(self.row().url, &[("q", req["q"].as_str().unwrap_or_default())]);
712        if q.is_empty() { url } else { format!("{url}?{q}") }
713    }
714}
715
716/// A provider's dashboard pages, printed after a `!` row's fix (`→ <link>`); never requested, never sent a key.
717/// Only pages the providers' own docs give as a URL (read 2026-10-12);
718/// a page the docs reach only by menu path is None, never a guessed URL. In rank order (`fats setup` lists them so,
719/// best first), with the setup card's words.
720#[derive(serde::Deserialize)]
721#[serde(deny_unknown_fields)]
722pub struct Links {
723    pub short: &'static str,
724    pub name: &'static str,
725    pub signup: &'static str,
726    pub mint: &'static str,
727    pub keys: Option<&'static str>,
728    pub billing: Option<&'static str>,
729    pub usage: Option<&'static str>,
730    pub rank: &'static str,
731    pub free: &'static str,
732    pub cost: &'static str,
733    pub step: &'static str,
734}
735
736/// A provider's pages by any tier name that uses its key (`oxyjs` → Oxylabs).
737pub fn links(short: &str) -> Option<&'static Links> {
738    PROVIDERS.links.iter().find(|l| l.short == Tier::parse(short).map_or(short, |t| t.owner().spec().short))
739}
740
741/// THE page a `!` row about a provider's key or money ends with: `no_key` → sign-up, `bad_key` → the keys
742/// page, `low_balance` → billing. None = another code, or the docs give no URL for that page.
743pub fn page(code: &str, short: &str) -> Option<String> {
744    let l = links(short)?;
745    match code {
746        "no_key" => Some(l.signup.into()),
747        "bad_key" => l.keys.map(String::from),
748        "low_balance" => l.billing.map(String::from),
749        _ => None,
750    }
751}
752
753/// `page` for every provider a row names, appended after its fix: ` · bd https://…` ("" when none has one).
754pub fn pages<'a>(code: &str, names: impl IntoIterator<Item = &'a str>) -> String {
755    names.into_iter().filter_map(|n| page(code, n).map(|p| format!(" · {n} {p}"))).collect()
756}
757
758/// A provider API's answer before it is read: HTTP status, headers (lower-case names), body. Headers live only
759/// here: `read` takes the few values it needs, nothing stores or prints them.
760pub struct Reply {
761    pub status: u16,
762    pub headers: Vec<(String, String)>,
763    pub body: Vec<u8>,
764}
765
766impl Reply {
767    fn header(&self, name: &str) -> Option<&str> {
768        self.headers.iter().find(|h| h.0 == name).map(|h| h.1.as_str())
769    }
770
771    /// Bright Data's refusal: HTTP 200 (also for `format: raw` with an empty body) and the reason in `x-brd-error`
772    /// (`x-luminati-error` before the rename), its code in `x-brd-error-code` (observed 2026-10-12).
773    fn refused(&self) -> bool {
774        self.header("x-brd-error").or(self.header("x-luminati-error")).is_some()
775    }
776
777    /// Seconds until a rate-limited call is worth retrying, None = not a rate limit that says so. Oxylabs: a 429
778    /// titled `RATE_LIMIT_EXCEEDED` (`retry-after`, else `RETRY_AFTER`). GitHub (docs.github.com rest
779    /// "Exceeding the rate limit"): a 403 or 429 with `retry-after`, or with `x-ratelimit-remaining: 0` until
780    /// `x-ratelimit-reset` (UTC epoch seconds).
781    fn retry_in(&self) -> Option<u64> {
782        let num = |name: &str| self.header(name).and_then(|s| s.trim().parse::<u64>().ok());
783        let after = num("retry-after").filter(|s| (1..=3600).contains(s));
784        let titled = serde_json::from_slice::<Value>(&self.body).is_ok_and(|j| j["title"] == "RATE_LIMIT_EXCEEDED");
785        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
786        let reset = num("x-ratelimit-reset").filter(|_| num("x-ratelimit-remaining") == Some(0));
787        let rate = self.status == 429 && titled;
788        after.or(if rate { Some(RETRY_AFTER) } else { reset.map(|t| t.saturating_sub(now).max(1)) })
789    }
790
791    /// The account's own `x-ratelimit-…-limit` / `-remaining` pair (not the `system_` one every client shares).
792    fn limit(&self) -> Option<Limit> {
793        let num = |end: &str| {
794            let mine = |n: &str| n.starts_with("x-ratelimit-") && !n.contains("system_") && n.ends_with(end);
795            self.headers.iter().find(|h| mine(&h.0)).and_then(|h| h.1.trim().parse().ok())
796        };
797        Some(Limit { limit: num("-limit")?, remaining: num("-remaining")? })
798    }
799}
800
801/// The provider's own reason for its error answer (`Fail::why`, the `!` row's): its status, then what an RFC 9457
802/// problem document names (Oxylabs Web API, developers.oxylabs.io/api-reference/errors-and-status-codes): the
803/// first field error's pointer and detail (`400 url: value not supported`), else `faulted` when its own retries
804/// gave up (`state`) and the title (`500 faulted: request failed after too many retries`). Fields only, never raw
805/// text, each masked (`lang::redact`) as DECODED (a key spelled in JSON escapes is a key) before it is lowered:
806/// words of `[a-z0-9.,:/#-]` (a masked `***` drops), whole words up to 50 chars (the tier's name before it stays
807/// ≤ 60); the bare status when the body names nothing (Oxylabs' 401: empty; HTML). `fetch::settled` reads the
808/// status back.
809fn reason(status: u16, body: &[u8], secrets: &[String]) -> String {
810    let j: Value = serde_json::from_slice(body).unwrap_or_default();
811    let text = |v: &Value| crate::lang::redact(v.as_str().unwrap_or_default(), secrets).to_lowercase();
812    let e = &j["errors"][0];
813    let faulted = if j["state"] == "faulted" { "faulted".into() } else { String::new() };
814    let (label, said) = match text(&e["detail"]) {
815        d if !d.is_empty() => (text(&e["pointer"]).rsplit('/').next().unwrap_or_default().to_string(), d),
816        _ => (faulted, text(&j["title"]).replace('_', " ")),
817    };
818    said_short(&format!("{status} {} {said}", if label.is_empty() { label } else { label + ":" }))
819}
820
821/// Words as a printable reason: those of `[a-z0-9.,:/#-]` only, at most `reason_chars` chars, no trailing `.` or `:`.
822fn said_short(words: &str) -> String {
823    let ok = |w: &&str| w.bytes().all(|b| b.is_ascii_alphanumeric() || b".,:/#-".contains(&b));
824    let (mut n, cap) = (0, crate::settings::limit::<usize>("reason_chars") + 1);
825    let fits = words.split_whitespace().filter(ok).take_while(|w| {
826        n += w.len() + 1;
827        n <= cap
828    });
829    let fits: Vec<&str> = fits.collect();
830    fits.join(" ").trim_end_matches(['.', ':']).to_string()
831}
832
833/// A header value as a printable token: `[a-z0-9_]`, at most 32 chars; anything else is dropped (empty).
834fn token(v: Option<&str>) -> String {
835    let v = v.unwrap_or_default().trim().to_ascii_lowercase();
836    let ok =
837        !v.is_empty() && v.len() <= 32 && v.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
838    if ok { v } else { String::new() }
839}
840
841/// The fake network of tests (tests/redact.rs): (api, key, request) → reply, set once per process. Only
842/// in builds with the `fake` feature; the shipped binary has no such hook.
843#[cfg(feature = "fake")]
844pub type Fake = fn(Api, &str, &Value) -> Reply;
845#[cfg(feature = "fake")]
846static FAKE: std::sync::OnceLock<Fake> = std::sync::OnceLock::new();
847
848#[cfg(feature = "fake")]
849pub fn fake(f: Fake) {
850    FAKE.set(f).ok(); // the first fake holds
851}
852
853/// A test's fake transport answers (`fake`): it lives in this process only, so a detached fetch runs on a
854/// thread here, not in a new process (`cli::detach`). A unit test has no network at all: the same.
855pub fn in_process() -> bool {
856    #[cfg(feature = "fake")]
857    if FAKE.get().is_some() {
858        return true;
859    }
860    cfg!(test)
861}
862
863/// Call a provider API; Ok = the body of a 200. `cap` = the largest body kept (a JSON-escaped page can be twice
864/// its size: fetches pass twice their page cap).
865async fn api(to: Api, key: &str, req: Value, cap: u64, wait: Duration) -> Result<Answer, Fail> {
866    #[cfg(feature = "fake")]
867    if let Some(f) = FAKE.get() {
868        // a fake answer may ask to be slow (`x-fake-delay-ms`): the router's cancel and wait paths under test
869        let r = f(to, key, &req);
870        let ms = r.header("x-fake-delay-ms").and_then(|v| v.parse().ok()).unwrap_or(0);
871        tokio::time::sleep(Duration::from_millis(ms).min(wait)).await;
872        return if ms > wait.as_millis() as u64 { Err("provider_timeout".into()) } else { read(to, key, r) };
873    }
874    read(to, key, send(to, key, req, cap, wait).await?)
875}
876
877/// The only request that carries a key (`bearer_auth`; none when empty), to `to.url()` only: a POST with `req` as
878/// JSON, or a GET with `req`'s string fields as the query. Every call names this tool (`user-agent`).
879async fn send(to: Api, key: &str, req: Value, cap: u64, wait: Duration) -> Result<Reply, &'static str> {
880    let client = wreq::Client::builder().timeout(wait).build().map_err(|_| "net_error")?;
881    let r = match to.row().method {
882        "GET" => client.get(to.url(&req)),
883        _ => client.post(to.row().url).header("content-type", "application/json").body(req.to_string()),
884    };
885    let r = r.header("user-agent", concat!("fatsearch/", env!("CARGO_PKG_VERSION")));
886    let r = if to.row().accept.is_empty() { r } else { r.header("accept", to.row().accept) };
887    let r = if key.is_empty() { r } else { r.bearer_auth(key) };
888    let r = r.send().await.map_err(|e| net(&e).code)?;
889    let status = r.status().as_u16();
890    let mut reply = Reply { status, headers: pairs(r.headers()), body: Vec::new() };
891    reply.body = match (reply.refused(), status) {
892        (false, 200) => capped(r, cap).await.map_err(|f| f.code)?,
893        // an error body over the cap is not worth keeping; the code says what happened
894        _ => capped(r, crate::settings::limit("err_cap_bytes")).await.unwrap_or_default(),
895    };
896    Ok(reply)
897}
898
899/// A provider API's 200: the body, the request budget (`Reply::limit`), and the target's own status where the API
900/// reports it in a header: Bright Data's `/request` answers 200 once its unlocker ran and puts the site's status in
901/// `x-brd-status-code` (docs.brightdata.com products/web-unlocker/error-codes, "Direct API").
902type Answer = (Vec<u8>, Option<Limit>, Option<u16>);
903
904/// A reply → the 200 body, or the code + the body for `error.txt`, masked with the saved keys and `key`, the one
905/// sent (a key `fats setup` checks is saved by none yet).
906/// A 200 with an empty body is a failure too: no API answers a good call with nothing. A rate limit that says
907/// when to retry (`Reply::retry_in`) gets `retry in Ns`; another 429 may be an exhausted quota (Oxylabs' docs give
908/// no title for it), so it gets no retry time; another 403 is a refused key. A 400 whose field error names the URL
909/// (Oxylabs: `url: value not supported` on a host it serves no one) refuses this URL: the same call is refused
910/// again ("No, fix all entries", developers.oxylabs.io/products/web-api/troubleshooting). One naming `location`
911/// refuses the country we sent, not the URL: a `provider_error`, settled for that country only (`fetch::settled`).
912fn read(to: Api, key: &str, r: Reply) -> Result<Answer, Fail> {
913    let limit = r.limit();
914    // the account's own cap (`Limit`: the plan's, not the key's; no window is sent), beside its wait: `cap 10 on
915    // this account · retry in 5s`
916    let cap = limit.map(|l| format!("cap {} on this account · ", l.limit)).filter(|_| !key.is_empty());
917    let target = r.header("x-brd-status-code").and_then(|s| s.trim().parse().ok());
918    // our setup: Bright Data's 400 naming the zone we sent (`zone "nozone" not found`:
919    // its own APIs, the name quoted, a 200 never decoded), its zone-cost read's 422 `Unknown zone` (live
920    // 2026-10-15, naming none)
921    let named = |z: &str| match (to, r.status) {
922        (Api::BdZoneCost, 422) => true,
923        (Api::BdRequest | Api::BdZoneCost, 400) => String::from_utf8_lossy(&r.body).contains(&format!("zone \"{z}\"")),
924        _ => false,
925    };
926    let zone = crate::settings::zone().filter(|z| !z.is_empty() && named(z));
927    let (code, why) = match (r.refused(), r.status) {
928        (false, 200) if !r.body.is_empty() => return Ok((r.body, limit, target)),
929        (false, 200) => ("provider_error", "empty".into()),
930        (true, _) => bd_refused(token(r.header("x-brd-error-code")), r.header("x-brd-status-code"), r.retry_in()),
931        (_, 400 | 422) if let Some(z) = zone => ("bad_zone", z.into()),
932        (_, 403 | 429) if let Some(s) = r.retry_in() => {
933            ("rate_limited", format!("{}retry in {s}s", cap.unwrap_or_default()))
934        }
935        (_, 401 | 403) => ("bad_key", String::new()),
936        (_, 408) => ("provider_timeout", String::new()),
937        (_, 429) => ("rate_limited", String::new()),
938        _ => ("provider_error", String::new()),
939    };
940    let mut secrets = crate::settings::secrets();
941    secrets.extend(Some(key.to_string()).filter(|k| !k.is_empty()));
942    let why = if code == "provider_error" && why.is_empty() { reason(r.status, &r.body, &secrets) } else { why };
943    // the call's own field error on the URL refuses this URL (`reason`: `400 url: …`)
944    let code = if why.starts_with("400 url:") { "provider_refused" } else { code };
945    // a JSON answer is read as decoded (a key spelled in `\u00XX` escapes is a key), then masked
946    let text = serde_json::from_slice::<Value>(&r.body)
947        .map_or_else(|_| String::from_utf8_lossy(&r.body).into(), |j| j.to_string());
948    let body = crate::lang::redact(&text, &secrets).into_bytes();
949    Err(Fail { code, status: r.status, body, why, limit })
950}
951
952/// Bright Data's refusal (`x-brd-error-code`, the `why`) → our code: a rate limit is a wait, not a no
953/// (`bucket_rate_limit`, the same eBay URL served 4 min later), with its retry time when sent; a site status it
954/// relayed (`http_status` + `x-brd-status-code: 403`: a 0-byte body, the zone counter +0) is the
955/// site's block; anything else its own policy (`provider_refused`). None of them is billed (`charged`: no answer).
956fn bd_refused(why: String, site: Option<&str>, retry: Option<u64>) -> (&'static str, String) {
957    const SITE: [&str; 4] = ["blocked_401", "blocked_403", "blocked_429", "blocked_451"];
958    let relayed = site.and_then(|s| SITE.into_iter().find(|c| c[8..] == *s.trim())).filter(|_| why == "http_status");
959    match retry {
960        _ if !why.contains("rate_limit") => (relayed.unwrap_or("provider_refused"), why),
961        Some(s) => ("rate_limited", format!("{why} retry in {s}s")),
962        None => ("rate_limited", why),
963    }
964}
965
966/// Web Unlocker REST: `{zone, url, format: "json", country}` → `{status_code, headers, body}` (the BD CLI's
967/// request shape; `country` = lower-case ISO alpha-2, docs.brightdata.com api-reference unlock-website; sent only
968/// when one is named, `bd_body`). The page's
969/// final URL is `headers["x-unblocker-redirected-to"]` when the site redirected (observed live 2026-10-13 on a
970/// wrong product slug; not in the unlock-website docs); absent = the asked URL.
971async fn brightdata(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
972    let (body, _, target) = api(Api::BdRequest, key, bd_body(ask), 2 * ask.max_bytes, wait).await?;
973    if ask.doc {
974        // the target's body and status as sent (a failure is a header + empty body, `read`). A page (a `/pdf/`
975        // path that was not a file) is decoded to UTF-8 like plain's
976        let (body, charset) = decode_body(body, None);
977        let status = target.unwrap_or(200);
978        return Ok(Raw { status, final_url: ask.url.clone(), body, charset, ..Raw::default() });
979    }
980    let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
981    // its own policy refusal inside the answer: `x-brd-error` among the headers beside a `status_code` below 500
982    // that is Bright Data's, not the site's (a bad port: 403, empty body; zone counter +0 four times).
983    // Beside a 5xx it is an unlock failure (`reject_block`), retried as the 5xx it is (`fetch::FINAL`)
984    let inner = |k: &str| j["headers"][k].as_str();
985    if inner("x-brd-error").is_some() && j["status_code"].as_u64().is_some_and(|s| s < 500) {
986        let why = token(inner("x-brd-err-code").or(inner("x-brd-error-code")));
987        let (code, why) = bd_refused(why, inner("x-brd-status-code"), None);
988        return Err(Fail { why, ..Fail::from(code) });
989    }
990    relayed(&j, "body", j["headers"]["x-unblocker-redirected-to"].as_str().unwrap_or(&ask.url))
991}
992
993/// A target's answer a provider relayed as JSON, `{status_code, headers, <body>}` (Bright Data `body`, Decodo
994/// `content`): no `status_code` = 200; one that is no HTTP status is a broken answer, never truncated (65940 → 404).
995fn relayed(j: &Value, body: &str, final_url: &str) -> Result<Raw, Fail> {
996    let headers =
997        header_lines(j["headers"].as_object().into_iter().flatten().map(|(k, v)| (k, v.as_str().unwrap_or(""))));
998    let status = j["status_code"].as_u64().map_or(Ok(200), u16::try_from).map_err(|_| "provider_error")?;
999    let body = j[body].as_str().unwrap_or_default().as_bytes().to_vec();
1000    Ok(Raw { status, final_url: final_url.into(), headers, body, ..Raw::default() })
1001}
1002
1003/// The country a page's domain names, upper case: its ccTLD's `Providers::cctld` row (sites that answer best from
1004/// inside the country; `.uk` → GB); a gTLD names none.
1005pub fn domain_country(url: &str) -> Option<String> {
1006    let host = crate::clean::host_of(url);
1007    PROVIDERS.cctld.get(host.rsplit('.').next().unwrap_or_default()).map(|c| c[..2].to_uppercase())
1008}
1009
1010/// `FATS_COUNTRY`, upper case: `US` unless set, the country of the Accept-Language plain sends (`settings`).
1011pub fn home() -> String {
1012    crate::settings::get().country.value.to_uppercase()
1013}
1014
1015/// THE geo rule (from a replay of saved copies): the country a page call of `t` sends, upper
1016/// case: the one named (`country:`; an empty one names none), else the domain's (`domain_country`), else `home`:
1017/// always on Oxylabs, whose unset `location` is a random exit (developers.oxylabs.io products/web-api/scrape; 196
1018/// saved paid copies: none sent = 18 of 110 in another language, a country sent = 0 of 8; Reddit's captcha
1019/// came at either exit, 0 of 10), on Bright Data only when it is not the default `US`, else none there: its unset
1020/// default is the best location for the target (docs.brightdata.com products/web-unlocker features; 2 of 77 saved
1021/// copies foreign). Plain sends none. A copy in another language is flagged (`fetch::geo`) with a fix that changes
1022/// the request (`outline::geo_fix`). What the serving call sent is the page's `meta.json` country (`stats` `@FR`).
1023pub fn sent(ask: &Ask, t: Tier) -> Option<String> {
1024    let named = ask.country.as_ref().filter(|c| !c.is_empty()).map(|c| c.to_uppercase());
1025    let home = Some(home()).filter(|h| h != "US" || !t.can("auto_geo"));
1026    (t != Tier::Plain).then(|| named.or_else(|| domain_country(&ask.url)).or(home)).flatten()
1027}
1028
1029/// Web Unlocker `/request` body: `country` only when one is `sent`, `format: raw` for a file's bytes.
1030fn bd_body(ask: &Ask) -> Value {
1031    let format = if ask.doc { "raw" } else { "json" };
1032    let mut req = json!({"zone": crate::settings::zone(), "url": ask.url, "format": format});
1033    if let Some(c) = sent(ask, Tier::Bd) {
1034        req["country"] = c.to_lowercase().into();
1035    }
1036    req
1037}
1038
1039/// Web API `/v1/scrape` request: `{url, output: ["html"], run_js, location, device}` (developers.oxylabs.io
1040/// products/web-api/scrape: `location` = ISO alpha-2, `sent`, never empty; `device` = `desktop` (default) or
1041/// `mobile`). `run_js` is always sent: the same page says an omitted `run_js` takes "the optimal execution path",
1042/// which may render (and bill) JavaScript, and to pass `"run_js": false` for static pages.
1043fn oxy_body(ask: &Ask) -> Value {
1044    let mut req = json!({"url": ask.url, "output": ["html"], "run_js": ask.js, "location": sent(ask, Tier::Oxy)});
1045    if ask.mobile {
1046        req["device"] = "mobile".into();
1047    }
1048    req
1049}
1050
1051/// `/v1/scrape` → `results[0].html`; a file (PDF, zip magic) comes back as bytes (`file_bytes`). The JSON cap is
1052/// 5× the page cap: a file byte can take 5 JSON bytes (`\\x9c`).
1053async fn oxylabs(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
1054    let (body, limit, _) = api(Api::OxyScrape, key, oxy_body(ask), 5 * ask.max_bytes, wait).await?;
1055    let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
1056    let r = &j["results"][0];
1057    let html = r["html"].as_str().ok_or("provider_error")?.as_bytes();
1058    // the target's own answer (a 404 page is a 404, not a page): `metadata.statuses.http_request.code`, observed
1059    // live 2026-10-13, not in the /scrape docs (developers.oxylabs.io products/web-api/scrape.md); absent = 200
1060    let status = r["metadata"]["statuses"]["http_request"]["code"].as_u64().and_then(|c| u16::try_from(c).ok());
1061    Ok(Raw {
1062        status: status.unwrap_or(200),
1063        final_url: r["metadata"]["url"].as_str().unwrap_or(&ask.url).to_string(),
1064        body: if crate::clean::sniff(html).is_some() { file_bytes(html) } else { html.to_vec() },
1065        limit,
1066        ..Raw::default()
1067    })
1068}
1069
1070/// Web Data API `/v1/scrape`, `universal` target (github.com/Decodo/sdk-ts `src/generated/request-schemas.ts`):
1071/// `{url, target, geo, headless, device_type}` → `results[0].{content, status_code, url, headers}`. HTML, never
1072/// `markdown: true`: a Markdown answer skips the content check (walls, shells) and loses the page's own data.
1073/// `geo` = `sent` as Decodo's own CLI passes it (`--geo de`, github.com/Decodo/cli); `headless: "html"` = the JS
1074/// rung; `device_type: "mobile"` (Decodo/Web-Scraping-API README).
1075fn decodo_body(ask: &Ask) -> Value {
1076    let mut req = json!({"url": ask.url, "target": "universal"});
1077    if let Some(c) = sent(ask, Tier::Decodo) {
1078        req["geo"] = c.to_lowercase().into();
1079    }
1080    if ask.js {
1081        req["headless"] = "html".into();
1082    }
1083    if ask.mobile {
1084        req["device_type"] = "mobile".into();
1085    }
1086    req
1087}
1088
1089async fn decodo(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
1090    let (body, limit, _) = api(Api::DecodoScrape, key, decodo_body(ask), 2 * ask.max_bytes, wait).await?;
1091    let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
1092    let r = &j["results"][0];
1093    r["content"].as_str().ok_or("provider_error")?;
1094    Ok(Raw { limit, ..relayed(r, "content", r["url"].as_str().unwrap_or(&ask.url))? })
1095}
1096
1097/// A file's bytes from Oxylabs' `html` string. It is the file decoded as UTF-8 with every byte that does not
1098/// decode written as the 4 characters `\xNN` (Python's `backslashreplace`: lower-case hex, and only bytes
1099/// 0x80–0xff, since every byte below 0x80 decodes). So only `\x[89a-f][0-9a-f]` is an escape; a `\x48` is the
1100/// file's own text. Measured: arXiv 2405.15793 (4,963,538 B) holds two such runs; reading every `\xNN` as an
1101/// escape left it 6 bytes short; this rule gives it back byte for byte.
1102/// Still ambiguous: the file's own text `\x80`–`\xff`; a PDF copy it broke fails `pdf::xref_ok` (`pdf_mangled`), so
1103/// the ladder goes on to Bright Data's raw bytes.
1104fn file_bytes(s: &[u8]) -> Vec<u8> {
1105    let hex = |c: u8| (c as char).to_digit(16).filter(|_| !c.is_ascii_uppercase()).map(|d| d as u8);
1106    let (mut out, mut i) = (Vec::with_capacity(s.len()), 0);
1107    while i < s.len() {
1108        match (&s[i..], s.get(i + 2).copied().and_then(hex), s.get(i + 3).copied().and_then(hex)) {
1109            ([b'\\', b'x', ..], Some(h @ 8..), Some(l)) => {
1110                out.push(h << 4 | l);
1111                i += 4;
1112            }
1113            _ => {
1114                out.push(s[i]);
1115                i += 1;
1116            }
1117        }
1118    }
1119    out
1120}
1121
1122// ---------------------------------------------------------------- web search
1123
1124/// One web search result.
1125#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
1126pub struct Hit {
1127    pub url: String,
1128    pub title: String,
1129    pub snippet: String,
1130}
1131
1132/// Tiers that search = the `search` rows (`Spec::can`): Oxylabs Web API `/v1/search`, then Google results through
1133/// the Bright Data zone. Results per call: 1–20 (`max_results`, Oxylabs search docs); one wait for both.
1134pub const SEARCH_MAX: usize = 20;
1135pub const SEARCH_TIMEOUT: Duration = Duration::from_secs(15);
1136
1137/// THE spend text: `$0.0225`, and `+ ≤$0.0060 unverified` when calls we cut may have been billed.
1138pub fn bill(cost: f64, upto: f64) -> String {
1139    if upto > 0.0 { format!("${cost:.4} + ≤${upto:.4} unverified") } else { format!("${cost:.4}") }
1140}
1141
1142/// An `=` line's spend after `glue`: `spent $0.0015`, nothing when the answer cost nothing (a free fetch ends
1143/// `plain 76ms`), so a price on screen always means money.
1144pub fn spent(glue: &str, cost: f64, upto: f64) -> String {
1145    if cost > 0.0 || upto > 0.0 { format!("{glue}spent {}", bill(cost, upto)) } else { String::new() }
1146}
1147
1148/// The request for one search: (endpoint, body). Oxylabs (developers.oxylabs.io products/web-api/search):
1149/// `{query, max_results, location}`, `location` = ISO alpha-2, unknown fields are a 400. Bright Data: a Google
1150/// URL with `brd_json=1` (parsed JSON, as the BD CLI's `search` sends it) and `gl` for the country, through the
1151/// `/request` API (`country` = proxy location, BD SERP API reference). Google returns about 10 results a page.
1152fn search_req(t: Tier, q: &str, limit: usize, country: Option<&str>) -> (Api, Value) {
1153    let c = search_country(country);
1154    if t == Tier::Bd {
1155        let p = [("q", q.to_string()), ("brd_json", "1".into()), ("gl", c.to_lowercase())];
1156        let url =
1157            url::Url::parse_with_params("https://www.google.com/search", &p).map(String::from).unwrap_or_default();
1158        let req = json!({"zone": crate::settings::zone(), "url": url, "format": "json", "country": c.to_lowercase()});
1159        return (Api::BdRequest, req);
1160    }
1161    (Api::OxySearch, json!({"query": q, "max_results": limit.min(SEARCH_MAX), "location": c}))
1162}
1163
1164/// The country a search sends, both providers: `country:`, else `home` (never none: Google's `gl`).
1165pub fn search_country(country: Option<&str>) -> String {
1166    country.filter(|c| !c.is_empty()).map_or_else(home, str::to_uppercase)
1167}
1168
1169/// A search answer → hits, best first. Oxylabs: `results[].{url, title, outline[]}`. Bright Data: `organic[].{link,
1170/// title, description}`, top level from a SERP zone, inside the `body` string from an unlocker zone.
1171pub fn hits(t: Tier, body: &[u8], limit: usize) -> Result<Vec<Hit>, &'static str> {
1172    let j: Value = serde_json::from_slice(body).map_err(|_| "provider_error")?;
1173    let s = |v: &Value| crate::clean::collapse(v.as_str().unwrap_or_default());
1174    let (list, url, snip) = match t {
1175        Tier::Bd => {
1176            let inner = j["body"].as_str().and_then(|b| serde_json::from_str::<Value>(b).ok()).unwrap_or_default();
1177            let j = if j["organic"].is_array() { &j } else { &inner };
1178            (j["organic"].as_array().cloned().ok_or("provider_error")?, "link", "description")
1179        }
1180        _ => (j["results"].as_array().cloned().ok_or("provider_error")?, "url", "outline"),
1181    };
1182    let hits = list.iter().filter(|r| r[url].is_string()).take(limit);
1183    Ok(hits
1184        .map(|r| Hit {
1185            url: s(&r[url]),
1186            title: s(&r["title"]),
1187            snippet: if r[snip].is_array() { s(&r[snip][0]) } else { s(&r[snip]) },
1188        })
1189        .collect())
1190}
1191
1192/// One search call. `billed` as in `get`.
1193pub async fn search(
1194    t: Tier,
1195    q: &str,
1196    limit: usize,
1197    country: Option<&str>,
1198    wait: Duration,
1199) -> (Result<(Vec<Hit>, Option<Limit>), Fail>, bool) {
1200    let key = t.key().unwrap_or_default();
1201    let (to, req) = search_req(t, q, limit, country);
1202    let r = api(to, &key, req, 2 * crate::cli::MAX_BYTES, wait).await;
1203    let r = r.and_then(|(body, lim, _)| hits(t, &body, limit).map(|h| (h, lim)).map_err(Fail::from));
1204    // an answer without a result list is bd's failed SERP: the zone counter +0 for 2
1205    let billed = charged(t, r.as_ref().map(|_| 200));
1206    (r, billed)
1207}
1208
1209/// `fats gh <words>`: GitHub REST `GET /search/repositories` sorted by stars (docs.github.com rest/search "Search
1210/// repositories": `q`, `sort=stars`, `order`, `per_page`), free: 30 searches a minute with a token, 10 without.
1211/// A login-shaped word (`[A-Za-z0-9-]`, ≤ 39: GitHub's username rule) also lists that account's repos, at once,
1212/// its top 100 by stars (`q=user:<login>`, one more search; `GET /users/{q}/repos` holds only its 100 last pushed,
1213/// so a ★71 repo of an account with 164 was missing), that list only for an account the search leaves out (422
1214/// with or without a token, seen live on a real account) or none (then 404): a login's own repos rarely bear it in
1215/// their text (0 hits, or repos about the person). The lists merge by stars, so a
1216/// squatter account of a topic word (★0 repos) stays below the topic's hits. A repository → a hit: its page,
1217/// `★12.4k owner/repo`, `description (80 chars) · pushed YYYY-MM-DD`. Ok = the hits + each call's code and `=` line
1218/// note (the search's, then the account's: ` · no user <q>`, ` · user lookup: rate_limited retry in 60s`); the
1219/// account's failure with no hit at all is the answer's (`! rate_limited gh user <q> …`), never `0 results`.
1220pub async fn gh_repos(q: String, limit: usize) -> Result<(Vec<Hit>, Vec<(&'static str, String)>), Fail> {
1221    let (key, per) = (crate::settings::key("gh").unwrap_or_default(), limit.min(crate::settings::limit("gh_max")));
1222    let call = |to: Api, req: Value| api(to, &key, req, 4 << 20, SEARCH_TIMEOUT);
1223    let login = q.len() <= 39 && !q.contains(|c: char| !c.is_ascii_alphanumeric() && c != '-');
1224    let user = login.then_some(async {
1225        let by_stars = json!({"q": format!("user:{q}"), "sort": "stars", "order": "desc", "per_page": "100"});
1226        match call(Api::GhRepos, by_stars).await {
1227            Err(f) if f.status == 422 => call(Api::GhUser, json!({"q": q, "sort": "pushed", "per_page": "100"})).await,
1228            r => r,
1229        }
1230    });
1231    let req = json!({"q": q, "sort": "stars", "order": "desc", "per_page": per.to_string()});
1232    let (found, user) = tokio::join!(call(Api::GhRepos, req), async { Some(user?.await) });
1233    let items =
1234        |r: Result<Answer, Fail>| serde_json::from_slice::<Value>(&r?.0).map_err(|_| Fail::from("provider_error"));
1235    let items = |r| items(r).map(|j| j["items"].as_array().or(j.as_array()).cloned().unwrap_or_default());
1236    let mut repos = items(found)?;
1237    // the account call's hop (`cli::github`): its code and the `=` line's note when it got no list
1238    let user = match user.map(items) {
1239        Some(Err(f)) if f.status == 404 => Some(("not_found", format!(" · no user {q}"))),
1240        Some(Err(f)) if repos.is_empty() => return Err(Fail { why: format!("user {q} {}", f.why), ..f }),
1241        Some(Err(f)) => Some((f.code, format!(" · user lookup: {} {}", f.code, f.why).trim_end().into())),
1242        theirs => theirs.map(|r| repos.extend(r.unwrap_or_default())).map(|()| ("ok", String::new())),
1243    };
1244    repos.sort_by_key(|r| std::cmp::Reverse(r["stargazers_count"].as_u64()));
1245    let s = |v: &Value| crate::clean::collapse(v.as_str().unwrap_or_default());
1246    let hit = |r: &Value| {
1247        let stars = crate::lang::ksize(r["stargazers_count"].as_u64().unwrap_or(0) as usize);
1248        let pushed = format!("pushed {}", crate::lang::cut(&s(&r["pushed_at"]), 10));
1249        let about: Vec<String> =
1250            [crate::lang::short(&s(&r["description"]), 80), pushed].into_iter().filter(|x| !x.is_empty()).collect();
1251        Hit { url: s(&r["html_url"]), title: format!("★{stars} {}", s(&r["full_name"])), snippet: about.join(" · ") }
1252    };
1253    let on_github =
1254        |h: &Hit| url::Url::parse(&h.url).is_ok_and(|u| u.scheme() == "https" && u.host_str() == Some("github.com"));
1255    let hits = crate::lang::uniq(repos.iter().map(hit).filter(on_github), |h| h.url.clone());
1256    Ok((hits.into_iter().take(per).collect(), [("ok", String::new())].into_iter().chain(user).collect()))
1257}
1258
1259// ---------------------------------------------------------------- account (`fats account`)
1260
1261/// The providers `fats account` reads, in row order (Decodo documents no usage read for its API key).
1262pub const ACCOUNTS: [Tier; 2] = [Tier::Oxy, Tier::Bd];
1263/// Every provider with a key, in the order `fats setup` and the status line name them.
1264pub const KEYS: [Tier; 3] = [Tier::Oxy, Tier::Bd, Tier::Decodo];
1265/// Per call; the account APIs answered in 0.1–0.5 s (measured 2026-10-12).
1266pub const ACCOUNT_TIMEOUT: Duration = Duration::from_secs(10);
1267/// The largest account answer kept (the scraper list is ~14 KB).
1268const ACCOUNT_CAP: u64 = 1 << 20;
1269
1270/// One provider's account as read from its answers (never the answers themselves). None = not offered or not read.
1271#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
1272#[serde(default)]
1273pub struct Account {
1274    /// `oxy`, `bd`.
1275    pub provider: String,
1276    /// `ok`, or the failed call's code (`bad_key`, `rate_limited` …); `why` = its printable token.
1277    pub code: String,
1278    #[serde(skip_serializing_if = "String::is_empty")]
1279    pub why: String,
1280    pub ms: u64,
1281    pub calls: usize,
1282    pub scrapers: Option<usize>,
1283    /// USD.
1284    pub balance: Option<f64>,
1285    /// USD this calendar month (UTC).
1286    pub spend: Option<f64>,
1287    pub reqs_unblocker: Option<u64>,
1288    pub reqs_serp: Option<u64>,
1289    /// USD this month on the zone fats calls (`BRIGHTDATA_UNLOCKER_ZONE`): what `stats` reconciles against.
1290    pub zone_cost: Option<f64>,
1291    pub zones: Vec<String>,
1292    /// The reads a scoped key may not make (403 on that one only), by endpoint (`stats::READS` names them).
1293    pub denied: Vec<Api>,
1294}
1295
1296/// The calls one provider's account takes, in order, with their request fields. `month` = (its first day, the
1297/// next month's first day), `YYYY-MM-DD` UTC (Bright Data: `to` is exclusive). The zone's month needs the
1298/// configured zone and is skipped without one.
1299pub fn account_calls(t: Tier, month: (&str, &str), zone: Option<&str>) -> Vec<(Api, Value)> {
1300    let (from, to) = month;
1301    match t {
1302        Tier::Bd => {
1303            let mut v = vec![
1304                (Api::BdBalance, json!({})),
1305                (Api::BdZones, json!({})),
1306                (Api::BdCosts, json!({"dimension": "products", "filters": {}, "from": from, "to": to})),
1307            ];
1308            v.extend(zone.map(|z| (Api::BdZoneCost, json!({"from": from, "to": to, "zone": z}))));
1309            v
1310        }
1311        _ => vec![(Api::OxyScrapers, json!({}))],
1312    }
1313}
1314
1315/// One account answer into `a`. Bright Data's cost export has a key per day **and** a `total` key: the month's
1316/// spend is the sum of `total` only (summing every key counts each day twice). A zone's month is keyed by
1317/// customer, then plan: requests are summed over the plans.
1318pub fn account_read(a: &mut Account, to: Api, body: &[u8]) {
1319    let j: Value = serde_json::from_slice(body).unwrap_or_default();
1320    match to {
1321        Api::OxyScrapers => a.scrapers = j["scrapers"].as_array().map(Vec::len),
1322        Api::BdBalance => a.balance = j["balance"].as_f64(),
1323        Api::BdZones => {
1324            let z = j.as_array().into_iter().flatten().filter_map(|z| z["type"].as_str().map(String::from));
1325            a.zones = z.collect::<std::collections::BTreeSet<_>>().into_iter().collect();
1326        }
1327        Api::BdCosts => a.spend = j["total"].as_object().map(|t| spend(t.values().filter_map(Value::as_f64))),
1328        Api::BdZoneCost => {
1329            let customers = j.as_object().into_iter().flat_map(|c| c.values());
1330            let plans: Vec<&Value> = customers.filter_map(Value::as_object).flat_map(|p| p.values()).collect();
1331            let sum = |k: &str| plans.iter().map(|p| p[k].as_u64()).sum::<Option<u64>>();
1332            let n = |k: &str| sum(k).filter(|_| !plans.is_empty());
1333            (a.reqs_unblocker, a.reqs_serp) = (n("reqs_unblocker"), n("reqs_serp"));
1334            a.zone_cost = plans.iter().map(|p| p["cost"].as_f64()).sum::<Option<f64>>().filter(|_| !plans.is_empty());
1335        }
1336        _ => {}
1337    }
1338}
1339
1340/// Read one provider's account: its calls in order; the first failure stops the rest (a refused key fails them
1341/// all). A 403 on one read is a key scoped without it (Bright Data's per-permission keys: `denied`, the rest
1342/// read on); a 401, or a 403 on every read, is a bad key. Answers are parsed and dropped; an error body is never
1343/// kept.
1344pub async fn account(t: Tier, key: String, month: (String, String), zone: Option<&str>) -> Account {
1345    let t0 = std::time::Instant::now();
1346    let mut a = Account { provider: t.spec().short.into(), code: "ok".into(), ..Account::default() };
1347    for (to, req) in account_calls(t, (&month.0, &month.1), zone) {
1348        a.calls += 1;
1349        match api(to, &key, req, ACCOUNT_CAP, ACCOUNT_TIMEOUT).await {
1350            Ok((body, ..)) => account_read(&mut a, to, &body),
1351            Err(f) if f.status == 403 && f.code == "bad_key" => {
1352                a.denied.push(to);
1353            }
1354            Err(f) => {
1355                (a.code, a.why) = (f.code.into(), f.why);
1356                break;
1357            }
1358        }
1359    }
1360    if a.denied.len() == a.calls {
1361        a.code = "bad_key".into();
1362    }
1363    a.ms = t0.elapsed().as_millis() as u64;
1364    a
1365}
1366
1367/// A target that does not exist: Decodo's key check scrapes it (`check_call`); a key is never sent there.
1368pub const NO_HOST: &str = "https://does-not-exist.decodo.com";
1369
1370/// `fats setup`'s free key check of `t`'s key: Oxylabs the scraper list, Bright Data the zone list (names and types,
1371/// never an endpoint with a zone password), Decodo a `universal` scrape of `NO_HOST`, its CLI's own check
1372/// (github.com/Decodo/cli `src/scrape/services/auth-validation.ts`): 401 = a bad key, a 400 = a good one.
1373pub fn check_call(t: Tier) -> (Api, Value) {
1374    match t.owner() {
1375        Tier::Bd => (Api::BdZones, json!({})),
1376        Tier::Decodo => (Api::DecodoScrape, json!({"url": NO_HOST, "target": "universal"})),
1377        _ => (Api::OxyScrapers, json!({})),
1378    }
1379}
1380
1381/// `t`'s key check (`check_call`): what it shows (Oxylabs' scraper count, else `key ok`) and Bright Data's Web
1382/// Unlocker zones in the list's order (its rows carry `name` and `type` only); Decodo's 400 on `NO_HOST` = a good key.
1383pub async fn check_key(t: Tier, key: String) -> Result<(String, Vec<String>), Fail> {
1384    let (to, req) = check_call(t);
1385    let j: Value = match api(to, &key, req, ACCOUNT_CAP, ACCOUNT_TIMEOUT).await {
1386        Err(f) if to == Api::DecodoScrape && f.status == 400 => json!({}),
1387        r => serde_json::from_slice(&r?.0).unwrap_or_default(),
1388    };
1389    let zones = j.as_array().into_iter().flatten().filter(|z| z["type"] == "unblocker");
1390    let what = j["scrapers"].as_array().map_or("key ok".into(), |s| format!("{} scrapers", s.len()));
1391    Ok((what, zones.filter_map(|z| z["name"].as_str().map(String::from)).collect()))
1392}
1393
1394/// Safari 26 on macOS (TLS ClientHello, HTTP/2 settings, navigation headers, as maintained by wreq-util). Measured
1395/// on 121 test URLs, one run each: Safari 26 passed 85, Chrome 149 73 (Cloudflare challenged it more).
1396fn browser() -> wreq_util::Emulation {
1397    wreq_util::Emulation::builder().profile(wreq_util::Profile::Safari26).platform(wreq_util::Platform::MacOS).build()
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402    use super::*;
1403
1404    /// THE home-IP brake: a second plain call to a host waits while the first holds its turn, and until
1405    /// `plain_host_pace_ms` after its start (unit tests run with every key: a key never skips the wait).
1406    #[test]
1407    fn plain_calls_to_one_host_are_paced() {
1408        let url = format!("https://pace-{}.example/a", std::process::id());
1409        let (first, waited) = pace(&url);
1410        assert!(first.is_some() && waited < 500, "the first call runs at once: {waited} ms");
1411        let second = std::thread::spawn(move || pace(&url).1);
1412        std::thread::sleep(Duration::from_millis(300));
1413        drop(first);
1414        let waited = second.join().expect("second call");
1415        assert!((600..2000).contains(&waited), "the held turn, then 1 s from the first start: {waited} ms");
1416        // the start is written over the last one, fixed-width: a longer old file's tail is never read
1417        let other = format!("https://pace-tail-{}.example/", std::process::id());
1418        let at = crate::settings::get().cache.value.join("pace").join(crate::clean::host_of(&other));
1419        std::fs::create_dir_all(at.parent().expect("pace dir")).ok();
1420        std::fs::write(&at, format!("1.0{}", "x".repeat(40))).ok();
1421        drop(pace(&other));
1422        let kept = std::fs::read_to_string(&at).unwrap_or_default();
1423        assert!(kept.get(..20).and_then(|k| k.parse::<f64>().ok()).is_some_and(|t| t > 1e9), "one start: {kept}");
1424        assert_eq!(kept.len(), 43, "written over, never cut or grown");
1425    }
1426
1427    /// THE billing rule (bd's zone counter): an answer below 500 is billed, a 5xx (bd's
1428    /// `http_502`), a timeout (a search's too: counter +0 for 2) or a refusal is not, for both providers.
1429    #[test]
1430    fn charged_only_on_a_charged_reply() {
1431        let (late, err) = (Fail::from("provider_timeout"), Fail::from("provider_error"));
1432        for t in [Tier::Oxy, Tier::OxyJs, Tier::Bd] {
1433            let fetch = |s| charged(t, s);
1434            assert!(fetch(Ok(200)) && fetch(Ok(404)), "{t:?}: an answer");
1435            // Oxylabs' finished job relaying the site's 502 is billed; Bright Data's inner 5xx is not
1436            assert_eq!(fetch(Ok(502)), t != Tier::Bd, "{t:?}: a site's 5xx");
1437            assert!(!fetch(Err(&late)) && !fetch(Err(&err)), "{t:?}: a timeout or refusal is free");
1438        }
1439        assert!(!charged(Tier::Plain, Ok(200)), "plain is free");
1440    }
1441
1442    /// The Oxylabs request always says `run_js` and a `location` (`US` where nothing names one: an unset one is a
1443    /// random exit), and carries `device` only for `device:mobile` (desktop is the API's default).
1444    #[test]
1445    fn oxy_request_body() {
1446        let ask = Ask { url: "https://ex.com/a".into(), ..Ask::default() };
1447        let want = json!({"url": "https://ex.com/a", "output": ["html"], "run_js": false, "location": "US"});
1448        assert_eq!(oxy_body(&ask), want);
1449        let ask = Ask { url: "https://ex.com/a".into(), js: true, mobile: true, ..Ask::default() };
1450        assert_eq!(
1451            oxy_body(&ask),
1452            json!({"url": "https://ex.com/a", "output": ["html"], "run_js": true, "location": "US", "device": "mobile"})
1453        );
1454        assert_eq!(oxy_body(&Ask { url: "https://www.lemonde.fr/".into(), ..Ask::default() })["location"], "FR");
1455    }
1456
1457    /// Oxylabs' escaped file → the file: only lower-case `\x80`–`\xff` are escapes; the file's own `\x48`, an
1458    /// upper-case `\x9C`, a cut `\x9` and UTF-8 stay as they are (the arXiv case: two literal runs, 0 bytes lost).
1459    #[test]
1460    fn oxylabs_file_bytes() {
1461        let file: &[u8] = b"%PDF-1.5 \x9c\xff\\x48 \xc3\xa9 \\x9C \\x9";
1462        let escaped = r"%PDF-1.5 \x9c\xff\x48 é \x9C \x9";
1463        assert_eq!(file_bytes(escaped.as_bytes()), file);
1464    }
1465
1466    /// A key goes only to `Providers::apis`: scrape, search and account reads on the two provider API hosts, never an
1467    /// endpoint that returns secrets (Bright Data `GET /zone`, `/zone/passwords`; Webshare `/proxy/list`), and a
1468    /// POST only where the docs make it a query. `send` is the only request with a key, and no provider URL is
1469    /// written outside `apis` and `links` in providers.json (pages printed for people, never requested): a new one is a
1470    /// visible row.
1471    #[test]
1472    fn keys_go_only_to_listed_endpoints() {
1473        // 1.1.1.1 (DoH) and fatsearch.com (telemetry, `ours`) are sent no key: an empty one, which `send` never puts
1474        // in a header
1475        const HOSTS: &[&str] = &[
1476            "api.brightdata.com", "webapi.oxylabs.io", "1.1.1.1", "api.github.com", "data.decodo.com", "fatsearch.com",
1477        ];
1478        const NEVER: &[&str] = &["password", "/proxy/list", "/billing", "/account", "/users"];
1479        const POST: &[&str] = &["/request", "/scrape", "/search", "/costs/export/json", "/v1/l2"];
1480        for (i, ApiRow { api, method, url, .. }) in PROVIDERS.apis.iter().enumerate() {
1481            assert_eq!(*api as usize, i, "apis is indexed by Api");
1482            let u = url::Url::parse(url).expect("url");
1483            assert_eq!(u.scheme(), "https", "{url}");
1484            assert!(HOSTS.contains(&u.host_str().unwrap_or_default()), "{url}: unlisted host");
1485            let p = u.path();
1486            // GitHub's `/users/{login}/repos` lists an account's public repositories, nothing of the caller's
1487            let public = u.host_str() == Some("api.github.com") && p.ends_with("/repos");
1488            assert!(p != "/zone" && (public || NEVER.iter().all(|n| !p.contains(n))), "{url}: returns secrets");
1489            assert!(*method == "GET" || (*method == "POST" && POST.iter().any(|e| p.ends_with(e))), "{url}");
1490        }
1491        let links: Vec<&str> = PROVIDERS
1492            .links
1493            .iter()
1494            .flat_map(|l| [Some(l.signup), Some(l.mint), l.keys, l.billing, l.usage])
1495            .flatten()
1496            .collect();
1497        assert!(links.iter().all(|l| l.starts_with("https://")));
1498        let src: String = [
1499            include_str!("provider.rs"),
1500            include_str!("fetch.rs"),
1501            include_str!("cli.rs"),
1502            include_str!("stats.rs"),
1503            include_str!("settings.rs"),
1504            include_str!("mcp.rs"),
1505            include_str!("data/providers.json"),
1506        ]
1507        .iter()
1508        .map(|f| f.split("#[cfg(test)]").next().unwrap_or_default())
1509        .collect();
1510        assert_eq!(src.matches("bearer_auth(").count(), 1, "one request carries a key");
1511        assert!(!src.contains("basic_auth(") && !src.to_ascii_lowercase().contains("\"authorization\""));
1512        let listed: Vec<&str> = PROVIDERS.apis.iter().map(|a| a.url).chain(links).collect();
1513        let provider = [
1514            "oxylabs.io", "brightdata.com", "luminati", "webshare.io", "decodo.com", "1.1.1.1", "github.com",
1515            "fatsearch.com",
1516        ];
1517        let lits: Vec<String> =
1518            src.split("\"http").skip(1).filter_map(|r| r.split('"').next()).map(|r| format!("http{r}")).collect();
1519        // Decodo's key check target is a page asked for, no place a key goes
1520        let found: Vec<&String> =
1521            lits.iter().filter(|l| *l != NO_HOST && provider.iter().any(|h| l.contains(h))).collect();
1522        assert_eq!(found.len(), listed.len(), "each provider URL is written once, in apis or links: {found:?}");
1523        assert!(found.iter().all(|l| listed.contains(&l.as_str())), "provider URL outside apis/links: {found:?}");
1524    }
1525
1526    /// A provider's answer → a code; an error body is kept for `error.txt`, the 200 body is the answer.
1527    #[test]
1528    fn replies_become_codes() {
1529        let r = |status, refused: bool, body: &str| {
1530            let h = [
1531                ("x-brd-error", "Access denied: x.gov is classified as Government"),
1532                ("x-brd-error-code", "proxy_error"),
1533            ];
1534            let headers = h.iter().filter(|_| refused).map(|(k, v)| (k.to_string(), v.to_string())).collect();
1535            read(Api::BdRequest, "", Reply { status, headers, body: body.into() })
1536        };
1537        assert_eq!(r(200, false, "{}"), Ok((b"{}".to_vec(), None, None)));
1538        let raw = Reply { status: 200, headers: vec![("x-brd-status-code".into(), "404".into())], body: b"<p>".into() };
1539        assert_eq!(
1540            read(Api::BdRequest, "", raw),
1541            Ok((b"<p>".to_vec(), None, Some(404))),
1542            "Bright Data's target status"
1543        );
1544        let empty = r(200, false, "").expect_err("200 + empty body");
1545        assert_eq!((empty.code, empty.why.as_str()), ("provider_error", "empty"));
1546        let gov = r(200, true, "").expect_err("Bright Data refusal");
1547        assert_eq!(
1548            (gov.code, gov.why.as_str()),
1549            ("provider_refused", "proxy_error"),
1550            "the code header, not the message"
1551        );
1552        // A status bd relayed is the site's block, a rate limit a wait; neither is bd's policy
1553        let brd = |code: &str, site: &str| {
1554            let h = [("x-brd-error", "rejected"), ("x-brd-error-code", code), ("x-brd-status-code", site)];
1555            let reply = Reply { status: 200, headers: h.map(|(k, v)| (k.into(), v.into())).to_vec(), body: vec![] };
1556            let f = read(Api::BdRequest, "", reply);
1557            f.map_err(|f| (f.code, f.why)).expect_err("refused")
1558        };
1559        assert_eq!(brd("http_status", "403"), ("blocked_403", "http_status".into()), "a relayed site 403");
1560        assert_eq!(brd("http_status", "502").0, "provider_refused", "no site block row");
1561        assert_eq!(brd("bucket_rate_limit", "").0, "rate_limited", "a rate limit");
1562        assert_eq!(bd_refused("bucket_rate_limit".into(), None, Some(30)).1, "bucket_rate_limit retry in 30s");
1563        assert!(!charged(Tier::Bd, Err(&Fail::from("blocked_403"))), "a relayed status is no answer: not billed");
1564        assert_eq!(token(Some("Access denied: x.gov")), "", "free text is never a token");
1565        assert_eq!(token(Some(" Proxy_Error ")), "proxy_error");
1566        let f = r(401, false, "Invalid api key").expect_err("401");
1567        assert_eq!((f.code, f.status, f.body.as_slice()), ("bad_key", 401, &b"Invalid api key"[..]));
1568        assert_eq!(r(403, false, "").map_err(|f| f.code), Err("bad_key"));
1569        assert_eq!(r(408, false, "").map_err(|f| f.code), Err("provider_timeout"));
1570        assert_eq!(r(429, false, "").map_err(|f| (f.code, f.why)), Err(("rate_limited", String::new())), "quota?");
1571        assert_eq!(r(500, false, "<html>oops").map_err(|f| (f.code, f.why)), Err(("provider_error", "500".into())));
1572    }
1573
1574    /// A rate limit says when to retry (`retry-after`, else Oxylabs' 5 s) and the key's own cap beside it.
1575    #[test]
1576    fn a_rate_limit_says_when_and_its_cap() {
1577        let acct = |h: &[(&str, &str)]| Reply {
1578            status: 429,
1579            headers: h.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
1580            body: br#"{"status":429,"title":"RATE_LIMIT_EXCEEDED","detail":"Too many requests."}"#.to_vec(),
1581        };
1582        let h = [
1583            ("x-ratelimit-search_total_dynamic_europe-1234567-limit", "10"),
1584            ("x-ratelimit-search_total_dynamic_europe-1234567-remaining", "0"),
1585            ("x-ratelimit-system_search_total_dynamic_europe-remaining", "9999"),
1586        ];
1587        let f = read(Api::OxyScrape, "", acct(&h)).expect_err("429");
1588        assert_eq!(
1589            (f.why.as_str(), f.limit),
1590            ("retry in 5s", Some(Limit { limit: 10, remaining: 0 })),
1591            "no key, no cap"
1592        );
1593        let f = read(Api::OxyScrape, "k3y", acct(&h)).expect_err("429");
1594        assert_eq!(f.why, "cap 10 on this account · retry in 5s", "the account's own cap beside its wait");
1595        let f = read(Api::OxyScrape, "", acct(&[("retry-after", "7")])).expect_err("429");
1596        assert_eq!((f.why.as_str(), f.limit), ("retry in 7s", None), "retry-after wins; no budget sent");
1597        assert_eq!(
1598            read(Api::OxyScrape, "", acct(&[("retry-after", "Wed, 21 Oct 2026 07:28:00 GMT")])).map_err(|f| f.why),
1599            Err("retry in 5s".into())
1600        );
1601    }
1602
1603    /// The provider's own reason (`reason`): an RFC 9457 field error, its faulted title; fields only, ≤ 50 chars.
1604    #[test]
1605    fn a_refusal_keeps_its_reason() {
1606        let fail = |status, body: &str| {
1607            let r = Reply { status, headers: vec![], body: body.into() };
1608            read(Api::OxyScrape, "", r).map_err(|f| (f.code, f.why)).expect_err("refused")
1609        };
1610        let why = |status, body: &str| fail(status, body).1;
1611        let url =
1612            r##"{"title":"INVALID_BODY_PROPERTY","errors":[{"detail":"Value not supported.","pointer":"#/url"}]}"##;
1613        assert_eq!(fail(400, url), ("provider_refused", "400 url: value not supported".into()), "it refuses the URL");
1614        let zip = r##"{"errors":[{"detail":"Value should be in zip/postal codes.","pointer":"#/location"}]}"##;
1615        assert_eq!(fail(400, zip), ("provider_error", "400 location: value should be in zip/postal codes".into()));
1616        let field = r##"{"errors":[{"detail":"Input should be less than or equal to 20","pointer":"#/max_results"}]}"##;
1617        assert_eq!(fail(400, field).0, "provider_error", "our own field: no refusal of the URL");
1618        let faulted =
1619            r#"{"status":500,"state":"faulted","title":"REQUEST_FAILED_AFTER_TOO_MANY_RETRIES","detail":"x"}"#;
1620        assert_eq!(why(500, faulted), "500 faulted: request failed after too many retries");
1621        let long = r#"{"title":"A_B","errors":[{"detail":"key=*** <b>is</b> wrong and this sentence goes on far too long to fit"}]}"#;
1622        assert_eq!(why(400, long), "400 wrong and this sentence goes on far too long", "masked and markup words drop");
1623        // a key in JSON escapes is masked once decoded, before it is lowered: no run of it in the reason
1624        let key = ["Ab3dEf6hIj9kLm2nOp".to_string()];
1625        let escaped: String = key[0].chars().map(|c| format!("\\u{:04x}", c as u32)).collect();
1626        let body = format!(r##"{{"errors":[{{"detail":"key {escaped} refused","pointer":"#/key"}}]}}"##);
1627        assert_eq!(reason(400, body.as_bytes(), &key), "400 key: key refused");
1628    }
1629
1630    /// Search requests carry only the documented fields; the parser reads both providers' saved answers.
1631    #[test]
1632    fn search_requests_and_answers() {
1633        let (u, r) = search_req(Tier::Oxy, "heidelberg university", 50, Some("fr"));
1634        assert_eq!(u.row().url, "https://webapi.oxylabs.io/v1/search");
1635        assert_eq!(r, json!({"query": "heidelberg university", "max_results": 20, "location": "FR"}));
1636        assert_eq!(search_req(Tier::Oxy, "a", 10, None).1, json!({"query": "a", "max_results": 10, "location": "US"}));
1637        let none = search_req(Tier::Bd, "a", 10, None).1;
1638        assert_eq!(
1639            (none["country"].as_str(), none["url"].as_str()),
1640            (Some("us"), Some("https://www.google.com/search?q=a&brd_json=1&gl=us"))
1641        );
1642        let (u, r) = search_req(Tier::Bd, "a b&c", 10, Some("fr"));
1643        assert_eq!(u.row().url, "https://api.brightdata.com/request");
1644        assert_eq!(r["url"], "https://www.google.com/search?q=a+b%26c&brd_json=1&gl=fr");
1645        assert_eq!((r["format"].as_str(), r["country"].as_str()), (Some("json"), Some("fr")));
1646        let oxy = hits(Tier::Oxy, include_bytes!("../tests/fixtures/oxy-search.json"), 10).expect("oxy fixture");
1647        assert_eq!(oxy.len(), 5);
1648        assert_eq!(
1649            (oxy[0].url.as_str(), oxy[0].title.as_str()),
1650            ("https://www.uni-heidelberg.de/en", "Heidelberg University")
1651        );
1652        assert!(oxy[0].snippet.starts_with("Heidelberg University – the oldest in Germany"));
1653        assert_eq!(hits(Tier::Oxy, include_bytes!("../tests/fixtures/oxy-search.json"), 2).map(|h| h.len()), Ok(2));
1654        let bd = hits(Tier::Bd, include_bytes!("../tests/fixtures/bd-serp.json"), 10).expect("bd fixture");
1655        assert_eq!(bd.len(), 3);
1656        assert_eq!(bd[0].url, "https://pizza.example.com/delivery-springfield");
1657        assert!(bd[0].snippet.starts_with("Example Pizzeria offers fast pizza delivery"));
1658        assert_eq!(hits(Tier::Oxy, b"<html>", 10), Err("provider_error"));
1659        assert_eq!(hits(Tier::Oxy, br#"{"state":"done","results":[]}"#, 10), Ok(vec![]));
1660    }
1661
1662    /// Account answers in the providers' shapes (made-up numbers) → the fields; BD spend = the `total` key only
1663    /// (summing every key gives 11.00: each day counted twice).
1664    #[test]
1665    fn account_answers() {
1666        let mut a = Account::default();
1667        account_read(&mut a, Api::OxyScrapers, include_bytes!("../tests/fixtures/account-oxy-scrapers.json"));
1668        assert_eq!(a.scrapers, Some(351));
1669        account_read(&mut a, Api::BdBalance, include_bytes!("../tests/fixtures/account-bd-balance.json"));
1670        account_read(&mut a, Api::BdZones, include_bytes!("../tests/fixtures/account-bd-zones.json"));
1671        account_read(&mut a, Api::BdCosts, include_bytes!("../tests/fixtures/account-bd-costs.json"));
1672        account_read(&mut a, Api::BdZoneCost, include_bytes!("../tests/fixtures/account-bd-zone-cost.json"));
1673        assert_eq!((a.balance, format!("{:.2}", a.spend.unwrap_or_default())), (Some(1234.56), "5.50".into()));
1674        assert_eq!((a.reqs_unblocker, a.reqs_serp, a.zone_cost), (Some(1500), Some(700), Some(3.21)));
1675        let all: Value = serde_json::from_slice(include_bytes!("../tests/fixtures/account-bd-costs.json")).unwrap();
1676        let every: f64 = all
1677            .as_object()
1678            .unwrap()
1679            .values()
1680            .flat_map(|d| d.as_object().unwrap().values())
1681            .filter_map(Value::as_f64)
1682            .sum();
1683        assert_eq!(format!("{every:.2}"), "11.00", "the double count the `total` rule avoids");
1684        assert_eq!(a.zones, ["dc", "serp", "unblocker"], "zone types, sorted, each once");
1685        let mut b = Account::default();
1686        account_read(&mut b, Api::BdZoneCost, b"{}");
1687        account_read(&mut b, Api::BdBalance, b"<html>");
1688        assert_eq!((b.reqs_unblocker, b.balance, b.zone_cost), (None, None, None), "no answer = n/a, never 0");
1689        let calls = |z| account_calls(Tier::Bd, ("2026-10-01", "2026-11-01"), z);
1690        assert_eq!(calls(None).len(), 3, "no zone, no zone month");
1691        let all = calls(Some("unblocker"));
1692        assert_eq!(all[3].1, json!({"zone": "unblocker", "from": "2026-10-01", "to": "2026-11-01"}));
1693        assert_eq!(account_calls(Tier::Oxy, ("", ""), None)[0].0.row().url, "https://webapi.oxylabs.io/v1/scrapers");
1694    }
1695
1696    /// `!` row pages: documented URLs only (the Oxylabs keys page is not), by any tier name of the key.
1697    #[test]
1698    fn row_pages() {
1699        assert_eq!(
1700            pages("no_key", ["oxyjs", "bd"]),
1701            " · oxyjs https://dashboard.oxylabs.io/en/registration · bd https://brightdata.com/cp/start"
1702        );
1703        assert_eq!(pages("bad_key", "oxy bd".split(' ')), format!("{K} · bd https://brightdata.com/cp/setting/users"));
1704        // developers.oxylabs.io/products/web-api/authentication "Getting a key": only a Web API key works
1705        const K: &str = " · oxy https://dashboard.oxylabs.io (a Web API instance's key)";
1706        assert_eq!(pages("bad_key", ["oxy"]), K);
1707        assert_eq!(pages("provider_error", ["bd"]), "", "only key and money codes");
1708        assert_eq!(page("low_balance", "bd").as_deref(), Some("https://brightdata.com/cp/billing"));
1709        assert_eq!(page("no_key", "plain"), None);
1710    }
1711
1712    /// ccTLD → country for both providers; `country:` wins; a gTLD names `home` on Oxylabs, none on Bright Data;
1713    /// plain never has one.
1714    #[test]
1715    fn country_from_tld() {
1716        let at = |url: &str, c: Option<&str>, t: Tier| {
1717            sent(&Ask { url: url.into(), country: c.map(String::from), ..Ask::default() }, t)
1718        };
1719        for (url, want) in [
1720            ("https://www.lemonde.fr/a", Some("FR")),
1721            ("https://www.spiegel.de/", Some("DE")),
1722            ("https://www.bbc.co.uk/news", Some("GB")),
1723            ("https://www.idealo.fr/x", Some("FR")),
1724            ("https://ex.gr/", Some("GR")),
1725            ("https://example.com/", None),
1726            ("https://europa.eu/", None),
1727            ("https://crates.io/", None),
1728            ("https://ex.us/", None),
1729        ] {
1730            assert_eq!(at(url, None, Tier::Bd).as_deref(), want, "{url}");
1731            for t in [Tier::Oxy, Tier::OxyJs] {
1732                assert_eq!(at(url, None, t).as_deref(), want.or(Some("US")), "{url} {t:?}");
1733            }
1734        }
1735        assert_eq!(at("https://www.lemonde.fr/", Some("de"), Tier::Oxy).as_deref(), Some("DE"), "country: wins");
1736        assert_eq!(at("https://ex.com/", Some("pl"), Tier::Bd).as_deref(), Some("PL"));
1737        assert_eq!(at("https://www.lemonde.fr/", Some("de"), Tier::Plain), None);
1738    }
1739
1740    /// An Oxylabs page call always names a `location`
1741    /// (unset = a random exit: 18 of 110 saved copies foreign); a Bright Data page names a country only when one is
1742    /// named or the domain gives one (unset = its best location for the target).
1743    #[test]
1744    fn oxylabs_always_names_a_location_bd_only_a_named_one() {
1745        let ask = |url: &str, c: Option<&str>| Ask { url: url.into(), country: c.map(String::from), ..Ask::default() };
1746        for (url, c, oxy, bd) in [
1747            ("https://example.com/", None, "US", None),
1748            ("https://example.com/", Some(""), "US", None),
1749            ("https://www.lemonde.fr/a", None, "FR", Some("fr")),
1750            ("https://example.com/", Some("de"), "DE", Some("de")),
1751        ] {
1752            let a = ask(url, c);
1753            assert_eq!(oxy_body(&a)["location"].as_str(), Some(oxy), "{url} {c:?}");
1754            assert_eq!(bd_body(&a).get("country").and_then(Value::as_str), bd, "{url} {c:?}");
1755            assert_eq!(decodo_body(&a)["geo"].as_str(), Some(oxy.to_lowercase().as_str()), "Decodo as Oxylabs");
1756        }
1757        // Decodo: `universal`, HTML (no `markdown`), `headless: html` on its render only, a mobile ask as its device
1758        let js = Ask { js: true, mobile: true, ..ask("https://ex.com/", None) };
1759        let mut want = json!({"url": "https://ex.com/", "target": "universal", "geo": "us"});
1760        assert_eq!(decodo_body(&ask("https://ex.com/", None)), want);
1761        (want["headless"], want["device_type"]) = ("html".into(), "mobile".into());
1762        assert_eq!(decodo_body(&js), want);
1763    }
1764
1765    /// Every spelling of a private address is private; public ones pass.
1766    #[test]
1767    fn private_addresses() {
1768        for ip in [
1769            "127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0",
1770            "255.255.255.255", "224.0.0.1", "240.0.0.1", "198.18.0.1", "192.0.0.8", "::1", "::", "fe80::1", "fc00::1",
1771            "fd12::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1", "64:ff9b::a9fe:a9fe", "2001:db8::1", "::7f00:1",
1772            "::a9fe:a9fe", "2002:7f00:1::", "2002:c0a8:101::1", "203.0.113.9", "fec0::1", "ff02::1", "192.0.2.1",
1773            "198.51.100.7",
1774        ] {
1775            assert!(private_ip(ip.parse().unwrap()), "{ip} is private");
1776        }
1777        // every block parses: one that does not is silently no block (`private_ip`'s `filter_map`)
1778        let block =
1779            |b: &str| b.split_once('/').map(|(ip, n)| (ip.parse::<std::net::IpAddr>().is_ok(), n.parse::<u32>()));
1780        let bad: Vec<&&str> =
1781            crate::fetch::SITES.fence.iter().filter(|b| !matches!(block(b), Some((true, Ok(_))))).collect();
1782        assert!(bad.is_empty(), "{bad:?}");
1783        for ip in [
1784            "8.8.8.8", "172.32.0.1", "100.128.0.1", "198.20.0.1", "2606:4700::1111", "::ffff:8.8.8.8",
1785            "2002:808:808::1",
1786        ] {
1787            assert!(!private_ip(ip.parse().unwrap()), "{ip} is public");
1788        }
1789        for url in [
1790            "http://localhost:8080/",
1791            "http://api.localhost/",
1792            "http://127.0.0.1/",
1793            "http://2130706433/",
1794            "http://0x7f.1/",
1795            "http://[::1]/",
1796            "http://169.254.169.254/latest/meta-data/",
1797            "http://10.0.0.1:9000/x",
1798            "data:text/html,hi",
1799        ] {
1800            assert!(private_host(url), "{url} is refused");
1801        }
1802        assert!(!private_host("https://example.com/") && !private_host("http://8.8.8.8/"));
1803    }
1804
1805    /// A meta refresh is a redirect only as the page's one move: no delay, its own host, no script, under
1806    /// `page_chars` shown, a 2xx page. A challenge's `<noscript>` refresh (a time, no URL) and a scripted page's
1807    /// no-JS fallback are no redirect (the 27 saved plain copies with a refresh were all of those kinds).
1808    #[test]
1809    fn a_meta_refresh_moves_only_alone() {
1810        let page = |status: u16, head: &str, body: &str| Raw {
1811            status,
1812            ctype: "text/html".into(),
1813            body: format!("<html><head>{head}</head><body>{body}</body></html>").into_bytes(),
1814            final_url: "https://a.example/releases/latest/".into(),
1815            ..Raw::default()
1816        };
1817        let tag = |c: &str| format!("<meta http-equiv=\"Refresh\" content=\"{c}\">");
1818        let to = |status, head: &str, body: &str| refresh(&page(status, head, body));
1819        let at = Some("https://a.example/2026/10/15/one/".to_string());
1820        assert_eq!(to(200, &tag("0; url=/2026/10/15/one/"), ""), at);
1821        assert_eq!(to(200, &tag("0;URL='../../2026/10/15/one/'"), ""), at, "WHATWG: any case, quotes, relative");
1822        assert_eq!(to(200, &tag("0, https://a.example/2026/10/15/one/"), ""), at, "a comma, no url=");
1823        assert_eq!(to(200, &tag("5; url=/2026/10/15/one/"), ""), None, "a delay");
1824        assert_eq!(to(200, &tag("0; url=https://b.example/one/"), ""), None, "another host");
1825        // one origin: scheme, host and port; http → https the one scheme move
1826        assert_eq!(to(200, &tag("0; url=https://a.example:8443/one/"), ""), None, "another port");
1827        assert_eq!(to(200, &tag("0; url=http://a.example/one/"), ""), None, "https → http");
1828        let up = Raw { final_url: "http://a.example/x".into(), ..page(200, &tag("0; url=https://a.example/one/"), "") };
1829        assert_eq!(refresh(&up).as_deref(), Some("https://a.example/one/"), "http → https");
1830        // a time of digits only; an empty `url=` reloads the page
1831        for c in ["+0; url=/one/", "-0; url=/one/", "0.0; url=/one/", " ; url=/one/", "0; url=", "0; url=''"] {
1832            assert_eq!(to(200, &tag(c), ""), None, "{c}");
1833        }
1834        assert_eq!(to(200, &tag("00 ; url=/one/"), "").as_deref(), Some("https://a.example/one/"));
1835        // the bytes `http-equiv` gate the parse: a page that merely says refresh is no candidate
1836        assert_eq!(to(200, "<meta name=refresh content='0; url=/one/'>", ""), None, "no http-equiv");
1837        assert_eq!(to(200, &tag("0; url=/one/"), "<script src=/app.js></script>"), None, "a script");
1838        assert_eq!(to(200, "", &format!("<noscript>{}</noscript>", tag("360"))), None, "no URL");
1839        assert_eq!(to(404, &tag("0; url=/one/"), ""), None, "no 2xx");
1840        assert_eq!(to(200, &tag("0; url=/one/"), &"<p>A page of its own. </p>".repeat(80)), None, "a page");
1841    }
1842
1843    /// Redirects run through the fence: a public page that bounces to the metadata address or a name that
1844    /// resolves private is refused before the second request; relative Locations resolve; an endless chain stops.
1845    #[test]
1846    fn redirects_are_fenced() {
1847        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
1848        let calls = std::cell::RefCell::new(Vec::<String>::new());
1849        let fake = |to: Option<&'static str>| {
1850            let calls = &calls;
1851            move |u: String| {
1852                calls.borrow_mut().push(u);
1853                let reply = match to {
1854                    Some(t) => (302, Some(t.to_string()), ()),
1855                    None => (200, None, ()),
1856                };
1857                std::future::ready(Ok::<_, &'static str>(reply))
1858            }
1859        };
1860        let r = rt.block_on(follow("https://ex.com/a", fake(Some("http://169.254.169.254/latest/meta-data/"))));
1861        assert_eq!(r.err(), Some("private_address"));
1862        assert_eq!(*calls.borrow(), ["https://ex.com/a"], "the private hop is never requested");
1863        calls.borrow_mut().clear();
1864        // a name that resolves private (the fake resolver's `lan.`) is refused at the hop, not only at the first URL
1865        let r = rt.block_on(follow("https://ex.com/a", fake(Some("http://lan.ex.com:8765/admin"))));
1866        assert_eq!(r.err(), Some("private_address"));
1867        assert_eq!(*calls.borrow(), ["https://ex.com/a"], "the private hop is never requested");
1868        calls.borrow_mut().clear();
1869        assert_eq!(
1870            rt.block_on(follow("https://ex.com/a", fake(Some("http://[::ffff:7f00:1]/")))).err(),
1871            Some("private_address")
1872        );
1873        calls.borrow_mut().clear();
1874        assert_eq!(rt.block_on(follow("https://ex.com/a", fake(Some("/b")))).err(), Some("redirect_loop"));
1875        assert_eq!(calls.borrow().len(), 11, "the first request + 10 redirects");
1876        assert!(calls.borrow()[1..].iter().all(|u| u == "https://ex.com/b"));
1877        let ok = rt.block_on(follow("https://ex.com/a", fake(None)));
1878        assert_eq!(ok.map(|r| r.0), Ok("https://ex.com/a".to_string()));
1879    }
1880
1881    /// A DNS name that resolves only to loopback gets no address (`localhost` resolves from the hosts file,
1882    /// no network), and the error is recognised as `private_address`.
1883    #[test]
1884    fn resolver_drops_private_answers() {
1885        use wreq::dns::Resolve;
1886        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
1887        let e = rt.block_on(Fence.resolve("localhost".into())).err().expect("refused");
1888        assert!(e.is::<Private>());
1889    }
1890}