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