Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(renderer): settle shared stylesheet clients per owner

ldm08e6dd03abc90
diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs
index 6fde12b31..2502f8437 100644
--- a/moli-renderer-v8/src/document_runtime.rs
+++ b/moli-renderer-v8/src/document_runtime.rs
@@ -92,12 +92,13 @@ pub(crate) use stylesheet_runtime::attribute_reprocesses_connected_stylesheet;
#[cfg(test)]
use stylesheet_runtime::{ConnectedLinkReadinessFetchOptions, ConnectedLoadParameters};
pub(crate) use stylesheet_runtime::{
- ConnectedLoadCompletion, LiveStylesheetImportLoadCompletion,
- fetch_complete_stylesheet_import_graph,
+ ConnectedLoadCompletion, LinkedStylesheetImportGraphCompletion,
+ LiveStylesheetImportLoadCompletion, fetch_complete_stylesheet_import_graph,
+ live_stylesheet_import_responses,
};
use stylesheet_runtime::{
- ConnectedLoadOperation, QueuedConnectedStyleLoad, StylesheetLinkClientIndex,
- StylesheetOwnerCspDisposition, StylesheetOwnerRuntimeStates,
+ ConnectedLoadOperation, LinkedStylesheetImportGraphs, QueuedConnectedStyleLoad,
+ StylesheetLinkClientIndex, StylesheetOwnerCspDisposition, StylesheetOwnerRuntimeStates,
};
pub(crate) use stylesheet_runtime::{
ConnectedStyleEventElementKind, ConnectedStyleLoadEventAdmission, ConnectedStyleLoadEventPlan,
@@ -273,7 +274,10 @@ struct StylesheetLifecycleState {
/// discovery deduplication fact.
pre_initial_scan_processed_owners: HashSet<DomHandle>,
ready_connected_load_network_results: VecDeque<ConnectedLoadNetworkResult>,
+ /// Client completions accepted while applying the selected physical
+ /// stylesheet Networking task.
ready_stylesheet_link_client_terminals: VecDeque<StylesheetLinkClientTerminal>,
+ linked_stylesheet_import_graphs: LinkedStylesheetImportGraphs,
// One canonical entry owns each stylesheet-related owner's operation,
// completion/event disposition, and link state.
owner_states: StylesheetOwnerRuntimeStates,
@@ -296,6 +300,7 @@ impl StylesheetLifecycleState {
pre_initial_scan_processed_owners: HashSet::new(),
ready_connected_load_network_results: VecDeque::new(),
ready_stylesheet_link_client_terminals: VecDeque::new(),
+ linked_stylesheet_import_graphs: LinkedStylesheetImportGraphs::default(),
owner_states: StylesheetOwnerRuntimeStates::default(),
link_client_index: StylesheetLinkClientIndex::default(),
link_promotion_trace: StylesheetLinkPromotionTrace::default(),
@@ -360,41 +365,6 @@ impl ConnectedStyleImportRoot {
}
}
-#[derive(Debug)]
-pub(crate) struct ReadyBlockingStyleImportGraph {
- operation: Arc<ConnectedLoadOperation>,
- roots: Vec<ConnectedStyleImportRoot>,
- graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
- successful: bool,
-}
-
-impl ReadyBlockingStyleImportGraph {
- fn new(
- operation: Arc<ConnectedLoadOperation>,
- roots: Vec<ConnectedStyleImportRoot>,
- graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
- successful: bool,
- ) -> Self {
- Self {
- operation,
- roots,
- graph,
- successful,
- }
- }
-
- pub(crate) fn into_parts(
- self,
- ) -> (
- Arc<ConnectedLoadOperation>,
- Vec<ConnectedStyleImportRoot>,
- Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
- bool,
- ) {
- (self.operation, self.roots, self.graph, self.successful)
- }
-}
-
#[derive(Debug, Clone)]
pub(crate) struct ConnectedLoadNetworkResult {
pub(crate) stylesheet_fetch: Option<crate::stylesheet_blocking::StylesheetFetch>,
@@ -3334,7 +3304,7 @@ mod tests {
for parameters in [
preload_load_parameters(request_url.clone()),
ConnectedLoadParameters::StyleImports {
- source: super::stylesheet_runtime::ConnectedStyleImportSource::Inline(Arc::clone(
+ source: super::stylesheet_runtime::InlineStyleImportSource::new(Arc::clone(
&inline_source,
)),
urls: vec![request_url.clone()],
@@ -3434,7 +3404,7 @@ mod tests {
owner,
ConnectedStyleEventElementKind::Style,
ConnectedLoadParameters::StyleImports {
- source: super::stylesheet_runtime::ConnectedStyleImportSource::Inline(source),
+ source: super::stylesheet_runtime::InlineStyleImportSource::new(source),
urls: vec![request_url.clone()],
roots: Vec::new(),
},
@@ -3492,7 +3462,7 @@ mod tests {
owner,
ConnectedStyleEventElementKind::Style,
ConnectedLoadParameters::StyleImports {
- source: super::stylesheet_runtime::ConnectedStyleImportSource::Inline(source),
+ source: super::stylesheet_runtime::InlineStyleImportSource::new(source),
urls: vec![request_url.clone()],
roots: Vec::new(),
},
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index e639d0598..76722a8fe 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -414,11 +414,17 @@ impl DocumentRuntime {
.discovery_signals
.modulepreload_link_candidates,
);
- self.note_discovered_document_owned_blocking_stylesheet_inputs(
- finish_signals
- .discovery_signals
- .blocking_stylesheet_inputs
- .iter(),
+ let completed_stylesheet_clients = self
+ .note_discovered_document_owned_blocking_stylesheet_inputs(
+ finish_signals
+ .discovery_signals
+ .blocking_stylesheet_inputs
+ .iter(),
+ );
+ self.settle_stylesheet_link_clients_in_current_scope(
+ scope,
+ host_ptr,
+ completed_stylesheet_clients,
);
unsafe { &mut *host_ptr }.resync_child_browsing_contexts(scope);
self.run_pending_parser_post_step_runtime_work(scope, host_ptr);
@@ -2500,8 +2506,14 @@ impl DocumentRuntime {
chunk.clear();
begin_insertion = false;
- self.note_discovered_document_owned_blocking_stylesheet_inputs(
- discovered_blocking_stylesheet_inputs.iter(),
+ let completed_stylesheet_clients = self
+ .note_discovered_document_owned_blocking_stylesheet_inputs(
+ discovered_blocking_stylesheet_inputs.iter(),
+ );
+ self.settle_stylesheet_link_clients_in_current_scope(
+ scope,
+ host_ptr,
+ completed_stylesheet_clients,
);
match result {
diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
index e894af850..c2168c36f 100644
--- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs
+++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
@@ -1808,6 +1808,7 @@ pub(super) fn finish_runtime_mutation_effects(
}
runtime.apply_pending_stylesheet_source_css_projections(scope, host_ptr);
if changed {
+ let mut prime_result = ConnectedStyleLoadPrimeResult::default();
let prepared_owner_changes =
runtime.prepare_stylesheet_owner_runtime_changes(&stylesheet_owner_changes);
let (canceled_load_event_bindings, prepared_owner_changes) =
@@ -1844,12 +1845,12 @@ pub(super) fn finish_runtime_mutation_effects(
continue;
};
debug_assert_eq!(prepared_load.owner(), owner);
- runtime.apply_prepared_connected_style_load(
+ prime_result.extend(runtime.apply_prepared_connected_style_load(
prepared_load,
inline_source.clone(),
event_admission,
host_ptr,
- );
+ ));
}
}
crate::native_bridge::document::apply_stylesheet_owner_css_projections(
@@ -1857,6 +1858,11 @@ pub(super) fn finish_runtime_mutation_effects(
unsafe { &*host_ptr },
&stylesheet_owner_changes,
);
+ let completed_clients = prime_result.take_completed_stylesheet_clients();
+ runtime.settle_stylesheet_link_clients_in_current_scope(scope, host_ptr, completed_clients);
+ runtime
+ .pending_connected_style_load_prime_result
+ .extend(prime_result);
}
changed
}
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling.rs b/moli-renderer-v8/src/document_runtime/script_scheduling.rs
index ea3fb57a0..315c49369 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling.rs
@@ -390,7 +390,12 @@ mod tests {
.expect("parser stylesheet should retain its exact event client");
// This low-level fixture has no ScriptVm to parse the root stylesheet and
// publish its import graph. Complete the known-empty graph explicitly.
- runtime.note_stylesheet_import_graph_completion(link_load.fetch(), true);
+ runtime.note_stylesheet_import_graph_completion(
+ link_load.fetch(),
+ Arc::new(
+ crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(true, Vec::new()),
+ ),
+ );
assert!(
runtime.has_connected_style_event_for_test(),
"the link load event should be resident in its independent DOM-manipulation source"
diff --git a/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs b/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs
index 8cf070b68..b53486756 100644
--- a/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs
+++ b/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs
@@ -1,7 +1,8 @@
use crate::{
document_runtime::{
ConnectedLoadCompletion, ConnectedStyleEventElementKind,
- LiveStylesheetImportLoadCompletion, ReadyConnectedStyleLoad,
+ LinkedStylesheetImportGraphCompletion, LiveStylesheetImportLoadCompletion,
+ ReadyConnectedStyleLoad,
},
frame_owner_model::FrameDocumentTaskOwner,
runtime::{PageOwnerTurnOutcome, RendererDocumentToken},
@@ -28,6 +29,7 @@ pub(crate) type RendererPageStylesheetTaskOwner = super::RendererPageMainDocumen
pub(crate) enum RendererPageStylesheetCompletion {
Blocking(StylesheetCompletion),
Connected(ConnectedLoadCompletion),
+ LinkedImport(LinkedStylesheetImportGraphCompletion),
LiveImport(LiveStylesheetImportLoadCompletion),
}
@@ -131,6 +133,13 @@ impl RendererPageStylesheetTaskProducer {
self.send_networking_completion(RendererPageStylesheetCompletion::Connected(completion))
}
+ pub(crate) fn send_linked_import_completion(
+ &self,
+ completion: LinkedStylesheetImportGraphCompletion,
+ ) -> Result<(), RendererPageStylesheetTaskRouteClosed> {
+ self.send_networking_completion(RendererPageStylesheetCompletion::LinkedImport(completion))
+ }
+
pub(crate) fn send_live_import_completion(
&self,
completion: LiveStylesheetImportLoadCompletion,
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs b/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs
index 81e34aae1..364ab56fe 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs
@@ -2,8 +2,8 @@ use super::*;
use crate::page_task_queue::{
PageConnectedStyleEventTargetEffect, PageConnectedStyleLoadDelayEffect,
- PageNetworkingTurnAction, PageStylesheetNetworkingTargetEffect, RendererOwnerWakeSource,
- RendererPageConnectedStyleEventTask,
+ PageDomManipulationTurnAction, PageNetworkingTurnAction, PageStylesheetNetworkingTargetEffect,
+ RendererOwnerWakeSource, RendererPageConnectedStyleEventTask,
};
use crate::runtime::PageTaskCompletion;
@@ -67,6 +67,48 @@ async fn wait_for_stylesheet_source(
);
}
+async fn complete_stylesheet_preload_for_cache_hit(
+ page_vm: &mut PageVm,
+ wake_rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::page_task_queue::RendererOwnerWake>,
+ loader: &crate::network::ResourceRequestClient,
+ href: &str,
+) -> anyhow::Result<()> {
+ let href = serde_json::to_string(href)?;
+ page_vm.vm_mut().eval(&format!(
+ r#"
+const cachedPreload = document.createElement("link");
+cachedPreload.rel = "preload";
+cachedPreload.as = "style";
+cachedPreload.href = {href};
+document.head.append(cachedPreload);
+"queued"
+"#,
+ ))?;
+ page_vm
+ .vm_mut()
+ .prime_document_lifecycle_processing_and_record_stylesheet_network_results();
+ wait_for_stylesheet_source(wake_rx, RendererOwnerWakeSource::NetworkingTask).await;
+ assert!(
+ page_vm
+ .run_exact_selected_page_task_for_test(
+ PageSelectedTaskTestSelector::StylesheetCompletion,
+ loader,
+ )
+ .await?,
+ "the preload physical terminal should consume one exact Networking turn"
+ );
+ wait_for_stylesheet_source(wake_rx, RendererOwnerWakeSource::DomManipulationTask).await;
+ let event = take_next_link_element_event_task_for_test(page_vm)
+ .expect("the completed preload should publish one link event");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(event),
+ loader,
+ )
+ .await?;
+ Ok(())
+}
+
fn parser_captured_stylesheet_input_for_test(
page_vm: &PageVm,
id: &str,
@@ -98,10 +140,13 @@ fn note_parser_captured_stylesheet_inputs_for_test(
page_vm: &mut PageVm,
inputs: &[crate::DocumentOwnedBlockingStylesheetDiscoveryInput],
) {
- page_vm
+ let completed_clients = page_vm
.vm_mut()
.document_runtime
.note_discovered_document_owned_blocking_stylesheet_inputs(inputs);
+ page_vm
+ .vm_mut()
+ .settle_stylesheet_link_clients(completed_clients);
}
fn queue_stylesheet_checkpoint_marker(page_vm: &mut PageVm, marker: &str) -> anyhow::Result<()> {
@@ -123,6 +168,714 @@ fn stylesheet_checkpoint_marker(page_vm: &mut PageVm, marker: &str) -> anyhow::R
.eval_without_microtask_checkpoint_for_test(&format!("String(globalThis.{marker})"))
}
+#[tokio::test(flavor = "current_thread")]
+async fn completed_data_preload_settles_new_stylesheet_client_synchronously() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url = Url::parse("https://example.com/stylesheet-completed-cache-hit").unwrap();
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let href = "data:text/css,.completed-cache-hit%7Bcolor%3Argb(1%2C%202%2C%203)%7D";
+ complete_stylesheet_preload_for_cache_hit(&mut page_vm, &mut wake_rx, &loader, href)
+ .await?;
+
+ let href = serde_json::to_string(href)?;
+ let synchronous_state = page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__completedCacheHitEvents = [];
+const cachedTarget = document.createElement("div");
+cachedTarget.className = "completed-cache-hit";
+document.body.append(cachedTarget);
+const cachedStyle = document.createElement("link");
+cachedStyle.id = "completed-cache-hit-style";
+cachedStyle.rel = "stylesheet";
+cachedStyle.href = {href};
+cachedStyle.addEventListener("load", () => __completedCacheHitEvents.push("load"));
+cachedStyle.addEventListener("error", () => __completedCacheHitEvents.push("error"));
+document.head.append(cachedStyle);
+[
+ Object.prototype.toString.call(cachedStyle.sheet),
+ getComputedStyle(cachedTarget).color,
+ __completedCacheHitEvents.join(",")
+].join("|")
+"#,
+ ))?;
+ assert_eq!(
+ synchronous_state,
+ "[object CSSStyleSheet]|rgb(1, 2, 3)|",
+ "a completed cache hit must install and style in the same append call while its link event remains asynchronous"
+ );
+
+ assert!(
+ page_vm
+ .take_stylesheet_networking_body_task_for_test()
+ .is_none(),
+ "a completed cache hit must not manufacture another physical Networking terminal"
+ );
+ assert!(
+ page_vm.has_ready_dom_manipulation_task_for_test(),
+ "client admission must publish the later link event without an external parser retry"
+ );
+
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the synchronously settled stylesheet should retain one link event");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(event),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm
+ .vm_mut()
+ .eval("__completedCacheHitEvents.join('|')")?,
+ "load"
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("completed data stylesheet cache-hit test should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn completed_data_import_graph_settles_late_stylesheet_client() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url =
+ Url::parse("https://example.com/stylesheet-completed-data-import").unwrap();
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let href = concat!(
+ "data:text/css,@import%20url(%22data:text/css,",
+ ".late-data-imported%257Bcolor%253Argb(21%252C%252022%252C%252023)%257D",
+ "%22)%3B"
+ );
+ complete_stylesheet_preload_for_cache_hit(&mut page_vm, &mut wake_rx, &loader, href)
+ .await?;
+
+ let href = serde_json::to_string(href)?;
+ assert_eq!(
+ page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__lateDataImportEvents = [];
+const target = document.createElement("div");
+target.className = "late-data-imported";
+document.body.append(target);
+const first = document.createElement("link");
+first.id = "data-import-first";
+first.rel = "stylesheet";
+first.href = {href};
+first.addEventListener("load", () => __lateDataImportEvents.push("first-load"));
+first.addEventListener("error", () => __lateDataImportEvents.push("first-error"));
+document.head.append(first);
+[
+ Object.prototype.toString.call(first.sheet),
+ getComputedStyle(target).color,
+ __lateDataImportEvents.join(",")
+].join("|")
+"#,
+ ))?,
+ "[object CSSStyleSheet]|rgb(21, 22, 23)|",
+ "the first client must complete the shared data import graph before its asynchronous event"
+ );
+ let first_event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the first data import client should publish one load event");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ first_event,
+ ),
+ &loader,
+ )
+ .await?;
+
+ assert_eq!(
+ page_vm.vm_mut().eval(&format!(
+ r#"
+const second = document.createElement("link");
+second.id = "data-import-second";
+second.rel = "stylesheet";
+second.href = {href};
+second.addEventListener("load", () => __lateDataImportEvents.push("second-load"));
+second.addEventListener("error", () => __lateDataImportEvents.push("second-error"));
+document.head.append(second);
+[
+ Object.prototype.toString.call(second.sheet),
+ getComputedStyle(target).color,
+ __lateDataImportEvents.join(",")
+].join("|")
+"#,
+ ))?,
+ "[object CSSStyleSheet]|rgb(21, 22, 23)|first-load",
+ "a late client must synchronously install the retained data import graph"
+ );
+ assert!(
+ !page_vm.has_ready_page_networking_task(),
+ "late data graph installation must not create another Networking task"
+ );
+
+ let second_event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the late data import client must publish one terminal event");
+ let body = page_vm.apply_selected_page_connected_style_event_turn(second_event)?;
+ assert_eq!(
+ body.action.target_effect,
+ PageConnectedStyleEventTargetEffect::DispatchedToCurrentOwner {
+ load_delay_effect: PageConnectedStyleLoadDelayEffect::ReleasedExactBinding,
+ },
+ "the late client event must release its exact Document load-delay binding"
+ );
+ page_vm
+ .finish_selected_page_dom_manipulation_task(
+ PageDomManipulationTurnAction::ConnectedStyleEvent(body.action),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm
+ .vm_mut()
+ .eval("__lateDataImportEvents.join(',')")?,
+ "first-load,second-load"
+ );
+ assert!(
+ take_next_link_element_event_task_for_test(&mut page_vm).is_none(),
+ "each data import client must settle exactly once"
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("completed data import graph late-client test should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn completed_preload_settlement_starts_imports_before_publishing_link_load() {
+ run_page_vm_async_test(async move {
+ let (base_url, server) = spawn_path_response_http_server(vec![
+ (
+ "/cached-root.css",
+ "HTTP/1.1 200 OK",
+ "@import './cached-child.css'; .cached-root { color: rgb(4, 5, 6); }"
+ .to_owned(),
+ Duration::ZERO,
+ ),
+ (
+ "/cached-child.css",
+ "HTTP/1.1 200 OK",
+ ".cached-child { color: rgb(7, 8, 9); }".to_owned(),
+ Duration::ZERO,
+ ),
+ ])
+ .await;
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url = Url::parse(&format!("{base_url}/page.html"))?;
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let href = format!("{base_url}/cached-root.css");
+ complete_stylesheet_preload_for_cache_hit(&mut page_vm, &mut wake_rx, &loader, &href)
+ .await?;
+
+ let href = serde_json::to_string(&href)?;
+ let synchronous_state = page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__cachedImportEvents = [];
+for (const className of ["cached-root", "cached-child"]) {{
+ const target = document.createElement("div");
+ target.className = className;
+ document.body.append(target);
+}}
+const cachedImport = document.createElement("link");
+cachedImport.id = "cached-import";
+cachedImport.rel = "stylesheet";
+cachedImport.href = {href};
+cachedImport.addEventListener("load", () => __cachedImportEvents.push("load"));
+cachedImport.addEventListener("error", () => __cachedImportEvents.push("error"));
+document.head.append(cachedImport);
+[
+ Object.prototype.toString.call(cachedImport.sheet),
+ String(cachedImport.sheet.cssRules[0].styleSheet),
+ getComputedStyle(document.querySelector(".cached-root")).color,
+ __cachedImportEvents.join(",")
+].join("|")
+"#,
+ ))?;
+
+ assert_eq!(
+ synchronous_state,
+ "[object CSSStyleSheet]|null|rgb(4, 5, 6)|",
+ "client admission must synchronously install the root and start its import while keeping the event asynchronous"
+ );
+ assert!(
+ !page_vm.has_ready_dom_manipulation_task_for_test(),
+ "the cached link event must wait for its import graph"
+ );
+
+ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;
+ assert!(
+ page_vm
+ .run_exact_selected_page_task_for_test(
+ PageSelectedTaskTestSelector::StylesheetCompletion,
+ &loader,
+ )
+ .await?,
+ "the cache-hit import graph should complete as Networking work"
+ );
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ r##"
+(() => {
+ const sheet = document.querySelector("#cached-import").sheet;
+ const child = sheet.cssRules[0].styleSheet;
+ return [
+ Object.prototype.toString.call(child),
+ child.cssRules.length,
+ getComputedStyle(document.querySelector(".cached-child")).color,
+ __cachedImportEvents.join(",")
+ ].join("|");
+})()
+"##,
+ )?,
+ "[object CSSStyleSheet]|1|rgb(7, 8, 9)|"
+ );
+
+ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::DomManipulationTask)
+ .await;
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the completed cache-hit import graph should publish one link event");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(event),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm.vm_mut().eval("__cachedImportEvents.join('|')")?,
+ "load"
+ );
+ server.await.expect("cached import fixture server");
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("completed stylesheet cache-hit import test should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn separately_appended_cache_hit_links_share_import_fetch_but_install_both_graphs() {
+ run_page_vm_async_test(async move {
+ let (base_url, server) = spawn_path_response_http_server(vec![
+ (
+ "/shared-root.css",
+ "HTTP/1.1 200 OK",
+ "@import './slow-child.css';".to_owned(),
+ Duration::ZERO,
+ ),
+ (
+ "/slow-child.css",
+ "HTTP/1.1 200 OK",
+ ".shared-import-target { color: rgb(17, 34, 51); }".to_owned(),
+ Duration::from_millis(100),
+ ),
+ ])
+ .await;
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url = Url::parse(&format!("{base_url}/page.html"))?;
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let href = format!("{base_url}/shared-root.css");
+ complete_stylesheet_preload_for_cache_hit(&mut page_vm, &mut wake_rx, &loader, &href)
+ .await?;
+
+ let href = serde_json::to_string(&href)?;
+ assert_eq!(
+ page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__sharedImportEvents = [];
+const target = document.createElement("div");
+target.className = "shared-import-target";
+document.body.append(target);
+const first = document.createElement("link");
+first.id = "shared-import-first";
+first.rel = "stylesheet";
+first.href = {href};
+first.addEventListener("load", () => __sharedImportEvents.push("first-load"));
+document.head.append(first);
+const second = document.createElement("link");
+second.id = "shared-import-second";
+second.rel = "stylesheet";
+second.href = {href};
+second.addEventListener("load", () => __sharedImportEvents.push("second-load"));
+document.head.append(second);
+[
+ String(first.sheet.cssRules[0].styleSheet),
+ String(second.sheet.cssRules[0].styleSheet),
+ __sharedImportEvents.join(",")
+].join("|")
+"#,
+ ))?,
+ "null|null|",
+ "both owners must synchronously install their root sheet while the shared import remains pending"
+ );
+
+ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;
+ assert!(
+ page_vm
+ .run_exact_selected_page_task_for_test(
+ PageSelectedTaskTestSelector::StylesheetCompletion,
+ &loader,
+ )
+ .await?,
+ "the shared import graph must complete as one Networking turn"
+ );
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ r##"
+(() => {
+ const first = document.querySelector("#shared-import-first");
+ const second = document.querySelector("#shared-import-second");
+ return [
+ first.sheet.cssRules[0].styleSheet !== null,
+ second.sheet.cssRules[0].styleSheet !== null,
+ getComputedStyle(document.querySelector(".shared-import-target")).color
+ ].join("|");
+})()
+"##,
+ )?,
+ "true|true|rgb(17, 34, 51)",
+ "the shared terminal must install the import graph into every owner sheet"
+ );
+
+ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::DomManipulationTask)
+ .await;
+ for _ in 0..2 {
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("each current link client must publish one load event");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ event,
+ ),
+ &loader,
+ )
+ .await?;
+ }
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ r##"
+(() => {
+ document.querySelector("#shared-import-first").remove();
+ const surviving = document.querySelector("#shared-import-second");
+ return [
+ surviving.sheet.cssRules[0].styleSheet !== null,
+ getComputedStyle(document.querySelector(".shared-import-target")).color,
+ __sharedImportEvents.sort().join(",")
+ ].join("|");
+})()
+"##,
+ )?,
+ "true|rgb(17, 34, 51)|first-load,second-load",
+ "removing the first owner must not remove the second owner's imported stylesheet"
+ );
+ assert_eq!(
+ page_vm.vm_mut().eval(&format!(
+ r#"
+const late = document.createElement("link");
+late.id = "shared-import-late";
+late.rel = "stylesheet";
+late.href = {href};
+late.addEventListener("load", () => __sharedImportEvents.push("late-load"));
+document.head.append(late);
+[
+ late.sheet.cssRules[0].styleSheet !== null,
+ getComputedStyle(document.querySelector(".shared-import-target")).color,
+ __sharedImportEvents.sort().join(",")
+].join("|")
+"#,
+ ))?,
+ "true|rgb(17, 34, 51)|first-load,second-load",
+ "a client admitted after graph completion must synchronously replay the retained graph"
+ );
+ assert!(
+ !page_vm.has_ready_page_networking_task(),
+ "late per-owner graph replay must not manufacture another Networking task"
+ );
+ let late_event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the late graph replay must publish its link event");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ late_event,
+ ),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm.vm_mut().eval("__sharedImportEvents.sort().join(',')")?,
+ "first-load,late-load,second-load"
+ );
+ server.await.expect("shared cache-hit import fixture server");
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("shared cache-hit stylesheet import test should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn failed_completed_preload_settles_empty_sheet_synchronously_before_link_error() {
+ run_page_vm_async_test(async move {
+ let (base_url, server) = spawn_path_response_http_server(vec![(
+ "/cached-failure.css",
+ "HTTP/1.1 404 Not Found",
+ "not found".to_owned(),
+ Duration::ZERO,
+ )])
+ .await;
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url = Url::parse(&format!("{base_url}/page.html"))?;
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let href = format!("{base_url}/cached-failure.css");
+ complete_stylesheet_preload_for_cache_hit(&mut page_vm, &mut wake_rx, &loader, &href)
+ .await?;
+
+ let href = serde_json::to_string(&href)?;
+ let synchronous_state = page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__failedCacheHitEvents = [];
+const failedCacheHit = document.createElement("link");
+failedCacheHit.id = "failed-cache-hit";
+failedCacheHit.rel = "stylesheet";
+failedCacheHit.href = {href};
+failedCacheHit.addEventListener("load", () => __failedCacheHitEvents.push("load"));
+failedCacheHit.addEventListener("error", () => __failedCacheHitEvents.push("error"));
+document.head.append(failedCacheHit);
+[
+ Object.prototype.toString.call(failedCacheHit.sheet),
+ failedCacheHit.sheet.cssRules.length,
+ __failedCacheHitEvents.join(",")
+].join("|")
+"#,
+ ))?;
+ assert_eq!(
+ synchronous_state,
+ "[object CSSStyleSheet]|0|",
+ "Blink-compatible failure settlement must install an empty CSSOM sheet in the append call while keeping error asynchronous"
+ );
+
+ assert!(
+ page_vm
+ .take_stylesheet_networking_body_task_for_test()
+ .is_none(),
+ "a failed completed cache hit must not create another physical task"
+ );
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the failed cache hit should publish one link error task");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ event,
+ ),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm.vm_mut().eval("__failedCacheHitEvents.join('|')")?,
+ "error"
+ );
+ server.await.expect("failed cache-hit fixture server");
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("failed completed stylesheet cache-hit test should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn posted_cache_hit_events_follow_link_and_document_lifetimes() {
+ run_page_vm_async_test(async move {
+ let (base_url, server) = spawn_path_response_http_server(vec![(
+ "/checkpoint-cache-hit.css",
+ "HTTP/1.1 200 OK",
+ ".checkpoint-cache-hit { color: green; }".to_owned(),
+ Duration::ZERO,
+ )])
+ .await;
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url = Url::parse(&format!("{base_url}/page.html"))?;
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let href = format!("{base_url}/checkpoint-cache-hit.css");
+ complete_stylesheet_preload_for_cache_hit(&mut page_vm, &mut wake_rx, &loader, &href)
+ .await?;
+ let href = serde_json::to_string(&href)?;
+
+ page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__retiredCacheHitEvents = [];
+globalThis.__hrefInvalidatedCacheHit = document.createElement("link");
+__hrefInvalidatedCacheHit.rel = "stylesheet";
+__hrefInvalidatedCacheHit.href = {href};
+__hrefInvalidatedCacheHit.addEventListener("load", () => __retiredCacheHitEvents.push("href-load"));
+__hrefInvalidatedCacheHit.addEventListener("error", () => __retiredCacheHitEvents.push("href-error"));
+document.head.append(__hrefInvalidatedCacheHit);
+Promise.resolve().then(() => __hrefInvalidatedCacheHit.removeAttribute("href"));
+"queued"
+"#,
+ ))?;
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ "[__hrefInvalidatedCacheHit.hasAttribute('href'), String(__hrefInvalidatedCacheHit.sheet), __retiredCacheHitEvents.join(',')].join('|')",
+ )?,
+ "false|null|"
+ );
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the already-posted href-invalidated event should remain selectable");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ event,
+ ),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm.vm_mut().eval("__retiredCacheHitEvents.join(',')")?,
+ "href-load",
+ "removing href must not retract a load task posted by an already-settled client"
+ );
+
+ page_vm.vm_mut().eval(&format!(
+ r#"
+globalThis.__disconnectedCacheHit = document.createElement("link");
+__disconnectedCacheHit.rel = "stylesheet";
+__disconnectedCacheHit.href = {href};
+__disconnectedCacheHit.addEventListener("load", () => __retiredCacheHitEvents.push("remove-load"));
+__disconnectedCacheHit.addEventListener("error", () => __retiredCacheHitEvents.push("remove-error"));
+document.head.append(__disconnectedCacheHit);
+Promise.resolve().then(() => __disconnectedCacheHit.remove());
+"queued"
+"#,
+ ))?;
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ "[__disconnectedCacheHit.isConnected, String(__disconnectedCacheHit.sheet), __retiredCacheHitEvents.join(',')].join('|')",
+ )?,
+ "false|null|href-load"
+ );
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the already-posted disconnected event should remain selectable");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ event,
+ ),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm.vm_mut().eval("__retiredCacheHitEvents.join(',')")?,
+ "href-load,remove-load",
+ "disconnecting the element must not retract its already-posted load task"
+ );
+
+ page_vm.vm_mut().eval(&format!(
+ r#"
+const replacedCacheHit = document.createElement("link");
+replacedCacheHit.rel = "stylesheet";
+replacedCacheHit.href = {href};
+replacedCacheHit.addEventListener("load", () => __retiredCacheHitEvents.push("replace-load"));
+replacedCacheHit.addEventListener("error", () => __retiredCacheHitEvents.push("replace-error"));
+document.head.append(replacedCacheHit);
+Promise.resolve().then(() => {{
+ document.open();
+ document.write("<!doctype html><body>replacement</body>");
+ document.close();
+}});
+"queued"
+"#,
+ ))?;
+ assert_eq!(page_vm.vm_mut().eval("document.body.textContent")?, "replacement");
+ let event = take_next_link_element_event_task_for_test(&mut page_vm)
+ .expect("the old Document's already-posted event should remain selectable");
+ page_vm
+ .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(
+ crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(
+ event,
+ ),
+ &loader,
+ )
+ .await?;
+ assert_eq!(
+ page_vm.vm_mut().eval("__retiredCacheHitEvents.join(',')")?,
+ "href-load,remove-load",
+ "exact-Document validation must discard the replaced Document's event task"
+ );
+ assert!(
+ page_vm
+ .take_stylesheet_networking_body_task_for_test()
+ .is_none(),
+ "invalidating cached clients must not create physical completion tasks"
+ );
+ server.await.expect("checkpoint cache-hit fixture server");
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("checkpoint stylesheet cache-hit invalidation test should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn completed_client_settlement_does_not_consume_an_unselected_physical_completion() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url = Url::parse("https://example.com/stylesheet-physical-residence").unwrap();
+ let (mut page_vm, _resource_source, mut wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ page_vm.vm_mut().eval(
+ r#"
+globalThis.__unselectedPhysicalEvents = [];
+const physical = document.createElement("link");
+physical.rel = "stylesheet";
+physical.href = "data:text/css,.unselected%7Bcolor%3Agreen%7D";
+physical.addEventListener("load", () => __unselectedPhysicalEvents.push("load"));
+document.head.append(physical);
+"queued"
+"#,
+ )?;
+ page_vm
+ .vm_mut()
+ .prime_document_lifecycle_processing_and_record_stylesheet_network_results();
+ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;
+
+ page_vm
+ .vm_mut()
+ .eval("globalThis.__unrelatedTurnFinished = true")?;
+ assert!(
+ !page_vm.has_ready_dom_manipulation_task_for_test(),
+ "an unrelated owner turn must not apply an unselected physical terminal"
+ );
+ let task = page_vm
+ .take_stylesheet_networking_body_task_for_test()
+ .expect("the physical stylesheet completion must remain in its Networking source");
+ let outcome = page_vm.apply_selected_page_stylesheet_networking_turn(task)?;
+ page_vm
+ .finish_selected_page_networking_task(
+ PageNetworkingTurnAction::StylesheetCompletion(outcome.action),
+ &loader,
+ )
+ .await?;
+ assert!(
+ page_vm.has_ready_dom_manipulation_task_for_test(),
+ "selecting the physical completion should publish its later link event"
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("unselected physical stylesheet residence test should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn stylesheet_networking_body_leaves_checkpoint_and_runtime_residence_untouched() {
run_page_vm_async_test(async move {
diff --git a/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs b/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs
index 0c4dfd83b..85ac13495 100644
--- a/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs
@@ -164,6 +164,97 @@ async fn spawn_two_document_write_script_server(
)
}
+async fn spawn_document_write_script_with_completed_stylesheet_preload_server() -> (
+ Url,
+ Url,
+ tokio::sync::oneshot::Sender<()>,
+ tokio::sync::oneshot::Receiver<()>,
+ JoinHandle<()>,
+) {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("document.write stylesheet preload server should bind");
+ let address = listener
+ .local_addr()
+ .expect("document.write stylesheet preload server should have an address");
+ let (script_release_tx, script_release_rx) = tokio::sync::oneshot::channel();
+ let (stylesheet_served_tx, stylesheet_served_rx) = tokio::sync::oneshot::channel();
+ let server = tokio::spawn(async move {
+ let mut script_stream = None;
+ let mut stylesheet_served_tx = Some(stylesheet_served_tx);
+ while script_stream.is_none() || stylesheet_served_tx.is_some() {
+ let (mut stream, _) = listener
+ .accept()
+ .await
+ .expect("document.write stylesheet preload request should arrive");
+ let mut request = vec![0; 4096];
+ let read = stream
+ .read(&mut request)
+ .await
+ .expect("document.write stylesheet preload request should be readable");
+ let request = String::from_utf8_lossy(&request[..read]);
+ if request.starts_with("GET /written.js ") {
+ assert!(
+ script_stream.replace(stream).is_none(),
+ "document.write external script should be requested once"
+ );
+ continue;
+ }
+ assert!(
+ request.starts_with("GET /ready.css "),
+ "unexpected document.write stylesheet preload request: {request}"
+ );
+ let body = "body { color: rgb(1, 2, 3); }";
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/css\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body,
+ );
+ stream
+ .write_all(response.as_bytes())
+ .await
+ .expect("stylesheet preload response should be writable");
+ stream
+ .shutdown()
+ .await
+ .expect("stylesheet preload response should close");
+ stylesheet_served_tx
+ .take()
+ .expect("stylesheet preload should be served once")
+ .send(())
+ .expect("stylesheet preload observer should remain attached");
+ }
+
+ script_release_rx
+ .await
+ .expect("document.write external script should be released");
+ let mut stream = script_stream.expect("document.write script request should be retained");
+ let body = "globalThis.__completedPreloadEvents.push('external');";
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body,
+ );
+ stream
+ .write_all(response.as_bytes())
+ .await
+ .expect("document.write external script response should be writable");
+ stream
+ .shutdown()
+ .await
+ .expect("document.write external script response should close");
+ });
+ (
+ Url::parse(&format!("http://{address}/written.js"))
+ .expect("document.write external script URL should parse"),
+ Url::parse(&format!("http://{address}/ready.css"))
+ .expect("stylesheet preload URL should parse"),
+ script_release_tx,
+ stylesheet_served_rx,
+ server,
+ )
+}
+
struct PendingStandaloneDocumentWritePage {
runtime: Box<ConcurrentParseTimeRuntime>,
started: Instant,
@@ -268,6 +359,62 @@ async fn wait_for_standalone_page_resource(
resource_source
}
+async fn wait_for_standalone_stylesheet_completion(
+ pending: &mut PendingStandaloneDocumentWritePage,
+) {
+ loop {
+ if pending
+ .runtime
+ .page_vm
+ .page_task_executor_sources_for_test()
+ .has_scheduler_task_for_executor_test(|descriptor| {
+ matches!(
+ descriptor,
+ crate::page_task_queue::RendererPageReadyDescriptor::Networking {
+ owner:
+ crate::page_task_queue::RendererPageNetworkingOwner::StylesheetCompletion(
+ _
+ ),
+ ..
+ }
+ )
+ })
+ {
+ return;
+ }
+ pending
+ .owner_wake_rx
+ .recv()
+ .await
+ .expect("stylesheet preload producer should retain its owner wake route");
+ }
+}
+
+async fn run_standalone_selected_page_task(
+ mut pending: PendingStandaloneDocumentWritePage,
+ selector: crate::runtime::page_vm::PageSelectedTaskTestSelector,
+) -> PendingStandaloneDocumentWritePage {
+ let executor = pending.runtime.page_vm.local_executor.clone();
+ super::access::run_named_owner_local_task(
+ executor,
+ "standalone selected Page task channel closed",
+ async move {
+ let loader = pending.runtime.loader.clone();
+ assert!(
+ pending
+ .runtime
+ .page_vm
+ .run_exact_selected_page_task_for_test(selector, &loader)
+ .await?,
+ "the fixture should expose one exact {selector:?} task"
+ );
+ Ok(pending)
+ },
+ )
+ .await
+ .expect("selected standalone Page task should execute on the owner lane")
+}
+
async fn resume_standalone_document_write_page(
pending: PendingStandaloneDocumentWritePage,
) -> (
@@ -523,6 +670,113 @@ globalThis.__documentWriteEvents.push('inline-after');
});
}
+#[test]
+fn document_write_completion_settles_a_completed_stylesheet_preload_during_parser_admission() {
+ super::tests::run_phase_one_large_stack_test(
+ "document-write-completed-stylesheet-preload",
+ || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("current-thread runtime should build");
+ runtime.block_on(tokio::task::LocalSet::new().run_until(async move {
+ let _js_runtime = crate::JsRuntime::initialize();
+ let (
+ script_url,
+ stylesheet_url,
+ script_release,
+ stylesheet_served,
+ server,
+ ) = spawn_document_write_script_with_completed_stylesheet_preload_server().await;
+ let document_url = script_url.join("page.html").expect("document URL");
+ let html = format!(
+ r#"<!doctype html><html><head><script>
+globalThis.__completedPreloadEvents = ['inline-before'];
+document.write(`<script src="{script_url}" onload="__completedPreloadEvents.push('script-load')"><\/script><link id="inserted-ready-style" rel="stylesheet" href="{stylesheet_url}" onload="__completedPreloadEvents.push('style-load')"><script>__completedPreloadEvents.push('tail')<\/script>`);
+globalThis.__completedPreloadEvents.push('inline-after');
+</script><link rel="preload" as="style" href="{stylesheet_url}"></head><body></body></html>"#,
+ );
+ let mut pending =
+ start_standalone_document_write_page(html, document_url).await;
+
+ tokio::time::timeout(std::time::Duration::from_secs(2), stylesheet_served)
+ .await
+ .expect("the scanned stylesheet preload should reach the local server")
+ .expect("the scanned stylesheet preload server should report completion");
+ wait_for_standalone_stylesheet_completion(&mut pending).await;
+ pending = run_standalone_selected_page_task(
+ pending,
+ crate::runtime::page_vm::PageSelectedTaskTestSelector::StylesheetCompletion,
+ )
+ .await;
+ assert!(
+ !pending
+ .runtime
+ .page_vm
+ .has_ready_dom_manipulation_task_for_test(),
+ "an ownerless preload must not publish an element event"
+ );
+
+ script_release
+ .send(())
+ .expect("document.write script response should be released");
+ drop(wait_for_standalone_page_resource(&mut pending).await);
+ pending = run_standalone_selected_page_task(
+ pending,
+ crate::runtime::page_vm::PageSelectedTaskTestSelector::ResourceCompletion,
+ )
+ .await;
+
+ let (pending_after_resource, result) = evaluate_pending_on_owner_local_task(
+ pending,
+ r#"JSON.stringify({
+ events: globalThis.__completedPreloadEvents,
+ linkConnected: !!document.getElementById('inserted-ready-style'),
+ sheet: Object.prototype.toString.call(document.getElementById('inserted-ready-style').sheet)
+})"#,
+ )
+ .await;
+ pending = pending_after_resource;
+ assert_eq!(
+ result.get("value").and_then(serde_json::Value::as_str),
+ Some(
+ r#"{"events":["inline-before","inline-after","external","script-load"],"linkConnected":true,"sheet":"[object CSSStyleSheet]"}"#,
+ ),
+ "the external script callback should synchronously install the completed-preload client but keep the following script behind its event"
+ );
+ assert!(
+ pending
+ .runtime
+ .page_vm
+ .has_ready_dom_manipulation_task_for_test(),
+ "parser admission must settle the adopted stylesheet and publish its later link event"
+ );
+
+ pending = run_standalone_selected_page_task(
+ pending,
+ crate::runtime::page_vm::PageSelectedTaskTestSelector::DomManipulation(
+ crate::runtime::page_vm::PageDomManipulationTestFamily::ConnectedStyleEvent,
+ ),
+ )
+ .await;
+ let (_, result) = evaluate_pending_on_owner_local_task(
+ pending,
+ "__completedPreloadEvents.join('|')",
+ )
+ .await;
+ assert_eq!(
+ result.get("value").and_then(serde_json::Value::as_str),
+ Some("inline-before|inline-after|external|script-load|style-load|tail"),
+ "the link event must release the parser-inserted script behind the adopted stylesheet"
+ );
+ server
+ .await
+ .expect("document.write stylesheet preload server should finish");
+ }));
+ },
+ );
+}
+
#[test]
fn document_write_external_script_live_collection_walk_uses_incremental_parser_frontier() {
super::tests::run_phase_one_large_stack_test("document-write-live-collection", || {
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 7b344d615..fe06c76d0 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -7737,9 +7737,11 @@ impl ScriptVm {
.await;
}
None => {
- self.document_runtime
+ let completed_stylesheet_clients = self
+ .document_runtime
.wait_for_script_blockers_before(script.node_id)
.await;
+ self.settle_stylesheet_link_clients(completed_stylesheet_clients);
}
}
self.record_ready_stylesheet_network_results();
diff --git a/moli-renderer-v8/src/script_vm/main_document_owner.rs b/moli-renderer-v8/src/script_vm/main_document_owner.rs
index 299d29cd0..d44e5eb54 100644
--- a/moli-renderer-v8/src/script_vm/main_document_owner.rs
+++ b/moli-renderer-v8/src/script_vm/main_document_owner.rs
@@ -35,12 +35,13 @@ impl ScriptVm {
);
continue;
};
- self.document_runtime.apply_prepared_connected_style_load(
+ let prime_result = self.document_runtime.apply_prepared_connected_style_load(
prepared,
inline_source,
event_admission,
self._context_host.as_ref().as_ptr(),
);
+ self.apply_connected_style_load_prime_result(prime_result);
}
}
@@ -58,8 +59,10 @@ impl ScriptVm {
);
return 0;
}
- self.document_runtime
+ let completed_stylesheet_clients = self
+ .document_runtime
.note_discovered_document_owned_blocking_stylesheet_inputs(inputs.iter());
+ self.settle_stylesheet_link_clients(completed_stylesheet_clients);
inputs.len()
}
diff --git a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs
index 45e6d3335..083e1bb95 100644
--- a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs
+++ b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs
@@ -2263,6 +2263,28 @@ impl ScriptVm {
});
}
+ pub(crate) fn settle_stylesheet_link_clients(
+ &mut self,
+ clients: Vec<crate::document_runtime::StylesheetLinkClientTerminal>,
+ ) {
+ if clients.is_empty() {
+ return;
+ }
+ let context_ptr: *const v8::Global<v8::Context> = &self.page_default_context;
+ let context_host = self._context_host.clone();
+ let document_runtime = &mut self.document_runtime;
+ self.renderer_document_isolate
+ .with_renderer_document_isolate_mut(|isolate| {
+ let scope = pin!(v8::HandleScope::new(isolate));
+ let scope = &mut scope.init();
+ let context = unsafe { v8::Local::new(scope, &*context_ptr) };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let host_ptr: *mut JsContextHost = (*context_host).as_ptr();
+ document_runtime
+ .settle_stylesheet_link_clients_in_current_scope(scope, host_ptr, clients);
+ });
+ }
+
pub(crate) fn dispatch_preload_like_link_error_event(&mut self, handle: DomHandle) -> bool {
let context_ptr: *const v8::Global<v8::Context> = &self.page_default_context;
let context_host = self._context_host.clone();
@@ -2335,16 +2357,18 @@ impl ScriptVm {
let prime_result = self
.document_runtime
.prime_document_lifecycle_processing_for_owner(self._context_host.as_ref().as_ptr());
- self.schedule_connected_modulepreloads_from_prime_result(prime_result);
+ self.apply_connected_style_load_prime_result(prime_result);
self.record_ready_stylesheet_network_results();
self.reconcile_document_web_fonts_for_layout();
}
- pub(crate) fn schedule_connected_modulepreloads_from_prime_result(
+ pub(crate) fn apply_connected_style_load_prime_result(
&mut self,
prime_result: crate::document_runtime::ConnectedStyleLoadPrimeResult,
) {
- let (modulepreload_starts, runtime_warnings) = prime_result.into_parts();
+ let (modulepreload_starts, runtime_warnings, completed_stylesheet_clients) =
+ prime_result.into_parts_with_completed_stylesheet_clients();
+ self.settle_stylesheet_link_clients(completed_stylesheet_clients);
for warning in runtime_warnings {
self.record_runtime_warning(format_args!("{warning}"));
}
@@ -2361,6 +2385,7 @@ impl ScriptVm {
}
}
+ #[cfg(test)]
pub(in crate::script_vm) fn queue_linked_stylesheet_import_csp_violations(
&mut self,
import_urls: impl IntoIterator<Item = url::Url>,
@@ -2424,8 +2449,6 @@ impl ScriptVm {
);
let mut performance_entries = Vec::new();
let mut css_subresources = Vec::new();
- let mut linked_stylesheet_import_urls = Vec::new();
- let mut linked_stylesheet_import_loads = Vec::new();
let mut import_graph_results: Vec<(
crate::document_runtime::ConnectedStyleImportRoot,
Vec<crate::live_stylesheet::LiveStylesheetImportResponse>,
@@ -2575,7 +2598,8 @@ impl ScriptVm {
}
}
for blocking_import_graph in blocking_import_graphs {
- let (operation, roots, graph, mut successful) = blocking_import_graph.into_parts();
+ let (source, roots, graph) = blocking_import_graph.into_parts();
+ let mut successful = graph.successful();
let expected_root_count = roots.len();
let roots = roots
.into_iter()
@@ -2585,27 +2609,8 @@ impl ScriptVm {
})
.collect::<Vec<_>>();
successful &= !roots.is_empty() && roots.len() == expected_root_count;
- let responses = graph
- .network_results()
- .iter()
- .map(|result| {
- let terminal = result.terminal();
- let physical_response = terminal.physical().as_result().ok();
- let ready_response = terminal.ready_response();
- crate::live_stylesheet::LiveStylesheetImportResponse {
- request_url: result.request_url().clone(),
- response_url: physical_response
- .as_ref()
- .map(|response| response.final_url.clone())
- .unwrap_or_else(|| result.request_url().clone()),
- css_text: ready_response
- .map(|response| response.body_text().to_owned())
- .unwrap_or_default(),
- successful: ready_response.is_some(),
- origin_clean: terminal.origin_clean().unwrap_or(false),
- }
- })
- .collect::<Vec<_>>();
+ let responses =
+ crate::document_runtime::live_stylesheet_import_responses(graph.as_ref());
if !roots.is_empty() {
for response in &responses {
if !response.successful {
@@ -2638,86 +2643,10 @@ impl ScriptVm {
}
}
self.document_runtime
- .complete_ready_blocking_style_import_graph(&operation, successful);
- }
- for client in client_terminals {
- let load = client.load();
- if !load.installs_stylesheet() {
- continue;
- }
- let terminal = client.terminal();
- // Blink creates the owner's CSSStyleSheet even when the resource
- // failed or was cancelled. An unusable terminal therefore installs
- // an empty source; its existing link task still reports the error.
- let ready_response = terminal.ready_response();
- let stylesheet_text = ready_response
- .map(|response| response.body_text().to_owned())
- .unwrap_or_default();
- let stylesheet_base_url = match terminal.physical() {
- crate::stylesheet_blocking::StylesheetPhysicalOutcome::Response(response) => {
- response.final_url.clone()
- }
- crate::stylesheet_blocking::StylesheetPhysicalOutcome::NetworkError(_) => {
- load.request_url().clone()
- }
- };
- let request_url = load.request_url().clone();
- let prepared = host.prepare_linked_stylesheet_resource(
- load.owner(),
- &stylesheet_text,
- stylesheet_base_url.clone(),
- request_url.clone(),
- terminal.origin_clean().unwrap_or(false),
- );
- if let Some(prepared) = prepared.as_ref() {
- host.install_linked_stylesheet(
- crate::document_runtime::InstallLinkedStylesheet::from_prepared(
- load.owner(),
- request_url.clone(),
- prepared.clone(),
- ),
- );
- }
- if !load.fetch().claim_dependent_resource_start() {
- continue;
- }
- let import_urls = ready_response
- .and(prepared.as_ref())
- .map(|prepared| prepared.import_urls().to_vec())
- .unwrap_or_default();
- linked_stylesheet_import_loads.push((Arc::clone(load), import_urls.clone()));
- if ready_response.is_none() {
- // Only a usable response may contribute CSS text, imports, or
- // other dependent resources. The empty owner sheet is CSSOM-only.
- continue;
- }
- if request_url.scheme() != "data" {
- linked_stylesheet_import_urls.extend(import_urls);
- }
- for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(
- &stylesheet_text,
- &stylesheet_base_url,
- optional_resource_fetch_mask,
- ) {
- let Some(binding) = host.accept_current_main_stylesheet_subresource_load_delay()
- else {
- tracing::debug!(
- url = %resource.request_url(),
- kind = ?resource.kind(),
- "skipping stylesheet subresource for stale main document owner"
- );
- continue;
- };
- css_subresources.push((binding, resource));
- }
+ .complete_ready_blocking_style_import_graph(source, successful, Arc::clone(&graph));
}
drop(host);
- let host_ptr: *mut JsContextHost = (*self._context_host).as_ptr();
- for (load, urls) in linked_stylesheet_import_loads {
- self.document_runtime
- .prime_network_stylesheet_import_loads(load, urls, host_ptr);
- }
- self.queue_linked_stylesheet_import_csp_violations(linked_stylesheet_import_urls);
+ self.settle_stylesheet_link_clients(client_terminals);
self.apply_pending_stylesheet_source_css_projections();
self.start_stylesheet_subresource_fetches(css_subresources);
self.record_resource_performance_entries(performance_entries);
@@ -2752,115 +2681,16 @@ impl ScriptVm {
if resources.is_empty() {
return;
}
- let started = Instant::now();
- let resource_count = resources.len();
- let context_host = self._context_host.clone();
- let retain_css_images = context_host.borrow().layout_policy().uses_real_layout();
- let mut admitted = Vec::with_capacity(resources.len());
- let mut duplicate_bindings = Vec::new();
- for (binding, resource) in resources {
- match resource.kind() {
- crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Font
- if binding.child_handle().is_none() =>
- {
- match self
- ._context_host
- .borrow()
- .admit_document_web_font(resource)
- {
- Some(resource) => admitted.push((binding, resource, None)),
- None => duplicate_bindings.push(binding),
- }
- }
- crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Image
- if retain_css_images =>
- {
- let resolved_url = resource.request_url().as_str().to_owned();
- match self
- ._context_host
- .borrow_mut()
- .admit_stylesheet_css_image(binding, resolved_url)
- {
- crate::native_bridge::CssImageResourceAdmission::Fetch(identity) => {
- admitted.push((binding, resource, Some(identity)));
- }
- crate::native_bridge::CssImageResourceAdmission::Reused => {
- duplicate_bindings.push(binding);
- }
- crate::native_bridge::CssImageResourceAdmission::Untracked => {
- admitted.push((binding, resource, None));
- }
- }
- }
- _ => admitted.push((binding, resource, None)),
- }
- }
- if !duplicate_bindings.is_empty() {
- let mut host = context_host.borrow_mut();
- for binding in duplicate_bindings {
- host.settle_stylesheet_subresource_load_delay(binding);
- }
- }
- let result = self.with_default_context_scope(move |scope, _host_ptr| {
- let mut host = context_host.borrow_mut();
- let mut local_web_fonts = Vec::new();
- for (binding, resource, css_image) in admitted {
- let request_url = resource.request_url().clone();
- let kind = resource.kind();
- let failed_css_image = css_image.clone();
- let failed_web_font = (binding.child_handle().is_none()
- && kind == crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Font)
- .then(|| {
- resource
- .web_font()
- .cloned()
- .map(crate::css_resource_urls::CompletedStylesheetWebFont::failure)
- })
- .flatten();
- match crate::network_host::start_stylesheet_subresource_fetch(
- scope, &mut host, binding, resource, css_image,
- ) {
- Ok(crate::network_host::StylesheetSubresourceFetchStart::WebFontSettled(
- web_font,
- )) => local_web_fonts.push(web_font),
- Ok(
- crate::network_host::StylesheetSubresourceFetchStart::Pending
- | crate::network_host::StylesheetSubresourceFetchStart::Settled,
- ) => {}
- Err(error) => {
- if let Some(identity) = failed_css_image.as_ref() {
- let _ = host.fail_stylesheet_css_image(identity);
- }
- let settlement = host.settle_stylesheet_subresource_load_delay(binding);
- local_web_fonts.extend(failed_web_font);
- tracing::warn!(
- url = %request_url,
- ?kind,
- owner = ?binding.owner(),
- settled = settlement.settled(),
- %error,
- "stylesheet subresource failed before network scheduling"
- );
- }
- }
- }
- Ok(local_web_fonts)
- });
- match result {
- Ok(web_fonts) => {
- for web_font in web_fonts {
- self.complete_document_web_font(web_font);
- }
- }
- Err(error) => self.record_runtime_warning(format_args!(
+ if let Err(error) = self.with_default_context_scope(move |scope, host_ptr| {
+ crate::document_runtime::DocumentRuntime::start_stylesheet_subresource_fetches_in_current_scope(
+ scope, host_ptr, resources,
+ );
+ Ok(())
+ }) {
+ self.record_runtime_warning(format_args!(
"failed to enter stylesheet subresource request scope: {error}"
- )),
+ ));
}
- debug!(
- resource_count,
- elapsed_ms = started.elapsed().as_millis(),
- "started owner-bound stylesheet subresource requests"
- );
}
pub(crate) fn record_script_subresource_network_result(
diff --git a/moli-renderer-v8/src/script_vm/stylesheet_page_tasks.rs b/moli-renderer-v8/src/script_vm/stylesheet_page_tasks.rs
index e14eb7a68..4278ae621 100644
--- a/moli-renderer-v8/src/script_vm/stylesheet_page_tasks.rs
+++ b/moli-renderer-v8/src/script_vm/stylesheet_page_tasks.rs
@@ -39,6 +39,9 @@ impl ScriptVm {
RendererPageStylesheetCompletion::Connected(completion) => self
.document_runtime
.apply_connected_style_load_completion(completion),
+ RendererPageStylesheetCompletion::LinkedImport(completion) => self
+ .document_runtime
+ .apply_linked_stylesheet_import_graph_completion(completion),
RendererPageStylesheetCompletion::LiveImport(completion) => self
.document_runtime
.apply_live_stylesheet_import_load_completion(completion, current),
diff --git a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs
index 364908ae4..be4664828 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs
@@ -113,22 +113,27 @@ impl DocumentRuntime {
pub(crate) fn note_discovered_document_owned_blocking_stylesheet_inputs<'a>(
&mut self,
inputs: impl IntoIterator<Item = &'a DocumentOwnedBlockingStylesheetDiscoveryInput>,
- ) {
+ ) -> Vec<super::StylesheetLinkClientTerminal> {
let document_url = self.document_url().clone();
self.note_discovered_document_owned_blocking_stylesheet_inputs_for_document_url(
&document_url,
inputs,
- );
+ )
}
pub(crate) fn note_discovered_document_owned_blocking_stylesheet_inputs_for_document_url<'a>(
&mut self,
document_url: &url::Url,
inputs: impl IntoIterator<Item = &'a DocumentOwnedBlockingStylesheetDiscoveryInput>,
- ) {
+ ) -> Vec<super::StylesheetLinkClientTerminal> {
let inputs = inputs.into_iter().cloned().collect::<Vec<_>>();
let fetcher = self.stylesheet_fetcher();
- self.discover_unblocked_stylesheet_inputs(&fetcher, document_url, inputs);
+ let inputs = self.discover_unblocked_stylesheet_inputs(&fetcher, document_url, inputs);
+ self.bind_discovered_link_owner_operations(
+ inputs
+ .iter()
+ .map(|input| (input.node_id(), input.signature())),
+ )
}
fn discover_unblocked_stylesheet_inputs(
@@ -136,7 +141,7 @@ impl DocumentRuntime {
fetcher: &crate::stylesheet_blocking::RendererStylesheetFetcher,
document_url: &url::Url,
inputs: impl IntoIterator<Item = DocumentOwnedBlockingStylesheetDiscoveryInput>,
- ) {
+ ) -> Vec<DocumentOwnedBlockingStylesheetDiscoveryInput> {
let inputs = inputs
.into_iter()
.filter(|input| {
@@ -148,15 +153,20 @@ impl DocumentRuntime {
document_url,
inputs.iter(),
);
- self.bind_discovered_link_owner_operations(
- inputs
- .iter()
- .map(|input| (input.node_id(), input.signature())),
- );
+ inputs
}
- pub(crate) async fn wait_for_script_blockers_before(&mut self, target_node_id: NodeId) {
- self.note_discovered_live_blocking_stylesheets();
+ pub(crate) async fn wait_for_script_blockers_before(
+ &mut self,
+ target_node_id: NodeId,
+ ) -> Vec<super::StylesheetLinkClientTerminal> {
+ let blockers = collect_document_owned_blocking_stylesheets(&self.dom_host);
+ let inputs = blockers
+ .iter()
+ .map(DocumentOwnedBlockingStylesheetDiscoveryInput::from)
+ .collect::<Vec<_>>();
+ let completed_clients =
+ self.note_discovered_document_owned_blocking_stylesheet_inputs(inputs.iter());
loop {
self.drain_blocking_stylesheet_completions();
if !self
@@ -164,7 +174,7 @@ impl DocumentRuntime {
.fetches
.blocks_script(&self.dom_host, target_node_id)
{
- return;
+ return completed_clients;
}
if !self
.stylesheet_lifecycle
@@ -172,7 +182,7 @@ impl DocumentRuntime {
.wait_for_completion_arrival_without_timeout()
.await
{
- return;
+ return completed_clients;
}
}
}
@@ -180,7 +190,8 @@ impl DocumentRuntime {
fn bind_discovered_link_owner_operations<'a>(
&mut self,
blockers: impl IntoIterator<Item = (moli_dom::NodeId, &'a DocumentBlockingStylesheetSignature)>,
- ) {
+ ) -> Vec<super::StylesheetLinkClientTerminal> {
+ let mut completed_clients = Vec::new();
for (node_id, signature) in blockers {
let DocumentBlockingStylesheetSignature::Link { url, .. } = signature else {
continue;
@@ -201,17 +212,19 @@ impl DocumentRuntime {
if already_bound {
continue;
}
- let import_completion_successful =
- super::connected::initial_stylesheet_import_completion_successful(url, &fetch);
+ let import_completion = self.initial_stylesheet_import_completion(url, &fetch);
let load = super::StylesheetLinkClient::new(owner, url.clone(), fetch);
self.install_stylesheet_link_state(
owner,
- super::LinkStyleState::new(Arc::clone(&load), import_completion_successful),
+ super::LinkStyleState::new(Arc::clone(&load), import_completion),
);
// A speculative resource may already be terminal when the parser
// creates its first real owner. No future terminal will revisit it.
- self.promote_stylesheet_link_client_if_ready(load);
+ if let Some(client) = self.promote_stylesheet_link_client_if_ready(load) {
+ completed_clients.push(client);
+ }
}
+ completed_clients
}
pub(crate) async fn wait_for_document_owned_blocking_stylesheet_signatures<'a>(
diff --git a/moli-renderer-v8/src/stylesheet_runtime/blocking_import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/blocking_import_graph.rs
new file mode 100644
index 000000000..d9fcb22d3
--- /dev/null
+++ b/moli-renderer-v8/src/stylesheet_runtime/blocking_import_graph.rs
@@ -0,0 +1,225 @@
+//! Bridge between parser-blocking import discovery and live CSSOM owners.
+//!
+//! Inline `<style>` imports remain owner-bound. Linked stylesheet imports are
+//! fetch-bound: the parser may have started their graph for one link, but the
+//! retained result belongs to the shared physical fetch and can be installed
+//! into every current or future client.
+
+use super::*;
+
+#[derive(Debug)]
+pub(crate) struct ReadyBlockingStyleImportGraph {
+ source: ReadyBlockingStyleImportGraphSource,
+ roots: Vec<ConnectedStyleImportRoot>,
+ graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+}
+
+#[derive(Debug)]
+pub(crate) enum ReadyBlockingStyleImportGraphSource {
+ Inline(Arc<ConnectedLoadOperation>),
+ Linked(crate::stylesheet_blocking::StylesheetFetch),
+}
+
+impl ReadyBlockingStyleImportGraph {
+ fn inline(
+ operation: Arc<ConnectedLoadOperation>,
+ roots: Vec<ConnectedStyleImportRoot>,
+ graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ ) -> Self {
+ Self {
+ source: ReadyBlockingStyleImportGraphSource::Inline(operation),
+ roots,
+ graph,
+ }
+ }
+
+ fn linked(
+ fetch: crate::stylesheet_blocking::StylesheetFetch,
+ roots: Vec<ConnectedStyleImportRoot>,
+ graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ ) -> Self {
+ Self {
+ source: ReadyBlockingStyleImportGraphSource::Linked(fetch),
+ roots,
+ graph,
+ }
+ }
+
+ pub(crate) fn into_parts(
+ self,
+ ) -> (
+ ReadyBlockingStyleImportGraphSource,
+ Vec<ConnectedStyleImportRoot>,
+ Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ ) {
+ (self.source, self.roots, self.graph)
+ }
+}
+
+impl DocumentRuntime {
+ pub(crate) fn reconcile_connected_style_imports_with_blocking_stylesheets(&mut self) {
+ self.restart_invalidated_linked_stylesheet_import_blocking_operations();
+ let pending_imports = self
+ .stylesheet_lifecycle
+ .owner_states
+ .pending_operations()
+ .into_iter()
+ .filter(|operation| {
+ matches!(
+ &operation.parameters,
+ ConnectedLoadParameters::StyleImports { .. }
+ ) && operation.blocking_operation.is_some()
+ })
+ .collect::<Vec<_>>();
+ for operation in pending_imports {
+ if self.connected_style_import_uses_blocking_stylesheet(&operation) {
+ continue;
+ }
+ let handle = operation.owner;
+ if self
+ .stylesheet_lifecycle
+ .owner_states
+ .pending_operation(handle)
+ .is_none_or(|pending| !ConnectedLoadOperation::ptr_eq(pending, &operation))
+ {
+ continue;
+ }
+ self.stylesheet_lifecycle
+ .owner_states
+ .clear_connected_operation(handle);
+ let inline_source = match &operation.parameters {
+ ConnectedLoadParameters::StyleImports { source, .. } => {
+ Some(Arc::clone(source.source()))
+ }
+ ConnectedLoadParameters::ImmediateOwnerProcessing
+ | ConnectedLoadParameters::PreloadLikeLink { .. } => None,
+ };
+ self.stylesheet_lifecycle.pending_connected_loads.push_back(
+ QueuedConnectedStyleLoad::new(
+ handle,
+ inline_source,
+ operation
+ .load_event_binding()
+ .map(ConnectedStyleLoadEventAdmission::LoadDelaying),
+ ),
+ );
+ }
+ }
+
+ pub(super) fn connected_style_import_uses_blocking_stylesheet(
+ &self,
+ operation: &Arc<ConnectedLoadOperation>,
+ ) -> bool {
+ let ConnectedLoadParameters::StyleImports { urls, .. } = &operation.parameters else {
+ return false;
+ };
+ let Some(blocking_operation) = &operation.blocking_operation else {
+ return false;
+ };
+ debug_assert_eq!(
+ blocking_operation.signature(),
+ &DocumentBlockingStylesheetSignature::ParserCreatedStyleImport {
+ urls: urls.to_vec(),
+ }
+ );
+ self.stylesheet_lifecycle
+ .fetches
+ .status_for_blocking_operation(blocking_operation)
+ .is_some()
+ }
+
+ pub(crate) fn take_ready_blocking_style_import_graphs(
+ &mut self,
+ ) -> Vec<ReadyBlockingStyleImportGraph> {
+ let pending_inline_imports = self
+ .stylesheet_lifecycle
+ .owner_states
+ .pending_operations()
+ .into_iter()
+ .filter(|operation| {
+ matches!(
+ &operation.parameters,
+ ConnectedLoadParameters::StyleImports { .. }
+ ) && operation.blocking_operation.is_some()
+ })
+ .collect::<Vec<_>>();
+ let mut ready = Vec::new();
+ for operation in pending_inline_imports {
+ let Some(blocking_operation) = operation.blocking_operation.as_ref() else {
+ continue;
+ };
+ let Some(status) = self
+ .stylesheet_lifecycle
+ .fetches
+ .status_for_blocking_operation(blocking_operation)
+ else {
+ continue;
+ };
+ if status == StylesheetBlockingStatus::Pending {
+ continue;
+ }
+ let ConnectedLoadParameters::StyleImports { roots, .. } = &operation.parameters else {
+ continue;
+ };
+ let roots = roots.clone();
+ let Some(graph) = self
+ .stylesheet_lifecycle
+ .fetches
+ .take_completed_import_graph_for_blocking_operation(blocking_operation)
+ else {
+ continue;
+ };
+ ready.push(ReadyBlockingStyleImportGraph::inline(
+ operation, roots, graph,
+ ));
+ }
+
+ for (fetch, blocking_operation, _) in self.linked_stylesheet_import_blocking_operations() {
+ let Some(status) = self
+ .stylesheet_lifecycle
+ .fetches
+ .status_for_blocking_operation(&blocking_operation)
+ else {
+ continue;
+ };
+ if status == StylesheetBlockingStatus::Pending {
+ continue;
+ }
+ let Some(graph) = self
+ .stylesheet_lifecycle
+ .fetches
+ .take_completed_import_graph_for_blocking_operation(&blocking_operation)
+ else {
+ continue;
+ };
+ let roots = self.linked_stylesheet_import_roots(&fetch);
+ ready.push(ReadyBlockingStyleImportGraph::linked(fetch, roots, graph));
+ }
+ ready
+ }
+
+ pub(crate) fn complete_ready_blocking_style_import_graph(
+ &mut self,
+ source: ReadyBlockingStyleImportGraphSource,
+ owner_install_successful: bool,
+ graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ ) {
+ match source {
+ ReadyBlockingStyleImportGraphSource::Linked(fetch) => {
+ self.note_stylesheet_import_graph_completion(&fetch, graph);
+ }
+ ReadyBlockingStyleImportGraphSource::Inline(operation) => {
+ if self
+ .stylesheet_lifecycle
+ .owner_states
+ .accept_completion(&operation, 0, true)
+ {
+ self.note_connected_style_import_completion(
+ &operation,
+ owner_install_successful,
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/stylesheet_runtime/completion.rs b/moli-renderer-v8/src/stylesheet_runtime/completion.rs
index 7ff67d02e..f566e6cdd 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/completion.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/completion.rs
@@ -52,6 +52,7 @@ impl DocumentRuntime {
self.stylesheet_lifecycle
.link_client_index
.unregister(replaced.active_load());
+ self.unregister_linked_stylesheet_import_consumer(replaced.active_load());
}
if load.fetch().terminal().is_none() {
self.stylesheet_lifecycle.link_client_index.register(load);
@@ -68,6 +69,7 @@ impl DocumentRuntime {
self.stylesheet_lifecycle
.link_client_index
.unregister(&load);
+ self.unregister_linked_stylesheet_import_consumer(&load);
}
self.stylesheet_lifecycle
.owner_states
@@ -77,9 +79,11 @@ impl DocumentRuntime {
pub(super) fn promote_stylesheet_link_client_if_ready(
&mut self,
load: Arc<StylesheetLinkClient>,
- ) {
+ ) -> Option<StylesheetLinkClientTerminal> {
let active_link_clients = self.stylesheet_lifecycle.link_client_index.len();
- self.promote_stylesheet_link_client_candidates(vec![load], active_link_clients);
+ self.promote_stylesheet_link_client_candidates(vec![load], active_link_clients)
+ .into_iter()
+ .next()
}
pub(super) fn promote_stylesheet_link_clients_for_fetch(
@@ -91,14 +95,18 @@ impl DocumentRuntime {
.stylesheet_lifecycle
.link_client_index
.take_for_fetch(fetch);
- self.promote_stylesheet_link_client_candidates(clients, active_link_clients);
+ let terminals =
+ self.promote_stylesheet_link_client_candidates(clients, active_link_clients);
+ self.stylesheet_lifecycle
+ .ready_stylesheet_link_client_terminals
+ .extend(terminals);
}
fn promote_stylesheet_link_client_candidates(
&mut self,
candidates: Vec<Arc<StylesheetLinkClient>>,
active_link_clients: usize,
- ) {
+ ) -> Vec<StylesheetLinkClientTerminal> {
#[cfg(test)]
let trace_enabled = true;
#[cfg(not(test))]
@@ -106,6 +114,7 @@ impl DocumentRuntime {
let trace_started = trace_enabled.then(std::time::Instant::now);
let mut inspected_link_states = 0_u64;
let mut promoted_clients = 0_u64;
+ let mut terminals = Vec::new();
for load in candidates {
if trace_enabled {
inspected_link_states += 1;
@@ -127,12 +136,10 @@ impl DocumentRuntime {
.unwrap_or((false, None));
if accepted {
promoted_clients += 1;
- self.stylesheet_lifecycle
- .ready_stylesheet_link_client_terminals
- .push_back(StylesheetLinkClientTerminal::new(
- Arc::clone(&load),
- terminal,
- ));
+ terminals.push(StylesheetLinkClientTerminal::new(
+ Arc::clone(&load),
+ terminal,
+ ));
}
if let Some((load, successful)) = ready {
self.push_ready_connected_style_load(ReadyConnectedStyleLoad::for_stylesheet_link(
@@ -162,6 +169,7 @@ impl DocumentRuntime {
stage = "stylesheet_link_client_promotion_done",
);
}
+ terminals
}
pub(super) fn note_connected_style_import_completion(
@@ -169,36 +177,13 @@ impl DocumentRuntime {
operation: &Arc<ConnectedLoadOperation>,
successful: bool,
) {
- if let ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Linked(load),
- ..
- } = &operation.parameters
- {
- self.note_stylesheet_import_graph_completion(load.fetch(), successful);
- return;
- }
- let handle = operation.owner;
- if let Some(state) = self
- .stylesheet_lifecycle
- .owner_states
- .link_state_mut(handle)
- {
- let accepted = state.accept_import_completion(successful);
- let ready = accepted.then(|| state.take_ready_event()).flatten();
- if let Some((load, successful)) = ready {
- self.push_ready_connected_style_load(ReadyConnectedStyleLoad::for_stylesheet_link(
- load, successful,
- ));
- }
- return;
- }
self.push_ready_connected_style_load(ReadyConnectedStyleLoad::for_operation(
Arc::clone(operation),
successful,
));
}
- fn note_stylesheet_link_import_completion(
+ pub(super) fn note_stylesheet_link_import_completion(
&mut self,
load: &Arc<StylesheetLinkClient>,
successful: bool,
@@ -220,27 +205,6 @@ impl DocumentRuntime {
}
}
- pub(crate) fn note_stylesheet_import_graph_completion(
- &mut self,
- fetch: &crate::stylesheet_blocking::StylesheetFetch,
- successful: bool,
- ) {
- let _ = fetch.finish_import_graph(successful);
- let successful = fetch
- .import_graph_terminal()
- .expect("a finished stylesheet import graph must retain its terminal");
- let clients = self
- .stylesheet_lifecycle
- .owner_states
- .link_states()
- .filter(|(_, state)| state.active_load().fetch().ptr_eq(fetch))
- .map(|(_, state)| Arc::clone(state.active_load()))
- .collect::<Vec<_>>();
- for client in clients {
- self.note_stylesheet_link_import_completion(&client, successful);
- }
- }
-
pub(in crate::document_runtime) fn apply_network_result_install_authority(
&mut self,
mut result: ConnectedLoadNetworkResult,
@@ -280,27 +244,6 @@ impl DocumentRuntime {
result.import_roots.clear();
return result;
};
- if let ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Linked(load),
- roots,
- ..
- } = &operation.parameters
- {
- result.import_roots = roots
- .iter()
- .filter(|root| {
- self.dom_host.is_connected(root.owner)
- && self
- .stylesheet_lifecycle
- .owner_states
- .link_state(root.owner)
- .is_some_and(|state| state.active_load().fetch().ptr_eq(load.fetch()))
- })
- .cloned()
- .collect();
- result.source_owners = result.import_roots.iter().map(|root| root.owner).collect();
- return result;
- }
let accepted = self.dom_host.is_connected(operation.owner)
&& self
.stylesheet_lifecycle
@@ -339,37 +282,10 @@ impl DocumentRuntime {
successful,
mut network_results,
} = completion;
- if matches!(
- &operation.parameters,
- ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Linked(_),
- ..
- }
- ) {
- // A linked sheet's import graph is owned by its shared physical
- // fetch, not by whichever DOM client happened to start it. Keep all
- // responses observable while avoiding top-level source rebinding,
- // then fan completion out to every still-current client.
- let _ = self
- .stylesheet_lifecycle
- .owner_states
- .accept_completion(&operation, 0, false);
- for result in &mut network_results {
- result.source_operation = Some(Arc::clone(&operation));
- }
- self.stylesheet_lifecycle
- .ready_connected_load_network_results
- .extend(network_results);
- self.note_connected_style_import_completion(&operation, successful);
- return;
- }
let (source_result_count, event_pending) = match &operation.parameters {
ConnectedLoadParameters::ImmediateOwnerProcessing
| ConnectedLoadParameters::PreloadLikeLink { .. } => (0, true),
- ConnectedLoadParameters::StyleImports { source, .. } => (
- network_results.len(),
- matches!(source, ConnectedStyleImportSource::Inline(_)),
- ),
+ ConnectedLoadParameters::StyleImports { .. } => (network_results.len(), true),
};
if !self.stylesheet_lifecycle.owner_states.accept_completion(
&operation,
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index 0e75494d0..715958b7d 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -3,23 +3,19 @@ use tracing::debug;
use super::*;
use crate::frame_owner_model::MainDocumentStyleLoadEventBinding;
use crate::link_as::{LinkAsDestination, link_as_destination};
-use crate::live_stylesheet::import_url_identity;
use crate::module_runtime::{
ModuleMapKey, NativeModuleSingleFetchRequest, NativeModulepreloadLinkClient,
};
use crate::planning::{ScriptFetchMetadata, module_script_credentials_mode};
use crate::service_worker_runtime::ServiceWorkerRequestDestination;
use crate::stylesheet_blocking::{
- StylesheetFetchOptions, StylesheetFetcher, connected_preload_like_link_url,
+ StylesheetFetchOptions, connected_preload_like_link_url,
document_owned_blocking_stylesheet_candidate_for_node, link_rel_includes_token,
preload_like_link_loads_stylesheet, stylesheet_link_disposition,
stylesheet_preload_link_request,
};
use crate::types::{AsyncSubresourceFetchResponseFilter, SubresourceResourceType};
-use futures_util::future::join_all;
-use moli_encoding::decode_text_for_legacy_web;
use moli_fetch::{FetchPriorityHint, RequestCredentialsMode, RequestResourceType};
-use moli_web_mime::{data_url_body_and_mime_type, mime_charset};
struct ConnectedLinkReadinessFetchResponse {
response: crate::protocol_types::NavigationResponse,
@@ -41,13 +37,6 @@ impl ConnectedLinkReadinessFetchResponse {
}
}
-#[derive(Debug, Clone, PartialEq, Eq)]
-enum DataStylesheetImportReadiness {
- NoImports,
- Imports(Vec<Url>),
- Failed,
-}
-
#[derive(Debug)]
pub(crate) struct ConnectedModulepreloadStart {
request: NativeModuleSingleFetchRequest,
@@ -79,6 +68,7 @@ impl ConnectedModulepreloadStart {
pub(crate) struct ConnectedStyleLoadPrimeResult {
modulepreload_starts: Vec<ConnectedModulepreloadStart>,
runtime_warnings: Vec<String>,
+ completed_stylesheet_clients: Vec<StylesheetLinkClientTerminal>,
}
/// One DOM-derived connected-style operation awaiting lifecycle commit.
@@ -177,19 +167,45 @@ impl ConnectedStyleLoadPrimeResult {
self.runtime_warnings.push(warning.into());
}
- fn extend(&mut self, other: Self) {
+ fn push_completed_stylesheet_client(&mut self, client: StylesheetLinkClientTerminal) {
+ self.completed_stylesheet_clients.push(client);
+ }
+
+ pub(in crate::document_runtime) fn extend(&mut self, other: Self) {
self.modulepreload_starts.extend(other.modulepreload_starts);
self.runtime_warnings.extend(other.runtime_warnings);
+ self.completed_stylesheet_clients
+ .extend(other.completed_stylesheet_clients);
}
+ pub(crate) fn take_completed_stylesheet_clients(
+ &mut self,
+ ) -> Vec<StylesheetLinkClientTerminal> {
+ std::mem::take(&mut self.completed_stylesheet_clients)
+ }
+
+ #[cfg(test)]
pub(crate) fn into_parts(self) -> (Vec<ConnectedModulepreloadStart>, Vec<String>) {
+ debug_assert!(
+ self.completed_stylesheet_clients.is_empty(),
+ "completed stylesheet clients require immediate settlement"
+ );
(self.modulepreload_starts, self.runtime_warnings)
}
-}
-enum ConnectedStyleImportReadiness {
- Ready(bool),
- Pending(Vec<Url>),
+ pub(crate) fn into_parts_with_completed_stylesheet_clients(
+ self,
+ ) -> (
+ Vec<ConnectedModulepreloadStart>,
+ Vec<String>,
+ Vec<StylesheetLinkClientTerminal>,
+ ) {
+ (
+ self.modulepreload_starts,
+ self.runtime_warnings,
+ self.completed_stylesheet_clients,
+ )
+ }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -205,136 +221,6 @@ impl ConnectedStyleOwnerKind {
}
}
-const MAX_DATA_STYLESHEET_IMPORT_EXPANSIONS: usize = 16;
-const MAX_DATA_STYLESHEET_IMPORT_URL_BYTES: usize = 16 * 1024;
-
-#[derive(Default)]
-struct ConnectedNetworkStyleImportGraph {
- pending_urls: std::collections::VecDeque<Url>,
- admitted_identities: std::collections::HashSet<Url>,
-}
-
-impl ConnectedNetworkStyleImportGraph {
- fn extend(&mut self, urls: impl IntoIterator<Item = Url>) {
- for url in urls {
- let identity = import_url_identity(&url);
- if self.admitted_identities.contains(&identity) {
- continue;
- }
- self.admitted_identities.insert(identity);
- self.pending_urls.push_back(url);
- }
- }
-
- fn is_empty(&self) -> bool {
- self.pending_urls.is_empty()
- }
-
- fn take_pending(&mut self) -> Vec<Url> {
- self.pending_urls.drain(..).collect()
- }
-}
-
-pub(crate) async fn fetch_complete_stylesheet_import_graph(
- stylesheet_fetcher: crate::stylesheet_blocking::RendererStylesheetFetcher,
- document_url: Url,
- urls: Vec<Url>,
-) -> crate::stylesheet_blocking::StylesheetImportGraphFetchResult {
- let (mut successful, urls) = match connected_style_import_readiness(urls) {
- ConnectedStyleImportReadiness::Ready(successful) => {
- return crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(
- successful,
- Vec::new(),
- );
- }
- ConnectedStyleImportReadiness::Pending(urls) => (true, urls),
- };
- let mut network_results = Vec::new();
- let mut import_graph = ConnectedNetworkStyleImportGraph::default();
- import_graph.extend(urls);
- while !import_graph.is_empty() {
- let current_urls = import_graph.take_pending();
- let pending_fetches = join_all(current_urls.into_iter().map(|url| {
- let stylesheet_fetcher = stylesheet_fetcher.clone();
- let fetch_document_url = document_url.clone();
- let request_url = url.clone();
- let start_unix_millis = moli_time::unix_epoch_millis();
- async move {
- let terminal = stylesheet_fetcher
- .fetch_stylesheet_resource(
- fetch_document_url,
- request_url,
- StylesheetFetchOptions::default(),
- )
- .await;
- (url, start_unix_millis, terminal)
- }
- }))
- .await;
- for (url, start_unix_millis, terminal) in pending_fetches {
- successful &= terminal.is_ready();
- if let Some(response) = terminal.ready_response() {
- let nested_urls = crate::style_engine::stylesheet_top_level_import_urls(
- response.body_text(),
- &response.final_url,
- false,
- )
- .unwrap_or_default();
- match connected_style_import_readiness(nested_urls) {
- ConnectedStyleImportReadiness::Ready(nested_successful) => {
- successful &= nested_successful;
- }
- ConnectedStyleImportReadiness::Pending(urls) => {
- import_graph.extend(urls);
- }
- }
- }
- network_results.push(
- crate::stylesheet_blocking::StylesheetImportNetworkResult::new(
- url,
- start_unix_millis,
- terminal,
- ),
- );
- }
- }
- crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(successful, network_results)
-}
-
-async fn fetch_connected_style_import_graph(
- stylesheet_fetcher: crate::stylesheet_blocking::RendererStylesheetFetcher,
- document_url: Url,
- urls: Vec<Url>,
- source_owners: Vec<DomHandle>,
-) -> (bool, Vec<ConnectedLoadNetworkResult>) {
- let graph =
- fetch_complete_stylesheet_import_graph(stylesheet_fetcher, document_url.clone(), urls)
- .await;
- let (successful, network_results) = graph.into_parts();
- let network_results = network_results
- .into_iter()
- .map(|result| {
- let (request_url, start_unix_millis, terminal) = result.into_parts();
- let origin_clean = terminal.origin_clean().unwrap_or(false);
- let result = terminal.physical().as_result();
- ConnectedLoadNetworkResult {
- stylesheet_fetch: None,
- blocking_operation: None,
- source_operation: None,
- import_roots: Vec::new(),
- document_url: document_url.clone(),
- request_url,
- source_owners: source_owners.clone(),
- resource_type: SubresourceResourceType::Stylesheet,
- start_unix_millis: Some(start_unix_millis),
- origin_clean,
- result,
- }
- })
- .collect();
- (successful, network_results)
-}
-
impl DocumentRuntime {
pub(crate) fn prepare_initial_connected_style_loads(
&mut self,
@@ -529,7 +415,7 @@ impl DocumentRuntime {
inline_source: Option<Arc<crate::style_engine::OwnerStyleSheetSource>>,
event_admission: ConnectedStyleLoadEventAdmission,
host_ptr: *mut JsContextHost,
- ) {
+ ) -> ConnectedStyleLoadPrimeResult {
assert!(
event_admission.matches_plan(prepared.event_plan),
"connected-style commit must match its synchronously prepared plan"
@@ -547,17 +433,10 @@ impl DocumentRuntime {
false,
event_admission.load_event_binding(),
);
- return;
+ return ConnectedStyleLoadPrimeResult::default();
}
let inline_source = inline_source.or_else(|| self.inline_style_source_for_test(handle));
- let prime_result = self.enqueue_connected_style_load(
- handle,
- inline_source,
- host_ptr,
- Some(event_admission),
- );
- self.pending_connected_style_load_prime_result
- .extend(prime_result);
+ self.enqueue_connected_style_load(handle, inline_source, host_ptr, Some(event_admission))
}
#[cfg(test)]
@@ -565,6 +444,7 @@ impl DocumentRuntime {
&mut self,
prepared: Vec<PreparedConnectedStyleLoad>,
) {
+ let mut result = ConnectedStyleLoadPrimeResult::default();
for prepared in prepared {
let plan = prepared.event_plan();
let admission = match plan {
@@ -583,13 +463,15 @@ impl DocumentRuntime {
)
}
};
- self.apply_prepared_connected_style_load(
+ result.extend(self.apply_prepared_connected_style_load(
prepared,
None,
admission,
std::ptr::null_mut(),
- );
+ ));
}
+ self.pending_connected_style_load_prime_result
+ .extend(result);
}
fn parser_created_style_load_waits_for_initial_scan(&self, handle: DomHandle) -> bool {
@@ -895,8 +777,8 @@ impl DocumentRuntime {
disposition.url().clone(),
disposition.options().clone(),
);
- let import_completion_successful =
- initial_stylesheet_import_completion_successful(disposition.url(), &fetch);
+ let import_completion =
+ self.initial_stylesheet_import_completion(disposition.url(), &fetch);
let existing_load = self
.stylesheet_lifecycle
.owner_states
@@ -927,14 +809,16 @@ impl DocumentRuntime {
);
self.install_stylesheet_link_state(
handle,
- LinkStyleState::new(Arc::clone(&load), import_completion_successful),
+ LinkStyleState::new(Arc::clone(&load), import_completion),
);
load
};
// `adopt_or_begin_link_load` may attach this owner to a fetch that
// completed for an earlier link. Such an admission has no future
// network terminal, so deliver only this exact client now.
- self.promote_stylesheet_link_client_if_ready(Arc::clone(&load));
+ if let Some(client) = self.promote_stylesheet_link_client_if_ready(Arc::clone(&load)) {
+ result.push_completed_stylesheet_client(client);
+ }
// Network and data responses are processed through the same exact
// stylesheet terminal. That boundary owns import discovery and
// starts the shared dependency graph once per physical fetch.
@@ -1066,9 +950,11 @@ impl DocumentRuntime {
);
self.install_stylesheet_link_state(
handle,
- LinkStyleState::new(Arc::clone(&load), Some(true)),
+ LinkStyleState::new(Arc::clone(&load), StylesheetCompletionState::Succeeded),
);
- self.promote_stylesheet_link_client_if_ready(load);
+ if let Some(client) = self.promote_stylesheet_link_client_if_ready(load) {
+ result.push_completed_stylesheet_client(client);
+ }
return result;
}
let fetch_options = element
@@ -1197,14 +1083,14 @@ impl DocumentRuntime {
};
if !urls.is_empty() {
self.prime_connected_style_import_loads(
- ConnectedStyleImportSource::Inline(source),
+ InlineStyleImportSource::new(source),
urls,
load_event_binding,
host_ptr,
);
return result;
}
- let source = ConnectedStyleImportSource::Inline(source);
+ let source = InlineStyleImportSource::new(source);
let roots = self.connected_style_import_roots(&source, host_ptr);
let operation = ConnectedLoadOperation::new_with_load_event_binding(
handle,
@@ -1254,13 +1140,12 @@ impl DocumentRuntime {
fn prime_connected_style_import_loads(
&mut self,
- source: ConnectedStyleImportSource,
+ source: InlineStyleImportSource,
urls: Vec<Url>,
load_event_binding: Option<MainDocumentStyleLoadEventBinding>,
host_ptr: *mut JsContextHost,
) {
let handle = source.owner();
- let element_kind = source.element_kind();
let roots = self.connected_style_import_roots(&source, host_ptr);
let urls = match connected_style_import_readiness(urls.clone()) {
ConnectedStyleImportReadiness::Ready(mut successful) => {
@@ -1278,10 +1163,9 @@ impl DocumentRuntime {
}
}
}
- let event_pending = matches!(&source, ConnectedStyleImportSource::Inline(_));
let operation = ConnectedLoadOperation::new_with_load_event_binding(
handle,
- element_kind,
+ ConnectedStyleEventElementKind::Style,
ConnectedLoadParameters::StyleImports {
source,
urls,
@@ -1293,11 +1177,10 @@ impl DocumentRuntime {
self.stylesheet_lifecycle
.owner_states
.install_pending_operation(Arc::clone(&operation));
- let _ = self.stylesheet_lifecycle.owner_states.accept_completion(
- &operation,
- 0,
- event_pending,
- );
+ let _ = self
+ .stylesheet_lifecycle
+ .owner_states
+ .accept_completion(&operation, 0, true);
self.note_connected_style_import_completion(&operation, successful);
return;
}
@@ -1326,7 +1209,7 @@ impl DocumentRuntime {
}
let operation = ConnectedLoadOperation::new_with_load_event_binding(
handle,
- element_kind,
+ ConnectedStyleEventElementKind::Style,
parameters,
blocking_operation,
load_event_binding,
@@ -1354,7 +1237,7 @@ impl DocumentRuntime {
.current_document_resource_loader()
.expect("connected stylesheet import requires its Document authority");
resource_loader.spawn_resource_task(async move {
- let (successful, network_results) = fetch_connected_style_import_graph(
+ let (graph, network_results) = fetch_observed_stylesheet_import_graph(
stylesheet_fetcher,
document_url,
urls,
@@ -1363,7 +1246,7 @@ impl DocumentRuntime {
.await;
let completion = ConnectedLoadCompletion {
operation,
- successful,
+ successful: graph.successful(),
network_results,
};
let _ = task_producer.send_connected_completion(completion);
@@ -1372,56 +1255,20 @@ impl DocumentRuntime {
fn connected_style_import_roots(
&self,
- source: &ConnectedStyleImportSource,
+ source: &InlineStyleImportSource,
host_ptr: *mut JsContextHost,
) -> Vec<ConnectedStyleImportRoot> {
if host_ptr.is_null() {
return Vec::new();
}
- let owners = match source {
- ConnectedStyleImportSource::Inline(source) => vec![source.owner()],
- ConnectedStyleImportSource::Linked(load) => self
- .stylesheet_lifecycle
- .owner_states
- .link_states()
- .filter(|(_, state)| state.active_load().fetch().ptr_eq(load.fetch()))
- .map(|(owner, _)| owner)
- .collect(),
- };
- owners
+ let owner = source.owner();
+ unsafe { &*host_ptr }
+ .owner_live_stylesheet(owner)
+ .map(|stylesheet| ConnectedStyleImportRoot::new(owner, &stylesheet, false))
.into_iter()
- .filter_map(|owner| {
- let stylesheet = match source {
- ConnectedStyleImportSource::Inline(_) => {
- unsafe { &*host_ptr }.owner_live_stylesheet(owner)
- }
- ConnectedStyleImportSource::Linked(_) => {
- unsafe { &*host_ptr }.linked_live_stylesheet(owner)
- }
- }?;
- Some(ConnectedStyleImportRoot::new(
- owner,
- &stylesheet,
- matches!(source, ConnectedStyleImportSource::Linked(_)),
- ))
- })
.collect()
}
- pub(crate) fn prime_network_stylesheet_import_loads(
- &mut self,
- load: Arc<StylesheetLinkClient>,
- urls: Vec<Url>,
- host_ptr: *mut JsContextHost,
- ) {
- self.prime_connected_style_import_loads(
- ConnectedStyleImportSource::Linked(load),
- urls,
- None,
- host_ptr,
- );
- }
-
fn prime_live_stylesheet_import_loads(
&mut self,
owner: DomHandle,
@@ -1467,7 +1314,7 @@ impl DocumentRuntime {
.current_document_resource_loader()
.expect("live stylesheet import requires its Document authority");
resource_loader.spawn_resource_task(async move {
- let (_, mut network_results) = fetch_connected_style_import_graph(
+ let (_, mut network_results) = fetch_observed_stylesheet_import_graph(
stylesheet_fetcher,
document_url,
urls,
@@ -1495,158 +1342,6 @@ impl DocumentRuntime {
self.prime_document_lifecycle_processing_for_owner(std::ptr::null_mut())
}
- pub(crate) fn reconcile_connected_style_imports_with_blocking_stylesheets(&mut self) {
- let pending_imports = self
- .stylesheet_lifecycle
- .owner_states
- .pending_operations()
- .into_iter()
- .filter_map(|operation| match &operation.parameters {
- ConnectedLoadParameters::StyleImports { .. }
- if operation.blocking_operation.is_some() =>
- {
- Some(operation)
- }
- ConnectedLoadParameters::ImmediateOwnerProcessing => None,
- ConnectedLoadParameters::PreloadLikeLink { .. } => None,
- ConnectedLoadParameters::StyleImports { .. } => None,
- })
- .collect::<Vec<_>>();
- for operation in pending_imports {
- if self.connected_style_import_uses_blocking_stylesheet(&operation) {
- continue;
- }
- let handle = operation.owner;
- if self
- .stylesheet_lifecycle
- .owner_states
- .pending_operation(handle)
- .is_none_or(|pending| !ConnectedLoadOperation::ptr_eq(pending, &operation))
- {
- continue;
- }
- self.stylesheet_lifecycle
- .owner_states
- .clear_connected_operation(handle);
- let inline_source = match &operation.parameters {
- ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Inline(source),
- ..
- } => Some(Arc::clone(source)),
- ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Linked(_),
- ..
- }
- | ConnectedLoadParameters::ImmediateOwnerProcessing
- | ConnectedLoadParameters::PreloadLikeLink { .. } => None,
- };
- self.stylesheet_lifecycle.pending_connected_loads.push_back(
- QueuedConnectedStyleLoad::new(
- handle,
- inline_source,
- operation
- .load_event_binding()
- .map(ConnectedStyleLoadEventAdmission::LoadDelaying),
- ),
- );
- }
- }
-
- fn connected_style_import_uses_blocking_stylesheet(
- &self,
- operation: &Arc<ConnectedLoadOperation>,
- ) -> bool {
- let ConnectedLoadParameters::StyleImports { urls, .. } = &operation.parameters else {
- return false;
- };
- let Some(blocking_operation) = &operation.blocking_operation else {
- return false;
- };
- debug_assert_eq!(
- blocking_operation.signature(),
- &DocumentBlockingStylesheetSignature::ParserCreatedStyleImport {
- urls: urls.to_vec(),
- }
- );
- self.stylesheet_lifecycle
- .fetches
- .status_for_blocking_operation(blocking_operation)
- .is_some()
- }
-
- pub(crate) fn take_ready_blocking_style_import_graphs(
- &mut self,
- ) -> Vec<ReadyBlockingStyleImportGraph> {
- let pending_imports = self
- .stylesheet_lifecycle
- .owner_states
- .pending_operations()
- .into_iter()
- .filter(|operation| {
- matches!(
- &operation.parameters,
- ConnectedLoadParameters::StyleImports { .. }
- ) && operation.blocking_operation.is_some()
- })
- .collect::<Vec<_>>();
- let mut ready = Vec::new();
- for operation in pending_imports {
- let Some(blocking_operation) = operation.blocking_operation.as_ref() else {
- continue;
- };
- let Some(status) = self
- .stylesheet_lifecycle
- .fetches
- .status_for_blocking_operation(blocking_operation)
- else {
- continue;
- };
- if status == StylesheetBlockingStatus::Pending {
- continue;
- }
- let roots = match &operation.parameters {
- ConnectedLoadParameters::StyleImports { roots, .. } => roots.clone(),
- _ => continue,
- };
- if roots.is_empty() {
- continue;
- }
- let Some(graph) = self
- .stylesheet_lifecycle
- .fetches
- .take_completed_import_graph_for_blocking_operation(blocking_operation)
- else {
- continue;
- };
- let successful = status == StylesheetBlockingStatus::Ready && graph.successful();
- ready.push(ReadyBlockingStyleImportGraph::new(
- operation, roots, graph, successful,
- ));
- }
- ready
- }
-
- pub(crate) fn complete_ready_blocking_style_import_graph(
- &mut self,
- operation: &Arc<ConnectedLoadOperation>,
- successful: bool,
- ) {
- let event_pending = matches!(
- &operation.parameters,
- ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Inline(_),
- ..
- }
- );
- if self
- .stylesheet_lifecycle
- .owner_states
- .accept_completion(operation, 0, event_pending)
- {
- self.note_connected_style_import_completion(operation, successful);
- }
- }
-
pub(crate) fn prepare_stylesheet_owner_runtime_changes(
&mut self,
changes: &[crate::dom::native::DomStylesheetOwnerChange],
@@ -2247,89 +1942,6 @@ fn link_rel_is_standalone_prefetch(rel: &str) -> bool {
&& !link_rel_includes_token(rel, "modulepreload")
}
-pub(super) fn initial_stylesheet_import_completion_successful(
- stylesheet_url: &Url,
- fetch: &crate::stylesheet_blocking::StylesheetFetch,
-) -> Option<bool> {
- if stylesheet_url.scheme() != "data" {
- // A network stylesheet's import graph is not known until its response
- // body has been parsed. Keep the link pending so parser-blocking scripts
- // and the load event wait for every imported sheet, as Blink does.
- return fetch.import_graph_terminal();
- }
- match data_stylesheet_import_readiness(stylesheet_url) {
- DataStylesheetImportReadiness::NoImports => Some(true),
- DataStylesheetImportReadiness::Imports(_) => None,
- DataStylesheetImportReadiness::Failed => Some(false),
- }
-}
-
-fn data_stylesheet_import_readiness(stylesheet_url: &Url) -> DataStylesheetImportReadiness {
- if stylesheet_url.scheme() != "data" {
- return DataStylesheetImportReadiness::NoImports;
- }
- if stylesheet_url.as_str().len() > MAX_DATA_STYLESHEET_IMPORT_URL_BYTES {
- return DataStylesheetImportReadiness::Failed;
- }
- let Some((body, mime_type)) = data_url_body_and_mime_type(stylesheet_url.as_str()) else {
- return DataStylesheetImportReadiness::Failed;
- };
- // Chromium treats a data: URL selected by a stylesheet request as CSS even
- // when its media type is omitted or is not text/css. HTTP response MIME
- // enforcement belongs to the network stylesheet response validator and
- // must not be reused for this local-scheme path.
- let css_text = decode_text_for_legacy_web(&body, mime_charset(&mime_type).as_deref());
- let Ok(urls) =
- crate::style_engine::stylesheet_top_level_import_urls(&css_text, stylesheet_url, true)
- else {
- return DataStylesheetImportReadiness::Failed;
- };
- if urls.is_empty() {
- DataStylesheetImportReadiness::NoImports
- } else {
- DataStylesheetImportReadiness::Imports(urls)
- }
-}
-
-fn connected_style_import_readiness(urls: Vec<Url>) -> ConnectedStyleImportReadiness {
- let mut pending = Vec::new();
- let mut stack = std::collections::VecDeque::from(urls);
- let mut seen = std::collections::HashSet::new();
- let mut data_expansions = 0;
- while let Some(url) = stack.pop_front() {
- if !seen.insert(import_url_identity(&url)) {
- continue;
- }
- if url.scheme() != "data" {
- pending.push(url);
- continue;
- }
- if url.as_str().len() > MAX_DATA_STYLESHEET_IMPORT_URL_BYTES {
- return ConnectedStyleImportReadiness::Ready(false);
- }
- data_expansions += 1;
- if data_expansions > MAX_DATA_STYLESHEET_IMPORT_EXPANSIONS {
- return ConnectedStyleImportReadiness::Ready(false);
- }
- match data_stylesheet_import_readiness(&url) {
- DataStylesheetImportReadiness::NoImports => {}
- DataStylesheetImportReadiness::Failed => {
- return ConnectedStyleImportReadiness::Ready(false);
- }
- DataStylesheetImportReadiness::Imports(imports) => {
- for import in imports.into_iter().rev() {
- stack.push_front(import);
- }
- }
- }
- }
- if pending.is_empty() {
- ConnectedStyleImportReadiness::Ready(true)
- } else {
- ConnectedStyleImportReadiness::Pending(pending)
- }
-}
-
fn preload_like_link_request_resource_type(
element: &crate::dom::native::Element,
resource_type: SubresourceResourceType,
@@ -2624,6 +2236,9 @@ async fn fetch_connected_link_readiness_with_request(
#[cfg(test)]
mod tests {
+ use super::super::import_graph::{
+ DataStylesheetImportReadiness, data_stylesheet_import_readiness,
+ };
use super::*;
use crate::module_runtime::{
ModuleAttributesKey, ModuleLoadError, ModuleLoadStage, ModuleMapFetchDisposition,
@@ -2746,9 +2361,17 @@ mod tests {
runtime: &mut DocumentRuntime,
owner: DomHandle,
) -> ReadyConnectedStyleLoad {
- let (starts, warnings) = runtime.prime_pending_connected_style_loads().into_parts();
+ let (starts, warnings, completed_clients) = runtime
+ .prime_pending_connected_style_loads()
+ .into_parts_with_completed_stylesheet_clients();
assert!(starts.is_empty(), "stylesheet must not start module work");
assert!(warnings.is_empty(), "stylesheet warnings: {warnings:?}");
+ assert!(
+ completed_clients
+ .iter()
+ .all(|client| client.load().owner() == owner),
+ "a completed admission must belong to the exact requested owner"
+ );
runtime.drain_ready_connected_style_load_completions();
if let Some(ready) = runtime.pop_ready_connected_style_load() {
@@ -3568,71 +3191,6 @@ mod tests {
);
}
- #[test]
- fn data_stylesheet_import_readiness_tracks_top_level_imports() {
- let stylesheet_url =
- Url::parse("data:/,@import url('https://example.test/imported.css');").unwrap();
-
- assert_eq!(
- data_stylesheet_import_readiness(&stylesheet_url),
- DataStylesheetImportReadiness::Imports(vec![
- Url::parse("https://example.test/imported.css").unwrap()
- ])
- );
- }
-
- #[test]
- fn connected_style_import_readiness_preserves_external_import_order() {
- let first = Url::parse("https://example.test/first.css").unwrap();
- let second = Url::parse("https://example.test/second.css").unwrap();
-
- let ConnectedStyleImportReadiness::Pending(pending) =
- connected_style_import_readiness(vec![first.clone(), second.clone()])
- else {
- panic!("external imports must remain pending");
- };
-
- assert_eq!(pending, vec![first, second]);
- }
-
- #[test]
- fn connected_style_import_readiness_deduplicates_url_fragments() {
- let first = Url::parse("https://example.test/shared.css#first").unwrap();
- let duplicate = Url::parse("https://example.test/shared.css#second").unwrap();
-
- let ConnectedStyleImportReadiness::Pending(pending) =
- connected_style_import_readiness(vec![first.clone(), duplicate])
- else {
- panic!("external import must remain pending");
- };
-
- assert_eq!(pending, vec![first]);
- }
-
- #[test]
- fn network_style_import_graph_deduplicates_fragments_before_fetch() {
- let first = Url::parse("https://example.test/shared.css#first").unwrap();
- let duplicate = Url::parse("https://example.test/shared.css#second").unwrap();
- let second = Url::parse("https://example.test/second.css").unwrap();
- let mut graph = ConnectedNetworkStyleImportGraph::default();
-
- graph.extend([first.clone(), duplicate, second.clone()]);
- assert_eq!(graph.take_pending(), vec![first, second]);
- assert!(graph.is_empty());
- }
-
- #[test]
- fn network_style_import_graph_leaves_admission_to_resource_scheduler() {
- let urls = (0..1_100)
- .map(|index| Url::parse(&format!("https://example.test/import-{index}.css")).unwrap());
- let mut graph = ConnectedNetworkStyleImportGraph::default();
-
- graph.extend(urls);
-
- assert_eq!(graph.take_pending().len(), 1_100);
- assert!(graph.is_empty());
- }
-
#[test]
fn processed_inline_source_deduplicates_imports_in_document_order() {
let parser = HtmlParser;
@@ -3680,7 +3238,7 @@ mod tests {
style,
ConnectedStyleEventElementKind::Style,
ConnectedLoadParameters::StyleImports {
- source: ConnectedStyleImportSource::Inline(source),
+ source: InlineStyleImportSource::new(source),
urls: vec![Url::parse("https://example.test/runtime.css").unwrap()],
roots: Vec::new(),
},
@@ -4426,9 +3984,11 @@ mod tests {
assert!(runtime.apply_next_stylesheet_networking_task_for_test());
assert!(speculative.terminal().is_some());
- runtime.note_discovered_document_owned_blocking_stylesheet_inputs(
+ let completed_clients = runtime.note_discovered_document_owned_blocking_stylesheet_inputs(
blocking_stylesheet_inputs.iter(),
);
+ assert_eq!(completed_clients.len(), 1);
+ assert_eq!(completed_clients[0].load().owner(), link);
let parser_client = runtime
.active_stylesheet_link_client_for_test(link)
.expect("parser discovery should bind the exact owner client");
@@ -4483,9 +4043,6 @@ mod tests {
let first_physical = runtime.take_ready_stylesheet_network_results();
assert_eq!(first_physical.len(), 1);
assert!(first_physical[0].source_owners.is_empty());
- let first_client = runtime.take_ready_stylesheet_link_client_terminals();
- assert_eq!(first_client.len(), 1);
- assert_eq!(first_client[0].load().owner(), first_link);
let head = runtime
.dom_host()
@@ -4505,9 +4062,13 @@ mod tests {
assert!(runtime.dom_host_mut().append_child(head, second_link));
runtime.queue_connected_style_loads(second_link);
- let (starts, warnings) = runtime.prime_pending_connected_style_loads().into_parts();
+ let (starts, warnings, completed_clients) = runtime
+ .prime_pending_connected_style_loads()
+ .into_parts_with_completed_stylesheet_clients();
assert!(starts.is_empty(), "stylesheet must not start module work");
assert!(warnings.is_empty(), "stylesheet warnings: {warnings:?}");
+ assert_eq!(completed_clients.len(), 1);
+ assert_eq!(completed_clients[0].load().owner(), second_link);
let second_ready = runtime
.pop_ready_connected_style_load()
@@ -4518,9 +4079,16 @@ mod tests {
runtime.take_ready_stylesheet_network_results().is_empty(),
"late compatible client admission must not publish another physical terminal"
);
- let second_client = runtime.take_ready_stylesheet_link_client_terminals();
- assert_eq!(second_client.len(), 1);
- assert_eq!(second_client[0].load().owner(), second_link);
+ let selected_physical_client = runtime.take_ready_stylesheet_link_client_terminals();
+ assert_eq!(selected_physical_client.len(), 1);
+ assert_eq!(selected_physical_client[0].load().owner(), first_link);
+ let (_, _, repeated_clients) = runtime
+ .prime_pending_connected_style_loads()
+ .into_parts_with_completed_stylesheet_clients();
+ assert!(
+ repeated_clients.is_empty(),
+ "repeated lifecycle priming must not settle one client twice"
+ );
assert!(
!runtime.apply_ready_stylesheet_networking_tasks_for_test(),
"cached admission must not require a second network terminal"
@@ -4576,9 +4144,11 @@ mod tests {
.is_some_and(|terminal| !terminal.is_ready())
);
- runtime.note_discovered_document_owned_blocking_stylesheet_inputs(
+ let completed_clients = runtime.note_discovered_document_owned_blocking_stylesheet_inputs(
blocking_stylesheet_inputs.iter(),
);
+ assert_eq!(completed_clients.len(), 1);
+ assert_eq!(completed_clients[0].load().owner(), link);
let signatures = blocking_stylesheet_inputs
.iter()
.map(|input| input.signature().clone())
@@ -4711,7 +4281,12 @@ mod tests {
// import graph. This low-level fixture has no ScriptVm, so publish the
// known-empty graph explicitly before asserting the install client's
// load event.
- runtime.note_stylesheet_import_graph_completion(stylesheet_client.fetch(), true);
+ runtime.note_stylesheet_import_graph_completion(
+ stylesheet_client.fetch(),
+ Arc::new(
+ crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(true, Vec::new()),
+ ),
+ );
let mut ready_owners = Vec::new();
while let Some(ready) = runtime.pop_ready_connected_style_load() {
assert!(ready.successful());
@@ -4729,7 +4304,7 @@ mod tests {
}
#[tokio::test]
- async fn completed_style_preload_replays_to_late_stylesheet_install_client() {
+ async fn completed_style_preload_admits_late_stylesheet_install_client() {
let href = "data:text/css,.late%7Bcolor%3Agreen%7D";
let parser = HtmlParser;
let document = parser.parse(
@@ -4768,7 +4343,9 @@ mod tests {
);
assert!(runtime.dom_host_mut().append_child(head, stylesheet));
runtime.queue_connected_style_loads(stylesheet);
- runtime.prime_pending_connected_style_loads();
+ let (_, _, completed_clients) = runtime
+ .prime_pending_connected_style_loads()
+ .into_parts_with_completed_stylesheet_clients();
let stylesheet_client = runtime
.active_stylesheet_link_client_for_test(stylesheet)
@@ -4781,17 +4358,16 @@ mod tests {
assert_eq!(ready.owner(), stylesheet);
assert!(ready.successful());
assert!(runtime.take_ready_stylesheet_network_results().is_empty());
- let terminals = runtime.take_ready_stylesheet_link_client_terminals();
- assert_eq!(terminals.len(), 1);
- assert!(terminals[0].load().installs_stylesheet());
+ assert_eq!(completed_clients.len(), 1);
+ assert!(completed_clients[0].load().installs_stylesheet());
assert!(
!runtime.apply_ready_stylesheet_networking_tasks_for_test(),
- "terminal replay must not create another physical task"
+ "completed-client admission must not create another physical task"
);
}
#[tokio::test]
- async fn completed_stylesheet_replays_to_late_preload_event_only_client() {
+ async fn completed_stylesheet_admits_late_preload_event_only_client() {
let href = "data:text/css,.first%7Bcolor%3Agreen%7D";
let parser = HtmlParser;
let document = parser.parse(
@@ -4828,7 +4404,9 @@ mod tests {
assert!(runtime.dom_host_mut().set_attribute(preload, "href", href));
assert!(runtime.dom_host_mut().append_child(head, preload));
runtime.queue_connected_style_loads(preload);
- runtime.prime_pending_connected_style_loads();
+ let (_, _, completed_clients) = runtime
+ .prime_pending_connected_style_loads()
+ .into_parts_with_completed_stylesheet_clients();
let preload_client = runtime
.active_stylesheet_link_client_for_test(preload)
@@ -4841,9 +4419,8 @@ mod tests {
assert_eq!(ready.owner(), preload);
assert!(ready.successful());
assert!(runtime.take_ready_stylesheet_network_results().is_empty());
- let terminals = runtime.take_ready_stylesheet_link_client_terminals();
- assert_eq!(terminals.len(), 1);
- assert!(!terminals[0].load().installs_stylesheet());
+ assert_eq!(completed_clients.len(), 1);
+ assert!(!completed_clients[0].load().installs_stylesheet());
}
#[test]
diff --git a/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs
new file mode 100644
index 000000000..826a43069
--- /dev/null
+++ b/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs
@@ -0,0 +1,260 @@
+//! Fetching and readiness classification for stylesheet import graphs.
+//!
+//! This module has no owner lifecycle. It produces one immutable graph result;
+//! linked and inline stylesheet code decide separately where that result may be
+//! installed.
+
+use super::*;
+use crate::live_stylesheet::import_url_identity;
+use crate::stylesheet_blocking::{StylesheetFetchOptions, StylesheetFetcher};
+use futures_util::future::join_all;
+use moli_encoding::decode_text_for_legacy_web;
+use moli_web_mime::{data_url_body_and_mime_type, mime_charset};
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(in crate::document_runtime) enum DataStylesheetImportReadiness {
+ NoImports,
+ Imports(Vec<Url>),
+ Failed,
+}
+
+pub(in crate::document_runtime) enum ConnectedStyleImportReadiness {
+ Ready(bool),
+ Pending(Vec<Url>),
+}
+
+const MAX_DATA_STYLESHEET_IMPORT_EXPANSIONS: usize = 16;
+const MAX_DATA_STYLESHEET_IMPORT_URL_BYTES: usize = 16 * 1024;
+
+#[derive(Default)]
+struct ConnectedNetworkStyleImportGraph {
+ pending_urls: VecDeque<Url>,
+ admitted_identities: HashSet<Url>,
+}
+
+impl ConnectedNetworkStyleImportGraph {
+ fn extend(&mut self, urls: impl IntoIterator<Item = Url>) {
+ for url in urls {
+ let identity = import_url_identity(&url);
+ if self.admitted_identities.contains(&identity) {
+ continue;
+ }
+ self.admitted_identities.insert(identity);
+ self.pending_urls.push_back(url);
+ }
+ }
+
+ fn is_empty(&self) -> bool {
+ self.pending_urls.is_empty()
+ }
+
+ fn take_pending(&mut self) -> Vec<Url> {
+ self.pending_urls.drain(..).collect()
+ }
+}
+
+pub(crate) async fn fetch_complete_stylesheet_import_graph(
+ stylesheet_fetcher: crate::stylesheet_blocking::RendererStylesheetFetcher,
+ document_url: Url,
+ urls: Vec<Url>,
+) -> crate::stylesheet_blocking::StylesheetImportGraphFetchResult {
+ let (mut successful, urls) = match connected_style_import_readiness(urls) {
+ ConnectedStyleImportReadiness::Ready(successful) => {
+ return crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(
+ successful,
+ Vec::new(),
+ );
+ }
+ ConnectedStyleImportReadiness::Pending(urls) => (true, urls),
+ };
+ let mut network_results = Vec::new();
+ let mut import_graph = ConnectedNetworkStyleImportGraph::default();
+ import_graph.extend(urls);
+ while !import_graph.is_empty() {
+ let current_urls = import_graph.take_pending();
+ let pending_fetches = join_all(current_urls.into_iter().map(|url| {
+ let stylesheet_fetcher = stylesheet_fetcher.clone();
+ let fetch_document_url = document_url.clone();
+ let request_url = url.clone();
+ let start_unix_millis = moli_time::unix_epoch_millis();
+ async move {
+ let terminal = stylesheet_fetcher
+ .fetch_stylesheet_resource(
+ fetch_document_url,
+ request_url,
+ StylesheetFetchOptions::default(),
+ )
+ .await;
+ (url, start_unix_millis, terminal)
+ }
+ }))
+ .await;
+ for (url, start_unix_millis, terminal) in pending_fetches {
+ successful &= terminal.is_ready();
+ if let Some(response) = terminal.ready_response() {
+ let nested_urls = crate::style_engine::stylesheet_top_level_import_urls(
+ response.body_text(),
+ &response.final_url,
+ false,
+ )
+ .unwrap_or_default();
+ match connected_style_import_readiness(nested_urls) {
+ ConnectedStyleImportReadiness::Ready(nested_successful) => {
+ successful &= nested_successful;
+ }
+ ConnectedStyleImportReadiness::Pending(urls) => {
+ import_graph.extend(urls);
+ }
+ }
+ }
+ network_results.push(
+ crate::stylesheet_blocking::StylesheetImportNetworkResult::new(
+ url,
+ start_unix_millis,
+ terminal,
+ ),
+ );
+ }
+ }
+ crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(successful, network_results)
+}
+
+pub(in crate::document_runtime) fn data_stylesheet_import_readiness(
+ stylesheet_url: &Url,
+) -> DataStylesheetImportReadiness {
+ if stylesheet_url.scheme() != "data" {
+ return DataStylesheetImportReadiness::NoImports;
+ }
+ if stylesheet_url.as_str().len() > MAX_DATA_STYLESHEET_IMPORT_URL_BYTES {
+ return DataStylesheetImportReadiness::Failed;
+ }
+ let Some((body, mime_type)) = data_url_body_and_mime_type(stylesheet_url.as_str()) else {
+ return DataStylesheetImportReadiness::Failed;
+ };
+ // Chromium treats a data: URL selected by a stylesheet request as CSS even
+ // when its media type is omitted or is not text/css. HTTP response MIME
+ // enforcement belongs to the network stylesheet response validator and
+ // must not be reused for this local-scheme path.
+ let css_text = decode_text_for_legacy_web(&body, mime_charset(&mime_type).as_deref());
+ let Ok(urls) =
+ crate::style_engine::stylesheet_top_level_import_urls(&css_text, stylesheet_url, true)
+ else {
+ return DataStylesheetImportReadiness::Failed;
+ };
+ if urls.is_empty() {
+ DataStylesheetImportReadiness::NoImports
+ } else {
+ DataStylesheetImportReadiness::Imports(urls)
+ }
+}
+
+pub(in crate::document_runtime) fn connected_style_import_readiness(
+ urls: Vec<Url>,
+) -> ConnectedStyleImportReadiness {
+ let mut pending = Vec::new();
+ let mut stack = VecDeque::from(urls);
+ let mut seen = HashSet::new();
+ let mut data_expansions = 0;
+ while let Some(url) = stack.pop_front() {
+ if !seen.insert(import_url_identity(&url)) {
+ continue;
+ }
+ if url.scheme() != "data" {
+ pending.push(url);
+ continue;
+ }
+ if url.as_str().len() > MAX_DATA_STYLESHEET_IMPORT_URL_BYTES {
+ return ConnectedStyleImportReadiness::Ready(false);
+ }
+ data_expansions += 1;
+ if data_expansions > MAX_DATA_STYLESHEET_IMPORT_EXPANSIONS {
+ return ConnectedStyleImportReadiness::Ready(false);
+ }
+ match data_stylesheet_import_readiness(&url) {
+ DataStylesheetImportReadiness::NoImports => {}
+ DataStylesheetImportReadiness::Failed => {
+ return ConnectedStyleImportReadiness::Ready(false);
+ }
+ DataStylesheetImportReadiness::Imports(imports) => {
+ for import in imports.into_iter().rev() {
+ stack.push_front(import);
+ }
+ }
+ }
+ }
+ if pending.is_empty() {
+ ConnectedStyleImportReadiness::Ready(true)
+ } else {
+ ConnectedStyleImportReadiness::Pending(pending)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn data_stylesheet_import_readiness_tracks_top_level_imports() {
+ let stylesheet_url =
+ Url::parse("data:/,@import url('https://example.test/imported.css');").unwrap();
+
+ assert_eq!(
+ data_stylesheet_import_readiness(&stylesheet_url),
+ DataStylesheetImportReadiness::Imports(vec![
+ Url::parse("https://example.test/imported.css").unwrap()
+ ])
+ );
+ }
+
+ #[test]
+ fn connected_style_import_readiness_preserves_external_import_order() {
+ let first = Url::parse("https://example.test/first.css").unwrap();
+ let second = Url::parse("https://example.test/second.css").unwrap();
+
+ let ConnectedStyleImportReadiness::Pending(pending) =
+ connected_style_import_readiness(vec![first.clone(), second.clone()])
+ else {
+ panic!("external imports must remain pending");
+ };
+
+ assert_eq!(pending, vec![first, second]);
+ }
+
+ #[test]
+ fn connected_style_import_readiness_deduplicates_url_fragments() {
+ let first = Url::parse("https://example.test/shared.css#first").unwrap();
+ let duplicate = Url::parse("https://example.test/shared.css#second").unwrap();
+
+ let ConnectedStyleImportReadiness::Pending(pending) =
+ connected_style_import_readiness(vec![first.clone(), duplicate])
+ else {
+ panic!("external import must remain pending");
+ };
+
+ assert_eq!(pending, vec![first]);
+ }
+
+ #[test]
+ fn network_style_import_graph_deduplicates_fragments_before_fetch() {
+ let first = Url::parse("https://example.test/shared.css#first").unwrap();
+ let duplicate = Url::parse("https://example.test/shared.css#second").unwrap();
+ let second = Url::parse("https://example.test/second.css").unwrap();
+ let mut graph = ConnectedNetworkStyleImportGraph::default();
+
+ graph.extend([first.clone(), duplicate, second.clone()]);
+ assert_eq!(graph.take_pending(), vec![first, second]);
+ assert!(graph.is_empty());
+ }
+
+ #[test]
+ fn network_style_import_graph_leaves_admission_to_resource_scheduler() {
+ let urls = (0..1_100)
+ .map(|index| Url::parse(&format!("https://example.test/import-{index}.css")).unwrap());
+ let mut graph = ConnectedNetworkStyleImportGraph::default();
+
+ graph.extend(urls);
+
+ assert_eq!(graph.take_pending().len(), 1_100);
+ assert!(graph.is_empty());
+ }
+}
diff --git a/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs b/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs
new file mode 100644
index 000000000..dc989971a
--- /dev/null
+++ b/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs
@@ -0,0 +1,80 @@
+//! Renderer projections of an immutable stylesheet import graph result.
+//!
+//! Graph acquisition does not know about DOM owners. This module is the one
+//! boundary that decorates a terminal graph for network observation or turns
+//! it into the inputs consumed by the live CSSOM installer.
+
+use super::*;
+
+pub(in crate::document_runtime) async fn fetch_observed_stylesheet_import_graph(
+ stylesheet_fetcher: crate::stylesheet_blocking::RendererStylesheetFetcher,
+ document_url: Url,
+ urls: Vec<Url>,
+ source_owners: Vec<DomHandle>,
+) -> (
+ Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ Vec<ConnectedLoadNetworkResult>,
+) {
+ let graph = Arc::new(
+ super::import_graph::fetch_complete_stylesheet_import_graph(
+ stylesheet_fetcher,
+ document_url.clone(),
+ urls,
+ )
+ .await,
+ );
+ let network_results = graph
+ .network_results()
+ .iter()
+ .map(|result| {
+ let request_url = result.request_url().clone();
+ let start_unix_millis = result.start_unix_millis();
+ let terminal = result.terminal();
+ let origin_clean = terminal.origin_clean().unwrap_or(false);
+ let result = terminal.physical().as_result();
+ ConnectedLoadNetworkResult {
+ stylesheet_fetch: None,
+ blocking_operation: None,
+ source_operation: None,
+ import_roots: Vec::new(),
+ document_url: document_url.clone(),
+ request_url,
+ source_owners: source_owners.clone(),
+ resource_type: SubresourceResourceType::Stylesheet,
+ start_unix_millis: Some(start_unix_millis),
+ origin_clean,
+ result,
+ }
+ })
+ .collect();
+ (graph, network_results)
+}
+
+pub(crate) fn live_stylesheet_import_responses(
+ graph: &crate::stylesheet_blocking::StylesheetImportGraphFetchResult,
+) -> Vec<crate::live_stylesheet::LiveStylesheetImportResponse> {
+ graph
+ .network_results()
+ .iter()
+ .map(|result| {
+ let terminal = result.terminal();
+ let ready_response = terminal.ready_response();
+ crate::live_stylesheet::LiveStylesheetImportResponse {
+ request_url: result.request_url().clone(),
+ response_url: match terminal.physical() {
+ crate::stylesheet_blocking::StylesheetPhysicalOutcome::Response(response) => {
+ response.final_url.clone()
+ }
+ crate::stylesheet_blocking::StylesheetPhysicalOutcome::NetworkError(_) => {
+ result.request_url().clone()
+ }
+ },
+ css_text: ready_response
+ .map(|response| response.body_text().to_owned())
+ .unwrap_or_default(),
+ successful: ready_response.is_some(),
+ origin_clean: terminal.origin_clean().unwrap_or(false),
+ }
+ })
+ .collect()
+}
diff --git a/moli-renderer-v8/src/stylesheet_runtime/link_state.rs b/moli-renderer-v8/src/stylesheet_runtime/link_state.rs
index 945e8f282..a1539dfd8 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/link_state.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/link_state.rs
@@ -4,11 +4,51 @@ use crate::frame_owner_model::MainDocumentStyleLoadEventBinding;
use super::load::StylesheetLinkClient;
+/// Settlement state of one required phase of a linked stylesheet load.
+///
+/// `Pending` means only that the phase has not settled. A stylesheet with no
+/// imports therefore starts its import phase as `Succeeded`, not `Pending`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(in crate::document_runtime) enum StylesheetCompletionState {
+ Pending,
+ Succeeded,
+ Failed,
+}
+
+impl StylesheetCompletionState {
+ pub(super) fn from_successful(successful: bool) -> Self {
+ if successful {
+ Self::Succeeded
+ } else {
+ Self::Failed
+ }
+ }
+
+ fn followed_by(self, dependent: Self) -> Self {
+ // Imports exist only after a usable root resource. A root failure is
+ // therefore immediately terminal; import state matters only after the
+ // root succeeds.
+ match self {
+ Self::Pending => Self::Pending,
+ Self::Succeeded => dependent,
+ Self::Failed => Self::Failed,
+ }
+ }
+
+ fn settle(&mut self, successful: bool) -> bool {
+ if *self != Self::Pending {
+ return false;
+ }
+ *self = Self::from_successful(successful);
+ true
+ }
+}
+
#[derive(Debug)]
pub(in crate::document_runtime) struct LinkStyleState {
active_load: Arc<StylesheetLinkClient>,
- resource_completion_successful: Option<bool>,
- import_completion_successful: Option<bool>,
+ resource_completion: StylesheetCompletionState,
+ import_completion: StylesheetCompletionState,
event_phase: LinkLoadEventPhase,
}
@@ -22,12 +62,12 @@ enum LinkLoadEventPhase {
impl LinkStyleState {
pub(super) fn new(
active_load: Arc<StylesheetLinkClient>,
- import_completion_successful: Option<bool>,
+ import_completion: StylesheetCompletionState,
) -> Self {
Self {
active_load,
- resource_completion_successful: None,
- import_completion_successful,
+ resource_completion: StylesheetCompletionState::Pending,
+ import_completion,
event_phase: LinkLoadEventPhase::WaitingForCompletion,
}
}
@@ -37,7 +77,7 @@ impl LinkStyleState {
}
pub(super) fn is_pending(&self) -> bool {
- self.completion_successful().is_none()
+ self.completion() == StylesheetCompletionState::Pending
}
pub(super) fn cancelable_load_event_binding(
@@ -48,15 +88,19 @@ impl LinkStyleState {
.flatten()
}
- pub(super) fn completion_successful(&self) -> Option<bool> {
- Some(self.resource_completion_successful? && self.import_completion_successful?)
+ fn completion(&self) -> StylesheetCompletionState {
+ self.resource_completion.followed_by(self.import_completion)
}
pub(super) fn take_ready_event(&mut self) -> Option<(Arc<StylesheetLinkClient>, bool)> {
if self.event_phase != LinkLoadEventPhase::WaitingForCompletion {
return None;
}
- let successful = self.completion_successful()?;
+ let successful = match self.completion() {
+ StylesheetCompletionState::Pending => return None,
+ StylesheetCompletionState::Succeeded => true,
+ StylesheetCompletionState::Failed => false,
+ };
self.event_phase = LinkLoadEventPhase::Posted;
Some((Arc::clone(&self.active_load), successful))
}
@@ -80,20 +124,45 @@ impl LinkStyleState {
load: &Arc<StylesheetLinkClient>,
successful: bool,
) -> bool {
- if !StylesheetLinkClient::ptr_eq(&self.active_load, load)
- || self.resource_completion_successful.is_some()
- {
+ if !StylesheetLinkClient::ptr_eq(&self.active_load, load) {
return false;
}
- self.resource_completion_successful = Some(successful);
- true
+ self.resource_completion.settle(successful)
}
pub(super) fn accept_import_completion(&mut self, successful: bool) -> bool {
- if self.import_completion_successful.is_some() {
- return false;
+ self.import_completion.settle(successful)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::StylesheetCompletionState::{Failed, Pending, Succeeded};
+
+ #[test]
+ fn combined_completion_preserves_resource_then_import_dependency() {
+ let cases = [
+ ((Pending, Pending), Pending),
+ ((Pending, Succeeded), Pending),
+ ((Pending, Failed), Pending),
+ ((Succeeded, Pending), Pending),
+ ((Succeeded, Succeeded), Succeeded),
+ ((Succeeded, Failed), Failed),
+ ((Failed, Pending), Failed),
+ ((Failed, Succeeded), Failed),
+ ((Failed, Failed), Failed),
+ ];
+ for ((resource, imports), expected) in cases {
+ assert_eq!(resource.followed_by(imports), expected);
}
- self.import_completion_successful = Some(successful);
- true
+ }
+
+ #[test]
+ fn completion_state_settles_only_once() {
+ let mut completion = Pending;
+ assert!(completion.settle(true));
+ assert_eq!(completion, Succeeded);
+ assert!(!completion.settle(false));
+ assert_eq!(completion, Succeeded);
}
}
diff --git a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs
new file mode 100644
index 000000000..98d22c439
--- /dev/null
+++ b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs
@@ -0,0 +1,573 @@
+use super::*;
+
+#[derive(Debug)]
+pub(crate) struct LinkedStylesheetImportGraphCompletion {
+ pub(in crate::document_runtime) fetch: crate::stylesheet_blocking::StylesheetFetch,
+ pub(in crate::document_runtime) graph:
+ Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ pub(in crate::document_runtime) network_results: Vec<ConnectedLoadNetworkResult>,
+}
+
+/// Per-Document lifecycle for the import graph shared by one exact stylesheet
+/// fetch.
+///
+/// The physical stylesheet response is shared, but every linked owner keeps a
+/// distinct CSSOM root. Keeping the phase and roots in one entry prevents a
+/// one-shot network decision from accidentally suppressing per-owner install
+/// work.
+#[derive(Debug, Default)]
+pub(in crate::document_runtime) struct LinkedStylesheetImportGraphs {
+ entries:
+ HashMap<crate::stylesheet_blocking::StylesheetFetchIdentity, LinkedStylesheetImportGraph>,
+}
+
+#[derive(Debug)]
+struct LinkedStylesheetImportGraph {
+ /// Retains the allocation backing the pointer-derived map identity.
+ fetch: crate::stylesheet_blocking::StylesheetFetch,
+ roots: Vec<ConnectedStyleImportRoot>,
+ phase: LinkedStylesheetImportGraphPhase,
+}
+
+#[derive(Debug)]
+enum LinkedStylesheetImportGraphPhase {
+ NotStarted,
+ InFlight {
+ blocking: Option<LinkedStylesheetBlockingImportGraph>,
+ },
+ Completed(Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>),
+}
+
+#[derive(Debug)]
+struct LinkedStylesheetBlockingImportGraph {
+ operation: crate::stylesheet_blocking::StylesheetBlockingOperation,
+ urls: Vec<Url>,
+}
+
+pub(in crate::document_runtime) enum LinkedStylesheetImportGraphAdmission {
+ /// This admission owns the only dependent-resource start for the fetch.
+ Start,
+ /// Another owner already started the shared graph.
+ InFlight,
+ /// The graph is terminal and can be installed into the new owner now.
+ Completed(Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>),
+}
+
+impl LinkedStylesheetImportGraphs {
+ pub(super) fn admit(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ root: Option<ConnectedStyleImportRoot>,
+ ) -> LinkedStylesheetImportGraphAdmission {
+ let entry =
+ self.entries
+ .entry(fetch.identity())
+ .or_insert_with(|| LinkedStylesheetImportGraph {
+ fetch: fetch.clone(),
+ roots: Vec::new(),
+ phase: LinkedStylesheetImportGraphPhase::NotStarted,
+ });
+ debug_assert!(entry.fetch.ptr_eq(fetch));
+ if let Some(root) = root {
+ entry
+ .roots
+ .retain(|candidate| candidate.owner != root.owner);
+ entry.roots.push(root);
+ }
+ match &entry.phase {
+ LinkedStylesheetImportGraphPhase::NotStarted => {
+ entry.phase = LinkedStylesheetImportGraphPhase::InFlight { blocking: None };
+ LinkedStylesheetImportGraphAdmission::Start
+ }
+ LinkedStylesheetImportGraphPhase::InFlight { .. } => {
+ LinkedStylesheetImportGraphAdmission::InFlight
+ }
+ LinkedStylesheetImportGraphPhase::Completed(graph) => {
+ LinkedStylesheetImportGraphAdmission::Completed(Arc::clone(graph))
+ }
+ }
+ }
+
+ pub(super) fn complete(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ ) -> Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult> {
+ let entry =
+ self.entries
+ .entry(fetch.identity())
+ .or_insert_with(|| LinkedStylesheetImportGraph {
+ fetch: fetch.clone(),
+ roots: Vec::new(),
+ phase: LinkedStylesheetImportGraphPhase::InFlight { blocking: None },
+ });
+ debug_assert!(entry.fetch.ptr_eq(fetch));
+ if !matches!(entry.phase, LinkedStylesheetImportGraphPhase::Completed(_)) {
+ entry.phase = LinkedStylesheetImportGraphPhase::Completed(graph);
+ }
+ match &entry.phase {
+ LinkedStylesheetImportGraphPhase::Completed(graph) => Arc::clone(graph),
+ LinkedStylesheetImportGraphPhase::NotStarted
+ | LinkedStylesheetImportGraphPhase::InFlight { .. } => {
+ unreachable!("completing an import graph must retain its terminal")
+ }
+ }
+ }
+
+ pub(super) fn completion_state(
+ &self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ ) -> StylesheetCompletionState {
+ let Some(entry) = self.entry(fetch) else {
+ return StylesheetCompletionState::Pending;
+ };
+ match &entry.phase {
+ LinkedStylesheetImportGraphPhase::Completed(graph) => {
+ StylesheetCompletionState::from_successful(graph.successful())
+ }
+ LinkedStylesheetImportGraphPhase::NotStarted
+ | LinkedStylesheetImportGraphPhase::InFlight { .. } => {
+ StylesheetCompletionState::Pending
+ }
+ }
+ }
+
+ pub(super) fn bind_blocking_operation(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ operation: crate::stylesheet_blocking::StylesheetBlockingOperation,
+ urls: Vec<Url>,
+ ) {
+ let entry = self
+ .entries
+ .get_mut(&fetch.identity())
+ .filter(|entry| entry.fetch.ptr_eq(fetch))
+ .expect("a linked import graph must be admitted before its work is started");
+ let LinkedStylesheetImportGraphPhase::InFlight { blocking } = &mut entry.phase else {
+ unreachable!("only an in-flight linked import graph can bind blocking work")
+ };
+ debug_assert!(
+ blocking
+ .as_ref()
+ .is_none_or(|current| current.operation.ptr_eq(&operation))
+ );
+ *blocking = Some(LinkedStylesheetBlockingImportGraph { operation, urls });
+ }
+
+ pub(super) fn blocking_operations(
+ &self,
+ ) -> Vec<(
+ crate::stylesheet_blocking::StylesheetFetch,
+ crate::stylesheet_blocking::StylesheetBlockingOperation,
+ Vec<Url>,
+ )> {
+ self.entries
+ .values()
+ .filter_map(|entry| {
+ let LinkedStylesheetImportGraphPhase::InFlight {
+ blocking: Some(blocking),
+ } = &entry.phase
+ else {
+ return None;
+ };
+ Some((
+ entry.fetch.clone(),
+ blocking.operation.clone(),
+ blocking.urls.clone(),
+ ))
+ })
+ .collect()
+ }
+
+ pub(super) fn replace_blocking_with_async(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ operation: &crate::stylesheet_blocking::StylesheetBlockingOperation,
+ ) -> bool {
+ let Some(entry) = self
+ .entries
+ .get_mut(&fetch.identity())
+ .filter(|entry| entry.fetch.ptr_eq(fetch))
+ else {
+ return false;
+ };
+ let LinkedStylesheetImportGraphPhase::InFlight { blocking } = &mut entry.phase else {
+ return false;
+ };
+ if blocking
+ .as_ref()
+ .is_none_or(|current| !current.operation.ptr_eq(operation))
+ {
+ return false;
+ }
+ *blocking = None;
+ true
+ }
+
+ pub(super) fn roots(
+ &self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ ) -> Vec<ConnectedStyleImportRoot> {
+ self.entry(fetch)
+ .map(|entry| entry.roots.clone())
+ .unwrap_or_default()
+ }
+
+ pub(super) fn unregister_owner(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ owner: DomHandle,
+ ) {
+ let Some(entry) = self.entries.get_mut(&fetch.identity()) else {
+ return;
+ };
+ debug_assert!(entry.fetch.ptr_eq(fetch));
+ entry.roots.retain(|root| root.owner != owner);
+ }
+
+ fn entry(
+ &self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ ) -> Option<&LinkedStylesheetImportGraph> {
+ self.entries
+ .get(&fetch.identity())
+ .filter(|entry| entry.fetch.ptr_eq(fetch))
+ }
+}
+
+impl DocumentRuntime {
+ pub(super) fn admit_linked_stylesheet_import_graph(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ root: Option<ConnectedStyleImportRoot>,
+ ) -> LinkedStylesheetImportGraphAdmission {
+ self.stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .admit(fetch, root)
+ }
+
+ pub(super) fn linked_stylesheet_import_roots(
+ &self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ ) -> Vec<ConnectedStyleImportRoot> {
+ self.stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .roots(fetch)
+ }
+
+ pub(super) fn bind_linked_stylesheet_import_blocking_operation(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ operation: crate::stylesheet_blocking::StylesheetBlockingOperation,
+ urls: Vec<Url>,
+ ) {
+ self.stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .bind_blocking_operation(fetch, operation, urls);
+ }
+
+ pub(super) fn linked_stylesheet_import_blocking_operations(
+ &self,
+ ) -> Vec<(
+ crate::stylesheet_blocking::StylesheetFetch,
+ crate::stylesheet_blocking::StylesheetBlockingOperation,
+ Vec<Url>,
+ )> {
+ self.stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .blocking_operations()
+ }
+
+ pub(super) fn restart_invalidated_linked_stylesheet_import_blocking_operations(&mut self) {
+ let operations = self.linked_stylesheet_import_blocking_operations();
+ for (fetch, operation, urls) in operations {
+ if self
+ .stylesheet_lifecycle
+ .fetches
+ .status_for_blocking_operation(&operation)
+ .is_some()
+ {
+ continue;
+ }
+ if !self
+ .stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .replace_blocking_with_async(&fetch, &operation)
+ {
+ continue;
+ }
+ self.spawn_linked_stylesheet_import_graph(fetch, urls);
+ }
+ }
+
+ pub(super) fn unregister_linked_stylesheet_import_consumer(
+ &mut self,
+ load: &Arc<StylesheetLinkClient>,
+ ) {
+ self.stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .unregister_owner(load.fetch(), load.owner());
+ }
+
+ pub(super) fn initial_stylesheet_import_completion(
+ &self,
+ stylesheet_url: &Url,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ ) -> StylesheetCompletionState {
+ let graph_completion = self
+ .stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .completion_state(fetch);
+ if graph_completion != StylesheetCompletionState::Pending {
+ return graph_completion;
+ }
+ if stylesheet_url.scheme() != "data" {
+ return StylesheetCompletionState::Pending;
+ }
+ match super::import_graph::data_stylesheet_import_readiness(stylesheet_url) {
+ super::import_graph::DataStylesheetImportReadiness::NoImports => {
+ StylesheetCompletionState::Succeeded
+ }
+ super::import_graph::DataStylesheetImportReadiness::Imports(_) => {
+ StylesheetCompletionState::Pending
+ }
+ super::import_graph::DataStylesheetImportReadiness::Failed => {
+ StylesheetCompletionState::Failed
+ }
+ }
+ }
+
+ pub(crate) fn prime_network_stylesheet_import_loads(
+ &mut self,
+ load: Arc<StylesheetLinkClient>,
+ urls: Vec<Url>,
+ host_ptr: *mut JsContextHost,
+ ) {
+ let fetch = load.fetch().clone();
+ let roots = self.linked_stylesheet_import_roots(&fetch);
+ let urls = match super::import_graph::connected_style_import_readiness(urls.clone()) {
+ super::import_graph::ConnectedStyleImportReadiness::Ready(graph_successful) => {
+ if !host_ptr.is_null() {
+ for root in &roots {
+ if unsafe { &*host_ptr }
+ .install_live_stylesheet_import_graph(root.clone(), &[])
+ .is_some()
+ {
+ let _ = unsafe { &mut *host_ptr }
+ .refresh_live_stylesheet_after_import_graph(
+ root.owner,
+ root.stylesheet_id,
+ );
+ }
+ }
+ }
+ self.note_stylesheet_import_graph_completion(
+ &fetch,
+ Arc::new(
+ crate::stylesheet_blocking::StylesheetImportGraphFetchResult::new(
+ graph_successful,
+ Vec::new(),
+ ),
+ ),
+ );
+ return;
+ }
+ super::import_graph::ConnectedStyleImportReadiness::Pending(urls) => urls,
+ };
+ let blocking_signature =
+ DocumentBlockingStylesheetSignature::ParserCreatedStyleImport { urls: urls.clone() };
+ let blocking_operation = self
+ .stylesheet_lifecycle
+ .fetches
+ .blocking_operation(NodeId::new(load.owner().index()), &blocking_signature);
+ if let Some(blocking_operation) = blocking_operation {
+ self.bind_linked_stylesheet_import_blocking_operation(&fetch, blocking_operation, urls);
+ return;
+ }
+ self.spawn_linked_stylesheet_import_graph(fetch, urls);
+ }
+
+ fn spawn_linked_stylesheet_import_graph(
+ &mut self,
+ fetch: crate::stylesheet_blocking::StylesheetFetch,
+ urls: Vec<Url>,
+ ) {
+ let task_producer = self
+ .stylesheet_lifecycle
+ .task_producer
+ .clone()
+ .expect("linked stylesheet import requires a bound Page task producer");
+ let stylesheet_fetcher = self.stylesheet_fetcher();
+ let document_url = self
+ .dom_host
+ .node(self.dom_host.document_handle())
+ .and_then(Node::as_document)
+ .map(|document| document.url().clone())
+ .expect("live dom host must retain a document url")
+ .clone();
+ let resource_loader = self
+ .current_document_resource_loader()
+ .expect("linked stylesheet import requires its Document authority");
+ resource_loader.spawn_resource_task(async move {
+ let (graph, network_results) =
+ super::import_graph_projection::fetch_observed_stylesheet_import_graph(
+ stylesheet_fetcher,
+ document_url,
+ urls,
+ Vec::new(),
+ )
+ .await;
+ let completion = LinkedStylesheetImportGraphCompletion {
+ fetch,
+ graph,
+ network_results,
+ };
+ let _ = task_producer.send_linked_import_completion(completion);
+ });
+ }
+
+ pub(crate) fn note_stylesheet_import_graph_completion(
+ &mut self,
+ fetch: &crate::stylesheet_blocking::StylesheetFetch,
+ graph: Arc<crate::stylesheet_blocking::StylesheetImportGraphFetchResult>,
+ ) {
+ let graph = self
+ .stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .complete(fetch, graph);
+ let successful = graph.successful();
+ let clients = self
+ .stylesheet_lifecycle
+ .owner_states
+ .link_states()
+ .filter(|(_, state)| state.active_load().fetch().ptr_eq(fetch))
+ .map(|(_, state)| Arc::clone(state.active_load()))
+ .collect::<Vec<_>>();
+ for client in clients {
+ self.note_stylesheet_link_import_completion(&client, successful);
+ }
+ }
+
+ pub(crate) fn apply_linked_stylesheet_import_graph_completion(
+ &mut self,
+ completion: LinkedStylesheetImportGraphCompletion,
+ ) {
+ let LinkedStylesheetImportGraphCompletion {
+ fetch,
+ graph,
+ mut network_results,
+ } = completion;
+ let roots = self
+ .linked_stylesheet_import_roots(&fetch)
+ .into_iter()
+ .filter(|root| {
+ self.dom_host.is_connected(root.owner)
+ && self
+ .stylesheet_lifecycle
+ .owner_states
+ .link_state(root.owner)
+ .is_some_and(|state| state.active_load().fetch().ptr_eq(&fetch))
+ })
+ .collect::<Vec<_>>();
+ let source_owners = roots.iter().map(|root| root.owner).collect::<Vec<_>>();
+ for result in &mut network_results {
+ result.import_roots = roots.clone();
+ result.source_owners = source_owners.clone();
+ }
+ self.stylesheet_lifecycle
+ .ready_connected_load_network_results
+ .extend(network_results);
+ self.note_stylesheet_import_graph_completion(&fetch, graph);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{network::ResourceRequestClient, parser::HtmlParser};
+ use moli_fetch::FetchConfig;
+
+ #[tokio::test]
+ async fn invalidated_blocking_transport_can_release_the_shared_graph() {
+ let document_url = Url::parse("https://example.test/page").unwrap();
+ let parser = HtmlParser;
+ let first_document = parser.parse(
+ document_url.clone(),
+ "<!doctype html><style>@import url('data:text/css,.first%7Bcolor:red%7D');</style>"
+ .to_owned(),
+ );
+ let first_input = crate::stylesheet_blocking::collect_document_owned_blocking_stylesheets(
+ &first_document,
+ )
+ .into_iter()
+ .next()
+ .map(|blocker| {
+ crate::stylesheet_blocking::DocumentOwnedBlockingStylesheetDiscoveryInput::from(
+ &blocker,
+ )
+ })
+ .expect("first parser-created import blocker");
+ let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let mut runtime = DocumentRuntime::new_networked(&first_document, &loader);
+ runtime.note_discovered_document_owned_blocking_stylesheet_inputs([&first_input]);
+ let first_operation = runtime
+ .stylesheet_lifecycle
+ .fetches
+ .blocking_operation(first_input.node_id(), first_input.signature())
+ .expect("first blocking operation");
+ let fetch = runtime
+ .preload_stylesheet(
+ Url::parse("data:text/css,.root%7Bcolor:blue%7D").unwrap(),
+ crate::stylesheet_blocking::StylesheetFetchOptions::default(),
+ )
+ .expect("ownerless stylesheet fetch");
+ assert!(matches!(
+ runtime.admit_linked_stylesheet_import_graph(&fetch, None),
+ LinkedStylesheetImportGraphAdmission::Start
+ ));
+ runtime.bind_linked_stylesheet_import_blocking_operation(
+ &fetch,
+ first_operation.clone(),
+ vec![Url::parse("data:text/css,.first%7Bcolor:red%7D").unwrap()],
+ );
+
+ let second_document = parser.parse(
+ document_url,
+ "<!doctype html><style>@import url('data:text/css,.second%7Bcolor:green%7D');</style>"
+ .to_owned(),
+ );
+ let second_input = crate::stylesheet_blocking::collect_document_owned_blocking_stylesheets(
+ &second_document,
+ )
+ .into_iter()
+ .next()
+ .map(|blocker| {
+ crate::stylesheet_blocking::DocumentOwnedBlockingStylesheetDiscoveryInput::from(
+ &blocker,
+ )
+ .with_node_id(first_input.node_id())
+ })
+ .expect("replacement parser-created import blocker");
+ runtime.note_discovered_document_owned_blocking_stylesheet_inputs([&second_input]);
+ assert!(
+ runtime
+ .stylesheet_lifecycle
+ .fetches
+ .status_for_blocking_operation(&first_operation)
+ .is_none(),
+ "the old parser transport must lose canonical authority"
+ );
+ assert!(
+ runtime
+ .stylesheet_lifecycle
+ .linked_stylesheet_import_graphs
+ .replace_blocking_with_async(&fetch, &first_operation),
+ "the shared graph must be able to continue independently"
+ );
+ assert!(
+ runtime
+ .linked_stylesheet_import_blocking_operations()
+ .is_empty()
+ );
+ }
+}
diff --git a/moli-renderer-v8/src/stylesheet_runtime/load.rs b/moli-renderer-v8/src/stylesheet_runtime/load.rs
index bb996d693..3415c36aa 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/load.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/load.rs
@@ -295,7 +295,7 @@ impl QueuedConnectedStyleLoad {
pub(in crate::document_runtime) enum ConnectedLoadParameters {
ImmediateOwnerProcessing,
StyleImports {
- source: ConnectedStyleImportSource,
+ source: InlineStyleImportSource,
urls: Vec<Url>,
roots: Vec<ConnectedStyleImportRoot>,
},
@@ -305,43 +305,34 @@ pub(in crate::document_runtime) enum ConnectedLoadParameters {
},
}
+/// Exact processing identity for one inline `<style>` import graph.
+///
+/// Linked stylesheets have a fetch-owned graph lifecycle and deliberately do
+/// not use an owner-bound `ConnectedLoadOperation`.
#[derive(Debug, Clone)]
-pub(in crate::document_runtime) enum ConnectedStyleImportSource {
- Inline(Arc<OwnerStyleSheetSource>),
- Linked(Arc<StylesheetLinkClient>),
-}
+pub(in crate::document_runtime) struct InlineStyleImportSource(Arc<OwnerStyleSheetSource>);
-impl ConnectedStyleImportSource {
- pub(in crate::document_runtime) fn owner(&self) -> DomHandle {
- match self {
- Self::Inline(source) => source.owner(),
- Self::Linked(load) => load.owner(),
- }
+impl InlineStyleImportSource {
+ pub(in crate::document_runtime) fn new(source: Arc<OwnerStyleSheetSource>) -> Self {
+ Self(source)
}
- pub(in crate::document_runtime) const fn element_kind(&self) -> ConnectedStyleEventElementKind {
- match self {
- Self::Inline(_) => ConnectedStyleEventElementKind::Style,
- Self::Linked(_) => ConnectedStyleEventElementKind::Link,
- }
+ pub(in crate::document_runtime) fn owner(&self) -> DomHandle {
+ self.0.owner()
}
- pub(in crate::document_runtime) fn ptr_eq(&self, other: &Self) -> bool {
- match (self, other) {
- (Self::Inline(left), Self::Inline(right)) => Arc::ptr_eq(left, right),
- (Self::Linked(left), Self::Linked(right)) => StylesheetLinkClient::ptr_eq(left, right),
- (Self::Inline(_), Self::Linked(_)) | (Self::Linked(_), Self::Inline(_)) => false,
- }
+ pub(in crate::document_runtime) fn source(&self) -> &Arc<OwnerStyleSheetSource> {
+ &self.0
}
}
-impl PartialEq for ConnectedStyleImportSource {
+impl PartialEq for InlineStyleImportSource {
fn eq(&self, other: &Self) -> bool {
- self.ptr_eq(other)
+ Arc::ptr_eq(&self.0, &other.0)
}
}
-impl Eq for ConnectedStyleImportSource {}
+impl Eq for InlineStyleImportSource {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::document_runtime) struct ConnectedLinkReadinessFetchOptions {
diff --git a/moli-renderer-v8/src/stylesheet_runtime/mod.rs b/moli-renderer-v8/src/stylesheet_runtime/mod.rs
index 52a0fbea1..aae26ceab 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/mod.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/mod.rs
@@ -11,12 +11,17 @@ use crate::modulepreload::{
mod attributes;
mod blocking;
+mod blocking_import_graph;
mod client_index;
mod completion;
mod connected;
+mod import_graph;
+mod import_graph_projection;
mod link_state;
+mod linked_import_graph;
mod load;
mod owner_state;
+mod settlement;
mod source_install;
#[cfg(test)]
mod test_driver;
@@ -25,15 +30,20 @@ pub(crate) use attributes::attribute_reprocesses_connected_stylesheet;
pub(crate) use blocking::OwnerlessStylesheetAdmissionError;
pub(super) use client_index::StylesheetLinkClientIndex;
pub(crate) use completion::{ConnectedLoadCompletion, LiveStylesheetImportLoadCompletion};
-pub(crate) use connected::{
- ConnectedStyleLoadPrimeResult, PreparedConnectedStyleLoad,
- fetch_complete_stylesheet_import_graph,
+pub(crate) use connected::{ConnectedStyleLoadPrimeResult, PreparedConnectedStyleLoad};
+pub(crate) use import_graph::fetch_complete_stylesheet_import_graph;
+pub(super) use import_graph::{ConnectedStyleImportReadiness, connected_style_import_readiness};
+pub(super) use import_graph_projection::fetch_observed_stylesheet_import_graph;
+pub(crate) use import_graph_projection::live_stylesheet_import_responses;
+pub(super) use link_state::{LinkStyleState, StylesheetCompletionState};
+pub(crate) use linked_import_graph::LinkedStylesheetImportGraphCompletion;
+pub(super) use linked_import_graph::{
+ LinkedStylesheetImportGraphAdmission, LinkedStylesheetImportGraphs,
};
-pub(super) use link_state::LinkStyleState;
pub(crate) use load::StylesheetLinkClientTerminal;
pub(super) use load::{
ConnectedLinkReadinessFetchOptions, ConnectedLoadOperation, ConnectedLoadParameters,
- ConnectedStyleImportSource, QueuedConnectedStyleLoad, ReadyConnectedStyleLoadOperation,
+ InlineStyleImportSource, QueuedConnectedStyleLoad, ReadyConnectedStyleLoadOperation,
StylesheetLinkClient,
};
pub(crate) use load::{ConnectedStyleEventElementKind, ReadyConnectedStyleLoad};
diff --git a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs
new file mode 100644
index 000000000..1332136f3
--- /dev/null
+++ b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs
@@ -0,0 +1,318 @@
+//! Immediate settlement of exact stylesheet clients.
+//!
+//! A client that adopts an already-terminal physical fetch is completed in the
+//! same owner operation that admitted it. Only the resulting element event and
+//! genuinely asynchronous dependent resources cross a Page task boundary.
+
+use super::*;
+
+impl DocumentRuntime {
+ pub(crate) fn settle_stylesheet_link_clients_in_current_scope(
+ &mut self,
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ clients: Vec<StylesheetLinkClientTerminal>,
+ ) {
+ if clients.is_empty() {
+ return;
+ }
+ debug_assert!(!host_ptr.is_null());
+ let clients = clients
+ .into_iter()
+ .filter(|client| {
+ self.dom_host.is_connected(client.load().owner())
+ && self
+ .stylesheet_lifecycle
+ .owner_states
+ .accepts_stylesheet_link_client(client.load())
+ })
+ .collect::<Vec<_>>();
+ if clients.is_empty() {
+ return;
+ }
+ let optional_resource_fetch_mask = self.current_document_resource_loader().map_or(
+ crate::protocol_types::OptionalResourceFetchMask::NONE,
+ |loader| loader.request_client().optional_resource_fetch_mask(),
+ );
+ let mut css_subresources = Vec::new();
+ self.apply_stylesheet_link_client_terminals(
+ scope,
+ host_ptr,
+ clients,
+ optional_resource_fetch_mask,
+ &mut css_subresources,
+ );
+ self.apply_pending_stylesheet_source_css_projections(scope, host_ptr);
+ Self::start_stylesheet_subresource_fetches_in_current_scope(
+ scope,
+ host_ptr,
+ css_subresources,
+ );
+ }
+
+ fn apply_stylesheet_link_client_terminals(
+ &mut self,
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ client_terminals: Vec<StylesheetLinkClientTerminal>,
+ optional_resource_fetch_mask: crate::protocol_types::OptionalResourceFetchMask,
+ css_subresources: &mut Vec<(
+ crate::frame_owner_model::StylesheetSubresourceLoadDelayBinding,
+ crate::css_resource_urls::StylesheetLoadBlockingResource,
+ )>,
+ ) {
+ let mut linked_stylesheet_import_urls = Vec::new();
+ let mut linked_stylesheet_import_loads = Vec::new();
+ let host = unsafe { &mut *host_ptr };
+ for client in client_terminals {
+ let load = client.load();
+ if !load.installs_stylesheet() {
+ continue;
+ }
+ let terminal = client.terminal();
+ // Blink creates the owner's CSSStyleSheet even when the resource
+ // failed or was cancelled. An unusable terminal therefore installs
+ // an empty source; its existing link task still reports the error.
+ let ready_response = terminal.ready_response();
+ let stylesheet_text = ready_response
+ .map(|response| response.body_text().to_owned())
+ .unwrap_or_default();
+ let stylesheet_base_url = match terminal.physical() {
+ crate::stylesheet_blocking::StylesheetPhysicalOutcome::Response(response) => {
+ response.final_url.clone()
+ }
+ crate::stylesheet_blocking::StylesheetPhysicalOutcome::NetworkError(_) => {
+ load.request_url().clone()
+ }
+ };
+ let request_url = load.request_url().clone();
+ let prepared = host.prepare_linked_stylesheet_resource(
+ load.owner(),
+ &stylesheet_text,
+ stylesheet_base_url.clone(),
+ request_url.clone(),
+ terminal.origin_clean().unwrap_or(false),
+ );
+ if let Some(prepared) = prepared.as_ref() {
+ host.install_linked_stylesheet(InstallLinkedStylesheet::from_prepared(
+ load.owner(),
+ request_url.clone(),
+ prepared.clone(),
+ ));
+ }
+ let import_root = prepared.as_ref().and_then(|_| {
+ host.linked_live_stylesheet(load.owner()).map(|stylesheet| {
+ ConnectedStyleImportRoot::new(load.owner(), &stylesheet, true)
+ })
+ });
+ match self.admit_linked_stylesheet_import_graph(load.fetch(), import_root.clone()) {
+ LinkedStylesheetImportGraphAdmission::Start => {}
+ LinkedStylesheetImportGraphAdmission::InFlight => continue,
+ LinkedStylesheetImportGraphAdmission::Completed(graph) => {
+ if let Some(root) = import_root {
+ let responses = live_stylesheet_import_responses(&graph);
+ if host
+ .install_live_stylesheet_import_graph(root.clone(), &responses)
+ .is_some()
+ {
+ let _ = host.refresh_live_stylesheet_after_import_graph(
+ root.owner,
+ root.stylesheet_id,
+ );
+ }
+ }
+ continue;
+ }
+ }
+ let import_urls = ready_response
+ .and(prepared.as_ref())
+ .map(|prepared| prepared.import_urls().to_vec())
+ .unwrap_or_default();
+ linked_stylesheet_import_loads.push((Arc::clone(load), import_urls.clone()));
+ if ready_response.is_none() {
+ // Only a usable response may contribute CSS text, imports, or
+ // other dependent resources. The empty owner sheet is CSSOM-only.
+ continue;
+ }
+ if request_url.scheme() != "data" {
+ linked_stylesheet_import_urls.extend(import_urls);
+ }
+ for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(
+ &stylesheet_text,
+ &stylesheet_base_url,
+ optional_resource_fetch_mask,
+ ) {
+ let Some(binding) = host.accept_current_main_stylesheet_subresource_load_delay()
+ else {
+ tracing::debug!(
+ url = %resource.request_url(),
+ kind = ?resource.kind(),
+ "skipping stylesheet subresource for stale main document owner"
+ );
+ continue;
+ };
+ css_subresources.push((binding, resource));
+ }
+ }
+ for (load, urls) in linked_stylesheet_import_loads {
+ self.prime_network_stylesheet_import_loads(load, urls, host_ptr);
+ }
+ self.queue_linked_stylesheet_import_csp_violations_in_current_scope(
+ scope,
+ host_ptr,
+ linked_stylesheet_import_urls,
+ );
+ }
+
+ fn queue_linked_stylesheet_import_csp_violations_in_current_scope(
+ &mut self,
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ import_urls: impl IntoIterator<Item = url::Url>,
+ ) {
+ let violations = import_urls
+ .into_iter()
+ .flat_map(|url| {
+ let (report_only, enforced) = self
+ .style_element_request_csp_check(
+ &url,
+ crate::content_security_policy::ContentSecurityPolicyStyleElementRequest {
+ nonce: None,
+ },
+ )
+ .into_violations();
+ [report_only, enforced].into_iter().flatten()
+ })
+ .collect::<Vec<_>>();
+ for violation in violations {
+ self.queue_content_security_policy_violation_event_best_effort(
+ scope, host_ptr, &violation,
+ );
+ }
+ }
+
+ pub(crate) fn start_stylesheet_subresource_fetches_in_current_scope(
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ resources: Vec<(
+ crate::frame_owner_model::StylesheetSubresourceLoadDelayBinding,
+ crate::css_resource_urls::StylesheetLoadBlockingResource,
+ )>,
+ ) {
+ if resources.is_empty() {
+ return;
+ }
+ debug_assert!(!host_ptr.is_null());
+ let started = std::time::Instant::now();
+ let resource_count = resources.len();
+ let host = unsafe { &mut *host_ptr };
+ let retain_css_images = host.layout_policy().uses_real_layout();
+ let mut admitted = Vec::with_capacity(resources.len());
+ for (binding, resource) in resources {
+ match resource.kind() {
+ crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Font
+ if binding.child_handle().is_none() =>
+ {
+ match host.admit_document_web_font(resource) {
+ Some(resource) => admitted.push((binding, resource, None)),
+ None => {
+ host.settle_stylesheet_subresource_load_delay(binding);
+ }
+ }
+ }
+ crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Image
+ if retain_css_images =>
+ {
+ let resolved_url = resource.request_url().as_str().to_owned();
+ match host.admit_stylesheet_css_image(binding, resolved_url) {
+ crate::native_bridge::CssImageResourceAdmission::Fetch(identity) => {
+ admitted.push((binding, resource, Some(identity)));
+ }
+ crate::native_bridge::CssImageResourceAdmission::Reused => {
+ host.settle_stylesheet_subresource_load_delay(binding);
+ }
+ crate::native_bridge::CssImageResourceAdmission::Untracked => {
+ admitted.push((binding, resource, None));
+ }
+ }
+ }
+ _ => admitted.push((binding, resource, None)),
+ }
+ }
+ for (binding, resource, css_image) in admitted {
+ let request_url = resource.request_url().clone();
+ let kind = resource.kind();
+ let failed_css_image = css_image.clone();
+ let failed_web_font = (binding.child_handle().is_none()
+ && kind == crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Font)
+ .then(|| {
+ resource
+ .web_font()
+ .cloned()
+ .map(crate::css_resource_urls::CompletedStylesheetWebFont::failure)
+ })
+ .flatten();
+ match crate::network_host::start_stylesheet_subresource_fetch(
+ scope, host, binding, resource, css_image,
+ ) {
+ Ok(crate::network_host::StylesheetSubresourceFetchStart::WebFontSettled(
+ web_font,
+ )) => {
+ Self::complete_document_web_font(host, web_font);
+ }
+ Ok(
+ crate::network_host::StylesheetSubresourceFetchStart::Pending
+ | crate::network_host::StylesheetSubresourceFetchStart::Settled,
+ ) => {}
+ Err(error) => {
+ if let Some(identity) = failed_css_image.as_ref() {
+ let _ = host.fail_stylesheet_css_image(identity);
+ }
+ let settlement = host.settle_stylesheet_subresource_load_delay(binding);
+ if let Some(web_font) = failed_web_font {
+ Self::complete_document_web_font(host, web_font);
+ }
+ tracing::warn!(
+ url = %request_url,
+ ?kind,
+ owner = ?binding.owner(),
+ settled = settlement.settled(),
+ %error,
+ "stylesheet subresource failed before network scheduling"
+ );
+ }
+ }
+ }
+ tracing::debug!(
+ resource_count,
+ elapsed_ms = started.elapsed().as_millis(),
+ "started owner-bound stylesheet subresource requests"
+ );
+ }
+
+ fn complete_document_web_font(
+ host: &JsContextHost,
+ terminal: crate::css_resource_urls::CompletedStylesheetWebFont,
+ ) {
+ match host.complete_document_web_font(terminal) {
+ crate::script_vm::web_fonts::DocumentWebFontCompletion::Registered(outcome) => {
+ tracing::debug!(
+ ?outcome,
+ "registered current document web font for the next fresh layout refresh"
+ )
+ }
+ crate::script_vm::web_fonts::DocumentWebFontCompletion::Invalid(error) => {
+ tracing::warn!(
+ %error,
+ "discarded invalid current document web font response"
+ )
+ }
+ crate::script_vm::web_fonts::DocumentWebFontCompletion::NetworkFailed => {
+ tracing::debug!("current document web font request reached a failed terminal")
+ }
+ crate::script_vm::web_fonts::DocumentWebFontCompletion::Stale => {
+ tracing::debug!("discarded superseded document web font response")
+ }
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/stylesheet_runtime/test_driver.rs b/moli-renderer-v8/src/stylesheet_runtime/test_driver.rs
index f3c876a40..bc820dc17 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/test_driver.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/test_driver.rs
@@ -29,6 +29,9 @@ impl DocumentRuntime {
crate::page_task_queue::RendererPageStylesheetCompletion::Connected(completion) => {
self.apply_connected_style_load_completion(completion);
}
+ crate::page_task_queue::RendererPageStylesheetCompletion::LinkedImport(completion) => {
+ self.apply_linked_stylesheet_import_graph_completion(completion);
+ }
crate::page_task_queue::RendererPageStylesheetCompletion::LiveImport(completion) => {
self.apply_live_stylesheet_import_load_completion(completion, true);
}
diff --git a/moli-stylesheet-blocking/src/fetcher.rs b/moli-stylesheet-blocking/src/fetcher.rs
index 8a8bade51..1d39a8121 100644
--- a/moli-stylesheet-blocking/src/fetcher.rs
+++ b/moli-stylesheet-blocking/src/fetcher.rs
@@ -323,8 +323,6 @@ struct StylesheetFetchRequest {
start_unix_millis: f64,
terminal: OnceLock<Arc<StylesheetFetchTerminal>>,
physical_observation_emitted: AtomicBool,
- dependent_resources_started: AtomicBool,
- import_graph_terminal: OnceLock<bool>,
}
impl StylesheetFetch {
@@ -342,8 +340,6 @@ impl StylesheetFetch {
start_unix_millis,
terminal: OnceLock::new(),
physical_observation_emitted: AtomicBool::new(false),
- dependent_resources_started: AtomicBool::new(false),
- import_graph_terminal: OnceLock::new(),
}))
}
@@ -397,21 +393,6 @@ impl StylesheetFetch {
.physical_observation_emitted
.swap(true, Ordering::AcqRel)
}
-
- pub fn claim_dependent_resource_start(&self) -> bool {
- !self
- .0
- .dependent_resources_started
- .swap(true, Ordering::AcqRel)
- }
-
- pub fn finish_import_graph(&self, successful: bool) -> bool {
- self.0.import_graph_terminal.set(successful).is_ok()
- }
-
- pub fn import_graph_terminal(&self) -> Option<bool> {
- self.0.import_graph_terminal.get().copied()
- }
}
impl std::fmt::Debug for StylesheetFetch {