The headless browser for AI agents and web scraping
fix(browser): navigation chain limit adjustable and correctly named
aech7aec2e8d66d5
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex e1aa4ae6..87bf3e00 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -264,6 +264,8 @@ pub struct Page {/// 50-second navigation is not silently cut off by the process default./// Pages without an override retain the environment-configurable default.navigation_timeout: Option<std::time::Duration>,+ /// Optional per-page cap. Pages without a value keep the default.+ navigation_chain_limit: Option<usize>,/// Navigation history for Page.getNavigationHistory / navigateToHistoryEntry./// Entries are URLs in visit order; `history_index` is the current position./// Pushed on every successful navigation; truncated on goBack -> new nav.@@ -310,6 +312,10 @@ fn max_live_frames() -> usize {.unwrap_or(64)}+/// The first navigation counts. The low default stops a page that resets+/// `location` on every load.+const DEFAULT_NAVIGATION_CHAIN_LIMIT: usize = 10;+fn default_navigation_timeout() -> std::time::Duration {navigation_timeout_from_env_value(std::env::var("OBSCURA_NAV_TIMEOUT_MS").ok().as_deref())}@@ -321,6 +327,19 @@ fn navigation_timeout_from_env_value(value: Option<&str>) -> std::time::Durationstd::time::Duration::from_millis(milliseconds)}+fn default_navigation_chain_limit() -> usize {+ navigation_chain_limit_from_env_value(std::env::var("OBSCURA_NAV_CHAIN_LIMIT").ok().as_deref())+}++fn navigation_chain_limit_from_env_value(value: Option<&str>) -> usize {+ // Only an unreadable value falls back to the default, so+ // `OBSCURA_NAV_CHAIN_LIMIT=0` and `set_navigation_chain_limit(0)` agree.+ value+ .and_then(|value| value.parse::<usize>().ok())+ .map(|limit| limit.max(1))+ .unwrap_or(DEFAULT_NAVIGATION_CHAIN_LIMIT)+}+fn duration_millis_u64(duration: std::time::Duration) -> u64 {duration.as_millis().min(u128::from(u64::MAX)) as u64}@@ -921,6 +940,7 @@ impl Page {encoding: "UTF-8".to_string(),document_timeline_origin: std::time::Instant::now(),navigation_timeout: None,+ navigation_chain_limit: None,history: Vec::new(),history_index: 0,network_events: Vec::new(),@@ -952,6 +972,18 @@ impl Page {.unwrap_or_else(default_navigation_timeout)}+ /// Takes precedence over `OBSCURA_NAV_CHAIN_LIMIT`. A limit of 0 is+ /// raised to 1, which would otherwise report success having loaded+ /// nothing.+ pub fn set_navigation_chain_limit(&mut self, limit: usize) {+ self.navigation_chain_limit = Some(limit.max(1));+ }++ pub fn navigation_chain_limit(&self) -> usize {+ self.navigation_chain_limit+ .unwrap_or_else(default_navigation_chain_limit)+ }+fn should_block_url(&self, url: &str) -> bool {for pattern in &self.blocked_url_patterns {if url_matches_cdp_pattern(pattern, url) {@@ -2732,8 +2764,8 @@ impl Page {let mut current_method = method.to_string();let mut current_body = body.to_string();let mut document_referrer = initial_referrer.to_string();- const REDIRECT_LIMIT: usize = 10;- for chain in 0..REDIRECT_LIMIT {+ let chain_limit = self.navigation_chain_limit();+ for chain in 0..chain_limit {self.navigate_single(¤t_url,wait_until,@@ -2775,12 +2807,12 @@ impl Page {current_url = next_url;current_method = next_method;current_body = next_body;- if chain + 1 == REDIRECT_LIMIT {+ if chain + 1 == chain_limit {// Hit the cap and the page still wants to keep// chaining. Surface that as an error instead of// returning Ok(()) so callers can distinguish a- // successful load from a redirect storm.- return Err(PageError::TooManyRedirects(REDIRECT_LIMIT));+ // successful load from a navigation storm.+ return Err(PageError::TooManyClientNavigations(chain_limit));}continue;}@@ -4146,9 +4178,11 @@ fn url_matches_cdp_pattern(pattern: &str, url: &str) -> bool {mod tests {use super::{css_resource_urls, linked_stylesheet_requests, materialize_linked_stylesheet_script,- materialize_stylesheet_graph, navigation_referrer, navigation_timeout_from_env_value,- parse_import_url, rebase_css_urls, script_response_is_executable, split_css_imports,- truncate_on_char_boundary, url_matches_cdp_pattern, LoadedStylesheet, StylesheetImport,+ materialize_stylesheet_graph, navigation_chain_limit_from_env_value, navigation_referrer,+ navigation_timeout_from_env_value, parse_import_url, rebase_css_urls,+ script_response_is_executable, split_css_imports, truncate_on_char_boundary,+ url_matches_cdp_pattern, LoadedStylesheet, StylesheetImport,+ DEFAULT_NAVIGATION_CHAIN_LIMIT,};#[cfg(feature = "render")]use super::remaining_settle_resource_warmup_ms;@@ -4175,6 +4209,25 @@ mod tests {);}+ #[test]+ fn navigation_chain_limit_environment_default_remains_ten() {+ assert_eq!(navigation_chain_limit_from_env_value(None), 10);+ assert_eq!(+ navigation_chain_limit_from_env_value(Some("not-a-limit")),+ 10+ );+ }++ #[test]+ fn navigation_chain_limit_environment_override_remains_available() {+ assert_eq!(navigation_chain_limit_from_env_value(Some("25")), 25);+ }++ #[test]+ fn navigation_chain_limit_raises_a_zero_that_would_load_nothing() {+ assert_eq!(navigation_chain_limit_from_env_value(Some("0")), 1);+ }+#[test]fn css_resource_discovery_ignores_strings_comments_data_and_fragments() {let base = url::Url::parse("https://example.test/css/app/main.css").unwrap();@@ -4396,6 +4449,161 @@ mod tests {);}+ /// `/hop/N` sets `location.href = "/hop/N-1"`, `/hop/0` is the target.+ /// An unreadable path gets a 404, so a broken fixture fails the test.+ fn client_navigation_chain_address(name: &str, connections: usize) -> std::net::SocketAddr {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let name = name.to_string();+ std::thread::spawn(move || {+ use std::io::{Read as _, Write as _};++ for _ in 0..connections {+ let Ok((mut stream, _)) = listener.accept() else {+ return;+ };+ let mut buffer = [0u8; 2048];+ let length = stream.read(&mut buffer).unwrap_or(0);+ let hop = String::from_utf8_lossy(&buffer[..length])+ .lines()+ .next()+ .and_then(|line| line.split_ascii_whitespace().nth(1))+ .and_then(|path| path.strip_prefix("/hop/"))+ .and_then(|hop| hop.parse::<usize>().ok());+ let response = match hop {+ Some(0) => {+ let body = format!("<!doctype html><title>{name}</title>");+ format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len(),+ )+ }+ Some(hop) => {+ let body = format!("<script>location.href='/hop/{}'</script>", hop - 1);+ format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len(),+ )+ }+ None => {+ "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"+ .to_string()+ }+ };+ let _ = stream.write_all(response.as_bytes());+ }+ });+ address+ }++ /// Without a limit set the getter reaches its fallback to the environment.+ fn page_without_chain_limit(name: &str) -> super::Page {+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(+ name.to_string(),+ None,+ false,+ None,+ None,+ true,+ ));+ super::Page::new(name.to_string(), context)+ }++ /// The only place where the name of the environment variable is checked+ /// as a string, and the variable is the only way to raise the limit at+ /// runtime. Without this test a typo in the name would stay green.+ #[test]+ fn navigation_chain_limit_reads_the_environment_variable_by_name() {+ std::env::set_var("OBSCURA_NAV_CHAIN_LIMIT", "17");++ let page = page_without_chain_limit("chain-from-environment");++ assert_eq!(page.navigation_chain_limit(), 17);+ }++ #[test]+ fn a_per_page_navigation_chain_limit_wins_over_the_environment() {+ std::env::set_var("OBSCURA_NAV_CHAIN_LIMIT", "17");++ let mut page = page_without_chain_limit("chain-per-page-wins");+ page.set_navigation_chain_limit(4);++ assert_eq!(page.navigation_chain_limit(), 4);+ }++ /// The limit is always set explicitly, never inherited. Otherwise anyone+ /// running the suite with `OBSCURA_NAV_CHAIN_LIMIT` set would see these+ /// tests fail through no fault of the code.+ fn chain_page(name: &str, limit: usize) -> super::Page {+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(+ name.to_string(),+ None,+ false,+ None,+ None,+ true,+ ));+ let mut page = super::Page::new(name.to_string(), context);+ page.set_navigation_chain_limit(limit);+ page+ }++ #[tokio::test(flavor = "current_thread")]+ async fn navigation_chain_default_allows_nine_client_navigations() {+ let address = client_navigation_chain_address("arrived", 10);+ let mut page = chain_page("chain-within-default", DEFAULT_NAVIGATION_CHAIN_LIMIT);++ page.navigate(&format!("http://{address}/hop/9"))+ .await+ .unwrap();++ assert_eq!(page.url_string(), format!("http://{address}/hop/0"));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn navigation_chain_beyond_the_default_reports_client_navigations() {+ let address = client_navigation_chain_address("arrived", 10);+ let mut page = chain_page("chain-beyond-default", DEFAULT_NAVIGATION_CHAIN_LIMIT);++ let error = page+ .navigate(&format!("http://{address}/hop/10"))+ .await+ .expect_err("a chain past the limit must not report success");++ assert!(+ matches!(error, super::PageError::TooManyClientNavigations(10)),+ "unexpected error: {error:?}"+ );+ assert_eq!(+ error.to_string(),+ "Too many client-initiated navigations, the chain reached its limit of 10 documents"+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn raised_navigation_chain_limit_reaches_a_longer_chain() {+ let address = client_navigation_chain_address("arrived", 12);+ let mut page = chain_page("chain-raised", 12);++ page.navigate(&format!("http://{address}/hop/11"))+ .await+ .unwrap();++ assert_eq!(page.url_string(), format!("http://{address}/hop/0"));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn a_zero_navigation_chain_limit_still_loads_the_initial_document() {+ let address = client_navigation_chain_address("arrived", 1);+ let mut page = chain_page("chain-zero", 0);++ page.navigate(&format!("http://{address}/hop/0"))+ .await+ .unwrap();++ assert_eq!(page.url_string(), format!("http://{address}/hop/0"));+ }+#[tokio::test(flavor = "current_thread")]async fn linked_stylesheet_graph_fetches_once_and_preserves_order_and_bases() {use std::sync::atomic::{AtomicUsize, Ordering};@@ -6724,8 +6932,11 @@ pub enum PageError {#[error("Parse error: {0}")]ParseError(String),- #[error("Too many redirects (limit {0})")]- TooManyRedirects(usize),+ /// A page kept triggering its own navigations until the chain's limit+ /// was exhausted. HTTP 3xx redirects are followed one layer down, in+ /// obscura-net, and report `ObscuraNetError::TooManyRedirects`.+ #[error("Too many client-initiated navigations, the chain reached its limit of {0} documents")]+ TooManyClientNavigations(usize),}impl From<ObscuraNetError> for PageError {diff --git a/docs/Environment-variables.md b/docs/Environment-variables.mdindex 99f6eeac..82535e6e 100644--- a/docs/Environment-variables.md+++ b/docs/Environment-variables.md@@ -22,6 +22,18 @@ Hard ceiling on a single navigation. Default 30000 (30 seconds). Applies to `PagOBSCURA_NAV_TIMEOUT_MS=60000 obscura serve```+### `OBSCURA_NAV_CHAIN_LIMIT`++How many documents a navigation chain may load, the first navigation included. Default 10, which allows the requested document and nine navigations the page itself triggers via `location` assignments or form submissions. Raise the value for an endpoint that chains longer for good reasons, such as an SSO handover across several providers. The low default is what stops a page that resets `location` on every load.++A zero is raised to 1. This loads the requested document. If the page wants to chain further afterwards, the call reports an error, as at any other limit. A value the engine does not read as a number is replaced by the default. This also applies to a negative value and to a value with a trailing space.++The time budget is not tied to this limit. A longer chain usually also needs a higher `OBSCURA_NAV_TIMEOUT_MS`, because its default of 30 seconds applies to the whole chain and not to the individual document.++```bash+OBSCURA_NAV_CHAIN_LIMIT=20 obscura serve+```+### `OBSCURA_SCRIPT_DEADLINE_MS`Soft deadline for the complete page script-execution phase, including classic scripts and ES modules. Default 30000 (30 seconds). Raise it for a heavy SPA whose initial module is responsible for mounting an otherwise empty document. The engine also uses this value as a hard V8 watchdog budget, with a one-second grace period, so a synchronous script cannot run forever.