Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions moli-core/src/page/wait_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ use crate::{
};

impl Page {
pub(crate) async fn complete_post_load_ready_tasks(&mut self) -> Result<()> {
self.dispatch_unit_page_command_async(
RendererPageCommand::CompletePostLoadReadyTasks,
"complete post-load ready tasks",
)
.await
}

pub async fn ms_to_next_timeout(&mut self) -> Result<Option<u64>> {
let reply = self
.dispatch_page_command_async(RendererPageCommand::MsToNextTimeout)
Expand Down
34 changes: 23 additions & 11 deletions moli-core/src/runtime/lifecycle_fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ impl Browser {
/// 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. The original `timeout` covers the request, the first lifecycle
/// target, any successor-navigation grace period, and the successor target.
/// target, any successor-navigation grace period, the successor target,
/// and the post-Load stability observation requested by Done.
pub async fn fetch_document_with_lifecycle_decider<F>(
&self,
request: Request,
Expand All @@ -43,7 +44,8 @@ impl Browser {
}

/// Applies a lifecycle decision using a caller-owned absolute deadline.
/// The same deadline can then gate response, selector, and script waits;
/// Done consumes this deadline while observing post-Load DOM stability;
/// the caller can reuse any remaining budget for later waits.
/// `raw_document_policy` decides whether a non-Page response is read or
/// rejected from its headers.
pub async fn fetch_document_with_lifecycle_decider_and_deadline<F>(
Expand All @@ -67,14 +69,24 @@ impl Browser {
"a lifecycle decider requires DCL, load, or done"
);
let decider = RendererLifecycleDecider::new(decider);
self.fetch_document_to_base_stage(
request,
wait_until,
deadline,
RendererReplyBoundary::Stage,
Some(decider),
raw_document_policy,
)
.await
let fetched = self
.fetch_document_to_base_stage(
request,
wait_until,
deadline,
RendererReplyBoundary::Stage,
Some(decider),
raw_document_policy,
)
.await?;

match fetched {
FetchedDocument::Page(mut page) => {
self.wait_for_page_readiness_with_deadline(&mut page, wait_until, deadline)
.await?;
Ok(FetchedDocument::Page(page))
}
FetchedDocument::Raw(raw) => Ok(FetchedDocument::Raw(raw)),
}
}
}
96 changes: 67 additions & 29 deletions moli-core/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,10 @@ impl RawDocumentFetchPolicy {
}

fn is_fetch_readiness_timeout(error: &anyhow::Error, wait_until: RenderedDomWaitUntil) -> bool {
let expected = match wait_until {
RenderedDomWaitUntil::NetworkIdle => "timed out waiting for networkidle",
RenderedDomWaitUntil::DomStable => "timed out waiting for domstable",
RenderedDomWaitUntil::DomContentLoaded
| RenderedDomWaitUntil::Load
| RenderedDomWaitUntil::Done => return false,
let Some(wait) = wait_until.best_effort_page_wait() else {
return false;
};
let expected = wait.timeout_message();

error.chain().any(|cause| cause.to_string() == expected)
}
Expand Down Expand Up @@ -178,22 +175,48 @@ pub enum RenderedDomWaitUntil {
Load,
NetworkIdle,
DomStable,
/// Reach Load, then observe best-effort DOM stability.
Done,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BestEffortPageWait {
NetworkIdle,
DomStable,
}

// `done` is the default content-extraction boundary, so it must collect the
// common post-Load render turn without turning a continuously mutating page
// into a full command-timeout wait. Callers that need a longer observation can
// request `domstable` explicitly.
const DONE_POST_LOAD_STABILITY_BUDGET: Duration = Duration::from_secs(3);

impl BestEffortPageWait {
fn timeout_message(self) -> &'static str {
match self {
Self::NetworkIdle => "timed out waiting for networkidle",
Self::DomStable => "timed out waiting for domstable",
}
}
}

impl RenderedDomWaitUntil {
/// The concrete lifecycle boundary at which a live `Page` can first be
/// handed back to the host. Network-idle and DOM-stable are observations
/// made on that live Page, after Load and DCL respectively.
/// handed back to the host. Network-idle, DOM-stable, and Done add an
/// observation on that live Page after Load, DCL, and Load respectively.
fn base_stage(self) -> PageVmInitStage {
match self {
Self::DomContentLoaded | Self::DomStable => PageVmInitStage::DomContentLoaded,
Self::Load | Self::NetworkIdle | Self::Done => PageVmInitStage::Load,
}
}

fn has_best_effort_page_wait(self) -> bool {
matches!(self, Self::NetworkIdle | Self::DomStable)
fn best_effort_page_wait(self) -> Option<BestEffortPageWait> {
match self {
Self::NetworkIdle => Some(BestEffortPageWait::NetworkIdle),
Self::DomStable | Self::Done => Some(BestEffortPageWait::DomStable),
Self::DomContentLoaded | Self::Load => None,
}
}
}

Expand Down Expand Up @@ -498,8 +521,9 @@ impl Browser {
}

/// Reaches the concrete lifecycle boundary that makes a live Page
/// available. For NetworkIdle and DomStable this is only the Load or DCL
/// base stage; their best-effort observation runs outside materialization.
/// available. For NetworkIdle, DomStable, and Done this is only the Load,
/// DCL, or Load base stage; their best-effort observation runs outside
/// materialization.
async fn fetch_document_to_base_stage(
&self,
request: Request,
Expand All @@ -523,8 +547,8 @@ impl Browser {
);
// This deadline is strict: if the response or base DCL/Load stage does
// not arrive in time, there is no Page on which best-effort readiness
// can operate. Only the later NetworkIdle/DomStable observation may
// soften an expired deadline.
// can operate. Only the later NetworkIdle/DOM-stability observation
// may soften an expired deadline.
let outer_deadline = deadline.at();
let requested_url = request.url.clone();
if is_about_blank_url(&requested_url) {
Expand Down Expand Up @@ -807,7 +831,10 @@ impl Browser {
.await
}

/// Observes NetworkIdle or DomStable with the unspent part of `deadline`.
/// Observes NetworkIdle or DOM stability with the unspent part of
/// `deadline`. Done uses the DOM-stability observation after first reaching
/// Load, so post-load fragments are included by the default completion
/// strategy without changing the explicit Load boundary.
///
/// A timeout in this observation is deliberately best-effort: the Page
/// has already reached its required Load/DCL base stage, so the current
Expand All @@ -819,29 +846,39 @@ impl Browser {
wait_until: RenderedDomWaitUntil,
deadline: FetchDeadline,
) -> Result<()> {
if !wait_until.has_best_effort_page_wait() {
return Ok(());
if matches!(wait_until, RenderedDomWaitUntil::Done) {
page.complete_post_load_ready_tasks().await?;
}
let Some(page_wait) = wait_until.best_effort_page_wait() else {
return Ok(());
};

let loader = self.resource_request_client();
let remaining = deadline.remaining();
let result = match wait_until {
RenderedDomWaitUntil::NetworkIdle => {
let observation_budget = if matches!(wait_until, RenderedDomWaitUntil::Done) {
remaining.min(DONE_POST_LOAD_STABILITY_BUDGET)
} else {
remaining
};
let observation_deadline = tokio::time::Instant::now()
.checked_add(observation_budget)
.unwrap_or_else(|| deadline.at())
.min(deadline.at());
let result = match page_wait {
BestEffortPageWait::NetworkIdle => {
tokio::time::timeout_at(
deadline.at(),
page.wait_for_network_idle(&loader, remaining),
observation_deadline,
page.wait_for_network_idle(&loader, observation_budget),
)
.await
}
RenderedDomWaitUntil::DomStable => {
tokio::time::timeout_at(deadline.at(), page.wait_for_dom_stable(&loader, remaining))
.await
BestEffortPageWait::DomStable => {
tokio::time::timeout_at(
observation_deadline,
page.wait_for_dom_stable(&loader, observation_budget),
)
.await
}
RenderedDomWaitUntil::DomContentLoaded
| RenderedDomWaitUntil::Load
| RenderedDomWaitUntil::Done => unreachable!(
"concrete lifecycle modes returned before starting a best-effort Page wait"
),
};

let timeout_error = match result {
Expand All @@ -862,6 +899,7 @@ impl Browser {
wait_until = ?wait_until,
timeout_ms = deadline.timeout().as_millis(),
remaining_ms = remaining.as_millis(),
observation_ms = observation_budget.as_millis(),
error = %timeout_error,
"fetch readiness wait timed out; returning best-effort page"
);
Expand Down
62 changes: 62 additions & 0 deletions moli-core/src/runtime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,58 @@ async fn fetch_done_does_not_wait_for_future_interval_timers() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fetch_done_consumes_one_queued_render_turn_without_waiting_for_background_timers()
-> Result<()> {
let server = FixtureServer::spawn().await?;
let browser = Browser::new(AppConfig::default())?;

let page = tokio::time::timeout(
Duration::from_secs(1),
browser.fetch_with_wait_until(
&server.url("/runtime/post-load-ready-turn"),
RenderedDomWaitUntil::Done,
Duration::from_millis(750),
),
)
.await
.context("done should settle the queued render turn without waiting for background timers")??;

let html = page.serialize_html_async().await?;
assert!(
html.contains("<table id=\"live-demo\"><tbody><tr><td>ready</td></tr></tbody></table>"),
"the post-load rAF, zero-delay task, and microtask chain should reach the snapshot: {html}"
);
assert!(
!html.contains("data-fallback=\"ran\""),
"the five-second fallback must stay pending: {html}"
);
server.shutdown().await;
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fetch_load_stops_at_the_exact_lifecycle_boundary() -> Result<()> {
let server = FixtureServer::spawn().await?;
let browser = Browser::new(AppConfig::default())?;

let page = browser
.fetch_with_wait_until(
&server.url("/runtime/post-load-ready-turn"),
RenderedDomWaitUntil::Load,
Duration::from_millis(750),
)
.await?;

let html = page.serialize_html_async().await?;
assert!(
!html.contains("id=\"live-demo\""),
"load must not settle work queued after its exact lifecycle boundary: {html}"
);
server.shutdown().await;
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fetch_allow_http_error_materializes_error_status_pages() -> Result<()> {
let server = FixtureServer::spawn().await?;
Expand Down Expand Up @@ -2147,6 +2199,11 @@ async fn best_effort_page_readiness_consumes_only_the_remaining_fetch_deadline()
"/wait-until-slow-interval-dom-mutation",
"id=\"mutation-count\"",
),
(
RenderedDomWaitUntil::Done,
"/wait-until-slow-interval-dom-mutation",
"id=\"mutation-count\"",
),
] {
// The main response costs 500 ms. Readiness must receive only the
// roughly 500 ms left in this one-second plan, not a fresh second.
Expand Down Expand Up @@ -2216,6 +2273,10 @@ async fn page_fetch_wait_until_apis_do_not_restart_best_effort_timeout() -> Resu
RenderedDomWaitUntil::DomStable,
"/wait-until-slow-interval-dom-mutation",
),
(
RenderedDomWaitUntil::Done,
"/wait-until-slow-interval-dom-mutation",
),
] {
let started = std::time::Instant::now();
let page = browser
Expand All @@ -2241,6 +2302,7 @@ async fn best_effort_readiness_does_not_soften_a_base_lifecycle_timeout() -> Res
for wait_until in [
RenderedDomWaitUntil::NetworkIdle,
RenderedDomWaitUntil::DomStable,
RenderedDomWaitUntil::Done,
] {
// No Page exists at 200 ms because the main response itself takes
// 500 ms. Best effort applies only after the Load/DCL base boundary.
Expand Down
41 changes: 41 additions & 0 deletions moli-core/tests/fetch_behaviors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1566,6 +1566,47 @@ async fn fetch_with_domstable_waits_for_delayed_fetch_dom_mutation() -> Result<(
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fetch_with_done_waits_for_post_load_fetch_dom_mutation() -> Result<()> {
let server = FixtureServer::spawn().await?;
let browser = Browser::new(AppConfig::default())?;

let page = browser
.fetch_with_wait_until(
&server.url("/wait-until-delayed-fetch"),
RenderedDomWaitUntil::Done,
Duration::from_secs(5),
)
.await?;
let html = page.serialize_html_async().await?;
assert!(html.contains("data-state=\"settled\""), "html={html}");
assert!(html.contains("id=\"late\""), "html={html}");
assert!(html.contains(">settled<"), "html={html}");

server.shutdown().await;
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fetch_with_done_waits_for_external_script_inserted_after_load() -> Result<()> {
let server = FixtureServer::spawn().await?;
let browser = Browser::new(AppConfig::default())?;

let page = browser
.fetch_with_wait_until(
&server.url("/wait-until-post-load-external-script"),
RenderedDomWaitUntil::Done,
Duration::from_secs(5),
)
.await?;
let html = page.serialize_html_async().await?;
assert!(html.contains("id=\"post-load-results\""), "html={html}");
assert!(html.contains(">rendered result<"), "html={html}");

server.shutdown().await;
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fetch_with_domstable_waits_for_late_complete_dom_mutation() -> Result<()> {
let server = FixtureServer::spawn().await?;
Expand Down
1 change: 1 addition & 0 deletions moli-renderer-v8/src/devtools/command/nested.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl RendererPageCommand {
| Self::WaitForScriptTruthy { .. }
| Self::WaitForSubresourceResponse { .. }
| Self::CompleteChildFrameLifecycleWorkBestEffort { .. }
| Self::CompletePostLoadReadyTasks
| Self::SetDocumentContent { .. }
| Self::NavigateChildFrame { .. }
| Self::NavigateTopLevelSameDocument { .. }
Expand Down
9 changes: 9 additions & 0 deletions moli-renderer-v8/src/document_runtime/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,15 @@ impl DocumentRuntime {
self.timeouts.next_ready_timer_deadline(selection)
}

pub(crate) fn next_post_load_ready_deadline_at_or_before(
&self,
cutoff: std::time::Instant,
animation_frame_queued_at_or_before: std::time::Instant,
) -> Option<std::time::Instant> {
self.timeouts
.next_post_load_ready_deadline_at_or_before(cutoff, animation_frame_queued_at_or_before)
}

pub(crate) fn ms_to_next_timeout(&self) -> Option<u64> {
self.timeouts.ms_to_next()
}
Expand Down
Loading
Loading