Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(fetch): clarify transport redirects and cancellation

ldm0b6a1e93e89f7
diff --git a/moli-fetch/src/blocking/cache.rs b/moli-fetch/src/blocking/cache.rs
index c9afc8743..7f3ccfd7a 100644
--- a/moli-fetch/src/blocking/cache.rs
+++ b/moli-fetch/src/blocking/cache.rs
@@ -157,14 +157,14 @@ pub(crate) fn next_followed_redirect_url_from_parts(
// A browser may follow redirects itself, preserving the full URL list for
// CORS and Fetch Metadata while asking this transport for only one hop.
// Only automatically followed transport requests consume this layer's limit.
- let transport_redirect_count = if request.follows_redirects() {
+ let transport_redirect_count = if request.transport_follows_redirects() {
redirect_count
} else {
0
};
let next_url =
next_redirect_url_from_parts(final_url, status, headers, transport_redirect_count)?;
- if request.follows_redirects()
+ if request.transport_follows_redirects()
&& let Some(next_url) = next_url.as_ref()
{
ensure_http_network_transport_url(next_url)?;
diff --git a/moli-fetch/src/blocking/collectors.rs b/moli-fetch/src/blocking/collectors.rs
index 12e4a62ce..278fe9321 100644
--- a/moli-fetch/src/blocking/collectors.rs
+++ b/moli-fetch/src/blocking/collectors.rs
@@ -958,7 +958,7 @@ impl RawStreamingResponseCollector {
let Some(current_url) = self.current_url.clone() else {
return;
};
- if self.redirect_handling.follows_redirects() && is_redirect_response {
+ if self.redirect_handling.transport_follows_redirects() && is_redirect_response {
return;
}
if self.defer_not_modified_start && self.status == 304 {
diff --git a/moli-fetch/src/cancellation.rs b/moli-fetch/src/cancellation.rs
index bd454db69..0203bb1fc 100644
--- a/moli-fetch/src/cancellation.rs
+++ b/moli-fetch/src/cancellation.rs
@@ -143,6 +143,9 @@ struct FetchLifecycleState {
response_progress: Mutex<ResponseProgress>,
}
+/// Cancellation authority and selected response progress are independent.
+/// Only pending-only cancellation arbitrates with transport completion;
+/// unconditional cancellation can coexist with committed response progress.
#[derive(Debug, Clone, Default)]
pub struct FetchCancelHandle {
state: Arc<FetchLifecycleState>,
@@ -168,6 +171,11 @@ impl FetchCancelHandle {
Self::default()
}
+ /// Unconditionally requests cancellation of this handle and its descendants.
+ /// This does not lock response selection or change the selected progress.
+ /// An already committed result or a racing completion can therefore coexist
+ /// with cancellation, including when cancellation comes from an ancestor.
+ /// Use [`Self::cancel_if_response_pending`] to arbitrate with completion.
pub fn cancel(&self) {
self.state.cancellation.cancel();
}
@@ -175,6 +183,9 @@ impl FetchCancelHandle {
/// Cancels only if this response's transport result has not committed.
/// Completion and this cancellation compete on the same atomic state, so
/// a completion arriving between a separate check and cancel cannot lose.
+ /// Response selection is serialized with this cancellation. A false return
+ /// means this call did not request cancellation; independent unconditional
+ /// or inherited cancellation may still have cancelled the handle.
pub fn cancel_if_response_pending(&self) -> bool {
let progress = self.state.response_progress.lock();
if !progress.cancel_if_pending() {
@@ -205,8 +216,10 @@ impl FetchCancelHandle {
/// child's cancellation authority. Call only after the accepted response's
/// headers arrive: selection is a snapshot, and starting another transfer
/// on the child does not change this choice.
- /// Once cancellation wins, later selection cannot replace its terminal
- /// progress with a pending or already committed response.
+ /// Selection is skipped if cancellation is already observed. Pending-only
+ /// cancellation holds the same selection lock, so once it wins, adoption
+ /// cannot replace its terminal progress. Unconditional or inherited
+ /// cancellation may race with selection and does not arbitrate completion.
pub fn adopt_response_progress(&self, response: &Self) {
let progress = response.state.response_progress.lock().clone();
let mut selected = self.state.response_progress.lock();
@@ -217,8 +230,9 @@ impl FetchCancelHandle {
}
}
- /// Returns whether transport facts already determine this response's
- /// terminal result, so a later consumer cancellation must not replace it.
+ /// Returns whether the selected response's terminal transport result has
+ /// committed. A committed result rejects later pending-only cancellation,
+ /// but does not imply that unconditional cancellation has not occurred.
pub fn response_completion_is_committed(&self) -> bool {
self.state.response_progress.lock().is_committed()
}
@@ -395,6 +409,35 @@ mod tests {
assert!(!child.is_cancelled());
}
+ #[test]
+ fn unconditional_cancellation_does_not_arbitrate_response_completion() {
+ for cancel_ancestor in [false, true] {
+ for complete_before_cancellation in [false, true] {
+ let root = FetchCancelHandle::new();
+ let parent = root.child_for_subrequest();
+ let child = parent.child_for_subrequest();
+ let writer = child.begin_response_progress();
+ parent.adopt_response_progress(&child);
+ if complete_before_cancellation {
+ writer.commit();
+ }
+
+ if cancel_ancestor {
+ root.cancel();
+ } else {
+ parent.cancel();
+ }
+ writer.commit();
+
+ assert!(parent.is_cancelled());
+ assert!(child.is_cancelled());
+ assert!(parent.response_completion_is_committed());
+ assert!(!parent.cancel_if_response_pending());
+ assert!(parent.is_cancelled());
+ }
+ }
+ }
+
#[test]
fn consumer_cancellation_wins_later_completion() {
let parent = FetchCancelHandle::new();
diff --git a/moli-fetch/src/client.rs b/moli-fetch/src/client.rs
index a88cb4524..399c424f6 100644
--- a/moli-fetch/src/client.rs
+++ b/moli-fetch/src/client.rs
@@ -116,7 +116,7 @@ impl FetchClientHandle {
request: Request,
cancel_handle: FetchCancelHandle,
) -> Result<Response> {
- if request.auth_requires_buffered_transport() || !request.follows_redirects() {
+ if request.auth_requires_buffered_transport() || !request.transport_follows_redirects() {
// Auth retries still need the buffered libcurl path so
// intermediate 401/407 challenge bodies are not exposed as final
// streaming responses. Manual redirect callers also need the
diff --git a/moli-fetch/src/request.rs b/moli-fetch/src/request.rs
index f50cd5f21..8d7b0d671 100644
--- a/moli-fetch/src/request.rs
+++ b/moli-fetch/src/request.rs
@@ -366,7 +366,9 @@ impl RequestRedirectHandling {
}
}
- pub fn follows_redirects(self) -> bool {
+ /// Whether the fetch runtime follows redirects itself. `FollowByCaller`
+ /// retains Fetch's follow policy but returns false here.
+ pub fn transport_follows_redirects(self) -> bool {
matches!(self, Self::Follow)
}
@@ -848,8 +850,10 @@ impl Request {
self.redirect_handling.redirect_mode()
}
- pub fn follows_redirects(&self) -> bool {
- self.redirect_handling.follows_redirects()
+ /// Whether the fetch runtime follows redirects itself. A caller-owned loop
+ /// returns false while [`Self::redirect_mode`] still returns `Follow`.
+ pub fn transport_follows_redirects(&self) -> bool {
+ self.redirect_handling.transport_follows_redirects()
}
pub fn with_redirect_handling(mut self, handling: RequestRedirectHandling) -> Self {
@@ -858,11 +862,16 @@ impl Request {
}
/// Stops at this hop while preserving the browser's redirect policy.
+ /// Apply this at transport dispatch, after configuring the policy:
+ /// a later [`Self::with_redirect_mode`] call resets redirect ownership.
pub fn with_single_hop(mut self) -> Self {
self.redirect_handling = self.redirect_handling.single_hop();
self
}
+ /// Sets the browser's redirect policy and its default transport handling.
+ /// `Follow` enables runtime following, including after `with_single_hop()`.
+ /// Caller-owned redirect loops must apply [`Self::with_single_hop`] last.
pub fn with_redirect_mode(mut self, redirect_mode: RequestRedirectMode) -> Self {
self.redirect_handling = redirect_mode.into();
self
diff --git a/moli-fetch/src/runtime.rs b/moli-fetch/src/runtime.rs
index 86456b33b..79f09ebfe 100644
--- a/moli-fetch/src/runtime.rs
+++ b/moli-fetch/src/runtime.rs
@@ -1582,7 +1582,7 @@ impl RuntimeOwner {
Err(error) => return Err((job.response_tx, error)),
};
if let Some(next_url) = next_url
- && job.request.follows_redirects()
+ && job.request.transport_follows_redirects()
{
job.request
.update_referrer_for_redirect(&response.final_url, &response.headers);
@@ -1865,7 +1865,7 @@ impl RuntimeOwner {
}
};
if let Some(next_url) = next_url
- && job.request.follows_redirects()
+ && job.request.transport_follows_redirects()
{
let cache_body_writer = easy
.get_mut()
@@ -2262,7 +2262,7 @@ impl RuntimeOwner {
}
};
if let Some(next_url) = next_url {
- if job.request.follows_redirects() {
+ if job.request.transport_follows_redirects() {
let cache_body_writer = easy
.get_mut()
.raw_streaming_mut()
@@ -2425,7 +2425,7 @@ impl RuntimeOwner {
Err(error) => return Err((Box::new(job), error)),
};
if let Some(next_url) = next_url
- && job.request.follows_redirects()
+ && job.request.transport_follows_redirects()
{
job.request
.update_referrer_for_redirect(&final_url, &cached.headers);
@@ -2489,7 +2489,7 @@ impl RuntimeOwner {
Err(error) => return Err((Box::new(job), error)),
};
if let Some(next_url) = next_url
- && job.request.follows_redirects()
+ && job.request.transport_follows_redirects()
{
job.request
.update_referrer_for_redirect(&final_url, &cached.headers);
diff --git a/moli-fetch/src/tests/mod.rs b/moli-fetch/src/tests/mod.rs
index 5183131f0..06fd5de68 100644
--- a/moli-fetch/src/tests/mod.rs
+++ b/moli-fetch/src/tests/mod.rs
@@ -273,7 +273,7 @@ fn single_hop_requests_preserve_redirect_mode() {
let hop = request.with_single_hop();
assert_eq!(hop.redirect_mode(), mode);
- assert!(!hop.follows_redirects());
+ assert!(!hop.transport_follows_redirects());
}
}
diff --git a/moli-fetch/src/tests/response_progress.rs b/moli-fetch/src/tests/response_progress.rs
index 436a7c245..6aa8b129c 100644
--- a/moli-fetch/src/tests/response_progress.rs
+++ b/moli-fetch/src/tests/response_progress.rs
@@ -82,7 +82,6 @@ async fn buffered_redirect_body_wait_is_cancellable_without_committing_completio
// Known compatibility limitation: the buffered transport retains redirect
// bodies, so headers alone cannot deliver its materialized response. Keep
// cancellation working until that fallback can retire bodies at headers.
- // See docs/inner/fetch-buffered-redirect-limitations.md.
assert!(
tokio::time::timeout(Duration::from_millis(100), &mut rx)
.await
diff --git a/moli-renderer-v8/src/network/backend/memory_cache.rs b/moli-renderer-v8/src/network/backend/memory_cache.rs
index e5da707b7..08353462f 100644
--- a/moli-renderer-v8/src/network/backend/memory_cache.rs
+++ b/moli-renderer-v8/src/network/backend/memory_cache.rs
@@ -586,7 +586,7 @@ pub(in crate::network) fn script_text_request_is_memory_cacheable(request: &Requ
&& request.method.eq_ignore_ascii_case("GET")
&& request.body.is_none()
&& request.auth().is_none()
- && request.follows_redirects()
+ && request.transport_follows_redirects()
}
pub(in crate::network) fn script_text_cache_key(request: &Request) -> ScriptTextCacheKey {
@@ -668,7 +668,7 @@ fn raw_subresource_request_is_memory_cacheable(request: &Request) -> bool {
&& request.method.eq_ignore_ascii_case("GET")
&& request.body.is_none()
&& request.auth().is_none()
- && request.follows_redirects()
+ && request.transport_follows_redirects()
&& raw_subresource_memory_cacheable_headers(request)
}
diff --git a/moli-renderer-v8/src/network/request_client.rs b/moli-renderer-v8/src/network/request_client.rs
index 4fdec45a5..198251d98 100644
--- a/moli-renderer-v8/src/network/request_client.rs
+++ b/moli-renderer-v8/src/network/request_client.rs
@@ -273,7 +273,7 @@ impl ResourceRequestClient {
cancel_handle: FetchCancelHandle,
) -> Result<NetworkFetchResult<Response>> {
let request = self.apply_network_policy(request)?;
- if request.auth_requires_buffered_transport() || !request.follows_redirects() {
+ if request.auth_requires_buffered_transport() || !request.transport_follows_redirects() {
return self
.resource_runtime
.client()
@@ -649,7 +649,7 @@ impl ResourceRequestClient {
request: Request,
cancel_handle: FetchCancelHandle,
) -> Result<Response> {
- if request.auth_requires_buffered_transport() || !request.follows_redirects() {
+ if request.auth_requires_buffered_transport() || !request.transport_follows_redirects() {
// Challenge-response schemes still need libcurl's buffered auth
// retry behavior until the streaming collector models
// intermediate authentication challenges explicitly. Manual
@@ -915,7 +915,7 @@ impl ResourceRequestClient {
cancel_handle: Option<FetchCancelHandle>,
) -> Result<Response> {
let request = self.apply_network_policy(request)?;
- if request.auth_requires_buffered_transport() || !request.follows_redirects() {
+ if request.auth_requires_buffered_transport() || !request.transport_follows_redirects() {
// Digest auth retries are still completed inside libcurl on the
// buffered path. Keep auth requests there until the streaming
// collector can distinguish intermediate auth challenges from
diff --git a/moli-renderer-v8/src/network_host/async_fetch.rs b/moli-renderer-v8/src/network_host/async_fetch.rs
index 1f835a775..3c964fac1 100644
--- a/moli-renderer-v8/src/network_host/async_fetch.rs
+++ b/moli-renderer-v8/src/network_host/async_fetch.rs
@@ -148,7 +148,9 @@ impl ManualCorsRedirectState {
&self.preflight_request_headers
}
- fn hop_request(&self) -> Request {
+ // Construct this copy at transport dispatch, after configuring Fetch
+ // policy: a later with_redirect_mode(Follow) would enable runtime following.
+ fn single_hop_transport_request(&self) -> Request {
self.request.clone().with_single_hop()
}
@@ -267,7 +269,9 @@ async fn fetch_browser_subresource_with_manual_preflight_redirects(
// Auth challenge-response and manual/error redirect compatibility still
// use the buffered collector, which waits for each response's entire body.
- // See docs/inner/fetch-buffered-redirect-limitations.md.
+ // Unfinished bodies can stall these paths until cancellation or timeout.
+ // Covered by buffered_redirect_body_wait_is_cancellable_without_committing_completion
+ // in moli-fetch/src/tests/response_progress.rs.
let mut redirects = ManualCorsRedirectState::new(request, preflight_request_headers);
let cancel_handle = cancel_handle.unwrap_or_default();
@@ -279,7 +283,7 @@ async fn fetch_browser_subresource_with_manual_preflight_redirects(
let response_cancel = cancel_handle.child_for_subrequest();
let mut observed = fetch_once_with_network_metadata_unvalidated(
&loader,
- redirects.hop_request(),
+ redirects.single_hop_transport_request(),
Some(response_cancel.clone()),
)
.await?;
@@ -318,7 +322,7 @@ async fn fetch_browser_subresource_raw_stream_with_manual_preflight_redirects(
let mut observed = loader
.fetch_raw_stream_with_cancel_and_network_metadata(
- redirects.hop_request(),
+ redirects.single_hop_transport_request(),
cancel_handle.child_for_subrequest(),
)
.await
@@ -558,10 +562,10 @@ pub(crate) fn spawn_async_subresource_fetch(
| BrowserRequestMetadata::StyleModule
| BrowserRequestMetadata::Xhr,
)
- ) && request.follows_redirects()
+ ) && request.transport_follows_redirects()
&& request.request_mode != RequestMode::NoCors;
let can_collect_image_body =
- parkable_image_manager.is_some() && request.follows_redirects();
+ parkable_image_manager.is_some() && request.transport_follows_redirects();
if moli_trace::cdp_runtime_trace_enabled() {
tracing::info!(
target: "moli_cdp_nav_timing",
@@ -1009,8 +1013,8 @@ mod tests {
.with_request_origin(moli_url::WebOrigin::from_url(&current_url))
.with_redirect_mode(mode);
let mut redirects = ManualCorsRedirectState::new(request, Vec::new());
- let hop = redirects.hop_request();
- assert!(!hop.follows_redirects());
+ let hop = redirects.single_hop_transport_request();
+ assert!(!hop.transport_follows_redirects());
assert_eq!(hop.redirect_mode(), mode);
let transition = redirects.advance(
@@ -1458,7 +1462,12 @@ mod tests {
.with_initiator_url(&document_url)
.with_request_origin(moli_url::WebOrigin::from_url(&document_url))
.with_credentials_mode(RequestCredentialsMode::SameOrigin)
- .with_browser_request_metadata(BrowserRequestMetadata::Xhr);
+ .with_browser_request_metadata(BrowserRequestMetadata::Xhr)
+ // A later policy setter re-enables runtime following. The browser loop
+ // must reapply single-hop handling at dispatch to preflight the next URL.
+ .with_single_hop()
+ .with_redirect_mode(RequestRedirectMode::Follow);
+ assert!(request.transport_follows_redirects());
let cancel = FetchCancelHandle::new();
let response = tokio::time::timeout(
diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rs
index 204793d8d..cf6743450 100644
--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs
+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs
@@ -209,7 +209,7 @@ pub(in crate::worker) fn spawn_worker_fetch_network(
}
if request.auth_requires_buffered_transport()
|| request.request_mode == RequestMode::NoCors
- || !request.follows_redirects()
+ || !request.transport_follows_redirects()
|| browser_request_needs_manual_preflight_redirects(
&request,
&cors_preflight_request_headers,