1use crate::cache::{Asset, Cache, Cursor, Detached, Done, Entry, HopRow, Meta, NoDoc, Snap, State, jload, now};
5use crate::clean::{Doc, host_of};
6use crate::fetch::{self, Hop, Plan};
7use crate::lang::{
8 At, CARD, Cmd, Flag, GUIDE, Id, Match, Out, WORDS, bang, bin, emit, fix, ksize, mib, parse, short, to_guide,
9};
10use crate::outline::{self, Page, Shown};
11use crate::provider::{self, Ask, Hit, Tier};
12use crate::{search, settings, stats};
13use std::io::Read;
14use std::path::{Path, PathBuf};
15use std::sync::OnceLock;
16use std::time::{Duration, Instant};
17
18pub const MAX_BYTES: u64 = 16 << 20;
22pub const MAX_BYTES_CEIL: u64 = 64 << 20;
23
24fn cap_of(cmd: &Cmd) -> u64 {
26 cmd.get("max_bytes").and_then(|v| v.parse().ok()).unwrap_or(MAX_BYTES)
27}
28
29pub static FENCE: OnceLock<Vec<PathBuf>> = OnceLock::new();
32
33pub fn fence(dirs: Vec<PathBuf>) {
34 FENCE.set(dirs).ok(); }
36
37pub fn outside(path: &Path) -> bool {
40 let Some(dirs) = FENCE.get() else { return false };
41 let mut p = PathBuf::new();
42 for c in std::env::current_dir().unwrap_or_default().join(path).components() {
43 match c {
44 std::path::Component::ParentDir => {
45 p.pop();
46 }
47 c => p.push(c),
48 }
49 }
50 !dirs.iter().any(|d| p.starts_with(d) || d.canonicalize().is_ok_and(|d| p.starts_with(d)))
51}
52
53pub fn secret(p: &Path) -> bool {
57 let name = p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
58 let named = |s: &&str| s.strip_suffix('*').map_or(name == *s, |pre| name.starts_with(pre));
59 crate::lang::WORDS.secret_names.iter().any(named) || crate::fetch::doc_kind(&name) == Some("secret")
60}
61
62fn fenced(f: &str, path: &Path) -> Result<std::io::Result<PathBuf>, (&'static str, &'static str)> {
68 if f == "-" && FENCE.get().is_some() {
69 return Err(("not_allowed", "stdin carries the MCP protocol"));
70 }
71 let real = path.canonicalize();
72 if outside(path) || real.as_ref().is_ok_and(|p| outside(p)) {
74 return Err(("not_allowed", "outside the working directory and the cache"));
75 }
76 if real.as_ref().is_ok_and(|p| secret(p) || secret(path)) {
77 return Err(("secret_file", "a key or credential file is not read · $0"));
78 }
79 Ok(real)
80}
81
82fn json_of(cmd: &Cmd) -> bool {
84 cmd.has("json") || cmd.flag("json") || settings::get().json.value
85}
86
87pub fn run(argv: &[String]) -> (String, i32, Option<String>) {
90 let cmd = parse(argv);
91 settings::mods(&cmd.mods);
92 let set = settings::get();
93 let json = json_of(&cmd);
94 let mut c = Cache::open();
95 let human = crate::lang::human(json);
97 let screen = || if argv.is_empty() { Some(stats::home(&c)) } else { crate::lang::help_screen(argv) };
98 if let Some(s) = human.then(screen).flatten() {
99 return (s, 0, None);
100 }
101 let mut out = if let Some(q) = &cmd.ask {
102 Out::ask(q.clone())
103 } else if cmd.flag("dry") {
104 plan(&cmd, &c)
105 } else {
106 let t0 = Instant::now();
107 let mut o = dispatch(&cmd, &mut c);
108 o.rec.entry("ms").or_insert((t0.elapsed().as_millis() as u64).into());
109 if let Err(e) = c.save() {
110 o = cache_write(e);
111 }
112 o
113 };
114 if let Some(m) = cmd.count("max") {
115 out.cap(m, &cmd.with_mod("max", Some(&(m * 2).to_string())));
116 }
117 if let Some(i) = cmd.ids.first() {
118 out.rec.entry("id").or_insert(i.page().into());
119 }
120 if let Some(u) = cmd.urls.first().or(cmd.files.first()) {
121 out.rec.entry("url").or_insert(u.as_str().into());
122 }
123 let mut rows = set.rejects.clone();
124 rows.extend(ignored(&cmd));
125 out.warn(rows);
126 let image = out.rec.get("image").and_then(|v| v.as_str()).map(String::from);
127 stats::tally_run(&c.root, &cmd, &out);
128 let tail = footer(&c, &out.lines, !json && FENCE.get().is_none());
129 if let Some(t) = human.then(|| crate::lang::tip(&cmd, &out, is_search(&cmd))).flatten() {
130 return (t, out.rc, image);
131 }
132 (emit(&out, json) + &tail, out.rc, image)
133}
134
135fn footer(c: &Cache, lines: &[String], show: bool) -> String {
139 let named = |n| lines.iter().any(|h| h.starts_with('=') && h.split([' ', '.']).any(|w| w == format!("u{n}")));
140 let (mut over, mut on) = (Vec::new(), Vec::new());
141 for (n, r, alive) in c.runs().into_iter().filter(|r| !r.1.told) {
142 let id = if is_prefetch(&r) { format!("prefetch u{n}") } else { format!("u{n}") };
143 if alive && r.done.is_none() {
144 on.extend((!named(n)).then_some((id, n, r)));
145 continue;
146 }
147 let m: Meta = c.st.u.get(n - 1).and_then(|e| jload(&c.dir(e)?.join("meta.json"))).unwrap_or_default();
150 let bill =
151 |cost: f64| if cost + m.upto() > 0.0 { provider::bill(cost, m.upto()) } else { "not charged".into() };
152 let fail = |d: Done| format!("failed · {} · {}", d.code, bill(d.cost));
153 let end = r.done.map_or("! abandoned".into(), |d| if d.ok { "done".into() } else { fail(d) });
154 over.extend((!named(n)).then(|| format!("{id} {end}")));
155 if show || named(n) {
156 c.run_tell(n);
157 }
158 }
159 on.sort_by_key(|o| o.0.starts_with("prefetch"));
162 let ids = on.iter().map(|o| o.0.as_str()).collect::<Vec<_>>().join(", ").replace(", prefetch u", ", u");
163 over.extend(
164 on.first().map(|(_, n, r)| format!("{ids} pending {:.0}s · next: {}", now() - r.t, ready(c, *n, r, &[]))),
165 );
166 if over.is_empty() || !show { String::new() } else { format!("~ {}\n", over.join(" · ")) }
167}
168
169fn ignored(cmd: &Cmd) -> Vec<String> {
173 let search = is_search(cmd);
174 let lists = WORDS.lists.iter().copied().chain(["media", "comments"]);
175 let (list, at) = (lists.into_iter().find(|w| cmd.has(w)), cmd.ids.first().map(|i| i.page() + " "));
176 let fix = |w| format!("! ignored more · lists page by from:K → {} {}{w} from:K", bin(), at.unwrap_or_default());
177 let more = list.filter(|_| cmd.has("more")).map(fix);
178 let row = |(k, v): &(String, String)| {
179 let (code, why) = match k.as_str() {
180 "verbose" if v == "true" => ("not_in_v1", "no diagnostics in this build"),
181 "fetch" if !search => ("ignored", "only a web search prefetches"),
182 "site" | "since" if !search || is_gh(cmd) => ("ignored", "only a web search uses it"),
183 "country" if is_gh(cmd) => ("ignored", "only a web search or a page fetch uses it"),
184 "zone" if !cmd.has("setup") => ("ignored", "only setup uses it"),
185 "from" if list.is_none() => ("ignored", "only a links, cards, media or comments list pages"),
186 _ => return None,
187 };
188 let rest = Some(cmd.with_mod(k, None)).filter(|r| !parse(std::slice::from_ref(r)).idle);
190 Some(format!("! {code} {k}:{v} · {why}{}", rest.map_or(String::new(), |r| format!(" → {} {r}", bin()))))
191 };
192 cmd.mods.iter().filter_map(row).chain(more).collect()
193}
194
195pub fn is_search(cmd: &Cmd) -> bool {
198 let any = !cmd.words.is_empty() || cmd.get("site").is_some();
199 any && cmd.ids.is_empty() && cmd.files.is_empty() && page_url(cmd).is_none()
200}
201
202pub fn is_gh(cmd: &Cmd) -> bool {
204 cmd.words.len() > 1 && cmd.words[0] == "gh" && cmd.urls.is_empty()
205}
206
207fn page_url(cmd: &Cmd) -> Option<&str> {
209 let page = |u: &&String| url::Url::parse(u).is_ok_and(|p| p.path() != "/" || p.query().is_some());
210 cmd.urls.first().filter(page).filter(|_| cmd.urls.len() == 1).map(String::as_str)
211}
212
213struct Search {
215 q: String,
217 site: Option<String>,
219 limit: usize,
220 country: Option<String>,
221 gh: bool,
223 plan: Plan,
225}
226
227fn search_of(cmd: &Cmd) -> Result<Search, Out> {
231 let b = bin();
232 if let Some(l) = cmd.links.first() {
233 return Err(Out::ask(format!("? l{l} needs a page: {b} u1 l{l} · search: {b} {}", cmd.words.join(" "))));
234 }
235 if cmd.urls.len() > 1 {
236 let (site, words) = (short(&cmd.urls[0], 60), cmd.words.join(" "));
237 return Err(Out::ask(format!("? one site per search: {b} {site} {words}")));
238 }
239 let gh = is_gh(cmd);
240 let site =
241 cmd.get("site").map(String::from).or(cmd.urls.first().map(|u| short(u, 2048).trim_end_matches('/').into()));
242 let site = site.filter(|_| !gh);
243 let after = cmd.get("since").filter(|_| !gh).and_then(|v| crate::lang::since_date(v, (now() / 86_400.0) as i64));
244 let words = cmd.words[usize::from(gh)..].iter().cloned();
245 let q = site.iter().map(|s| format!("site:{s}")).chain(words).chain(after.map(|d| format!("after:{d}")));
246 let q = q.collect::<Vec<_>>().join(" ");
247 if crate::lang::redact(&q, &settings::secrets()) != q {
249 let what = "search · the words hold a configured key · not sent · $0";
250 return Err(refused("key_in_query", "", what, &At::default()));
251 }
252 if q.chars().count() > 2048 {
253 return Err(Out::ask(format!("? query is {} chars · a search takes 2048 at most", q.chars().count())));
254 }
255 if let Some(p) = cmd.get("provider").filter(|p| !gh && !matches!(*p, "oxy" | "bd" | "auto")) {
256 return Err(Out::ask(format!("? provider:{p} cannot search · provider:oxy|bd|auto")));
257 }
258 let max = if gh { settings::limit("gh_max") } else { provider::SEARCH_MAX };
259 let (p, asked) = (plan_of(cmd, None), wait_of(cmd));
260 let wait = Some(p.search_wait(asked)).filter(|w| *w <= asked);
262 Ok(Search {
263 q,
264 site: site.map(|s| s.split('/').next().unwrap_or_default().to_ascii_lowercase()),
265 limit: cmd.count("limit").unwrap_or(10).min(max),
266 country: cmd.get("country").filter(|_| !gh).map(str::to_uppercase),
267 gh,
268 plan: Plan { wait, ..p },
269 })
270}
271
272fn web(cmd: &Cmd, c: &mut Cache) -> Result<Out, Out> {
276 let s = search_of(cmd)?;
277 let what = format!("search \"{}\"", s.q);
278 if settings::get().offline.value {
279 return Ok(offline(&what));
280 }
281 let t0 = Instant::now();
282 if s.gh {
283 return github(cmd, c, &s, t0);
284 }
285 if s.plan.wait.is_none() && c.job.is_none() {
287 return searching(c, cmd);
288 }
289 let mut run = fetch::run_search(&s.plan, &s.q, s.limit, s.country.as_deref());
290 let mut found = run.iter_mut().find(|h| h.ok).map(|h| (h.tier, std::mem::take(&mut h.hits)));
291 let mut rows = match (&mut found, &s.site) {
292 (None, _) => fetch::skipped(&s.plan, &run, "", &cmd.canon(), ""),
293 (Some((_, hits)), Some(host)) => on_site(hits, host),
294 _ => Vec::new(),
295 };
296 if s.limit < cmd.count("limit").unwrap_or(0) {
298 rows.push(format!("! ignored limit · a search returns {} at most", s.limit));
299 }
300 if run.is_empty() {
301 return Ok(nothing_searched(&s, &what, rows));
302 }
303 let job = c.job_of(&cmd.raw).map_err(cache_write)?;
304 let served = found.as_ref().map_or("", |f| f.0.spec().name);
305 let meta = search_meta(&s, run.iter().map(Hop::row).collect(), served, t0);
306 let o = match found {
307 Some((_, hits)) => listed(c, job, meta, &hits)?,
308 None => c
310 .serp_put(job, &meta, fetch::error_text(&run).as_deref())
311 .map_err(cache_write)
312 .and_then(|()| search_out(c, cmd, job, &meta))?,
313 };
314 let mut o = prefetched(c, cmd, job, o);
315 o.warn(rows);
316 Ok(o)
317}
318
319const PATIENCE: Duration = provider::SEARCH_TIMEOUT.saturating_mul(2);
321
322fn searching(c: &mut Cache, cmd: &Cmd) -> Result<Out, Out> {
327 let job = c.job_of(&cmd.raw).map_err(cache_write)?;
328 detach(format!("j{job}"), &c.root.join(&c.session).join(format!("run/j{job}.log")), None).map_err(cache_write)?;
329 poll_until(c.born, wait_of(cmd), || c.serp(job).is_some());
330 match c.serp(job) {
331 Some(m) if m.ok => Ok(serp_list(c, job, 0, true)),
332 Some(m) => search_out(c, cmd, job, &m),
333 None => Ok(search_pending(c, job).unwrap_or_default()),
334 }
335}
336
337fn search_pending(c: &Cache, job: usize) -> Option<Out> {
339 let j = c.job(job)?;
340 let q = Some(parse(std::slice::from_ref(&j.cmd))).filter(is_search).and_then(|cmd| search_of(&cmd).ok())?.q;
341 let age = (now() - j.t).max(0.0);
342 let row = format!("= j{job} pending {age:.0}s search \"{q}\" → {}", poll_next(&format!("j{job}"), 0));
343 (c.serp(job).is_none() && age < PATIENCE.as_secs_f64()).then(|| waiting(row, format!("j{job}")))
344}
345
346fn github(cmd: &Cmd, c: &mut Cache, s: &Search, t0: Instant) -> Result<Out, Out> {
349 let wait = wait_of(cmd);
350 let got = provider::all_within(vec![provider::gh_repos(s.q.clone(), s.limit)], wait).pop().flatten();
351 let got = got.unwrap_or_else(|| Err(provider::late(wait)));
352 let job = c.job_of(&cmd.raw).map_err(cache_write)?;
353 let calls = got.as_ref().map_or_else(|f| vec![(f.code, f.why.clone())], |(_, calls)| calls.clone());
355 let gh = HopRow { provider: "gh".into(), ms: t0.elapsed().as_millis() as u64, ..Default::default() };
356 let hops = calls.into_iter().map(|(code, why)| HopRow { code: code.into(), why, ..gh.clone() });
357 let meta = search_meta(s, hops.collect(), if got.is_ok() { "github" } else { "" }, t0);
358 let fail = match got {
359 Ok((hits, _)) => return listed(c, job, meta, &hits).map(|o| prefetched(c, cmd, job, o)),
360 Err(fail) => fail,
361 };
362 c.serp_put(job, &meta, Some(&fail.body)).map_err(cache_write)?;
363 search_out(c, cmd, job, &meta).and_then(Err) }
365
366fn prefetched(c: &mut Cache, cmd: &Cmd, job: usize, mut o: Out) -> Out {
370 let open =
371 |(i, e): (usize, &Entry)| (e.job == Some(job) && e.serp && e.dir.is_empty()).then(|| (i + 1, e.url.clone()));
372 let top: Vec<(usize, String)> = c.st.u.iter().enumerate().filter_map(open).take(prefetch_n(cmd)).collect();
373 let mut queued = Vec::new();
374 for (n, url) in &top {
375 let want = Want { url, slot: Some(*n), ..Want::default() };
377 let free = c.lookup(url).is_none() && at_once(c, want, cmd).is_none();
378 queued.extend(free.then(|| reserve(c, Entry::default(), want, cmd).ok()).flatten().map(|n| (n, want)));
379 }
380 let ids: Vec<String> = queued.iter().map(|q| format!("u{}", q.0)).collect();
382 if !ids.is_empty() && launch(c, &queued, cmd).is_ok() {
383 let row =
384 format!("prefetching {} free, plain only (detached; fetch:0 = none) · status: {}", ids.join(" "), bin());
385 o.lines.insert(o.lines.len() - 1, row);
386 o.set("prefetch", ids);
387 }
388 o
389}
390
391pub const PREFETCH: usize = 1;
393
394fn prefetch_n(cmd: &Cmd) -> usize {
395 cmd.get("fetch").and_then(|v| v.parse().ok()).unwrap_or(PREFETCH)
396}
397
398fn on_site(hits: &mut Vec<Hit>, host: &str) -> Vec<String> {
401 let n = hits.len();
402 hits.retain(|h| format!(".{}", host_of(&h.url)).ends_with(&format!(".{host}")));
404 let gone = n - hits.len();
405 (gone > 0).then(|| format!("! dropped {gone} off-site · not on {host}")).into_iter().collect()
406}
407
408fn is_prefetch(r: &Detached) -> bool {
410 is_search(&parse(std::slice::from_ref(&r.cmd)))
411}
412
413fn nothing_searched(s: &Search, what: &str, mut rows: Vec<String>) -> Out {
416 let code = if s.plan.keys.is_empty() { "no_key" } else { "budget_hit" };
417 let eq = format!("= ! {code} {what} · no search provider can run · 0ms spent $0");
418 let first = if rows.is_empty() { bang("", code, "", &At::default()) } else { rows.remove(0) };
419 let mut o = Out::fail(code, eq, first);
420 o.warn(rows);
421 o
422}
423
424fn search_meta(s: &Search, hops: Vec<HopRow>, served: &str, t0: Instant) -> Meta {
427 Meta {
428 url: format!("search:{}", s.q),
429 provider: served.into(),
430 ms: t0.elapsed().as_millis() as u64,
431 cost: provider::spend(hops.iter().map(|h| h.cost)),
432 ok: !served.is_empty(),
433 code: hops.last().map(|h| h.code.clone()).unwrap_or_default(),
434 t: now(),
435 kind: "serp".into(),
436 hops,
437 country: s.country.clone().unwrap_or_default(),
438 ..Default::default()
439 }
440}
441
442fn search_out(c: &Cache, cmd: &Cmd, job: usize, m: &Meta) -> Result<Out, Out> {
444 let q = m.url.strip_prefix("search:").unwrap_or(&m.url);
445 let detail = format!("· tried {} · {}ms spent {}", m.tried(), m.ms, provider::bill(m.cost, m.upto()));
446 let last = m.hops.last();
449 let arg = match m.code.as_str() {
450 "provider_timeout" if last.is_some_and(|h| h.why.starts_with("wait:")) => "wait:30",
451 "provider_timeout" if last.is_some_and(|h| h.ms < 30_000) => "timeout:30",
452 _ => "",
453 };
454 let (id, done) = (cmd.canon(), fetch::spent(m, &[], &fetch::keyed()));
455 let at = At { id: &id, arg, done: &done, ..At::default() };
456 let (who, owners) = fetch::fail_detail(m, "");
457 let n = fetch::fail_count(m, c.serps().iter().filter(|s| s.0 != job).map(|s| &s.1), Some(arg));
459 let next = if n.is_some() { String::new() } else { fix(&m.code, &at) };
460 let what = format!("{who}{}", n.unwrap_or_default()).trim_start().into();
461 let row = Flag { code: m.code.clone(), what, next, row: true }.bang("") + &provider::pages(&m.code, owners);
462 Ok(Out::fail(&m.code, format!("= ! {} j{job} search \"{q}\" {detail}", m.code), row))
463}
464
465fn listed(c: &mut Cache, job: usize, mut m: Meta, hits: &[Hit]) -> Result<Out, Out> {
467 let es: Vec<Entry> =
468 hits.iter().map(|h| Entry { url: h.url.clone(), job: Some(job), serp: true, ..Entry::default() }).collect();
469 let first = c.alloc(es, None).map_err(cache_write)?;
470 m.extra.insert("first".into(), first.into());
471 m.extra.insert("hits".into(), serde_json::to_value(hits).unwrap_or_default());
472 c.serp_put(job, &m, None).map_err(cache_write)?;
473 Ok(serp_list(c, job, 0, true))
474}
475
476fn searched(rec: &Meta) -> String {
478 let cc = if rec.country.is_empty() { String::new() } else { format!(" {}", rec.country) };
479 let gh = rec.provider == "github";
482 let tried = if rec.hops.len() > 1 && !gh { format!(" after {}", rec.tried()) } else { String::new() };
483 let mut note: String = rec.hops.iter().filter(|h| gh && h.code != "ok").map(|h| h.why.as_str()).collect();
484 note += if gh && settings::key("gh").is_none() { " · no token: 10 searches/min" } else { "" };
485 let usd = provider::bill(rec.cost, rec.upto());
486 format!("{}{cc}{tried}{note} · {:.1}s · spent {usd}", rec.provider, rec.ms as f64 / 1e3)
487}
488
489fn serp_list(c: &mut Cache, job: usize, off: usize, new: bool) -> Out {
492 let b = bin();
493 let Some(rec) = c.serp(job) else { return Out::ask(format!("? j{job} has no search record · {b} <words>")) };
494 let hits: Vec<Hit> = rec.extra.get("hits").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
495 let first = rec.extra.get("first").and_then(|v| v.as_u64()).unwrap_or(1) as usize;
496 let query = rec.url.strip_prefix("search:").unwrap_or(&rec.url);
497 let (mut parts, mut rows) = (Vec::new(), Vec::new());
498 for (i, hit) in hits.iter().enumerate().skip(off) {
499 let n = first + i;
500 let snip = if hit.snippet.is_empty() { String::new() } else { format!(" — \"{}\"", short(&hit.snippet, 90)) };
501 let row = match rec.provider.as_str() {
502 "github" => format!("u{n} {} · {}", hit.title, hit.snippet),
504 _ => format!("u{n} {} {}{snip}", short(&hit.url, 40), short(&hit.title, 60)),
505 };
506 let row = if c.lookup(&hit.url).is_some() { format!("{row} · cached $0") } else { row };
509 let billed = new && i == off;
510 let mut part = Out::new(vec![row.clone()]);
511 part.set("i", i).set("id", format!("u{n}")).set("url", hit.url.clone()).set("cache", !new);
512 part.set("title", hit.title.clone()).set("snippet", hit.snippet.clone()).set("position", i + 1);
513 part.set("query", query).set("job", format!("j{job}")).set("provider", rec.provider.clone());
514 part.set("cost", if billed { rec.cost } else { 0.0 }).set("ms", if billed { rec.ms } else { 0 });
515 parts.push(part);
516 rows.push(row);
517 }
518 let n = c.job(job).and_then(|j| parse(&[j.cmd]).count("limit")).map(|n| n.min(provider::SEARCH_MAX));
521 let (mut lines, cap) = (Vec::new(), settings::limit::<usize>(if n.is_some() { "read_cap" } else { "list_cap" }));
522 let next = off + outline::cap_rows(&mut lines, &rows, 0, (cap, 1, n));
523 let cut = n.filter(|&n| lines.len() < n && next < hits.len());
524 let cut = cut.map_or(String::new(), |n| format!(" of limit:{n} ({cap} tok cap)"));
525 let total = hits.len();
526 let how = if new { searched(&rec) } else { format!("cache {}", outline::fmt_age((now() - rec.t).max(0.0))) };
527 let shown = match (off, lines.len()) {
528 (0, count) if count == total => String::new(),
529 (_, 0) => " · all shown".into(),
530 (_, count) => format!(" · {count} shown u{}-u{}{cut}", first + off, first + off + count - 1),
532 };
533 let mut head = vec![format!("= j{job} search \"{query}\" · {total} results{shown} · {how}")];
534 head.append(&mut lines);
535 let at = first + off.min(total.saturating_sub(1));
536 head.push(match (total, next < total) {
537 (0, _) if query.starts_with("site:") => format!("no on-site results · try without site: → {b} <words>"),
538 (0, _) => format!("no results · fewer words: {b} <words>"),
539 (_, true) => format!("open one: {b} u{at} · filter: {b} u{at} <words> · more: {b} more"),
540 (_, false) => format!("open one: {b} u{at} · filter: {b} u{at} <words>"),
541 });
542 if total > 0 {
543 c.st.cursor = Some(Cursor { u: at, serp: Some((job, next)), ..Cursor::default() });
544 }
545 let mut o = Out::new(head);
546 o.set("id", format!("j{job}")).set("provider", rec.provider.clone()).set("query", query).set("results", total);
547 o.set("cost", if new { rec.cost } else { 0.0 }).set("ms", if new { rec.ms } else { 0 }).set("cache", !new);
548 o.parts = parts;
549 o
550}
551
552fn search_dry(cmd: &Cmd, c: &Cache) -> Result<Out, Out> {
554 let search = search_of(cmd)?;
555 let (runs, max) = fetch::route(&search.plan);
556 let cc = search.country.as_ref().map(|cc| format!(" · country:{cc}")).unwrap_or_default();
557 let off = settings::get().offline.value;
558 let (q, lim, nokey) = (&search.q, search.limit, nokey_row(&search.plan));
559 let (via, wait) = (path_of(&runs), wait_of(cmd).as_secs());
560 let new = format!("new u{}-u{}", c.st.u.len() + 1, c.st.u.len() + lim);
561 let line = match (runs.is_empty(), off) {
562 (_, true) => format!("search \"{q}\" · $0 · ! offline → {}", fix("offline", &At::default())),
563 _ if search.gh => format!("search github \"{q}\" by stars · limit:{lim} → {new} · $0"),
564 (true, _) => format!("search \"{q}\" · nothing can search · $0{nokey}"),
565 _ => format!("search \"{q}\" via {via} · limit:{lim}{cc} · wait:{wait}s → {new} · up to ${max:.4}{nokey}"),
566 };
567 let n = prefetch_n(cmd).min(search.limit);
568 let pre = format!("then fetch:{n} prefetches the top {n} detached · free, plain only");
569 let mut o = Out::new(vec![
570 format!("= dry {} · spends nothing now", cmd.canon()),
571 line,
572 fetch::hedges(cmd.get("hedge")),
573 format!("run it: {} {}", bin(), cmd.with_mod("dry", None)),
574 ]);
575 if n > 0 && !runs.is_empty() && !off {
576 o.lines.insert(2, pre);
577 }
578 o.set("cost", 0.0).set("dry", true);
579 Ok(o)
580}
581
582fn nokey_row(p: &Plan) -> String {
585 let paid = p.keys.iter().any(|t| *t != Tier::Plain);
586 let asked = |t: &Tier| matches!(p.mode, fetch::Mode::Only(o) if o.owner() == t.owner());
587 let left: Vec<Tier> = p.ladder(&[]).into_iter().filter(|t| !paid || asked(t)).collect();
588 fetch::no_key(p, &left, "", false).iter().map(|r| format!(" · {r}")).collect()
589}
590
591fn plan_of(cmd: &Cmd, url: Option<&str>) -> Plan {
593 let mut p = Plan::of(cmd, url);
594 p.prefetch = url.is_some() && is_search(cmd);
595 if settings::get().offline.value {
596 p.keys.clear();
597 }
598 p
599}
600
601pub fn path_of(route: &[(Tier, Option<Duration>)]) -> String {
605 let gate = route.iter().any(|r| r.1.is_some()) && route.first().is_some_and(|r| r.0 == Tier::Plain);
606 let step = |(i, (t, hedge)): (usize, &(Tier, Option<Duration>))| match (i, hedge) {
607 (0, _) => t.spec().short.to_string(),
608 (_, Some(d)) => format!(" ∥ {} after {}s", t.spec().short, d.as_secs_f64()),
609 (_, None) if route[..i].iter().any(|r| r.0 == *t) => format!(" → {} retry", t.spec().short),
610 (_, None) => format!(" → {}{}", t.spec().short, if !t.can("js") && gate { " (after a captcha)" } else { "" }),
612 };
613 route.iter().enumerate().map(step).collect()
614}
615
616pub fn plan(cmd: &Cmd, c: &Cache) -> Out {
618 if cmd.has("account") {
619 return stats::account_dry(c, cmd.flag("fresh"));
620 }
621 if !cmd.sub.is_empty() && cmd.get("zone").is_none() {
622 return stats::change(cmd);
623 }
624 if cmd.has("setup") {
625 return stats::setup(cmd.get("zone"), true, wait_of(cmd));
626 }
627 if is_search(cmd) {
628 return merged(search_dry(cmd, c));
629 }
630 let mut dry = Dry { cmd, c, next: c.st.u.len(), refused: 0, total: 0.0 };
631 let mut lines = vec![format!("= dry {} · spends nothing now", cmd.canon())];
632 for f in &cmd.files {
634 let size = match fenced(f, &crate::lang::local_path(f)) {
635 Err((code, _)) => Err(code),
636 Ok(_) if f == "-" => Ok(0),
637 Ok(real) => real.and_then(std::fs::metadata).map(|m| m.len()).map_err(|_| "no_file"),
638 };
639 dry.refused += usize::from(size.is_err());
640 lines.push(match size {
641 Ok(n) => format!("{f} {}B local → clean → outline → {} · $0", ksize(n as usize), dry.to(None)),
642 Err(code) => format!("! {code} {f} · $0"),
643 });
644 }
645 for (i, u) in cmd.urls.iter().enumerate() {
646 let twice = cmd.urls[..i].contains(u).then(|| format!("{} (same as above) · $0", short(u, 60)));
648 lines.push(twice.unwrap_or_else(|| dry.would(&short(u, 60), u, None)));
649 }
650 if cmd.urls.len() > 1 {
652 let cap = plan_of(cmd, None).cap;
653 lines.push(format!("batch up to ${:.4} · cap ${cap:.4}", dry.total.min(cap)));
654 }
655 let cur = c.st.cursor.clone().unwrap_or_default();
656 let ids = match (&cmd.ids[..], cur.u) {
657 ([], u) if u > 0 && cmd.urls.is_empty() && cmd.files.is_empty() => vec![Id { u, ..Id::default() }],
658 (ids, _) => ids.to_vec(),
659 };
660 if let Some(id) = ids.iter().find(|i| load(c, i).is_none()) {
662 return unknown(c, id);
663 }
664 for id in &ids {
665 lines.push(dry.id_row(id));
666 }
667 let none = dry.refused > 0 && dry.refused == lines.len() - 1;
669 if !none {
670 lines.push(fetch::hedges(cmd.get("hedge")));
671 lines.push(format!("run it: {} {}", bin(), cmd.with_mod("dry", None)));
672 }
673 let mut o = Out::new(lines);
674 o.rc = i32::from(none);
675 o.set("cost", 0.0).set("dry", true);
676 o
677}
678
679struct Dry<'a> {
681 cmd: &'a Cmd,
682 c: &'a Cache,
683 next: usize,
685 refused: usize,
687 total: f64,
689}
690
691impl Dry<'_> {
692 fn to(&mut self, slot: Option<usize>) -> String {
694 self.next += usize::from(slot.is_none());
695 slot.map_or_else(|| format!("new u{}", self.next), |n| format!("fills u{n}"))
696 }
697
698 fn would(&mut self, what: &str, u: &str, slot: Option<usize>) -> String {
700 if let Some(n) = render_of(self.c, u, self.cmd) {
701 return format!("{what} = u{n} (rendered, cache) · $0");
702 }
703 if let Some((_, age)) = self.c.lookup(u).filter(|_| !self.cmd.fresh()) {
704 return format!("{what} cache hit, cache {} → {} · $0", outline::fmt_age(age), self.to(slot));
705 }
706 if provider::private_host(u) {
707 self.refused += 1;
708 return format!("{what} ! private_address → {}", fix("private_address", &At { url: u, ..At::default() }));
709 }
710 let mut p = plan_of(self.cmd, Some(u));
711 fetch::route_of(self.c, u, &mut p);
712 let (tiers, cost) = fetch::route(&p);
713 if settings::get().offline.value {
714 return format!("{what} not cached → ! offline (FATS_OFFLINE) · $0");
715 }
716 if !crate::lang::real_host(u) {
720 self.refused += 1;
721 let (host, to, id) = (host_of(u), fix("no_host", &At { id: u, url: u, ..At::default() }), self.to(slot));
723 return format!("{what} ! no_host {host} · {id} · $0 → {to}");
724 }
725 let nokey = nokey_row(&p);
726 if tiers.is_empty() {
727 return format!("{what} not cached · nothing can fetch it · {} · $0{nokey}", self.to(slot));
729 }
730 let to = self.to(slot);
731 let mods = dry_mods(self.cmd, u, &tiers);
732 let off = if p.hedged() { "" } else { " · hedge:off, one provider at a time" };
734 let quote = if p.js { format!(" · {}", fetch::JS_QUOTE) } else { String::new() };
735 self.total += cost;
736 format!("{what} fetch {} → {to} · up to ${cost:.4}{quote}{off}{mods}{nokey}", path_of(&tiers))
737 }
738
739 fn id_row(&mut self, i: &Id) -> String {
741 let (cmd, c, page) = (self.cmd, self.c, i.page());
742 if let Some(&li) = cmd.links.first() {
743 let link = load(c, i).and_then(|l| l.doc.ok()).and_then(|d| d.links.get(li.wrapping_sub(1)).cloned());
744 return match link {
745 Some(u) => self.would(&format!("{page}{} l{li} {}", i.sec_tail(), short(&u, 60)), &u, None),
746 None => format!("{page}{} l{li} unknown · $0", i.sec_tail()),
747 };
748 }
749 let again = cmd.fresh().then(|| load(c, i)).flatten().map(|l| l.meta.url).filter(|u| u.starts_with("http"));
752 let ran = pending(c, i.u, &[]).is_some_and(|o| o.rc == 0 || !cmd.fresh());
754 match c.st.result(i.u).filter(|e| i.job.is_none() && !ran && (e.dir.is_empty() || cmd.fresh())) {
755 Some(e) => self.would(&format!("{page} {} (search result)", short(&e.url, 60)), &e.url, Some(i.u)),
756 None if let Some(u) = again => self.would(&format!("{page} {}", short(&u, 60)), &u, None),
757 None => format!("{page} local read · $0"),
758 }
759 }
760}
761
762fn dry_mods(cmd: &Cmd, u: &str, tiers: &[(Tier, Option<Duration>)]) -> String {
764 let ask = Ask { url: u.into(), country: cmd.get("country").map(String::from), ..Ask::default() };
765 let paid = tiers.iter().any(|t| t.0 != Tier::Plain);
766 let from = if cmd.get("country").is_none() { " (from the domain)" } else { "" };
767 let country = provider::sent(&ask, Tier::Bd).filter(|_| paid).map(|cc| format!(" · country:{cc}{from}"));
768 let device = match cmd.get("device") {
769 Some("mobile") => " · device:mobile (oxy, decodo; bd serves desktop)",
770 _ => "",
771 };
772 country.unwrap_or_default() + device
773}
774
775fn job_read(cmd: &Cmd, c: &mut Cache, j: usize) -> Out {
778 poll_until(c.born, wait_of(cmd), || search_pending(c, j).is_none());
779 c.reload();
780 let failed = c.serp(j).filter(|m| !m.ok).zip(c.job(j)).map(|(m, x)| search_out(c, &parse(&[x.cmd]), j, &m));
781 let mut o = failed.map(merged).or_else(|| search_pending(c, j)).unwrap_or_else(|| job_view(c, j));
782 if !cmd.words.is_empty() {
783 let q = cmd.words.join(" ");
784 o.warn(vec![format!("j{j} ! not_in_v1 multi-page filter → {} j{j}.u1 {q}", bin())]);
785 }
786 o
787}
788
789fn nothing_to_do(cmd: &Cmd, u: usize) -> Out {
791 let (b, list) = (bin(), WORDS.lists.iter().chain(&["media", "comments"]).find(|w| cmd.has(w)));
792 let page = list.map(|w| format!("? {w} needs a page: {b} u{} {w}", u.max(1)));
793 Out::ask(page.unwrap_or(format!("? nothing to do · {b} <url> · {b} u1#2 · {b} u1 <words>")))
794}
795
796fn dispatch(cmd: &Cmd, c: &mut Cache) -> Out {
797 let b = bin();
798 if let Some(o) = command(cmd, c) {
799 return o;
800 }
801 if let Some(&j) = cmd.jobs.first()
802 && cmd.ids.is_empty()
803 && cmd.urls.is_empty()
804 && cmd.files.is_empty()
805 {
806 return job_read(cmd, c, j);
807 }
808 let one = match (cmd.files.as_slice(), page_url(cmd), cmd.words.is_empty()) {
809 ([f], None, false) if cmd.urls.is_empty() => Some(local(c, f, cmd)),
810 ([], Some(u), false) => Some(fetch(c, Want { url: u, ..Want::default() }, cmd)),
811 _ => None,
812 };
813 if let Some(o) = one {
814 let o = merged(o);
816 return match (o.rc, c.st.cursor.clone(), o.rec.contains_key("pending")) {
817 (0, Some(cur), false) => dispatch_one(cmd, c, &cur, Id { u: cur.u, ..Id::default() }, true),
818 _ => o,
819 };
820 }
821 if is_search(cmd) {
822 return merged(web(cmd, c));
824 }
825 if !cmd.files.is_empty() || !cmd.urls.is_empty() {
826 return fetch_all(cmd, c);
827 }
828 let cur = c.st.cursor.clone().unwrap_or_default();
829 let mut ids = cmd.ids.clone();
830 if ids.is_empty() && (!cmd.links.is_empty() || cmd.has("more") || cmd.has("up")) {
831 if cur.u == 0 {
832 return Out::ask(format!("? no current page · {b} <url> first"));
833 }
834 if let Some((j, off)) = cur.serp.filter(|_| cmd.links.is_empty() && cmd.has("more")) {
836 return serp_list(c, j, off, false);
837 }
838 ids.push(Id { u: cur.u, ..Id::default() });
839 }
840 let Some(id) = ids.first().cloned() else { return nothing_to_do(cmd, cur.u) };
841 let q = cmd.words.join(" ");
843 let what = if q.is_empty() { "read" } else { "filter" };
844 let row = |p: String| format!("{p} ! not_in_v1 multi-page {what} → {}", format!("{b} {p} {q}").trim_end());
845 let rest: Vec<String> = ids[1..].iter().map(|i| row(i.page())).collect();
846 let mut out = dispatch_one(cmd, c, &cur, id, false);
847 out.warn(rest);
848 out
849}
850
851fn command(cmd: &Cmd, c: &mut Cache) -> Option<Out> {
855 let b = bin();
856 Some(match () {
857 _ if cmd.idle || cmd.has("status") => stats::status(c),
858 _ if cmd.has("version") => {
859 Out::new(vec![format!("= {b} {} · status: {b} · {}", env!("CARGO_PKG_VERSION"), to_guide())])
860 }
861 _ if cmd.has("stats") => stats::stats(c, cmd, json_of(cmd)),
862 _ if cmd.has("telemetry") => crate::telemetry::show(),
863 _ if cmd.has("setup") && cmd.sub == ["telemetry"] => Out::new(crate::telemetry::row()),
864 _ if !cmd.sub.is_empty() && cmd.get("zone").is_none() => stats::change(cmd),
865 _ if cmd.has("config") => stats::config(),
866 _ if cmd.has("account") => stats::account(c, cmd.flag("fresh"), wait_of(cmd)),
867 _ if cmd.has("setup") => stats::setup(cmd.get("zone"), settings::get().offline.value, wait_of(cmd)),
868 _ if cmd.has("routes") => {
870 Out::ask(format!("? routes: gone (no learned starts) · a page's route: {b} <url> dry:true · {b} config"))
871 }
872 _ if cmd.has("help") => Out::new(CARD.lines().map(String::from).chain([to_guide()]).collect()),
873 _ if cmd.has("guide") => Out::new(GUIDE.lines().map(String::from).collect()),
874 _ => return None,
875 })
876}
877
878fn dispatch_one(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: Id, new: bool) -> Out {
880 let mine = id.job.is_none_or(|j| c.job(j).is_some_and(|x| x.session == c.session));
881 let live = mine && c.run(id.u).is_some_and(|(r, alive)| alive && r.done.is_none());
885 let ended = live && wait_for(c, id.u, wait_of(cmd)).is_some();
886 if ended {
887 c.reload();
888 }
889 let refetch = cmd.fresh() && cmd.links.is_empty() && cmd.media.is_empty() && !new && !ended;
890 if let Some(o) = pending(c, id.u, &cmd.words).filter(|o| mine && (o.rc == 0 || !refetch)) {
891 return o;
892 }
893 let missed = || c.run(id.u).is_some_and(|(r, _)| r.done.as_ref().is_some_and(|d| !d.ok) && is_prefetch(&r));
896 let again = refetch || (!cmd.ids.is_empty() && missed());
897 if let Some(url) = c.st.result(id.u).filter(|e| mine && (e.dir.is_empty() || again)).map(|e| e.url.clone()) {
898 return open_result(cmd, c, cur, id, &url);
899 }
900 if refetch {
901 return fetch_again(cmd, c, &id);
902 }
903 if let Some(&li) = cmd.links.first() {
904 return open_link(cmd, c, &id, li);
905 }
906 if let Some(&k) = cmd.media.first() { asset(c, &id, k, cmd.fresh()) } else { read(cmd, c, cur, &id, new) }
907}
908
909pub const ASSET_MAX: u64 = 10_000_000;
912pub const ASSET_WAIT: Duration = Duration::from_secs(15);
913
914fn asset(c: &Cache, id: &Id, k: usize, fresh: bool) -> Out {
920 let Some(page) = load(c, id) else { return unknown(c, id) };
921 let media = page.doc.as_ref().map_or(&[][..], |d| &d.media[..]);
922 let (pic, rec) = (media.get(k.wrapping_sub(1)), page.dir.join("assets").join(format!("m{k}.json")));
923 let src = pic.map_or("", |p| p.src.as_str());
924 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());
926 let (new, got) = match (pic, kept) {
927 (None, _) => (true, Err(("no_media".into(), format!("· the page lists {}", media.len())))),
928 (_, Some(a)) => (false, Ok(a)),
929 _ => (true, download(&rec, src)),
930 };
931 let subject = format!("{} m{k}", page.eq);
932 let a = match got {
933 Ok(a) => a,
934 Err((code, what)) => {
935 let at = At { id: &page.pid, url: src, arg: &format!("m{k}"), done: &["max_bytes:64m"] };
936 let row = bang(&format!("{} m{k}", page.pid), &code, &what, &at);
937 return Out::fail(&code, format!("= {subject} ! {code} {what}"), row);
938 }
939 };
940 let (kind, path) = (if pic.is_some_and(|p| p.video) { "poster" } else { "photo" }, rec.with_extension(&a.ext));
941 let (ext, bytes, path) = (&a.ext, ksize(a.bytes as usize), path.display());
942 let [lo, hi] = [outline::STD, outline::HI_RES].map(|t| ksize(outline::viewed(a.w, a.h, t).1 as usize));
944 let lo = if lo == hi { String::new() } else { lo.replace('k', "") + "–" };
945 let view = if a.w == 0 { "size unread, view cost unknown".into() } else { format!("~{lo}{hi} tok if viewed") };
946 let how = if new { format!("plain {}ms $0", a.ms) } else { format!("cache {}", outline::fmt_age(now() - a.t)) };
947 let mut o =
948 Out::new(vec![format!("= {subject} {kind} {}x{} {ext} {bytes}B · saved {path} · {view} · {how}", a.w, a.h)]);
949 o.set("id", page.eq).set("image", path.to_string()).set("cost", 0.0).set("cache", !new);
950 o
951}
952
953fn download(rec: &Path, src: &str) -> Result<Asset, (String, String)> {
957 let err = |code: &str, what: String| (code.to_string(), what);
958 if settings::get().offline.value {
959 return Err(err("offline", "FATS_OFFLINE is on".into()));
960 }
961 let (_turn, t0) = (provider::pace(src), Instant::now());
962 let ask = Ask { url: src.into(), timeout: Some(ASSET_WAIT), max_bytes: ASSET_MAX, html: true, ..Ask::default() };
963 let got = provider::block(provider::get(Tier::Plain, &ask, "")).map_or(Err("net_error".into()), |g| g.0);
964 let raw = got.map_err(|f| match f.code {
965 "too_big" => err(f.code, format!("{} (>{}B)", f.why, ksize(ASSET_MAX as usize)).trim_start().into()),
966 code => err(code, f.why),
967 })?;
968 let ctype = raw.ctype.split(';').next().unwrap_or_default().trim().to_string();
969 match raw.status {
970 200..300 if ctype.starts_with("image/") => {}
971 200..300 => return Err(err("not_image", if ctype.is_empty() { "no content-type".into() } else { ctype })),
972 s @ (403 | 410) => return Err(err(&format!("http_{s}"), "· signed link expired or hotlink-blocked".into())),
973 s => return Err(err(&format!("http_{s}"), String::new())),
974 }
975 let reader = image::ImageReader::new(std::io::Cursor::new(&raw.body)).with_guessed_format().ok();
976 let (w, h) = reader.and_then(|r| r.into_dimensions().ok()).unwrap_or_default();
977 let ext = image::ImageFormat::from_mime_type(&ctype).map_or("img", |f| f.extensions_str()[0]);
978 let file = rec.with_extension(ext);
979 let write = |e: std::io::Error| err("cache_write", format!("{}: {e}", file.display()));
980 std::fs::create_dir_all(rec.parent().unwrap_or(rec)).map_err(write)?;
981 std::fs::write(&file, &raw.body).map_err(write)?;
982 let (bytes, ms) = (raw.body.len() as u64, t0.elapsed().as_millis() as u64);
983 let a = Asset { src: src.into(), ext: ext.into(), bytes, ms, t: now(), w, h };
984 crate::cache::jsave(rec, &a).map_err(|e| err("cache_write", e))?;
985 Ok(a)
986}
987
988fn open_result(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: Id, url: &str) -> Out {
989 let o = merged(fetch(c, Want { url, slot: Some(id.u), ..Want::default() }, cmd));
990 let open = cmd.words.is_empty() && cmd.links.is_empty() && cmd.media.is_empty() && cmd.reserved.is_empty();
991 let open = open && id.sec.is_none();
992 if o.rc != 0 || open || c.st.result(id.u).is_some_and(|e| e.dir.is_empty()) {
993 return o;
994 }
995 let mut out = dispatch_one(cmd, c, cur, id, true);
996 let warn = o.rec.get("warnings").and_then(|w| w.as_array()).into_iter().flatten();
997 out.warn(warn.filter_map(|w| w.as_str().map(String::from)).collect());
998 out
999}
1000
1001fn refetch(c: &mut Cache, cmd: &Cmd, url: &str, from: &str) -> Out {
1003 merged(fetch(c, Want { url, prov: Some(from), slot: None }, cmd))
1004}
1005
1006fn fetch_again(cmd: &Cmd, c: &mut Cache, id: &Id) -> Out {
1008 let Some(l) = load(c, id) else { return unknown(c, id) };
1009 match l.meta.url.strip_prefix("file://") {
1010 Some(f) => merged(local(c, f, cmd)),
1011 None if l.meta.url == "stdin:" => {
1012 Out::ask(format!("? {} came from stdin · pipe it again: … | {} -", l.pid, bin()))
1013 }
1014 None if l.meta.url.is_empty() => no_doc(&l.pid, &l.eq, &l.meta, &[], &NoDoc::Missing, None), None => refetch(c, cmd, &l.meta.url, &format!("{} fresh", l.pid)),
1016 }
1017}
1018
1019fn open_link(cmd: &Cmd, c: &mut Cache, id: &Id, li: usize) -> Out {
1021 let Some(l) = load(c, id) else { return unknown(c, id) };
1022 let doc = match &l.doc {
1023 Ok(d) => d,
1024 Err(why) => return no_doc(&l.pid, &l.eq, &l.meta, &[], why, None),
1025 };
1026 let sec = id.sec_tail();
1027 match li.checked_sub(1).and_then(|i| doc.links.get(i)) {
1028 Some(u) => refetch(c, cmd, u, &format!("{}{sec} l{li}", l.pid)),
1029 None => {
1030 let n = doc.links.len();
1031 let have = if n == 0 { "no links".into() } else { format!("have l1-l{n}") };
1032 Out::ask(format!("? l{li} unknown on {} · {have} · {} {} links", l.pid, bin(), l.pid))
1033 }
1034 }
1035}
1036
1037fn read(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: &Id, new: bool) -> Out {
1039 let named = |m: &Match| cmd.get("match") == Some(m.name());
1040 let rung = [Match::Exact, Match::Near, Match::Topic].into_iter().find(named).unwrap_or(Match::Words);
1041 let pinned = cmd.get("match").is_some();
1042 let more = cmd.has("more") && cur.u == id.u && id.job.is_none();
1043 let (from, limit) = (cmd.count("from").map_or(0, |n| n.saturating_sub(1)), cmd.count("limit"));
1044 page_cmd(c, id, new, |p| {
1045 Ok(if let Some(kind) = WORDS.lists.iter().find(|w| cmd.has(w)) {
1046 outline::list(p, from, limit, &cmd.words, kind)
1047 } else if !cmd.words.is_empty() {
1048 search::grep(p, &cmd.words, (rung, pinned), id.sec, limit)?
1049 } else if cmd.has("all") {
1050 outline::outline_all(p)
1051 } else if cmd.has("media") {
1052 outline::media(p, from, limit)
1053 } else if cmd.has("comments") {
1054 outline::comments(p, id.sec, from, limit)
1055 } else if cmd.has("full") && (1..=p.doc.sections.len()).contains(&id.sec.unwrap_or(1)) || more && cur.full {
1056 outline::read_full(p, id.sec.or(cur.k.filter(|_| more)), if more && cur.full { cur.part + 1 } else { 0 })
1057 } else if let Some(k) = id.sec.or(cur.k.filter(|_| more)) {
1058 outline::read_sec(p, k, if more && cur.k == Some(k) { cur.part + 1 } else { id.part })?
1059 } else if cmd.has("more") {
1060 outline::outline_all(p)
1061 } else {
1062 outline::outline(p, None)
1063 })
1064 })
1065 .unwrap_or_else(|| unknown(c, id))
1066}
1067
1068fn refused(code: &str, subject: &str, what: &str, at: &At) -> Out {
1071 Out::fail(code, format!("= ! {code} {what}"), bang(subject, code, "", at))
1072}
1073
1074fn cache_write(e: impl std::fmt::Display) -> Out {
1076 refused("cache_write", "", &e.to_string(), &At::default())
1077}
1078
1079fn merged(r: Result<Out, Out>) -> Out {
1081 r.unwrap_or_else(|o| o)
1082}
1083
1084fn private(url: &str) -> Out {
1086 let what = format!("{} · loopback, private and link-local hosts are not fetched · 0ms spent $0", short(url, 60));
1087 refused("private_address", &short(url, 60), &what, &At { url, ..At::default() })
1088}
1089
1090fn offline(what: &str) -> Out {
1091 let detail = format!("{what} · not cached · FATS_OFFLINE is on: cache and local files only · 0ms spent $0");
1092 refused("offline", what, &detail, &At::default())
1093}
1094
1095fn job_view(c: &Cache, j: usize) -> Out {
1097 let b = bin();
1098 let (Some(job), Some((st, _))) = (c.job(j), ids_of(c, Some(j))) else {
1099 return unknown(c, &Id { job: Some(j), u: 1, ..Id::default() });
1100 };
1101 if job.cmd.is_empty() {
1102 return refused("expired", "", &format!("j{j} · its command and pages went after an hour"), &At::default());
1103 }
1104 let mine = st.u.iter().enumerate().filter(|(_, e)| e.job == Some(j));
1106 let rows: Vec<_> = mine.map(|(i, e)| stats::page_row(c, i + 1, e, &format!("j{j}.")).lean).collect();
1107 let age = outline::fmt_age((now() - job.t).max(0.0));
1108 let what = if st.u.iter().any(|e| e.job == Some(j) && e.serp) { "results" } else { "pages" };
1110 let mut lines = vec![format!("= j{j} {} {what} · {age} ago · s:{} · {b} {}", rows.len(), job.session, job.cmd)];
1111 let next = match rows.len() {
1112 0 => format!("no pages stored · rerun: {b} {}", job.cmd),
1113 _ => format!("open: {b} j{j}.u{}", st.u.iter().position(|e| e.job == Some(j)).map_or(1, |p| p + 1)),
1114 };
1115 lines.extend(rows);
1116 lines.push(next);
1117 Out::new(lines).with("id", format!("j{j}"))
1118}
1119
1120fn unknown(c: &Cache, id: &Id) -> Out {
1121 let b = bin();
1122 let last = Some(c.job_count()).filter(|&n| n > 0).map(|n| format!("last job j{n}"));
1123 let Some((st, _)) = ids_of(c, id.job) else {
1124 let last = last.unwrap_or("no jobs yet".into());
1125 return Out::ask(format!("? j{} unknown · {last} · {b} <url>", id.job.unwrap_or_default()));
1126 };
1127 let have = if st.u.is_empty() { "none".into() } else { format!("u1-u{}", st.u.len()) };
1128 Out::ask(format!("? {} unknown · have {have} · {}", id.page(), last.unwrap_or(format!("{b} <url>"))))
1129}
1130
1131struct Loaded {
1132 pid: String,
1133 eq: String,
1134 meta: Meta,
1135 doc: Result<Doc, NoDoc>,
1136 dir: std::path::PathBuf,
1137 other: bool,
1138}
1139
1140fn ids_of(c: &Cache, j: Option<usize>) -> Option<(State, bool)> {
1143 let Some(j) = j else { return Some((c.st.clone(), false)) };
1144 let s = c.job(j)?.session;
1145 let other = || c.dir(&Entry { dir: s.clone(), ..Entry::default() }).and_then(|d| jload(&d.join("state.json")));
1147 Some(if s == c.session { (c.st.clone(), false) } else { (other().unwrap_or_default(), true) })
1148}
1149
1150fn load(c: &Cache, id: &Id) -> Option<Loaded> {
1152 let (st, other) = ids_of(c, id.job)?;
1153 let e = st.u.get(id.u.checked_sub(1)?)?.clone();
1154 let (meta, doc) = c.page(&e);
1155 let pid = if other { id.page() } else { format!("u{}", id.u) };
1156 let eq = if other { pid.clone() } else { e.eq(id.u) };
1157 Some(Loaded { pid, eq, meta, doc, dir: c.dir(&e).unwrap_or_default(), other })
1158}
1159
1160type Copies = (Option<String>, bool, (Option<String>, bool));
1170pub(crate) fn copies(c: &Cache, n: usize, (meta, doc): (&Meta, &Doc), log: &[String]) -> Copies {
1171 let text = |d: &Doc| d.sections[..d.served()].iter().flat_map(|s| s.lines.clone()).collect::<Vec<_>>();
1172 let me = &c.st.u[n - 1];
1174 let paid = |m: &Meta| m.hedge == "off";
1175 let owner = |m: &Meta| Tier::parse(&m.provider).map(Tier::owner);
1176 let runs = c.st.u.iter().enumerate().filter(|(_, e)| e.dir == me.dir).filter_map(|(i, _)| c.run(i + 1));
1177 let asked = runs.into_iter().any(|(r, _)| parse(std::slice::from_ref(&r.cmd)).get("country").is_some());
1178 let mut found = (None, false, (None, asked));
1179 let bare = outline::shown(doc, meta).is_none() && outline::record_in(doc, meta, &[]).is_none();
1181 let starved = fetch::budget_row(meta, "", &[]).is_some();
1183 for (i, o) in c.st.u.iter().enumerate().filter(|(_, o)| o.url == me.url && !o.dir.is_empty() && o.dir != me.dir) {
1184 let (m, Ok(d)) = c.page(o) else { continue };
1185 let other = m.ok && (m.country != meta.country || owner(&m) != owner(meta));
1186 found.2.0 = found.2.0.or((i >= n && other).then(|| format!("u{}", i + 1)));
1187 let same = text(&d) == text(doc);
1188 found.1 |= same && (paid(&m) || paid(meta));
1189 let held = outline::shown(&d, &m).filter(|_| outline::shown(doc, meta).is_none());
1192 let rec = || outline::record_in(&d, &m, log).filter(|_| bare).map(|r| format!("u{}{r}", i + 1));
1193 found.0 = match held {
1194 _ if i >= n && m.ok && starved => Some(format!("u{}", i + 1)),
1195 _ if !same && (rendered(&m) || m.ok && paid(&m)) => Some(format!("u{} · rendered", i + 1)),
1196 Some(tail) => Some(format!("u{}{tail} · page content", i + 1)),
1197 None => found.0.or_else(rec),
1198 };
1199 }
1200 found
1201}
1202
1203fn page_cmd(c: &mut Cache, id: &Id, new: bool, f: impl FnOnce(&Page) -> Result<Shown, String>) -> Option<Out> {
1206 let Loaded { pid, eq, meta, doc, dir, other } = load(c, id)?;
1207 let (before, others) = c.st.u.get(id.u - 1).filter(|_| !other).map(|me| seen(c, me)).unwrap_or_default();
1208 let blank = Doc::default();
1210 let (render, again, fixed) = if other {
1211 (None, false, (None, false))
1212 } else {
1213 copies(c, id.u, (&meta, doc.as_ref().unwrap_or(&blank)), &before)
1214 };
1215 let doc = match doc {
1216 Ok(d) => d,
1217 Err(why) => return Some(no_doc(&pid, &eq, &meta, &others, &why, render)),
1218 };
1219 let age = (!new).then(|| (now() - meta.t).max(0.0));
1220 let key = id.sec.and_then(|k| outline::part_key(&doc, k, id.part));
1222 let read = std::iter::once(id.sec_tail()).chain(key.clone()).chain(before).collect();
1223 let p = Page { id: pid, eq, doc: &doc, meta: &meta, age, at: (read, render, again, fixed, others) };
1224 let (mut lines, cursor) = match f(&p) {
1225 Ok(s) => s,
1226 Err(q) => return Some(Out::ask(q)),
1227 };
1228 if let Some(l) = lines.first_mut().filter(|l| l.starts_with("= ")) {
1230 if let Some(a) = age {
1231 let age = format!("cache {}", outline::fmt_age(a));
1233 let age = if l.contains(&format!(" {age}")) { String::new() } else { format!(" · {age}") };
1234 l.push_str(&(age + &stale(c, id)));
1235 }
1236 l.push_str(&outline::flags(&p));
1237 }
1238 let mut o = Out::new(lines);
1239 record(&mut o, &p, &dir.to_string_lossy(), new);
1240 if id.sec.is_some() {
1241 o.set("id", format!("{}{}", p.eq, id.sec_tail())); }
1243 if id.sec.is_some()
1244 && !other
1245 && let Err(e) = c.read_mark(id.u, &[id.sec_tail()].into_iter().chain(key).collect::<Vec<_>>())
1246 {
1247 o = cache_write(e);
1248 }
1249 if let Some(mut cur) = cursor
1250 && !other
1251 {
1252 cur.u = id.u;
1253 c.st.cursor = Some(cur);
1254 }
1255 Some(o)
1256}
1257
1258fn seen(c: &Cache, me: &Entry) -> (Vec<String>, Vec<Meta>) {
1262 let copies = c.st.u.iter().filter(|e| !e.dir.is_empty() && (e.url == me.url || e.dir == me.dir));
1263 let read = copies.clone().flat_map(|e| e.read.iter().filter(|r| e.dir == me.dir || r.starts_with('=')).cloned());
1264 let others = copies.filter(|e| e.dir != me.dir).filter_map(|e| c.meta(&e.dir));
1265 (read.collect(), others.collect())
1266}
1267
1268fn stale(c: &Cache, id: &Id) -> String {
1272 let Some(j) = c.st.u.get(id.u.wrapping_sub(1)).and_then(|e| e.job).filter(|_| id.job.is_none()) else {
1273 return String::new();
1274 };
1275 let newer: std::collections::BTreeSet<usize> = c.st.u.iter().filter_map(|e| e.job).filter(|&k| k > j).collect();
1276 let s = if newer.len() == 1 { "" } else { "s" };
1277 newer.last().map_or(String::new(), |n| format!(" ({} job{s} ago; newest j{n})", newer.len()))
1278}
1279
1280fn record(o: &mut Out, p: &Page, path: &str, new: bool) {
1281 let m = p.meta;
1282 o.set("id", p.eq.clone())
1283 .set("url", p.doc.final_url.clone())
1284 .set("provider", m.provider.clone())
1285 .set("cost", if new { m.cost } else { 0.0 })
1286 .set("bytes_in", if new { m.bytes } else { 0 })
1287 .set("cache", !new)
1288 .set("age", (now() - m.t).max(0.0) as u64)
1289 .set("path", path.to_string())
1290 .set("mode", p.doc.mode.clone());
1291 if let Some((_, m)) = o.lines.first().and_then(|l| l.split_once("match:")) {
1292 o.set("match", m.to_string());
1293 }
1294}
1295
1296fn text_of_zip(path: &str) -> String {
1298 format!("unzip -p {path} '*.xml' | {} -", bin())
1299}
1300
1301pub(crate) fn no_doc(id: &str, eq: &str, m: &Meta, others: &[Meta], why: &NoDoc, served: Option<String>) -> Out {
1305 let url = short(&m.url, 60);
1306 let mut at = At { id, url: &m.url, ..At::default() };
1307 let (mut owners, mut next, newer) = (Vec::new(), None, served.is_some());
1308 let zip = if let NoDoc::Zip(path) = why { text_of_zip(&path.to_string_lossy()) } else { String::new() };
1309 let (code, what, detail) = match why {
1310 NoDoc::Zip(_) => {
1311 at.arg = &zip;
1312 let what =
1313 format!("zip (docx/xlsx) · {url} · {}B cached, no zip text in this build", ksize(m.bytes as usize));
1314 ("not_in_v1", what, format!("zip {url}"))
1315 }
1316 NoDoc::Parse(e) => ("parse_failed", format!("· {url} · {e}"), url.clone()),
1317 NoDoc::Missing if !m.ok => {
1318 let code = if m.code.is_empty() || m.code == "ok" { "fetch_failed" } else { &m.code };
1319 let what = format!("· {} · tried {} · {}ms spent ${:.4}", host_of(&m.url), m.tried(), m.ms, m.cost);
1320 let (detail, again, fix, named) = fetch::fail_row(m, others, &url, id, served.is_some());
1322 (owners, next) = (named, Some(served.map(|s| format!("{} {s}", bin())).or(fix).unwrap_or_default()));
1323 (code, what, detail + &again)
1324 }
1325 NoDoc::Missing if m.url.is_empty() => ("expired", "· its page and URL went after an hour".into(), "".into()),
1326 NoDoc::Missing => ("snapshot_missing", format!("· {url} · the cached body is gone"), url.clone()),
1327 };
1328 let next = next.unwrap_or_else(|| fix(code, &at));
1330 let row = Flag { code: code.into(), what: detail, next, row: true }.bang(id) + &provider::pages(code, owners);
1331 let budget = fetch::budget_row(m, id, others).filter(|_| !newer);
1334 let row = budget.map_or(row, |r| format!("{id} {r}"));
1335 let mut o = Out::fail(code, format!("= {eq} ! {code} {what}"), row);
1336 if let NoDoc::Zip(path) = why {
1337 o.set("kind", "zip").set("path", path.to_string_lossy().into_owned());
1338 }
1339 o
1340}
1341
1342fn fetch_all(cmd: &Cmd, c: &mut Cache) -> Out {
1348 let t0 = Instant::now();
1349 let want = |url| Want { url, ..Want::default() };
1350 let mut started: Vec<_> = cmd.files.iter().map(|f| Some(local(c, f, cmd).map(Err))).collect();
1351 let mut queued = Vec::new();
1352 for (i, u) in cmd.urls.iter().enumerate() {
1353 if cmd.urls[..i].contains(u) {
1354 started.push(None);
1355 continue;
1356 }
1357 let now = at_once(c, want(u), cmd).map(Err);
1358 let id = now.unwrap_or_else(|| reserve(c, Entry::default(), want(u), cmd).map(Ok).map_err(cache_write));
1359 if let Ok(Ok(n)) = id {
1360 queued.push((n, want(u)));
1361 }
1362 started.push(Some(id));
1363 }
1364 if let Err(e) = launch(c, &queued, cmd) {
1366 return cache_write(e);
1367 }
1368 let mut parts: Vec<Out> = Vec::new();
1369 for (i, (f, s)) in cmd.files.iter().chain(&cmd.urls).zip(started).enumerate() {
1370 let first = cmd.urls.iter().position(|u| u == f).and_then(|j| parts.get(cmd.files.len() + j));
1372 let mut o = match s {
1373 Some(s) => merged(s.and_then(|s| s.map_or_else(Ok, |n| finish(c, n, want(f), cmd)))),
1374 None => first.map_or_else(Out::default, same),
1375 };
1376 o.rec.entry("url").or_insert(f.as_str().into());
1377 o.rec.entry("ms").or_insert((t0.elapsed().as_millis() as u64).into());
1378 o.set("i", i);
1379 parts.push(o);
1380 }
1381 if parts.len() == 1 {
1382 return parts.pop().unwrap_or_default();
1383 }
1384 let pending = parts.iter().filter(|p| p.rec.contains_key("pending")).count();
1386 let ok = parts.iter().filter(|p| p.rc == 0).count() - pending;
1387 let mut fails = indexmap::IndexMap::<&str, usize>::new(); let errs =
1389 parts.iter().filter(|p| p.rc != 0).map(|p| p.rec.get("error").and_then(|v| v.as_str()).unwrap_or("failed"));
1390 errs.for_each(|e| *fails.entry(e).or_default() += 1);
1391 let pend = if pending > 0 { format!(" · {pending} pending") } else { String::new() };
1392 let fails: String = pend + &fails.iter().map(|(e, n)| format!(" · {n} ! {e}")).collect::<String>();
1393 let cost = parts.iter().filter_map(|p| p.rec.get("cost").and_then(|v| v.as_f64())).fold(0.0, |a, b| a + b);
1394 let (job, ms) = (c.job.map(|j| format!("j{j} ")).unwrap_or_default(), t0.elapsed().as_millis());
1395 let mut all = Out::new(vec![format!("= {job}{} inputs · {ok} ok{fails} · {ms}ms spent ${cost:.4}", parts.len())]);
1396 all.rc = if ok + pending > 0 { 0 } else { parts.iter().map(|p| p.rc).max().unwrap_or(1) };
1397 all.lines.extend(parts.iter().flat_map(|p| p.lines.iter().cloned()));
1398 all.set("id", c.job.map(|j| format!("j{j}")));
1399 all.parts = parts;
1400 all
1401}
1402
1403fn same(first: &Out) -> Out {
1405 let eq = first.lines.first().and_then(|l| l.split(' ').nth(1)).unwrap_or_default();
1406 let rec = Box::new(first.rec.iter().filter(|(k, _)| *k != "cost").map(|(k, v)| (k.clone(), v.clone())).collect());
1407 Out { lines: vec![format!("= {eq} (same as above)")], rc: first.rc, rec, parts: vec![] }
1408}
1409
1410#[derive(Clone, Copy, Default)]
1413struct Want<'a> {
1414 url: &'a str,
1415 prov: Option<&'a str>,
1416 slot: Option<usize>,
1417}
1418
1419fn fetch(c: &mut Cache, want: Want, cmd: &Cmd) -> Result<Out, Out> {
1424 let new = |c: &mut Cache| {
1425 let n = reserve(c, Entry::default(), want, cmd).map_err(cache_write)?;
1426 launch(c, &[(n, want)], cmd).map_err(cache_write).and_then(|()| finish(c, n, want, cmd))
1427 };
1428 at_once(c, want, cmd).map_or_else(|| new(c), Ok)
1429}
1430
1431fn reserve(c: &mut Cache, entry: Entry, want: Want, cmd: &Cmd) -> Result<usize, String> {
1434 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)?;
1435 c.alloc(vec![Entry { url: want.url.into(), job: Some(job), ..entry }], want.slot)
1436}
1437
1438fn at_once(c: &mut Cache, want: Want, cmd: &Cmd) -> Option<Out> {
1440 let url = want.url;
1441 let out = cached(c, url, want, cmd).or_else(|| running(c, url, &cmd.words));
1442 let out = out.or_else(|| provider::private_host(url).then(|| private(url)));
1443 out.or_else(|| settings::get().offline.value.then(|| offline(&short(url, 60))))
1444}
1445
1446fn finish(c: &mut Cache, n: usize, want: Want, cmd: &Cmd) -> Result<Out, Out> {
1448 let Some(done) = wait_for(c, n, wait_of(cmd)) else {
1449 return Ok(pending(c, n, &cmd.words).unwrap_or_default());
1450 };
1451 if let Some(e) = done.fail {
1452 return Err(cache_write(e));
1453 }
1454 c.reload();
1455 let mut out = outlined(c, n, true, want.prov);
1456 out.warn(done.warn);
1457 if !done.ok && out.rc == 0 {
1458 out.rc = 1;
1460 out.set("error", done.code);
1461 }
1462 Ok(out)
1463}
1464
1465pub const WAIT: u64 = 30;
1469
1470pub fn wait_of(cmd: &Cmd) -> Duration {
1471 Duration::from_secs(cmd.get("wait").and_then(|v| v.parse().ok()).unwrap_or(WAIT))
1472}
1473pub const POLL: Duration = Duration::from_millis(20);
1475
1476fn launch(c: &Cache, runs: &[(usize, Want)], cmd: &Cmd) -> Result<(), String> {
1483 let (cap, pool) =
1484 (settings::limit::<usize>("batch_parallel").max(1), runs.get(1).map(|_| c.run_file(runs[0].0, "pool.json")));
1485 if let Some(at) = &pool {
1486 fetch::seed(at, runs.iter().map(|(n, w)| (*n, plan_of(cmd, Some(w.url)))), plan_of(cmd, None).cap)?;
1487 }
1488 for (head, &(n, ..)) in runs.iter().enumerate().take(cap) {
1489 let job = c.st.u.get(n - 1).and_then(|e| e.job).unwrap_or_default();
1490 let lock = c.run_claim(n).ok_or_else(|| format!("{}: not locked", c.run_file(n, "lock").display()))?;
1492 for (k, &(id, w)) in runs.iter().skip(head).step_by(cap).enumerate() {
1493 let (by, status) = if k == 0 { (0, String::new()) } else { (n, format!("queued after u{n}")) };
1494 let (url, line, prov, pool) = (w.url.into(), cmd.raw.clone(), w.prov.map(String::from), pool.clone());
1495 c.run_put(id, &Detached { url, cmd: line, prov, job, pool, by, status, t: now(), ..<_>::default() })?;
1496 }
1497 detach(format!("j{job}.u{n}"), &c.run_file(n, "log"), Some(lock))?;
1498 }
1499 Ok(())
1500}
1501
1502pub(crate) fn detach(id: String, log: &std::path::Path, lock: Option<std::fs::File>) -> Result<(), String> {
1506 let made = log.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|()| std::fs::File::create(log));
1508 let log = made.map_err(|e| e.to_string())?;
1509 if provider::in_process() {
1510 std::thread::spawn(move || (resume(&id), lock));
1511 return Ok(());
1512 }
1513 let mut p = std::process::Command::new(std::env::current_exe().map_err(|e| e.to_string())?);
1514 let (stdin, keep) = if cfg!(windows) { (None, lock) } else { (lock, None) };
1519 p.args(["--continue", &id]).stdin(stdin.map_or_else(std::process::Stdio::null, std::process::Stdio::from));
1520 p.stdout(log.try_clone().map_err(|e| e.to_string())?).stderr(log);
1521 #[cfg(unix)]
1522 std::os::unix::process::CommandExt::process_group(&mut p, 0);
1523 #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut p, 0x0800_0000);
1525 let mut child = p.spawn().map_err(|e| format!("fats --continue {id}: {e}"))?;
1526 std::thread::spawn(move || (child.wait().ok(), keep));
1528 Ok(())
1529}
1530
1531fn hold_lane(c: &Cache, n: usize) {
1534 if let Ok(f) = std::fs::File::open(c.run_file(n, "lock")) {
1535 std::thread::spawn(move || {
1536 if f.lock().is_ok() {
1538 loop {
1539 std::thread::park();
1540 }
1541 }
1542 });
1543 }
1544}
1545
1546fn wait_for(c: &Cache, n: usize, wait: Duration) -> Option<Done> {
1550 poll_until(c.born, wait, || c.run(n).is_none_or(|(r, alive)| r.done.is_some() || !alive));
1551 c.run(n)?.0.done
1552}
1553
1554fn poll_until(born: Instant, wait: Duration, done: impl Fn() -> bool) {
1556 while !done() && born.elapsed() < wait {
1557 std::thread::sleep(POLL);
1558 }
1559}
1560
1561fn ready(c: &Cache, n: usize, run: &Detached, words: &[String]) -> String {
1567 let words = words.iter().map(|w| format!(" {w}")).collect::<String>();
1568 let on = |h: &HopRow| run.status.contains(&format!("{} running", provider::short(&h.provider)));
1570 let metas = c.st.u.iter().filter(|e| !e.alias && host_of(&e.url) == host_of(&run.url));
1571 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();
1572 ms.sort_unstable();
1573 let end = ms.get(ms.len() / 2).filter(|_| ms.len() >= 3).map(|p| (run.since + *p as f64 / 1e3).min(run.until));
1574 let left = end.map_or(0.0, |e| (e - now()).round().max(0.0)) as u64;
1575 poll_next(&format!("u{n}{words}"), left)
1576}
1577
1578fn poll_next(id: &str, left: u64) -> String {
1581 let poll = settings::limit::<u64>("poll_wait");
1582 let eta = if left == 0 { format!("check again in {poll} s") } else { format!("usually ready in ≈{left}s") };
1583 format!("{} {id} wait:{poll} · free, {eta}", bin())
1584}
1585
1586fn pending(c: &Cache, n: usize, words: &[String]) -> Option<Out> {
1590 let (run, alive) = c.run(n).filter(|x| x.0.done.is_none())?;
1591 let (id, age, host) = (format!("u{n}"), (now() - run.t).max(0.0).round() as u64, host_of(&run.url));
1592 let eq = format!("j{}.u{n}", run.job);
1593 if alive {
1594 let status = if run.status.is_empty() { "starting" } else { &run.status };
1595 return Some(waiting(format!("= {eq} pending {age}s {host} · {status} → {}", ready(c, n, &run, words)), id));
1596 }
1597 Some(no_doc(&id, &eq, &run.cut(), &[], &NoDoc::Missing, None))
1598}
1599
1600fn waiting(row: String, id: String) -> Out {
1602 Out::new(vec![row]).with("id", id).with("pending", true)
1603}
1604
1605fn running(c: &Cache, url: &str, words: &[String]) -> Option<Out> {
1607 c.runs().into_iter().filter(|r| r.1.url == url).find_map(|r| pending(c, r.0, words).filter(|o| o.rc == 0))
1608}
1609
1610pub fn resume(id: &str) -> i32 {
1613 if let Some(p) = id.strip_prefix("setup-") {
1614 return crate::setup::serve(p);
1615 }
1616 if id == "telemetry" {
1617 return crate::telemetry::send();
1618 }
1619 let (mut c, cmd) = (Cache::open(), parse(&[id.to_string()]));
1620 if let (Some(&j), None) = (cmd.jobs.first(), cmd.ids.first()) {
1623 let Some(job) = c.job(j) else { return 2 };
1624 c.job = Some(j);
1625 let rc = web(&parse(&[format!("{} wait:0", job.cmd)]), &mut c).map_or(1, |o| o.rc);
1626 return rc.max(i32::from(c.save().is_err()));
1627 }
1628 let Some(n) = cmd.ids.first().map(|i| i.u) else { return 2 };
1629 if cfg!(windows) && !provider::in_process() {
1630 hold_lane(&c, n);
1631 }
1632 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)
1634}
1635
1636fn run_one(c: &mut Cache, n: usize) -> i32 {
1638 let Some((mut r, _)) = c.run(n).filter(|x| x.0.done.is_none() && x.0.pid == 0) else { return 1 };
1640 r.pid = std::process::id();
1641 if c.run_put(n, &r).is_err() {
1642 return 1;
1643 }
1644 let w = Cache::at(c.root.clone(), c.session.clone());
1645 let seen = |(status, since, until)| {
1646 w.run_put(n, &Detached { status, since, until, ..r.clone() }).ok(); };
1648 let done = routed(c, &r, n, &seen);
1649 r.done = Some(done);
1650 i32::from(w.run_put(n, &r).is_err())
1651}
1652
1653fn routed(c: &mut Cache, run: &Detached, n: usize, seen: fetch::Seen) -> Done {
1655 let (cmd, url) = (parse(std::slice::from_ref(&run.cmd)), run.url.as_str());
1656 settings::mods(&cmd.mods);
1657 let mut p = Plan { pool: run.pool.clone().map(|f| (f, n)), ..plan_of(&cmd, Some(url)) };
1658 fetch::route_of(c, url, &mut p);
1659 p.prior = c.lookup(url).and_then(|(dir, _)| c.dir(&Entry { dir, ..Entry::default() }));
1660 let t0 = Instant::now();
1661 let ask = Ask {
1662 url: url.into(),
1663 country: cmd.get("country").map(String::from),
1664 mobile: cmd.get("device") == Some("mobile"),
1665 max_bytes: cap_of(&cmd),
1666 ..Ask::default()
1667 };
1668 let mut hops = fetch::run(&p, &ask, seen);
1669 let mut got = fetch::outcome(url, &mut hops, t0.elapsed().as_millis() as u64);
1670 let served = Tier::parse(&got.meta.provider);
1671 got.meta.country = served.and_then(|t| provider::sent(&ask, t)).unwrap_or_default();
1672 got.meta.hedge = if p.hedged() { "" } else { "off" }.into();
1674 let (ok, cost, id) = (got.meta.ok, got.meta.cost, format!("u{n}"));
1675 let skipped = fetch::skipped(&p, &hops, "", &id, url);
1676 let starved = !hops.iter().any(|h| h.tier.spec().price > 0.0) && skipped.iter().any(|r| r.contains("budget_hit"));
1679 got.meta.code = if starved { "budget_hit".into() } else { got.meta.code };
1680 let code = got.meta.code.clone();
1681 got.meta.extra.insert("skipped".into(), skipped.into());
1682 got.meta.extra.extend(p.pool.as_ref().map(|(at, _)| ("pool".into(), at.to_string_lossy().into())));
1684 let file = got.file.as_ref().map(|(name, body)| (name.as_str(), body.as_slice()));
1685 let (index, error, doc) = (ok.then_some(url), got.error.as_deref(), got.doc.as_ref());
1686 let snap = Snap { file, error, doc, meta: got.meta, index, slot: Some(n) };
1687 if let Err(e) = c.ingest(snap, run.job, t0) {
1688 return Done { ok, code, cost, fail: Some(e), ..Done::default() };
1689 }
1690 Done { ok, code, cost, warn: fetch::ignored(&ask, &hops, &id).into_iter().collect(), fail: None }
1691}
1692fn cached(c: &mut Cache, key: &str, want: Want, cmd: &Cmd) -> Option<Out> {
1695 if let Some(n) = render_of(c, key, cmd) {
1696 return Some(outlined(c, n, false, None));
1697 }
1698 let (dir, _) = c.lookup(key).filter(|_| !cmd.fresh())?;
1699 let n = reserve(c, Entry { dir, alias: true, ..Entry::default() }, want, cmd);
1700 Some(n.map_or_else(cache_write, |n| outlined(c, n, false, want.prov)))
1701}
1702
1703fn render_of(c: &Cache, url: &str, cmd: &Cmd) -> Option<usize> {
1707 let has = |e: &Entry| e.url == url && !e.dir.is_empty() && c.meta(&e.dir).is_some_and(|m| rendered(&m));
1708 (cmd.flag("js") && !cmd.flag("fresh")).then(|| c.st.u.iter().rposition(has)).flatten().map(|i| i + 1)
1709}
1710
1711fn rendered(m: &Meta) -> bool {
1714 m.ok && m.kind != "og" && Tier::parse(&m.provider).is_some_and(|t| t.can("js"))
1715}
1716
1717fn shown(p: &Path) -> String {
1720 let p = p.to_string_lossy();
1721 p.strip_prefix(r"\\?\UNC\").map_or_else(|| p.strip_prefix(r"\\?\").unwrap_or(&p).into(), |s| format!(r"\\{s}"))
1722}
1723
1724fn local(c: &mut Cache, f: &str, cmd: &Cmd) -> Result<Out, Out> {
1727 let t0 = Instant::now();
1728 let path = crate::lang::local_path(f);
1729 let real = fenced(f, &path).map_err(|(code, why)| refused(code, f, &format!("{f} · {why}"), &At::default()))?;
1730 let bytes = read_local(f, real, &path, cap_of(cmd))?;
1731 let file = || format!("file://{}", shown(&std::fs::canonicalize(&path).unwrap_or(path)));
1732 let url = if f == "-" { "stdin:".to_string() } else { file() };
1733 let key = blake3::Hasher::new().update(url.as_bytes()).update(&[0]).update(&bytes).finalize();
1735 let key = format!("blake3:{}", key.to_hex());
1736 if let Some(out) = cached(c, &key, Want { url: &url, ..Want::default() }, cmd) {
1737 return Ok(out);
1738 }
1739 let (bytes, charset) = provider::decode_body(bytes, None);
1740 let kind = crate::clean::kind_of("", &bytes);
1741 if kind == "zip" {
1742 let next = text_of_zip(f);
1743 let eq = format!("= ! not_in_v1 zip text: {f} · not in this build (pages, files, cache) → {next}");
1744 let o = Out::new(vec![eq]).with("error", "not_in_v1").with("hint", next).with("what", "zip");
1745 return Ok(Out { rc: 1, ..o });
1746 }
1747 let meta = Meta {
1749 url,
1750 provider: "local".into(),
1751 ok: true,
1752 code: "ok".into(),
1753 t: now(),
1754 bytes: bytes.len() as u64,
1755 kind: kind.into(),
1756 render: Some(false),
1757 charset: charset.into(),
1758 hops: vec![HopRow { provider: "local".into(), code: "ok".into(), ..Default::default() }],
1759 ..Meta::default()
1760 };
1761 let doc = crate::cache::build(&bytes, &meta.url, &meta.url, meta.render == Some(true), kind)
1763 .map_err(|e| no_doc(f, f, &meta, &[], &NoDoc::Parse(e), None))?;
1764 let job = c.job_of(&cmd.raw).map_err(cache_write)?;
1765 let name = crate::cache::raw_name(kind);
1766 let snap = Snap { file: Some((&name, &bytes)), error: None, doc: Some(&doc), meta, index: Some(&key), slot: None };
1767 let n = c.ingest(snap, job, t0).map_err(cache_write)?;
1768 Ok(outlined(c, n, true, None))
1769}
1770
1771fn outlined(c: &mut Cache, n: usize, new: bool, prov: Option<&str>) -> Out {
1773 page_cmd(c, &Id { u: n, ..Id::default() }, new, |p| Ok(outline::outline(p, prov))).unwrap_or_default()
1774}
1775
1776fn read_local(f: &str, real: std::io::Result<PathBuf>, path: &Path, cap: u64) -> Result<Vec<u8>, Out> {
1779 let mut v = Vec::new();
1780 let read = match f {
1781 "-" => std::io::stdin().take(cap + 1).read_to_end(&mut v),
1782 _ => real.and_then(std::fs::File::open).and_then(|h| h.take(cap + 1).read_to_end(&mut v)),
1783 };
1784 if let Err(e) = read {
1785 let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
1786 let at = At { arg: &dir.to_string_lossy(), ..At::default() };
1787 return Err(refused("no_file", f, &format!("{f} · {e}"), &at));
1788 }
1789 if v.len() as u64 > cap {
1790 let what = format!("over the {} input cap (ceiling {}) · nothing stored", mib(cap), mib(MAX_BYTES_CEIL));
1791 let at = At { url: f, done: &["max_bytes:64m"][..usize::from(cap >= MAX_BYTES_CEIL)], ..At::default() };
1792 return Err(refused("too_big", f, &format!("{f} · {what}"), &at));
1793 }
1794 Ok(v)
1795}
1796
1797#[cfg(test)]
1798mod tests {
1799 use super::*;
1800 use crate::scratch::Scratch;
1801
1802 fn cmd(s: &str) -> Cmd {
1803 parse(&s.split(' ').map(String::from).collect::<Vec<_>>())
1804 }
1805
1806 #[test]
1808 fn a_path_is_shown_as_typed() {
1809 let p = |s: &str| shown(Path::new(s));
1810 assert_eq!(
1811 (p(r"\\?\C:\a\b.html"), p(r"\\?\UNC\host\share\b.html")),
1812 (r"C:\a\b.html".into(), r"\\host\share\b.html".into())
1813 );
1814 assert_eq!((p("/tmp/a b.html"), p(r"C:\a.html")), ("/tmp/a b.html".into(), r"C:\a.html".into()));
1815 }
1816
1817 #[test]
1821 #[cfg(unix)]
1822 fn a_local_read_opens_the_path_it_checked() {
1823 let root = Scratch::new("fenced");
1824 let [a, b, link] = ["a.txt", "b.txt", "l.txt"].map(|n| root.join(n));
1825 std::fs::write(&a, "checked").ok();
1826 std::fs::write(&b, "swapped").ok();
1827 std::os::unix::fs::symlink(&a, &link).ok();
1828 let real = fenced("l.txt", &link);
1829 assert_eq!(real.as_ref().ok().and_then(|r| r.as_ref().ok()), a.canonicalize().ok().as_ref());
1830 std::fs::remove_file(&link).ok();
1831 std::os::unix::fs::symlink(&b, &link).ok();
1832 let Ok(real) = real else { panic!("inside the fence") };
1833 let read = read_local("l.txt", real, &link, 64).ok();
1834 assert_eq!(read.as_deref(), Some(&b"checked"[..]), "the link's new target is never opened");
1835 assert!(fenced("x", &root.join("none")).is_ok_and(|r| r.is_err()), "a missing file falls to no_file");
1836 }
1837
1838 #[test]
1840 fn more_beside_a_list_is_named() {
1841 let b = bin();
1842 let row = |w: &str| format!("! ignored more · lists page by from:K → {b} {w} from:K");
1843 assert_eq!(ignored(&cmd("u1 links more")), [row("u1 links")]);
1844 assert_eq!(ignored(&cmd("u2#3 media more")), [row("u2 media")]);
1845 assert_eq!(ignored(&cmd("links more")), [row("links")]);
1846 assert!(ignored(&cmd("u1 more")).is_empty() && ignored(&cmd("u1 links from:3")).is_empty());
1847 }
1848
1849 #[test]
1851 fn a_search_timeout_fix_adds_time() {
1852 let row = |why: &str, ms: u64| {
1853 let hops = vec![HopRow {
1854 provider: "brightdata".into(),
1855 code: "provider_timeout".into(),
1856 ms,
1857 why: why.into(),
1858 ..Default::default()
1859 }];
1860 let m = Meta { url: "search:rust".into(), code: "provider_timeout".into(), hops, ..Meta::default() };
1861 let out = search_out(&Cache::at(PathBuf::new(), "t".into()), &parse(&["rust".into()]), 1, &m)
1862 .unwrap_or_else(|o| o);
1863 out.lines.join("\n")
1864 };
1865 let b = bin();
1866 let row15 = row("", 15_000);
1867 assert!(row15.ends_with(&format!("! provider_timeout → {b} rust fresh:true timeout:30 ≤$0.0025")), "{row15}");
1868 assert!(row("", 30_000).ends_with(&format!("! provider_timeout → {b} rust fresh:true ≤$0.0025")), "ran 30 s");
1869 let wait = row("wait:5s", 5_000);
1870 assert!(
1871 wait.ends_with(&format!("! provider_timeout bd wait:5s → {b} rust fresh:true wait:30 ≤$0.0025")),
1872 "{wait}"
1873 );
1874 }
1875
1876 #[test]
1880 fn no_doc_answers() {
1881 let b = bin();
1882 let hop = |code: &str| HopRow { provider: "oxylabs".into(), code: code.into(), ..Default::default() };
1883 let m = Meta { url: "https://ex.com/a".into(), ok: true, bytes: 2048, ..Meta::default() };
1884 let lines = |why: &NoDoc, m: &Meta| no_doc("u3", "j2.u3", m, &[], why, None).lines.join("\n");
1885 let zip = lines(&NoDoc::Zip("/c/u3/raw.zip".into()), &m);
1886 assert_eq!(
1887 zip,
1888 format!(
1889 "= j2.u3 ! not_in_v1 zip (docx/xlsx) · ex.com/a · 2.0kB cached, no zip text in this build\n\
1890 u3 ! not_in_v1 zip ex.com/a → unzip -p /c/u3/raw.zip '*.xml' | {b} -"
1891 )
1892 );
1893 let o = no_doc("u3", "u3", &m, &[], &NoDoc::Zip("/c/u3/raw.zip".into()), None);
1894 assert_eq!((o.rc, o.rec["kind"].as_str(), o.rec["path"].as_str()), (1, Some("zip"), Some("/c/u3/raw.zip")));
1895 assert_eq!(
1896 lines(&NoDoc::Parse("pdf: bad xref".into()), &m),
1897 format!(
1898 "= j2.u3 ! parse_failed · ex.com/a · pdf: bad xref\nu3 ! parse_failed ex.com/a → {b} config · report the URL"
1899 )
1900 );
1901 assert_eq!(
1902 lines(&NoDoc::Missing, &m),
1903 format!(
1904 "= j2.u3 ! snapshot_missing · ex.com/a · the cached body is gone\nu3 ! snapshot_missing ex.com/a → {}",
1905 crate::lang::priced(&format!("{b} https://ex.com/a fresh:true"), "https://ex.com/a")
1906 )
1907 );
1908 const K: &str = " · oxy https://dashboard.oxylabs.io (a Web API instance's key)";
1909 let failed =
1910 Meta { ok: false, code: "bad_key".into(), ms: 700, cost: 0.001, hops: vec![hop("bad_key")], ..m.clone() };
1911 assert_eq!(
1912 lines(&NoDoc::Missing, &failed),
1913 format!(
1914 "= j2.u3 ! bad_key · ex.com · tried oxy:bad_key✗ · 700ms spent $0.0010\nu3 ! bad_key oxy → {b} setup{K}"
1915 )
1916 );
1917 let timed = Meta { code: "provider_timeout".into(), hops: vec![hop("provider_timeout")], ..failed.clone() };
1918 let t = lines(&NoDoc::Missing, &timed);
1919 assert!(t.ends_with(&format!("\nu3 ! provider_timeout ex.com/a → {b} u3 fresh:true js:true ≤$0.0030")), "{t}");
1920 let gone = Meta { code: String::new(), hops: vec![], ..failed };
1921 assert!(lines(&NoDoc::Missing, &gone).starts_with("= j2.u3 ! fetch_failed · ex.com · tried - · "));
1922 }
1923
1924 #[test]
1928 fn a_run_lives_while_its_lock_is_held() {
1929 let root = Scratch::new("start");
1930 let mut c = Cache::at(root.to_path_buf(), "t".into());
1931 let job = c.job_of("https://ex.com/a").expect("job");
1932 c.alloc(vec![Entry { url: "https://ex.com/a".into(), job: Some(job), ..Entry::default() }], None).expect("id");
1933 let lock = c.run_claim(1).expect("the launcher's lock");
1934 c.run_put(1, &Detached { url: "https://ex.com/a".into(), job: 1, t: now() - 60.0, ..Detached::default() })
1935 .expect("run file");
1936 let read = || (c.run(1).map(|r| r.1), pending(&c, 1, &[]).expect("a run").lines.join("\n"));
1937 let (alive, out) = read();
1938 assert!(alive == Some(true) && out.contains(" pending 60s ex.com · starting → "), "pid 0 at 60 s: {out}");
1939 let row = |c: &Cache| job_view(c, job).lines.get(1).cloned().unwrap_or_default();
1940 assert!(row(&c).starts_with("j1.u1 ex.com/a · pending → "), "{}", row(&c));
1941 drop(lock);
1942 let (alive, out) = read();
1943 assert!(alive == Some(false) && out.contains(" ! abandoned ex.com"), "no lock: {out}");
1944 assert!(row(&c).starts_with("j1.u1 ex.com · ! abandoned ex.com/a · "), "{}", row(&c));
1945 }
1946
1947 fn listed_session(tag: &str) -> (Cache, Scratch, Vec<Hit>, Meta, Out) {
1950 let root = Scratch::new(&format!("serp-{tag}"));
1951 let mut cache = Cache::at(root.to_path_buf(), "t".into());
1952 let old = Entry { url: "https://ex.com/".into(), dir: "t/u1".into(), ..Entry::default() };
1953 assert_eq!(cache.alloc(vec![old], None), Ok(1));
1954 let body = include_bytes!("../tests/fixtures/oxy-search.json");
1955 let hits = provider::hits(Tier::Oxy, body, 10).expect("fixture");
1956 let job = cache.job_of("heidelberg university").expect("job");
1957 let meta = Meta {
1958 url: "search:heidelberg university".into(),
1959 provider: "oxylabs".into(),
1960 ms: 1630,
1961 cost: 0.001,
1962 kind: "serp".into(),
1963 t: now(),
1964 ..Default::default()
1965 };
1966 let out = merged(listed(&mut cache, job, meta.clone(), &hits));
1967 (cache, root, hits, meta, out)
1968 }
1969
1970 #[test]
1973 fn search_results_become_ids() {
1974 let (cache, _root, _, _, out) = listed_session("ids");
1975 let b = bin();
1976 let first =
1978 "= j1 search \"heidelberg university\" · 5 results · 4 shown u2-u5 · oxylabs · 1.6s · spent $0.0010";
1979 assert_eq!(out.lines[0], first);
1980 assert_eq!(
1981 out.lines[1],
1982 "u2 uni-heidelberg.de/en Heidelberg University — \"Heidelberg University – the oldest in Germany, recognized globally. \
1983 A leader in science, …\""
1984 );
1985 let wiki = "u4 en.wikipedia.org/wiki/Heidelberg_Univer… Heidelberg University - Wikipedia";
1986 assert!(out.lines[3].starts_with(wiki));
1987 let last = format!("open one: {b} u2 · filter: {b} u2 <words> · more: {b} more");
1988 assert_eq!(out.lines.last().map(String::as_str), Some(&*last));
1989 assert_eq!((out.lines.len(), out.parts.len(), out.rc), (6, 5, 0));
1990 assert_eq!(out.parts[0].rec["url"], "https://www.uni-heidelberg.de/en");
1991 assert_eq!((out.parts[0].rec["cost"].as_f64(), out.parts[1].rec["cost"].as_f64()), (Some(0.001), Some(0.0)));
1992 let unfetched = |n| cache.st.result(n).filter(|e| e.dir.is_empty()).cloned();
1993 let entry = unfetched(2).expect("u2 is a search result");
1994 assert_eq!((entry.url.as_str(), entry.job), ("https://www.uni-heidelberg.de/en", cache.job));
1995 assert!(unfetched(1).is_none() && unfetched(7).is_none());
1996 let dry = plan(&cmd("u2 dry:true"), &cache).lines.join("\n");
1997 assert!(dry.contains("u2 uni-heidelberg.de/en (search result)") && !dry.contains("local read"), "{dry}");
1998 }
1999
2000 #[test]
2002 fn more_lists_past_the_cap() {
2003 let (mut cache, _root, hits, meta, _) = listed_session("more");
2004 let b = bin();
2005 let many: Vec<Hit> = (0..4).flat_map(|_| hits.clone()).collect();
2006 let job = cache.job_of("again").expect("job");
2007 let out = merged(listed(&mut cache, job, meta, &many));
2008 let rows = out.lines.iter().filter(|l| l.starts_with('u')).count();
2009 assert!((3..20).contains(&rows), "{:?}", out.lines);
2010 assert!(out.lines.last().is_some_and(|l| l.ends_with(&format!("more: {b} more"))));
2011 assert_eq!(cache.st.cursor.as_ref().and_then(|k| k.serp), Some((job, rows)));
2012 let more = dispatch(&cmd("more"), &mut cache);
2013 assert!(more.lines[0].starts_with(&format!("= j{job} search ")), "{:?}", more.lines);
2014 assert!(more.lines[0].contains(&format!(" shown u{}-", 7 + rows)), "{:?}", more.lines);
2015 assert!(more.lines[1].starts_with(&format!("u{} ", 7 + rows)), "{:?}", more.lines);
2016 }
2017}