use crate::cache::{Asset, Cache, Cursor, Detached, Done, Entry, HopRow, Meta, NoDoc, Snap, State, jload, now};
use crate::clean::{Doc, host_of};
use crate::fetch::{self, Hop, Plan};
use crate::lang::{
At, CARD, Cmd, Flag, GUIDE, Id, Match, Out, WORDS, bang, bin, emit, fix, ksize, mib, parse, restamp, short,
to_guide,
};
use crate::outline::{self, Page, Shown};
use crate::provider::{self, Ask, Hit, Tier};
use crate::{search, settings, stats};
use std::io::Read;
#[cfg(windows)]
use std::os::windows::io::AsRawHandle;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
pub const MAX_BYTES: u64 = 16 << 20;
pub const MAX_BYTES_CEIL: u64 = 64 << 20;
fn cap_of(cmd: &Cmd) -> u64 {
cmd.get("max_bytes").and_then(|v| v.parse().ok()).unwrap_or(MAX_BYTES)
}
pub static FENCE: OnceLock<Vec<PathBuf>> = OnceLock::new();
pub fn fence(dirs: Vec<PathBuf>) {
FENCE.set(dirs).ok(); }
pub fn outside(path: &Path) -> bool {
let Some(dirs) = FENCE.get() else { return false };
let up = |p: PathBuf, c| match c {
std::path::Component::ParentDir => p.parent().map(PathBuf::from).unwrap_or(p),
c => p.join(c),
};
let p = std::env::current_dir().unwrap_or_default().join(path).components().fold(PathBuf::new(), up);
!dirs.iter().any(|d| p.starts_with(d) || d.canonicalize().is_ok_and(|d| p.starts_with(d)))
}
pub fn secret(p: &Path) -> bool {
let name = p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
let named = |s: &&str| s.strip_suffix('*').map_or(name == *s, |pre| name.starts_with(pre));
crate::lang::WORDS.secret_names.iter().any(named) || crate::fetch::doc_kind(&name) == Some("secret")
}
fn fenced(f: &str, path: &Path) -> Result<std::io::Result<PathBuf>, (&'static str, &'static str)> {
if f == "-" && FENCE.get().is_some() {
return Err(("not_allowed", "stdin carries the MCP protocol"));
}
let real = path.canonicalize();
if outside(path) || real.as_ref().is_ok_and(|p| outside(p)) {
return Err(("not_allowed", "outside the working directory and the cache"));
}
if real.as_ref().is_ok_and(|p| secret(p) || secret(path)) {
return Err(("secret_file", "a key or credential file is not read · $0"));
}
Ok(real)
}
fn json_of(cmd: &Cmd) -> bool {
cmd.has("json") || cmd.flag("json") || settings::get().json.value
}
pub fn run(argv: &[String]) -> (String, i32, Option<String>) {
let cmd = parse(argv);
if let Some(o) = crate::setup::key_in_argv(&cmd, argv).or_else(|| settings::lowered(&cmd.mods)) {
return (emit(&o, json_of(&cmd)), o.rc, None);
}
settings::mods(&cmd.mods);
let set = settings::get();
let json = json_of(&cmd);
let mut c = Cache::open();
let human = *crate::lang::HUMAN.get_or_init(|| crate::lang::human(json));
let screen = || if argv.is_empty() { Some(stats::home(&c)) } else { crate::lang::help_screen(argv) };
if let Some(s) = human.then(screen).flatten() {
return (s, 0, None);
}
let mut out = if let Some(q) = &cmd.ask {
Out::ask(q)
} else if cmd.flag("dry") {
plan(&cmd, &c)
} else {
let t0 = Instant::now();
let mut o = dispatch(&cmd, &mut c);
o.rec.entry("ms").or_insert((t0.elapsed().as_millis() as u64).into());
if let Err(e) = c.save() {
o = cache_write(e);
}
o
};
if let Some(m) = cmd.count("max") {
out.cap(m, &cmd.with_mod("max", Some(&(m * 2).to_string())));
}
if let Some(i) = cmd.ids.first() {
out.rec.entry("id").or_insert(i.page().into());
}
if let Some(u) = cmd.urls.first().or(cmd.files.first()) {
out.rec.entry("url").or_insert(u.as_str().into());
}
let mut rows = set.rejects.clone();
rows.extend(ignored(&cmd));
out.warn(rows);
let image = out.rec.get("image").and_then(|v| v.as_str()).map(String::from);
stats::tally_run(&c.root, &cmd, &out);
let tail = footer(&c, &out.lines, !json && FENCE.get().is_none());
if let Some(t) = human.then(|| crate::lang::tip(&cmd, &out, is_search(&cmd))).flatten() {
return (t, out.rc, image);
}
(emit(&out, json) + &tail, out.rc, image)
}
fn footer(c: &Cache, lines: &[String], show: bool) -> String {
let named = |n| lines.iter().any(|h| h.starts_with('=') && h.split([' ', '.']).any(|w| w == format!("u{n}")));
let (mut over, mut on) = (Vec::new(), Vec::new());
for (n, r, alive) in c.runs().into_iter().filter(|r| !r.1.told) {
let id = if is_prefetch(&r) { format!("prefetch u{n}") } else { format!("u{n}") };
if alive && r.done.is_none() {
on.extend((!named(n)).then_some((id, n, r)));
continue;
}
let m: Meta = c.st.u.get(n - 1).and_then(|e| jload(&c.dir(e)?.join("meta.json"))).unwrap_or_default();
let fail = |d: Done| format!("failed · {}{}", d.code, provider::spent(" · ", d.cost, m.upto()));
let end = r.done.map_or("! abandoned".into(), |d| if d.ok { "done".into() } else { fail(d) });
over.extend((!named(n)).then(|| format!("{id} {end}")));
if show || named(n) {
c.run_tell(n);
}
}
on.sort_by_key(|o| o.0.starts_with("prefetch"));
let ids = on.iter().map(|o| o.0.as_str()).collect::<Vec<_>>().join(", ").replace(", prefetch u", ", u");
over.extend(
on.first().map(|(_, n, r)| format!("{ids} pending {:.0}s · next: {}", now() - r.t, ready(c, *n, r, &[]))),
);
if over.is_empty() || !show { String::new() } else { format!("~ {}\n", over.join(" · ")) }
}
fn ignored(cmd: &Cmd) -> Vec<String> {
let search = is_search(cmd);
let (list, at) = (paged(cmd), cmd.ids.first().map(|i| i.page() + " "));
let path = cmd.words.iter().any(|w| w.starts_with('.')); let fix = |w| format!("! ignored more · lists page by from:K → {} {}{w} from:K", bin(), at.unwrap_or_default());
let more = list.filter(|_| cmd.has("more")).map(fix);
let row = |(k, v): &(String, String)| {
let (code, why) = match k.as_str() {
"verbose" if v == "true" => ("not_in_v1", "no diagnostics in this build"),
"fetch" if !search => ("ignored", "only a web search prefetches"),
"site" | "since" if !search || is_gh(cmd) => ("ignored", "only a web search uses it"),
"country" if is_gh(cmd) => ("ignored", "only a web search or a page fetch uses it"),
"zone" if !cmd.has("setup") => ("ignored", "only setup uses it"),
"from" if list.is_none() && !path => ("ignored", "only a links, cards, media or comments list pages"),
_ => return None,
};
let rest = Some(cmd.with_mod(k, None)).filter(|r| !parse(std::slice::from_ref(r)).idle);
Some(format!("! {code} {k}:{v} · {why}{}", rest.map_or(String::new(), |r| format!(" → {} {r}", bin()))))
};
cmd.mods.iter().filter_map(row).chain(more).collect()
}
pub fn is_search(cmd: &Cmd) -> bool {
let any = !cmd.words.is_empty() || cmd.get("site").is_some();
any && cmd.ids.is_empty() && cmd.files.is_empty() && page_url(cmd).is_none()
}
pub fn is_gh(cmd: &Cmd) -> bool {
cmd.words.len() > 1 && cmd.words[0] == "gh" && cmd.urls.is_empty()
}
fn page_url(cmd: &Cmd) -> Option<&str> {
let page = |u: &&String| url::Url::parse(u).is_ok_and(|p| p.path() != "/" || p.query().is_some());
cmd.urls.first().filter(page).filter(|_| cmd.urls.len() == 1).map(String::as_str)
}
struct Search {
q: String,
site: Option<String>,
limit: usize,
country: Option<String>,
gh: bool,
plan: Plan,
}
fn search_of(cmd: &Cmd) -> Result<Search, Out> {
let b = bin();
if let Some(l) = cmd.links.first() {
return Err(Out::ask(&format!("? l{l} needs a page: {b} u1 l{l} · search: {b} {}", cmd.words.join(" "))));
}
if cmd.urls.len() > 1 {
let (site, words) = (short(&cmd.urls[0], 60), cmd.words.join(" "));
return Err(Out::ask(&format!("? one site per search: {b} {site} {words}")));
}
let gh = is_gh(cmd);
let site =
cmd.get("site").map(String::from).or(cmd.urls.first().map(|u| short(u, 2048).trim_end_matches('/').into()));
let site = site.filter(|_| !gh);
let after = cmd.get("since").filter(|_| !gh).and_then(|v| crate::lang::since_date(v, (now() / 86_400.0) as i64));
let words = cmd.words[usize::from(gh)..].iter().cloned();
let q = site.iter().map(|s| format!("site:{s}")).chain(words).chain(after.map(|d| format!("after:{d}")));
let q = q.collect::<Vec<_>>().join(" ");
if crate::lang::redact(&q, &settings::secrets()) != q {
let what = "search · the words hold a configured key · not sent · $0";
return Err(refused("key_in_query", "", what, &At::default()));
}
if q.chars().count() > 2048 {
return Err(Out::ask(&format!("? query is {} chars · a search takes 2048 at most", q.chars().count())));
}
if let Some(p) = cmd.get("provider").filter(|p| !gh && !matches!(*p, "oxy" | "bd" | "auto")) {
return Err(Out::ask(&format!("? provider:{p} cannot search · provider:oxy|bd|auto")));
}
let max = if gh { settings::limit("gh_max") } else { provider::SEARCH_MAX };
let (p, asked) = (plan_of(cmd, None), wait_of(cmd));
let wait = Some(p.search_wait(asked)).filter(|w| *w <= asked);
Ok(Search {
q,
site: site.map(|s| s.split('/').next().unwrap_or_default().to_ascii_lowercase()),
limit: cmd.count("limit").unwrap_or(10).min(max),
country: cmd.get("country").filter(|_| !gh).map(str::to_uppercase),
gh,
plan: Plan { wait, ..p },
})
}
fn web(cmd: &Cmd, c: &mut Cache) -> Result<Out, Out> {
let s = search_of(cmd)?;
let what = format!("search \"{}\"", s.q);
if settings::get().offline.value {
return Ok(offline(&what));
}
let t0 = Instant::now();
if s.gh {
return github(cmd, c, &s, t0);
}
if s.plan.wait.is_none() && c.job.is_none() {
return searching(c, cmd);
}
let mut run = fetch::run_search(&s.plan, &s.q, s.limit, s.country.as_deref());
let mut found = run.iter_mut().find(|h| h.ok).map(|h| (h.tier, std::mem::take(&mut h.hits)));
let mut rows = match (&mut found, &s.site) {
(None, _) => fetch::skipped(&s.plan, &run, "", &cmd.canon(), ""),
(Some((_, hits)), Some(host)) => on_site(hits, host),
_ => Vec::new(),
};
if s.limit < cmd.count("limit").unwrap_or(0) {
rows.push(format!("! ignored limit · a search returns {} at most", s.limit));
}
if run.is_empty() {
return Ok(nothing_searched(&s, &what, rows));
}
let job = c.job_of(&cmd.raw).map_err(cache_write)?;
let meta = search_meta(&s, run.iter().map(Hop::row).collect(), found.as_ref().map_or("", |f| f.0.spec().name), t0);
let o = match found {
Some((_, hits)) => listed(c, job, meta, &hits)?,
None => c
.serp_put(job, &meta, fetch::error_text(&run).as_deref())
.map_err(cache_write)
.and_then(|()| search_out(c, cmd, job, &meta))?,
};
let mut o = prefetched(c, cmd, job, o);
o.warn(rows);
Ok(o)
}
const PATIENCE: Duration = provider::SEARCH_TIMEOUT.saturating_mul(2);
fn searching(c: &mut Cache, cmd: &Cmd) -> Result<Out, Out> {
let job = c.job_of(&cmd.raw).map_err(cache_write)?;
detach(format!("j{job}"), &c.root.join(&c.session).join(format!("run/j{job}.log")), None).map_err(cache_write)?;
poll_until(c.born, wait_of(cmd), || c.serp(job).is_some(), || "search running".into());
match c.serp(job) {
Some(m) if m.ok => Ok(serp_list(c, job, 0, true)),
Some(m) => search_out(c, cmd, job, &m),
None => Ok(search_pending(c, job).unwrap_or_default()),
}
}
fn search_pending(c: &Cache, job: usize) -> Option<Out> {
let j = c.job(job)?;
let q = Some(parse(std::slice::from_ref(&j.cmd))).filter(is_search).and_then(|cmd| search_of(&cmd).ok())?.q;
let age = (now() - j.t).max(0.0);
let row = format!("= j{job} pending {age:.0}s search \"{q}\" → {}", poll_next(&format!("j{job}"), 0));
(c.serp(job).is_none() && age < PATIENCE.as_secs_f64()).then(|| waiting(row, format!("j{job}")))
}
fn github(cmd: &Cmd, c: &mut Cache, s: &Search, t0: Instant) -> Result<Out, Out> {
let wait = wait_of(cmd);
let got = provider::all_within(vec![provider::gh_repos(s.q.clone(), s.limit)], wait).pop().flatten();
let got = got.unwrap_or_else(|| Err(provider::late(wait)));
let job = c.job_of(&cmd.raw).map_err(cache_write)?;
let calls = got.as_ref().map_or_else(|f| vec![(f.code, f.why.clone())], |(_, calls)| calls.clone());
let gh = HopRow { provider: "gh".into(), ms: t0.elapsed().as_millis() as u64, ..Default::default() };
let hops = calls.into_iter().map(|(code, why)| HopRow { code: code.into(), why, ..gh.clone() });
let meta = search_meta(s, hops.collect(), if got.is_ok() { "github" } else { "" }, t0);
let fail = match got {
Ok((hits, _)) => return listed(c, job, meta, &hits).map(|o| prefetched(c, cmd, job, o)),
Err(fail) => fail,
};
c.serp_put(job, &meta, Some(&fail.body)).map_err(cache_write)?;
search_out(c, cmd, job, &meta).and_then(Err) }
fn prefetched(c: &mut Cache, cmd: &Cmd, job: usize, mut o: Out) -> Out {
let open =
|(i, e): (usize, &Entry)| (e.job == Some(job) && e.serp && e.dir.is_empty()).then(|| (i + 1, e.url.clone()));
let top: Vec<(usize, String)> = c.st.u.iter().enumerate().filter_map(open).take(prefetch_n(cmd)).collect();
let mut queued = Vec::new();
for (n, url) in &top {
let want = Want { url, slot: Some(*n), ..Want::default() };
let free = c.lookup(url).is_none() && at_once(c, want, cmd).is_none();
queued.extend(free.then(|| reserve(c, Entry::default(), want, cmd).ok()).flatten().map(|n| (n, want)));
}
let ids: Vec<String> = queued.iter().map(|q| format!("u{}", q.0)).collect();
if !ids.is_empty() && launch(c, &queued, cmd).is_ok() {
let row =
format!("prefetching {} free, plain only (detached; fetch:0 = none) · status: {}", ids.join(" "), bin());
o.lines.insert(o.lines.len() - 1, row);
o.set("prefetch", ids);
}
o
}
pub const PREFETCH: usize = 1;
fn prefetch_n(cmd: &Cmd) -> usize {
let n = cmd.get("fetch").and_then(|v| v.parse().ok()).unwrap_or(PREFETCH);
if Tier::Plain.key().is_some() { n } else { 0 }
}
fn on_site(hits: &mut Vec<Hit>, host: &str) -> Vec<String> {
let n = hits.len();
hits.retain(|h| format!(".{}", host_of(&h.url)).ends_with(&format!(".{host}")));
let gone = n - hits.len();
(gone > 0).then(|| format!("! dropped {gone} off-site · not on {host}")).into_iter().collect()
}
fn is_prefetch(r: &Detached) -> bool {
is_search(&parse(std::slice::from_ref(&r.cmd)))
}
fn nothing_searched(s: &Search, what: &str, mut rows: Vec<String>) -> Out {
let code = if s.plan.keys.is_empty() { "no_key" } else { "budget_hit" };
let why =
if code == "no_key" { "web search needs one key (pages work without)" } else { "no search provider can run" };
let eq = format!("= ! {code} {what} · {why} · 0ms");
let first = if rows.is_empty() { bang("", code, "", &At::default()) } else { rows.remove(0) };
let mut o = Out::fail(code, eq, first);
o.warn(rows);
o
}
fn search_meta(s: &Search, hops: Vec<HopRow>, served: &str, t0: Instant) -> Meta {
Meta {
url: format!("search:{}", s.q),
provider: served.into(),
ms: t0.elapsed().as_millis() as u64,
cost: provider::spend(hops.iter().map(|h| h.cost)),
ok: !served.is_empty(),
code: hops.last().map(|h| h.code.clone()).unwrap_or_default(),
t: now(),
kind: "serp".into(),
hops,
country: s.country.clone().unwrap_or_default(),
..Default::default()
}
}
fn search_out(c: &Cache, cmd: &Cmd, job: usize, m: &Meta) -> Result<Out, Out> {
let q = m.url.strip_prefix("search:").unwrap_or(&m.url);
let detail = format!("· tried {} · {}ms{}", m.tried(), m.ms, provider::spent(" ", m.cost, m.upto()));
let last = m.hops.last();
let arg = match m.code.as_str() {
"provider_timeout" if last.is_some_and(|h| h.why.starts_with("wait:")) => "wait:30",
"provider_timeout" if last.is_some_and(|h| h.ms < 30_000) => "timeout:30",
_ => "",
};
let (id, done) = (cmd.canon(), fetch::spent(m, &[], &fetch::keyed()));
let at = At { id: &id, arg, done: &done, ..At::default() };
let (who, owners) = fetch::fail_detail(m, "");
let n = fetch::fail_count(m, c.serps().iter().filter(|s| s.0 != job).map(|s| &s.1), Some(arg));
let next = if n.is_some() { String::new() } else { fix(&m.code, &at) };
let what = format!("{who}{}", n.unwrap_or_default()).trim_start().into();
let row = Flag { code: m.code.clone(), what, next, row: true }.bang("") + &provider::pages(&m.code, owners);
Ok(Out::fail(&m.code, format!("= ! {} j{job} search \"{q}\" {detail}", m.code), row))
}
fn listed(c: &mut Cache, job: usize, mut m: Meta, hits: &[Hit]) -> Result<Out, Out> {
let es: Vec<Entry> =
hits.iter().map(|h| Entry { url: h.url.clone(), job: Some(job), serp: true, ..Entry::default() }).collect();
let first = c.alloc(es, None).map_err(cache_write)?;
m.extra.insert("first".into(), first.into());
m.extra.insert("hits".into(), serde_json::to_value(hits).unwrap_or_default());
c.serp_put(job, &m, None).map_err(cache_write)?;
Ok(serp_list(c, job, 0, true))
}
fn searched(rec: &Meta) -> String {
let cc = if rec.country.is_empty() { String::new() } else { format!(" {}", rec.country) };
let gh = rec.provider == "github";
let tried = if rec.hops.len() > 1 && !gh { format!(" after {}", rec.tried()) } else { String::new() };
let mut note: String = rec.hops.iter().filter(|h| gh && h.code != "ok").map(|h| h.why.as_str()).collect();
note += if gh && settings::key("gh").is_none() { " · no token: 10 searches/min" } else { "" };
let usd = provider::spent(" · ", rec.cost, rec.upto());
format!("{}{cc}{tried}{note} · {:.1}s{usd}", rec.provider, rec.ms as f64 / 1e3)
}
fn serp_list(c: &mut Cache, job: usize, off: usize, new: bool) -> Out {
let b = bin();
let Some(rec) = c.serp(job) else { return Out::ask(&format!("? j{job} has no search record · {b} <words>")) };
let hits: Vec<Hit> = rec.extra.get("hits").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
let first = rec.extra.get("first").and_then(|v| v.as_u64()).unwrap_or(1) as usize;
let query = rec.url.strip_prefix("search:").unwrap_or(&rec.url);
let (mut parts, mut rows) = (Vec::new(), Vec::new());
for (i, hit) in hits.iter().enumerate().skip(off) {
let n = first + i;
let snip = if hit.snippet.is_empty() { String::new() } else { format!(" — \"{}\"", short(&hit.snippet, 90)) };
let row = match rec.provider.as_str() {
"github" => format!("u{n} {} · {}", hit.title, hit.snippet),
_ => format!("u{n} {} {}{snip}", short(&hit.url, 40), short(&hit.title, 60)),
};
let row = if c.lookup(&hit.url).is_some() { format!("{row} · cached $0") } else { row };
let billed = new && i == off;
let mut part = Out::new(vec![row.clone()]);
part.set("i", i).set("id", format!("u{n}")).set("url", hit.url.clone()).set("cache", !new);
part.set("title", hit.title.clone()).set("snippet", hit.snippet.clone()).set("position", i + 1);
part.set("query", query).set("job", format!("j{job}")).set("provider", rec.provider.clone());
part.set("cost", if billed { rec.cost } else { 0.0 }).set("ms", if billed { rec.ms } else { 0 });
parts.push(part);
rows.push(row);
}
let n = c.job(job).and_then(|j| parse(&[j.cmd]).count("limit")).map(|n| n.min(provider::SEARCH_MAX));
let (mut lines, cap) = (Vec::new(), settings::limit::<usize>("read_cap"));
let next = off + outline::cap_rows(&mut lines, &rows, 0, (cap, 1, n));
let cut = n.filter(|&n| lines.len() < n && next < hits.len());
let cut = cut.map_or(String::new(), |n| format!(" of limit:{n} ({cap} tok cap)"));
let total = hits.len();
let how = if new { searched(&rec) } else { format!("cache {}", outline::fmt_age((now() - rec.t).max(0.0))) };
let shown = match (off, lines.len()) {
(0, count) if count == total => String::new(),
(_, 0) => " · all shown".into(),
(_, count) => format!(" · {count} shown u{}-u{}{cut}", first + off, first + off + count - 1),
};
let mut head = vec![format!("= j{job} search \"{query}\" · {total} results{shown} · {how}")];
head.append(&mut lines);
let at = first + off.min(total.saturating_sub(1));
head.push(match (total, next < total) {
(0, _) if query.starts_with("site:") => format!("no on-site results · try without site: → {b} <words>"),
(0, _) => format!("no results · fewer words: {b} <words>"),
(_, true) => format!("open one: {b} u{at} · filter: {b} u{at} <words> · more: {b} more"),
(_, false) => format!("open one: {b} u{at} · filter: {b} u{at} <words>"),
});
if total > 0 {
c.st.cursor = Some(Cursor { u: at, serp: Some((job, next)), ..Cursor::default() });
}
let mut o = Out::new(head);
o.set("id", format!("j{job}")).set("provider", rec.provider.clone()).set("query", query).set("results", total);
o.set("cost", if new { rec.cost } else { 0.0 }).set("ms", if new { rec.ms } else { 0 }).set("cache", !new);
o.parts = parts;
o
}
fn search_dry(cmd: &Cmd, c: &Cache) -> Result<Vec<String>, Out> {
let search = search_of(cmd)?;
let (runs, max) = fetch::route(&search.plan);
let cc = search.country.as_ref().map(|cc| format!(" · country:{cc}")).unwrap_or_default();
let off = settings::get().offline.value;
let (q, lim, nokey) = (&search.q, search.limit, nokey_row(&search.plan));
let (via, wait) = (path_of(&runs), wait_of(cmd).as_secs());
let new = format!("new u{}-u{}", c.st.u.len() + 1, c.st.u.len() + lim);
let line = match (runs.is_empty(), off) {
(_, true) => format!("search \"{q}\" · $0 · ! offline → {}", fix("offline", &At::default())),
_ if search.gh => format!("search github \"{q}\" by stars · limit:{lim} → {new} · $0"),
(true, _) => format!("search \"{q}\" · nothing can search · $0{nokey}"),
_ => format!("search \"{q}\" via {via} · limit:{lim}{cc} · wait:{wait}s → {new} · up to ${max:.4}{nokey}"),
};
let n = prefetch_n(cmd).min(search.limit);
let pre = format!("then fetch:{n} prefetches the top {n} detached · free, plain only");
Ok(std::iter::once(line).chain((n > 0 && !runs.is_empty() && !off).then_some(pre)).collect())
}
fn dried(cmd: &Cmd, rows: Vec<String>, none: bool) -> Out {
let head = format!("= dry {} · spends nothing now", cmd.canon());
let tail = [fetch::hedges(cmd.get("hedge")), format!("run it: {} {}", bin(), cmd.with_mod("dry", None))];
let mut o = Out::new(std::iter::once(head).chain(rows).chain(tail.into_iter().filter(|_| !none)).collect());
o.rc = i32::from(none);
o.set("cost", 0.0).set("dry", true);
o
}
fn nokey_row(p: &Plan) -> String {
let paid = p.keys.iter().any(|t| *t != Tier::Plain);
let asked = |t: &Tier| matches!(p.mode, fetch::Mode::Only(o) if o.owner() == t.owner());
let left: Vec<Tier> = p.ladder(&[]).into_iter().filter(|t| !paid || asked(t)).collect();
fetch::no_key(p, &left, "", false).iter().map(|r| format!(" · {r}")).collect()
}
fn plan_of(cmd: &Cmd, url: Option<&str>) -> Plan {
let mut p = Plan::of(cmd, url);
p.prefetch = url.is_some() && is_search(cmd);
if settings::get().offline.value {
p.keys.clear();
}
p
}
pub fn path_of(route: &[(Tier, Option<Duration>)]) -> String {
let gate = route.iter().any(|r| r.1.is_some()) && route.first().is_some_and(|r| r.0 == Tier::Plain);
let step = |(i, (t, hedge)): (usize, &(Tier, Option<Duration>))| match (i, hedge) {
(0, _) => t.spec().short.to_string(),
(_, Some(d)) => format!(" ∥ {} after {}s", t.spec().short, d.as_secs_f64()),
(_, None) if route[..i].iter().any(|r| r.0 == *t) => format!(" → {} retry", t.spec().short),
(_, None) => format!(" → {}{}", t.spec().short, if !t.can("js") && gate { " (after a captcha)" } else { "" }),
};
route.iter().enumerate().map(step).collect()
}
pub fn plan(cmd: &Cmd, c: &Cache) -> Out {
if cmd.has("account") {
return stats::account_dry(c, cmd.flag("fresh"));
}
if let Some(out) = setup_move(cmd, true) {
return out;
}
if is_search(cmd) {
return merged(search_dry(cmd, c).map(|rows| dried(cmd, rows, false)));
}
let mut dry = Dry { cmd, c, next: c.st.u.len(), refused: 0, total: 0.0 };
let mut lines = Vec::new();
for f in &cmd.files {
let size = match fenced(f, &crate::lang::local_path(f)) {
Err((code, _)) => Err(code),
Ok(_) if f == "-" => Ok(0),
Ok(real) => real.and_then(std::fs::metadata).map(|m| m.len()).map_err(|_| "no_file"),
};
dry.refused += usize::from(size.is_err());
lines.push(match size {
Ok(n) => format!("{f} {}B local → clean → outline → {} · $0", ksize(n as usize), dry.to(None)),
Err(code) => format!("! {code} {f} · $0"),
});
}
for (i, u) in cmd.urls.iter().enumerate() {
let twice = cmd.urls[..i].contains(u).then(|| format!("{} (same as above) · $0", short(u, 60)));
lines.push(twice.unwrap_or_else(|| dry.would(&short(u, 60), u, None)));
}
if cmd.urls.len() > 1 {
let cap = plan_of(cmd, None).cap;
lines.push(format!("batch up to ${:.4} · cap ${cap:.4}", dry.total.min(cap)));
}
let ids = match (&cmd.ids[..], c.st.cursor.as_ref().map_or(0, |k| k.u)) {
([], u) if u > 0 && cmd.urls.is_empty() && cmd.files.is_empty() => vec![Id { u, ..Id::default() }],
(ids, _) => ids.to_vec(),
};
if let Some(id) = ids.iter().find(|i| load(c, i).is_none()) {
return unknown(c, id);
}
for id in &ids {
lines.push(dry.id_row(id));
}
let none = dry.refused > 0 && dry.refused == lines.len();
dried(cmd, lines, none)
}
struct Dry<'a> {
cmd: &'a Cmd,
c: &'a Cache,
next: usize,
refused: usize,
total: f64,
}
impl Dry<'_> {
fn to(&mut self, slot: Option<usize>) -> String {
self.next += usize::from(slot.is_none());
slot.map_or_else(|| format!("new u{}", self.next), |n| format!("fills u{n}"))
}
fn would(&mut self, what: &str, u: &str, slot: Option<usize>) -> String {
if let Some(n) = render_of(self.c, u, self.cmd) {
return format!("{what} = u{n} (rendered, cache) · $0");
}
if let Some((dir, age)) = self.c.lookup(u).filter(|_| !self.cmd.fresh()) {
let to = held(self.c, &dir, slot).map_or_else(|| self.to(slot), |n| format!("u{n}"));
return format!("{what} cache hit, cache {} → {to} · $0", outline::fmt_age(age));
}
if let Some(n) = running(self.c, u) {
return format!("{what} = u{n} (running) · waits up to {}s for it · $0", wait_of(self.cmd).as_secs());
}
if provider::private_host(u) {
self.refused += 1;
return format!("{what} ! private_address → {}", fix("private_address", &At { url: u, ..At::default() }));
}
let mut p = plan_of(self.cmd, Some(u));
fetch::route_of(self.c, u, &mut p);
let (tiers, cost) = fetch::route(&p);
if settings::get().offline.value {
return format!("{what} not cached → ! offline (FATS_OFFLINE) · $0");
}
if !crate::lang::real_host(u) {
self.refused += 1;
let (host, to, id) = (host_of(u), fix("no_host", &At { id: u, url: u, ..At::default() }), self.to(slot));
return format!("{what} ! no_host {host} · {id} · $0 → {to}");
}
let nokey = nokey_row(&p);
if tiers.is_empty() {
return format!("{what} not cached · nothing can fetch it · {} · $0{nokey}", self.to(slot));
}
let to = self.to(slot);
let mods = dry_mods(self.cmd, u, &tiers);
let off = if p.hedged() { "" } else { " · hedge:off, one provider at a time" };
let quote = if p.js { format!(" · {}", fetch::JS_QUOTE) } else { String::new() };
self.total += cost;
format!("{what} fetch {} → {to} · up to ${cost:.4}{quote}{off}{mods}{nokey}", path_of(&tiers))
}
fn id_row(&mut self, i: &Id) -> String {
let (cmd, c, page) = (self.cmd, self.c, i.page());
if let Some(&li) = cmd.links.first() {
return match load(c, i).and_then(|l| l.doc.ok()).and_then(|d| d.links.get(li.wrapping_sub(1)).cloned()) {
Some(u) => self.would(&format!("{page}{} l{li} {}", i.sec_tail(), short(&u, 60)), &u, None),
None => format!("{page}{} l{li} unknown · $0", i.sec_tail()),
};
}
let again = cmd.fresh().then(|| load(c, i)).flatten().map(|l| l.meta.url).filter(|u| u.starts_with("http"));
let ran = pending(c, i.u, &[]).is_some_and(|o| o.rc == 0 || !cmd.fresh());
match c.st.result(i.u).filter(|e| i.job.is_none() && !ran && (e.dir.is_empty() || cmd.fresh())) {
Some(e) => self.would(&format!("{page} {} (search result)", short(&e.url, 60)), &e.url, Some(i.u)),
None if let Some(u) = again => self.would(&format!("{page} {}", short(&u, 60)), &u, None),
None => format!("{page} local read · $0"),
}
}
}
fn dry_mods(cmd: &Cmd, u: &str, tiers: &[(Tier, Option<Duration>)]) -> String {
let ask = Ask { url: u.into(), country: cmd.get("country").map(String::from), ..Ask::default() };
let paid = tiers.iter().any(|t| t.0 != Tier::Plain);
let from = if cmd.get("country").is_none() { " (from the domain)" } else { "" };
let country = provider::sent(&ask, Tier::Bd).filter(|_| paid).map(|cc| format!(" · country:{cc}{from}"));
let device = match cmd.get("device") {
Some("mobile") => " · device:mobile (oxy, decodo; bd serves desktop)",
_ => "",
};
country.unwrap_or_default() + device
}
fn job_read(cmd: &Cmd, c: &mut Cache, j: usize) -> Out {
poll_until(c.born, wait_of(cmd), || search_pending(c, j).is_none(), || "search running".into());
c.reload();
let failed = c.serp(j).filter(|m| !m.ok).zip(c.job(j)).map(|(m, x)| search_out(c, &parse(&[x.cmd]), j, &m));
let mut o = failed.map(merged).or_else(|| search_pending(c, j)).unwrap_or_else(|| job_view(c, j));
if !cmd.words.is_empty() {
o.warn(vec![format!("j{j} ! not_in_v1 multi-page filter → {} j{j}.u1 {}", bin(), cmd.words.join(" "))]);
}
o
}
fn paged(cmd: &Cmd) -> Option<&'static str> {
WORDS.lists.iter().copied().chain(["media", "comments"]).find(|w| cmd.has(w))
}
fn nothing_to_do(cmd: &Cmd, u: usize) -> Out {
let (b, list) = (bin(), paged(cmd));
let page = list.map(|w| format!("? {w} needs a page: {b} u{} {w}", u.max(1)));
Out::ask(&page.unwrap_or(format!("? nothing to do · {b} <url> · {b} u1#2 · {b} u1 <words>")))
}
fn dispatch(cmd: &Cmd, c: &mut Cache) -> Out {
let b = bin();
if let Some(o) = command(cmd, c) {
return o;
}
if let Some(&j) = cmd.jobs.first()
&& cmd.ids.is_empty()
&& cmd.urls.is_empty()
&& cmd.files.is_empty()
{
return job_read(cmd, c, j);
}
let reads = paged(cmd).is_some() || cmd.has("all") || cmd.has("full");
let host = cmd.urls.first().filter(|_| reads && cmd.urls.len() == 1 && cmd.words.is_empty());
let one = match (cmd.files.as_slice(), page_url(cmd).or(host.map(String::as_str)), cmd.words.is_empty() && !reads) {
([f], None, false) if cmd.urls.is_empty() => Some(local(c, f, cmd)),
([], Some(u), false) => Some(fetch(c, Want { url: u, ..Want::default() }, cmd)),
_ => None,
};
if let Some(o) = one {
let o = merged(o);
let new = o.rec.get("cache").and_then(serde_json::Value::as_bool) != Some(true);
return match (o.rc, c.st.cursor.clone(), o.rec.contains_key("pending")) {
(0, Some(cur), false) => dispatch_one(cmd, c, &cur, Id { u: cur.u, ..Id::default() }, new),
_ => o,
};
}
if is_search(cmd) {
return merged(web(cmd, c));
}
if !cmd.files.is_empty() || !cmd.urls.is_empty() {
return fetch_all(cmd, c);
}
let cur = c.st.cursor.clone().unwrap_or_default();
let mut ids = cmd.ids.clone();
if ids.is_empty() && (!cmd.links.is_empty() || cmd.has("more") || cmd.has("up")) {
if cur.u == 0 {
return Out::ask(&format!("? no current page · {b} <url> first"));
}
if let Some((j, off)) = cur.serp.filter(|_| cmd.links.is_empty() && cmd.has("more")) {
return serp_list(c, j, off, false);
}
ids.push(Id { u: cur.u, ..Id::default() });
}
let Some(id) = ids.first().cloned() else { return nothing_to_do(cmd, cur.u) };
let q = cmd.words.join(" ");
let what = if q.is_empty() { "read" } else { "filter" };
let row = |p: String| format!("{p} ! not_in_v1 multi-page {what} → {}", format!("{b} {p} {q}").trim_end());
let rest: Vec<String> = ids[1..].iter().map(|i| row(i.page())).collect();
let mut out = dispatch_one(cmd, c, &cur, id, false);
out.warn(rest);
out
}
fn setup_move(cmd: &Cmd, dry: bool) -> Option<Out> {
let import = cmd.sub == ["import-env"];
if !cmd.sub.is_empty() && cmd.get("zone").is_none() && !import {
return Some(stats::change(cmd));
}
cmd.has("setup").then(|| stats::setup(cmd.get("zone"), import, dry, wait_of(cmd)))
}
fn command(cmd: &Cmd, c: &mut Cache) -> Option<Out> {
let b = bin();
Some(match () {
_ if cmd.idle || cmd.has("status") => stats::status(c),
_ if cmd.has("version") => {
Out::new(vec![format!("= {b} {} · status: {b} · {}", env!("CARGO_PKG_VERSION"), to_guide())])
}
_ if cmd.has("stats") => stats::stats(c, cmd, json_of(cmd)),
_ if cmd.has("telemetry") => crate::telemetry::show(),
_ if cmd.has("setup") && cmd.sub == ["telemetry"] => Out::new(crate::telemetry::row()),
_ if let Some(out) = crate::setup::piped(cmd) => out,
_ if let Some(out) = setup_move(cmd, settings::get().offline.value) => out,
_ if cmd.has("config") => stats::config(),
_ if cmd.has("account") => stats::account(c, cmd.flag("fresh"), wait_of(cmd)),
_ if cmd.has("routes") => {
Out::ask(&format!("? routes: gone (no learned starts) · a page's route: {b} <url> dry:true · {b} config"))
}
_ if cmd.has("help") => Out::new(CARD.lines().map(String::from).chain([to_guide()]).collect()),
_ if cmd.has("guide") => Out::new(GUIDE.lines().map(String::from).collect()),
_ => return None,
})
}
fn dispatch_one(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: Id, new: bool) -> Out {
let mine = id.job.is_none_or(|j| c.job(j).is_some_and(|x| x.session == c.session));
let live = mine && c.run(id.u).is_some_and(|(r, alive)| alive && r.done.is_none());
let ended = live && wait_for(c, id.u, wait_of(cmd)).is_some();
if ended {
c.reload();
}
let refetch = cmd.fresh() && cmd.links.is_empty() && cmd.media.is_empty() && !new && !ended;
if let Some(o) = pending(c, id.u, &cmd.words).filter(|o| mine && (o.rc == 0 || !refetch)) {
return o;
}
let missed = || c.run(id.u).is_some_and(|(r, _)| r.done.as_ref().is_some_and(|d| !d.ok) && is_prefetch(&r));
let again = refetch || (!cmd.ids.is_empty() && missed());
if cmd.has("raw") || cmd.has("headers") {
return kept(c, &id, cmd.has("raw"));
}
if let Some(url) = c.st.result(id.u).filter(|e| mine && (e.dir.is_empty() || again)).map(|e| e.url.clone()) {
return open_result(cmd, c, cur, id, &url);
}
if refetch {
return fetch_again(cmd, c, &id);
}
if let Some(&li) = cmd.links.first() {
return merged(open_link(cmd, c, &id, li));
}
if let Some(&k) = cmd.media.first() { asset(c, &id, k, cmd.fresh()) } else { read(cmd, c, cur, &id, new) }
}
fn kept(c: &Cache, id: &Id, raw: bool) -> Out {
let Some(page) = load(c, id) else { return unknown(c, id) };
let (pid, path) = (&page.pid, page.dir.join(crate::cache::raw_name(&page.meta.kind)));
let Some(n) = std::fs::metadata(&path).ok().filter(|_| page.dir.is_dir()).map(|m| ksize(m.len() as usize)) else {
let why = if page.meta.hops.is_empty() { "not fetched" } else { "failed fetch" };
return Out::ask(&format!("? {pid} {} · no body kept ({why})", if raw { "raw" } else { "headers" }));
};
let (p, m) = (path.display(), &page.meta);
let none = if m.headers.is_empty() { " · none kept (a local file, or kept by an older fats)" } else { "" };
let row = format!("= {pid} raw · {} {n}B · grep: rg <re> {p}", m.kind);
let head = if raw { row } else { format!("= {pid} headers{none}") };
Out::new(std::iter::once(head).chain(m.headers.lines().map(String::from).filter(|_| !raw)).collect())
}
pub const ASSET_MAX: u64 = 10_000_000;
pub const ASSET_WAIT: Duration = Duration::from_secs(15);
fn asset(c: &Cache, id: &Id, k: usize, fresh: bool) -> Out {
let Some(page) = load(c, id) else { return unknown(c, id) };
let media = page.doc.as_ref().map_or(&[][..], |d| &d.media[..]);
let (pic, rec) = (media.get(k.wrapping_sub(1)), page.dir.join("assets").join(format!("m{k}.json")));
let src = pic.map_or("", |p| p.src.as_str());
let ok = |a: &Asset| a.src == src && a.ext.bytes().all(|b| b.is_ascii_alphanumeric()); let kept = jload::<Asset>(&rec).filter(|a| !fresh && ok(a) && rec.with_extension(&a.ext).is_file());
let (new, got) = match (pic, kept) {
(None, _) => (true, Err(("no_media".into(), format!("· the page lists {}", media.len())))),
(_, Some(a)) => (false, Ok(a)),
_ => (true, download(&rec, src)),
};
let subject = format!("{} m{k}", page.eq);
let a = match got {
Ok(a) => a,
Err((code, what)) => {
let at = At { id: &page.pid, url: src, arg: &format!("m{k}"), done: &["max_bytes:64m"] };
let row = bang(&format!("{} m{k}", page.pid), &code, &what, &at);
return Out::fail(&code, format!("= {subject} ! {code} {what}"), row);
}
};
let (kind, path) = (if pic.is_some_and(|p| p.video) { "poster" } else { "photo" }, rec.with_extension(&a.ext));
let (ext, bytes, path) = (&a.ext, ksize(a.bytes as usize), path.display());
let [lo, hi] = [outline::STD, outline::HI_RES].map(|t| ksize(outline::viewed(a.w, a.h, t).1 as usize));
let lo = if lo == hi { String::new() } else { lo.replace('k', "") + "–" };
let view = if a.w == 0 { "size unread, view cost unknown".into() } else { format!("~{lo}{hi} tok if viewed") };
let how = if new { format!("plain {}ms $0", a.ms) } else { format!("cache {}", outline::fmt_age(now() - a.t)) };
let mut o =
Out::new(vec![format!("= {subject} {kind} {}x{} {ext} {bytes}B · saved {path} · {view} · {how}", a.w, a.h)]);
o.set("id", page.eq).set("image", path.to_string()).set("cost", 0.0).set("cache", !new);
o
}
fn download(rec: &Path, src: &str) -> Result<Asset, (String, String)> {
let err = |code: &str, what: String| (code.to_string(), what);
if settings::get().offline.value {
return Err(err("offline", "FATS_OFFLINE is on".into()));
}
let (_turn, t0) = (provider::pace(src), Instant::now());
let ask = Ask { url: src.into(), timeout: Some(ASSET_WAIT), max_bytes: ASSET_MAX, html: true, ..Ask::default() };
let got = provider::block(provider::get(Tier::Plain, &ask, "")).map_or(Err("net_error".into()), |g| g.0);
let raw = got.map_err(|f| match f.code {
"too_big" => err(f.code, format!("{} (>{}B)", f.why, ksize(ASSET_MAX as usize)).trim_start().into()),
code => err(code, f.why),
})?;
let ctype = raw.ctype.split(';').next().unwrap_or_default().trim().to_string();
match raw.status {
200..300 if ctype.starts_with("image/") => {}
200..300 => return Err(err("not_image", if ctype.is_empty() { "no content-type".into() } else { ctype })),
s @ (403 | 410) => return Err(err(&format!("http_{s}"), "· signed link expired or hotlink-blocked".into())),
s => return Err(err(&format!("http_{s}"), String::new())),
}
let reader = image::ImageReader::new(std::io::Cursor::new(&raw.body)).with_guessed_format().ok();
let (w, h) = reader.and_then(|r| r.into_dimensions().ok()).unwrap_or_default();
let ext = image::ImageFormat::from_mime_type(&ctype).map_or("img", |f| f.extensions_str()[0]);
let file = rec.with_extension(ext);
let write = |e: std::io::Error| err("cache_write", format!("{}: {e}", file.display()));
std::fs::create_dir_all(rec.parent().unwrap_or(rec)).map_err(write)?;
std::fs::write(&file, &raw.body).map_err(write)?;
let (bytes, ms) = (raw.body.len() as u64, t0.elapsed().as_millis() as u64);
let a = Asset { src: src.into(), ext: ext.into(), bytes, ms, t: now(), w, h };
crate::cache::jsave(rec, &a).map_err(|e| err("cache_write", e))?;
Ok(a)
}
fn open_result(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: Id, url: &str) -> Out {
let o = merged(fetch(c, Want { url, slot: Some(id.u), ..Want::default() }, cmd));
let open = cmd.words.is_empty() && cmd.links.is_empty() && cmd.media.is_empty() && cmd.reserved.is_empty();
let open = open && id.sec.is_none();
if o.rc != 0 || open || c.st.result(id.u).is_some_and(|e| e.dir.is_empty()) {
return o;
}
let mut out = dispatch_one(cmd, c, cur, id, true);
let warn = o.rec.get("warnings").and_then(|w| w.as_array()).into_iter().flatten();
out.warn(warn.filter_map(|w| w.as_str().map(String::from)).collect());
out
}
fn fetch_again(cmd: &Cmd, c: &mut Cache, id: &Id) -> Out {
let Some(l) = load(c, id) else { return unknown(c, id) };
let (pid, b) = (&l.pid, bin());
match l.meta.url.strip_prefix("file://") {
Some(f) => merged(local(c, f, cmd)),
None if l.meta.url == "stdin:" => Out::ask(&format!("? {pid} came from stdin · pipe it again: … | {b} -")),
None if l.meta.url.is_empty() => no_doc(pid, &l.eq, &l.meta, &[], &NoDoc::Missing, None), None => merged(fetch(c, Want { url: &l.meta.url, prov: Some(&format!("{pid} fresh")), slot: None }, cmd)),
}
}
fn open_link(cmd: &Cmd, c: &mut Cache, id: &Id, li: usize) -> Result<Out, Out> {
let l = load(c, id).ok_or_else(|| unknown(c, id))?;
let doc = l.doc.as_ref().map_err(|why| no_doc(&l.pid, &l.eq, &l.meta, &[], why, None))?;
let n = doc.links.len();
let have = if n == 0 { "no links".into() } else { format!("have l1-l{n}") };
match li.checked_sub(1).and_then(|i| doc.links.get(i)) {
Some(url) => fetch(c, Want { url, prov: Some(&format!("{}{} l{li}", l.pid, id.sec_tail())), slot: None }, cmd),
None => Err(Out::ask(&format!("? l{li} unknown on {} · {have} · {} {} links", l.pid, bin(), l.pid))),
}
}
fn read(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: &Id, new: bool) -> Out {
let named = |m: &Match| cmd.get("match") == Some(m.name());
let rung = [Match::Exact, Match::Near, Match::Topic].into_iter().find(named).unwrap_or(Match::Words);
let pinned = cmd.get("match").is_some();
let more = cmd.has("more") && cur.u == id.u && id.job.is_none();
let (from, limit) = (cmd.count("from").map_or(0, |n| n.saturating_sub(1)), cmd.count("limit"));
page_cmd(c, id, new, |p| {
Ok(if let Some(kind) = WORDS.lists.iter().find(|w| cmd.has(w)) {
outline::list(p, from, limit, &cmd.words, kind)
} else if p.doc.mode == "json" && cmd.words.len() == 1 && cmd.words[0].starts_with('.') {
crate::text::path(p, &cmd.words[0], (from, limit))?
} else if !cmd.words.is_empty() {
let split = search::unpiped(&cmd.words);
let mut s = search::grep(p, split.as_deref().unwrap_or(&cmd.words), (rung, pinned), id.sec, limit)?;
let from = cmd.get("from").filter(|_| cmd.words.iter().any(|w| w.starts_with('.')));
s.0.extend(from.map(|v| format!("! ignored from:{v} · only a links, cards, media or comments list pages")));
s
} else if cmd.has("all") {
outline::outline_all(p)
} else if cmd.has("media") {
outline::media(p, from, limit)
} else if cmd.has("comments") {
outline::comments(p, id.sec, from, limit)
} else if cmd.has("full") && (1..=p.doc.sections.len()).contains(&id.sec.unwrap_or(1)) || more && cur.full {
let part = if more && cur.full { cur.part + 1 } else { 0 };
outline::read_full(p, id.sec.or(cur.k.filter(|_| more)), part, json_of(cmd))
} else if let Some(k) = id.sec.or(cur.k.filter(|_| more)) {
outline::read_sec(p, k, if more && cur.k == Some(k) { cur.part + 1 } else { id.part })?
} else if cmd.has("more") {
outline::outline_all(p)
} else {
outline::outline(p, None)
})
})
.unwrap_or_else(|| unknown(c, id))
}
fn refused(code: &str, subject: &str, what: &str, at: &At) -> Out {
Out::fail(code, format!("= ! {code} {what}"), bang(subject, code, "", at))
}
fn cache_write(e: impl std::fmt::Display) -> Out {
refused("cache_write", "", &e.to_string(), &At::default())
}
fn merged(r: Result<Out, Out>) -> Out {
r.unwrap_or_else(|o| o)
}
fn private(url: &str) -> Out {
let what = format!("{} · loopback, private and link-local hosts are not fetched · 0ms", short(url, 60));
refused("private_address", &short(url, 60), &what, &At { url, ..At::default() })
}
fn offline(what: &str) -> Out {
let detail = format!("{what} · not cached · FATS_OFFLINE is on: cache and local files only · 0ms");
refused("offline", what, &detail, &At::default())
}
fn job_view(c: &Cache, j: usize) -> Out {
let b = bin();
let (Some(job), Some((st, _))) = (c.job(j), ids_of(c, Some(j))) else {
return unknown(c, &Id { job: Some(j), u: 1, ..Id::default() });
};
if job.cmd.is_empty() {
return refused("expired", "", &format!("j{j} · its command and pages went after an hour"), &At::default());
}
let mine = st.u.iter().enumerate().filter(|(_, e)| e.in_job(j));
let rows: Vec<_> = mine.map(|(i, e)| stats::page_row(c, i + 1, e, &format!("j{j}.")).lean).collect();
let age = outline::fmt_age((now() - job.t).max(0.0));
let what = if st.u.iter().any(|e| e.job == Some(j) && e.serp) { "results" } else { "pages" };
let mut lines = vec![format!("= j{j} {} {what} · {age} ago · s:{} · {b} {}", rows.len(), job.session, job.cmd)];
let next = match rows.len() {
0 => format!("no pages stored · rerun: {b} {}", job.cmd),
_ => format!("open: {b} j{j}.u{}", st.u.iter().position(|e| e.in_job(j)).map_or(1, |p| p + 1)),
};
lines.extend(rows);
lines.push(next);
Out::new(lines).with("id", format!("j{j}"))
}
fn unknown(c: &Cache, id: &Id) -> Out {
let b = bin();
let last = Some(c.job_count()).filter(|&n| n > 0).map(|n| format!("last job j{n}"));
let Some((st, _)) = ids_of(c, id.job) else {
let last = last.unwrap_or("no jobs yet".into());
return Out::ask(&format!("? j{} unknown · {last} · {b} <url>", id.job.unwrap_or_default()));
};
let have = if st.u.is_empty() { "none".into() } else { format!("u1-u{}", st.u.len()) };
Out::ask(&format!("? {} unknown · have {have} · {}", id.page(), last.unwrap_or(format!("{b} <url>"))))
}
struct Loaded {
pid: String,
eq: String,
meta: Meta,
doc: Result<Doc, NoDoc>,
dir: std::path::PathBuf,
other: bool,
}
fn ids_of(c: &Cache, j: Option<usize>) -> Option<(State, bool)> {
let Some(j) = j else { return Some((c.st.clone(), false)) };
let s = c.job(j)?.session;
let other = || c.dir(&Entry { dir: s.clone(), ..Entry::default() }).and_then(|d| jload(&d.join("state.json")));
Some(if s == c.session { (c.st.clone(), false) } else { (other().unwrap_or_default(), true) })
}
fn load(c: &Cache, id: &Id) -> Option<Loaded> {
let (st, other) = ids_of(c, id.job)?;
let e = st.u.get(id.u.checked_sub(1)?)?.clone();
let (meta, doc) = c.page(&e);
let pid = if other { id.page() } else { format!("u{}", id.u) };
let hit = c.job.or(id.job).filter(|j| e.hits.contains(j));
let eq = if other { pid.clone() } else { hit.map_or_else(|| e.eq(id.u), |j| format!("j{j}.u{}", id.u)) };
Some(Loaded { pid, eq, meta, doc, dir: c.dir(&e).unwrap_or_default(), other })
}
type Copies = (Option<String>, bool, (Option<String>, bool));
pub(crate) fn copies(c: &Cache, n: usize, (meta, doc): (&Meta, &Doc), log: &[String]) -> Copies {
let text = |d: &Doc| d.sections[..d.served()].iter().flat_map(|s| s.lines.clone()).collect::<Vec<_>>();
let me = &c.st.u[n - 1];
let paid = |m: &Meta| m.hedge == "off";
let owner = |m: &Meta| Tier::parse(&m.provider).map(Tier::owner);
let runs = c.st.u.iter().enumerate().filter(|(_, e)| e.dir == me.dir).filter_map(|(i, _)| c.run(i + 1));
let asked = runs.into_iter().any(|(r, _)| parse(std::slice::from_ref(&r.cmd)).get("country").is_some());
let mut found = (None, false, (None, asked));
let bare = outline::shown(doc, meta).is_none() && outline::record_in(doc, meta, &[]).is_none();
let starved = fetch::budget_row(meta, "", &[]).is_some();
for (i, o) in c.st.u.iter().enumerate().filter(|(_, o)| o.url == me.url && !o.dir.is_empty() && o.dir != me.dir) {
let (m, Ok(d)) = c.page(o) else { continue };
let other = m.ok && (m.country != meta.country || owner(&m) != owner(meta));
found.2.0 = found.2.0.or((i >= n && other).then(|| format!("u{}", i + 1)));
let same = text(&d) == text(doc);
found.1 |= same && (paid(&m) || paid(meta));
let held = outline::shown(&d, &m).filter(|_| outline::shown(doc, meta).is_none());
let rec = || outline::record_in(&d, &m, log).filter(|_| bare).map(|r| format!("u{}{r}", i + 1));
found.0 = match held {
_ if i >= n && m.ok && starved => Some(format!("u{}", i + 1)),
_ if !same && (rendered(&m) || m.ok && paid(&m)) => Some(format!("u{} · rendered", i + 1)),
Some(tail) => Some(format!("u{}{tail} · page content", i + 1)),
None => found.0.or_else(rec),
};
}
found
}
fn page_cmd(c: &mut Cache, id: &Id, new: bool, f: impl FnOnce(&Page) -> Result<Shown, String>) -> Option<Out> {
let Loaded { pid, eq, meta, doc, dir, other } = load(c, id)?;
let (before, others) = c.st.u.get(id.u - 1).filter(|_| !other).map(|me| seen(c, me)).unwrap_or_default();
let blank = Doc::default();
let (render, again, fixed) = if other {
(None, false, (None, false))
} else {
copies(c, id.u, (&meta, doc.as_ref().unwrap_or(&blank)), &before)
};
let doc = match doc {
Ok(d) => d,
Err(why) => return Some(no_doc(&pid, &eq, &meta, &others, &why, render)),
};
let age = (!new).then(|| (now() - meta.t).max(0.0));
let key = id.sec.and_then(|k| outline::part_key(&doc, k, id.part));
let read = std::iter::once(id.sec_tail()).chain(key.clone()).chain(before).collect();
let p = Page { id: pid, eq, doc: &doc, meta: &meta, age, at: (read, render, again, fixed, others) };
let (mut lines, cursor) = match f(&p) {
Ok(s) => s,
Err(q) => return Some(Out::ask(&q)),
};
if let Some(l) = lines.first_mut().filter(|l| l.starts_with("= ")) {
let how = age.map_or_else(|| outline::fetched(&meta), |a| format!("cache {}", outline::fmt_age(a)));
if !l.contains(&format!(" {how}")) {
l.push_str(&format!(" · {how}"));
}
if age.is_some() {
l.push_str(&stale(c, id));
}
l.push_str(&outline::flags(&p));
}
let mut o = Out::new(lines);
record(&mut o, &p, &dir.to_string_lossy(), new);
if id.sec.is_some() {
o.set("id", format!("{}{}", p.eq, id.sec_tail())); }
if id.sec.is_some()
&& !other
&& let Err(e) = c.read_mark(id.u, &[id.sec_tail()].into_iter().chain(key).collect::<Vec<_>>())
{
o = cache_write(e);
}
if let Some(mut cur) = cursor
&& !other
{
cur.u = id.u;
c.st.cursor = Some(cur);
}
Some(o)
}
fn seen(c: &Cache, me: &Entry) -> (Vec<String>, Vec<Meta>) {
let copies = c.st.u.iter().filter(|e| !e.dir.is_empty() && (e.url == me.url || e.dir == me.dir));
let read = copies.clone().flat_map(|e| e.read.iter().filter(|r| e.dir == me.dir || r.starts_with('=')).cloned());
let others = copies.filter(|e| e.dir != me.dir).filter_map(|e| c.meta(&e.dir));
(read.collect(), others.collect())
}
fn stale(c: &Cache, id: &Id) -> String {
let Some(j) = c.st.u.get(id.u.wrapping_sub(1)).and_then(|e| e.job).filter(|_| id.job.is_none()) else {
return String::new();
};
let newer: std::collections::BTreeSet<usize> = c.st.u.iter().filter_map(|e| e.job).filter(|&k| k > j).collect();
let s = if newer.len() == 1 { "" } else { "s" };
newer.last().map_or(String::new(), |n| format!(" ({} job{s} ago; newest j{n})", newer.len()))
}
fn record(o: &mut Out, p: &Page, path: &str, new: bool) {
let m = p.meta;
o.set("id", p.eq.clone())
.set("url", p.doc.final_url.clone())
.set("provider", m.provider.clone())
.set("cost", if new { m.cost } else { 0.0 })
.set("upto", if new { m.upto() } else { 0.0 })
.set("bytes_in", if new { m.bytes } else { 0 })
.set("cache", !new)
.set("age", (now() - m.t).max(0.0) as u64)
.set("path", path.to_string())
.set("mode", p.doc.mode.clone());
if let Some((_, m)) = o.lines.first().and_then(|l| l.split_once("match:")) {
o.set("match", m.to_string());
}
}
fn text_of_zip(path: &str) -> String {
format!("unzip -p {path} '*.xml' | {} -", bin())
}
pub(crate) fn no_doc(id: &str, eq: &str, m: &Meta, others: &[Meta], why: &NoDoc, served: Option<String>) -> Out {
let url = short(&m.url, 60);
let mut at = At { id, url: &m.url, ..At::default() };
let (mut owners, mut next, newer) = (Vec::new(), None, served.is_some());
let zip = if let NoDoc::Zip(path) = why { text_of_zip(&path.to_string_lossy()) } else { String::new() };
let (code, what, detail) = match why {
NoDoc::Zip(_) => {
at.arg = &zip;
let what =
format!("zip (docx/xlsx) · {url} · {}B cached, no zip text in this build", ksize(m.bytes as usize));
("not_in_v1", what, format!("zip {url}"))
}
NoDoc::Parse(e) => ("parse_failed", format!("· {url} · {e}"), url.clone()),
NoDoc::Missing if !m.ok => {
let code = if m.code.is_empty() || m.code == "ok" { "fetch_failed" } else { &m.code };
let spent = provider::spent(" ", m.cost, m.upto());
let what = format!("· {} · tried {} · {}ms{spent}", host_of(&m.url), m.tried(), m.ms);
let (detail, again, fix, named) = fetch::fail_row(m, others, &url, id, served.is_some());
(owners, next) = (named, Some(served.map(|s| format!("{} {s}", bin())).or(fix).unwrap_or_default()));
(code, what, detail + &again)
}
NoDoc::Missing if m.url.is_empty() => ("expired", "· its page and URL went after an hour".into(), "".into()),
NoDoc::Missing => ("snapshot_missing", format!("· {url} · the cached body is gone"), url.clone()),
};
let next = next.unwrap_or_else(|| fix(code, &at));
let row = Flag { code: code.into(), what: detail, next, row: true }.bang(id) + &provider::pages(code, owners);
let key = fetch::no_key_left(m).first().filter(|_| m.hops.is_empty()).map(|r| restamp(r, id, &m.url));
let row = fetch::budget_row(m, id, others).or(key).filter(|_| !newer).map_or(row, |r| format!("{id} {r}"));
let mut o = Out::fail(code, format!("= {eq} ! {code} {what}"), row);
if let NoDoc::Zip(path) = why {
o.set("kind", "zip").set("path", path.to_string_lossy().into_owned());
}
o
}
fn fetch_all(cmd: &Cmd, c: &mut Cache) -> Out {
let t0 = Instant::now();
let want = |url| Want { url, ..Want::default() };
let mut started: Vec<_> = cmd.files.iter().map(|f| Some(local(c, f, cmd).map(Err))).collect();
let mut queued = Vec::new();
for (i, u) in cmd.urls.iter().enumerate() {
if cmd.urls[..i].contains(u) {
started.push(None);
continue;
}
let id = at_once(c, want(u), cmd).map(Err).unwrap_or_else(|| id_of(c, want(u), cmd).map(Ok));
if let Ok(Ok((n, true))) = id {
queued.push((n, want(u)));
}
started.push(Some(id.map(|r| r.map(|(n, _)| n))));
}
if let Err(e) = launch(c, &queued, cmd) {
return cache_write(e);
}
let mut parts: Vec<Out> = Vec::new();
for (i, (f, s)) in cmd.files.iter().chain(&cmd.urls).zip(started).enumerate() {
let first = cmd.urls.iter().position(|u| u == f).and_then(|j| parts.get(cmd.files.len() + j));
let mut o = match s {
Some(s) => merged(s.and_then(|s| s.map_or_else(Ok, |n| finish(c, n, want(f), cmd)))),
None => first.map_or_else(Out::default, same),
};
o.rec.entry("url").or_insert(f.as_str().into());
o.rec.entry("ms").or_insert((t0.elapsed().as_millis() as u64).into());
o.set("i", i);
parts.push(o);
}
if parts.len() == 1 {
return parts.pop().unwrap_or_default();
}
let pending = parts.iter().filter(|p| p.rec.contains_key("pending")).count();
let failed = |p: &&Out| p.rc != 0 || p.rec.contains_key("error");
let ok = parts.iter().filter(|p| !failed(p)).count() - pending;
let mut fails = indexmap::IndexMap::<&str, usize>::new(); let errs = parts.iter().filter(failed).map(|p| p.rec.get("error").and_then(|v| v.as_str()).unwrap_or("failed"));
errs.for_each(|e| *fails.entry(e).or_default() += 1);
let pend = if pending > 0 { format!(" · {pending} pending") } else { String::new() };
let fails: String = pend + &fails.iter().map(|(e, n)| format!(" · {n} ! {e}")).collect::<String>();
let sum = |k: &str| parts.iter().filter_map(|p| p.rec.get(k).and_then(|v| v.as_f64())).fold(0.0, |a, b| a + b);
let (job, ms) = (c.job.map(|j| format!("j{j} ")).unwrap_or_default(), t0.elapsed().as_millis());
let spent = provider::spent(" ", sum("cost"), sum("upto"));
let mut all = Out::new(vec![format!("= {job}{} inputs · {ok} ok{fails} · {ms}ms{spent}", parts.len())]);
all.rc = if ok + pending > 0 { 0 } else { parts.iter().map(|p| p.rc).max().unwrap_or(1) };
all.lines.extend(parts.iter().flat_map(|p| p.lines.iter().cloned()));
all.set("id", c.job.map(|j| format!("j{j}")));
all.parts = parts;
all
}
fn same(first: &Out) -> Out {
let eq = first.lines.first().and_then(|l| l.split(' ').nth(1)).unwrap_or_default();
let rec = Box::new(first.rec.iter().filter(|(k, _)| *k != "cost").map(|(k, v)| (k.clone(), v.clone())).collect());
Out { lines: vec![format!("= {eq} (same as above)")], rc: first.rc, rec, parts: vec![] }
}
#[derive(Clone, Copy, Default)]
struct Want<'a> {
url: &'a str,
prov: Option<&'a str>,
slot: Option<usize>,
}
fn fetch(c: &mut Cache, want: Want, cmd: &Cmd) -> Result<Out, Out> {
let new = |c: &mut Cache| {
let (n, start) = id_of(c, want, cmd)?;
if start {
launch(c, &[(n, want)], cmd).map_err(cache_write)?;
}
finish(c, n, want, cmd)
};
at_once(c, want, cmd).map_or_else(|| new(c), Ok)
}
fn id_of(c: &mut Cache, want: Want, cmd: &Cmd) -> Result<(usize, bool), Out> {
if let Some(n) = running(c, want.url) {
return Ok((n, false));
}
reserve(c, Entry::default(), want, cmd).map(|n| (n, true)).map_err(cache_write)
}
fn reserve(c: &mut Cache, entry: Entry, want: Want, cmd: &Cmd) -> Result<usize, String> {
let job = want.slot.and_then(|n| c.st.result(n)).and_then(|e| e.job).map_or_else(|| c.job_of(&cmd.raw), Ok)?;
c.alloc(vec![Entry { url: want.url.into(), job: Some(job), ..entry }], want.slot)
}
fn at_once(c: &mut Cache, want: Want, cmd: &Cmd) -> Option<Out> {
let url = want.url;
let out = cached(c, url, want, cmd);
let out = out.or_else(|| provider::private_host(url).then(|| private(url)));
out.or_else(|| settings::get().offline.value.then(|| offline(&short(url, 60))))
}
fn finish(c: &mut Cache, n: usize, want: Want, cmd: &Cmd) -> Result<Out, Out> {
let Some(done) = wait_for(c, n, wait_of(cmd)) else {
return Ok(pending(c, n, &cmd.words).unwrap_or_default());
};
if let Some(e) = done.fail {
return Err(cache_write(e));
}
c.reload();
let mut out = outlined(c, n, true, want.prov);
out.warn(done.warn);
if !done.ok && out.rc == 0 {
out.rc = i32::from(done.code != "budget_hit");
out.set("error", done.code);
}
Ok(out)
}
pub const WAIT: u64 = 30;
pub fn wait_of(cmd: &Cmd) -> Duration {
Duration::from_secs(cmd.get("wait").and_then(|v| v.parse().ok()).unwrap_or(WAIT))
}
pub const POLL: Duration = Duration::from_millis(20);
fn launch(c: &Cache, runs: &[(usize, Want)], cmd: &Cmd) -> Result<(), String> {
let (cap, pool) =
(settings::limit::<usize>("batch_parallel").max(1), runs.get(1).map(|_| c.run_file(runs[0].0, "pool.json")));
if let Some(at) = &pool {
fetch::seed(at, runs.iter().map(|(n, w)| (*n, plan_of(cmd, Some(w.url)))), plan_of(cmd, None).cap)?;
}
for (head, &(n, ..)) in runs.iter().enumerate().take(cap) {
let job = c.st.u.get(n - 1).and_then(|e| e.job).unwrap_or_default();
let lock = c.run_claim(n).ok_or_else(|| format!("{}: not locked", c.run_file(n, "lock").display()))?;
for (k, &(id, w)) in runs.iter().skip(head).step_by(cap).enumerate() {
let (by, status) = if k == 0 { (0, String::new()) } else { (n, format!("queued after u{n}")) };
let (url, line, prov, pool) = (w.url.into(), cmd.raw.clone(), w.prov.map(String::from), pool.clone());
c.run_put(id, &Detached { url, cmd: line, prov, job, pool, by, status, t: now(), ..<_>::default() })?;
}
detach(format!("j{job}.u{n}"), &c.run_file(n, "log"), Some(lock))?;
}
Ok(())
}
pub(crate) fn detach(id: String, log: &std::path::Path, lock: Option<std::fs::File>) -> Result<(), String> {
let made = log.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|()| std::fs::File::create(log));
let log = made.map_err(|e| e.to_string())?;
if provider::in_process() {
std::thread::spawn(move || (resume(&id), lock));
return Ok(());
}
let mut p = std::process::Command::new(std::env::current_exe().map_err(|e| e.to_string())?);
let (stdin, keep) = if cfg!(windows) { (None, lock) } else { (lock, None) };
p.args(["--continue", &id]).stdin(stdin.map_or_else(std::process::Stdio::null, std::process::Stdio::from));
p.stdout(log.try_clone().map_err(|e| e.to_string())?).stderr(log);
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut p, 0);
#[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut p, 0x0800_0000);
#[cfg(windows)] for out in [std::io::stdout().as_raw_handle(), std::io::stderr().as_raw_handle()] {
no_inherit(out, 1, 0);
}
let mut child = p.spawn().map_err(|e| format!("fats --continue {id}: {e}"))?;
std::thread::spawn(move || (child.wait().ok(), keep));
Ok(())
}
#[cfg(windows)]
#[expect(unsafe_code, reason = "kernel32 declarations, safe to call with any handle value")]
#[link(name = "kernel32")]
unsafe extern "system" {
#[link_name = "SetHandleInformation"]
safe fn no_inherit(handle: std::os::windows::io::RawHandle, mask: u32, flags: u32) -> i32;
#[link_name = "GetFileType"]
pub(crate) safe fn file_type(handle: std::os::windows::io::RawHandle) -> u32;
}
fn hold_lane(c: &Cache, n: usize) {
let Ok(f) = std::fs::File::open(c.run_file(n, "lock")) else { return };
std::thread::spawn(move || {
if f.lock().is_ok() {
loop {
std::thread::park();
}
}
});
}
fn wait_for(c: &Cache, n: usize, wait: Duration) -> Option<Done> {
let doing = || c.run(n).map(|r| on_now(&r.0.status)).unwrap_or_default();
poll_until(c.born, wait, || c.run(n).is_none_or(|(r, alive)| r.done.is_some() || !alive), doing);
c.run(n)?.0.done
}
fn on_now(status: &str) -> String {
let on: Vec<&str> = status.split(" · ").filter_map(|t| t.strip_suffix(" running")).collect();
if status.is_empty() {
return "starting".into();
}
if on.is_empty() { "next tier".into() } else { format!("{} running", on.join(", ")) }
}
pub const TICK: Duration = Duration::from_secs(5);
fn poll_until(born: Instant, wait: Duration, done: impl Fn() -> bool, doing: impl Fn() -> String) {
let human = std::io::IsTerminal::is_terminal(&std::io::stderr()) && FENCE.get().is_none();
let mut said = 0;
while !done() && born.elapsed() < wait {
let s = born.elapsed().as_secs() / TICK.as_secs() * TICK.as_secs();
if human && s > said {
said = s;
eprintln!("~ still working · {} · {s} s", doing());
}
std::thread::sleep(POLL);
}
}
fn ready(c: &Cache, n: usize, run: &Detached, words: &[String]) -> String {
let words = words.iter().map(|w| format!(" {w}")).collect::<String>();
let on = |h: &HopRow| run.status.contains(&format!("{} running", provider::short(&h.provider)));
let metas = c.st.u.iter().filter(|e| !e.alias && host_of(&e.url) == host_of(&run.url));
let mut ms: Vec<u64> = metas.filter_map(|e| c.meta(&e.dir)).flat_map(|m| m.hops).filter(on).map(|h| h.ms).collect();
ms.sort_unstable();
let end = ms.get(ms.len() / 2).filter(|_| ms.len() >= 3).map(|p| (run.since + *p as f64 / 1e3).min(run.until));
let left = end.map_or(0.0, |e| (e - now()).round().max(0.0)) as u64;
poll_next(&format!("u{n}{words}"), left)
}
fn poll_next(id: &str, left: u64) -> String {
let poll = settings::limit::<u64>("poll_wait");
let eta = if left == 0 { format!("check again in {poll} s") } else { format!("usually ready in ≈{left}s") };
format!("{} {id} wait:{poll} · free, {eta}", bin())
}
fn pending(c: &Cache, n: usize, words: &[String]) -> Option<Out> {
let (run, alive) = c.run(n).filter(|x| x.0.done.is_none())?;
let (id, age, host) = (format!("u{n}"), (now() - run.t).max(0.0).round() as u64, host_of(&run.url));
let eq = format!("j{}.u{n}", run.job);
if alive {
let status = if run.status.is_empty() { "starting" } else { &run.status };
return Some(waiting(format!("= {eq} pending {age}s {host} · {status} → {}", ready(c, n, &run, words)), id));
}
Some(no_doc(&id, &eq, &run.cut(), &[], &NoDoc::Missing, None))
}
fn waiting(row: String, id: String) -> Out {
Out::new(vec![row]).with("id", id).with("pending", true)
}
fn running(c: &Cache, url: &str) -> Option<usize> {
let live = |r: &(usize, Detached, bool)| r.1.url == url && r.1.done.is_none() && r.2 && !is_prefetch(&r.1);
c.runs().into_iter().find(live).map(|r| r.0)
}
pub fn resume(id: &str) -> i32 {
if let Some(p) = id.strip_prefix("setup-") {
return crate::setup::serve(p);
}
if id == "telemetry" {
return crate::telemetry::send();
}
let (mut c, cmd) = (Cache::open(), parse(&[id.to_string()]));
if let (Some(&j), None) = (cmd.jobs.first(), cmd.ids.first()) {
let Some(job) = c.job(j) else { return 2 };
c.job = Some(j);
let rc = web(&parse(&[format!("{} wait:0", job.cmd)]), &mut c).map_or(1, |o| o.rc);
return rc.max(i32::from(c.save().is_err()));
}
let Some(n) = cmd.ids.first().map(|i| i.u) else { return 2 };
if cfg!(windows) && !provider::in_process() {
hold_lane(&c, n);
}
c.runs().into_iter().filter(|r| r.0 == n || r.1.by == n).map(|r| run_one(&mut c, r.0)).max().unwrap_or(1)
}
fn run_one(c: &mut Cache, n: usize) -> i32 {
let Some((mut r, _)) = c.run(n).filter(|x| x.0.done.is_none() && x.0.pid == 0) else { return 1 };
r.pid = std::process::id();
if c.run_put(n, &r).is_err() {
return 1;
}
let w = Cache::at(c.root.clone(), c.session.clone());
let seen = |(status, since, until)| {
w.run_put(n, &Detached { status, since, until, ..r.clone() }).ok(); };
let done = routed(c, &r, n, &seen);
r.done = Some(done);
i32::from(w.run_put(n, &r).is_err())
}
fn routed(c: &mut Cache, run: &Detached, n: usize, seen: fetch::Seen) -> Done {
let (cmd, url) = (parse(std::slice::from_ref(&run.cmd)), run.url.as_str());
settings::mods(&cmd.mods);
let mut p = Plan { pool: run.pool.clone().map(|f| (f, n)), ..plan_of(&cmd, Some(url)) };
fetch::route_of(c, url, &mut p);
p.prior = c.lookup(url).and_then(|(dir, _)| c.dir(&Entry { dir, ..Entry::default() }));
let t0 = Instant::now();
let ask = Ask {
url: url.into(),
country: cmd.get("country").map(String::from),
mobile: cmd.get("device") == Some("mobile"),
max_bytes: cap_of(&cmd),
..Ask::default()
};
let mut hops = fetch::run(&p, &ask, seen);
let mut got = fetch::outcome(url, &mut hops, t0.elapsed().as_millis() as u64);
let served = Tier::parse(&got.meta.provider);
got.meta.country = served.and_then(|t| provider::sent(&ask, t)).unwrap_or_default();
got.meta.hedge = if p.hedged() { "" } else { "off" }.into();
let (ok, cost, id) = (got.meta.ok, got.meta.cost, format!("u{n}"));
let skipped = fetch::skipped(&p, &hops, "", &id, url);
let starved = !hops.iter().any(|h| h.tier.spec().price > 0.0) && skipped.iter().any(|r| r.contains("budget_hit"));
let first = skipped.first().filter(|_| hops.is_empty()).and_then(|r| r.split(' ').nth(1)).map(String::from);
got.meta.code = if starved { "budget_hit".into() } else { first.unwrap_or(got.meta.code) };
let code = got.meta.code.clone();
got.meta.extra.insert("skipped".into(), skipped.into());
got.meta.extra.extend(p.pool.as_ref().map(|(at, _)| ("pool".into(), at.to_string_lossy().into())));
let file = got.file.as_ref().map(|(name, body)| (name.as_str(), body.as_slice()));
let (index, error, doc) = (ok.then_some(url), got.error.as_deref(), got.doc.as_ref());
if let Err(e) = c.ingest(Snap { file, error, doc, meta: got.meta, index, slot: Some(n) }, run.job, t0) {
return Done { ok, code, cost, fail: Some(e), ..Done::default() };
}
Done { ok, code, cost, warn: fetch::ignored(&ask, &hops, &id).into_iter().collect(), fail: None }
}
fn cached(c: &mut Cache, key: &str, want: Want, cmd: &Cmd) -> Option<Out> {
if let Some(n) = render_of(c, key, cmd) {
return Some(outlined(c, n, false, None));
}
let (dir, _) = c.lookup(key).filter(|_| !cmd.fresh())?;
if let Some(n) = held(c, &dir, want.slot) {
let read = c.job_of(&cmd.raw).and_then(|j| c.hit_mark(n, j));
return Some(read.map_or_else(cache_write, |()| outlined(c, n, false, want.prov)));
}
let n = reserve(c, Entry { dir, alias: true, ..Entry::default() }, want, cmd);
Some(n.map_or_else(cache_write, |n| outlined(c, n, false, want.prov)))
}
fn held(c: &Cache, dir: &str, slot: Option<usize>) -> Option<usize> {
c.st.u.iter().rposition(|e| e.dir == dir).filter(|_| slot.is_none()).map(|i| i + 1)
}
fn render_of(c: &Cache, url: &str, cmd: &Cmd) -> Option<usize> {
let has = |e: &Entry| e.url == url && !e.dir.is_empty() && c.meta(&e.dir).is_some_and(|m| rendered(&m));
(cmd.flag("js") && !cmd.flag("fresh")).then(|| c.st.u.iter().rposition(has)).flatten().map(|i| i + 1)
}
fn rendered(m: &Meta) -> bool {
m.ok && m.kind != "og" && Tier::parse(&m.provider).is_some_and(|t| t.can("js"))
}
fn shown(p: &Path) -> String {
let p = p.to_string_lossy();
p.strip_prefix(r"\\?\UNC\").map_or_else(|| p.strip_prefix(r"\\?\").unwrap_or(&p).into(), |s| format!(r"\\{s}"))
}
pub fn dir_key(p: &str) -> String {
let p = shown(Path::new(p));
if cfg!(windows) { p.replace('/', "\\").to_lowercase() } else { p }
}
fn local(c: &mut Cache, f: &str, cmd: &Cmd) -> Result<Out, Out> {
let t0 = Instant::now();
let path = crate::lang::local_path(f);
let real = fenced(f, &path).map_err(|(code, why)| refused(code, f, &format!("{f} · {why}"), &At::default()))?;
let bytes = read_local(f, real, &path, cap_of(cmd))?;
let file = || format!("file://{}", shown(&std::fs::canonicalize(&path).unwrap_or(path)));
let url = if f == "-" { "stdin:".to_string() } else { file() };
let key = blake3::Hasher::new().update(url.as_bytes()).update(&[0]).update(&bytes).finalize();
let key = format!("blake3:{}", key.to_hex());
if let Some(out) = cached(c, &key, Want { url: &url, ..Want::default() }, cmd) {
return Ok(out);
}
let (bytes, charset) = provider::decode_body(bytes, None);
let kind = crate::clean::kind_of("", &bytes);
if kind == "zip" {
let next = text_of_zip(f);
let eq = format!("= ! not_in_v1 zip text: {f} · not in this build (pages, files, cache) → {next}");
let o = Out::new(vec![eq]).with("error", "not_in_v1").with("hint", next).with("what", "zip");
return Ok(Out { rc: 1, ..o });
}
let meta = Meta {
url,
provider: "local".into(),
ok: true,
code: "ok".into(),
t: now(),
bytes: bytes.len() as u64,
kind: kind.into(),
render: Some(false),
charset: charset.into(),
hops: vec![HopRow { provider: "local".into(), code: "ok".into(), ..Default::default() }],
..Meta::default()
};
let doc = crate::cache::build(&bytes, &meta.url, &meta.url, meta.render == Some(true), kind)
.map_err(|e| no_doc(f, f, &meta, &[], &NoDoc::Parse(e), None))?;
let job = c.job_of(&cmd.raw).map_err(cache_write)?;
let name = crate::cache::raw_name(kind);
let snap = Snap { file: Some((&name, &bytes)), error: None, doc: Some(&doc), meta, index: Some(&key), slot: None };
let n = c.ingest(snap, job, t0).map_err(cache_write)?;
Ok(outlined(c, n, true, None))
}
fn outlined(c: &mut Cache, n: usize, new: bool, prov: Option<&str>) -> Out {
page_cmd(c, &Id { u: n, ..Id::default() }, new, |p| Ok(outline::outline(p, prov))).unwrap_or_default()
}
fn read_local(f: &str, real: std::io::Result<PathBuf>, path: &Path, cap: u64) -> Result<Vec<u8>, Out> {
let mut v = Vec::new();
let read = match f {
"-" => std::io::stdin().take(cap + 1).read_to_end(&mut v),
_ => real.and_then(std::fs::File::open).and_then(|h| h.take(cap + 1).read_to_end(&mut v)),
};
if let Err(e) = read {
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
let at = At { arg: &dir.to_string_lossy(), ..At::default() };
return Err(refused("no_file", f, &format!("{f} · {e}"), &at));
}
if v.len() as u64 > cap {
let what = format!("over the {} input cap (ceiling {}) · nothing stored", mib(cap), mib(MAX_BYTES_CEIL));
let at = At { url: f, done: &["max_bytes:64m"][..usize::from(cap >= MAX_BYTES_CEIL)], ..At::default() };
return Err(refused("too_big", f, &format!("{f} · {what}"), &at));
}
Ok(v)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scratch::Scratch;
fn cmd(s: &str) -> Cmd {
parse(&s.split(' ').map(String::from).collect::<Vec<_>>())
}
#[test]
fn the_still_working_line_names_the_running_tiers() {
assert_eq!(on_now("plain:blocked_403✗ · bd running · oxyjs running"), "bd, oxyjs running");
assert_eq!(on_now("plain:blocked_403✗ · oxy:thin✗"), "next tier");
assert_eq!(on_now(""), "starting");
}
#[test]
fn a_path_is_shown_as_typed() {
let p = |s: &str| shown(Path::new(s));
assert_eq!(
(p(r"\\?\C:\a\b.html"), p(r"\\?\UNC\host\share\b.html")),
(r"C:\a\b.html".into(), r"\\host\share\b.html".into())
);
assert_eq!((p("/tmp/a b.html"), p(r"C:\a.html")), ("/tmp/a b.html".into(), r"C:\a.html".into()));
}
#[test]
#[cfg(unix)]
fn a_local_read_opens_the_path_it_checked() {
let root = Scratch::new("fenced");
let [a, b, link] = ["a.txt", "b.txt", "l.txt"].map(|n| root.join(n));
std::fs::write(&a, "checked").ok();
std::fs::write(&b, "swapped").ok();
std::os::unix::fs::symlink(&a, &link).ok();
let real = fenced("l.txt", &link);
assert_eq!(real.as_ref().ok().and_then(|r| r.as_ref().ok()), a.canonicalize().ok().as_ref());
std::fs::remove_file(&link).ok();
std::os::unix::fs::symlink(&b, &link).ok();
let Ok(real) = real else { panic!("inside the fence") };
let read = read_local("l.txt", real, &link, 64).ok();
assert_eq!(read.as_deref(), Some(&b"checked"[..]), "the link's new target is never opened");
assert!(fenced("x", &root.join("none")).is_ok_and(|r| r.is_err()), "a missing file falls to no_file");
}
#[test]
fn more_beside_a_list_is_named() {
let b = bin();
let row = |w: &str| format!("! ignored more · lists page by from:K → {b} {w} from:K");
assert_eq!(ignored(&cmd("u1 links more")), [row("u1 links")]);
assert_eq!(ignored(&cmd("u2#3 media more")), [row("u2 media")]);
assert_eq!(ignored(&cmd("links more")), [row("links")]);
assert!(ignored(&cmd("u1 more")).is_empty() && ignored(&cmd("u1 links from:3")).is_empty());
}
#[test]
fn a_search_timeout_fix_adds_time() {
let row = |why: &str, ms: u64| {
let hops = vec![HopRow {
provider: "brightdata".into(),
code: "provider_timeout".into(),
ms,
why: why.into(),
..Default::default()
}];
let m = Meta { url: "search:rust".into(), code: "provider_timeout".into(), hops, ..Meta::default() };
let out = search_out(&Cache::at(PathBuf::new(), "t".into()), &parse(&["rust".into()]), 1, &m)
.unwrap_or_else(|o| o);
out.lines.join("\n")
};
let b = bin();
let row15 = row("", 15_000);
assert!(row15.ends_with(&format!("! provider_timeout → {b} rust fresh:true timeout:30 ≤$0.0025")), "{row15}");
assert!(row("", 30_000).ends_with(&format!("! provider_timeout → {b} rust fresh:true ≤$0.0025")), "ran 30 s");
let wait = row("wait:5s", 5_000);
assert!(
wait.ends_with(&format!("! provider_timeout bd wait:5s → {b} rust fresh:true wait:30 ≤$0.0025")),
"{wait}"
);
}
#[test]
fn no_doc_answers() {
let b = bin();
let hop = |code: &str| HopRow { provider: "oxylabs".into(), code: code.into(), ..Default::default() };
let m = Meta { url: "https://ex.com/a".into(), ok: true, bytes: 2048, ..Meta::default() };
let lines = |why: &NoDoc, m: &Meta| no_doc("u3", "j2.u3", m, &[], why, None).lines.join("\n");
let zip = lines(&NoDoc::Zip("/c/u3/raw.zip".into()), &m);
assert_eq!(
zip,
format!(
"= j2.u3 ! not_in_v1 zip (docx/xlsx) · ex.com/a · 2.0kB cached, no zip text in this build\n\
u3 ! not_in_v1 zip ex.com/a → unzip -p /c/u3/raw.zip '*.xml' | {b} -"
)
);
let o = no_doc("u3", "u3", &m, &[], &NoDoc::Zip("/c/u3/raw.zip".into()), None);
assert_eq!((o.rc, o.rec["kind"].as_str(), o.rec["path"].as_str()), (1, Some("zip"), Some("/c/u3/raw.zip")));
assert_eq!(
lines(&NoDoc::Parse("pdf: bad xref".into()), &m),
format!(
"= j2.u3 ! parse_failed · ex.com/a · pdf: bad xref\nu3 ! parse_failed ex.com/a → {b} config · report the URL"
)
);
assert_eq!(
lines(&NoDoc::Missing, &m),
format!(
"= j2.u3 ! snapshot_missing · ex.com/a · the cached body is gone\nu3 ! snapshot_missing ex.com/a → {}",
crate::lang::priced(&format!("{b} https://ex.com/a fresh:true"), "https://ex.com/a")
)
);
const K: &str = " · oxy https://dashboard.oxylabs.io (a Web API instance's key)";
let failed =
Meta { ok: false, code: "bad_key".into(), ms: 700, cost: 0.001, hops: vec![hop("bad_key")], ..m.clone() };
assert_eq!(
lines(&NoDoc::Missing, &failed),
format!(
"= j2.u3 ! bad_key · ex.com · tried oxy:bad_key✗ · 700ms spent $0.0010\nu3 ! bad_key oxy → {b} setup{K}"
)
);
let timed = Meta { code: "provider_timeout".into(), hops: vec![hop("provider_timeout")], ..failed.clone() };
let t = lines(&NoDoc::Missing, &timed);
assert!(t.ends_with(&format!("\nu3 ! provider_timeout ex.com/a → {b} u3 fresh:true js:true ≤$0.0030")), "{t}");
let gone = Meta { code: String::new(), hops: vec![], ..failed };
assert!(lines(&NoDoc::Missing, &gone).starts_with("= j2.u3 ! fetch_failed · ex.com · tried - · "));
}
#[test]
fn a_run_lives_while_its_lock_is_held() {
let root = Scratch::new("start");
let mut c = Cache::at(root.to_path_buf(), "t".into());
let job = c.job_of("https://ex.com/a").expect("job");
c.alloc(vec![Entry { url: "https://ex.com/a".into(), job: Some(job), ..Entry::default() }], None).expect("id");
let lock = c.run_claim(1).expect("the launcher's lock");
c.run_put(1, &Detached { url: "https://ex.com/a".into(), job: 1, t: now() - 60.0, ..Detached::default() })
.expect("run file");
let read = || (c.run(1).map(|r| r.1), pending(&c, 1, &[]).expect("a run").lines.join("\n"));
let (alive, out) = read();
assert!(alive == Some(true) && out.contains(" pending 60s ex.com · starting → "), "pid 0 at 60 s: {out}");
let row = |c: &Cache| job_view(c, job).lines.get(1).cloned().unwrap_or_default();
assert!(row(&c).starts_with("j1.u1 ex.com/a · pending → "), "{}", row(&c));
drop(lock);
let (alive, out) = read();
assert!(alive == Some(false) && out.contains(" ! abandoned ex.com"), "no lock: {out}");
assert!(row(&c).starts_with("j1.u1 ex.com · ! abandoned ex.com/a · "), "{}", row(&c));
}
fn listed_session(tag: &str) -> (Cache, Scratch, Vec<Hit>, Meta, Out) {
let root = Scratch::new(&format!("serp-{tag}"));
let mut cache = Cache::at(root.to_path_buf(), "t".into());
let old = Entry { url: "https://ex.com/".into(), dir: "t/u1".into(), ..Entry::default() };
assert_eq!(cache.alloc(vec![old], None), Ok(1));
let body = include_bytes!("../tests/fixtures/oxy-search.json");
let hits = provider::hits(Tier::Oxy, body, 10).expect("fixture");
let job = cache.job_of("heidelberg university").expect("job");
let meta = Meta {
url: "search:heidelberg university".into(),
provider: "oxylabs".into(),
ms: 1630,
cost: 0.001,
kind: "serp".into(),
t: now(),
..Default::default()
};
let out = merged(listed(&mut cache, job, meta.clone(), &hits));
(cache, root, hits, meta, out)
}
#[test]
fn search_results_become_ids() {
let (cache, _root, _, _, out) = listed_session("ids");
let b = bin();
let first = "= j1 search \"heidelberg university\" · 5 results · oxylabs · 1.6s · spent $0.0010";
assert_eq!(out.lines[0], first);
assert_eq!(
out.lines[1],
"u2 uni-heidelberg.de/en Heidelberg University — \"Heidelberg University – the oldest in Germany, recognized globally. \
A leader in science, …\""
);
let wiki = "u4 en.wikipedia.org/wiki/Heidelberg_Univer… Heidelberg University - Wikipedia";
assert!(out.lines[3].starts_with(wiki));
let last = format!("open one: {b} u2 · filter: {b} u2 <words>");
assert_eq!(out.lines.last().map(String::as_str), Some(&*last));
assert_eq!((out.lines.len(), out.parts.len(), out.rc), (7, 5, 0));
assert_eq!(out.parts[0].rec["url"], "https://www.uni-heidelberg.de/en");
assert_eq!((out.parts[0].rec["cost"].as_f64(), out.parts[1].rec["cost"].as_f64()), (Some(0.001), Some(0.0)));
let unfetched = |n| cache.st.result(n).filter(|e| e.dir.is_empty()).cloned();
let entry = unfetched(2).expect("u2 is a search result");
assert_eq!((entry.url.as_str(), entry.job), ("https://www.uni-heidelberg.de/en", cache.job));
assert!(unfetched(1).is_none() && unfetched(7).is_none());
let dry = plan(&cmd("u2 dry:true"), &cache).lines.join("\n");
assert!(dry.contains("u2 uni-heidelberg.de/en (search result)") && !dry.contains("local read"), "{dry}");
}
#[test]
fn more_lists_past_the_cap() {
let (mut cache, _root, hits, meta, _) = listed_session("more");
let b = bin();
let many: Vec<Hit> = (0..4).flat_map(|_| hits.clone()).collect();
let job = cache.job_of("again").expect("job");
let out = merged(listed(&mut cache, job, meta, &many));
let rows = out.lines.iter().filter(|l| l.starts_with('u')).count();
assert!((3..20).contains(&rows), "{:?}", out.lines);
assert!(out.lines.last().is_some_and(|l| l.ends_with(&format!("more: {b} more"))));
assert_eq!(cache.st.cursor.as_ref().and_then(|k| k.serp), Some((job, rows)));
let more = dispatch(&cmd("more"), &mut cache);
assert!(more.lines[0].starts_with(&format!("= j{job} search ")), "{:?}", more.lines);
assert!(more.lines[0].contains(&format!(" shown u{}-", 7 + rows)), "{:?}", more.lines);
assert!(more.lines[1].starts_with(&format!("u{} ", 7 + rows)), "{:?}", more.lines);
}
}