fix(preload): start runtime modulepreloads in their document

Start connected main-document modulepreloads during mutation commit using the
same module-map reservation and scheduling path as parser preloads. Route child
links through the existing Document/realm-owned modulepreload queue instead of
leaving their start requests in the main lifecycle accumulator.

Cover post-load JavaScript/JSON/CSS/text preloads, import reuse, asynchronous
load/error delivery, CORS and integrity failures, per-Window module maps, and
queued child starts retired by document.open.
This commit is contained in:
ldm0
2026-11-02 06:03:23 +08:00
parent a6de018613
commit 48fc8c571f
9 changed files with 369 additions and 42 deletions
+16
View File
@@ -19,6 +19,9 @@ mod preload;
#[path = "text_network.rs"]
mod text_modules;
#[path = "runtime_modulepreload.rs"]
mod runtime_modulepreload;
struct IntegrityServers {
origin: String,
cross_origin: String,
@@ -152,6 +155,19 @@ fn fixture_response(
"/document-referrer.html" | "/meta-policy.html" | "/meta-policy-fetch" => {
document_referrer_dispatch::fixture_response(path, query, request.referer.as_deref())
}
"/runtime-modulepreload.html" => (
"200 OK",
"Content-Type: text/html\r\n".to_owned(),
r#"<!doctype html><script type="importmap">{"integrity":{
"/echo-origin.js?map-integrity":"sha384-AAAA"
}}</script><body>runtime modulepreload"#
.to_owned(),
),
"/module.json" => (
"200 OK",
"Content-Type: application/json\r\nCache-Control: no-store\r\n".to_owned(),
"{\"answer\":42}".to_owned(),
),
"/text-module.txt" => (
"200 OK",
"Content-Type: application/octet-stream\r\nCache-Control: no-store\r\n".to_owned(),
@@ -0,0 +1,188 @@
use super::*;
async fn check_runtime_modulepreloads(child: bool) -> Result<()> {
let servers = IntegrityServers::spawn().await?;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&format!("{}/runtime-modulepreload.html", servers.origin))
.await?;
let probe = format!(
r#"(async () => {{
if (document.readyState !== 'complete')
await new Promise(resolve => addEventListener('load', resolve, {{once:true}}));
const check = (value, message) => {{ if (!value) throw new Error(message); }};
const preload = (href, as, integrity) => new Promise((resolve, reject) => {{
const link = document.createElement('link');
link.rel = 'modulepreload'; link.as = as; link.href = href;
if (integrity !== undefined) link.integrity = integrity;
const timeout = setTimeout(() => reject(new Error('no preload event: ' + href)), 3000);
const done = event => {{ clearTimeout(timeout); resolve(event.type); }};
link.onload = done; link.onerror = done;
document.head.append(link);
}});
const paths = ['/echo-origin.js?runtime', '/module.json?runtime',
'/style.css?runtime', '/text-module.txt?runtime'];
const types = ['script', 'json', 'style', 'text'];
const events = await Promise.all(paths.map((path, i) => preload(path, types[i])));
check(events.every(event => event === 'load'), 'preload load events: ' + events);
check(!globalThis.sriExecutions, 'preload evaluated JavaScript');
const js = await import(paths[0]);
check(js === await import(paths[0]), 'module namespace identity');
check(sriExecutions === 1, 'JavaScript must evaluate once');
check((await import(paths[1], {{with:{{type:'json'}}}})).default.answer === 42, 'JSON');
check((await import(paths[2], {{with:{{type:'css'}}}})).default instanceof CSSStyleSheet, 'CSS');
check((await import(paths[3], {{with:{{type:'text'}}}})).default === {script}, 'text');
check(await preload(paths[0], 'script') === 'load', 'already fetched module event');
const failures = await Promise.all([
preload('/missing.js?runtime', 'script'),
preload({cross} + '/script.js?runtime', 'script'),
preload('/echo-origin.js?bad-integrity', 'script', 'sha384-AAAA'),
preload('/echo-origin.js?map-integrity', 'script'),
preload('/echo-origin.js?invalid-as', 'image')
]);
check(failures.every(event => event === 'error'), 'preload errors: ' + failures);
return true;
}})()"#,
script = serde_json::to_string(SCRIPT)?,
cross = serde_json::to_string(&servers.cross_origin)?,
);
let expression = if child {
format!(
r#"(async () => {{
const frame = document.createElement('iframe');
frame.src = '/runtime-modulepreload.html?child';
await new Promise(resolve => {{ frame.onload = resolve; document.body.append(frame); }});
return frame.contentWindow.eval({});
}})()"#,
serde_json::to_string(&probe)?
)
} else {
probe
};
let result = tokio::time::timeout(
Duration::from_secs(15),
page.evaluate_runtime_expression_with_await_async(&expression, true),
)
.await??;
assert_eq!(
result["value"],
true,
"child={child}: {result}; requests={:?}",
servers.requests.lock()
);
let requests = servers.requests.lock();
for (path, destination) in [
("/echo-origin.js?runtime", "script"),
("/module.json?runtime", "json"),
("/style.css?runtime", "style"),
("/text-module.txt?runtime", "text"),
("/missing.js?runtime", "script"),
("/script.js?runtime", "script"),
("/echo-origin.js?bad-integrity", "script"),
("/echo-origin.js?map-integrity", "script"),
] {
let matching: Vec<_> = requests
.iter()
.filter(|request| request.path == path)
.collect();
assert_eq!(matching.len(), 1, "child={child}, {path}: {requests:?}");
assert_eq!(
matching[0].sec_fetch_dest.as_deref(),
Some(destination),
"{path}"
);
assert_eq!(
matching[0].sec_fetch_mode.as_deref(),
Some("cors"),
"{path}"
);
}
assert!(
!requests
.iter()
.any(|request| request.path.contains("invalid-as"))
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn runtime_modulepreloads_fetch_after_load_and_reuse_the_main_module_map() -> Result<()> {
check_runtime_modulepreloads(false).await
}
#[tokio::test(flavor = "multi_thread")]
async fn runtime_modulepreloads_fetch_after_load_and_reuse_the_child_module_map() -> Result<()> {
check_runtime_modulepreloads(true).await
}
#[tokio::test(flavor = "multi_thread")]
async fn runtime_modulepreloads_keep_document_maps_and_retire_queued_child_starts() -> Result<()> {
let servers = IntegrityServers::spawn().await?;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&format!("{}/page.html", servers.origin))
.await?;
let result = tokio::time::timeout(
Duration::from_secs(15),
page.evaluate_runtime_expression_with_await_async(
r#"(async () => {
if (document.readyState !== 'complete')
await new Promise(resolve => addEventListener('load', resolve, {once:true}));
const preload = (doc, path) => new Promise((resolve, reject) => {
const link = doc.createElement('link');
link.rel = 'modulepreload'; link.href = path;
const timeout = setTimeout(() => reject(new Error('no preload event: ' + path)), 3000);
link.onload = () => { clearTimeout(timeout); resolve(); };
link.onerror = () => { clearTimeout(timeout); reject(new Error('preload error: ' + path)); };
doc.head.append(link);
});
const path = '/echo-origin.js?separate-maps';
await preload(document, path);
const frame = document.createElement('iframe');
frame.src = '/page.html?child';
await new Promise(resolve => { frame.onload = resolve; document.body.append(frame); });
const child = frame.contentDocument;
await preload(child, path);
let retiredEvents = 0;
const oldLink = child.createElement('link');
oldLink.rel = 'modulepreload'; oldLink.href = '/echo-origin.js?retired-child';
oldLink.onload = oldLink.onerror = () => retiredEvents++;
child.head.append(oldLink);
// Retire the captured Document before its queued start can run.
child.open(); child.write('<!doctype html><head></head><body>replacement'); child.close();
await preload(child, '/echo-origin.js?replacement-child');
if (retiredEvents !== 0) throw new Error('retired child link received an event');
document.open(); document.write('<!doctype html><head></head><body>replacement'); document.close();
await preload(document, path);
if (globalThis.sriExecutions) throw new Error('preload executed');
await import(path);
if (sriExecutions !== 1) throw new Error('replacement module evaluation');
return true;
})()"#,
true,
),
).await??;
assert_eq!(
result["value"],
true,
"{result}; requests={:?}",
servers.requests.lock()
);
let requests = servers.requests.lock();
for (path, expected) in [
// document.open replaces the tree but retains the Window's module map.
("/echo-origin.js?separate-maps", 2),
("/echo-origin.js?retired-child", 0),
("/echo-origin.js?replacement-child", 1),
] {
assert_eq!(
requests
.iter()
.filter(|request| request.path == path)
.count(),
expected,
"{path}: {requests:?}"
);
}
Ok(())
}
@@ -2051,6 +2051,7 @@ pub(super) fn finish_runtime_mutation_effects(
);
let completed_clients = prime_result.take_completed_stylesheet_clients();
runtime.settle_stylesheet_link_clients_in_current_scope(scope, host_ptr, completed_clients);
runtime.start_connected_modulepreloads_in_current_scope(scope, host_ptr, &mut prime_result);
runtime
.pending_connected_style_load_prime_result
.extend(prime_result);
@@ -24,6 +24,14 @@ pub(crate) struct MainDocumentModulepreloadFetchOutcome {
}
impl MainDocumentModulepreloadFetchOutcome {
fn idle() -> Self {
Self {
job_run: None,
csp_violations: Vec::new(),
runtime_warning: None,
}
}
pub(crate) fn into_parts(
self,
) -> (
@@ -120,11 +128,39 @@ impl DocumentRuntime {
) -> std::result::Result<MainDocumentModulepreloadFetchOutcome, ModuleLoadError> {
let start = self.fetch_single_native_module_for_modulepreload(request)?;
let Some(request) = start.started_request() else {
return Ok(MainDocumentModulepreloadFetchOutcome {
job_run: None,
csp_violations: Vec::new(),
runtime_warning: None,
});
return Ok(MainDocumentModulepreloadFetchOutcome::idle());
};
self.schedule_reserved_main_document_modulepreload_fetch(
document_owner,
resource_scheduler,
request,
)
}
/// Register a connected link and start its fetch in the same insertion
/// turn. Cached results still deliver their link event through the Page
/// queue; no script runs while the DOM mutation is being committed.
pub(crate) fn start_main_document_modulepreload_link_fetch(
&mut self,
document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
resource_scheduler: &RendererResourceScheduler,
request: NativeModuleSingleFetchRequest,
link_client: std::sync::Arc<crate::module_runtime::NativeModulepreloadLinkClient>,
) -> std::result::Result<MainDocumentModulepreloadFetchOutcome, ModuleLoadError> {
if link_client
.main_document_event_owner()
.is_none_or(|owner| owner.owner() != document_owner)
{
return Ok(MainDocumentModulepreloadFetchOutcome::idle());
}
let (start, pending_event) = self
.fetch_single_native_module_for_modulepreload_link(request, link_client)?
.into_parts();
if let Some(event) = pending_event {
self.enqueue_ready_native_modulepreload_link_event(event.into_ready_event());
}
let Some(request) = start.started_request() else {
return Ok(MainDocumentModulepreloadFetchOutcome::idle());
};
self.schedule_reserved_main_document_modulepreload_fetch(
document_owner,
@@ -394,7 +394,7 @@ impl JsContextHost {
)
}
pub(in crate::native_bridge::context_host) fn queue_child_modulepreload_link_error_for_current_document(
pub(crate) fn queue_child_modulepreload_link_error_for_current_document(
&mut self,
handle: DomHandle,
link_handle: DomHandle,
@@ -441,7 +441,7 @@ impl JsContextHost {
)
}
pub(in crate::native_bridge::context_host) fn queue_child_modulepreload_fetch_for_current_document(
pub(crate) fn queue_child_modulepreload_fetch_for_current_document(
&mut self,
handle: DomHandle,
link_handle: DomHandle,
@@ -301,9 +301,18 @@ async fn failed_main_modulepreload_queues_joined_client_fanout_for_a_later_turn(
let document_url = Url::parse(&format!("{base_url}/failure-page.html")).unwrap();
let request_url = Url::parse(&format!("{base_url}/failed-main-modulepreload.mjs")).unwrap();
let (key, request) = modulepreload_request(&document_url, &request_url);
let link_client = NativeModulepreloadLinkClient::new(NativeNodeId::new(7101), key.clone());
let (mut page_vm, mut queue, mut wake_rx) =
page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url.clone());
let owner = page_vm
.vm()
.current_main_document_task_owner()
.expect("main owner");
let link = NativeNodeId::new(7101);
let link_client = NativeModulepreloadLinkClient::new_with_main_document_event_owner(
link,
key.clone(),
crate::frame_owner_model::DocumentLinkEventOwner::new(owner, link),
);
assert_eq!(
page_vm
@@ -48,13 +48,12 @@ use crate::module_runtime::{
NativeDocumentModulator, NativeDynamicImportSingleModuleClient, NativeDynamicModuleImportReady,
NativeModuleGraphJob, NativeModuleGraphJobAdvance, NativeModuleMapSingleModuleClient,
NativeModuleOwnerEvent, NativeModuleScriptSingleModuleClient, NativeModuleSingleFetchRequest,
NativeModulepreloadFetchStart, PendingDynamicModuleImport, ResolverScopeGuard,
WasmDependencyModuleMessages, WasmImportRecord, WasmModuleRecord,
ensure_wasm_dependency_module_namespace_ready, evaluate_wasm_synthetic_module,
module_identity_hash_from_v8_module, preserve_current_v8_module_exception,
resolve_evaluation_module_callback, resolve_evaluation_source_callback,
resolve_static_module_callback, resolve_static_source_callback, throw_wasm_link_error,
wasm_dependency_export_value,
PendingDynamicModuleImport, ResolverScopeGuard, WasmDependencyModuleMessages, WasmImportRecord,
WasmModuleRecord, ensure_wasm_dependency_module_namespace_ready,
evaluate_wasm_synthetic_module, module_identity_hash_from_v8_module,
preserve_current_v8_module_exception, resolve_evaluation_module_callback,
resolve_evaluation_source_callback, resolve_static_module_callback,
resolve_static_source_callback, throw_wasm_link_error, wasm_dependency_export_value,
};
use crate::module_script_continuation::{
MainParserDeferredClassicSourceLoadCompletion, MainParserDocumentOwner,
@@ -249,15 +249,20 @@ impl ScriptVm {
request: NativeModuleSingleFetchRequest,
link_client: std::sync::Arc<crate::module_runtime::NativeModulepreloadLinkClient>,
) -> std::result::Result<Option<crate::module_runtime::ModulePreloadJobRun>, String> {
let document_owner = self.current_main_document_task_owner().ok_or_else(|| {
"main modulepreload fetch started without a current Document owner".to_owned()
})?;
let resource_scheduler = self.resource_scheduler();
let outcome = self
.document_runtime
.fetch_single_native_module_for_modulepreload_link(request, link_client)
.start_main_document_modulepreload_link_fetch(
document_owner,
&resource_scheduler,
request,
link_client,
)
.map_err(|error| error.message().to_owned())?;
let (start, pending_event) = outcome.into_parts();
if let Some(pending_event) = pending_event {
self.enqueue_main_modulepreload_link_event(pending_event);
}
self.run_native_modulepreload_fetch_start_for_owner(start)
Ok(self.consume_main_document_modulepreload_fetch_outcome(outcome))
}
pub(super) fn enqueue_main_modulepreload_link_event(
&mut self,
@@ -287,27 +292,6 @@ impl ScriptVm {
self.document_runtime
.enqueue_ready_native_modulepreload_link_event(ready);
}
pub(super) fn run_native_modulepreload_fetch_start_for_owner(
&mut self,
start: NativeModulepreloadFetchStart,
) -> std::result::Result<Option<crate::module_runtime::ModulePreloadJobRun>, String> {
let Some(request) = start.started_request() else {
return Ok(None);
};
let document_owner = self.current_main_document_task_owner().ok_or_else(|| {
"main modulepreload fetch started without a current Document owner".to_owned()
})?;
let resource_scheduler = self.resource_scheduler();
let outcome = self
.document_runtime
.schedule_reserved_main_document_modulepreload_fetch(
document_owner,
&resource_scheduler,
request,
)
.map_err(|error| error.message().to_owned())?;
Ok(self.consume_main_document_modulepreload_fetch_outcome(outcome))
}
pub(crate) fn drain_ready_runtime_owned_module_owner_actions(
&mut self,
) -> Result<NativeModuleOwnerActions> {
@@ -257,6 +257,42 @@ impl ConnectedStyleOwnerKind {
}
impl DocumentRuntime {
pub(crate) fn start_connected_modulepreloads_in_current_scope(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut JsContextHost,
result: &mut ConnectedStyleLoadPrimeResult,
) {
let starts = std::mem::take(&mut result.modulepreload_starts);
if starts.is_empty() {
return;
}
let host = unsafe { &*host_ptr };
let Some(owner) = host.current_main_document_task_owner() else {
return;
};
let scheduler = host.resource_scheduler();
for start in starts {
let (request, client) = start.into_parts();
match self
.start_main_document_modulepreload_link_fetch(owner, &scheduler, request, client)
{
Ok(outcome) => {
let (_, violations, warning) = outcome.into_parts();
for violation in violations {
self.queue_content_security_policy_violation_event_best_effort(
scope, host_ptr, &violation,
);
}
if let Some(warning) = warning {
result.push_runtime_warning(warning);
}
}
Err(error) => result.push_runtime_warning(error.message()),
}
}
}
pub(crate) fn prime_parser_preload_link(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
@@ -991,6 +1027,10 @@ impl DocumentRuntime {
);
return result;
}
if is_modulepreload && self.queue_connected_child_modulepreload(handle, &url, host_ptr)
{
return result;
}
if let Some((key, preload)) = self.connected_modulepreload_request(handle, &url) {
let unchanged = self
.stylesheet_lifecycle
@@ -1880,6 +1920,60 @@ impl DocumentRuntime {
self.push_ready_connected_style_load(ready);
}
/// Child links use the child's modulator and exact Document/realm task
/// route. They must never reserve an entry in the main Document's map.
fn queue_connected_child_modulepreload(
&self,
handle: DomHandle,
url: &url::Url,
host_ptr: *mut JsContextHost,
) -> bool {
let Some(document) = self.dom_host.owner_document_handle(handle) else {
return false;
};
if document == self.dom_host.document_handle() || host_ptr.is_null() {
return false;
}
let host = unsafe { &mut *host_ptr };
let Some(child) = host.child_browsing_context_host_for_document_handle(document) else {
return false;
};
if !host.child_browsing_context_scripting_enabled(child)
|| connected_modulepreload_has_non_matching_media(&self.dom_host, handle)
{
return true;
}
if connected_modulepreload_invalid_as(&self.dom_host, handle).is_some() {
let _ = host.queue_child_modulepreload_link_error_for_current_document(child, handle);
return true;
}
let Some(initiator) = host.child_browsing_context_request_initiator_url(child) else {
return true;
};
let integrity = host
.current_child_document_module_fetch_target(child)
.and_then(|target| {
host.resolve_frame_document_module_integrity(
target.task_owner().document_owner(),
target.realm_id(),
url,
)
});
let Some(element) = self.dom_host.node(handle).and_then(Node::as_element) else {
return true;
};
if let Some(candidate) =
modulepreload_fetch_candidate(element, url.clone(), &initiator, integrity)
{
let _ = host.queue_child_modulepreload_fetch_for_current_document(
child,
handle,
candidate.request,
);
}
true
}
fn connected_modulepreload_request(
&self,
handle: DomHandle,