Skip to main content

fats/
cache.rs

1//! CACHE: root, session, ids, cursor, URL index, global jobs, page snapshots.
2//! ```text
3//!   <root>/index.json                url → {dir, t}          (shared, flock)
4//!   <root>/jobs.json                 [{session, cmd, t}]     j<N> = N-th row, global monotonic (flock)
5//!   <root>/account.json              last `fats account` read: {t, rows: [Account]} (parsed numbers, no answers)
6//!   <root>/swept                     its mtime = the last sweep of every session (`sweep`)
7//!   <root>/pace/<host>               the home-IP brake: the last plain start to that host (`provider::pace`)
8//!   <root>/telemetry/                `ping/` day and week stamps · `days/` day marks · `week/` the weekly tally
9//!                                    (`bump`) · `latest.json` · `sent.jsonl` (`telemetry::at`); not in `usage`
10//!   <root>/<session>/state.json      {u: [{url, dir, alias?, job, serp?}], cursor}
11//!   <root>/<session>/u<N>/           raw.html · meta.json · doc.json (rebuilt from raw.html when stale)
12//!                                    · error.txt (0600): the providers' error answers, masked, never printed
13//!   <root>/<session>/u<N>/assets/    m<K>.<ext> + m<K>.json: picture K of the page, fetched on demand (`Asset`)
14//!   <root>/<session>/j<N>/           meta.json of web search j<N> (hits inside) · error.txt; its results are `serp`
15//!                                    entries with no dir until a command fetches them into the same id
16//!   <root>/<session>/run/u<N>.*      a fetch that outlives its call (`Detached`): .json the run, .lock held by
17//!                                    its process, .log that process's stdout + stderr
18//!   <root>/<session>/run/setup-<p>.* the key form for provider p (`setup::run_file`): .json token, port, deadline;
19//!                                    .log its output
20//! ```
21
22use crate::clean::{DOC_V, Doc, build_doc};
23use crate::settings::limit;
24use chrono::Datelike;
25use serde::{Deserialize, Serialize, de::DeserializeOwned};
26use serde_json::{Map, Value};
27use std::collections::BTreeMap;
28use std::fs::{self, File};
29use std::path::{Path, PathBuf};
30use std::time::{Instant, SystemTime, UNIX_EPOCH};
31
32pub fn now() -> f64 {
33    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0)
34}
35
36pub fn jload<T: DeserializeOwned>(p: &Path) -> Option<T> {
37    serde_json::from_slice(&fs::read(p).ok()?).ok()
38}
39
40/// A failed run's provider answers (`fetch::error_text`): `stats` points at the file, nothing prints it.
41pub const ERROR_FILE: &str = "error.txt";
42
43/// THE spend ledger, in the key dir (never swept, so `stats` still sums what was spent once the pages are gone):
44/// one JSON line `[unix s, [cost, unverified], "<dir>"]` per stored fetch or search record that cost or may have,
45/// and per dead run's calls in flight once its `run/` is swept; `dir` = the record's path (`<root>/default/u3`).
46/// No URL, no query. A row it cannot write is never a failed fetch: `stats` probes the file and says why.
47pub const SPEND_FILE: &str = "spend.log";
48
49fn spend_log(paid: [f64; 2], dir: &Path) {
50    let row = serde_json::json!([now(), paid, dir.to_string_lossy()]).to_string() + "\n";
51    let keys = &crate::settings::get().key_dir.value;
52    (paid[0] + paid[1] > 0.0).then(|| crate::settings::save_in(keys, SPEND_FILE, row.as_bytes(), true).ok());
53}
54
55/// Write `ERROR_FILE` in `dir`, readable by its owner only.
56fn keep_error(dir: &Path, body: &[u8]) -> Result<(), String> {
57    crate::settings::save_in(dir, ERROR_FILE, body, false).map_err(|e| format!("{}/{ERROR_FILE}: {e}", dir.display()))
58}
59
60/// The numbers in `dir`'s entries named `<prefix><N><suffix>` (`u3.json`, `j4`), smallest first; none when `dir`
61/// cannot be read.
62fn numbered(dir: &Path, prefix: char, suffix: &str) -> Vec<usize> {
63    let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
64    let name = |e: fs::DirEntry| e.file_name().to_str()?.strip_prefix(prefix)?.strip_suffix(suffix)?.parse().ok();
65    let mut v: Vec<usize> = rd.flatten().filter_map(name).collect();
66    v.sort_unstable();
67    v
68}
69
70/// Atomic write: tmp + rename.
71pub fn jsave<T: Serialize>(p: &Path, v: &T) -> Result<(), String> {
72    let dir = p.parent().ok_or("no parent dir")?;
73    fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
74    // pid + a per-process counter: two threads (MCP) never share a temp file
75    static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
76    let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
77    let tmp = p.with_extension(format!("{}.{n}.tmp", std::process::id()));
78    let body = serde_json::to_vec_pretty(v).map_err(|e| e.to_string())?;
79    fs::write(&tmp, body).and_then(|_| fs::rename(&tmp, p)).map_err(|e| format!("{}: {e}", p.display()))
80}
81
82/// Read-modify-write a shared root file under an exclusive lock.
83pub fn edit<T: DeserializeOwned + Serialize + Default, R>(p: &Path, f: impl FnOnce(&mut T) -> R) -> Result<R, String> {
84    edit_when(p, File::lock, f)
85}
86
87/// `edit` once `lock` takes the lock: `File::lock` waits for it, a `try_lock` gives up while another holds it.
88fn edit_when<T: DeserializeOwned + Serialize + Default, R>(
89    p: &Path,
90    lock: impl Fn(&File) -> std::io::Result<()>,
91    f: impl FnOnce(&mut T) -> R,
92) -> Result<R, String> {
93    fs::create_dir_all(p.parent().ok_or("no parent dir")?).map_err(|e| format!("{}: {e}", p.display()))?;
94    let file = File::create(p.with_extension("lock")).map_err(|e| e.to_string())?;
95    lock(&file).map_err(|e| e.to_string())?;
96    let mut v: T = jload(p).unwrap_or_default();
97    let r = f(&mut v);
98    jsave(p, &v)?;
99    Ok(r)
100}
101
102#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
103#[serde(default)]
104pub struct Cursor {
105    pub u: usize,
106    pub k: Option<usize>,
107    pub part: usize,
108    pub full: bool,
109    /// `more` continues the result list of this search: (job, next hit, 0-based).
110    pub serp: Option<(usize, usize)>,
111}
112
113#[derive(Serialize, Deserialize, Clone, Default)]
114#[serde(default)]
115pub struct Entry {
116    pub url: String,
117    pub dir: String,
118    pub alias: bool,
119    pub job: Option<usize>,
120    /// A web search result; an empty `dir` = not fetched yet.
121    pub serp: bool,
122    /// The parts of it read in this session (`#5`, `#5b`) and their text's keys (`=1f…`, read under any copy of the
123    /// URL): a next move never points back at one.
124    pub read: Vec<String>,
125}
126
127impl Entry {
128    /// Page `u`'s `=` line id read in its own session: `j3.u2` (the job that fetched it), else `u2`.
129    pub fn eq(&self, u: usize) -> String {
130        self.job.map_or_else(|| format!("u{u}"), |j| format!("j{j}.u{u}"))
131    }
132}
133
134/// Put `e` in slot `n` when it is a reserved id (`State::result`; keeping its job and `serp`), else append it:
135/// its 1-based u number.
136fn place(st: &mut State, mut e: Entry, slot: Option<usize>) -> usize {
137    match slot.filter(|&n| st.result(n).is_some()).and_then(|n| Some((n, st.u.get_mut(n - 1)?))) {
138        Some((n, old)) => {
139            (e.job, e.serp) = (old.job, old.serp);
140            *old = e;
141            n
142        }
143        None => {
144            st.u.push(e);
145            st.u.len()
146        }
147    }
148}
149
150#[derive(Serialize, Deserialize, Default, Clone)]
151pub struct State {
152    pub u: Vec<Entry>,
153    pub cursor: Option<Cursor>,
154    /// When this session began (unix s, its first state write, `with_state`, or search record, `serp_put`): `stats`
155    /// counts the ledger rows since; none (never written) counts none.
156    pub t: Option<f64>,
157}
158
159impl State {
160    /// THE slot check: the entry of `u<n>` when a fetch may fill it: a search result, fetched or not, or an id
161    /// reserved for a detached fetch (an empty `dir` = not yet). Its first fetch fills it, `fresh:true` refills a
162    /// search result.
163    pub fn result(&self, n: usize) -> Option<&Entry> {
164        self.u.get(n.checked_sub(1)?).filter(|e| e.serp || e.dir.is_empty())
165    }
166}
167
168/// A fetch that outlives its call (past `wait:`), `run/u<N>.json`: written by the call that reserved `u<N>`, then
169/// by the process that runs it (`fats --continue j<J>.u<N>`): its pid once it holds `u<N>.lock`, `status` as tiers
170/// start and land, `done` at the end. The lock is held for that process's life: no `done` + a free lock = it died.
171/// Any other writer writes under that lock, read again there (`run_tell`).
172#[derive(Serialize, Deserialize, Default, Clone)]
173#[serde(default)] // a run file an older binary wrote reads too
174pub struct Detached {
175    pub url: String,
176    /// The command line it came from (its mods: `country:`, `js:`, `cost:` …).
177    pub cmd: String,
178    /// The `← u3 l4` label of the page it fills.
179    pub prov: Option<String>,
180    pub job: usize,
181    /// Its batch's `cost:` pool (`fetch::pooled`); None = a run alone.
182    pub pool: Option<PathBuf>,
183    /// Queued behind run `by` of its lane: that run's process takes it after its own (`cli::launch`); 0 = none.
184    pub by: usize,
185    pub t: f64,
186    pub pid: u32,
187    /// The tiers so far: `plain:blocked_403✗ · oxy running`.
188    pub status: String,
189    /// When the newest running call started and when the last one is cut (epoch s; 0 = none yet): `cli::ready`.
190    pub since: f64,
191    pub until: f64,
192    pub done: Option<Done>,
193    /// Its end was shown (`cli::footer`).
194    pub told: bool,
195}
196
197impl Detached {
198    /// THE dead-run rule (`stats`, `sweep`): no lock held (`alive`, `Cache::run`), never ended, and its id holds
199    /// no page (a store that died before its `done` already wrote its ledger row).
200    pub fn dead(&self, alive: bool, id: Option<&Entry>) -> bool {
201        !alive && self.done.is_none() && id.is_some_and(|e| e.dir.is_empty())
202    }
203
204    /// A dead run as its id's failed copy: code `abandoned`, its calls in flight (`bd running` in its status) each a
205    /// call we cut (`bd:abandoned✗≤$0.0015 (unverified)`: no status came back). Its read and `stats` row before the
206    /// sweep, stored in the id by it.
207    pub fn cut(&self) -> Meta {
208        let hop = |t: &crate::provider::Spec| HopRow { provider: t.name.into(), upto: t.price, ..HopRow::default() };
209        let tier = |s: &str| crate::provider::Tier::parse(s.strip_suffix(" running")?).map(|t| hop(t.spec()));
210        let hops = self.status.split(" · ").filter_map(tier).map(|h| HopRow { code: "abandoned".into(), ..h });
211        let hops: Vec<_> = hops.collect();
212        let provider = hops.last().map(|h| h.provider.clone()).unwrap_or_default();
213        Meta { url: self.url.clone(), code: "abandoned".into(), t: self.t, provider, hops, ..Meta::default() }
214    }
215}
216
217/// How a detached fetch ended: what the call that waits for it adds to the stored page's outline.
218#[derive(Serialize, Deserialize, Default, Clone)]
219pub struct Done {
220    pub ok: bool,
221    pub code: String,
222    pub cost: f64,
223    /// Its `!` rows (tiers skipped, mods ignored, a route not kept).
224    pub warn: Vec<String>,
225    /// The page could not be stored: the cache write error.
226    pub fail: Option<String>,
227}
228
229#[derive(Serialize, Deserialize, Default, Clone)]
230#[serde(default)]
231pub struct Meta {
232    pub url: String,
233    pub final_url: Option<String>,
234    /// Where a bd ask landed by the page's same-site canonical link (`fetch::canonical`): `outline::lost_page`
235    /// judges it; the links' base stays `final_url`.
236    pub landed: Option<String>,
237    /// The page whose meta refresh plain followed (`provider::refresh`): the outline's `uN#0 info | refreshed
238    /// from: <url>` row, never judged; `lost_page` judges the target (`final_url`) as any landing.
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub refreshed_from: Option<String>,
241    pub provider: String,
242    pub ms: u64,
243    pub cost: f64,
244    pub ok: bool,
245    pub code: String,
246    pub t: f64,
247    pub bytes: u64,
248    pub kind: String,
249    pub hops: Vec<HopRow>,
250    /// The body is a browser render (its `<noscript>` was never shown, so the cleaner drops it). Set by
251    /// whoever stored the body.
252    pub render: Option<bool>,
253    /// The exit country the serving provider was asked for (`FR`); empty = none.
254    pub country: String,
255    /// The encoding the body was decoded from before it was stored as UTF-8 (`windows-1250`); empty = UTF-8.
256    pub charset: String,
257    /// `off` = a paid ask, one provider at a time (`fetch::Plan::hedged`), said on every read; empty = hedged.
258    pub hedge: String,
259    /// Keys this build does not know survive a rewrite.
260    #[serde(flatten)]
261    pub extra: Map<String, Value>,
262}
263
264/// One provider call in a fetch's or search's `hops`, as meta.json keeps it: `fetch::Hop::row` writes it, every
265/// view reads its fields. `provider` is the stored name (`brightdata`, `oxylabs-js`); only the fields a view
266/// surfaces are kept: provider, code, cost, ms, why (`tried`/`health`/`fail_detail`), and the request budget
267/// `limit`/`remaining` (`limits`, kept as the two numbers Oxylabs sends).
268#[derive(Serialize, Deserialize, Default, Clone)]
269#[serde(default)]
270pub struct HopRow {
271    pub provider: String,
272    pub code: String,
273    pub cost: f64,
274    pub ms: u64,
275    pub why: String,
276    /// A call WE cut (our timeout, `wait:`, abandoned): its list price, unverified (`fetch::billed`); not in `cost`.
277    pub upto: f64,
278    /// The request shape: the exit country sent (empty = none) and the call's timeout; the tier says `run_js`.
279    pub country: String,
280    pub timeout_s: u64,
281    pub limit: Option<u32>,
282    pub remaining: Option<u32>,
283    /// Ms plain waited for its turn (the home-IP brake), apart from `ms`; none = no wait.
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub waited_ms: Option<u64>,
286}
287
288impl Meta {
289    /// The tier path (`plain:js_shell✗ oxy✓ bd:abandoned✗$0.0015`, a code only on failures, the bill of a
290    /// cancelled call, why a served call was asked again: `plain✓md:thin`, `fetch::md_weak`), the one format every
291    /// view prints.
292    /// `·fr` beside the serving tier when its exit country is not the default one (`oxyjs·fr`), else empty.
293    pub fn geo(&self) -> String {
294        let c = self.country.to_uppercase();
295        if c.is_empty() || c == crate::provider::home() { String::new() } else { format!("·{}", c.to_lowercase()) }
296    }
297
298    pub fn tried(&self) -> String {
299        self.path(false)
300    }
301
302    /// `tried` with each paid call's request shape (`stats`): `oxyjs@US/60s✓`, `bd/60s` = no country sent.
303    pub fn path(&self, shape: bool) -> String {
304        // the failures a paid provider does not bill, said so (a refused key is no call: no `$`); a paid tier's
305        // site block with no cost is one bd relayed (`provider::bd_refused`), a billed one shows its `$` above
306        let unbilled = |c: &str| crate::provider::REFUSED.contains(&c) || matches!(c, "provider_timeout" | "abandoned");
307        let geo = if shape { String::new() } else { self.geo() };
308        let hop = |h: &HopRow| {
309            let (p, s) = (crate::provider::short(&h.provider), h.timeout_s);
310            let cc = if h.country.is_empty() { String::new() } else { format!("@{}", h.country) };
311            let p = if shape && s > 0 && p != "plain" { format!("{p}{cc}/{s}s") } else { p.to_string() };
312            match h.code.as_str() {
313                // the exit country beside the tier only when it is not the default one (`oxyjs·fr✓`)
314                "ok" => format!("{p}{geo}✓{}", h.why),
315                // a site's 5xx Oxylabs relayed: billed by assumption (`provider::charged`, none reconciled)
316                c if h.cost > 0.0 && c.starts_with("http_5") => format!("{p}:{c}✗${:.4} (assumed)", h.cost),
317                // every billed hop shows its bill; a paid tier's unbilled failure says it cost nothing
318                _ if h.cost > 0.0 => format!("{p}:{}✗${:.4}", h.code, h.cost),
319                // a call we cut: the provider may finish and bill it (bd billed 15 s search cuts)
320                _ if h.upto > 0.0 => format!("{p}:{}✗≤${:.4} (unverified)", h.code, h.upto),
321                // `stats` adds the provider's own reason (`provider::reason`, ≤ 50 chars, no body text)
322                c if p != "plain" && (unbilled(c) || c.starts_with("http_5") || c.starts_with("blocked_")) => {
323                    let why = if shape && c == "provider_error" && !h.why.is_empty() {
324                        format!(", {}", h.why)
325                    } else {
326                        String::new()
327                    };
328                    format!("{p}:{c}✗$0 (not charged{why})")
329                }
330                _ => format!("{p}:{}✗", h.code),
331            }
332        };
333        let hops: Vec<String> = self.hops.iter().map(hop).collect();
334        if hops.is_empty() { "-".into() } else { hops.join(" ") }
335    }
336
337    /// What the calls we cut may have cost on top of `cost` (`HopRow::upto`).
338    pub fn upto(&self) -> f64 {
339        crate::provider::spend(self.hops.iter().map(|h| h.upto))
340    }
341
342    /// How the run went besides its tiers, the one format `=` and `stats` print: ` · hedge:off` when a paid ask
343    /// ran one provider at a time (`fetch::Plan::hedged`), ` · waited 7.6s` when plain waited for its turn.
344    pub fn how(&self) -> String {
345        let waited = self.hops.iter().filter_map(|h| h.waited_ms).sum::<u64>() as f64 / 1e3;
346        let waited = if waited > 0.0 { format!(" · waited {waited:.1}s") } else { String::new() };
347        if self.hedge == "off" { " · hedge:off" } else { "" }.to_string() + &waited
348    }
349}
350
351/// Why a snapshot has no doc.
352pub enum NoDoc {
353    /// A zip body (docx, xlsx) this build cannot read, and where it is cached.
354    Zip(PathBuf),
355    /// No body stored: the fetch failed, or the snapshot is incomplete.
356    Missing,
357    /// The converter crashed on this body.
358    Parse(String),
359}
360
361#[derive(Serialize, Deserialize, Default)]
362pub struct Job {
363    pub session: String,
364    pub cmd: String,
365    pub t: f64,
366}
367
368/// Picture K of a page, fetched on demand (`cli::asset`): `<page>/assets/m<K>.<ext>` (`ext` from its content
369/// type), then this record as `m<K>.json` (written last: no record = not stored). `w`, `h` = the size read from
370/// the bytes (0 = unread).
371#[derive(Serialize, Deserialize, Default)]
372pub struct Asset {
373    pub src: String,
374    pub ext: String,
375    pub bytes: u64,
376    pub ms: u64,
377    pub t: f64,
378    pub w: u32,
379    pub h: u32,
380}
381
382/// The pictures stored under page dir `dir` (`Asset`).
383pub fn assets(dir: &Path) -> Vec<Asset> {
384    let d = dir.join("assets");
385    numbered(&d, 'm', ".json").into_iter().filter_map(|k| jload(&d.join(format!("m{k}.json")))).collect()
386}
387
388/// What `Cache::ingest` stores.
389pub struct Snap<'a> {
390    /// (`raw.html|raw.pdf|raw.zip|…`, body); None = a failed fetch with no body: meta.json alone.
391    pub file: Option<(&'a str, &'a [u8])>,
392    /// The providers' error answers (`ERROR_FILE`).
393    pub error: Option<&'a [u8]>,
394    pub doc: Option<&'a Doc>,
395    pub meta: Meta,
396    /// The key later reads find it by (the URL; a local file's content hash); None = not reused.
397    pub index: Option<&'a str>,
398    /// The unfetched search result this fills.
399    pub slot: Option<usize>,
400}
401
402/// `st` is a snapshot; every change goes through `alloc` / `save`, which re-read state.json under the session
403/// lock, so parallel agents in one session never overwrite each other's ids.
404pub struct Cache {
405    pub root: PathBuf,
406    pub session: String,
407    pub st: State,
408    cursor0: Option<Cursor>,
409    /// This invocation's job, created by the first page it stores: every page of one command shares it.
410    pub job: Option<usize>,
411    /// When this command opened the cache (`cli::run`, one MCP call): its `wait:` deadline (`cli::wait_for`).
412    pub born: Instant,
413    /// Every snapshot's meta.json this command read (`meta`): read once, however many answers ask.
414    metas: std::cell::RefCell<std::collections::HashMap<String, Option<Meta>>>,
415}
416
417/// A path read from a cache file stays inside the cache: relative, no `..`, no root (`"dir": "/etc"` is refused).
418/// Rebuilt from its parts: the stored `t/u1` joins with the OS separator (`…\cache\t\u1` on Windows). The
419/// rebuilt path is judged, not the stored one: on Windows a part with a drive (`t/C:x`) replaces what came before.
420fn inside(rel: &str) -> Option<PathBuf> {
421    let p: PathBuf = Path::new(rel).components().collect();
422    (!rel.is_empty() && p.components().all(|c| matches!(c, std::path::Component::Normal(_)))).then_some(p)
423}
424
425/// fats made this root (`private_root` writes it): the sweep deletes only under a root holding it.
426pub const MINE: &str = ".fatsearch-cache";
427
428/// The cache root is its owner's only (0700 on unix): jobs.json keeps every command (queries too), account.json
429/// balances. A missing root is created so, with `MINE` in it, and so is the default root (fats's own name in the
430/// OS cache dir, made by builds before the sweep); one `FATS_CACHE` names is left as it is (`fats` shows its mode,
431/// `config` whether it is swept). An error here is reported by the first write (`cache_write`).
432pub fn private_root(root: &Path, default: bool) -> bool {
433    let mut b = fs::DirBuilder::new();
434    #[cfg(unix)]
435    std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
436    if !root.exists() && b.recursive(true).create(root).is_ok() || default && !root.join(MINE).exists() {
437        fs::write(root.join(MINE), b"").ok();
438    }
439    root.is_dir()
440}
441
442/// What the sweep may delete in a session: a page `u<N>` (`u<N>-<k>`) or a search `j<N>` holding its meta.json,
443/// or `run/` (detached runs); nothing else, ever.
444fn ours(d: &Path) -> bool {
445    let n = d.file_name().and_then(|n| n.to_str()).unwrap_or_default();
446    n == "run" || matches!(n.as_bytes(), [b'u' | b'j', b'0'..=b'9', ..]) && d.join("meta.json").is_file()
447}
448
449/// Seconds since `p` was modified (a clock set back reads 0); a missing file is endlessly old.
450fn age(p: &Path) -> u64 {
451    fs::metadata(p).and_then(|m| m.modified()).map_or(u64::MAX, |t| t.elapsed().map_or(0, |d| d.as_secs()))
452}
453
454/// THE lifetime rule: a stored dir (a page `u<N>`, a search `j<N>`, `run/`) is gone once unread for `cache_idle_s`
455/// (the dir's mtime: `Cache::page` touches it) or `cache_ttl_s` after its fetch (its meta.json's mtime).
456fn expired(dir: &Path) -> bool {
457    let meta = dir.join("meta.json");
458    age(dir) >= limit("cache_idle_s") || meta.exists() && age(&meta) >= limit("cache_ttl_s")
459}
460
461fn dirs_in(p: &Path) -> Vec<PathBuf> {
462    let real = |e: &fs::DirEntry| e.file_type().is_ok_and(|t| t.is_dir()); // a symlink is never followed out
463    fs::read_dir(p).map_or_else(|_| Vec::new(), |rd| rd.flatten().filter(real).map(|e| e.path()).collect())
464}
465
466/// THE sweep, run after the answer is out (`main`, `mcp`): `expired` dirs of this session every run, of every
467/// session at most once per `sweep_every_s` (the `swept` file's mtime), only under a root fats made (`MINE`), only
468/// `ours` dirs of a session dir (a real dir holding a state.json; a symlink is never followed). A session dir and
469/// its state.json stay (ids never restart, so `u1` never names another page); the full sweep also forgets what
470/// the hour is over for: an index row with its page, a job's command once `cache_ttl_s` old, and a
471/// history row's URL (a search's results too) once its page is gone and its job forgotten: its id reads `! expired`.
472pub fn sweep() {
473    let s = crate::settings::get();
474    let (root, marker, mine) = (&s.cache.value, s.cache.value.join("swept"), s.cache.value.join(MINE).is_file());
475    let all = mine && age(&marker) >= limit("sweep_every_s") && fs::write(&marker, b"").is_ok();
476    let gone = |d: &str| inside(d).is_none_or(|d| expired(&root.join(d)));
477    let jobs = all.then(|| {
478        let idx = |i: &mut Map<String, Value>| i.retain(|_, r| !gone(r["dir"].as_str().unwrap_or_default()));
479        edit(&root.join("index.json"), idx).ok();
480        edit(&root.join("jobs.json"), |js: &mut Vec<Job>| {
481            js.iter_mut().filter(|j| now() - j.t >= limit::<f64>("cache_ttl_s")).for_each(|j| j.cmd.clear());
482            js.iter().map(|j| j.cmd.is_empty()).collect::<Vec<_>>()
483        })
484    });
485    // a fetched page keeps its (gone) dir name, never its URL; a result never fetched gets `-` (`{:-<1}` pads an
486    // empty name with one `-`): `stats` gives it no row
487    let forget = |e: &mut Entry| *e = Entry { dir: format!("{:-<1}", e.dir), job: e.job, ..Entry::default() };
488    let sessions = dirs_in(root).into_iter().filter(|d| all || d.ends_with(&s.session.value));
489    for session in sessions.filter(|d| mine && d.join("state.json").is_file()) {
490        let c = Cache::at(root.clone(), session.file_name().unwrap_or_default().to_string_lossy().into());
491        for d in dirs_in(&session).iter().filter(|d| ours(d) && expired(d)) {
492            let runs = if d.ends_with("run") { c.runs() } else { Vec::new() };
493            // a dead run's calls in flight (`Detached::cut`) are money no store wrote down: the one sweep whose rename
494            // claims its run file stores them as the id's failed copy (`! abandoned`, its ledger row); a live run
495            // keeps `run/`
496            let claim = |n: usize| fs::rename(c.run_file(n, "json"), c.run_file(n, "swept")).is_ok();
497            for (n, r, _) in runs.iter().filter(|r| r.1.dead(r.2, c.st.u.get(r.0.wrapping_sub(1))) && claim(r.0)) {
498                let snap = Snap { file: None, error: None, doc: None, meta: r.cut(), index: None, slot: Some(*n) };
499                Cache::at(root.clone(), c.session.clone()).ingest(snap, r.job, Instant::now()).ok();
500            }
501            runs.iter().all(|r| !r.2).then(|| fs::remove_dir_all(d).unwrap_or(()));
502        }
503        if let Some(Ok(js)) = &jobs {
504            let old = |e: &&mut Entry| e.job.and_then(|j| js.get(j.checked_sub(1)?)) != Some(&false) && gone(&e.dir);
505            edit(&session.join("state.json"), |st: &mut State| st.u.iter_mut().filter(old).for_each(forget)).ok();
506        }
507    }
508}
509
510pub fn url_key(url: &str) -> &str {
511    let u = crate::html::py_strip(url);
512    u.split('#').next().unwrap_or(u)
513}
514
515/// The detached run in file `json` (`Cache::run_file`) and whether it lives, THE liveness rule (a pending id,
516/// status, a batch pool's floor): its lock is held. The launcher takes it before the run file exists and hands it
517/// to the run's process (`Cache::run_claim`), so a run not scheduled yet lives too (a 2 s pid-0 window read
518/// `! abandoned` under load). The lock is probed BEFORE the file is read: a process that wrote `done` and let go
519/// reads as ended with it. A queued run lives while its lane's process does (the lock of the run it is queued
520/// behind, `by`).
521pub fn run_at(json: &Path) -> Option<(Detached, bool)> {
522    let held = |at: PathBuf| matches!(File::open(at).map(|f| f.try_lock()), Ok(Err(fs::TryLockError::WouldBlock)));
523    let own = held(json.with_extension("lock"));
524    let r: Detached = jload(json)?;
525    let alive = own || (r.by > 0 && r.done.is_none() && held(json.with_file_name(format!("u{}.lock", r.by))));
526    Some((r, alive))
527}
528
529impl Cache {
530    pub fn open() -> Cache {
531        let s = crate::settings::get();
532        private_root(&s.cache.value, s.cache.src == "default");
533        Cache::at(s.cache.value.clone(), s.session.value.clone())
534    }
535
536    pub fn at(root: PathBuf, session: String) -> Cache {
537        let st: State = jload(&root.join(&session).join("state.json")).unwrap_or_default();
538        Cache { root, session, cursor0: st.cursor.clone(), st, job: None, born: Instant::now(), metas: <_>::default() }
539    }
540
541    /// The meta.json of the snapshot in `dir` (an entry's, a `lookup`'s), read once a command: a snapshot's never
542    /// changes once stored.
543    pub fn meta(&self, dir: &str) -> Option<Meta> {
544        let load = || jload(&self.under(dir)?.join("meta.json"));
545        self.metas.borrow_mut().entry(dir.into()).or_insert_with(load).clone()
546    }
547
548    /// Change the freshest state.json under the session lock; `st` becomes that state.
549    /// A cursor this command moved is kept (a search's list, then its prefetch's `alloc`), else the file's.
550    fn with_state<R>(&mut self, f: impl FnOnce(&mut State) -> R) -> Result<R, String> {
551        let moved = (self.st.cursor != self.cursor0).then(|| self.st.cursor.clone());
552        let (r, st) = edit(&self.root.join(&self.session).join("state.json"), |st: &mut State| {
553            st.cursor = moved.unwrap_or_else(|| st.cursor.take());
554            st.t = st.t.or(Some(now())); // the session's start: its first write, before anything it spends is stored
555            let r = f(st);
556            (r, st.clone())
557        })?;
558        self.st = st;
559        Ok(r)
560    }
561
562    /// Re-read state.json: a detached fetch filled an id.
563    pub fn reload(&mut self) {
564        self.st = jload(&self.root.join(&self.session).join("state.json")).unwrap_or_default();
565    }
566
567    pub fn run_file(&self, n: usize, ext: &str) -> PathBuf {
568        self.root.join(&self.session).join("run").join(format!("u{n}.{ext}"))
569    }
570
571    /// Detached run `n` and whether it lives (`run_at`).
572    pub fn run(&self, n: usize) -> Option<(Detached, bool)> {
573        run_at(&self.run_file(n, "json"))
574    }
575
576    pub fn run_put(&self, n: usize, r: &Detached) -> Result<(), String> {
577        jsave(&self.run_file(n, "json"), r)
578    }
579
580    /// Run `n`'s end was shown (`cli::footer`): written under its lock, read again there; a busy lock = it runs
581    /// (or a reader probes): told next time.
582    pub fn run_tell(&self, n: usize) {
583        let Some(_lock) = File::create(self.run_file(n, "lock")).ok().filter(|f| f.try_lock().is_ok()) else { return };
584        if let Some(r) = jload::<Detached>(&self.run_file(n, "json")) {
585            self.run_put(n, &Detached { told: true, ..r }).ok(); // a footer line, shown again at worst
586        }
587    }
588
589    /// This session's runs: (n, run, alive).
590    pub fn runs(&self) -> Vec<(usize, Detached, bool)> {
591        let found = numbered(&self.root.join(&self.session).join("run"), 'u', ".json");
592        found.into_iter().filter_map(|n| self.run(n).map(|(r, a)| (n, r, a))).collect()
593    }
594
595    /// Run `n`'s lock, taken by its launcher (`cli::launch`) and handed to the run (`cli::detach`: the process's stdin,
596    /// so held until it ends; on Windows the launcher keeps it and the run takes it again; a reader's probe only delays
597    /// it). Its log (`run_file(n, "log")`) takes the process's stdout + stderr.
598    pub fn run_claim(&self, n: usize) -> Option<File> {
599        let p = self.run_file(n, "lock");
600        fs::create_dir_all(p.parent()?).ok()?;
601        let f = File::create(p).ok()?;
602        f.lock().ok()?;
603        Some(f)
604    }
605
606    /// Persist the cursor if this command moved it (read-only commands write nothing).
607    pub fn save(&mut self) -> Result<(), String> {
608        if self.st.cursor == self.cursor0 { Ok(()) } else { self.with_state(|_| ()) }
609    }
610
611    /// Log a part of `u<n>` as read (`Entry::read`): its id tail (`#2ft`) and its text's key (`outline::part_key`).
612    pub fn read_mark(&mut self, n: usize, read: &[String]) -> Result<(), String> {
613        let new = |e: &Entry| read.iter().filter(|t| !e.read.contains(t)).cloned().collect::<Vec<_>>();
614        self.with_state(|st| st.u.get_mut(n - 1).map(|e| e.read.extend(new(e)))).map(|_| ())
615    }
616
617    /// Append entries (or fill `slot`, see `place`): the first one's 1-based u number, unique even with parallel
618    /// writers.
619    pub fn alloc(&mut self, es: Vec<Entry>, slot: Option<usize>) -> Result<usize, String> {
620        self.with_state(|st| {
621            let n = st.u.len() + 1;
622            es.into_iter().map(|e| place(st, e, slot)).min().unwrap_or(n)
623        })
624    }
625
626    /// Store search `job`'s record (hits inside) and its providers' error answers; health and stats read it
627    /// like a fetch's.
628    pub fn serp_put(&self, job: usize, meta: &Meta, error: Option<&[u8]>) -> Result<(), String> {
629        let dir = self.root.join(&self.session).join(format!("j{job}"));
630        jsave(&dir.join("meta.json"), meta)?; // a failed search stores no ids: it starts the session (`State::t`)
631        edit(&self.root.join(&self.session).join("state.json"), |st: &mut State| st.t = st.t.or(Some(now())))?;
632        spend_log([meta.cost, meta.upto()], &dir);
633        tally(&self.root, meta, None);
634        error.map_or(Ok(()), |e| keep_error(&dir, e))
635    }
636
637    /// Search `job`'s record in this session.
638    pub fn serp(&self, job: usize) -> Option<Meta> {
639        jload(&self.dir(&Entry { dir: format!("{}/j{job}", self.session), ..Entry::default() })?.join("meta.json"))
640    }
641
642    /// This session's searches, oldest first: (job, record).
643    pub fn serps(&self) -> Vec<(usize, Meta)> {
644        numbered(&self.root.join(&self.session), 'j', "").into_iter().filter_map(|j| Some((j, self.serp(j)?))).collect()
645    }
646
647    /// A cache-relative dir from a cache file, still inside the root once symlinks are resolved (a link in the
648    /// cache to a dir outside it is refused); None when it leaves the root or does not exist.
649    fn under(&self, rel: &str) -> Option<PathBuf> {
650        let p = self.root.join(inside(rel)?);
651        p.canonicalize().ok()?.starts_with(self.root.canonicalize().ok()?).then_some(p)
652    }
653
654    /// Indexed snapshot of a URL (or a local file's content key, `blake3:`): (dir, age in s), while it lives
655    /// (`expired`) and is the page asked for: its meta.json names that URL, never another page in a reused dir.
656    pub fn lookup(&self, url: &str) -> Option<(String, f64)> {
657        let on = !crate::settings::get().nocache.value;
658        let idx: Map<String, Value> = on.then(|| jload(&self.root.join("index.json"))).flatten()?;
659        let row = idx.get(url_key(url))?; // `{dir, t}`, written by `ingest`
660        let (dir, t) = (row["dir"].as_str()?.to_string(), row["t"].as_f64()?);
661        let m: Meta = jload(&self.dir(&Entry { dir: dir.clone(), ..Entry::default() })?.join("meta.json"))?;
662        (url_key(&m.url) == url_key(url) || url.starts_with("blake3:")).then(|| (dir, now() - t))
663    }
664
665    /// New global job id for a fetch-type command.
666    /// The invocation's job number (`j8`), registered on first use.
667    pub fn job_of(&mut self, cmd: &str) -> Result<usize, String> {
668        if let Some(j) = self.job {
669            return Ok(j);
670        }
671        let (session, cmd) = (self.session.clone(), cmd.to_string());
672        let j = edit(&self.root.join("jobs.json"), |jobs: &mut Vec<Job>| {
673            jobs.push(Job { session, cmd, t: now() });
674            jobs.len()
675        })?;
676        self.job = Some(j);
677        Ok(j)
678    }
679
680    /// Job `j` (1-based); None when unknown or its session name would leave the cache root.
681    pub fn job(&self, j: usize) -> Option<Job> {
682        let jobs: Vec<Job> = jload(&self.root.join("jobs.json"))?;
683        jobs.into_iter().nth(j.checked_sub(1)?).filter(|x| inside(&x.session).is_some())
684    }
685
686    pub fn job_count(&self) -> usize {
687        jload::<Vec<Job>>(&self.root.join("jobs.json")).map_or(0, |j| j.len())
688    }
689
690    /// THE read of a stored dir (`page`, `lookup`, `serp`, `cli::seen`, `stats`): an entry's snapshot dir, under the
691    /// root (None when state.json, or a symlink in the cache, points outside it) and not `expired`.
692    pub fn dir(&self, e: &Entry) -> Option<PathBuf> {
693        self.under(&e.dir).filter(|d| !expired(d))
694    }
695
696    /// meta + doc of an entry; doc.json is rebuilt from the body (`raw_name` of its kind) when missing or of another
697    /// schema version.
698    pub fn page(&self, e: &Entry) -> (Meta, Result<Doc, NoDoc>) {
699        let Some(d) = self.dir(e) else {
700            return (Meta { url: e.url.clone(), ok: true, ..Meta::default() }, Err(NoDoc::Missing));
701        };
702        // a read keeps it (`expired`); by path: Windows sets a folder's time only through a handle `File::open` lacks
703        fs::set_times(&d, fs::FileTimes::new().set_modified(SystemTime::now())).ok();
704        let meta: Meta = jload(&d.join("meta.json")).unwrap_or_default();
705        let current = |x: &Doc| x.v == DOC_V && x.chunk == crate::settings::get().chunk.value;
706        if let Some(doc) = jload::<Doc>(&d.join("doc.json")).filter(current) {
707            return (meta, Ok(doc));
708        }
709        let f = raw_name(&meta.kind);
710        let Ok(raw) = fs::read(d.join(&f)) else { return (meta, Err(NoDoc::Missing)) };
711        if crate::clean::sniff(&raw) == Some("zip") {
712            return (meta, Err(NoDoc::Zip(d.join(f))));
713        }
714        let url = if meta.url.is_empty() { e.url.clone() } else { meta.url.clone() };
715        let fin = meta.final_url.clone().unwrap_or_else(|| url.clone());
716        let kind = crate::clean::sniff(&raw).unwrap_or(&meta.kind);
717        // a read-only cache still serves the page
718        let doc = build(&raw, &url, &fin, meta.render == Some(true), kind).map_err(NoDoc::Parse);
719        (meta, doc.inspect(|x| drop(jsave(&d.join("doc.json"), x))))
720    }
721
722    /// Store a fetched/local body as the next u of this session (or in `Snap::slot`). The snapshot is written to a
723    /// private temp dir first and renamed to `u<N>` under the session lock; an existing dir is never touched
724    /// (`u<N>-2` instead). `t0` = when the command started: a hop without `ms` gets the elapsed time. Storage
725    /// only: the caller builds the doc first, so every error from here is a cache write error.
726    pub fn ingest(&mut self, snap: Snap, job: usize, t0: Instant) -> Result<usize, String> {
727        let Snap { file, error, doc, mut meta, index, slot } = snap;
728        let sdir = self.root.join(&self.session);
729        fs::create_dir_all(&sdir).map_err(|e| format!("{}: {e}", sdir.display()))?;
730        if self.under(&self.session).is_none() {
731            return Err(format!("{}: links out of the cache", sdir.display()));
732        }
733        // one per ingest: detached runs of one job may share a process (threads under the test transport)
734        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
735        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
736        let tmp = sdir.join(format!(".tmp-{}-{job}-{seq}", std::process::id()));
737        fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
738        let staged = (|| {
739            file.map_or(Ok(()), |(name, raw)| fs::write(tmp.join(name), raw).map_err(|e| e.to_string()))?;
740            error.map_or(Ok(()), |e| keep_error(&tmp, e))?;
741            doc.map_or(Ok(()), |doc| jsave(&tmp.join("doc.json"), doc))?;
742            // a time no one measured (a hop's, the fetch's) = the time since the command started
743            let ms = t0.elapsed().as_millis() as u64;
744            let times = meta.hops.iter_mut().map(|h| &mut h.ms).chain([&mut meta.ms]);
745            times.filter(|m| **m == 0).for_each(|m| *m = ms);
746            jsave(&tmp.join("meta.json"), &meta)
747        })();
748        staged.inspect_err(|_| drop(fs::remove_dir_all(&tmp)))?; // our own temp dir, never a snapshot
749        let (session, url, root) = (self.session.clone(), meta.url.clone(), self.root.clone());
750        let placed = self.with_state(|st| -> Result<(usize, String), String> {
751            let free = slot.filter(|&n| st.result(n).is_some());
752            let n = free.unwrap_or(st.u.len() + 1);
753            let name = |k| if k == 1 { format!("{session}/u{n}") } else { format!("{session}/u{n}-{k}") };
754            let rel = (1..).map(name).find(|r| !root.join(r).exists()).unwrap_or_default();
755            fs::rename(&tmp, root.join(&rel)).map_err(|e| e.to_string())?;
756            place(st, Entry { url, dir: rel.clone(), job: Some(job), ..Entry::default() }, free);
757            Ok((n, rel))
758        })?;
759        let (n, rel) = placed.inspect_err(|_| drop(fs::remove_dir_all(&tmp)))?;
760        spend_log([meta.cost, meta.upto()], &self.root.join(&rel));
761        tally(&self.root, &meta, doc.map(|d| d.tokens.clean));
762        if let Some(key) = index {
763            edit(&self.root.join("index.json"), |idx: &mut Map<String, Value>| {
764                idx.insert(url_key(key).into(), serde_json::json!({"dir": rel, "t": now()}));
765            })?;
766        }
767        Ok(n)
768    }
769}
770
771/// Body → Doc by its kind (`clean::kind_of`, kept in meta.json): a PDF, a server's Markdown, a text document, else
772/// a page; `og` = a JS shell served as its own og card (`fetch::og_card`), made again from the same body.
773pub fn build(raw: &[u8], url: &str, fin: &str, js: bool, kind: &str) -> Result<Doc, String> {
774    guarded(|| match kind {
775        "pdf" => crate::pdf::build_pdf(raw, url, fin, limit("pdf_budget_s")),
776        "md" => Ok(crate::clean::markdown(raw, url, fin)),
777        k if crate::clean::LISTS.text.contains(&k) => Ok(crate::text::build(raw, k, url, fin)),
778        k => Ok(build_doc(&crate::html::parse(&String::from_utf8_lossy(raw)), url, fin, js))
779            .map(|d| if k == "og" { crate::clean::card(d) } else { d }),
780    })
781}
782
783/// The stored body's file name for a kind: `raw.html` (also an og card's), `raw.pdf`, `raw.zip`,
784/// `raw.txt`, `raw.json`, `raw.xml`.
785pub fn raw_name(kind: &str) -> String {
786    match kind {
787        "" | "og" => "raw.html".into(),
788        "text" => "raw.txt".into(),
789        k => format!("raw.{k}"),
790    }
791}
792
793/// A converter panic is an error, never a crash.
794pub fn guarded(run: impl FnOnce() -> Result<Doc, String>) -> Result<Doc, String> {
795    std::panic::catch_unwind(std::panic::AssertUnwindSafe(run))
796        .unwrap_or_else(|_| Err("parse_failed: converter crashed".to_string()))
797}
798
799/// Bytes under the root, the pictures among them (`assets/`), every live snapshot's meta.json path (`expired`:
800/// the sweep's rule, so a dead copy counts in no health row), all sessions (status: size, pages, provider health).
801/// Telemetry's `telemetry/` (its stamps, day marks and the weekly tally `Week`) is no cached page: a command's own
802/// count never changes the next's status.
803pub fn usage(root: &Path) -> (u64, u64, Vec<PathBuf>) {
804    fn walk(p: &Path, acc: &mut (u64, u64, Vec<PathBuf>), top: bool) {
805        let Ok(rd) = fs::read_dir(p) else { return };
806        for e in rd.flatten() {
807            let Ok(ft) = e.file_type() else { continue };
808            if ft.is_dir() {
809                (!top || e.file_name() != "telemetry").then(|| walk(&e.path(), acc, false));
810            } else if let Ok(m) = e.metadata() {
811                acc.0 += m.len();
812                acc.1 += if p.ends_with("assets") { m.len() } else { 0 };
813                if e.file_name() == "meta.json" && !expired(p) {
814                    acc.2.push(e.path());
815                }
816            }
817        }
818    }
819    let mut acc = (0, 0, Vec::new());
820    root.join(MINE).is_file().then(|| walk(root, &mut acc, true)); // never a dir fats did not make (`/`, a home)
821    acc
822}
823
824/// The weekly tally the usage summary is built from (`stats::weekly`): counts, codes and fixed names only, one file a
825/// week (`<cache>/telemetry/week/2026-W43.json`, this week's and last week's kept). Sessions are swept within the hour,
826/// so it counts as things happen: a stored fetch or search (`tally`), a command (`stats::tally_run`), a panic
827/// (`stats::crash`).
828/// `n` = each counter by its path in the summary (`tier\toxyjs\tok`), `samples` = the last `week_samples` of each
829/// `tok\tpage` (a stored page's clean tokens), `tok\tread` (a read's answer), `ms\tplain`, `ms\tpaid` (a page call
830/// that served).
831#[derive(serde::Serialize, serde::Deserialize, Default)]
832#[serde(default)]
833pub struct Week {
834    pub n: BTreeMap<String, u64>,
835    pub samples: BTreeMap<String, Vec<u64>>,
836}
837
838impl Week {
839    pub fn add(&mut self, path: &[&str], by: bool) {
840        by.then(|| *self.n.entry(path.join("\t")).or_default() += 1);
841    }
842
843    pub fn sample(&mut self, path: &str, x: u64) {
844        let v = self.samples.entry(path.into()).or_default();
845        v.push(x);
846        v.drain(..v.len().saturating_sub(crate::settings::limit("week_samples")));
847    }
848}
849
850pub const WEEK_S: f64 = 604_800.0;
851/// `2026-W43`: the ISO week of unix time `t`.
852pub fn week_of(t: f64) -> String {
853    let w = chrono::DateTime::from_timestamp(t as i64, 0).unwrap_or_default().date_naive().iso_week();
854    format!("{}-W{:02}", w.year(), w.week())
855}
856
857/// Add to this week's tally (`<root>/telemetry/week/`), at level `full` only (a count made under an opt-out would go
858/// once it is lifted), under its lock as `lock` takes it (`edit_when`); a week's first write drops every older file
859/// but last week's. A count fats cannot write is lost, never a failed command.
860pub fn bump(root: &Path, lock: impl Fn(&File) -> std::io::Result<()>, f: impl FnOnce(&mut Week)) {
861    let full = crate::telemetry::level() == crate::telemetry::Level::Full;
862    let (week, last, dir) = (week_of(now()), week_of(now() - WEEK_S), root.join("telemetry").join("week"));
863    let p = dir.join(format!("{week}.json"));
864    let keep = |e: &std::fs::DirEntry| [&week, &last].iter().any(|w| e.file_name().to_string_lossy().starts_with(*w));
865    let old = std::fs::read_dir(&dir).into_iter().flatten().flatten().filter(|e| full && !p.is_file() && !keep(e));
866    old.for_each(|e| drop(std::fs::remove_file(e.path())));
867    full.then(|| edit_when(&p, lock, f).ok());
868}
869
870/// A code as counted: one errors.json names (`js_shell`; a `*` row's prefix + digits: `http_404`), else `other`.
871pub fn code_of(c: &str) -> String {
872    let digits = |d: &str| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit());
873    let hit = |k: &&str| k.strip_suffix('*').map_or(*k == c, |p| c.strip_prefix(p).is_some_and(digits));
874    crate::lang::FIX.iter().map(|r| r.0).find(hit).map_or("other".into(), |_| c.into())
875}
876
877/// Count a stored fetch or search record (`cache::ingest`, `cache::serp_put`): its calls per tier (a call cut
878/// after the other provider won is neither ok nor failed) and paid provider, each failed call's code and the
879/// record's own when no call ended with it (`no_key`), the serving page call's ms, the page's clean tokens
880/// (`tok`), a PDF. No URL, no query: every name comes from our tables.
881pub fn tally(root: &Path, m: &Meta, tok: Option<usize>) {
882    let serp = m.kind == "serp";
883    bump(root, File::lock, |w| {
884        for h in &m.hops {
885            let t = crate::provider::Tier::parse(&h.provider);
886            let Some(short) = t.map(|t| t.spec().short).or((h.provider == "gh").then_some("gh")) else { continue };
887            let (ok, failed) = (h.code == "ok", !matches!(h.code.as_str(), "ok" | "abandoned"));
888            let tier = if serp { format!("{short}_search") } else { short.into() };
889            for (k, by) in [("ok", ok), ("fail", failed), ("billed", h.cost > 0.0), ("upto", h.upto > 0.0)] {
890                w.add(&["tier", &tier, k], by);
891            }
892            w.add(&["codes", &code_of(&h.code)], failed);
893            let paid = t.filter(|t| *t != crate::provider::Tier::Plain).map(crate::provider::Tier::switch);
894            w.add(&["provider", paid.unwrap_or_default(), if serp { "search" } else { "calls" }], paid.is_some());
895            let ms = if t == Some(crate::provider::Tier::Plain) { "ms\tplain" } else { "ms\tpaid" };
896            (ok && !serp).then(|| w.sample(ms, h.ms));
897        }
898        w.add(&["codes", &code_of(&m.code)], !m.ok && !m.code.is_empty() && !m.hops.iter().any(|h| h.code == m.code));
899        let served =
900            crate::provider::Tier::parse(&m.provider).filter(|t| m.ok && !serp && *t != crate::provider::Tier::Plain);
901        w.add(&["provider", served.map(crate::provider::Tier::switch).unwrap_or_default(), "served"], served.is_some());
902        tok.into_iter().for_each(|n| w.sample("tok\tpage", n as u64));
903        w.add(&["cmd", "pdf"], m.kind == "pdf");
904    });
905}
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910
911    /// A stored dir is a path under the cache root or nothing; on Windows `push("C:x")` replaces the path.
912    #[test]
913    fn a_stored_dir_stays_inside() {
914        assert_eq!(inside("t/u1"), Some(Path::new("t").join("u1")));
915        for bad in ["", "/etc", "../x", "t/../x", "./t"] {
916            assert_eq!(inside(bad), None, "{bad}");
917        }
918        assert_eq!(inside("t/C:x").is_none(), cfg!(windows), "a drive on Windows, a plain name elsewhere");
919    }
920
921    /// The footer read a run, the run's process wrote `done` and let go, the footer wrote its stale copy
922    /// back without `done` (`! abandoned` from then on). `told` is now written under the run's lock, read again.
923    #[test]
924    fn a_run_is_told_under_its_lock() {
925        let root = crate::scratch::Scratch::new("tell");
926        let c = Cache::at(root.to_path_buf(), "t".into());
927        let ended = Detached { url: "https://ex.com/".into(), done: Some(Done::default()), ..Detached::default() };
928        c.run_put(1, &ended).expect("run file");
929        let lock = c.run_claim(1).expect("the run's lock");
930        assert!(c.run(1).is_some_and(|r| r.1), "a held lock = alive");
931        c.run_tell(1);
932        assert!(c.run(1).is_some_and(|r| !r.0.told), "busy: nothing written");
933        drop(lock);
934        c.run_tell(1);
935        assert!(c.run(1).is_some_and(|r| r.0.told && r.0.done.is_some() && !r.1), "free: told, its done kept");
936    }
937
938    /// A run queued behind another (`by`) lives while that one's process holds its lock, and ends with it.
939    #[test]
940    fn a_queued_run_lives_with_its_lane() {
941        let root = crate::scratch::Scratch::new("lane");
942        let c = Cache::at(root.to_path_buf(), "t".into());
943        let lock = c.run_claim(1).expect("the lane's lock");
944        c.run_put(2, &Detached { url: "https://ex.com/b".into(), by: 1, ..Detached::default() }).expect("run file");
945        assert!(c.run(2).is_some_and(|r| r.1), "queued: alive");
946        drop(lock);
947        assert!(c.run(2).is_some_and(|r| !r.1), "its lane died: abandoned");
948    }
949}