fix(preload): consume stylesheet preload responses

This commit is contained in:
ldm0
2026-11-24 14:32:20 +08:00
parent c28d8273ea
commit 0f8742bfce
15 changed files with 560 additions and 56 deletions
@@ -0,0 +1,44 @@
async function () {
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 good = 'sha384-b9DQbErnj+wcR+dXhGEavTqeJs6OQTWA2lGTnjyUlV+dCmcdacihfgX5gSogUi4Z';
const rows = [];
for (const phase of ['pending', 'complete'])
for (const source of ['basic', 'cors', 'default', 'opaque'])
for (const integrity of ['', good, 'sha384-AAAA']) {
const token = 'style-sw-' + rows.length;
const url = new URL('/probe-worker-asset', location.href);
Object.entries({token, source, as: 'style'}).forEach(([key, value]) => url.searchParams.set(key, value));
const preload = document.createElement('link');
Object.assign(preload, {rel: 'preload', as: 'style', href: url.href, integrity});
const preloaded = new Promise(resolve => { preload.onload = preload.onerror = e => resolve(e.type); });
document.head.append(preload);
if (source !== 'default') await fetch('/probe-started?token=' + token);
if (phase === 'complete') {
await fetch('/probe-release?token=' + token);
await preloaded;
}
const consumer = document.createElement('link');
Object.assign(consumer, {rel: 'stylesheet', href: url.href});
const consumed = new Promise(resolve => { consumer.onload = consumer.onerror = e => resolve(e.type); });
document.head.append(consumer);
if (phase === 'pending') await fetch('/probe-release?token=' + token);
const events = await Promise.all([preloaded, consumed]);
const counts = await (await fetch('/probe-worker-counts')).json();
let css;
try { css = consumer.sheet?.cssRules[0]?.style.getPropertyValue('--preload-value') || ''; }
catch (e) { css = e.name; }
const rejected = integrity !== '' && (integrity !== good || source === 'opaque');
const expectedEvent = rejected ? 'error' : 'load';
const expectedCss = rejected ? '' : source === 'opaque' ? 'SecurityError' : 'loaded';
rows.push({phase, source, integrity, events, expectedEvent, css, expectedCss,
dispatches: counts[url.href], timing: performance.getEntriesByName(url.href).length});
consumer.remove();
preload.remove();
}
return {rows, failures: rows.filter(r => r.events.some(e => e !== r.expectedEvent) ||
r.css !== r.expectedCss || r.dispatches !== 1 || r.timing !== 1)};
}
+85
View File
@@ -0,0 +1,85 @@
async function () {
const good = 'sha384-b9DQbErnj+wcR+dXhGEavTqeJs6OQTWA2lGTnjyUlV+dCmcdacihfgX5gSogUi4Z';
const weaker = 'sha256-47XGYWUsSDkxStoU/S3LvDnl+iNx3+kDvJGmbIh1r8w=';
const bad = 'sha384-AAAA';
const rows = [];
async function run({cache, phase, cors = null, crossOrigin = false, name = 'basic',
preloadIntegrity = '', consumerIntegrity = '',
expectedEvents = ['load', 'load'], expectedRequests = 1}) {
const token = 'style-' + rows.length;
const url = new URL('/probe-asset', location.href);
Object.entries({token, as: 'style', cache}).forEach(([key, value]) => url.searchParams.set(key, value));
if (crossOrigin) url.hostname = location.hostname === 'localhost' ? '127.0.0.1' : 'localhost';
const preload = document.createElement('link');
Object.assign(preload, {rel: 'preload', as: 'style', href: url.href, integrity: preloadIntegrity});
if (cors !== null) preload.crossOrigin = cors;
const preloaded = new Promise(resolve => { preload.onload = preload.onerror = e => resolve(e.type); });
document.head.append(preload);
await fetch('/probe-started?token=' + token);
if (phase === 'complete') {
await fetch('/probe-release?token=' + token);
await preloaded;
}
const installedBeforeConsumer = document.styleSheets.length;
const consumer = document.createElement('link');
Object.assign(consumer, {rel: 'stylesheet', href: url.href, integrity: consumerIntegrity});
if (cors !== null) consumer.crossOrigin = cors;
// These fields are part of the stylesheet cache key, but not the preload key.
if (name === 'different-consumer-metadata') {
consumer.referrerPolicy = 'no-referrer';
consumer.charset = 'utf-8';
}
let timingAtConsumer;
const consumed = new Promise(resolve => {
consumer.onload = consumer.onerror = e => {
timingAtConsumer = performance.getEntriesByName(url.href).length;
resolve(e.type);
};
});
document.head.append(consumer);
if (phase === 'pending') await fetch('/probe-release?token=' + token);
const events = await Promise.all([preloaded, consumed]);
let css;
try { css = consumer.sheet?.cssRules[0]?.style.getPropertyValue('--preload-value') || ''; }
catch (e) { css = e.name; }
const {count} = await (await fetch('/probe-stats?token=' + token)).json();
const timing = performance.getEntriesByName(url.href).map(e => e.initiatorType);
const expectedCss = expectedEvents[1] === 'error' ? '' : crossOrigin && cors === null ? 'SecurityError' : 'loaded';
rows.push({name, cache, phase, cors, crossOrigin, events, expectedEvents, count, expectedRequests,
timing, timingAtConsumer, installedBeforeConsumer, css, expectedCss});
consumer.remove();
preload.remove();
}
for (const cache of ['max-age=60', 'no-store'])
for (const phase of ['pending', 'complete'])
for (const cors of [null, 'anonymous', 'use-credentials'])
for (const crossOrigin of [false, true])
await run({cache, phase, cors, crossOrigin});
const cases = [
['good-empty', good, '', 'load', 'load', 1],
['bad-empty', bad, '', 'error', 'error', 1],
['bad-same', bad, bad, 'error', 'error', 1],
['bad-good', bad, good, 'error', 'load', 2],
['good-bad', good, bad, 'load', 'error', 2],
['good-options', good + '?ignored=option', good, 'load', 'load', 1],
['different-algorithm', good, weaker, 'load', 'load', 2],
['empty-good', '', good, 'load', 'load', 2],
['same-set-different-order', good + ' ' + weaker, weaker + ' ' + good, 'load', 'load', 1],
['different-weaker-hash', good + ' ' + weaker, good + ' sha256-AAAA', 'load', 'load', 2],
['different-consumer-metadata', good, '', 'load', 'load', 1],
['unknown-metadata', 'unknown-AAAA', '', 'load', 'load', 1],
];
for (const cache of ['max-age=60', 'no-store'])
for (const phase of ['pending', 'complete'])
for (const [name, preloadIntegrity, consumerIntegrity, preloadEvent, consumerEvent, expectedRequests] of cases)
await run({cache, phase, name, preloadIntegrity, consumerIntegrity,
expectedEvents: [preloadEvent, consumerEvent], expectedRequests});
return {rows, failures: rows.filter(r =>
JSON.stringify(r.events) !== JSON.stringify(r.expectedEvents) ||
r.timing.length !== r.expectedRequests ||
(r.expectedRequests === 1 && r.timingAtConsumer !== 1) ||
(r.cache === 'no-store' && r.count !== r.expectedRequests) ||
(r.expectedRequests === 1 && r.count !== 1) ||
r.installedBeforeConsumer !== 0 || r.css !== r.expectedCss)};
}
+2 -1
View File
@@ -9,5 +9,6 @@ self.addEventListener('fetch', e=>{
const kind=u.searchParams.get('source');
const target=new URL('/probe-asset'+u.search,self.location.href);
if(kind==='cors'||kind==='opaque')target.hostname=target.hostname==='localhost'?'127.0.0.1':'localhost';
e.respondWith(kind==='default'?new Response('globalThis.preloadExecuted=(globalThis.preloadExecuted||0)+1;',{headers:{'Content-Type':'text/javascript'}}):fetch(target,{mode:kind==='opaque'?'no-cors':'cors'}));
const style=u.searchParams.get('as')==='style';
e.respondWith(kind==='default'?new Response(style?'body { --preload-value: loaded; }':'globalThis.preloadExecuted=(globalThis.preloadExecuted||0)+1;',{headers:{'Content-Type':style?'text/css':'text/javascript'}}):fetch(target,{mode:kind==='opaque'?'no-cors':'cors'}));
});
@@ -93,6 +93,8 @@ impl PreloadServer {
cache = query.get("cache").cloned().unwrap_or(cache);
if query.get("as").is_some_and(|kind| kind == "image") {
("image/svg+xml", "<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'><rect width='1' height='1'/></svg>".to_owned())
} else if query.get("as").is_some_and(|kind| kind == "style") {
("text/css", "body { --preload-value: loaded; }".to_owned())
} else { ("text/javascript", SCRIPT.to_owned()) }
}
"/probe-started" | "/probe-release" | "/probe-stats" => {
@@ -118,6 +120,60 @@ impl PreloadServer {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn stylesheet_preloads_supply_pending_and_completed_consumers_and_integrity_failures()
-> 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 page = browser.fetch(&server.origin).await?;
let probe = include_str!("../fixtures/preload-consumption-style.js");
let result = tokio::time::timeout(
Duration::from_secs(30),
page.evaluate_runtime_expression_with_await_async(
&format!("({probe})().then(JSON.stringify)"),
true,
),
)
.await??;
let value: serde_json::Value = serde_json::from_str(
result["value"]
.as_str()
.context("stylesheet preload consumption results")?,
)?;
assert_eq!(value["rows"].as_array().unwrap().len(), 72);
assert_eq!(value["failures"], serde_json::json!([]));
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn stylesheet_preload_consumption_preserves_service_worker_filters_without_redispatch()
-> 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 page = browser.fetch(&server.origin).await?;
let probe = include_str!("../fixtures/preload-consumption-style-sw.js");
let result = tokio::time::timeout(
Duration::from_secs(30),
page.evaluate_runtime_expression_with_await_async(
&format!("({probe})().then(JSON.stringify)"),
true,
),
)
.await??;
let value: serde_json::Value = serde_json::from_str(
result["value"]
.as_str()
.context("Service Worker stylesheet preload results")?,
)?;
assert_eq!(value["rows"].as_array().unwrap().len(), 24);
assert_eq!(value["failures"], serde_json::json!([]));
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn document_preloads_supply_pending_and_completed_consumers_including_failed_integrity()
-> Result<()> {
+10
View File
@@ -448,6 +448,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) consumed_preload_error: bool,
/// Exact request Document, independent of an element's current location.
pub(crate) document_owner: Option<crate::frame_owner_model::FrameDocumentTaskOwner>,
pub(crate) stylesheet_fetch: Option<crate::stylesheet_blocking::StylesheetFetch>,
@@ -2731,6 +2732,7 @@ mod tests {
.push_back(ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "link",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
@@ -2782,6 +2784,7 @@ mod tests {
.push_back(ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "link",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: Some(active_load.fetch().clone()),
blocking_operation: None,
@@ -2838,6 +2841,7 @@ mod tests {
.push_back(ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "link",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: Some(detached_load.fetch().clone()),
blocking_operation: None,
@@ -2894,6 +2898,7 @@ mod tests {
.push_back(ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "link",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: Some(detached_load.fetch().clone()),
blocking_operation: None,
@@ -3504,6 +3509,7 @@ mod tests {
network_results: vec![ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "link",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
@@ -3602,6 +3608,7 @@ mod tests {
network_results: vec![ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "css",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
@@ -3678,6 +3685,7 @@ mod tests {
network_results: vec![ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "css",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
@@ -3742,6 +3750,7 @@ mod tests {
network_results: vec![ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "css",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
@@ -3882,6 +3891,7 @@ mod tests {
.push_back(ConnectedLoadNetworkResult {
network_observed: false,
resource_timing_initiator_type: "link",
consumed_preload_error: false,
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
+14 -8
View File
@@ -191,6 +191,18 @@ pub(crate) struct DocumentPreloadConsumer {
}
impl DocumentPreloadConsumer {
pub(crate) fn try_response(&self) -> Option<PreloadResult> {
self.entry.result.lock().clone().map(|result| {
result.map(|mut preload| {
preload.response.preload_state = moli_fetch::ResponsePreloadState::Consumed {
filter: preload.response_filter.clone().map(Into::into),
from_service_worker: preload.from_service_worker,
};
preload
})
})
}
pub(crate) async fn into_completion(
self,
internal_id: u64,
@@ -231,14 +243,8 @@ impl DocumentPreloadConsumer {
let notified = self.entry.available.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if let Some(result) = self.entry.result.lock().clone() {
return result.map(|mut preload| {
preload.response.preload_state = moli_fetch::ResponsePreloadState::Consumed {
filter: preload.response_filter.clone().map(Into::into),
from_service_worker: preload.from_service_worker,
};
preload
});
if let Some(result) = self.try_response() {
return result;
}
notified.await;
}
@@ -2541,6 +2541,7 @@ impl ScriptVm {
let crate::document_runtime::ConnectedLoadNetworkResult {
network_observed,
resource_timing_initiator_type,
consumed_preload_error,
document_owner,
stylesheet_fetch,
blocking_operation: _,
@@ -2569,15 +2570,17 @@ impl ScriptVm {
} else {
!source_owners.is_empty()
};
performance_entries.push((
document_owner,
crate::context_bootstrap::ResourcePerformanceEntry::from_network_result(
request_url.as_str(),
resource_timing_initiator_type,
start_unix_millis,
&result,
),
));
if !consumed_preload_error {
performance_entries.push((
document_owner,
crate::context_bootstrap::ResourcePerformanceEntry::from_network_result(
request_url.as_str(),
resource_timing_initiator_type,
start_unix_millis,
&result,
),
));
}
if resource_type == SubresourceResourceType::Stylesheet && stylesheet_fetch.is_none() {
let validated_response = result
.as_ref()
+180 -10
View File
@@ -173,6 +173,68 @@ impl StylesheetFetcher for RendererStylesheetFetcher {
.page_network_policy()
.cache_disabled()
}
fn is_document_preload(&self, url: &Url) -> bool {
self.link_preload && matches!(url.scheme(), "http" | "https")
}
fn prepare_stylesheet_resource(
&self,
document_url: Url,
url: Url,
options: StylesheetFetchOptions,
) -> moli_stylesheet_blocking::PreparedStylesheetFetch {
let request_origin = self.loader.fetch_context().request_origin();
let request = stylesheet_readiness_request(
&document_url,
&request_origin,
&url,
&options,
self.request_resource_type,
self.link_preload,
None,
);
if !self.loader.request_client().author_styles_disabled()
&& let Some(consumer) = self
.loader
.request_client()
.consume_document_preload(&request)
{
return if let Some(response) = consumer.try_response() {
moli_stylesheet_blocking::PreparedStylesheetFetch::reused(
stylesheet_terminal_from_preload(&request_origin, &url, &options, response),
)
} else {
moli_stylesheet_blocking::PreparedStylesheetFetch::new(Box::pin(async move {
stylesheet_terminal_from_preload(
&request_origin,
&url,
&options,
consumer.response().await,
)
}))
};
}
let producer = self
.link_preload
.then(|| {
self.loader
.request_client()
.register_document_preload(&request)
})
.flatten();
let prepared = moli_stylesheet_blocking::PreparedStylesheetFetch::new(
self.fetch_stylesheet_resource(document_url, url, options.clone()),
);
if let Some(producer) = producer {
prepared.with_published_callback(move |terminal| {
producer.complete(stylesheet_preload_response(terminal, &options));
})
} else {
prepared
}
}
fn spawn_stylesheet_task(&self, task: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
self.loader.spawn_resource_task(task);
}
@@ -305,6 +367,26 @@ pub(crate) async fn fetch_stylesheet_readiness_with_service_worker(
loader.web_security_disabled(),
)
};
if let Some(preload) = loader.consume_document_preload(&request) {
let preload = preload.response().await;
if let Ok(preload) = &preload {
let response = &preload.response;
if let Some(check) = &csp_check {
for (index, redirect) in response.redirect_chain.iter().enumerate() {
if let Err(error) = check(&redirect.to_url, index + 1) {
return StylesheetFetchTerminal::network_error(error.to_string());
}
}
if response.redirected
&& let Err(error) =
check(&response.final_url, response.redirect_chain.len().max(1))
{
return StylesheetFetchTerminal::network_error(error.to_string());
}
}
}
return stylesheet_terminal_from_preload(&request_origin, &url, &options, preload);
}
if let Some(context) = service_worker_context {
match context
.browser_context_runtime
@@ -320,13 +402,23 @@ pub(crate) async fn fetch_stylesheet_readiness_with_service_worker(
.await
{
Ok(Some(response)) => {
let response_provenance = StylesheetResponseProvenance::ServiceWorker {
filter: response.response_filter,
let response_provenance = if response.from_network_fallback {
StylesheetResponseProvenance::Network
} else {
StylesheetResponseProvenance::ServiceWorker {
filter: response.response_filter,
}
};
return terminal_from_response(*response.response, response_provenance);
}
Ok(None) => {}
Err(error) => {
if error
.downcast_ref::<crate::network::preloads::ConsumedPreloadError>()
.is_some()
{
return StylesheetFetchTerminal::consumed_preload_error(error.to_string());
}
return StylesheetFetchTerminal::network_error(format!(
"failed to fetch stylesheet `{url}` through service worker: {error}"
));
@@ -417,6 +509,33 @@ pub(crate) async fn fetch_stylesheet_readiness_with_service_worker(
}
}
fn stylesheet_terminal_from_preload(
request_origin: &moli_url::WebOrigin,
url: &Url,
options: &StylesheetFetchOptions,
result: Result<crate::network::preloads::DocumentPreloadResponse, String>,
) -> StylesheetFetchTerminal {
match result {
Ok(preload) => {
let provenance = if preload.from_service_worker {
StylesheetResponseProvenance::ServiceWorker {
filter: preload.response_filter,
}
} else {
StylesheetResponseProvenance::Network
};
stylesheet_terminal_from_response(
request_origin,
url,
options,
preload.response,
provenance,
)
}
Err(error) => StylesheetFetchTerminal::consumed_preload_error(error),
}
}
pub(crate) fn stylesheet_request_mode_and_credentials(
options: &StylesheetFetchOptions,
) -> (moli_fetch::RequestMode, moli_fetch::RequestCredentialsMode) {
@@ -515,6 +634,28 @@ fn stylesheet_terminal_from_response(
response: crate::protocol_types::NavigationResponse,
response_provenance: StylesheetResponseProvenance,
web_security_disabled: bool,
) -> StylesheetFetchTerminal {
let terminal = classify_stylesheet_response(
request_origin,
request_url,
options,
response,
&response_provenance,
);
match response_provenance {
StylesheetResponseProvenance::Network => terminal,
StylesheetResponseProvenance::ServiceWorker { filter } => {
terminal.with_service_worker_response(filter.map(Into::into))
}
}
}
fn classify_stylesheet_response(
request_origin: &moli_url::WebOrigin,
request_url: &Url,
options: &StylesheetFetchOptions,
response: crate::protocol_types::NavigationResponse,
response_provenance: &StylesheetResponseProvenance,
) -> StylesheetFetchTerminal {
let (request_mode, credentials_mode) = options.request_mode_and_credentials();
let head = response.head();
@@ -577,15 +718,44 @@ pub(crate) fn stylesheet_preload_fetch_is_successful(
terminal: &StylesheetFetchTerminal,
options: &StylesheetFetchOptions,
) -> bool {
let moli_stylesheet_blocking::StylesheetPhysicalOutcome::Response(response) =
terminal.physical()
else {
return false;
validated_stylesheet_preload_response(terminal, options).is_ok()
}
fn stylesheet_preload_response(
terminal: &StylesheetFetchTerminal,
options: &StylesheetFetchOptions,
) -> Result<crate::network::preloads::DocumentPreloadResponse, String> {
let response =
validated_stylesheet_preload_response(terminal, options).map_err(str::to_owned)?;
// MIME interpretation and HTTP success belong to the stylesheet consumer.
// Preserve the fetch response even when it cannot be installed as CSS.
Ok(crate::network::preloads::DocumentPreloadResponse {
response: response.clone(),
from_service_worker: terminal.from_service_worker(),
response_filter: terminal.response_filter().cloned().map(Into::into),
})
}
fn validated_stylesheet_preload_response<'a>(
terminal: &'a StylesheetFetchTerminal,
options: &StylesheetFetchOptions,
) -> Result<&'a crate::protocol_types::NavigationResponse, &'a str> {
if terminal.failed_integrity() {
return Err("preload response failed its integrity check");
}
if options.request_mode_and_credentials().0 == moli_fetch::RequestMode::Cors
&& terminal.origin_clean() == Some(false)
{
return Err("preload response failed its CORS check");
}
let response = match terminal.physical() {
StylesheetPhysicalOutcome::Response(response) => response,
StylesheetPhysicalOutcome::NetworkError(error) => return Err(error),
};
!terminal.failed_integrity()
&& (options.request_mode_and_credentials().0 != moli_fetch::RequestMode::Cors
|| terminal.origin_clean() != Some(false))
&& !should_response_be_blocked_due_to_nosniff(&response.headers, FetchDestination::Style)
if should_response_be_blocked_due_to_nosniff(&response.headers, FetchDestination::Style) {
return Err("preload response blocked by X-Content-Type-Options nosniff");
}
Ok(response)
}
pub(crate) fn validate_stylesheet_response(
@@ -453,6 +453,7 @@ impl DocumentRuntime {
} else {
"link"
},
consumed_preload_error: result.terminal.is_consumed_preload_error(),
document_owner,
stylesheet_fetch: result.fetch,
blocking_operation: result.blocking_operation,
@@ -1270,6 +1270,7 @@ impl DocumentRuntime {
resource_timing_initiator_type: preload_like_resource_initiator_type(
resource_type,
),
consumed_preload_error: false,
document_owner,
stylesheet_fetch: None,
blocking_operation: None,
@@ -4620,7 +4621,7 @@ mod tests {
}
#[tokio::test]
async fn pending_style_preload_and_stylesheet_clients_share_one_typed_fetch() {
async fn pending_style_preload_supplies_a_distinct_stylesheet_consumer() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("stylesheet server");
@@ -4685,20 +4686,36 @@ mod tests {
.expect("stylesheet client");
assert!(stylesheet_client.installs_stylesheet());
assert!(
preload_client.fetch().ptr_eq(stylesheet_client.fetch()),
"pending preload and stylesheet clients must join the exact typed resource"
!preload_client.fetch().ptr_eq(stylesheet_client.fetch()),
"the producer and consumer retain distinct stylesheet validation and ownership"
);
release_tx.send(()).expect("release stylesheet response");
assert!(
runtime.wait_for_stylesheet_networking_task_for_test().await,
"shared typed fetch should publish one Networking terminal"
);
runtime.drain_ready_connected_style_load_completions();
tokio::time::timeout(std::time::Duration::from_secs(2), async {
while preload_client.fetch().terminal().is_none()
|| stylesheet_client.fetch().terminal().is_none()
{
assert!(runtime.wait_for_stylesheet_networking_task_for_test().await);
runtime.drain_ready_connected_style_load_completions();
}
})
.await
.expect("preload and consumer should both settle");
server.await.expect("stylesheet server should finish");
let physical = runtime.take_ready_stylesheet_network_results();
assert_eq!(physical.len(), 1);
assert_eq!(physical.len(), 2);
assert_eq!(
physical
.iter()
.filter(|result| result
.result
.as_ref()
.is_ok_and(|response| !response.preload_state.is_consumed()))
.count(),
1,
"only the producer performed a physical request"
);
let terminals = runtime.take_ready_stylesheet_link_client_terminals();
assert_eq!(terminals.len(), 2);
assert_eq!(
@@ -4726,11 +4743,11 @@ mod tests {
assert_eq!(
ready_owners,
vec![preload.index(), stylesheet.index()],
"shared resource clients must be notified in registration order"
"preload publication must precede its waiting consumer"
);
assert!(
!runtime.apply_ready_stylesheet_networking_tasks_for_test(),
"shared clients must not leave a second physical completion"
"both producer and consumer completions must be drained"
);
}
@@ -36,6 +36,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",
consumed_preload_error: terminal.is_consumed_preload_error(),
document_owner: None,
stylesheet_fetch: None,
blocking_operation: None,
@@ -190,7 +190,7 @@ impl DocumentRuntime {
}
};
let request_url = load.request_url().clone();
let prepared = if terminal.failed_integrity() {
let prepared = if terminal.failed_integrity() || terminal.is_consumed_preload_error() {
None
} else {
host.prepare_linked_stylesheet_resource(
+95
View File
@@ -198,6 +198,9 @@ pub struct StylesheetFetchTerminal {
usability: StylesheetUsability,
origin_clean: Option<bool>,
network_observed: bool,
from_service_worker: bool,
response_filter: Option<moli_fetch::PreloadResponseFilter>,
consumed_preload_error: bool,
}
impl StylesheetFetchTerminal {
@@ -219,6 +222,9 @@ impl StylesheetFetchTerminal {
usability,
origin_clean: Some(origin_clean),
network_observed: false,
from_service_worker: false,
response_filter: None,
consumed_preload_error: false,
}
}
@@ -247,9 +253,40 @@ impl StylesheetFetchTerminal {
usability: StylesheetUsability::Failed { reason },
origin_clean: None,
network_observed: false,
from_service_worker: false,
response_filter: None,
consumed_preload_error: false,
}
}
pub fn consumed_preload_error(reason: impl Into<Arc<str>>) -> Self {
Self {
consumed_preload_error: true,
..Self::network_error(reason)
}
}
pub fn is_consumed_preload_error(&self) -> bool {
self.consumed_preload_error
}
pub fn with_service_worker_response(
mut self,
filter: Option<moli_fetch::PreloadResponseFilter>,
) -> Self {
self.from_service_worker = true;
self.response_filter = filter;
self
}
pub fn from_service_worker(&self) -> bool {
self.from_service_worker
}
pub fn response_filter(&self) -> Option<&moli_fetch::PreloadResponseFilter> {
self.response_filter.as_ref()
}
pub fn integrity_failure(
response: NavigationResponse,
origin_clean: bool,
@@ -295,6 +332,49 @@ impl StylesheetFetchTerminal {
}
}
type StylesheetResponseFuture =
Pin<Box<dyn Future<Output = StylesheetFetchTerminal> + Send + 'static>>;
type StylesheetPublishedCallback = Box<dyn FnOnce(&StylesheetFetchTerminal) + Send + 'static>;
pub(crate) enum PreparedStylesheetResponse {
Reused(StylesheetFetchTerminal),
Pending(StylesheetResponseFuture),
}
/// Prepared before spawning so a preload is discoverable by subsequent consumers.
/// The callback runs after the producer's completion has been queued, preserving
/// its observation order when publishing the response wakes a waiting consumer.
pub struct PreparedStylesheetFetch {
pub(crate) response: PreparedStylesheetResponse,
pub(crate) on_published: Option<StylesheetPublishedCallback>,
}
impl PreparedStylesheetFetch {
pub fn new(response: StylesheetResponseFuture) -> Self {
Self {
response: PreparedStylesheetResponse::Pending(response),
on_published: None,
}
}
/// Reuse an already observed response without introducing another task or
/// physical observation. A link can install this sheet during admission.
pub fn reused(terminal: StylesheetFetchTerminal) -> Self {
Self {
response: PreparedStylesheetResponse::Reused(terminal),
on_published: None,
}
}
pub fn with_published_callback(
mut self,
callback: impl FnOnce(&StylesheetFetchTerminal) + Send + 'static,
) -> Self {
self.on_published = Some(Box::new(callback));
self
}
}
pub trait StylesheetFetcher: Clone + Send + 'static {
/// Distinguishes environment-specific responses when a store serves several Documents.
fn resource_cache_scope(&self) -> u64 {
@@ -307,6 +387,21 @@ pub trait StylesheetFetcher: Clone + Send + 'static {
true
}
/// A link preload supplies the Document preload map, while speculative
/// ordinary stylesheets remain directly adoptable through this store.
fn is_document_preload(&self, _url: &Url) -> bool {
false
}
fn prepare_stylesheet_resource(
&self,
document_url: Url,
url: Url,
options: StylesheetFetchOptions,
) -> PreparedStylesheetFetch {
PreparedStylesheetFetch::new(self.fetch_stylesheet_resource(document_url, url, options))
}
/// An exact request-owner route overrides the store's default route.
/// The store captures this before spawning, so later Document replacement
/// cannot redirect an in-flight completion to another owner.
+3 -3
View File
@@ -30,9 +30,9 @@ pub use discovery::{
stylesheet_preload_link_request,
};
pub use fetcher::{
StylesheetFetch, StylesheetFetchIdentity, StylesheetFetchNetworkResult, StylesheetFetchOptions,
StylesheetFetchTerminal, StylesheetFetcher, StylesheetPhysicalOutcome, StylesheetResourceKey,
StylesheetUsability,
PreparedStylesheetFetch, StylesheetFetch, StylesheetFetchIdentity,
StylesheetFetchNetworkResult, StylesheetFetchOptions, StylesheetFetchTerminal,
StylesheetFetcher, StylesheetPhysicalOutcome, StylesheetResourceKey, StylesheetUsability,
};
pub use state::StylesheetBlockingState;
pub use types::{
+28 -13
View File
@@ -28,7 +28,7 @@ use crate::types::{
pub struct StylesheetBlockingState {
owner_fetches: HashMap<NodeId, StylesheetFetchEntry>,
blocking_entries: HashMap<NodeId, StylesheetBlockingEntry>,
url_fetches: HashMap<(u64, Url, StylesheetResourceKey), CachedStylesheetFetch>,
url_fetches: HashMap<(u64, Url, StylesheetResourceKey, bool), CachedStylesheetFetch>,
completion_source: OwnerTaskSource<StylesheetCompletion>,
ready_network_results: VecDeque<StylesheetFetchNetworkResult>,
// The stylesheet queue is local to document processing, not the renderer
@@ -366,10 +366,12 @@ impl StylesheetBlockingState {
{
let resource_cache_scope = fetcher.resource_cache_scope();
let resource_key = options.resource_key(url.clone());
let is_link_preload = fetcher.is_document_preload(&url);
if let Some(cached) = self.url_fetches.get_mut(&(
resource_cache_scope,
document_url.clone(),
resource_key.clone(),
is_link_preload,
)) {
let terminal = cached.fetch.terminal();
let failed_transfer = terminal.as_ref().is_some_and(|terminal| {
@@ -408,30 +410,43 @@ impl StylesheetBlockingState {
.or_else(|| self.completion_publisher.clone());
let completion_fetch = fetch.clone();
self.url_fetches.insert(
(resource_cache_scope, document_url.clone(), resource_key),
(
resource_cache_scope,
document_url.clone(),
resource_key,
is_link_preload,
),
CachedStylesheetFetch {
fetch: fetch.clone(),
unused_preload: preload,
},
);
let task_fetcher = fetcher.clone();
let prepared = fetcher.prepare_stylesheet_resource(document_url, request_url, options);
let response = match prepared.response {
crate::fetcher::PreparedStylesheetResponse::Reused(terminal) => {
fetch.finish(Arc::new(terminal));
return fetch;
}
crate::fetcher::PreparedStylesheetResponse::Pending(response) => response,
};
fetcher.spawn_stylesheet_task(Box::pin(async move {
let terminal = task_fetcher
.fetch_stylesheet_resource(document_url, request_url, options)
.await;
let terminal = response.await;
let completion = StylesheetCompletion::fetch(StylesheetFetchCompletion {
fetch: completion_fetch,
terminal,
terminal: terminal.clone(),
});
if let Some(publisher) = completion_publisher {
publisher(completion);
return;
} else {
let sent = sender.send(completion);
if sent.is_ok()
&& let Some(wake) = completion_wake
{
wake();
}
}
let sent = sender.send(completion);
if sent.is_ok()
&& let Some(wake) = completion_wake
{
wake();
if let Some(on_published) = prepared.on_published {
on_published(&terminal);
}
}));
fetch