diff --git a/Cargo.lock b/Cargo.lock index b8068dc35..a5b66afa6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7388,6 +7388,7 @@ dependencies = [ "zephium-blocker", "zephium-core", "zephium-map", + "zephium-map-driver", "zephium-public-fetch", ] @@ -7849,6 +7850,20 @@ dependencies = [ "zephium-core", ] +[[package]] +name = "zephium-map-driver" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "specta", + "tokio", + "url", + "zephium-core", + "zephium-map", + "zephium-public-fetch", +] + [[package]] name = "zephium-mcp" version = "0.1.0" diff --git a/crates/zephium-map-driver/Cargo.toml b/crates/zephium-map-driver/Cargo.toml new file mode 100644 index 000000000..31f2ffcec --- /dev/null +++ b/crates/zephium-map-driver/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "zephium-map-driver" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[features] +ipc-types = ["dep:specta"] + +[dependencies] +serde.workspace = true +specta = { workspace = true, optional = true } +tokio = { workspace = true, features = ["rt", "sync", "time", "macros"] } +url.workspace = true +zephium-core.workspace = true +zephium-map = { version = "=0.1.0", path = "../zephium-map" } +zephium-public-fetch = { version = "=0.1.0", path = "../zephium-public-fetch" } + +[dev-dependencies] +serde_json.workspace = true +tokio = { workspace = true, features = ["rt", "sync", "time", "macros", "test-util"] } diff --git a/crates/zephium-map-driver/src/driver.rs b/crates/zephium-map-driver/src/driver.rs new file mode 100644 index 000000000..0473ae3af --- /dev/null +++ b/crates/zephium-map-driver/src/driver.rs @@ -0,0 +1,844 @@ +use std::{ + collections::{BTreeMap, HashMap, VecDeque}, + sync::{ + atomic::{AtomicU32, AtomicU64, Ordering}, + Arc, Mutex, MutexGuard, PoisonError, + }, + time::Duration, +}; + +use tokio::{ + runtime::Handle, + sync::{mpsc, watch}, + task::{self, JoinError, JoinHandle, JoinSet}, +}; +use url::Url; +use zephium_core::search::SearchEngine; +use zephium_map::{ + query::Confidence, + read_query, + session::{Failure, HeldSite, Id, ReadState, Sections, MAX_CONCURRENT, MAX_HOST_CONCURRENT}, + Config, Effect, Input, MapEvent, QueryKind, Session, +}; + +use crate::{ + io::{FetchRequest, Io}, + page, + wire::{self, Change, OpenRefusal, OpenResult, StartRefusal, Target, Targets}, +}; + +pub const TICK: Duration = Duration::from_millis(250); +pub const CHANGE_BUFFER: usize = 64; +pub const MAX_WAITING_OPENS: usize = 4; +/// The longest a run waits for its first results page when its source sets +/// no bound of its own. +pub const RESULTS_WAIT: Duration = Duration::from_secs(60); +const SLOTS: usize = 2; + +pub struct MapRequest { + pub query: String, + pub engine: SearchEngine, + /// Distinct for every live map; the session namespaces its effect ids with it. + pub session_id: u64, + /// Opaque; memos are kept apart per profile. + pub profile: String, + pub private: bool, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Counts { + pub fetches: u32, + pub bytes: u64, + pub render_unavailable: u32, + pub anonymous_unavailable: u32, + pub truncated_results: u32, + pub over_ceiling: u32, +} + +#[derive(Default)] +struct Shared { + published: Mutex, + fetches: AtomicU32, + bytes: AtomicU64, + render_unavailable: AtomicU32, + anonymous_unavailable: AtomicU32, + truncated_results: AtomicU32, + over_ceiling: AtomicU32, +} + +impl Shared { + fn published(&self) -> MutexGuard<'_, Published> { + self.published + .lock() + .unwrap_or_else(PoisonError::into_inner) + } +} + +fn bump(counter: &AtomicU32) { + let _ = counter.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_add(1)); +} + +#[derive(Default)] +struct Published { + slots: [Option; SLOTS], + also: Vec, +} + +struct PublishedPlace { + targets: Targets, + held: Option>, + confidence: Confidence, + stale: bool, +} + +struct OpenRequest { + slot: u8, + id: String, +} + +enum Publication { + Place(usize, Box), + PlaceFailed(usize), + Also(Vec), +} + +pub struct Driver { + cancel: watch::Sender, + task: JoinHandle<()>, + shared: Arc, + opens: mpsc::Sender, +} + +impl Driver { + pub fn start( + request: MapRequest, + io: Io, + runtime: &Handle, + ) -> Result<(Self, mpsc::Receiver), StartRefusal> { + Self::start_buffered(request, io, runtime, CHANGE_BUFFER) + } + + fn start_buffered( + request: MapRequest, + io: Io, + runtime: &Handle, + buffer: usize, + ) -> Result<(Self, mpsc::Receiver), StartRefusal> { + let read = read_query(&request.query).map_err(|_| StartRefusal::Invalid)?; + if !matches!( + read.kind(), + QueryKind::Place { .. } | QueryKind::Compare { .. } + ) { + return Err(StartRefusal::NotAMap); + } + if request.engine == SearchEngine::Custom { + return Err(StartRefusal::UnsupportedEngine); + } + let config = Config { + session_id: request.session_id, + engine: request.engine, + now: io.clock.unix(), + sections: Sections::Asked, + ..Config::default() + }; + let (session, effects) = + Session::start(config, &request.query).map_err(|_| StartRefusal::Invalid)?; + let (tx, rx) = mpsc::channel(buffer); + let (cancel, cancelled) = watch::channel(false); + let (opens, open_requests) = mpsc::channel(MAX_WAITING_OPENS); + let shared = Arc::new(Shared::default()); + let run = Run { + started: None, + session: Some(session), + io, + profile: request.profile, + private: request.private, + tx, + shared: Arc::clone(&shared), + reads: JoinSet::new(), + tasks: HashMap::new(), + hosts: BTreeMap::new(), + immediate: VecDeque::new(), + seq: 0, + cancelled, + cancelling: false, + unsent: None, + open_requests, + opening: None, + session_id: request.session_id, + }; + let task = runtime.spawn(run.run(effects)); + Ok(( + Self { + cancel, + task, + shared, + opens, + }, + rx, + )) + } + + pub fn cancel(&self) { + let _published = self.shared.published(); + self.cancel.send_replace(true); + } + + pub fn open(&self, slot: u8, id: &str) -> Result<(), OpenRefusal> { + let published = self.shared.published(); + if *self.cancel.borrow() || self.opens.is_closed() { + return Err(OpenRefusal::Cancelled); + } + let place = published + .slots + .get(usize::from(slot)) + .and_then(Option::as_ref) + .ok_or(OpenRefusal::NoPlace)?; + if !place.targets.has(id) { + return Err(OpenRefusal::UnknownEntry); + } + place + .held + .as_ref() + .ok_or(OpenRefusal::NotOpenable)? + .check_open(id)?; + self.opens + .try_send(OpenRequest { + slot, + id: id.to_owned(), + }) + .map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => OpenRefusal::TooManyWaiting, + mpsc::error::TrySendError::Closed(_) => OpenRefusal::Cancelled, + }) + } + + pub fn target(&self, slot: u8, target: &Target) -> Option { + let published = self.shared.published(); + if let Target::Also { index } = target { + return wire::also_target(&published.also, *index); + } + published + .slots + .get(usize::from(slot))? + .as_ref()? + .targets + .resolve(target) + } + + pub fn counts(&self) -> Counts { + let load = |counter: &AtomicU32| counter.load(Ordering::Acquire); + Counts { + fetches: load(&self.shared.fetches), + bytes: self.shared.bytes.load(Ordering::Acquire), + render_unavailable: load(&self.shared.render_unavailable), + anonymous_unavailable: load(&self.shared.anonymous_unavailable), + truncated_results: load(&self.shared.truncated_results), + over_ceiling: load(&self.shared.over_ceiling), + } + } +} + +impl Drop for Driver { + fn drop(&mut self) { + let _published = self.shared.published(); + self.task.abort(); + self.cancel.send_replace(true); + } +} + +#[derive(Clone, Copy)] +enum Kind { + Results, + Fetch, +} + +enum Next { + Ready, + Tick, + Cancel, + Stop, +} + +#[derive(PartialEq)] +enum Applied { + Continue, + Cancel, + Stop, +} + +struct Run { + session: Option, + io: Io, + profile: String, + private: bool, + tx: mpsc::Sender, + shared: Arc, + reads: JoinSet, + tasks: HashMap, + hosts: BTreeMap, + immediate: VecDeque, + seq: u32, + started: Option, + cancelled: watch::Receiver, + cancelling: bool, + unsent: Option, + open_requests: mpsc::Receiver, + opening: Option, + session_id: u64, +} + +fn is_end(effect: &Effect) -> bool { + matches!( + effect, + Effect::Emit { + event: MapEvent::End { .. }, + .. + } + ) +} + +impl Run { + async fn run(mut self, mut effects: Vec) { + loop { + let next = match self.apply(effects).await { + Applied::Stop => return, + Applied::Continue if self.session.is_none() => { + let Some(next) = self.next_open().await else { + return; + }; + effects = next; + continue; + } + Applied::Cancel => Next::Cancel, + Applied::Continue if *self.cancelled.borrow() => Next::Cancel, + Applied::Continue if self.immediate.is_empty() => self.wait().await, + Applied::Continue => Next::Ready, + }; + let input = match next { + Next::Stop => return, + Next::Cancel => { + self.clear_reads(); + if self.opening.is_some() { + return; + } + self.cancelling = true; + Some(Input::Cancel) + } + Next::Tick => None, + Next::Ready => self.immediate.pop_front(), + }; + match self.handle(input).await { + Some(next) => effects = next, + None => return, + } + } + } + + fn clear_reads(&mut self) { + self.reads = JoinSet::new(); + self.tasks.clear(); + self.hosts.clear(); + self.immediate.clear(); + } + + async fn next_open(&mut self) -> Option> { + loop { + let request = tokio::select! { + biased; + _ = self.cancelled.wait_for(|cancelled| *cancelled) => return None, + () = self.tx.closed() => return None, + request = self.open_requests.recv() => request?, + }; + let slot = request.slot; + let place = { + let published = self.shared.published(); + published.slots[usize::from(slot)] + .as_ref() + .and_then(|item| { + Some((item.held.as_ref()?.clone(), item.confidence, item.stale)) + }) + }; + if let Some((held, confidence, stale)) = place { + let cfg = Config { + session_id: self.session_id, + now: self.io.clock.unix(), + ..Config::default() + }; + if let Ok((session, effects)) = + Session::open(cfg, (*held).clone(), slot, &request.id, confidence, stale) + { + self.session = Some(session); + self.opening = Some(request); + self.started = Some(self.io.clock.now()); + return Some(effects); + } + let (place, _) = wire::place(held.place(), Some(held.robots())); + let change = Change::Place { + seq: self.next_seq(), + slot, + place, + stale, + confidence: confidence.into(), + complete: true, + }; + if self.deliver(change).await != Applied::Continue { + return None; + } + } + let result = self.open_result(&request); + let change = Change::Opened { + seq: self.next_seq(), + slot, + id: request.id, + result, + }; + if self.deliver(change).await != Applied::Continue { + return None; + } + } + } + + fn open_result(&self, request: &OpenRequest) -> OpenResult { + let published = self.shared.published(); + let entry = published.slots[usize::from(request.slot)] + .as_ref() + .and_then(|slot| slot.held.as_ref()) + .and_then(|held| { + held.place() + .sections + .iter() + .find(|entry| entry.id.as_str() == request.id) + }); + match entry.and_then(|entry| entry.read) { + Some(ReadState::Read) => OpenResult::Read, + Some(ReadState::Refused { failure }) => OpenResult::Refused { + failure: failure.into(), + }, + Some(ReadState::Skipped { .. }) => OpenResult::Refused { + failure: wire::Failure::Limit, + }, + _ => OpenResult::Refused { + failure: if entry.is_some() { + wire::Failure::Blocked + } else { + wire::Failure::Missing + }, + }, + } + } + + async fn wait(&mut self) -> Next { + let done = tokio::select! { + changed = self.cancelled.changed() => { + return match changed { + Ok(()) if *self.cancelled.borrow() => Next::Cancel, + Ok(()) => Next::Tick, + Err(_) => Next::Stop, + }; + } + () = self.tx.closed() => return Next::Stop, + Some(done) = self.reads.join_next_with_id() => done, + () = tokio::time::sleep(TICK), if self.started.is_some() => return Next::Tick, + }; + match self.completed(done) { + Some(input) => { + self.immediate.push_back(input); + Next::Ready + } + None => Next::Tick, + } + } + + fn completed(&mut self, done: Result<(task::Id, Input), JoinError>) -> Option { + let (task, input) = match done { + Ok((task, input)) => (task, Some(input)), + Err(error) => (error.id(), None), + }; + let (id, kind) = self.tasks.remove(&task)?; + self.hosts.remove(&id); + Some(input.unwrap_or(match kind { + Kind::Results => Input::Results { + id, + result: Err(Failure::Unavailable), + }, + Kind::Fetch => Input::Fetch { + id, + result: Err(Failure::Unavailable), + }, + })) + } + + fn elapsed(&self) -> Duration { + self.started.map_or(Duration::ZERO, |start| { + self.io.clock.now().saturating_sub(start) + }) + } + + async fn handle(&mut self, input: Option) -> Option> { + let mut session = self.session.take()?; + if matches!(input, Some(Input::Results { .. })) { + self.started.get_or_insert_with(|| self.io.clock.now()); + } + let time = self.elapsed(); + let cancelling = self.cancelling; + let shared = Arc::clone(&self.shared); + let done = task::spawn_blocking(move || { + let mut effects = if cancelling { + Vec::new() + } else { + session.handle(Input::Elapsed { time }) + }; + if let Some(input) = input { + if !effects.iter().any(is_end) { + if let Input::Fetch { + result: Ok(answer), .. + } = &input + { + let size = answer.bytes.len() as u64; + let _ = + shared + .bytes + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + Some(n.saturating_add(size)) + }); + } + effects.extend(session.handle(input)); + } + } + (session, effects) + }) + .await; + match done { + Ok((session, effects)) => { + self.session = Some(session); + Some(effects) + } + Err(_) => { + if self.opening.is_none() { + let end = self.end(wire::Outcome::Failed { + failure: wire::Failure::Unavailable, + }); + self.deliver(end).await; + } + None + } + } + } + + async fn deliver(&mut self, change: Change) -> Applied { + if self.cancelling { + return match self.tx.send(change).await { + Ok(()) => Applied::Continue, + Err(_) => Applied::Stop, + }; + } + let seq = change.seq(); + if seq == u32::MAX { + return Applied::Stop; + } + tokio::select! { + biased; + cancelled = async { self.cancelled.wait_for(|cancelled| *cancelled).await.is_ok() } => { + self.seq = seq; + self.unsent = None; + if cancelled { Applied::Cancel } else { Applied::Stop } + } + permit = self.tx.reserve() => { + let Ok(permit) = permit else { return Applied::Stop }; + let mut published = self.shared.published(); + if *self.cancelled.borrow() { + self.seq = seq; + self.unsent = None; + return Applied::Cancel; + } + match self.unsent.take() { + Some(Publication::Place(index, place)) => published.slots[index] = Some(*place), + Some(Publication::PlaceFailed(index)) => published.slots[index] = None, + Some(Publication::Also(targets)) => published.also = targets, + None => {} + } + permit.send(change); + Applied::Continue + } + } + } + + async fn apply(&mut self, effects: Vec) -> Applied { + for effect in effects { + if self.cancelling { + if let Effect::Emit { + event: event @ MapEvent::End { .. }, + .. + } = effect + { + if let Some(change) = self.project(event) { + self.deliver(change).await; + } + return Applied::Stop; + } + continue; + } + if *self.cancelled.borrow() { + return Applied::Cancel; + } + match effect { + Effect::LoadResults { id, url } => self.load(id, url), + Effect::Fetch { + id, + url, + expect, + max_bytes, + timeout, + } => self.fetch( + id, + FetchRequest { + url, + expect, + max_bytes, + timeout, + }, + ), + Effect::Render { id, .. } => { + bump(&self.shared.render_unavailable); + self.immediate.push_back(Input::Render { + id, + result: Err(Failure::Unavailable), + }); + } + Effect::ReadResultsAnonymously { id, .. } => { + bump(&self.shared.anonymous_unavailable); + self.immediate.push_back(Input::Results { + id, + result: Err(Failure::Unavailable), + }); + } + Effect::LookupSite { id, site } => { + let memo = if self.private { + None + } else { + self.io.memo.lookup(&self.profile, &site) + }; + self.immediate.push_back(Input::Cache { id, memo }); + } + Effect::RememberSite { site, memo, .. } => { + if !self.private { + self.io.memo.remember(&self.profile, &site, memo); + } + } + Effect::Emit { event, .. } => { + if matches!(event, MapEvent::End { .. }) { + if let Some(request) = self.opening.take() { + let result = self.open_result(&request); + let change = Change::Opened { + seq: self.next_seq(), + slot: request.slot, + id: request.id, + result, + }; + if self.deliver(change).await != Applied::Continue { + return Applied::Stop; + } + } else if let Some(change) = self.project(event) { + let applied = self.deliver(change).await; + if applied != Applied::Continue { + return applied; + } + } + self.clear_reads(); + self.session = None; + return Applied::Continue; + } + if let Some(change) = self.project(event) { + let applied = self.deliver(change).await; + if applied != Applied::Continue { + return applied; + } + } + } + } + } + if self.cancelling { + let end = self.end(wire::Outcome::Cancelled); + self.deliver(end).await; + return Applied::Stop; + } + Applied::Continue + } + + fn load(&mut self, id: Id, url: Url) { + let source = Arc::clone(&self.io.results); + let shared = Arc::clone(&self.shared); + let read = self.reads.spawn(async move { + let loaded = tokio::time::timeout(RESULTS_WAIT, source.load(url)) + .await + .unwrap_or(Err(Failure::Timeout)); + let result = match loaded { + Ok(page) => { + if page.truncated || page.html.len() > page::MAX_RESULTS_SOURCE_BYTES { + bump(&shared.truncated_results); + } + task::spawn_blocking(move || page::parse(&page)) + .await + .unwrap_or(Err(Failure::Unavailable)) + } + Err(failure) => Err(failure), + }; + Input::Results { id, result } + }); + self.tasks.insert(read.id(), (id, Kind::Results)); + } + + fn fetch(&mut self, id: Id, mut request: FetchRequest) { + let Some(started) = self.started else { + self.immediate.push_back(Input::Fetch { + id, + result: Err(Failure::Unavailable), + }); + return; + }; + let host = request.url.host_str().unwrap_or_default().to_owned(); + if self.hosts.len() >= MAX_CONCURRENT + || self.hosts.values().filter(|h| **h == host).count() >= MAX_HOST_CONCURRENT + { + bump(&self.shared.over_ceiling); + self.immediate.push_back(Input::Fetch { + id, + result: Err(Failure::Limit), + }); + return; + } + let fetcher = Arc::clone(&self.io.fetch); + let clock = Arc::clone(&self.io.clock); + let shared = Arc::clone(&self.shared); + let read = self.reads.spawn(async move { + let elapsed = clock.now().saturating_sub(started); + let remaining = zephium_map::session::MAX_ELAPSED.saturating_sub(elapsed); + if elapsed >= zephium_map::session::LAST_START || remaining.is_zero() { + return Input::Fetch { + id, + result: Err(Failure::Timeout), + }; + } + request.timeout = request.timeout.min(remaining); + bump(&shared.fetches); + let result = tokio::time::timeout(request.timeout, fetcher.fetch(request)) + .await + .unwrap_or(Err(Failure::Timeout)); + Input::Fetch { id, result } + }); + self.tasks.insert(read.id(), (id, Kind::Fetch)); + self.hosts.insert(id, host); + } + + fn end(&mut self, outcome: wire::Outcome) -> Change { + let seq = self.next_seq(); + Change::End { + seq, + outcome, + elapsed_ms: u32::try_from(self.elapsed().as_millis()).unwrap_or(u32::MAX), + } + } + + fn next_seq(&mut self) -> u32 { + let seq = self.seq; + self.seq = self.seq.saturating_add(1); + seq + } + + fn project(&mut self, event: MapEvent) -> Option { + Some(match event { + MapEvent::FirstLayer { layer } => { + let places = self + .session + .as_ref() + .map(|session| session.result_places().collect::>()) + .unwrap_or_default(); + let wire::Layer { + official, + social, + organic, + also, + targets, + } = wire::first_layer(&layer, &places); + self.unsent = Some(Publication::Also(targets)); + Change::FirstLayer { + seq: self.next_seq(), + official, + social, + organic, + also, + } + } + MapEvent::Place { + slot, + place, + stale, + confidence, + complete, + } => { + let index = usize::from(slot); + if index >= SLOTS { + return None; + } + let held = self + .session + .as_ref() + .and_then(|session| session.hold_place(slot, place.clone())); + let (place, targets) = wire::place(&place, held.as_ref().map(HeldSite::robots)); + self.unsent = Some(Publication::Place( + index, + Box::new(PublishedPlace { + targets, + held: held.map(Arc::new), + confidence, + stale, + }), + )); + Change::Place { + seq: self.next_seq(), + slot, + place, + stale, + confidence: confidence.into(), + complete, + } + } + MapEvent::PlaceFailed { slot, failure } => { + if usize::from(slot) >= SLOTS { + return None; + } + self.unsent = Some(Publication::PlaceFailed(usize::from(slot))); + Change::PlaceFailed { + seq: self.next_seq(), + slot, + failure: failure.into(), + } + } + MapEvent::Compare { rows } => { + let rows = { + let published = self.shared.published(); + let none = Targets::default(); + wire::rows( + &rows, + published.slots[0] + .as_ref() + .map_or(&none, |slot| &slot.targets), + published.slots[1] + .as_ref() + .map_or(&none, |slot| &slot.targets), + ) + }; + Change::Compare { + seq: self.next_seq(), + rows, + } + } + MapEvent::End { outcome, .. } => self.end(outcome.into()), + MapEvent::Kind { .. } | MapEvent::Passages { .. } => return None, + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/zephium-map-driver/src/driver/tests.rs b/crates/zephium-map-driver/src/driver/tests.rs new file mode 100644 index 000000000..7a63fec56 --- /dev/null +++ b/crates/zephium-map-driver/src/driver/tests.rs @@ -0,0 +1,1058 @@ +use super::*; +use crate::{ + io::{Clock, Fetcher, ResultsPage, ResultsSource, SystemClock}, + memo::{Memo, MemoryMemo}, + wire::{Failure as WireFailure, Network, Outcome, Target}, + Reading, +}; +use std::sync::atomic::AtomicUsize; +use tokio::sync::oneshot; +use zephium_map::{ + session::{FetchResult, FETCH_TIMEOUT, LAST_START, MAX_ELAPSED}, + PlaceKey, +}; + +const RESULT: &str = + "
"; +const BOTH: &str = "
"; +const NAV: &str = + "Acme Workshop"; + +#[derive(Clone)] +enum Plan { + Page(&'static str, String), + Hang, + Fail(Failure), +} + +#[derive(Default)] +struct Seen { + active: BTreeMap, + max_active: usize, + max_host: usize, + fetches: Vec, +} + +struct Fake { + results: Plan, + results_wait: Option>>, + pages: BTreeMap, + delay: Duration, + seen: Mutex, + calls: AtomicUsize, + memo_calls: AtomicUsize, + memo: MemoryMemo, + clock: SystemClock, +} + +impl Fake { + fn new(results: Plan) -> Self { + Self { + results, + results_wait: None, + pages: BTreeMap::new(), + delay: Duration::from_millis(5), + seen: Mutex::default(), + calls: AtomicUsize::new(0), + memo_calls: AtomicUsize::new(0), + memo: MemoryMemo::new(), + clock: SystemClock::new(), + } + } + + fn site(mut self, host: &str, pages: &[(&str, Plan)]) -> Self { + for (path, plan) in pages { + self.pages.insert(format!("{host}{path}"), plan.clone()); + } + self + } + + fn seen(&self) -> std::sync::MutexGuard<'_, Seen> { + self.seen.lock().unwrap() + } +} + +fn html(body: &str) -> Plan { + Plan::Page("text/html", body.to_owned()) +} + +fn acme(fake: Fake) -> Fake { + fake.site( + "acme.com", + &[ + ("/", html(NAV)), + ( + "/pricing", + html("

Tiers

Teams

"), + ), + ("/news", html("

Launch

")), + ], + ) +} + +struct Active(Arc, String); + +impl Drop for Active { + fn drop(&mut self) { + if let Some(n) = self.0.seen().active.get_mut(&self.1) { + *n -= 1; + } + } +} + +impl ResultsSource for Fake { + fn load(&self, url: Url) -> Reading> { + self.calls.fetch_add(1, Ordering::SeqCst); + let plan = self.results.clone(); + let wait = self.results_wait.clone(); + Box::pin(async move { + if let Some(wait) = wait { + let (deliver, delivery) = oneshot::channel(); + wait.send(deliver).await.unwrap(); + delivery.await.unwrap(); + } + match plan { + Plan::Page(_, html) => Ok(ResultsPage { + html, + url, + truncated: false, + }), + Plan::Hang => std::future::pending().await, + Plan::Fail(failure) => Err(failure), + } + }) + } +} + +struct Reader(Arc); + +impl Fetcher for Reader { + fn fetch(&self, request: FetchRequest) -> Reading> { + let fake = Arc::clone(&self.0); + fake.calls.fetch_add(1, Ordering::SeqCst); + let host = request.url.host_str().unwrap_or_default().to_owned(); + let page = format!("{host}{}", request.url.path()); + let plan = fake + .pages + .get(&page) + .cloned() + .unwrap_or(Plan::Fail(Failure::Missing)); + Box::pin(async move { + { + let mut seen = fake.seen(); + seen.fetches.push(page); + *seen.active.entry(host.clone()).or_default() += 1; + let total = seen.active.values().sum(); + let here = seen.active[&host]; + seen.max_host = seen.max_host.max(here); + seen.max_active = seen.max_active.max(total); + } + let _active = Active(Arc::clone(&fake), host); + tokio::time::sleep(fake.delay).await; + match plan { + Plan::Page(media, body) => Ok(FetchResult { + final_url: request.url, + content_type: media.into(), + charset: None, + bytes: body.into_bytes(), + truncated: false, + }), + Plan::Hang => std::future::pending().await, + Plan::Fail(failure) => Err(failure), + } + }) + } +} + +impl Memo for Fake { + fn lookup(&self, profile: &str, site: &PlaceKey) -> Option> { + self.memo_calls.fetch_add(1, Ordering::SeqCst); + self.memo.lookup(profile, site) + } + + fn remember(&self, profile: &str, site: &PlaceKey, memo: Vec) { + self.memo_calls.fetch_add(1, Ordering::SeqCst); + self.memo.remember(profile, site, memo) + } +} + +impl Clock for Fake { + fn now(&self) -> Duration { + self.calls.fetch_add(1, Ordering::SeqCst); + self.clock.now() + } + + fn unix(&self) -> u64 { + self.calls.fetch_add(1, Ordering::SeqCst); + 1_000_000 + } +} + +fn io(fake: &Arc) -> Io { + Io { + results: fake.clone(), + fetch: Arc::new(Reader(Arc::clone(fake))), + memo: fake.clone(), + clock: fake.clone(), + } +} + +fn request(query: &str) -> MapRequest { + MapRequest { + query: query.into(), + engine: SearchEngine::DuckDuckGo, + session_id: 7, + profile: "profile".into(), + private: false, + } +} + +fn start(fake: &Arc, request: MapRequest) -> (Driver, mpsc::Receiver) { + Driver::start(request, io(fake), &Handle::current()).unwrap() +} + +async fn rest(rx: &mut mpsc::Receiver) -> Vec { + let mut out = Vec::new(); + while let Some(change) = rx.recv().await { + let end = matches!(change, Change::End { .. }); + out.push(change); + if end { + break; + } + } + out +} + +fn checked(changes: &[Change], first: u32) { + for (n, change) in changes.iter().enumerate() { + assert_eq!(change.seq(), first + n as u32); + } + let ends = changes + .iter() + .filter(|c| matches!(c, Change::End { .. })) + .count(); + assert_eq!(ends, 1); + assert!(matches!(changes.last(), Some(Change::End { .. }))); +} + +fn outcome(changes: &[Change]) -> (Outcome, u32) { + match changes.last() { + Some(Change::End { + outcome, + elapsed_ms, + .. + }) => (*outcome, *elapsed_ms), + _ => panic!("no end"), + } +} + +fn last_for(changes: &[Change], slot: u8) -> Option<&Change> { + changes.iter().rev().find(|c| { + matches!(c, Change::Place { slot: s, .. } | Change::PlaceFailed { slot: s, .. } if *s == slot) + }) +} + +fn noisy_results() -> Plan { + html(&format!( + "{RESULT}", + "var s = '';".repeat(page::MAX_RESULTS_PAGE_BYTES / 8), + "p{}".repeat(1000) + )) +} + +async fn until(fake: &Fake, path: &str) { + while !fake.seen().fetches.iter().any(|f| f == path) { + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +fn active(fake: &Fake) -> usize { + fake.seen().active.values().sum() +} + +#[tokio::test(start_paused = true)] +async fn a_place_streams_first_layer_then_places_then_one_end() { + let fake = Arc::new(acme(Fake::new(noisy_results()))); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert!(matches!(changes[0], Change::FirstLayer { organic: 1, .. })); + let places = &changes[1..changes.len() - 1]; + assert!(!places.is_empty()); + assert!(places + .iter() + .all(|c| matches!(c, Change::Place { slot: 0, .. }))); + assert!(matches!( + places.last(), + Some(Change::Place { complete: true, .. }) + )); + assert!(places[..places.len() - 1].iter().all(|c| matches!( + c, + Change::Place { + complete: false, + .. + } + ))); + assert_eq!(outcome(&changes).0, Outcome::Done); + let Some(Change::Place { place, .. }) = places.last() else { + unreachable!() + }; + let pricing = place + .sections + .iter() + .find(|e| e.label == "Pricing") + .unwrap(); + assert!(pricing.open && pricing.read.is_none() && pricing.children.is_empty()); + let before = driver.counts(); + driver.open(0, &pricing.id).unwrap(); + let Some(Change::Place { + slot: 0, + place, + complete: true, + seq, + .. + }) = rx.recv().await + else { + panic!("expected complete replacement"); + }; + assert_eq!(seq, changes.last().unwrap().seq() + 1); + let opened = rx.recv().await.unwrap(); + assert_eq!( + opened, + Change::Opened { + seq: seq + 1, + slot: 0, + id: pricing.id.clone(), + result: OpenResult::Read, + } + ); + let pricing = place.sections.iter().find(|e| e.id == pricing.id).unwrap(); + assert!(!pricing.open); + assert_eq!(driver.counts().fetches, before.fetches + 1); + assert!(driver.counts().bytes > before.bytes); + let tiers = pricing + .children + .iter() + .find(|e| e.label == "Tiers") + .unwrap(); + assert_eq!( + driver + .target( + 0, + &Target::Entry { + id: tiers.id.clone() + } + ) + .map(|u| u.to_string()), + Some("https://acme.com/pricing#tiers".into()) + ); + assert_eq!( + driver.target(0, &Target::Site).map(|u| u.to_string()), + Some("https://acme.com/".into()) + ); + let unknown = Target::Entry { + id: "0000000000000000".into(), + }; + let social = Target::Social { + network: Network::GitHub, + }; + for (slot, target) in [ + (0, &unknown), + (1, &Target::Site), + (2, &Target::Site), + (0, &social), + ] { + assert_eq!(driver.target(slot, target), None); + } + let counts = driver.counts(); + assert_eq!( + counts, + Counts { + fetches: counts.fetches, + bytes: counts.bytes, + ..Counts::default() + } + ); + let fetched = fake.seen().fetches.len(); + tokio::time::sleep(Duration::from_secs(30)).await; + assert_eq!(fake.seen().fetches.len(), fetched); + assert_eq!(active(&fake), 0); +} + +#[tokio::test(start_paused = true)] +async fn a_comparison_side_without_a_site_ends_failed() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = start(&fake, request("acme vs other")); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert!(matches!( + last_for(&changes, 0), + Some(Change::Place { complete: true, .. }) + )); + assert!(matches!( + last_for(&changes, 1), + Some(Change::PlaceFailed { + failure: WireFailure::Unavailable, + .. + }) + )); + assert!(!changes.iter().any(|c| matches!(c, Change::Compare { .. }))); + assert_eq!(driver.counts().anonymous_unavailable, 1); + assert_eq!(driver.target(1, &Target::Site), None); +} + +#[tokio::test(start_paused = true)] +async fn both_sides_compare_and_reads_stay_under_the_ceilings() { + let many = |prefix: &str| { + let links: String = (0..12) + .map(|n| format!("Part {n}")) + .collect(); + html(&format!( + "T" + )) + }; + let mut fake = Fake::new(html(BOTH)) + .site( + "acme.com", + &[("/", many("a")), ("/pricing", html("

Plans

"))], + ) + .site( + "other.com", + &[("/", many("o")), ("/pricing", html("

Plans

"))], + ); + fake.delay = Duration::from_millis(200); + let fake = Arc::new(fake); + let (driver, mut rx) = start(&fake, request("acme vs other")); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert!(changes.iter().any(|c| matches!(c, Change::Compare { .. }))); + let seen = fake.seen(); + assert!(seen.fetches.len() > MAX_CONCURRENT); + assert!(seen.max_active <= MAX_CONCURRENT && seen.max_active > 1); + assert!(seen.max_host <= MAX_HOST_CONCURRENT); + assert_eq!(driver.counts().over_ceiling, 0); +} + +#[tokio::test(start_paused = true)] +async fn the_driver_refuses_reads_over_the_ceilings() { + let fake = Arc::new(Fake::new(Plan::Hang).site("a.com", &[("/", Plan::Hang)])); + let (session, _) = Session::start(Config::default(), "acme").unwrap(); + let (tx, _rx) = mpsc::channel(CHANGE_BUFFER); + let mut run = Run { + session: Some(session), + io: io(&fake), + profile: String::new(), + private: false, + tx, + shared: Arc::default(), + reads: JoinSet::new(), + tasks: HashMap::new(), + hosts: BTreeMap::new(), + immediate: VecDeque::new(), + seq: 0, + started: Some(Duration::ZERO), + cancelled: watch::channel(false).1, + cancelling: false, + unsent: None, + open_requests: mpsc::channel(MAX_WAITING_OPENS).1, + opening: None, + session_id: 0, + }; + for (n, host) in ["a.com", "a.com", "a.com", "b.com", "c.com", "d.com"] + .into_iter() + .enumerate() + { + run.fetch( + Id { + session: 0, + sequence: n as u32, + }, + FetchRequest { + url: Url::parse(&format!("https://{host}/")).unwrap(), + expect: zephium_map::session::Expect::Html, + max_bytes: 1, + timeout: Duration::from_secs(1), + }, + ); + } + assert_eq!(run.hosts.len(), MAX_CONCURRENT); + assert_eq!(run.reads.len(), MAX_CONCURRENT); + assert_eq!(run.shared.over_ceiling.load(Ordering::SeqCst), 2); + assert_eq!(run.immediate.len(), 2); + assert!(run.immediate.iter().all(|i| matches!( + i, + Input::Fetch { + result: Err(Failure::Limit), + .. + } + ))); + let done = run.reads.join_next_with_id().await.unwrap(); + assert!(matches!( + run.completed(done), + Some(Input::Fetch { + result: Err(Failure::Missing), + .. + }) + )); + assert_eq!(run.hosts.len(), MAX_CONCURRENT - 1); +} + +#[tokio::test] +async fn two_fetch_answers_are_counted_and_the_counts_survive_cancel() { + const ROBOTS: &str = "User-agent: *\nAllow: /\n"; + let fake = Arc::new(Fake::new(html(RESULT)).site( + "acme.com", + &[ + ("/robots.txt", Plan::Page("text/plain", ROBOTS.into())), + ("/", html(NAV)), + ], + )); + // The first layer fills the buffer so the first place blocks further effects. + let (driver, mut rx) = + Driver::start_buffered(request("acme"), io(&fake), &Handle::current(), 1).unwrap(); + let bytes = (ROBOTS.len() + NAV.len()) as u64; + tokio::time::timeout(FETCH_TIMEOUT, async { + while driver.counts().bytes < bytes { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + assert_eq!(driver.counts().fetches, 2); + assert_eq!(driver.counts().bytes, bytes); + driver.cancel(); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!(outcome(&changes).0, Outcome::Cancelled); + assert_eq!(driver.counts().fetches, 2); + assert_eq!(driver.counts().bytes, bytes); +} + +#[tokio::test(start_paused = true)] +async fn cancel_ends_once_and_starts_nothing_after() { + let fake = Arc::new(Fake::new(html(RESULT)).site("acme.com", &[("/", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + let first = rx.recv().await.unwrap(); + assert!(matches!(first, Change::FirstLayer { seq: 0, .. })); + until(&fake, "acme.com/").await; + assert_eq!(active(&fake), 1); + let fetched = fake.seen().fetches.len(); + driver.cancel(); + driver.cancel(); + let changes = rest(&mut rx).await; + checked(&changes, 1); + assert_eq!(changes.len(), 1); + assert_eq!(outcome(&changes).0, Outcome::Cancelled); + assert!(tokio::time::timeout(FETCH_TIMEOUT, rx.recv()) + .await + .unwrap() + .is_none()); + tokio::time::sleep(Duration::from_secs(30)).await; + assert_eq!(active(&fake), 0); + assert_eq!(fake.seen().fetches.len(), fetched); + driver.cancel(); +} + +#[tokio::test(start_paused = true)] +async fn a_blocked_place_cannot_dispatch_a_fetch_after_the_deadline() { + for deadline in [zephium_map::session::LAST_START, MAX_ELAPSED] { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = stalled(&fake); + while driver.counts().bytes < NAV.len() as u64 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + tokio::time::advance(deadline).await; + let changes = rest(&mut rx).await; + assert_eq!(outcome(&changes).0, Outcome::Done); + assert_eq!(driver.counts().fetches, 2); + } +} + +fn stalled(fake: &Arc) -> (Driver, mpsc::Receiver) { + Driver::start_buffered(request("acme"), io(fake), &Handle::current(), 1).unwrap() +} + +#[tokio::test(start_paused = true)] +async fn cancel_does_not_wait_behind_a_stalled_receiver() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = stalled(&fake); + until(&fake, "acme.com/").await; + tokio::time::sleep(Duration::from_secs(1)).await; + let fetched = fake.seen().fetches.len(); + assert_eq!(fetched, 2); + driver.cancel(); + tokio::time::sleep(Duration::from_secs(30)).await; + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!(changes.len(), 2); + assert!(matches!(changes[0], Change::FirstLayer { .. })); + assert_eq!(outcome(&changes).0, Outcome::Cancelled); + assert_eq!(fake.seen().fetches.len(), fetched); + assert_eq!(active(&fake), 0); + assert_eq!(driver.target(0, &Target::Site), None); +} + +#[tokio::test(start_paused = true)] +async fn a_receiver_that_never_reads_is_released_by_dropping_the_driver() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = stalled(&fake); + until(&fake, "acme.com/").await; + tokio::time::sleep(Duration::from_secs(1)).await; + driver.cancel(); + tokio::time::sleep(Duration::from_secs(1)).await; + drop(driver); + let changes = rest(&mut rx).await; + assert_eq!(changes.len(), 1); + assert!(matches!(changes[0], Change::FirstLayer { .. })); +} + +#[tokio::test(start_paused = true)] +async fn dropping_the_driver_or_the_receiver_stops_reads_silently() { + for drop_driver in [true, false] { + let fake = Arc::new(Fake::new(html(RESULT)).site("acme.com", &[("/", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + rx.recv().await.unwrap(); + until(&fake, "acme.com/").await; + let fetched = fake.seen().fetches.len(); + if drop_driver { + drop(driver); + assert!(rx.recv().await.is_none()); + } else { + drop(rx); + tokio::time::sleep(Duration::from_secs(1)).await; + assert_eq!(active(&fake), 0); + drop(driver); + } + tokio::time::sleep(Duration::from_secs(30)).await; + assert_eq!(active(&fake), 0); + assert_eq!(fake.seen().fetches.len(), fetched); + } +} + +async fn waiting_for_results( + plan: Plan, +) -> ( + Arc, + Driver, + mpsc::Receiver, + oneshot::Sender<()>, +) { + let (wait, mut pending) = mpsc::channel(1); + let mut fake = acme(Fake::new(plan)); + fake.results_wait = Some(wait); + let fake = Arc::new(fake); + let (driver, rx) = stalled(&fake); + let deliver = pending.recv().await.unwrap(); + (fake, driver, rx, deliver) +} + +#[tokio::test(start_paused = true)] +async fn delayed_results_leave_the_site_read_budget_intact() { + for pause in [LAST_START - Duration::from_secs(1), LAST_START, MAX_ELAPSED] { + let (_fake, driver, mut rx, deliver) = waiting_for_results(html(RESULT)).await; + tokio::time::advance(Duration::from_secs(11)).await; + deliver.send(()).unwrap(); + // A full change buffer holds the first place before its follow-up reads. + tokio::time::timeout(FETCH_TIMEOUT, async { + while driver.counts().bytes < NAV.len() as u64 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the initial site reads should start after results delivery"); + assert_eq!(driver.counts().fetches, 2); + tokio::time::advance(pause).await; + let changes = rest(&mut rx).await; + checked(&changes, 0); + let (result, elapsed_ms) = outcome(&changes); + assert_eq!(result, Outcome::Done); + assert!((pause..pause + TICK).contains(&Duration::from_millis(elapsed_ms.into()))); + assert_eq!(driver.counts().fetches > 2, pause < LAST_START); + } +} + +#[tokio::test(start_paused = true)] +async fn a_late_results_failure_keeps_the_source_failure() { + let (fake, _driver, mut rx, deliver) = waiting_for_results(Plan::Fail(Failure::Consent)).await; + tokio::time::advance(MAX_ELAPSED * 2).await; + deliver.send(()).unwrap(); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!( + outcome(&changes), + ( + Outcome::Failed { + failure: WireFailure::Consent + }, + 0 + ) + ); + assert!(fake.seen().fetches.is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_results_page_that_never_arrives_ends_as_a_timeout() { + let (fake, _driver, mut rx, mut deliver) = waiting_for_results(html(RESULT)).await; + assert!(tokio::time::timeout(RESULTS_WAIT - TICK, rx.recv()) + .await + .is_err()); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!( + outcome(&changes), + ( + Outcome::Failed { + failure: WireFailure::Timeout + }, + 0 + ) + ); + tokio::time::timeout(TICK, deliver.closed()).await.unwrap(); + assert!(fake.seen().fetches.is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn cancel_or_drop_releases_a_pending_first_results_page() { + for cancel in [true, false] { + let (fake, driver, mut rx, mut deliver) = waiting_for_results(html(RESULT)).await; + assert!(tokio::time::timeout(MAX_ELAPSED * 2, rx.recv()) + .await + .is_err()); + if cancel { + driver.cancel(); + driver.cancel(); + let changes = rest(&mut rx).await; + assert_eq!(changes.len(), 1); + checked(&changes, 0); + assert_eq!(outcome(&changes), (Outcome::Cancelled, 0)); + } else { + drop(driver); + } + assert_eq!(rx.recv().await, None); + tokio::time::timeout(TICK, deliver.closed()).await.unwrap(); + assert!(fake.seen().fetches.is_empty()); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), 0); + } +} + +#[tokio::test(start_paused = true)] +async fn a_hanging_fetch_is_ended_by_its_own_timeout() { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/robots.txt", Plan::Hang)])); + let (_driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + checked(&changes, 0); + let (_, elapsed) = outcome(&changes); + assert!(elapsed >= FETCH_TIMEOUT.as_millis() as u32); + assert!(elapsed < MAX_ELAPSED.as_millis() as u32); + assert_eq!(active(&fake), 0); +} + +#[tokio::test(start_paused = true)] +async fn a_results_failure_ends_the_map() { + let fake = Arc::new(Fake::new(Plan::Fail(Failure::Consent))); + let (_driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!( + outcome(&changes).0, + Outcome::Failed { + failure: WireFailure::Consent + } + ); + let over = "a".repeat(page::MAX_RESULTS_PAGE_BYTES + 1); + let fake = Arc::new(Fake::new(html(&over))); + let (_driver, mut rx) = start(&fake, request("acme")); + assert_eq!( + outcome(&rest(&mut rx).await).0, + Outcome::Failed { + failure: WireFailure::Limit + } + ); +} + +#[tokio::test(start_paused = true)] +async fn non_map_queries_are_refused_before_any_io() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + for (query, engine, refusal) in [ + ("", SearchEngine::DuckDuckGo, StartRefusal::Invalid), + ( + "san francisco time", + SearchEngine::DuckDuckGo, + StartRefusal::NotAMap, + ), + ( + "how to reset the timer", + SearchEngine::Google, + StartRefusal::NotAMap, + ), + ( + "acme", + SearchEngine::Custom, + StartRefusal::UnsupportedEngine, + ), + ] { + let result = Driver::start( + MapRequest { + engine, + ..request(query) + }, + io(&fake), + &Handle::current(), + ); + assert_eq!(result.err(), Some(refusal), "{query}"); + } + tokio::time::sleep(Duration::from_secs(1)).await; + assert_eq!(fake.calls.load(Ordering::SeqCst), 0); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test(start_paused = true)] +async fn a_private_map_never_reads_or_writes_the_memo() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (_driver, mut rx) = start(&fake, request("acme")); + rest(&mut rx).await; + let site = PlaceKey::from_url(&Url::parse("https://acme.com/").unwrap()).unwrap(); + assert!(fake.memo.lookup("profile", &site).is_some()); + let fetched = fake.seen().fetches.len(); + let (_driver, mut rx) = start(&fake, request("acme")); + let remembered = rest(&mut rx).await; + checked(&remembered, 0); + assert!(matches!( + last_for(&remembered, 0), + Some(Change::Place { + complete: true, + stale: false, + .. + }) + )); + assert_eq!(fake.seen().fetches.len(), fetched); + let calls = fake.memo_calls.load(Ordering::SeqCst); + let (driver, mut rx) = start( + &fake, + MapRequest { + private: true, + ..request("acme") + }, + ); + let private = rest(&mut rx).await; + checked(&private, 0); + assert!(fake.seen().fetches.len() > fetched); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), calls); + let Some(Change::Place { place, .. }) = last_for(&private, 0) else { + panic!("expected place") + }; + let pricing = place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap(); + driver.open(0, &pricing.id).unwrap(); + assert!(matches!( + rx.recv().await, + Some(Change::Place { complete: true, .. }) + )); + assert!(matches!( + rx.recv().await, + Some(Change::Opened { + result: OpenResult::Read, + .. + }) + )); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), calls); +} + +#[tokio::test(start_paused = true)] +async fn opens_wait_for_search_end_and_the_queue_refuses_at_capacity() { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/llms.txt", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + assert_eq!( + driver.open(1, "0000000000000000"), + Err(OpenRefusal::NoPlace) + ); + assert!(matches!(rx.recv().await, Some(Change::FirstLayer { .. }))); + let Some(Change::Place { + slot: 0, + place, + complete: false, + .. + }) = rx.recv().await + else { + panic!("expected a partial place"); + }; + assert_eq!( + driver.open(0, "0000000000000000"), + Err(OpenRefusal::UnknownEntry) + ); + let id = &place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap() + .id; + for _ in 0..MAX_WAITING_OPENS { + assert_eq!(driver.open(0, id), Ok(())); + } + assert_eq!(driver.open(0, id), Err(OpenRefusal::TooManyWaiting)); + assert!(!fake + .seen() + .fetches + .iter() + .any(|path| path.ends_with("/pricing"))); + let changes = rest(&mut rx).await; + let mut seq = changes.last().unwrap().seq(); + for _ in 0..MAX_WAITING_OPENS { + let place = rx.recv().await.unwrap(); + assert!(matches!(place, Change::Place { complete: true, .. })); + assert_eq!(place.seq(), seq + 1); + let opened = rx.recv().await.unwrap(); + seq += 2; + assert_eq!( + opened, + Change::Opened { + seq, + slot: 0, + id: id.clone(), + result: OpenResult::Read + } + ); + } + assert_eq!(driver.open(0, id), Err(OpenRefusal::NotOpenable)); + assert_eq!( + fake.seen() + .fetches + .iter() + .filter(|path| path.ends_with("/pricing")) + .count(), + 1 + ); +} + +#[tokio::test(start_paused = true)] +async fn an_open_after_a_long_idle_gets_its_full_fetch_timeout() { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/pricing", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + let Some(Change::Place { place, .. }) = last_for(&changes, 0) else { + panic!("expected place"); + }; + let id = &place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap() + .id; + tokio::time::advance(MAX_ELAPSED * 2).await; + let opened = fake.clock.now(); + driver.open(0, id).unwrap(); + assert!(matches!( + rx.recv().await, + Some(Change::Place { complete: true, .. }) + )); + assert!(matches!( + rx.recv().await, + Some(Change::Opened { + result: OpenResult::Refused { + failure: WireFailure::Timeout + }, + .. + }) + )); + assert!(fake + .seen() + .fetches + .iter() + .any(|path| path == "acme.com/pricing")); + assert_eq!(fake.clock.now() - opened, FETCH_TIMEOUT); +} + +#[tokio::test(start_paused = true)] +async fn cancelling_or_dropping_during_an_open_aborts_it_silently() { + for cancel in [true, false] { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/pricing", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + let Some(Change::Place { place, .. }) = last_for(&changes, 0) else { + panic!("expected place") + }; + let id = &place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap() + .id; + driver.open(0, id).unwrap(); + until(&fake, "acme.com/pricing").await; + assert_eq!(active(&fake), 1); + if cancel { + driver.cancel(); + assert_eq!(driver.open(0, id), Err(OpenRefusal::Cancelled)); + assert_eq!(rx.recv().await, None); + } else { + drop(driver); + assert_eq!(rx.recv().await, None); + } + tokio::task::yield_now().await; + assert_eq!(active(&fake), 0); + } +} + +#[tokio::test(start_paused = true)] +async fn an_idle_map_keeps_no_periodic_clock_or_io_activity() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + let calls = fake.calls.load(Ordering::SeqCst); + let memo_calls = fake.memo_calls.load(Ordering::SeqCst); + for _ in 0..10 { + tokio::time::advance(TICK).await; + tokio::task::yield_now().await; + } + assert_eq!(fake.calls.load(Ordering::SeqCst), calls); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), memo_calls); + assert_eq!(rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)); + checked(&changes, 0); + driver.cancel(); + assert_eq!(rx.recv().await, None); +} + +#[tokio::test(start_paused = true)] +async fn comparison_also_targets_use_the_original_results_without_fetching_them() { + let results = BOTH.replace( + "", + concat!( + "", + "", + "" + ), + ); + let fake = Arc::new(acme(Fake::new(html(&results)))); + let (driver, mut rx) = start(&fake, request("acme vs other")); + let Some(Change::FirstLayer { also, .. }) = rx.recv().await else { + panic!("expected results") + }; + assert_eq!( + also.iter() + .map(|item| item.host.as_str()) + .collect::>(), + ["reddit.com", "reviews.example"] + ); + assert_eq!( + driver + .target(0, &Target::Also { index: 0 }) + .unwrap() + .host_str(), + Some("reddit.com") + ); + assert_eq!(driver.target(1, &Target::Also { index: 1 }), None); + assert_eq!(driver.target(0, &Target::Also { index: 2 }), None); + let _ = rest(&mut rx).await; + assert!(!fake + .seen() + .fetches + .iter() + .any(|path| path.starts_with("reddit.com") || path.starts_with("reviews.example"))); +} diff --git a/crates/zephium-map-driver/src/io.rs b/crates/zephium-map-driver/src/io.rs new file mode 100644 index 000000000..1149f9844 --- /dev/null +++ b/crates/zephium-map-driver/src/io.rs @@ -0,0 +1,80 @@ +use std::{ + future::Future, + pin::Pin, + sync::Arc, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use url::Url; +use zephium_map::session::{Expect, Failure, FetchResult}; + +use crate::memo::Memo; + +pub type Reading = Pin + Send + 'static>>; + +pub struct ResultsPage { + /// The serialised live DOM of the committed results page. + pub html: String, + pub url: Url, + pub truncated: bool, +} + +pub trait ResultsSource: Send + Sync { + fn load(&self, url: Url) -> Reading>; +} + +pub struct FetchRequest { + pub url: Url, + pub expect: Expect, + pub max_bytes: u32, + pub timeout: Duration, +} + +pub trait Fetcher: Send + Sync { + fn fetch(&self, request: FetchRequest) -> Reading>; +} + +pub trait Clock: Send + Sync { + /// Monotonic time since an arbitrary origin. + fn now(&self) -> Duration; + /// Wall-clock seconds, used only to judge a memo's age. + fn unix(&self) -> u64; +} + +pub struct SystemClock { + origin: tokio::time::Instant, +} + +impl SystemClock { + pub fn new() -> Self { + Self { + origin: tokio::time::Instant::now(), + } + } +} + +impl Default for SystemClock { + fn default() -> Self { + Self::new() + } +} + +impl Clock for SystemClock { + fn now(&self) -> Duration { + self.origin.elapsed() + } + + fn unix(&self) -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.as_secs()) + } +} + +#[derive(Clone)] +pub struct Io { + pub results: Arc, + pub fetch: Arc, + pub memo: Arc, + pub clock: Arc, +} diff --git a/crates/zephium-map-driver/src/lib.rs b/crates/zephium-map-driver/src/lib.rs new file mode 100644 index 000000000..e3b210631 --- /dev/null +++ b/crates/zephium-map-driver/src/lib.rs @@ -0,0 +1,16 @@ +#![forbid(unsafe_code)] + +mod driver; +mod io; +mod memo; +mod page; +mod public; +pub mod wire; + +pub use driver::{Counts, Driver, MapRequest, CHANGE_BUFFER, MAX_WAITING_OPENS, TICK}; +pub use io::{Clock, FetchRequest, Fetcher, Io, Reading, ResultsPage, ResultsSource, SystemClock}; +pub use memo::{ + Memo, MemoryMemo, MAX_MEMO_BYTES, MAX_MEMO_PLACES, MAX_MEMO_PROFILES, MAX_PROFILE_KEY_BYTES, +}; +pub use page::{MAX_RESULTS_PAGE_BYTES, MAX_RESULTS_SOURCE_BYTES}; +pub use public::PublicIo; diff --git a/crates/zephium-map-driver/src/memo.rs b/crates/zephium-map-driver/src/memo.rs new file mode 100644 index 000000000..b275bfa49 --- /dev/null +++ b/crates/zephium-map-driver/src/memo.rs @@ -0,0 +1,160 @@ +use std::{ + collections::VecDeque, + sync::{Mutex, PoisonError}, +}; + +use zephium_map::PlaceKey; + +pub const MAX_MEMO_PLACES: usize = 64; +pub const MAX_MEMO_BYTES: usize = 8 * 1024 * 1024; +pub const MAX_MEMO_PROFILES: usize = 16; +pub const MAX_PROFILE_KEY_BYTES: usize = 128; + +pub trait Memo: Send + Sync { + fn lookup(&self, profile: &str, site: &PlaceKey) -> Option>; + fn remember(&self, profile: &str, site: &PlaceKey, memo: Vec); +} + +#[derive(Default)] +struct Shelf { + places: VecDeque<(PlaceKey, Vec)>, + bytes: usize, +} + +impl Shelf { + fn remove(&mut self, site: &PlaceKey) { + if let Some(at) = self.places.iter().position(|(key, _)| key == site) { + if let Some((_, memo)) = self.places.remove(at) { + self.bytes -= memo.len(); + } + } + } + + fn insert(&mut self, site: &PlaceKey, memo: Vec) { + self.remove(site); + self.bytes += memo.len(); + self.places.push_back((site.clone(), memo)); + while self.places.len() > MAX_MEMO_PLACES || self.bytes > MAX_MEMO_BYTES { + let Some((_, oldest)) = self.places.pop_front() else { + break; + }; + self.bytes -= oldest.len(); + } + } +} + +#[derive(Default)] +pub struct MemoryMemo { + profiles: Mutex>, +} + +impl MemoryMemo { + pub fn new() -> Self { + Self::default() + } +} + +impl Memo for MemoryMemo { + fn lookup(&self, profile: &str, site: &PlaceKey) -> Option> { + if profile.len() > MAX_PROFILE_KEY_BYTES { + return None; + } + let profiles = self.profiles.lock().unwrap_or_else(PoisonError::into_inner); + let (_, shelf) = profiles.iter().find(|(key, _)| key == profile)?; + shelf + .places + .iter() + .find(|(key, _)| key == site) + .map(|(_, memo)| memo.clone()) + } + + fn remember(&self, profile: &str, site: &PlaceKey, memo: Vec) { + if profile.len() > MAX_PROFILE_KEY_BYTES { + return; + } + let mut profiles = self.profiles.lock().unwrap_or_else(PoisonError::into_inner); + let mut shelf = match profiles.iter().position(|(key, _)| key == profile) { + Some(at) => profiles + .remove(at) + .map(|(_, shelf)| shelf) + .unwrap_or_default(), + None => Shelf::default(), + }; + if memo.len() > MAX_MEMO_BYTES { + shelf.remove(site); + } else { + shelf.insert(site, memo); + } + profiles.push_back((profile.to_owned(), shelf)); + while profiles.len() > MAX_MEMO_PROFILES { + profiles.pop_front(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use url::Url; + + fn site(n: usize) -> PlaceKey { + PlaceKey::from_url(&Url::parse(&format!("https://site{n}.com/")).unwrap()).unwrap() + } + + #[test] + fn places_are_capped_and_the_oldest_goes_first() { + let memo = MemoryMemo::new(); + for n in 0..=MAX_MEMO_PLACES { + memo.remember("a", &site(n), vec![n as u8]); + } + assert_eq!(memo.lookup("a", &site(0)), None); + assert_eq!(memo.lookup("a", &site(1)), Some(vec![1])); + assert_eq!( + memo.lookup("a", &site(MAX_MEMO_PLACES)), + Some(vec![MAX_MEMO_PLACES as u8]) + ); + memo.remember("a", &site(1), vec![9]); + memo.remember("a", &site(MAX_MEMO_PLACES + 1), vec![0]); + assert_eq!(memo.lookup("a", &site(1)), Some(vec![9])); + assert_eq!(memo.lookup("a", &site(2)), None); + } + + #[test] + fn bytes_are_capped_at_the_limit() { + let memo = MemoryMemo::new(); + let quarter = MAX_MEMO_BYTES / 4; + for n in 0..4 { + memo.remember("a", &site(n), vec![0; quarter]); + } + assert!((0..4).all(|n| memo.lookup("a", &site(n)).is_some())); + memo.remember("a", &site(4), vec![0; 1]); + assert_eq!(memo.lookup("a", &site(0)), None); + assert!(memo.lookup("a", &site(4)).is_some()); + memo.remember("a", &site(5), vec![0; MAX_MEMO_BYTES]); + assert_eq!( + memo.lookup("a", &site(5)).map(|m| m.len()), + Some(MAX_MEMO_BYTES) + ); + assert!((1..5).all(|n| memo.lookup("a", &site(n)).is_none())); + memo.remember("a", &site(5), vec![0; MAX_MEMO_BYTES + 1]); + assert_eq!(memo.lookup("a", &site(5)), None); + } + + #[test] + fn profiles_are_isolated_and_bounded() { + let memo = MemoryMemo::new(); + memo.remember("a", &site(0), vec![1]); + assert_eq!(memo.lookup("b", &site(0)), None); + let long = "p".repeat(MAX_PROFILE_KEY_BYTES + 1); + memo.remember(&long, &site(0), vec![1]); + assert_eq!(memo.lookup(&long, &site(0)), None); + let edge = "p".repeat(MAX_PROFILE_KEY_BYTES); + memo.remember(&edge, &site(0), vec![2]); + assert_eq!(memo.lookup(&edge, &site(0)), Some(vec![2])); + for n in 0..MAX_MEMO_PROFILES { + memo.remember(&format!("other{n}"), &site(0), vec![3]); + } + assert_eq!(memo.lookup("a", &site(0)), None); + assert_eq!(memo.lookup("other0", &site(0)), Some(vec![3])); + } +} diff --git a/crates/zephium-map-driver/src/page.rs b/crates/zephium-map-driver/src/page.rs new file mode 100644 index 000000000..3fc38b7bd --- /dev/null +++ b/crates/zephium-map-driver/src/page.rs @@ -0,0 +1,293 @@ +use zephium_map::{session::Failure, Doc, DocLimits}; + +use crate::io::ResultsPage; + +pub const MAX_RESULTS_SOURCE_BYTES: usize = 8 * 1024 * 1024; +pub const MAX_RESULTS_PAGE_BYTES: usize = DocLimits::RESULTS.input_bytes as usize; + +const DROPPED: [&[u8]; 2] = [b"script", b"style"]; +const VERBATIM: [&[u8]; 6] = [ + b"textarea", + b"title", + b"xmp", + b"iframe", + b"noembed", + b"noframes", +]; + +pub(crate) fn parse(page: &ResultsPage) -> Result { + let text = strip(&page.html)?; + Doc::from_html( + &page.url, + text.as_bytes(), + Some("utf-8"), + DocLimits::RESULTS, + ) + .map_err(|_| Failure::Unreadable) +} + +pub(crate) fn floor_boundary(text: &str, at: usize) -> usize { + let mut at = at.min(text.len()); + while !text.is_char_boundary(at) { + at -= 1; + } + at +} + +struct Out(String); + +impl Out { + fn push(&mut self, text: &str) -> Result<(), Failure> { + if self.0.len() + text.len() > MAX_RESULTS_PAGE_BYTES { + return Err(Failure::Limit); + } + self.0.push_str(text); + Ok(()) + } +} + +/// Where a script or style ends must agree with the HTML tokenizer, or a +/// dropped span could swallow markup the parser would have read. +pub(crate) fn strip(source: &str) -> Result { + let source = &source[..floor_boundary(source, MAX_RESULTS_SOURCE_BYTES)]; + let bytes = source.as_bytes(); + let mut out = Out(String::with_capacity( + source.len().min(MAX_RESULTS_PAGE_BYTES), + )); + let mut copied = 0; + let mut at = 0; + while let Some(lt) = find_byte(bytes, at, b'<') { + let rest = &bytes[lt..]; + if rest.starts_with(b"").map_or(bytes.len(), |end| end + 3); + } else if rest.starts_with(b"").map_or(bytes.len(), |end| end + 3); + } else if rest.get(1).is_some_and(u8::is_ascii_alphabetic) { + let name_end = bytes[lt + 1..] + .iter() + .position(|b| matches!(b, b'\t' | b'\n' | b'\x0c' | b'\r' | b' ' | b'/' | b'>')) + .map_or(bytes.len(), |n| lt + 1 + n); + let name = &bytes[lt + 1..name_end]; + let open_end = tag_end(bytes, name_end); + at = open_end; + if DROPPED.iter().any(|d| d.eq_ignore_ascii_case(name)) { + out.push(&source[copied..open_end])?; + let close = if name.eq_ignore_ascii_case(b"script") { + script_end(bytes, open_end) + } else { + end_tag(bytes, open_end, name) + }; + copied = close; + at = close; + } else if VERBATIM.iter().any(|v| v.eq_ignore_ascii_case(name)) { + at = end_tag(bytes, open_end, name); + } else if name.eq_ignore_ascii_case(b"plaintext") { + at = bytes.len(); + } + } else if rest.get(1) == Some(&b'/') && rest.get(2).is_some_and(u8::is_ascii_alphabetic) { + at = tag_end(bytes, lt + 2); + } else if matches!(rest.get(1), Some(b'!' | b'?' | b'/')) { + at = find_byte(bytes, lt + 1, b'>').map_or(bytes.len(), |end| end + 1); + } else { + at = lt + 1; + } + } + out.push(&source[copied..])?; + Ok(out.0) +} + +fn find_byte(bytes: &[u8], from: usize, byte: u8) -> Option { + bytes + .get(from..)? + .iter() + .position(|&b| b == byte) + .map(|n| from + n) +} + +fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option { + bytes + .get(from..)? + .windows(needle.len()) + .position(|w| w == needle) + .map(|n| from + n) +} + +fn tag_end(bytes: &[u8], from: usize) -> usize { + let mut at = from; + while at < bytes.len() { + match bytes[at] { + b'>' => return at + 1, + b'=' => { + at += 1; + while bytes.get(at).is_some_and(|b| b.is_ascii_whitespace()) { + at += 1; + } + if let Some("e @ (b'"' | b'\'')) = bytes.get(at) { + at = find_byte(bytes, at + 1, quote).map_or(bytes.len(), |end| end + 1); + } + } + _ => at += 1, + } + } + bytes.len() +} + +fn delimited(bytes: &[u8], at: usize) -> bool { + matches!( + bytes.get(at), + Some(b'\t' | b'\n' | b'\x0c' | b'\r' | b' ' | b'/' | b'>') + ) +} + +fn tag_at(bytes: &[u8], at: usize, prefix: &[u8], name: &[u8]) -> bool { + let start = at + prefix.len(); + bytes.get(at..start) == Some(prefix) + && bytes + .get(start..start + name.len()) + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + && delimited(bytes, start + name.len()) +} + +fn end_tag(bytes: &[u8], from: usize, name: &[u8]) -> usize { + let mut at = from; + while let Some(lt) = find_byte(bytes, at, b'<') { + if tag_at(bytes, lt, b" usize { + #[derive(PartialEq)] + enum State { + Data, + Escaped, + DoubleEscaped, + } + let mut state = State::Data; + let mut at = from; + while at < bytes.len() { + let rest = &bytes[at..]; + if state != State::Data && rest.starts_with(b"-->") { + state = State::Data; + at += 3; + } else if state == State::Data && rest.starts_with(b"

z

").unwrap(), + "

z

" + ); + assert_eq!( + strip("

z

").unwrap(), + "

z

" + ); + } + + #[test] + fn tags_only_count_where_the_tokenizer_reads_tags() { + for kept in [ + "

a

", + "
\">a

b

", + "
a
", + "

b

", + "<style>

b

", + "\">

b

", + " ?>

a

", + "<script>a", + "a < b <3 <<script", + ] { + assert_eq!(strip(kept).unwrap(), kept); + } + } + + #[test] + fn the_page_limit_applies_after_stripping() { + let at = "a".repeat(MAX_RESULTS_PAGE_BYTES); + assert_eq!(strip(&at).unwrap().len(), MAX_RESULTS_PAGE_BYTES); + let over = "a".repeat(MAX_RESULTS_PAGE_BYTES + 1); + assert_eq!(strip(&over), Err(Failure::Limit)); + let wrapped = format!( + "<p>a</p><script>{}</script>", + "x".repeat(MAX_RESULTS_PAGE_BYTES) + ); + assert_eq!(strip(&wrapped).unwrap(), "<p>a</p><script></script>"); + } + + #[test] + fn the_source_is_cut_at_a_character_boundary() { + let lead = "<p>a</p><script>"; + let fill = MAX_RESULTS_SOURCE_BYTES - lead.len() - 1; + let source = format!("{lead}{}é<p>after the cap</p>", "x".repeat(fill)); + assert!(!source.is_char_boundary(MAX_RESULTS_SOURCE_BYTES)); + assert_eq!(strip(&source).unwrap(), "<p>a</p><script>"); + assert_eq!(floor_boundary("é", 1), 0); + assert_eq!(floor_boundary("é", 9), 2); + } + + #[test] + fn a_page_over_the_parser_limit_parses_once_stripped() { + let url = url::Url::parse("https://duckduckgo.com/").unwrap(); + let html = format!( + "<main><article><h2><a href='https://acme.com/'>Acme</a></h2></article></main><script>{}</script>", + "x".repeat(MAX_RESULTS_PAGE_BYTES * 2) + ); + assert!(Doc::from_html(&url, html.as_bytes(), None, DocLimits::RESULTS).is_err()); + let page = ResultsPage { + html, + url, + truncated: false, + }; + assert!(parse(&page).is_ok()); + } +} diff --git a/crates/zephium-map-driver/src/public.rs b/crates/zephium-map-driver/src/public.rs new file mode 100644 index 000000000..5aaebdb76 --- /dev/null +++ b/crates/zephium-map-driver/src/public.rs @@ -0,0 +1,147 @@ +use std::{sync::Arc, time::Instant}; + +use zephium_map::session::{Expect, Failure, FetchResult}; +use zephium_public_fetch::{ + Expect as PublicExpect, PublicBody, PublicReader, ReadRefusal, ReadRequest, ReadSession, + StatusRefusal, +}; + +use crate::io::{FetchRequest, Fetcher, Reading}; + +/// One per map: reads share connections only within it. +pub struct PublicIo { + session: Arc<ReadSession>, +} + +impl PublicIo { + pub fn new(reader: &PublicReader) -> Self { + Self { + session: Arc::new(reader.session()), + } + } +} + +impl Fetcher for PublicIo { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + let session = Arc::clone(&self.session); + Box::pin(async move { + let now = Instant::now(); + let read = ReadRequest { + url: request.url, + expect: match request.expect { + Expect::Html => PublicExpect::Html, + Expect::Xml => PublicExpect::Xml, + Expect::Text => PublicExpect::Text, + }, + max_bytes: request.max_bytes as usize, + deadline: now.checked_add(request.timeout).unwrap_or(now), + }; + session + .read(read) + .await + .map(|body| fetch_result(body, request.expect)) + .map_err(failure) + }) + } +} + +fn fetch_result(body: PublicBody, expect: Expect) -> FetchResult { + let sniffed = match expect { + Expect::Html => "text/html", + Expect::Xml => "application/xml", + Expect::Text => "text/plain", + }; + FetchResult { + final_url: body.final_url, + content_type: match body.media_type.as_deref() { + Some("application/gzip" | "application/x-gzip") if expect == Expect::Xml => { + sniffed.into() + } + _ => body.media_type.unwrap_or_else(|| sniffed.into()), + }, + charset: body.charset, + bytes: body.bytes, + truncated: body.truncated, + } +} + +pub(crate) fn failure(refusal: ReadRefusal) -> Failure { + use ReadRefusal as R; + use StatusRefusal as S; + match refusal { + R::NotPublicHttps | R::RedirectRefused | R::TooManyRedirects | R::DnsRefused => { + Failure::External + } + R::ProxyUnsupported | R::RouteChanged | R::Transport | R::Status(S::Denied) => { + Failure::Unavailable + } + R::Timeout(_) => Failure::Timeout, + R::Status(S::Client) => Failure::Client, + R::Status(S::RateLimited | S::Server) => Failure::Server, + R::Status(S::Challenge) => Failure::Challenge, + R::Status(S::Unexpected) | R::Encoding => Failure::Unreadable, + R::WrongContentType => Failure::ContentType, + R::TooLarge(_) => Failure::Limit, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_reader_refusal_maps_to_the_bench_decision() { + use Failure as F; + let expected = [ + F::External, + F::External, + F::External, + F::External, + F::Unavailable, + F::Unavailable, + F::Timeout, + F::Timeout, + F::Timeout, + F::Timeout, + F::Unavailable, + F::Server, + F::Challenge, + F::Client, + F::Server, + F::Unreadable, + F::ContentType, + F::Limit, + F::Limit, + F::Unreadable, + F::Unavailable, + ]; + assert_eq!(ReadRefusal::ALL.map(failure), expected); + } + + #[test] + fn sniffed_and_compressed_sitemaps_keep_the_expected_media_type() { + let body = |media: Option<&str>| PublicBody { + final_url: url::Url::parse("https://acme.com/sitemap.xml").unwrap(), + hops: 0, + status: zephium_public_fetch::StatusClass::Ok, + media_type: media.map(str::to_owned), + charset: None, + bytes: Vec::new(), + truncated: false, + wire_bytes: 0, + timings: Default::default(), + }; + assert_eq!( + fetch_result(body(None), Expect::Html).content_type, + "text/html" + ); + assert_eq!( + fetch_result(body(Some("application/gzip")), Expect::Xml).content_type, + "application/xml" + ); + assert_eq!( + fetch_result(body(Some("application/gzip")), Expect::Html).content_type, + "application/gzip" + ); + } +} diff --git a/crates/zephium-map-driver/src/wire.rs b/crates/zephium-map-driver/src/wire.rs new file mode 100644 index 000000000..2569d0814 --- /dev/null +++ b/crates/zephium-map-driver/src/wire.rs @@ -0,0 +1,636 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use url::Url; +use zephium_map::{ + compare, + query::{self, SectionRole}, + results::{self, FirstLayer, Profile}, + robots::Robots, + session::{self, ReadState}, + site, PageKey, PlaceKey, SiteKey, +}; + +pub const MAX_TEXT_BYTES: usize = 300; +pub use site::MAX_PATH_CHARS; +pub const MAX_SECTIONS: usize = site::MAX_SECTIONS; +pub const MAX_CHILDREN: usize = 12; +pub const MAX_SOCIAL: usize = 10; +pub const MAX_ALSO: usize = 8; +pub use site::MAX_HOST_BYTES; +pub const MAX_ROWS: usize = 2 * MAX_SECTIONS; +pub const ID_BYTES: usize = 16; + +macro_rules! mirror { + ($name:ident from $engine:path { $($variant:ident),+ $(,)? }) => { + #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] + #[cfg_attr(feature = "ipc-types", derive(specta::Type))] + #[serde(rename_all = "snake_case")] + pub enum $name { + $($variant),+ + } + impl From<$engine> for $name { + fn from(value: $engine) -> Self { + match value { + $(<$engine>::$variant => Self::$variant),+ + } + } + } + }; +} + +mirror!(Role from SectionRole { + News, Product, Features, Solutions, Enterprise, Customers, Community, Security, Legal, + Contact, SignUp, Learn, Examples, Playground, Integrations, Home, Pricing, Documentation, + Api, Reference, Changelog, Releases, Status, Download, Install, Login, Blog, About, Careers, + Support, +}); +mirror!(Network from results::Network { + Twitter, GitHub, YouTube, LinkedIn, Discord, Reddit, Mastodon, Bluesky, Instagram, Facebook, +}); +mirror!(Tier from site::Tier { Primary, Secondary, Action }); +mirror!(Confidence from query::Confidence { Low, High }); + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum StartRefusal { + NotAMap, + UnsupportedEngine, + Invalid, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum OpenRefusal { + NoPlace, + UnknownEntry, + NotOpenable, + TooManyWaiting, + Cancelled, +} + +impl From<session::OpenRefusal> for OpenRefusal { + fn from(refusal: session::OpenRefusal) -> Self { + match refusal { + session::OpenRefusal::UnknownEntry => Self::UnknownEntry, + session::OpenRefusal::NotOpenable => Self::NotOpenable, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum Failure { + Cancelled, + Blocked, + Challenge, + Consent, + NoResults, + Unreadable, + Unavailable, + Timeout, + Limit, + Missing, +} + +impl From<session::Failure> for Failure { + fn from(failure: session::Failure) -> Self { + use session::Failure as F; + match failure { + F::Cancelled => Self::Cancelled, + F::Missing | F::Client => Self::Missing, + F::Server | F::Unavailable => Self::Unavailable, + F::Unreadable | F::ContentType => Self::Unreadable, + F::Timeout => Self::Timeout, + F::External | F::Robots => Self::Blocked, + F::Challenge => Self::Challenge, + F::Consent => Self::Consent, + F::NoResults => Self::NoResults, + F::Limit => Self::Limit, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum Read { + Queued, + Read, + Refused, + Skipped, +} + +impl From<ReadState> for Read { + fn from(state: ReadState) -> Self { + match state { + ReadState::Queued => Self::Queued, + ReadState::Read => Self::Read, + ReadState::Refused { .. } => Self::Refused, + ReadState::Skipped { .. } => Self::Skipped, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Official { + pub title: String, + pub site: String, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum AlsoKind { + Page, + Discussion, + Video, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Also { + pub title: String, + pub host: String, + pub kind: AlsoKind, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Entry { + pub id: String, + pub tier: Tier, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option<Role>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option<String>, + pub off_site: bool, + #[serde(default)] + pub menu_only: bool, + pub open: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host: Option<String>, + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read: Option<Read>, + pub children: Vec<Entry>, + pub more: bool, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Notes { + #[serde(default)] + pub thin: bool, + pub shell: bool, + pub wall: bool, + pub robots_disallowed: bool, + pub truncated: bool, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Place { + pub title: String, + pub site: String, + pub host: String, + pub sections: Vec<Entry>, + pub focus: Option<String>, + pub social: Vec<Network>, + pub notes: Notes, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Row { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option<Role>, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub left: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub right: Option<String>, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Outcome { + Done, + Cancelled, + Failed { failure: Failure }, +} + +impl From<session::EndOutcome> for Outcome { + fn from(outcome: session::EndOutcome) -> Self { + match outcome { + session::EndOutcome::Done => Self::Done, + session::EndOutcome::Cancelled => Self::Cancelled, + session::EndOutcome::Failed { failure } => Self::Failed { + failure: failure.into(), + }, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum OpenResult { + Read, + Refused { failure: Failure }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Change { + FirstLayer { + seq: u32, + official: Option<Official>, + social: Vec<Network>, + organic: u8, + also: Vec<Also>, + }, + Place { + seq: u32, + slot: u8, + place: Place, + stale: bool, + confidence: Confidence, + complete: bool, + }, + PlaceFailed { + seq: u32, + slot: u8, + failure: Failure, + }, + Compare { + seq: u32, + rows: Vec<Row>, + }, + End { + seq: u32, + outcome: Outcome, + elapsed_ms: u32, + }, + Opened { + seq: u32, + slot: u8, + id: String, + result: OpenResult, + }, +} + +impl Change { + pub fn seq(&self) -> u32 { + match self { + Self::FirstLayer { seq, .. } + | Self::Place { seq, .. } + | Self::PlaceFailed { seq, .. } + | Self::Compare { seq, .. } + | Self::End { seq, .. } + | Self::Opened { seq, .. } => *seq, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Target { + Entry { id: String }, + Site, + Social { network: Network }, + Also { index: u8 }, +} + +#[derive(Default)] +pub(crate) struct Targets { + entries: BTreeMap<String, Option<Url>>, + site: Option<Url>, + social: BTreeMap<Network, Url>, +} + +impl Targets { + pub(crate) fn resolve(&self, target: &Target) -> Option<Url> { + let url = match target { + Target::Entry { id } => self.entries.get(id)?.as_ref(), + Target::Site => self.site.as_ref(), + Target::Social { network } => self.social.get(network), + Target::Also { .. } => None, + }?; + (url.scheme() == "https").then(|| url.clone()) + } + + pub(crate) fn has(&self, id: &str) -> bool { + self.entries.contains_key(id) + } +} + +pub(crate) fn text(raw: &str) -> String { + let mut out = String::new(); + let mut space = false; + for c in zephium_map::clean_text(raw).chars() { + if c.is_whitespace() || c.is_control() { + space = !out.is_empty(); + continue; + } + if out.len() + c.len_utf8() + usize::from(space) > MAX_TEXT_BYTES { + break; + } + if std::mem::take(&mut space) { + out.push(' '); + } + out.push(c); + } + out +} + +fn address_shaped(text: &str) -> bool { + let lower = text.to_ascii_lowercase(); + lower.contains("://") + || lower.split(' ').any(|word| { + ["http:", "https:", "www."] + .iter() + .any(|prefix| word.starts_with(prefix)) + }) +} + +fn shown(raw: &str) -> Option<String> { + let text = text(raw); + (!text.is_empty() && !address_shaped(&text)).then_some(text) +} + +fn valid_id(id: &str) -> bool { + id.len() == ID_BYTES && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +pub(crate) use site::display_path as path; + +fn address(entry: &site::Entry) -> Url { + let mut url = entry.key.as_url().clone(); + if url.fragment().is_none() { + if let Some(fragment) = entry.locator.fragment() { + url.set_fragment(fragment.strip_prefix('#')); + } + } + url +} + +fn hostname(url: &Url) -> Option<String> { + site::display_hostname(url).map(str::to_owned) +} + +fn networks(profiles: &[Profile], social: &mut BTreeMap<Network, Url>) -> Vec<Network> { + let mut out = Vec::new(); + for profile in profiles { + let network = Network::from(profile.network); + if out.len() >= MAX_SOCIAL { + break; + } + if !out.contains(&network) { + out.push(network); + social.insert(network, profile.url.clone()); + } + } + out +} + +fn entry( + source: &site::Entry, + child: bool, + place_host: Option<&str>, + open: bool, + seen: &mut BTreeSet<String>, + targets: &mut BTreeMap<String, Option<Url>>, +) -> Option<Entry> { + let id = source.id.as_str(); + if !valid_id(id) || seen.contains(id) { + return None; + } + let path = if source.menu_only { + String::new() + } else { + path(source.key.as_url()) + }; + let label = text(&source.label); + let label = if label.is_empty() { + return None; + } else if !address_shaped(&label) { + label + } else if !path.is_empty() && path != "/" { + path.clone() + } else { + return None; + }; + seen.insert(id.to_owned()); + targets.insert(id.to_owned(), (!source.menu_only).then(|| address(source))); + let mut children = Vec::new(); + let mut more = source.more > 0; + if child { + more |= !source.children.is_empty(); + } else { + let mut rest = source.children.iter(); + for next in rest.by_ref() { + if let Some(projected) = entry(next, true, place_host, false, seen, targets) { + children.push(projected); + if children.len() == MAX_CHILDREN { + break; + } + } + } + more |= rest.next().is_some(); + } + Some(Entry { + id: id.to_owned(), + tier: source.tier.into(), + label, + role: source.role.map(Role::from), + group: source.group.as_deref().and_then(shown), + off_site: source.off_site, + menu_only: source.menu_only, + open, + host: hostname(source.key.as_url()).filter(|host| Some(host.as_str()) != place_host), + path, + read: source.read.map(Read::from), + children, + more, + }) +} + +pub(crate) fn place( + source: &site::Place, + robots: Option<&BTreeMap<String, Robots>>, +) -> (Place, Targets) { + let mut targets = Targets { + site: Some(source.entry.as_url().clone()), + ..Targets::default() + }; + let mut seen = BTreeSet::new(); + let mut ordered: Vec<_> = source.sections.iter().collect(); + ordered.sort_by_key(|e| e.tier); + let mut sections = Vec::new(); + let host = hostname(source.entry.as_url()); + let mut actions = 0; + for section in ordered { + if section.tier == site::Tier::Action && actions == site::MAX_ACTIONS { + continue; + } + if sections.len() == MAX_SECTIONS { + break; + } + let open = robots.is_some_and(|rules| source.entry_openable(&section.id, rules)); + if let Some(projected) = entry( + section, + false, + host.as_deref(), + open, + &mut seen, + &mut targets.entries, + ) { + actions += usize::from(projected.tier == Tier::Action); + sections.push(projected); + } + } + let site = text(source.site.as_str()); + let place = Place { + title: shown(&source.title).unwrap_or_else(|| site.clone()), + host: text(&source.key.host), + site, + sections, + focus: source + .focus + .as_ref() + .map(|id| id.as_str()) + .filter(|id| seen.contains(*id)) + .map(str::to_owned), + social: networks(&source.social, &mut targets.social), + notes: Notes { + thin: source.notes.thin, + shell: source.notes.shell, + wall: source.notes.wall, + robots_disallowed: source.notes.robots_disallowed, + truncated: source.notes.truncated, + }, + }; + (place, targets) +} + +pub(crate) struct Layer { + pub official: Option<Official>, + pub social: Vec<Network>, + pub organic: u8, + pub also: Vec<Also>, + pub targets: Vec<Url>, +} + +pub(crate) fn first_layer(layer: &FirstLayer, places: &[(&PlaceKey, SiteKey)]) -> Layer { + let official = layer.organic.iter().find_map(|hit| { + let site = text(hit.official.as_ref()?.site.as_str()); + Some(Official { + title: shown(&hit.title).unwrap_or_else(|| site.clone()), + site, + }) + }); + let mut social_targets = BTreeMap::new(); + let social = networks(&layer.social, &mut social_targets); + let organic = u8::try_from(layer.organic.len()).unwrap_or(u8::MAX); + let mut seen: BTreeSet<_> = social_targets + .values() + .filter_map(|url| Some(PageKey::from_url(url).ok()?.page_match())) + .collect(); + let (also, targets) = layer + .organic + .iter() + .filter(|hit| hit.official.is_none()) + .map(|hit| { + ( + &hit.url, + &hit.title, + if hit.discussion { + AlsoKind::Discussion + } else { + AlsoKind::Page + }, + ) + }) + .chain( + layer + .video + .iter() + .map(|hit| (&hit.url, &hit.title, AlsoKind::Video)), + ) + .filter_map(|(url, title, kind)| { + let host = hostname(url)?; + let key = PageKey::from_url(url).ok()?.page_match(); + if places.iter().any(|(place, site)| { + if place.tenant.is_some() { + PlaceKey::from_url(url).as_ref() == Some(*place) + } else { + SiteKey::from_url(url).as_ref() == Some(site) + } + }) || !seen.insert(key) + { + return None; + } + let title = shown(title) + .filter(|text| { + !text.split_whitespace().any(|word| { + word.starts_with('/') + || word + .split_once('/') + .is_some_and(|(head, _)| head.contains('.')) + }) + }) + .unwrap_or_else(|| host.clone()); + Some((Also { title, host, kind }, url.clone())) + }) + .take(MAX_ALSO) + .unzip(); + Layer { + official, + social, + organic, + also, + targets, + } +} + +pub(crate) fn also_target(urls: &[Url], index: u8) -> Option<Url> { + let url = urls.get(usize::from(index))?; + (url.scheme() == "https").then(|| url.clone()) +} + +pub(crate) fn rows(source: &[compare::Row], left: &Targets, right: &Targets) -> Vec<Row> { + source + .iter() + .filter_map(|row| { + let side = |id: &Option<site::EntryId>, targets: &Targets| { + id.as_ref() + .map(|id| id.as_str()) + .filter(|id| valid_id(id) && targets.has(id)) + .map(str::to_owned) + }; + let (l, r) = (side(&row.left, left), side(&row.right, right)); + if l.is_none() && r.is_none() { + return None; + } + Some(Row { + role: row.role.map(Role::from), + label: shown(&row.label)?, + left: l, + right: r, + }) + }) + .take(MAX_ROWS) + .collect() +} + +#[cfg(test)] +mod tests; diff --git a/crates/zephium-map-driver/src/wire/tests.rs b/crates/zephium-map-driver/src/wire/tests.rs new file mode 100644 index 000000000..66c4b2248 --- /dev/null +++ b/crates/zephium-map-driver/src/wire/tests.rs @@ -0,0 +1,510 @@ +use super::*; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use zephium_map::{site::SiteInputs, Doc, DocLimits}; + +fn long_host() -> String { + format!("{}example.com", "ab.".repeat(MAX_HOST_BYTES / 3)) +} + +fn base() -> Value { + let url = Url::parse("https://acme.com/").unwrap(); + let doc = Doc::from_html( + &url, + b"<title>Acme</title><nav><a href='/pricing'>Pricing</a><a href='/news'>News</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let inputs = SiteInputs { + result_section: None, + sitelinks: &[], + robots: None, + llms: None, + sitemaps: BTreeMap::new(), + pages: BTreeMap::new(), + }; + serde_json::to_value(site::read_site(&doc, &inputs).unwrap()).unwrap() +} + +fn id(n: usize) -> String { + format!("{n:016x}") +} + +fn section(id: &str, label: &str, key: &str, tier: &str) -> Value { + json!({ + "children": [], + "group": null, + "id": id, + "key": key, + "label": label, + "locator": {}, + "more": 0, + "off_site": false, + "role": null, + "sources": ["Footer"], + "tier": tier, + }) +} + +fn engine(value: Value) -> site::Place { + serde_json::from_value(value).unwrap() +} + +fn hostile() -> site::Place { + let mut place = base(); + place["title"] = json!(format!("\u{202e}Acme\u{7}\n{}", "T".repeat(1000))); + place["focus"] = json!("not-an-id"); + place["social"] = json!([ + {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/acme"}, + {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/other"}, + ]); + let mut sections = Vec::new(); + let mut long = section( + &id(1), + &format!("{}\u{0}\u{200b}{}", "L".repeat(200), "é".repeat(400)), + "https://acme.com/long?token=secret#frag", + "Secondary", + ); + long["group"] = json!("G".repeat(1000)); + sections.push(long); + sections.push(section( + &id(2), + "https://evil.example/path?x=1", + "https://acme.com/a", + "Primary", + )); + sections.push(section( + &id(3), + "visit www.evil.example now", + "https://acme.com/b", + "Primary", + )); + sections.push(section( + &id(8), + "https://evil.example/root", + "https://acme.com/", + "Primary", + )); + sections.push(section("ZZZZ", "Bad", "https://acme.com/c", "Primary")); + sections.push(section( + &id(4).to_uppercase().replace('0', "A"), + "Upper", + "https://acme.com/d", + "Primary", + )); + sections.push(section( + &id(5), + "Redirect", + "https://acme.com/go/https://evil.example/x?u=1", + "Primary", + )); + sections.push(section( + &id(6), + "Deep", + &format!("https://acme.com/{}", "p".repeat(300)), + "Primary", + )); + sections.push(section( + &id(9), + "Guide", + "https://docs.acme.com/guide", + "Primary", + )); + sections.push(section( + &id(10), + "Oversized host", + &format!("https://{}/guide", long_host()), + "Primary", + )); + let mut parent = section(&id(7), "Parent", "https://acme.com/parent", "Primary"); + let mut children = Vec::new(); + for n in 0..20 { + let mut child = section( + &id(100 + n), + &format!("Child {n}"), + &format!("https://acme.com/parent/{n}?q=hidden"), + "Primary", + ); + if n == 0 { + child["children"] = json!([section( + &id(999), + "Grandchild", + "https://acme.com/grand", + "Primary" + )]); + } + children.push(child); + } + parent["children"] = Value::Array(children); + sections.push(parent); + sections.push(section( + &id(7), + "Duplicate", + "https://acme.com/dup", + "Primary", + )); + for n in 0..40 { + sections.push(section( + &id(200 + n), + &format!("Section {n}"), + &format!("https://acme.com/s/{n}?session=hidden"), + if n % 2 == 0 { "Secondary" } else { "Primary" }, + )); + } + place["sections"] = Value::Array(sections); + engine(place) +} + +fn entries(place: &Place) -> impl Iterator<Item = &Entry> { + place + .sections + .iter() + .flat_map(|s| std::iter::once(s).chain(&s.children)) +} + +#[test] +fn the_projection_bounds_a_hostile_place() { + let source = hostile(); + let rules = BTreeMap::from([( + "https://acme.com".to_owned(), + Robots::parse("User-agent: *\nDisallow: /parent"), + )]); + let (projected, targets) = place(&source, Some(&rules)); + let json = serde_json::to_string(&projected).unwrap(); + for banned in [ + "http", "://", "?", "token", "hidden", "evil", "frag", "secret", + ] { + assert!(!json.contains(banned), "{banned} in {json}"); + } + assert!(!json + .chars() + .any(|c| c.is_control() || c == '\u{202e}' || c == '\u{200b}')); + assert_eq!(projected.sections.len(), MAX_SECTIONS); + let tiers: Vec<_> = projected.sections.iter().map(|s| s.tier).collect(); + let mut sorted = tiers.clone(); + sorted.sort(); + assert_eq!(tiers, sorted); + assert!(projected.title.len() <= MAX_TEXT_BYTES && projected.title.starts_with("Acme T")); + assert_eq!(projected.site, "acme.com"); + assert_eq!(projected.host, "acme.com"); + assert_eq!(projected.focus, None); + assert_eq!(projected.social, [Network::GitHub]); + let mut ids = BTreeSet::new(); + for e in entries(&projected) { + assert!(valid_id(&e.id) && ids.insert(e.id.clone())); + assert!(e.label.len() <= MAX_TEXT_BYTES && !e.label.is_empty()); + assert!(e.group.as_ref().is_none_or(|g| g.len() <= MAX_TEXT_BYTES)); + assert!(e.path.starts_with('/') && e.path.chars().count() <= MAX_PATH_CHARS); + assert!(e.children.len() <= MAX_CHILDREN); + assert!(e.children.iter().all(|c| c.children.is_empty())); + } + let parent = projected + .sections + .iter() + .find(|s| s.label == "Parent") + .unwrap(); + assert_eq!(parent.children.len(), MAX_CHILDREN); + assert!(parent.more && parent.children[0].more); + assert!(!parent.open && parent.children.iter().all(|child| !child.open)); + assert!(!ids.contains(&id(999)) && !ids.contains(&id(8))); + let label = |n: usize| { + entries(&projected) + .find(|e| e.id == id(n)) + .map(|e| e.label.clone()) + }; + assert_eq!(label(2).as_deref(), Some("/a")); + assert_eq!(label(3).as_deref(), Some("/b")); + assert!(!json.contains("Duplicate") && !json.contains("Upper") && !json.contains("Bad")); + let long = entries(&projected).find(|e| e.id == id(1)).unwrap(); + assert!(long.open && long.host.is_none()); + let guide = entries(&projected).find(|e| e.id == id(9)).unwrap(); + assert!(guide.open); + assert_eq!(guide.host.as_deref(), Some("docs.acme.com")); + let oversized = entries(&projected).find(|e| e.id == id(10)).unwrap(); + assert!(!oversized.open && oversized.host.is_none()); + assert!(long.label.len() > MAX_TEXT_BYTES - 2); + assert_eq!(long.group.as_ref().map(String::len), Some(MAX_TEXT_BYTES)); + let redirect = entries(&projected).find(|e| e.id == id(5)).unwrap(); + assert_eq!(redirect.path, "/go"); + let deep = entries(&projected).find(|e| e.id == id(6)).unwrap(); + assert_eq!(deep.path.chars().count(), MAX_PATH_CHARS); + assert_eq!( + targets + .resolve(&Target::Entry { id: id(1) }) + .map(|u| u.to_string()), + Some("https://acme.com/long?token=secret#frag".into()) + ); + assert_eq!(targets.resolve(&Target::Entry { id: id(999) }), None); + + let organic = |raw: &str, title: String, discussion: bool, rank: u32| { + let url = Url::parse(raw).unwrap(); + results::Organic { + key: PageKey::from_url(&url).unwrap(), + url, + title, + rank, + discussion, + snippet: Some("secret snippet".into()), + official: None, + sitelinks: Vec::new(), + } + }; + let mut layer = FirstLayer { + social: source.social.clone(), + organic: vec![ + organic("https://acme.com/official", "Official".into(), false, 1), + organic("https://github.com/acme", "Social profile".into(), false, 2), + organic( + &format!("https://{}/oversized", long_host()), + "Oversized".into(), + false, + 3, + ), + organic( + "http://plain.example/hidden", + "https://abuse.example/secret".into(), + false, + 4, + ), + organic( + "https://FORUM.example/hidden", + format!("Line\u{7}\nHere {}", "é".repeat(MAX_TEXT_BYTES)), + true, + 5, + ), + ], + video: vec![results::Link { + url: Url::parse("https://video.example/movie").unwrap(), + title: "Film".into(), + }], + ..FirstLayer::default() + }; + let places = [(&source.key, source.site.clone())]; + let preview = first_layer(&layer, &places); + assert_eq!( + preview + .also + .iter() + .map(|result| result.kind) + .collect::<Vec<_>>(), + [AlsoKind::Page, AlsoKind::Discussion, AlsoKind::Video] + ); + for rank in 6..6 + MAX_ALSO { + layer.organic.push(organic( + &format!("https://result.example/{rank}"), + "Result".into(), + false, + rank as u32, + )); + } + let projected = first_layer(&layer, &places); + assert_eq!(projected.also.len(), MAX_ALSO); + assert_eq!(projected.also[0].title, "plain.example"); + assert_eq!(projected.also[1].host, "forum.example"); + assert!(projected.also[1].title.starts_with("Line Here ")); + assert!(projected.also[1].title.len() <= MAX_TEXT_BYTES); + assert_eq!(also_target(&projected.targets, 0), None); + assert_eq!( + also_target(&projected.targets, 1).unwrap().host_str(), + Some("forum.example") + ); + assert_eq!(also_target(&projected.targets, MAX_ALSO as u8), None); + let json = serde_json::to_string(&projected.also).unwrap(); + for banned in [ + "http", + "://", + "hidden", + "secret", + "video.example", + "github.com", + "acme.com", + ] { + assert!(!json.contains(banned)); + } + assert!(!json.contains("\\u0007") && !json.contains("\\n")); +} + +#[test] +fn text_is_cleaned_then_clipped_at_a_character_boundary() { + assert_eq!(text(" a\u{0}\tb\u{feff}c \n "), "a bc"); + let clipped = text(&"é".repeat(MAX_TEXT_BYTES)); + assert_eq!(clipped.len(), MAX_TEXT_BYTES); + let odd = text(&format!("a{}", "é".repeat(MAX_TEXT_BYTES))); + assert_eq!(odd.len(), MAX_TEXT_BYTES - 1); + assert_eq!(text(&"a".repeat(MAX_TEXT_BYTES + 1)).len(), MAX_TEXT_BYTES); + assert!(address_shaped("HTTPS:example") && address_shaped("x WWW.a.b")); + assert!(!address_shaped("HTTP API") && !address_shaped("Pricing")); +} + +#[test] +fn targets_open_only_known_https_addresses() { + let mut value = base(); + value["entry"] = json!("http://acme.com/"); + let mut fragment = section(&id(1), "Pricing", "https://acme.com/pricing", "Primary"); + fragment["locator"] = json!({"element": "plans"}); + let mut route = section(&id(2), "Route", "https://acme.com/#/app", "Primary"); + route["locator"] = json!({"element": "ignored"}); + value["sections"] = json!([ + fragment, + route, + section(&id(3), "Plain", "http://acme.com/plain", "Primary"), + ]); + value["social"] = json!([ + {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/acme"}, + {"basis": "Navigation", "network": "Reddit", "url": "http://reddit.com/r/acme"}, + ]); + let (_, targets) = place(&engine(value), None); + let open = |t: Target| targets.resolve(&t).map(|u| u.to_string()); + assert_eq!( + open(Target::Entry { id: id(1) }), + Some("https://acme.com/pricing#plans".into()) + ); + assert_eq!( + open(Target::Entry { id: id(2) }), + Some("https://acme.com/#/app".into()) + ); + assert_eq!(open(Target::Entry { id: id(3) }), None); + assert_eq!(open(Target::Entry { id: id(4) }), None); + assert_eq!(open(Target::Site), None); + assert_eq!( + open(Target::Social { + network: Network::GitHub + }), + Some("https://github.com/acme".into()) + ); + for network in [Network::Reddit, Network::Discord] { + assert_eq!(open(Target::Social { network }), None); + } + let (_, targets) = place(&engine(base()), None); + assert_eq!( + targets.resolve(&Target::Site).map(|u| u.to_string()), + Some("https://acme.com/".into()) + ); +} + +#[test] +fn rows_keep_only_projected_ids_and_are_capped() { + let (_, left) = place(&engine(base()), None); + let known = base()["sections"][0]["id"].as_str().unwrap().to_owned(); + let entry_id = |s: &str| -> Option<site::EntryId> { serde_json::from_value(json!(s)).ok() }; + let row = |label: &str, left: &str, right: &str| compare::Row { + role: None, + label: label.into(), + left: entry_id(left), + right: entry_id(right), + }; + let mut source = vec![ + compare::Row { + role: Some(SectionRole::Pricing), + ..row("Pricing", &known, &id(9)) + }, + row("Gone", &id(9), &id(9)), + row("https://evil.example/", &known, &known), + ]; + for _ in 0..MAX_ROWS + 5 { + source.push(row("Row", &known, &id(9))); + } + let rows = rows(&source, &left, &Targets::default()); + assert_eq!(rows.len(), MAX_ROWS); + assert_eq!( + rows[0], + Row { + role: Some(Role::Pricing), + label: "Pricing".into(), + left: Some(known), + right: None, + } + ); + assert!(rows + .iter() + .all(|r| r.label != "Gone" && !r.label.contains("evil"))); +} + +#[test] +fn every_engine_failure_has_a_wire_class() { + use session::Failure as F; + let all = [ + (F::Cancelled, Failure::Cancelled), + (F::Missing, Failure::Missing), + (F::Client, Failure::Missing), + (F::Server, Failure::Unavailable), + (F::Unreadable, Failure::Unreadable), + (F::Unavailable, Failure::Unavailable), + (F::Timeout, Failure::Timeout), + (F::External, Failure::Blocked), + (F::Robots, Failure::Blocked), + (F::Challenge, Failure::Challenge), + (F::Consent, Failure::Consent), + (F::NoResults, Failure::NoResults), + (F::Limit, Failure::Limit), + (F::ContentType, Failure::Unreadable), + ]; + for (engine, wire) in all { + assert_eq!(Failure::from(engine), wire); + } + assert_eq!( + serde_json::to_value(Change::End { + seq: 3, + outcome: Outcome::Failed { + failure: Failure::NoResults + }, + elapsed_ms: 7, + }) + .unwrap(), + json!({"type": "end", "seq": 3, "outcome": {"kind": "failed", "failure": "no_results"}, "elapsed_ms": 7}) + ); +} + +#[test] +fn action_tier_is_bounded_and_round_trips_with_its_target() { + let mut value = base(); + value["sections"] = Value::Array( + (0..=site::MAX_ACTIONS) + .map(|i| { + section( + &id(i), + "Enter", + &format!("https://acme.com/flow/{i}"), + "Action", + ) + }) + .collect(), + ); + let (card, targets) = place(&engine(value), None); + assert_eq!(card.sections.len(), site::MAX_ACTIONS); + for e in card.sections { + assert_eq!(serde_json::to_value(e.tier).unwrap(), "action"); + assert!(targets.has(&e.id)); + } +} + +#[test] +fn a_menu_only_row_projects_children_without_registering_a_page_target() { + let url = Url::parse("https://acme.com/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><div><button>Tools</button><a href='/a'>Alpha</a><a href='/b'>Beta</a></div></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let source = site::read_site(&doc, &Default::default()).unwrap(); + let (card, targets) = place(&source, Some(&Default::default())); + let menu = &card.sections[0]; + assert!(card.notes.thin && menu.menu_only && !menu.open && menu.path.is_empty()); + assert!(targets.has(&menu.id)); + assert!(targets + .resolve(&Target::Entry { + id: menu.id.clone() + }) + .is_none()); + assert_eq!(menu.children.len(), 2); + for child in &menu.children { + assert!(targets + .resolve(&Target::Entry { + id: child.id.clone() + }) + .is_some()); + } +} diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs index 08b4cb18a..dce0f7378 100644 --- a/crates/zephium-map/src/doc.rs +++ b/crates/zephium-map/src/doc.rs @@ -165,7 +165,7 @@ pub enum Role { } #[derive(Clone, Copy, Default, PartialEq, Eq)] -pub struct Marks(u8); +pub struct Marks(u16); impl Marks { pub const SPONSORED: Self = Self(1); pub const ACCEPTED: Self = Self(2); @@ -174,6 +174,8 @@ impl Marks { pub const FEATURED: Self = Self(16); pub const WIDGET: Self = Self(32); pub(crate) const ANCILLARY: Self = Self(64); + pub(crate) const LANGUAGE_HOST: Self = Self(512); + pub(crate) const ACTION: Self = Self(256); pub(crate) const PROSE: Self = Self(128); pub fn has(self, mark: Self) -> bool { self.0 & mark.0 != 0 @@ -186,12 +188,14 @@ pub struct Node { pub role: Role, pub parent: Option<u32>, pub name: String, + pub(crate) link_prefix_bytes: usize, pub text: String, pub destination: Option<Url>, pub image_source: Option<Url>, pub hidden: bool, pub marks: Marks, pub language: Option<String>, + pub(crate) link_language: Option<String>, pub element_id: Option<String>, pub element_id_cleaned: bool, } @@ -221,12 +225,14 @@ impl Node { role, parent, name: String::new(), + link_prefix_bytes: 0, text: String::new(), destination: None, image_source: None, hidden: false, marks: Marks::default(), language: None, + link_language: None, element_id: None, element_id_cleaned: false, } @@ -239,6 +245,7 @@ pub struct Head { pub title: String, pub canonical: Option<Url>, pub site_name: String, + pub application_name: String, pub alternates: Vec<Alternate>, pub linked_data: Vec<String>, } @@ -251,10 +258,16 @@ pub struct Alternate { pub struct Doc { page: Url, + pub(crate) menu_links: std::collections::BTreeMap<usize, Vec<MenuLink>>, nodes: Vec<Node>, head: Head, truncated: bool, } +pub(crate) struct MenuLink { + pub url: Url, + pub label: String, + pub language: Option<String>, +} impl Doc { pub fn page(&self) -> &Url { &self.page @@ -287,6 +300,7 @@ impl DocBuilder { Ok(Self { doc: Doc { page: page.clone(), + menu_links: Default::default(), nodes: Vec::new(), head: Head::default(), truncated: false, @@ -341,6 +355,7 @@ impl DocBuilder { .len() .saturating_add(node.text.len()) .saturating_add(node.language.as_deref().map_or(0, str::len)) + .saturating_add(node.link_language.as_deref().map_or(0, str::len)) .saturating_add(node.element_id.as_deref().map_or(0, str::len)); if size > self.limits.node_text_bytes as usize || size > self.limits.text_bytes as usize - self.text_bytes @@ -356,6 +371,13 @@ impl DocBuilder { pub fn finish(mut self) -> Doc { for n in &mut self.doc.nodes { + n.link_prefix_bytes = n.text.get(..n.link_prefix_bytes).map_or(0, |prefix| { + prefix + .chars() + .filter(|&c| crate::visible_char(c)) + .map(char::len_utf8) + .sum() + }); n.text.retain(crate::visible_char); n.name.retain(crate::visible_char); if let Some(id) = &mut n.element_id { @@ -366,6 +388,7 @@ impl DocBuilder { } self.doc.head.title.retain(crate::visible_char); self.doc.head.site_name.retain(crate::visible_char); + self.doc.head.application_name.retain(crate::visible_char); for a in &mut self.doc.head.alternates { a.title.retain(crate::visible_char); } diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index 802b22002..9486b3efd 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -139,11 +139,22 @@ impl DocBuilder { .attr("property") .is_some_and(|v| v.eq_ignore_ascii_case("og:site_name")) => { - if let Some(value) = node.attr("content") { + if let Some(value) = node.attr("content").filter(|_| !node.clipped("content")) { let text = self.words(value); self.doc.head.site_name = self.head_text(&text, limit); } } + "meta" + if self.doc.head.application_name.is_empty() + && node + .attr("name") + .is_some_and(|s| s.eq_ignore_ascii_case("application-name")) => + { + if let Some(value) = node.attr("content").filter(|_| !node.clipped("content")) { + let text = self.words(value); + self.doc.head.application_name = self.head_text(&text, limit); + } + } "link" => { let rel = node.attr("rel").unwrap_or_default(); let has = |word: &str| { @@ -198,6 +209,7 @@ impl DocBuilder { let node = &self.doc.nodes[at]; let room = self.limits.node_text_bytes as usize - node.language.as_deref().map_or(0, str::len) + - node.link_language.as_deref().map_or(0, str::len) - node.text.len() - node.name.len() - node.element_id.as_deref().map_or(0, str::len); @@ -292,7 +304,11 @@ impl DocBuilder { ) { captured = true; + let first_link_run = n.role == Role::Link && n.text.is_empty(); self.append(at, &words, verbatim, gap); + if first_link_run { + self.doc.nodes[at].link_prefix_bytes = self.doc.nodes[at].text.len(); + } } inside_list_or_code |= matches!( self.doc.nodes[at].role, @@ -345,6 +361,101 @@ impl DocBuilder { } } + fn disclosure_links(&mut self, button: NodeRef<'_>, base: &Url, index: usize) { + let Some(id) = button + .attr("aria-controls") + .filter(|s| !s.is_empty() && !button.clipped("aria-controls")) + else { + return; + }; + let Some(panel) = + std::iter::successors(button.sibling(), |n| n.sibling()).find(|n| !n.is_text()) + else { + return; + }; + if panel.attr("id") != Some(id) + || panel.clipped("id") + || panel.hidden_by_lift() + || excluded(marks(&panel)) + || excluded(panel.lifted_marks()) + || panel.has_attr("hidden") + || panel.attr("aria-hidden") != Some("true") + || !super::super::ancestors(&self.doc.nodes, index).any(|a| { + matches!( + self.doc.nodes[a].role, + Role::Landmark { + landmark: Some(Landmark::Navigation) + } + ) + }) + { + return; + } + // Collapsed panel links belong to the control. Its hidden text never enters the document. + let mut links = Vec::new(); + let mut pending = panel + .children() + .next() + .map(|n| (n, None)) + .into_iter() + .collect::<Vec<_>>(); + while let Some((n, anchor)) = pending.pop() { + if let Some(next) = n.sibling() { + pending.push((next, anchor)); + } + if hidden(&n) + || excluded(marks(&n)) + || excluded(n.lifted_marks()) + || matches!( + n.tag(), + "script" | "style" | "template" | "noscript" | "svg" + ) + { + continue; + } + let mut anchor: Option<usize> = anchor; + if n.tag() == "a" { + anchor = None; + if let Some(url) = self + .resolve(&n, "href", base) + .filter(|_| !n.has_attr("download")) + { + let size = url.as_str().len(); + if size > self.limits.text_bytes as usize - self.text_bytes { + self.mark_truncated(); + break; + } + self.text_bytes += size; + let label = self.head_text( + n.attr("aria-label").unwrap_or_default(), + self.limits.node_text_bytes as usize, + ); + anchor = Some(links.len()); + let language = link_language(&n) + .filter(|s| s.len() <= self.limits.text_bytes as usize - self.text_bytes) + .map(str::to_ascii_lowercase); + self.text_bytes += language.as_deref().map_or(0, str::len); + links.push(MenuLink { + url, + label, + language, + }); + } + } else if let Some(i) = anchor { + let label = &mut links[i].label; + if label.is_empty() && n.is_text() && !n.text().trim().is_empty() { + *label = self.head_text(n.text().trim(), self.limits.node_text_bytes as usize); + } + } + if let Some(child) = n.children().next() { + pending.push((child, anchor)); + } + } + if !links.is_empty() { + self.doc.menu_links.insert(index, links); + } + } + fn walk(&mut self, body: NodeRef<'_>, base: &Url) -> Result<(), DocError> { let mut pending = vec![Some((body, None::<usize>, 0, false))]; while let Some(step) = pending.pop() { @@ -459,6 +570,14 @@ impl DocBuilder { node.marks.insert(Marks::ANCILLARY); } if role == Role::Link { + if n.has_attr("download") + || n.attr("class").is_some_and(|v| { + v.split_ascii_whitespace() + .any(|t| t.eq_ignore_ascii_case("cta")) + }) + { + node.marks.insert(Marks::ACTION); + } node.destination = self.resolve(&n, "href", base); } if role == Role::Image { @@ -507,7 +626,32 @@ impl DocBuilder { - node.element_id.as_deref().map_or(0, str::len); node.language = language.filter(|s| s.len() <= room).map(str::to_owned); } - (Some(self.push(node)? as usize), level + 1) + if role == Role::Link { + let room = (self.limits.node_text_bytes as usize) + .min(self.limits.text_bytes as usize - self.text_bytes) + - node.name.len() + - node.element_id.as_deref().map_or(0, str::len); + node.link_language = link_language(&n) + .filter(|s| s.len() <= room) + .map(str::to_ascii_lowercase); + if node + .destination + .as_ref() + .and_then(Url::domain) + .and_then(|h| h.split_once('.')) + .zip(node.link_language.as_deref()) + .is_some_and(|((prefix, _), lang)| { + prefix.len() == 2 && prefix.eq_ignore_ascii_case(lang) + }) + { + node.marks.insert(Marks::LANGUAGE_HOST); + } + } + let index = self.push(node)? as usize; + if matches!(role, Role::Button | Role::Link) { + self.disclosure_links(n, base, index); + } + (Some(index), level + 1) } else { (parent, level) }; @@ -566,6 +710,17 @@ fn marks(n: &NodeRef) -> Marks { marks } +fn link_language<'a>(n: &NodeRef<'a>) -> Option<&'a str> { + ["hreflang", "lang"].into_iter().find_map(|attr| { + n.attr(attr).filter(|s| { + !n.clipped(attr) + && s.len() <= MAX_LANGUAGE_BYTES + && s.split('-') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric())) + }) + }) +} + fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option<Role> { use super::Landmark as L; use Role::*; @@ -611,6 +766,7 @@ fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option<Role> { }, "paragraph" => Paragraph, "link" => Link, + "button" if tag == "a" && n.has_attr("href") => Link, "button" => Button, "dialog" | "alertdialog" => Dialog, "list" | "feed" => List, @@ -630,6 +786,7 @@ fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option<Role> { "spinbutton" => Spinbutton, "slider" => Slider, "tab" => Tab, + "menuitem" if tag == "a" && n.has_attr("href") => Link, "menuitem" => MenuItem, "progressbar" => Progress, "status" | "alert" => Status, diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs index fc186e2ff..7c4dcc808 100644 --- a/crates/zephium-map/src/doc/html/arena.rs +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -37,7 +37,10 @@ const ATTRIBUTE_NAMES: &[&str] = &[ "data-type", "data-testid", "aria-labelledby", + "aria-controls", "hreflang", + "lang", + "download", ]; const ATTRIBUTES_PER_ELEMENT_BUDGET: usize = 4; diff --git a/crates/zephium-map/src/lib.rs b/crates/zephium-map/src/lib.rs index 971aecb9b..387bd7e2e 100644 --- a/crates/zephium-map/src/lib.rs +++ b/crates/zephium-map/src/lib.rs @@ -42,6 +42,6 @@ fn visible(nodes: &[Node], at: usize) -> bool { fn visible_char(c: char) -> bool { !matches!(c, '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}') } -fn clean_text(text: &str) -> String { +pub fn clean_text(text: &str) -> String { text.chars().filter(|&c| visible_char(c)).collect() } diff --git a/crates/zephium-map/src/session.rs b/crates/zephium-map/src/session.rs index cdaf2a7eb..ddec284f9 100644 --- a/crates/zephium-map/src/session.rs +++ b/crates/zephium-map/src/session.rs @@ -19,6 +19,8 @@ mod types; pub use memo::*; pub use types::*; +const SEARCH_SLOTS: usize = 2; + #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] enum Work { Robots, @@ -78,6 +80,11 @@ enum Pending { Cache(usize), Job(Job), } +#[derive(Clone, Copy)] +enum Unseeded { + Searching, + Failed(Failure), +} struct Seed { site: PlaceKey, result: Link, @@ -127,6 +134,10 @@ struct SiteState { clean: bool, stale: bool, external: BTreeMap<PageMatch, PageKey>, + asked: BTreeSet<site::EntryId>, + probed_section: bool, + eager: Vec<site::SectionRead>, + memo: Option<SiteMemo>, } impl SiteState { fn new(seed: Seed) -> Self { @@ -151,6 +162,10 @@ impl SiteState { clean: true, stale: false, external: BTreeMap::new(), + asked: BTreeSet::new(), + probed_section: false, + eager: Vec::new(), + memo: None, } } } @@ -174,7 +189,8 @@ impl SiteState { } pub struct Session { cfg: Config, - query: QueryRead, + query: Option<QueryRead>, + opening: Option<Opening>, sequence: u32, elapsed: Duration, finished: bool, @@ -183,16 +199,104 @@ pub struct Session { queue: VecDeque<Job>, seen: BTreeSet<(Work, PageMatch)>, robots: BTreeMap<String, Robots>, + landings: BTreeMap<String, Vec<(Job, FetchResult)>>, hosts: BTreeMap<String, u32>, started: u32, sections: u32, - sites: [Option<SiteState>; 2], + sites: [Option<SiteState>; SEARCH_SLOTS], + unseeded: [Option<Unseeded>; SEARCH_SLOTS], articles: BTreeMap<usize, Doc>, first_passage: Option<Passage>, passages: Vec<Passage>, } + +#[derive(Clone, serde::Serialize)] +pub struct HeldSite { + payload: SitePayload, + memo: Option<SiteMemo>, +} + +impl HeldSite { + pub fn place(&self) -> &Place { + &self.payload.place + } + + pub fn robots(&self) -> &BTreeMap<String, Robots> { + &self.payload.robots + } + + pub fn check_open(&self, id: &str) -> Result<(), OpenRefusal> { + self.open_index(id).map(|_| ()) + } + + fn open_index(&self, id: &str) -> Result<usize, OpenRefusal> { + let place = self.place(); + if let Some(index) = place.sections.iter().position(|e| e.id.as_str() == id) { + return place + .entry_openable(&place.sections[index].id, self.robots()) + .then_some(index) + .ok_or(OpenRefusal::NotOpenable); + } + if place + .sections + .iter() + .flat_map(|e| &e.children) + .any(|e| e.id.as_str() == id) + { + return Err(OpenRefusal::NotOpenable); + } + Err(OpenRefusal::UnknownEntry) + } + + fn bounded(mut self) -> Option<Self> { + let place = self.place(); + if place.sections.len() > site::MAX_SECTIONS + || !place.sections.iter().all(|entry| { + entry.children.len() <= site::MAX_CHILDREN + && entry.children.iter().all(|child| child.children.is_empty()) + }) + || place.check_ids().is_err() + { + return None; + } + if !self.fits() { + self.memo = None; + if !self.fits() { + return None; + } + } + Some(self) + } + + fn fits(&mut self) -> bool { + // Reserve space for the longest serialized read state on every top-level row. + let state = ReadState::Skipped { + budget: Budget::HostConcurrent, + }; + let sections = &mut self.payload.place.sections; + let reads: Vec<_> = sections + .iter_mut() + .map(|entry| entry.read.replace(state)) + .collect(); + let fits = memo::encode_bounded(self).is_ok(); + for (entry, read) in self.payload.place.sections.iter_mut().zip(reads) { + entry.read = read; + } + fits + } +} + +struct Opening { + held: HeldSite, + slot: u8, + index: usize, + confidence: Confidence, + stale: bool, + clean: bool, +} + impl Session { - pub fn start(mut cfg: Config, query_text: &str) -> Result<(Self, Vec<Effect>), QueryError> { + pub fn start(cfg: Config, query_text: &str) -> Result<(Self, Vec<Effect>), QueryError> { let query = read_query(query_text)?; if cfg.custom_template.len() > crate::key::MAX_URL_BYTES { return Err(QueryError::Search); @@ -201,11 +305,121 @@ impl Session { .engine .configured_search(query_text, &cfg.custom_template) .ok_or(QueryError::Search)?; - cfg.tighten(); let kind = query.kind().clone(); - let mut s = Self { + let mut s = Self::new(cfg, Some(query)); + let mut out = Vec::new(); + s.emit(MapEvent::Kind { kind }, &mut out); + let id = s.id(); + s.pending.insert(id, Pending::Results); + s.counts(Phase::Results).started += 1; + out.push(Effect::LoadResults { id, url }); + Ok((s, out)) + } + + pub fn open( + cfg: Config, + held: HeldSite, + slot: u8, + id: &str, + confidence: Confidence, + stale: bool, + ) -> Result<(Self, Vec<Effect>), OpenRefusal> { + if usize::from(slot) >= SEARCH_SLOTS { + return Err(OpenRefusal::NotOpenable); + } + let index = held.open_index(id)?; + let url = held.place().sections[index].key.as_url().clone(); + let key = held.place().sections[index].key.page_match(); + let mut s = Self::new(cfg, None); + s.robots = held.robots().clone(); + s.opening = Some(Opening { + held, + slot, + index, + confidence, + stale, + clean: true, + }); + s.enqueue(Work::Section(usize::from(slot), key), url); + let mut out = Vec::new(); + s.schedule(&mut out); + Ok((s, out)) + } + + pub fn hold_place(&self, slot: u8, place: Place) -> Option<HeldSite> { + if let Some(open) = self.opening.as_ref().filter(|open| open.slot == slot) { + return Some(open.held.clone()); + } + let memo = self + .sites + .get(usize::from(slot)) + .and_then(Option::as_ref) + .and_then(|site| site.memo.clone()); + HeldSite { + payload: SitePayload { + robots: self.place_robots(&place), + place, + }, + memo, + } + .bounded() + } + + pub fn result_places(&self) -> impl Iterator<Item = (&PlaceKey, SiteKey)> { + self.sites + .iter() + .flatten() + .filter_map(|site| Some((&site.seed.site, SiteKey::from_url(&site.seed.url)?))) + } + + pub fn section_fetch(&self, id: Id) -> Option<(u8, &site::EntryId)> { + let Some(Pending::Job(Job { + work: Work::Section(slot, key), + .. + })) = self.pending.get(&id) + else { + return None; + }; + let site = self.sites.get(*slot)?.as_ref()?; + let id = site + .place + .as_ref()? + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .find(|entry| { + entry.read == Some(ReadState::Queued) && site.discovered.get(&entry.id) == Some(key) + }) + .map(|entry| &entry.id) + .or_else(|| { + site.discovered + .iter() + .find(|(_, discovered)| *discovered == key) + .map(|(id, _)| id) + })?; + Some((*slot as u8, id)) + } + + fn place_robots(&self, place: &Place) -> BTreeMap<String, Robots> { + self.robots + .iter() + .filter(|(host, _)| { + Url::parse(host) + .ok() + .and_then(|url| SiteKey::from_url(&url)) + .as_ref() + == Some(&place.site) + }) + .map(|(host, rules)| (host.clone(), rules.clone())) + .collect() + } + + fn new(mut cfg: Config, query: Option<QueryRead>) -> Self { + cfg.tighten(); + Self { cfg, query, + opening: None, sequence: 0, elapsed: Duration::ZERO, finished: false, @@ -214,21 +428,16 @@ impl Session { queue: VecDeque::new(), seen: BTreeSet::new(), robots: BTreeMap::new(), + landings: BTreeMap::new(), hosts: BTreeMap::new(), started: 0, sections: 0, sites: [None, None], + unseeded: [None, None], articles: BTreeMap::new(), first_passage: None, passages: Vec::new(), - }; - let mut out = Vec::new(); - s.emit(MapEvent::Kind { kind }, &mut out); - let id = s.id(); - s.pending.insert(id, Pending::Results); - s.counts(Phase::Results).started += 1; - out.push(Effect::LoadResults { id, url }); - Ok((s, out)) + } } fn id(&mut self) -> Id { self.sequence += 1; @@ -274,6 +483,8 @@ impl Session { self.queue.push_back(Job { work, url }); } fn lookup(&mut self, side: usize, seed: Seed, out: &mut Vec<Effect>) { + let Some(query) = &self.query else { return }; + self.unseeded[side] = None; if self.elapsed >= self.cfg.last_start { self.budget(Budget::LastStart); self.emit( @@ -286,7 +497,7 @@ impl Session { return; } let site = seed.site.clone(); - let role = match self.query.kind() { + let role = match query.kind() { QueryKind::Place { section, .. } => section.map(|s| s.role), QueryKind::Compare { shared, .. } => shared.map(|s| s.role), _ => None, @@ -299,7 +510,7 @@ impl Session { entity, fresh: is_fresh, .. - } = self.query.kind() + } = query.kind() { fresh = *is_fresh; if let Some((brand, rest)) = entity.split_first() { @@ -351,10 +562,11 @@ impl Session { Seed::official(&self.read(doc, &read).ok()?) } fn results(&mut self, doc: Doc, out: &mut Vec<Effect>) -> Result<(), Failure> { + let query = self.query.as_ref().ok_or(Failure::Unreadable)?; let layer = match results::read_results_with_stats( self.cfg.engine, None, - &self.query, + query, &doc, &mut self.stats.results, ) { @@ -363,12 +575,12 @@ impl Session { }; let mut seeds = Vec::new(); let mut missing = Vec::new(); - match self.query.kind() { + match query.kind() { QueryKind::Instant | QueryKind::List => {} QueryKind::Place { .. } => { let seed = Seed::official(&layer).or_else(|| { let hit = layer.organic.first()?; - (self.query.confidence() == Confidence::High && !hit.sitelinks.is_empty()) + (query.confidence() == Confidence::High && !hit.sitelinks.is_empty()) .then(|| Seed::new(hit, Confidence::Low)) .flatten() }); @@ -392,19 +604,13 @@ impl Session { .organic .iter() .find(|hit| hit.key.page_match() == f.cites.page_match()) - .and_then(|r| passage::featured(&self.query, f, r)); + .and_then(|r| passage::featured(query, f, r)); } let count = self.cfg.result_pages as usize; - if layer.organic.len() > count { - self.budget(Budget::ResultPages); - } - for (i, r) in layer.organic.iter().take(count).enumerate() { - self.enqueue(Work::Passage(i), r.url.clone()); - } if let Some(hit) = layer.organic.first() { if let Some(site) = SiteKey::from_url(&hit.url) { let name = site.as_str().split('.').next().unwrap_or_default(); - if self.query.terms().iter().any(|w| { + if query.terms().iter().any(|w| { w.trim_end_matches('?') == site.as_str() || !hit.sitelinks.is_empty() && w == name }) { @@ -414,6 +620,12 @@ impl Session { } } } + if layer.organic.len() > count { + self.budget(Budget::ResultPages); + } + for (i, r) in layer.organic.iter().take(count).enumerate() { + self.enqueue(Work::Passage(i), r.url.clone()); + } } } self.emit(MapEvent::FirstLayer { layer }, out); @@ -424,12 +636,17 @@ impl Session { self.lookup(side, seed, out); } for (side, query) in missing { + self.unseeded[side] = Some(Unseeded::Failed(Failure::Missing)); if let Some(url) = self .cfg .engine .configured_search(&query, &self.cfg.custom_template) { + let queued = self.queue.len(); self.enqueue(Work::Anonymous(side, query), url); + if self.queue.len() > queued { + self.unseeded[side] = Some(Unseeded::Searching); + } } } Ok(()) @@ -454,7 +671,7 @@ impl Session { } state.stale = stale; let Ok(place) = site::with_results( - m.payload.place, + m.payload.place.clone(), &state.seed.links, state.section_hint.as_ref(), state.requested.as_ref(), @@ -465,22 +682,26 @@ impl Session { }; state.place = Some(place.clone()); let complete = !stale + && (self.cfg.sections == Sections::Asked || m.eager) && state.section_hint.is_none() && (state.requested.is_none() || place.focus.is_some()); state.complete = complete; - self.emit_place(i, place, stale, confidence, complete, out); if complete { if let Some(pos) = shared_passage { self.queue.push_back(Job { work: Work::Passage(pos), - url, + url: url.clone(), }); } - for (host, rules) in m.payload.robots { - if !self.pending.values().any(|p|matches!(p,Pending::Job(j) if j.work==Work::Robots && origin(&j.url)==host)){ - self.robots.entry(host).or_insert(rules); + for (host, rules) in &m.payload.robots { + if !self.pending.values().any(|p|matches!(p,Pending::Job(j) if j.work==Work::Robots && origin(&j.url)==*host)){ + self.robots.entry(host.clone()).or_insert_with(|| rules.clone()); } } + state.memo = Some(m); + } + self.emit_place(i, place, stale, confidence, complete, out); + if complete { return; } } else if supplied { @@ -503,6 +724,9 @@ impl Session { } fn update_passages(&mut self, out: &mut Vec<Effect>) { + let Some(query) = self.query.as_ref() else { + return; + }; let mut ordered: BTreeMap<_, _> = self.articles.iter().map(|(pos, doc)| (*pos, doc)).collect(); for site in self.sites.iter().flatten() { @@ -512,7 +736,7 @@ impl Session { } let pages: Vec<_> = ordered.into_values().collect(); let mut passages: Vec<_> = self.first_passage.clone().into_iter().collect(); - for p in passage::read_passages(&self.query, &pages) { + for p in passage::read_passages(query, &pages) { if !passages .iter() .any(|f| f.source.page_match() == p.source.page_match()) @@ -552,6 +776,7 @@ impl Session { ); } fn rebuild(&mut self, i: usize, out: &mut Vec<Effect>) { + let probe_available = !self.sites.iter().flatten().any(|s| s.probed_section); let Some(state) = self.sites[i].as_mut() else { return; }; @@ -564,7 +789,7 @@ impl Session { sitemaps: state.maps.iter().map(|(k, v)| (k.clone(), v)).collect(), pages: state.pages.iter().map(|(k, v)| (k.clone(), v)).collect(), }; - let Ok((mut place, mut detail)) = + let Ok((mut place, mut detail, eager)) = site::read_site_for(doc, &inputs, state.requested.as_ref()) else { state.entry_failure = Some(Failure::Unreadable); @@ -577,7 +802,7 @@ impl Session { detail.sitemap_truncated |= state.cut.contains(&Phase::Sitemap); detail.llms_truncated |= state.cut.contains(&Phase::Llms); place.notes.truncated |= detail.truncated(); - self.stats.places.insert(i as u8, detail); + if let Some(previous) = &state.place { place.keep_discovery(previous); if place.check_ids().is_err() { @@ -586,12 +811,42 @@ impl Session { return; } } - let candidates: BTreeSet<_> = place - .fetch_sections() - .into_iter() - .map(|e| e.id.clone()) - .collect(); - for entry in &mut place.sections { + let candidates: BTreeSet<_> = match self.cfg.sections { + Sections::All => { + for read in &eager { + state + .discovered + .entry(read.id.clone()) + .or_insert_with(|| read.key.page_match()); + } + state.eager = eager; + state.eager.iter().map(|e| e.id.clone()).collect() + } + Sections::Asked => { + state + .asked + .extend(place.asked_sections(doc.page()).map(|e| e.id.clone())); + if place.focus.is_none() && state.asked.is_empty() && probe_available { + if let Some(entry) = state + .requested + .as_ref() + .and_then(|role| place.likely_section(role, doc.page())) + { + state.asked.insert(entry.id.clone()); + state.probed_section = true; + } + } + state.asked.clone() + } + }; + detail.probed_section = state.probed_section; + self.stats.places.insert(i as u8, detail); + let mut update_read = |entry: &mut site::Entry| { + if entry.menu_only + || self.cfg.sections == Sections::Asked && !candidates.contains(&entry.id) + { + return; + } let discovered = state .discovered .entry(entry.id.clone()) @@ -604,8 +859,15 @@ impl Session { if let Some(key) = state.external.get(discovered) { entry.off_site = SiteKey::from_url(key.as_url()).as_ref() != Some(&place.site); entry.key = key.clone(); + entry.localized = false; entry.locator = Locator::default(); } + }; + for entry in &mut place.sections { + update_read(entry); + if self.cfg.sections == Sections::Asked { + entry.children.iter_mut().for_each(&mut update_read); + } } if !std::mem::take(&mut state.stale) && state.place.as_ref() == Some(&place) { return; @@ -621,12 +883,27 @@ impl Session { let Some(place) = state.place.as_ref() else { return; }; - let keys: Vec<_> = place - .fetch_sections() - .into_iter() - .filter(|e| e.read == Some(ReadState::Queued)) - .map(|e| e.key.clone()) - .collect(); + let keys: Vec<_> = match self.cfg.sections { + Sections::All => state + .eager + .iter() + .filter(|r| { + state + .discovered + .get(&r.id) + .and_then(|key| state.reads.get(key)) + .is_none_or(|s| *s == ReadState::Queued) + }) + .map(|r| r.key.clone()) + .collect(), + Sections::Asked => place + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .filter(|e| e.read == Some(ReadState::Queued)) + .map(|e| e.key.clone()) + .collect(), + }; for key in keys { self.enqueue(Work::Section(i, key.page_match()), key.as_url().clone()); } @@ -661,26 +938,13 @@ impl Session { let Some(state) = &self.sites[i] else { continue; }; - let Some((doc, place)) = state.doc.as_ref().zip(state.place.as_ref()) else { - continue; - }; + let Some(doc) = &state.doc else { continue }; if state.maps_wanted >= MAX_SITEMAP_READS - || place - .sections - .iter() - .filter(|e| { - e.sources.iter().any(|s| { - matches!( - s, - Source::PrimaryNav - | Source::Footer - | Source::MenuGroup - | Source::Llms - ) - }) - }) - .count() - >= SITEMAP_SECTION_THRESHOLD + || self + .stats + .places + .get(&(i as u8)) + .is_some_and(|p| p.navigation_sections >= SITEMAP_SECTION_THRESHOLD) { continue; } @@ -719,8 +983,13 @@ impl Session { match input { Input::Cancel => { self.stats.cancelled = true; + if self.opening.is_some() { + self.done(&mut out); + return out; + } for i in 0..self.sites.len() { let Some(state) = self.sites[i].as_mut() else { + self.close_slot(i, Failure::Cancelled, &mut out); continue; }; if state.complete { @@ -786,6 +1055,7 @@ impl Session { if let Some(seed) = self.side_seed(&doc, &text) { self.lookup(i, seed, &mut out); } else { + self.unseeded[i] = None; self.emit( MapEvent::PlaceFailed { slot: i as u8, @@ -796,6 +1066,7 @@ impl Session { } } Err(failure) => { + self.unseeded[i] = None; self.refused(Phase::AnonymousResults, failure); self.emit( MapEvent::PlaceFailed { @@ -876,6 +1147,7 @@ impl Session { self.finished = true; self.pending.clear(); self.queue.clear(); + self.landings.clear(); self.emit( MapEvent::End { outcome: if self.stats.cancelled { @@ -890,6 +1162,19 @@ impl Session { } fn close_slot(&mut self, i: usize, missing: Failure, out: &mut Vec<Effect>) { let Some(s) = &self.sites[i] else { + if let Some(unseeded) = self.unseeded[i].take() { + let failure = match unseeded { + Unseeded::Searching => missing, + Unseeded::Failed(failure) => failure, + }; + self.emit( + MapEvent::PlaceFailed { + slot: i as u8, + failure, + }, + out, + ); + } return; }; if s.complete { @@ -910,6 +1195,48 @@ impl Session { self.emit_place(i, place, s.stale, s.seed.confidence, true, out); } } + + fn finish_open(&mut self, out: &mut Vec<Effect>) { + let Some(open) = self.opening.as_ref() else { + return; + }; + let robots = self.place_robots(open.held.place()); + let Some(open) = self.opening.as_mut() else { + return; + }; + let mut updated = open.held.clone(); + updated.payload.robots = robots; + if let Some(updated) = updated.bounded() { + open.held = updated; + } + let remember = if open.clean && self.stats.budgets.is_empty() { + open.held.memo.clone().and_then(|mut memo| { + let mut updated = open.held.clone(); + memo.payload.robots.clone_from(&open.held.payload.robots); + let bytes = memo.encode().ok()?; + let site = memo.payload.place.key.clone(); + updated.memo = Some(memo); + let retained = updated.bounded()?; + retained.memo.as_ref()?; + open.held = retained; + Some((site, bytes)) + }) + } else { + None + }; + let (slot, place, stale, confidence) = ( + open.slot, + open.held.place().clone(), + open.stale, + open.confidence, + ); + self.emit_place(usize::from(slot), place, stale, confidence, true, out); + if let Some((site, memo)) = remember { + let id = self.id(); + out.push(Effect::RememberSite { id, site, memo }); + } + self.done(out); + } fn finish(&mut self, out: &mut Vec<Effect>) { if self.elapsed >= self.cfg.elapsed { let jobs: Vec<_> = self @@ -922,6 +1249,9 @@ impl Session { .chain(self.queue.drain(..)) .collect(); for job in jobs { + if self.opening.is_some() && matches!(job.work, Work::Section(..)) { + self.refused(Phase::Section, Failure::Timeout); + } self.set_read( &job, ReadState::Skipped { @@ -931,12 +1261,16 @@ impl Session { ); } } - if matches!(self.query.kind(), QueryKind::Passage { kind: _ }) - && self.sites.iter().any(Option::is_some) + if self.opening.is_some() { + self.finish_open(out); + return; + } + let kind = self.query.as_ref().map(|q| q.kind().clone()); + if matches!(kind, Some(QueryKind::Passage { .. })) && self.sites.iter().any(Option::is_some) { self.update_passages(out); } - if matches!(self.query.kind(), QueryKind::Passage { kind: _ }) + if matches!(kind, Some(QueryKind::Passage { .. })) && self.passages.is_empty() && self .stats @@ -953,7 +1287,9 @@ impl Session { } for i in 0..self.sites.len() { self.close_slot(i, Failure::Limit, out); - let Some(s) = &self.sites[i] else { continue }; + let Some(s) = &mut self.sites[i] else { + continue; + }; if s.clean && self.stats.budgets.is_empty() && s.place @@ -980,16 +1316,22 @@ impl Session { let site = s.seed.site.clone(); let memo = SiteMemo { version: MEMO_VERSION, + eager: self.cfg.sections == Sections::All, read_at: self.cfg.now, payload: SitePayload { place, robots }, }; - if let Ok(memo) = memo.encode() { + if let Ok(bytes) = memo.encode() { + s.memo = Some(memo); let id = self.id(); - out.push(Effect::RememberSite { id, site, memo }); + out.push(Effect::RememberSite { + id, + site, + memo: bytes, + }); } } } - if let QueryKind::Compare { shared, .. } = self.query.kind() { + if let Some(QueryKind::Compare { shared, .. }) = kind { let place = |i: usize| self.sites[i].as_ref()?.place.as_ref(); if let Some((l, r)) = place(0).zip(place(1)) { self.emit( @@ -1003,11 +1345,132 @@ impl Session { self.done(out); } } -fn origin(url: &Url) -> String { +pub(crate) fn origin(url: &Url) -> String { url.origin().ascii_serialization() } mod scheduler; +#[cfg(test)] +mod slot_tests { + use super::*; + const RESULT: &str = + "<main><article><h2><a href='https://acme.com/'>Acme workshop</a></h2></article></main>"; + fn doc(url: &str, markup: &str) -> Doc { + Doc::from_html( + &Url::parse(url).unwrap(), + markup.as_bytes(), + None, + DocLimits::RESULTS, + ) + .unwrap() + } + fn closing( + anonymous: Option<Result<&str, Failure>>, + cancel_at_anonymous: bool, + engine_robots: Option<&str>, + ) -> Vec<String> { + let (mut session, effects) = Session::start(Config::default(), "acme vs other").unwrap(); + let mut queue: VecDeque<_> = effects.into(); + let mut last: [Option<String>; 2] = [None, None]; + let mut ended = false; + while let Some(effect) = queue.pop_front() { + assert!(!ended); + let input = match effect { + Effect::LoadResults { id, .. } => Some(Input::Results { + id, + result: Ok(doc("https://duckduckgo.com/", RESULT)), + }), + Effect::Fetch { id, url, .. } => Some(Input::Fetch { + id, + result: match (url.host_str(), url.path(), engine_robots) { + (_, "/", _) => Ok(FetchResult { + final_url: url, + content_type: "text/html".into(), + charset: None, + bytes: b"<nav><a href='/about'>About</a></nav>".to_vec(), + truncated: false, + }), + (Some("duckduckgo.com"), "/robots.txt", Some(rules)) => Ok(FetchResult { + final_url: url, + content_type: "text/plain".into(), + charset: None, + bytes: rules.as_bytes().to_vec(), + truncated: false, + }), + _ => Err(Failure::Missing), + }, + }), + Effect::ReadResultsAnonymously { id, .. } => { + if cancel_at_anonymous { + Some(Input::Cancel) + } else { + anonymous.map(|answer| Input::Results { + id, + result: answer.map(|markup| doc("https://duckduckgo.com/", markup)), + }) + } + } + Effect::LookupSite { id, .. } => Some(Input::Cache { id, memo: None }), + Effect::Emit { event, .. } => { + match event { + MapEvent::Place { slot, complete, .. } => { + last[slot as usize] = Some(format!("place {complete}")) + } + MapEvent::PlaceFailed { slot, failure } => { + last[slot as usize] = Some(format!("failed {failure:?}")) + } + MapEvent::End { .. } => ended = true, + _ => {} + } + None + } + Effect::Render { id, .. } => Some(Input::Render { + id, + result: Err(Failure::Unavailable), + }), + Effect::RememberSite { .. } => None, + }; + if let Some(input) = input { + queue.extend(session.handle(input)); + } + if queue.is_empty() && !ended { + queue.extend(session.handle(Input::Elapsed { time: MAX_ELAPSED })); + } + } + assert!(ended); + last.into_iter().map(Option::unwrap_or_default).collect() + } + #[test] + fn every_opened_comparison_side_closes_before_the_end() { + let other = RESULT.replace("acme.com", "other.com"); + assert_eq!( + closing(Some(Ok(&other)), false, None), + ["place true", "place true"] + ); + assert_eq!( + closing(Some(Err(Failure::Unavailable)), false, None), + ["place true", "failed Unavailable"] + ); + assert_eq!( + closing(Some(Ok("<main></main>")), false, None), + ["place true", "failed Missing"] + ); + assert_eq!(closing(None, false, None), ["place true", "failed Limit"]); + assert_eq!( + closing(None, true, None), + ["failed Cancelled", "failed Cancelled"] + ); + } + #[test] + fn a_refused_comparison_search_reports_its_own_reason() { + let other = RESULT.replace("acme.com", "other.com"); + assert_eq!( + closing(Some(Ok(&other)), false, Some("User-agent: *\nDisallow: /")), + ["place true", "failed Robots"] + ); + } +} + #[cfg(test)] mod arrival_tests { use super::*; diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index 44fbc7cc8..deb5dca06 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -3,12 +3,13 @@ use crate::results::{MAX_SOCIAL, TITLE_BYTES}; use crate::site::{MAX_CHILDREN, MAX_SECTIONS}; use serde::{Deserialize, Serialize}; -pub const MEMO_VERSION: u16 = 3; +pub const MEMO_VERSION: u16 = 7; pub const MAX_MEMO_BYTES: usize = 256 * 1024; pub const MEMO_TTL: u64 = 24 * 60 * 60; #[derive(Clone, Serialize, Deserialize)] pub struct SiteMemo { pub version: u16, + pub eager: bool, pub read_at: u64, pub payload: SitePayload, } @@ -49,6 +50,13 @@ impl SiteMemo { || SiteKey::from_url(p.entry.as_url()).as_ref() != Some(&p.site) || p.title.len() > TITLE_BYTES || p.focus.is_some() + || p.notes.thin + != (p + .sections + .iter() + .filter(|e| e.tier == site::Tier::Primary) + .count() + < site::MIN_NAV_ROWS) || p.notes.shell || p.notes.wall || p.sections @@ -65,6 +73,15 @@ impl SiteMemo { .windows(2) .any(|pair| pair[0].tier > pair[1].tier) || p.sections.iter().map(|e| e.children.len()).sum::<usize>() > site::MAX_PLACE_CHILDREN + || p.sections + .iter() + .filter(|e| e.tier == site::Tier::Action) + .count() + > site::MAX_ACTIONS + || p.sections.iter().any(|e| { + e.tier == site::Tier::Primary + && e.label.chars().count() > site::MAX_PRIMARY_LABEL_CHARS + }) || p.sections.len() > MAX_SECTIONS || p.social.len() > MAX_SOCIAL || !p.social.iter().all(|v| { @@ -92,23 +109,27 @@ impl SiteMemo { return Err(MemoError::Version); } self.validate(&self.payload.place.key)?; - let mut bytes = Vec::new(); - struct Limited<'a>(&'a mut Vec<u8>); - impl std::io::Write for Limited<'_> { - fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { - if b.len() > MAX_MEMO_BYTES - self.0.len() { - return Err(std::io::ErrorKind::FileTooLarge.into()); - } - self.0.extend_from_slice(b); - Ok(b.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) + encode_bounded(self) + } +} + +pub(super) fn encode_bounded(value: &impl Serialize) -> Result<Vec<u8>, MemoError> { + let mut bytes = Vec::new(); + struct Limited<'a>(&'a mut Vec<u8>); + impl std::io::Write for Limited<'_> { + fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { + if b.len() > MAX_MEMO_BYTES - self.0.len() { + return Err(std::io::ErrorKind::FileTooLarge.into()); } + self.0.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) } - serde_json::to_writer(Limited(&mut bytes), self).map_err(|_| MemoError::Limit)?; - Ok(bytes) } + serde_json::to_writer(Limited(&mut bytes), value).map_err(|_| MemoError::Limit)?; + Ok(bytes) } fn valid_entry(e: &Entry, place: &Place, parent: Option<&Entry>) -> bool { let Some(site) = SiteKey::from_url(e.key.as_url()) else { @@ -123,6 +144,17 @@ fn valid_entry(e: &Entry, place: &Place, parent: Option<&Entry>) -> bool { if site != place.site && !delegated && !(site_nav && site::external_role(e.role)) { return false; } + if e.menu_only + && (parent.is_some() + || e.key != place.entry + || e.locator != Locator::default() + || e.tier != site::Tier::Primary + || e.children.is_empty() + || e.id != site::EntryId::menu(&place.entry, &e.label) + || !e.navigation_row()) + { + return false; + } if e.off_site != (site != place.site) { return false; } diff --git a/crates/zephium-map/src/session/scheduler.rs b/crates/zephium-map/src/session/scheduler.rs index 7b667cb85..a54549755 100644 --- a/crates/zephium-map/src/session/scheduler.rs +++ b/crates/zephium-map/src/session/scheduler.rs @@ -5,7 +5,15 @@ impl Session { let Work::Section(i, key) = &job.work else { return None; }; - let place = self.sites[*i].as_ref()?.place.as_ref()?; + let state = self.sites.get(*i)?.as_ref()?; + if self.cfg.sections == Sections::All { + return state + .eager + .iter() + .find(|e| e.key.page_match() == *key) + .map(|e| e.priority); + } + let place = state.place.as_ref()?; let entry = place.sections.iter().find(|e| e.key.page_match() == *key)?; Some(place.read_priority(entry)) } @@ -56,11 +64,7 @@ impl Session { .iter() .filter_map(|job| self.section_rank(job)) .min(); - let received = self - .stats - .phases - .values() - .fold(0u64, |bytes, phase| bytes.saturating_add(phase.bytes)); + let received = self.received_bytes(); let mut progressed = false; for _ in 0..self.queue.len() { let Some(job) = self.queue.pop_front() else { @@ -77,10 +81,20 @@ impl Session { let host = origin(&job.url); let hostname = job.url.host_str().unwrap_or_default(); let phase = job.work.phase(); + let landing_policy = job.work == Work::Robots; + if landing_policy && self.robots.contains_key(&host) { + self.resolve_landings(&host, out); + progressed = true; + continue; + } let blocked = if received >= self.cfg.total_bytes && matches!( job.work, - Work::Section(..) | Work::Sitemap(_) | Work::Llms(_) | Work::Passage(_) + Work::Robots + | Work::Section(..) + | Work::Sitemap(_) + | Work::Llms(_) + | Work::Passage(_) ) { Some(Budget::TotalBytes) } else if self.started >= self.cfg.fetches { @@ -120,6 +134,15 @@ impl Session { self.queue.push_back(job); continue; } + if landing_policy { + if active.iter().any(|(h, robots)| h == &host && *robots) { + self.queue.push_back(job); + continue; + } + self.start_job(job, out); + progressed = true; + break; + } if let Some(policy) = self.robots.get(&host) { if !policy.allows(&job.url[Position::BeforePath..Position::AfterQuery]) { self.set_read( @@ -130,7 +153,7 @@ impl Session { out, ); self.refused(phase, Failure::Robots); - if let Some(i) = job.work.side() { + if let Some(i) = job.work.side().filter(|_| self.opening.is_none()) { if let Some(s) = self.sites[i].as_mut() { s.denied = true; if !matches!( @@ -192,6 +215,38 @@ impl Session { } } pub(super) fn set_read(&mut self, job: &Job, read: ReadState, out: &mut Vec<Effect>) { + if job.work == Work::Robots { + self.resolve_landings(&origin(&job.url), out); + return; + } + if let Some(open) = &mut self.opening { + if matches!(job.work, Work::Section(..)) { + let failure = match read { + ReadState::Refused { failure } => failure, + ReadState::Skipped { + budget: Budget::Elapsed, + } => Failure::Timeout, + _ => Failure::Limit, + }; + let place = &mut open.held.payload.place; + place.sections[open.index].read = Some(match read { + ReadState::Skipped { budget } if budget != Budget::Elapsed => read, + _ => ReadState::Refused { failure }, + }); + place.notes.robots_disallowed |= failure == Failure::Robots; + place.notes.truncated |= failure == Failure::Limit; + self.stats + .places + .entry(open.slot) + .or_default() + .section_page_truncated |= read + == ReadState::Refused { + failure: Failure::Limit, + }; + open.clean &= matches!(failure, Failure::Missing | Failure::Client); + } + return; + } match &job.work { Work::Section(i, key) => { if let Some(s) = &mut self.sites[*i] { @@ -208,6 +263,13 @@ impl Session { }; } } + Work::Anonymous(i, _) if self.unseeded[*i].is_some() => { + let failure = match read { + ReadState::Refused { failure } => failure, + _ => Failure::Limit, + }; + self.unseeded[*i] = Some(Unseeded::Failed(failure)); + } _ => {} } } @@ -234,9 +296,15 @@ impl Session { } else { Effect::Fetch { id, - url, expect, - max_bytes: job.work.byte_cap(&self.cfg), + max_bytes: if job.work == Work::Robots && self.landings.contains_key(&origin(&url)) + { + let remaining = self.cfg.total_bytes.saturating_sub(self.received_bytes()); + u64::from(job.work.byte_cap(&self.cfg)).min(remaining) as u32 + } else { + job.work.byte_cap(&self.cfg) + }, + url, timeout: self .cfg .timeout @@ -274,13 +342,31 @@ impl Session { return Err(Failure::ContentType); } if let Work::Section(i, ref key) = job.work { - let other_tenant = self.sites[i].as_ref().is_some_and(|s| { - let place = s.place.as_ref().map_or(&s.seed.site, |p| &p.key); + let place_key = if let Some(open) = &self.opening { + Some(&open.held.place().key) + } else { + self.sites[i] + .as_ref() + .map(|s| s.place.as_ref().map_or(&s.seed.site, |p| &p.key)) + }; + let other_tenant = place_key.is_some_and(|place| { place.tenant.is_some() && PlaceKey::from_url(&r.final_url).as_ref() != Some(place) }); if other_tenant || SiteKey::from_url(&job.url) != SiteKey::from_url(&r.final_url) { - if let Some((s, landing)) = self.sites[i] + if let Some(open) = &mut self.opening { + open.held.payload.place.sections[open.index].off_site = true; + if let Ok(landing) = PageKey::from_url(&r.final_url) { + let mut updated = open.held.clone(); + let entry = &mut updated.payload.place.sections[open.index]; + entry.key = landing; + entry.localized = false; + entry.locator = Locator::default(); + if let Some(updated) = updated.bounded() { + open.held = updated; + } + } + } else if let Some((s, landing)) = self.sites[i] .as_mut() .zip(PageKey::from_url(&r.final_url).ok()) { @@ -298,13 +384,6 @@ impl Session { if job.work == Work::Robots && !r.final_url.path().ends_with("/robots.txt") { return Err(Failure::External); } - if job.work != Work::Robots - && self.robots.get(&origin(&r.final_url)).is_some_and(|p| { - !p.allows(&r.final_url[Position::BeforePath..Position::AfterQuery]) - }) - { - return Err(Failure::Robots); - } Ok(r) }); if job.work == Work::Robots { @@ -313,7 +392,18 @@ impl Session { (r.final_url.as_str().strip_prefix(landing.as_str()) == Some("/robots.txt")) .then_some(landing) }); + let host = origin(&job.url); + let received = self.received_bytes(); + let over_budget = self.landings.contains_key(&host) + && (received > self.cfg.total_bytes + || received == self.cfg.total_bytes + && result.as_ref().is_ok_and(|r| r.truncated)); let policy = match result { + Ok(_) if over_budget => { + self.budget(Budget::TotalBytes); + self.refused(phase, Failure::Limit); + Robots::limited() + } Ok(r) => Robots::from_sample(&r.bytes, r.truncated), Err(f) => { self.refused(phase, f); @@ -325,18 +415,84 @@ impl Session { } }; *self.stats.robots.entry(policy.outcome).or_default() += 1; + if let Some(open) = &mut self.opening { + let truncated = policy.truncated || policy.outcome == RobotsOutcome::Limit; + open.held.payload.place.notes.truncated |= truncated; + self.stats + .places + .entry(open.slot) + .or_default() + .robots_truncated |= truncated; + } if let Some(landing) = landing { - self.robots.insert(landing, policy.clone()); + self.robots + .entry(landing.clone()) + .or_insert_with(|| policy.clone()); + if landing != host { + self.resolve_landings(&landing, out); + } } - self.robots.insert(origin(&job.url), policy); + self.robots.insert(host.clone(), policy); + self.resolve_landings(&host, out); return; } + let Ok(r) = result else { + self.settle(job, result, out); + return; + }; + let host = origin(&r.final_url); + if self.robots.contains_key(&host) { + self.accept_landing(job, r, out); + return; + } + let Ok(url) = r.final_url.join("/robots.txt") else { + self.settle(job, Err(Failure::Robots), out); + return; + }; + let in_flight = self.pending.values().any(|p| { + matches!(p, Pending::Job(j) if j.work == Work::Robots && j.url.origin() == url.origin()) + }); + let waiting = self.landings.entry(host).or_default(); + if waiting.is_empty() && !in_flight { + self.queue.push_front(Job { + work: Work::Robots, + url, + }); + } + waiting.push((job, r)); + } + + fn received_bytes(&self) -> u64 { + self.stats + .phases + .values() + .fold(0, |sum, phase| sum.saturating_add(phase.bytes)) + } + + fn resolve_landings(&mut self, host: &str, out: &mut Vec<Effect>) { + for (job, result) in self.landings.remove(host).into_iter().flatten() { + self.accept_landing(job, result, out); + } + } + + fn accept_landing(&mut self, job: Job, r: FetchResult, out: &mut Vec<Effect>) { + let allowed = self + .robots + .get(&origin(&r.final_url)) + .is_some_and(|policy| { + policy.allows(&r.final_url[Position::BeforePath..Position::AfterQuery]) + }); + self.settle(job, if allowed { Ok(r) } else { Err(Failure::Robots) }, out); + } + + fn settle(&mut self, job: Job, result: Result<FetchResult, Failure>, out: &mut Vec<Effect>) { + let phase = job.work.phase(); let side = job.work.side(); let applied = result.and_then(|r| self.apply(job.clone(), r, out)); if let Err(f) = applied { self.set_read(&job, ReadState::Refused { failure: f }, out); self.refused(phase, f); - if let Some(i) = side { + if let Some(i) = side.filter(|_| self.opening.is_none()) { if let Some(s) = self.sites[i].as_mut() { if f == Failure::Limit { s.cut.insert(phase); @@ -359,6 +515,52 @@ impl Session { self.stats.walls += 1; return Err(Failure::Challenge); } + if let Some(open) = &mut self.opening { + let (mut place, mut detail) = site::enrich_held( + open.held.place().clone(), + open.index, + &doc, + site::MAX_CHILDREN, + ); + place.check_ids().map_err(|_| Failure::Unreadable)?; + place.sections[open.index].read = Some(ReadState::Read); + let mut updated = open.held.clone(); + updated.payload.place = place; + if let Some(memo) = &mut updated.memo { + if let Some(index) = memo + .payload + .place + .sections + .iter() + .position(|e| e.id == open.held.place().sections[open.index].id) + { + let occupied = memo + .payload + .place + .sections + .iter() + .enumerate() + .filter(|(other, _)| *other != index) + .map(|(_, entry)| entry.children.len()) + .sum::<usize>(); + let cap = site::MAX_CHILDREN + .min(site::MAX_PLACE_CHILDREN.saturating_sub(occupied)); + let (place, _) = + site::enrich_held(memo.payload.place.clone(), index, &doc, cap); + if place.check_ids().is_ok() { + memo.payload.place = place; + } + } + } + open.held = updated.bounded().ok_or(Failure::Limit)?; + detail.robots_truncated = self + .stats + .places + .get(&open.slot) + .is_some_and(|prior| prior.robots_truncated); + self.stats.places.insert(open.slot, detail); + return Ok(()); + } if let Some(s) = self.sites[i].as_mut() { s.reads.insert(key, ReadState::Read); s.pages.insert( @@ -367,6 +569,7 @@ impl Session { ); } self.rebuild(i, out); + self.plan_sections(i); } Work::Passage(pos) => { let doc = html(&r, DocLimits::ARTICLE)?; diff --git a/crates/zephium-map/src/session/types.rs b/crates/zephium-map/src/session/types.rs index b610001fa..ecb800c2a 100644 --- a/crates/zephium-map/src/session/types.rs +++ b/crates/zephium-map/src/session/types.rs @@ -18,6 +18,13 @@ pub const LAST_START: Duration = Duration::from_secs(10); pub const FETCH_TIMEOUT: Duration = Duration::from_secs(4); pub const MAX_MEDIA_TYPE_BYTES: usize = 256; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sections { + #[default] + All, + Asked, +} + #[derive(Clone)] pub struct Config { /// The caller assigns a distinct namespace to each live search and reuses it for replay. @@ -33,6 +40,7 @@ pub struct Config { pub html_bytes: u32, pub xml_bytes: u32, pub text_bytes: u32, + pub sections: Sections, pub section_pages: u32, pub result_pages: u32, pub elapsed: Duration, @@ -54,6 +62,7 @@ impl Default for Config { html_bytes: MAX_HTML_BYTES as u32, xml_bytes: MAX_XML_BYTES as u32, text_bytes: MAX_TEXT_BYTES as u32, + sections: Sections::All, section_pages: MAX_SECTION_PAGES as u32, result_pages: MAX_RESULT_PAGES as u32, elapsed: MAX_ELAPSED, @@ -195,6 +204,12 @@ pub enum ReadState { Refused { failure: Failure }, Skipped { budget: Budget }, } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OpenRefusal { + UnknownEntry, + NotOpenable, +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EndOutcome { Done, diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index 204fc7f1f..2ca52ffa4 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -9,20 +9,30 @@ use crate::{ clip, site_profile, Link, Profile, CHALLENGE, MAX_SITELINKS, MAX_SOCIAL, TITLE_BYTES, }, robots::{Robots, RobotsOutcome, MAX_SITEMAPS}, - session::ReadState, + session::{origin, Failure, ReadState}, visible, Doc, Locator, PageKey, PlaceKey, SectionRole, SiteKey, }; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use url::Url; +pub const MIN_NAV_ROWS: usize = 3; +mod card; +pub use card::{ + display_hostname, display_path, skip_label, MAX_HOST_BYTES, MAX_PATH_CHARS, + MAX_PRIMARY_LABEL_CHARS, +}; +mod menus; mod navigation; mod sitemap; +mod title; pub use sitemap::{Sitemap, XmlError, MAX_SITEMAP_URLS, MAX_XML_BYTES, MAX_XML_DEPTH}; +pub use title::{title_segments, MAX_SITE_NAME_BYTES}; pub const ENTRY_ID_BYTES: usize = 16; pub const MAX_PRIMARY_SECTIONS: usize = 12; pub const MAX_SECONDARY_SECTIONS: usize = 20; -pub const MAX_SECTIONS: usize = MAX_PRIMARY_SECTIONS + MAX_SECONDARY_SECTIONS; +pub const MAX_ACTIONS: usize = 4; +pub const MAX_SECTIONS: usize = MAX_PRIMARY_SECTIONS + MAX_SECONDARY_SECTIONS + MAX_ACTIONS; pub const MAX_PLACE_CHILDREN: usize = 36; pub const MAX_CHILDREN: usize = 12; pub const MAX_SECTION_PAGES: usize = 6; @@ -50,6 +60,7 @@ pub enum Source { pub enum Tier { Primary, Secondary, + Action, } impl Source { fn tier(self) -> Tier { @@ -64,10 +75,10 @@ pub struct EntryId(String); impl EntryId { fn new(parent: Option<&EntryId>, key: &PageKey, locator: &Locator) -> Self { // FNV-1a over length-delimited discovery fields, independent of Rust's Hash implementation. - let mut hash = 0xcbf29ce484222325u64; + let matched = key.page_match(); let q = locator.quote.as_ref(); - for part in [ + Self::hash([ parent.map(|p| p.0.as_str()), Some(matched.as_str()), locator.element.as_ref().map(LocatorText::as_str), @@ -75,7 +86,18 @@ impl EntryId { q.map(|q| q.start.as_str()), q.and_then(|q| q.end.as_ref()).map(LocatorText::as_str), q.and_then(|q| q.suffix.as_ref()).map(LocatorText::as_str), - ] { + ]) + } + pub(crate) fn menu(root: &PageKey, label: &str) -> Self { + Self::hash([ + Some("menu"), + Some(root.page_match().as_str()), + Some(&normal(label)), + ]) + } + fn hash<'a>(parts: impl IntoIterator<Item = Option<&'a str>>) -> Self { + let mut hash = 0xcbf29ce484222325u64; + for part in parts { let bytes = part.unwrap_or_default().as_bytes(); for b in (bytes.len() as u32) .to_be_bytes() @@ -109,6 +131,14 @@ pub struct Entry { pub label: String, pub role: Option<SectionRole>, pub sources: Vec<Source>, + #[serde(default)] + pub menu_only: bool, + #[serde(default)] + pub menu_item: bool, + #[serde(default)] + pub path_name: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) localized: bool, pub off_site: bool, pub group: Option<String>, pub children: Vec<Entry>, @@ -116,6 +146,8 @@ pub struct Entry { } #[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PlaceNotes { + #[serde(default)] + pub thin: bool, pub shell: bool, pub wall: bool, pub robots_disallowed: bool, @@ -123,6 +155,9 @@ pub struct PlaceNotes { } #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct PlaceStats { + pub missing_header_links: usize, + pub invalid_group_pages: usize, + pub language_groups: usize, pub robots_truncated: bool, pub entry_truncated: bool, pub sections_truncated: bool, @@ -132,6 +167,8 @@ pub struct PlaceStats { pub sitelinks_truncated: bool, pub linked_data_truncated: bool, pub links_seen: u32, + pub(crate) navigation_sections: usize, + pub probed_section: bool, pub sitemap_urls: u32, pub section_pages: u32, } @@ -223,7 +260,7 @@ fn normal(s: &str) -> String { .join(" ") } pub(crate) fn section_role(name: &str, url: &Url) -> Option<SectionRole> { - for value in [ + [ name, url.path() .trim_matches('/') @@ -233,18 +270,24 @@ pub(crate) fn section_role(name: &str, url: &Url) -> Option<SectionRole> { url.host_str() .and_then(|h| h.split('.').next()) .unwrap_or_default(), - ] { - let label = normal(value); - if let Some((_, role)) = SECTION_WORDS.iter().find(|(w, _)| { - label.match_indices(w).any(|(i, _)| { - (i == 0 || label.as_bytes()[i - 1] == b' ') - && label.as_bytes().get(i + w.len()).is_none_or(|b| *b == b' ') - }) - }) { - return Some(*role); - } + ] + .into_iter() + .find_map(label_role) + .or_else(|| { + (url.path() == "/" && name.eq_ignore_ascii_case("home")).then_some(SectionRole::Home) + }) +} +fn label_role(value: &str) -> Option<SectionRole> { + let label = normal(value); + if let Some((_, role)) = SECTION_WORDS.iter().find(|(w, _)| { + label.match_indices(w).any(|(i, _)| { + (i == 0 || label.as_bytes()[i - 1] == b' ') + && label.as_bytes().get(i + w.len()).is_none_or(|b| *b == b' ') + }) + }) { + return Some(*role); } - (url.path() == "/" && name.eq_ignore_ascii_case("home")).then_some(SectionRole::Home) + None } pub(crate) fn external_role(role: Option<SectionRole>) -> bool { matches!( @@ -299,7 +342,21 @@ impl Focus { Some((!exact, path, label)) } } +pub(crate) struct SectionRead { + pub id: EntryId, + pub key: PageKey, + pub priority: (bool, bool), +} +struct LinkName { + text: String, + action: bool, + language_host: bool, + host_root: bool, +} struct Build<'a> { + localized: BTreeSet<crate::PageMatch>, + llms_headings: BTreeMap<EntryId, String>, + names: std::collections::HashMap<EntryId, LinkName>, place: Place, index: std::collections::HashMap<(crate::PageMatch, Locator), usize>, requested: Option<&'a Focus>, @@ -359,6 +416,10 @@ impl Build<'_> { let locator = element_locator(url).ok()?; Some(Entry { id: EntryId::new(None, &key, &locator), + menu_only: false, + menu_item: false, + path_name: false, + localized: self.localized.contains(&key.page_match()), read: None, tier: source.tier(), key, @@ -375,6 +436,9 @@ impl Build<'_> { fn section(&mut self, entry: Entry) -> usize { let destination = (entry.key.page_match(), entry.locator.clone()); if let Some(&i) = self.index.get(&destination) { + if entry.tier == Tier::Action { + self.sections[i].tier = Tier::Action; + } self.sections[i].add_sources(entry.sources); return i; } @@ -387,83 +451,78 @@ impl Build<'_> { let requested = self.requested; self.sections[index].child(entry, requested); } - fn finish_sections(&mut self) { - let requested = self.requested; + fn finish_sections(&mut self, landing: Option<&Url>, menus: Option<menus::Menus>) { + for e in &mut self.sections { + if e.sources + .first() + .is_some_and(|s| matches!(s, Source::Llms | Source::Sitemap)) + { + e.role = label_role(&e.label); + } + } + let saw_nav = self + .sections + .iter() + .any(|e| e.sources.contains(&Source::PrimaryNav)); + self.edit_card(landing); let cluster_primary = !self .sections .iter() - .any(|e| e.tier == Tier::Primary && !e.utility()); + .any(|e| e.tier == Tier::Primary && e.navigation_row() && !e.utility()); + if cluster_primary { + for e in &mut self.sections { + if e.tier != Tier::Action + && e.sources.contains(&Source::LinkCluster) + && !card::sentence(&e.label) + { + e.tier = Tier::Primary; + } + } + } + if let Some(menus) = menus { + menus.apply(self); + } + self.fill_from_footer(saw_nav); + self.merge_supplements(); let globals: BTreeSet<_> = self .sections .iter() - .map(|e| (e.key.page_match(), e.locator.fragment())) + .map(Entry::card_route) .chain(std::iter::once((self.entry.page_match(), None))) .collect(); - let first_signup = self - .sections - .iter() - .find(|e| e.role == Some(SectionRole::SignUp)) - .map(|e| e.id.clone()); - let demoted = |e: &Entry| { - e.utility() - || e.role == Some(SectionRole::SignUp) && Some(&e.id) != first_signup.as_ref() - }; + let demoted = Entry::utility; for e in &mut self.sections { - if e.sources.contains(&Source::LinkCluster) && cluster_primary { - e.tier = Tier::Primary; - } - if demoted(e) { + if e.tier != Tier::Action && demoted(e) { e.tier = Tier::Secondary; } - e.children.retain(|c| { - c.sources.contains(&Source::Heading) - || !globals.contains(&(c.key.page_match(), c.locator.fragment())) - }); - } - self.sections.sort_by_cached_key(|e| (e.tier, demoted(e))); - let mut focus = None; - if let Some(request) = requested { - focus = self - .sections - .iter() - .flat_map(|e| std::iter::once((e, e)).chain(e.children.iter().map(move |c| (e, c)))) - .filter_map(|(p, e)| Some((request.rank(e)?, p, e))) - .min_by_key(|(rank, p, e)| (*rank, e.tier, p.id != e.id)) - .map(|(_, parent, entry)| (parent.id.clone(), entry.id.clone())); - } - let mut sections = std::mem::take(&mut self.sections); - for tier in [Tier::Primary, Tier::Secondary] { - let cap = match tier { - Tier::Primary => MAX_PRIMARY_SECTIONS, - Tier::Secondary => MAX_SECONDARY_SECTIONS, - }; - let priority = |entry: &Entry| { - ( - focus - .as_ref() - .is_some_and(|(parent, _)| parent == &entry.id), - entry.role.is_some(), - ) - }; - let mut kept = Vec::new(); - for e in sections.extract_if(.., |e| e.tier == tier) { - if kept.len() == cap { - self.stats.sections_truncated = true; - let rank = priority(&e); - let replace = kept - .iter() - .enumerate() - .rev() - .min_by_key(|(_, entry)| priority(entry)) - .filter(|(_, entry)| priority(entry) < rank); - let Some((index, _)) = replace else { continue }; - kept.remove(index); + let mut children = std::mem::take(&mut e.children); + children.retain(|c| { + !card::child_self(c, e) && { + c.sources.contains(&Source::Heading) || !globals.contains(&c.card_route()) } - kept.push(e); - } - self.sections.extend(kept); + }); + let mut distinct = BTreeSet::new(); + children.retain(|c| distinct.insert(c.card_route())); + e.children = children; } - self.focus = focus.map(|(_, id)| id); + self.sections + .retain(|e| !e.menu_only || !e.children.is_empty()); + self.sections.sort_by_cached_key(|e| { + let supplemental = e.tier == Tier::Primary && !e.navigation_row(); + ( + e.tier, + e.utility(), + supplemental, + supplemental && e.role.is_none(), + ) + }); + self.select_sections(); + self.notes.thin = self + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .count() + < MIN_NAV_ROWS; let total: usize = self.sections.iter().map(|e| e.children.len()).sum(); for _ in MAX_PLACE_CHILDREN..total { if let Some(section) = self @@ -484,6 +543,69 @@ impl Build<'_> { } } } + fn select_sections(&mut self) { + let focus = self + .focus_entries() + .map(|(parent, entry)| (parent.clone(), entry.clone())); + let selected = self.shortlist(focus.as_ref().map(|(p, _)| p)); + self.stats.sections_truncated |= selected.len() < self.sections.len(); + self.place.sections.retain(|e| selected.contains(&e.id)); + self.focus = focus.map(|(_, id)| id); + } + fn shortlist(&self, focus: Option<&EntryId>) -> BTreeSet<EntryId> { + let mut selected = BTreeSet::new(); + for (tier, cap) in [ + (Tier::Primary, MAX_PRIMARY_SECTIONS), + (Tier::Secondary, MAX_SECONDARY_SECTIONS), + (Tier::Action, MAX_ACTIONS), + ] { + let mut rows: Vec<_> = self.sections.iter().filter(|e| e.tier == tier).collect(); + rows.sort_by_key(|e| { + ( + Some(&e.id) != focus, + tier == Tier::Action + && !e.sources.contains(&Source::PrimaryNav) + && !e.sources.contains(&Source::MenuGroup), + e.role.is_none(), + ) + }); + selected.extend(rows.into_iter().take(cap).map(|e| e.id.clone())); + } + selected + } + + fn focus_entries(&self) -> Option<(&EntryId, &EntryId)> { + let request = self.requested?; + self.sections + .iter() + .flat_map(|parent| { + std::iter::once(parent) + .chain(&parent.children) + .map(move |e| (parent, e)) + }) + .filter_map(|(parent, e)| Some((request.rank(e)?, parent, e))) + .min_by_key(|(rank, parent, e)| (*rank, e.tier, parent.id != e.id)) + .map(|(_, parent, e)| (&parent.id, &e.id)) + } + + fn eager_reads(&self) -> Vec<SectionRead> { + let focus = self.focus_entries().map(|(parent, _)| parent); + let visible = self.shortlist(focus); + let mut reads: Vec<_> = self + .fetch_sections() + .into_iter() + .filter(|e| visible.contains(&e.id)) + .collect(); + reads.sort_by_key(|e| (Some(&e.id) != focus, e.role.is_none(), e.tier)); + reads + .into_iter() + .map(|e| SectionRead { + id: e.id.clone(), + key: e.key.clone(), + priority: (Some(&e.id) != focus, e.role.is_none()), + }) + .collect() + } fn profile(&mut self, url: &Url, basis: ProfileBasis) -> bool { let Some(network) = site_profile(url) else { return false; @@ -618,6 +740,10 @@ impl Build<'_> { i } }; + let id = self.sections[parent].id.clone(); + self.llms_headings + .entry(id) + .or_insert_with(|| normal(&clip(label, TITLE_BYTES))); self.sections[parent].add_sources([Source::Llms]); self.child(parent, child); } @@ -646,9 +772,15 @@ impl Build<'_> { let index = if let Some(i) = existing { i } else { - let Some(entry) = self.entry_for(first.as_url(), seg, Source::Sitemap) else { + let Some(entry) = self.entry_for( + first.as_url(), + &card::capitalized(&decode_fragment(seg)), + Source::Sitemap, + ) else { continue; }; + let mut entry = entry; + entry.path_name = true; self.section(entry) }; self.sections[index].add_sources([Source::Sitemap]); @@ -664,7 +796,11 @@ impl Build<'_> { .next() .unwrap_or_default() .replace('-', " "); - if let Some(child) = self.entry_for(key.as_url(), &label, Source::Sitemap) { + if let Some(child) = self.entry_for( + key.as_url(), + &card::capitalized(&decode_fragment(&label)), + Source::Sitemap, + ) { self.child(index, child); } } @@ -717,10 +853,81 @@ impl Place { entry.id == *focus || entry.children.iter().any(|child| child.id == *focus) }) } + pub fn entry_openable(&self, id: &EntryId, robots: &BTreeMap<String, Robots>) -> bool { + let Some(entry) = self.sections.iter().find(|entry| &entry.id == id) else { + return false; + }; + !entry.menu_only + && !entry.off_site + && SiteKey::from_url(entry.key.as_url()).as_ref() == Some(&self.site) + && (self.key.tenant.is_none() + || PlaceKey::from_url(entry.key.as_url()).as_ref() == Some(&self.key)) + && entry.key.page_match() != self.entry.page_match() + && matches!( + entry.read, + None | Some(ReadState::Queued | ReadState::Skipped { .. }) + | Some(ReadState::Refused { + failure: Failure::Timeout | Failure::Unavailable | Failure::Server, + }) + ) + && robots.get(&origin(entry.key.as_url())).is_none_or(|rules| { + rules.allows( + &entry.key.as_url()[url::Position::BeforePath..url::Position::AfterQuery], + ) + }) + } + pub(crate) fn read_priority(&self, entry: &Entry) -> (bool, bool) { (!self.focuses(entry), entry.role.is_none()) } - pub(crate) fn fetch_sections(&self) -> Vec<&Entry> { + pub(crate) fn asked_sections<'a>( + &'a self, + landing: &'a Url, + ) -> impl Iterator<Item = &'a Entry> { + self.sections + .iter() + .flat_map(|e| { + std::iter::once(e).chain( + e.children + .iter() + .filter(|c| c.sources.contains(&Source::EngineResult)), + ) + }) + .filter(move |entry| { + !entry.menu_only + && entry.key.page_match() != self.entry.page_match() + && !crate::key::same_page(entry.key.as_url(), landing) + && (self.focuses(entry) || entry.sources.contains(&Source::EngineResult)) + }) + } + pub(crate) fn likely_section(&self, request: &Focus, landing: &Url) -> Option<&Entry> { + use SectionRole::*; + let affinity: &[SectionRole] = match request.role { + Changelog => &[Releases, News], + Releases => &[Changelog, News], + Api | Reference | Install => &[Documentation], + Documentation => &[Learn, Reference], + _ => &[], + }; + self.sections + .iter() + .filter(|e| { + !e.menu_only + && !e.off_site + && e.tier != Tier::Action + && e.key.as_url().origin() == landing.origin() + && !crate::key::same_page(e.key.as_url(), landing) + }) + .filter_map(|e| Some((affinity.iter().position(|role| Some(*role) == e.role)?, e))) + .min_by_key(|(rank, e)| (*rank, e.tier)) + .map(|(_, e)| e) + } + fn fetch_sections(&self) -> Vec<&Entry> { + let globals: BTreeSet<_> = self + .sections + .iter() + .map(|e| (e.key.page_match(), e.locator.fragment())) + .collect(); let mut entries: Vec<_> = self .sections .iter() @@ -729,10 +936,10 @@ impl Place { return true; } e.key.page_match() != self.entry.page_match() - && !e - .children - .iter() - .any(|c| c.sources.first() == Some(&Source::MenuGroup)) + && !e.children.iter().any(|c| { + c.sources.first() == Some(&Source::MenuGroup) + && !globals.contains(&(c.key.page_match(), c.locator.fragment())) + }) && matches!( e.role, Some( @@ -811,16 +1018,67 @@ pub(crate) fn quote(text: &str) -> Option<Locator> { }) } impl Entry { + fn footer_utility(&self) -> bool { + self.utility() + || normal(&self.label).split_whitespace().any(|w| { + matches!( + w, + "policy" + | "policies" + | "restricted" + | "prohibited" + | "licences" + | "licenses" + | "sitemap" + ) + }) + } fn utility(&self) -> bool { let label = self.label.to_lowercase(); self.role == Some(SectionRole::Legal) - || ["skip to", "language", "cookie", "select region"] + || self + .locator + .element + .as_ref() + .is_some_and(|id| matches!(id.as_str(), "breadcrumb" | "breadcrumbs")) + || matches!( + normal(&label).as_str(), + "rss" + | "settings" + | "translations" + | "dashboard" + | "your account" + | "account" + | "ask ai" + | "search" + | "shopping bag" + | "shopping cart" + ) + || label.strip_prefix("search ").is_some_and(|target| { + self.key.as_url().domain().is_some_and(|host| { + host.trim_start_matches("www.").eq_ignore_ascii_case(target) + }) + }) + || self + .key + .as_url() + .path() + .rsplit('/') + .next() + .is_some_and(|s| { + (s.starts_with("llms") && s.ends_with(".txt")) || s.ends_with(".xml") + }) + || ["skip to", "cookie", "select region"] .iter() .any(|s| label.contains(s)) } fn leaf(&self, source: Source, label: &str) -> Entry { Entry { id: self.id.clone(), + menu_only: false, + menu_item: false, + path_name: false, + localized: self.localized, read: None, tier: source.tier(), key: self.key.clone(), @@ -836,7 +1094,9 @@ impl Entry { } fn add_sources(&mut self, sources: impl IntoIterator<Item = Source>) { for source in sources { - self.tier = self.tier.min(source.tier()); + if self.tier != Tier::Action { + self.tier = self.tier.min(source.tier()); + } if !self.sources.contains(&source) { self.sources.push(source); } @@ -861,13 +1121,26 @@ impl Entry { !exact(&self.label), ) } - fn child(&mut self, mut entry: Entry, requested: Option<&Focus>) { + fn child(&mut self, entry: Entry, requested: Option<&Focus>) { + self.insert_child(entry, requested, None); + } + fn insert_child( + &mut self, + mut entry: Entry, + requested: Option<&Focus>, + discovered: Option<EntryId>, + ) { if let Some(existing) = self .children .iter_mut() - .find(|e| e.key.page_match() == entry.key.page_match() && e.locator == entry.locator) + .find(|e| e.card_page() == entry.card_page() && e.locator == entry.locator) { existing.add_sources(entry.sources); + if let Some(id) = + discovered.filter(|_| existing.key.page_match() == entry.key.page_match()) + { + existing.id = id; + } return; } if self.children.len() == MAX_CHILDREN @@ -884,7 +1157,8 @@ impl Entry { self.more += 1; } if self.children.len() < MAX_CHILDREN { - entry.id = EntryId::new(Some(&self.id), &entry.key, &entry.locator); + entry.id = discovered + .unwrap_or_else(|| EntryId::new(Some(&self.id), &entry.key, &entry.locator)); self.children.push(entry); } else { self.more += 1; @@ -892,6 +1166,80 @@ impl Entry { } } +impl Build<'_> { + fn enrich_section(&mut self, index: usize, page: &Doc) { + let (mut preferred, others): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.sections[index].children) + .into_iter() + .partition(|e| e.sources.first() == Some(&Source::MenuGroup)); + self.sections[index].children.append(&mut preferred); + self.section_page(index, page); + for child in others { + let id = child.id.clone(); + let requested = self.requested; + self.sections[index].insert_child(child, requested, Some(id)); + } + } +} + +pub(crate) fn enrich_held( + place: Place, + index: usize, + page: &Doc, + child_cap: usize, +) -> (Place, PlaceStats) { + let mut build = Build { + localized: card::localized_pages(page), + names: Default::default(), + llms_headings: Default::default(), + place, + index: Default::default(), + requested: None, + stats: PlaceStats::default(), + }; + let focus = build.focus.clone(); + let focused_child = build.sections[index] + .children + .iter() + .find(|entry| Some(&entry.id) == focus.as_ref()) + .cloned(); + build.enrich_section(index, page); + let siblings: BTreeSet<_> = build + .sections + .iter() + .map(Entry::card_route) + .chain(std::iter::once((build.entry.page_match(), None))) + .collect(); + let section = &mut build.sections[index]; + let mut opened_children = std::mem::take(&mut section.children); + opened_children.retain(|child| { + !card::child_self(child, section) && { + focus.as_ref() == Some(&child.id) + || child.sources.contains(&Source::Heading) + || !siblings.contains(&child.card_route()) + } + }); + section.children = opened_children; + if let Some(focused) = focused_child { + if !section.children.iter().any(|e| e.id == focused.id) { + section.children.push(focused); + } + } + while section.children.len() > child_cap { + let Some(index) = section + .children + .iter() + .rposition(|e| Some(&e.id) != focus.as_ref()) + else { + break; + }; + section.children.remove(index); + section.more = section.more.saturating_add(1); + } + build.notes.truncated |= build.stats.truncated() || build.sections[index].more > 0; + (build.place, build.stats) +} + pub(crate) fn with_results( place: Place, links: &[Link], @@ -899,10 +1247,14 @@ pub(crate) fn with_results( requested: Option<&Focus>, ) -> Result<Place, KeyError> { let mut build = Build { + localized: Default::default(), + names: Default::default(), + llms_headings: Default::default(), index: place .sections .iter() .enumerate() + .filter(|(_, e)| !e.menu_only) .map(|(i, e)| ((e.key.page_match(), e.locator.clone()), i)) .collect(), requested, @@ -916,19 +1268,24 @@ pub(crate) fn with_results( .chain(hint.map(|link| (link, Source::EngineResult))) { if let Some(entry) = build.entry_for(&link.url, &link.title, source) { - if let Some(existing) = build + if let Some(existing) = build.sections.iter_mut().find(|e| { + !e.menu_only && (e.id == entry.id || e.card_route() == entry.card_route()) + }) { + existing.add_sources(entry.sources); + } else if let Some(child) = build .sections .iter_mut() - .find(|existing| existing.id == entry.id) + .flat_map(|e| &mut e.children) + .find(|e| e.id == entry.id || e.card_route() == entry.card_route()) { - existing.add_sources(entry.sources); + child.add_sources(entry.sources); } else { build.section(entry); } } } build.stats.sitelinks_truncated = links.len() > MAX_SITELINKS; - build.finish_sections(); + build.finish_sections(None, None); build.notes.truncated |= build.stats.truncated(); build.check_ids()?; Ok(build.place) @@ -940,29 +1297,25 @@ pub fn read_site_with_stats( doc: &Doc, inputs: &SiteInputs<'_>, ) -> Result<(Place, PlaceStats), KeyError> { - read_site_for(doc, inputs, None) + read_site_for(doc, inputs, None).map(|(place, stats, _)| (place, stats)) } pub(crate) fn read_site_for( doc: &Doc, inputs: &SiteInputs<'_>, requested: Option<&Focus>, -) -> Result<(Place, PlaceStats), KeyError> { +) -> Result<(Place, PlaceStats, Vec<SectionRead>), KeyError> { let key = PlaceKey::from_url(doc.page()).ok_or(KeyError::Url)?; let site = SiteKey::from_url(doc.page()).ok_or(KeyError::Url)?; - let title = [ - doc.head().site_name.as_str(), - doc.head().title.as_str(), - site.as_str(), - ] - .into_iter() - .find(|s| !s.trim().is_empty()) - .unwrap_or_default(); + let title = title::site_title(doc.head(), &site, doc.page()); let mut place = Build { + localized: card::localized_pages(doc), + names: Default::default(), + llms_headings: Default::default(), index: Default::default(), requested, stats: PlaceStats::default(), place: Place { - title: clip(title, TITLE_BYTES), + title, site, entry: key.root(doc.page())?, key, @@ -1038,15 +1391,9 @@ pub(crate) fn read_site_for( }) .collect(); for (i, page) in page_sections { - let (mut preferred, others): (Vec<_>, Vec<_>) = - std::mem::take(&mut place.sections[i].children) - .into_iter() - .partition(|e| e.sources.first() == Some(&Source::MenuGroup)); - place.sections[i].children.append(&mut preferred); - place.section_page(i, page); - for c in others { - place.child(i, c); - } + let home_paths = std::mem::replace(&mut place.localized, card::localized_pages(page)); + place.enrich_section(i, page); + place.localized = home_paths; } place.stats.section_page_truncated |= inputs.pages.len() > MAX_SECTION_PAGES; if let Some(robots) = inputs.robots { @@ -1056,10 +1403,40 @@ pub(crate) fn read_site_for( && !robots.allows(&e.key.as_url()[url::Position::BeforePath..]) }); } - place.finish_sections(); + place.stats.navigation_sections = place + .sections + .iter() + .filter(|e| { + e.sources.iter().any(|s| { + matches!( + s, + Source::PrimaryNav | Source::MenuGroup | Source::Llms | Source::Footer + ) + }) + }) + .count(); + let mut eager = place.eager_reads(); + let mut menus = (!place.notes.wall).then(|| menus::Menus::read(&place, doc)); + let evidence = menus.as_mut().map(|menus| { + for action in menus.take_actions() { + place.section(action); + } + menus.take_evidence() + }); + place.finish_sections(Some(doc.page()), menus); + let mut discovered: BTreeSet<_> = eager.iter().map(|r| r.id.clone()).collect(); + eager.extend( + place + .eager_reads() + .into_iter() + .filter(|r| discovered.insert(r.id.clone())), + ); + if let Some(evidence) = evidence { + evidence.measure(&place.place, &mut place.stats); + } place.check_ids()?; place.notes.truncated = place.stats.truncated() || place.sections.iter().any(|e| e.more > 0); - Ok((place.place, place.stats)) + Ok((place.place, place.stats, eager)) } pub(crate) fn sitemap_priority(url: &Url, entry: &Url) -> (bool, bool, bool) { @@ -1119,7 +1496,8 @@ mod tests { let html = format!("<nav><ul>{links}{menu}</ul></nav>"); let doc = Doc::from_html(&root, html.as_bytes(), None, crate::DocLimits::SITE_PAGE).unwrap(); - let (place, _) = read_site_for(&doc, &SiteInputs::default(), Some(&request)).unwrap(); + let (place, _, _) = + read_site_for(&doc, &SiteInputs::default(), Some(&request)).unwrap(); assert_eq!(place.sections.len(), MAX_PRIMARY_SECTIONS); let focus = place .sections @@ -1149,6 +1527,24 @@ mod tests { mod review_tests { use super::*; + #[test] + fn the_final_card_admits_eager_rows_displaced_from_the_first_shortlist() { + let mut html = String::from("<nav>"); + for i in 0..MAX_PRIMARY_SECTIONS { + html.push_str(&format!("<a href='/docs/{i}'>Docs</a>")); + } + html.push_str("<a href='/pricing'>Pricing</a></nav>"); + let url = Url::parse("https://example.com/").unwrap(); + let doc = Doc::from_html(&url, html.as_bytes(), None, crate::DocLimits::SITE_PAGE).unwrap(); + let (place, _, eager) = read_site_for(&doc, &SiteInputs::default(), None).unwrap(); + let pricing = place + .sections + .iter() + .find(|e| e.label == "Pricing") + .unwrap(); + assert!(eager.iter().any(|r| r.id == pricing.id)); + } + #[test] fn result_sitelink_merges_with_the_discovered_id_after_a_redirect() { let base = Url::parse("https://example.com/").unwrap(); diff --git a/crates/zephium-map/src/site/card.rs b/crates/zephium-map/src/site/card.rs new file mode 100644 index 000000000..547a5aea9 --- /dev/null +++ b/crates/zephium-map/src/site/card.rs @@ -0,0 +1,672 @@ +use super::*; +use crate::PageMatch; + +pub const MAX_PRIMARY_LABEL_CHARS: usize = 48; +pub const MAX_HOST_BYTES: usize = 253; +pub const MAX_PATH_CHARS: usize = 128; +const SENTENCE_WORDS: usize = 7; +const MIN_DIRECTORY_ITEMS: usize = 3; + +pub(super) fn locale(segment: &str) -> bool { + let mut parts = segment.split('-'); + let language = parts.next().unwrap_or_default(); + let alpha = |s: &str| s.bytes().all(|b| b.is_ascii_alphabetic()); + if !(language.len() == 2 || language.len() == 3 && segment.contains('-')) || !alpha(language) { + return false; + } + let mut region = parts.next(); + if region.is_some_and(|s| s.len() == 4 && alpha(s)) { + region = parts.next(); + } + parts.next().is_none() + && region.is_none_or(|s| { + s.len() == 2 && alpha(s) || s.len() == 3 && s.bytes().all(|b| b.is_ascii_digit()) + }) +} + +impl Entry { + pub fn card_page(&self) -> PageMatch { + if self.localized { + if let Some((_, rest)) = locale_path(self.key.as_url()) { + let mut url = self.key.as_url().clone(); + url.set_path(&format!("/{rest}")); + if let Ok(key) = PageKey::from_url(&url) { + return key.page_match(); + } + } + } + self.key.page_match() + } + pub(super) fn card_route(&self) -> (PageMatch, Option<String>) { + (self.card_page(), self.locator.fragment()) + } +} + +pub(super) fn skip_link(url: &Url, label: &str, landing: &Url) -> bool { + url.fragment().is_some_and(|s| !s.is_empty()) + && crate::key::same_page(url, landing) + && skip_label(label) +} + +pub fn skip_label(label: &str) -> bool { + let label = normal(label); + label.starts_with("skip to ") + || matches!( + label.as_str(), + "skip navigation" + | "skip navigation links" + | "jump to content" + | "jump to main content" + ) +} + +fn locale_path(url: &Url) -> Option<(&str, &str)> { + let path = url.path().trim_matches('/'); + let (first, rest) = path.split_once('/').unwrap_or((path, "")); + locale(first).then_some((first, rest)) +} + +pub(super) fn localized_pages(doc: &Doc) -> BTreeSet<PageMatch> { + fn primary(tag: &str) -> &str { + tag.split_once('-').map_or(tag, |(language, _)| language) + } + let links = doc + .nodes() + .iter() + .enumerate() + .filter_map(|(i, n)| { + let url = n.destination.as_ref()?; + visible(doc.nodes(), i).then_some((url, n.link_language.as_deref())) + }) + .chain( + doc.menu_links + .iter() + .filter(|(i, _)| visible(doc.nodes(), **i)) + .flat_map(|(_, links)| links.iter()) + .map(|l| (&l.url, l.language.as_deref())), + ) + .map(|(url, language)| { + let tagged = language + .zip(locale_path(url)) + .is_some_and(|(tag, (prefix, _))| { + primary(tag).eq_ignore_ascii_case(primary(prefix)) + }); + (url, tagged) + }) + .chain( + doc.head() + .alternates + .iter() + .filter(|a| !a.language.is_empty()) + .map(|a| (&a.url, true)), + ); + let observed: BTreeSet<_> = links + .clone() + .map(|(u, _)| u) + .chain([doc.page()]) + .filter_map(|u| PageKey::from_url(u).ok().map(|k| k.page_match())) + .collect(); + let current = locale_path(doc.page()).map(|(lang, _)| lang); + links + .filter_map(|(url, tagged)| { + let (prefix, rest) = locale_path(url)?; + let key = PageKey::from_url(url).ok()?.page_match(); + if tagged || current.is_some_and(|c| c.eq_ignore_ascii_case(prefix)) { + return Some(key); + } + if rest.is_empty() && current.is_none() { + return None; + } + let mut counterpart = url.clone(); + counterpart.set_path(&match current { + Some(lang) => format!("/{lang}/{rest}"), + None => format!("/{rest}"), + }); + observed + .contains(&PageKey::from_url(&counterpart).ok()?.page_match()) + .then_some(key) + }) + .collect() +} + +pub(super) fn placeholder(label: &str) -> bool { + matches!( + normal(label).as_str(), + "" | "other" + | "more" + | "optional" + | "menu" + | "main navigation menu" + | "open sidebar" + | "learn more" + ) +} + +pub(super) fn sentence(label: &str) -> bool { + label.chars().count() > MAX_PRIMARY_LABEL_CHARS + || label.contains(". ") + || label.split_whitespace().count() >= SENTENCE_WORDS +} + +fn version_badge(label: &str) -> bool { + let Some(version) = label.strip_prefix('v') else { + return false; + }; + version.contains('.') + && version + .split('.') + .all(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) +} + +fn path_name(url: &Url) -> Option<String> { + let slug = url.path_segments()?.rfind(|s| !s.is_empty())?; + let slug = super::decode_fragment(slug); + let name = slug + .trim_end_matches(".html") + .trim_end_matches(".md") + .replace(['-', '_'], " "); + (!name.is_empty() + && !sentence(&name) + && !placeholder(&name) + && name.chars().any(char::is_alphabetic) + && name.chars().all(|c| c.is_alphanumeric() || c == ' ')) + .then(|| capitalized(&name)) + .filter(|s| !sentence(s)) +} + +pub(super) fn capitalized(name: &str) -> String { + let mut chars = name.chars(); + match chars.next() { + Some(c) => c.to_uppercase().chain(chars).collect(), + None => String::new(), + } +} + +pub(super) fn action(entry: &Entry) -> bool { + let url = entry.key.as_url(); + let path = url.path().trim_matches('/').to_ascii_lowercase(); + let last = path.rsplit('/').next().unwrap_or_default(); + let label = normal(&entry.label); + if matches!( + last, + "login" + | "signin" + | "sign-in" + | "sign_in" + | "register" + | "signup" + | "sign-up" + | "sign_up" + | "contact-sales" + | "request-demo" + | "book-demo" + ) || path.trim_end_matches(".md").ends_with("contact/sales") + || last.ends_with("enterprise-sales") + || last.ends_with(".dmg") + || last.ends_with(".msi") + || last.ends_with(".exe") + { + return true; + } + if path.starts_with("downloads/") + && label.contains("download") + && label.split_whitespace().next_back() == Some(last) + { + return true; + } + if matches!(last, "download" | "downloads" | "download.html") { + return false; + } + entry.tier == Tier::Action + || (last == "refer" && label.starts_with("refer ")) + || (matches!(last, "shell" | "app") && label.starts_with("launch ")) + || (last == "get-started" && label == "get started" && !path.contains('/')) + || matches!( + label.as_str(), + "sign in" + | "log in or sign up" + | "log in" + | "login" + | "sign up" + | "contact sales" + | "request a demo" + | "get a demo" + | "start free trial" + | "book a demo" + | "get started download" + | "new chat" + | "donate" + | "under attack" + ) +} + +pub(super) fn self_link(entry: &Entry, root: &PageKey, landing: Option<&Url>) -> bool { + if entry.locator != Locator::default() { + return false; + } + let url = entry.key.as_url(); + if entry.card_page() == root.page_match() + || landing.is_some_and(|u| crate::key::same_page(u, url)) + { + return true; + } + let host = |u: &Url| u.domain().map(|h| h.trim_start_matches("www.").to_owned()); + if host(url) != host(root.as_url()) || url.query().is_some() { + return false; + } + let named_home = normal(&entry.label) + .split_whitespace() + .any(|w| matches!(w, "home" | "homepage")); + let brand = host(url).is_some_and(|h| { + h.split('.') + .next() + .is_some_and(|s| s.eq_ignore_ascii_case(&entry.label)) + }); + match url.path().trim_matches('/') { + "index.html" | "homepage" => true, + "home" => brand || named_home && !entry.label.eq_ignore_ascii_case("home"), + "product" => named_home, + path if locale(path) => named_home, + _ => false, + } +} + +impl Build<'_> { + pub(super) fn link_is_edition(&self, entry: &Entry) -> bool { + self.link_name(entry).is_some_and(|n| n.language_host) + } + fn link_name(&self, entry: &Entry) -> Option<&LinkName> { + self.names.get(&entry.id).or_else(|| { + self.names + .get(&EntryId::new(None, &entry.key, &entry.locator)) + }) + } + fn apply_link_name(&self, entry: &mut Entry) { + let is_action = action(entry); + if let Some(name) = self.link_name(entry) { + if !name.text.is_empty() { + entry.label.clone_from(&name.text); + if entry.off_site + && normal(&entry.label).starts_with("open on ") + && entry.role.is_some() + { + if let Some(name) = path_name(entry.key.as_url()) { + entry.path_name = true; + entry.label = name; + } + } + } + if name.action { + entry.tier = Tier::Action; + } + } + if is_action { + entry.tier = Tier::Action; + } + } + + pub(super) fn edit_card(&mut self, landing: Option<&Url>) { + let mut candidates = Vec::new(); + let entries = std::mem::take(&mut self.sections); + let home = |e: &Entry| { + self_link(e, &self.entry, landing) + || e.locator.element.is_some() + && skip_label(&e.label) + && (e.key.page_match() == self.entry.page_match() + || landing.is_some_and(|u| crate::key::same_page(u, e.key.as_url()))) + }; + let originals: std::collections::HashMap<_, _> = entries + .iter() + .map(|e| ((e.key.page_match(), e.locator.clone()), e.id.clone())) + .collect(); + for mut entry in entries { + self.apply_link_name(&mut entry); + for child in &mut entry.children { + self.apply_link_name(child); + } + let remove = !entry.menu_only && (home(&entry) || placeholder(&entry.label)); + let keep_members = !placeholder(&entry.label) || !entry.sources.contains(&Source::Llms); + for mut child in entry + .children + .extract_if(.., |c| remove || c.tier == Tier::Action) + { + if (keep_members || child.tier == Tier::Action) + && !placeholder(&child.label) + && !home(&child) + { + if let Some(id) = + originals.get(&(child.key.page_match(), child.locator.clone())) + { + child.id = id.clone(); + } + candidates.push(child); + } + } + if !remove { + candidates.push(entry); + } + } + // Prefer the site's navigation over a second representation in a list or result. + candidates.sort_by_key(|e| (!e.navigation_row(), e.tier)); + let roots: BTreeSet<_> = candidates + .iter() + .filter(|e| { + (e.key.as_url().path() == "/" || self.link_name(e).is_some_and(|n| n.host_root)) + && e.locator == Locator::default() + }) + .map(|e| e.key.as_url().host_str().map(str::to_owned)) + .collect(); + let mut destinations = std::collections::HashMap::new(); + let mut labels = BTreeMap::new(); + let mut editions = BTreeMap::new(); + for mut e in candidates { + if action(&e) { + e.tier = Tier::Action; + } else if e.tier == Tier::Primary + && ((e.key.as_url().host_str() != self.entry.as_url().host_str() + && roots.contains(&e.key.as_url().host_str().map(str::to_owned)) + && e.key.as_url().path().trim_matches('/').contains('/')) + || e.key.as_url().path().contains("/news/") && e.label.ends_with('!')) + { + e.tier = Tier::Secondary; + } else if e.tier == Tier::Primary && (sentence(&e.label) || version_badge(&e.label)) { + if let Some(name) = path_name(e.key.as_url()) { + e.path_name = true; + e.label = name; + } else { + e.tier = Tier::Secondary; + } + } + let destination = ( + e.card_page(), + e.locator.clone(), + e.menu_only.then(|| e.id.clone()), + ); + let label = crate::flatten(&e.label).to_lowercase(); + let edition = self + .link_name(&e) + .filter(|n| n.language_host) + .and_then(|_| e.key.as_url().domain()?.split_once('.')) + .map(|(_, host)| { + ( + host.to_owned(), + e.key.as_url()[url::Position::BeforePath..].to_owned(), + e.locator.fragment(), + ) + }); + if edition.is_some() { + e.tier = Tier::Secondary; + } + let existing = destinations + .get(&destination) + .or_else(|| edition.as_ref().and_then(|key| editions.get(key))) + .or_else(|| labels.get(&(label.clone(), e.menu_only))) + .copied(); + if let Some(i) = existing { + let kept: &mut Entry = &mut self.place.sections[i]; + let tier = kept.tier; + kept.add_sources(e.sources.iter().copied()); + kept.tier = if tier == Tier::Action || e.tier == Tier::Action { + Tier::Action + } else { + tier.min(e.tier) + }; + let children = std::mem::take(&mut e.children); + if destination + != ( + kept.card_page(), + kept.locator.clone(), + kept.menu_only.then(|| kept.id.clone()), + ) + { + kept.child(e, self.requested); + } + for child in children { + kept.child(child, self.requested); + } + labels.insert((label, destination.2.is_some()), i); + destinations.insert(destination, i); + if let Some(key) = edition { + editions.insert(key, i); + } + } else { + let index = self.sections.len(); + destinations.insert(destination, index); + labels.insert((label, e.menu_only), index); + if let Some(key) = edition { + editions.insert(key, index); + } + self.sections.push(e); + } + } + self.prefer_observed_directories(); + } + pub(super) fn fill_from_footer(&mut self, saw_nav: bool) { + if saw_nav + && self + .sections + .iter() + .filter(|e| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) + .count() + < MIN_NAV_ROWS + { + for e in &mut self.sections { + if e.tier == Tier::Secondary + && e.sources.contains(&Source::Footer) + && !e.utility() + && !sentence(&e.label) + && e.role.is_some() + && section_role("", e.key.as_url()) == e.role + { + e.tier = Tier::Primary; + } + } + } + } + fn prefer_observed_directories(&mut self) { + let mut children = BTreeMap::<_, Vec<usize>>::new(); + for (i, e) in self.sections.iter().enumerate().filter(|(_, e)| { + e.tier == Tier::Primary + && !e + .children + .iter() + .any(|c| c.sources.contains(&Source::MenuGroup)) + }) { + let url = e.key.as_url(); + if let Some((parent, _)) = url.path().trim_end_matches('/').rsplit_once('/') { + if !parent.is_empty() { + children + .entry((url.origin().ascii_serialization(), parent.to_owned())) + .or_default() + .push(i); + } + } + } + let parents: BTreeMap<_, _> = self + .sections + .iter() + .enumerate() + .filter(|(_, e)| { + e.tier != Tier::Action + && e.locator == Locator::default() + && e.key.as_url().query().is_none() + }) + .map(|(i, e)| { + ( + ( + e.key.as_url().origin().ascii_serialization(), + e.key.as_url().path().trim_end_matches('/').to_owned(), + ), + i, + ) + }) + .collect(); + for (path, indices) in children { + let Some(&i) = parents.get(&path) else { + continue; + }; + let parent = &mut self.sections[i]; + let release_listing = matches!( + parent.role, + Some(SectionRole::Changelog | SectionRole::Releases) + ); + if release_listing + || (path.1.trim_matches('/').contains('/') && indices.len() >= MIN_DIRECTORY_ITEMS) + { + if let Some(name) = path_name(parent.key.as_url()) { + if parent.label.starts_with(char::is_numeric) || sentence(&parent.label) { + parent.path_name = true; + parent.label = name; + } + parent.tier = Tier::Primary; + for i in indices { + let child = &mut self.sections[i]; + if !release_listing || !child.sources.contains(&Source::Footer) { + child.tier = Tier::Secondary; + } + } + } + } + } + } +} + +pub(super) fn child_self(child: &Entry, parent: &Entry) -> bool { + !parent.menu_only && child.locator == parent.locator && child.card_page() == parent.card_page() +} + +fn scheme_like(segment: &str) -> bool { + segment.strip_suffix(':').is_some_and(|scheme| { + scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }) +} + +pub fn display_path(url: &Url) -> String { + let mut out = String::new(); + for segment in url.path().split('/').filter(|s| !s.is_empty()) { + if scheme_like(segment) { + break; + } + out.push('/'); + out.push_str(segment); + } + if out.is_empty() { + out.push('/'); + } + match out.char_indices().nth(MAX_PATH_CHARS) { + Some((cut, _)) => out[..cut].to_owned(), + None => out, + } +} + +pub fn display_hostname(url: &Url) -> Option<&str> { + let host = url.domain()?.trim_end_matches('.'); + (!host.is_empty() + && host.len() <= MAX_HOST_BYTES + && host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))) + .then_some(host) +} + +impl Entry { + pub fn navigation_row(&self) -> bool { + self.sources.iter().any(|s| { + matches!( + s, + Source::PrimaryNav | Source::MenuGroup | Source::LinkCluster + ) + }) + } +} + +impl Build<'_> { + pub(super) fn merge_supplements(&mut self) { + let sparse = self + .sections + .iter() + .filter(|e| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) + .count() + < MIN_NAV_ROWS; + let mut roles = BTreeMap::new(); + let mut names = BTreeMap::new(); + let mut merged = BTreeMap::new(); + for (i, e) in self + .sections + .iter() + .enumerate() + .filter(|(_, e)| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) + { + let label = normal(&e.label); + names.entry(label).or_insert(i); + if let Some(role) = e.role { + roles.entry(role).or_insert(i); + } + } + let headings = &self.llms_headings; + for (i, e) in self.place.sections.iter_mut().enumerate() { + if e.navigation_row() + || e.tier == Tier::Action + || e.utility() + || !e + .sources + .iter() + .any(|s| matches!(s, Source::Llms | Source::Sitemap)) + { + continue; + } + let heading = headings.get(&e.id); + if let Some(parent) = heading.and_then(|name| names.get(name)) { + merged.insert(i, *parent); + continue; + } + let role = heading.map_or(e.role, |name| label_role(name)); + if let Some(role) = role { + if let Some(&parent) = roles.get(&role) { + merged.insert(i, parent); + } else if !sentence(&e.label) + && (e.tier == Tier::Primary + || e.sources.first() == Some(&Source::Sitemap) + && SECTION_WORDS + .iter() + .any(|(name, r)| *r == role && e.label.eq_ignore_ascii_case(name))) + { + e.tier = Tier::Primary; + roles.insert(role, i); + } + } else if !sparse { + e.tier = Tier::Secondary; + } + } + if merged.is_empty() { + return; + } + let mut rows: Vec<_> = std::mem::take(&mut self.sections) + .into_iter() + .map(Some) + .collect(); + for (index, owner) in merged { + let Some(mut entry) = rows[index].take() else { + continue; + }; + let Some(kept) = &mut rows[owner] else { + continue; + }; + let mut children = std::mem::take(&mut entry.children); + kept.add_sources(entry.sources.iter().copied()); + let prior = entry.id.clone(); + if let Some(i) = children.iter().position(|c| child_self(c, &entry)) { + kept.insert_child(children.remove(i), self.requested, Some(prior)); + } else if !entry.menu_only && !child_self(&entry, kept) { + kept.insert_child(entry, self.requested, Some(prior)); + } + for child in children { + kept.child(child, self.requested); + } + } + self.sections = rows.into_iter().flatten().collect(); + } +} diff --git a/crates/zephium-map/src/site/menus.rs b/crates/zephium-map/src/site/menus.rs new file mode 100644 index 000000000..228a99de1 --- /dev/null +++ b/crates/zephium-map/src/site/menus.rs @@ -0,0 +1,888 @@ +use super::*; +use crate::Node; + +const MIN_MENU_ITEMS: usize = 2; + +mod editions; +use editions::Editions; +#[cfg(test)] +mod tests; + +#[derive(Default)] +pub(super) struct Menus { + actions: Vec<Entry>, + members: BTreeSet<EntryId>, + groups: BTreeMap<usize, Menu>, + order: BTreeMap<EntryId, usize>, + direct: BTreeMap<(crate::PageMatch, Option<String>), (usize, Entry)>, + excluded: BTreeSet<EntryId>, + evidence: Evidence, +} + +#[derive(Default)] +pub(super) struct Evidence { + direct: BTreeMap<EntryId, (crate::PageMatch, Option<String>)>, + pages: BTreeMap<String, Option<EntryId>>, + languages: BTreeSet<String>, + editions: std::collections::HashSet<(crate::PageMatch, Locator)>, +} + +impl Evidence { + pub(super) fn measure(&self, place: &Place, stats: &mut PlaceStats) { + let primary: BTreeSet<_> = place + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .flat_map(|e| [e.id.clone(), EntryId::new(None, &e.key, &e.locator)]) + .collect(); + let primary_routes: BTreeSet<_> = place + .sections + .iter() + .filter(|e| e.tier == Tier::Primary && !e.menu_only) + .map(Entry::card_route) + .collect(); + stats.missing_header_links = self + .direct + .iter() + .filter(|(id, route)| !primary.contains(id) && !primary_routes.contains(route)) + .count(); + for e in &place.sections { + let label = normal(&e.label); + let language_group = self.languages.contains(&label) && !e.children.is_empty() + || e.children.len() >= MIN_MENU_ITEMS + && e.children + .iter() + .all(|c| self.editions.contains(&(c.card_page(), c.locator.clone()))); + stats.language_groups += usize::from(language_group); + if !e.menu_only + && (e.children.iter().any(|c| c.card_route() == e.card_route()) + || !self.direct.contains_key(&e.id) + && self.pages.get(&label).is_some_and(|page| { + page.as_ref().is_none_or(|id| { + *id != e.id && *id != EntryId::new(None, &e.key, &e.locator) + }) + })) + { + stats.invalid_group_pages += 1; + } + } + } +} + +#[derive(Clone, Copy, Default, PartialEq)] +enum Region { + #[default] + Other, + Navigation, + Footer, + Excluded, +} + +struct Menu { + label: String, + page: Option<Entry>, + index: Option<Entry>, + items: Vec<Entry>, + trigger: Option<EntryId>, + source: Source, + editions: Editions, +} + +impl Menu { + fn add_item(&mut self, mut item: Entry) { + let label = normal(&item.label); + let group = normal(&self.label); + if label == group + || group_page(&label) == Some(group.as_str()) + || matches!( + label.as_str(), + "see all" | "view all" | "browse all" | "explore all" + ) + || label == "overview" + && item + .key + .as_url() + .path_segments() + .and_then(|mut s| s.next_back()) + .is_some_and(|s| normal(s) == group) + { + self.index.get_or_insert(item); + } else { + item.menu_item = true; + self.items.push(item); + } + } +} + +pub(super) fn link_label(n: &Node) -> &str { + let prefix = n.text.get(..n.link_prefix_bytes).filter(|s| { + !s.is_empty() + && n.text[s.len()..].starts_with(char::is_whitespace) + && s.chars().any(char::is_alphabetic) + && !matches!(normal(s).as_str(), "new" | "beta") + }); + [Some(n.name.trim()), Some(n.text.trim()), prefix] + .into_iter() + .flatten() + .filter(|s| !s.is_empty()) + .min_by_key(|s| s.chars().count()) + .unwrap_or_default() +} + +fn group_page(label: &str) -> Option<&str> { + ["see all ", "view all ", "browse all ", "explore all "] + .into_iter() + .find_map(|prefix| label.strip_prefix(prefix)) +} + +impl Menus { + pub(super) fn read(build: &Build<'_>, doc: &Doc) -> Self { + let nodes = doc.nodes(); + let mut menus = Self::default(); + let mut scopes = BTreeMap::new(); + let mut named = BTreeMap::new(); + let mut footer = BTreeMap::new(); + let mut first_nav = None; + let alternates: BTreeSet<_> = doc + .head() + .alternates + .iter() + .filter(|a| !a.language.is_empty()) + .filter_map(|a| { + Some(( + PageKey::from_url(&a.url).ok()?.page_match(), + a.url.fragment().map(str::to_owned), + )) + }) + .collect(); + let mut standalone = Vec::new(); + let actions: BTreeSet<_> = build + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .filter(|e| card::action(e)) + .map(Entry::card_route) + .collect(); + let clusters: BTreeSet<_> = build + .sections + .iter() + .filter(|e| e.sources.contains(&Source::LinkCluster)) + .map(|e| e.id.clone()) + .collect(); + let mut following = vec![None; nodes.len()]; + let mut sibling = vec![None; nodes.len()]; + let mut peer_buttons = vec![0; nodes.len()]; + for (i, n) in nodes.iter().enumerate().rev() { + if let Some(p) = n.parent_index() { + following[i] = sibling[p].replace(i); + peer_buttons[p] += usize::from(n.role == Role::Button && visible(nodes, i)); + } + } + let mut regions = Vec::with_capacity(nodes.len()); + for (i, n) in nodes.iter().enumerate() { + let inherited = n.parent_index().map(|p| regions[p]).unwrap_or_default(); + let region = match (inherited, n.role) { + (Region::Excluded, _) + | (_, Role::Document) + | ( + _, + Role::Landmark { + landmark: Some(Landmark::Main | Landmark::Complementary), + }, + ) => Region::Excluded, + (Region::Footer, _) + | ( + _, + Role::Landmark { + landmark: Some(Landmark::Contentinfo), + }, + ) => Region::Footer, + ( + _, + Role::Landmark { + landmark: Some(Landmark::Banner), + }, + ) => Region::Navigation, + ( + _, + Role::Landmark { + landmark: Some(Landmark::Navigation), + }, + ) if visible(nodes, i) && *first_nav.get_or_insert(i) == i => Region::Navigation, + _ => inherited, + }; + regions.push(region); + if region == Region::Excluded + || region == Region::Other && (clusters.is_empty() || n.role != Role::Link) + || !visible(nodes, i) + { + continue; + } + let nav = region == Region::Navigation; + let parent = n.parent_index(); + let label = if n.role == Role::Text { + n.text.trim() + } else { + n.accessible_name().trim() + }; + if n.destination + .as_ref() + .is_some_and(|u| card::skip_link(u, link_label(n), doc.page())) + { + continue; + } + if n.role == Role::Link + && n.destination.as_ref().is_some_and(|u| { + u.fragment().is_none() + && build + .entry_for(u, label, Source::PrimaryNav) + .is_some_and(|e| card::self_link(&e, &build.entry, Some(doc.page()))) + }) + { + continue; + } + if region == Region::Footer { + if matches!(n.role, Role::Text | Role::Heading { .. } | Role::Button) + && !n.text.trim().is_empty() + && !ancestors(nodes, i).any(|a| nodes[a].role == Role::Link) + { + if let Some(p) = parent { + footer.insert(p, normal(&n.text)); + } + } + continue; + } + let paired_panel = |control: usize| { + let p = nodes[control].parent_index()?; + let panel = following[control]?; + (matches!(nodes[p].role, Role::Group | Role::ListItem) + && sibling[p] == Some(control) + && following[panel].is_none() + && matches!( + nodes[panel].role, + Role::List + | Role::Group + | Role::Landmark { + landmark: Some(Landmark::Navigation) + } + )) + .then_some(panel) + }; + let scope = match n.role { + Role::Group | Role::List if !label.is_empty() => Some(i), + Role::Button | Role::Link if doc.menu_links.contains_key(&i) => Some(i), + Role::Button | Role::Heading { .. } => parent + .filter(|&p| { + matches!(nodes[p].role, Role::Group | Role::ListItem) + && (n.role != Role::Button || peer_buttons[p] == 1) + }) + .or_else(|| { + following[i] + .filter(|&next| matches!(nodes[next].role, Role::Group | Role::List)) + }), + Role::Link => parent + .filter(|&p| nodes[p].role == Role::ListItem && !scopes.contains_key(&p)) + .or_else(|| paired_panel(i)), + Role::Text if nav => paired_panel(i).or_else(|| { + parent + .filter(|&p| { + nodes[p].role == Role::Group + && sibling[p] == Some(i) + && following[i].is_none() + }) + .and_then(paired_panel) + }), + _ => None, + }; + let Some(scope) = scope else { continue }; + if normal(label) + .split_whitespace() + .any(|w| w == "menu" || w == "navigation") + || card::placeholder(label) + || card::sentence(label) + || ancestors(nodes, i) + .skip(1) + .any(|a| nodes[a].role == Role::Link) + { + continue; + } + let key = normal(label); + let page = n + .destination + .as_ref() + .and_then(|u| build.entry_for(u, label, Source::PrimaryNav)); + if page.as_ref().is_some_and(card::action) { + continue; + } + let page = page.filter(|e| !card::self_link(e, &build.entry, Some(doc.page()))); + let trigger = page + .as_ref() + .filter(|e| e.key.page_match() == build.entry.page_match()) + .map(|e| e.id.clone()); + let page = page.filter(|_| trigger.is_none()); + let owner = if page.is_none() { + *named.entry(key).or_insert(i) + } else { + i + }; + menus.groups.entry(owner).or_insert_with(|| Menu { + label: clip(&crate::clean_text(label), TITLE_BYTES), + page, + index: None, + trigger, + source: if nav { + Source::PrimaryNav + } else { + Source::LinkCluster + }, + items: Vec::new(), + editions: Editions::default(), + }); + if let Some(links) = doc.menu_links.get(&i) { + if let Some(menu) = menus.groups.get_mut(&owner) { + for link in links { + let (url, label) = (&link.url, link.label.as_str()); + if card::skip_link(url, label, doc.page()) { + continue; + } + menu.editions + .observe(url, &build.localized, doc.page(), &alternates); + if let Some(mut e) = + build.entry_for(url, label, Source::MenuGroup).filter(|e| { + !(card::placeholder(label) + || card::self_link(e, &build.entry, Some(doc.page())) + || e.off_site && site_profile(url).is_some()) + }) + { + if card::action(&e) { + e.tier = Tier::Action; + menus.actions.push(e); + } else { + menu.add_item(e); + } + } + } + } + } + scopes + .entry(scope) + .and_modify(|previous| { + if *previous != Some(owner) { + *previous = None; + } + }) + .or_insert(Some(owner)); + } + let mut footer_links = Vec::new(); + let mut seen = BTreeSet::new(); + let mut flat_scopes = vec![None; nodes.len()]; + let mut flat_headings = BTreeMap::new(); + for (i, n) in nodes.iter().enumerate() { + let region = regions[i]; + let nav = region == Region::Navigation; + if nav { + if let Some(p) = n.parent_index() { + if matches!(n.role, Role::Text | Role::ListItem) + && (sibling[p] == Some(i) || flat_headings.contains_key(&p)) + && !n.text.is_empty() + && visible(nodes, i) + { + if let Some(&owner) = named.get(&normal(&n.text)) { + flat_headings.insert(p, owner); + } + } + flat_scopes[i] = flat_headings.get(&p).copied().or(flat_scopes[p]); + } + } + let Some(url) = &n.destination else { continue }; + if region == Region::Excluded + || region == Region::Other && clusters.is_empty() + || !visible(nodes, i) + { + continue; + } + let label = link_label(n); + if card::skip_link(url, label, doc.page()) { + if let Some(entry) = build.entry_for(url, label, Source::MenuGroup) { + menus.excluded.insert(entry.id); + } + continue; + } + let owner = ancestors(nodes, i) + .filter_map(|a| scopes.get(&a).copied().flatten()) + .last(); + if let Some(menu) = owner + .filter(|&o| o != i) + .and_then(|o| menus.groups.get_mut(&o)) + { + menu.editions + .observe(url, &build.localized, doc.page(), &alternates); + } + if SiteKey::from_url(url).as_ref() != Some(&build.site) && site_profile(url).is_some() { + continue; + } + let Some(entry) = build.entry_for(url, label, Source::MenuGroup) else { + continue; + }; + if n.marks.has(crate::doc::Marks::ACTION) + || card::action(&entry) + || actions.contains(&entry.card_route()) + || card::self_link(&entry, &build.entry, Some(doc.page())) + || card::placeholder(label) + { + continue; + } + if region == Region::Footer { + if entry.footer_utility() { + continue; + } + let group = ancestors(nodes, i).find_map(|a| footer.get(&a)); + if let Some(owner) = group.and_then(|g| { + named.get(g).or_else(|| { + g.split_once(" and ") + .and_then(|(first, _)| named.get(first)) + }) + }) { + footer_links.push((*owner, entry)); + } + continue; + } + if !nav && !clusters.contains(&entry.id) { + continue; + } + menus.order.entry(entry.id.clone()).or_insert(i); + let label = normal(label); + let all = group_page(&label).and_then(|g| named.get(g)).copied(); + if let Some(owner) = all { + if let Some(menu) = menus.groups.get_mut(&owner) { + menu.index.get_or_insert(entry); + } + } else if let Some(owner) = owner.filter(|&o| o != i) { + if seen.insert((owner, entry.id.clone())) { + if let Some(menu) = menus.groups.get_mut(&owner) { + menu.add_item(entry); + } + } + } else if nav { + standalone.push((i, entry)); + } + } + let mut by_label = BTreeMap::new(); + let mut joined = BTreeMap::<usize, Menu>::new(); + let mut owners = BTreeMap::new(); + for (i, menu) in menus.groups { + let key = normal(&menu.label); + let owner = *by_label.entry(key).or_insert(i); + owners.insert(i, owner); + if let Some(kept) = joined.get_mut(&owner) { + if kept.page.is_none() { + kept.page = menu.page; + } + if kept.index.is_none() { + kept.index = menu.index; + } + kept.items.extend(menu.items); + kept.editions.merge(menu.editions); + } else { + joined.insert(owner, menu); + } + } + menus.groups = joined; + let header_items: BTreeSet<_> = menus + .groups + .iter() + .flat_map(|(&i, menu)| menu.items.iter().map(move |e| (i, e.card_route()))) + .collect(); + let empty: BTreeSet<_> = menus + .groups + .iter() + .filter(|(_, m)| m.editions.targets.is_empty()) + .map(|(&i, _)| i) + .collect(); + for (owner, mut entry) in footer_links { + if let Some(menu) = owners + .get(&owner) + .filter(|o| empty.contains(o)) + .and_then(|o| menus.groups.get_mut(o)) + { + menu.editions.observe( + entry.key.as_url(), + &build.localized, + doc.page(), + &alternates, + ); + entry.sources = vec![Source::Footer, Source::MenuGroup]; + menu.add_item(entry); + } + } + for (i, entry) in standalone { + if flat_scopes[i] + .map(|owner| { + ancestors(nodes, owner) + .filter_map(|a| scopes.get(&a).copied().flatten()) + .last() + .unwrap_or(owner) + }) + .and_then(|owner| owners.get(&owner)) + .is_some_and(|owner| header_items.contains(&(*owner, entry.card_route()))) + { + continue; + } + let control = owners + .get(&i) + .and_then(|o| menus.groups.get(o)) + .is_some_and(|m| !m.items.is_empty() || m.editions.is_picker()); + if !control { + menus.direct.entry(entry.card_route()).or_insert((i, entry)); + } + } + menus.groups.retain(|_, m| { + if m.editions.is_picker() { + menus.evidence.languages.insert(normal(&m.label)); + menus + .evidence + .editions + .extend(m.items.iter().map(|e| (e.card_page(), e.locator.clone()))); + menus + .excluded + .extend(m.items.iter().chain(&m.page).map(|e| e.id.clone())); + false + } else { + true + } + }); + let landings: BTreeMap<_, _> = build + .sections + .iter() + .filter(|e| e.id != EntryId::new(None, &e.key, &e.locator)) + .map(|e| (&e.id, e.card_route())) + .collect(); + let route = |e: &Entry| { + landings + .get(&e.id) + .cloned() + .unwrap_or_else(|| e.card_route()) + }; + let mut claimed = BTreeMap::new(); + let mut ambiguous = BTreeSet::new(); + for (owner, menu) in menus.groups.iter().filter(|(_, m)| !m.items.is_empty()) { + for page in menu.page.iter().chain(&menu.index) { + let destination = route(page); + if claimed + .insert(destination.clone(), owner) + .is_some_and(|previous| previous != owner) + { + ambiguous.insert(destination); + } + } + } + for menu in menus.groups.values_mut() { + let items: BTreeSet<_> = menu.items.iter().map(&route).collect(); + menu.page = menu + .page + .take() + .into_iter() + .chain(menu.index.take()) + .find(|p| { + let target = route(p); + !menus.direct.contains_key(&p.card_route()) + && !ambiguous.contains(&target) + && !items.contains(&target) + }); + let mut distinct = BTreeSet::new(); + menu.items.retain(|e| { + distinct.insert(e.card_route()) && !menus.direct.contains_key(&e.card_route()) + }); + if !menu.items.is_empty() { + menus.evidence.pages.insert( + normal(&menu.label), + menu.page.as_ref().map(|e| e.id.clone()), + ); + menus + .members + .extend(menu.items.iter().map(|e| e.id.clone())); + } + } + let triggers: BTreeSet<_> = menus + .groups + .values() + .filter(|m| !m.items.is_empty()) + .filter_map(|m| m.trigger.as_ref()) + .collect(); + menus.direct.retain(|_, (_, e)| { + !(e.utility() + || card::sentence(&e.label) + || build.link_is_edition(e) + || menus.excluded.contains(&e.id) + || triggers.contains(&e.id)) + }); + menus.evidence.direct.extend( + menus + .direct + .values() + .map(|(_, e)| (e.id.clone(), e.card_route())), + ); + for e in build + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + { + if menus + .members + .contains(&EntryId::new(None, &e.key, &e.locator)) + { + menus.members.insert(e.id.clone()); + } + } + menus + } + + pub(super) fn take_evidence(&mut self) -> Evidence { + std::mem::take(&mut self.evidence) + } + pub(super) fn take_actions(&mut self) -> Vec<Entry> { + std::mem::take(&mut self.actions) + } +} + +impl Menus { + pub(super) fn apply(mut self, build: &mut Build<'_>) { + let mut direct_routes = BTreeSet::new(); + let member_routes: BTreeSet<_> = self + .groups + .values() + .flat_map(|m| m.items.iter().map(Entry::card_route)) + .collect(); + build.sections.retain(|e| { + !self + .excluded + .contains(&EntryId::new(None, &e.key, &e.locator)) + }); + for e in &mut build.sections { + e.children.retain(|c| { + !self + .excluded + .contains(&EntryId::new(None, &c.key, &c.locator)) + }); + } + let available: BTreeMap<_, _> = build + .sections + .iter() + .enumerate() + .map(|(i, e)| (e.card_route(), i)) + .collect(); + let discovered: BTreeMap<_, _> = build + .sections + .iter() + .enumerate() + .map(|(i, e)| (e.id.clone(), i)) + .collect(); + let mut named_rows: BTreeSet<_> = build.sections.iter().map(|e| normal(&e.label)).collect(); + for (route, (position, mut entry)) in self.direct { + if let Some(i) = discovered + .get(&entry.id) + .or_else(|| available.get(&route)) + .copied() + { + let e = &mut build.sections[i]; + if e.tier != Tier::Action { + e.add_sources([Source::PrimaryNav]); + if !e.path_name { + e.label = entry.label; + e.role = entry.role; + } + direct_routes.insert(route); + } + continue; + } + if named_rows.insert(normal(&entry.label)) { + entry.sources = vec![Source::PrimaryNav]; + entry.tier = Tier::Primary; + self.order.insert(entry.id.clone(), position); + direct_routes.insert(route); + build.sections.push(entry); + } + } + let mut old: BTreeMap<_, _> = std::mem::take(&mut build.sections) + .into_iter() + .enumerate() + .map(|(position, e)| (e.id.clone(), (position, e))) + .collect(); + let routes: BTreeMap<_, _> = old + .iter() + .map(|(id, (_, e))| (EntryId::new(None, &e.key, &e.locator), id.clone())) + .collect(); + let prior_id = |id: &EntryId| routes.get(id).cloned().unwrap_or_else(|| id.clone()); + let localized: BTreeMap<_, _> = old + .values() + .map(|(_, e)| (e.card_route(), e.id.clone())) + .collect(); + let mut rows = Vec::new(); + let mut taken: BTreeSet<_> = self + .groups + .values() + .filter(|m| !m.items.is_empty()) + .filter_map(|m| m.page.as_ref().map(|e| e.id.clone())) + .collect(); + for (position, menu) in self.groups { + if menu.items.is_empty() { + continue; + } + if let Some(id) = &menu.trigger { + old.remove(&prior_id(id)); + } + let Some(mut parent) = menu.page.or_else(|| { + let mut e = build.entry_for(build.entry.as_url(), &menu.label, menu.source)?; + e.id = EntryId::menu(&build.entry, &menu.label); + e.menu_only = true; + Some(e) + }) else { + continue; + }; + let mut extra = Vec::new(); + let mut prior_more = 0; + if let Some((_, existing)) = old.remove(&prior_id(&parent.id)) { + parent = existing; + extra = std::mem::take(&mut parent.children); + prior_more = std::mem::take(&mut parent.more); + } + parent.label = menu.label; + parent.tier = Tier::Primary; + parent.path_name = false; + parent.role = label_role(&parent.label); + parent.add_sources([menu.source]); + self.order.insert(parent.id.clone(), position); + let mut items = menu.items; + if items.len() > MAX_CHILDREN { + let mut ranked: Vec<_> = items.iter().collect(); + ranked.sort_by_key(|e| { + ( + build.requested.and_then(|r| r.rank(e)).is_none(), + e.role.is_none(), + ) + }); + let selected: BTreeSet<_> = ranked + .into_iter() + .take(MAX_CHILDREN) + .map(|e| e.id.clone()) + .collect(); + parent.more += (items.len() - MAX_CHILDREN) as u32; + items.retain(|e| { + if selected.contains(&e.id) { + true + } else { + old.remove(&prior_id(&e.id)); + false + } + }); + } + for mut item in items { + let original = item.id.clone(); + let prior = routes + .get(&original) + .or_else(|| localized.get(&item.card_route())) + .cloned() + .unwrap_or_else(|| original.clone()); + if let Some((_, e)) = old.remove(&prior) { + if build + .llms_headings + .get(&e.id) + .is_some_and(|h| *h == normal(&parent.label)) + { + extra.extend( + e.children + .into_iter() + .filter(|c| c.sources.contains(&Source::Llms)), + ); + } + if prior == original || routes.contains_key(&original) { + item.key = e.key; + item.localized = e.localized; + item.off_site = e.off_site; + item.locator = e.locator; + } + item.add_sources(e.sources); + } + let existing = extra + .iter() + .find(|c| c.card_route() == item.card_route()) + .map(|c| c.id.clone()); + let discovered = taken + .insert(prior.clone()) + .then(|| existing.unwrap_or(prior)); + parent.insert_child(item, build.requested, discovered); + } + for mut child in extra { + let route = EntryId::new(None, &child.key, &child.locator); + if self.members.contains(&route) + || direct_routes.contains(&child.card_route()) + || child.sources.first() == Some(&Source::Footer) + { + continue; + } + let previous = prior_id(&route); + let secondary = child.sources.contains(&Source::Llms) + && old + .get(&previous) + .is_some_and(|(_, e)| e.tier == Tier::Secondary && !e.navigation_row()); + let discovered = if secondary { + old.remove(&previous).map(|(_, e)| { + child.add_sources(e.sources); + e.id + }) + } else { + None + }; + parent.insert_child(child, build.requested, discovered); + } + parent.more = parent.more.max(prior_more); + rows.push((position, parent)); + } + let labels: BTreeMap<_, _> = rows + .iter() + .enumerate() + .map(|(i, (_, e))| (normal(&e.label), i)) + .collect(); + let mut original: Vec<_> = old.into_values().collect(); + original.sort_by_key(|(pos, _)| *pos); + for (_, mut e) in original { + if let Some(&i) = labels + .get(&normal(&e.label)) + .filter(|_| e.tier != Tier::Action && !direct_routes.contains(&e.card_route())) + { + let group = &mut rows[i].1; + if build + .llms_headings + .get(&e.id) + .is_some_and(|name| *name == normal(&group.label)) + { + for child in e.children.into_iter().filter(|c| { + c.sources.contains(&Source::Llms) + && !direct_routes.contains(&c.card_route()) + }) { + group.child(child, build.requested); + } + } + continue; + } + if member_routes.contains(&e.card_route()) { + continue; + } + // Menu destinations can also occur in result, footer or index sections. + e.children.retain(|c| { + !taken.contains(&EntryId::new(None, &c.key, &c.locator)) + && !direct_routes.contains(&c.card_route()) + }); + e.menu_item |= self.members.contains(&e.id); + let order = self + .order + .get(&e.id) + .or_else(|| self.order.get(&EntryId::new(None, &e.key, &e.locator))) + .copied() + .unwrap_or(usize::MAX); + rows.push((order, e)); + } + rows.sort_by_key(|(i, _)| *i); + build.sections = rows.into_iter().map(|(_, e)| e).collect(); + } +} diff --git a/crates/zephium-map/src/site/menus/editions.rs b/crates/zephium-map/src/site/menus/editions.rs new file mode 100644 index 000000000..2782b7927 --- /dev/null +++ b/crates/zephium-map/src/site/menus/editions.rs @@ -0,0 +1,59 @@ +use super::*; + +#[derive(Default)] +pub(super) struct Editions { + pub(super) targets: BTreeSet<crate::PageMatch>, + matched: bool, + unrelated: bool, +} + +fn edition_path(url: &Url, localized: bool) -> (&str, &str) { + let host = url.domain().unwrap_or_default().trim_start_matches("www."); + let host = host + .split_once('.') + .filter(|(first, rest)| card::locale(first) && psl::domain_str(rest).is_some()) + .map_or(host, |(_, rest)| rest); + let path = url.path().trim_matches('/'); + let (first, rest) = path.split_once('/').unwrap_or((path, "")); + ( + host, + if localized && card::locale(first) { + rest + } else { + path + }, + ) +} + +impl Editions { + pub(super) fn observe( + &mut self, + url: &Url, + localized: &BTreeSet<crate::PageMatch>, + current: &Url, + alternates: &BTreeSet<(crate::PageMatch, Option<String>)>, + ) { + let Ok(key) = PageKey::from_url(url) else { + return; + }; + let target = key.page_match(); + let edition = url.port_or_known_default() == current.port_or_known_default() + && url.query() == current.query() + && url.fragment().is_none() + && edition_path(url, localized.contains(&target)) == edition_path(current, true); + let alternate = alternates.contains(&(target.clone(), url.fragment().map(str::to_owned))); + self.unrelated |= !edition && !alternate; + self.matched |= (edition && !crate::key::same_page(url, current)) || alternate; + self.targets.insert(target); + } + + pub(super) fn merge(&mut self, other: Self) { + self.targets.extend(other.targets); + self.matched |= other.matched; + self.unrelated |= other.unrelated; + } + + pub(super) fn is_picker(&self) -> bool { + !self.unrelated && self.targets.len() >= MIN_MENU_ITEMS && self.matched + } +} diff --git a/crates/zephium-map/src/site/menus/tests.rs b/crates/zephium-map/src/site/menus/tests.rs new file mode 100644 index 000000000..31b2bde3b --- /dev/null +++ b/crates/zephium-map/src/site/menus/tests.rs @@ -0,0 +1,31 @@ +use super::*; + +#[test] +fn structural_quality_compares_the_emitted_rows_to_observations() { + let url = Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>One</a><a href='/b'>Two</a></nav>", + None, + crate::DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut place = read_site(&doc, &Default::default()).unwrap(); + let child = place.sections.pop().unwrap(); + let evidence = Evidence { + direct: [(child.id.clone(), child.card_route())].into(), + pages: [("topics".into(), None)].into(), + languages: ["editions".into()].into(), + editions: Default::default(), + }; + place.sections[0].label = "Topics".into(); + place.sections[0].children.push(child); + let mut stats = PlaceStats::default(); + evidence.measure(&place, &mut stats); + assert_eq!(stats.missing_header_links, 1); + assert_eq!(stats.invalid_group_pages, 1); + place.sections[0].label = "Editions".into(); + let mut stats = PlaceStats::default(); + evidence.measure(&place, &mut stats); + assert_eq!(stats.language_groups, 1); +} diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index e22f88bfb..9253c21a1 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -80,18 +80,42 @@ impl Build<'_> { { continue; } + let label = menus::link_label(n); + let marked_action = n.marks.has(crate::doc::Marks::ACTION); let parent = ancestors(nodes, i).skip(1).find_map(|a| { owners .get(&a) .copied() .filter(|_| n.parent_index() != Some(a) || nodes[a].role == Role::ListItem) }); + let hint = |name: &str| LinkName { + text: clip(&crate::clean_text(name), TITLE_BYTES), + action: marked_action, + host_root: url.path() == "/" && url.query().is_none(), + language_host: n.marks.has(crate::doc::Marks::LANGUAGE_HOST), + }; if nav && !footer && parent.is_none() { - if let Some((item, label)) = ancestors(nodes, i) + if let Some((item, group)) = ancestors(nodes, i) .take_while(|&a| !matches!(nodes[a].role, Role::Landmark { landmark: _ })) .find_map(|a| menu_labels.get(&a).map(|s| (a, *s))) { - if let Some(section) = self.entry_for(url, label, Source::PrimaryNav) { + if let Some(section) = self.entry_for(url, group, Source::PrimaryNav) { + let name = if section_role(label, url).is_some() + && normal(label) + == normal( + url.path() + .trim_matches('/') + .rsplit('/') + .next() + .unwrap_or_default(), + ) { + label + } else { + group + }; + self.names + .entry(section.id.clone()) + .or_insert_with(|| hint(name)); let index = self.section(section); owners.insert(item, index); } @@ -108,6 +132,14 @@ impl Build<'_> { let Some(mut entry) = self.entry_for(url, n.accessible_name(), source) else { continue; }; + let name = self + .names + .entry(entry.id.clone()) + .or_insert_with(|| hint(label)); + name.action |= marked_action; + if card::sentence(&name.text) && !card::sentence(label) && !label.is_empty() { + name.text = clip(&crate::clean_text(label), TITLE_BYTES); + } if footer { entry.group = ancestors(nodes, i).find_map(|a| group_labels.get(&a).cloned()); } @@ -156,6 +188,7 @@ impl Build<'_> { } if let Some(url) = &n.destination { if n.accessible_name().is_empty() + || card::skip_link(url, menus::link_label(n), doc.page()) || n.accessible_name().chars().count() > MAX_CLUSTER_LABEL_CHARS || SiteKey::from_url(url).as_ref() != Some(&self.site) { @@ -260,6 +293,7 @@ impl Build<'_> { if !crate::key::same_page(doc.page(), self.sections[index].key.as_url()) || doc.page().fragment().is_some() { + self.sections[index].localized = self.localized.contains(&key.page_match()); self.sections[index].locator = element_locator(doc.page()).unwrap_or_default(); } self.sections[index].key = key.clone(); diff --git a/crates/zephium-map/src/site/title.rs b/crates/zephium-map/src/site/title.rs new file mode 100644 index 000000000..f234e41bf --- /dev/null +++ b/crates/zephium-map/src/site/title.rs @@ -0,0 +1,78 @@ +use super::*; +use crate::doc::Head; + +pub const MAX_SITE_NAME_BYTES: usize = 128; + +pub fn title_segments(title: &str) -> impl Iterator<Item = &str> { + title + .split(['|', '–', '—', '·', '•', ':', '\\']) + .flat_map(|s| s.split(" - ")) + .map(str::trim) +} + +pub(super) fn site_title(head: &Head, site: &SiteKey, page: &Url) -> String { + fn name(value: &str) -> Option<String> { + let value = crate::flatten(&crate::clean_text(value)); + (!value.is_empty() && value.len() <= MAX_SITE_NAME_BYTES).then_some(value) + } + if let Some(value) = name(&head.site_name).or_else(|| name(&head.application_name)) { + return value; + } + let mut website = None; + let mut organization = None; + let mut visit = |obj: &serde_json::Value| { + if obj.get("url").is_some_and(|v| { + v.as_str() + .and_then(|s| page.join(s).ok()) + .and_then(|u| SiteKey::from_url(&u)) + .as_ref() + != Some(site) + }) { + return; + } + let slot = if linked::typed(obj, "WebSite") { + &mut website + } else if linked::typed(obj, "Organization") { + &mut organization + } else { + return; + }; + if slot.is_none() { + *slot = obj["name"].as_str().and_then(name); + } + }; + for raw in &head.linked_data { + let Ok(root) = serde_json::from_str::<serde_json::Value>(raw) else { + continue; + }; + for node in root + .as_array() + .map(Vec::as_slice) + .unwrap_or(std::slice::from_ref(&root)) + { + visit(node); + if let Some(graph) = node["@graph"].as_array() { + graph.iter().for_each(&mut visit); + } + } + } + let label = site.as_str().split('.').next().unwrap_or_default(); + website + .or(organization) + .or_else(|| { + let brand = normal(label).replace(' ', ""); + title_segments(&head.title) + .find(|s| normal(s).replace(' ', "") == brand) + .and_then(name) + }) + .unwrap_or_else(|| { + clip( + if head.title.trim().is_empty() { + site.as_str() + } else { + head.title.trim() + }, + TITLE_BYTES, + ) + }) +} diff --git a/crates/zephium-map/tests/card.rs b/crates/zephium-map/tests/card.rs new file mode 100644 index 000000000..12f85d289 --- /dev/null +++ b/crates/zephium-map/tests/card.rs @@ -0,0 +1,385 @@ +use proptest::prelude::*; +use url::Url; +use zephium_map::{ + site::{read_site, MAX_ACTIONS, MAX_PRIMARY_LABEL_CHARS}, + Doc, DocLimits, Place, Tier, +}; + +fn card(markup: &str) -> Place { + let url = Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html(&url, markup.as_bytes(), None, DocLimits::SITE_PAGE).unwrap(); + read_site(&doc, &Default::default()).unwrap() +} + +#[test] +fn the_action_tray_observes_markup_destination_and_section_evidence() { + for count in [MAX_ACTIONS, MAX_ACTIONS + 1] { + let links: String = (0..count) + .map(|i| format!("<a download href='/asset/{i}'>Abrir {i}</a>")) + .collect(); + let p = card(&format!( + "<nav><a href='/download'>Download</a>{links}</nav>" + )); + let actions: Vec<_> = p + .sections + .iter() + .filter(|e| e.tier == Tier::Action) + .collect(); + assert_eq!(actions.len(), MAX_ACTIONS); + assert_eq!( + actions.last().unwrap().label, + format!("Abrir {}", MAX_ACTIONS - 1) + ); + assert_eq!(p.sections[0].label, "Download"); + assert_eq!(p.sections[0].tier, Tier::Primary); + assert_eq!(p.notes.truncated, count > MAX_ACTIONS); + } + let p=card("<nav><a href='/auth/login'>Continuer</a><a href='/guides/get-started'>Get started</a><a href='/contact'>Contact</a></nav>"); + assert_eq!( + p.sections.iter().map(|e| e.tier).collect::<Vec<_>>(), + [Tier::Primary, Tier::Primary, Tier::Action] + ); +} + +#[test] +fn names_come_from_link_text_or_an_observed_path() { + let p=card("<nav><a href='/a'><p>Hilfe</p><p>Information für alle, die hier eine Antwort suchen.</p></a><a href='/research-notes'>Read all the stories that our researchers have published this year</a><a href='/12345'>Read everything that the team has shared with the community</a></nav>"); + assert_eq!( + p.sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Hilfe", "Research notes"] + ); + assert_eq!(p.sections.last().unwrap().tier, Tier::Secondary); + for n in [MAX_PRIMARY_LABEL_CHARS, MAX_PRIMARY_LABEL_CHARS + 1] { + let label = "界".repeat(n); + let p = card(&format!("<nav><a href='/12345'>{label}</a></nav>")); + assert_eq!( + p.sections[0].tier == Tier::Primary, + n == MAX_PRIMARY_LABEL_CHARS + ); + } +} + +#[test] +fn home_and_unnamed_menu_owners_yield_their_named_destinations() { + let p=card("<nav><ul><li><a href='/'>Accueil</a><ul><li><a href='/agenda'>Agenda</a></li></ul></li><li><a href='/extras'>More</a><ul><li><a href='/archives'>Archives</a></li></ul></li><li><a href='/home'>Home</a></li></ul></nav>"); + assert_eq!( + p.sections + .iter() + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Agenda", "Archives", "Home"] + ); +} + +#[test] +fn destination_label_and_localized_duplicates_keep_the_first_representative() { + let base = card("<nav><a href='/de/preise'>Preise</a></nav>"); + let merged=card("<nav><a href='/de/preise'>Preise</a><a href='/de/preise/'>Tarif</a><a href='/preise'>Kosten</a><a href='/business'>Preise</a></nav>"); + assert_eq!(merged.sections.len(), 1); + assert_eq!(merged.sections[0].id, base.sections[0].id); + assert_eq!( + merged.sections[0].children[0].key.as_url().path(), + "/business" + ); +} + +#[test] +fn sibling_identity_includes_query_and_host() { + let p=card("<nav><ul><li><a href='/learn'>Learn</a><ul><li><a href='https://alpha.workshop.example/?mode=1'>Manual</a></li><li><a href='https://alpha.workshop.example/?mode=2'>Manual</a></li><li><a href='https://beta.workshop.example/'>Manual</a></li></ul></li></ul></nav>"); + let children = &p.sections[0].children; + assert_eq!(children.len(), 3); + assert_eq!( + children[0].key.as_url().domain(), + Some("alpha.workshop.example") + ); + assert_eq!( + children[2].key.as_url().domain(), + Some("beta.workshop.example") + ); +} + +proptest! { + #[test] + fn surviving_ids_ignore_label_noise_and_action_insertion(slugs in proptest::collection::btree_set("[a-z]{4,10}",1..10)) { + let mut plain=String::from("<nav>"); + let mut noisy=String::from("<nav><a href='/'>Home</a><a href='/login'>Enter</a>"); + for slug in &slugs { + plain.push_str(&format!("<a href='/pages/{slug}'>{slug}</a>")); + noisy.push_str(&format!("<a href='/pages/{slug}'><span>{slug}</span><span>A longer explanation</span></a><a href='/de/pages/{slug}'>{slug}</a>")); + } + let a=card(&(plain+"</nav>")); + let b=card(&(noisy+"</nav>")); + let ids=|p:Place|p.sections.into_iter().filter(|e|e.tier==Tier::Primary).map(|e|(e.label,e.id)).collect::<Vec<_>>(); + let original = ids(a); + prop_assert_eq!(&original,&ids(b)); + let children = original.iter().map(|(slug, _)| format!("<a href='/pages/{slug}'>{slug}</a>")).collect::<String>(); + let grouped = card(&format!("<nav><div><button>Topics</button>{children}</div></nav>")); + let placed: std::collections::BTreeSet<_> = grouped.sections.iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .filter(|e| !e.menu_only && e.tier == Tier::Primary) + .map(|e| e.id.clone()).collect(); + prop_assert_eq!(original.into_iter().map(|(_, id)| id).collect::<std::collections::BTreeSet<_>>(), placed); + } +} + +#[test] +fn the_generated_topics_destination_can_be_the_menu_index() { + let p = card( + "<nav><div><button>Topics</button><a href='/pages/aaaa'>aaaa</a> + <a href='/pages/topics'>topics</a></div></nav>", + ); + assert_eq!(p.sections.len(), 1); + assert_eq!(p.sections[0].key.as_url().path(), "/pages/topics"); + assert_eq!(p.sections[0].children.len(), 1); + assert_eq!(p.sections[0].children[0].key.as_url().path(), "/pages/aaaa"); +} + +#[test] +fn language_editions_need_a_matching_language_declaration() { + let p=card("<nav><a lang='ja' href='https://ja.workshop.example/'>日本語</a><a hreflang='de' href='https://de.workshop.example/'>Deutsch</a><a href='https://ai.workshop.example/'>Studio</a><a href='/go/'>Go</a></nav>"); + assert_eq!( + p.sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Studio", "Go"] + ); + let edition = p.sections.last().unwrap(); + assert_eq!(edition.label, "日本語"); + assert_eq!(edition.children[0].label, "Deutsch"); +} + +#[test] +fn sparse_navigation_uses_a_named_footer_section_without_promoting_ancillary_links() { + for (nav, footer_tier) in [ + ("", Tier::Primary), + ("<a href='/c'>Third</a>", Tier::Secondary), + ] { + let p=card(&format!("<nav><a href='/a'>First</a><a href='/b'>Second</a>{nav}</nav><footer><a href='/pricing'>Pricing</a><a href='/privacy'>Privacy</a></footer>")); + assert_eq!( + p.sections + .iter() + .find(|e| e.label == "Pricing") + .unwrap() + .tier, + footer_tier + ); + assert_eq!( + p.sections + .iter() + .find(|e| e.label == "Privacy") + .unwrap() + .tier, + Tier::Secondary + ); + } +} + +#[test] +fn repeated_locale_roots_are_not_sections_and_query_specific_routes_remain_distinct() { + let p=card("<nav><a hreflang='fr' href='/fr/'>Français</a><a hreflang='de' href='/de'>Deutsch</a><a href='/products?t=one'>First</a><a href='/products?t=two'>Second</a></nav>"); + assert_eq!( + p.sections + .iter() + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["First", "Second"] + ); +} + +#[test] +fn the_word_boundary_refuses_a_teaser_and_keeps_a_short_title() { + let p = card("<nav><a href='/one'>A B C D E F</a><a href='/two'>A B C D E F G</a></nav>"); + assert_eq!(p.sections[0].label, "A B C D E F"); + assert_eq!(p.sections[1].label, "Two"); +} + +#[test] +fn an_observed_directory_represents_three_or_more_deep_sibling_articles() { + for (count, tier) in [(2, Tier::Secondary), (3, Tier::Primary)] { + let links: String = (0..count) + .map(|i| format!("<a href='/docs/manuals/tools/{i}'>Tool {i}</a>")) + .collect(); + let p = card(&format!( + "<nav>{links}</nav><footer><a href='/docs/manuals/tools'>42 tools</a></footer>" + )); + let directory = p + .sections + .iter() + .find(|e| e.key.as_url().path().ends_with("tools")) + .unwrap(); + assert_eq!(directory.tier, tier); + if count == 3 { + assert_eq!(directory.label, "Tools"); + } + } +} + +#[test] +fn a_shared_clipped_display_path_preserves_distinct_destinations() { + let common = "x".repeat(zephium_map::site::MAX_PATH_CHARS); + let p=card(&format!("<nav><ul><li><a href='/guide'>Guide</a><ul><li><a href='/{common}1'>Index</a></li><li><a href='/{common}2'>Index</a></li><li><a href='/{common}3'>Index C#</a></li><li><a href='/{common}4'>Index C++</a></li></ul></li></ul></nav>")); + assert_eq!( + p.sections[0] + .children + .iter() + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Index", "Index", "Index C#", "Index C++"] + ); +} + +#[test] +fn direct_release_links_stay_primary_with_a_named_version_index_and_no_breadcrumbs() { + let p = card("<nav><a href='/versions'>v3.4</a><a href='/changelog'>Changelog</a><a href='/changelog/cedar'>Cedar</a><a href='/changelog/feeds'>Feeds</a><a href='/topics#breadcrumbs'>Trail</a><a href='/topics#formats'>Formats</a></nav><footer><a href='/changelog/feeds'>Feeds</a></footer>"); + let primary: Vec<_> = p + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .map(|e| e.label.as_str()) + .collect(); + assert_eq!( + primary, + ["Versions", "Changelog", "Cedar", "Feeds", "Formats"] + ); + assert!(p + .sections + .iter() + .any(|e| e.label == "Trail" && e.tier == Tier::Secondary)); +} + +#[test] +fn platform_download_calls_and_markdown_sales_contacts_are_actions() { + let p = card("<nav><a href='/downloads/solaris'>Download for Solaris</a><a href='/downloads/bsd'>BSD</a><a href='/contact/sales.md'>Talk to us</a></nav>"); + let actions: Vec<_> = p + .sections + .iter() + .filter(|e| e.tier == Tier::Action) + .map(|e| e.label.as_str()) + .collect(); + assert_eq!(actions, ["Download for Solaris", "Talk to us"]); + assert_eq!(p.sections[0].label, "BSD"); +} + +#[test] +fn a_group_uses_its_observed_index_and_flattens_nested_menus() { + let p=card("<nav><div><button>Tools</button><a href='/catalog'>See all tools</a><a href='/one'>First</a><div><button>Editors</button><a href='/two'>Second</a><a href='/three'>Third</a></div></div></nav>"); + assert_eq!(p.sections.len(), 1); + let tools = &p.sections[0]; + assert_eq!(tools.label, "Tools"); + assert_eq!(tools.key.as_url().path(), "/catalog"); + assert!(!tools.menu_only); + assert!(p.entry_openable(&tools.id, &Default::default())); + assert_eq!( + tools + .children + .iter() + .map(|c| c.label.as_str()) + .collect::<Vec<_>>(), + ["First", "Second", "Third"] + ); + assert!(tools.children.iter().all(|e| e.children.is_empty())); +} + +#[test] +fn a_collapsed_panel_needs_its_controls_reference_and_visible_members() { + for (id, expected) in [("panel", 1), ("other", 0)] { + let p=card(&format!("<nav><button aria-controls='panel'>Tools</button><div aria-hidden='true' id='{id}'><a href='/x'>First</a><a href='/y'>Second</a><div hidden><a href='/hidden'>Hidden</a></div></div></nav>")); + assert_eq!(p.sections.len(), expected); + if let Some(group) = p.sections.first() { + assert!(group.menu_only); + assert_eq!(group.children.len(), 2); + } + } +} + +#[test] +fn only_path_names_change_case_and_thin_counts_primary_rows() { + for (extra, thin) in [("", true), ("<a href='/third'>tHIRD</a>", false)] { + let p=card(&format!("<nav><a href='/ёж'>Here are the latest versions of this resource</a><a href='/foo'>lower case</a>{extra}<a href='/login'>Log in</a></nav>")); + assert_eq!(p.notes.thin, thin); + assert_eq!( + (&*p.sections[0].label, p.sections[0].path_name), + ("Ёж", true) + ); + assert_eq!( + (&*p.sections[1].label, p.sections[1].path_name), + ("lower case", false) + ); + if !thin { + assert_eq!(p.sections[2].label, "tHIRD"); + } + } +} + +#[test] +fn supplemental_roles_keep_the_navigation_id_and_fill_sparse_cards_roles_first() { + use zephium_map::site::SiteInputs; + let url = Url::parse("https://workshop.example/").unwrap(); + for (extra, sparse) in [("", true), ("<a href='/three'>Three</a>", false)] { + let html = format!("<nav><a href='/manual'>Docs</a><a href='/two'>Two</a>{extra}</nav>"); + let d = Doc::from_html(&url, html.as_bytes(), None, DocLimits::SITE_PAGE).unwrap(); + let base = read_site(&d, &Default::default()).unwrap(); + let p=read_site(&d,&SiteInputs {llms:Some("## Documentation\n- [One](/help/one)\n- [Two guides](/help/two)\n## Assorted\n- [Start](/pricing)\n## Careers\n- [Open roles](/work)"),..Default::default()}).unwrap(); + let docs = &p.sections[0]; + assert_eq!(docs.id, base.sections[0].id); + assert_eq!(docs.label, "Docs"); + assert_eq!(docs.children.len(), 2); + assert!(!p.sections.iter().any(|e| e.label == "Documentation")); + let row = |name: &str| p.sections.iter().position(|e| e.label == name).unwrap(); + assert!(row("Careers") < row("Assorted")); + assert_eq!(p.sections[row("Careers")].tier, Tier::Primary); + assert_eq!(p.sections[row("Assorted")].tier == Tier::Primary, sparse); + } +} + +#[test] +fn an_index_heading_does_not_take_its_first_footer_links_role() { + let url = Url::parse("https://workshop.example/").unwrap(); + let doc=Doc::from_html(&url,b"<nav><div><button>Resources</button><a href='/one'>One</a><a href='/two'>Two</a></div><a href='/three'>Three</a><a href='/four'>Four</a></nav><footer><a href='/help'>Support</a></footer>",None,DocLimits::SITE_PAGE).unwrap(); + let p = read_site( + &doc, + &zephium_map::site::SiteInputs { + llms: Some("## Resources\n- [Help center](/help)\n- [Reports](/reports)"), + ..Default::default() + }, + ) + .unwrap(); + assert!(p.sections.iter().all(|e| e.label != "Support")); + let row = p.sections.iter().find(|e| e.label == "Resources").unwrap(); + assert!(row.menu_only); + assert!(row + .children + .iter() + .any(|e| e.key.as_url().path() == "/help")); + assert!(row.children.iter().any(|e| e.label == "Reports")); +} + +#[test] +fn a_collapsed_menu_obeys_the_documents_text_budget() { + let url = Url::parse("https://workshop.example/").unwrap(); + let html="<nav><button aria-controls='menu'>Tools</button><div id='menu' aria-hidden='true'><a href='/first'>First</a><a href='/second'>Second</a></div></nav>"; + let room = ["/first", "/second"] + .iter() + .map(|path| url.join(path).unwrap().as_str().len()) + .sum::<usize>() + + "ToolsFirstSecond".len(); + for (limit, truncated) in [(room, false), (room - 1, true)] { + let d = Doc::from_html( + &url, + html.as_bytes(), + None, + DocLimits { + text_bytes: limit as u32, + ..DocLimits::SITE_PAGE + }, + ) + .unwrap(); + assert_eq!(d.body_truncated(), truncated); + } +} diff --git a/crates/zephium-map/tests/card_ownership.rs b/crates/zephium-map/tests/card_ownership.rs new file mode 100644 index 000000000..14bfb686c --- /dev/null +++ b/crates/zephium-map/tests/card_ownership.rs @@ -0,0 +1,433 @@ +use url::Url; +use zephium_map::{ + site::{read_site_with_stats, PlaceStats, MAX_SITE_NAME_BYTES}, + Doc, DocLimits, Entry, Place, Tier, +}; + +fn read(html: &str) -> (Place, PlaceStats) { + let base = Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html(&base, html.as_bytes(), None, DocLimits::SITE_PAGE).unwrap(); + read_site_with_stats(&doc, &Default::default()).unwrap() +} + +fn row<'a>(p: &'a Place, label: &str) -> &'a Entry { + p.sections + .iter() + .find(|e| e.label == label && e.tier == Tier::Primary) + .unwrap() +} + +fn labels(e: &Entry) -> Vec<&str> { + e.children.iter().map(|c| c.label.as_str()).collect() +} + +#[test] +fn short_topical_paths_are_independent_destinations() { + let (p, _) = + read("<nav><a href='/go/install'>Install Go</a><a href='/js/install'>Install JS</a></nav>"); + assert_eq!(row(&p, "Install Go").key.as_url().path(), "/go/install"); + assert_eq!(row(&p, "Install JS").key.as_url().path(), "/js/install"); + let (p, _) = read("<nav><div><button>Install</button><a lang='en' href='/go/install'>Go</a><a lang='en' href='/js/install'>JS</a></div></nav>"); + assert_eq!(labels(row(&p, "Install")), ["Go", "JS"]); +} + +#[test] +fn topical_root_links_do_not_make_an_edition_picker() { + let (p, _) = read( + "<nav><div><button>Topics</button><a href='/ai'>AI</a><a href='/ml'>ML</a></div></nav>", + ); + assert_eq!(labels(row(&p, "Topics")), ["AI", "ML"]); +} + +#[test] +fn a_counterpart_under_the_entry_locale_confirms_only_its_own_remainder() { + let url = Url::parse("https://workshop.example/en/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><div><button>Guides</button> + <a href='/en/install'>Setup</a><a href='/de/install'>Installation</a> + <a href='/go/guide'>Go</a><a href='/js/guide'>JS</a></div></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let (p, _) = read_site_with_stats(&doc, &Default::default()).unwrap(); + assert_eq!(labels(row(&p, "Guides")), ["Setup", "Go", "JS"]); +} + +#[test] +fn a_menu_and_a_direct_page_can_share_a_label() { + let (place, stats) = read( + "<nav><a href='/catalog'>Products</a><div><button>Products</button> + <a href='/one'>First</a><a href='/two'>Second</a></div></nav>", + ); + let rows: Vec<_> = place + .sections + .iter() + .filter(|e| e.label == "Products") + .collect(); + assert_eq!(rows.len(), 2); + assert!(rows + .iter() + .any(|e| e.menu_only && labels(e) == ["First", "Second"])); + assert!(rows + .iter() + .any(|e| !e.menu_only && e.key.as_url().path() == "/catalog")); + assert_eq!( + (stats.missing_header_links, stats.invalid_group_pages), + (0, 0) + ); +} + +#[test] +fn disclosure_actions_leave_the_named_single_item_menu_intact() { + let (place, _) = read("<nav><button aria-controls='items'>Resources</button> + <div aria-hidden='true' id='items'><a href='/signin'>Sign in</a><a href='/guides'>Guides</a></div></nav>"); + assert_eq!(labels(row(&place, "Resources")), ["Guides"]); + assert!(place + .sections + .iter() + .any(|e| e.label == "Sign in" && e.tier == Tier::Action)); +} + +#[test] +fn marked_disclosure_panels_supply_no_destinations() { + for mark in ["data-type='ad'", "aria-label='AI-generated overview'"] { + let (place, _) = read(&format!("<nav><button aria-controls='items'>Resources</button> + <div {mark} aria-hidden='true' id='items'><a href='/a'>First</a><a href='/b'>Second</a></div></nav>")); + assert!(place.sections.is_empty(), "{mark}"); + } +} + +#[test] +fn menu_members_with_the_same_label_keep_their_fragment_targets() { + let (p, _) = read( + "<nav><div><button>Resources</button><a href='/docs#api'>Overview</a> + <a href='/docs#cli'>Overview</a><a href='/docs#api'>Overview</a></div></nav>", + ); + assert_eq!(labels(row(&p, "Resources")), ["Overview", "Overview"]); +} + +#[test] +fn a_mixed_menu_keeps_its_unrelated_language_tagged_guide() { + for guide in ["/guide", "/fr#guide"] { + let (p, _) = read(&format!( + "<link rel='alternate' hreflang='fr' href='/fr'><nav><div><button>Resources</button> + <a href='/fr'>French</a><a href='{guide}' hreflang='de'>Guide</a></div></nav>" + )); + assert!(labels(row(&p, "Resources")).contains(&"Guide")); + } +} + +#[test] +fn the_document_language_does_not_declare_a_link_target_language() { + let (p, _) = read( + "<html lang='en'><nav><a href='https://en.workshop.example/docs'>Docs</a></nav></html>", + ); + assert_eq!(row(&p, "Docs").tier, Tier::Primary); +} + +#[test] +fn cleaned_link_prefix_keeps_its_byte_boundary() { + let (p, _) = read( + "<nav><a href='/guide'><span>Docs\u{200b}</span><span> API reference</span></a></nav>", + ); + assert_eq!(p.sections[0].label, "Docs"); +} + +#[test] +fn site_title_uses_only_owned_top_level_entities() { + for (json, expected) in [ + ( + r#"{"@type":"JobPosting","hiringOrganization":{"@type":"Organization","name":"Recruiter"}}"#, + "Workshop", + ), + ( + r#"{"@type":"WebSite","url":"https://other.example","name":"Other"}"#, + "Workshop", + ), + ( + r#"{"@graph":[{"@type":"WebSite","url":"https://www.workshop.example","name":"Workshop tools"}]}"#, + "Workshop tools", + ), + ] { + assert_eq!( + read(&format!( + "<title>Home | Workshop</title><script type='application/ld+json'>{json}</script>" + )) + .0 + .title, + expected + ); + } +} + +#[test] +fn a_control_that_repeats_an_item_cannot_supply_the_group_page() { + for (href, index, expected) in [ + ("/one", "", None), + ("/topics", "", Some("/topics")), + ( + "/one", + "<li><a href='/index'>View all topics</a></li>", + Some("/index"), + ), + ] { + let (p, stats) = read(&format!( + "<nav><ul><li><a href='{href}'>Topics</a><ul> + <li><a href='/one'>One</a></li><li><a href='/two'>Two</a></li>{index} + </ul></li></ul></nav>" + )); + let group = row(&p, "Topics"); + assert_eq!(labels(group), ["One", "Two"]); + assert_eq!( + (!group.menu_only).then(|| group.key.as_url().path()), + expected + ); + assert_eq!( + p.entry_openable(&group.id, &Default::default()), + expected.is_some() + ); + assert_eq!(stats.invalid_group_pages, 0); + } +} + +#[test] +fn an_observed_redirect_to_a_member_cannot_become_the_menu_page() { + let base = Url::parse("https://workshop.example/").unwrap(); + let parse = |url: &Url, html: &str| { + Doc::from_html(url, html.as_bytes(), None, DocLimits::SITE_PAGE).unwrap() + }; + let home = parse( + &base, + "<nav><ul><li><a href='/topics'>Topics</a><ul> + <li><a href='/one'>One</a></li><li><a href='/two'>Two</a></li></ul></li></ul></nav>", + ); + let landing = parse(&base.join("/one").unwrap(), "<p>First topic</p>"); + let key = zephium_map::PageKey::from_url(&base.join("/topics").unwrap()).unwrap(); + let inputs = zephium_map::site::SiteInputs { + pages: [(key, &landing)].into(), + ..Default::default() + }; + let (place, _) = read_site_with_stats(&home, &inputs).unwrap(); + assert!(row(&place, "Topics").menu_only); + assert_eq!(labels(row(&place, "Topics")), ["One", "Two"]); +} + +#[test] +fn footer_lending_respects_both_header_membership_and_standalone_destinations() { + for (members, expected) in [ + ("", vec!["Studio", "Labs"]), + ( + "<a href='/studio'>Our studio</a><a href='/events'>Events</a>", + vec!["Our studio", "Events"], + ), + ] { + let (p, stats) = read(&format!("<header><nav><div><button>Product</button>{members}</div> + <a href='/pricing'>Pricing</a><a href='/enterprise'>Enterprise</a></nav></header> + <footer><div><h3>Product</h3><a href='/studio'>Studio</a><a href='/labs'>Labs</a> + <a href='/de/pricing'>Plans</a><a href='/enterprise'>For business</a> + <a href='/rules'>Privacy and terms</a><a href='/restrictions'>Prohibited and restricted businesses</a> + </div></footer>")); + assert_eq!(labels(row(&p, "Product")), expected); + for direct in ["Enterprise", "Pricing"] { + let target = row(&p, direct).card_page(); + assert!(p + .sections + .iter() + .flat_map(|e| &e.children) + .all(|c| c.card_page() != target)); + } + assert_eq!(stats.missing_header_links, 0); + } +} + +#[test] +fn repeated_mobile_control_cannot_lend_footer_items_to_a_populated_desktop_menu() { + let (p, _) = read( + "<nav><ul><li><a href='/tools'>Tools</a><ul><li><a href='/a'>First</a></li> + <li><a href='/b'>Second</a></li></ul></li></ul><div><button>Tools</button></div></nav> + <footer><div><h3>Tools</h3><a href='/c'>Third</a></div></footer>", + ); + assert_eq!(labels(row(&p, "Tools")), ["First", "Second"]); +} + +#[test] +fn localized_children_keep_the_observed_name_and_existing_identity_in_both_orders() { + for (first, other) in [("/review", "/de/review"), ("/de/review", "/review")] { + let nav = |extra: &str| { + format!( + "<nav><div><button>Tools</button><a href='{first}'>Review</a> + <a href='/cli'>CLI</a>{extra}</div></nav>" + ) + }; + let (baseline, _) = read(&nav("")); + let aliases = format!("<a href='{other}'>Code Review</a>"); + let (p, _) = read(&format!( + "{}<footer><div><h3>Tools</h3>{aliases}</div></footer>", + nav(&aliases) + )); + let tools = row(&p, "Tools"); + assert_eq!(labels(tools), ["Review", "CLI"]); + assert_eq!(tools.children[0].id, row(&baseline, "Tools").children[0].id); + assert_eq!(tools.children[0].key.as_url().path(), first); + } +} + +#[test] +fn skip_links_never_create_or_own_a_row() { + for following in ["", "<a href='/a'>First</a><a href='/b'>Second</a>"] { + let (p, _) = read(&format!( + "<header><div><a href='#main'>Skip to content</a>{following}</div></header>" + )); + assert!(p.sections.iter().all(|e| e.label != "Skip to content")); + if following.is_empty() { + assert!(p.sections.is_empty()); + } else { + for name in ["First", "Second"] { + assert!(row(&p, name).children.is_empty()); + } + } + } +} + +#[test] +fn a_disclosed_header_link_reuses_a_previously_discovered_footer_identity() { + for (header, footer) in [("/de/review", "/review"), ("/review", "/de/review")] { + let column = + format!("<footer><div><h3>Work</h3><a href='{footer}'>Code review</a></div></footer>"); + let (before, _) = read(&column); + let id = before + .sections + .iter() + .find(|e| e.label == "Code review") + .unwrap() + .id + .clone(); + let (after, _) = read(&format!( + "<nav><button aria-controls='panel'>Tools</button> + <div id='panel' aria-hidden='true'><a href='{header}'>Review</a><a href='/cli'>CLI</a> + <a href='/catalog'>See all tools</a></div></nav>{column}" + )); + let tools = row(&after, "Tools"); + assert_eq!(tools.key.as_url().path(), "/catalog"); + assert_eq!(labels(tools), ["Review", "CLI"]); + assert_eq!(tools.children[0].id, id); + assert_eq!(tools.children[0].key.as_url().path(), header); + } +} + +#[test] +fn separate_navigation_representations_agree_on_members_and_independent_links() { + let (p, _) = read("<header><nav><ul><li><span>Explore</span><ul><li><a href='/a'>One</a></li> + <li><a href='/b'>Two</a></li></ul></li><li><a href='/pricing'>Pricing</a></li></ul></nav> + <nav><ul><li>Explore</li><li><a href='/de/a'>First</a></li><li><a href='/b'>Second</a></li></ul> + <a href='/pricing'>Pricing</a></nav></header>"); + assert_eq!(labels(row(&p, "Explore")), ["One", "Two"]); + assert!(row(&p, "Pricing").children.is_empty()); +} + +#[test] +fn language_controls_need_evidence_from_their_destinations() { + let alternates = "<link rel='alternate' hreflang='de' href='/eins'><link rel='alternate' hreflang='fr' href='/deux'>"; + for (head, links, picker) in [ + ("", "<a hreflang='de' href='/eins'>First</a><a hreflang='fr' href='/deux'>Second</a>", false), + ("", "<a lang='de' href='/de'>First</a><a lang='fr' href='/fr'>Second</a>", true), + (alternates, "<a href='/eins'>First</a><a href='/deux'>Second</a>", true), + ("", "<a hreflang='pt-BR' href='/pt-BR/'>First</a><a hreflang='fr' href='/fr/'>Second</a>", true), + ("", "<a lang='zh-Hant-TW' href='/zh-Hant-TW/'>First</a><a lang='es-419' href='/es-419/'>Second</a>", true), + ("", "<a href='https://de.workshop.example/'>First</a><a href='https://fr.workshop.example/'>Second</a>", true), + ("", "<a lang='en' href='/docs/rust'>Rust</a><a lang='en' href='/docs/go'>Go</a>", false), + ] { + let (p, _) = read(&format!("<head>{head}</head><header><nav><div><button>Languages</button>{links}</div> + <a href='/about'>About</a></nav></header>")); + if picker { + assert_eq!(p.sections.len(), 1); + assert!(row(&p, "About").children.is_empty()); + } else { + assert_eq!(labels(row(&p, "Languages")).len(), 2); + } + } +} + +#[test] +fn a_standalone_page_and_a_differently_named_control_keep_separate_rows() { + let (p, _) = read("<nav><a href='/library'>Library</a><ul><li><a href='/library'>Resources</a> + <ul><li><a href='/news'>News</a></li><li><a href='/talks'>Talks</a></li></ul></li></ul></nav>"); + assert!(!row(&p, "Library").menu_only); + let resources = row(&p, "Resources"); + assert!(resources.menu_only); + assert_eq!(labels(resources), ["News", "Talks"]); +} + +#[test] +fn a_home_link_and_peer_utility_buttons_do_not_own_neighbouring_destinations() { + let (p, _) = read( + "<header><div><a href='/'>Workshop Home</a><div> + <a href='/pricing'>Pricing</a></div></div> + <div><button>Languages and currency</button><a href='/help'>Help</a> + <button>Choose a profile</button><a href='/events'>Events</a></div></header>", + ); + assert!(p.sections.iter().all(|e| !e.menu_only)); + for label in ["Pricing", "Help", "Events"] { + assert!(row(&p, label).children.is_empty()); + } +} + +#[test] +fn oversized_link_language_cannot_hide_an_ordinary_menu() { + let too_long = "a".repeat(zephium_map::doc::MAX_LANGUAGE_BYTES + 1); + let (p, _) = read(&format!( + "<nav><div><button>Topics</button><a lang='{too_long}' href='/a'>One</a> + <a lang='fr' href='/b'>Two</a></div></nav>" + )); + assert_eq!(labels(row(&p, "Topics")), ["One", "Two"]); +} + +#[test] +fn site_names_use_bounded_metadata_then_the_registrable_brand_then_the_title() { + let og = "<meta property='og:site_name' content='OG name'>"; + let application = "<meta name='application-name' content='App name'>"; + let website = + r#"<script type='application/ld+json'>{"@type":"WebSite","name":"Site name"}</script>"#; + let organization = + r#"<script type='application/ld+json'>{"@type":"Organization","name":"Org name"}</script>"#; + let title = "<title>Build something new | Work Shop</title>"; + let inputs = [og, application, website, organization, title]; + for (i, expected) in ["OG name", "App name", "Site name", "Org name", "Work Shop"] + .iter() + .enumerate() + { + assert_eq!( + read(&inputs[i..].iter().rev().copied().collect::<String>()) + .0 + .title, + *expected + ); + } + assert_eq!( + read("<title>Build something new | Catalog</title>").0.title, + "Build something new | Catalog" + ); + assert_eq!(read("").0.title, "workshop.example"); + for separator in [" • ", " \\ "] { + assert_eq!( + read(&format!( + "<title>Welcome to our site{separator}Workshop</title>" + )) + .0 + .title, + "Workshop" + ); + } + for (n, accepted) in [ + (MAX_SITE_NAME_BYTES, true), + (MAX_SITE_NAME_BYTES + 1, false), + ] { + let value = "a".repeat(n); + let (p, _) = read(&format!( + "<meta property='og:site_name' content='{value}'>{application}" + )); + assert_eq!(p.title, if accepted { &value } else { "App name" }); + } +} diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index 419991937..0642ee40c 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -79,11 +79,13 @@ fn name(e: &Effect) -> String { } struct Run { trace: Vec<String>, + identified_sections: BTreeSet<String>, stats: Stats, places: Vec<Place>, conf: Vec<Confidence>, memo: Option<Vec<u8>>, passages: Vec<Vec<String>>, + held: Option<HeldSite>, } fn run( c: Config, @@ -95,17 +97,24 @@ fn run( let mut queue: VecDeque<_> = effects.into(); let mut run = Run { trace: Vec::new(), + identified_sections: BTreeSet::new(), stats: Stats::default(), places: Vec::new(), conf: Vec::new(), memo: None, passages: Vec::new(), + held: None, }; let mut ids = BTreeSet::new(); while let Some(effect) = queue.pop_front() { let id = effect.id(); assert!(ids.insert(id)); run.trace.push(name(&effect)); + if let Effect::Fetch { id, url, .. } = &effect { + if session.section_fetch(*id).is_some() { + run.identified_sections.insert(url.path().to_owned()); + } + } let input = reply(&effect).or_else(|| { Some(match &effect { Effect::LoadResults { .. } => Input::Results { @@ -173,6 +182,10 @@ fn run( } } assert_eq!(run.trace.last().unwrap(), "done"); + run.held = run + .places + .last() + .and_then(|place| session.hold_place(0, place.clone())); run } #[test] @@ -191,6 +204,709 @@ fn engine_only_and_no_site_evidence() { ); assert!(low.conf.iter().all(|c| *c == Confidence::Low) && !low.conf.is_empty()); } + +fn asked() -> Config { + Config { + sections: Sections::Asked, + ..cfg() + } +} + +fn section<'a>(place: &'a Place, label: &str) -> &'a Entry { + place + .sections + .iter() + .find(|entry| entry.label == label) + .unwrap() +} + +fn open(held: HeldSite, label: &str, cfg: Config) -> (Session, Vec<Effect>) { + let id = section(held.place(), label).id.clone(); + Session::open(cfg, held, 0, id.as_str(), Confidence::High, false) + .ok() + .unwrap() +} + +fn open_complete(mut session: Session, effects: Vec<Effect>) -> (HeldSite, bool, Stats) { + let mut events = effects.into_iter(); + let Some(Effect::Emit { + event: + MapEvent::Place { + place, + slot: 0, + complete: true, + .. + }, + .. + }) = events.next() + else { + panic!("open must emit one complete place"); + }; + let next = events.next().unwrap(); + let (remembered, end) = if matches!(next, Effect::RememberSite { .. }) { + (true, events.next().unwrap()) + } else { + (false, next) + }; + let Effect::Emit { + event: MapEvent::End { + outcome: EndOutcome::Done, + stats, + }, + .. + } = end + else { + panic!("open must end done"); + }; + assert!(events.next().is_none()); + assert!(session.handle(Input::Cancel).is_empty()); + (session.hold_place(0, place).unwrap(), remembered, stats) +} + +fn open_fetch(effects: &[Effect], path: &str) -> (Id, Url) { + let [Effect::Fetch { id, url, .. }] = effects else { + panic!("expected one read") + }; + assert_eq!(url.path(), path); + (*id, url.clone()) +} + +#[test] +fn asked_reads_only_focus_and_the_results_section_link() { + let unfocused = run(asked(), "acme", RESULT, |_| None); + assert!(!unfocused + .trace + .iter() + .any(|event| event.ends_with("/pricing") || event.ends_with("/news"))); + assert!(unfocused + .held + .unwrap() + .place() + .sections + .iter() + .all(|entry| entry.read.is_none())); + + let focused = run(asked(), "acme pricing", RESULT, |_| None); + let place = focused.held.as_ref().unwrap().place(); + assert_eq!(section(place, "Pricing").read, Some(ReadState::Read)); + assert_eq!(section(place, "News").read, None); + assert_eq!(focused.stats.phases[&Phase::Section].started, 1); + + let result = RESULT.replace( + "https://acme.com/'>Acme workshop", + "https://acme.com/guide'>Acme Docs", + ); + let both = run(asked(), "acme docs", &result, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<title>Acme</title><nav><a href='/docs'>Docs</a><a href='/pricing'>Pricing</a></nav>", + )), + Effect::Fetch { id, url, .. } if matches!(url.path(), "/docs" | "/guide") => Some( + response(*id, url, "text/html", "<h2 id='intro'>Introduction</h2>"), + ), + _ => None, + }); + let place = both.held.as_ref().unwrap().place(); + assert_eq!(place.focus.as_ref(), Some(&section(place, "Docs").id)); + assert_eq!(section(place, "Docs").read, Some(ReadState::Read)); + assert!(section(place, "Acme Docs") + .sources + .contains(&Source::EngineResult)); + assert_eq!(section(place, "Acme Docs").read, Some(ReadState::Read)); + assert_eq!(section(place, "Pricing").read, None); + assert_eq!(both.stats.phases[&Phase::Section].started, 2); +} + +#[test] +fn eager_capture_identifies_a_read_displaced_from_the_card() { + let run = run(cfg(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<nav><a href='/docs'>More</a><a href='/pricing'>Pricing</a></nav>", + )), + _ => None, + }); + assert!(run + .held + .unwrap() + .place() + .sections + .iter() + .all(|e| e.key.as_url().path() != "/docs")); + assert!(run.identified_sections.contains("/docs")); +} + +#[test] +fn open_from_a_fresh_memo_matches_the_eager_section_and_keeps_other_rows() { + let eager = run(cfg(), "acme", RESULT, |_| None); + let memo = run(asked(), "acme", RESULT, |_| None).memo.unwrap(); + let cached = run(asked(), "acme", RESULT, |effect| match effect { + Effect::LookupSite { id, .. } => Some(Input::Cache { + id: *id, + memo: Some(memo.clone()), + }), + _ => None, + }); + assert_eq!(cached.stats.fresh_memos, 1); + assert!(!cached.trace.iter().any(|event| event.starts_with("fetch"))); + let held = cached.held.unwrap(); + let entry_id = section(held.place(), "Pricing").id.clone(); + assert_eq!(held.check_open("unknown"), Err(OpenRefusal::UnknownEntry)); + assert!(matches!( + Session::open(asked(), held.clone(), 0, "unknown", Confidence::High, false), + Err(OpenRefusal::UnknownEntry) + )); + let news = serde_json::to_vec(section(held.place(), "News")).unwrap(); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, url) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response( + id, + &url, + "text/html", + include_str!("fixtures/section-pricing.html"), + )); + let (opened, remembered, stats) = open_complete(session, effects); + assert!(remembered); + assert_eq!( + stats.phases.keys().copied().collect::<Vec<_>>(), + [Phase::Section] + ); + let pricing = section(opened.place(), "Pricing"); + let eager = section(eager.held.as_ref().unwrap().place(), "Pricing"); + assert_eq!(pricing.id, entry_id); + assert!(pricing.children == eager.children); + assert_eq!(pricing.more, eager.more); + assert_eq!( + serde_json::to_vec(section(opened.place(), "News")).unwrap(), + news + ); + assert_eq!( + opened.check_open(entry_id.as_str()), + Err(OpenRefusal::NotOpenable) + ); + assert_eq!( + opened.check_open(pricing.children[0].id.as_str()), + Err(OpenRefusal::NotOpenable) + ); +} + +#[test] +fn opening_can_show_children_on_a_card_that_filled_its_discovery_budget() { + use zephium_map::site::{MAX_CHILDREN, MAX_PLACE_CHILDREN}; + let mut markup = String::from("<nav><a href='/pricing'>Pricing</a><ul>"); + for group in 0..MAX_PLACE_CHILDREN / MAX_CHILDREN { + markup.push_str(&format!( + "<li><a href='/group{group}'>Group {group}</a><ul>" + )); + for child in 0..MAX_CHILDREN { + markup.push_str(&format!( + "<li><a href='/group{group}/{child}'>Child {child}</a></li>" + )); + } + markup.push_str("</ul></li>"); + } + markup.push_str("</ul></nav>"); + let discovery = run(asked(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => { + Some(response(*id, url, "text/html", &markup)) + } + _ => None, + }); + let held = discovery.held.unwrap(); + let children = |place: &Place| { + place + .sections + .iter() + .map(|e| e.children.len()) + .sum::<usize>() + }; + assert_eq!(children(held.place()), MAX_PLACE_CHILDREN); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, url) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &url, "text/html", "<h2 id='plans'>Plans</h2>")); + let (opened, remembered, _) = open_complete(session, effects); + assert!(remembered); + assert_eq!(children(opened.place()), MAX_PLACE_CHILDREN + 1); + assert_eq!(section(opened.place(), "Pricing").children.len(), 1); +} + +#[test] +fn a_held_place_over_the_memo_ceiling_cannot_be_retained() { + let mut place = run(asked(), "acme", RESULT, |_| None).places.pop().unwrap(); + let (session, _) = Session::start(asked(), "acme").unwrap(); + assert!(session.hold_place(0, place.clone()).is_some()); + place.title = "X".repeat(MAX_MEMO_BYTES); + assert!(session.hold_place(0, place).is_none()); +} + +#[test] +fn open_fetches_robots_for_a_new_origin_and_never_retries_its_denial() { + let held = + run(asked(), "acme", RESULT, |effect| { + match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response(*id, url, "text/html", + "<nav><a href='https://docs.acme.com/guide'>Docs</a><a href='/about'>About</a></nav>")), + _ => None, + } + }) + .held + .unwrap(); + let entry_id = section(held.place(), "Docs").id.clone(); + let (mut session, effects) = open(held, "Docs", asked()); + let (id, url) = open_fetch(&effects, "/robots.txt"); + assert_eq!(url.host_str(), Some("docs.acme.com")); + let effects = session.handle(response( + id, + &url, + "text/plain", + "User-agent: *\nDisallow: /guide", + )); + let (refused, remembered, stats) = open_complete(session, effects); + assert!(!remembered); + assert_eq!(stats.phases[&Phase::Section].started, 0); + assert_eq!( + section(refused.place(), "Docs").read, + Some(ReadState::Refused { + failure: Failure::Robots + }) + ); + assert_eq!( + refused.check_open(entry_id.as_str()), + Err(OpenRefusal::NotOpenable) + ); + assert!(matches!( + Session::open( + asked(), + refused, + 0, + entry_id.as_str(), + Confidence::High, + false + ), + Err(OpenRefusal::NotOpenable) + )); +} + +#[test] +fn an_open_can_retry_a_transient_section_failure() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let entry_id = section(held.place(), "Pricing").id.clone(); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(Input::Fetch { + id, + result: Err(Failure::Timeout), + }); + let (held, remembered, _) = open_complete(session, effects); + assert!(!remembered); + assert_eq!(held.check_open(entry_id.as_str()), Ok(())); + let (_, effects) = open(held, "Pricing", asked()); + open_fetch(&effects, "/pricing"); +} + +#[test] +fn off_place_redirects_and_other_tenants_do_not_enrich_the_row() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let tenant = run(asked(), "github", + "<main><h2><a href='https://github.com/org/first'>GitHub First</a></h2></main>", + |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/org/first" => Some(response(*id, url, "text/html", + "<nav><a href='/org/first/pricing'>Pricing</a><a href='/org/second/news'>News</a></nav>")), + _ => None, + }).held.unwrap(); + assert_eq!( + tenant.check_open(section(tenant.place(), "News").id.as_str()), + Err(OpenRefusal::NotOpenable) + ); + for (held, path, landing) in [ + (held, "/pricing", "https://other.example/plans"), + ( + tenant, + "/org/first/pricing", + "https://github.com/org/second/plans", + ), + ] { + let before = section(held.place(), "Pricing").id.clone(); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, _) = open_fetch(&effects, path); + let landing = Url::parse(landing).unwrap(); + let effects = session.handle(response( + id, + &landing, + "text/html", + "<h2 id='bad'>Other place</h2>", + )); + let (opened, remembered, _) = open_complete(session, effects); + let entry = section(opened.place(), "Pricing"); + assert_eq!(entry.id, before); + assert_eq!(entry.key.as_url(), &landing); + assert!(entry.off_site && entry.children.is_empty()); + assert_eq!( + entry.read, + Some(ReadState::Refused { + failure: Failure::External + }) + ); + assert!(!remembered); + } +} + +#[test] +fn open_respects_read_ceilings_media_and_truncation() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + for (config, budget) in [ + ( + Config { + section_pages: 0, + ..asked() + }, + Budget::SectionPages, + ), + ( + Config { + fetches: 0, + ..asked() + }, + Budget::Fetches, + ), + ( + Config { + html_bytes: 0, + ..asked() + }, + Budget::HtmlBytes, + ), + ( + Config { + timeout: Duration::ZERO, + ..asked() + }, + Budget::Timeout, + ), + ] { + let (session, effects) = open(held.clone(), "Pricing", config); + let (place, _, stats) = open_complete(session, effects); + assert!(stats.budgets.contains(&budget)); + assert_eq!( + section(place.place(), "Pricing").read, + Some(ReadState::Skipped { budget }) + ); + open_fetch(&open(place, "Pricing", asked()).1, "/pricing"); + } + for (bytes, truncated, media, failure) in [ + (9, false, "text/html", Failure::Limit), + (8, true, "text/html", Failure::Limit), + (8, false, "text/plain", Failure::ContentType), + ] { + let (mut session, effects) = open( + held.clone(), + "Pricing", + Config { + html_bytes: 8, + ..asked() + }, + ); + let (id, url) = open_fetch(&effects, "/pricing"); + let effects = session.handle(Input::Fetch { + id, + result: Ok(FetchResult { + final_url: url, + content_type: media.into(), + charset: None, + bytes: vec![b'a'; bytes], + truncated, + }), + }); + let (place, remembered, _) = open_complete(session, effects); + assert_eq!( + section(place.place(), "Pricing").read, + Some(ReadState::Refused { failure }) + ); + assert_eq!(place.place().notes.truncated, failure == Failure::Limit); + assert!(!remembered); + } + let (mut session, effects) = open(held, "Pricing", asked()); + assert!( + matches!(effects.as_slice(), [Effect::Fetch { max_bytes, timeout, .. }] + if *max_bytes == MAX_HTML_BYTES as u32 && *timeout == FETCH_TIMEOUT) + ); + let effects = session.handle(Input::Elapsed { time: MAX_ELAPSED }); + let (place, _, stats) = open_complete(session, effects); + assert!(stats.budgets.contains(&Budget::Elapsed)); + assert_eq!( + section(place.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Timeout + }) + ); +} + +#[test] +fn open_refuses_an_out_of_range_slot() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let id = section(held.place(), "Pricing").id.clone(); + assert!(Session::open(cfg(), held, 2, id.as_str(), Confidence::High, false).is_err()); +} + +#[test] +fn a_fresh_asked_memo_is_provisional_for_an_eager_search() { + let prior = run(asked(), "acme", RESULT, |_| None).memo.unwrap(); + let replay = run(cfg(), "acme", RESULT, |effect| match effect { + Effect::LookupSite { id, .. } => Some(Input::Cache { + id: *id, + memo: Some(prior.clone()), + }), + _ => None, + }); + assert_eq!(replay.stats.fresh_memos, 1); + assert_eq!(replay.stats.phases[&Phase::Section].started, 2); +} + +#[test] +fn landing_policy_precedes_section_acceptance_and_is_shared_by_origin() { + let landing = Url::parse("https://docs.acme.com/private").unwrap(); + for (policy, allowed) in [ + (Ok("User-agent: *\nAllow: /"), true), + (Ok("User-agent: *\nDisallow: /private"), false), + (Err(Failure::Unavailable), false), + ] { + let result = run(cfg(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if matches!(url.path(), "/news" | "/pricing") => Some( + response(*id, &landing, "text/html", "<h2 id='member'>Member</h2>"), + ), + Effect::Fetch { id, url, .. } if url.origin() == landing.origin() => { + Some(match policy { + Ok(text) => response(*id, url, "text/plain", text), + Err(failure) => Input::Fetch { + id: *id, + result: Err(failure), + }, + }) + } + _ => None, + }); + assert_eq!( + result + .trace + .iter() + .filter(|e| *e == "fetch docs.acme.com/robots.txt") + .count(), + 1 + ); + let reads = &result.stats.phases[&Phase::Section]; + assert_eq!(reads.completed, 2); + assert_eq!( + reads.refused.get(&Failure::Robots).copied().unwrap_or(0), + if allowed { 0 } else { 2 } + ); + if allowed { + let place = result.held.as_ref().unwrap().place(); + assert!(place + .sections + .iter() + .any(|e| e.read == Some(ReadState::Read) + && e.children.iter().any(|c| c.label == "Member"))); + } else { + assert!(result.memo.is_none()); + assert!(result + .places + .iter() + .flat_map(|p| &p.sections) + .all(|e| e.children.is_empty())); + } + } +} + +#[test] +fn an_open_charges_its_landing_policy_to_both_budgets() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let landing = Url::parse("https://docs.acme.com/price").unwrap(); + let body = "<h2 id='tiers'>Tiers</h2>"; + for config in [ + Config { + fetches: 1, + ..asked() + }, + Config { + total_bytes: body.len() as u64, + ..asked() + }, + ] { + let (mut session, effects) = open(held.clone(), "Pricing", config); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &landing, "text/html", body)); + let (after, remembered, stats) = open_complete(session, effects); + assert_eq!( + section(after.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Robots + }) + ); + assert!(!remembered && !stats.budgets.is_empty()); + } + let rules = "User-agent: *\nAllow: /\n"; + for (room, truncated, accepted) in [(rules.len(), false, true), (rules.len(), true, false)] { + let (mut session, effects) = open( + held.clone(), + "Pricing", + Config { + total_bytes: (body.len() + room) as u64, + ..asked() + }, + ); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &landing, "text/html", body)); + let (id, url) = open_fetch(&effects, "/robots.txt"); + assert!( + matches!(&effects[0], Effect::Fetch { max_bytes, .. } if *max_bytes as usize == room) + ); + let mut input = response(id, &url, "text/plain", rules); + if let Input::Fetch { + result: Ok(result), .. + } = &mut input + { + result.truncated = truncated; + } + let effects = session.handle(input); + let (after, remembered, stats) = open_complete(session, effects); + assert_eq!(remembered, accepted); + assert_eq!( + section(after.place(), "Pricing").read == Some(ReadState::Read), + accepted + ); + assert_eq!(stats.budgets.contains(&Budget::TotalBytes), !accepted); + } + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &landing, "text/html", body)); + let (id, url) = open_fetch(&effects, "/robots.txt"); + assert_eq!(url.origin(), landing.origin()); + let rules = "User-agent: *\nDisallow: /price"; + let policy_landing = Url::parse("https://rules.acme.com/robots.txt").unwrap(); + let effects = session.handle(response(id, &policy_landing, "text/plain", rules)); + let (after, remembered, stats) = open_complete(session, effects); + assert_eq!(stats.phases[&Phase::Robots].bytes, rules.len() as u64); + assert_eq!( + section(after.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Robots + }) + ); + assert!(!remembered); +} + +#[test] +fn search_landing_policy_obeys_search_caps_and_coalesces_concurrent_redirects() { + let landing = Url::parse("https://docs.acme.com/private").unwrap(); + let body = "<h2 id='private'>Restricted</h2>"; + for (config, budget) in [ + ( + Config { + fetches: 3, + ..cfg() + }, + Some(Budget::Fetches), + ), + ( + Config { + total_bytes: (NAV.len() + body.len()) as u64, + ..cfg() + }, + Some(Budget::TotalBytes), + ), + ( + Config { + concurrent: 4, + host_concurrent: 2, + ..cfg() + }, + None, + ), + ] { + let run = + run(config, "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if matches!(url.path(), "/pricing" | "/news") => { + Some(response(*id, &landing, "text/html", body)) + } + Effect::Fetch { id, url, .. } if url.origin() == landing.origin() => Some( + response(*id, url, "text/plain", "User-agent: *\nDisallow: /"), + ), + _ => None, + }); + assert!(run.memo.is_none()); + let denials = run.stats.phases[&Phase::Section].refused[&Failure::Robots]; + if let Some(budget) = budget { + assert!(run.stats.budgets.contains(&budget)); + assert_eq!(run.stats.phases[&Phase::Robots].started, 1); + assert_eq!(denials, 1); + } else { + assert_eq!(run.stats.phases[&Phase::Robots].started, 2); + assert_eq!(denials, 2); + } + } +} + +#[test] +fn opening_a_fragment_enriches_the_same_memo_row() { + let initial = run(asked(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<nav><a href='/docs#setup'>Setup</a><a href='/docs#reference'>Reference</a></nav>", + )), + _ => None, + }); + let (mut session, effects) = open(initial.held.unwrap(), "Reference", asked()); + let (id, url) = open_fetch(&effects, "/docs"); + let effects = session.handle(response(id, &url, "text/html", "<h2 id='cli'>CLI</h2>")); + let memo = effects + .iter() + .find_map(|e| match e { + Effect::RememberSite { site, memo, .. } => Some(SiteMemo::decode(memo, site).unwrap()), + _ => None, + }) + .unwrap(); + assert!(section(&memo.payload.place, "Setup").children.is_empty()); + assert!(!section(&memo.payload.place, "Reference") + .children + .is_empty()); +} + +#[test] +fn asked_reads_the_result_child_under_a_menu_only_parent() { + let result = RESULT.replace( + "https://acme.com/'>Acme workshop", + "https://acme.com/guide'>Acme Docs", + ); + let run = run(asked(), "acme docs", &result, |effect| { + match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response(*id, url, "text/html", + "<nav><div><button>Resources</button><a href='/guide'>Docs</a><a href='/news'>News</a></div></nav>")), + Effect::Fetch { id, url, .. } if url.path() == "/guide" => Some(response(*id, url, "text/html", "<h2>Reference</h2>")), + _ => None, + } + }); + assert_eq!( + run.trace.iter().filter(|e| e.ends_with("/guide")).count(), + 1 + ); + let place = run.held.unwrap(); + let menu = section(place.place(), "Resources"); + assert!(menu.menu_only); + assert_eq!( + menu.children + .iter() + .find(|c| c.key.as_url().path() == "/guide") + .unwrap() + .read, + Some(ReadState::Read) + ); +} #[test] fn fresh_place_streams_complete_replacements() { let r = run(cfg(), "acme news", RESULT, |_| None); @@ -738,7 +1454,7 @@ fn late_time_limits_allow_only_completions_and_one_terminal_event() { }); assert_eq!( end.iter().map(name).collect::<Vec<_>>(), - ["layer", "place_failed", "done"] + ["layer", "place_failed", "place_failed", "done"] ); assert!( matches!(end.last(),Some(Effect::Emit{event:MapEvent::End{stats:s,..},..}) if s.budgets.contains(&Budget::LastStart)) @@ -1122,7 +1838,7 @@ fn sitemap_samples_obey_read_byte_and_section_bounds() { .unwrap() .sections .iter() - .any(|e| e.label == "sampled")); + .any(|e| e.label == "Sampled")); } } } @@ -1592,3 +2308,41 @@ fn sitemap_fetch_requires_a_valid_media_type_essence() { ); } } + +#[test] +fn asked_probes_one_affine_section_and_focuses_only_observed_content() { + for has_match in [true, false] { + let run = run(asked(), "acme changelog", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<nav><a href='/news'>News</a><a href='/releases'>Releases</a></nav>", + )), + Effect::Fetch { id, url, .. } if url.path() == "/releases" => Some(response( + *id, + url, + "text/html", + if has_match { + "<aside><a href='/changes'>Changelog</a></aside>" + } else { + "<aside><a href='/archive'>Archive</a></aside>" + }, + )), + _ => None, + }); + assert_eq!(run.stats.phases[&Phase::Section].started, 1); + assert!(run.stats.places[&0].probed_section); + assert!(!run.trace.iter().any(|s| s.ends_with("/news"))); + let p = run.places.last().unwrap(); + assert_eq!(p.focus.is_some(), has_match); + if has_match { + let found = section(p, "Releases") + .children + .iter() + .find(|e| e.label == "Changelog") + .unwrap(); + assert_eq!(p.focus.as_ref(), Some(&found.id)); + } + } +} diff --git a/crates/zephium-map/tests/site.rs b/crates/zephium-map/tests/site.rs index c86ab2517..23b97a8cf 100644 --- a/crates/zephium-map/tests/site.rs +++ b/crates/zephium-map/tests/site.rs @@ -47,7 +47,6 @@ fn ordered_site_with_all_evidence() { ("Careers", Some(Careers), Footer, false), ("Security", Some(Security), Footer, false), ("Examples", Some(Examples), LinkedData, false), - ("Home", Some(Home), LinkedData, false), ("Privacy", Some(Legal), Footer, false), ]; assert_eq!( @@ -202,7 +201,7 @@ fn sitemap_sampling_and_index_bounds() { .unwrap(); assert_eq!( labels(&p.sections), - ["downloads", "docs", "examples", "news", "products"] + ["Downloads", "Docs", "Examples", "News", "Products"] ); assert_eq!(stats.sitemap_urls, 50_000); let count = p.sections.len(); @@ -215,7 +214,10 @@ fn sitemap_sampling_and_index_bounds() { assert_eq!(e.more, 10_000 - 1 - expected as u32); assert_eq!(e.children.len(), expected); assert_eq!(e.sources[0], Source::Sitemap); - assert_eq!(e.key.as_url().path(), format!("/{}/0", e.label)); + assert_eq!( + e.key.as_url().path(), + format!("/{}/0", e.label.to_lowercase()) + ); assert_eq!( labels(&e.children), (1..=expected).map(|n| n.to_string()).collect::<Vec<_>>() @@ -337,12 +339,14 @@ fn labelled_menus_and_deep_landings_use_observed_destinations() { let home=doc("/","<header><nav><div><button>Products</button><ul><li><a href='/editor'>Editor</a></li><li><a href='/reader'>Reader</a></li></ul></div><div><a href='/a'>Alpha</a><a href='/b'>Beta</a></div></nav></header>"); let place = read_site(&home, &Default::default()).unwrap(); assert_eq!(labels(&place.sections), ["Products", "Alpha", "Beta"]); - assert_eq!(place.sections[0].key.as_url().path(), "/editor"); - assert_eq!(labels(&place.sections[0].children), ["Reader"]); + assert!(place.sections[0].menu_only); + assert!(!place.entry_openable(&place.sections[0].id, &Default::default())); + assert_eq!(labels(&place.sections[0].children), ["Editor", "Reader"]); let deep = doc("/pricing", include_str!("fixtures/section-pricing.html")); let p = read_site(&deep, &Default::default()).unwrap(); assert_eq!(p.sections[0].key.as_url(), deep.page()); - assert_eq!(labels(&p.sections[0].children), ["Plan tiers", "Questions"]); + assert_eq!(labels(&p.sections), ["Plan tiers", "Questions"]); + assert!(p.sections.iter().all(|e| e.locator != Locator::default())); assert_eq!(p.entry.as_url().path(), "/"); } #[test] @@ -386,9 +390,9 @@ fn separate_sitemaps_merge_one_cluster_regardless_of_arrival() { }; let p = run([(key("/b.xml"), &b), (key("/a.xml"), &a)].into()); assert!(p == run([(key("/a.xml"), &a), (key("/b.xml"), &b)].into())); - assert_eq!(labels(&p.sections), ["docs"]); + assert_eq!(labels(&p.sections), ["Docs"]); assert_eq!(p.sections[0].key.as_url().path(), "/docs/read"); - assert_eq!(labels(&p.sections[0].children), ["print"]); + assert_eq!(labels(&p.sections[0].children), ["Print"]); } #[test] @@ -441,7 +445,7 @@ fn metadata_and_section_page_boundaries() { .iter() .map(|d| Link { url: d.page().clone(), - title: "Guide".into(), + title: format!("Guide {}", d.page().path()), }) .collect::<Vec<_>>(); let (p, stats) = read_site_with_stats( @@ -590,10 +594,14 @@ fn landmark_free_link_rows_require_short_labels_and_little_intervening_text() { assert_eq!( p.sections .iter() - .filter(|e| e.tier == Tier::Secondary) + .filter(|e| e.tier == Tier::Primary && e.sources == [Source::LinkCluster]) .count(), 8 ); + assert!(p + .sections + .iter() + .any(|e| e.label == "Manual" && e.tier == Tier::Secondary)); } #[test] @@ -689,7 +697,11 @@ fn footer_navigation_does_not_hide_primary_link_clusters() { fn nested_menu_links_keep_distinct_anchors_on_the_parent_page() { let home = doc("/", "<nav><ul><li><a href='/pricing'>Pricing</a><ul><li><a href='/pricing#students'>Students</a></li><li><a href='/pricing'>Same page</a></li></ul></li></ul></nav>"); let place = read_site(&home, &SiteInputs::default()).unwrap(); - assert_eq!(labels(&place.sections[0].children), ["Students"]); + assert!(place.sections[0].menu_only); + assert_eq!( + labels(&place.sections[0].children), + ["Students", "Same page"] + ); assert_eq!( place.sections[0].children[0].locator.fragment().as_deref(), Some("#students") diff --git a/docs/architecture.md b/docs/architecture.md index 5ad178041..0795f95d1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,7 +45,7 @@ These groups locate work; they do not define a dependency graph. | Provider and decision services | `zephium-agent-provider-transport`, `zephium-agent-model-catalog`, `zephium-decision` | | Account and credentials | `zephium-account`, `zephium-credentials` | | Sidebar assistance and voice | `zephium-page-assist`, `zephium-voice`, desktop adapters | -| Search map | `zephium-map` (pure logic, depends only on `zephium-core`), `zephium-public-fetch` (anonymous public reads and the public-address guard) | +| Search map | `zephium-map` (pure logic, depends only on `zephium-core`), `zephium-public-fetch` (anonymous public reads and the public-address guard), `zephium-map-driver` (runs one search session over a results source and the anonymous reader, and projects it for the interface) | | External protocol integration | `zephium-mcp` | | Development and qualification | `xtask`, `scripts/`, `zephium-terra-macos-probe` | diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index d7a0aa6d6..4f02de376 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -26,9 +26,10 @@ tempfile.workspace = true time = { version = "0.3", features = ["parsing"] } toml = "0.9" psl = "=2.1.220" -tokio = { workspace = true, features = ["time"] } +tokio = { workspace = true, features = ["time", "signal"] } url.workspace = true zephium-map = { version = "=0.1.0", path = "../crates/zephium-map" } +zephium-map-driver = { version = "=0.1.0", path = "../crates/zephium-map-driver" } zephium-public-fetch = { version = "=0.1.0", path = "../crates/zephium-public-fetch" } [target.'cfg(target_os = "macos")'.dependencies] diff --git a/xtask/src/main.rs b/xtask/src/main.rs index bcd8687fd..888fe1f06 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -14,6 +14,9 @@ mod foreground_rendering_boundary; mod macos_imports; mod macos_process_family; mod map_bench; +#[path = "map_bench/section_flags.rs"] +mod map_bench_section_flags; +mod map_try; mod page_assist_boundary; mod page_reader_boundary; mod password_manager_qa; @@ -96,11 +99,12 @@ fn main() { } } Some("map-bench") => { - if let Err(error) = map_bench::run(&arguments[1..]) { + if let Err(error) = map_bench_section_flags::run(&arguments[1..]) { eprintln!("map bench: {error}"); exit(1); } } + Some("map") => exit(map_try::run(&arguments[1..])), Some("webext-suite") => { if let Err(error) = webext_suite::run(&arguments[1..]) { eprintln!("extension suite: {error}"); @@ -153,7 +157,7 @@ fn main() { } _ => { eprintln!( - "usage: cargo xtask <ci|webext-suite [--only NAME,...] [--soak]|blocker-bench --zephium PATH [--browsers LIST] [--runs N] [--only SITES] [--settle-ms N] [--youtube|--startup N] [--label NAME] [--compare RESULTS]|map-bench <record|replay|report> ...|check-frame-styles|check-macos-imports <binary>|check-engine-floors [--strict]|check-release-engine-security|check-release-assets <directory> <tag> <owner/repo>|check-agentic-probe-boundary|check-advisory-exceptions [--strict]|check-security-fork-locks|check-native-adapter-locks|check-blocker-security-fork|measure-macos-process-family --bundle-id ID --duration-seconds N [--interval-millis N] [--label LABEL]|serve-password-manager-webauthn-qa [--port PORT]|check-blocker-seed|materialize-blocker-seed-webkit --output PATH|{UPDATE_BLOCKER_SEED_USAGE}|blocker-prune <materialize|notify|hosts|build> ...|check-webview2-floor [--strict]>" + "usage: cargo xtask <ci|webext-suite [--only NAME,...] [--soak]|blocker-bench --zephium PATH [--browsers LIST] [--runs N] [--only SITES] [--settle-ms N] [--youtube|--startup N] [--label NAME] [--compare RESULTS]|map-bench <record|replay|report> ...|map <query> --site HOST [--site HOST] [--private]|check-frame-styles|check-macos-imports <binary>|check-engine-floors [--strict]|check-release-engine-security|check-release-assets <directory> <tag> <owner/repo>|check-agentic-probe-boundary|check-advisory-exceptions [--strict]|check-security-fork-locks|check-native-adapter-locks|check-blocker-security-fork|measure-macos-process-family --bundle-id ID --duration-seconds N [--interval-millis N] [--label LABEL]|serve-password-manager-webauthn-qa [--port PORT]|check-blocker-seed|materialize-blocker-seed-webkit --output PATH|{UPDATE_BLOCKER_SEED_USAGE}|blocker-prune <materialize|notify|hosts|build> ...|check-webview2-floor [--strict]>" ); exit(2); } diff --git a/xtask/src/map_bench/report.rs b/xtask/src/map_bench/report.rs index 8d7a5d4e3..9f324c85e 100644 --- a/xtask/src/map_bench/report.rs +++ b/xtask/src/map_bench/report.rs @@ -93,6 +93,7 @@ struct Summary { struct SessionTotals { sites: u64, places_with_three_sections: u64, + card_quality: BTreeMap<&'static str, BTreeMap<&'static str, Defects>>, sources: Counts, shells: u64, walls: u64, @@ -104,6 +105,12 @@ struct SessionTotals { passage: Counts, } +#[derive(Default, Serialize)] +struct Defects { + rows: u64, + places: u64, +} + impl SessionTotals { fn collect(&mut self, label: &QueryLabel, result: &QueryResult, samples: &mut Samples) { let site_count = match label.kind { @@ -174,6 +181,18 @@ impl SessionTotals { if let Some(&sections) = outcome.stats.get(&format!("place.{index}.sections")) { if site_count > 0 { self.places_with_three_sections += u64::from(sections >= 3); + if let Some(mode) = ["all", "asked"] + .into_iter() + .find(|m| count(&format!("card.{m}")) > 0) + { + let quality = self.card_quality.entry(mode).or_default(); + for class in super::session::quality::CLASSES { + let rows = count(&format!("place.{index}.card.{class}")); + let defects = quality.entry(class).or_default(); + defects.rows = defects.rows.saturating_add(rows); + defects.places += u64::from(rows != 0); + } + } samples.sections.push(sections); samples .primary @@ -204,6 +223,20 @@ Places with at least 3 sections — {} of {} place and compare sites. ", self.places_with_three_sections, self.sites, ); + for (mode, quality) in &self.card_quality { + let _ = writeln!( + markdown, + "\n### Card quality ({mode})\n\n| Defect | Rows | Place cards |\n|---|---:|---:|" + ); + for (class, defects) in quality { + let _ = writeln!( + markdown, + "| {class} | {} | {} |", + defects.rows, defects.places + ); + } + markdown.push('\n'); + } markdown.push_str( "| Session activity | Count | | --- | ---: | diff --git a/xtask/src/map_bench/run.rs b/xtask/src/map_bench/run.rs index 1e651d689..54ac5f8c9 100644 --- a/xtask/src/map_bench/run.rs +++ b/xtask/src/map_bench/run.rs @@ -8,6 +8,10 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; use tokio::task::{Id as TaskId, JoinSet}; use url::Url; +use zephium_map::{ + session::{ReadState, Sections}, + Entry, +}; use zephium_public_fetch::{ PublicReader, ReadRefusal, ReadRequest, ReadSession, ReaderLimits, RouteSource, }; @@ -21,7 +25,7 @@ use super::score::{self, Reason, Score, Verdict}; use super::store::{ self, query_dir, write_json, Journal, MatchPolicy, RecordedMatch, ResultsSlot, Transfer, }; -use super::{platform, BenchError, Options, Result}; +use super::{platform, session, BenchError, Options, Result}; const SCHEMA: u32 = 1; pub(super) const BETWEEN_QUERIES: Duration = Duration::from_millis(500); @@ -29,6 +33,7 @@ pub(super) const MANIFEST: &str = "run.json"; pub(super) const OUTCOME: &str = "outcome.json"; pub(super) const MEASURE: &str = "measure.json"; pub(super) const REPLAY: &str = "replay.json"; +const SECTION_COMPARISON: &str = "sections.json"; #[derive(Debug, Deserialize, Serialize)] pub(super) struct RunManifest { @@ -385,6 +390,8 @@ struct QueryIo<'a> { failure: Option<Reason>, submitted: usize, claimed: BTreeSet<usize>, + open_record: Option<usize>, + matched: BTreeMap<usize, usize>, active: BTreeMap<usize, (usize, Option<u64>)>, ready: BTreeMap<(Option<usize>, Duration, usize), Ready>, } @@ -421,6 +428,8 @@ impl<'a> QueryIo<'a> { failure: None, submitted: 0, claimed: BTreeSet::new(), + open_record: None, + matched: BTreeMap::new(), active: BTreeMap::new(), ready: BTreeMap::new(), } @@ -447,14 +456,23 @@ impl<'a> QueryIo<'a> { }; if let Some(matched) = self.journal.find( &request, - |index| probe || !self.claimed.contains(&index), + |index| { + probe + || !self.claimed.contains(&index) + && (request.expect != super::engine::Expectation::Html + || self.open_record.is_none_or(|record| record == index)) + }, policy, ) { self.claimed.insert(matched.index); - self.ready.insert( - (Some(matched.order), matched.end, token), - Ready::Recorded(matched), - ); + self.matched.insert(token, matched.index); + let end = if self.open_record.is_some() { + self.elapsed.saturating_add(matched.duration) + } else { + matched.end + }; + self.ready + .insert((Some(matched.order), end, token), Ready::Recorded(matched)); } else if let Some(live) = &mut self.live { let index = self.journal.reserve(&request, self.query, live.elapsed())?; self.claimed.insert(index); @@ -880,6 +898,167 @@ fn replay_query( Ok(result) } +#[derive(Serialize)] +struct SectionComparison { + slot: u8, + id: String, + role: Option<String>, + state: &'static str, + read: Option<ReadState>, + requests: u64, + decoded_bytes: u64, + not_recorded: u64, + difference: Option<SectionDifference>, +} + +#[derive(Serialize)] +struct SectionDifference { + all_children: usize, + asked_children: usize, + all_more: u32, + asked_more: u32, + all_only: usize, + asked_only: usize, + changed: usize, +} + +fn section_difference(all: &Entry, asked: &Entry) -> Option<SectionDifference> { + if all.children == asked.children && all.more == asked.more { + return None; + } + let missing = |left: &Entry, right: &Entry| { + left.children + .iter() + .filter(|child| !right.children.iter().any(|other| child.id == other.id)) + .count() + }; + Some(SectionDifference { + all_children: all.children.len(), + asked_children: asked.children.len(), + all_more: all.more, + asked_more: asked.more, + all_only: missing(all, asked), + asked_only: missing(asked, all), + changed: all + .children + .iter() + .filter(|child| { + asked + .children + .iter() + .any(|other| child.id == other.id && *child != other) + }) + .count(), + }) +} + +fn compare_sections( + root: &Path, + query: &CorpusQuery, + clock: RunClock, + index: usize, +) -> Result<Vec<SectionComparison>> { + let path = query_dir(root, &query.label.id, false)?; + let replay_io = || -> Result<QueryIo<'_>> { + let mut io = QueryIo::new(&path, Journal::load(&path)?, clock, None); + io.query_index = index; + Ok(io) + }; + let mut all_io = replay_io()?; + let all = session::search(query, &mut all_io, Sections::All, true); + let asked = session::search(query, &mut replay_io()?, Sections::Asked, true); + let mut comparisons = Vec::new(); + for attempt in &all.sections { + let mut comparison = SectionComparison { + slot: attempt.slot, + id: attempt.id.as_str().to_owned(), + role: None, + state: "missing_recorded_response", + read: None, + requests: 0, + decoded_bytes: 0, + not_recorded: 0, + difference: None, + }; + if let Some(&record) = all_io.matched.get(&attempt.token) { + let slot = usize::from(attempt.slot); + let find = |capture: &session::Capture| -> Option<Entry> { + capture.places[slot] + .as_ref()? + .place() + .sections + .iter() + .find(|entry| entry.id == attempt.id) + .cloned() + }; + let baseline = find(&all); + comparison.role = baseline + .as_ref() + .and_then(|entry| entry.role) + .map(|role| format!("{role:?}")); + comparison.state = "missing_asked_place"; + if let Some(held) = &asked.places[slot] { + let mut open_io = replay_io()?; + open_io.open_record = Some(record); + let before = find(&asked); + if let Some(entry) = before + .as_ref() + .filter(|entry| entry.read == Some(ReadState::Read)) + { + comparison.state = "already_read"; + comparison.read = entry.read; + comparison.difference = baseline + .as_ref() + .and_then(|all| section_difference(all, entry)); + } else { + match session::open( + query, + &mut open_io, + held.clone(), + attempt.slot, + &comparison.id, + ) { + Ok(opened) => { + comparison.state = "opened"; + comparison.requests = open_io.activity.site_requests; + comparison.not_recorded = open_io.activity.not_recorded; + comparison.decoded_bytes = opened + .outcome + .stats + .iter() + .filter(|(key, _)| { + key.starts_with("phase.") && key.ends_with(".bytes") + }) + .map(|(_, bytes)| bytes) + .sum(); + if let Some(entry) = find(&opened) { + comparison.read = entry.read; + comparison.difference = baseline + .as_ref() + .and_then(|all| section_difference(all, &entry)); + } else { + comparison.state = "missing_opened_entry"; + } + } + Err(zephium_map::session::OpenRefusal::UnknownEntry) => { + comparison.state = "missing_asked_entry" + } + Err(zephium_map::session::OpenRefusal::NotOpenable) => { + comparison.state = "not_openable"; + comparison.read = before.as_ref().and_then(|entry| entry.read); + } + } + } + if baseline.is_none() { + comparison.state = "missing_all_entry"; + } + } + } + comparisons.push(comparison); + } + Ok(comparisons) +} + pub(super) fn replay( root: &Path, corpus: &Corpus, @@ -927,6 +1106,20 @@ pub(super) fn replay( }, )?; save_outcome(&path.join(OUTCOME), result)?; + if crate::map_bench_section_flags::get().compare + && matches!( + query.label.kind, + super::corpus::Kind::Place | super::corpus::Kind::Compare + ) + { + match compare_sections(root, query, recorded.clock(), index) { + Ok(comparisons) => write_json(&path.join(SECTION_COMPARISON), &comparisons)?, + Err(error) => { + write_json(&path.join("sections-error.json"), &error.class)?; + eprintln!("map bench: {}", error.for_query(&query.label.id)); + } + } + } } let manifest = ReplayManifest { started_unix_ns, diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 97dfef0f4..9c0916b27 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -584,9 +584,9 @@ This run used synthetic results pages. Group checks and first-layer latency were | full_ns | 1 | 10 | 10 | 10 | | memo_bytes | 1 | 256 | — | 256 | | peak_rss_delta_bytes | 0 | — | — | — | -| primary_sections_per_place | 1 | 3 | 3 | 3 | +| primary_sections_per_place | 1 | 5 | 5 | 5 | | requests | 2 | 0 | 0 | 0 | -| secondary_sections_per_place | 1 | 2 | 2 | 2 | +| secondary_sections_per_place | 1 | 0 | 0 | 0 | | sections_per_place | 1 | 5 | 5 | 5 | | wall_ns | 2 | 0 | 0 | 0 | | wire_bytes | 2 | 0 | 0 | 0 | @@ -597,6 +597,33 @@ This run used synthetic results pages. Group checks and first-layer latency were Places with at least 3 sections — 1 of 1 place and compare sites. + +### Card quality (all) + +| Defect | Rows | Place cards | +|---|---:|---:| +| action | 0 | 0 | +| detail | 0 | 0 | +| duplicate | 0 | 0 | +| duplicate_children | 0 | 0 | +| invalid_group_pages | 0 | 0 | +| language_groups | 0 | 0 | +| long_compound_titles | 0 | 0 | +| missing_header_links | 0 | 0 | +| nameless | 0 | 0 | +| off_host_root_children | 0 | 0 | +| off_host_without_display | 0 | 0 | +| order | 0 | 0 | +| path_names | 1 | 1 | +| same_role_pairs | 0 | 0 | +| self | 0 | 0 | +| sentence | 0 | 0 | +| skip_links | 0 | 0 | +| supplemental_only | 2 | 1 | +| thin_cards | 0 | 0 | +| top_level_menu_items | 0 | 0 | +| utility | 0 | 0 | + | Session activity | Count | | --- | ---: | | Shells | 0 | @@ -701,6 +728,43 @@ fn replay_refuses_a_different_engine_before_writing_a_run() { assert!(!root.path().join("replay").exists()); } +#[test] +fn section_comparison_finishes_after_one_corrupt_journal() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("corpus.toml"); + let entries: String = ["first", "second"] + .iter() + .map(|id| format!("[[query]]\nid='{id}'\ntext='Acme docs'\n{ACME}\n")) + .collect(); + fs::write(&path, entries).unwrap(); + let corpus = Corpus::load(std::slice::from_ref(&path)).unwrap(); + init_engine(root.path(), &corpus, EngineKind::Session); + let mut source = ScriptedSource::new(site); + for query in &corpus.queries { + run_session(root.path(), query, &mut source); + } + fs::write( + root.path().join("queries/first/requests.jsonl"), + b"incomplete", + ) + .unwrap(); + crate::map_bench_section_flags::run(&[ + "replay".into(), + "--compare-sections".into(), + "--engine".into(), + "session".into(), + "--from".into(), + root.path().display().to_string(), + "--corpus".into(), + path.display().to_string(), + ]) + .unwrap(); + let (run, manifest) = latest_replay(root.path()).unwrap().unwrap(); + assert_eq!(manifest.queries.len(), 2); + assert!(run.join("queries/first/sections-error.json").is_file()); + assert!(run.join("queries/second/sections.json").is_file()); +} + fn save_row(root: &Path, path: &Path, request: &FetchRequest, result: FetchResult) { let mut journal = Journal::load(path).unwrap(); let start = Duration::from_secs(10); diff --git a/xtask/src/map_bench/score.rs b/xtask/src/map_bench/score.rs index a2455a488..e6ae9e738 100644 --- a/xtask/src/map_bench/score.rs +++ b/xtask/src/map_bench/score.rs @@ -169,6 +169,9 @@ pub(super) fn score(query: &CorpusQuery, outcome: &Outcome, activity: &Activity) .then(|| query.group.difference(&outcome.groups).copied().collect()); let missing_count = missing_groups.as_ref().map_or(0, Vec::len); let matched = |entry: &super::engine::Entry| { + if entry.tags.contains("action") { + return None; + } query .want .iter() diff --git a/xtask/src/map_bench/section_flags.rs b/xtask/src/map_bench/section_flags.rs new file mode 100644 index 000000000..bb3a82e5e --- /dev/null +++ b/xtask/src/map_bench/section_flags.rs @@ -0,0 +1,107 @@ +use std::cell::Cell; + +use zephium_map::session::Sections; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SectionFlags { + pub(crate) sections: Sections, + pub(crate) compare: bool, +} + +thread_local! { + static FLAGS: Cell<SectionFlags> = const { Cell::new(SectionFlags { + sections: Sections::All, compare: false, + }) }; +} + +pub(crate) fn get() -> SectionFlags { + FLAGS.get() +} + +pub(crate) fn run(args: &[String]) -> Result<(), String> { + let (flags, forwarded) = parse(args)?; + if matches!(args, [help] if help == "--help") + || matches!(args, [mode, help] if mode == "replay" && help == "--help") + { + println!("Session replay options: [--sections all|asked] [--compare-sections]"); + } + let previous = FLAGS.replace(flags); + let result = crate::map_bench::run(&forwarded).map_err(|error| error.to_string()); + FLAGS.set(previous); + result +} + +fn parse(args: &[String]) -> Result<(SectionFlags, Vec<String>), String> { + let mut forwarded = Vec::new(); + let mut sections = None; + let mut compare = false; + let mut args_iter = args.iter(); + while let Some(argument) = args_iter.next() { + match argument.as_str() { + "--sections" if sections.is_none() => { + sections = Some(match args_iter.next().map(String::as_str) { + Some("all") => Sections::All, + Some("asked") => Sections::Asked, + _ => return Err("--sections requires all or asked".into()), + }); + } + "--compare-sections" if !compare => compare = true, + "--sections" | "--compare-sections" => { + return Err("duplicate session replay flag".into()) + } + _ => forwarded.push(argument.clone()), + } + } + if (sections.is_some() || compare) + && (args.first().is_none_or(|arg| arg != "replay") + || forwarded + .windows(2) + .any(|pair| pair == ["--engine", "probe"])) + { + return Err("section flags require session replay".into()); + } + Ok(( + SectionFlags { + sections: sections.unwrap_or_default(), + compare, + }, + forwarded, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flags_are_bounded_and_specific_to_session_replay() { + let parse = |args: &str| { + parse( + &args + .split_whitespace() + .map(str::to_owned) + .collect::<Vec<_>>(), + ) + }; + assert_eq!(parse("replay").unwrap().0.sections, Sections::All); + assert_eq!( + parse("replay --sections asked --compare-sections --engine session").unwrap(), + ( + SectionFlags { + sections: Sections::Asked, + compare: true + }, + vec!["replay".to_owned(), "--engine".into(), "session".into()] + ) + ); + for args in [ + "replay --sections", + "replay --sections both", + "replay --sections all --sections all", + "record --compare-sections", + "replay --engine probe --sections all", + ] { + assert!(parse(args).is_err()); + } + } +} diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index 3dd84f585..c07a1567e 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -3,9 +3,10 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use url::Url; use zephium_core::search::SearchEngine; use zephium_map::session::{ - EndOutcome, Expect, Failure, FetchResult as SessionFetch, Id, Phase, Stats, MAX_CONCURRENT, - MAX_HOST_CONCURRENT, MAX_MEMO_BYTES, + EndOutcome, Expect, Failure, FetchResult as SessionFetch, HeldSite, Id, Phase, Sections, Stats, + MAX_CONCURRENT, MAX_HOST_CONCURRENT, MAX_MEMO_BYTES, }; +use zephium_map::{query::Confidence, site::EntryId}; use zephium_map::{ read_query, Config, Doc, DocLimits, Effect, FirstLayer, Input, MapEvent, Place, QueryKind, Session, SiteKey, Source, @@ -25,25 +26,79 @@ pub(super) struct SessionEngine; impl Engine for SessionEngine { fn run(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Outcome { - let mut driver = Driver::new(query); - if query.label.kind == Kind::Passage && query.pages.is_empty() { - driver.outcome.needs_results_page = true; - return driver.outcome; - } - let config = Config { - session_id: io.session_id(), - engine: SearchEngine::Google, - now: io.now(), - ..Config::default() - }; - let Ok((session, effects)) = Session::start(config, &query.text) else { - driver.outcome.failure = Some(EngineFailure::InvalidInput); - return driver.outcome; - }; - driver.run(session, effects, query, io) + search( + query, + io, + crate::map_bench_section_flags::get().sections, + false, + ) + .outcome } } +pub(super) struct SectionAttempt { + pub(super) token: usize, + pub(super) slot: u8, + pub(super) id: EntryId, +} + +pub(super) struct Capture { + pub(super) outcome: Outcome, + pub(super) places: [Option<HeldSite>; MAX_PLACES], + pub(super) sections: Vec<SectionAttempt>, +} + +pub(super) mod quality; + +pub(super) fn search( + query: &CorpusQuery, + io: &mut dyn BenchIo, + sections: Sections, + capture: bool, +) -> Capture { + let mut driver = Driver::new(query); + if query.label.kind == Kind::Passage && query.pages.is_empty() { + driver.outcome.needs_results_page = true; + return driver.capture(None); + } + driver.outcome.stats.insert( + match sections { + Sections::Asked => "card.asked", + Sections::All => "card.all", + } + .into(), + 1, + ); + let config = Config { + session_id: io.session_id(), + engine: SearchEngine::Google, + now: io.now(), + sections, + ..Config::default() + }; + let Ok((session, effects)) = Session::start(config, &query.text) else { + driver.outcome.failure = Some(EngineFailure::InvalidInput); + return driver.capture(None); + }; + driver.run(session, effects, query, io, capture) +} + +pub(super) fn open( + query: &CorpusQuery, + io: &mut dyn BenchIo, + held: HeldSite, + slot: u8, + id: &str, +) -> Result<Capture, zephium_map::session::OpenRefusal> { + let config = Config { + session_id: io.session_id(), + now: io.now(), + ..Config::default() + }; + let (session, effects) = Session::open(config, held, slot, id, Confidence::High, false)?; + Ok(Driver::new(query).run(session, effects, query, io, true)) +} + struct Driver { outcome: Outcome, places: [Option<Place>; MAX_PLACES], @@ -52,6 +107,7 @@ struct Driver { terminal: bool, immediate: VecDeque<Input>, in_flight: BTreeMap<usize, (Id, Url, Expectation)>, + sections: Vec<SectionAttempt>, } impl Driver { @@ -64,6 +120,7 @@ impl Driver { terminal: false, immediate: VecDeque::new(), in_flight: BTreeMap::new(), + sections: Vec::new(), } } @@ -73,10 +130,26 @@ impl Driver { mut effects: Vec<Effect>, query: &CorpusQuery, io: &mut dyn BenchIo, - ) -> Outcome { + capture: bool, + ) -> Capture { loop { for effect in effects { + let effect_id = effect.id(); + let section = capture.then(|| session.section_fetch(effect_id)).flatten(); self.effect(effect, query, io); + if let Some((slot, id)) = section { + if let Some((&token, _)) = self + .in_flight + .iter() + .find(|(_, (id, _, _))| *id == effect_id) + { + self.sections.push(SectionAttempt { + token, + slot, + id: id.clone(), + }); + } + } if self .outcome .failure @@ -128,12 +201,24 @@ impl Driver { self.outcome .stats .insert("official_sites".into(), self.lookups as u64); + self.capture(capture.then_some(&session)) + } + + fn capture(mut self, session: Option<&Session>) -> Capture { + let mut places = [None, None]; for (index, place) in self.places.into_iter().enumerate() { if let Some(place) = place { + if let Some(session) = session { + places[index] = session.hold_place(index as u8, place.clone()); + } flatten_place(&mut self.outcome, index, place); } } - self.outcome + Capture { + outcome: self.outcome, + places, + sections: self.sections, + } } fn completion(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Option<(Input, bool)> { @@ -494,7 +579,15 @@ fn flatten_stats(outcome: &mut Outcome, stats: Stats) { put("stale_memos", stats.stale_memos.into()); put("rejected_memos", stats.rejected_memos.into()); for (index, notes) in stats.places { + for (key, count) in [ + ("invalid_group_pages", notes.invalid_group_pages), + ("missing_header_links", notes.missing_header_links), + ("language_groups", notes.language_groups), + ] { + put(&format!("place.{index}.card.{key}"), count as u64); + } for (key, value) in [ + ("probed_section", notes.probed_section), ("robots_truncated", notes.robots_truncated), ("entry_truncated", notes.entry_truncated), ("sections_truncated", notes.sections_truncated), @@ -565,9 +658,12 @@ fn source_tag(source: Source) -> &'static str { } fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { - let mut put = |key, value| { + let mut put = |key: &str, value| { outcome.stats.insert(format!("place.{index}.{key}"), value); }; + for (class, count) in quality::CLASSES.into_iter().zip(quality::measure(&place)) { + put(&format!("card.{class}"), count); + } let notes = place.notes; for (key, value) in [ ("shell", notes.shell), @@ -582,7 +678,14 @@ fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { .filter(|e| e.tier == zephium_map::Tier::Primary) .count(); put("primary", primary as u64); - put("secondary", (place.sections.len() - primary) as u64); + put( + "secondary", + place + .sections + .iter() + .filter(|e| e.tier == zephium_map::Tier::Secondary) + .count() as u64, + ); put("sections", place.sections.len() as u64); put( "children", @@ -602,6 +705,9 @@ fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { .iter() .filter(|source| **source != Source::Heading || depth == Depth::Two), ); + if entry.menu_only { + continue; + } let mut url = entry.key.as_url().clone(); if let Some(fragment) = entry .locator @@ -626,9 +732,14 @@ fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { .iter() .map(|&source| source_tag(source).into()) .chain(std::iter::once( - match entry.tier { + match if section.tier == zephium_map::Tier::Action { + section.tier + } else { + entry.tier + } { zephium_map::Tier::Primary => "primary", zephium_map::Tier::Secondary => "secondary", + zephium_map::Tier::Action => "action", } .into(), )) diff --git a/xtask/src/map_bench/session/quality.rs b/xtask/src/map_bench/session/quality.rs new file mode 100644 index 000000000..6ef92f04e --- /dev/null +++ b/xtask/src/map_bench/session/quality.rs @@ -0,0 +1,236 @@ +use std::collections::BTreeSet; +use zephium_map::{site::MAX_PRIMARY_LABEL_CHARS, Place, SectionRole, Source, Tier}; + +const SHORT_TITLE_WORDS: usize = 3; +const CARD_MEASURES: usize = 18; +pub(in crate::map_bench) const CLASSES: [&str; 21] = [ + "action", + "sentence", + "self", + "nameless", + "duplicate", + "off_host_without_display", + "order", + "utility", + "detail", + "off_host_root_children", + "top_level_menu_items", + "supplemental_only", + "same_role_pairs", + "path_names", + "thin_cards", + "duplicate_children", + "skip_links", + "long_compound_titles", + "invalid_group_pages", + "missing_header_links", + "language_groups", +]; + +pub(super) fn measure(place: &Place) -> [u64; CARD_MEASURES] { + let mut counts = [0; CARD_MEASURES]; + counts[17] = u64::from( + zephium_map::site::title_segments(&place.title).count() > 1 + && zephium_map::site::title_segments(&place.title) + .flat_map(str::split_whitespace) + .count() + > SHORT_TITLE_WORDS, + ); + for row in &place.sections { + let mut children = BTreeSet::new(); + for child in &row.children { + counts[15] += + u64::from(!children.insert((child.card_page(), child.locator.fragment()))); + } + for e in std::iter::once(row).chain(&row.children) { + counts[16] += u64::from( + e.locator.element.is_some() + && e.key.page_match() == place.entry.page_match() + && zephium_map::site::skip_label(&e.label), + ); + } + } + let mut labels = BTreeSet::new(); + let mut destinations = BTreeSet::new(); + let mut roles = std::collections::BTreeMap::new(); + counts[14] = u64::from( + place + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .count() + < zephium_map::site::MIN_NAV_ROWS, + ); + let mut lower_priority = false; + for entry in place.sections.iter().filter(|e| e.tier == Tier::Primary) { + counts[10] += u64::from(entry.menu_item); + counts[11] += u64::from( + entry + .sources + .iter() + .all(|s| matches!(s, Source::Llms | Source::Sitemap)), + ); + if let Some(role) = entry.role { + let previous = roles.entry(role).or_insert(0); + counts[12] += *previous; + *previous += 1; + } + counts[13] += u64::from(entry.path_name); + let url = entry.key.as_url(); + let label = entry.label.to_lowercase(); + let path = url.path().trim_matches('/'); + let leaf = path.rsplit('/').next().unwrap_or_default(); + let action = matches!( + leaf, + "signup" | "sign-up" | "login" | "register" | "signin" | "contact-sales" + ) || path.ends_with("contact/sales") + || matches!( + label.as_str(), + "sign in" + | "sign up" + | "log in" + | "request a demo" + | "contact sales" + | "start free trial" + ); + let sentence = entry.label.chars().count() > MAX_PRIMARY_LABEL_CHARS + || label.contains(". ") + || label.split_whitespace().count() >= 7; + let home = !entry.menu_only + && entry.key.page_match() == place.entry.page_match() + && entry.locator == Default::default(); + let nameless = matches!( + label.as_str(), + "" | "more" | "other" | "optional" | "menu" | "learn more" + ); + let fresh_label = labels.insert(label.clone()); + let fresh_destination = destinations.insert(( + entry.card_page(), + entry.locator.fragment(), + entry.menu_only.then_some(&entry.id), + )); + let utility = entry.role == Some(SectionRole::Legal) + || matches!( + label.as_str(), + "settings" | "rss" | "account" | "dashboard" | "translations" | "search" + ) + || leaf.ends_with(".xml") + || leaf.starts_with("llms") && leaf.ends_with(".txt"); + let detail = entry.locator.element.is_some() + && url.host_str() != place.entry.as_url().host_str() + && path.contains('/'); + let minor = action || home || nameless || utility || detail; + let direct = entry.navigation_row(); + let order = !minor && direct && lower_priority; + lower_priority |= minor || !direct; + for (n, hit) in counts.iter_mut().zip([ + action, + sentence, + home, + nameless, + !fresh_label || !fresh_destination, + false, + order, + utility, + detail, + false, + ]) { + *n += u64::from(hit); + } + } + for child in place.sections.iter().flat_map(|e| &e.children) { + let url = child.key.as_url(); + if url.path() == "/" && url.host_str() != place.entry.as_url().host_str() { + counts[9] += 1; + counts[5] += u64::from(zephium_map::site::display_hostname(url).is_none()); + } + } + counts +} + +#[cfg(test)] +mod tests { + use super::*; + use url::Url; + use zephium_map::{site::read_site, Doc, DocLimits, PageKey}; + + #[test] + fn counts_rows_for_independent_defects_and_checks_the_root_child_host() { + let url = Url::parse("https://acme.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>First</a><a href='/b'>Second</a><a href='/c'>Third</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut p = read_site(&doc, &Default::default()).unwrap(); + p.sections[0].label = "More".into(); + p.sections[0].key = p.entry.clone(); + p.sections[1].key = PageKey::from_url(&url.join("/login").unwrap()).unwrap(); + p.sections[2].label = "More".into(); + let mut child = p.sections[1].clone(); + child.key = PageKey::from_url(&Url::parse("https://docs.acme.example/").unwrap()).unwrap(); + p.sections[2].children.push(child); + let scores: std::collections::BTreeMap<_, _> = + CLASSES.into_iter().zip(measure(&p)).collect(); + assert_eq!(scores["nameless"], 2); + for class in ["action", "self", "duplicate", "off_host_root_children"] { + assert_eq!(scores[class], 1); + } + assert_eq!(scores["off_host_without_display"], 0); + } +} + +#[cfg(test)] +mod extended_tests { + use super::*; + use zephium_map::{site::read_site, Doc, DocLimits}; + #[test] + fn counts_locale_duplicates_skip_links_and_compound_titles_across_tiers() { + let url = url::Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>One</a><a hreflang='de' href='/de/b'>Two</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut place = read_site(&doc, &Default::default()).unwrap(); + let first = place.sections.pop().unwrap(); + let mut alias = first.clone(); + alias.key = zephium_map::PageKey::from_url(&url.join("/b").unwrap()).unwrap(); + let row = &mut place.sections[0]; + row.tier = Tier::Secondary; + row.key = place.entry.clone(); + row.locator.element = Some(zephium_map::key::LocatorText::new("main").unwrap()); + row.label = "Skip to content".into(); + row.children = vec![first, alias]; + place.title = "Site | Three Words".into(); + assert_eq!(measure(&place)[15..], [1, 1, 0]); + place.title.push_str(" Four"); + assert_eq!(measure(&place)[15..], [1, 1, 1]); + } + #[test] + fn provenance_and_role_pairs_are_counted_per_primary_row() { + let url = url::Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>A</a><a href='/b'>B</a><a href='/c'>C</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut place = read_site(&doc, &Default::default()).unwrap(); + for e in &mut place.sections { + e.role = Some(SectionRole::Documentation); + } + place.sections[0].menu_item = true; + place.sections[0].path_name = true; + place.sections[0].sources = vec![Source::Sitemap, Source::Llms]; + place.sections[1].sources = vec![Source::Llms, Source::PrimaryNav]; + assert_eq!(measure(&place)[10..15], [1, 1, 3, 1, 0]); + place.sections[0].tier = Tier::Secondary; + assert_eq!(measure(&place)[10..15], [0, 0, 1, 0, 1]); + } +} diff --git a/xtask/src/map_bench/store.rs b/xtask/src/map_bench/store.rs index a03f13b63..3e816a2c8 100644 --- a/xtask/src/map_bench/store.rs +++ b/xtask/src/map_bench/store.rs @@ -542,6 +542,7 @@ pub(super) enum MatchPolicy { pub(super) struct RecordedMatch { pub(super) index: usize, pub(super) end: Duration, + pub(super) duration: Duration, pub(super) order: usize, pub(super) relaxed_cap: Option<usize>, } @@ -619,6 +620,9 @@ impl Journal { let matched = |relaxed_cap| RecordedMatch { index, end: row.elapsed_at_return, + duration: row.elapsed_at_start.map_or(row.timings.total, |start| { + row.elapsed_at_return.saturating_sub(start) + }), order: row.completion_order.unwrap_or(index), relaxed_cap, }; diff --git a/xtask/src/map_try.rs b/xtask/src/map_try.rs new file mode 100644 index 000000000..f143447bf --- /dev/null +++ b/xtask/src/map_try.rs @@ -0,0 +1,517 @@ +mod printer; +#[cfg(test)] +mod tests; + +use std::{ + fmt::{self, Write as _}, + future::Future, + io::{self, Write}, + sync::Arc, + time::Instant, +}; + +use tokio::{runtime::Handle, sync::watch}; +use url::{Host, Url}; +use zephium_core::search::SearchEngine; +use zephium_map::{ + read_query, + session::{Failure, FetchResult}, + QueryKind, +}; +use zephium_map_driver::{ + wire::{Change, OpenResult, Outcome, StartRefusal, MAX_SECTIONS, MAX_TEXT_BYTES}, + Counts, Driver, FetchRequest, Fetcher, Io, MapRequest, MemoryMemo, PublicIo, Reading, + ResultsPage, ResultsSource, SystemClock, +}; +use zephium_public_fetch::{ + guard::{public_target, MAX_HOST_BYTES}, + PublicReader, PublicRoute, ReaderLimits, RouteSource, +}; + +use self::printer::{intro, refusal, Printer}; + +const ENGINE: SearchEngine = SearchEngine::DuckDuckGo; +const MAX_SITES: usize = 2; +const MAX_DNS_LABEL_BYTES: usize = 63; +const MAX_OPEN_LABELS: usize = MAX_SECTIONS * MAX_SITES; + +#[derive(Debug, PartialEq, Eq)] +enum Error { + MissingQuery, + MissingSite, + BadHost, + BadOpenLabel, + TooManySites, + UnexpectedOption, + PlaceArity, + CompareArity, + Refused(StartRefusal), + Proxy, + Runtime, + Interrupt, + Stream, + OpenFailed, + Output, +} + +impl Error { + fn usage(&self) -> bool { + matches!( + self, + Self::MissingQuery + | Self::MissingSite + | Self::BadHost + | Self::BadOpenLabel + | Self::TooManySites + | Self::UnexpectedOption + | Self::PlaceArity + | Self::CompareArity + ) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::MissingQuery => { + "Usage: cargo xtask map <query> --site <host> [--site <host>] [--private] [--open <label|left::label|right::label>]..." + } + Self::MissingSite => "Usage error: specify a host with --site", + Self::BadHost => "Usage error: --site needs a bare public hostname", + Self::BadOpenLabel => "Usage error: invalid --open label or too many labels", + Self::TooManySites => "Usage error: specify at most two sites", + Self::UnexpectedOption => { + "Usage error: supported flags are --site, --private and --open" + } + Self::PlaceArity => "Usage error: a place query needs one --site", + Self::CompareArity => "Usage error: a comparison needs two --site flags", + Self::Refused(reason) => return f.write_str(refusal(*reason)), + Self::Proxy => "The reader refuses to go around a proxy. A direct route is required.", + Self::Runtime => "Could not start the map runtime.", + Self::Interrupt => "Could not listen for Ctrl-C.", + Self::Stream => "The map stopped without an outcome.", + Self::OpenFailed => "One or more requested sections could not be read.", + Self::Output => "Could not write the map to the terminal.", + }) + } +} + +struct Options<'a> { + query: &'a str, + sites: Vec<Url>, + private: bool, + opens: Vec<&'a str>, +} + +impl<'a> Options<'a> { + fn parse(arguments: &'a [String]) -> Result<Self, Error> { + let (query, rest) = arguments.split_first().ok_or(Error::MissingQuery)?; + if query.starts_with("--") { + return Err(Error::MissingQuery); + } + + let mut options = Self { + query, + sites: Vec::new(), + private: false, + opens: Vec::new(), + }; + let mut args = rest.iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--site" => { + if options.sites.len() == MAX_SITES { + return Err(Error::TooManySites); + } + let raw = args + .next() + .filter(|raw| !raw.starts_with("--")) + .ok_or(Error::MissingSite)?; + options.sites.push(site_url(raw).ok_or(Error::BadHost)?); + } + "--private" if !options.private => options.private = true, + "--open" => { + let label = args + .next() + .filter(|label| { + !label.starts_with("--") + && !label.trim().is_empty() + && label.len() <= MAX_TEXT_BYTES + && !label.chars().any(char::is_control) + }) + .ok_or(Error::BadOpenLabel)?; + if options.opens.len() == MAX_OPEN_LABELS { + return Err(Error::BadOpenLabel); + } + options.opens.push(label); + } + _ => return Err(Error::UnexpectedOption), + } + } + if options.sites.is_empty() { + return Err(Error::MissingSite); + } + Ok(options) + } + + fn prepare(self) -> Result<(MapRequest, StandIn), Error> { + let query = read_query(self.query).map_err(|_| Error::Refused(StartRefusal::Invalid))?; + let titles = match query.kind() { + QueryKind::Place { entity, .. } => { + if self.sites.len() != 1 { + return Err(Error::PlaceArity); + } + vec![if entity.is_empty() { + self.query.to_owned() + } else { + original_terms(self.query, entity) + }] + } + QueryKind::Compare { left, right, .. } => { + if self.sites.len() != MAX_SITES { + return Err(Error::CompareArity); + } + vec![ + original_terms(self.query, left), + original_terms(self.query, right), + ] + } + _ => return Err(Error::Refused(StartRefusal::NotAMap)), + }; + let stand_in = StandIn::new(self.sites.iter().zip(titles.iter().map(String::as_str))); + let request = MapRequest { + query: self.query.to_owned(), + engine: ENGINE, + session_id: 1, + profile: "terminal".into(), + private: self.private, + }; + Ok((request, stand_in)) + } +} + +fn site_url(raw: &str) -> Option<Url> { + let bare = raw.strip_suffix('.').unwrap_or(raw); + if bare.is_empty() + || bare.len() > MAX_HOST_BYTES + || bare.chars().any(|c| { + c.is_whitespace() + || c.is_control() + || (c.is_ascii() && !(c.is_ascii_alphanumeric() || matches!(c, '-' | '.'))) + }) + { + return None; + } + let url = Url::parse(&format!("https://{bare}/")).ok()?; + let Host::Domain(domain) = url.host()? else { + return None; + }; + (domain.split('.').all(|label| { + !label.is_empty() + && label.len() <= MAX_DNS_LABEL_BYTES + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }) && public_target(&url)) + .then_some(url) +} + +fn original_terms(text: &str, terms: &[String]) -> String { + let mut words = text.split_whitespace(); + terms + .iter() + .filter_map(|term| words.find(|word| word.to_lowercase() == *term)) + .collect::<Vec<_>>() + .join(" ") +} + +struct StandIn(String); + +impl StandIn { + fn new<'a>(results: impl IntoIterator<Item = (&'a Url, &'a str)>) -> Self { + let mut html = String::from("<main>"); + for (url, title) in results { + let _ = write!( + html, + "<article><h2><a href=\"{}\">{}</a></h2></article>", + escape_html(url.as_str()), + escape_html(title) + ); + } + html.push_str("</main>"); + Self(html) + } +} + +fn escape_html(text: &str) -> String { + let mut escaped = String::new(); + for ch in text.chars() { + match ch { + '&' => escaped.push_str("&amp;"), + '<' => escaped.push_str("&lt;"), + '>' => escaped.push_str("&gt;"), + '"' => escaped.push_str("&quot;"), + _ => escaped.push(ch), + } + } + escaped +} + +impl ResultsSource for StandIn { + fn load(&self, url: Url) -> Reading<Result<ResultsPage, Failure>> { + let html = self.0.clone(); + Box::pin(async move { + Ok(ResultsPage { + html, + url, + truncated: false, + }) + }) + } +} + +struct DirectIo { + routes: RouteSource, + public: PublicIo, +} + +impl Fetcher for DirectIo { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + let routes = self.routes.clone(); + let fetch = self.public.fetch(request); + Box::pin(async move { + // On the current-thread runtime, route publication cannot interleave + // between this check and the reader taking its route snapshot. + if routes.route() != PublicRoute::Direct { + return Err(Failure::Unavailable); + } + fetch.await + }) + } +} + +fn on_direct_route<T>( + route: PublicRoute, + start: impl FnOnce() -> Result<T, Error>, +) -> Result<T, Error> { + if route != PublicRoute::Direct { + return Err(Error::Proxy); + } + start() +} + +fn print_lines( + output: &mut impl Write, + lines: impl IntoIterator<Item = String>, +) -> Result<(), Error> { + for line in lines { + writeln!(output, "{line}").map_err(|_| Error::Output)?; + } + output.flush().map_err(|_| Error::Output) +} + +async fn live( + request: MapRequest, + results: StandIn, + opens: Vec<&str>, + output: &mut impl Write, +) -> Result<Outcome, Error> { + print_lines(output, [intro(&request.query)])?; + let runtime = Handle::current(); + let routes = RouteSource::new(&runtime); + routes.set_app_proxy(None); + let interrupt = tokio::signal::ctrl_c(); + tokio::pin!(interrupt); + let started = Instant::now(); + tokio::select! { + biased; + signal = &mut interrupt => { + signal.map_err(|_| Error::Interrupt)?; + let end = Change::End { seq: 0, outcome: Outcome::Cancelled, elapsed_ms: elapsed_ms(started) }; + print_lines(output, Printer::default().lines(&end, started.elapsed(), Counts::default()))?; + return Ok(Outcome::Cancelled); + } + () = routes.settled() => {} + } + + let changed = routes.changed(); + let (driver, changes) = on_direct_route(routes.route(), || { + let reader = PublicReader::new(ReaderLimits::default(), routes.clone()); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(DirectIo { + routes, + public: PublicIo::new(&reader), + }), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + Driver::start(request, io, &runtime).map_err(Error::Refused) + })?; + stream(&driver, changes, changed, interrupt, output, opens).await +} + +fn elapsed_ms(started: Instant) -> u32 { + u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX) +} + +async fn stream( + driver: &Driver, + mut changes: tokio::sync::mpsc::Receiver<Change>, + mut route: watch::Receiver<PublicRoute>, + mut interrupt: impl Future<Output = io::Result<()>> + Unpin, + output: &mut impl Write, + opens: Vec<&str>, +) -> Result<Outcome, Error> { + let started = Instant::now(); + let mut printer = Printer::default(); + let mut cancelling = false; + let mut watching = true; + let mut interrupted_by = None; + let mut opens = opens.into_iter(); + let mut open_failed = false; + let mut open_started = None; + loop { + let mut change = tokio::select! { + biased; + signal = &mut interrupt, if !cancelling => { + interrupted_by = signal.err().map(|_| Error::Interrupt); + driver.cancel(); + if open_started.is_some() { + return interrupted_by.map_or(Ok(Outcome::Cancelled), Err); + } + cancelling = true; + continue; + } + left = route.wait_for(|class| *class != PublicRoute::Direct), if !cancelling && watching => { + if left.is_err() { + watching = false; + continue; + } + interrupted_by = Some(Error::Proxy); + driver.cancel(); + if open_started.is_some() { + return Err(Error::Proxy); + } + cancelling = true; + continue; + } + change = changes.recv() => change.ok_or(Error::Stream)?, + }; + if let Change::End { outcome, .. } = &mut change { + if cancelling { + *outcome = Outcome::Cancelled; + } + let outcome = *outcome; + print_lines( + output, + printer.lines(&change, started.elapsed(), driver.counts()), + )?; + if outcome != Outcome::Done || cancelling { + return interrupted_by.map_or(Ok(outcome), Err); + } + open_started = start_open(driver, &printer, &mut opens, &mut open_failed, output)?; + if open_started.is_none() { + return if open_failed { + Err(Error::OpenFailed) + } else { + Ok(outcome) + }; + } + continue; + } + if let Change::Opened { result, .. } = change { + if let Some((time, before)) = open_started.take() { + let after = driver.counts(); + let status = match result { + OpenResult::Read => "read".to_owned(), + OpenResult::Refused { failure } => { + open_failed = true; + format!("refused ({})", printer::failure_text(failure)) + } + }; + print_lines( + output, + [format!( + "Opened {status} {}ms reads {} bytes {}", + time.elapsed().as_millis(), + after.fetches.saturating_sub(before.fetches), + after.bytes.saturating_sub(before.bytes), + )], + )?; + } + open_started = start_open(driver, &printer, &mut opens, &mut open_failed, output)?; + if open_started.is_none() { + return if open_failed { + Err(Error::OpenFailed) + } else { + Ok(Outcome::Done) + }; + } + continue; + } + if !cancelling { + let lines = printer.lines(&change, started.elapsed(), Counts::default()); + if !lines.is_empty() { + print_lines(output, lines)?; + } + } + } +} + +fn start_open<'a>( + driver: &Driver, + printer: &Printer, + opens: &mut impl Iterator<Item = &'a str>, + failed: &mut bool, + output: &mut impl Write, +) -> Result<Option<(Instant, Counts)>, Error> { + for label in opens { + let before = driver.counts(); + let started = Instant::now(); + let message = match printer.section(label) { + Ok((slot, id)) => match driver.open(slot, id) { + Ok(()) => return Ok(Some((started, before))), + Err(refusal) => format!("Open refused ({refusal:?})"), + }, + Err(reason) => format!("Open refused ({reason})"), + }; + *failed = true; + print_lines(output, [message])?; + } + Ok(None) +} + +fn execute(arguments: &[String]) -> Result<Outcome, Error> { + let options = Options::parse(arguments)?; + let opens = options.opens.clone(); + let (request, results) = options.prepare()?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| Error::Runtime)?; + let result = runtime.block_on(live(request, results, opens, &mut io::stdout().lock())); + runtime.shutdown_background(); + result +} + +pub(crate) fn run(arguments: &[String]) -> i32 { + std::panic::set_hook(Box::new(|_| { + let _ = writeln!(io::stderr(), "Unexpected map runtime failure."); + })); + match execute(arguments) { + Ok(Outcome::Done) => 0, + Ok(Outcome::Cancelled) => 130, + Ok(Outcome::Failed { .. }) => 1, + Err(error) => { + let _ = writeln!(io::stderr(), "{error}"); + if error.usage() { + 2 + } else { + 1 + } + } + } +} diff --git a/xtask/src/map_try/printer.rs b/xtask/src/map_try/printer.rs new file mode 100644 index 000000000..adb650458 --- /dev/null +++ b/xtask/src/map_try/printer.rs @@ -0,0 +1,315 @@ +use std::{collections::BTreeMap, time::Duration}; + +use zephium_map_driver::{ + wire::{Change, Entry, Failure, Outcome, Place, Row, StartRefusal, Tier}, + Counts, +}; + +const COLUMNS: usize = 100; +const PLACE_INTERVAL: Duration = Duration::from_millis(500); +const TABLE_DIVIDER: &str = " | "; +const TABLE_CELL: usize = (COLUMNS - TABLE_DIVIDER.len()) / 2; +const ELLIPSIS: char = '…'; + +#[derive(Default)] +struct Slot { + printed: Option<Duration>, + labels: BTreeMap<String, String>, + sections: Vec<(String, String)>, +} + +#[derive(Default)] +pub(super) struct Printer { + slots: [Slot; super::MAX_SITES], +} + +impl Printer { + pub(super) fn section(&self, label: &str) -> Result<(u8, &str), &'static str> { + let (side, label) = match label.trim().split_once("::") { + Some(("left", label)) => (Some(0), label.trim()), + Some(("right", label)) => (Some(1), label.trim()), + _ => (None, label.trim()), + }; + let mut matches = self + .slots + .iter() + .enumerate() + .filter(|(i, _)| side.is_none_or(|side| *i == side)) + .flat_map(|(index, slot)| { + slot.sections.iter().filter_map(move |(id, name)| { + name.eq_ignore_ascii_case(label) + .then_some((index as u8, id.as_str())) + }) + }); + let section = matches.next().ok_or("unknown label")?; + if matches.next().is_some() { + return Err("ambiguous label"); + } + Ok(section) + } + + pub(super) fn lines( + &mut self, + change: &Change, + elapsed: Duration, + counts: Counts, + ) -> Vec<String> { + match change { + Change::FirstLayer { + official, + social, + organic, + also, + .. + } => { + let mut line = format!("First layer {organic} organic"); + if let Some(official) = official { + line.push_str(&format!( + " official {} ({})", + official.title, official.site + )); + } + if !social.is_empty() { + let networks = social + .iter() + .map(|network| format!("{network:?}")) + .collect::<Vec<_>>(); + line.push_str(&format!(" social {}", networks.join(", "))); + } + let mut lines = vec![clip(&line, COLUMNS)]; + lines.extend(also.iter().map(|result| { + clip( + &format!(" {:?} {} ({})", result.kind, result.title, result.host), + COLUMNS, + ) + })); + lines + } + Change::Place { + slot, + place, + complete, + .. + } => { + let Some(state) = self.slots.get_mut(usize::from(*slot)) else { + return Vec::new(); + }; + state.labels = entries(place) + .map(|entry| (entry.id.clone(), entry.label.clone())) + .collect(); + state.sections = place + .sections + .iter() + .filter(|e| !e.menu_only) + .map(|entry| (entry.id.clone(), entry.label.clone())) + .collect(); + if *complete + || state + .printed + .is_none_or(|last| elapsed.saturating_sub(last) > PLACE_INTERVAL) + { + state.printed = Some(elapsed); + place_lines(*slot, place) + } else { + Vec::new() + } + } + Change::PlaceFailed { slot, failure, .. } => { + if let Some(state) = self.slots.get_mut(usize::from(*slot)) { + state.labels.clear(); + state.sections.clear(); + state.printed = Some(elapsed); + } + vec![format!( + "Place {} failed {}", + u16::from(*slot) + 1, + failure_text(*failure) + )] + } + Change::Compare { rows, .. } => { + let mut lines = vec![table_line("Left", "Right")]; + lines.extend(rows.iter().map(|row| self.row(row))); + lines + } + Change::End { + outcome, + elapsed_ms, + .. + } => vec![end_line(*outcome, *elapsed_ms, counts)], + Change::Opened { .. } => Vec::new(), + } + } + + fn row(&self, row: &Row) -> String { + let label = |slot: &Slot, id: &Option<String>| { + id.as_ref() + .and_then(|id| slot.labels.get(id)) + .map_or_else(|| "-".into(), |label| clip(label, TABLE_CELL)) + }; + table_line( + &label(&self.slots[0], &row.left), + &label(&self.slots[1], &row.right), + ) + } +} + +pub(super) fn intro(query: &str) -> String { + clip(&format!("Stand-in results page for {query}"), COLUMNS) +} + +pub(super) fn refusal(reason: StartRefusal) -> &'static str { + match reason { + StartRefusal::NotAMap => { + "Map refused This query does not describe a place or a comparison." + } + StartRefusal::UnsupportedEngine => "Map refused The search engine is unsupported.", + StartRefusal::Invalid => "Map refused The query is invalid or exceeds a limit.", + } +} + +pub(super) fn failure_text(failure: Failure) -> &'static str { + match failure { + Failure::Cancelled => "cancelled", + Failure::Blocked => "access blocked", + Failure::Challenge => "site requires a challenge", + Failure::Consent => "site requires consent", + Failure::NoResults => "no usable results", + Failure::Unreadable => "page unreadable", + Failure::Unavailable => "page unavailable", + Failure::Timeout => "read timed out", + Failure::Limit => "read limit reached", + Failure::Missing => "page or result missing", + } +} + +fn end_line(outcome: Outcome, elapsed_ms: u32, counts: Counts) -> String { + let outcome = match outcome { + Outcome::Done => "Done".to_owned(), + Outcome::Cancelled => "Cancelled".to_owned(), + Outcome::Failed { failure } => format!("Failed ({})", failure_text(failure)), + }; + let suffix = format!( + " {elapsed_ms}ms reads {} data {:.1} MB renders wanted {}", + counts.fetches, + counts.bytes as f64 / 1_000_000.0, + counts.render_unavailable + ); + format!("{}{suffix}", clip(&outcome, COLUMNS - suffix.len())) +} + +fn table_line(left: &str, right: &str) -> String { + let pad = " ".repeat(TABLE_CELL.saturating_sub(columns(left))); + format!("{left}{pad}{TABLE_DIVIDER}{right}") +} + +fn entries(place: &Place) -> impl Iterator<Item = &Entry> { + place + .sections + .iter() + .flat_map(|section| std::iter::once(section).chain(&section.children)) +} + +fn place_lines(slot: u8, place: &Place) -> Vec<String> { + let heading = format!("Place {} ", u16::from(slot) + 1); + let (title, host) = pair( + &place.title, + &place.host, + COLUMNS - heading.len() - " ()".len(), + ); + let mut lines = vec![format!("{heading}{title} ({host})")]; + for tier in [Tier::Primary, Tier::Secondary, Tier::Action] { + let mut sections = place + .sections + .iter() + .filter(|entry| entry.tier == tier) + .peekable(); + if tier != Tier::Primary && sections.peek().is_some() { + lines.push(format!(" --- {tier:?} ---")); + } + for section in sections { + lines.push(entry_line(section, place.focus.as_deref(), " ")); + for child in &section.children { + lines.push(entry_line(child, place.focus.as_deref(), " ")); + } + } + } + lines +} + +fn entry_line(entry: &Entry, focus: Option<&str>, indent: &str) -> String { + let mark = if Some(entry.id.as_str()) == focus { + "* " + } else { + "" + }; + if entry.menu_only { + return format!( + "{indent}{mark}{} ▸", + clip(&entry.label, COLUMNS - indent.len() - mark.len() - 2) + ); + } + let off_site = if entry.off_site { " [off-site]" } else { "" }; + let more = if entry.more { " [more]" } else { "" }; + let available = COLUMNS - indent.len() - mark.len() - off_site.len() - more.len() - " ".len(); + let display = entry + .host + .as_ref() + .map(|host| format!("{host}{}", entry.path)); + let (label, path) = pair( + &entry.label, + display.as_deref().unwrap_or(&entry.path), + available, + ); + format!("{indent}{mark}{label} {path}{off_site}{more}") +} + +fn pair(left: &str, right: &str, available: usize) -> (String, String) { + let right_min = columns(right).min(available / 2); + let left = clip(left, available - right_min); + let right = clip(right, available - columns(&left)); + (left, right) +} + +fn char_columns(ch: char) -> usize { + if ch.is_ascii() { + 1 + } else { + 2 + } +} + +fn columns(text: &str) -> usize { + text.chars().map(char_columns).sum() +} + +fn clip(text: &str, limit: usize) -> String { + let text: String = zephium_map::clean_text(text) + .chars() + .map(|ch| { + if ch.is_control() || ch.is_whitespace() { + ' ' + } else { + ch + } + }) + .collect(); + if columns(&text) <= limit { + return text; + } + let Some(available) = limit.checked_sub(char_columns(ELLIPSIS)) else { + return String::new(); + }; + let mut used = 0; + let mut out: String = text + .chars() + .take_while(|ch| { + used += char_columns(*ch); + used <= available + }) + .collect(); + out.push(ELLIPSIS); + out +} + +#[cfg(test)] +mod tests; diff --git a/xtask/src/map_try/printer/tests.rs b/xtask/src/map_try/printer/tests.rs new file mode 100644 index 000000000..1e8124785 --- /dev/null +++ b/xtask/src/map_try/printer/tests.rs @@ -0,0 +1,306 @@ +use super::*; +use zephium_map_driver::wire::{Confidence, Network, Official}; + +fn entry(id: &str, label: &str, path: &str) -> Entry { + Entry { + menu_only: false, + id: id.into(), + tier: Tier::Primary, + label: label.into(), + role: None, + group: None, + off_site: false, + open: false, + host: None, + path: path.into(), + read: None, + children: Vec::new(), + more: false, + } +} + +fn place(title: &str, host: &str, sections: Vec<Entry>) -> Place { + Place { + title: title.into(), + site: host.into(), + host: host.into(), + sections, + focus: None, + social: Vec::new(), + notes: Default::default(), + } +} + +fn changed(slot: u8, place: Place, complete: bool) -> Change { + Change::Place { + seq: 1, + slot, + place, + confidence: Confidence::High, + stale: false, + complete, + } +} + +#[test] +fn comparison_sides_disambiguate_an_open_label() { + let mut printer = Printer::default(); + for (slot, id) in [(0, "first"), (1, "second")] { + let mut rows = vec![entry(id, "Pricing", "/pricing")]; + if slot == 1 { + rows.push(entry("docs", "Docs", "/docs")); + } + printer.lines( + &changed(slot, place("Site", "example.com", rows), true), + Duration::ZERO, + Counts::default(), + ); + } + assert_eq!(printer.section("Pricing"), Err("ambiguous label")); + assert_eq!(printer.section("left::Pricing"), Ok((0, "first"))); + assert_eq!(printer.section("right::Pricing"), Ok((1, "second"))); + assert_eq!(printer.section("Docs"), Ok((1, "docs"))); + assert_eq!(printer.section("left::Docs"), Err("unknown label")); +} + +#[test] +fn place_stream_golden() { + let first = Change::FirstLayer { + seq: 0, + official: Some(Official { + title: "Stripe".into(), + site: "stripe.com".into(), + }), + social: vec![Network::GitHub], + organic: 1, + also: Vec::new(), + }; + let mut place = place( + "Stripe", + "stripe.com", + vec![ + Entry { + tier: Tier::Secondary, + ..entry("about", "About", "/about") + }, + Entry { + children: vec![entry("tiers", "Tiers", "/pricing/tiers")], + more: true, + ..entry("pricing", "Pricing", "/pricing") + }, + Entry { + off_site: true, + ..entry("docs", "Docs", "/docs") + }, + ], + ); + place.focus = Some("tiers".into()); + let update = changed(0, place, true); + let end = Change::End { + seq: 2, + outcome: Outcome::Done, + elapsed_ms: 650, + }; + let counts = Counts { + fetches: 2, + bytes: 512, + render_unavailable: 1, + ..Counts::default() + }; + let mut printer = Printer::default(); + assert_eq!( + intro("Stripe Pricing"), + "Stand-in results page for Stripe Pricing" + ); + let mut lines = Vec::new(); + for change in [first, update, end] { + lines.extend(printer.lines(&change, Duration::ZERO, counts)); + } + assert_eq!( + lines.join("\n"), + concat!( + "First layer 1 organic official Stripe (stripe.com) social GitHub\n", + "Place 1 Stripe (stripe.com)\n", + " Pricing /pricing [more]\n", + " * Tiers /pricing/tiers\n", + " Docs /docs [off-site]\n", + " --- Secondary ---\n", + " About /about\n", + "Done 650ms reads 2 data 0.0 MB renders wanted 1" + ) + ); +} + +#[test] +fn comparison_uses_current_labels_for_each_side_including_throttled_updates() { + let mut printer = Printer::default(); + let print = |printer: &mut Printer, change: &Change| { + printer.lines(change, Duration::ZERO, Counts::default()) + }; + let left = changed( + 0, + place( + "Figma", + "figma.com", + vec![entry("price", "Plans", "/pricing")], + ), + false, + ); + let right = changed( + 1, + place( + "Sketch", + "sketch.com", + vec![ + entry("price", "Pricing", "/pricing"), + Entry { + children: vec![entry("help", "Tutorials", "/help/learn")], + ..entry("docs", "Documentation", "/docs") + }, + ], + ), + false, + ); + let updated_left = changed( + 0, + place( + "Figma", + "figma.com", + vec![entry("price", "Plans and Pricing", "/pricing")], + ), + false, + ); + assert!(!print(&mut printer, &left).is_empty()); + assert!(!print(&mut printer, &right).is_empty()); + assert!(print(&mut printer, &updated_left).is_empty()); + let compare = Change::Compare { + seq: 3, + rows: vec![ + Row { + role: None, + label: "Prices".into(), + left: Some("price".into()), + right: Some("price".into()), + }, + Row { + role: None, + label: "Learn".into(), + left: None, + right: Some("help".into()), + }, + ], + }; + assert_eq!( + print(&mut printer, &compare).join("\n"), + concat!( + "Left | Right\n", + "Plans and Pricing | Pricing\n", + "- | Tutorials", + ) + ); +} + +#[test] +fn failed_side_and_refusals_use_plain_words() { + let failed = Change::PlaceFailed { + seq: 2, + slot: 1, + failure: Failure::Challenge, + }; + let mut printer = Printer::default(); + assert_eq!( + printer.lines(&failed, Duration::ZERO, Counts::default()), + ["Place 2 failed site requires a challenge"] + ); + assert_eq!( + refusal(StartRefusal::NotAMap), + "Map refused This query does not describe a place or a comparison." + ); + assert_eq!( + refusal(StartRefusal::Invalid), + "Map refused The query is invalid or exceeds a limit." + ); + assert_eq!( + refusal(StartRefusal::UnsupportedEngine), + "Map refused The search engine is unsupported." + ); + let end = Change::End { + seq: 3, + outcome: Outcome::Cancelled, + elapsed_ms: 4, + }; + assert_eq!( + printer.lines(&end, Duration::ZERO, Counts::default()), + ["Cancelled 4ms reads 0 data 0.0 MB renders wanted 0"] + ); +} + +#[test] +fn throttles_partial_places_at_the_interval_and_prints_complete_immediately() { + let mut printer = Printer::default(); + let place = place("Figma", "figma.com", Vec::new()); + let partial = changed(0, place.clone(), false); + let complete = changed(0, place, true); + let print = |printer: &mut Printer, change: &Change, time| { + printer.lines(change, time, Counts::default()) + }; + assert!(!print(&mut printer, &partial, Duration::ZERO).is_empty()); + assert!(print(&mut printer, &partial, PLACE_INTERVAL).is_empty()); + let just_past = PLACE_INTERVAL + Duration::from_nanos(1); + assert!(!print(&mut printer, &partial, just_past).is_empty()); + assert!(!print(&mut printer, &complete, just_past).is_empty()); +} + +#[test] +fn clips_to_the_column_limit_and_removes_terminal_controls() { + assert_eq!(clip(&"a".repeat(COLUMNS), COLUMNS), "a".repeat(COLUMNS)); + assert_eq!( + clip(&"a".repeat(COLUMNS + 1), COLUMNS), + format!("{}…", "a".repeat(COLUMNS - 2)) + ); + assert_eq!(clip("Test\x1b[2J\u{202e}\n界", COLUMNS), "Test [2J 界"); + let long = "界".repeat(COLUMNS); + let place = place( + &long, + "figma.com", + vec![Entry { + off_site: true, + more: true, + ..entry("long", &long, &format!("/{long}")) + }], + ); + let lines = place_lines(0, &place); + assert!(lines.iter().all(|line| columns(line) <= COLUMNS)); + assert!(lines[0].ends_with("… (figma.com)")); + assert!(lines[1].ends_with("… [off-site] [more]")); + let mut printer = Printer::default(); + for slot in [0, 1] { + printer.lines( + &changed(slot, place.clone(), true), + Duration::ZERO, + Counts::default(), + ); + } + let line = printer.row(&Row { + role: None, + label: "Long".into(), + left: Some("long".into()), + right: Some("long".into()), + }); + assert!(columns(&line) <= COLUMNS); + assert_eq!(line.matches(ELLIPSIS).count(), 2); + let end = end_line( + Outcome::Failed { + failure: Failure::Challenge, + }, + u32::MAX, + Counts { + fetches: u32::MAX, + bytes: u64::MAX, + render_unavailable: u32::MAX, + ..Counts::default() + }, + ); + assert!(columns(&end) <= COLUMNS); + assert!(end.ends_with("renders wanted 4294967295")); +} diff --git a/xtask/src/map_try/tests.rs b/xtask/src/map_try/tests.rs new file mode 100644 index 000000000..c0d4e4180 --- /dev/null +++ b/xtask/src/map_try/tests.rs @@ -0,0 +1,464 @@ +use super::*; +use zephium_map::{read_results, Doc, DocLimits, ResultsRead}; + +fn args(values: &[&str]) -> Vec<String> { + values.iter().map(|value| (*value).to_owned()).collect() +} + +#[test] +fn accepts_one_or_two_public_sites_in_order_and_passes_private_through() { + let arguments = args(&["Stripe Pricing", "--site", "Stripe.COM.", "--private"]); + let (request, _) = Options::parse(&arguments).unwrap().prepare().unwrap(); + assert_eq!(request.query, "Stripe Pricing"); + assert!(request.private); + let arguments = args(&[ + "Figma vs Sketch", + "--site", + "figma.com", + "--site", + "sketch.com", + ]); + let options = Options::parse(&arguments).unwrap(); + assert_eq!(options.sites[0].as_str(), "https://figma.com/"); + assert_eq!(options.sites[1].as_str(), "https://sketch.com/"); + assert!(!options.prepare().unwrap().0.private); + assert_eq!( + site_url("bücher.de").unwrap().host_str(), + Some("xn--bcher-kva.de") + ); + assert_eq!(site_url("stripe.com.").unwrap().path(), "/"); +} + +#[test] +fn accepts_repeated_open_labels_and_enforces_their_bounds() { + let mut arguments = args(&[ + "Stripe", + "--site", + "stripe.com", + "--open", + "Docs", + "--open", + "Pricing", + ]); + assert_eq!( + Options::parse(&arguments).unwrap().opens, + ["Docs", "Pricing"] + ); + arguments.truncate(3); + for _ in 0..MAX_OPEN_LABELS { + arguments.extend(args(&["--open", "Docs"])); + } + assert!(Options::parse(&arguments).is_ok()); + arguments.extend(args(&["--open", "Docs"])); + assert_eq!(Options::parse(&arguments).err(), Some(Error::BadOpenLabel)); + arguments.truncate(4); + for label in [ + "".to_owned(), + "Docs\nPricing".to_owned(), + "x".repeat(MAX_TEXT_BYTES + 1), + ] { + arguments.push(label); + assert_eq!(Options::parse(&arguments).err(), Some(Error::BadOpenLabel)); + arguments.pop(); + } + assert_eq!(Options::parse(&arguments).err(), Some(Error::BadOpenLabel)); +} + +#[test] +fn refuses_malformed_options_and_arity() { + for (raw, error) in [ + (&[][..], Error::MissingQuery), + (&["--site", "stripe.com"], Error::MissingQuery), + (&["Stripe"], Error::MissingSite), + (&["Stripe", "--site"], Error::MissingSite), + (&["Stripe", "--site", "--private"], Error::MissingSite), + ( + &["Stripe", "--site", "stripe.com", "--help"], + Error::UnexpectedOption, + ), + ( + &["Stripe", "--site", "stripe.com", "--private", "--private"], + Error::UnexpectedOption, + ), + ( + &["Figma", "vs", "Sketch", "--site", "figma.com"], + Error::UnexpectedOption, + ), + ( + &["Stripe", "--site", "stripe.com", "--site", "figma.com"], + Error::PlaceArity, + ), + ( + &["Figma vs Sketch", "--site", "figma.com"], + Error::CompareArity, + ), + ( + &[ + "A vs B", + "--site", + "stripe.com", + "--site", + "figma.com", + "--site", + "sketch.com", + ], + Error::TooManySites, + ), + ( + &["2 + 2", "--site", "stripe.com"], + Error::Refused(StartRefusal::NotAMap), + ), + ( + &["", "--site", "stripe.com"], + Error::Refused(StartRefusal::Invalid), + ), + ] { + let arguments = args(raw); + assert_eq!( + Options::parse(&arguments).and_then(Options::prepare).err(), + Some(error), + "{raw:?}" + ); + } +} + +#[test] +fn rejects_each_non_public_or_non_bare_host_shape() { + for host in [ + "", + "https://stripe.com", + "stripe.com/", + "stripe.com/pricing", + "stripe.com:443", + "stripe.com:8443", + "user@stripe.com", + "user:password@stripe.com", + "stripe.com?x", + "stripe.com#here", + "stripe.com\\", + " stripe.com", + "stripe.com\n", + "stri\tpe.com", + "127.0.0.1", + "8.8.8.8", + "0x08080808", + "[2001:4860:4860::8888]", + "localhost", + "test.localhost", + "test.local", + "test.internal", + "stripe", + "stripe.invalid", + "test.onion", + "test.arpa", + "test.alt", + "com", + "co.uk", + "stripe%2ecom", + "stripe..com", + "stripe.com..", + "-stripe.com", + "stripe-.com", + "stripe_.com", + ] { + let arguments = args(&["Stripe", "--site", host]); + assert_eq!( + Options::parse(&arguments).err(), + Some(Error::BadHost), + "{host:?}" + ); + } + + let max_label = "a".repeat(MAX_DNS_LABEL_BYTES); + assert!(site_url(&format!("{max_label}.com")).is_some()); + assert!(site_url(&format!("{max_label}a.com")).is_none()); + let max_host = format!("{max_label}.{max_label}.{max_label}.{}.com", "a".repeat(57)); + assert_eq!(max_host.len(), MAX_HOST_BYTES); + assert!(site_url(&max_host).is_some()); + assert!(site_url(&format!("a{max_host}")).is_none()); +} + +#[test] +fn query_refusal_uses_the_engines_byte_and_term_limits() { + use zephium_map::query::{MAX_QUERY_BYTES, MAX_QUERY_TERMS}; + for query in [ + "a".repeat(MAX_QUERY_BYTES + 1), + "a ".repeat(MAX_QUERY_TERMS + 1), + ] { + let arguments = args(&[&query, "--site", "stripe.com"]); + assert_eq!( + Options::parse(&arguments).unwrap().prepare().err(), + Some(Error::Refused(StartRefusal::Invalid)) + ); + } +} + +#[tokio::test] +async fn the_engine_reads_one_and_two_stand_in_results_in_order() { + for (values, expected) in [ + ( + &["Stripe Pricing", "--site", "stripe.com"][..], + &[("Stripe", "https://stripe.com/")][..], + ), + ( + &[ + "Figma vs Sketch", + "--site", + "figma.com", + "--site", + "sketch.com", + ][..], + &[ + ("Figma", "https://figma.com/"), + ("Sketch", "https://sketch.com/"), + ][..], + ), + ] { + let arguments = args(values); + let (request, stand_in) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let url = request + .engine + .configured_search(&request.query, "") + .unwrap(); + let page = stand_in.load(url).await.unwrap(); + let doc = + Doc::from_html(&page.url, page.html.as_bytes(), None, DocLimits::RESULTS).unwrap(); + let query = read_query(&request.query).unwrap(); + let ResultsRead::FirstLayer { layer } = read_results(request.engine, None, &query, &doc) + else { + panic!("the stand-in must parse as results"); + }; + assert!(layer.social.is_empty()); + let actual = layer + .organic + .iter() + .map(|hit| { + assert!(hit.snippet.is_none()); + assert!(hit.sitelinks.is_empty()); + (hit.title.as_str(), hit.url.as_str()) + }) + .collect::<Vec<_>>(); + assert_eq!(actual, expected); + } +} + +#[test] +fn injected_non_direct_route_exits_before_creating_any_io() { + for route in [PublicRoute::Proxied, PublicRoute::Unsupported] { + assert_eq!( + on_direct_route::<()>(route, || panic!("I/O started")), + Err(Error::Proxy) + ); + } + assert_eq!(on_direct_route(PublicRoute::Direct, || Ok(7)), Ok(7)); + assert_eq!( + Error::Proxy.to_string(), + "The reader refuses to go around a proxy. A direct route is required." + ); +} + +#[tokio::test] +async fn an_interrupt_cancels_the_driver_and_prints_its_end() { + struct NoFetch; + impl Fetcher for NoFetch { + fn fetch(&self, _: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + panic!("the cancelled driver must not start a fetch"); + } + } + + for buffered in [false, true] { + let arguments = args(&["Stripe Pricing", "--site", "stripe.com"]); + let (request, results) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(NoFetch), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, mut changes) = Driver::start(request, io, &Handle::current()).unwrap(); + if buffered { + let (tx, rx) = tokio::sync::mpsc::channel(1); + tx.try_send(Change::End { + seq: 0, + outcome: Outcome::Done, + elapsed_ms: 0, + }) + .unwrap(); + changes = rx; + } + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::ready(Ok(())), + &mut output, + vec!["Pricing"], + ) + .await; + assert_eq!(outcome, Ok(Outcome::Cancelled)); + assert_eq!(driver.counts(), Counts::default()); + let printed = std::str::from_utf8(&output).unwrap(); + assert_eq!(printed.lines().count(), 1); + assert!(printed.starts_with("Cancelled ")); + assert!(printed.ends_with("ms reads 0 data 0.0 MB renders wanted 0\n")); + } +} + +#[tokio::test] +async fn a_closed_route_watch_is_not_a_proxy() { + struct Refuse; + impl Fetcher for Refuse { + fn fetch(&self, _: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + Box::pin(async { Err(Failure::Unavailable) }) + } + } + + let arguments = args(&["Stripe Pricing", "--site", "stripe.com"]); + let (request, results) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(Refuse), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (route, direct) = watch::channel(PublicRoute::Direct); + drop(route); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::pending(), + &mut output, + Vec::new(), + ) + .await; + assert!(outcome.is_ok(), "{outcome:?}"); + let printed = std::str::from_utf8(&output).unwrap(); + assert!(printed.lines().count() > 1, "{printed}"); +} + +#[tokio::test] +async fn labelled_opens_after_end_reprint_the_card_and_each_read_cost() { + struct Fixture; + impl Fetcher for Fixture { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + Box::pin(async move { + let html = match request.url.path() { + "/" => "<nav><a href='/docs'>Docs</a><a href='/pricing'>Pricing</a></nav>", + "/docs" => "<h2 id='first'>First guide</h2>", + "/pricing" => "<h2 id='teams'>Team plans</h2>", + _ => return Err(Failure::Missing), + }; + Ok(FetchResult { + final_url: request.url, + content_type: "text/html".into(), + charset: None, + bytes: html.as_bytes().to_vec(), + truncated: false, + }) + }) + } + } + let arguments = args(&[ + "Stripe", + "--site", + "stripe.com", + "--open", + "Docs", + "--open", + "Pricing", + ]); + let options = Options::parse(&arguments).unwrap(); + let opens = options.opens.clone(); + let (request, results) = options.prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(Fixture), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + assert_eq!( + stream( + &driver, + changes, + direct, + std::future::pending(), + &mut output, + opens + ) + .await, + Ok(Outcome::Done) + ); + let printed = std::str::from_utf8(&output).unwrap(); + let end = printed.find("Done").unwrap(); + let docs = printed.find("First guide").unwrap(); + let plans = printed.find("Team plans").unwrap(); + assert!(end < docs && docs < plans); + let opens: Vec<_> = printed + .lines() + .filter(|line| line.starts_with("Opened read")) + .collect(); + assert_eq!(opens.len(), 2); + assert!(opens.iter().all(|line| line.contains("reads 1 bytes "))); +} + +#[tokio::test] +async fn failed_opens_affect_status_and_remaining_opens_still_run() { + struct Fixture; + impl Fetcher for Fixture { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + Box::pin(async move { + let body = match request.url.path() { + "/" => "<nav><a href='/docs'>Docs</a><a href='/pricing'>Pricing</a></nav>", + "/pricing" => "<h2 id='annual'>Annual</h2>", + "/docs" => return Err(Failure::Timeout), + _ => return Err(Failure::Missing), + }; + Ok(FetchResult { + final_url: request.url, + bytes: body.as_bytes().into(), + content_type: "text/html".into(), + charset: None, + truncated: false, + }) + }) + } + } + for labels in [ + vec!["Unknown", "Pricing"], + vec!["Docs", "Pricing"], + vec!["Pricing", "Pricing"], + ] { + let args = args(&["Stripe", "--site", "stripe.com"]); + let (request, results) = Options::parse(&args).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(Fixture), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::pending(), + &mut output, + labels, + ) + .await; + assert!(matches!(outcome, Err(_) | Ok(Outcome::Failed { .. }))); + let printed = String::from_utf8(output).unwrap(); + assert!(printed.contains("Opened read")); + assert!(printed.contains("refused")); + } +}