From 478329ec8da79c8cd56cdc850cfbea6818ba85cc Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sat, 7 Nov 2026 10:32:32 +0800 Subject: [PATCH] fix(performance): retain preload request attribution and completion Keep initiating sources on connected-link requests and report their real network terminal clocks. Attribute image and other link preloads to link, and preserve the actual caller for stylesheet preloads. Attribute response header preloads to their requesting Document. Cover pending and completed consumption, cache policies, Document realms, and HTTP Link preloads. Hide initiating sources for Service Worker responses while retaining them on actual network fallback. --- .../tests/fixtures/preload-resource-timing.js | 105 +++++++++++ .../tests/scripts/preload_consumption.rs | 166 +++++++++++++++++- .../context_bootstrap/performance_runtime.rs | 17 ++ moli-renderer-v8/src/document_runtime.rs | 18 ++ .../src/script_vm/post_parse_lifecycle.rs | 32 +++- .../subresource_fetch/response_preload.rs | 3 + .../src/stylesheet_runtime/blocking.rs | 3 +- .../src/stylesheet_runtime/connected.rs | 51 +++--- .../import_graph_projection.rs | 1 + moli-stylesheet-blocking/src/fetcher.rs | 16 ++ 10 files changed, 372 insertions(+), 40 deletions(-) create mode 100644 moli-core/tests/fixtures/preload-resource-timing.js diff --git a/moli-core/tests/fixtures/preload-resource-timing.js b/moli-core/tests/fixtures/preload-resource-timing.js new file mode 100644 index 00000000000..512abd812b8 --- /dev/null +++ b/moli-core/tests/fixtures/preload-resource-timing.js @@ -0,0 +1,105 @@ +(() => { + const source = document.currentScript.src; + const realm = new URL(source).searchParams.get('realm'); + globalThis.preloadResourceTimingResult = (async () => { + const rows = []; + for (const kind of ['script', 'style', 'image', 'font', 'fetch']) { + for (const cache of ['no-store', 'max-age=60']) { + for (const phase of ['pending', 'complete']) { + const token = `${realm}-${kind}-${cache}-${phase}`; + const url = new URL('/probe-asset', location.href); + url.searchParams.set('token', token); + url.searchParams.set('as', kind); + url.searchParams.set('cache', cache); + const link = document.createElement('link'); + Object.assign(link, {rel: 'preload', as: kind, href: url.href}); + if (kind === 'font' || kind === 'fetch') link.crossOrigin = 'anonymous'; + const loaded = new Promise(resolve => { + link.onload = link.onerror = event => resolve(event.type); + }); + document.head.append(link); + await fetch('/probe-started?token=' + encodeURIComponent(token)); + if (phase === 'complete') { + await fetch('/probe-release?token=' + encodeURIComponent(token)); + await loaded; + } + let consumer; + let consumed; + if (kind === 'fetch') { + consumed = fetch(url).then(response => response.text()).then(() => 'load'); + } else if (kind === 'font') { + consumer = new FontFace('TimingFont' + rows.length, `url("${url}")`); + consumed = consumer.load().then(() => 'load', () => 'error'); + } else { + consumer = document.createElement(kind === 'style' ? 'link' : kind === 'image' ? 'img' : 'script'); + if (kind === 'style') Object.assign(consumer, {rel: 'stylesheet', href: url.href}); + else consumer.src = url.href; + consumed = new Promise(resolve => { + consumer.onload = consumer.onerror = event => resolve(event.type); + }); + document.body.append(consumer); + } + if (phase === 'pending') await fetch('/probe-release?token=' + encodeURIComponent(token)); + const events = await Promise.all([loaded, consumed]); + const stats = await (await fetch('/probe-stats?token=' + encodeURIComponent(token))).json(); + const entries = performance.getEntriesByName(url.href, 'resource').map(entry => ({ + type: entry.initiatorType, source: entry.initiatorUrl, + encoded: entry.encodedBodySize, end: entry.responseEnd + })); + rows.push({kind, cache, phase, events, requests: stats.count, entries}); + link.remove(); + if (consumer && consumer.remove) consumer.remove(); + } + } + } + const controlled = navigator.serviceWorker.controller ? Promise.resolve() : + new Promise(resolve => navigator.serviceWorker.addEventListener('controllerchange', resolve, {once: true})); + await navigator.serviceWorker.register('/probe-worker.js'); + await navigator.serviceWorker.ready; + await controlled; + const swRows = []; + for (const response of ['network', 'default', 'basic']) { + for (const kind of response === 'network' ? ['script'] : ['script', 'style']) { + const token = `${realm}-sw-${response}-${kind}`; + const url = new URL(response === 'network' ? '/probe-asset' : '/probe-worker-asset', location.href); + url.searchParams.set('token', token); + url.searchParams.set('as', kind); + url.searchParams.set('source', response); + await fetch('/probe-release?token=' + encodeURIComponent(token)); + const link = document.createElement('link'); + Object.assign(link, {rel: 'preload', as: kind, href: url.href}); + const loaded = new Promise(resolve => { + link.onload = link.onerror = event => resolve(event.type); + }); + document.head.append(link); + const preloadEvent = await loaded; + const consumer = document.createElement(kind === 'style' ? 'link' : 'script'); + if (kind === 'style') Object.assign(consumer, {rel: 'stylesheet', href: url.href}); + else consumer.src = url.href; + const consumed = new Promise(resolve => { + consumer.onload = consumer.onerror = event => resolve(event.type); + }); + document.body.append(consumer); + const events = [preloadEvent, await consumed]; + const stats = await (await fetch('/probe-stats?token=' + encodeURIComponent(token))).json(); + const counts = await (await fetch('/probe-worker-counts')).json(); + const entries = performance.getEntriesByName(url.href, 'resource').map(entry => ({ + type: entry.initiatorType, source: entry.initiatorUrl, + encoded: entry.encodedBodySize, end: entry.responseEnd + })); + swRows.push({response, kind, events, requests: stats.count, + workerRequests: counts[url.href] || 0, entries}); + link.remove(); + consumer.remove(); + } + } + const swFailures = swRows.filter(row => row.requests !== (row.response === 'default' ? 0 : 1) || + row.workerRequests !== (row.response === 'network' ? 0 : 1) || row.events.some(event => event !== 'load') || + row.entries.length !== 1 || row.entries.some(entry => entry.type !== 'link' || + entry.source !== (row.response === 'network' ? source : '') || entry.encoded <= 0 || entry.end <= 0)); + const failures = rows.filter(row => row.requests !== 1 || row.events.some(event => event !== 'load') || + row.entries.length !== 1 || row.entries.some(entry => entry.type !== 'link' || + entry.source !== source || entry.encoded <= 0 || entry.end <= 0)); + return {source, rows, failures, swRows, swFailures}; + })(); +})(); diff --git a/moli-core/tests/scripts/preload_consumption.rs b/moli-core/tests/scripts/preload_consumption.rs index 2d78a181ac0..5ade0bf9b98 100644 --- a/moli-core/tests/scripts/preload_consumption.rs +++ b/moli-core/tests/scripts/preload_consumption.rs @@ -51,6 +51,7 @@ impl Asset { pub(super) struct PreloadServer { pub(super) origin: String, task: JoinHandle<()>, + assets: Arc>>>, } impl Drop for PreloadServer { @@ -63,8 +64,10 @@ impl PreloadServer { pub(super) async fn spawn() -> Result { let listener = TcpListener::bind("127.0.0.1:0").await?; let origin = format!("http://{}", listener.local_addr()?); + let assets = Arc::new(Mutex::new(HashMap::>::new())); + let server_assets = assets.clone(); let task = tokio::spawn(async move { - let assets = Arc::new(Mutex::new(HashMap::>::new())); + let assets = server_assets; let mut connections = JoinSet::new(); loop { tokio::select! { @@ -82,14 +85,16 @@ impl PreloadServer { let url = url::Url::parse(&format!("http://test{path}")).unwrap(); let query: HashMap<_,_> = url.query_pairs().into_owned().collect(); let token = query.get("token").cloned().unwrap_or_default(); - let asset = assets.lock().entry(token).or_default().clone(); + let asset = assets.lock().entry(token.clone()).or_default().clone(); let mut cache = "no-store".to_owned(); let (mime, body) = match url.path() { "/probe-worker.js" => ("text/javascript", include_str!("../fixtures/preload-consumption-worker.js").to_owned()), + "/probe-timing.js" => ("text/javascript", include_str!("../fixtures/preload-resource-timing.js").to_owned()), + "/timing-header" => ("text/html", "Header preload timing".to_owned()), "/probe-asset" | "/probe-font-final" => { asset.count.fetch_add(1, Ordering::AcqRel); asset.started.notify_waiters(); - asset.wait(true).await; + if !query.contains_key("auto") { asset.wait(true).await; } cache = query.get("cache").cloned().unwrap_or(cache); if query.get("as").is_some_and(|kind| kind == "image") { ("image/svg+xml", "".to_owned()) @@ -119,7 +124,13 @@ impl PreloadServer { let cors = if query.get("cors").is_some_and(|value| value == "none") { String::new() } else { format!("Access-Control-Allow-Origin: {origin}\r\nAccess-Control-Allow-Credentials: true\r\n") }; let policy = query.get("reportPolicy").map(|policy| format!("Content-Security-Policy-Report-Only: {policy}\r\n")).unwrap_or_default(); - let response = format!("HTTP/1.1 {status} OK\r\nContent-Type: {mime}\r\nCache-Control: {cache}\r\n{cors}{location}{policy}Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()); + let link = if url.path() == "/timing-header" { + let kind = query.get("as").map(String::as_str).unwrap_or("script"); + let source = query.get("source").map(String::as_str).unwrap_or("network"); + let path = if source == "network" { "/probe-asset" } else { "/probe-worker-asset" }; + format!("Link: <{path}?token={token}&as={kind}&source={source}&auto=1>; rel=preload; as={kind}\r\n") + } else { String::new() }; + let response = format!("HTTP/1.1 {status} OK\r\nContent-Type: {mime}\r\nCache-Control: {cache}\r\n{cors}{location}{policy}{link}Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()); let _ = stream.write_all(response.as_bytes()).await; let _ = stream.write_all(&body).await; }); @@ -128,10 +139,155 @@ impl PreloadServer { } } }); - Ok(Self { origin, task }) + Ok(Self { + origin, + task, + assets, + }) } } +#[tokio::test(flavor = "multi_thread")] +async fn preload_resource_timings_retain_the_initiator_through_consumption() -> Result<()> { + let server = PreloadServer::spawn().await?; + let mut config = AppConfig::default(); + config.set_optional_resource_fetch_mask(moli_page_types::OptionalResourceFetchMask::ALL); + let browser = Browser::new(config)?; + for realm in ["main", "child"] { + let mut page = browser.fetch(&server.origin).await?; + let expression = format!( + r#"(async () => {{ + let target = window; + if ({realm:?} === 'child') {{ + const frame = document.createElement('iframe'); + frame.src = '/?preload-timing-child'; + await new Promise(resolve => {{ frame.onload = resolve; document.body.append(frame); }}); + target = frame.contentWindow; + }} + const script = target.document.createElement('script'); + script.src = '/probe-timing.js?realm=' + {realm:?}; + await new Promise((resolve, reject) => {{ + script.onload = resolve; script.onerror = reject; + target.document.body.append(script); + }}); + return JSON.stringify(await target.preloadResourceTimingResult); + }})()"#, + ); + let result = tokio::time::timeout( + Duration::from_secs(30), + page.evaluate_runtime_expression_with_await_async(&expression, true), + ) + .await??; + let value: serde_json::Value = serde_json::from_str( + result["value"] + .as_str() + .context("preload resource timing results")?, + )?; + assert_eq!( + value["rows"].as_array().unwrap().len(), + 20, + "{realm}: {value}" + ); + assert_eq!( + value["failures"], + serde_json::json!([]), + "preloads must retain their own initiating source and one network timing: {realm}: {value}" + ); + assert_eq!( + value["swRows"].as_array().unwrap().len(), + 5, + "{realm}: {value}" + ); + assert_eq!( + value["swFailures"], + serde_json::json!([]), + "SW responses must hide the source while network fallback retains it: {realm}: {value}" + ); + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn response_header_preload_timings_retain_the_request_document() -> Result<()> { + let server = PreloadServer::spawn().await?; + let mut config = AppConfig::default(); + config.set_optional_resource_fetch_mask(moli_page_types::OptionalResourceFetchMask::ALL); + let browser = Browser::new(config)?; + let mut setup = browser.fetch(&server.origin).await?; + tokio::time::timeout(Duration::from_secs(30), setup.evaluate_runtime_expression_with_await_async( + r#"(async () => { + const controlled = navigator.serviceWorker.controller ? Promise.resolve() : + new Promise(resolve => navigator.serviceWorker.addEventListener('controllerchange', resolve, {once: true})); + await navigator.serviceWorker.register('/probe-worker.js'); + await navigator.serviceWorker.ready; + await controlled; + })()"#, true)).await??; + for source in ["network", "default", "basic"] { + for kind in ["script", "style"] { + let document_url = format!( + "{}/timing-header?token=header-{source}-{kind}&as={kind}&source={source}", + server.origin + ); + let mut page = browser.fetch(&document_url).await?; + let result = tokio::time::timeout( + Duration::from_secs(30), + page.evaluate_runtime_expression_with_await_async( + r#"new Promise(resolve => { + const read = entries => { + const entry = entries.find(entry => entry.name.includes('/probe-asset?') || entry.name.includes('/probe-worker-asset?')); + if (!entry) return false; + resolve(JSON.stringify({type: entry.initiatorType, source: entry.initiatorUrl, + encoded: entry.encodedBodySize, end: entry.responseEnd})); + return true; + }; + if (!read(performance.getEntriesByType('resource'))) { + const observer = new PerformanceObserver(list => { + if (read(list.getEntries())) observer.disconnect(); + }); + observer.observe({type: 'resource', buffered: true}); + } + })"#, + true, + ), + ) + .await??; + let value: serde_json::Value = serde_json::from_str( + result["value"] + .as_str() + .context("header preload resource timing")?, + )?; + assert_eq!(value["type"], "link", "{kind}: {value}"); + assert_eq!( + value["source"], + if source == "network" { + &document_url + } else { + "" + }, + "header preload must retain its Document only for network fallback: {source}/{kind}: {value}" + ); + assert!( + value["encoded"].as_u64().is_some_and(|bytes| bytes > 0), + "{value}" + ); + assert!( + value["end"].as_f64().is_some_and(|end| end > 0.0), + "{value}" + ); + assert_eq!( + server + .assets + .lock() + .get(&format!("header-{source}-{kind}")) + .map(|asset| asset.count.load(Ordering::Acquire)), + Some(if source == "default" { 0 } else { 1 }), + "header preload must count actual network requests: {source}/{kind}" + ); + } + } + Ok(()) +} + #[tokio::test(flavor = "multi_thread")] async fn stylesheet_preloads_supply_pending_and_completed_consumers_and_integrity_failures() -> Result<()> { diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs index caec52e22a8..0f92cd1a6ba 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs @@ -255,6 +255,23 @@ pub(crate) struct ResourcePerformanceEntry { } impl ResourcePerformanceEntry { + pub(crate) fn mark_aborted(&mut self, transfer_complete: bool) { + self.response_status = 0.0; + self.content_type.clear(); + self.content_encoding.clear(); + if !transfer_complete { + self.encoded_body_size = 0.0; + self.decoded_body_size = 0.0; + if self.transfer_size > 0.0 { + self.transfer_size = 300.0; + } + } + } + + pub(crate) fn set_response_end_unix_millis(&mut self, end: f64) { + self.end_unix_millis = Some(end); + } + pub(crate) fn clear_initiator(&mut self) { self.initiator_url.clear(); } diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs index b45b6a5693e..9a20af487ff 100644 --- a/moli-renderer-v8/src/document_runtime.rs +++ b/moli-renderer-v8/src/document_runtime.rs @@ -451,6 +451,7 @@ impl ConnectedStyleImportRoot { pub(crate) struct ConnectedLoadNetworkResult { /// Request provenance survives clearing the stylesheet installation owner. pub(crate) resource_timing_initiator_type: &'static str, + pub(crate) resource_timing: Option, pub(crate) import_options: Option, pub(crate) consumed_preload_error: bool, /// Exact request Document, independent of an element's current location. @@ -470,6 +471,14 @@ pub(crate) struct ConnectedLoadNetworkResult { pub(crate) result: std::result::Result, } +/// Attribution and terminal observation of the physical connected-link request. +/// Neither depends on a link's later location or on callback execution. +#[derive(Debug, Clone)] +pub(crate) struct ConnectedResourceTiming { + pub(crate) initiator: crate::context_bootstrap::ResourceTimingInitiator, + pub(crate) end_unix_millis: f64, +} + #[derive(Debug)] struct DocumentWriteExternalScriptStart { node: DomHandle, @@ -2730,6 +2739,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -2783,6 +2793,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -2841,6 +2852,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -2899,6 +2911,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -3511,6 +3524,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -3611,6 +3625,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "css", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -3689,6 +3704,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "css", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -3755,6 +3771,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "css", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, @@ -3900,6 +3917,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + resource_timing: None, import_options: None, consumed_preload_error: false, document_owner: None, 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 ac8a68426a1..8c9cf592008 100644 --- a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs +++ b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs @@ -2550,6 +2550,7 @@ impl ScriptVm { let crate::document_runtime::ConnectedLoadNetworkResult { network_observed, resource_timing_initiator_type, + resource_timing, import_options, consumed_preload_error, document_owner, @@ -2588,14 +2589,29 @@ impl ScriptVm { start_unix_millis, &result, ); - if let (Some(fetch), Ok(response)) = (stylesheet_fetch.as_ref(), &result) { - let source = fetch - .resource_timing_initiator_url() - .unwrap_or(document_url.as_str()); - crate::context_bootstrap::ResourceTimingInitiator::from_captured_url( - source.to_owned(), - ) - .apply(&mut entry, &response.head(), origin_clean); + if let Some(timing) = resource_timing { + entry.set_response_end_unix_millis(timing.end_unix_millis); + if let Ok(response) = &result { + timing + .initiator + .apply(&mut entry, &response.head(), origin_clean); + } + } else if let (Some(fetch), Ok(response)) = (stylesheet_fetch.as_ref(), &result) { + if let Some(end) = fetch.end_unix_millis() { + entry.set_response_end_unix_millis(end); + } + if !fetch + .terminal() + .is_some_and(|terminal| terminal.from_service_worker()) + { + let source = fetch + .resource_timing_initiator_url() + .unwrap_or(document_url.as_str()); + crate::context_bootstrap::ResourceTimingInitiator::from_captured_url( + source.to_owned(), + ) + .apply(&mut entry, &response.head(), origin_clean); + } } performance_entries.push((document_owner, entry)); } diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/response_preload.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/response_preload.rs index 63fed11bc03..db25a42c7f8 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch/response_preload.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/response_preload.rs @@ -15,6 +15,9 @@ impl ScriptVm { if let Some(native) = pending.load.response_timing() { preload.timing.observe_native_timing(native); } + if from_service_worker { + preload.timing.clear_initiator(); + } let (entry, response) = match result { Ok(response) => { let filter = response_filter.cloned().unwrap_or_else(|| { diff --git a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs index 473ac3fc91d..ad387fc4eae 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs @@ -375,7 +375,7 @@ impl DocumentRuntime { .extend(completed); } - pub(super) fn parser_blocking_stylesheet_release_is_ready(&self) -> bool { + pub(crate) fn parser_blocking_stylesheet_release_is_ready(&self) -> bool { !self.stylesheet_lifecycle.fetches.has_any_pending_entries() && !self.has_pending_parser_blocking_link() } @@ -453,6 +453,7 @@ impl DocumentRuntime { } else { "link" }, + resource_timing: None, import_options: None, consumed_preload_error: result.terminal.is_consumed_preload_error(), document_owner, diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs index 8d7fa383048..cfcaf32d42c 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs @@ -18,28 +18,6 @@ use crate::stylesheet_blocking::{ use crate::types::{AsyncSubresourceFetchResponseFilter, SubresourceResourceType}; use moli_fetch::{FetchPriorityHint, RequestCredentialsMode, RequestResourceType}; -fn preload_like_resource_initiator_type(resource_type: SubresourceResourceType) -> &'static str { - match resource_type { - SubresourceResourceType::Script => "link", - SubresourceResourceType::Image => "img", - SubresourceResourceType::Audio => "audio", - SubresourceResourceType::Media => "video", - SubresourceResourceType::Video => "video", - SubresourceResourceType::TextTrack => "track", - SubresourceResourceType::Document - | SubresourceResourceType::Fetch - | SubresourceResourceType::EventSource - | SubresourceResourceType::Font - | SubresourceResourceType::Ping - | SubresourceResourceType::CspReport - | SubresourceResourceType::Dictionary - | SubresourceResourceType::Manifest - | SubresourceResourceType::Xhr - | SubresourceResourceType::WebSocket - | SubresourceResourceType::Stylesheet => "link", - } -} - struct ConnectedLinkReadinessFetchResponse { response: crate::protocol_types::NavigationResponse, origin_clean: bool, @@ -1308,10 +1286,17 @@ impl DocumentRuntime { .clone(); let fetch = self.stylesheet_lifecycle.fetches.preload_stylesheet( &fetcher, - document_url, + document_url.clone(), request.url().clone(), request.options().clone(), ); + fetch.set_resource_timing_initiator_url( + resource_timing_initiator + .as_ref() + .map(|source| source.as_str()) + .unwrap_or(document_url.as_str()) + .to_owned(), + ); let load = StylesheetLinkClient::new_preload_with_event_admission( handle, request.url().clone(), @@ -1434,6 +1419,10 @@ impl DocumentRuntime { }) }; let document_url = resource_loader.fetch_context().document_url().clone(); + let resource_initiator = resource_timing_initiator.unwrap_or_else(|| { + crate::context_bootstrap::ResourceTimingInitiator::from_document(&document_url) + }); + let started = std::time::Instant::now(); let start_unix_millis = moli_time::unix_epoch_millis(); let resource_task_runner = resource_loader.task_runner(); let request_origin = resource_loader.fetch_context().request_origin(); @@ -1461,6 +1450,17 @@ impl DocumentRuntime { service_worker_context, ) .await; + let resource_timing = crate::document_runtime::ConnectedResourceTiming { + initiator: if result + .as_ref() + .is_ok_and(|response| response.from_service_worker) + { + crate::context_bootstrap::ResourceTimingInitiator::default() + } else { + resource_initiator + }, + end_unix_millis: start_unix_millis + started.elapsed().as_secs_f64() * 1000.0, + }; let preload = preload.map(|producer| { let response = result .as_ref() @@ -1475,9 +1475,8 @@ impl DocumentRuntime { .is_ok_and(|response| response.load_event_successful), network_results: vec![ConnectedLoadNetworkResult { network_observed: false, - resource_timing_initiator_type: preload_like_resource_initiator_type( - resource_type, - ), + resource_timing_initiator_type: "link", + resource_timing: Some(resource_timing), import_options: None, consumed_preload_error: false, document_owner, diff --git a/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs b/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs index 327adf56562..9dd2ce15ef3 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs @@ -39,6 +39,7 @@ pub(in crate::document_runtime) async fn fetch_observed_stylesheet_import_graph( ConnectedLoadNetworkResult { network_observed: terminal.network_was_observed(), resource_timing_initiator_type: "css", + resource_timing: None, import_options, consumed_preload_error: terminal.is_consumed_preload_error(), document_owner: None, diff --git a/moli-stylesheet-blocking/src/fetcher.rs b/moli-stylesheet-blocking/src/fetcher.rs index 04a91781238..3b6d1859663 100644 --- a/moli-stylesheet-blocking/src/fetcher.rs +++ b/moli-stylesheet-blocking/src/fetcher.rs @@ -230,6 +230,7 @@ impl StylesheetUsability { #[derive(Debug, Clone)] pub struct StylesheetFetchTerminal { + completed_at: std::time::Instant, service_worker_response_url: Option, physical: StylesheetPhysicalOutcome, usability: StylesheetUsability, @@ -256,6 +257,7 @@ impl StylesheetFetchTerminal { ) -> Self { Self { physical: StylesheetPhysicalOutcome::Response(Arc::new(response)), + completed_at: std::time::Instant::now(), usability, origin_clean: Some(origin_clean), network_observed: false, @@ -288,6 +290,7 @@ impl StylesheetFetchTerminal { let reason = reason.into(); Self { physical: StylesheetPhysicalOutcome::NetworkError(Arc::clone(&reason)), + completed_at: std::time::Instant::now(), usability: StylesheetUsability::Failed { reason }, origin_clean: None, network_observed: false, @@ -534,6 +537,7 @@ struct StylesheetFetchRequest { key: StylesheetResourceKey, options: StylesheetFetchOptions, start_unix_millis: f64, + started_at: std::time::Instant, terminal: OnceLock>, resource_timing_initiator_url: OnceLock, physical_observation_emitted: AtomicBool, @@ -552,6 +556,7 @@ impl StylesheetFetch { key, options, start_unix_millis, + started_at: std::time::Instant::now(), terminal: OnceLock::new(), resource_timing_initiator_url: OnceLock::new(), physical_observation_emitted: AtomicBool::new(false), @@ -583,6 +588,17 @@ impl StylesheetFetch { .map(String::as_str) } + pub fn end_unix_millis(&self) -> Option { + self.0.terminal.get().map(|terminal| { + self.0.start_unix_millis + + terminal + .completed_at + .saturating_duration_since(self.0.started_at) + .as_secs_f64() + * 1000.0 + }) + } + pub(crate) fn request_url(&self) -> &Url { self.0.key.request_url() }