Skip to main content

fats/
settings.rs

1//! SETTINGS: every knob read once, with where it came from and any input that was refused.
2//! One reader per knob, so `fats config` shows the value in effect: a second reader that parses the same env var
3//! its own way can disagree with it. A refused value is never silent: it prints a `!` row and shows in `config`.
4
5use crate::telemetry::Level;
6use std::path::{Path, PathBuf, absolute};
7use std::sync::{LazyLock, OnceLock};
8use std::{collections::BTreeMap, env::home_dir, fmt::Debug, ops::RangeInclusive};
9
10/// A value and its source (`env FATS_X`, `default`).
11pub struct Set<T> {
12    pub value: T,
13    pub src: &'static str,
14}
15
16pub struct Settings {
17    pub session: Set<String>,
18    pub cache: Set<PathBuf>,
19    pub key_dir: Set<PathBuf>,
20    pub json: Set<bool>,
21    pub nocache: Set<bool>,
22    /// No network calls: URLs come from the cache only (`FATS_OFFLINE=1`; the test suite runs this way).
23    pub offline: Set<bool>,
24    /// Fetch loopback, private and link-local addresses too (`FATS_ALLOW_PRIVATE=1`); off, a URL that is or
25    /// resolves to one is refused at every hop (a prompt-injected `http://169.254.169.254/` reads nothing).
26    pub allow_private: Set<bool>,
27    /// Plain asks for Markdown first (`provider::MD_ACCEPT`; `FATS_ACCEPT_MD=0`: Safari's own `Accept`). On by default.
28    pub accept_md: Set<bool>,
29    /// What telemetry sends (`telemetry::Level`): off under a CI marker (telemetry.json `ci_env`), `DO_NOT_TRACK` or
30    /// `FATS_OFFLINE`, whatever is set; else `FATS_TELEMETRY`, then `settings.json` (`fats setup telemetry <level>`),
31    /// then full.
32    pub telemetry: Set<Level>,
33    /// `FATS_TELEMETRY_DEBUG=1`: every payload printed on stderr, nothing sent.
34    pub telemetry_debug: Set<bool>,
35    /// The exit country of a paid call that names none (`provider::exit`): `FATS_COUNTRY`, else `us`, the
36    /// country of the Accept-Language plain sends (`en-US,en;q=0.9`, wreq-util's Safari profile `header.rs`).
37    pub country: Set<String>,
38    /// Heading-less text is cut into blocks of this many tokens (default 300).
39    pub chunk: Set<usize>,
40    /// Minutes a `fats account` read stands in for a new one (`FATS_ACCOUNT_TTL`, default 15; 0 = always read).
41    pub account_ttl: Set<u64>,
42    /// Bright Data Web Unlocker zone (the BD CLI's `BRIGHTDATA_UNLOCKER_ZONE`, else `settings.json` `bd_zone`
43    /// that `fats setup` writes); no default, zones are per account.
44    pub bd_zone: Option<Set<String>>,
45    /// Thresholds set outside limits.json (env `FATS_<NAME>`, `settings.json`), checked against its kinds (`limit_of`).
46    pub limits: std::collections::HashMap<&'static str, Set<serde_json::Value>>,
47    /// `settings.json` as read at start (`set`, the zone; the `off` switches are read at each call: `on`).
48    pub saved: Saved,
49    /// One `! bad_setting …` row per refused value.
50    pub rejects: Vec<String>,
51}
52
53pub const CHUNK_RANGE: RangeInclusive<usize> = 50..=10_000;
54pub const ACCOUNT_TTL: u64 = 15;
55
56pub fn get() -> &'static Settings {
57    static S: OnceLock<Settings> = OnceLock::new();
58    // unit tests read no env (`FATS_CACHE`, keys) and no home dirs (`load`): never the developer's cache or keys
59    S.get_or_init(|| load(&env))
60}
61
62/// Env `k` as settings read it: empty = unset; unit tests read none.
63pub fn env(k: &str) -> Option<String> {
64    std::env::var(k).ok().filter(|v| !v.is_empty() && !cfg!(test))
65}
66
67/// THE Bright Data zone read: the configured Web Unlocker zone (`BRIGHTDATA_UNLOCKER_ZONE`), None = unset.
68pub fn zone() -> Option<&'static str> {
69    get().bd_zone.as_ref().map(|z| z.value.as_str())
70}
71
72/// The key-dir files: `auth.json` = secrets only (0600, `keys` by provider: `oxy`, `bd`, `decodo`, `gh`);
73/// `settings.json` = the rest `fats setup` and `fats config set` keep (providers switched `off`, the Bright Data
74/// zone, settings in `set`). Both `{"version": 1, …}`, written whole (`save`).
75pub const AUTH: &str = "auth.json";
76pub const PREFS: &str = "settings.json";
77/// The files 0.1 kept keys and the zone in, moved into those two once (`migrate`).
78const LEGACY: [(&str, &str); 3] = [("oxy", "oxylabs.key"), ("bd", "brightdata.key"), ("bd_zone", "brightdata.zone")];
79
80/// One of the two key-dir files; the fields the other one keeps stay empty and unwritten.
81#[derive(Default, Clone, serde::Serialize, serde::Deserialize)]
82#[serde(default)]
83pub struct Saved {
84    pub version: u32,
85    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
86    pub keys: BTreeMap<String, String>,
87    #[serde(skip_serializing_if = "Vec::is_empty")]
88    pub off: Vec<String>,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub bd_zone: Option<String>,
91    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
92    pub set: BTreeMap<String, serde_json::Value>,
93}
94
95/// Key-dir file `name` as saved; a missing or unreadable one is empty.
96pub fn saved(name: &str) -> Saved {
97    saved_in(&get().key_dir.value, name)
98}
99
100/// Key-dir file `name`'s path (a unit test's own dir, `tests::key_dir`).
101pub fn key_file(name: &str) -> PathBuf {
102    let dir = &get().key_dir.value;
103    #[cfg(test)]
104    let dir = &tests::key_dir(dir);
105    dir.join(name)
106}
107
108fn saved_in(dir: &Path, name: &str) -> Saved {
109    #[cfg(test)]
110    let dir = &tests::key_dir(dir);
111    std::fs::read(dir.join(name)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
112}
113
114/// Change key-dir file `name` with `edit` and write it whole: a temp file (0600, synced), then a rename, so a
115/// crash leaves the old file or the new one. A file a newer fats wrote (`version` > 1) is never overwritten; one
116/// whose edit replaces or removes a key is copied to `<name>.bak` (0600) first. Err = `<name>: <why>`.
117fn save(name: &str, edit: impl FnOnce(&mut Saved)) -> Result<(), String> {
118    save_to(&get().key_dir.value, name, edit).map_err(|e| format!("{name}: {e}"))
119}
120
121fn save_to(dir: &Path, name: &str, edit: impl FnOnce(&mut Saved)) -> std::io::Result<()> {
122    #[cfg(test)]
123    let dir = &tests::key_dir(dir);
124    let mut s = saved_in(dir, name);
125    if s.version > 1 {
126        return Err(std::io::Error::other(format!("{name} is version {}: written by a newer fats", s.version)));
127    }
128    let old = s.keys.clone();
129    edit(&mut s);
130    if old.iter().any(|(k, v)| s.keys.get(k) != Some(v)) {
131        save_in(dir, &format!("{name}.bak"), &std::fs::read(dir.join(name))?, false)?;
132    }
133    s.version = 1;
134    let tmp = format!(".{name}.tmp");
135    save_in(dir, &tmp, &serde_json::to_vec_pretty(&s).map_err(std::io::Error::other)?, false)?;
136    std::fs::rename(dir.join(&tmp), dir.join(name))
137}
138
139/// The 0.1 key files into `auth.json` / `settings.json`, once: copied, read back, then deleted (a file still
140/// there wins: a move cut short is done again).
141fn migrate(dir: &Path) {
142    for (k, f) in LEGACY {
143        let Ok(v) = std::fs::read_to_string(dir.join(f)).map(|v| v.trim().to_string()) else { continue };
144        let (zone, v) = (k == "bd_zone", Some(v).filter(|v| !v.is_empty()));
145        let name = if zone { PREFS } else { AUTH };
146        let put = |s: &mut Saved| {
147            if zone { s.bd_zone.clone_from(&v) } else { s.keys.extend(v.clone().map(|v| (k.into(), v))) }
148        };
149        let back = |s: Saved| if zone { s.bd_zone } else { s.keys.get(k).cloned() };
150        if v.is_none() || save_to(dir, name, put).is_ok() && back(saved_in(dir, name)) == v {
151            std::fs::remove_file(dir.join(f)).ok();
152        }
153    }
154}
155
156/// THE names `fats setup` keys, switches and saves under (`auth.json`): `free` = the plain fetch.
157pub const SWITCHES: [&str; 5] = ["free", "oxy", "bd", "decodo", "gh"];
158
159/// THE key read (fetches, setup, config, status): `auth.json` only, read at each call (a long `fats mcp` sees a
160/// key `fats setup` saved). A key in the environment is never sent: `fats setup import-env` copies it in, so the
161/// key a person saved is the key every call uses. Never printed or logged.
162pub fn key(name: &str) -> Option<String> {
163    saved(AUTH).keys.get(name).map(|v| v.trim().to_string()).filter(|k| !k.is_empty())
164}
165
166/// `name`'s key in the environment when it is not the one `auth.json` holds: (its variable, the providers.json
167/// row's or `GH_TOKEN` for gh; the key). Never sent, only copied in (`fats setup import-env`) or named as unused.
168/// Unit tests read none.
169pub fn env_key(name: &str) -> Option<(&'static str, String)> {
170    let var = crate::provider::Tier::parse(name).map_or(if name == "gh" { "GH_TOKEN" } else { "" }, |t| t.spec().env);
171    env(var).map(|v| (var, v.trim().to_string())).filter(|v| !v.1.is_empty() && key(name).as_ref() != Some(&v.1))
172}
173
174/// `name`'s key into `auth.json`, a Bright Data zone into `settings.json`. Err = the reason, never the key.
175pub fn save_key(name: &str, key: &str, zone: Option<&str>) -> Result<(), String> {
176    save(AUTH, |f| drop(f.keys.insert(name.into(), key.trim().into())))?;
177    zone.map_or(Ok(()), |z| save(PREFS, |f| f.bd_zone = Some(z.into())))
178}
179
180/// `name`'s key out of `auth.json` (and bd's zone out of `settings.json`).
181pub fn remove_key(name: &str) -> Result<(), String> {
182    save(AUTH, |f| drop(f.keys.remove(name)))?;
183    save(PREFS, |f| f.bd_zone = f.bd_zone.take().filter(|_| name != "bd"))
184}
185
186/// `name` is not switched off (`settings.json` `off`, read at each call as `key` reads keys: a `set_on` in this
187/// process, a `fats setup` beside a long `fats mcp`, shows at once).
188pub fn on(name: &str) -> bool {
189    !saved(PREFS).off.iter().any(|o| o == name)
190}
191
192/// Switch `name` on or off (`switched`). Err = the reason (`! refused · <it>`).
193pub fn set_on(name: &str, on: bool) -> Result<(), String> {
194    switched(name, on).and_then(|off| save(PREFS, |f| f.off = off))
195}
196
197/// THE switch rule: `settings.json`'s `off` with `name` switched, never leaving nothing that can fetch: after it,
198/// the free fetch or a keyed provider (not gh) stays on. Err = why not; `fats setup` shows no button it refuses.
199pub fn switched(name: &str, on: bool) -> Result<Vec<String>, String> {
200    if !SWITCHES.contains(&name) {
201        return Err(format!("unknown {name} · one of {}", SWITCHES.join(" ")));
202    }
203    let mut off = saved(PREFS).off;
204    off.retain(|o| o != name);
205    if !on {
206        off.push(name.to_string());
207    }
208    let fetches = |n: &&str| *n != "gh" && !off.iter().any(|o| o == n) && (*n == "free" || key(n).is_some());
209    if !SWITCHES.iter().any(fetches) {
210        return Err("nothing left that can fetch: turn one on or add a key".into());
211    }
212    Ok(off)
213}
214
215/// The settings `config set` takes besides the thresholds: the env readers', by their env name less `FATS_`.
216const READERS: [&str; 10] = [
217    "json", "nocache", "offline", "accept_md", "country", "chunk", "account_ttl", "session", "telemetry",
218    "telemetry_debug",
219];
220/// The env readers no command sets and `settings.json` never holds: the fences (the private-address fence; the
221/// cache dir, which bounds the MCP file fence), the key folder (where `settings.json` lives) and the human switch.
222/// A tool call can run `fats`, never set the env of the host that runs it.
223const ENV_ONLY: [&str; 4] = ["allow_private", "cache", "key_dir", "human"];
224/// The changes a tool call never makes (under MCP, `guard`): the home-IP brake and the usage counts, besides every
225/// `setup <name> on|off|<level>`. The speed knobs stay settable.
226const NOT_UNDER_MCP: [&str; 2] = ["plain_host_pace_ms", "telemetry"];
227
228/// How env-only setting `name` is set: `set FATS_CACHE=<dir> in the host's env, never from a tool call`.
229fn env_way(name: &str) -> String {
230    let v = if matches!(name, "cache" | "key_dir") { "<dir>" } else { "1" };
231    format!("set FATS_{}={v} in the host's env, never from a tool call", name.to_uppercase())
232}
233
234/// THE fence rule of a change (`config set|unset <name> …`, `setup <name> <on|off|level>`; `words` = what follows the
235/// verb): Some = (code, the `!` row). An env-only setting is never set, on the CLI and under MCP alike (`unset`
236/// removes an older fats' value: it only closes a fence); under MCP (`mcp`) so is every `setup` switch and a
237/// `NOT_UNDER_MCP` name, whatever the value.
238pub fn guard(words: &[&str], setup: bool, mcp: bool) -> Option<(&'static str, String)> {
239    let name = *if setup { words.first() } else { words.get(1) }?;
240    if !setup && ENV_ONLY.contains(&name) && words[0] == "set" {
241        return Some(("env_only", format!("! env_only {name} · {}", env_way(name))));
242    }
243    let verb = if setup { "setup" } else { "config" };
244    let row = format!("! not_under_mcp {verb} {} · run it in a terminal", words.join(" "));
245    (mcp && (setup || NOT_UNDER_MCP.contains(&name))).then_some(("not_under_mcp", row))
246}
247
248/// The same fence on a mod (under MCP, `cli::run`): a tool call never lowers a `NOT_UNDER_MCP` threshold below its
249/// setting for itself (`plain_host_pace_ms:0`); the whole call is refused, as `config set` is. Raising it is allowed.
250pub fn lowered(mods: &[(String, String)]) -> Option<crate::lang::Out> {
251    crate::cli::FENCE.get()?;
252    let set = |k: &str| get().limits.get(k).map_or(LIMITS.get(k), |s| Some(&s.value))?.as_f64();
253    let low = |(k, v): &&(String, String)| fits(k, v).and_then(|m| m.as_f64()).is_some_and(|m| Some(m) < set(k));
254    let (k, v) = mods.iter().filter(|m| NOT_UNDER_MCP.contains(&m.0.as_str())).find(low)?;
255    let row = format!("! not_under_mcp {k}:{v} · run it in a terminal");
256    Some(crate::lang::Out::fail("not_under_mcp", format!("= ! not_under_mcp {k}:{v} · $0"), row))
257}
258
259/// A name in the env (`FATS_<NAME>`) or `settings.json` that no setting reads (a removed or mistyped one): one
260/// `! unknown_setting` row each in `fats config`, never on every answer. Unit tests read no env.
261pub fn unknown(s: &Settings) -> Vec<String> {
262    let known = |n: &str| LIMITS.contains_key(n) || READERS.contains(&n) || ENV_ONLY.contains(&n);
263    let vars = std::env::vars().filter(|_| !cfg!(test));
264    let env = vars.filter_map(|(k, _)| Some((k.strip_prefix("FATS_")?.to_lowercase(), format!("env {k}"))));
265    let file = s.saved.set.keys().map(|n| (n.clone(), format!("{PREFS} {n}")));
266    let fix = |at: &str| match at.strip_prefix("env ") {
267        Some(k) => format!("unset {k}"),
268        None => format!("{} config unset {}", crate::lang::bin(), at.rsplit(' ').next().unwrap_or_default()),
269    };
270    let rows = env.chain(file).filter(|(n, _)| !known(n));
271    let rows = rows.map(|(_, at)| format!("! unknown_setting {at} · read by nothing → {}", fix(&at)));
272    // an older fats took `config set cache|allow_private`: such a value is never read, its row says how instead
273    let fenced = s.saved.set.keys().filter(|n| ENV_ONLY.contains(&n.as_str())).map(|n| format!("{PREFS} {n}"));
274    rows.chain(fenced.map(|at| format!("! env_only {at} · ignored → {}", fix(&at)))).collect()
275}
276
277/// `fats config set <name> <value>` into `settings.json`: a threshold of limits.json or a reader, checked by THE
278/// reader (`load`, `fits`) as if the env said it: its `! bad_setting` row is the refusal. Used from the next command.
279/// A mod's own `config` row (`cost_cap` of `cost:`, `wait`) is set per call only.
280pub fn set(name: &str, value: &str) -> Result<(), String> {
281    let m = name.strip_suffix("_cap").unwrap_or(name);
282    if !LIMITS.contains_key(name) && !READERS.contains(&name) {
283        let per = crate::lang::WORDS.keys.contains(&m).then(|| format!("{name} is per call: the {m}: mod"));
284        return Err(per.unwrap_or(format!("unknown {name} · the names: {} config", crate::lang::bin())));
285    }
286    let k = format!("FATS_{}", name.to_uppercase());
287    let read = load(&|e| if e == k { Some(value.into()) } else { env(e) });
288    if let Some(bad) = read.rejects.iter().find(|r| r.starts_with(&format!("! bad_setting {k}="))) {
289        let want = bad.split_once(" · want ").and_then(|w| w.1.split_once(" · using ")).map_or("", |w| w.0);
290        return Err(format!("{name} {value} · want {want}"));
291    }
292    let v = fits(name, value).unwrap_or_else(|| value.into());
293    save(PREFS, |f| drop(f.set.insert(name.into(), v)))
294}
295
296pub fn unset(name: &str) -> Result<(), String> {
297    save(PREFS, |f| drop(f.set.remove(name)))
298}
299
300/// THE owner-only writer (keys in the key dir, a provider's kept error answer, the spend ledger's rows, `append`):
301/// `<dir>/<file>` at 0600, an old file's wider mode too, before the bytes go in; the dir 0700, also one that
302/// exists already (an installer's receipt can make the key dir 0755 before `fats` first runs). A whole write is
303/// synced before it returns (`save` renames it next).
304pub fn save_in(dir: &Path, file: &str, bytes: &[u8], append: bool) -> std::io::Result<()> {
305    let mut open = std::fs::OpenOptions::new();
306    std::fs::create_dir_all(dir)?;
307    #[cfg(unix)]
308    {
309        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
310        open.mode(0o600);
311        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
312    }
313    let mut f = open.write(true).create(true).append(append).truncate(!append).open(dir.join(file))?;
314    #[cfg(unix)]
315    f.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
316    std::io::Write::write_all(&mut f, bytes)?;
317    if append { Ok(()) } else { f.sync_all() }
318}
319
320/// THE secret register: every credential this binary can send (every key in `auth.json`, `key`) and every key the
321/// environment holds (`env_key`: never sent, still never printed). `lang::emit` masks them in everything it
322/// prints, a provider's error body is masked before it is kept. A new credential goes in here.
323pub fn secrets() -> Vec<String> {
324    let env = SWITCHES.into_iter().filter_map(|p| env_key(p).map(|e| e.1));
325    saved(AUTH).keys.into_values().map(|k| k.trim().to_string()).chain(env).filter(|k| !k.is_empty()).collect()
326}
327
328/// The built-in tables: data, not logic, as JSON under `src/data/`, each parsed once (`table`) into its owner's
329/// typed struct. `fats config` counts them (`table_rows`); `tables_load` fails `cargo test` on a typo.
330pub const TABLES: [(&str, &str); 8] =
331    embed!("", ".json": "providers", "errors", "check", "sites", "clean", "words", "limits", "telemetry");
332
333/// `[(name, text)]` of the files `src/data/<dir><name><ext>`, built in.
334macro_rules! embed {
335    ($dir:literal, $ext:literal: $($n:literal),+) => { [$(($n, include_str!(concat!("data/", $dir, $n, $ext)))),+] };
336}
337pub(crate) use embed;
338
339/// Built-in table `name` as its owner's type. One that does not parse is a build defect, never an input:
340/// `tables_load` fails `cargo test` before such a binary exists.
341pub fn table<T: serde::Deserialize<'static>>(name: &str) -> T {
342    let json = TABLES.iter().find(|t| t.0 == name).map_or("", |t| t.1);
343    serde_json::from_str(json).unwrap_or_else(|e| panic!("built-in table {name}: {e}"))
344}
345
346/// The behaviour thresholds (`src/data/limits.json`: name with its unit → value), each a `fats config` row.
347pub static LIMITS: LazyLock<indexmap::IndexMap<&str, serde_json::Value>> = LazyLock::new(|| table("limits"));
348
349thread_local! {
350    /// The running command's mods (`cli::run`): a threshold named as a mod (`batch_parallel:8`) wins for it.
351    static MODS: std::cell::RefCell<Vec<(String, String)>> = const { std::cell::RefCell::new(Vec::new()) };
352}
353
354/// The mods of the command this thread runs (`cli::run`, once per command; `fats mcp` runs each on its own).
355pub fn mods(m: &[(String, String)]) {
356    MODS.set(m.to_vec());
357}
358
359/// THE value of threshold `name`: its mod, else env `FATS_<NAME>`, else `settings.json` (`fats config set`), else
360/// limits.json (`limit_of`). A missing or mistyped built-in is a build defect, never an input: `limits_used`
361/// fails `cargo test` on a name, the owner's tests on a type; a user value of the wrong kind never gets here.
362pub fn limit<T: serde::de::DeserializeOwned>(name: &str) -> T {
363    serde_json::from_value(limit_of(name).0).unwrap_or_else(|e| panic!("limits.json {name}: {e}"))
364}
365
366/// `limit`'s value and where it came from: `mod`, `env`, `settings.json`, `build`.
367pub fn limit_of(name: &str) -> (serde_json::Value, &'static str) {
368    let built = LIMITS.get(name).cloned().unwrap_or_default();
369    let m = MODS.with_borrow(|m| m.iter().rev().find(|x| x.0 == name).and_then(|x| fits(name, &x.1)));
370    m.map_or_else(|| get().limits.get(name).map_or((built, "build"), |s| (s.value.clone(), s.src)), |v| (v, "mod"))
371}
372
373/// THE check of a threshold's value (a mod, env, `settings.json`, `config set`): `v` as threshold `name`'s, a whole
374/// number for a whole row, any number for a fraction, never under its floor (`least`); `reason_chars` at most 200
375/// (a reason is a few words, never the provider's answer: `provider::said_short`).
376pub fn fits(name: &str, v: &str) -> Option<serde_json::Value> {
377    let n: serde_json::Value = serde_json::from_str(v.trim()).ok().filter(serde_json::Value::is_number)?;
378    let kind = LIMITS.get(name)?.is_f64() || n.is_u64();
379    let most = if name == "reason_chars" { 200.0 } else { f64::MAX };
380    (kind && n.as_f64().is_some_and(|f| f >= least(name) && f <= most)).then_some(n)
381}
382
383/// A threshold's floor: 0 for a fraction and where 0 turns it off (no host pace, no grace, no error body, a sweep
384/// every run); 100 for `read_cap` (a chunk keeps 50 tokens back); else 1 (a count, cap or lane of 0 does nothing).
385fn least(name: &str) -> f64 {
386    match name {
387        "plain_host_pace_ms" | "grace_s" | "err_cap_bytes" | "sweep_every_s" => 0.0,
388        "read_cap" => 100.0,
389        _ => f64::from(u8::from(!LIMITS.get(name).is_some_and(serde_json::Value::is_f64))),
390    }
391}
392
393/// A table's rows: every array element and object entry that holds no list or map itself.
394pub fn table_rows(v: &serde_json::Value) -> usize {
395    match v {
396        serde_json::Value::Array(a) => a.len(),
397        serde_json::Value::Object(o) => o.values().map(table_rows).sum(),
398        _ => 1,
399    }
400}
401
402/// `1 true yes on` / `0 false no off`, any case.
403pub fn boolean(v: &str) -> Option<bool> {
404    match v.to_ascii_lowercase().as_str() {
405        "1" | "true" | "yes" | "on" => Some(true),
406        "0" | "false" | "no" | "off" => Some(false),
407        _ => None,
408    }
409}
410
411/// A system folder: on Windows the variable the install guide names (`%APPDATA%`, `%LOCALAPPDATA%`) when it holds
412/// an absolute path, else the OS's own folder (`dirs`: Windows' known folder, which ignores the variable); in a unit
413/// test a scratch home's, never the developer's.
414pub fn system_dir(env: &dyn Fn(&str) -> Option<String>, var: &str, os: fn() -> Option<PathBuf>) -> Option<PathBuf> {
415    let os = if cfg!(test) { || Some(std::env::temp_dir().join("fats-unit")) } else { os };
416    env(var).map(PathBuf::from).filter(|p| cfg!(windows) && p.is_absolute()).or_else(os)
417}
418
419fn load(env: &dyn Fn(&str) -> Option<String>) -> Settings {
420    let mut r = Reader { env, rejects: Vec::new(), file: BTreeMap::new() };
421    let key_dir = system_dir(env, "APPDATA", dirs::config_dir).unwrap_or_default().join("fatsearch");
422    let key_dir = r.read("env FATS_KEY_DIR", key_dir, "", |v| Some(v.into()));
423    migrate(&key_dir.value);
424    let saved = saved_in(&key_dir.value, PREFS);
425    r.file.clone_from(&saved.set);
426    let session = r.session();
427    let cache = system_dir(env, "LOCALAPPDATA", dirs::cache_dir).unwrap_or_else(std::env::temp_dir).join("fatsearch");
428    // made absolute once (a relative dir is the cwd's at start); `~/…` no shell expanded, a dir fats can't make
429    // (a host started in `/`) and one holding the keys (a sweep deletes in it) are refused for the default
430    let safe = |v: &str, p: &PathBuf| !v.starts_with('~') && p.parent().is_some() && home_dir() != Some(p.into());
431    let safe = |v: &str, p: &PathBuf| safe(v, p) && !key_dir.value.starts_with(p) && !p.starts_with(&key_dir.value);
432    let ok = |v: &str| absolute(v).ok().filter(|p| safe(v, p) && crate::cache::private_root(p, false));
433    let cache =
434        r.read("env FATS_CACHE", cache, "a dir fats can make, not /, $HOME, in or over the key dir, never ~/…", ok);
435    let mut limits = std::collections::HashMap::new();
436    for (k, built) in LIMITS.iter() {
437        let name = format!("FATS_{}", k.to_uppercase());
438        let file = || saved.set.get(*k).map(|v| (v.to_string(), "settings.json"));
439        let Some((v, src)) = env(&name).map(|v| (v, "env")).or_else(file) else { continue };
440        match fits(k, &v) {
441            Some(value) => drop(limits.insert(*k, Set { value, src })),
442            None => r.refuse(&name, src, &v, &format!("a number ≥ {} like {built}", least(k)), &built.to_string()),
443        }
444    }
445    let zone_env = env("BRIGHTDATA_UNLOCKER_ZONE").map(|value| Set { value, src: "env BRIGHTDATA_UNLOCKER_ZONE" });
446    let zone_file = saved.bd_zone.clone().filter(|v| !v.is_empty()).map(|value| Set { value, src: "settings.json" });
447    let want = format!("an integer {}-{}", CHUNK_RANGE.start(), CHUNK_RANGE.end());
448    // fields run in order: the `! bad_setting` rows come out as listed
449    let mut s = Settings {
450        session,
451        cache,
452        key_dir,
453        json: r.read("env FATS_JSON", false, BOOLS, boolean),
454        nocache: r.read("env FATS_NOCACHE", false, BOOLS, boolean),
455        offline: r.read("env FATS_OFFLINE", false, BOOLS, boolean),
456        allow_private: r.read("env FATS_ALLOW_PRIVATE", false, BOOLS, boolean),
457        accept_md: r.read("env FATS_ACCEPT_MD", true, BOOLS, boolean),
458        telemetry: r.read("env FATS_TELEMETRY", Level::Full, "full|minimal|off", Level::parse),
459        telemetry_debug: r.read("env FATS_TELEMETRY_DEBUG", false, BOOLS, boolean),
460        country: r.read("env FATS_COUNTRY", "us".into(), "two letters: us · de", |v| {
461            (v.len() == 2 && v.bytes().all(|b| b.is_ascii_alphabetic())).then(|| v.to_ascii_lowercase())
462        }),
463        chunk: r.read("env FATS_CHUNK", 300, &want, |v| v.parse().ok().filter(|n| CHUNK_RANGE.contains(n))),
464        account_ttl: r.read("env FATS_ACCOUNT_TTL", ACCOUNT_TTL, "minutes 0-1440", |v| {
465            v.parse().ok().filter(|n| (0..=1440).contains(n))
466        }),
467        bd_zone: zone_env.or(zone_file),
468        limits,
469        saved,
470        rejects: r.rejects,
471    };
472    s.telemetry = crate::telemetry::quiet(env, s.offline.value).unwrap_or(s.telemetry);
473    s
474}
475
476/// What a boolean setting takes (`boolean`).
477const BOOLS: &str = "1|true|yes|on or 0|false|no|off";
478
479/// The environment being read, and a `! bad_setting` row for each value it refused.
480struct Reader<'a> {
481    env: &'a dyn Fn(&str) -> Option<String>,
482    rejects: Vec<String>,
483    /// `settings.json`'s `set`: read when the env has no value (`FATS_JSON` → `json`).
484    file: BTreeMap<String, serde_json::Value>,
485}
486
487impl Reader<'_> {
488    /// The `! bad_setting` row of env `k`'s value, or of its `settings.json` name when `src` is the file.
489    fn refuse(&mut self, k: &str, src: &str, v: &str, want: &str, using: &str) {
490        let n = k.trim_start_matches("FATS_").to_lowercase();
491        let (at, fix) = match src {
492            PREFS => (format!("{PREFS} {n}"), format!("{} config unset {n} or set it again", crate::lang::bin())),
493            _ => (k.into(), format!("unset {k} or fix it")),
494        };
495        self.rejects.push(format!("! bad_setting {at}={v} · want {want} · using {using} → {fix}"));
496    }
497
498    /// `FATS_SESSION` when it is a safe name (a refused name hashes to its own session, so parallel callers that
499    /// each set one never merge); else one session per user, `default` under the cache root: every shell, tty and
500    /// directory of that user reads the same ids (a cwd hash gave each directory its own `u1`).
501    fn session(&mut self) -> Set<String> {
502        match self.raw("env FATS_SESSION") {
503            Some((v, src)) if v.len() <= 64 && v.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') => {
504                Set { value: v, src }
505            }
506            Some((v, src)) => {
507                let value = blake3::hash(v.as_bytes()).to_hex()[..8].to_string();
508                self.refuse("FATS_SESSION", src, &v, "letters, digits, - and _ (≤ 64)", &value);
509                Set { value, src: "hash of FATS_SESSION" }
510            }
511            None => Set { value: "default".into(), src: "default" },
512        }
513    }
514
515    /// Env `src` (`env FATS_JSON`), else its `settings.json` value (`json`): (value as text, source).
516    fn raw(&self, src: &'static str) -> Option<(String, &'static str)> {
517        let k = src.trim_start_matches("env ");
518        let n = k.trim_start_matches("FATS_").to_lowercase();
519        let v = self.file.get(&n).filter(|_| !ENV_ONLY.contains(&n.as_str()));
520        let file = v.map(|v| (v.as_str().map_or_else(|| v.to_string(), String::from), "settings.json"));
521        (self.env)(k).map(|v| (v, src)).or(file)
522    }
523
524    /// Env `k` (`src` = `env k`), else `settings.json`, as `fit` reads it, else `default`; a value it refuses
525    /// gets a `! bad_setting` row naming `want`.
526    fn read<T: Debug>(&mut self, src: &'static str, default: T, want: &str, fit: impl Fn(&str) -> Option<T>) -> Set<T> {
527        let Some((v, from)) = self.raw(src) else { return Set { value: default, src: "default" } };
528        if let Some(value) = fit(&v) {
529            return Set { value, src: from };
530        }
531        self.refuse(src.trim_start_matches("env "), from, &v, want, &format!("{default:?}"));
532        Set { value: default, src: "default" }
533    }
534}
535
536#[cfg(test)]
537pub(crate) mod tests {
538    use super::*;
539
540    thread_local! {
541        /// This thread's key dir in place of the scratch home's one that every unit test process shares: a test
542        /// that saves keys and switches owns its `auth.json` and `settings.json`, no other test sees them.
543        pub(crate) static KEY_DIR: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
544    }
545
546    /// The key dir `saved_in` and `save_to` use for `dir`: this thread's own (`KEY_DIR`), else `dir`.
547    pub(crate) fn key_dir(dir: &Path) -> PathBuf {
548        KEY_DIR.with_borrow(Clone::clone).unwrap_or_else(|| dir.into())
549    }
550
551    /// A key replaced (or removed) leaves the file it was in as `auth.json.bak`, 0600; a new key replaces nothing and
552    /// writes none. The key read is `auth.json`'s, never the environment's (unit tests read no env at all).
553    #[test]
554    fn a_replaced_key_leaves_a_backup() {
555        let dir = crate::scratch::Scratch::new("auth-bak");
556        KEY_DIR.set(Some(dir.to_path_buf()));
557        crate::scratch::auth(&dir, &[("oxy", "first-oxy-key-0123456789")]);
558        save_key("bd", "bd-key-0123456789", Some("zone_a")).expect("save");
559        assert!(!dir.join("auth.json.bak").exists(), "a new key replaces nothing");
560        let before = std::fs::read(dir.join(AUTH)).expect("auth.json");
561        save_key("oxy", " second-oxy-key-0123456789 ", None).expect("replace");
562        assert_eq!(std::fs::read(dir.join("auth.json.bak")).expect("the backup"), before);
563        assert_eq!(key("oxy").as_deref(), Some("second-oxy-key-0123456789"));
564        #[cfg(unix)]
565        {
566            use std::os::unix::fs::PermissionsExt;
567            let mode = std::fs::metadata(dir.join("auth.json.bak")).map(|m| m.permissions().mode() & 0o777);
568            assert_eq!(mode.ok(), Some(0o600));
569        }
570        remove_key("bd").expect("remove");
571        let bak = String::from_utf8(std::fs::read(dir.join("auth.json.bak")).expect("the backup")).expect("utf-8");
572        assert!(bak.contains("bd-key-0123456789") && key("bd").is_none() && env_key("oxy").is_none(), "{bak}");
573        KEY_DIR.set(None);
574    }
575
576    /// Review 0.1.7: a unit test never reads the developer's cache, keys or zone (`worst` read its stored copies):
577    /// the settings of a test run sit under a scratch home and take nothing from the env.
578    #[test]
579    fn unit_tests_use_a_scratch_home() {
580        let (s, home) = (get(), std::env::temp_dir().join("fats-unit"));
581        assert!(s.cache.value.starts_with(&home) && s.key_dir.value.starts_with(&home), "{:?}", s.cache.value);
582        assert_eq!((s.cache.src, s.bd_zone.as_ref().map(|z| z.src)), ("default", None));
583    }
584
585    /// A user's threshold has the built-in's kind: a whole number for a whole row, any number for a fraction;
586    /// text, a negative or a fraction for a whole row is refused (never a panic in `limit`).
587    #[test]
588    fn a_threshold_keeps_its_kind() {
589        let (whole, frac) = ("batch_parallel", "loss_max");
590        assert_eq!(
591            (fits(whole, "8"), fits(frac, "2"), fits("grace_s", "0")),
592            (Some(8.into()), Some(2.into()), Some(0.into()))
593        );
594        let refused =
595            [fits(whole, "2.5"), fits(whole, "-1"), fits(whole, "x"), fits(frac, "\"1\""), fits(frac, "-0.1")];
596        assert!(refused.iter().all(Option::is_none));
597        // a count of 0 does nothing (0 lanes, 0 rows): each row has its floor
598        assert_eq!((fits(whole, "0"), fits("read_cap", "60"), fits("nope", "1")), (None, None, None));
599        assert_eq!((fits("reason_chars", "200"), fits("reason_chars", "201")), (Some(200.into()), None), "a ceiling");
600    }
601
602    /// Every threshold in limits.json is read by name somewhere in src/ and every name read is in the file: a typo
603    /// or a dead row fails here, and `fats config` prints exactly what the code uses.
604    #[test]
605    fn limits_used() {
606        let src: String = std::fs::read_dir("src")
607            .expect("src")
608            .filter_map(|e| std::fs::read_to_string(e.ok()?.path()).ok())
609            .collect();
610        let read: std::collections::BTreeSet<&str> = src
611            .split("limit(\"")
612            .skip(1)
613            .chain(src.split("limit::<u64>(\"").skip(1))
614            .chain(src.split("limit::<usize>(\"").skip(1))
615            .filter_map(|s| s.split('"').next())
616            .collect();
617        let have: std::collections::BTreeSet<&str> = LIMITS.keys().copied().collect();
618        assert_eq!(read, have);
619        assert_eq!((limit::<usize>("max_depth"), limit::<f64>("loss_max")), (512, 0.30));
620    }
621
622    /// `%APPDATA%` and `%LOCALAPPDATA%` count on Windows when absolute; elsewhere, and relative, the OS's folder
623    /// (a unit test's: the scratch home).
624    #[test]
625    fn a_system_dir_takes_an_absolute_variable_on_windows() {
626        let os = Some(std::env::temp_dir().join("fats-unit"));
627        let abs = if cfg!(windows) { r"D:\Users\a\AppData\Local" } else { "/home/a/local" };
628        let want = if cfg!(windows) { Some(abs.into()) } else { os.clone() };
629        assert_eq!(system_dir(&|_| Some(abs.into()), "LOCALAPPDATA", dirs::cache_dir), want);
630        assert_eq!(system_dir(&|_| Some("AppData".into()), "APPDATA", dirs::config_dir), os, "relative: the OS's");
631        assert_eq!(system_dir(&|_| None, "APPDATA", dirs::config_dir), os);
632    }
633
634    /// Every built-in table parses into its owner's type, with its row count and a sample row (a JSON typo, an
635    /// unknown field or a lost row fails here, not in front of an agent).
636    #[test]
637    fn tables_load() {
638        let rows: Vec<(&str, usize)> =
639            TABLES.iter().map(|(n, j)| (*n, table_rows(&serde_json::from_str(j).expect("json")))).collect();
640        assert_eq!(
641            rows,
642            [
643                ("providers", 49),
644                ("errors", 53),
645                ("check", 86),
646                ("sites", 69),
647                ("clean", 194),
648                ("words", 1620),
649                ("limits", 55),
650                ("telemetry", 10)
651            ]
652        );
653        let words = &crate::lang::WORDS;
654        assert_eq!((words.stop[0], words.stop.len(), words.commands[0]), ("the", 30, "stats"));
655        let clean = &crate::clean::LISTS;
656        assert_eq!((crate::clean::sniff(b"PK\x03\x04x"), clean.text[2]), (Some("zip"), "xml"));
657        let sites = &crate::fetch::SITES;
658        assert_eq!((sites.gov[1], sites.gov.len()), ("mil", 7));
659        let check = &crate::fetch::CHECK;
660        assert_eq!((check.rules.len(), check.rules[3].code, check.rules[4].code), (6, "captcha_wall", ""));
661        let fix = &crate::lang::FIX;
662        assert_eq!(
663            (fix[0], fix[48]),
664            (("provider_timeout", "{b} {id} fresh:true {arg}"), ("fetch_failed", "{b} {id} fresh:true"))
665        );
666        let p = &crate::provider::PROVIDERS;
667        assert_eq!((p.specs.len(), p.apis.len(), p.links.len(), p.cctld.len()), (6, 14, 4, 25));
668        let bd = crate::provider::Tier::Bd.spec();
669        assert_eq!((bd.short, bd.env, bd.timeout.as_secs(), bd.price), ("bd", "BRIGHTDATA_API_KEY", 40, 0.0015));
670        // every render tier gets 40 s
671        use crate::provider::Tier;
672        let renders = [Tier::Bd, Tier::OxyJs, Tier::DecodoJs].map(|t| t.spec().timeout.as_secs());
673        assert_eq!(renders, [40; 3]);
674        let costs = crate::provider::Api::BdCosts.row();
675        assert_eq!((costs.method, costs.url), ("POST", "https://api.brightdata.com/costs/export/json"));
676        assert_eq!((p.links[2].billing, p.cctld["uk"]), (Some("https://brightdata.com/cp/billing"), "gb en"));
677    }
678
679    fn with(pairs: &[(&str, &str)]) -> Settings {
680        let m: std::collections::HashMap<String, String> =
681            pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
682        load(&|k| m.get(k).cloned())
683    }
684
685    /// What `config` shows is what consumers use; a refused value is a `!` row, never a silent default.
686    #[test]
687    fn values_sources_and_refusals() {
688        let s = with(&[("FATS_JSON", "true"), ("FATS_NOCACHE", "on"), ("FATS_CHUNK", "400"), ("FATS_SESSION", "a-1")]);
689        assert_eq!((s.json.value, s.nocache.value, s.chunk.value, s.session.value.as_str()), (true, true, 400, "a-1"));
690        assert_eq!((s.json.src, s.chunk.src), ("env FATS_JSON", "env FATS_CHUNK"));
691        assert!(s.rejects.is_empty());
692        let s = with(&[("FATS_JSON", "maybe"), ("FATS_CHUNK", "abc"), ("FATS_SESSION", "../../etc")]);
693        assert_eq!((s.json.value, s.chunk.value, s.session.src), (false, 300, "hash of FATS_SESSION"));
694        assert_eq!(s.session.value.len(), 8, "hex hash, printed as s:<hash> (not s:s<hash>)");
695        let (a, b) = (with(&[("FATS_SESSION", "p-a.x-1")]), with(&[("FATS_SESSION", "p-b.x-1")]));
696        assert_ne!(a.session.value, b.session.value, "two refused names never share a session");
697        assert!(a.rejects[0].contains("FATS_SESSION=p-a.x-1 · want letters, digits, - and _"));
698        assert_eq!((with(&[]).session.value.as_str(), with(&[]).session.src), ("default", "default"));
699        assert_eq!(s.rejects.len(), 3);
700        assert!(s.rejects.iter().all(|r| r.starts_with("! bad_setting ") && r.contains('→')));
701        assert!(with(&[("FATS_CHUNK", "0")]).rejects[0].contains("FATS_CHUNK=0"));
702        // a default-on switch: on unless switched off; a refused value keeps it on and says so
703        assert_eq!((with(&[]).accept_md.value, with(&[]).accept_md.src), (true, "default"));
704        let off = with(&[("FATS_ACCEPT_MD", "off")]);
705        assert_eq!((off.accept_md.value, off.accept_md.src), (false, "env FATS_ACCEPT_MD"));
706        let bad = with(&[("FATS_ACCEPT_MD", "sometimes")]);
707        let refused = &bad.rejects[0];
708        assert!(bad.accept_md.value && refused.contains("FATS_ACCEPT_MD=sometimes") && refused.contains("using true"));
709        // account TTL: minutes, 0 = always read; a refused value keeps the default and says so
710        assert_eq!((with(&[]).account_ttl.value, with(&[("FATS_ACCOUNT_TTL", "0")]).account_ttl.value), (15, 0));
711        let bad = with(&[("FATS_ACCOUNT_TTL", "15m")]);
712        assert!(bad.account_ttl.value == 15 && bad.rejects[0].contains("FATS_ACCOUNT_TTL=15m · want minutes 0-1440"));
713    }
714}