Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat: follow HTTP error replacement navigations

ldm0eb4b7e4a36ac
diff --git a/moli-core/src/renderer.rs b/moli-core/src/renderer.rs
index c4d80abbd..5a1eaa4dc 100644
--- a/moli-core/src/renderer.rs
+++ b/moli-core/src/renderer.rs
@@ -37,7 +37,7 @@ pub use moli_renderer_v8::{
RendererStyleSheetHeader, RendererStyleSheetInventoryUpdate, RendererStyleSheetPayload,
};
-pub use moli_renderer_v8::{PageVmInitStage, RendererPageCreationReplyBoundary};
+pub use moli_renderer_v8::{PageVmInitStage, RendererReplyBoundary};
pub(crate) struct MaterializedPageCreatedReply {
pub(crate) page: Page,
diff --git a/moli-core/src/runtime/lifecycle_fetch.rs b/moli-core/src/runtime/lifecycle_fetch.rs
new file mode 100644
index 000000000..c14674446
--- /dev/null
+++ b/moli-core/src/runtime/lifecycle_fetch.rs
@@ -0,0 +1,154 @@
+//! Core fetch bridge for synchronous renderer lifecycle-target decisions.
+//!
+//! The renderer owns the exact DCL/load boundary. This module owns the async
+//! host-side budget transition: the original fetch deadline remains active
+//! until the synchronous decider chooses `FollowNextDocument`, at which point a
+//! separate successor-navigation budget replaces it.
+
+use super::{
+ Browser, FetchedDocument, PageVmInitStage, RenderedDomWaitUntil, RendererLifecycleDecider,
+ RendererLifecycleDecision, RendererLifecycleSnapshot, RendererReplyBoundary,
+};
+use anyhow::{Context, Result, anyhow};
+use moli_fetch::Request;
+use std::{future::Future, time::Duration};
+use tokio::sync::oneshot;
+use tracing::warn;
+
+pub(super) struct FollowTimeout {
+ follow_rx: oneshot::Receiver<()>,
+ successor_timeout: Duration,
+}
+
+impl Browser {
+ /// Fetches an executable document with a synchronous one-shot policy at
+ /// the exact requested lifecycle target.
+ ///
+ /// The decision runs in the renderer owner turn that observes DCL/load;
+ /// it does not expose an intermediate Page or require a second owner
+ /// command. `successor_timeout` reserves the independent budget used
+ /// after a decision chooses to follow a successor Document.
+ pub async fn fetch_document_with_lifecycle_decider<F>(
+ &self,
+ request: Request,
+ wait_until: RenderedDomWaitUntil,
+ timeout: Duration,
+ successor_timeout: Duration,
+ decider: F,
+ ) -> Result<FetchedDocument>
+ where
+ F: FnOnce(RendererLifecycleSnapshot) -> Result<RendererLifecycleDecision> + Send + 'static,
+ {
+ anyhow::ensure!(
+ matches!(
+ wait_until,
+ RenderedDomWaitUntil::DomContentLoaded
+ | RenderedDomWaitUntil::Load
+ | RenderedDomWaitUntil::Done
+ ),
+ "a lifecycle decider requires DCL, load, or done"
+ );
+ let (follow_tx, follow_rx) = oneshot::channel();
+ let decider = RendererLifecycleDecider::new(move |target| {
+ let decision = decider(target)?;
+ if matches!(
+ decision,
+ RendererLifecycleDecision::FollowNextDocument { .. }
+ ) {
+ let _ = follow_tx.send(());
+ }
+ Ok(decision)
+ });
+ self.fetch_document_with_wait(
+ request,
+ wait_until,
+ timeout,
+ RendererReplyBoundary::Stage,
+ Some(decider),
+ Some(FollowTimeout {
+ follow_rx,
+ successor_timeout,
+ }),
+ )
+ .await
+ .with_context(|| {
+ anyhow!(
+ "failed while applying the {wait_until:?} lifecycle-target decision or following its successor navigation"
+ )
+ })
+ }
+
+ pub(super) async fn materialize_with_follow_timeout<T, F>(
+ &self,
+ raw_url: &str,
+ wait_until: RenderedDomWaitUntil,
+ timeout: Duration,
+ stage: PageVmInitStage,
+ initial_timeout: Duration,
+ extension: Option<FollowTimeout>,
+ future: F,
+ ) -> Result<T>
+ where
+ F: Future<Output = Result<T>>,
+ {
+ let Some(mut extension) = extension else {
+ return self
+ .fetch_document_wait_timeout(
+ raw_url,
+ wait_until,
+ timeout,
+ stage,
+ initial_timeout,
+ future,
+ )
+ .await;
+ };
+
+ let initial_deadline = tokio::time::Instant::now()
+ .checked_add(initial_timeout)
+ .unwrap_or_else(tokio::time::Instant::now);
+ let initial_deadline_sleep = tokio::time::sleep_until(initial_deadline);
+ tokio::pin!(initial_deadline_sleep);
+ tokio::pin!(future);
+
+ let follow = tokio::select! {
+ biased;
+ result = &mut future => return result,
+ selected = &mut extension.follow_rx => selected,
+ _ = &mut initial_deadline_sleep => {
+ return Err(self.fetch_document_wait_timeout_error(
+ raw_url, wait_until, timeout, stage,
+ ));
+ }
+ };
+
+ if follow.is_err() {
+ // Finish drops the extension sender in the same callback turn.
+ // Keep the original deadline while the Page creation reply is
+ // finalized; only Follow is allowed to replace this budget.
+ return match tokio::time::timeout_at(initial_deadline, &mut future).await {
+ Ok(result) => result,
+ Err(_) => {
+ Err(self.fetch_document_wait_timeout_error(raw_url, wait_until, timeout, stage))
+ }
+ };
+ }
+
+ match tokio::time::timeout(extension.successor_timeout, &mut future).await {
+ Ok(result) => result,
+ Err(_) => {
+ warn!(
+ url = %raw_url,
+ wait_until = ?wait_until,
+ timeout_ms = extension.successor_timeout.as_millis(),
+ stage = ?stage,
+ "successor navigation lifecycle target timed out"
+ );
+ Err(anyhow!(
+ "successor navigation to {stage:?} timed out after {} ms for `{raw_url}`",
+ extension.successor_timeout.as_millis()
+ ))
+ }
+ }
+ }
+}
diff --git a/moli-core/src/runtime/mod.rs b/moli-core/src/runtime/mod.rs
index 67568f515..678d80bef 100644
--- a/moli-core/src/runtime/mod.rs
+++ b/moli-core/src/runtime/mod.rs
@@ -1,3 +1,4 @@
+mod lifecycle_fetch;
mod navigation_engine;
pub mod storage_partition;
@@ -32,10 +33,11 @@ use url::Url;
pub use crate::renderer::ExternalRawDocumentBodyStream;
pub use crate::renderer::PageVmInitStage;
-pub use crate::renderer::RendererPageCreationReplyBoundary;
+pub use crate::renderer::RendererReplyBoundary;
pub use moli_renderer_v8::{
DetachedParserScriptFetchContinuation, RendererBrowserContextRuntime,
RendererBrowserContextRuntimeOwner, RendererBrowserContextRuntimeOwnerAccess,
+ RendererLifecycleDecider, RendererLifecycleDecision, RendererLifecycleSnapshot,
RendererPageReservationToken, RendererReservedServiceWorkerClient,
RendererServiceWorkerMainResourceFetch, RendererSharedWorkerRuntimeDiagnostics,
};
@@ -48,6 +50,8 @@ pub use navigation_engine::{
static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);
+use self::lifecycle_fetch::FollowTimeout;
+
fn wait_until_outer_timeout(wait_until: RenderedDomWaitUntil, timeout: Duration) -> Duration {
match wait_until {
RenderedDomWaitUntil::NetworkIdle | RenderedDomWaitUntil::DomStable => {
@@ -347,8 +351,13 @@ impl Browser {
&self,
request: Request,
) -> Result<FetchedDocument> {
- self.fetch_document_allow_http_error_internal(request, PageVmInitStage::Load, None)
- .await
+ self.fetch_document_allow_http_error_internal(
+ request,
+ PageVmInitStage::Load,
+ RendererReplyBoundary::Stage,
+ None,
+ )
+ .await
}
pub async fn fetch_request_allow_http_error_with_wait_until(
@@ -402,6 +411,26 @@ impl Browser {
request: Request,
wait_until: RenderedDomWaitUntil,
timeout: Duration,
+ ) -> Result<FetchedDocument> {
+ self.fetch_document_with_wait(
+ request,
+ wait_until,
+ timeout,
+ RendererReplyBoundary::Stage,
+ None,
+ None,
+ )
+ .await
+ }
+
+ async fn fetch_document_with_wait(
+ &self,
+ request: Request,
+ wait_until: RenderedDomWaitUntil,
+ timeout: Duration,
+ reply_boundary: RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
+ follow_timeout: Option<FollowTimeout>,
) -> Result<FetchedDocument> {
let stage = match wait_until {
RenderedDomWaitUntil::DomContentLoaded => PageVmInitStage::DomContentLoaded,
@@ -424,16 +453,19 @@ impl Browser {
let requested_url = request.url.clone();
if is_about_blank_url(&requested_url) {
return self
- .fetch_document_wait_timeout(
+ .materialize_with_follow_timeout(
&raw_url,
wait_until,
timeout,
stage,
outer_timeout,
+ follow_timeout,
self.materialize_static_html_page(
&raw_url,
requested_url,
stage,
+ reply_boundary,
+ lifecycle_decider,
Some((wait_until, timeout)),
String::new(),
),
@@ -478,16 +510,19 @@ impl Browser {
.checked_sub(timeout_started.elapsed())
.unwrap_or_default();
return self
- .fetch_document_wait_timeout(
+ .materialize_with_follow_timeout(
&raw_url,
wait_until,
timeout,
stage,
remaining_timeout,
+ follow_timeout,
self.materialize_streaming_raw_response_page(
&raw_url,
requested_url,
stage,
+ reply_boundary,
+ lifecycle_decider,
Some((wait_until, timeout)),
streaming_raw_response_from_navigation_response(response)?,
document_fetch_context_seed,
@@ -524,16 +559,19 @@ impl Browser {
.checked_sub(timeout_started.elapsed())
.unwrap_or_default();
let document_fetch_context_seed = navigation_loader.commit(response.final_url.clone())?;
- self.fetch_document_wait_timeout(
+ self.materialize_with_follow_timeout(
&raw_url,
wait_until,
timeout,
stage,
remaining_timeout,
+ follow_timeout,
self.materialize_streaming_raw_response_page(
&raw_url,
requested_url,
stage,
+ reply_boundary,
+ lifecycle_decider,
Some((wait_until, timeout)),
response,
document_fetch_context_seed,
@@ -670,7 +708,15 @@ impl Browser {
let requested_url = request.url.clone();
if is_about_blank_url(&requested_url) {
return self
- .materialize_static_html_page(&raw_url, requested_url, stage, wait, String::new())
+ .materialize_static_html_page(
+ &raw_url,
+ requested_url,
+ stage,
+ RendererReplyBoundary::Stage,
+ None,
+ wait,
+ String::new(),
+ )
.await;
}
let navigation_loader = NavigationResourceLoader::new(
@@ -695,6 +741,8 @@ impl Browser {
&raw_url,
requested_url,
stage,
+ RendererReplyBoundary::Stage,
+ None,
wait,
response,
document_fetch_context_seed,
@@ -711,6 +759,8 @@ impl Browser {
&raw_url,
requested_url,
stage,
+ RendererReplyBoundary::Stage,
+ None,
wait,
response,
document_fetch_context_seed,
@@ -731,7 +781,15 @@ impl Browser {
let requested_url = request.url.clone();
if is_about_blank_url(&requested_url) {
return self
- .materialize_static_html_page(&raw_url, requested_url, stage, wait, String::new())
+ .materialize_static_html_page(
+ &raw_url,
+ requested_url,
+ stage,
+ RendererReplyBoundary::Stage,
+ None,
+ wait,
+ String::new(),
+ )
.await;
}
let navigation_loader = NavigationResourceLoader::new(
@@ -755,6 +813,8 @@ impl Browser {
&raw_url,
requested_url,
stage,
+ RendererReplyBoundary::Stage,
+ None,
wait,
streaming_raw_response_from_navigation_response(response)?,
document_fetch_context_seed,
@@ -768,6 +828,8 @@ impl Browser {
&raw_url,
requested_url,
stage,
+ RendererReplyBoundary::Stage,
+ None,
wait,
response,
document_fetch_context_seed,
@@ -780,13 +842,22 @@ impl Browser {
&self,
request: Request,
stage: PageVmInitStage,
+ reply_boundary: RendererReplyBoundary,
wait: Option<(RenderedDomWaitUntil, Duration)>,
) -> Result<FetchedDocument> {
let raw_url = request.url.as_str().to_owned();
let requested_url = request.url.clone();
if is_about_blank_url(&requested_url) {
return self
- .materialize_static_html_page(&raw_url, requested_url, stage, wait, String::new())
+ .materialize_static_html_page(
+ &raw_url,
+ requested_url,
+ stage,
+ reply_boundary,
+ None,
+ wait,
+ String::new(),
+ )
.await
.map(FetchedDocument::Page);
}
@@ -818,6 +889,8 @@ impl Browser {
&raw_url,
requested_url,
stage,
+ reply_boundary,
+ None,
wait,
streaming_raw_response_from_navigation_response(response)?,
document_fetch_context_seed,
@@ -838,6 +911,8 @@ impl Browser {
&raw_url,
requested_url,
stage,
+ reply_boundary,
+ None,
wait,
response,
document_fetch_context_seed,
@@ -873,26 +948,38 @@ impl Browser {
match tokio::time::timeout(outer_timeout, future).await {
Ok(result) => result,
Err(_) => {
- warn!(
- url = %raw_url,
- wait_until = ?wait_until,
- timeout_ms = timeout.as_millis(),
- stage = ?stage,
- "fetch_document_allow_http_error_with_wait_until timed out"
- );
- Err(anyhow!(
- "fetch document allow-http-error wait_until {wait_until:?} timed out after {} ms for `{raw_url}`",
- timeout.as_millis()
- ))
+ Err(self.fetch_document_wait_timeout_error(raw_url, wait_until, timeout, stage))
}
}
}
+ fn fetch_document_wait_timeout_error(
+ &self,
+ raw_url: &str,
+ wait_until: RenderedDomWaitUntil,
+ timeout: Duration,
+ stage: PageVmInitStage,
+ ) -> anyhow::Error {
+ warn!(
+ url = %raw_url,
+ wait_until = ?wait_until,
+ timeout_ms = timeout.as_millis(),
+ stage = ?stage,
+ "fetch_document_allow_http_error_with_wait_until timed out"
+ );
+ anyhow!(
+ "fetch document allow-http-error wait_until {wait_until:?} timed out after {} ms for `{raw_url}`",
+ timeout.as_millis()
+ )
+ }
+
async fn materialize_static_html_page(
&self,
raw_url: &str,
requested_url: Url,
stage: PageVmInitStage,
+ reply_boundary: RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
wait: Option<(RenderedDomWaitUntil, Duration)>,
response_body: String,
) -> Result<Page> {
@@ -943,6 +1030,8 @@ impl Browser {
stage,
);
create_page_request.wpt_extensions_enabled = self.config.wpt_extensions_enabled();
+ create_page_request.reply_boundary = reply_boundary;
+ create_page_request.lifecycle_decider = lifecycle_decider;
create_page_request.indexed_db_manager = Some(self.partition.weak_indexed_db_manager());
create_page_request.storage_bucket_store = Some(self.partition.storage_bucket_store());
let reply = renderer_owner
@@ -967,6 +1056,8 @@ impl Browser {
raw_url: &str,
requested_url: Url,
stage: PageVmInitStage,
+ reply_boundary: RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
wait: Option<(RenderedDomWaitUntil, Duration)>,
response: StreamingRawResponse,
document_fetch_context_seed: DocumentFetchContextSeed,
@@ -1052,12 +1143,13 @@ impl Browser {
Vec::new(),
self.config.wpt_extensions_enabled(),
stage,
- moli_renderer_v8::RendererPageCreationReplyBoundary::LifecycleTarget,
+ reply_boundary,
moli_renderer_v8::RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- moli_renderer_v8::RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ moli_renderer_v8::RendererNavigationReplyPolicy::FollowBeforeReply,
None,
reserved_service_worker_client,
None,
+ lifecycle_decider,
)
.await
.with_context(|| anyhow!("failed to execute scripts for page `{raw_url}`"))?;
diff --git a/moli-core/src/runtime/navigation_engine.rs b/moli-core/src/runtime/navigation_engine.rs
index d6cf2cb75..50c0197d6 100644
--- a/moli-core/src/runtime/navigation_engine.rs
+++ b/moli-core/src/runtime/navigation_engine.rs
@@ -1700,7 +1700,7 @@ impl NavigationEngine {
fetch_subresource_interception_enabled: bool,
fetch_subresource_interception_resource_type: Option<SubresourceResourceType>,
stage: PageVmInitStage,
- reply_boundary: moli_renderer_v8::RendererPageCreationReplyBoundary,
+ reply_boundary: moli_renderer_v8::RendererReplyBoundary,
root_frame_id: Option<String>,
resource_source: CommittedDocumentResourceSource,
reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
@@ -1781,7 +1781,7 @@ impl NavigationEngine {
fetch_subresource_interception_enabled: bool,
fetch_subresource_interception_resource_type: Option<SubresourceResourceType>,
stage: PageVmInitStage,
- reply_boundary: moli_renderer_v8::RendererPageCreationReplyBoundary,
+ reply_boundary: moli_renderer_v8::RendererReplyBoundary,
root_frame_id: Option<String>,
resource_source: CommittedDocumentResourceSource,
reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
@@ -1830,10 +1830,11 @@ impl NavigationEngine {
stage,
reply_boundary,
moli_renderer_v8::RendererTopLevelNavigationDispatch::DelegateToBrowser,
- moli_renderer_v8::RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ moli_renderer_v8::RendererNavigationReplyPolicy::ReturnWithPendingNavigation,
root_frame_id,
reserved_service_worker_client,
main_document_commit,
+ None,
)
.await
.context("failed to prepare streaming raw page")?;
@@ -1892,7 +1893,7 @@ impl NavigationEngine {
fetch_subresource_interception_enabled,
fetch_subresource_interception_resource_type,
stage,
- moli_renderer_v8::RendererPageCreationReplyBoundary::LifecycleTarget,
+ moli_renderer_v8::RendererReplyBoundary::Stage,
None,
CommittedDocumentResourceSource::Synthetic,
None,
@@ -1928,7 +1929,7 @@ impl NavigationEngine {
fetch_subresource_interception_enabled: bool,
fetch_subresource_interception_resource_type: Option<SubresourceResourceType>,
stage: PageVmInitStage,
- reply_boundary: moli_renderer_v8::RendererPageCreationReplyBoundary,
+ reply_boundary: moli_renderer_v8::RendererReplyBoundary,
root_frame_id: Option<String>,
resource_source: CommittedDocumentResourceSource,
reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
@@ -2002,7 +2003,7 @@ impl NavigationEngine {
fetch_subresource_interception_enabled: bool,
fetch_subresource_interception_resource_type: Option<SubresourceResourceType>,
stage: PageVmInitStage,
- reply_boundary: moli_renderer_v8::RendererPageCreationReplyBoundary,
+ reply_boundary: moli_renderer_v8::RendererReplyBoundary,
root_frame_id: Option<String>,
resource_source: CommittedDocumentResourceSource,
reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
@@ -2156,7 +2157,7 @@ impl NavigationEngine {
options.fetch_subresource_interception_enabled,
options.fetch_subresource_interception_resource_type,
stage,
- moli_renderer_v8::RendererPageCreationReplyBoundary::LifecycleTarget,
+ moli_renderer_v8::RendererReplyBoundary::Stage,
options.root_frame_id,
options.resource_source,
None,
diff --git a/moli-core/tests/lifecycle_decision.rs b/moli-core/tests/lifecycle_decision.rs
new file mode 100644
index 000000000..b5c2a2beb
--- /dev/null
+++ b/moli-core/tests/lifecycle_decision.rs
@@ -0,0 +1,306 @@
+use moli_test_support as support;
+
+use anyhow::{Result, anyhow};
+use moli_core::{
+ page::Page,
+ runtime::{
+ Browser, BrowserConfig as AppConfig, FetchedDocument, PageVmInitStage,
+ RenderedDomWaitUntil, RendererLifecycleDecision,
+ },
+ testing::JsValueSnapshot,
+};
+use moli_fetch::Request;
+use parking_lot::Mutex;
+use std::sync::Arc;
+use support::FixtureServer;
+use tokio::time::Duration;
+
+fn executable_page(document: FetchedDocument) -> Result<Page> {
+ match document {
+ FetchedDocument::Page(page) => Ok(page),
+ FetchedDocument::Raw(document) => Err(anyhow!(
+ "expected an executable Page, got raw document status {}",
+ document.status()
+ )),
+ }
+}
+
+fn diagnostic_global<'a>(page: &'a Page, name: &str) -> Option<&'a JsValueSnapshot> {
+ page.script_execution().global(name)
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn lifecycle_decider_finishes_without_extra_owner_command() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let url = server.url("/wait-until-domcontentloaded-runtime-script-slow");
+
+ let observed_targets = Arc::new(Mutex::new(Vec::new()));
+ let observed_targets_for_decider = observed_targets.clone();
+ let mut page = executable_page(
+ browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get(&url)?,
+ RenderedDomWaitUntil::DomContentLoaded,
+ Duration::from_secs(5),
+ Duration::ZERO,
+ move |target| {
+ observed_targets_for_decider.lock().push(target);
+ Ok(RendererLifecycleDecision::Finish)
+ },
+ )
+ .await?,
+ )?;
+ assert_eq!(page.status(), 200);
+ {
+ let observed_targets = observed_targets.lock();
+ assert_eq!(observed_targets.len(), 1);
+ assert_eq!(observed_targets[0].stage, PageVmInitStage::DomContentLoaded);
+ assert_eq!(observed_targets[0].status, 200);
+ assert_eq!(observed_targets[0].final_url.as_str(), url);
+ }
+ assert!(
+ !page
+ .serialize_html_async()
+ .await?
+ .contains("id=\"late-dcl-script-slow\"")
+ );
+
+ browser
+ .wait_for_page_delay(&mut page, Duration::from_millis(500))
+ .await?;
+ assert!(
+ page.serialize_html_async()
+ .await?
+ .contains("id=\"late-dcl-script-slow\"")
+ );
+
+ server.shutdown().await;
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn lifecycle_decider_supports_static_about_blank() -> Result<()> {
+ let browser = Browser::new(AppConfig::default())?;
+ let observed_target = Arc::new(Mutex::new(None));
+ let observed_target_for_decider = observed_target.clone();
+ let page = executable_page(
+ browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get("about:blank")?,
+ RenderedDomWaitUntil::Done,
+ Duration::from_secs(1),
+ Duration::ZERO,
+ move |target| {
+ *observed_target_for_decider.lock() = Some(target);
+ Ok(RendererLifecycleDecision::Finish)
+ },
+ )
+ .await?,
+ )?;
+
+ assert_eq!(page.status(), 200);
+ assert_eq!(page.final_url().as_str(), "about:blank");
+ let observed_target = observed_target.lock();
+ let observed_target = observed_target.as_ref().unwrap();
+ assert_eq!(observed_target.stage, PageVmInitStage::Load);
+ assert_eq!(observed_target.status, 200);
+ assert_eq!(observed_target.final_url.as_str(), "about:blank");
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn follow_budget_does_not_extend_initial_stage_timeout() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let decider_was_called = Arc::new(Mutex::new(false));
+ let decider_was_called_in_hook = decider_was_called.clone();
+
+ let error = browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get(&server.url("/wait-until-domcontentloaded-runtime-script-very-slow"))?,
+ RenderedDomWaitUntil::Load,
+ Duration::from_millis(100),
+ Duration::from_secs(5),
+ move |_| {
+ *decider_was_called_in_hook.lock() = true;
+ Ok(RendererLifecycleDecision::Finish)
+ },
+ )
+ .await
+ .expect_err("a follow budget must not relax the initial Load deadline");
+
+ assert!(
+ format!("{error:#}").contains("timed out after 100 ms"),
+ "error={error:#}"
+ );
+ assert!(!*decider_was_called.lock());
+ server.shutdown().await;
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn lifecycle_decider_error_and_panic_retire_only_pending_page() -> Result<()> {
+ let browser = Browser::new(AppConfig::default())?;
+
+ let error = browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get("about:blank")?,
+ RenderedDomWaitUntil::Done,
+ Duration::from_secs(1),
+ Duration::ZERO,
+ |_| Err(anyhow!("policy rejected target")),
+ )
+ .await
+ .expect_err("a decision error must fail page creation");
+ assert!(
+ format!("{error:#}").contains("policy rejected target"),
+ "error={error:#}"
+ );
+
+ let error = browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get("about:blank")?,
+ RenderedDomWaitUntil::Done,
+ Duration::from_secs(1),
+ Duration::ZERO,
+ |_| -> Result<RendererLifecycleDecision> { panic!("policy panic sentinel") },
+ )
+ .await
+ .expect_err("a decision panic must fail page creation without unwinding the owner");
+ assert!(
+ format!("{error:#}").contains("lifecycle decider panicked: policy panic sentinel"),
+ "error={error:#}"
+ );
+
+ // The panic is contained to the failed pending Page; the same renderer
+ // owner must remain usable for the next creation.
+ let page = executable_page(
+ browser
+ .fetch_request_document_allow_http_error(Request::get("about:blank")?)
+ .await?,
+ )?;
+ assert_eq!(page.status(), 200);
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn http_error_navigation_wait_follows_same_url_reload_to_domcontentloaded() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let url = server.url("/wait-until-http-error-navigation");
+
+ let observed_target = Arc::new(Mutex::new(None));
+ let observed_target_for_decider = observed_target.clone();
+ let page = executable_page(
+ browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get(&url)?,
+ RenderedDomWaitUntil::DomContentLoaded,
+ Duration::from_secs(5),
+ Duration::from_secs(6),
+ move |target| {
+ *observed_target_for_decider.lock() = Some(target);
+ Ok(RendererLifecycleDecision::FollowNextDocument {
+ navigation_grace_ms: 1_000,
+ })
+ },
+ )
+ .await?,
+ )?;
+ {
+ let observed_target = observed_target.lock();
+ let observed_target = observed_target.as_ref().unwrap();
+ assert_eq!(observed_target.stage, PageVmInitStage::DomContentLoaded);
+ assert_eq!(observed_target.status, 403);
+ assert_eq!(observed_target.final_url.as_str(), url);
+ }
+ assert_eq!(page.status(), 200);
+ assert_eq!(page.final_url().as_str(), url);
+ assert_eq!(
+ diagnostic_global(&page, "httpErrorNavigationDcl"),
+ Some(&JsValueSnapshot::Bool(true))
+ );
+
+ server.shutdown().await;
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn http_error_navigation_wait_follows_same_url_reload_to_load() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let url = server.url("/wait-until-http-error-navigation");
+
+ let observed_target = Arc::new(Mutex::new(None));
+ let observed_target_for_decider = observed_target.clone();
+ let page = executable_page(
+ browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get(&url)?,
+ RenderedDomWaitUntil::Load,
+ Duration::from_secs(5),
+ Duration::from_secs(6),
+ move |target| {
+ *observed_target_for_decider.lock() = Some(target);
+ Ok(RendererLifecycleDecision::FollowNextDocument {
+ navigation_grace_ms: 1_000,
+ })
+ },
+ )
+ .await?,
+ )?;
+ {
+ let observed_target = observed_target.lock();
+ let observed_target = observed_target.as_ref().unwrap();
+ assert_eq!(observed_target.stage, PageVmInitStage::Load);
+ assert_eq!(observed_target.status, 403);
+ assert_eq!(observed_target.final_url.as_str(), url);
+ }
+ assert_eq!(page.status(), 200);
+ assert_eq!(page.final_url().as_str(), url);
+ assert_eq!(
+ diagnostic_global(&page, "httpErrorNavigationDcl"),
+ Some(&JsValueSnapshot::Bool(true))
+ );
+ assert_eq!(
+ diagnostic_global(&page, "httpErrorNavigationLoad"),
+ Some(&JsValueSnapshot::Bool(true))
+ );
+ assert_eq!(
+ diagnostic_global(&page, "httpErrorNavigationSlowScript"),
+ Some(&JsValueSnapshot::Bool(true))
+ );
+
+ server.shutdown().await;
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn http_error_navigation_wait_reports_no_navigation_without_refetching() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let url = server.url("/net/upstream/xhr/404-then-200");
+
+ let error = browser
+ .fetch_document_with_lifecycle_decider(
+ Request::get(&url)?,
+ RenderedDomWaitUntil::Load,
+ Duration::from_secs(5),
+ Duration::from_millis(1_100),
+ |target| {
+ assert_eq!(target.status, 404);
+ Ok(RendererLifecycleDecision::FollowNextDocument {
+ navigation_grace_ms: 100,
+ })
+ },
+ )
+ .await
+ .expect_err("a static 404 document must not be refetched or accepted");
+ let error = format!("{error:#}");
+ assert!(error.contains("404 Not Found"), "error={error}");
+ assert!(error.contains("100 ms grace period"), "error={error}");
+
+ server.shutdown().await;
+ Ok(())
+}
diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rs
index f9e8fe3a8..3210f3227 100644
--- a/moli-protocol/src/conn/runtime_load.rs
+++ b/moli-protocol/src/conn/runtime_load.rs
@@ -5,7 +5,7 @@ use moli_core::{
runtime::{
CommittedDocumentResourceSource, PageVmInitStage, PreparedDocumentPage,
PreparedDocumentPageCommitConfiguration, PreparedDocumentPageCommitPermit,
- RendererPageCreationReplyBoundary, RendererPageReservationToken,
+ RendererPageReservationToken, RendererReplyBoundary,
},
};
use moli_fetch::{
@@ -92,7 +92,7 @@ async fn prepare_browser_owned_error_page_navigation_with_engine_async(
request_headers: Vec<(String, String)>,
error_text: String,
body: CapturedBody,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Result<ResponseCommitReady, String> {
let error_page_url = Url::parse(NETWORK_ERROR_PAGE_URL)
.expect("the browser-owned network error page URL must be valid");
@@ -138,7 +138,7 @@ async fn prepare_network_error_page_navigation_with_engine_async(
request_method: String,
request_headers: Vec<(String, String)>,
error_text: String,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Result<NavigationLoadOutcome, String> {
let body = CapturedBody::from_string(network_error_page_html(&unreachable_url, &error_text));
prepare_browser_owned_error_page_navigation_with_engine_async(
@@ -855,7 +855,7 @@ impl BackgroundNavigationLoadJob {
&self.method,
&self.raw_url,
self.request_headers.clone(),
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
)
.await
{
@@ -871,7 +871,7 @@ impl BackgroundNavigationLoadJob {
&self.method,
&self.raw_url,
self.request_headers.clone(),
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
)
.await
{
@@ -941,7 +941,7 @@ impl BackgroundNavigationLoadJob {
self.method,
self.request_headers,
failure.network_error_text().to_owned(),
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
)
.await;
}
@@ -976,7 +976,7 @@ impl BackgroundNavigationLoadJob {
body_completion_sink,
reserved_service_worker_client,
CommittedDocumentResourceSource::Navigation(Box::new(document_fetch_context_seed)),
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
)
.await;
if defer_early_result_for_http_error_body {
@@ -1024,7 +1024,7 @@ impl BackgroundStreamingResponseNavigationLoadJob {
body_completion_sink,
None,
CommittedDocumentResourceSource::Synthetic,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
)
.await;
(engine, navigation)
@@ -1154,7 +1154,7 @@ async fn load_inline_html_navigation_with_engine_async(
method: &str,
raw_url: &str,
request_headers: Vec<(String, String)>,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Option<Result<NavigationLoadOutcome, String>> {
let source = inline_html_navigation_source(raw_url)?;
Some(
@@ -1204,7 +1204,7 @@ async fn load_data_url_navigation_with_engine_async(
method: &str,
raw_url: &str,
request_headers: Vec<(String, String)>,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Option<Result<NavigationLoadOutcome, String>> {
let source = decoded_data_url_navigation_response(raw_url)?;
Some(
@@ -1252,7 +1252,7 @@ async fn build_navigation_from_streaming_raw_response_with_engine_async(
body_completion_sink: Option<BackgroundNavigationBodyCompletionSink>,
reserved_service_worker_client: Option<moli_core::runtime::RendererReservedServiceWorkerClient>,
resource_source: CommittedDocumentResourceSource,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Result<NavigationLoadOutcome, String> {
let timing_enabled = moli_trace::cdp_nav_timing_enabled();
let timing_started = std::time::Instant::now();
@@ -1714,7 +1714,7 @@ impl CdpConnection {
fetch_subresource_interception_enabled,
fetch_subresource_interception_resource_type,
PageVmInitStage::DomContentLoaded,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
load_inputs.root_frame_id.clone(),
CommittedDocumentResourceSource::Synthetic,
None,
@@ -2291,7 +2291,7 @@ impl CdpConnection {
method,
raw_url,
request_headers.clone(),
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
{
@@ -2312,7 +2312,7 @@ impl CdpConnection {
method,
raw_url,
request_headers.clone(),
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
{
@@ -2326,7 +2326,7 @@ impl CdpConnection {
method,
raw_url,
request_headers.clone(),
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
{
@@ -2694,7 +2694,7 @@ impl CdpConnection {
method,
raw_url,
request_headers,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
}
@@ -2707,7 +2707,7 @@ impl CdpConnection {
method: &str,
raw_url: &str,
request_headers: Vec<(String, String)>,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Option<Result<NavigationLoadOutcome, String>> {
load_inline_html_navigation_with_engine_async(
engine,
@@ -2915,7 +2915,7 @@ impl CdpConnection {
network_observation_journal,
None,
false,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
.map(NavigationLoadOutcome::response_commit_ready)
@@ -3483,7 +3483,7 @@ impl CdpConnection {
network_observation_journal,
None,
false,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
.map(NavigationLoadOutcome::response_commit_ready)
@@ -3608,7 +3608,7 @@ impl CdpConnection {
None,
None,
CommittedDocumentResourceSource::Synthetic,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await;
}
@@ -3631,7 +3631,7 @@ impl CdpConnection {
None,
None,
CommittedDocumentResourceSource::Synthetic,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await?;
Ok(navigation.with_navigation_engine(engine))
@@ -3716,7 +3716,7 @@ async fn prepare_navigation_from_captured_raw_response_with_engine_async(
network_observation_journal: NetworkObservationJournal,
network_error_page: Option<NetworkErrorPageNavigation>,
synthetic_body: bool,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Result<ResponseCommitReady, String> {
let network_extra_info_available = !network_observation_journal.is_empty();
if network_error_page.is_none()
@@ -3785,7 +3785,7 @@ async fn prepare_captured_document_response_with_engine_async(
network_observation_journal: NetworkObservationJournal,
network_error_page: Option<NetworkErrorPageNavigation>,
synthetic_body: bool,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> Result<ResponseCommitReady, String> {
let network_extra_info_available = !network_observation_journal.is_empty();
body_progress_source.emit_response_metadata(
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index 59f4db242..5fc19b2e7 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -250,8 +250,9 @@ pub use runtime::{
RendererGeometryQuad, RendererInputDispatchOutcome, RendererInspectorProtocolConfiguration,
RendererInspectorProtocolConfigurationCommand, RendererInspectorSessionRestoreSnapshot,
RendererJavaScriptDialogCompletion, RendererJavaScriptDialogId, RendererJavaScriptDialogResult,
- RendererJavaScriptDialogSource, RendererLayoutMetrics, RendererLifecycleEpoch,
- RendererLifecycleEventStamp, RendererLifecycleStartReason, RendererLifecycleTerminationStamp,
+ RendererJavaScriptDialogSource, RendererLayoutMetrics, RendererLifecycleDecider,
+ RendererLifecycleDecision, RendererLifecycleEpoch, RendererLifecycleEventStamp,
+ RendererLifecycleSnapshot, RendererLifecycleStartReason, RendererLifecycleTerminationStamp,
RendererMainDocumentCommit, RendererMoliDomMemoryDiagnostics, RendererMoliMemoryDiagnostics,
RendererMoliMemoryScopeDiagnostics, RendererMoliRuntimeMemoryDiagnostics, RendererOutputCursor,
RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,
@@ -317,13 +318,19 @@ pub enum PageVmInitStage {
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RendererPageCreationReplyBoundary {
+pub enum RendererReplyBoundary {
/// Resolve page creation only after the requested lifecycle milestone.
- LifecycleTarget,
+ Stage,
/// Publish the committed Document and continue DCL/load on owner turns.
DocumentCommit,
}
+impl RendererReplyBoundary {
+ pub(crate) const fn waits_for_stage(self) -> bool {
+ matches!(self, Self::Stage)
+ }
+}
+
/// Host integration route for cross-document top-level navigation requests.
///
/// This is not navigation ownership and is not Document lifecycle state. The
@@ -344,12 +351,12 @@ pub enum RendererTopLevelNavigationDispatch {
/// that command observer. It is discarded when the command replies or
/// detaches and never becomes stable Page or Document lifecycle state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RendererPageCreationNavigationReplyPolicy {
+pub enum RendererNavigationReplyPolicy {
FollowBeforeReply,
ReturnWithPendingNavigation,
}
-impl RendererPageCreationNavigationReplyPolicy {
+impl RendererNavigationReplyPolicy {
pub(crate) const fn returns_with_pending_navigation(self) -> bool {
matches!(self, Self::ReturnWithPendingNavigation)
}
@@ -357,8 +364,7 @@ impl RendererPageCreationNavigationReplyPolicy {
pub mod renderer {
pub use super::{
- PageVmInitStage, RendererPageCreationNavigationReplyPolicy,
- RendererPageCreationReplyBoundary, RendererTopLevelNavigationDispatch,
- is_on_js_local_executor,
+ PageVmInitStage, RendererNavigationReplyPolicy, RendererReplyBoundary,
+ RendererTopLevelNavigationDispatch, is_on_js_local_executor,
};
}
diff --git a/moli-renderer-v8/src/runtime/document_lifecycle.rs b/moli-renderer-v8/src/runtime/document_lifecycle.rs
index d93f36f05..d33e1888a 100644
--- a/moli-renderer-v8/src/runtime/document_lifecycle.rs
+++ b/moli-renderer-v8/src/runtime/document_lifecycle.rs
@@ -1,8 +1,7 @@
use std::{cell::RefCell, collections::VecDeque, rc::Rc};
-use tracing::trace;
-
use super::PageId;
+use tracing::trace;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct RendererFrameToken {
diff --git a/moli-renderer-v8/src/runtime/lifecycle_decision.rs b/moli-renderer-v8/src/runtime/lifecycle_decision.rs
new file mode 100644
index 000000000..f7f8287d9
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/lifecycle_decision.rs
@@ -0,0 +1,96 @@
+//! Host contract for deciding a pending Page's exact lifecycle target.
+//!
+//! This module contains only the data and one-shot callback crossing the
+//! renderer boundary. Snapshot capture, callback isolation, scheduler gates,
+//! and successor navigation stay in `owner::lifecycle_decision`.
+
+use super::document_lifecycle::RendererDocumentLifecycleIdentity;
+use crate::PageVmInitStage;
+use url::Url;
+
+/// Immutable facts for the exact Document that reached a requested
+/// page-creation lifecycle target.
+///
+/// This snapshot is intentionally narrow. In particular, producing it does
+/// not capture the whole Page VM state or advance lifecycle execution.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct RendererLifecycleSnapshot {
+ pub stage: PageVmInitStage,
+ pub document: RendererDocumentLifecycleIdentity,
+ pub requested_url: Url,
+ pub final_url: Url,
+ pub status: u16,
+}
+
+/// One-shot decision made synchronously when page creation reaches its exact
+/// lifecycle target.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum RendererLifecycleDecision {
+ /// Accept the Page at the lifecycle target and let page creation reply.
+ Finish,
+ /// Observe one cross-Document navigation within the supplied grace
+ /// period, then follow its successor to the same lifecycle target before
+ /// page creation replies.
+ FollowNextDocument { navigation_grace_ms: u64 },
+}
+
+/// Synchronous, one-shot policy decider for a page-creation lifecycle target.
+///
+/// The renderer invokes this decider in the owner turn that observes the target,
+/// after lifecycle output has been settled and before another Page turn can
+/// run. The callback must only inspect the supplied snapshot and return
+/// promptly. It must not block, await, or call back into this renderer owner;
+/// doing so would stall or deadlock the owner lane.
+pub struct RendererLifecycleDecider {
+ callback: Box<
+ dyn FnOnce(RendererLifecycleSnapshot) -> anyhow::Result<RendererLifecycleDecision>
+ + Send
+ + 'static,
+ >,
+}
+
+impl RendererLifecycleDecider {
+ pub fn new<F>(callback: F) -> Self
+ where
+ F: FnOnce(RendererLifecycleSnapshot) -> anyhow::Result<RendererLifecycleDecision>
+ + Send
+ + 'static,
+ {
+ Self {
+ callback: Box::new(callback),
+ }
+ }
+
+ pub(super) fn decide(
+ self,
+ snapshot: RendererLifecycleSnapshot,
+ ) -> anyhow::Result<RendererLifecycleDecision> {
+ (self.callback)(snapshot)
+ }
+}
+
+impl std::fmt::Debug for RendererLifecycleDecider {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("RendererLifecycleDecider")
+ .finish_non_exhaustive()
+ }
+}
+
+pub(super) struct PendingLifecycleDecision {
+ target_stage: PageVmInitStage,
+ decider: RendererLifecycleDecider,
+}
+
+impl PendingLifecycleDecision {
+ pub(super) fn new(target_stage: PageVmInitStage, decider: RendererLifecycleDecider) -> Self {
+ Self {
+ target_stage,
+ decider,
+ }
+ }
+
+ pub(super) fn into_parts(self) -> (PageVmInitStage, RendererLifecycleDecider) {
+ (self.target_stage, self.decider)
+ }
+}
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index bcf8d5a9a..21daaaca2 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -45,6 +45,7 @@ mod browser_context_runtime;
mod document_lifecycle;
mod document_lifecycle_turn;
mod javascript_dialog;
+mod lifecycle_decision;
mod main_document_ready_gate;
mod navigation;
mod owner;
@@ -271,6 +272,9 @@ pub(crate) use self::javascript_dialog::{
pub use self::javascript_dialog::{
RendererJavaScriptDialogCompletion, RendererJavaScriptDialogResult,
};
+pub use self::lifecycle_decision::{
+ RendererLifecycleDecider, RendererLifecycleDecision, RendererLifecycleSnapshot,
+};
use self::owner::RendererOwnerState;
pub use self::owner::{
RendererOwnerCommand, RendererOwnerHandle, RendererOwnerReply,
diff --git a/moli-renderer-v8/src/runtime/navigation/page_creation_resolution.rs b/moli-renderer-v8/src/runtime/navigation/page_creation_resolution.rs
index 84ce2332b..1a442270b 100644
--- a/moli-renderer-v8/src/runtime/navigation/page_creation_resolution.rs
+++ b/moli-renderer-v8/src/runtime/navigation/page_creation_resolution.rs
@@ -18,6 +18,11 @@ pub(in crate::runtime) enum PageCreationResolution<Pending, Attached> {
pending: Pending,
document: RendererDocumentLifecycleIdentity,
},
+ /// The exact lifecycle target was reached, but a synchronous decider must
+ /// run before page creation can either reply or follow another
+ /// Document. This is an intra-owner-turn result, not a request to enqueue
+ /// another turn.
+ LifecycleDecisionRequired { pending: Pending },
/// The owner-local store retired the Page before returning this result.
Retired { failure: PageCreationRetirement },
/// Checkout did not obtain the resident entry. The store remains its
diff --git a/moli-renderer-v8/src/runtime/owner.rs b/moli-renderer-v8/src/runtime/owner.rs
index 5b589b4e3..278df865b 100644
--- a/moli-renderer-v8/src/runtime/owner.rs
+++ b/moli-renderer-v8/src/runtime/owner.rs
@@ -7,13 +7,13 @@ use super::owner_local::RendererAttachedPage;
use super::owner_local_store::{
LivePageNavigationFailureRecipient, LivePageNavigationFollowOutcome,
LivePageNavigationFollowTurn, LivePagePendingNavigationCompletion,
- LivePagePendingNavigationPhaseOneAdvance, PageCreationNavigationReplyPolicy,
- RendererDisplacedOrdinaryTurn, RendererDocumentIsolateAllocator,
- RendererDocumentIsolateReservation, RendererOwnerLocalContext, RendererOwnerLocalStore,
- RendererPageCommandDispatch, RendererPageCreationResolution, RendererPageLocalEntry,
- RendererPageLocalEntryCheckoutError, RendererPageScheduledTurn, RendererPageToken,
- RendererPageTurnAdmission, RendererPageTurnCheckoutError, RendererPendingPageCreation,
- RendererPreparedDocumentResidence, advance_document_lifecycle_one_page_turn_via_local_task,
+ LivePagePendingNavigationPhaseOneAdvance, NavigationReplyPolicy, RendererDisplacedOrdinaryTurn,
+ RendererDocumentIsolateAllocator, RendererDocumentIsolateReservation,
+ RendererOwnerLocalContext, RendererOwnerLocalStore, RendererPageCommandDispatch,
+ RendererPageCreationResolution, RendererPageLocalEntry, RendererPageLocalEntryCheckoutError,
+ RendererPageScheduledTurn, RendererPageToken, RendererPageTurnAdmission,
+ RendererPageTurnCheckoutError, RendererPendingPageCreation, RendererPreparedDocumentResidence,
+ advance_document_lifecycle_one_page_turn_via_local_task,
advance_dom_stable_wait_turn_on_entry_via_local_task,
advance_network_idle_wait_turn_on_entry_via_local_task,
advance_page_owner_one_turn_via_local_task,
@@ -39,6 +39,7 @@ use super::owner_local_store::{
owner_local_store_session, page_turn_readiness_after_restore_on_bound_owner_local_store,
pending_phase_one_admission_after_restore_on_bound_owner_local_store,
publish_page_navigation_failure_on_bound_owner_local_store,
+ release_lifecycle_gate_on_bound_owner_local_store,
release_post_response_document_lifecycle_on_bound_owner_local_store,
remove_page_on_bound_owner_local_store, remove_page_on_bound_owner_local_store_via_local_task,
renderer_output_fence_for_tail_on_bound_owner_local_store,
@@ -87,6 +88,10 @@ use moli_page_types::LayoutPolicy;
use std::collections::VecDeque;
use tokio::sync::{mpsc, oneshot};
+mod lifecycle_decision;
+
+use self::lifecycle_decision::PendingLifecycleNavigation;
+
#[derive(Debug, Clone)]
pub struct RendererPreparedDocumentCommitConfiguration {
pub document_start_scripts: Vec<DocumentStartScript>,
@@ -153,6 +158,8 @@ pub struct RendererCreateHtmlPageRequest {
pub layout_policy: LayoutPolicy,
pub wpt_extensions_enabled: bool,
pub stage: PageVmInitStage,
+ pub reply_boundary: crate::RendererReplyBoundary,
+ pub lifecycle_decider: Option<RendererLifecycleDecider>,
/// Decides whether a non-`javascript:` location request remains inside
/// the standalone adapter or becomes a browser-owner output action.
///
@@ -198,9 +205,10 @@ pub struct RendererCreateStreamingRawPageRequest {
pub layout_policy: LayoutPolicy,
pub wpt_extensions_enabled: bool,
pub stage: PageVmInitStage,
- pub reply_boundary: crate::RendererPageCreationReplyBoundary,
+ pub reply_boundary: crate::RendererReplyBoundary,
+ pub lifecycle_decider: Option<RendererLifecycleDecider>,
pub(super) top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
- pub(super) navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ pub(super) navigation_reply_policy: NavigationReplyPolicy,
pub reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
}
@@ -520,15 +528,16 @@ enum RenderRuntimeTurn {
page_tasks: Vec<PostParsePageOwnedWork>,
stage: PageVmInitStage,
started: Instant,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
},
ContinueAttachedPageCreationLifecycle {
pending: RendererPendingPageCreation,
document: RendererDocumentLifecycleIdentity,
target_stage: PageVmInitStage,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
},
DrainSharedWorkerServiceLane,
DrainServiceWorkerServiceLane,
@@ -570,6 +579,7 @@ enum RenderRuntimeTurn {
deadline: Instant,
loader: ResourceRequestClient,
},
+ WaitLifecycleNavigation(PendingLifecycleNavigation),
WaitLivePageSelector {
token: RendererPageToken,
selector: String,
@@ -675,6 +685,7 @@ impl RenderRuntimeTurn {
fn is_page_creation_lifecycle_observer_for(&self, token: RendererPageToken) -> bool {
match self {
Self::ContinueAttachedPageCreationLifecycle { pending, .. } => pending.token == token,
+ Self::WaitLifecycleNavigation(wait) => wait.token() == token,
Self::ContinueLivePageNavigationPostParseLifecycle {
token: observer_token,
completion: LivePagePendingNavigationCompletion::CompletePageCreation { .. },
@@ -763,13 +774,13 @@ fn live_page_command_requires_materialized_child_realms(command: &RendererPageCo
const fn page_creation_navigation_reply_policy(
dispatch: RendererTopLevelNavigationDispatch,
-) -> PageCreationNavigationReplyPolicy {
+) -> NavigationReplyPolicy {
match dispatch {
RendererTopLevelNavigationDispatch::DelegateToBrowser => {
- PageCreationNavigationReplyPolicy::ReturnWithPendingNavigation
+ NavigationReplyPolicy::ReturnWithPendingNavigation
}
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter => {
- PageCreationNavigationReplyPolicy::FollowBeforeReply
+ NavigationReplyPolicy::FollowBeforeReply
}
}
}
@@ -1044,7 +1055,7 @@ impl RendererOwnerHandle {
response_headers: Vec<(String, String)>,
page_vm: PageVm,
pending_download: Option<RendererPendingDownloadActivation>,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_decision: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
self.run_owner_lane_local_task(async move {
install_page_vm_on_bound_owner_local_store(
@@ -1057,7 +1068,7 @@ impl RendererOwnerHandle {
response_headers,
page_vm,
pending_download,
- page_creation_lifecycle_target,
+ lifecycle_decision,
)
})
.await
@@ -1073,7 +1084,7 @@ impl RendererOwnerHandle {
response_status: u16,
response_headers: Vec<(String, String)>,
pending_navigation: PageVmPendingPhaseOneNavigation,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_decision: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
self.run_owner_lane_local_task(async move {
install_phase_one_blocked_page_on_bound_owner_local_store(
@@ -1085,7 +1096,7 @@ impl RendererOwnerHandle {
response_status,
response_headers,
pending_navigation,
- page_creation_lifecycle_target,
+ lifecycle_decision,
)
})
.await
@@ -1119,7 +1130,7 @@ impl RendererOwnerHandle {
pending: RendererPendingPageCreation,
document: RendererDocumentLifecycleIdentity,
target_stage: PageVmInitStage,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
) -> Result<RendererPageCreationResolution> {
self.run_owner_lane_local_task(async move {
Ok(resolve_pending_page_creation_on_bound_owner_local_store(
@@ -1144,7 +1155,8 @@ impl RendererOwnerHandle {
page_tasks: Vec<PostParsePageOwnedWork>,
stage: PageVmInitStage,
started: Instant,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
) -> Result<(RendererPendingPageCreation, DocumentLifecycleTurnOutcome)> {
let owner_local_context = self.owner_local_context()?;
@@ -1159,13 +1171,10 @@ impl RendererOwnerHandle {
response_headers,
page_vm,
None,
- matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget
- )
- .then_some(stage),
+ reply_boundary.waits_for_stage().then_some(stage),
)
.await?;
+ let pending = pending.with_lifecycle_decider(stage, lifecycle_decider);
let token = pending.token;
let mut entry = match take_entry_for_command_on_bound_owner_local_store(token) {
Ok(entry) => entry,
@@ -1203,9 +1212,10 @@ impl RendererOwnerHandle {
response_headers: Vec<(String, String)>,
pending_navigation: PageVmPendingPhaseOneNavigation,
stage: PageVmInitStage,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
) -> RenderRuntimeDispatchOutcome {
let owner_local_context = match self.owner_local_context() {
Ok(context) => context,
@@ -1221,17 +1231,14 @@ impl RendererOwnerHandle {
response_status,
response_headers,
pending_navigation,
- matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget
- )
- .then_some(stage),
+ reply_boundary.waits_for_stage().then_some(stage),
)
.await
{
Ok(pending) => pending,
Err(error) => return Err(error).into(),
};
+ let pending = pending.with_lifecycle_decider(stage, lifecycle_decider);
let token = pending.token;
let mut entry = match take_entry_for_command_on_bound_owner_local_store(token) {
Ok(entry) => entry,
@@ -1240,10 +1247,7 @@ impl RendererOwnerHandle {
entry.set_top_level_navigation_dispatch(top_level_navigation_dispatch);
self.restore_live_page_entry(token, entry);
- if matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::DocumentCommit
- ) {
+ if matches!(reply_boundary, crate::RendererReplyBoundary::DocumentCommit) {
self.publish_pending_page_creation_and_continue(
pending,
RenderRuntimePageCreationContinuation::AfterCommittedDocumentResponse {
@@ -1291,9 +1295,10 @@ impl RendererOwnerHandle {
response_headers: Vec<(String, String)>,
page_vm: PageVm,
stage: PageVmInitStage,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
+ lifecycle_decider: Option<RendererLifecycleDecider>,
top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
) -> RenderRuntimeDispatchOutcome {
let owner_local_context = match self.owner_local_context() {
Ok(context) => context,
@@ -1310,11 +1315,7 @@ impl RendererOwnerHandle {
response_headers,
page_vm,
None,
- matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget
- )
- .then_some(stage),
+ reply_boundary.waits_for_stage().then_some(stage),
)
.await
{
@@ -1322,6 +1323,7 @@ impl RendererOwnerHandle {
Err(error) => return Err(error).into(),
};
+ let pending = pending.with_lifecycle_decider(stage, lifecycle_decider);
let token = pending.token;
let mut entry = match take_entry_for_command_on_bound_owner_local_store(token) {
Ok(entry) => entry,
@@ -1334,10 +1336,7 @@ impl RendererOwnerHandle {
return self.finish_pending_page_creation(pending).await;
}
- if matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::DocumentCommit
- ) {
+ if matches!(reply_boundary, crate::RendererReplyBoundary::DocumentCommit) {
self.restore_live_page_entry(token, entry);
self.publish_pending_page_creation_and_continue(
pending,
@@ -1368,6 +1367,19 @@ impl RendererOwnerHandle {
}
async fn finish_pending_page_creation(
+ &self,
+ mut pending: RendererPendingPageCreation,
+ ) -> RenderRuntimeDispatchOutcome {
+ if let Some((target_stage, decider)) = pending.take_lifecycle_decider() {
+ return self
+ .apply_lifecycle_decision(pending, target_stage, decider)
+ .await;
+ }
+
+ self.finalize_pending_page_creation_reply(pending).await
+ }
+
+ async fn finalize_pending_page_creation_reply(
&self,
pending: RendererPendingPageCreation,
) -> RenderRuntimeDispatchOutcome {
@@ -1456,7 +1468,7 @@ impl RendererOwnerHandle {
pending: RendererPendingPageCreation,
document: RendererDocumentLifecycleIdentity,
target_stage: PageVmInitStage,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
) -> RenderRuntimeDispatchOutcome {
let token = pending.token;
let resolution = self
@@ -1499,6 +1511,10 @@ impl RendererOwnerHandle {
wake_token: token,
}
}
+ PageCreationResolution::LifecycleDecisionRequired { pending } => {
+ debug_assert!(!retire_page_after_publication);
+ self.finish_pending_page_creation(pending).await
+ }
PageCreationResolution::Retired { failure } => {
debug_assert!(retire_page_after_publication);
let _ = remove_page_on_bound_owner_local_store_via_local_task(
@@ -1957,6 +1973,8 @@ impl RendererOwnerHandle {
layout_policy: self.seal_layout_policy_for_page_creation(),
wpt_extensions_enabled: false,
stage,
+ reply_boundary: crate::RendererReplyBoundary::Stage,
+ lifecycle_decider: None,
top_level_navigation_dispatch:
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
reserved_service_worker_client: None,
@@ -2028,10 +2046,11 @@ impl RendererOwnerHandle {
layout_policy: self.seal_layout_policy_for_page_creation(),
wpt_extensions_enabled: false,
stage,
- reply_boundary: crate::RendererPageCreationReplyBoundary::LifecycleTarget,
+ reply_boundary: crate::RendererReplyBoundary::Stage,
+ lifecycle_decider: None,
top_level_navigation_dispatch:
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- navigation_reply_policy: PageCreationNavigationReplyPolicy::FollowBeforeReply,
+ navigation_reply_policy: NavigationReplyPolicy::FollowBeforeReply,
reserved_service_worker_client: None,
}
}
@@ -4224,6 +4243,9 @@ impl RendererOwnerHandle {
RenderRuntimeTurn::ContinueAttachedPageCreationLifecycle { pending, .. } => {
remove_page_on_bound_owner_local_store(pending.token);
}
+ RenderRuntimeTurn::WaitLifecycleNavigation(wait) => {
+ remove_page_on_bound_owner_local_store(wait.token());
+ }
RenderRuntimeTurn::ContinueLivePageRuntimeCommandLifecycle {
token, scope_id, ..
} => {
@@ -4515,7 +4537,8 @@ impl RendererOwnerHandle {
reply,
capture_policy,
} => {
- let reply = self.merge_pending_download_into_reply(*reply, download);
+ let reply = *reply;
+ let reply = self.merge_pending_download_into_reply(reply, download);
self.finish_live_page_entry_with_page_state_and_continuation(
token,
entry,
@@ -5786,6 +5809,7 @@ impl RendererOwnerHandle {
stage,
started,
reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
navigation_reply_policy,
} => {
@@ -5802,6 +5826,7 @@ impl RendererOwnerHandle {
stage,
started,
reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
)
.await
@@ -5815,10 +5840,7 @@ impl RendererOwnerHandle {
..
} => {
let target_stage = stage;
- if matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::DocumentCommit
- ) {
+ if matches!(reply_boundary, crate::RendererReplyBoundary::DocumentCommit) {
let token = pending.token;
self.signal_internal_document_lifecycle_turn(token);
self.publish_pending_page_creation_and_continue(
@@ -5858,10 +5880,7 @@ impl RendererOwnerHandle {
..
} => {
let target_stage = stage;
- if matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::DocumentCommit
- ) {
+ if matches!(reply_boundary, crate::RendererReplyBoundary::DocumentCommit) {
let token = pending.token;
self.publish_pending_page_creation_and_continue(
pending,
@@ -5898,10 +5917,7 @@ impl RendererOwnerHandle {
DocumentLifecycleTurnAction::RequestedTopLevelNavigation { stage, .. },
..
} => {
- if matches!(
- reply_boundary,
- crate::RendererPageCreationReplyBoundary::DocumentCommit
- ) {
+ if matches!(reply_boundary, crate::RendererReplyBoundary::DocumentCommit) {
if navigation_reply_policy.returns_with_pending_navigation() {
self.finish_pending_page_creation(pending).await
} else {
@@ -6125,6 +6141,9 @@ impl RendererOwnerHandle {
self.wait_live_page_dom_stable_turn(token, state, deadline, loader)
.await
}
+ RenderRuntimeTurn::WaitLifecycleNavigation(wait) => {
+ self.wait_lifecycle_navigation_turn(wait).await
+ }
RenderRuntimeTurn::WaitLivePageSelector {
token,
selector,
@@ -6260,6 +6279,8 @@ impl RendererOwnerHandle {
layout_policy,
wpt_extensions_enabled,
stage,
+ reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
reserved_service_worker_client,
} = request;
@@ -6271,6 +6292,18 @@ impl RendererOwnerHandle {
))
.into();
}
+ if lifecycle_decider.is_some()
+ && (!matches!(reply_boundary, crate::RendererReplyBoundary::Stage)
+ || !matches!(
+ top_level_navigation_dispatch,
+ RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter
+ ))
+ {
+ return Err(anyhow!(
+ "a lifecycle decider requires a standalone lifecycle-boundary page creation"
+ ))
+ .into();
+ }
let loader = loader_for_new_page(
&loader,
&extra_http_headers,
@@ -6419,7 +6452,8 @@ impl RendererOwnerHandle {
PageVmFollowedNavigationMetadata::default(),
),
stage,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget,
+ reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
page_creation_navigation_reply_policy(top_level_navigation_dispatch),
)
@@ -6439,7 +6473,8 @@ impl RendererOwnerHandle {
response_headers,
page_vm,
stage,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget,
+ reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
page_creation_navigation_reply_policy(top_level_navigation_dispatch),
)
@@ -6462,7 +6497,8 @@ impl RendererOwnerHandle {
page_tasks,
stage,
started,
- reply_boundary: crate::RendererPageCreationReplyBoundary::LifecycleTarget,
+ reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
navigation_reply_policy: page_creation_navigation_reply_policy(
top_level_navigation_dispatch,
@@ -6593,10 +6629,27 @@ impl RendererOwnerHandle {
wpt_extensions_enabled,
stage,
reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
navigation_reply_policy,
reserved_service_worker_client,
} = request;
+ if lifecycle_decider.is_some()
+ && (!matches!(reply_boundary, crate::RendererReplyBoundary::Stage)
+ || !matches!(
+ top_level_navigation_dispatch,
+ RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter
+ )
+ || !matches!(
+ navigation_reply_policy,
+ NavigationReplyPolicy::FollowBeforeReply
+ ))
+ {
+ return Err(anyhow!(
+ "a lifecycle decider requires standalone follow-before-reply page creation"
+ ))
+ .into();
+ }
let loader = loader_for_new_page(
&loader,
&extra_http_headers,
@@ -6749,6 +6802,7 @@ impl RendererOwnerHandle {
),
stage,
reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
navigation_reply_policy,
)
@@ -6765,6 +6819,7 @@ impl RendererOwnerHandle {
page_vm,
stage,
reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
navigation_reply_policy,
)
@@ -6788,6 +6843,7 @@ impl RendererOwnerHandle {
stage,
started,
reply_boundary,
+ lifecycle_decider,
top_level_navigation_dispatch,
navigation_reply_policy,
},
diff --git a/moli-renderer-v8/src/runtime/owner/lifecycle_decision.rs b/moli-renderer-v8/src/runtime/owner/lifecycle_decision.rs
new file mode 100644
index 000000000..997d96bc5
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/owner/lifecycle_decision.rs
@@ -0,0 +1,270 @@
+//! Owner-turn state machine for lifecycle-target Page creation decisions.
+//!
+//! This module is the only place that couples the synchronous host decision
+//! contract to Page-creation gates and successor-navigation scheduling. The
+//! generic owner loop only stores and dispatches the typed continuation.
+
+use super::{
+ LivePagePendingNavigationCompletion, NavigationReplyPolicy, RenderRuntimeDispatchOutcome,
+ RenderRuntimeTurn, RendererOwnerHandle, RendererOwnerWakeSource, RendererPageToken,
+ RendererPendingPageCreation, checked_live_page_wait_deadline,
+ release_lifecycle_gate_on_bound_owner_local_store,
+ take_entry_for_command_on_bound_owner_local_store,
+};
+use crate::runtime::document_lifecycle::RendererDocumentLifecycleWaitOutcome;
+use crate::runtime::lifecycle_decision::{
+ RendererLifecycleDecider, RendererLifecycleDecision, RendererLifecycleSnapshot,
+};
+use crate::runtime::owner_local_store::RendererPageLocalEntry;
+use crate::runtime::page_vm::renderer_document_lifecycle_milestone_for_stage;
+use anyhow::{Context, Result, anyhow, ensure};
+use std::time::Instant;
+
+pub(super) struct PendingLifecycleNavigation {
+ pending: RendererPendingPageCreation,
+ snapshot: RendererLifecycleSnapshot,
+ navigation_grace_ms: u64,
+ navigation_deadline: Instant,
+ resume_parked_page_turn: bool,
+}
+
+impl PendingLifecycleNavigation {
+ pub(super) const fn token(&self) -> RendererPageToken {
+ self.pending.token
+ }
+}
+
+fn capture_lifecycle_snapshot(
+ entry: &RendererPageLocalEntry,
+ target_stage: crate::PageVmInitStage,
+) -> Result<RendererLifecycleSnapshot> {
+ let document = entry.page_vm().document_lifecycle.identity();
+ ensure!(
+ matches!(
+ entry.page_vm().document_lifecycle_wait_outcome(
+ renderer_document_lifecycle_milestone_for_stage(target_stage)
+ ),
+ RendererDocumentLifecycleWaitOutcome::Reached(_)
+ ),
+ "renderer page {} tried to invoke its lifecycle decider before {target_stage:?}",
+ entry.slot.page_id().as_u64()
+ );
+
+ // Read only response identity from the active VM. The stable Page state
+ // may still describe the predecessor when navigation replaced a Document
+ // before this first target was reached, and a full PageVm state capture
+ // here would add unrelated work to the lifecycle boundary.
+ let stable_page_state = entry.slot.active_page_state()?;
+ let (requested_url, status) = entry
+ .page_vm()
+ .navigation_response
+ .as_ref()
+ .map(|response| (response.requested_url.clone(), response.status))
+ .unwrap_or_else(|| {
+ (
+ stable_page_state.requested_url.clone(),
+ stable_page_state.status,
+ )
+ });
+ Ok(RendererLifecycleSnapshot {
+ stage: target_stage,
+ document,
+ requested_url,
+ final_url: entry.page_vm().vm().document_runtime.document_url().clone(),
+ status,
+ })
+}
+
+fn invoke_lifecycle_decider(
+ decider: RendererLifecycleDecider,
+ snapshot: RendererLifecycleSnapshot,
+) -> Result<RendererLifecycleDecision> {
+ // A host panic must retire only this pending Page, not unwind the renderer
+ // owner lane. AssertUnwindSafe is appropriate because the one-shot decider is
+ // consumed regardless of its outcome and no reference escapes this call.
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decider.decide(snapshot))) {
+ Ok(result) => result.context("page lifecycle decider failed"),
+ Err(payload) => {
+ let description = panic_payload_description(payload.as_ref());
+ anyhow::bail!("page lifecycle decider panicked: {description}")
+ }
+ }
+}
+
+fn lifecycle_navigation_timeout_error(
+ snapshot: &RendererLifecycleSnapshot,
+ navigation_grace_ms: u64,
+) -> anyhow::Error {
+ let status = http::StatusCode::from_u16(snapshot.status)
+ .map(|status| status.to_string())
+ .unwrap_or_else(|_| snapshot.status.to_string());
+ anyhow!(
+ "lifecycle target document `{}` returned {status} and did not start a successor navigation within the {navigation_grace_ms} ms grace period",
+ snapshot.final_url
+ )
+}
+
+fn panic_payload_description(payload: &(dyn std::any::Any + Send)) -> &str {
+ payload
+ .downcast_ref::<&'static str>()
+ .copied()
+ .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
+ .unwrap_or("non-string panic payload")
+}
+
+impl RendererOwnerHandle {
+ pub(super) async fn apply_lifecycle_decision(
+ &self,
+ pending: RendererPendingPageCreation,
+ target_stage: crate::PageVmInitStage,
+ decider: RendererLifecycleDecider,
+ ) -> RenderRuntimeDispatchOutcome {
+ let token = pending.token;
+ let (snapshot, renderer_output) = {
+ let mut entry = match take_entry_for_command_on_bound_owner_local_store(token) {
+ Ok(entry) => entry,
+ Err(error) => return self.retire_failed_page_creation(token, error).await,
+ };
+ let snapshot = capture_lifecycle_snapshot(&entry, target_stage);
+ let renderer_output = entry.page_vm_mut().settle_renderer_output_publication();
+ self.restore_live_page_entry(token, entry);
+ let snapshot = match snapshot {
+ Ok(snapshot) => snapshot,
+ Err(error) => return self.retire_failed_page_creation(token, error).await,
+ };
+ (snapshot, renderer_output)
+ };
+ if let Some(output) = renderer_output {
+ self.publish_renderer_output(output);
+ }
+
+ let decision = match invoke_lifecycle_decider(decider, snapshot.clone()) {
+ Ok(decision) => decision,
+ Err(error) => return self.retire_failed_page_creation(token, error).await,
+ };
+
+ match decision {
+ RendererLifecycleDecision::Finish => {
+ self.finalize_pending_page_creation_reply(pending).await
+ }
+ RendererLifecycleDecision::FollowNextDocument {
+ navigation_grace_ms,
+ } => {
+ let navigation_deadline = match checked_live_page_wait_deadline(
+ navigation_grace_ms,
+ "lifecycle-target successor navigation grace",
+ ) {
+ Ok(deadline) => deadline,
+ Err(error) => return self.retire_failed_page_creation(token, error).await,
+ };
+ let released = match release_lifecycle_gate_on_bound_owner_local_store(token) {
+ Ok(released) => released,
+ Err(error) => {
+ return self.retire_failed_page_creation(token, error).await;
+ }
+ };
+ if released.target_stage != target_stage {
+ return self
+ .retire_failed_page_creation(
+ token,
+ anyhow!(
+ "renderer page lifecycle-target gate changed from {target_stage:?} to {:?}",
+ released.target_stage
+ ),
+ )
+ .await;
+ }
+ RenderRuntimeDispatchOutcome::ContinueNextTurn(Box::new(
+ RenderRuntimeTurn::WaitLifecycleNavigation(PendingLifecycleNavigation {
+ pending,
+ snapshot,
+ navigation_grace_ms,
+ navigation_deadline,
+ resume_parked_page_turn: released.resume_parked_page_turn,
+ }),
+ ))
+ }
+ }
+ }
+
+ pub(super) async fn wait_lifecycle_navigation_turn(
+ &self,
+ wait: PendingLifecycleNavigation,
+ ) -> RenderRuntimeDispatchOutcome {
+ let PendingLifecycleNavigation {
+ pending,
+ snapshot,
+ navigation_grace_ms,
+ navigation_deadline,
+ resume_parked_page_turn,
+ } = wait;
+ let token = pending.token;
+ let mut entry = match take_entry_for_command_on_bound_owner_local_store(token) {
+ Ok(entry) => entry,
+ Err(error) => return self.retire_failed_page_creation(token, error).await,
+ };
+ let current = entry.page_vm().document_lifecycle.identity();
+ if current != snapshot.document {
+ self.restore_live_page_entry(token, entry);
+ return RenderRuntimeDispatchOutcome::ContinueNextTurn(Box::new(
+ RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle {
+ token,
+ document: current,
+ target_stage: snapshot.stage,
+ follow_count: 0,
+ completion: LivePagePendingNavigationCompletion::CompletePageCreation {
+ pending,
+ navigation_reply_policy: NavigationReplyPolicy::FollowBeforeReply,
+ },
+ },
+ ));
+ }
+ if entry.page_vm().vm().has_pending_location_navigation()
+ && entry.begin_standalone_navigation_follow()
+ {
+ return self.continue_live_page_pending_navigation(
+ token,
+ entry,
+ snapshot.stage,
+ 0,
+ LivePagePendingNavigationCompletion::CompletePageCreation {
+ pending,
+ navigation_reply_policy: NavigationReplyPolicy::FollowBeforeReply,
+ },
+ );
+ }
+ if Instant::now() >= navigation_deadline {
+ self.restore_live_page_entry(token, entry);
+ return self
+ .retire_failed_page_creation(
+ token,
+ lifecycle_navigation_timeout_error(&snapshot, navigation_grace_ms),
+ )
+ .await;
+ }
+
+ self.restore_live_page_entry(token, entry);
+ if resume_parked_page_turn {
+ // Give the lifecycle-target continuation the first chance to claim
+ // a navigation already pending at the retained boundary. Resume
+ // the scheduler source only after that inspection.
+ self.signal_internal_page_turn_source(
+ token,
+ RendererOwnerWakeSource::SchedulerContinuation,
+ );
+ }
+ RenderRuntimeDispatchOutcome::ContinueAfterPageWakeOrDeadline {
+ turn: Box::new(RenderRuntimeTurn::WaitLifecycleNavigation(
+ PendingLifecycleNavigation {
+ pending,
+ snapshot,
+ navigation_grace_ms,
+ navigation_deadline,
+ resume_parked_page_turn: false,
+ },
+ )),
+ wake_token: token,
+ ready_at: navigation_deadline,
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/runtime/owner_local_store.rs b/moli-renderer-v8/src/runtime/owner_local_store.rs
index daa484b4c..1762659a1 100644
--- a/moli-renderer-v8/src/runtime/owner_local_store.rs
+++ b/moli-renderer-v8/src/runtime/owner_local_store.rs
@@ -7,8 +7,11 @@ use std::rc::Rc;
#[cfg(debug_assertions)]
use std::thread::ThreadId;
+use anyhow::Context;
+
use super::access::run_named_owner_local_task;
use super::document_lifecycle_turn::DocumentLifecycleObserverOutcome;
+use super::lifecycle_decision::PendingLifecycleDecision;
use super::navigation::{
PageCreationNavigationFailureObserver, PageCreationNavigationFailurePublication,
PageCreationNavigationFailurePublisher, PageCreationResolution, PageCreationRetirement,
@@ -40,7 +43,7 @@ use crate::script_vm::{
RendererDocumentIsolateHandle, RendererDocumentIsolateReservationAccounting,
RendererPageScriptEnvironment,
};
-use crate::{RendererPageCreationNavigationReplyPolicy, RendererTopLevelNavigationDispatch};
+use crate::{RendererNavigationReplyPolicy, RendererTopLevelNavigationDispatch};
use tokio::sync::oneshot;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
@@ -223,6 +226,7 @@ pub(super) struct RendererPendingPageCreation {
navigation_failure_observer: PageCreationNavigationFailureObserver,
page_context_cancel_tx: RendererPageContextCancelSender,
pending_download: Option<RendererPendingDownloadActivation>,
+ lifecycle_decider: Option<PendingLifecycleDecision>,
}
pub(super) struct RendererPageCreationResolution {
@@ -275,23 +279,51 @@ impl RendererPendingPageCreation {
self.pending_download = Some(download);
self
}
+
+ pub(super) fn with_lifecycle_decider(
+ mut self,
+ target_stage: PageVmInitStage,
+ decider: Option<RendererLifecycleDecider>,
+ ) -> Self {
+ self.lifecycle_decider =
+ decider.map(|decider| PendingLifecycleDecision::new(target_stage, decider));
+ self
+ }
+
+ pub(super) fn has_lifecycle_decider(&self) -> bool {
+ self.lifecycle_decider.is_some()
+ }
+
+ pub(super) fn take_lifecycle_decider(
+ &mut self,
+ ) -> Option<(PageVmInitStage, RendererLifecycleDecider)> {
+ self.lifecycle_decider
+ .take()
+ .map(PendingLifecycleDecision::into_parts)
+ }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-enum RendererPageCreationLifecycleTargetTurnPolicy {
+enum LifecycleGateTurnPolicy {
Normal,
- LifecycleTarget { reconsider_displaced_ordinary: bool },
- ParkAtReplyBoundary,
+ Drive { reconsider_displaced_ordinary: bool },
+ Park,
}
#[derive(Debug)]
-struct RendererPageCreationLifecycleTargetGate {
+struct LifecycleGate {
target_stage: PageVmInitStage,
parked_admitted_wake: bool,
reconsider_ordinary_on_next_turn: bool,
}
-impl RendererPageCreationLifecycleTargetGate {
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) struct ReleasedLifecycleGate {
+ pub(super) target_stage: PageVmInitStage,
+ pub(super) resume_parked_page_turn: bool,
+}
+
+impl LifecycleGate {
fn new(target_stage: PageVmInitStage) -> Self {
Self {
target_stage,
@@ -304,10 +336,10 @@ impl RendererPageCreationLifecycleTargetGate {
&mut self,
entry: &mut RendererPageLocalEntry,
has_eligible_ordinary_source: bool,
- ) -> RendererPageCreationLifecycleTargetTurnPolicy {
+ ) -> LifecycleGateTurnPolicy {
if entry.page_vm().vm().has_pending_location_navigation() {
self.reconsider_ordinary_on_next_turn = false;
- return RendererPageCreationLifecycleTargetTurnPolicy::Normal;
+ return LifecycleGateTurnPolicy::Normal;
}
match entry.page_vm().document_lifecycle_wait_outcome(
renderer_document_lifecycle_milestone_for_stage(self.target_stage),
@@ -315,13 +347,13 @@ impl RendererPageCreationLifecycleTargetGate {
RendererDocumentLifecycleWaitOutcome::Reached(_)
| RendererDocumentLifecycleWaitOutcome::Interrupted(_) => {
self.parked_admitted_wake = true;
- RendererPageCreationLifecycleTargetTurnPolicy::ParkAtReplyBoundary
+ LifecycleGateTurnPolicy::Park
}
RendererDocumentLifecycleWaitOutcome::Pending
if matches!(self.target_stage, PageVmInitStage::Load) =>
{
self.reconsider_ordinary_on_next_turn = false;
- RendererPageCreationLifecycleTargetTurnPolicy::Normal
+ LifecycleGateTurnPolicy::Normal
}
RendererDocumentLifecycleWaitOutcome::Pending
if entry.pending_document_lifecycle_identity().is_some() =>
@@ -329,13 +361,13 @@ impl RendererPageCreationLifecycleTargetGate {
let reconsider_displaced_ordinary =
self.reconsider_ordinary_on_next_turn && has_eligible_ordinary_source;
self.reconsider_ordinary_on_next_turn = false;
- RendererPageCreationLifecycleTargetTurnPolicy::LifecycleTarget {
+ LifecycleGateTurnPolicy::Drive {
reconsider_displaced_ordinary,
}
}
RendererDocumentLifecycleWaitOutcome::Pending => {
self.reconsider_ordinary_on_next_turn = false;
- RendererPageCreationLifecycleTargetTurnPolicy::Normal
+ LifecycleGateTurnPolicy::Normal
}
}
}
@@ -371,16 +403,16 @@ impl RendererPageCreationCommit {
}
}
-pub(super) type PageCreationNavigationReplyPolicy = RendererPageCreationNavigationReplyPolicy;
+pub(super) type NavigationReplyPolicy = RendererNavigationReplyPolicy;
pub(super) enum LivePagePendingNavigationCompletion {
Background,
PublishedPageCreation {
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
},
CompletePageCreation {
pending: RendererPendingPageCreation,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
},
ReplyWithSnapshot {
reply: Box<RendererPageReply>,
@@ -621,7 +653,7 @@ struct RendererOwnerLocalPageSlot {
turn_scheduler: PageTurnScheduler<RendererPageLocalEntry>,
owner_maintenance: RendererPageOwnerMaintenanceResidence,
task_sources: RendererPageOwnedTaskSources,
- page_creation_lifecycle_target: Option<RendererPageCreationLifecycleTargetGate>,
+ lifecycle_gate: Option<LifecycleGate>,
page_creation_navigation_failure_publisher: PageCreationNavigationFailurePublisher,
script_environment_pin: RendererPageScriptEnvironmentPin,
}
@@ -631,7 +663,7 @@ impl RendererOwnerLocalPageSlot {
owner_slot: RendererPageSlotHandle,
entry: RendererPageLocalEntry,
task_sources: RendererPageOwnedTaskSources,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
page_creation_navigation_failure_publisher: PageCreationNavigationFailurePublisher,
script_environment_pin: RendererPageScriptEnvironmentPin,
) -> Self {
@@ -640,8 +672,7 @@ impl RendererOwnerLocalPageSlot {
turn_scheduler: PageTurnScheduler::new(entry),
owner_maintenance: RendererPageOwnerMaintenanceResidence::new(std::time::Instant::now()),
task_sources,
- page_creation_lifecycle_target: page_creation_lifecycle_target
- .map(RendererPageCreationLifecycleTargetGate::new),
+ lifecycle_gate: lifecycle_gate.map(LifecycleGate::new),
page_creation_navigation_failure_publisher,
script_environment_pin,
}
@@ -1320,7 +1351,7 @@ pub(super) fn install_page_vm_on_bound_owner_local_store(
response_headers: Vec<(String, String)>,
vm: PageVm,
pending_download: Option<RendererPendingDownloadActivation>,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
with_bound_render_runtime_owner_local_store_session(|mut session| {
session.install_page_vm(
@@ -1333,7 +1364,7 @@ pub(super) fn install_page_vm_on_bound_owner_local_store(
response_headers,
vm,
pending_download,
- page_creation_lifecycle_target,
+ lifecycle_gate,
)
})
}
@@ -1347,7 +1378,7 @@ pub(super) fn install_phase_one_blocked_page_on_bound_owner_local_store(
response_status: u16,
response_headers: Vec<(String, String)>,
pending_navigation: PageVmPendingPhaseOneNavigation,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
with_bound_render_runtime_owner_local_store_session(|mut session| {
session.install_phase_one_blocked_page_for_owner(
@@ -1359,7 +1390,7 @@ pub(super) fn install_phase_one_blocked_page_on_bound_owner_local_store(
response_status,
response_headers,
pending_navigation,
- page_creation_lifecycle_target,
+ lifecycle_gate,
)
})
}
@@ -1376,7 +1407,7 @@ pub(super) fn resolve_pending_page_creation_on_bound_owner_local_store(
pending: RendererPendingPageCreation,
document: RendererDocumentLifecycleIdentity,
target_stage: PageVmInitStage,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
) -> RendererPageCreationResolution {
// This operation runs inside one owner-lane task and contains no await
// boundary. Before the task starts the entry remains resident; once it is
@@ -1630,13 +1661,21 @@ pub(super) fn restore_entry_after_document_lifecycle_on_bound_owner_local_store(
.page_hosts
.get_mut(&token.local_host_id)
.and_then(|host| host.pages.get_mut(&token.page_id))
- .and_then(|slot| slot.page_creation_lifecycle_target.as_mut())
+ .and_then(|slot| slot.lifecycle_gate.as_mut())
{
gate.settle_lifecycle_turn(reconsider_displaced_ordinary);
}
});
}
+pub(super) fn release_lifecycle_gate_on_bound_owner_local_store(
+ token: RendererPageToken,
+) -> Result<ReleasedLifecycleGate> {
+ with_bound_render_runtime_owner_local_store_session(|session| {
+ session.store.release_lifecycle_gate(token)
+ })
+}
+
pub(super) fn renderer_page_token_for_owner_context(
owner: &RendererOwnerLocalContext,
page_id: PageId,
@@ -2111,7 +2150,7 @@ fn select_page_scheduler_turn(
scheduler: &mut PageTurnScheduler<RendererPageLocalEntry>,
entry: &mut RendererPageLocalEntry,
task_sources: &mut RendererPageOwnedTaskSources,
- page_creation_lifecycle_target: &mut Option<RendererPageCreationLifecycleTargetGate>,
+ lifecycle_gate: &mut Option<LifecycleGate>,
trigger: PageTurnTrigger,
) -> RendererPageScheduledTurn {
let snapshot = page_ready_descriptor_snapshot(entry, task_sources);
@@ -2131,22 +2170,22 @@ fn select_page_scheduler_turn(
document_lifecycle_owner_turn_is_runnable,
has_ready_main_parser_script_continuation,
);
- let target_turn_policy = page_creation_lifecycle_target
+ let gate_policy = lifecycle_gate
.as_mut()
- .map(|target| target.turn_policy(entry, !snapshot.eligible.is_empty()))
- .unwrap_or(RendererPageCreationLifecycleTargetTurnPolicy::Normal);
- let selected_class = match target_turn_policy {
- RendererPageCreationLifecycleTargetTurnPolicy::Normal => {
+ .map(|gate| gate.turn_policy(entry, !snapshot.eligible.is_empty()))
+ .unwrap_or(LifecycleGateTurnPolicy::Normal);
+ let selected_class = match gate_policy {
+ LifecycleGateTurnPolicy::Normal => {
scheduler.select_turn_class(trigger, !snapshot.eligible.is_empty(), document_lifecycle)
}
- RendererPageCreationLifecycleTargetTurnPolicy::LifecycleTarget {
+ LifecycleGateTurnPolicy::Drive {
reconsider_displaced_ordinary,
- } => scheduler.select_lifecycle_target_turn_class(
+ } => scheduler.select_lifecycle_turn(
reconsider_displaced_ordinary,
!snapshot.eligible.is_empty(),
document_lifecycle,
),
- RendererPageCreationLifecycleTargetTurnPolicy::ParkAtReplyBoundary => {
+ LifecycleGateTurnPolicy::Park => {
return RendererPageScheduledTurn::SpentWake;
}
};
@@ -2320,7 +2359,7 @@ impl RendererOwnerLocalStoreSession<'_> {
response_headers: Vec<(String, String)>,
vm: PageVm,
pending_download: Option<RendererPendingDownloadActivation>,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
self.store.install_page_vm_for_owner(
owner,
@@ -2332,7 +2371,7 @@ impl RendererOwnerLocalStoreSession<'_> {
response_headers,
vm,
pending_download,
- page_creation_lifecycle_target,
+ lifecycle_gate,
)
}
@@ -2346,7 +2385,7 @@ impl RendererOwnerLocalStoreSession<'_> {
response_status: u16,
response_headers: Vec<(String, String)>,
pending_navigation: PageVmPendingPhaseOneNavigation,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
self.store.install_phase_one_blocked_page_for_owner(
owner,
@@ -2357,7 +2396,7 @@ impl RendererOwnerLocalStoreSession<'_> {
response_status,
response_headers,
pending_navigation,
- page_creation_lifecycle_target,
+ lifecycle_gate,
)
}
@@ -2544,7 +2583,7 @@ impl RendererOwnerLocalStore {
pending: RendererPendingPageCreation,
document: RendererDocumentLifecycleIdentity,
target_stage: PageVmInitStage,
- navigation_reply_policy: PageCreationNavigationReplyPolicy,
+ navigation_reply_policy: NavigationReplyPolicy,
) -> RendererPageCreationResolution {
// Failure selection and lifecycle entry checkout are one owner-local
// operation. The creation observer was registered before this Page
@@ -2910,6 +2949,29 @@ impl RendererOwnerLocalStore {
.is_some_and(|entry| entry.release_document_lifecycle_after_response(document))
}
+ fn release_lifecycle_gate(
+ &mut self,
+ token: RendererPageToken,
+ ) -> Result<ReleasedLifecycleGate> {
+ #[cfg(debug_assertions)]
+ Self::ensure_token_thread(&token)?;
+ let gate = self
+ .page_hosts
+ .get_mut(&token.local_host_id)
+ .and_then(|host| host.pages.get_mut(&token.page_id))
+ .and_then(|slot| slot.lifecycle_gate.take())
+ .with_context(|| {
+ anyhow!(
+ "renderer page {} has no page-creation lifecycle-target gate",
+ token.page_id.as_u64()
+ )
+ })?;
+ Ok(ReleasedLifecycleGate {
+ target_stage: gate.target_stage,
+ resume_parked_page_turn: gate.parked_admitted_wake,
+ })
+ }
+
fn checkout_scheduled_page_turn(
&mut self,
token: RendererPageToken,
@@ -2929,7 +2991,7 @@ impl RendererOwnerLocalStore {
let RendererOwnerLocalPageSlot {
turn_scheduler,
task_sources,
- page_creation_lifecycle_target,
+ lifecycle_gate,
..
} = page_slot;
match turn_scheduler.checkout_scheduled_turn() {
@@ -2938,7 +3000,7 @@ impl RendererOwnerLocalStore {
turn_scheduler,
&mut entry,
task_sources,
- page_creation_lifecycle_target,
+ lifecycle_gate,
trigger,
);
Ok((entry, trigger, scheduled_turn))
@@ -3151,7 +3213,7 @@ impl RendererOwnerLocalStore {
response_headers: Vec<(String, String)>,
mut vm: PageVm,
pending_download: Option<RendererPendingDownloadActivation>,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
debug_assert!(
is_on_named_owner_execution_lane_for(&owner.owner_state.local_executor),
@@ -3176,7 +3238,7 @@ impl RendererOwnerLocalStore {
owner,
slot,
entry,
- page_creation_lifecycle_target,
+ lifecycle_gate,
navigation_failure_publisher,
)?;
Ok(self.prepare_pending_page_creation(
@@ -3197,7 +3259,7 @@ impl RendererOwnerLocalStore {
response_status: u16,
response_headers: Vec<(String, String)>,
mut pending_navigation: PageVmPendingPhaseOneNavigation,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
) -> Result<RendererPendingPageCreation> {
debug_assert!(
is_on_named_owner_execution_lane_for(&owner.owner_state.local_executor),
@@ -3226,7 +3288,7 @@ impl RendererOwnerLocalStore {
owner,
slot,
entry,
- page_creation_lifecycle_target,
+ lifecycle_gate,
navigation_failure_publisher,
)?;
Ok(self.prepare_pending_page_creation(
@@ -3251,6 +3313,7 @@ impl RendererOwnerLocalStore {
navigation_failure_observer,
page_context_cancel_tx,
pending_download,
+ lifecycle_decider: None,
}
}
@@ -3291,6 +3354,12 @@ impl RendererOwnerLocalStore {
pending: RendererPendingPageCreation,
entry: RendererPageLocalEntry,
) -> RendererPageCreationResolution {
+ if pending.has_lifecycle_decider() {
+ self.restore_entry_after_command(pending.token, entry);
+ return RendererPageCreationResolution::without_renderer_output(
+ PageCreationResolution::LifecycleDecisionRequired { pending },
+ );
+ }
let commit = self.commit_page_creation_reply(pending, entry);
match commit.finalized {
Ok(finalized) => RendererPageCreationResolution {
@@ -3329,15 +3398,15 @@ impl RendererOwnerLocalStore {
navigation_failure_observer: _,
page_context_cancel_tx,
pending_download,
+ lifecycle_decider,
} = pending;
debug_assert_eq!(entry.slot.page_id(), token.page_id);
- let resume_parked_page_turn = self
- .page_hosts
- .get_mut(&token.local_host_id)
- .and_then(|host| host.pages.get_mut(&token.page_id))
- .and_then(|page_slot| page_slot.page_creation_lifecycle_target.take())
- .is_some_and(|gate| gate.parked_admitted_wake);
let result = (|| -> Result<_> {
+ ensure!(
+ lifecycle_decider.is_none(),
+ "renderer page {} tried to reply before its lifecycle decider ran",
+ token.page_id.as_u64()
+ );
if matches!(
entry.top_level_navigation_dispatch(),
RendererTopLevelNavigationDispatch::DelegateToBrowser
@@ -3366,6 +3435,12 @@ impl RendererOwnerLocalStore {
creation_artifacts,
))
})();
+ let lifecycle_gate = self
+ .page_hosts
+ .get_mut(&token.local_host_id)
+ .and_then(|host| host.pages.get_mut(&token.page_id))
+ .and_then(|page_slot| page_slot.lifecycle_gate.take());
+ let resume_parked_page_turn = lifecycle_gate.is_some_and(|gate| gate.parked_admitted_wake);
let renderer_output = entry.page_vm_mut().settle_renderer_output_publication();
// Page creation can span several admitted owner turns. Earlier turns
// may already have settled Runtime/lifecycle observations before the
@@ -3685,7 +3760,7 @@ impl RendererOwnerLocalStore {
owner: &RendererOwnerLocalContext,
slot: RendererPageSlotHandle,
mut entry: RendererPageLocalEntry,
- page_creation_lifecycle_target: Option<PageVmInitStage>,
+ lifecycle_gate: Option<PageVmInitStage>,
page_creation_navigation_failure_publisher: PageCreationNavigationFailurePublisher,
) -> Result<RendererPageToken> {
let page_id = slot.page_id();
@@ -3799,7 +3874,7 @@ impl RendererOwnerLocalStore {
slot.clone(),
entry,
task_sources,
- page_creation_lifecycle_target,
+ lifecycle_gate,
page_creation_navigation_failure_publisher,
script_environment_pin,
),
@@ -4424,8 +4499,7 @@ mod navigation_dispatch_tests {
#[test]
fn runnable_page_creation_lifecycle_clears_displaced_ordinary_grant() {
- let mut gate =
- RendererPageCreationLifecycleTargetGate::new(PageVmInitStage::DomContentLoaded);
+ let mut gate = LifecycleGate::new(PageVmInitStage::DomContentLoaded);
gate.settle_lifecycle_turn(true);
assert!(gate.reconsider_ordinary_on_next_turn);
@@ -4584,7 +4658,7 @@ mod navigation_dispatch_tests {
#[test]
fn published_page_creation_discards_reply_policy_when_observer_detaches() {
let completion = LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy: PageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ navigation_reply_policy: NavigationReplyPolicy::ReturnWithPendingNavigation,
};
let (completion, detached) = completion.detach_command_observer();
@@ -4607,7 +4681,7 @@ mod navigation_dispatch_tests {
#[test]
fn already_published_page_creation_reports_later_navigation_failure_as_background() {
let completion = LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy: PageCreationNavigationReplyPolicy::FollowBeforeReply,
+ navigation_reply_policy: NavigationReplyPolicy::FollowBeforeReply,
};
assert_eq!(
diff --git a/moli-renderer-v8/src/runtime/page.rs b/moli-renderer-v8/src/runtime/page.rs
index 4c733879e..25e05fa6c 100644
--- a/moli-renderer-v8/src/runtime/page.rs
+++ b/moli-renderer-v8/src/runtime/page.rs
@@ -670,7 +670,7 @@ impl JsRuntime {
wpt_extensions_enabled: bool,
stage: PageVmInitStage,
top_level_navigation_dispatch: crate::RendererTopLevelNavigationDispatch,
- navigation_reply_policy: crate::RendererPageCreationNavigationReplyPolicy,
+ navigation_reply_policy: crate::RendererNavigationReplyPolicy,
) -> Result<(
RendererPageHandle,
Arc<RendererPageState>,
@@ -708,12 +708,13 @@ impl JsRuntime {
Vec::new(),
wpt_extensions_enabled,
stage,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget,
+ crate::RendererReplyBoundary::Stage,
top_level_navigation_dispatch,
navigation_reply_policy,
None,
None,
None,
+ None,
)
.await
}
@@ -750,12 +751,13 @@ impl JsRuntime {
runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
wpt_extensions_enabled: bool,
stage: PageVmInitStage,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
top_level_navigation_dispatch: crate::RendererTopLevelNavigationDispatch,
- navigation_reply_policy: crate::RendererPageCreationNavigationReplyPolicy,
+ navigation_reply_policy: crate::RendererNavigationReplyPolicy,
root_frame_id: Option<String>,
reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
main_document_commit: Option<crate::RendererMainDocumentCommit>,
+ lifecycle_decider: Option<crate::RendererLifecycleDecider>,
) -> Result<(
RendererPageHandle,
Arc<RendererPageState>,
@@ -801,6 +803,7 @@ impl JsRuntime {
root_frame_id,
reserved_service_worker_client,
main_document_commit,
+ lifecycle_decider,
)
.await?;
let permit = prepared.issue_commit_permit();
@@ -842,12 +845,13 @@ impl JsRuntime {
runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
wpt_extensions_enabled: bool,
stage: PageVmInitStage,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
top_level_navigation_dispatch: crate::RendererTopLevelNavigationDispatch,
- navigation_reply_policy: crate::RendererPageCreationNavigationReplyPolicy,
+ navigation_reply_policy: crate::RendererNavigationReplyPolicy,
root_frame_id: Option<String>,
reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
main_document_commit: Option<crate::RendererMainDocumentCommit>,
+ lifecycle_decider: Option<crate::RendererLifecycleDecider>,
) -> Result<PreparedRendererDocument> {
let mut request = self
.inner
@@ -889,6 +893,7 @@ impl JsRuntime {
request.top_level_navigation_dispatch = top_level_navigation_dispatch;
request.navigation_reply_policy = navigation_reply_policy;
request.reserved_service_worker_client = reserved_service_worker_client;
+ request.lifecycle_decider = lifecycle_decider;
let reply = self
.inner
.renderer_owner
diff --git a/moli-renderer-v8/src/runtime/page_turn_scheduler.rs b/moli-renderer-v8/src/runtime/page_turn_scheduler.rs
index a55167342..e795df94c 100644
--- a/moli-renderer-v8/src/runtime/page_turn_scheduler.rs
+++ b/moli-renderer-v8/src/runtime/page_turn_scheduler.rs
@@ -270,7 +270,7 @@ impl<Entry> PageTurnScheduler<Entry> {
/// ordinary source one turn before lifecycle arbitration resumes. This
/// keeps post-target work behind the reply boundary without starving
/// resource tasks needed to reach that boundary.
- pub(super) fn select_lifecycle_target_turn_class(
+ pub(super) fn select_lifecycle_turn(
&mut self,
reconsider_displaced_ordinary: bool,
has_eligible_ordinary_task: bool,
@@ -1369,7 +1369,7 @@ mod tests {
for _ in 0..=MAX_CONSECUTIVE_PAGE_TURNS_PER_CLASS {
assert_eq!(
- scheduler.select_lifecycle_target_turn_class(
+ scheduler.select_lifecycle_turn(
false,
true,
DocumentLifecycleClassReadiness::Available,
@@ -1378,23 +1378,16 @@ mod tests {
);
}
assert_eq!(
- scheduler.select_lifecycle_target_turn_class(
- true,
- true,
- DocumentLifecycleClassReadiness::Available,
- ),
+ scheduler
+ .select_lifecycle_turn(true, true, DocumentLifecycleClassReadiness::Available,),
Some(PageTurnClass::Ordinary)
);
assert_eq!(
- scheduler.select_lifecycle_target_turn_class(
- false,
- true,
- DocumentLifecycleClassReadiness::Absent,
- ),
+ scheduler.select_lifecycle_turn(false, true, DocumentLifecycleClassReadiness::Absent,),
Some(PageTurnClass::Ordinary)
);
assert_eq!(
- scheduler.select_lifecycle_target_turn_class(
+ scheduler.select_lifecycle_turn(
true,
true,
DocumentLifecycleClassReadiness::ReadyMainParserScriptContinuation,
diff --git a/moli-renderer-v8/src/runtime/phase_one/streaming.rs b/moli-renderer-v8/src/runtime/phase_one/streaming.rs
index 9114d8034..c11c8336f 100644
--- a/moli-renderer-v8/src/runtime/phase_one/streaming.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/streaming.rs
@@ -224,7 +224,7 @@ impl ConcurrentParseTimeRuntime {
response_status: u16,
response_headers: Vec<(String, String)>,
raw_body: ExternalRawDocumentBodyStream,
- reply_boundary: crate::RendererPageCreationReplyBoundary,
+ reply_boundary: crate::RendererReplyBoundary,
) -> Result<StreamingNavigationPageCreationResult> {
if response_headers_indicate_download(&response_headers) {
let mut body_source = RawDocumentBodySource::External(raw_body);
@@ -243,13 +243,10 @@ impl ConcurrentParseTimeRuntime {
));
}
- let bootstrap_boundary = match reply_boundary {
- crate::RendererPageCreationReplyBoundary::LifecycleTarget => {
- CommittedNavigationBootstrapBoundary::ContinuePhaseOne
- }
- crate::RendererPageCreationReplyBoundary::DocumentCommit => {
- CommittedNavigationBootstrapBoundary::DocumentCommit
- }
+ let bootstrap_boundary = if reply_boundary.waits_for_stage() {
+ CommittedNavigationBootstrapBoundary::ContinuePhaseOne
+ } else {
+ CommittedNavigationBootstrapBoundary::DocumentCommit
};
Self::create_from_committed_external_raw_document_response(
page_id,
diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rs
index a5f6556ba..21c866428 100644
--- a/moli-renderer-v8/src/runtime/tests.rs
+++ b/moli-renderer-v8/src/runtime/tests.rs
@@ -14,8 +14,7 @@ use crate::local_executor::{is_on_script_execution_lane_for, scope_on_scaffold_j
use crate::network::ResourceRequestClient;
use crate::{
RendererDocumentLifecycleEventKind, RendererDocumentLifecycleMilestone,
- RendererPageCreationNavigationReplyPolicy, RendererPageCreationReplyBoundary,
- RendererTopLevelNavigationDispatch,
+ RendererNavigationReplyPolicy, RendererReplyBoundary, RendererTopLevelNavigationDispatch,
};
use parking_lot::Mutex;
use std::collections::HashSet;
@@ -57,7 +56,7 @@ async fn prepare_test_external_raw_document_with_content_type(
url,
content_type,
raw_body,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ RendererReplyBoundary::Stage,
)
.await
}
@@ -68,7 +67,7 @@ async fn prepare_test_external_raw_document_with_content_type_and_reply_boundary
url: url::Url,
content_type: &str,
raw_body: ExternalRawDocumentBodyStream,
- reply_boundary: RendererPageCreationReplyBoundary,
+ reply_boundary: RendererReplyBoundary,
) -> PreparedRendererDocument {
runtime
.prepare_streaming_raw_document_from_external_body_with_inspector_session_restores(
@@ -104,7 +103,8 @@ async fn prepare_test_external_raw_document_with_content_type_and_reply_boundary
PageVmInitStage::Load,
reply_boundary,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
+ None,
None,
None,
None,
@@ -2038,7 +2038,7 @@ async fn external_raw_streaming_page_command_builds_phase_one_page() {
false,
PageVmInitStage::Load,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
)
.await
.expect("external raw streaming page should build");
@@ -2080,7 +2080,7 @@ async fn external_raw_streaming_body_failure_preserves_committed_document_and_ow
url,
"text/html",
raw_body,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
)
.await;
drop(body_tx);
@@ -2765,7 +2765,7 @@ async fn external_raw_streaming_empty_document_reaches_dom_content_loaded() {
false,
PageVmInitStage::DomContentLoaded,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
)
.await
.expect("empty external raw streaming page should reach DOMContentLoaded");
@@ -2997,7 +2997,7 @@ async fn external_raw_streaming_delegates_post_load_meta_refresh_to_browser() {
false,
PageVmInitStage::Load,
RendererTopLevelNavigationDispatch::DelegateToBrowser,
- RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ RendererNavigationReplyPolicy::ReturnWithPendingNavigation,
)
.await
.expect("meta refresh streaming page should attach first document");
@@ -3085,7 +3085,7 @@ async fn external_raw_streaming_defers_dcl_handler_navigation_to_page_reply() {
false,
PageVmInitStage::DomContentLoaded,
RendererTopLevelNavigationDispatch::DelegateToBrowser,
- RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ RendererNavigationReplyPolicy::ReturnWithPendingNavigation,
)
.await
.expect("DCL handler page should reach its reply boundary");
@@ -3171,7 +3171,7 @@ globalThis.__ordinaryAfterDcl = new Promise(resolve => {
false,
PageVmInitStage::DomContentLoaded,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
)
.await
.expect("page should reach its DCL reply boundary");
@@ -3264,9 +3264,10 @@ async fn renderer_owned_navigation_survives_page_creation_observer_detach() {
Vec::new(),
false,
PageVmInitStage::Load,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
+ None,
None,
None,
None,
@@ -15626,7 +15627,7 @@ async fn domcontentloaded_page_creation_reply_resumes_owner_to_load_without_exte
false,
PageVmInitStage::DomContentLoaded,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
)
.await
.expect("page should reply at DOMContentLoaded");
@@ -15714,12 +15715,13 @@ async fn document_commit_background_dcl_completion_resumes_owner_to_load() {
Vec::new(),
false,
PageVmInitStage::DomContentLoaded,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
RendererTopLevelNavigationDispatch::DelegateToBrowser,
- RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ RendererNavigationReplyPolicy::ReturnWithPendingNavigation,
Some("TID-1".to_owned()),
None,
None,
+ None,
)
.await
.expect("page should attach at document commit");
@@ -15868,7 +15870,7 @@ document.addEventListener("DOMContentLoaded", () => {
page_url,
html,
RendererTopLevelNavigationDispatch::DelegateToBrowser,
- RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ RendererNavigationReplyPolicy::ReturnWithPendingNavigation,
)
.await;
@@ -15936,7 +15938,7 @@ async fn document_commit_release_runs_parser_script_location_handoff_in_backgrou
page_url,
r#"<!doctype html><script>location.href = "/final"</script>"#,
RendererTopLevelNavigationDispatch::DelegateToBrowser,
- RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ RendererNavigationReplyPolicy::ReturnWithPendingNavigation,
)
.await;
@@ -16026,7 +16028,7 @@ async fn owner_loop_completes_post_dcl_async_script_without_wait_command() {
false,
PageVmInitStage::DomContentLoaded,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
)
.await
.expect("page should reach DOMContentLoaded");
@@ -16417,7 +16419,7 @@ document.addEventListener("DOMContentLoaded", () => {
false,
PageVmInitStage::Load,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
);
tokio::pin!(creation);
@@ -16543,7 +16545,7 @@ blocked page
false,
PageVmInitStage::Load,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
);
tokio::pin!(blocked_creation);
tokio::select! {
@@ -16999,7 +17001,7 @@ async fn create_test_html_page_at_document_commit(
url,
html,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
)
.await
}
@@ -17010,7 +17012,7 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(
url: url::Url,
html: &str,
top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
- navigation_reply_policy: RendererPageCreationNavigationReplyPolicy,
+ navigation_reply_policy: RendererNavigationReplyPolicy,
) -> RendererPageHandle {
let (completion_tx, completion_rx) = oneshot::channel();
let (body_tx, raw_body) = ExternalRawDocumentBodyStream::channel(completion_rx);
@@ -17056,12 +17058,13 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(
Vec::new(),
false,
PageVmInitStage::Load,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
top_level_navigation_dispatch,
navigation_reply_policy,
None,
None,
None,
+ None,
)
.await
.expect("test HTML page should attach at document commit");
diff --git a/moli-renderer-v8/src/runtime/tests/open_streaming.rs b/moli-renderer-v8/src/runtime/tests/open_streaming.rs
index 2f34291ce..68eb8de0b 100644
--- a/moli-renderer-v8/src/runtime/tests/open_streaming.rs
+++ b/moli-renderer-v8/src/runtime/tests/open_streaming.rs
@@ -207,9 +207,10 @@ impl OpenStreamingPage {
Vec::new(),
false,
PageVmInitStage::Load,
- RendererPageCreationReplyBoundary::DocumentCommit,
+ RendererReplyBoundary::DocumentCommit,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ RendererNavigationReplyPolicy::FollowBeforeReply,
+ None,
None,
None,
None,
diff --git a/moli-test-support/src/routes_wait.rs b/moli-test-support/src/routes_wait.rs
index d596e166f..a604e1450 100644
--- a/moli-test-support/src/routes_wait.rs
+++ b/moli-test-support/src/routes_wait.rs
@@ -37,6 +37,9 @@ const WAIT_UNTIL_OUTER_HTML_TAMPER_HTML: &str = "<!doctype html><html><body data
// is around 500 ms; a 50 ms interval leaves enough margin under nextest load.
const WAIT_UNTIL_INTERVAL_FETCH_HTML: &str = "<!doctype html><html><body data-state=\"init\"><script>window.addEventListener('load', () => { setInterval(() => { fetch('/wait-until-data').then(() => { document.body.setAttribute('data-ping', String((Number(document.body.getAttribute('data-ping') || '0') + 1))); }); }, 50); });</script></body></html>";
const WAIT_UNTIL_INTERVAL_DOM_MUTATION_HTML: &str = "<!doctype html><html><body data-state=\"init\"><main id=\"mutation-count\">0</main><script>window.addEventListener('load', () => { setInterval(() => { const count = Number(document.body.getAttribute('data-mutation-count') || '0') + 1; document.body.setAttribute('data-mutation-count', String(count)); document.getElementById('mutation-count').textContent = String(count); }, 50); });</script></body></html>";
+const WAIT_UNTIL_HTTP_ERROR_NAVIGATION_CHALLENGE_HTML: &str = "<!doctype html><html><head><title>403 challenge</title></head><body><main id=\"challenge\">http-error-navigation=challenge</main><script>window.addEventListener('load', () => { setTimeout(() => { document.cookie = 'moli-http-error-navigation=passed; Path=/; Max-Age=3600; SameSite=Lax'; location.reload(); }, 75); });</script></body></html>";
+const WAIT_UNTIL_HTTP_ERROR_LATE_NAVIGATION_CHALLENGE_HTML: &str = "<!doctype html><html><head><title>late 403 challenge</title></head><body><main id=\"challenge\">http-error-navigation=late-challenge</main><script>window.addEventListener('load', () => { setTimeout(() => { document.cookie = 'moli-http-error-navigation=passed; Path=/; Max-Age=3600; SameSite=Lax'; location.reload(); }, 1200); });</script></body></html>";
+const WAIT_UNTIL_HTTP_ERROR_NAVIGATION_FINAL_HTML: &str = "<!doctype html><html><head><title>challenge passed</title></head><body><main id=\"http-error-navigation-target\">http-error-navigation=done</main><script>window.httpErrorNavigationDcl = false; window.httpErrorNavigationLoad = false; document.addEventListener('DOMContentLoaded', () => { window.httpErrorNavigationDcl = true; document.body.setAttribute('data-reached-dcl', 'true'); const script = document.createElement('script'); script.src = '/assets/runtime_owned_in_order_load_very_slow.js'; script.onload = () => { window.httpErrorNavigationSlowScript = true; const tail = document.createElement('main'); tail.id = 'http-error-navigation-load-tail'; tail.textContent = 'http-error-navigation=load-tail'; document.body.appendChild(tail); }; document.head.appendChild(script); }); window.addEventListener('load', () => { window.httpErrorNavigationLoad = true; document.body.setAttribute('data-reached-load', 'true'); });</script></body></html>";
pub(super) fn add_wait_routes(router: Router) -> Router {
router
@@ -114,6 +117,18 @@ pub(super) fn add_wait_routes(router: Router) -> Router {
"/wait-until-interval-dom-mutation",
get(wait_until_interval_dom_mutation_page),
)
+ .route(
+ "/wait-until-http-error-navigation",
+ get(wait_until_http_error_navigation_page),
+ )
+ .route(
+ "/wait-until-http-error-navigation-to-error",
+ get(wait_until_http_error_navigation_to_error_page),
+ )
+ .route(
+ "/wait-until-http-error-late-navigation",
+ get(wait_until_http_error_late_navigation_page),
+ )
.route("/wait-until-data", get(wait_until_data_page))
.route("/wait-until-json-data", get(wait_until_json_data_page))
.route("/wait-until-cookie-data", get(wait_until_cookie_data_page))
@@ -129,6 +144,46 @@ async fn wait_until_lifecycle_page() -> Html<&'static str> {
Html(WAIT_UNTIL_LIFECYCLE_HTML)
}
+async fn wait_until_http_error_navigation_page(headers: HeaderMap) -> Response {
+ if has_cookie(&headers, "moli-http-error-navigation=passed") {
+ return Html(WAIT_UNTIL_HTTP_ERROR_NAVIGATION_FINAL_HTML).into_response();
+ }
+
+ (
+ StatusCode::FORBIDDEN,
+ Html(WAIT_UNTIL_HTTP_ERROR_NAVIGATION_CHALLENGE_HTML),
+ )
+ .into_response()
+}
+
+async fn wait_until_http_error_navigation_to_error_page(headers: HeaderMap) -> Response {
+ if has_cookie(&headers, "moli-http-error-navigation=passed") {
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Html(WAIT_UNTIL_HTTP_ERROR_NAVIGATION_FINAL_HTML),
+ )
+ .into_response();
+ }
+
+ (
+ StatusCode::FORBIDDEN,
+ Html(WAIT_UNTIL_HTTP_ERROR_NAVIGATION_CHALLENGE_HTML),
+ )
+ .into_response()
+}
+
+async fn wait_until_http_error_late_navigation_page(headers: HeaderMap) -> Response {
+ if has_cookie(&headers, "moli-http-error-navigation=passed") {
+ return Html(WAIT_UNTIL_HTTP_ERROR_NAVIGATION_FINAL_HTML).into_response();
+ }
+
+ (
+ StatusCode::FORBIDDEN,
+ Html(WAIT_UNTIL_HTTP_ERROR_LATE_NAVIGATION_CHALLENGE_HTML),
+ )
+ .into_response()
+}
+
async fn wait_until_domcontentloaded_fetch_page() -> Html<&'static str> {
Html(WAIT_UNTIL_DOMCONTENTLOADED_FETCH_HTML)
}
diff --git a/moli/src/app.rs b/moli/src/app.rs
index 7df178cba..e56b73b94 100644
--- a/moli/src/app.rs
+++ b/moli/src/app.rs
@@ -1,6 +1,8 @@
//! Callable command runner for the Moli CLI.
-use std::{io::Write, sync::Arc};
+mod http_error_navigation;
+
+use std::{io::Write, sync::Arc, time::Duration};
use crate::{
cli::{Cli, Commands, FetchWaitUntil, normalize_args_for_compat},
@@ -11,12 +13,14 @@ use anyhow::Result;
use anyhow::{Context, anyhow};
use clap::{CommandFactory, Parser};
use moli_core::runtime::{
- Browser, FetchedDocument, NavigationRuntimeConfig, RenderedDomWaitUntil,
+ Browser, FetchedDocument, NavigationRuntimeConfig, PageVmInitStage, RenderedDomWaitUntil,
storage_partition::StoragePartitionState,
};
-use moli_fetch::Request;
+use moli_fetch::{Request, ensure_http_status_success};
use moli_protocol_server::ProtocolServer;
+use self::http_error_navigation::{fetch_with_http_error_navigation, is_http_error_status};
+
pub async fn run_from_env() -> Result<()> {
let cli = Cli::parse_from(normalize_args_for_compat(std::env::args_os()));
let config = AppConfig::from_cli(&cli).context("failed to build app configuration")?;
@@ -58,30 +62,38 @@ pub async fn run_cli_with_config<W: Write>(
.context("failed to initialize browser runtime")?;
load_cookie_state(&browser, &config)?;
let timeout = std::time::Duration::from_millis(args.timeout);
+ let navigation_grace = Duration::from_millis(args.redirect_time);
let request = build_fetch_request(&args.url, &config)?;
let fetch_result = match args.wait_until {
FetchWaitUntil::Done => {
- browser
- .fetch_request_document_allow_http_error(request)
- .await
+ fetch_with_http_error_navigation(
+ &browser,
+ request,
+ RenderedDomWaitUntil::Done,
+ timeout,
+ navigation_grace,
+ )
+ .await
}
FetchWaitUntil::DomContentLoaded => {
- browser
- .fetch_request_document_allow_http_error_with_wait_until(
- request,
- RenderedDomWaitUntil::DomContentLoaded,
- timeout,
- )
- .await
+ fetch_with_http_error_navigation(
+ &browser,
+ request,
+ RenderedDomWaitUntil::DomContentLoaded,
+ timeout,
+ navigation_grace,
+ )
+ .await
}
FetchWaitUntil::Load => {
- browser
- .fetch_request_document_allow_http_error_with_wait_until(
- request,
- RenderedDomWaitUntil::Load,
- timeout,
- )
- .await
+ fetch_with_http_error_navigation(
+ &browser,
+ request,
+ RenderedDomWaitUntil::Load,
+ timeout,
+ navigation_grace,
+ )
+ .await
}
FetchWaitUntil::NetworkIdle => {
browser
@@ -113,6 +125,21 @@ pub async fn run_cli_with_config<W: Write>(
let mut page = match fetched_document {
FetchedDocument::Page(page) => page,
FetchedDocument::Raw(raw_document) => {
+ if lifecycle_stage_for_fetch_wait(args.wait_until).is_some()
+ && is_http_error_status(raw_document.status())
+ {
+ let status_error = ensure_http_status_success(
+ raw_document.final_url().as_str(),
+ raw_document.status(),
+ false,
+ );
+ finalize_fetch_browser(browser);
+ return status_error
+ .context(
+ "HTTP error response is not an executable document and cannot navigate",
+ )
+ .with_context(|| anyhow!("failed to fetch `{}`", args.url));
+ }
if config.fetch.response_wait.is_some()
|| args.wait_selector.is_some()
|| args.wait_script.is_some()
@@ -136,6 +163,28 @@ pub async fn run_cli_with_config<W: Write>(
}
};
+ if lifecycle_stage_for_fetch_wait(args.wait_until).is_some()
+ && is_http_error_status(page.status())
+ {
+ let error = ensure_http_status_success(
+ page.final_url().as_str(),
+ page.status(),
+ false,
+ )
+ .context(
+ "navigation from the HTTP error document reached another HTTP error document",
+ )
+ .expect_err("HTTP error status must fail success validation");
+ if let Err(close_error) = page.close_async().await {
+ tracing::warn!(
+ error = %close_error,
+ "failed to close fetched page after HTTP error navigation failure"
+ );
+ }
+ finalize_fetch_browser(browser);
+ return Err(error).with_context(|| anyhow!("failed to fetch `{}`", args.url));
+ }
+
if let Some(response_wait) = config.fetch.response_wait.clone() {
browser
.wait_for_subresource_response(&mut page, response_wait, timeout)
@@ -217,6 +266,18 @@ fn build_fetch_request(url: &str, config: &AppConfig) -> Result<Request> {
Ok(request)
}
+fn lifecycle_stage_for_fetch_wait(wait_until: FetchWaitUntil) -> Option<PageVmInitStage> {
+ // Only waits defined by a concrete Document lifecycle milestone opt into
+ // HTTP-error navigation recovery. `done` uses the fetch path's historical
+ // load boundary; network-idle and DOM-stable remain post-load page-state
+ // waits and keep their existing HTTP-error dump behavior.
+ match wait_until {
+ FetchWaitUntil::DomContentLoaded => Some(PageVmInitStage::DomContentLoaded),
+ FetchWaitUntil::Load | FetchWaitUntil::Done => Some(PageVmInitStage::Load),
+ FetchWaitUntil::NetworkIdle | FetchWaitUntil::DomStable => None,
+ }
+}
+
fn load_cookie_state(browser: &Browser, config: &AppConfig) -> Result<()> {
browser.import_cookies(load_cookie_state_cookies(config)?)?;
Ok(())
diff --git a/moli/src/app/http_error_navigation.rs b/moli/src/app/http_error_navigation.rs
new file mode 100644
index 000000000..cf5810f29
--- /dev/null
+++ b/moli/src/app/http_error_navigation.rs
@@ -0,0 +1,45 @@
+//! CLI policy for replacing an HTTP error Document with its next navigation.
+//!
+//! HTTP status interpretation and timeout configuration belong to the CLI
+//! layer. The renderer receives only the generic lifecycle-target decision.
+
+use anyhow::Result;
+use moli_core::runtime::{
+ Browser, FetchedDocument, RenderedDomWaitUntil, RendererLifecycleDecision,
+};
+use moli_fetch::Request;
+use std::time::Duration;
+
+pub(super) fn is_http_error_status(status: u16) -> bool {
+ (400..=599).contains(&status)
+}
+
+pub(super) async fn fetch_with_http_error_navigation(
+ browser: &Browser,
+ request: Request,
+ wait_until: RenderedDomWaitUntil,
+ stage_timeout: Duration,
+ navigation_grace: Duration,
+) -> Result<FetchedDocument> {
+ let navigation_grace_ms = navigation_grace.as_millis().min(u128::from(u64::MAX)) as u64;
+ // The first DCL/load is delivered to this synchronous decision normally.
+ // A 4xx/5xx gets one grace window to start a replacement navigation; the
+ // successor then has its own complete budget to reach the same stage.
+ browser
+ .fetch_document_with_lifecycle_decider(
+ request,
+ wait_until,
+ stage_timeout,
+ navigation_grace.saturating_add(stage_timeout),
+ move |target| {
+ Ok(if is_http_error_status(target.status) {
+ RendererLifecycleDecision::FollowNextDocument {
+ navigation_grace_ms,
+ }
+ } else {
+ RendererLifecycleDecision::Finish
+ })
+ },
+ )
+ .await
+}
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index 0ed5b0e82..6576ac386 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -13,6 +13,7 @@ const FETCH_INFER_FLAGS: &[&str] = &[
"--with-base",
"--with-frames",
"--wait-until",
+ "--redirect-time",
"--wait-selector",
"--wait-script",
"--wait-script-file",
@@ -49,6 +50,8 @@ const DUMP_MODES: &[&str] = &[
"semantic_tree_text",
];
+pub const DEFAULT_REDIRECT_TIME_MS: u64 = 1_000;
+
#[derive(Debug, Clone, PartialEq, Eq, Parser)]
#[command(
name = "moli",
@@ -101,6 +104,18 @@ pub struct FetchArgs {
#[arg(long, value_enum, default_value = "done")]
pub wait_until: FetchWaitUntil,
+ /// Milliseconds to wait for a client-side replacement navigation after an
+ /// executable 4xx/5xx Document reaches the selected lifecycle stage. A
+ /// value of 0 disables additional waiting but still accepts a navigation
+ /// that is already pending when the stage result is inspected. This only
+ /// applies to `domcontentloaded`, `load`, and `done` waits.
+ #[arg(
+ long,
+ value_name = "MILLISECONDS",
+ default_value_t = DEFAULT_REDIRECT_TIME_MS
+ )]
+ pub redirect_time: u64,
+
#[arg(long)]
pub wait_selector: Option<String>,
@@ -502,7 +517,10 @@ fn infer_command(next: Option<&OsString>) -> Option<&'static str> {
return Some("fetch");
}
- if FETCH_INFER_FLAGS.contains(&next.as_ref()) {
+ if FETCH_INFER_FLAGS
+ .iter()
+ .any(|flag| next == *flag || next.starts_with(&format!("{flag}=")))
+ {
return Some("fetch");
}
@@ -559,6 +577,18 @@ mod tests {
}
}
+ #[test]
+ fn redirect_time_infers_fetch_command() {
+ let args =
+ normalize_args_for_compat(["moli", "--redirect-time=1500", "https://example.test/"]);
+ let cli = Cli::parse_from(args);
+
+ match cli.command {
+ Commands::Fetch(args) => assert_eq!(args.redirect_time, 1_500),
+ other => panic!("expected fetch command, got {other:?}"),
+ }
+ }
+
#[test]
fn port_equals_infers_serve_command() {
let args = normalize_args_for_compat(["moli", "--port=0"]);
diff --git a/moli/tests/cli.rs b/moli/tests/cli.rs
index 101cf4a6b..bc6b9d675 100644
--- a/moli/tests/cli.rs
+++ b/moli/tests/cli.rs
@@ -93,6 +93,7 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
trace_matched_response_body: false,
strip_mode: vec![StripModeChoice::Css, StripModeChoice::Ui],
wait_until: FetchWaitUntil::Done,
+ redirect_time: 1_000,
wait_selector: None,
wait_script: None,
wait_script_file: None,
@@ -384,6 +385,7 @@ fn infers_fetch_mode_from_bare_url() {
trace_matched_response_body: false,
strip_mode: vec![],
wait_until: FetchWaitUntil::Done,
+ redirect_time: 1_000,
wait_selector: None,
wait_script: None,
wait_script_file: None,
@@ -419,6 +421,7 @@ fn infers_fetch_mode_from_fetch_only_flags_and_defaults_dump_to_html() {
trace_matched_response_body: false,
strip_mode: vec![],
wait_until: FetchWaitUntil::Done,
+ redirect_time: 1_000,
wait_selector: None,
wait_script: None,
wait_script_file: None,
@@ -458,6 +461,7 @@ fn infers_fetch_mode_from_header_flag() {
trace_matched_response_body: false,
strip_mode: vec![],
wait_until: FetchWaitUntil::Done,
+ redirect_time: 1_000,
wait_selector: None,
wait_script: None,
wait_script_file: None,
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs
index 904d26759..1af0c5f73 100644
--- a/moli/tests/fetch_cli.rs
+++ b/moli/tests/fetch_cli.rs
@@ -131,6 +131,20 @@ fn run_fetch_cli_with_dump_and_args(url: &str, dump: &str, args: &[&str]) -> Res
run_moli(cli_args)
}
+fn run_fetch_cli_with_default_wait_and_dump(url: &str, dump: &str) -> Result<Output> {
+ run_moli([
+ "moli",
+ "fetch",
+ "--log-level",
+ "error",
+ "--http-no-proxy",
+ "*",
+ "--dump",
+ dump,
+ url,
+ ])
+}
+
fn run_moli<I, S>(args: I) -> Result<Output>
where
I: IntoIterator<Item = S>,
@@ -2028,11 +2042,11 @@ fn cli_load_waits_for_slow_post_domcontentloaded_runtime_script() -> Result<()>
}
#[test]
-fn cli_dump_json_preserves_non_success_status_without_process_failure() -> Result<()> {
+fn cli_domcontentloaded_recovers_from_delayed_403_navigation_at_same_stage() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let server = runtime.block_on(FixtureServer::spawn())?;
- let url = server.url("/net/upstream/xhr/404");
- let output = run_fetch_cli_with_dump_and_args(&url, "json", &[])?;
+ let url = server.url("/wait-until-http-error-navigation");
+ let output = run_fetch_cli_with_wait_until(&url, "domcontentloaded")?;
runtime.block_on(server.shutdown());
assert!(
@@ -2041,45 +2055,268 @@ fn cli_dump_json_preserves_non_success_status_without_process_failure() -> Resul
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("id=\"http-error-navigation-target\""),
+ "stdout={stdout}"
+ );
+ assert!(
+ stdout.contains("data-reached-dcl=\"true\""),
+ "stdout={stdout}"
+ );
+ assert!(!stdout.contains("id=\"challenge\""), "stdout={stdout}");
+ Ok(())
+}
+
+#[test]
+fn cli_load_recovers_from_delayed_403_navigation_at_same_stage() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/wait-until-http-error-navigation");
+ let output = run_fetch_cli_with_wait_until(&url, "load")?;
+ runtime.block_on(server.shutdown());
+
+ assert!(
+ output.status.success(),
+ "moli fetch failed: stdout={}\nstderr={}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("id=\"http-error-navigation-target\""),
+ "stdout={stdout}"
+ );
+ assert!(
+ stdout.contains("data-reached-load=\"true\""),
+ "stdout={stdout}"
+ );
+ assert!(
+ stdout.contains("id=\"http-error-navigation-load-tail\""),
+ "load must include the replacement load tail: stdout={stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn cli_load_keeps_the_successor_stage_timeout_after_403_navigation() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/wait-until-http-error-navigation");
+ let output = run_fetch_cli_with_dump_and_args(&url, "html", &["--timeout", "250"])?;
+ runtime.block_on(server.shutdown());
+
+ assert!(!output.status.success());
+ let stdout = clean_output(&output.stdout);
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(
+ stderr.contains("successor navigation")
+ && stderr.contains("Load")
+ && stderr.contains("timed out"),
+ "stderr={stderr}"
+ );
+ Ok(())
+}
+
+#[test]
+fn cli_default_done_recovers_from_delayed_403_navigation_at_load() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/wait-until-http-error-navigation");
+ let output = run_fetch_cli_with_default_wait_and_dump(&url, "json")?;
+ runtime.block_on(server.shutdown());
+ assert!(
+ output.status.success(),
+ "moli fetch failed: stdout={}\nstderr={}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
let stdout = clean_output(&output.stdout);
let payload: Value = serde_json::from_str(&stdout)?;
- assert_json_dump_shape(&payload, &url, 404);
+ assert_json_dump_shape(&payload, &url, 200);
+ let html = payload["html"].as_str().unwrap_or_default();
assert!(
- payload["html"]
- .as_str()
- .unwrap_or_default()
- .contains("Not Found"),
+ html.contains("id=\"http-error-navigation-target\""),
+ "stdout={stdout}"
+ );
+ assert!(
+ html.contains("id=\"http-error-navigation-load-tail\""),
"stdout={stdout}"
);
Ok(())
}
#[test]
-fn cli_dump_json_non_success_does_not_retry_request() -> Result<()> {
+fn cli_explicit_load_fails_when_404_does_not_navigate_and_does_not_retry() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let server = runtime.block_on(FixtureServer::spawn())?;
let url = server.url("/net/upstream/xhr/404-then-200");
let output = run_fetch_cli_with_dump_and_args(&url, "json", &[])?;
runtime.block_on(server.shutdown());
+ assert!(
+ !output.status.success(),
+ "an HTTP error document without navigation must fail: stdout={}\nstderr={}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(stderr.contains("404 Not Found"), "stderr={stderr}");
+ assert!(stderr.contains("1000 ms grace period"), "stderr={stderr}");
+ Ok(())
+}
+
+#[test]
+fn cli_explicit_domcontentloaded_fails_when_500_does_not_navigate() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/net/upstream/xhr/500");
+ let output = run_fetch_cli_with_wait_until(&url, "domcontentloaded")?;
+ runtime.block_on(server.shutdown());
+
+ assert!(!output.status.success());
+ let stdout = clean_output(&output.stdout);
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(
+ stderr.contains("500 Internal Server Error"),
+ "stderr={stderr}"
+ );
+ assert!(stderr.contains("1000 ms grace period"), "stderr={stderr}");
+ Ok(())
+}
+
+#[test]
+fn cli_explicit_load_rejects_navigation_after_the_one_second_grace() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/wait-until-http-error-late-navigation");
+ let output = run_fetch_cli_with_wait_until(&url, "load")?;
+ runtime.block_on(server.shutdown());
+
+ assert!(!output.status.success());
+ let stdout = clean_output(&output.stdout);
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(stderr.contains("403 Forbidden"), "stderr={stderr}");
+ assert!(stderr.contains("1000 ms grace period"), "stderr={stderr}");
+ Ok(())
+}
+
+#[test]
+fn cli_redirect_time_can_extend_http_error_navigation_grace() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/wait-until-http-error-late-navigation");
+ let output = run_fetch_cli_with_dump_and_args(&url, "html", &["--redirect-time", "1500"])?;
+ runtime.block_on(server.shutdown());
+
assert!(
output.status.success(),
"moli fetch failed: stdout={}\nstderr={}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
-
let stdout = clean_output(&output.stdout);
- let payload: Value = serde_json::from_str(&stdout)?;
- assert_json_dump_shape(&payload, &url, 404);
assert!(
- payload["html"]
- .as_str()
- .unwrap_or_default()
- .contains("first-hit-404"),
+ stdout.contains("id=\"http-error-navigation-target\""),
"stdout={stdout}"
);
+ assert!(
+ stdout.contains("id=\"http-error-navigation-load-tail\""),
+ "the configured grace must still preserve the requested Load stage: stdout={stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn cli_explicit_load_rejects_http_error_navigation_to_another_error() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/wait-until-http-error-navigation-to-error");
+ let output = run_fetch_cli_with_wait_until(&url, "load")?;
+ runtime.block_on(server.shutdown());
+
+ assert!(!output.status.success());
+ let stdout = clean_output(&output.stdout);
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(
+ stderr.contains("500 Internal Server Error"),
+ "stderr={stderr}"
+ );
+ assert!(
+ stderr.contains("reached another HTTP error document"),
+ "stderr={stderr}"
+ );
+ Ok(())
+}
+
+#[test]
+fn cli_non_lifecycle_wait_modes_keep_http_error_dump_behavior() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/net/upstream/xhr/404");
+
+ for wait_until in ["networkidle", "domstable"] {
+ let output = run_fetch_cli_with_wait_until(&url, wait_until)?;
+ assert!(
+ output.status.success(),
+ "wait_until={wait_until} stdout={} stderr={}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ clean_output(&output.stdout).contains("Not Found"),
+ "wait_until={wait_until} stdout={}",
+ clean_output(&output.stdout)
+ );
+ }
+
+ runtime.block_on(server.shutdown());
+ Ok(())
+}
+
+#[test]
+fn cli_default_done_fails_when_http_error_document_does_not_navigate() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/net/upstream/xhr/404");
+ let output = run_fetch_cli_with_default_wait_and_dump(&url, "json")?;
+ runtime.block_on(server.shutdown());
+
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ !output.status.success(),
+ "default done must fail an HTTP error document without navigation: stdout={stdout}"
+ );
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(stderr.contains("404 Not Found"), "stderr={stderr}");
+ assert!(stderr.contains("1000 ms grace period"), "stderr={stderr}");
+ Ok(())
+}
+
+#[test]
+fn cli_default_done_http_error_wait_does_not_retry_request() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(FixtureServer::spawn())?;
+ let url = server.url("/net/upstream/xhr/404-then-200");
+ let output = run_fetch_cli_with_default_wait_and_dump(&url, "json")?;
+ runtime.block_on(server.shutdown());
+
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ !output.status.success(),
+ "a hidden HTTP retry would incorrectly receive the fixture's second 200 response"
+ );
+ let stderr = clean_output(&output.stderr);
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(stderr.contains("404 Not Found"), "stderr={stderr}");
Ok(())
}