1use 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
40pub const ERROR_FILE: &str = "error.txt";
42
43pub 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
55fn 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
60fn 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
70pub 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 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
82pub 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
87fn 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 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 pub serp: bool,
122 pub read: Vec<String>,
125}
126
127impl Entry {
128 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
134fn 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 pub t: Option<f64>,
157}
158
159impl State {
160 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#[derive(Serialize, Deserialize, Default, Clone)]
173#[serde(default)] pub struct Detached {
175 pub url: String,
176 pub cmd: String,
178 pub prov: Option<String>,
180 pub job: usize,
181 pub pool: Option<PathBuf>,
183 pub by: usize,
185 pub t: f64,
186 pub pid: u32,
187 pub status: String,
189 pub since: f64,
191 pub until: f64,
192 pub done: Option<Done>,
193 pub told: bool,
195}
196
197impl Detached {
198 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 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#[derive(Serialize, Deserialize, Default, Clone)]
219pub struct Done {
220 pub ok: bool,
221 pub code: String,
222 pub cost: f64,
223 pub warn: Vec<String>,
225 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 pub landed: Option<String>,
237 #[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 pub render: Option<bool>,
253 pub country: String,
255 pub charset: String,
257 pub hedge: String,
259 #[serde(flatten)]
261 pub extra: Map<String, Value>,
262}
263
264#[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 pub upto: f64,
278 pub country: String,
280 pub timeout_s: u64,
281 pub limit: Option<u32>,
282 pub remaining: Option<u32>,
283 #[serde(skip_serializing_if = "Option::is_none")]
285 pub waited_ms: Option<u64>,
286}
287
288impl Meta {
289 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 pub fn path(&self, shape: bool) -> String {
304 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 "ok" => format!("{p}{geo}✓{}", h.why),
315 c if h.cost > 0.0 && c.starts_with("http_5") => format!("{p}:{c}✗${:.4} (assumed)", h.cost),
317 _ if h.cost > 0.0 => format!("{p}:{}✗${:.4}", h.code, h.cost),
319 _ if h.upto > 0.0 => format!("{p}:{}✗≤${:.4} (unverified)", h.code, h.upto),
321 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 pub fn upto(&self) -> f64 {
339 crate::provider::spend(self.hops.iter().map(|h| h.upto))
340 }
341
342 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
351pub enum NoDoc {
353 Zip(PathBuf),
355 Missing,
357 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#[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
382pub 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
388pub struct Snap<'a> {
390 pub file: Option<(&'a str, &'a [u8])>,
392 pub error: Option<&'a [u8]>,
394 pub doc: Option<&'a Doc>,
395 pub meta: Meta,
396 pub index: Option<&'a str>,
398 pub slot: Option<usize>,
400}
401
402pub struct Cache {
405 pub root: PathBuf,
406 pub session: String,
407 pub st: State,
408 cursor0: Option<Cursor>,
409 pub job: Option<usize>,
411 pub born: Instant,
413 metas: std::cell::RefCell<std::collections::HashMap<String, Option<Meta>>>,
415}
416
417fn 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
425pub const MINE: &str = ".fatsearch-cache";
427
428pub 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
442fn 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
449fn 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
454fn 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()); fs::read_dir(p).map_or_else(|_| Vec::new(), |rd| rd.flatten().filter(real).map(|e| e.path()).collect())
464}
465
466pub 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 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 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
515pub 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 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 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())); let r = f(st);
556 (r, st.clone())
557 })?;
558 self.st = st;
559 Ok(r)
560 }
561
562 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 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 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(); }
587 }
588
589 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 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 pub fn save(&mut self) -> Result<(), String> {
608 if self.st.cursor == self.cursor0 { Ok(()) } else { self.with_state(|_| ()) }
609 }
610
611 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 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 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)?; 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 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 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 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 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))?; 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 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 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 pub fn dir(&self, e: &Entry) -> Option<PathBuf> {
693 self.under(&e.dir).filter(|d| !expired(d))
694 }
695
696 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 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 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 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 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 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)))?; 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
771pub 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
783pub 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
793pub 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
799pub 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)); acc
822}
823
824#[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;
851pub 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
857pub 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
870pub 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
877pub 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 #[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 #[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 #[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}