diff --git a/moli-core/tests/scripts/child_module_records.rs b/moli-core/tests/scripts/child_module_records.rs new file mode 100644 index 00000000000..07357793080 --- /dev/null +++ b/moli-core/tests/scripts/child_module_records.rs @@ -0,0 +1,212 @@ +use super::*; + +pub(super) fn fixture_response(path: &str, cross: &str) -> (&'static str, String, String) { + let javascript = "Content-Type: text/javascript\r\nCache-Control: no-store\r\n"; + match path { + "/module-records.html" => ( + "200 OK", + "Content-Type: text/html\r\nCache-Control: no-store\r\n".to_owned(), + r#" + + + + + + + + "# + .to_owned(), + ), + "/module-record.js" => ( + "200 OK", + javascript.to_owned(), + format!( + "export const identity = {{}}; globalThis.moduleRecords.push(identity); \ + export const later = () => import('{cross}/echo-origin.js?child-record-later');" + ), + ), + "/module-record-tla.js" => ( + "200 OK", + javascript.to_owned(), + "globalThis.moduleStarts++; globalThis.moduleStarted(); \ + await globalThis.moduleGate; export const identity = {};" + .to_owned(), + ), + "/module-record-wrapper.js" => ( + "200 OK", + javascript.to_owned(), + "import {identity} from './module-record.js'; globalThis.wrapperRecord = identity;" + .to_owned(), + ), + "/module-record-redirect.js" => ( + "302 Found", + format!("{javascript}Location: /module-record.js\r\n"), + String::new(), + ), + _ => unreachable!("unexpected module record fixture: {path}"), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn child_module_scripts_reuse_records_within_each_realm() -> Result<()> { + let servers = IntegrityServers::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let mut page = browser + .fetch(&format!("{}/cookie-page.html", servers.origin)) + .await?; + let probe = r#"(async () => { + const check = (value, message) => { if (!value) throw new Error(message); }; + check(moduleRecords.length === 1, 'parser roots and static dependency share evaluation'); + check(moduleLoads === 4, 'each parser script receives its load event'); + check(inlineRuns === 2, 'identical inline scripts have independent records'); + const first = await import('/module-record.js'); + check(first.identity === moduleRecords[0], 'import reuses parser record'); + check(first.identity === wrapperRecord, 'static dependency uses same namespace'); + const attach = url => new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.type = 'module'; script.src = url; + script.crossOrigin = 'use-credentials'; + script.integrity = 'sha384-AAAA'; + script.onload = resolve; script.onerror = () => reject(new Error('script failed: ' + url)); + document.head.append(script); + }); + await Promise.all([attach('/module-record.js'), attach('/module-record.js')]); + check(first === await import('/module-record.js'), 'runtime consumers retain namespace identity'); + check(moduleRecords.length === 1, 'runtime consumers reuse evaluation'); + // The cached record retains the first script's anonymous credentials. + await first.later(); + const redirected = await import('/module-record-redirect.js'); + check(redirected !== first, 'different request URLs have separate module records'); + check(redirected.identity !== first.identity, 'redirect does not alias the request key'); + await Promise.all([attach('/module-record-redirect.js'), attach('/module-record-redirect.js')]); + check(redirected === await import('/module-record-redirect.js'), 'redirected record is reused'); + check(first === await import('/module-record.js'), 'redirect preserves original record'); + check(moduleRecords.length === 2, 'one evaluation per request URL'); + return true; + })()"#; + let expression = format!( + r#"(async () => {{ + const frames = []; + for (let i = 0; i < 2; i++) {{ + const frame = document.createElement('iframe'); + frame.src = '/module-records.html'; + await new Promise(resolve => {{ frame.onload = resolve; document.body.append(frame); }}); + if (await frame.contentWindow.eval({probe}) !== true) throw new Error('child probe'); + frames.push(frame.contentWindow); + }} + if (frames[0].moduleRecords[0] === frames[1].moduleRecords[0]) + throw new Error('record leaked between realms'); + if (!(frames[0].moduleRecords[0] instanceof frames[0].Object)) + throw new Error('record created in wrong realm'); + return globalThis.moduleRecords === undefined; + }})()"#, + probe = serde_json::to_string(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, + "{result}; {:?}", + servers.requests.lock() + ); + let requests = servers.requests.lock(); + for (path, count) in [ + ("/module-record.js", 4), + ("/module-record-wrapper.js", 2), + ("/module-record-redirect.js", 2), + ("/echo-origin.js?child-record-later", 2), + ] { + assert_eq!( + requests + .iter() + .filter(|request| request.path == path) + .count(), + count, + "{path}: {requests:?}" + ); + } + for request in requests + .iter() + .filter(|request| request.path == "/echo-origin.js?child-record-later") + { + assert_eq!( + request.cookie, None, + "cached module credentials: {request:?}" + ); + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn child_module_script_consumers_share_pending_evaluation() -> Result<()> { + let servers = IntegrityServers::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let mut page = browser + .fetch(&format!("{}/page.html", servers.origin)) + .await?; + let probe = r#"(async () => { + const check = (value, message) => { if (!value) throw new Error(message); }; + for (const fail of [false, true]) { + globalThis.moduleStarts = 0; + const started = new Promise(resolve => globalThis.moduleStarted = resolve); + let finish, reject; + globalThis.moduleGate = new Promise((resolve, fail) => { finish = resolve; reject = fail; }); + const url = '/module-record-tla.js?fail=' + fail; + const imported = import(url).then(value => ({value}), error => ({error})); + await started; + const loads = [0, 1].map(() => new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.type = 'module'; script.src = url; + script.onload = resolve; script.onerror = () => reject(new Error('script load')); + document.head.append(script); + })); + await Promise.all(loads); + check(moduleStarts === 1, 'consumers re-evaluated a pending module'); + const sentinel = {failure: true}; + if (fail) reject(sentinel); else finish(); + const first = await imported; + const second = await import(url).then(value => ({value}), error => ({error})); + if (fail) check(first.error === sentinel && second.error === sentinel, 'rejection identity'); + else check(first.value === second.value, 'fulfilled namespace identity'); + check(moduleStarts === 1, 'settled import restarted evaluation'); + } + return true; + })()"#; + let expression = format!( + r#"(async () => {{ + const frame = document.createElement('iframe'); + frame.src = '/page.html?child'; + await new Promise(resolve => {{ frame.onload = resolve; document.body.append(frame); }}); + return frame.contentWindow.eval({}); + }})()"#, + serde_json::to_string(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, + "{result}; {:?}", + servers.requests.lock() + ); + let requests = servers.requests.lock(); + for failed in [false, true] { + let path = format!("/module-record-tla.js?fail={failed}"); + assert_eq!( + requests + .iter() + .filter(|request| request.path == path) + .count(), + 1, + "{path}: {requests:?}" + ); + } + Ok(()) +} diff --git a/moli-core/tests/scripts/integrity.rs b/moli-core/tests/scripts/integrity.rs index b60f08dc14c..72dcc568792 100644 --- a/moli-core/tests/scripts/integrity.rs +++ b/moli-core/tests/scripts/integrity.rs @@ -28,6 +28,9 @@ mod preload; #[path = "runtime_modulepreload.rs"] mod runtime_modulepreload; +#[path = "child_module_records.rs"] +mod child_module_records; + struct IntegrityServers { origin: String, cross_origin: String, @@ -191,6 +194,11 @@ fn fixture_response( | "/child-sri-rejected.css" | "/child-sri-accepted.css" | "/child-sri-forbidden.css" => child_stylesheet_integrity::fixture_response(path, query), + "/module-records.html" + | "/module-record.js" + | "/module-record-tla.js" + | "/module-record-wrapper.js" + | "/module-record-redirect.js" => child_module_records::fixture_response(path, cross), "/module-response-started" | "/module-response-release" => ( "200 OK", "Content-Type: text/plain\r\nCache-Control: no-store\r\n".to_owned(), diff --git a/moli-core/tests/scripts/runtime_modulepreload.rs b/moli-core/tests/scripts/runtime_modulepreload.rs index ee0ca3026ae..b2b03981988 100644 --- a/moli-core/tests/scripts/runtime_modulepreload.rs +++ b/moli-core/tests/scripts/runtime_modulepreload.rs @@ -115,8 +115,7 @@ async fn runtime_modulepreloads_fetch_after_load_and_reuse_the_child_module_map( check_runtime_modulepreloads(true).await } -#[tokio::test(flavor = "multi_thread")] -async fn module_script_consumers_share_the_main_module_map() -> Result<()> { +async fn check_module_script_consumers(child: bool) -> Result<()> { let servers = IntegrityServers::spawn().await?; let browser = Browser::new(AppConfig::default())?; let mut page = browser @@ -172,15 +171,28 @@ async fn module_script_consumers_share_the_main_module_map() -> Result<()> { check(sriExecutions === beforeClassic + 2, 'classic scripts must each evaluate'); return true; })()"#; + let expression = if child { + format!( + r#"(async () => {{ + const frame = document.createElement('iframe'); + frame.src = '/page.html?child'; + await new Promise(resolve => {{ frame.onload = resolve; document.body.append(frame); }}); + return frame.contentWindow.eval({}); + }})()"#, + serde_json::to_string(probe)? + ) + } else { + probe.to_owned() + }; let result = tokio::time::timeout( Duration::from_secs(15), - page.evaluate_runtime_expression_with_await_async(probe, true), + page.evaluate_runtime_expression_with_await_async(&expression, true), ) .await??; assert_eq!( result["value"], true, - "{result}; requests={:?}", + "child={child}: {result}; requests={:?}", servers.requests.lock() ); let requests = servers.requests.lock(); @@ -225,6 +237,16 @@ async fn module_script_consumers_share_the_main_module_map() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread")] +async fn module_script_consumers_share_the_main_module_map() -> Result<()> { + check_module_script_consumers(false).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn module_script_consumers_share_the_child_module_map() -> Result<()> { + check_module_script_consumers(true).await +} + #[tokio::test(flavor = "multi_thread")] async fn module_script_map_reservations_preserve_service_worker_responses() -> Result<()> { let servers = IntegrityServers::spawn().await?; diff --git a/moli-renderer-v8/src/frame_owner_model.rs b/moli-renderer-v8/src/frame_owner_model.rs index b2b6dfde700..01e95c6c500 100644 --- a/moli-renderer-v8/src/frame_owner_model.rs +++ b/moli-renderer-v8/src/frame_owner_model.rs @@ -117,6 +117,7 @@ pub(crate) use module_clients::FrameDocumentParserModuleRootStartKind; pub(crate) use module_clients::FrameDocumentParserModuleRootStartTask; pub(crate) use module_clients::FrameDocumentParserRootModuleClient; pub(crate) use module_clients::FrameDocumentParserRootTerminalClient; +pub(crate) use module_clients::FrameDocumentParserRootTerminalResult; pub(crate) use module_clients::FrameDocumentParserRootTerminalWork; pub(crate) use module_clients::FrameDocumentStaticDependencyModuleClient; #[cfg(test)] diff --git a/moli-renderer-v8/src/frame_owner_model/module_clients.rs b/moli-renderer-v8/src/frame_owner_model/module_clients.rs index 7d01f022bdf..6a293b19df7 100644 --- a/moli-renderer-v8/src/frame_owner_model/module_clients.rs +++ b/moli-renderer-v8/src/frame_owner_model/module_clients.rs @@ -1360,11 +1360,18 @@ pub(crate) enum FrameDocumentModuleFetchTerminalResult { Failed(String), } +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum FrameDocumentParserRootTerminalResult { + Fetched(ModuleGraphFetchedSource), + Compiled, + Failed(String), +} + #[derive(Clone, Debug)] pub(crate) struct FrameDocumentParserRootTerminalPayload { key: ModuleMapKey, client: FrameDocumentParserRootTerminalClient, - result: FrameDocumentModuleFetchTerminalResult, + result: FrameDocumentParserRootTerminalResult, } pub(crate) type FrameDocumentParserRootTerminalWork = @@ -1376,7 +1383,7 @@ impl FrameDocumentParserRootTerminalWork { realm_id: FrameRealmId, key: ModuleMapKey, client: FrameDocumentParserRootTerminalClient, - result: FrameDocumentModuleFetchTerminalResult, + result: FrameDocumentParserRootTerminalResult, ) -> Self { Self::new( owner, @@ -1400,7 +1407,7 @@ impl FrameDocumentParserRootTerminalWork { } #[cfg(test)] - pub(crate) fn result(&self) -> &FrameDocumentModuleFetchTerminalResult { + pub(crate) fn result(&self) -> &FrameDocumentParserRootTerminalResult { &self.payload().result } @@ -1411,7 +1418,7 @@ impl FrameDocumentParserRootTerminalWork { FrameRealmId, ModuleMapKey, FrameDocumentParserRootModuleClient, - FrameDocumentModuleFetchTerminalResult, + FrameDocumentParserRootTerminalResult, ) { let (owner, realm_id, payload) = self.into_parts(); ( diff --git a/moli-renderer-v8/src/frame_owner_model/module_graph/tests/followups.rs b/moli-renderer-v8/src/frame_owner_model/module_graph/tests/followups.rs index ae031319551..6c74c6604b0 100644 --- a/moli-renderer-v8/src/frame_owner_model/module_graph/tests/followups.rs +++ b/moli-renderer-v8/src/frame_owner_model/module_graph/tests/followups.rs @@ -1467,10 +1467,12 @@ fn module_script_terminal_runner_dispatches_parser_root_terminal_batch() { let root_url = Url::parse("https://module-owner-event-runner.test/root.js").expect("module url"); let key = ModuleMapKey::java_script(root_url.clone()); - let fetched = FrameDocumentModuleFetchTerminalResult::Fetched(ModuleGraphFetchedSource::new( - root_url.clone(), - ModuleSource::text("export const value = 1;".to_owned()), - )); + let fetched = crate::frame_owner_model::FrameDocumentParserRootTerminalResult::Fetched( + ModuleGraphFetchedSource::new( + root_url.clone(), + ModuleSource::text("export const value = 1;".to_owned()), + ), + ); let works = vec![ FrameDocumentParserRootTerminalWork::from_terminal_parts( task_owner, diff --git a/moli-renderer-v8/src/frame_owner_model/module_graph/tests/parser_roots.rs b/moli-renderer-v8/src/frame_owner_model/module_graph/tests/parser_roots.rs index 28a7c60dbd4..a6e5a5a9524 100644 --- a/moli-renderer-v8/src/frame_owner_model/module_graph/tests/parser_roots.rs +++ b/moli-renderer-v8/src/frame_owner_model/module_graph/tests/parser_roots.rs @@ -1,3 +1,5 @@ +use crate::frame_owner_model::FrameDocumentParserRootTerminalResult; + use super::*; use crate::frame_owner_model::FrameDocumentModuleScriptTerminalTask; @@ -112,11 +114,11 @@ fn child_parser_root_clients_fan_out_from_module_map_entry() { ); assert!(matches!( works[0].result(), - FrameDocumentModuleFetchTerminalResult::Fetched(_) + FrameDocumentParserRootTerminalResult::Fetched(_) )); assert!(matches!( works[1].result(), - FrameDocumentModuleFetchTerminalResult::Fetched(_) + FrameDocumentParserRootTerminalResult::Fetched(_) )); } @@ -164,7 +166,7 @@ fn child_parser_root_already_terminal_entries_emit_owner_tasks() { ); assert!(matches!( first_parser_root_work.result(), - FrameDocumentModuleFetchTerminalResult::Fetched(_) + FrameDocumentParserRootTerminalResult::Fetched(_) )); let already_fetched_reservation = store.reserve_parser_root_module_client( @@ -185,7 +187,7 @@ fn child_parser_root_already_terminal_entries_emit_owner_tasks() { let work = works.pop().expect("synthetic parser root terminal work"); assert!(matches!( work.result(), - FrameDocumentModuleFetchTerminalResult::Fetched(_) + FrameDocumentParserRootTerminalResult::Fetched(_) )); assert_eq!( work.parser_root_payload().script_handle(), @@ -226,7 +228,7 @@ fn child_parser_root_already_terminal_entries_emit_owner_tasks() { ); assert!(matches!( first_failed_work.result(), - FrameDocumentModuleFetchTerminalResult::Failed(_) + FrameDocumentParserRootTerminalResult::Failed(_) )); let already_failed_reservation = store.reserve_parser_root_module_client( @@ -249,7 +251,7 @@ fn child_parser_root_already_terminal_entries_emit_owner_tasks() { .expect("synthetic failed parser root terminal work"); assert!(matches!( work.result(), - FrameDocumentModuleFetchTerminalResult::Failed(_) + FrameDocumentParserRootTerminalResult::Failed(_) )); assert_eq!( work.parser_root_payload().script_handle(), diff --git a/moli-renderer-v8/src/module_runtime/frame_document_parser_tree.rs b/moli-renderer-v8/src/module_runtime/frame_document_parser_tree.rs index 79a6ff35853..a5976289420 100644 --- a/moli-renderer-v8/src/module_runtime/frame_document_parser_tree.rs +++ b/moli-renderer-v8/src/module_runtime/frame_document_parser_tree.rs @@ -11,8 +11,8 @@ use crate::frame_owner_model::{ FrameDocumentModuleClientEntryId, FrameDocumentModuleClientId, FrameDocumentModuleClientRegistration, FrameDocumentModuleClientReservation, FrameDocumentModuleDependencyFetchTask, FrameDocumentModuleFetchDisposition, - FrameDocumentModuleFetchTerminalResult, FrameDocumentParserRootModuleClient, - FrameDocumentParserRootTerminalClient, FrameDocumentParserRootTerminalWork, + FrameDocumentParserRootModuleClient, FrameDocumentParserRootTerminalClient, + FrameDocumentParserRootTerminalResult, FrameDocumentParserRootTerminalWork, FrameDocumentStaticDependencyModuleClient, FrameDocumentTaskOwner, FrameRealmId, }; use crate::planning::PreparedScript; @@ -127,10 +127,13 @@ impl NativeDocumentModulator { &self, key: &ModuleMapKey, successful: bool, - ) -> Option { + ) -> Option { let entry_id = self.entry_id(key)?; let entry = self.entry(entry_id); if successful { + if entry.usable_compiled_record_id().is_some() { + return Some(FrameDocumentParserRootTerminalResult::Compiled); + } let source = entry.source().cloned()?; let final_url = entry.effective_key().url().clone(); let response_referrer_policy = entry @@ -138,7 +141,7 @@ impl NativeDocumentModulator { .request_metadata .referrer_policy .clone(); - Some(FrameDocumentModuleFetchTerminalResult::Fetched( + Some(FrameDocumentParserRootTerminalResult::Fetched( ModuleGraphFetchedSource::new(final_url.clone(), source) .with_response_referrer_policy(response_referrer_policy), )) @@ -147,7 +150,7 @@ impl NativeDocumentModulator { .failure() .map(|error| error.message().to_owned()) .unwrap_or_else(|| "module map entry fetch failed".to_owned()); - Some(FrameDocumentModuleFetchTerminalResult::Failed(message)) + Some(FrameDocumentParserRootTerminalResult::Failed(message)) } } diff --git a/moli-renderer-v8/src/script_vm/child_module_script_terminal.rs b/moli-renderer-v8/src/script_vm/child_module_script_terminal.rs index f5517af331b..b4355e39279 100644 --- a/moli-renderer-v8/src/script_vm/child_module_script_terminal.rs +++ b/moli-renderer-v8/src/script_vm/child_module_script_terminal.rs @@ -6,16 +6,16 @@ use crate::{ FrameDocumentParserModuleTreeAdvanceDependencyFetchResult, FrameDocumentParserModuleTreeAdvanceFailureTrace, FrameDocumentParserModuleTreeAdvanceHooks, FrameDocumentParserModuleTreeAdvanceRunner, - FrameDocumentParserRootModuleClient, FrameDocumentParserRootTerminalWork, - FrameDocumentStaticDependencyModuleClient, FrameDocumentTaskOwner, FrameRealmId, - frame_document_parser_module_tree_advance_action, + FrameDocumentParserRootModuleClient, FrameDocumentParserRootTerminalResult, + FrameDocumentParserRootTerminalWork, FrameDocumentStaticDependencyModuleClient, + FrameDocumentTaskOwner, FrameRealmId, frame_document_parser_module_tree_advance_action, module_script_graph_failed_work_from_root_client, module_script_graph_failed_work_from_tree_job, trace_child_module_dependency_failure, trace_child_parser_module_root_failure, }, module_runtime::{ ModuleEntryId, ModuleFetchMetadata, ModuleGraphFetchedSource, ModuleLoadError, - ModuleLoadStage, ModuleMapKey, ModuleRequestRecord, ModuleSource, + ModuleLoadStage, ModuleMapEntryState, ModuleMapKey, ModuleRequestRecord, ModuleSource, NativeModuleGraphFetchRequest, NativeModuleGraphJobAdvance, NativeModuleTreeDocumentOwnerAdapter, NativeParserModuleTreeJobResume, }, @@ -33,6 +33,41 @@ struct ScriptVmParserModuleTreeAdvanceHooks<'vm> { vm: &'vm mut ScriptVm, } +struct ChildModuleRootRecord { + entry_id: ModuleEntryId, + key: ModuleMapKey, + base_url: Url, + requests: Vec, + fetch_metadata: ModuleFetchMetadata, +} + +// Terminal tasks may have been queued before another consumer compiled the +// module. Recheck the map at delivery, retaining its record and fetch options. +fn cached_module_root_record( + owner: &impl NativeModuleTreeDocumentOwnerAdapter, + key: &ModuleMapKey, +) -> Result, ModuleLoadError> { + let Some(entry_id) = owner.module_entry_id(key) else { + return Ok(None); + }; + match owner.module_entry_state(entry_id) { + ModuleMapEntryState::Compiled + | ModuleMapEntryState::Instantiated + | ModuleMapEntryState::Evaluating + | ModuleMapEntryState::Evaluated => Ok(Some(ChildModuleRootRecord { + entry_id, + key: owner.module_entry_key(entry_id), + base_url: owner.module_entry_url(entry_id), + requests: owner.module_requests(entry_id), + fetch_metadata: owner.module_effective_fetch_metadata(entry_id), + })), + ModuleMapEntryState::Failed => Err(owner.module_failure(entry_id).unwrap_or_else(|| { + ModuleLoadError::new(ModuleLoadStage::Fetch, "module previously failed to load") + })), + ModuleMapEntryState::Fetching | ModuleMapEntryState::Fetched => Ok(None), + } +} + impl<'vm> ChildModuleScriptTerminalOwner<'vm> { pub(super) fn new(vm: &'vm mut ScriptVm) -> Self { Self { vm } @@ -78,7 +113,7 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { realm_id, request_key, client, - FrameDocumentModuleFetchTerminalResult::Fetched(ModuleGraphFetchedSource::new( + FrameDocumentParserRootTerminalResult::Fetched(ModuleGraphFetchedSource::new( source_url, source, )), ) @@ -175,7 +210,7 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { self.apply_tree_advance(document_owner, realm_id, tree_id, resume, advance_result) } - fn compile_module_record_into_owner( + fn compile_or_reuse_module_record( &mut self, document_owner: FrameDocumentOwner, realm_id: FrameRealmId, @@ -184,13 +219,16 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { source: &ModuleSource, source_url: &Url, fetch_metadata: &ModuleFetchMetadata, - ) -> Result<(ModuleEntryId, ModuleMapKey, Vec), ModuleLoadError> { + ) -> Result { self.vm .with_current_child_module_tree_owner_or_module_load_error( document_owner, realm_id, source_url, |module_owner| { + if let Some(record) = cached_module_root_record(module_owner, &request_key)? { + return Ok(record); + } module_owner .compile_module_record(compile_key, source, source_url, fetch_metadata) .map(|(record, identity)| { @@ -202,7 +240,13 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { identity, fetch_metadata.clone(), ); - (entry_id, parent_key, requests) + ChildModuleRootRecord { + entry_id, + key: parent_key, + base_url: source_url.clone(), + requests, + fetch_metadata: fetch_metadata.clone(), + } }) }, ) @@ -319,10 +363,10 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { realm_id: FrameRealmId, request_key: ModuleMapKey, client: FrameDocumentParserRootModuleClient, - result: FrameDocumentModuleFetchTerminalResult, + result: FrameDocumentParserRootTerminalResult, ) -> FrameDocumentModuleScriptTerminalFollowup { - match result { - FrameDocumentModuleFetchTerminalResult::Fetched(fetched_source) => { + let record = match result { + FrameDocumentParserRootTerminalResult::Fetched(fetched_source) => { let compile_url = if client.source_is_external() { fetched_source.final_url().clone() } else { @@ -333,7 +377,6 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { } else { request_key.clone() }; - let root_source = fetched_source.source().clone(); let fetch_metadata = if client.source_is_external() { ModuleFetchMetadata::from_top_level_script_fetch_metadata( client.fetch_metadata(), @@ -344,87 +387,68 @@ impl<'vm> ChildModuleScriptTerminalOwner<'vm> { ) } .with_response_referrer_policy(fetched_source.response_referrer_policy()); - let compile_result = self.compile_module_record_into_owner( + self.compile_or_reuse_module_record( task_owner.document_owner(), realm_id, request_key.clone(), compile_key, - &root_source, + fetched_source.source(), &compile_url, &fetch_metadata, - ); - match compile_result { - Ok((entry_id, parent_key, requests)) => { - let tree_id = self.vm.record_compiled_child_parser_root( - task_owner, - realm_id, - client.pending_script_id(task_owner.document_owner()), - client.script().clone(), - client.script_handle(), - request_key, - compile_url.clone(), - entry_id, - parent_key, - requests, - fetch_metadata, - client.load_delay_token(), - ); - self.advance_tree_job( - task_owner.document_owner(), - realm_id, - tree_id, - &compile_url, - ) - } - Err(error) => { - trace_child_parser_module_root_failure( - task_owner, - realm_id, - client.script_handle(), - &request_key, - &error, - ); - let work = module_script_graph_failed_work_from_root_client( - task_owner, - realm_id, - client.pending_script_id(task_owner.document_owner()), - client.script().clone(), - client.script_handle(), - request_key, - client.load_delay_token(), - error, - ); - self.notify_graph_terminal_work( - FrameDocumentModuleScriptGraphNotification::failed(work), - ) - } - } + ) } - FrameDocumentModuleFetchTerminalResult::Failed(error) => { - let error = ModuleLoadError::new(ModuleLoadStage::Fetch, error) - .with_failed_resource(request_key.clone()); - trace_child_parser_module_root_failure( + FrameDocumentParserRootTerminalResult::Compiled => self + .vm + .with_current_child_module_tree_owner_or_module_load_error( + task_owner.document_owner(), + realm_id, + request_key.url(), + |module_owner| { + cached_module_root_record(module_owner, &request_key)?.ok_or_else(|| { + ModuleLoadError::new( + ModuleLoadStage::Compile, + "compiled child module terminal lost its module record", + ) + }) + }, + ), + FrameDocumentParserRootTerminalResult::Failed(error) => { + Err(ModuleLoadError::new(ModuleLoadStage::Fetch, error) + .with_failed_resource(request_key.clone())) + } + }; + let record = match record { + Ok(record) => record, + Err(error) => { + return self.handle_parser_root_start_failure( task_owner, realm_id, - client.script_handle(), - &request_key, - &error, - ); - let work = module_script_graph_failed_work_from_root_client( - task_owner, - realm_id, - client.pending_script_id(task_owner.document_owner()), - client.script().clone(), - client.script_handle(), request_key, - client.load_delay_token(), + client, error, ); - self.notify_graph_terminal_work(FrameDocumentModuleScriptGraphNotification::failed( - work, - )) } - } + }; + let tree_id = self.vm.record_compiled_child_parser_root( + task_owner, + realm_id, + client.pending_script_id(task_owner.document_owner()), + client.script().clone(), + client.script_handle(), + request_key, + record.base_url.clone(), + record.entry_id, + record.key, + record.requests, + record.fetch_metadata, + client.load_delay_token(), + ); + self.advance_tree_job( + task_owner.document_owner(), + realm_id, + tree_id, + &record.base_url, + ) } }