diff --git a/moli-protocol/src/domains/fetch/subresource.rs b/moli-protocol/src/domains/fetch/subresource.rs index d68d27d3229..5b423d070e1 100644 --- a/moli-protocol/src/domains/fetch/subresource.rs +++ b/moli-protocol/src/domains/fetch/subresource.rs @@ -16,6 +16,7 @@ use crate::conn::{ PendingSubresourceFetchResponseRequest, monotonic_timestamp_seconds, }; use crate::domains::network; +use moli_core::page::SubresourceRequestInitiatorType; use moli_core::runtime::DetachedParserScriptFetchContinuation; use super::subresource_continuation::{ @@ -59,6 +60,7 @@ struct PendingSubresourceFetchPauseSource { /// Network request id is the loader id of the Document it creates. child_document: Option, native_network: bool, + request_initiator_type: SubresourceRequestInitiatorType, redirect: Option, } @@ -94,6 +96,11 @@ pub(crate) fn subresource_fetch_pause_prepared_outputs_for_renderer_record( return network::NetworkPreparedOutputs::default(); }; let native_network = network_pause.is_some(); + let request_initiator_type = network_pause + .as_ref() + .map_or(SubresourceRequestInitiatorType::Script, |pause| { + pause.request_initiator_type() + }); let network_redirect = network_pause .as_ref() .and_then(|pause| pause.request_redirect().cloned()) @@ -116,6 +123,7 @@ pub(crate) fn subresource_fetch_pause_prepared_outputs_for_renderer_record( detached_parser_script_fetch_continuation: None, child_document, native_network, + request_initiator_type, redirect, }], ) @@ -145,6 +153,7 @@ pub(crate) fn detached_parser_script_fetch_pause_prepared_outputs_for_renderer_r detached_parser_script_fetch_continuation: Some(continuation), child_document: None, native_network: false, + request_initiator_type: SubresourceRequestInitiatorType::Script, redirect: None, }], ) @@ -188,6 +197,7 @@ fn prepare_subresource_fetch_pause_sources( detached_parser_script_fetch_continuation, child_document, native_network, + request_initiator_type, redirect, } = source; let redirect = redirect.or_else(|| { @@ -269,6 +279,7 @@ fn prepare_subresource_fetch_pause_sources( &info, ) .with_fetch_request_id(request_id.clone()) + .with_request_initiator_type(request_initiator_type) .with_child_document(child_document.clone()) .with_redirect(redirect.clone()); outputs.push(network::TargetSubresourceFetchPauseOutput::network_only( @@ -483,6 +494,7 @@ fn prepare_subresource_fetch_pause_sources( &info, ) .with_blocked_intercepts(blocked_intercepts) + .with_request_initiator_type(request_initiator_type) .with_fetch_request_id(request_id.clone()) .with_child_document(child_document) .with_redirect(redirect); @@ -578,6 +590,14 @@ pub(crate) fn emit_subresource_fetch_pause_outputs( }) .collect::>(); let Some(fetch) = output.into_fetch_event_parts() else { + // Response-only and URL-nonmatching native interceptions still + // publish this initial Network event. Their terminal record must + // not synthesize another start for the same physical request. + if !network_events.is_empty() + && let Some(slot) = conn.runtime_session_owner_slot_mut_for_owner(owner) + { + slot.record_fetch_pause_announced_request_id(network_request_id); + } out.extend(network_events); continue; }; diff --git a/moli-protocol/src/domains/fetch/tests/mod.rs b/moli-protocol/src/domains/fetch/tests/mod.rs index 3afe52351bb..40f40f9d1a9 100644 --- a/moli-protocol/src/domains/fetch/tests/mod.rs +++ b/moli-protocol/src/domains/fetch/tests/mod.rs @@ -310,4 +310,5 @@ mod runtime_auth_response; mod runtime_fetch; mod runtime_websocket; mod runtime_xhr; +mod stylesheets; mod subresource_auth_retry; diff --git a/moli-protocol/src/domains/fetch/tests/stylesheets.rs b/moli-protocol/src/domains/fetch/tests/stylesheets.rs new file mode 100644 index 00000000000..7898950e403 --- /dev/null +++ b/moli-protocol/src/domains/fetch/tests/stylesheets.rs @@ -0,0 +1,471 @@ +use super::*; +use base64::Engine as _; + +const CSS: &str = "body{background-color:rgb(4,5,6)}"; +const FULFILLED_CSS: &str = "body{background-color:rgb(1,2,3)}"; + +async fn stylesheet_server() -> (String, Arc, tokio::task::JoinHandle<()>) { + let hits = Arc::new(AtomicUsize::new(0)); + let captured = hits.clone(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let app = Router::new() + .route( + "/page", + get(|| async { + ( + [(CONTENT_TYPE.as_str(), "text/html")], + "styles", + ) + }), + ) + .route( + "/parser", + get(|| async { + ( + [(CONTENT_TYPE.as_str(), "text/html")], + "parser", + ) + }), + ) + .route( + "/start.css", + get(|| async { axum::response::Redirect::temporary("/actual.css") }), + ) + .route( + "/actual.css", + get(|| async { + ( + [(CONTENT_TYPE.as_str(), "text/css")], + "@import url('/nested.css');body{background-color:rgb(4,5,6)}", + ) + }), + ) + .route( + "/nested.css", + get(|| async { ([(CONTENT_TYPE.as_str(), "text/css")], "body{color:red}") }), + ) + .route( + "/cors.css", + get(|| async { ([(CONTENT_TYPE.as_str(), "text/css")], CSS) }), + ) + .route( + "/cors-allow.css", + get(|| async { + ( + [ + (CONTENT_TYPE.as_str(), "text/css"), + ("access-control-allow-origin", "*"), + ], + CSS, + ) + }), + ) + .route( + "/same.css", + get(move || { + let captured = captured.clone(); + async move { + captured.fetch_add(1, Ordering::SeqCst); + ([(CONTENT_TYPE.as_str(), "text/css")], CSS) + } + }), + ); + axum::serve(listener, app).await.unwrap(); + }); + (format!("http://{addr}"), hits, server) +} + +async fn command(ctx: &mut TestContext, id: &mut u64, method: &str, params: Value) { + let current = *id; + *id += 1; + ctx.process_async(json!({"id":current,"sessionId":"SID-1","method":method,"params":params})) + .await; + ctx.expect_result(current, json!({}), Some("SID-1")); +} + +async fn evaluate(ctx: &mut TestContext, id: &mut u64, expression: &str) -> Value { + let current = *id; + *id += 1; + ctx.process_async(json!({"id":current,"sessionId":"SID-1","method":"Runtime.evaluate","params":{"expression":expression}})).await; + let response = take_response_by_id(ctx, current); + assert!( + response["result"].get("exceptionDetails").is_none(), + "{response}" + ); + response["result"]["result"]["value"].clone() +} + +async fn append_link( + ctx: &mut TestContext, + id: &mut u64, + name: &str, + url: &str, + preload: bool, + cross_origin: Option<&str>, +) { + evaluate( + ctx, + id, + &format!( + r#"(() => {{ + globalThis.__cssDone ??= {{}}; globalThis.__cssLinks ??= {{}}; + const name = {name}; const link = document.createElement('link'); + __cssDone[name] = null; __cssLinks[name] = link; + link.rel = {rel}; if ({preload}) link.as = 'style'; + if ({cross_origin} !== null) link.crossOrigin = {cross_origin}; + link.href = {url}; + link.onload = () => __cssDone[name] = 'load'; + link.onerror = () => __cssDone[name] = 'error'; + document.head.appendChild(link); + }})()"#, + name = json!(name), + rel = json!(if preload { "preload" } else { "stylesheet" }), + cross_origin = json!(cross_origin), + url = json!(url), + ), + ) + .await; +} + +async fn expect_value(ctx: &mut TestContext, id: &mut u64, expression: &str, expected: Value) { + evaluate_until_value_async(ctx, "SID-1", *id, expression, &expected, expression).await; + *id += 100; +} + +async fn pause_for(ctx: &mut TestContext, url: &str) -> Value { + wait_until_message(ctx, "SID-1", "stylesheet interception", |m| { + m["method"] == "Fetch.requestPaused" && m["params"]["request"]["url"] == url + }) + .await; + let paused = ctx.take_first_matching("stylesheet pause", |m| { + m["method"] == "Fetch.requestPaused" && m["params"]["request"]["url"] == url + }); + assert_eq!(paused["params"]["resourceType"], "Stylesheet"); + paused +} + +async fn fulfill(ctx: &mut TestContext, id: &mut u64, pause: &Value) { + command( + ctx, + id, + "Fetch.fulfillRequest", + json!({ + "requestId":pause["params"]["requestId"], "responseCode":200, + "responseHeaders":[{"name":"Content-Type","value":"text/css"}], + "body":base64::engine::general_purpose::STANDARD.encode(FULFILLED_CSS), + }), + ) + .await; +} + +async fn setup(ctx: &mut TestContext, base: &str, id: &mut u64, stage: &str) { + with_loaded_http_document(ctx, &format!("{base}/page"), "SID-1", "TID-1").await; + ctx.with_fixture(|conn| { + conn.runtime_session_owner_slot_mut(Some("SID-1")) + .expect("stylesheet test target") + .disable_primary_network_events(); + }); + enable_runtime_async(ctx, "SID-1", *id).await; + *id += 1; + command(ctx, id, "Network.enable", json!({})).await; + command( + ctx, + id, + "Network.setCacheDisabled", + json!({"cacheDisabled":true}), + ) + .await; + command( + ctx, + id, + "Fetch.enable", + json!({"patterns":[{"resourceType":"Stylesheet","requestStage":stage}]}), + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn stylesheet_disabled_cache_reintercepts_a_successful_same_url_for_a_new_owner() { + let (base, hits, server) = stylesheet_server().await; + for disable_after_first in [false, true] { + let mut ctx = TestContext::new(); + let mut id = 81000; + setup(&mut ctx, &base, &mut id, "Request").await; + if disable_after_first { + command( + &mut ctx, + &mut id, + "Network.setCacheDisabled", + json!({"cacheDisabled":false}), + ) + .await; + } + let url = format!("{base}/same.css"); + append_link(&mut ctx, &mut id, "first", &url, false, None).await; + let first = pause_for(&mut ctx, &url).await; + fulfill(&mut ctx, &mut id, &first).await; + expect_value(&mut ctx, &mut id, "__cssDone.first", json!("load")).await; + expect_value( + &mut ctx, + &mut id, + "getComputedStyle(document.body).backgroundColor", + json!("rgb(1, 2, 3)"), + ) + .await; + evaluate(&mut ctx, &mut id, "__cssLinks.first.remove()").await; + command( + &mut ctx, + &mut id, + "Network.setCacheDisabled", + json!({"cacheDisabled":true}), + ) + .await; + append_link(&mut ctx, &mut id, "second", &url, false, None).await; + let second = pause_for(&mut ctx, &url).await; + assert_ne!(first["params"]["requestId"], second["params"]["requestId"]); + assert_ne!(first["params"]["networkId"], second["params"]["networkId"]); + command( + &mut ctx, + &mut id, + "Fetch.failRequest", + json!({"requestId":second["params"]["requestId"],"errorReason":"Aborted"}), + ) + .await; + expect_value(&mut ctx, &mut id, "__cssDone.second", json!("error")).await; + expect_value( + &mut ctx, + &mut id, + "getComputedStyle(document.body).backgroundColor", + json!("rgba(0, 0, 0, 0)"), + ) + .await; + assert_eq!( + hits.load(Ordering::SeqCst), + 0, + "fulfilled and aborted requests never reach the origin" + ); + } + server.abort(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stylesheet_disabled_cache_preserves_pending_sharing_and_preload_consumption() { + let (base, hits, server) = stylesheet_server().await; + for (preload, completed_preload) in [(false, false), (true, false), (true, true)] { + let mut ctx = TestContext::new(); + let mut id = 82000; + setup(&mut ctx, &base, &mut id, "Request").await; + let url = format!("{base}/same.css"); + append_link(&mut ctx, &mut id, "first", &url, preload, None).await; + let first = pause_for(&mut ctx, &url).await; + if completed_preload { + fulfill(&mut ctx, &mut id, &first).await; + expect_value(&mut ctx, &mut id, "__cssDone.first", json!("load")).await; + } + append_link(&mut ctx, &mut id, "second", &url, false, None).await; + if !completed_preload { + fulfill(&mut ctx, &mut id, &first).await; + } + expect_value(&mut ctx, &mut id, "__cssDone.first", json!("load")).await; + expect_value(&mut ctx, &mut id, "__cssDone.second", json!("load")).await; + assert!( + !ctx.sent + .iter() + .any(|m| m["method"] == "Fetch.requestPaused" + && m["params"]["request"]["url"] == url), + "a pending transfer or unused preload must supply both consumers" + ); + expect_value( + &mut ctx, + &mut id, + "getComputedStyle(document.body).backgroundColor", + json!("rgb(1, 2, 3)"), + ) + .await; + append_link(&mut ctx, &mut id, "third", &url, false, None).await; + let third = pause_for(&mut ctx, &url).await; + command( + &mut ctx, + &mut id, + "Fetch.failRequest", + json!({"requestId":third["params"]["requestId"],"errorReason":"Aborted"}), + ) + .await; + expect_value(&mut ctx, &mut id, "__cssDone.third", json!("error")).await; + expect_value( + &mut ctx, + &mut id, + "getComputedStyle(document.body).backgroundColor", + json!("rgb(1, 2, 3)"), + ) + .await; + assert_eq!(hits.load(Ordering::SeqCst), 0); + } + server.abort(); +} + +fn assert_initiator(ctx: &TestContext, paused: &Value, url: &str, expected: &str) { + let event = ctx + .sent + .iter() + .find(|m| { + m["method"] == "Network.requestWillBeSent" + && m["params"]["requestId"] == paused["params"]["networkId"] + && m["params"]["request"]["url"] == url + }) + .expect("Network request must precede its Fetch pause"); + assert_eq!(event["params"]["type"], "Stylesheet"); + assert_eq!(event["params"]["initiator"]["type"], expected, "{event}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stylesheet_interception_preserves_parser_import_redirect_and_script_initiators() { + let (base, _, server) = stylesheet_server().await; + let mut ctx = TestContext::new(); + let mut id = 83000; + setup(&mut ctx, &base, &mut id, "Request").await; + ctx.process_async(json!({"id":id,"sessionId":"SID-1","method":"Page.navigate","params":{"url":format!("{base}/parser")}})).await; + let navigation = take_response_by_id(&mut ctx, id); + assert!(navigation.get("error").is_none(), "{navigation}"); + id += 1; + for path in ["/start.css", "/actual.css", "/nested.css"] { + let url = format!("{base}{path}"); + let paused = pause_for(&mut ctx, &url).await; + assert_initiator(&ctx, &paused, &url, "parser"); + command( + &mut ctx, + &mut id, + "Fetch.continueRequest", + json!({"requestId":paused["params"]["requestId"]}), + ) + .await; + } + expect_value( + &mut ctx, + &mut id, + "getComputedStyle(document.body).backgroundColor", + json!("rgb(4, 5, 6)"), + ) + .await; + let url = format!("{base}/same.css"); + append_link(&mut ctx, &mut id, "dynamic", &url, false, None).await; + let paused = pause_for(&mut ctx, &url).await; + assert_initiator(&ctx, &paused, &url, "script"); + command( + &mut ctx, + &mut id, + "Fetch.continueRequest", + json!({"requestId":paused["params"]["requestId"]}), + ) + .await; + expect_value(&mut ctx, &mut id, "__cssDone.dynamic", json!("load")).await; + server.abort(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stylesheet_response_interception_preserves_cors_and_cssom_access() { + let (base, _, page_server) = stylesheet_server().await; + let (cross, _, css_server) = stylesheet_server().await; + for (cross_origin, path, stage, done, cssom) in [ + ( + None, + "/cors.css", + "Response", + "load", + json!("SecurityError"), + ), + ( + Some("anonymous"), + "/cors-allow.css", + "Response", + "load", + json!(1), + ), + ( + Some("anonymous"), + "/cors.css", + "Request", + "error", + json!("SecurityError"), + ), + ] { + let mut ctx = TestContext::new(); + let mut id = 84000; + setup(&mut ctx, &base, &mut id, stage).await; + let url = format!("{cross}{path}"); + append_link(&mut ctx, &mut id, "cors", &url, false, cross_origin).await; + let paused = pause_for(&mut ctx, &url).await; + assert_initiator(&ctx, &paused, &url, "script"); + if stage == "Response" { + assert_eq!(paused["params"]["responseStatusCode"], 200); + let body_id = id; + id += 1; + ctx.process_async(json!({"id":body_id,"sessionId":"SID-1","method":"Fetch.getResponseBody","params":{"requestId":paused["params"]["requestId"]}})).await; + let response = take_response_by_id(&mut ctx, body_id); + let body = response["result"]["body"].as_str().expect("response body"); + let bytes = if response["result"]["base64Encoded"] == true { + base64::engine::general_purpose::STANDARD + .decode(body) + .unwrap() + } else { + body.as_bytes().to_vec() + }; + assert_eq!(bytes, CSS.as_bytes()); + command( + &mut ctx, + &mut id, + "Fetch.continueResponse", + json!({"requestId":paused["params"]["requestId"]}), + ) + .await; + } else { + command( + &mut ctx, + &mut id, + "Fetch.continueRequest", + json!({"requestId":paused["params"]["requestId"]}), + ) + .await; + } + expect_value(&mut ctx, &mut id, "__cssDone.cors", json!(done)).await; + expect_value(&mut ctx, &mut id, "(() => {const sheet=__cssLinks.cors.sheet;if(!sheet)return 'no-sheet';try{return sheet.cssRules.length}catch(e){return e.name}})()", cssom).await; + expect_value( + &mut ctx, + &mut id, + "getComputedStyle(document.body).backgroundColor", + json!(if done == "load" { + "rgb(4, 5, 6)" + } else { + "rgba(0, 0, 0, 0)" + }), + ) + .await; + let network_id = &paused["params"]["networkId"]; + assert_eq!( + ctx.sent + .iter() + .filter(|m| m["method"] == "Network.requestWillBeSent" + && m["params"]["requestId"] == *network_id) + .count(), + 1, + "{cross_origin:?} {path} {stage}; events={:?}", + ctx.sent + .iter() + .filter(|m| m["params"]["requestId"] == *network_id) + .collect::>() + ); + assert_eq!( + ctx.sent + .iter() + .filter(|m| (m["method"] == "Network.loadingFinished" + || m["method"] == "Network.loadingFailed") + && m["params"]["requestId"] == *network_id) + .count(), + 1 + ); + } + page_server.abort(); + css_server.abort(); +} diff --git a/moli-protocol/src/domains/network/events.rs b/moli-protocol/src/domains/network/events.rs index 12ca18ec38b..5633cfee2e0 100644 --- a/moli-protocol/src/domains/network/events.rs +++ b/moli-protocol/src/domains/network/events.rs @@ -371,12 +371,13 @@ pub(crate) fn fetch_subresource_initial_request_network_events( request_headers: output.request_headers().to_vec(), request_body: output.request_body().map(str::to_owned), request_initiator_type: Some( - SubresourceRequestInitiatorType::Script + output + .request_initiator_type() .as_cdp_initiator_type() .to_owned(), ), bidi_request_initiator_type: bidi_request_initiator_type_override( - SubresourceRequestInitiatorType::Script, + output.request_initiator_type(), ) .map(str::to_owned), redirect_response: output diff --git a/moli-protocol/src/domains/network/output.rs b/moli-protocol/src/domains/network/output.rs index 4c4a419ee97..df839360016 100644 --- a/moli-protocol/src/domains/network/output.rs +++ b/moli-protocol/src/domains/network/output.rs @@ -1,6 +1,7 @@ use moli_cookie_jar::StoredCookieQueryReport; use moli_core::page::{ - PendingSubresourceFetchInfo, SubresourceNetworkRequestHandle, SubresourceResourceType, + PendingSubresourceFetchInfo, SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType, + SubresourceResourceType, }; use serde_json::Value; use url::Url; @@ -71,6 +72,7 @@ pub(crate) struct TargetSubresourceFetchPauseNetworkOutput { request_body: Option, request_body_bytes: Option, resource_type: SubresourceResourceType, + request_initiator_type: SubresourceRequestInitiatorType, request_cookie_report: Option, blocked_intercepts: Vec, fetch_request_id: Option, @@ -100,6 +102,7 @@ impl TargetSubresourceFetchPauseNetworkOutput { request_body: info.request_body.clone(), request_body_bytes: info.request_body_bytes.clone(), resource_type: info.resource_type, + request_initiator_type: SubresourceRequestInitiatorType::Script, request_cookie_report: info.request_cookie_report.clone(), blocked_intercepts: Vec::new(), fetch_request_id: None, @@ -116,6 +119,18 @@ impl TargetSubresourceFetchPauseNetworkOutput { self } + pub(crate) fn with_request_initiator_type( + mut self, + initiator: SubresourceRequestInitiatorType, + ) -> Self { + self.request_initiator_type = initiator; + self + } + + pub(crate) fn request_initiator_type(&self) -> SubresourceRequestInitiatorType { + self.request_initiator_type + } + pub(crate) fn redirect(&self) -> Option<&moli_page_types::NavigationRedirect> { self.redirect.as_ref().or_else(|| { self.child_document diff --git a/moli-renderer-v8/src/document_runtime/lifecycle.rs b/moli-renderer-v8/src/document_runtime/lifecycle.rs index 43d2fc69540..71b6064f23d 100644 --- a/moli-renderer-v8/src/document_runtime/lifecycle.rs +++ b/moli-renderer-v8/src/document_runtime/lifecycle.rs @@ -165,8 +165,20 @@ impl DocumentRuntime { owner: DomHandle, host_ptr: *mut PageScriptHost, ) -> crate::stylesheet_blocking::RendererStylesheetFetcher { + let request_initiator_type = if self + .dom_host + .node(owner) + .and_then(Node::as_element) + .is_some_and(|element| element.link_created_by_parser()) + { + crate::types::SubresourceRequestInitiatorType::Parser + } else { + crate::types::SubresourceRequestInitiatorType::Script + }; if host_ptr.is_null() { - return self.stylesheet_fetcher(); + return self + .stylesheet_fetcher() + .with_request_initiator_type(request_initiator_type); } let host = unsafe { &*host_ptr }; let scope = host @@ -190,6 +202,7 @@ impl DocumentRuntime { host.subresource_request_environment(&loader, scope) .and_then(|environment| environment.frame_id), ) + .with_request_initiator_type(request_initiator_type) } pub(super) fn speculative_stylesheet_fetcher( diff --git a/moli-renderer-v8/src/network/interception_control.rs b/moli-renderer-v8/src/network/interception_control.rs index e851cb01c3a..9741112dab0 100644 --- a/moli-renderer-v8/src/network/interception_control.rs +++ b/moli-renderer-v8/src/network/interception_control.rs @@ -5,7 +5,9 @@ use parking_lot::Mutex; use tokio::sync::oneshot; use url::Url; -use crate::{RendererPageCommand, RendererSyntheticResponseBody}; +use crate::{ + RendererPageCommand, RendererSyntheticResponseBody, types::SubresourceRequestInitiatorType, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum InterceptionPhase { @@ -22,6 +24,7 @@ pub struct ResourceInterceptionPause { phase: InterceptionPhase, target_policy: crate::network::PageNetworkPolicy, request_redirect: Option>, + request_initiator_type: SubresourceRequestInitiatorType, response_body: Option, sender: Arc>>>, } @@ -78,6 +81,7 @@ impl ResourceInterceptionPause { phase, target_policy, request_redirect: None, + request_initiator_type: SubresourceRequestInitiatorType::Script, response_body: None, sender: Arc::new(Mutex::new(Some(tx))), }, @@ -97,6 +101,18 @@ impl ResourceInterceptionPause { self.request_redirect.as_deref() } + pub(crate) fn with_request_initiator_type( + mut self, + initiator: SubresourceRequestInitiatorType, + ) -> Self { + self.request_initiator_type = initiator; + self + } + + pub fn request_initiator_type(&self) -> SubresourceRequestInitiatorType { + self.request_initiator_type + } + pub(crate) fn with_response_body(mut self, body: super::ResourceInterceptionBody) -> Self { self.response_body = Some(body); self diff --git a/moli-renderer-v8/src/network_host/controlled_xhr.rs b/moli-renderer-v8/src/network_host/controlled_xhr.rs index c034781de6c..cffc4fc3d97 100644 --- a/moli-renderer-v8/src/network_host/controlled_xhr.rs +++ b/moli-renderer-v8/src/network_host/controlled_xhr.rs @@ -24,7 +24,7 @@ use crate::{ runtime::{RendererDocumentLifecycleIdentity, RendererOwnerAction}, types::{ PendingSubresourceAuthInfo, PendingSubresourceContinueEvent, PendingSubresourceFetchInfo, - PendingSubresourceResponseInfo, SubresourceResponseBody, + PendingSubresourceResponseInfo, SubresourceRequestInitiatorType, SubresourceResponseBody, }, }; @@ -38,6 +38,7 @@ pub(crate) struct ControlledResourceLoad { connect_policy: Option, preflight_headers: Vec<(String, String)>, initial_decision: Option>, + request_initiator_type: SubresourceRequestInitiatorType, } use super::loaded_response::LoadedResponse; @@ -86,6 +87,7 @@ impl ControlledResourceLoad { info: PendingSubresourceFetchInfo, load: ResourceLoadLease, cancel: FetchCancelHandle, + request_initiator_type: SubresourceRequestInitiatorType, ) -> Self { Self { request, @@ -97,6 +99,7 @@ impl ControlledResourceLoad { connect_policy: None, preflight_headers: Vec::new(), initial_decision: None, + request_initiator_type, } } @@ -144,7 +147,10 @@ impl ControlledResourceLoad { } Err(error) => (Err(error), None), }; - let completed = XhrLoadResult::new(self.info.clone(), result, network_headers); + let mut completed = XhrLoadResult::new(self.info.clone(), result, network_headers); + completed.network_record = completed + .network_record + .with_request_initiator_type(self.request_initiator_type); if completed.info.network_request_handle.is_some() { // Redirects already crossed their own native request-pause boundary. // Diagnostics retain the full chain; protocol sees only the terminal. @@ -188,7 +194,12 @@ impl ControlledResourceLoad { let redirect = (phase == InterceptionPhase::Request) .then(|| self.request.redirect_chain().last().cloned()) .flatten(); - (pause.with_request_redirect(redirect), rx) + ( + pause + .with_request_redirect(redirect) + .with_request_initiator_type(self.request_initiator_type), + rx, + ) } async fn decision( diff --git a/moli-renderer-v8/src/network_host/controlled_xhr/context.rs b/moli-renderer-v8/src/network_host/controlled_xhr/context.rs index 98f59a70058..94f71588010 100644 --- a/moli-renderer-v8/src/network_host/controlled_xhr/context.rs +++ b/moli-renderer-v8/src/network_host/controlled_xhr/context.rs @@ -49,6 +49,7 @@ impl ControlledXhrContext { connect_policy: Some(self.connect_policy), preflight_headers, initial_decision: None, + request_initiator_type: crate::types::SubresourceRequestInitiatorType::Script, } } } diff --git a/moli-renderer-v8/src/stylesheet_blocking.rs b/moli-renderer-v8/src/stylesheet_blocking.rs index 0787d353bc1..cd7abdcab12 100644 --- a/moli-renderer-v8/src/stylesheet_blocking.rs +++ b/moli-renderer-v8/src/stylesheet_blocking.rs @@ -9,7 +9,9 @@ use url::Url; use crate::network::ResourceRequestClient; use crate::service_worker_runtime::{ServiceWorkerClientId, ServiceWorkerRequestDestination}; use crate::subresource_integrity::response_matches_subresource_integrity_metadata; -use crate::types::{AsyncSubresourceFetchResponseFilter, SubresourceResourceType}; +use crate::types::{ + AsyncSubresourceFetchResponseFilter, SubresourceRequestInitiatorType, SubresourceResourceType, +}; pub(crate) use moli_stylesheet_blocking::{ DocumentBlockingStylesheetSignature, DocumentOwnedStylesheetDiscoveryInput, @@ -42,9 +44,18 @@ pub(crate) struct RendererStylesheetFetcher { csp_context: Option, interception: Option, frame_id: Option, + request_initiator_type: SubresourceRequestInitiatorType, } impl RendererStylesheetFetcher { + pub(crate) fn with_request_initiator_type( + mut self, + initiator: SubresourceRequestInitiatorType, + ) -> Self { + self.request_initiator_type = initiator; + self + } + pub(crate) fn with_interception( mut self, context: Option, @@ -81,6 +92,7 @@ impl RendererStylesheetFetcher { csp_context: None, interception: None, frame_id: None, + request_initiator_type: SubresourceRequestInitiatorType::Parser, } } @@ -98,6 +110,7 @@ impl RendererStylesheetFetcher { csp_context: None, interception: None, frame_id: None, + request_initiator_type: SubresourceRequestInitiatorType::Parser, } } @@ -120,6 +133,13 @@ impl StylesheetFetcher for RendererStylesheetFetcher { fn resource_cache_scope(&self) -> u64 { self.loader.identity().value() } + fn reuse_completed_stylesheets(&self) -> bool { + !self + .loader + .request_client() + .page_network_policy() + .cache_disabled() + } fn spawn_stylesheet_task(&self, task: Pin + Send + 'static>>) { self.loader.spawn_resource_task(task); } @@ -140,6 +160,7 @@ impl StylesheetFetcher for RendererStylesheetFetcher { let authority = self.loader.clone(); let interception = self.interception.clone(); let frame_id = self.frame_id.clone(); + let request_initiator_type = self.request_initiator_type; let loader = self.loader.request_client().clone(); let request_origin = self.loader.fetch_context().request_origin(); let resource_task_runner = self.loader.task_runner(); @@ -165,6 +186,7 @@ impl StylesheetFetcher for RendererStylesheetFetcher { authority, interception, frame_id, + request_initiator_type, ) .await }) @@ -205,6 +227,7 @@ pub(crate) async fn fetch_stylesheet_readiness_with_service_worker( authority: crate::network::context::DocumentResourceLoader, interception: Option, frame_id: Option, + request_initiator_type: SubresourceRequestInitiatorType, ) -> StylesheetFetchTerminal { let mut request = stylesheet_readiness_request( &document_url, @@ -306,7 +329,12 @@ pub(crate) async fn fetch_stylesheet_readiness_with_service_worker( }; let completed = crate::network_host::controlled_xhr::ControlledResourceLoad::for_stylesheet( - context, request, info, load, cancel, + context, + request, + info, + load, + cancel, + request_initiator_type, ) .run() .await; diff --git a/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs index 2f915447358..981a4453b39 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs @@ -185,11 +185,14 @@ fn prepare_import_requests( *data_expansions, ))) } else { - fetcher.fetch_stylesheet_resource( - document_url.clone(), - url.clone(), - StylesheetFetchOptions::default(), - ) + fetcher + .clone() + .with_request_initiator_type(crate::types::SubresourceRequestInitiatorType::Css) + .fetch_stylesheet_resource( + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ) }; Box::pin(async move { crate::stylesheet_blocking::StylesheetImportNetworkResult::new( diff --git a/moli-stylesheet-blocking/src/fetcher.rs b/moli-stylesheet-blocking/src/fetcher.rs index 751880935b0..0d2a74c0ce9 100644 --- a/moli-stylesheet-blocking/src/fetcher.rs +++ b/moli-stylesheet-blocking/src/fetcher.rs @@ -301,6 +301,12 @@ pub trait StylesheetFetcher: Clone + Send + 'static { 0 } + /// Controls reuse of a completed resource by a new stylesheet consumer. + /// In-flight sharing and adoption of an unused preload are independent. + fn reuse_completed_stylesheets(&self) -> bool { + true + } + fn spawn_stylesheet_task(&self, task: Pin + Send + 'static>>); fn fetch_stylesheet_resource( diff --git a/moli-stylesheet-blocking/src/state.rs b/moli-stylesheet-blocking/src/state.rs index 06631352b8e..f58d8dfab88 100644 --- a/moli-stylesheet-blocking/src/state.rs +++ b/moli-stylesheet-blocking/src/state.rs @@ -28,7 +28,7 @@ use crate::types::{ pub struct StylesheetBlockingState { owner_fetches: HashMap, blocking_entries: HashMap, - url_fetches: HashMap<(u64, Url, StylesheetResourceKey), StylesheetFetch>, + url_fetches: HashMap<(u64, Url, StylesheetResourceKey), CachedStylesheetFetch>, completion_source: OwnerTaskSource, ready_network_results: VecDeque, // The stylesheet queue is local to document processing, not the renderer @@ -44,6 +44,11 @@ pub struct StylesheetBlockingState { completion_publisher: Option>, } +struct CachedStylesheetFetch { + fetch: StylesheetFetch, + unused_preload: bool, +} + impl StylesheetBlockingState { pub fn discover_from_document( &mut self, @@ -256,7 +261,7 @@ impl StylesheetBlockingState { where F: StylesheetFetcher, { - self.ensure_resource(fetcher.clone(), document_url, url, options) + self.ensure_resource(fetcher.clone(), document_url, url, options, true) } fn rebind_blocking_link( @@ -334,7 +339,7 @@ impl StylesheetBlockingState { return entry.fetch.clone(); } let resource_cache_scope = fetcher.resource_cache_scope(); - let fetch = self.ensure_resource(fetcher, document_url, url, options); + let fetch = self.ensure_resource(fetcher, document_url, url, options, false); self.owner_fetches.insert( node_id, StylesheetFetchEntry { @@ -352,27 +357,40 @@ impl StylesheetBlockingState { document_url: Url, url: Url, options: StylesheetFetchOptions, + preload: bool, ) -> StylesheetFetch where F: StylesheetFetcher, { let resource_cache_scope = fetcher.resource_cache_scope(); let resource_key = options.resource_key(url.clone()); - if let Some(url_fetch) = self.url_fetches.get(&( + if let Some(cached) = self.url_fetches.get_mut(&( resource_cache_scope, document_url.clone(), resource_key.clone(), - )) && !url_fetch.terminal().is_some_and(|terminal| { - matches!( - terminal.physical(), - crate::StylesheetPhysicalOutcome::NetworkError(_) - ) - }) { - return url_fetch.clone(); + )) { + let terminal = cached.fetch.terminal(); + let failed_transfer = terminal.as_ref().is_some_and(|terminal| { + matches!( + terminal.physical(), + crate::StylesheetPhysicalOutcome::NetworkError(_) + ) + }); + if !failed_transfer + && (terminal.is_none() + || cached.unused_preload + || fetcher.reuse_completed_stylesheets()) + { + if !preload { + cached.unused_preload = false; + } + return cached.fetch.clone(); + } } - // A failed transfer has no resource to reuse. A later owner can retry; - // existing owners retain their own terminal and concurrent loads join - // the newly pending physical request as usual. + // Failed transfers can be retried. A completed response also needs a + // new request when caching is disabled, after any preload was consumed. + // Existing owners retain their terminal; concurrent new owners join + // this newly pending transfer. let start_unix_millis = moli_time::unix_epoch_millis(); let request_url = resource_key.request_url().clone(); let fetch = StylesheetFetch::new( @@ -387,7 +405,10 @@ impl StylesheetBlockingState { let completion_fetch = fetch.clone(); self.url_fetches.insert( (resource_cache_scope, document_url.clone(), resource_key), - fetch.clone(), + CachedStylesheetFetch { + fetch: fetch.clone(), + unused_preload: preload, + }, ); let task_fetcher = fetcher.clone(); fetcher.spawn_stylesheet_task(Box::pin(async move { @@ -839,6 +860,32 @@ mod tests { #[derive(Clone)] struct PendingStylesheetFetcher; + #[derive(Clone)] + struct NoCacheStylesheetFetcher(F); + + impl StylesheetFetcher for NoCacheStylesheetFetcher { + fn resource_cache_scope(&self) -> u64 { + self.0.resource_cache_scope() + } + + fn reuse_completed_stylesheets(&self) -> bool { + false + } + + fn spawn_stylesheet_task(&self, task: Pin + Send + 'static>>) { + self.0.spawn_stylesheet_task(task); + } + + fn fetch_stylesheet_resource( + &self, + document_url: Url, + url: Url, + options: StylesheetFetchOptions, + ) -> Pin + Send + 'static>> { + self.0.fetch_stylesheet_resource(document_url, url, options) + } + } + impl StylesheetFetcher for PendingStylesheetFetcher { fn spawn_stylesheet_task(&self, task: Pin + Send + 'static>>) { spawn_test_stylesheet_task(task); @@ -1681,6 +1728,133 @@ mod tests { assert_eq!(state.take_ready_network_results().len(), 1); } + #[tokio::test] + async fn disabled_cache_refetches_completed_resources_for_new_and_readmitted_owners() { + for same_owner in [false, true] { + let mut state = StylesheetBlockingState::default(); + let document_url = Url::parse("https://example.com/").unwrap(); + let url = Url::parse("https://example.com/a.css").unwrap(); + let first_owner = NodeId::new(1); + let first = state.adopt_or_begin_link_load( + &PendingStylesheetFetcher, + first_owner, + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ); + complete_cached_resource(&first); + let next_owner = if same_owner { + state.invalidate_node(first_owner); + first_owner + } else { + NodeId::new(2) + }; + let fetcher = NoCacheStylesheetFetcher(PendingStylesheetFetcher); + let next = state.adopt_or_begin_link_load( + &fetcher, + next_owner, + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ); + assert!( + !first.ptr_eq(&next), + "completed material cannot bypass the new request" + ); + assert!( + first.terminal().unwrap().is_ready(), + "existing consumers keep their response" + ); + assert!(next.terminal().is_none()); + let concurrent = state.adopt_or_begin_link_load( + &fetcher, + NodeId::new(3), + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ); + assert!( + next.ptr_eq(&concurrent), + "pending transfers still coalesce with caching disabled" + ); + let adopted = state.adopt_or_begin_link_load( + &fetcher, + next_owner, + document_url, + url, + StylesheetFetchOptions::default(), + ); + assert!( + next.ptr_eq(&adopted), + "rediscovery of an existing owner is not a new load" + ); + } + } + + fn complete_cached_resource(fetch: &StylesheetFetch) { + assert!(fetch.finish(Arc::new(StylesheetFetchTerminal::ready( + moli_page_types::NavigationResponse::from_text_body( + fetch.request_url().clone(), + 200, + vec![("content-type".into(), b"text/css".to_vec())], + "body{color:red}".into(), + ), + true, + )))); + } + + #[tokio::test] + async fn disabled_cache_preserves_preload_adoption_once_before_or_after_completion() { + for completed_before_adoption in [false, true] { + let mut state = StylesheetBlockingState::default(); + let document_url = Url::parse("https://example.com/").unwrap(); + let url = Url::parse("https://example.com/preload.css").unwrap(); + let fetcher = NoCacheStylesheetFetcher(PendingStylesheetFetcher); + let preload = state.preload_stylesheet( + &fetcher, + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ); + if completed_before_adoption { + complete_cached_resource(&preload); + } + let consumer = state.adopt_or_begin_link_load( + &fetcher, + NodeId::new(1), + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ); + assert!( + preload.ptr_eq(&consumer), + "an unused preload supplies its first stylesheet consumer" + ); + if !completed_before_adoption { + let concurrent = state.adopt_or_begin_link_load( + &fetcher, + NodeId::new(2), + document_url.clone(), + url.clone(), + StylesheetFetchOptions::default(), + ); + assert!(consumer.ptr_eq(&concurrent)); + complete_cached_resource(&preload); + } + let fresh = state.adopt_or_begin_link_load( + &fetcher, + NodeId::new(3), + document_url, + url, + StylesheetFetchOptions::default(), + ); + assert!( + !consumer.ptr_eq(&fresh), + "a consumed preload cannot become a sticky response cache" + ); + } + } + #[tokio::test] async fn completed_same_url_reprocess_reuses_the_sticky_document_resource() { let mut state = StylesheetBlockingState::default();