Skip to content

The headless browser for AI agents and web scraping

fix(render): route resource loads through page transport

SGavrl97ff86dbaca8
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index abc9819a..fdbc3b40 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -891,16 +891,11 @@ fn css_import_rule_len(css: &str) -> Option<usize> {
None
}
-fn render_resource_type(url: &url::Url) -> ResourceType {
+fn render_resource_is_font(url: &url::Url) -> bool {
let path = url.path().to_ascii_lowercase();
- if [".woff", ".woff2", ".ttf", ".otf", ".eot"]
+ [".woff", ".woff2", ".ttf", ".otf", ".eot"]
.iter()
.any(|extension| path.ends_with(extension))
- {
- ResourceType::Font
- } else {
- ResourceType::Image
- }
}
/// Pull leading `@import` rules out of a stylesheet. Returns each import target
@@ -1865,6 +1860,8 @@ impl Page {
// runtime does not exist yet, so the new runtime would otherwise start
// with interception disabled and op_fetch_url would never intercept.
rt.set_intercept_enabled(self.intercept_enabled);
+ #[cfg(feature = "render")]
+ rt.set_intercept_block_patterns(self.intercept_block_patterns.clone());
rt.set_runtime_events_enabled(self.runtime_events_enabled.get());
if let Some(dom) = self.dom.take() {
@@ -3029,6 +3026,10 @@ impl Page {
let _ = js.run_event_loop_until_quiescent(remaining, 150).await;
}
}
+ #[cfg(feature = "render")]
+ {
+ self.queue_pending_render_resources();
+ }
if !self.advance_frames().await {
break;
}
@@ -3078,15 +3079,70 @@ impl Page {
/// higher-priority automation commands.
#[doc(hidden)]
pub async fn run_autonomous_event_loop_turn(&mut self) -> Result<bool, String> {
+ #[cfg(feature = "render")]
+ {
+ self.queue_pending_render_resources();
+ }
let reached_idle = match self.js.as_mut() {
- Some(js) => js.run_autonomous_event_loop_turn().await,
- None => Ok(true),
- }?;
+ Some(js) => {
+ #[cfg(feature = "render")]
+ {
+ // A finished transport load is page work too: wake up as
+ // soon as it lands so the next layout, paint or lifecycle
+ // read sees the real bytes instead of waiting for the next
+ // protocol command. The runtime turn is cancel-safe (the
+ // connection processor already races it against commands).
+ // The waiter is registered before the pending check, so a
+ // load finishing in between cannot be missed.
+ let notify = js.render_resource_notify();
+ let notified = notify.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+ let loads_pending = js.has_pending_render_resources();
+ tokio::select! {
+ biased;
+ turn = js.run_autonomous_event_loop_turn() => turn?,
+ _ = &mut notified, if loads_pending => false,
+ }
+ }
+ #[cfg(not(feature = "render"))]
+ js.run_autonomous_event_loop_turn().await?
+ }
+ None => true,
+ };
// Dynamic iframe fetches finish on the page event loop, but their
// realms must be built by Page between turns. Keep the autonomous CDP
// pump on the same generic frame path as settle(), so a client that
// stays attached can observe and run child documents as they arrive.
let frame_work = self.advance_frames().await;
+ #[cfg(feature = "render")]
+ {
+ if reached_idle && !frame_work && self.js.is_some() {
+ // The runtime may have nothing to do until a resource lands.
+ // Park on the next result instead of reporting "busy" (which
+ // would spin the connection pump). `notified` is cancel-safe,
+ // so the processor can still preempt this turn with a
+ // command. Register the waiter first, then service (a load
+ // that finished before this point is applied here; its wake
+ // is already past), then decide whether to park.
+ let notify = self.js.as_ref().unwrap().render_resource_notify();
+ let notified = notify.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+ self.queue_pending_render_resources();
+ if self.has_pending_render_resources() {
+ notified.await;
+ self.drain_render_resource_results();
+ return Ok(false);
+ }
+ return Ok(true);
+ }
+ // Geometry this turn produced may have missed resources; start
+ // their loads now.
+ self.queue_pending_render_resources();
+ return Ok(reached_idle && !frame_work);
+ }
+ #[cfg(not(feature = "render"))]
Ok(reached_idle && !frame_work)
}
@@ -3205,6 +3261,8 @@ impl Page {
) -> Result<(), PageError> {
let url = Url::parse(url_str).map_err(|e| PageError::InvalidUrl(e.to_string()))?;
+ // The previous document's background loads end with the document.
+ self.retire_render_resources();
self.lifecycle = LifecycleState::Loading;
self.referrer = referrer.to_string();
self.url = Some(url.clone());
@@ -3544,6 +3602,7 @@ impl Page {
}
pub fn navigate_blank(&mut self) {
+ self.retire_render_resources();
self.pending_frame_work.clear();
self.frames.clear();
self.js = None;
@@ -3570,180 +3629,248 @@ impl Page {
self.dom.as_ref().map(f)
}
- /// Concurrently seed the synchronous renderer cache through the owning
- /// page transport. This removes serial image/font HTTP from the first
- /// screenshot while retaining cookies, proxy policy, interception, CORS,
- /// response limits, and connection pooling.
+ /// Render resources the retained document references but the renderer
+ /// cache does not know yet, found by scanning the light DOM for `<img>`,
+ /// `<video poster>`, `<style>`, `style` attributes and `<use>`. This is
+ /// only the navigation warmup: everything layout or paint actually asks
+ /// for later is reported by the renderer itself (`take_render_resource_requests`).
+ /// Blocked or disallowed URLs come back separately so they can be
+ /// remembered as missing.
#[cfg(feature = "render")]
- pub async fn prepare_screenshot_resources(&mut self, max_ms: u64) -> usize {
- let started = std::time::Instant::now();
- if max_ms == 0 || self.js.is_none() {
- return 0;
- }
+ fn render_resource_candidates(
+ &self,
+ ) -> (
+ Vec<(String, Option<obscura_js::ImageRequestProfile>, bool)>,
+ Vec<(String, Option<obscura_js::ImageRequestProfile>, bool)>,
+ ) {
+ let Some(js) = &self.js else {
+ return (Vec::new(), Vec::new());
+ };
let Some(document_url) = self.url.clone() else {
- return 0;
+ return (Vec::new(), Vec::new());
};
let base_url = self
.resolve_base_url()
.unwrap_or_else(|| document_url.clone());
- let mut candidates = std::collections::BTreeMap::new();
+ let mut candidates = std::collections::BTreeSet::new();
- if let Some(js) = &self.js {
- for (raw, profile) in js.pending_render_image_urls() {
- if let Ok(mut url) = url::Url::parse(&raw) {
- url.set_fragment(None);
- candidates.insert((url.to_string(), Some(profile)), ResourceType::Image);
- }
+ for (raw, profile) in js.pending_render_image_urls() {
+ if let Ok(mut url) = url::Url::parse(&raw) {
+ url.set_fragment(None);
+ candidates.insert((url.to_string(), Some(profile), false));
}
- let css_sources = js
- .with_dom(|dom| {
- let mut sources = Vec::new();
- for id in dom.descendants(dom.document()) {
- let Some(node) = dom.get_node(id) else {
- continue;
- };
- if node
- .as_element()
- .is_some_and(|element| element.local.as_ref() == "style")
+ }
+ let css_sources = js
+ .with_dom(|dom| {
+ let mut sources = Vec::new();
+ for id in dom.descendants(dom.document()) {
+ let Some(node) = dom.get_node(id) else {
+ continue;
+ };
+ if node
+ .as_element()
+ .is_some_and(|element| element.local.as_ref() == "style")
+ {
+ sources.push(dom.text_content(id));
+ }
+ if let Some(style) = node.get_attribute("style") {
+ sources.push(style.to_string());
+ }
+ if node
+ .as_element()
+ .is_some_and(|element| element.local.as_ref() == "use")
+ {
+ if let Some(href) = node
+ .get_attribute("href")
+ .or_else(|| node.get_attribute("xlink:href"))
{
- sources.push(dom.text_content(id));
- }
- if let Some(style) = node.get_attribute("style") {
- sources.push(style.to_string());
+ sources.push(format!("url({href})"));
}
- if node
- .as_element()
- .is_some_and(|element| element.local.as_ref() == "use")
- {
- if let Some(href) = node
- .get_attribute("href")
- .or_else(|| node.get_attribute("xlink:href"))
- {
- sources.push(format!("url({href})"));
- }
- }
- }
- sources
- })
- .unwrap_or_default();
- for css in css_sources {
- for raw in css_resource_urls(&css, &base_url) {
- if let Ok(mut url) = url::Url::parse(&raw) {
- let kind = render_resource_type(&url);
- url.set_fragment(None);
- candidates.insert((url.to_string(), None), kind);
}
}
+ sources
+ })
+ .unwrap_or_default();
+ for css in css_sources {
+ for raw in css_resource_urls(&css, &base_url) {
+ if let Ok(mut url) = url::Url::parse(&raw) {
+ url.set_fragment(None);
+ let is_font = render_resource_is_font(&url);
+ candidates.insert((url.to_string(), None, is_font));
+ }
}
- candidates.retain(|(url, profile), _| match profile {
- Some(profile) => !js.render_image_resource_is_known(url, *profile),
- None => !js.render_resource_is_known(url),
- });
}
-
- candidates.retain(|(url, _), _| {
- subresource_allowed(Some(&document_url), url) && !self.should_block_url(url)
+ candidates.retain(|(url, profile, _)| match profile {
+ Some(profile) => !js.render_image_resource_is_known(url, *profile),
+ None => !js.render_resource_is_known(url),
});
- if candidates.len() > 128 {
- candidates = candidates.into_iter().take(128).collect();
+
+ let mut loadable = Vec::new();
+ let mut rejected = Vec::new();
+ // Preserve the historical warmup bound. Anything beyond this batch
+ // is reported again by a later cache-only layout.
+ for (url, profile, is_font) in candidates.into_iter().take(MAX_STYLESHEET_RESOURCES) {
+ if subresource_allowed(Some(&document_url), &url) && !self.should_block_url(&url) {
+ loadable.push((url, profile, is_font));
+ } else {
+ rejected.push((url, profile, is_font));
+ }
}
- if candidates.is_empty() {
+ (loadable, rejected)
+ }
+
+ /// Abandon every background load of the current document. Navigation, a
+ /// blank reset, suspension and teardown call this so a response that
+ /// belongs to a previous document can neither seed the next document's
+ /// cache nor be mistaken for that document's own request of the same URL
+ /// (the runtime also fences results by document generation). Aborting
+ /// the tasks drops their in-progress HTTP requests.
+ #[cfg(feature = "render")]
+ pub fn retire_render_resources(&mut self) {
+ if let Some(js) = &self.js {
+ js.abandon_render_resources();
+ }
+ }
+
+ #[cfg(not(feature = "render"))]
+ pub fn retire_render_resources(&mut self) {}
+
+ /// Apply every finished background load without waiting and report the
+ /// responses as Network events. Returns the number of loads that stored
+ /// usable bytes. Successful image and font bytes invalidate the retained
+ /// geometry, so the next layout or paint observes the real intrinsic size.
+ #[cfg(feature = "render")]
+ pub fn drain_render_resource_results(&mut self) -> usize {
+ let Some(js) = self.js.as_mut() else {
return 0;
+ };
+ let loaded = js.apply_render_resource_results();
+ self.record_render_resource_events();
+ loaded
+ }
+
+ /// Report the responses of applied background loads as Network events
+ /// (recording needs the page, not the runtime).
+ #[cfg(feature = "render")]
+ fn record_render_resource_events(&mut self) {
+ let Some(js) = self.js.as_mut() else {
+ return;
+ };
+ let events = js.take_render_resource_events();
+ for event in events {
+ self.record_network_event_with_body(
+ &event.response.url,
+ "GET",
+ if event.is_font { "Font" } else { "Image" },
+ event.response.status,
+ &event.response.headers,
+ event.response.body.as_ref(),
+ true,
+ );
}
+ }
- let requested: Vec<(String, Option<obscura_js::ImageRequestProfile>, ResourceType)> =
- candidates
- .into_iter()
- .map(|((url, profile), kind)| (url, profile, kind))
- .collect();
- let client = self.http_client.clone();
- #[cfg(feature = "stealth")]
- let stealth_client = self.stealth_client.clone();
- let callbacks = self.callbacks.clone();
- let initiator = document_url.clone();
- use futures::StreamExt as _;
- let requests = futures::stream::iter(requested.into_iter().map(|(raw, profile, kind)| {
- let client = client.clone();
- #[cfg(feature = "stealth")]
- let stealth_client = stealth_client.clone();
- let callbacks = callbacks.clone();
- let initiator = initiator.clone();
- async move {
- let parsed = url::Url::parse(&raw).expect("validated render resource URL");
- let mut request = ResourceRequest::subresource(kind, &initiator);
- match profile {
- Some(obscura_js::ImageRequestProfile::CorsSameOrigin) => {
- request.mode = obscura_net::RequestMode::Cors;
- request.credentials = obscura_net::RequestCredentials::SameOrigin;
- }
- Some(obscura_js::ImageRequestProfile::CorsInclude) => {
- request.mode = obscura_net::RequestMode::Cors;
- request.credentials = obscura_net::RequestCredentials::Include;
+ #[cfg(not(feature = "render"))]
+ pub fn drain_render_resource_results(&mut self) -> usize {
+ 0
+ }
+
+ /// Apply finished loads and start transport loads for the resources
+ /// cache-only layout or paint missed since the last call (the runtime's
+ /// own service step, plus the Network events). Returns the number of
+ /// loads that stored usable bytes.
+ #[cfg(feature = "render")]
+ pub fn queue_pending_render_resources(&mut self) -> usize {
+ let Some(js) = self.js.as_mut() else {
+ return 0;
+ };
+ let loaded = js.service_render_resources();
+ self.record_render_resource_events();
+ loaded
+ }
+
+ #[cfg(not(feature = "render"))]
+ pub fn queue_pending_render_resources(&mut self) -> usize {
+ 0
+ }
+
+ /// Start loads for everything the light-DOM scan finds. Used by the
+ /// navigation warmups before any layout has run.
+ #[cfg(feature = "render")]
+ pub fn spawn_pending_render_resources(&mut self) -> usize {
+ if let Some(js) = &self.js {
+ // A runtime attached without `init_js` loads through the page
+ // transport all the same.
+ if !js.has_page_transport() {
+ js.set_http_client(self.http_client.clone());
+ js.set_callbacks(self.callbacks.clone());
+ #[cfg(feature = "stealth")]
+ if let Some(stealth) = &self.stealth_client {
+ js.set_stealth_client(stealth.clone());
+ }
+ }
+ }
+ let (loadable, rejected) = self.render_resource_candidates();
+ let started = match &mut self.js {
+ Some(js) => {
+ for (url, profile, _) in rejected {
+ match profile {
+ Some(profile) => js.seed_render_image_resource(url, profile, None),
+ None => js.seed_render_resource(url, None),
}
- _ => {}
}
- #[cfg(feature = "stealth")]
- let result = if let Some(stealth_client) = stealth_client {
- stealth_client
- .fetch_resource_with_callbacks(&parsed, request, Some(&callbacks))
- .await
- } else {
- client
- .fetch_resource_with_callbacks(&parsed, request, Some(&callbacks))
- .await
- };
- #[cfg(not(feature = "stealth"))]
- let result = client
- .fetch_resource_with_callbacks(&parsed, request, Some(&callbacks))
- .await;
- (raw, profile, kind, result)
+ let mut requests = js.mark_render_resources_in_flight(loadable);
+ requests.extend(js.take_render_resource_requests());
+ js.start_render_resource_loads(requests)
}
- }))
- .buffer_unordered(16);
- futures::pin_mut!(requests);
+ None => 0,
+ };
+ started
+ }
+
+ /// Whether background render-resource loads are still running.
+ #[cfg(feature = "render")]
+ pub fn has_pending_render_resources(&self) -> bool {
+ self.js
+ .as_ref()
+ .is_some_and(|js| js.has_pending_render_resources())
+ }
+
+ /// Seed the renderer cache through the owning page transport and wait up
+ /// to `max_ms` for the results. This removes serial image/font HTTP from
+ /// the first screenshot while retaining cookies, proxy policy,
+ /// interception, CORS, response limits, and connection pooling. Loads
+ /// that miss the deadline keep running in the background and are applied
+ /// by a later drain; they are neither cancelled nor negative-cached.
+ #[cfg(feature = "render")]
+ pub async fn prepare_screenshot_resources(&mut self, max_ms: u64) -> usize {
+ let started = std::time::Instant::now();
+ if max_ms == 0 || self.js.is_none() {
+ return 0;
+ }
+ let mut loaded = 0;
+ self.spawn_pending_render_resources();
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(max_ms);
- let mut loaded = 0usize;
+ let Some(notify) = self.js.as_ref().map(|js| js.render_resource_notify()) else {
+ return loaded;
+ };
loop {
- match tokio::time::timeout_at(deadline, requests.next()).await {
- Ok(Some((raw, profile, kind, result))) => {
- let outcome = match result {
- Ok(response) => {
- self.record_network_event_with_body(
- response.url.as_str(),
- "GET",
- match kind {
- ResourceType::Font => "Font",
- _ => "Image",
- },
- response.status,
- &response.headers,
- &response.body,
- true,
- );
- if (200..300).contains(&response.status) {
- loaded += 1;
- Some(response.body)
- } else {
- None
- }
- }
- Err(_) => None,
- };
- if let Some(js) = &mut self.js {
- match profile {
- Some(profile) => {
- js.seed_render_image_resource(raw, profile, outcome)
- }
- None => js.seed_render_resource(raw, outcome),
- }
- }
- }
- Ok(None) | Err(_) => break,
+ // Register the waiter first, then apply what already arrived,
+ // then decide whether to wait: a load that finished after the
+ // scan (its wake is already past) is picked up by the drain, and
+ // one that finishes after the drain wakes the registered waiter.
+ let notified = notify.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+ loaded += self.drain_render_resource_results();
+ if !self.has_pending_render_resources() {
+ break;
+ }
+ if tokio::time::timeout_at(deadline, notified).await.is_err() {
+ loaded += self.drain_render_resource_results();
+ break;
}
}
- // A deadline drops unfinished futures without negative-caching them,
- // so a later warmup can retry slow resources.
- drop(requests);
tracing::debug!(
loaded,
elapsed_ms = started.elapsed().as_millis(),
@@ -4369,6 +4496,12 @@ impl Page {
}
pub fn suspend_js(&mut self) {
+ if self.js.is_none() {
+ return;
+ }
+ // Suspension rebuilds the renderer cache on resume (`take_dom`), so
+ // results for the suspended realm would have nowhere to go.
+ self.retire_render_resources();
let Some(js) = &mut self.js else {
return;
};
@@ -4554,6 +4687,10 @@ impl Page {
self.intercept_enabled = enabled;
if let Some(js) = &self.js {
js.set_intercept_enabled(enabled);
+ // `Fetch.enable` assigns the patterns right before this call;
+ // the renderer's loads follow the same interception policy.
+ #[cfg(feature = "render")]
+ js.set_intercept_block_patterns(self.intercept_block_patterns.clone());
}
}
}
@@ -4589,6 +4726,14 @@ fn url_matches_cdp_pattern(pattern: &str, url: &str) -> bool {
pattern.ends_with('*') || remainder.is_empty()
}
+impl Drop for Page {
+ fn drop(&mut self) {
+ // A closed target must not keep fetching for a document nobody can
+ // observe any more.
+ self.retire_render_resources();
+ }
+}
+
#[cfg(test)]
mod tests {
use super::{
@@ -7266,6 +7411,862 @@ mod tests {
);
}
+ /// Serve one SVG for every request after `delay_ms`, for `seconds`.
+ /// Reports each request line so tests can count transport requests.
+ #[cfg(feature = "render")]
+ fn spawn_delayed_svg_server(
+ delay_ms: u64,
+ seconds: u64,
+ ) -> (std::net::SocketAddr, std::sync::mpsc::Receiver<String>) {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let address = listener.local_addr().unwrap();
+ let (seen_tx, seen_rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
+ while std::time::Instant::now() < deadline {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let seen_tx = seen_tx.clone();
+ std::thread::spawn(move || {
+ let mut request = [0u8; 2048];
+ let read = stream.read(&mut request).unwrap_or(0);
+ let first = String::from_utf8_lossy(&request[..read])
+ .lines()
+ .next()
+ .unwrap_or_default()
+ .to_string();
+ let _ = seen_tx.send(first);
+ std::thread::sleep(std::time::Duration::from_millis(delay_ms));
+ let body = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#f00"/></svg>"##;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.write_all(body);
+ });
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ Err(_) => break,
+ }
+ }
+ });
+ (address, seen_rx)
+ }
+
+ /// A page with a transport and one `<img>`, wired the way `init_js` does
+ /// it (transport installed on the runtime before page script runs).
+ #[cfg(feature = "render")]
+ fn page_with_transport_and_image(id: &str, page_url: &str, image_url: &str) -> super::Page {
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ id.to_string(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ ));
+ let mut page = super::Page::new(id.to_string(), context);
+ page.set_viewport((100.0, 80.0));
+ let dom = parse_html(&format!(
+ r#"<html><body><img id="i" src="{image_url}"></body></html>"#
+ ));
+ let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
+ runtime.set_dom(dom);
+ runtime.set_url(page_url);
+ runtime.set_viewport(100.0, 80.0);
+ runtime.set_http_client(page.http_client.clone());
+ runtime.set_callbacks(page.callbacks.clone());
+ runtime.run_page_init();
+ page.js = Some(runtime);
+ page.url = Some(url::Url::parse(page_url).unwrap());
+ page
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn render_resource_warmup_keeps_the_existing_candidate_bound() {
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ "warmup-bound".to_string(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ ));
+ let mut page = super::Page::new("warmup-bound".to_string(), context);
+ let mut html = String::from("<html><body>");
+ for index in 0..(super::MAX_STYLESHEET_RESOURCES + 4) {
+ html.push_str(&format!("<img src=\"https://assets.test/{index}.png\">"));
+ }
+ html.push_str("</body></html>");
+ let runtime = obscura_js::runtime::ObscuraJsRuntime::new();
+ runtime.set_dom(parse_html(&html));
+ runtime.set_url("https://example.test/page");
+ page.js = Some(runtime);
+ page.url = Some(url::Url::parse("https://example.test/page").unwrap());
+
+ let (loadable, rejected) = page.render_resource_candidates();
+ assert_eq!(
+ loadable.len() + rejected.len(),
+ super::MAX_STYLESHEET_RESOURCES
+ );
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn cache_only_layout_never_blocks_on_a_slow_asset_and_late_bytes_update_geometry() {
+ let (address, seen_rx) = spawn_delayed_svg_server(1_200, 8);
+ let page_url = format!("http://{address}/page");
+ let asset_url = format!("http://{address}/slow.svg");
+ let mut page = page_with_transport_and_image("cache-only", &page_url, &asset_url);
+ assert!(
+ !page
+ .js
+ .as_ref()
+ .unwrap()
+ .render_resource_sync_loading_enabled(),
+ "a page-owned runtime must not own a synchronous loader"
+ );
+
+ // Layout must answer from placeholder geometry immediately instead of
+ // fetching the asset on the V8 thread.
+ let started = std::time::Instant::now();
+ let width = page
+ .js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').getBoundingClientRect().width")
+ .unwrap();
+ assert!(
+ started.elapsed() < std::time::Duration::from_millis(600),
+ "layout query took {:?} while the asset needs 1.2 s",
+ started.elapsed()
+ );
+ // Chromium lays out a not-yet-loaded <img> without size attributes as
+ // an empty box; the intrinsic width must not be known yet either way.
+ assert!(width.is_number(), "layout answered: {width}");
+ assert_ne!(width.as_f64(), Some(20.0), "intrinsic size is not known yet");
+ assert_eq!(
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').naturalWidth")
+ .unwrap()
+ .as_f64(),
+ Some(0.0)
+ );
+
+ // The miss is queued through the page transport exactly once (the
+ // geometry read above already handed it to the transport).
+ page.queue_pending_render_resources();
+ assert!(page.has_pending_render_resources());
+ page.queue_pending_render_resources();
+ // The load runs on the runtime, so yield to it instead of blocking the
+ // single test thread on the channel.
+ let mut first_request = None;
+ for _ in 0..40 {
+ if let Ok(line) = seen_rx.try_recv() {
+ first_request = Some(line);
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ assert!(
+ first_request
+ .as_deref()
+ .is_some_and(|line| line.starts_with("GET /slow.svg ")),
+ "transport request expected, got {first_request:?}"
+ );
+
+ // Waiting for the transport (here via the capture warmup) applies the
+ // late bytes: cache known, intrinsic size visible to script and layout.
+ assert_eq!(page.prepare_screenshot_resources(5_000).await, 1);
+ assert!(!page.has_pending_render_resources());
+ assert!(page.js.as_ref().unwrap().render_image_resource_is_known(
+ &asset_url,
+ obscura_js::ImageRequestProfile::NoCorsInclude
+ ));
+ assert_eq!(
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').naturalWidth")
+ .unwrap()
+ .as_f64(),
+ Some(20.0)
+ );
+ assert_eq!(
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').getBoundingClientRect().width")
+ .unwrap()
+ .as_f64(),
+ Some(20.0)
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ assert!(
+ seen_rx.try_recv().is_err(),
+ "neither layout nor capture may open a second request"
+ );
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn blocked_render_resources_are_never_fetched_by_layout_or_transport() {
+ let (address, seen_rx) = spawn_delayed_svg_server(0, 4);
+ let page_url = format!("http://{address}/page");
+ let asset_url = format!("http://{address}/blocked.svg");
+ let mut page = page_with_transport_and_image("blocked", &page_url, &asset_url);
+ page.set_blocked_urls(vec!["*blocked.svg".to_string()]);
+
+ let started = std::time::Instant::now();
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').getBoundingClientRect().width")
+ .unwrap();
+ assert!(started.elapsed() < std::time::Duration::from_millis(600));
+ assert_eq!(
+ page.queue_pending_render_resources(),
+ 0,
+ "a blocked URL must not start a transport request"
+ );
+ assert!(
+ page.js.as_ref().unwrap().render_image_resource_is_known(
+ &asset_url,
+ obscura_js::ImageRequestProfile::NoCorsInclude
+ ),
+ "a blocked URL is remembered as missing so layout stops asking"
+ );
+ assert_eq!(page.prepare_screenshot_resources(200).await, 0);
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ assert!(
+ seen_rx.try_recv().is_err(),
+ "Network.setBlockedURLs must also stop renderer-initiated loads"
+ );
+ }
+
+ /// Serve every request after `delay_ms` for `seconds`, tracking how many
+ /// connections are open at once. Bodies are a 20x10 SVG.
+ #[cfg(feature = "render")]
+ fn spawn_counting_svg_server(
+ delay_ms: u64,
+ seconds: u64,
+ ) -> (
+ std::net::SocketAddr,
+ std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ std::sync::mpsc::Receiver<String>,
+ ) {
+ use std::io::{Read, Write};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let address = listener.local_addr().unwrap();
+ let open = std::sync::Arc::new(AtomicUsize::new(0));
+ let peak = std::sync::Arc::new(AtomicUsize::new(0));
+ let (seen_tx, seen_rx) = std::sync::mpsc::channel();
+ let (open_thread, peak_thread) = (open.clone(), peak.clone());
+ std::thread::spawn(move || {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
+ while std::time::Instant::now() < deadline {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let (open, peak, seen_tx) =
+ (open_thread.clone(), peak_thread.clone(), seen_tx.clone());
+ std::thread::spawn(move || {
+ let now = open.fetch_add(1, Ordering::SeqCst) + 1;
+ peak.fetch_max(now, Ordering::SeqCst);
+ let mut request = [0u8; 4096];
+ let read = stream.read(&mut request).unwrap_or(0);
+ let first = String::from_utf8_lossy(&request[..read])
+ .lines()
+ .next()
+ .unwrap_or_default()
+ .to_string();
+ let _ = seen_tx.send(first);
+ std::thread::sleep(std::time::Duration::from_millis(delay_ms));
+ let body = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#f00"/></svg>"##;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.write_all(body);
+ open.fetch_sub(1, Ordering::SeqCst);
+ });
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ }
+ Err(_) => break,
+ }
+ }
+ });
+ (address, peak, open, seen_rx)
+ }
+
+ /// A page with a transport and arbitrary body markup, wired like `init_js`.
+ #[cfg(feature = "render")]
+ fn page_with_transport_and_body(id: &str, page_url: &str, body: &str) -> super::Page {
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ id.to_string(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ ));
+ let mut page = super::Page::new(id.to_string(), context);
+ page.set_viewport((400.0, 300.0));
+ let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
+ runtime.set_dom(parse_html(&format!("<html><body>{body}</body></html>")));
+ runtime.set_url(page_url);
+ runtime.set_viewport(400.0, 300.0);
+ runtime.set_http_client(page.http_client.clone());
+ runtime.set_callbacks(page.callbacks.clone());
+ runtime.run_page_init();
+ page.js = Some(runtime);
+ page.url = Some(url::Url::parse(page_url).unwrap());
+ page
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn renderer_misses_cover_script_fonts_and_shadow_root_styles() {
+ let (address, _peak, _open, seen_rx) = spawn_counting_svg_server(0, 6);
+ let page_url = format!("http://{address}/page");
+ let shadow_font = format!("http://{address}/shadow.ttf");
+ let dynamic_font = format!("http://{address}/dynamic.ttf");
+ let mut page = page_with_transport_and_body(
+ "misses",
+ &page_url,
+ r#"<div id="host"></div><p id="dyn" style="font-family:Dyn">dynamic</p>"#,
+ );
+ {
+ let js = page.js.as_mut().unwrap();
+ // Neither source is visible to a light-DOM scan: one lives in a
+ // shadow root, the other only in the script FontFaceSet.
+ js.evaluate(&format!(
+ r#"(function() {{
+ const root = document.getElementById('host').attachShadow({{mode: 'open'}});
+ root.innerHTML = '<style>@font-face {{ font-family: Shadow; src: url({shadow_font}); }}</style><p style="font-family:Shadow">shadow</p>';
+ document.fonts.add(new FontFace('Dyn', 'url({dynamic_font})'));
+ return true;
+ }})()"#
+ ))
+ .unwrap();
+ js.evaluate("document.getElementById('dyn').getBoundingClientRect().width")
+ .unwrap();
+ }
+ page.queue_pending_render_resources();
+ assert!(page.has_pending_render_resources(), "layout misses must name both fonts");
+ page.prepare_screenshot_resources(3_000).await;
+ assert!(!page.has_pending_render_resources());
+ let mut lines = Vec::new();
+ while let Ok(line) = seen_rx.try_recv() {
+ lines.push(line);
+ }
+ assert!(
+ lines.iter().any(|line| line.starts_with("GET /shadow.ttf ")),
+ "shadow-root font must be requested through the transport: {lines:?}"
+ );
+ assert!(
+ lines.iter().any(|line| line.starts_with("GET /dynamic.ttf ")),
+ "script-registered font must be requested through the transport: {lines:?}"
+ );
+ let js = page.js.as_ref().unwrap();
+ assert!(js.render_resource_is_known(&shadow_font));
+ assert!(js.render_resource_is_known(&dynamic_font));
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn late_bytes_apply_while_the_runtime_waits_for_a_promise() {
+ let (address, _peak, _open, _seen_rx) = spawn_counting_svg_server(1_200, 6);
+ let page_url = format!("http://{address}/page");
+ let asset_url = format!("http://{address}/late.svg");
+ let mut page = page_with_transport_and_image("promise-wait", &page_url, &asset_url);
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').getBoundingClientRect().width")
+ .unwrap();
+ page.queue_pending_render_resources();
+ assert!(page.has_pending_render_resources());
+
+ // No protocol command and no page pump runs here: only the runtime's
+ // own promise wait, as `Runtime.evaluate` with `awaitPromise` does.
+ let started = std::time::Instant::now();
+ let resolved = page
+ .js
+ .as_mut()
+ .unwrap()
+ .resolve_promises_until(
+ |js| {
+ js.evaluate("document.getElementById('i').naturalWidth")
+ .ok()
+ .and_then(|value| value.as_f64())
+ == Some(20.0)
+ },
+ 4_000,
+ )
+ .await;
+ assert!(resolved, "the wait must observe the late bytes");
+ assert!(
+ started.elapsed() < std::time::Duration::from_millis(3_000),
+ "observed after {:?}, expected shortly after the 1.2 s response",
+ started.elapsed()
+ );
+ }
+
+ /// Serves one fixed body with one content type after `delay_ms`, for
+ /// `seconds`. Reports every request line.
+ #[cfg(feature = "render")]
+ fn spawn_delayed_bytes_server(
+ delay_ms: u64,
+ seconds: u64,
+ content_type: &'static str,
+ body: &'static [u8],
+ ) -> (std::net::SocketAddr, std::sync::mpsc::Receiver<String>) {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let address = listener.local_addr().unwrap();
+ let (seen_tx, seen_rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
+ while std::time::Instant::now() < deadline {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let seen_tx = seen_tx.clone();
+ std::thread::spawn(move || {
+ let mut request = [0u8; 4096];
+ let read = stream.read(&mut request).unwrap_or(0);
+ let first = String::from_utf8_lossy(&request[..read])
+ .lines()
+ .next()
+ .unwrap_or_default()
+ .to_string();
+ let _ = seen_tx.send(first);
+ std::thread::sleep(std::time::Duration::from_millis(delay_ms));
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.write_all(body);
+ });
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ Err(_) => break,
+ }
+ }
+ });
+ (address, seen_rx)
+ }
+
+ /// DejaVu Sans is much wider than the renderer's default Liberation
+ /// Sans, so a paragraph changes width once the served font applies.
+ #[cfg(feature = "render")]
+ static LATE_FONT: &[u8] = include_bytes!("../../obscura-render/assets/dejavu-sans.ttf");
+
+ /// A single awaited CDP expression creates the miss (a script-added
+ /// `@font-face`), and nothing but the runtime's own promise wait runs
+ /// until it resolves: the load must be started and its bytes applied
+ /// from inside that wait.
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn a_miss_created_inside_an_awaited_expression_loads_during_the_wait() {
+ let (address, seen_rx) = spawn_delayed_bytes_server(1_200, 8, "font/ttf", LATE_FONT);
+ let page_url = format!("http://{address}/page");
+ let font_url = format!("http://{address}/late.ttf");
+ let mut page = page_with_transport_and_body(
+ "await-miss",
+ &page_url,
+ r#"<p><span id="t" style="font-size:20px">MMMMMMMMMMMMMMMMMMMM</span></p>"#,
+ );
+ let expression = format!(
+ r#"(async () => {{
+ const style = document.createElement('style');
+ style.textContent = '@font-face {{ font-family: Late; src: url({font_url}); }}';
+ document.head.appendChild(style);
+ const t = document.getElementById('t');
+ t.style.fontFamily = 'Late';
+ const before = t.getBoundingClientRect().width;
+ const started = Date.now();
+ while (Date.now() - started < 4000) {{
+ await new Promise(resolve => setTimeout(resolve, 20));
+ const now = t.getBoundingClientRect().width;
+ if (now !== before) return [before, now, Date.now() - started];
+ }}
+ return [before, t.getBoundingClientRect().width, -1];
+ }})()"#
+ );
+ let started = std::time::Instant::now();
+ let result = page
+ .js
+ .as_mut()
+ .unwrap()
+ .evaluate_for_cdp_with_timeout(&expression, true, true, 5_000)
+ .await
+ .unwrap();
+ let elapsed = started.elapsed();
+ let value = result.value.clone().unwrap_or_default();
+ let samples = value.as_array().cloned().unwrap_or_default();
+ assert_eq!(samples.len(), 3, "unexpected result {value}");
+ let (before, after, at_ms) = (
+ samples[0].as_f64().unwrap(),
+ samples[1].as_f64().unwrap(),
+ samples[2].as_f64().unwrap(),
+ );
+ let requests: Vec<String> = seen_rx.try_iter().collect();
+ assert!(
+ at_ms >= 0.0,
+ "the font must apply inside the awaited expression (before {before}, after {after}, requests {requests:?}, pending {})",
+ page.has_pending_render_resources()
+ );
+ assert!(after != before && after > 0.0, "before {before}, after {after}");
+ assert!(
+ elapsed < std::time::Duration::from_millis(3_500),
+ "resolved after {elapsed:?}, expected shortly after the 1.2 s response"
+ );
+ assert!(
+ requests.iter().any(|line| line.starts_with("GET /late.ttf ")),
+ "the font is requested through the transport: {requests:?}"
+ );
+ }
+
+ /// Timer-driven page script inside one fixed-length wait
+ /// (`run_event_loop_for_duration`, the CLI `--wait` path) observes the
+ /// bytes that land during the wait; no external evaluate samples for it.
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn timers_inside_a_fixed_wait_observe_bytes_that_land_during_it() {
+ let (address, _seen_rx) = spawn_delayed_bytes_server(1_200, 8, "font/ttf", LATE_FONT);
+ let page_url = format!("http://{address}/page");
+ let font_url = format!("http://{address}/late.ttf");
+ let mut page = page_with_transport_and_body(
+ "fixed-wait",
+ &page_url,
+ &format!(
+ r#"<style>@font-face {{ font-family: Late; src: url({font_url}); }}</style>
+ <p><span id="t" style="font-family:Late;font-size:20px">MMMMMMMMMMMMMMMMMMMM</span></p>"#
+ ),
+ );
+ {
+ let js = page.js.as_mut().unwrap();
+ js.evaluate(
+ r#"(function() {
+ const t = document.getElementById('t');
+ // The first geometry read records the miss; the timers
+ // only sample.
+ window.__samples = [[0, t.getBoundingClientRect().width]];
+ const started = Date.now();
+ setInterval(() => {
+ window.__samples.push([Date.now() - started, t.getBoundingClientRect().width]);
+ }, 20);
+ return true;
+ })()"#,
+ )
+ .unwrap();
+ }
+ page.queue_pending_render_resources();
+ assert!(page.has_pending_render_resources(), "the font is a layout miss");
+ page.js
+ .as_mut()
+ .unwrap()
+ .run_event_loop_for_duration(2_200)
+ .await
+ .unwrap();
+ let samples = page
+ .js
+ .as_mut()
+ .unwrap()
+ .evaluate("JSON.stringify(window.__samples)")
+ .unwrap();
+ let samples: Vec<(f64, f64)> =
+ serde_json::from_str(samples.as_str().unwrap_or("[]")).unwrap();
+ assert!(samples.len() > 20, "timers must have run: {samples:?}");
+ let first = samples[0].1;
+ let changed = samples.iter().find(|(_, width)| *width != first);
+ assert!(
+ changed.is_some(),
+ "a sample inside the wait must show the applied font, all {first}: {samples:?}"
+ );
+ let (at_ms, _) = changed.unwrap();
+ assert!(*at_ms < 2_100.0, "observed only at {at_ms} ms: {samples:?}");
+ }
+
+ /// A load that finishes while the warmup scan runs (its wake is already
+ /// past when the wait is registered) must be applied without waiting for
+ /// the whole deadline. Two worker threads let the transport finish while
+ /// the page is busy scanning a large document.
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn a_load_that_finished_during_the_scan_does_not_cost_the_deadline() {
+ let (address, _seen_rx) = spawn_delayed_bytes_server(1, 8, "font/ttf", LATE_FONT);
+ let page_url = format!("http://{address}/page");
+ let font_url = format!("http://{address}/quick.ttf");
+ // A large document makes the warmup's light-DOM scan take tens of
+ // milliseconds without any layout (nothing here reads geometry).
+ let filler: String = (0..200_000).map(|_| "<i></i>").collect();
+ let mut page = page_with_transport_and_body(
+ "scan-race",
+ &page_url,
+ &format!(
+ r#"<style>@font-face {{ font-family: Q; src: url({font_url}); }}</style>
+ <span id="t" style="font-family:Q">t</span>{filler}"#
+ ),
+ );
+ {
+ // The font is already in flight (as after a layout miss); it
+ // answers in about a millisecond, while the scan runs far longer.
+ let js = page.js.as_mut().unwrap();
+ let requests =
+ js.mark_render_resources_in_flight(vec![(font_url.clone(), None, true)]);
+ assert_eq!(js.start_render_resource_loads(requests), 1);
+ }
+ assert!(page.has_pending_render_resources());
+ let started = std::time::Instant::now();
+ let loaded = page.prepare_screenshot_resources(1_000).await;
+ let elapsed = started.elapsed();
+ assert_eq!(loaded, 1);
+ assert!(!page.has_pending_render_resources());
+ assert!(
+ elapsed < std::time::Duration::from_millis(900),
+ "prepare must return once the load is applied, took {elapsed:?}"
+ );
+ }
+
+ /// Renderer misses follow the page's `Fetch.enable` interception policy
+ /// like the warmup scan: an intercepted URL is not fetched behind the
+ /// client's back, other URLs still load.
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn renderer_misses_honour_fetch_interception_patterns() {
+ let (address, _peak, _open, seen_rx) = spawn_counting_svg_server(0, 6);
+ let page_url = format!("http://{address}/page");
+ let intercepted = format!("http://{address}/intercepted.ttf");
+ let plain = format!("http://{address}/plain.ttf");
+ let mut page = page_with_transport_and_body(
+ "interception",
+ &page_url,
+ &format!(
+ r#"<style>@font-face {{ font-family: A; src: url({intercepted}); }}
+ @font-face {{ font-family: B; src: url({plain}); }}</style>
+ <p id="a" style="font-family:A">a</p><p id="b" style="font-family:B">b</p>"#
+ ),
+ );
+ // What `Fetch.enable` does: patterns first, then enable.
+ page.intercept_block_patterns = vec!["*intercepted.ttf".to_string()];
+ page.enable_intercept(true);
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('a').getBoundingClientRect().width + document.getElementById('b').getBoundingClientRect().width")
+ .unwrap();
+ page.queue_pending_render_resources();
+ assert!(page.prepare_screenshot_resources(3_000).await <= 1);
+ assert!(!page.has_pending_render_resources());
+ let mut lines = Vec::new();
+ while let Ok(line) = seen_rx.try_recv() {
+ lines.push(line);
+ }
+ assert!(
+ lines.iter().all(|line| !line.contains("/intercepted.ttf")),
+ "an intercepted URL must not be fetched: {lines:?}"
+ );
+ assert!(
+ lines.iter().any(|line| line.starts_with("GET /plain.ttf ")),
+ "other URLs still load: {lines:?}"
+ );
+ let js = page.js.as_ref().unwrap();
+ assert!(js.render_resource_is_known(&intercepted), "intercepted URL is settled as missing");
+ assert!(js.render_resource_is_known(&plain));
+ // Disabling interception lifts the rule for later misses.
+ page.intercept_block_patterns.clear();
+ page.enable_intercept(false);
+ let late = format!("http://{address}/late-intercepted.ttf");
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate(&format!(
+ r#"(function() {{
+ document.fonts.add(new FontFace('C', 'url({late})'));
+ const a = document.getElementById('a');
+ a.style.fontFamily = 'C';
+ return a.getBoundingClientRect().width;
+ }})()"#
+ ))
+ .unwrap();
+ page.queue_pending_render_resources();
+ page.prepare_screenshot_resources(3_000).await;
+ assert!(
+ seen_rx.try_iter().any(|line| line.starts_with("GET /late-intercepted.ttf ")),
+ "without interception the URL loads"
+ );
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn render_resource_loads_share_one_page_wide_concurrency_limit() {
+ let (address, peak, _open, _seen_rx) = spawn_counting_svg_server(300, 8);
+ let page_url = format!("http://{address}/page");
+ let mut page = page_with_transport_and_body("limit", &page_url, "");
+ // Three groups added one after the other, each queued by its own
+ // paint miss while the previous group's loads are still running: all
+ // of them share one limiter. Every group must actually start loads.
+ for group in 0..3 {
+ let markup: String = (0..14)
+ .map(|index| {
+ format!(
+ r#"<div style="width:10px;height:10px;background-image:url(http://{address}/bg{group}-{index}.svg)"></div>"#
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("");
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate(&format!(
+ "document.body.insertAdjacentHTML('beforeend', {});",
+ serde_json::to_string(&markup).unwrap()
+ ))
+ .unwrap();
+ page.screenshot(page.viewport);
+ page.queue_pending_render_resources();
+ assert!(
+ page.has_pending_render_resources(),
+ "group {group} must have started loads of its own"
+ );
+ }
+ assert_eq!(page.prepare_screenshot_resources(8_000).await, 42);
+ assert!(!page.has_pending_render_resources());
+ let peak = peak.load(std::sync::atomic::Ordering::SeqCst);
+ assert!(
+ peak <= obscura_js::ops::RENDER_RESOURCE_CONCURRENCY,
+ "at most {} concurrent transport requests, observed {peak}",
+ obscura_js::ops::RENDER_RESOURCE_CONCURRENCY
+ );
+ assert!(peak >= 2, "loads still run concurrently, observed {peak}");
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn retired_document_loads_never_seed_the_next_document() {
+ use std::io::{Read, Write};
+ // First request: slow, 20x10. Every later request: immediate, 30x10.
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let address = listener.local_addr().unwrap();
+ let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let served = hits.clone();
+ std::thread::spawn(move || {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
+ while std::time::Instant::now() < deadline {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let index = served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ std::thread::spawn(move || {
+ let mut request = [0u8; 2048];
+ let _ = stream.read(&mut request);
+ let width = if index == 0 {
+ std::thread::sleep(std::time::Duration::from_millis(1_500));
+ 20
+ } else {
+ 30
+ };
+ let body = format!(
+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="10"><rect width="{width}" height="10" fill="#f00"/></svg>"##
+ );
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.write_all(body.as_bytes());
+ });
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ Err(_) => break,
+ }
+ }
+ });
+
+ let page_url = format!("http://{address}/page");
+ let asset_url = format!("http://{address}/shared.svg");
+ let mut page = page_with_transport_and_image("retire", &page_url, &asset_url);
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').getBoundingClientRect().width")
+ .unwrap();
+ page.queue_pending_render_resources();
+ assert!(page.has_pending_render_resources(), "document A requests the asset");
+ // Let A's request reach the server before the document changes; the
+ // slow response is still 1.5 s away.
+ for _ in 0..40 {
+ if hits.load(std::sync::atomic::Ordering::SeqCst) >= 1 {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
+ assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 1, "A's request is in flight");
+
+ // Document B replaces A before A's slow response arrives (what
+ // navigate_single does before loading the next document).
+ page.retire_render_resources();
+ assert!(!page.has_pending_render_resources());
+ let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
+ runtime.set_dom(parse_html(&format!(
+ r#"<html><body><img id="i" src="{asset_url}"></body></html>"#
+ )));
+ runtime.set_url(&page_url);
+ runtime.set_viewport(100.0, 80.0);
+ runtime.set_http_client(page.http_client.clone());
+ runtime.set_callbacks(page.callbacks.clone());
+ runtime.run_page_init();
+ page.js = Some(runtime);
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').getBoundingClientRect().width")
+ .unwrap();
+ page.queue_pending_render_resources();
+ assert!(
+ page.has_pending_render_resources(),
+ "document B must request the same URL itself despite A's abandoned load"
+ );
+ assert_eq!(page.prepare_screenshot_resources(3_000).await, 1);
+ let natural_width = |page: &mut super::Page| {
+ page.js
+ .as_mut()
+ .unwrap()
+ .evaluate("document.getElementById('i').naturalWidth")
+ .unwrap()
+ .as_f64()
+ };
+ assert_eq!(natural_width(&mut page), Some(30.0), "B sees its own response");
+
+ // A's response would land now if its task were still alive; either
+ // way it must not replace B's bytes.
+ tokio::time::sleep(std::time::Duration::from_millis(1_800)).await;
+ page.drain_render_resource_results();
+ assert_eq!(natural_width(&mut page), Some(30.0), "A's stale response is discarded");
+ assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 2, "one request per document");
+ }
+
#[cfg(feature = "render")]
#[tokio::test(flavor = "current_thread")]
async fn render_resource_deadline_does_not_negative_cache_cancelled_requests() {
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index 2346de37..daa1eb9d 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -905,6 +905,7 @@ async fn cdp_processor(
tokio::task::yield_now().await;
}
}
+ service_live_page_render_resources(&mut ctx);
sync_live_page_network_events(&mut ctx);
dispatch::drain_runtime_events(&mut ctx);
dispatch::drain_binding_calls(&mut ctx);
@@ -1112,6 +1113,17 @@ async fn pump_live_page_event_loop(ctx: &mut CdpContext) -> Result<bool, String>
Ok(all_idle)
}
+/// Apply finished background render-resource loads and start loads for
+/// resources the last layout/paint missed, for every live page. Runs before a
+/// command (so it observes bytes that landed while the client was silent),
+/// after a command (so its layout misses start loading immediately) and after
+/// each autonomous pump turn.
+fn service_live_page_render_resources(ctx: &mut CdpContext) {
+ for page in ctx.pages.iter_mut().filter(|page| page.has_js()) {
+ page.queue_pending_render_resources();
+ }
+}
+
fn sync_live_page_network_events(ctx: &mut CdpContext) {
// Emit script-initiated network events for every live page, each attributed
// to its own session/frame — not just the first live page (#872).
@@ -1572,7 +1584,9 @@ async fn process_cdp_message(
tracing::debug!("CDP: {} (id={}, s={:?})", req.method, req.id, req.session_id);
+ service_live_page_render_resources(ctx);
let response = dispatch::dispatch(&req, ctx).await;
+ service_live_page_render_resources(ctx);
// Chromium CDP semantics: events emitted as a side-effect of a command
// (e.g. Target.targetCreated + Target.attachedToTarget from
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 01fcf9ec..9066a71b 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -225,6 +225,40 @@ pub struct ObscuraState {
#[cfg(feature = "render")]
pub render_image_in_flight:
HashMap<(u64, String, ImageRequestProfile), Vec<tokio::sync::oneshot::Sender<()>>>,
+ /// Page-transport loads for resources that cache-only layout or paint
+ /// missed. The owning page fetches them and sends the outcome here; the
+ /// runtime applies results at its own event-loop turns and at every
+ /// promise wait, so a script polling geometry sees them. `document_generation`
+ /// in each result fences a previous document's late answer.
+ #[cfg(feature = "render")]
+ pub render_resource_tx: tokio::sync::mpsc::UnboundedSender<RenderResourceLoad>,
+ #[cfg(feature = "render")]
+ pub render_resource_rx: tokio::sync::mpsc::UnboundedReceiver<RenderResourceLoad>,
+ /// Resources currently loading through the page transport, so repeated
+ /// misses never duplicate a request.
+ #[cfg(feature = "render")]
+ pub render_resource_in_flight:
+ std::collections::HashSet<(String, Option<ImageRequestProfile>, bool)>,
+ /// Applied transport responses the page still has to report as
+ /// Network events (recording needs the page, not the runtime).
+ #[cfg(feature = "render")]
+ pub render_resource_events: Vec<RenderResourceEvent>,
+ /// `Fetch.enable` URL patterns mirrored from the owning page, so the
+ /// renderer's resource loads follow the same interception policy as the
+ /// page's own subresource fetches (a matching URL is not fetched here).
+ #[cfg(feature = "render")]
+ pub intercept_block_patterns: Vec<String>,
+ /// Background transport tasks of this document, one page-wide
+ /// concurrency limit shared by all of them, a wake-up for waiters, and
+ /// requests that could not be started outside a Tokio context.
+ #[cfg(feature = "render")]
+ pub render_resource_tasks: Vec<tokio::task::JoinHandle<()>>,
+ #[cfg(feature = "render")]
+ pub render_resource_limiter: Arc<tokio::sync::Semaphore>,
+ #[cfg(feature = "render")]
+ pub render_resource_notify: Arc<tokio::sync::Notify>,
+ #[cfg(feature = "render")]
+ pub render_resource_backlog: Vec<(String, Option<ImageRequestProfile>, bool)>,
/// One exact-key compiled author stylesheet for this document. Connected
/// mutations still discard `prepared_render`; the next prepare reuses only
/// parsing/indexing when ordered CSS source and viewport remain identical.
@@ -301,6 +335,8 @@ pub struct PendingFrameMessage {
impl ObscuraState {
pub fn new() -> Self {
+ #[cfg(feature = "render")]
+ let (render_resource_tx, render_resource_rx) = tokio::sync::mpsc::unbounded_channel();
ObscuraState {
dom: None,
url: "about:blank".to_string(),
@@ -357,6 +393,26 @@ impl ObscuraState {
#[cfg(feature = "render")]
render_image_in_flight: HashMap::new(),
#[cfg(feature = "render")]
+ render_resource_tx,
+ #[cfg(feature = "render")]
+ render_resource_rx,
+ #[cfg(feature = "render")]
+ render_resource_in_flight: std::collections::HashSet::new(),
+ #[cfg(feature = "render")]
+ render_resource_events: Vec::new(),
+ #[cfg(feature = "render")]
+ intercept_block_patterns: Vec::new(),
+ #[cfg(feature = "render")]
+ render_resource_tasks: Vec::new(),
+ #[cfg(feature = "render")]
+ render_resource_limiter: Arc::new(tokio::sync::Semaphore::new(
+ RENDER_RESOURCE_CONCURRENCY,
+ )),
+ #[cfg(feature = "render")]
+ render_resource_notify: Arc::new(tokio::sync::Notify::new()),
+ #[cfg(feature = "render")]
+ render_resource_backlog: Vec::new(),
+ #[cfg(feature = "render")]
stylesheet_cache: obscura_render::StylesheetCache::default(),
#[cfg(feature = "render")]
dynamic_fonts: Vec::new(),
@@ -1035,6 +1091,73 @@ pub(crate) fn queue_retained_style_mutation(
true
}
+/// Page-wide limit on concurrent background render-resource requests: the
+/// bound the navigation warmup stream always had, now shared by every load
+/// of the document however many scans or layout misses queue them.
+#[cfg(feature = "render")]
+pub const RENDER_RESOURCE_CONCURRENCY: usize = 16;
+
+/// One finished page-transport load for the renderer cache.
+#[cfg(feature = "render")]
+#[derive(Debug)]
+pub struct RenderResourceLoad {
+ /// `document_generation` the request was made for.
+ pub generation: u64,
+ pub url: String,
+ pub profile: Option<ImageRequestProfile>,
+ pub is_font: bool,
+ /// Final URL, status, headers and body of the response; `None` when the
+ /// request failed or was blocked.
+ pub response: Option<RenderResourceResponse>,
+}
+
+#[cfg(feature = "render")]
+#[derive(Debug)]
+pub struct RenderResourceResponse {
+ pub url: String,
+ pub status: u16,
+ pub headers: std::collections::HashMap<String, String>,
+ pub body: Arc<[u8]>,
+}
+
+/// A transport response the runtime applied; the page turns it into the
+/// Network events a client expects for a subresource.
+#[cfg(feature = "render")]
+#[derive(Debug)]
+pub struct RenderResourceEvent {
+ pub is_font: bool,
+ pub response: RenderResourceResponse,
+}
+
+/// Whether this runtime is owned by a page with an asynchronous transport.
+#[cfg(feature = "render")]
+pub(crate) fn has_page_transport(state: &ObscuraState) -> bool {
+ #[cfg(feature = "stealth")]
+ {
+ state.http_client.is_some() || state.stealth_client.is_some()
+ }
+ #[cfg(not(feature = "stealth"))]
+ {
+ state.http_client.is_some()
+ }
+}
+
+/// Build the renderer resource cache for this runtime. A runtime owned by a
+/// page must never let layout or paint open their own synchronous HTTP
+/// requests: the compatibility loader bypasses the page's proxy, cookies,
+/// interception and URL blocking, and it pins V8 for the full network
+/// latency of every unknown asset (retries included). Such runtimes start
+/// cache-only and are fed through the page transport; standalone render
+/// runtimes without a transport keep the compatibility loader.
+#[cfg(feature = "render")]
+pub(crate) fn fresh_render_resources(state: &ObscuraState) -> obscura_render::RenderResourceCache {
+ let mut cache = obscura_render::RenderResourceCache::default();
+ if has_page_transport(state) {
+ cache.set_sync_loading_enabled(false);
+ }
+ cache
+}
+
/// Rebuild resource-dependent geometry while retaining the previous computed
/// style graph. Image intrinsic sizes and font metrics can reflow the whole
/// document, but neither changes selector matching or computed declarations.
@@ -3109,7 +3232,7 @@ async fn stealth_fetch_all(
.to_string())
}
-fn glob_match(pattern: &str, url: &str) -> bool {
+pub(crate) fn glob_match(pattern: &str, url: &str) -> bool {
if pattern == "*" {
return true;
}
@@ -5650,8 +5773,9 @@ fn op_image_metadata(state: &OpState, nid: u32, _cached_only: bool) -> String {
/// Compatibility path for standalone render runtimes which deliberately
/// install an in-memory `RenderResourceLoader` but have no owning page
-/// transport. Browser pages always install `ObscuraHttpClient` before page
-/// script runs and never enter this synchronous loader.
+/// transport. Browser pages install their transport before page script runs;
+/// their caches are cache-only (`fresh_render_resources`), so neither this
+/// path nor layout/paint can open a synchronous request for them.
#[cfg(feature = "render")]
fn load_image_metadata_without_page_transport(gs: &mut ObscuraState, node_id: NodeId) -> String {
let base_url = document_base_url(&gs);
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 5ff65d96..561b5d6a 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -8,6 +8,8 @@ use std::task::{Context, Poll};
use deno_core::{JsRuntime, RuntimeOptions};
use obscura_dom::{DomTree, NodeId};
+#[cfg(feature = "render")]
+use obscura_net::{RequestCredentials, RequestMode, ResourceRequest};
/// Re-exported so other crates (obscura-browser, obscura-cdp) can name the V8
/// isolate handle without taking a direct dependency on deno_core.
@@ -59,6 +61,21 @@ static ISOLATE_CREATE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
const DEFAULT_CDP_AWAIT_TIMEOUT_MS: u64 = 30_000;
const HEAP_LIMIT_RECOVERY_HEADROOM_BYTES: usize = 64 * 1024 * 1024;
+#[cfg(feature = "render")]
+const MAX_PENDING_RENDER_RESOURCES: usize = 128;
+
+#[cfg(feature = "render")]
+fn page_render_resource_url_allowed(document_url: &str, resource_url: &str) -> bool {
+ url::Url::parse(resource_url)
+ .map(|resource| match resource.scheme() {
+ "http" | "https" => true,
+ "file" => url::Url::parse(document_url)
+ .map(|document| document.scheme() == "file")
+ .unwrap_or(false),
+ _ => false,
+ })
+ .unwrap_or(false)
+}
#[derive(Default)]
struct HeapLimitState {
@@ -445,6 +462,13 @@ impl Drop for EnteredRuntime<'_> {
impl Drop for ObscuraJsRuntime {
fn drop(&mut self) {
+ // Background render-resource loads belong to this runtime's document;
+ // a dropped JoinHandle would only detach them (the page also calls
+ // `abandon_render_resources`, a directly embedded runtime may not).
+ #[cfg(feature = "render")]
+ for task in self.state.borrow_mut().render_resource_tasks.drain(..) {
+ task.abort();
+ }
// Teardown needs the isolate current as much as any other V8 work:
// deno_core's context cleanup clears the context's embedder slots, and
// rusty_v8's `OwnedIsolate::drop` asserts it before disposing. Both run
@@ -867,6 +891,14 @@ impl ObscuraJsRuntime {
{
frame.stealth_client = parent.stealth_client.clone();
}
+ // A frame realm shares the page transport, so its renderer cache must
+ // not open synchronous requests either. Frame geometry currently
+ // resolves against the main document's renderer state, so frame-scoped
+ // background loading is not wired up here.
+ #[cfg(feature = "render")]
+ if crate::ops::has_page_transport(&parent) {
+ frame.render_resources.set_sync_loading_enabled(false);
+ }
}
/// The origin of the document this runtime is running, or `"null"` for a
@@ -1063,7 +1095,12 @@ impl ObscuraJsRuntime {
}
pub fn set_http_client(&self, client: std::sync::Arc<obscura_net::ObscuraHttpClient>) {
- self.state.borrow_mut().http_client = Some(client);
+ let mut state = self.state.borrow_mut();
+ state.http_client = Some(client);
+ // A page transport makes the renderer cache-only; see
+ // `ops::fresh_render_resources` for why layout must not fetch itself.
+ #[cfg(feature = "render")]
+ state.render_resources.set_sync_loading_enabled(false);
}
/// Install the owning page's passive on_request/on_response callback
@@ -1076,7 +1113,10 @@ impl ObscuraJsRuntime {
/// through it in stealth mode (see op_fetch_url / stealth_fetch_all).
#[cfg(feature = "stealth")]
pub fn set_stealth_client(&self, client: std::sync::Arc<obscura_net::StealthHttpClient>) {
- self.state.borrow_mut().stealth_client = Some(client);
+ let mut state = self.state.borrow_mut();
+ state.stealth_client = Some(client);
+ #[cfg(feature = "render")]
+ state.render_resources.set_sync_loading_enabled(false);
}
pub fn set_dom(&self, dom: DomTree) {
@@ -1096,8 +1136,21 @@ impl ObscuraJsRuntime {
gs.animation_task_generation = 0;
gs.animation_sampled_task_generation = 0;
gs.pending_style_mutations.clear();
- gs.render_resources = obscura_render::RenderResourceCache::default();
+ let render_resources = crate::ops::fresh_render_resources(&gs);
+ gs.render_resources = render_resources;
gs.render_image_in_flight.clear();
+ for task in gs.render_resource_tasks.drain(..) {
+ task.abort();
+ }
+ gs.render_resource_in_flight.clear();
+ gs.render_resource_backlog.clear();
+ gs.render_resource_events.clear();
+ // A fresh channel: a load of the old document that is still
+ // finishing (abort is not a join) delivers into a dropped
+ // receiver, never into this document's results.
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ gs.render_resource_tx = tx;
+ gs.render_resource_rx = rx;
gs.stylesheet_cache = obscura_render::StylesheetCache::default();
gs.dynamic_fonts.clear();
gs.canvas_surfaces.clear();
@@ -1282,6 +1335,13 @@ impl ObscuraJsRuntime {
state.intercept_enabled = enabled;
}
+ /// `Fetch.enable` URL patterns of the owning page. Renderer resource
+ /// loads honour them like the page's own subresource fetches do.
+ #[cfg(feature = "render")]
+ pub fn set_intercept_block_patterns(&self, patterns: Vec<String>) {
+ self.state.borrow_mut().intercept_block_patterns = patterns;
+ }
+
pub fn set_user_agent(&mut self, ua: &str) {
let _ = self.execute_runtime_script(
"<set-ua>",
@@ -1771,10 +1831,19 @@ impl ObscuraJsRuntime {
/// retained layout/scroll.
#[cfg(feature = "render")]
pub fn seed_render_resource(&mut self, url: String, bytes: Option<Vec<u8>>) {
+ self.seed_shared_render_resource(url, bytes.map(std::sync::Arc::from));
+ }
+
+ #[cfg(feature = "render")]
+ fn seed_shared_render_resource(
+ &mut self,
+ url: String,
+ bytes: Option<std::sync::Arc<[u8]>>,
+ ) {
let mut state = self.state.borrow_mut();
match bytes {
Some(bytes) => {
- state.render_resources.seed(url, bytes);
+ state.render_resources.seed_shared(url, bytes);
crate::ops::invalidate_render_resource_geometry(&mut state);
}
None => state.render_resources.seed_missing(url),
@@ -1787,6 +1856,16 @@ impl ObscuraJsRuntime {
url: String,
profile: crate::ops::ImageRequestProfile,
bytes: Option<Vec<u8>>,
+ ) {
+ self.seed_shared_render_image_resource(url, profile, bytes.map(std::sync::Arc::from));
+ }
+
+ #[cfg(feature = "render")]
+ fn seed_shared_render_image_resource(
+ &mut self,
+ url: String,
+ profile: crate::ops::ImageRequestProfile,
+ bytes: Option<std::sync::Arc<[u8]>>,
) {
let mut state = self.state.borrow_mut();
match bytes {
@@ -1797,7 +1876,9 @@ impl ObscuraJsRuntime {
}
_ => true,
};
- state.render_resources.seed_image(url, profile, bytes);
+ state
+ .render_resources
+ .seed_image_shared(url, profile, bytes);
state.activity_generation = state.activity_generation.wrapping_add(1);
if needs_geometry {
crate::ops::invalidate_render_resource_geometry(&mut state);
@@ -1812,6 +1893,367 @@ impl ObscuraJsRuntime {
self.state.borrow().render_resources.has_live_outcome(url)
}
+ /// Whether layout and paint may still open synchronous compatibility
+ /// requests. False for every runtime owned by a page transport.
+ #[cfg(feature = "render")]
+ pub fn render_resource_sync_loading_enabled(&self) -> bool {
+ self.state.borrow().render_resources.sync_loading_enabled()
+ }
+
+ #[cfg(test)]
+ fn document_generation(&self) -> u64 {
+ self.state.borrow().document_generation
+ }
+
+ /// Resources cache-only layout or paint asked for and did not have, ready
+ /// for the page transport: blocked URLs are remembered as missing instead
+ /// of returned, URLs already loading are skipped, the rest are marked in
+ /// flight. Cheap when nothing was missed.
+ #[cfg(feature = "render")]
+ pub fn take_render_resource_requests(
+ &self,
+ ) -> Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)> {
+ let mut state = self.state.borrow_mut();
+ if !state.render_resources.has_sync_misses() {
+ return Vec::new();
+ }
+ let misses = state.render_resources.take_sync_misses();
+ let mut requests = Vec::new();
+ for (url, profile, is_font) in misses {
+ // Same policy as `Page::should_block_url`: `Network.setBlockedURLs`
+ // patterns, and while `Fetch.enable` is active also its patterns
+ // (an intercepted subresource is not fetched behind the client's
+ // back). The matcher is the page's CDP pattern matcher.
+ let blocked = state
+ .blocked_urls
+ .iter()
+ .any(|pattern| crate::ops::glob_match(pattern, &url))
+ || (state.intercept_enabled
+ && state
+ .intercept_block_patterns
+ .iter()
+ .any(|pattern| crate::ops::glob_match(pattern, &url)));
+ let allowed = page_render_resource_url_allowed(&state.url, &url);
+ if blocked || !allowed {
+ match profile {
+ Some(profile) => state.render_resources.seed_image_missing(url, profile),
+ None => state.render_resources.seed_missing(url),
+ }
+ continue;
+ }
+ if state.render_resource_in_flight.len() >= MAX_PENDING_RENDER_RESOURCES {
+ continue;
+ }
+ if state
+ .render_resource_in_flight
+ .insert((url.clone(), profile, is_font))
+ {
+ requests.push((url, profile, is_font));
+ }
+ }
+ requests
+ }
+
+ /// Mark resources the page discovered itself (navigation warmup scan) as
+ /// loading, returning the ones that were not already in flight.
+ #[cfg(feature = "render")]
+ pub fn mark_render_resources_in_flight(
+ &self,
+ candidates: Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)>,
+ ) -> Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)> {
+ let mut state = self.state.borrow_mut();
+ let available = MAX_PENDING_RENDER_RESOURCES
+ .saturating_sub(state.render_resource_in_flight.len());
+ candidates
+ .into_iter()
+ .filter(|(url, profile, is_font)| {
+ state
+ .render_resource_in_flight
+ .insert((url.clone(), *profile, *is_font))
+ })
+ .take(available)
+ .collect()
+ }
+
+ /// Abort every background load of this document and discard results
+ /// that already arrived. The page calls this when the document goes away
+ /// (navigation, blank reset, suspension, teardown); `set_dom` and
+ /// `take_dom` do the same. Aborting drops the in-progress HTTP requests;
+ /// a load that is past the point of no return delivers into the old,
+ /// dropped channel.
+ #[cfg(feature = "render")]
+ pub fn abandon_render_resources(&self) {
+ let mut state = self.state.borrow_mut();
+ for task in state.render_resource_tasks.drain(..) {
+ task.abort();
+ }
+ state.render_resource_in_flight.clear();
+ state.render_resource_backlog.clear();
+ state.render_resource_events.clear();
+ // A fresh channel fences results that are still on their way (abort
+ // is not a join) even when this runtime survives, as after a failed
+ // navigation.
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ state.render_resource_tx = tx;
+ state.render_resource_rx = rx;
+ }
+
+ /// Whether a page transport (plain or stealth client) is installed.
+ #[cfg(feature = "render")]
+ pub fn has_page_transport(&self) -> bool {
+ crate::ops::has_page_transport(&self.state.borrow())
+ }
+
+ /// Wake-up shared with the background loads: notified after every
+ /// finished load. Waiters must create and enable their `Notified`
+ /// before checking `has_pending_render_resources`, or a load finishing
+ /// in between is missed.
+ #[cfg(feature = "render")]
+ pub fn render_resource_notify(&self) -> std::sync::Arc<tokio::sync::Notify> {
+ self.state.borrow().render_resource_notify.clone()
+ }
+
+ /// Start page-transport loads for `requests` (already marked in flight).
+ /// Requests keep cookies, proxy policy, callbacks, CORS and response
+ /// limits of the page transport, share the page-wide concurrency limit,
+ /// run to completion in the background and deliver into this runtime's
+ /// result channel. Outside a Tokio context the requests are kept in a
+ /// backlog and started at the next event-loop turn. Returns the number
+ /// of requests started now.
+ #[cfg(feature = "render")]
+ pub fn start_render_resource_loads(
+ &self,
+ requests: Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)>,
+ ) -> usize {
+ if requests.is_empty() {
+ return 0;
+ }
+ let mut state = self.state.borrow_mut();
+ if tokio::runtime::Handle::try_current().is_err() {
+ state.render_resource_backlog.extend(requests);
+ return 0;
+ }
+ // The page transport is the plain client or, when installed, the
+ // stealth client; either one on its own is enough (`has_page_transport`).
+ let http_client = state.http_client.clone();
+ #[cfg(feature = "stealth")]
+ let stealth_client = state.stealth_client.clone();
+ let initiator = url::Url::parse(&state.url).ok();
+ if !crate::ops::has_page_transport(&state) || initiator.is_none() {
+ // No transport or no document URL: nothing can be loaded; forget
+ // the in-flight marks so a later scan may retry.
+ for request in &requests {
+ state.render_resource_in_flight.remove(request);
+ }
+ return 0;
+ }
+ let initiator = initiator.expect("checked above");
+ let callbacks = state.callbacks.clone();
+ let generation = state.document_generation;
+ let tx = state.render_resource_tx.clone();
+ let limiter = state.render_resource_limiter.clone();
+ let notify = state.render_resource_notify.clone();
+ let started = requests.len();
+ let task = tokio::spawn(async move {
+ use deno_core::futures::StreamExt as _;
+ let loads = deno_core::futures::stream::iter(requests.into_iter().map(|(raw, profile, is_font)| {
+ let http_client = http_client.clone();
+ #[cfg(feature = "stealth")]
+ let stealth_client = stealth_client.clone();
+ let callbacks = callbacks.clone();
+ let initiator = initiator.clone();
+ let limiter = limiter.clone();
+ let fallback = (raw.clone(), profile, is_font);
+ let load = async move {
+ // Every load of this page waits for the same permits, so
+ // repeated scans cannot multiply the request rate.
+ let _permit = limiter.acquire_owned().await.ok();
+ let parsed = match url::Url::parse(&raw) {
+ Ok(parsed) => parsed,
+ Err(_) => {
+ return crate::ops::RenderResourceLoad {
+ generation,
+ url: raw,
+ profile,
+ is_font,
+ response: None,
+ }
+ }
+ };
+ let kind = if is_font {
+ obscura_net::ResourceType::Font
+ } else {
+ obscura_net::ResourceType::Image
+ };
+ let mut request = ResourceRequest::subresource(kind, &initiator);
+ match profile {
+ Some(crate::ops::ImageRequestProfile::CorsSameOrigin) => {
+ request.mode = RequestMode::Cors;
+ request.credentials = RequestCredentials::SameOrigin;
+ }
+ Some(crate::ops::ImageRequestProfile::CorsInclude) => {
+ request.mode = RequestMode::Cors;
+ request.credentials = RequestCredentials::Include;
+ }
+ _ => {}
+ }
+ #[cfg(feature = "stealth")]
+ let response = match (stealth_client, http_client) {
+ (Some(stealth_client), _) => stealth_client
+ .fetch_resource_with_callbacks(&parsed, request, callbacks.as_deref())
+ .await
+ .ok(),
+ (None, Some(http_client)) => http_client
+ .fetch_resource_with_callbacks(&parsed, request, callbacks.as_deref())
+ .await
+ .ok(),
+ (None, None) => None,
+ };
+ #[cfg(not(feature = "stealth"))]
+ let response = match http_client {
+ Some(http_client) => http_client
+ .fetch_resource_with_callbacks(&parsed, request, callbacks.as_deref())
+ .await
+ .ok(),
+ None => None,
+ };
+ crate::ops::RenderResourceLoad {
+ generation,
+ url: raw,
+ profile,
+ is_font,
+ response: response.map(|response| crate::ops::RenderResourceResponse {
+ url: response.url.to_string(),
+ status: response.status,
+ headers: response.headers,
+ body: std::sync::Arc::from(response.body),
+ }),
+ }
+ };
+ // One failing load must not strand the rest of the batch: an
+ // in-flight entry without a result would keep waiters waiting.
+ use deno_core::futures::FutureExt as _;
+ std::panic::AssertUnwindSafe(load)
+ .catch_unwind()
+ .map(move |outcome| {
+ outcome.unwrap_or_else(|_| crate::ops::RenderResourceLoad {
+ generation,
+ url: fallback.0,
+ profile: fallback.1,
+ is_font: fallback.2,
+ response: None,
+ })
+ })
+ }))
+ .buffer_unordered(crate::ops::RENDER_RESOURCE_CONCURRENCY);
+ deno_core::futures::pin_mut!(loads);
+ while let Some(load) = loads.next().await {
+ tracing::debug!(
+ url = %load.url,
+ ok = load.response.is_some(),
+ "render resource load finished"
+ );
+ if tx.send(load).is_err() {
+ break;
+ }
+ notify.notify_waiters();
+ }
+ notify.notify_waiters();
+ });
+ state.render_resource_tasks.retain(|task| !task.is_finished());
+ state.render_resource_tasks.push(task);
+ tracing::debug!(started, generation, "started background render resource loads");
+ started
+ }
+
+ /// One service step for the renderer's resources: apply every finished
+ /// load, then start loads for everything layout or paint missed since
+ /// the last step. Runs at every event-loop turn and promise wait of this
+ /// runtime, so a script that creates a miss while a command is waiting
+ /// still gets its bytes without a further protocol round trip. Returns
+ /// the number of loads that stored usable bytes.
+ #[cfg(feature = "render")]
+ pub fn service_render_resources(&mut self) -> usize {
+ {
+ let state = self.state.borrow();
+ if state.render_resource_rx.is_empty()
+ && state.render_resource_backlog.is_empty()
+ && !state.render_resources.has_sync_misses()
+ {
+ return 0;
+ }
+ }
+ let loaded = self.apply_render_resource_results();
+ let mut requests = std::mem::take(&mut self.state.borrow_mut().render_resource_backlog);
+ requests.extend(self.take_render_resource_requests());
+ self.start_render_resource_loads(requests);
+ loaded
+ }
+
+ /// Whether page-transport loads are still running for this document.
+ #[cfg(feature = "render")]
+ pub fn has_pending_render_resources(&self) -> bool {
+ !self.state.borrow().render_resource_in_flight.is_empty()
+ }
+
+ /// Apply every finished page-transport load without waiting. Called at
+ /// the runtime's own event-loop turns and promise waits and by the page
+ /// around protocol commands, so late bytes reach layout, paint and the
+ /// lifecycle getters wherever the runtime is being driven. Returns the
+ /// number of loads that stored usable bytes.
+ #[cfg(feature = "render")]
+ pub fn apply_render_resource_results(&mut self) -> usize {
+ let loads = {
+ let mut state = self.state.borrow_mut();
+ let mut loads = Vec::new();
+ while let Ok(load) = state.render_resource_rx.try_recv() {
+ loads.push(load);
+ }
+ loads
+ };
+ let mut loaded = 0;
+ for load in loads {
+ let generation = self.state.borrow().document_generation;
+ if load.generation != generation {
+ // A previous document's response: no seed, no event, and it
+ // must not clear a same-URL request of the current document.
+ tracing::debug!(url = %load.url, "discarded render resource load of a retired document");
+ continue;
+ }
+ self.state
+ .borrow_mut()
+ .render_resource_in_flight
+ .remove(&(load.url.clone(), load.profile, load.is_font));
+ let is_font = load.is_font;
+ let bytes = match &load.response {
+ Some(response) if (200..300).contains(&response.status) => {
+ loaded += 1;
+ Some(std::sync::Arc::clone(&response.body))
+ }
+ _ => None,
+ };
+ tracing::debug!(url = %load.url, loaded = bytes.is_some(), "applied render resource load");
+ match load.profile {
+ Some(profile) => self.seed_shared_render_image_resource(load.url, profile, bytes),
+ None => self.seed_shared_render_resource(load.url, bytes),
+ }
+ if let Some(response) = load.response {
+ self.state
+ .borrow_mut()
+ .render_resource_events
+ .push(crate::ops::RenderResourceEvent { is_font, response });
+ }
+ }
+ loaded
+ }
+
+ /// Applied transport responses the page has not reported as Network
+ /// events yet.
+ #[cfg(feature = "render")]
+ pub fn take_render_resource_events(&self) -> Vec<crate::ops::RenderResourceEvent> {
+ std::mem::take(&mut self.state.borrow_mut().render_resource_events)
+ }
+
#[cfg(feature = "render")]
pub fn render_image_resource_is_known(
&self,
@@ -1847,6 +2289,8 @@ impl ObscuraJsRuntime {
}
pub fn evaluate(&mut self, expression: &str) -> Result<serde_json::Value, String> {
+ #[cfg(feature = "render")]
+ self.service_render_resources();
self.begin_javascript_task();
let wrapped = Self::wrap_expression(expression);
let result = self
@@ -2879,6 +3323,8 @@ impl ObscuraJsRuntime {
/// the watchdog terminates it. A well-behaved page returns as soon as the
/// loop goes idle.
pub async fn run_event_loop_bounded(&mut self, budget_ms: u64) -> Result<(), String> {
+ #[cfg(feature = "render")]
+ self.service_render_resources();
if budget_ms == 0 {
return self.run_event_loop().await;
}
@@ -2903,6 +3349,10 @@ impl ObscuraJsRuntime {
if tokio::time::Instant::now() >= deadline {
break Ok(());
}
+ // Timer-driven page script observes resources that landed during
+ // the interval, and misses it creates start loading right away.
+ #[cfg(feature = "render")]
+ self.service_render_resources();
match tokio::time::timeout_at(deadline, self.run_cooperative_event_loop_tick()).await {
Ok(Ok(true)) => break Ok(()),
@@ -3006,6 +3456,8 @@ impl ObscuraJsRuntime {
const AUTONOMOUS_TASK_WATCHDOG_MS: u64 =
SYNCHRONOUS_TASK_FLOOR_MS + WATCHDOG_SCHEDULING_MARGIN_MS;
+ #[cfg(feature = "render")]
+ self.service_render_resources();
self.begin_javascript_task();
let checkpoint_watchdog = crate::cdp_watchdog::arm(
@@ -3070,6 +3522,8 @@ impl ObscuraJsRuntime {
/// boolean is true only when deno_core reached full idle.
#[doc(hidden)]
pub async fn run_load_delaying_event_loop_tick(&mut self) -> Result<bool, String> {
+ #[cfg(feature = "render")]
+ self.service_render_resources();
self.run_cooperative_event_loop_tick().await
}
@@ -3115,6 +3569,8 @@ impl ObscuraJsRuntime {
let mut generation = self.activity_generation();
let mut quiet_since: Option<tokio::time::Instant> = None;
let result = loop {
+ #[cfg(feature = "render")]
+ self.service_render_resources();
let now = tokio::time::Instant::now();
let Some(_remaining) = deadline.checked_duration_since(now) else {
break Ok(());
@@ -3271,6 +3727,8 @@ impl ObscuraJsRuntime {
tokio::time::Instant::now() + tokio::time::Duration::from_millis(max_total_ms);
let mut tick_ms: u64 = 1;
loop {
+ #[cfg(feature = "render")]
+ self.service_render_resources();
self.begin_javascript_task();
if done_check(self) {
return true;
@@ -3304,7 +3762,17 @@ impl ObscuraJsRuntime {
{
state.prepared_render = None;
state.pending_style_mutations.clear();
- state.render_resources = obscura_render::RenderResourceCache::default();
+ let render_resources = crate::ops::fresh_render_resources(&state);
+ state.render_resources = render_resources;
+ for task in state.render_resource_tasks.drain(..) {
+ task.abort();
+ }
+ state.render_resource_in_flight.clear();
+ state.render_resource_backlog.clear();
+ state.render_resource_events.clear();
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ state.render_resource_tx = tx;
+ state.render_resource_rx = rx;
state.stylesheet_cache = obscura_render::StylesheetCache::default();
state.dynamic_fonts.clear();
state.element_scroll_offsets.clear();
@@ -3739,6 +4207,159 @@ mod tests {
rt
}
+ #[cfg(feature = "render")]
+ #[test]
+ fn page_transport_keeps_render_resources_cache_only_across_document_resets() {
+ let standalone = ObscuraJsRuntime::new();
+ assert!(
+ standalone.render_resource_sync_loading_enabled(),
+ "standalone render runtimes keep the compatibility loader"
+ );
+ standalone.set_dom(parse_html("<html><body></body></html>"));
+ assert!(standalone.render_resource_sync_loading_enabled());
+
+ let rt = ObscuraJsRuntime::new();
+ rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));
+ assert!(
+ !rt.render_resource_sync_loading_enabled(),
+ "installing a page transport must switch the cache to cache-only"
+ );
+ rt.set_dom(parse_html(
+ "<html><body><img src=\"https://example.test/a.png\"></body></html>",
+ ));
+ assert!(
+ !rt.render_resource_sync_loading_enabled(),
+ "set_dom rebuilds the cache and must keep it cache-only"
+ );
+ assert!(rt.take_dom().is_some());
+ assert!(
+ !rt.render_resource_sync_loading_enabled(),
+ "take_dom rebuilds the cache and must keep it cache-only"
+ );
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn renderer_resource_transport_preserves_file_subresource_policy() {
+ let file = "file:///tmp/obscura-render-resource.svg";
+ assert!(page_render_resource_url_allowed(
+ "file:///tmp/obscura-page.html",
+ file
+ ));
+ assert!(!page_render_resource_url_allowed(
+ "https://example.test/page",
+ file
+ ));
+ assert!(page_render_resource_url_allowed(
+ "https://example.test/page",
+ "https://assets.test/image.svg"
+ ));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn render_resource_in_flight_set_has_a_page_wide_bound() {
+ let rt = ObscuraJsRuntime::new();
+ let requests = (0..(MAX_PENDING_RENDER_RESOURCES + 4))
+ .map(|index| (format!("https://assets.test/{index}.png"), None, false))
+ .collect();
+
+ assert_eq!(
+ rt.mark_render_resources_in_flight(requests).len(),
+ MAX_PENDING_RENDER_RESOURCES
+ );
+ assert!(rt
+ .mark_render_resources_in_flight(vec![(
+ "https://assets.test/extra.png".to_string(),
+ None,
+ false,
+ )])
+ .is_empty());
+ }
+
+ /// A load that answers after the document was retired (abort is not a
+ /// join) must neither seed the surviving runtime nor clear a same-URL
+ /// request of the document that replaced it.
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn late_channel_answer_of_a_retired_document_is_discarded() {
+ let url = "https://example.test/a.svg".to_string();
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));
+ rt.set_dom(parse_html(&format!("<html><body><img src=\"{url}\"></body></html>")));
+ rt.set_url("https://example.test/page");
+ let body = std::sync::Arc::<[u8]>::from(
+ br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"></svg>"##.as_slice(),
+ );
+ let answer = |generation, tx: &tokio::sync::mpsc::UnboundedSender<_>| {
+ tx.send(crate::ops::RenderResourceLoad {
+ generation,
+ url: url.clone(),
+ profile: None,
+ is_font: false,
+ response: Some(crate::ops::RenderResourceResponse {
+ url: url.clone(),
+ status: 200,
+ headers: Default::default(),
+ body: body.clone(),
+ }),
+ })
+ };
+ // The old document's load holds the sender it was started with.
+ let old_tx = rt.state.borrow().render_resource_tx.clone();
+ let generation = rt.document_generation();
+ rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);
+ rt.abandon_render_resources();
+ assert!(!rt.has_pending_render_resources());
+ assert!(answer(generation, &old_tx).is_err(), "retired channel is closed");
+ assert_eq!(rt.apply_render_resource_results(), 0);
+ assert!(!rt.render_resource_is_known(&url), "late bytes must not seed the runtime");
+
+ // The same runtime requests the URL again; a stale-generation answer
+ // that somehow reaches the live channel is fenced too.
+ let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);
+ assert_eq!(requests.len(), 1);
+ let live_tx = rt.state.borrow().render_resource_tx.clone();
+ assert!(answer(generation.wrapping_sub(1), &live_tx).is_ok());
+ assert_eq!(rt.apply_render_resource_results(), 0);
+ assert!(rt.has_pending_render_resources(), "stale answer must not clear the live request");
+ assert!(!rt.render_resource_is_known(&url));
+ assert!(answer(generation, &live_tx).is_ok());
+ assert_eq!(rt.apply_render_resource_results(), 1);
+ assert!(!rt.has_pending_render_resources());
+ assert!(rt.render_resource_is_known(&url));
+ }
+
+ /// A runtime with only the stealth client installed has a page transport
+ /// (`has_page_transport`, cache-only renderer) and must load through it.
+ #[cfg(all(feature = "render", feature = "stealth"))]
+ #[tokio::test(flavor = "current_thread")]
+ async fn stealth_only_transport_starts_render_resource_loads() {
+ let url = "http://127.0.0.1:9/a.svg".to_string();
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_stealth_client(std::sync::Arc::new(obscura_net::StealthHttpClient::with_proxy(
+ std::sync::Arc::new(obscura_net::CookieJar::new()),
+ None,
+ true,
+ )));
+ assert!(rt.has_page_transport());
+ assert!(!rt.render_resource_sync_loading_enabled());
+ rt.set_dom(parse_html(&format!("<html><body><img src=\"{url}\"></body></html>")));
+ rt.set_url("http://127.0.0.1:9/page");
+ let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);
+ assert_eq!(rt.start_render_resource_loads(requests), 1, "stealth client is a transport");
+ assert!(rt.has_pending_render_resources());
+ // The unreachable origin answers with a failed load, which settles it.
+ for _ in 0..200 {
+ if rt.apply_render_resource_results() > 0 || !rt.has_pending_render_resources() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
+ assert!(!rt.has_pending_render_resources(), "the load must finish through the stealth client");
+ assert!(rt.render_resource_is_known(&url));
+ }
+
// SEC-503 / #820 — createObjectURL must reject non-Blob input (an object
// that merely has a .text() method, e.g. Response) with a TypeError, as
// Chrome does; a real Blob is still accepted.
diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rs
index 92984adf..35dd15dd 100644
--- a/crates/obscura-render/src/paint.rs
+++ b/crates/obscura-render/src/paint.rs
@@ -146,6 +146,12 @@ pub struct RenderResourceCache {
#[cfg(test)]
content_image_layout_retries: usize,
sync_loading_enabled: bool,
+ /// Resources a cache-only lookup missed since the last `take_sync_misses`,
+ /// with the request identity layout used (image CORS profile or none) and
+ /// whether the consumer is a font.
+ /// Deduplicated so repeated layouts do not grow the list.
+ sync_misses: Vec<(String, Option<ImageRequestProfile>, bool)>,
+ sync_miss_keys: HashSet<String>,
loader: Box<dyn RenderResourceLoader>,
}
@@ -185,6 +191,8 @@ impl RenderResourceCache {
#[cfg(test)]
content_image_layout_retries: 0,
sync_loading_enabled: true,
+ sync_misses: Vec::new(),
+ sync_miss_keys: HashSet::new(),
loader: Box::new(loader),
}
}
@@ -197,6 +205,47 @@ impl RenderResourceCache {
std::mem::replace(&mut self.sync_loading_enabled, enabled)
}
+ /// Whether layout and paint may still open synchronous compatibility
+ /// requests. Page-owned caches disable this permanently and are fed by
+ /// the page transport instead.
+ pub fn sync_loading_enabled(&self) -> bool {
+ self.sync_loading_enabled
+ }
+
+ /// Take the resources that cache-only layout or paint asked for and did
+ /// not have, exactly as they were resolved (network URL plus the image
+ /// request profile, or `None` for CSS images and fonts). The owning page
+ /// loads them through its asynchronous transport; nothing is
+ /// reconstructed from the DOM, so script-registered fonts, shadow roots
+ /// and every other renderer-only source are covered.
+ pub fn take_sync_misses(&mut self) -> Vec<(String, Option<ImageRequestProfile>, bool)> {
+ self.sync_miss_keys.clear();
+ std::mem::take(&mut self.sync_misses)
+ }
+
+ /// Whether any cache-only miss is waiting to be taken.
+ pub fn has_sync_misses(&self) -> bool {
+ !self.sync_misses.is_empty()
+ }
+
+ fn record_sync_miss(
+ &mut self,
+ key: String,
+ url: String,
+ profile: Option<ImageRequestProfile>,
+ is_font: bool,
+ ) {
+ // Bound a hostile document's per-layout queue to the number of
+ // entries this cache could retain. A later layout reports skipped
+ // misses again after the current batch has been drained.
+ if self.sync_misses.len() >= self.max_entries {
+ return;
+ }
+ if self.sync_miss_keys.insert(key) {
+ self.sync_misses.push((url, profile, is_font));
+ }
+ }
+
pub fn retained_entry_count(&self) -> usize {
self.entries.len()
}
@@ -228,7 +277,16 @@ impl RenderResourceCache {
}
pub fn seed_image(&mut self, url: String, profile: ImageRequestProfile, bytes: Vec<u8>) {
- self.seed(image_resource_key(&url, profile), bytes);
+ self.seed_shared(image_resource_key(&url, profile), Arc::from(bytes));
+ }
+
+ pub fn seed_image_shared(
+ &mut self,
+ url: String,
+ profile: ImageRequestProfile,
+ bytes: Arc<[u8]>,
+ ) {
+ self.seed_shared(image_resource_key(&url, profile), bytes);
}
pub fn seed_image_missing(&mut self, url: String, profile: ImageRequestProfile) {
@@ -242,9 +300,14 @@ impl RenderResourceCache {
/// layer uses this entry point to fetch a bounded resource batch through
/// its cookie/proxy/CORS-aware connection pool before entering layout.
pub fn seed(&mut self, url: String, bytes: Vec<u8>) {
+ self.seed_shared(url, Arc::from(bytes));
+ }
+
+ /// Seed already-shared bytes without copying a complete response body.
+ pub fn seed_shared(&mut self, url: String, bytes: Arc<[u8]>) {
let url = network_resource_url(&url);
self.remove(&url);
- self.insert_bytes(url, Arc::from(bytes));
+ self.insert_bytes(url, bytes);
}
/// Retain a page-transport failure so capture does not immediately repeat
@@ -406,7 +469,7 @@ impl RenderResourceCache {
}
}
- fn get_or_load(&mut self, url: &str) -> Option<Arc<[u8]>> {
+ fn get_or_load(&mut self, url: &str, is_font: bool) -> Option<Arc<[u8]>> {
let url = network_resource_url(url);
if let Some(entry) = self.entries.get(&url) {
match entry {
@@ -418,6 +481,7 @@ impl RenderResourceCache {
}
}
if !self.sync_loading_enabled {
+ self.record_sync_miss(url.clone(), url, None, is_font);
return None;
}
self.remove(&url);
@@ -451,6 +515,7 @@ impl RenderResourceCache {
}
}
if !self.sync_loading_enabled {
+ self.record_sync_miss(key, network_resource_url(url), Some(profile), false);
return None;
}
self.remove(&key);
@@ -6932,6 +6997,23 @@ fn fetch_bytes(
src: &str,
base_url: Option<&str>,
cache: &mut RenderResourceCache,
+) -> Option<Arc<[u8]>> {
+ fetch_bytes_with_kind(src, base_url, cache, false)
+}
+
+fn fetch_font_bytes(
+ src: &str,
+ base_url: Option<&str>,
+ cache: &mut RenderResourceCache,
+) -> Option<Arc<[u8]>> {
+ fetch_bytes_with_kind(src, base_url, cache, true)
+}
+
+fn fetch_bytes_with_kind(
+ src: &str,
+ base_url: Option<&str>,
+ cache: &mut RenderResourceCache,
+ is_font: bool,
) -> Option<Arc<[u8]>> {
if let Some(rest) = src.strip_prefix("data:") {
let comma_idx = rest.find(',')?;
@@ -6948,7 +7030,7 @@ fn fetch_bytes(
return Some(Arc::from(bytes));
}
let resolved = resolve_resource_url(src, base_url)?;
- cache.get_or_load(&resolved)
+ cache.get_or_load(&resolved, is_font)
}
fn fetch_profiled_image_bytes(
@@ -7169,7 +7251,7 @@ fn fetch_and_decode_font(
base_url: Option<&str>,
cache: &mut RenderResourceCache,
) -> Option<Vec<u8>> {
- let compressed = fetch_bytes(src, base_url, cache)?;
+ let compressed = fetch_font_bytes(src, base_url, cache)?;
if compressed.len() > 8 * 1024 * 1024 {
return None;
}
@@ -11706,7 +11788,7 @@ mod tests {
let previous = cache.set_sync_loading_enabled(false);
assert!(previous);
- assert!(cache.get_or_load(url).is_none());
+ assert!(cache.get_or_load(url, false).is_none());
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
assert!(
!cache.has_live_outcome(url),
@@ -11715,10 +11797,79 @@ mod tests {
cache.set_sync_loading_enabled(previous);
cache.seed(url.to_string(), vec![9, 8, 7]);
- assert_eq!(cache.get_or_load(url).as_deref(), Some([9, 8, 7].as_slice()));
+ assert_eq!(cache.get_or_load(url, false).as_deref(), Some([9, 8, 7].as_slice()));
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
+ #[test]
+ fn cache_only_misses_are_reported_with_their_request_identity() {
+ let mut cache = RenderResourceCache::with_loader(|_url: &str| Some(vec![1, 2, 3]));
+ let font = "https://example.test/font?id=late";
+ let image = "https://example.test/late.png#fragment";
+ assert!(!cache.has_sync_misses());
+
+ cache.set_sync_loading_enabled(false);
+ assert!(cache.get_or_load(font, true).is_none());
+ assert!(cache.get_or_load(font, true).is_none(), "a repeated miss is reported once");
+ assert!(cache
+ .get_or_load_image(image, ImageRequestProfile::CorsInclude)
+ .is_none());
+ assert!(cache.has_sync_misses());
+ assert_eq!(
+ cache.take_sync_misses(),
+ vec![
+ (font.to_string(), None, true),
+ (
+ "https://example.test/late.png".to_string(),
+ Some(ImageRequestProfile::CorsInclude),
+ false,
+ ),
+ ],
+ "misses carry the network URL, image request profile and resource kind"
+ );
+ assert!(!cache.has_sync_misses(), "take clears the report");
+
+ cache.seed(font.to_string(), vec![9]);
+ assert!(cache.get_or_load(font, true).is_some());
+ assert!(!cache.has_sync_misses(), "a hit is not a miss");
+
+ cache.set_sync_loading_enabled(true);
+ assert!(cache
+ .get_or_load("https://example.test/other.png", false)
+ .is_some());
+ assert!(
+ !cache.has_sync_misses(),
+ "the synchronous compatibility loader never reports a miss"
+ );
+ }
+
+ #[test]
+ fn cache_only_miss_queue_respects_the_cache_entry_limit() {
+ let mut cache = RenderResourceCache::with_loader_and_limits(
+ |_url: &str| None,
+ 1,
+ DEFAULT_RESOURCE_CACHE_BYTES,
+ );
+ cache.set_sync_loading_enabled(false);
+
+ assert!(cache
+ .get_or_load("https://example.test/first.png", false)
+ .is_none());
+ assert!(cache
+ .get_or_load("https://example.test/second.png", false)
+ .is_none());
+ assert_eq!(cache.take_sync_misses().len(), 1);
+
+ assert!(cache
+ .get_or_load("https://example.test/second.png", false)
+ .is_none());
+ assert_eq!(
+ cache.take_sync_misses().len(),
+ 1,
+ "a deferred miss is reported later"
+ );
+ }
+
#[test]
fn html_image_profiles_keep_intrinsic_geometry_and_paint_separate() {
let network_url = "https://assets.test/shared.svg";