use crate::clean::{DOC_V, Doc, build_doc};
use crate::settings::limit;
use chrono::Datelike;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Map, Value};
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
pub fn now() -> f64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0)
}
pub fn jload<T: DeserializeOwned>(p: &Path) -> Option<T> {
serde_json::from_slice(&fs::read(p).ok()?).ok()
}
pub const ERROR_FILE: &str = "error.txt";
pub const SPEND_FILE: &str = "spend.log";
fn spend_log(paid: [f64; 2], dir: &Path) {
let row = serde_json::json!([now(), paid, dir.to_string_lossy()]).to_string() + "\n";
let keys = &crate::settings::get().key_dir.value;
(paid[0] + paid[1] > 0.0).then(|| crate::settings::save_in(keys, SPEND_FILE, row.as_bytes(), true).ok());
}
fn keep_error(dir: &Path, body: &[u8]) -> Result<(), String> {
crate::settings::save_in(dir, ERROR_FILE, body, false).map_err(|e| format!("{}/{ERROR_FILE}: {e}", dir.display()))
}
fn numbered(dir: &Path, prefix: char, suffix: &str) -> Vec<usize> {
let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
let name = |e: fs::DirEntry| e.file_name().to_str()?.strip_prefix(prefix)?.strip_suffix(suffix)?.parse().ok();
let mut v: Vec<usize> = rd.flatten().filter_map(name).collect();
v.sort_unstable();
v
}
pub fn jsave<T: Serialize>(p: &Path, v: &T) -> Result<(), String> {
let dir = p.parent().ok_or("no parent dir")?;
fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let tmp = p.with_extension(format!("{}.{n}.tmp", std::process::id()));
let body = serde_json::to_vec_pretty(v).map_err(|e| e.to_string())?;
fs::write(&tmp, body).and_then(|_| fs::rename(&tmp, p)).map_err(|e| format!("{}: {e}", p.display()))
}
pub fn edit<T: DeserializeOwned + Serialize + Default, R>(p: &Path, f: impl FnOnce(&mut T) -> R) -> Result<R, String> {
edit_when(p, File::lock, f)
}
fn edit_when<T: DeserializeOwned + Serialize + Default, R>(
p: &Path,
lock: impl Fn(&File) -> std::io::Result<()>,
f: impl FnOnce(&mut T) -> R,
) -> Result<R, String> {
fs::create_dir_all(p.parent().ok_or("no parent dir")?).map_err(|e| format!("{}: {e}", p.display()))?;
let file = File::create(p.with_extension("lock")).map_err(|e| e.to_string())?;
lock(&file).map_err(|e| e.to_string())?;
let mut v: T = jload(p).unwrap_or_default();
let r = f(&mut v);
jsave(p, &v)?;
Ok(r)
}
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
#[serde(default)]
pub struct Cursor {
pub u: usize,
pub k: Option<usize>,
pub part: usize,
pub full: bool,
pub serp: Option<(usize, usize)>,
}
#[derive(Serialize, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Entry {
pub url: String,
pub dir: String,
pub alias: bool,
pub job: Option<usize>,
pub serp: bool,
pub read: Vec<String>,
}
impl Entry {
pub fn eq(&self, u: usize) -> String {
self.job.map_or_else(|| format!("u{u}"), |j| format!("j{j}.u{u}"))
}
}
fn place(st: &mut State, mut e: Entry, slot: Option<usize>) -> usize {
match slot.filter(|&n| st.result(n).is_some()).and_then(|n| Some((n, st.u.get_mut(n - 1)?))) {
Some((n, old)) => {
(e.job, e.serp) = (old.job, old.serp);
*old = e;
n
}
None => {
st.u.push(e);
st.u.len()
}
}
}
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct State {
pub u: Vec<Entry>,
pub cursor: Option<Cursor>,
pub t: Option<f64>,
}
impl State {
pub fn result(&self, n: usize) -> Option<&Entry> {
self.u.get(n.checked_sub(1)?).filter(|e| e.serp || e.dir.is_empty())
}
}
#[derive(Serialize, Deserialize, Default, Clone)]
#[serde(default)] pub struct Detached {
pub url: String,
pub cmd: String,
pub prov: Option<String>,
pub job: usize,
pub pool: Option<PathBuf>,
pub by: usize,
pub t: f64,
pub pid: u32,
pub status: String,
pub since: f64,
pub until: f64,
pub done: Option<Done>,
pub told: bool,
}
impl Detached {
pub fn dead(&self, alive: bool, id: Option<&Entry>) -> bool {
!alive && self.done.is_none() && id.is_some_and(|e| e.dir.is_empty())
}
pub fn cut(&self) -> Meta {
let hop = |t: &crate::provider::Spec| HopRow { provider: t.name.into(), upto: t.price, ..HopRow::default() };
let tier = |s: &str| crate::provider::Tier::parse(s.strip_suffix(" running")?).map(|t| hop(t.spec()));
let hops = self.status.split(" · ").filter_map(tier).map(|h| HopRow { code: "abandoned".into(), ..h });
let hops: Vec<_> = hops.collect();
let provider = hops.last().map(|h| h.provider.clone()).unwrap_or_default();
Meta { url: self.url.clone(), code: "abandoned".into(), t: self.t, provider, hops, ..Meta::default() }
}
}
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct Done {
pub ok: bool,
pub code: String,
pub cost: f64,
pub warn: Vec<String>,
pub fail: Option<String>,
}
#[derive(Serialize, Deserialize, Default, Clone)]
#[serde(default)]
pub struct Meta {
pub url: String,
pub final_url: Option<String>,
pub landed: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refreshed_from: Option<String>,
pub provider: String,
pub ms: u64,
pub cost: f64,
pub ok: bool,
pub code: String,
pub t: f64,
pub bytes: u64,
pub kind: String,
pub hops: Vec<HopRow>,
pub render: Option<bool>,
pub country: String,
pub charset: String,
pub hedge: String,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Serialize, Deserialize, Default, Clone)]
#[serde(default)]
pub struct HopRow {
pub provider: String,
pub code: String,
pub cost: f64,
pub ms: u64,
pub why: String,
pub upto: f64,
pub country: String,
pub timeout_s: u64,
pub limit: Option<u32>,
pub remaining: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub waited_ms: Option<u64>,
}
impl Meta {
pub fn geo(&self) -> String {
let c = self.country.to_uppercase();
if c.is_empty() || c == crate::provider::home() { String::new() } else { format!("·{}", c.to_lowercase()) }
}
pub fn tried(&self) -> String {
self.path(false)
}
pub fn path(&self, shape: bool) -> String {
let unbilled = |c: &str| crate::provider::REFUSED.contains(&c) || matches!(c, "provider_timeout" | "abandoned");
let geo = if shape { String::new() } else { self.geo() };
let hop = |h: &HopRow| {
let (p, s) = (crate::provider::short(&h.provider), h.timeout_s);
let cc = if h.country.is_empty() { String::new() } else { format!("@{}", h.country) };
let p = if shape && s > 0 && p != "plain" { format!("{p}{cc}/{s}s") } else { p.to_string() };
match h.code.as_str() {
"ok" => format!("{p}{geo}✓{}", h.why),
c if h.cost > 0.0 && c.starts_with("http_5") => format!("{p}:{c}✗${:.4} (assumed)", h.cost),
_ if h.cost > 0.0 => format!("{p}:{}✗${:.4}", h.code, h.cost),
_ if h.upto > 0.0 => format!("{p}:{}✗≤${:.4} (unverified)", h.code, h.upto),
c if p != "plain" && (unbilled(c) || c.starts_with("http_5") || c.starts_with("blocked_")) => {
let why = if shape && c == "provider_error" && !h.why.is_empty() {
format!(", {}", h.why)
} else {
String::new()
};
format!("{p}:{c}✗$0 (not charged{why})")
}
_ => format!("{p}:{}✗", h.code),
}
};
let hops: Vec<String> = self.hops.iter().map(hop).collect();
if hops.is_empty() { "-".into() } else { hops.join(" ") }
}
pub fn upto(&self) -> f64 {
crate::provider::spend(self.hops.iter().map(|h| h.upto))
}
pub fn how(&self) -> String {
let waited = self.hops.iter().filter_map(|h| h.waited_ms).sum::<u64>() as f64 / 1e3;
let waited = if waited > 0.0 { format!(" · waited {waited:.1}s") } else { String::new() };
if self.hedge == "off" { " · hedge:off" } else { "" }.to_string() + &waited
}
}
pub enum NoDoc {
Zip(PathBuf),
Missing,
Parse(String),
}
#[derive(Serialize, Deserialize, Default)]
pub struct Job {
pub session: String,
pub cmd: String,
pub t: f64,
}
#[derive(Serialize, Deserialize, Default)]
pub struct Asset {
pub src: String,
pub ext: String,
pub bytes: u64,
pub ms: u64,
pub t: f64,
pub w: u32,
pub h: u32,
}
pub fn assets(dir: &Path) -> Vec<Asset> {
let d = dir.join("assets");
numbered(&d, 'm', ".json").into_iter().filter_map(|k| jload(&d.join(format!("m{k}.json")))).collect()
}
pub struct Snap<'a> {
pub file: Option<(&'a str, &'a [u8])>,
pub error: Option<&'a [u8]>,
pub doc: Option<&'a Doc>,
pub meta: Meta,
pub index: Option<&'a str>,
pub slot: Option<usize>,
}
pub struct Cache {
pub root: PathBuf,
pub session: String,
pub st: State,
cursor0: Option<Cursor>,
pub job: Option<usize>,
pub born: Instant,
metas: std::cell::RefCell<std::collections::HashMap<String, Option<Meta>>>,
}
fn inside(rel: &str) -> Option<&str> {
let p = Path::new(rel);
(!rel.is_empty() && p.components().all(|c| matches!(c, std::path::Component::Normal(_)))).then_some(rel)
}
pub const MINE: &str = ".fatsearch-cache";
pub fn private_root(root: &Path, default: bool) -> bool {
let mut b = fs::DirBuilder::new();
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
if !root.exists() && b.recursive(true).create(root).is_ok() || default && !root.join(MINE).exists() {
fs::write(root.join(MINE), b"").ok();
}
root.is_dir()
}
fn ours(d: &Path) -> bool {
let n = d.file_name().and_then(|n| n.to_str()).unwrap_or_default();
n == "run" || matches!(n.as_bytes(), [b'u' | b'j', b'0'..=b'9', ..]) && d.join("meta.json").is_file()
}
fn age(p: &Path) -> u64 {
fs::metadata(p).and_then(|m| m.modified()).map_or(u64::MAX, |t| t.elapsed().map_or(0, |d| d.as_secs()))
}
fn expired(dir: &Path) -> bool {
let meta = dir.join("meta.json");
age(dir) >= limit("cache_idle_s") || meta.exists() && age(&meta) >= limit("cache_ttl_s")
}
fn dirs_in(p: &Path) -> Vec<PathBuf> {
let real = |e: &fs::DirEntry| e.file_type().is_ok_and(|t| t.is_dir()); fs::read_dir(p).map_or_else(|_| Vec::new(), |rd| rd.flatten().filter(real).map(|e| e.path()).collect())
}
pub fn sweep() {
let s = crate::settings::get();
let (root, marker, mine) = (&s.cache.value, s.cache.value.join("swept"), s.cache.value.join(MINE).is_file());
let all = mine && age(&marker) >= limit("sweep_every_s") && fs::write(&marker, b"").is_ok();
let gone = |d: &str| inside(d).is_none_or(|d| expired(&root.join(d)));
let jobs = all.then(|| {
let idx = |i: &mut Map<String, Value>| i.retain(|_, r| !gone(r["dir"].as_str().unwrap_or_default()));
edit(&root.join("index.json"), idx).ok();
edit(&root.join("jobs.json"), |js: &mut Vec<Job>| {
js.iter_mut().filter(|j| now() - j.t >= limit::<f64>("cache_ttl_s")).for_each(|j| j.cmd.clear());
js.iter().map(|j| j.cmd.is_empty()).collect::<Vec<_>>()
})
});
let forget = |e: &mut Entry| *e = Entry { dir: format!("{:-<1}", e.dir), job: e.job, ..Entry::default() };
let sessions = dirs_in(root).into_iter().filter(|d| all || d.ends_with(&s.session.value));
for session in sessions.filter(|d| mine && d.join("state.json").is_file()) {
let c = Cache::at(root.clone(), session.file_name().unwrap_or_default().to_string_lossy().into());
for d in dirs_in(&session).iter().filter(|d| ours(d) && expired(d)) {
let runs = if d.ends_with("run") { c.runs() } else { Vec::new() };
let claim = |n: usize| fs::rename(c.run_file(n, "json"), c.run_file(n, "swept")).is_ok();
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)) {
let snap = Snap { file: None, error: None, doc: None, meta: r.cut(), index: None, slot: Some(*n) };
Cache::at(root.clone(), c.session.clone()).ingest(snap, r.job, Instant::now()).ok();
}
runs.iter().all(|r| !r.2).then(|| fs::remove_dir_all(d).unwrap_or(()));
}
if let Some(Ok(js)) = &jobs {
let old = |e: &&mut Entry| e.job.and_then(|j| js.get(j.checked_sub(1)?)) != Some(&false) && gone(&e.dir);
edit(&session.join("state.json"), |st: &mut State| st.u.iter_mut().filter(old).for_each(forget)).ok();
}
}
}
pub fn url_key(url: &str) -> &str {
let u = crate::html::py_strip(url);
u.split('#').next().unwrap_or(u)
}
pub fn run_at(json: &Path) -> Option<(Detached, bool)> {
let held = |at: PathBuf| matches!(File::open(at).map(|f| f.try_lock()), Ok(Err(fs::TryLockError::WouldBlock)));
let own = held(json.with_extension("lock"));
let r: Detached = jload(json)?;
let alive = own || (r.by > 0 && r.done.is_none() && held(json.with_file_name(format!("u{}.lock", r.by))));
Some((r, alive))
}
impl Cache {
pub fn open() -> Cache {
let s = crate::settings::get();
private_root(&s.cache.value, s.cache.src == "default");
Cache::at(s.cache.value.clone(), s.session.value.clone())
}
pub fn at(root: PathBuf, session: String) -> Cache {
let st: State = jload(&root.join(&session).join("state.json")).unwrap_or_default();
Cache { root, session, cursor0: st.cursor.clone(), st, job: None, born: Instant::now(), metas: <_>::default() }
}
pub fn meta(&self, dir: &str) -> Option<Meta> {
let load = || jload(&self.under(dir)?.join("meta.json"));
self.metas.borrow_mut().entry(dir.into()).or_insert_with(load).clone()
}
fn with_state<R>(&mut self, f: impl FnOnce(&mut State) -> R) -> Result<R, String> {
let moved = (self.st.cursor != self.cursor0).then(|| self.st.cursor.clone());
let (r, st) = edit(&self.root.join(&self.session).join("state.json"), |st: &mut State| {
st.cursor = moved.unwrap_or_else(|| st.cursor.take());
st.t = st.t.or(Some(now())); let r = f(st);
(r, st.clone())
})?;
self.st = st;
Ok(r)
}
pub fn reload(&mut self) {
self.st = jload(&self.root.join(&self.session).join("state.json")).unwrap_or_default();
}
pub fn run_file(&self, n: usize, ext: &str) -> PathBuf {
self.root.join(&self.session).join("run").join(format!("u{n}.{ext}"))
}
pub fn run(&self, n: usize) -> Option<(Detached, bool)> {
run_at(&self.run_file(n, "json"))
}
pub fn run_put(&self, n: usize, r: &Detached) -> Result<(), String> {
jsave(&self.run_file(n, "json"), r)
}
pub fn run_tell(&self, n: usize) {
let Some(_lock) = File::create(self.run_file(n, "lock")).ok().filter(|f| f.try_lock().is_ok()) else { return };
if let Some(r) = jload::<Detached>(&self.run_file(n, "json")) {
self.run_put(n, &Detached { told: true, ..r }).ok(); }
}
pub fn runs(&self) -> Vec<(usize, Detached, bool)> {
let found = numbered(&self.root.join(&self.session).join("run"), 'u', ".json");
found.into_iter().filter_map(|n| self.run(n).map(|(r, a)| (n, r, a))).collect()
}
pub fn run_claim(&self, n: usize) -> Option<File> {
let p = self.run_file(n, "lock");
fs::create_dir_all(p.parent()?).ok()?;
let f = File::create(p).ok()?;
f.lock().ok()?;
Some(f)
}
pub fn save(&mut self) -> Result<(), String> {
if self.st.cursor == self.cursor0 { Ok(()) } else { self.with_state(|_| ()) }
}
pub fn read_mark(&mut self, n: usize, read: &[String]) -> Result<(), String> {
let new = |e: &Entry| read.iter().filter(|t| !e.read.contains(t)).cloned().collect::<Vec<_>>();
self.with_state(|st| st.u.get_mut(n - 1).map(|e| e.read.extend(new(e)))).map(|_| ())
}
pub fn alloc(&mut self, es: Vec<Entry>, slot: Option<usize>) -> Result<usize, String> {
self.with_state(|st| {
let n = st.u.len() + 1;
es.into_iter().map(|e| place(st, e, slot)).min().unwrap_or(n)
})
}
pub fn serp_put(&self, job: usize, meta: &Meta, error: Option<&[u8]>) -> Result<(), String> {
let dir = self.root.join(&self.session).join(format!("j{job}"));
jsave(&dir.join("meta.json"), meta)?; edit(&self.root.join(&self.session).join("state.json"), |st: &mut State| st.t = st.t.or(Some(now())))?;
spend_log([meta.cost, meta.upto()], &dir);
tally(&self.root, meta, None);
error.map_or(Ok(()), |e| keep_error(&dir, e))
}
pub fn serp(&self, job: usize) -> Option<Meta> {
jload(&self.dir(&Entry { dir: format!("{}/j{job}", self.session), ..Entry::default() })?.join("meta.json"))
}
pub fn serps(&self) -> Vec<(usize, Meta)> {
numbered(&self.root.join(&self.session), 'j', "").into_iter().filter_map(|j| Some((j, self.serp(j)?))).collect()
}
fn under(&self, rel: &str) -> Option<PathBuf> {
let p = self.root.join(inside(rel)?);
p.canonicalize().ok()?.starts_with(self.root.canonicalize().ok()?).then_some(p)
}
pub fn lookup(&self, url: &str) -> Option<(String, f64)> {
let on = !crate::settings::get().nocache.value;
let idx: Map<String, Value> = on.then(|| jload(&self.root.join("index.json"))).flatten()?;
let row = idx.get(url_key(url))?; let (dir, t) = (row["dir"].as_str()?.to_string(), row["t"].as_f64()?);
let m: Meta = jload(&self.dir(&Entry { dir: dir.clone(), ..Entry::default() })?.join("meta.json"))?;
(url_key(&m.url) == url_key(url) || url.starts_with("blake3:")).then(|| (dir, now() - t))
}
pub fn job_of(&mut self, cmd: &str) -> Result<usize, String> {
if let Some(j) = self.job {
return Ok(j);
}
let (session, cmd) = (self.session.clone(), cmd.to_string());
let j = edit(&self.root.join("jobs.json"), |jobs: &mut Vec<Job>| {
jobs.push(Job { session, cmd, t: now() });
jobs.len()
})?;
self.job = Some(j);
Ok(j)
}
pub fn job(&self, j: usize) -> Option<Job> {
let jobs: Vec<Job> = jload(&self.root.join("jobs.json"))?;
jobs.into_iter().nth(j.checked_sub(1)?).filter(|x| inside(&x.session).is_some())
}
pub fn job_count(&self) -> usize {
jload::<Vec<Job>>(&self.root.join("jobs.json")).map_or(0, |j| j.len())
}
pub fn dir(&self, e: &Entry) -> Option<PathBuf> {
self.under(&e.dir).filter(|d| !expired(d))
}
pub fn page(&self, e: &Entry) -> (Meta, Result<Doc, NoDoc>) {
let Some(d) = self.dir(e) else {
return (Meta { url: e.url.clone(), ok: true, ..Meta::default() }, Err(NoDoc::Missing));
};
fs::set_times(&d, fs::FileTimes::new().set_modified(SystemTime::now())).ok();
let meta: Meta = jload(&d.join("meta.json")).unwrap_or_default();
let current = |x: &Doc| x.v == DOC_V && x.chunk == crate::settings::get().chunk.value;
if let Some(doc) = jload::<Doc>(&d.join("doc.json")).filter(current) {
return (meta, Ok(doc));
}
let f = raw_name(&meta.kind);
let Ok(raw) = fs::read(d.join(&f)) else { return (meta, Err(NoDoc::Missing)) };
if crate::clean::sniff(&raw) == Some("zip") {
return (meta, Err(NoDoc::Zip(d.join(f))));
}
let url = if meta.url.is_empty() { e.url.clone() } else { meta.url.clone() };
let fin = meta.final_url.clone().unwrap_or_else(|| url.clone());
let kind = crate::clean::sniff(&raw).unwrap_or(&meta.kind);
let doc = build(&raw, &url, &fin, meta.render == Some(true), kind).map_err(NoDoc::Parse);
(meta, doc.inspect(|x| drop(jsave(&d.join("doc.json"), x))))
}
pub fn ingest(&mut self, snap: Snap, job: usize, t0: Instant) -> Result<usize, String> {
let Snap { file, error, doc, mut meta, index, slot } = snap;
let sdir = self.root.join(&self.session);
fs::create_dir_all(&sdir).map_err(|e| format!("{}: {e}", sdir.display()))?;
if self.under(&self.session).is_none() {
return Err(format!("{}: links out of the cache", sdir.display()));
}
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let tmp = sdir.join(format!(".tmp-{}-{job}-{seq}", std::process::id()));
fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let staged = (|| {
file.map_or(Ok(()), |(name, raw)| fs::write(tmp.join(name), raw).map_err(|e| e.to_string()))?;
error.map_or(Ok(()), |e| keep_error(&tmp, e))?;
doc.map_or(Ok(()), |doc| jsave(&tmp.join("doc.json"), doc))?;
let ms = t0.elapsed().as_millis() as u64;
let times = meta.hops.iter_mut().map(|h| &mut h.ms).chain([&mut meta.ms]);
times.filter(|m| **m == 0).for_each(|m| *m = ms);
jsave(&tmp.join("meta.json"), &meta)
})();
staged.inspect_err(|_| drop(fs::remove_dir_all(&tmp)))?; let (session, url, root) = (self.session.clone(), meta.url.clone(), self.root.clone());
let placed = self.with_state(|st| -> Result<(usize, String), String> {
let free = slot.filter(|&n| st.result(n).is_some());
let n = free.unwrap_or(st.u.len() + 1);
let name = |k| if k == 1 { format!("{session}/u{n}") } else { format!("{session}/u{n}-{k}") };
let rel = (1..).map(name).find(|r| !root.join(r).exists()).unwrap_or_default();
fs::rename(&tmp, root.join(&rel)).map_err(|e| e.to_string())?;
place(st, Entry { url, dir: rel.clone(), job: Some(job), ..Entry::default() }, free);
Ok((n, rel))
})?;
let (n, rel) = placed.inspect_err(|_| drop(fs::remove_dir_all(&tmp)))?;
spend_log([meta.cost, meta.upto()], &self.root.join(&rel));
tally(&self.root, &meta, doc.map(|d| d.tokens.clean));
if let Some(key) = index {
edit(&self.root.join("index.json"), |idx: &mut Map<String, Value>| {
idx.insert(url_key(key).into(), serde_json::json!({"dir": rel, "t": now()}));
})?;
}
Ok(n)
}
}
pub fn build(raw: &[u8], url: &str, fin: &str, js: bool, kind: &str) -> Result<Doc, String> {
guarded(|| match kind {
"pdf" => crate::pdf::build_pdf(raw, url, fin, limit("pdf_budget_s")),
"md" => Ok(crate::clean::markdown(raw, url, fin)),
k if crate::clean::LISTS.text.contains(&k) => Ok(crate::text::build(raw, k, url, fin)),
k => Ok(build_doc(&crate::html::parse(&String::from_utf8_lossy(raw)), url, fin, js))
.map(|d| if k == "og" { crate::clean::card(d) } else { d }),
})
}
pub fn raw_name(kind: &str) -> String {
match kind {
"" | "og" => "raw.html".into(),
"text" => "raw.txt".into(),
k => format!("raw.{k}"),
}
}
pub fn guarded(run: impl FnOnce() -> Result<Doc, String>) -> Result<Doc, String> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(run))
.unwrap_or_else(|_| Err("parse_failed: converter crashed".to_string()))
}
pub fn usage(root: &Path) -> (u64, u64, Vec<PathBuf>) {
fn walk(p: &Path, acc: &mut (u64, u64, Vec<PathBuf>), top: bool) {
let Ok(rd) = fs::read_dir(p) else { return };
for e in rd.flatten() {
let Ok(ft) = e.file_type() else { continue };
if ft.is_dir() {
(!top || e.file_name() != "telemetry").then(|| walk(&e.path(), acc, false));
} else if let Ok(m) = e.metadata() {
acc.0 += m.len();
acc.1 += if p.ends_with("assets") { m.len() } else { 0 };
if e.file_name() == "meta.json" && !expired(p) {
acc.2.push(e.path());
}
}
}
}
let mut acc = (0, 0, Vec::new());
root.join(MINE).is_file().then(|| walk(root, &mut acc, true)); acc
}
#[derive(serde::Serialize, serde::Deserialize, Default)]
#[serde(default)]
pub struct Week {
pub n: BTreeMap<String, u64>,
pub samples: BTreeMap<String, Vec<u64>>,
}
impl Week {
pub fn add(&mut self, path: &[&str], by: bool) {
by.then(|| *self.n.entry(path.join("\t")).or_default() += 1);
}
pub fn sample(&mut self, path: &str, x: u64) {
let v = self.samples.entry(path.into()).or_default();
v.push(x);
v.drain(..v.len().saturating_sub(crate::settings::limit("week_samples")));
}
}
pub const WEEK_S: f64 = 604_800.0;
pub fn week_of(t: f64) -> String {
let w = chrono::DateTime::from_timestamp(t as i64, 0).unwrap_or_default().date_naive().iso_week();
format!("{}-W{:02}", w.year(), w.week())
}
pub fn bump(root: &Path, lock: impl Fn(&File) -> std::io::Result<()>, f: impl FnOnce(&mut Week)) {
let full = crate::telemetry::level() == crate::telemetry::Level::Full;
let (week, last, dir) = (week_of(now()), week_of(now() - WEEK_S), root.join("telemetry").join("week"));
let p = dir.join(format!("{week}.json"));
let keep = |e: &std::fs::DirEntry| [&week, &last].iter().any(|w| e.file_name().to_string_lossy().starts_with(*w));
let old = std::fs::read_dir(&dir).into_iter().flatten().flatten().filter(|e| full && !p.is_file() && !keep(e));
old.for_each(|e| drop(std::fs::remove_file(e.path())));
full.then(|| edit_when(&p, lock, f).ok());
}
pub fn code_of(c: &str) -> String {
let digits = |d: &str| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit());
let hit = |k: &&str| k.strip_suffix('*').map_or(*k == c, |p| c.strip_prefix(p).is_some_and(digits));
crate::lang::FIX.iter().map(|r| r.0).find(hit).map_or("other".into(), |_| c.into())
}
pub fn tally(root: &Path, m: &Meta, tok: Option<usize>) {
let serp = m.kind == "serp";
bump(root, File::lock, |w| {
for h in &m.hops {
let t = crate::provider::Tier::parse(&h.provider);
let Some(short) = t.map(|t| t.spec().short).or((h.provider == "gh").then_some("gh")) else { continue };
let (ok, failed) = (h.code == "ok", !matches!(h.code.as_str(), "ok" | "abandoned"));
let tier = if serp { format!("{short}_search") } else { short.into() };
for (k, by) in [("ok", ok), ("fail", failed), ("billed", h.cost > 0.0), ("upto", h.upto > 0.0)] {
w.add(&["tier", &tier, k], by);
}
w.add(&["codes", &code_of(&h.code)], failed);
let paid = t.filter(|t| *t != crate::provider::Tier::Plain).map(crate::provider::Tier::switch);
w.add(&["provider", paid.unwrap_or_default(), if serp { "search" } else { "calls" }], paid.is_some());
let ms = if t == Some(crate::provider::Tier::Plain) { "ms\tplain" } else { "ms\tpaid" };
(ok && !serp).then(|| w.sample(ms, h.ms));
}
w.add(&["codes", &code_of(&m.code)], !m.ok && !m.code.is_empty() && !m.hops.iter().any(|h| h.code == m.code));
let served =
crate::provider::Tier::parse(&m.provider).filter(|t| m.ok && !serp && *t != crate::provider::Tier::Plain);
w.add(&["provider", served.map(crate::provider::Tier::switch).unwrap_or_default(), "served"], served.is_some());
tok.into_iter().for_each(|n| w.sample("tok\tpage", n as u64));
w.add(&["cmd", "pdf"], m.kind == "pdf");
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_run_is_told_under_its_lock() {
let root = crate::scratch::Scratch::new("tell");
let c = Cache::at(root.to_path_buf(), "t".into());
let ended = Detached { url: "https://ex.com/".into(), done: Some(Done::default()), ..Detached::default() };
c.run_put(1, &ended).expect("run file");
let lock = c.run_claim(1).expect("the run's lock");
assert!(c.run(1).is_some_and(|r| r.1), "a held lock = alive");
c.run_tell(1);
assert!(c.run(1).is_some_and(|r| !r.0.told), "busy: nothing written");
drop(lock);
c.run_tell(1);
assert!(c.run(1).is_some_and(|r| r.0.told && r.0.done.is_some() && !r.1), "free: told, its done kept");
}
#[test]
fn a_queued_run_lives_with_its_lane() {
let root = crate::scratch::Scratch::new("lane");
let c = Cache::at(root.to_path_buf(), "t".into());
let lock = c.run_claim(1).expect("the lane's lock");
c.run_put(2, &Detached { url: "https://ex.com/b".into(), by: 1, ..Detached::default() }).expect("run file");
assert!(c.run(2).is_some_and(|r| r.1), "queued: alive");
drop(lock);
assert!(c.run(2).is_some_and(|r| !r.1), "its lane died: abandoned");
}
}