diff --git a/moli-renderer-v8/src/network/backend/runtime.rs b/moli-renderer-v8/src/network/backend/runtime.rs index e10c2465ea8..5393692f810 100644 --- a/moli-renderer-v8/src/network/backend/runtime.rs +++ b/moli-renderer-v8/src/network/backend/runtime.rs @@ -4,7 +4,7 @@ use std::{ marker::PhantomData, rc::{Rc, Weak as RcWeak}, sync::{ - Arc, Weak as ArcWeak, + Arc, OnceLock, Weak as ArcWeak, atomic::{AtomicBool, AtomicU64, Ordering}, }, }; @@ -24,6 +24,7 @@ use crate::network::loads::{ DetachedKeepaliveLoadDiagnostics, DetachedKeepaliveLoadRegistry, ResourceLoadId, ResourceLoadKind, }; +use crate::network::task_runner::{RendererResourceTaskOwner, RendererResourceTaskRunner}; static NEXT_BROWSER_RESOURCE_RUNTIME_ID: AtomicU64 = AtomicU64::new(0); static NEXT_BROWSER_RESOURCE_OWNER_ROOT_ID: AtomicU64 = AtomicU64::new(0); @@ -65,7 +66,6 @@ pub struct BrowserResourceRuntimeOwner { runtime_id: u64, runtime: ArcWeak, fetch_owner: FetchClient, - resource_executor: Option, _thread_affine: PhantomData>, } @@ -92,6 +92,7 @@ struct BrowserResourceRuntimeOwnerSet { binding: BrowserResourceRuntimeBinding, active_runtime_id: Option, owners: Vec, + resource_task_owner: RendererResourceTaskOwner, terminal: bool, _thread_affine: PhantomData>, } @@ -147,7 +148,7 @@ struct BrowserResourceRuntimeInner { id: u64, owner_root_id: AtomicU64, client: FetchClientHandle, - task_runner: crate::network::RendererResourceTaskRunner, + resource_task_runner: OnceLock, memory_cache: Mutex, cors_preflight_cache: Mutex, disk_pool: Option, @@ -165,19 +166,6 @@ impl BrowserResourceRuntimeOwner { config: &FetchConfig, cookie_store: SharedBrowserCookieStore, ) -> BrowserResourceRuntimeOwnerRegistration { - // A browser-scoped resource executor keeps Send loading futures moving - // when a renderer or Worker synchronously waits. Its sole lifetime owner - // stays here, outside all cloneable request/Document handles. - let resource_executor = tokio::runtime::Builder::new_multi_thread() - .worker_threads(1) - .max_blocking_threads(crate::tokio_blocking_budget::tokio_blocking_thread_budget()) - .thread_name("moli-resources") - .enable_all() - .build() - .expect("browser resource executor should initialize"); - let task_runner = crate::network::RendererResourceTaskRunner::from_tokio_handle( - resource_executor.handle().clone(), - ); let fetch_owner = FetchClient::new(config, cookie_store); let runtime_id = NEXT_BROWSER_RESOURCE_RUNTIME_ID .fetch_add(1, Ordering::Relaxed) @@ -195,7 +183,7 @@ impl BrowserResourceRuntimeOwner { id: runtime_id, owner_root_id: AtomicU64::new(0), client: fetch_owner.handle(), - task_runner, + resource_task_runner: OnceLock::new(), memory_cache: Mutex::new(SharedMemoryResourceCache::default()), cors_preflight_cache: Mutex::new(CorsPreflightCache::default()), parkable_images, @@ -209,7 +197,6 @@ impl BrowserResourceRuntimeOwner { runtime_id, runtime: Arc::downgrade(&runtime.inner), fetch_owner, - resource_executor: Some(resource_executor), _thread_affine: PhantomData, }; BrowserResourceRuntimeOwnerRegistration { @@ -221,15 +208,37 @@ impl BrowserResourceRuntimeOwner { } impl BrowserResourceRuntime { - fn bind_owner_root(&self, root_id: u64) -> Result<(), BrowserResourceRuntimeOwnerError> { + pub(crate) fn task_runner(&self) -> RendererResourceTaskRunner { + self.inner + .resource_task_runner + .get() + .expect("registered browser resource runtime must have an executor") + .clone() + } + + fn bind_owner_root( + &self, + root_id: u64, + runner: RendererResourceTaskRunner, + ) -> Result<(), BrowserResourceRuntimeOwnerError> { match self.inner.owner_root_id.compare_exchange( 0, root_id, Ordering::AcqRel, Ordering::Acquire, ) { - Ok(_) => Ok(()), - Err(existing) if existing == root_id => Ok(()), + Ok(_) => { + self.inner + .resource_task_runner + .set(runner) + .expect("unregistered resource runtime cannot already have an executor"); + Ok(()) + } + Err(existing) + if existing == root_id && self.task_runner().shares_executor_with(&runner) => + { + Ok(()) + } Err(_) => Err(BrowserResourceRuntimeOwnerError::DifferentOwnerRoot), } } @@ -238,10 +247,6 @@ impl BrowserResourceRuntime { self.inner.owner_root_id.load(Ordering::Acquire) } - pub(crate) fn task_runner(&self) -> crate::network::RendererResourceTaskRunner { - self.inner.task_runner.clone() - } - pub fn cookie_store(&self) -> SharedBrowserCookieStore { self.inner.client.cookie_store() } @@ -417,14 +422,7 @@ impl BrowserResourceRuntimeOwner { } pub fn join(&mut self) -> FetchRuntimeJoinReport { - let report = self.fetch_owner.join(); - if let Some(executor) = self.resource_executor.take() { - // Owners can be disposed from an embedding Tokio runtime. Cancel - // outstanding Send futures without blocking or dropping a runtime - // inside another runtime's async context. - executor.shutdown_background(); - } - report + self.fetch_owner.join() } fn runtime_is_gone(&self) -> bool { @@ -435,9 +433,6 @@ impl BrowserResourceRuntimeOwner { impl Drop for BrowserResourceRuntimeOwner { fn drop(&mut self) { self.fetch_owner.request_shutdown(); - if let Some(executor) = self.resource_executor.take() { - executor.shutdown_background(); - } } } @@ -452,6 +447,7 @@ impl BrowserResourceRuntimeOwnerSet { root_id: u64, binding: BrowserResourceRuntimeBinding, owner: BrowserResourceRuntimeOwner, + resource_task_owner: RendererResourceTaskOwner, ) -> Self { assert_eq!( root_id, binding.root_id, @@ -467,6 +463,7 @@ impl BrowserResourceRuntimeOwnerSet { binding, active_runtime_id: Some(owner.runtime_id), owners: vec![owner], + resource_task_owner, terminal: false, _thread_affine: PhantomData, } @@ -480,7 +477,7 @@ impl BrowserResourceRuntimeOwnerSet { return Err(BrowserResourceRuntimeOwnerError::RootShutDown); } let (runtime, owner) = registration.into_parts(); - runtime.bind_owner_root(self.root_id)?; + runtime.bind_owner_root(self.root_id, self.resource_task_owner.runner())?; debug_assert_eq!(owner.runtime_id, runtime.runtime_id_for_diagnostics()); // This is one closed operation over a root-bound binding: no arbitrary @@ -572,14 +569,20 @@ impl BrowserResourceRuntimeOwnerSet { shutdown_and_join_resource_runtime_owners(&mut retired) } - fn shutdown_and_join(&mut self) { + fn shutdown_and_join(&mut self) -> Vec { if self.terminal && self.owners.is_empty() { - return; + return Vec::new(); } self.terminal = true; self.active_runtime_id = None; - let _ = shutdown_and_join_resource_runtime_owners(&mut self.owners); + for owner in &self.owners { + owner.request_shutdown(); + } + self.resource_task_owner.request_shutdown(); + let reports = shutdown_and_join_resource_runtime_owners(&mut self.owners); + self.resource_task_owner.join(); self.owners.clear(); + reports } #[cfg(test)] @@ -596,11 +599,20 @@ impl BrowserResourceRuntimeOwnerRoot { .fetch_add(1, Ordering::Relaxed) .saturating_add(1); let (runtime, owner) = initial.into_parts(); + // This executor belongs to the browser-context root, rather than one + // Fetch configuration generation. A live Document may retain its runner + // while its transport is replaced or an old Fetch owner is reaped. + let resource_task_owner = RendererResourceTaskOwner::new(); runtime - .bind_owner_root(root_id) + .bind_owner_root(root_id, resource_task_owner.runner()) .expect("initial browser resource runtime must be unregistered"); let binding = BrowserResourceRuntimeBinding::new(root_id, runtime); - let owners = BrowserResourceRuntimeOwnerSet::new(root_id, binding.clone(), owner); + let owners = BrowserResourceRuntimeOwnerSet::new( + root_id, + binding.clone(), + owner, + resource_task_owner, + ); ( Self { inner: Rc::new(RefCell::new(owners)), @@ -623,20 +635,12 @@ impl BrowserResourceRuntimeOwnerRoot { } pub fn shutdown_and_join(&self) { - self.inner.borrow_mut().shutdown_and_join(); + let _ = self.inner.borrow_mut().shutdown_and_join(); } #[cfg(test)] pub(crate) fn shutdown_and_join_reports_for_testing(&self) -> Vec { - let mut owners = self.inner.borrow_mut(); - if owners.terminal && owners.owners.is_empty() { - return Vec::new(); - } - owners.terminal = true; - owners.active_runtime_id = None; - let reports = shutdown_and_join_resource_runtime_owners(&mut owners.owners); - owners.owners.clear(); - reports + self.inner.borrow_mut().shutdown_and_join() } #[cfg(test)] @@ -745,7 +749,7 @@ impl BrowserResourceRuntimeOwnerRegistrar { impl Drop for BrowserResourceRuntimeOwnerSet { fn drop(&mut self) { - self.shutdown_and_join(); + let _ = self.shutdown_and_join(); } } @@ -801,6 +805,71 @@ mod tests { BrowserResourceRuntimeOwner::new(&FetchConfig::default(), new_shared_browser_cookie_store()) } + #[test] + fn resource_tasks_progress_without_polling_the_owner_and_cannot_outlive_shutdown() { + struct PendingTask(std_mpsc::Sender<()>); + impl Drop for PendingTask { + fn drop(&mut self) { + let _ = self.0.send(()); + } + } + + let (root, binding) = BrowserResourceRuntimeOwnerRoot::new(registration()); + let runtime = binding.current(); + let runner = runtime.task_runner(); + assert!(runner.shares_executor_with(&runtime.clone().task_runner())); + let (progress_tx, progress_rx) = std_mpsc::channel(); + let (dropped_tx, dropped_rx) = std_mpsc::channel(); + let job = runner.spawn_abortable(async move { + let _pending = PendingTask(dropped_tx); + tokio::time::sleep(Duration::from_millis(10)).await; + progress_tx.send(()).unwrap(); + std::future::pending::<()>().await; + }); + + // There is no entered or driven Tokio runtime on this owner thread. + progress_rx + .recv_timeout(Duration::from_secs(5)) + .expect("resource timers must progress while the owner is blocked"); + root.shutdown_and_join(); + dropped_rx + .try_recv() + .expect("joining the resource owner must drop pending futures"); + assert!(job.is_finished()); + + let (late_tx, late_rx) = std_mpsc::channel(); + let late = runner.spawn_abortable(async move { + let _ = late_tx.send(()); + }); + assert!(late.is_finished()); + assert_eq!( + late_rx.try_recv(), + Err(std_mpsc::TryRecvError::Disconnected) + ); + root.shutdown_and_join(); + } + + #[test] + fn fetch_runtime_replacement_keeps_the_browser_context_resource_executor() { + let (root, binding) = BrowserResourceRuntimeOwnerRoot::new(registration()); + let old_runtime = binding.current(); + let runner = old_runtime.task_runner(); + let replacement = root.registrar().replace_owned(registration()).unwrap(); + assert!(runner.shares_executor_with(&replacement.task_runner())); + + drop(old_runtime); + root.reap_retired(); + assert_eq!(root.owner_count_for_testing(), 1); + let (completed_tx, completed_rx) = std_mpsc::channel(); + runner.spawn(async move { + completed_tx.send(()).unwrap(); + }); + completed_rx + .recv_timeout(Duration::from_secs(5)) + .expect("a live Document runner must survive replacement of its Fetch runtime"); + root.shutdown_and_join(); + } + #[test] fn preflight_cache_clear_reaches_retired_leases_without_crossing_browser_contexts() { use crate::network::CorsPreflightResult; diff --git a/moli-renderer-v8/src/network/task_runner.rs b/moli-renderer-v8/src/network/task_runner.rs index 5896edbd795..483a8273672 100644 --- a/moli-renderer-v8/src/network/task_runner.rs +++ b/moli-renderer-v8/src/network/task_runner.rs @@ -1,4 +1,87 @@ -use std::{future::Future, sync::Arc}; +use std::{ + cell::RefCell, + future::Future, + marker::PhantomData, + rc::Rc, + sync::{Arc, mpsc}, + thread, +}; + +/// Browser-context-owned executor for native resource coordination. +/// +/// The renderer and Worker executors may spend an entire turn running author +/// JavaScript. Resource futures must continue submitting requests and consuming +/// native responses during that turn. Only this thread-affine owner can stop +/// and join the executor; request-side runners cannot extend its lifetime. +#[derive(Debug)] +pub(in crate::network) struct RendererResourceTaskOwner { + runner: RendererResourceTaskRunner, + shutdown: RefCell>>, + thread: Option>, + _thread_affine: PhantomData>, +} + +impl RendererResourceTaskOwner { + pub(in crate::network) fn new() -> Self { + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let (ready_tx, ready_rx) = mpsc::sync_channel(1); + let thread = thread::Builder::new() + .name("lm-resource-io".to_owned()) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .max_blocking_threads( + crate::tokio_blocking_budget::tokio_blocking_thread_budget(), + ) + .build() + .expect("browser resource executor should initialize"); + if ready_tx.send(runtime.handle().clone()).is_ok() { + let _ = runtime.block_on(shutdown_rx); + } + // Dropping the runtime cancels pending futures and joins its + // blocking pool before the owner joins this thread. + }) + .expect("browser resource executor thread should start"); + let handle = match ready_rx.recv() { + Ok(handle) => handle, + Err(error) => { + let _ = thread.join(); + panic!("browser resource executor did not initialize: {error}"); + } + }; + Self { + runner: RendererResourceTaskRunner::from_tokio_handle(handle), + shutdown: RefCell::new(Some(shutdown_tx)), + thread: Some(thread), + _thread_affine: PhantomData, + } + } + + pub(in crate::network) fn runner(&self) -> RendererResourceTaskRunner { + self.runner.clone() + } + + pub(in crate::network) fn request_shutdown(&self) { + if let Some(shutdown) = self.shutdown.borrow_mut().take() { + let _ = shutdown.send(()); + } + } + + pub(in crate::network) fn join(&mut self) { + self.request_shutdown(); + if let Some(thread) = self.thread.take() + && thread.join().is_err() + { + tracing::error!("browser resource executor panicked"); + } + } +} + +impl Drop for RendererResourceTaskOwner { + fn drop(&mut self) { + self.join(); + } +} /// Executor selected by a concrete resource-loading authority. /// @@ -12,7 +95,9 @@ pub struct RendererResourceTaskRunner { } impl RendererResourceTaskRunner { - /// Captures the runtime that owns a production execution context. + /// Captures an explicitly supplied runtime, including test executors. + /// Browser contexts supply their independent resource executor instead of + /// capturing the renderer's JavaScript executor. pub fn from_current_tokio() -> anyhow::Result { let handle = tokio::runtime::Handle::try_current().map_err(|error| { anyhow::anyhow!("resource authority requires a Tokio runtime: {error}") diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs index 4ec295d6c2e..19932e039ad 100644 --- a/moli-renderer-v8/src/runtime/page_vm/mod.rs +++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs @@ -1408,8 +1408,9 @@ impl PageVmRuntimeHooks { owner_wake: Some(owner_wake), page_creation_progress: None, resource_task_runner: Some( - crate::network::RendererResourceTaskRunner::from_current_tokio() - .expect("renderer owner must install its resource task runner"), + browser_context_runtime + .browser_resource_runtime() + .task_runner(), ), browser_context_runtime, document_lifecycle: None, diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rs index fa191df3162..a0558d35376 100644 --- a/moli-renderer-v8/src/runtime/phase_one/mod.rs +++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs @@ -102,6 +102,12 @@ use super::script_preloads::{BufferedDocumentPreloadState, ServiceWorkerScriptPr fn script_preloads_require_owner_admission(env: &PageVmEnvConfig) -> bool { !main_document_parser_scripting_enabled(env) + // Prebootstrap scans precede installation of the Document's request + // policy. Background IO must not submit these requests before the + // owner applies its headers, blocking rules and network conditions. + || !env.extra_http_headers.is_empty() + || !env.blocked_url_patterns.is_empty() + || env.network_offline || (cfg!(feature = "devtools") && env .fetch_subresource_interception_classes diff --git a/moli-renderer-v8/src/worker/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rs index daedd5daa55..3b26d8cca8d 100644 --- a/moli-renderer-v8/src/worker/thread/mod.rs +++ b/moli-renderer-v8/src/worker/thread/mod.rs @@ -1731,16 +1731,15 @@ async fn worker_main( ) { debug!(url = %script_url, "worker started"); let mut bootstrap_completion = WorkerBootstrapCompletionReporter::new(bootstrap_completion_tx); - let resource_task_runner = resource_task_runner.unwrap_or_else(|| { - RendererResourceTaskRunner::from_current_tokio() - .expect("Worker owner loop must expose its resource task runner") - }); + let resource_task_runner = resource_task_runner + .unwrap_or_else(|| request_client.browser_resource_runtime().task_runner()); let interception_context = Some( interception_context .map(|context| context.fork_worker_observer()) .unwrap_or_else(|| super::resource_output::unobserved(parent_tx.clone())), ); + let loader = resource_loader_for_worker_context( request_client, &network_policy, diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs index 863622fcdeb..637e9008d3c 100644 --- a/moli/tests/fetch_cli.rs +++ b/moli/tests/fetch_cli.rs @@ -61,6 +61,8 @@ mod markdown; mod readiness; #[path = "fetch_cli/redirect_chain.rs"] mod redirect_chain; +#[path = "fetch_cli/resource_io.rs"] +mod resource_io; #[path = "fetch_cli/subprocess.rs"] mod subprocess; #[path = "fetch_cli/timing.rs"] diff --git a/moli/tests/fetch_cli/resource_io.html b/moli/tests/fetch_cli/resource_io.html new file mode 100644 index 00000000000..a4996037bb9 --- /dev/null +++ b/moli/tests/fetch_cli/resource_io.html @@ -0,0 +1,44 @@ + + + diff --git a/moli/tests/fetch_cli/resource_io.rs b/moli/tests/fetch_cli/resource_io.rs new file mode 100644 index 00000000000..218eab2cd2c --- /dev/null +++ b/moli/tests/fetch_cli/resource_io.rs @@ -0,0 +1,84 @@ +use super::{clean_output, run_fetch_cli_with_args}; +use anyhow::Result; +use axum::{ + Router, + extract::{Path, State}, + response::Html, + routing::get, +}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +const PAGE: &str = include_str!("resource_io.html"); + +async fn body(State(received): State>, Path(scope): Path) -> &'static str { + received.fetch_or(scope_bit(&scope), Ordering::SeqCst); + "network-body" +} + +async fn observed( + State(received): State>, + Path(scope): Path, +) -> &'static str { + if received.load(Ordering::SeqCst) & scope_bit(&scope) != 0 { + "yes" + } else { + "no" + } +} + +fn scope_bit(scope: &str) -> usize { + match scope { + "window" => 1, + "worker" => 2, + _ => panic!("unexpected probe scope: {scope}"), + } +} + +#[test] +fn resource_io_runs_while_window_and_worker_javascript_are_busy() -> Result<()> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(32) + .enable_all() + .build()?; + let received = Arc::new(AtomicUsize::new(0)); + let (url, server) = runtime.block_on(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}/page", listener.local_addr()?); + let app = Router::new() + .route("/page", get(|| async { Html(PAGE) })) + .route("/body/{scope}", get(body)) + .route("/observed/{scope}", get(observed)) + .with_state(Arc::clone(&received)); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + Ok::<_, anyhow::Error>((url, server)) + })?; + let output = run_fetch_cli_with_args( + &url, + &[ + "--timeout", + "10000", + "--wait-script", + "document.body.dataset.resourceIo !== undefined", + ], + )?; + server.abort(); + assert!(runtime.block_on(server).unwrap_err().is_cancelled()); + + let stdout = clean_output(&output.stdout); + assert!( + output.status.success(), + "stdout={stdout}\nstderr={}", + clean_output(&output.stderr) + ); + assert!( + stdout.contains("window:yes:200:network-body:true|worker:yes:200:network-body:true"), + "requests must start during the JS task, with events dispatched after it: {stdout}" + ); + assert_eq!(received.load(Ordering::SeqCst), 3); + Ok(()) +}