use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use pagesift::api::types::{CrawlSummary, Document};
use pagesift::api::{ApiError, BoxFuture, CrawlSink};
use pagesift_sink::out::{DirOut, Fanout, LinesOut, PageOut, WarcOut};
pub struct CrawlOutput {
dir: Option<Arc<DirOut>>,
out: Fanout,
counts: Mutex<(usize, usize)>,
}
impl CrawlOutput {
pub fn new(dir: Option<PathBuf>, warc: Option<PathBuf>) -> std::io::Result<Self> {
let dir = dir.map(DirOut::create).transpose()?.map(Arc::new);
let mut out = Fanout::default();
match &dir {
Some(d) => out.0.push(Box::new(Shared(d.clone()))),
None => out.0.push(Box::new(LinesOut)),
}
if let Some(w) = warc {
out.0.push(Box::new(WarcOut::create(&w)?));
}
Ok(Self {
dir,
out,
counts: Mutex::new((0, 0)),
})
}
pub fn counts(&self) -> (usize, usize) {
*self.counts.lock().expect("lock")
}
fn write_page(&self, doc: &Document) -> std::io::Result<()> {
self.counts.lock().expect("lock").0 += 1;
if let Some(warnings) = doc.metadata.pagesift.as_ref().map(|p| &p.warnings) {
for warning in warnings {
if warning.starts_with("crawl_followed_zero:")
|| warning.starts_with("crawl_scope:")
{
eprintln!("warning: {warning}");
}
}
}
self.out.page(doc)
}
}
struct Shared(Arc<DirOut>);
impl PageOut for Shared {
fn page(&self, doc: &Document) -> std::io::Result<()> {
self.0.page(doc)
}
}
impl CrawlSink for CrawlOutput {
fn page(&self, doc: Document) -> BoxFuture<'_, ()> {
if let Err(e) = self.write_page(&doc) {
eprintln!("could not write page: {e}");
}
Box::pin(async {})
}
fn error<'a>(&'a self, url: &'a str, err: ApiError) -> BoxFuture<'a, ()> {
self.counts.lock().expect("lock").1 += 1;
eprintln!("{url}: {} {}", err.code.as_str(), err.message);
Box::pin(async {})
}
fn total(&self, _total: usize) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
fn cancelled(&self) -> BoxFuture<'_, bool> {
Box::pin(async { false })
}
fn summary(&self, s: CrawlSummary) -> BoxFuture<'_, ()> {
match s.coverage {
Some(c) => eprintln!("stopped: {} (coverage {c:.2})", s.stop_reason),
None => eprintln!("stopped: {}", s.stop_reason),
}
if let Some(dir) = &self.dir {
let written = serde_json::to_vec_pretty(&s)
.map_err(std::io::Error::other)
.and_then(|json| dir.summary(&json));
if let Err(e) = written {
eprintln!("could not write summary.json: {e}");
}
}
if let Err(e) = self.out.finish() {
eprintln!("could not finish output: {e}");
}
Box::pin(async {})
}
}
fn config_detail(cfg: &pagesift::config::Config) -> String {
if cfg.config_files_disabled() {
return "defaults (config files disabled by PAGESIFT_CONFIG=)".into();
}
if let Some(path) = cfg.source() {
return path.display().to_string();
}
match pagesift::config::Config::default_path() {
Some(path) => format!(
"defaults (no config file; create {} to add one)",
path.display()
),
None => "defaults (no config file)".into(),
}
}
pub async fn doctor(cfg: &pagesift::config::Config) -> Result<ExitCode> {
let mut ok = true;
let mut report = |good: bool, what: &str, detail: String| {
println!("{} {what}: {detail}", if good { "ok " } else { "FAIL" });
ok &= good;
};
let warn = |what: &str, detail: String| println!("WARN {what}: {detail}");
report(true, "config", config_detail(cfg));
report(
true,
"llm",
match &cfg.llm {
Some(l) => format!("{} at {}", l.model, l.base_url),
None => "not configured (optional): summary, json and extract are unavailable".into(),
},
);
report(
true,
"search",
match &cfg.search {
Some(s) => s.backend.clone(),
None => "not configured (optional): /v2/search is unavailable".into(),
},
);
let mut sc = cfg.scraper(false)?;
sc.audit = None;
let chain: Vec<String> =
pagesift_cdp::engine_chain(&sc.browser, sc.fetcher.ssrf.allow_private_network)
.iter()
.filter_map(|c| match &c.source {
pagesift_cdp::BrowserSource::Executable(p) => Some(format!(
"{} ({})",
c.engine.map_or("chrome", |k| k.name()),
p.display()
)),
pagesift_cdp::BrowserSource::Remote(u) => Some(format!("remote {u}")),
pagesift_cdp::BrowserSource::Auto => None,
})
.collect();
if chain.is_empty() {
report(
false,
"browser",
"no browser engine found; pages that need JavaScript will be returned from HTTP only. Install Lightpanda, moli or Chromium, or set the browser path".into(),
);
} else if !matches!(sc.browser.source, pagesift_cdp::BrowserSource::Remote(_))
&& pagesift_cdp::running_as_root()
{
report(
false,
"browser",
format!(
"{} installed, but rendering will fail: pagesift is running as root, and the Chrome sandbox does not work as root (pagesift will not disable it). Run as an unprivileged user",
chain.join(" → ")
),
);
}
let probe = !chain.is_empty()
&& (matches!(sc.browser.source, pagesift_cdp::BrowserSource::Remote(_))
|| !pagesift_cdp::running_as_root());
if probe {
report(true, "browser", chain.join(" → "));
}
let scraper = pagesift::Scraper::new(sc)?;
if probe {
let probes = scraper.probe_engines().await;
let started = probes.iter().filter(|p| p.result.is_ok()).count();
let first_ok = probes.iter().position(|p| p.result.is_ok());
for (i, p) in probes.iter().enumerate() {
match &p.result {
Ok(()) => report(
true,
&format!("engine {}", p.engine),
format!("starts ({})", p.location),
),
Err(e) if started == 0 => report(
false,
&format!("engine {}", p.engine),
format!("does not start ({}): {e}", p.location),
),
Err(e) => {
let effect = match first_ok {
Some(j) if j > i => {
format!("pages are rendered by {} instead", probes[j].engine)
}
_ => "pages the engines before it cannot render get no fallback".into(),
};
warn(
&format!("engine {}", p.engine),
format!("does not start ({}): {e}; {effect}", p.location),
)
}
}
}
scraper.shutdown().await;
}
let opts = pagesift::api::types::ScrapeOptions {
engine: Some("http".into()),
..Default::default()
};
match scraper.scrape("https://example.com/", &opts).await {
Ok(doc) => report(
true,
"network",
format!(
"fetched https://example.com/ (HTTP {})",
doc.metadata.status_code
),
),
Err(e) => report(
false,
"network",
format!("{}: {}", e.code.as_str(), e.message),
),
}
let dir = cfg.data_dir();
let writable = std::fs::create_dir_all(&dir).is_ok() && tempfile_in(&dir);
report(writable, "data directory", dir.display().to_string());
Ok(if ok {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
})
}
fn tempfile_in(dir: &std::path::Path) -> bool {
let probe = dir.join(".pagesift-doctor");
let ok = std::fs::write(&probe, b"ok").is_ok();
let _ = std::fs::remove_file(&probe);
ok
}