Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(fetch): enforce deadlines before transfer start
ldm06a8a4d7b9800
diff --git a/moli-curl/src/dns_adapter.rs b/moli-curl/src/dns_adapter.rsindex dadb4b354..70fc7e689 100644--- a/moli-curl/src/dns_adapter.rs+++ b/moli-curl/src/dns_adapter.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, hash::Hash, net::IpAddr};+use std::{collections::HashMap, hash::Hash, net::IpAddr, time::Instant};use anyhow::{Context, Result, anyhow};use crossbeam_channel::{Receiver, Sender};@@ -179,6 +179,39 @@ where}}+ pub(crate) fn next_deadline(+ &self,+ mut deadline_for: impl FnMut(&P) -> Option<Instant>,+ ) -> Option<Instant> {+ self.waiting.values().filter_map(&mut deadline_for).min()+ }++ /// Retires expired requests from the owner residence.+ ///+ /// The resolver may still publish a late completion because a blocking+ /// system lookup cannot be cancelled safely. Exact request identity makes+ /// that completion harmless: [`Self::claim`] ignores it after this method+ /// removes the waiting entry.+ pub(crate) fn take_expired(+ &mut self,+ now: Instant,+ mut deadline_for: impl FnMut(&P) -> Option<Instant>,+ ) -> Vec<P> {+ let expired_ids = self+ .waiting+ .iter()+ .filter_map(|(request_id, pending)| {+ deadline_for(pending)+ .is_some_and(|deadline| deadline <= now)+ .then_some(*request_id)+ })+ .collect::<Vec<_>>();+ expired_ids+ .into_iter()+ .filter_map(|request_id| self.waiting.remove(&request_id))+ .collect()+ }+pub(crate) fn drain(&mut self) -> impl Iterator<Item = P> + '_ {self.waiting.drain().map(|(_, pending)| pending)}@@ -238,6 +271,29 @@ mod tests {);}+ #[test]+ fn expired_dns_residence_rejects_a_late_completion() {+ let mut residence = CurlDnsOwnerResidence::<u64, _>::default();+ let request_id = 11;+ let now = Instant::now();+ residence.waiting.insert(request_id, ("pending", Some(now)));++ assert_eq!(residence.next_deadline(|pending| pending.1), Some(now));+ assert_eq!(+ residence.take_expired(now, |pending| pending.1),+ [("pending", Some(now))]+ );+ assert!(+ residence+ .claim(CurlDnsOwnerCompletion {+ request_id,+ result: test_result(),+ })+ .is_none(),+ "a resolver completion must not recover a timed-out transfer"+ );+ }+#[test]fn queued_stale_completion_does_not_hide_next_ready_request() {let mut residence = CurlDnsOwnerResidence::<u64, _>::default();diff --git a/moli-curl/src/runtime.rs b/moli-curl/src/runtime.rsindex 09e850004..b65240c7b 100644--- a/moli-curl/src/runtime.rs+++ b/moli-curl/src/runtime.rs@@ -10,6 +10,7 @@ use std::{atomic::{AtomicBool, Ordering},},thread,+ time::Instant,};use anyhow::{Context, Result, anyhow};@@ -41,6 +42,13 @@ pub struct CurlMultiJob<H: Handler, C> {pub easy: Easy2<H>,pub context: C,pub origin: Option<CurlOriginKey>,+ /// Absolute deadline for the whole scheduler-owned transfer attempt.+ ///+ /// libcurl cannot account for time spent in Moli's priority queue or in+ /// the shared DNS residence because both happen before the easy handle is+ /// added to the multi handle. The owner enforces this deadline in those+ /// residences and gives libcurl only the remaining duration.+ pub deadline: Option<Instant>,/// DNS ownership chosen by the caller before this transfer enters curl.////// A curl-managed policy preserves libcurl's resolver behavior. A shared@@ -56,6 +64,7 @@ impl<H: Handler, C> fmt::Debug for CurlMultiJob<H, C> {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {f.debug_struct("CurlMultiJob").field("origin", &self.origin)+ .field("deadline", &self.deadline).field("dns_resolution", &self.dns_resolution).field("priority", &self.priority).field("label", &self.label)@@ -277,6 +286,7 @@ mod tests {easy,context: "matching-context".to_owned(),origin: None,+ deadline: None,dns_resolution: CurlDnsResolution::curl_managed(),priority: 1,label: "identity-test".to_owned(),diff --git a/moli-curl/src/runtime/owner.rs b/moli-curl/src/runtime/owner.rsindex 59538a85a..e51a1427a 100644--- a/moli-curl/src/runtime/owner.rs+++ b/moli-curl/src/runtime/owner.rs@@ -4,7 +4,7 @@ use std::{Arc, OnceLock,atomic::{AtomicBool, Ordering},},- time::Instant,+ time::{Duration, Instant},};use anyhow::{Context, Result, anyhow};@@ -23,7 +23,7 @@ use super::{residence::{CurlActiveTransfer, CurlOwnerState, CurlPendingJob, active_origin_count,completed_transfers, enqueue_existing_pending_job, enqueue_pending_job, job_is_eligible,- pending_origin_count, take_transfers_in_notification_order,+ pending_origin_count, take_expired_pending_jobs, take_transfers_in_notification_order,},};@@ -39,6 +39,7 @@ pub(super) enum CurlRuntimeCommand<H: Handler, C> {enum CurlOwnerEvent<H: Handler, C> {Command(std::result::Result<CurlRuntimeCommand<H, C>, crossbeam_channel::RecvError>),Dns(std::result::Result<CurlDnsOwnerCompletion<CurlTransferId>, crossbeam_channel::RecvError>),+ Deadline,}pub(super) struct CurlRuntimeOwner<H: Handler + Send + 'static, C: Send + 'static> {@@ -85,6 +86,7 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {loop {self.drain_commands(&mut state, &mut multi);self.drain_dns_completions(&mut state);+ self.expire_waiting_jobs(&mut state);self.start_eligible_jobs(&mut state, &mut multi);self.process_completed_transfers(&mut state, &mut multi);@@ -99,7 +101,7 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {if state.active.is_empty() && state.pending.is_empty() {self.wait_for_next_owner_event(&mut state, &mut multi);} else if !state.active.is_empty() {- self.wait_for_curl_progress(&multi);+ self.wait_for_curl_progress(&multi, &state);}}}@@ -128,9 +130,20 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {}return;}- let event = crossbeam_channel::select! {- recv(self.command_rx) -> command => CurlOwnerEvent::Command(command),- recv(state.dns.completion_receiver()) -> completion => CurlOwnerEvent::Dns(completion),+ let event = if let Some(deadline) = state.dns.next_deadline(|pending| pending.job.deadline)+ {+ let deadline_rx =+ crossbeam_channel::after(deadline.saturating_duration_since(Instant::now()));+ crossbeam_channel::select! {+ recv(self.command_rx) -> command => CurlOwnerEvent::Command(command),+ recv(state.dns.completion_receiver()) -> completion => CurlOwnerEvent::Dns(completion),+ recv(deadline_rx) -> _ => CurlOwnerEvent::Deadline,+ }+ } else {+ crossbeam_channel::select! {+ recv(self.command_rx) -> command => CurlOwnerEvent::Command(command),+ recv(state.dns.completion_receiver()) -> completion => CurlOwnerEvent::Dns(completion),+ }};match event {CurlOwnerEvent::Command(command) => match command {@@ -142,6 +155,7 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {self.claim_dns_completion(state, completion);}}+ CurlOwnerEvent::Deadline => {}}}@@ -302,6 +316,10 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {});return;}+ if pending.deadline_reached(Instant::now()) {+ self.complete_timed_out_job(pending, "while waiting for DNS");+ return;+ }match ready.result {Ok(addresses) => {if let Err(error) = pending@@ -342,10 +360,34 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {multi: &mut Multi,pending: CurlPendingJob<H, C>,) {+ if pending.deadline_reached(Instant::now()) {+ self.complete_timed_out_job(pending, "while waiting to start");+ return;+ }let transfer_id = pending.transfer_id;let queued_for = pending.enqueued_at.elapsed();- let job = pending.job;+ let mut job = pending.job;let label = job.label.clone();+ if let Some(deadline) = job.deadline {+ let Some(remaining) = curl_timeout_for_deadline(deadline, Instant::now()) else {+ self.send_completion(CurlMultiCompletion {+ transfer_id,+ easy: Some(job.easy),+ context: job.context,+ result: Err(curl_runtime_timeout_error("while waiting to start")),+ });+ return;+ };+ if let Err(error) = job.easy.timeout(remaining) {+ self.send_completion(CurlMultiCompletion {+ transfer_id,+ easy: Some(job.easy),+ context: job.context,+ result: Err(error).context("failed to apply remaining curl request deadline"),+ });+ return;+ }+ }match multi.add2(job.easy).with_context(|| anyhow!("failed to add curl easy handle for {label}"))@@ -424,6 +466,28 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {}}+ fn expire_waiting_jobs(&self, state: &mut CurlOwnerState<H, C>) {+ let now = Instant::now();+ for pending in take_expired_pending_jobs(&mut state.pending, now) {+ self.complete_timed_out_job(pending, "while waiting in the scheduler");+ }+ for pending in state.dns.take_expired(now, |pending| pending.job.deadline) {+ self.complete_timed_out_job(pending, "while waiting for DNS");+ }+ }++ fn complete_timed_out_job(&self, pending: CurlPendingJob<H, C>, stage: &'static str) {+ let CurlPendingJob {+ transfer_id, job, ..+ } = pending;+ self.send_completion(CurlMultiCompletion {+ transfer_id,+ easy: Some(job.easy),+ context: job.context,+ result: Err(curl_runtime_timeout_error(stage)),+ });+ }+fn finish_active_transfer(&self,state: &CurlOwnerState<H, C>,@@ -517,9 +581,12 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {});}- fn wait_for_curl_progress(&self, multi: &Multi) {- let wait_timeout = runtime_wait_timeout(multi, self.config.poll_interval)+ fn wait_for_curl_progress(&self, multi: &Multi, state: &CurlOwnerState<H, C>) {+ let mut wait_timeout = runtime_wait_timeout(multi, self.config.poll_interval).unwrap_or(self.config.poll_interval);+ if let Some(deadline) = state.next_waiting_deadline() {+ wait_timeout = wait_timeout.min(deadline.saturating_duration_since(Instant::now()));+ }if wait_timeout.is_zero() {return;}@@ -533,6 +600,18 @@ impl<H: Handler + Send + 'static, C: Send + 'static> CurlRuntimeOwner<H, C> {}}+fn curl_runtime_timeout_error(stage: &str) -> anyhow::Error {+ anyhow!("curl multi runtime request timed out {stage}")+}++fn curl_timeout_for_deadline(deadline: Instant, now: Instant) -> Option<Duration> {+ let remaining = deadline.saturating_duration_since(now);+ // curl-rust converts CURLOPT_TIMEOUT_MS with `Duration::as_millis()`. A+ // positive sub-millisecond value would therefore become zero, which+ // libcurl interprets as disabling the timeout entirely.+ (remaining >= Duration::from_millis(1)).then_some(remaining)+}+fn curl_runtime_trace_enabled() -> bool {static ENABLED: OnceLock<bool> = OnceLock::new();*ENABLED.get_or_init(|| {@@ -546,3 +625,21 @@ fn env_flag_enabled(name: &str) -> bool {!value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")})}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sub_millisecond_deadline_never_disables_the_libcurl_timeout() {+ let now = Instant::now();+ assert_eq!(+ curl_timeout_for_deadline(now + Duration::from_micros(999), now),+ None+ );+ assert_eq!(+ curl_timeout_for_deadline(now + Duration::from_millis(1), now),+ Some(Duration::from_millis(1))+ );+ }+}diff --git a/moli-curl/src/runtime/residence.rs b/moli-curl/src/runtime/residence.rsindex 69e0b450e..f4651cb9f 100644--- a/moli-curl/src/runtime/residence.rs+++ b/moli-curl/src/runtime/residence.rs@@ -33,6 +33,16 @@ impl<H: Handler, C> Default for CurlOwnerState<H, C> {}}+impl<H: Handler, C> CurlOwnerState<H, C> {+ pub(super) fn next_waiting_deadline(&self) -> Option<Instant> {+ self.pending+ .iter()+ .filter_map(|pending| pending.job.deadline)+ .chain(self.dns.next_deadline(|pending| pending.job.deadline))+ .min()+ }+}+pub(super) struct CurlActiveTransfer<H: Handler, C> {pub(super) handle: Easy2Handle<H>,pub(super) context: C,@@ -49,6 +59,29 @@ pub(super) struct CurlPendingJob<H: Handler, C> {pub(super) enqueued_at: Instant,}+impl<H: Handler, C> CurlPendingJob<H, C> {+ pub(super) fn deadline_reached(&self, now: Instant) -> bool {+ self.job.deadline.is_some_and(|deadline| deadline <= now)+ }+}++pub(super) fn take_expired_pending_jobs<H: Handler, C>(+ pending: &mut VecDeque<CurlPendingJob<H, C>>,+ now: Instant,+) -> Vec<CurlPendingJob<H, C>> {+ let mut retained = VecDeque::with_capacity(pending.len());+ let mut expired = Vec::new();+ while let Some(job) = pending.pop_front() {+ if job.deadline_reached(now) {+ expired.push(job);+ } else {+ retained.push_back(job);+ }+ }+ *pending = retained;+ expired+}+pub(super) fn enqueue_pending_job<H: Handler, C>(pending: &mut VecDeque<CurlPendingJob<H, C>>,transfer_id: CurlTransferId,@@ -176,6 +209,7 @@ mod tests {easy: Easy2::new(TestHandler),context: label.to_owned(),origin,+ deadline: None,dns_resolution: CurlDnsResolution::curl_managed(),priority,label: label.to_owned(),@@ -236,6 +270,59 @@ mod tests {);}+ #[test]+ fn expired_pending_jobs_are_removed_without_reordering_live_jobs() {+ let now = Instant::now();+ let mut expired = test_job("expired", 2, None);+ expired.deadline = Some(now);+ let mut live_high = test_job("live-high", 2, None);+ live_high.deadline = now.checked_add(Duration::from_secs(1));+ let live_low = test_job("live-low", 1, None);+ let mut pending = VecDeque::new();+ enqueue_pending_job(&mut pending, test_transfer_id(1), expired);+ enqueue_pending_job(&mut pending, test_transfer_id(2), live_high);+ enqueue_pending_job(&mut pending, test_transfer_id(3), live_low);++ let expired = take_expired_pending_jobs(&mut pending, now);++ assert_eq!(+ expired+ .iter()+ .map(|pending| pending.job.label.as_str())+ .collect::<Vec<_>>(),+ ["expired"]+ );+ assert_eq!(+ pending+ .iter()+ .map(|pending| pending.job.label.as_str())+ .collect::<Vec<_>>(),+ ["live-high", "live-low"]+ );+ }++ #[test]+ fn active_transfer_wait_is_capped_by_the_earliest_queued_deadline() {+ let now = Instant::now();+ let later = now + Duration::from_secs(2);+ let earlier = now + Duration::from_secs(1);+ let mut later_job = test_job("later", 1, None);+ later_job.deadline = Some(later);+ let mut earlier_job = test_job("earlier", 1, None);+ earlier_job.deadline = Some(earlier);+ let mut pending = VecDeque::new();+ enqueue_pending_job(&mut pending, test_transfer_id(1), later_job);+ enqueue_pending_job(&mut pending, test_transfer_id(2), earlier_job);+ let state = CurlOwnerState {+ closed: false,+ pending,+ dns: CurlDnsOwnerResidence::default(),+ active: HashMap::new(),+ };++ assert_eq!(state.next_waiting_deadline(), Some(earlier));+ }+#[test]fn completed_jobs_preserve_libcurl_notification_order() {let mut active = HashMap::from([diff --git a/moli-dns-resolver/src/service.rs b/moli-dns-resolver/src/service.rsindex b91c09a36..4e6902faf 100644--- a/moli-dns-resolver/src/service.rs+++ b/moli-dns-resolver/src/service.rs@@ -56,6 +56,14 @@ impl DnsResolverService {target: DnsTarget,completion: impl FnOnce(DnsLookupResult) + Send + 'static,) {+ if target_is_reserved_invalid(&target) {+ completion(Err(Arc::from(format!(+ "failed to resolve {}:{}: reserved .invalid domain",+ target.host(),+ target.port()+ ))));+ return;+ }let key = DnsLookupKey { partition, target };let admission = {let mut state = self.state.lock();@@ -96,6 +104,18 @@ impl DnsResolverService {}}+/// `.invalid` is a special-use top-level domain whose names are guaranteed not+/// to exist. Resolve it locally so a deterministic negative answer cannot be+/// delayed behind blocking host-resolver work or depend on the machine's DNS+/// configuration.+fn target_is_reserved_invalid(target: &DnsTarget) -> bool {+ let host = target.host().trim_end_matches('.');+ host.eq_ignore_ascii_case("invalid")+ || host+ .get(host.len().saturating_sub(".invalid".len())..)+ .is_some_and(|suffix| suffix.eq_ignore_ascii_case(".invalid"))+}+fn shared_dns_worker_count() -> NonZeroUsize {let available = thread::available_parallelism().map(NonZeroUsize::get)diff --git a/moli-dns-resolver/src/tests.rs b/moli-dns-resolver/src/tests.rsindex 83cc6436b..9242f61eb 100644--- a/moli-dns-resolver/src/tests.rs+++ b/moli-dns-resolver/src/tests.rs@@ -183,3 +183,33 @@ fn cache_answers_do_not_cross_runtime_partitions() {assert_eq!(lookup_count.load(Ordering::SeqCst), 2);}++#[test]+fn reserved_invalid_names_fail_synchronously_without_consuming_a_worker() {+ let lookup_count = Arc::new(AtomicUsize::new(0));+ let service = test_service(1, {+ let lookup_count = Arc::clone(&lookup_count);+ move |_| {+ lookup_count.fetch_add(1, Ordering::SeqCst);+ test_result()+ }+ });+ let (completion_tx, completion_rx) = crossbeam_channel::bounded(1);++ service.resolve(+ DnsCachePartition::fresh(),+ DnsTarget::new("Moli-Failure.INVALID.", 80),+ move |result| {+ completion_tx+ .send(result)+ .expect("reserved-name completion should be observed");+ },+ );++ let error = completion_rx+ .try_recv()+ .expect("reserved-name failure should complete on the caller")+ .expect_err("a reserved .invalid name cannot resolve");+ assert!(error.contains("reserved .invalid domain"));+ assert_eq!(lookup_count.load(Ordering::SeqCst), 0);+}diff --git a/moli-fetch/src/runtime.rs b/moli-fetch/src/runtime.rsindex 89cd830e1..876853be4 100644--- a/moli-fetch/src/runtime.rs+++ b/moli-fetch/src/runtime.rs@@ -14,7 +14,7 @@ use std::{atomic::{AtomicBool, AtomicU64, Ordering},},thread,- time::Duration,+ time::{Duration, Instant},};use anyhow::{Context, Result, anyhow};@@ -66,6 +66,15 @@ const CURLINFO_HTTP_VERSION: curl_sys::CURLINFO = curl_sys::CURLINFO_LONG + 46;static NEXT_FETCH_RUNTIME_ID: AtomicU64 = AtomicU64::new(0);static INSTALL_FETCH_RUNTIME_PANIC_HOOK: Once = Once::new();+fn curl_runtime_deadline(request: &Request, config: &FetchConfig) -> Option<Instant> {+ let timeout = request.effective_request_timeout(config);+ if timeout.is_zero() {+ None+ } else {+ Instant::now().checked_add(timeout)+ }+}+thread_local! {/// Panic diagnostics are opt-in per semantic owner thread. The process-wide/// hook below observes all panics so that it can preserve the previously@@ -920,6 +929,7 @@ impl RuntimeOwner {let curl_job = CurlMultiJob {easy,origin: context.job.origin_key.clone(),+ deadline: curl_runtime_deadline(&context.job.request, &self.config),dns_resolution,priority: request_fetch_priority_rank(&context.job.request),label,@@ -1105,6 +1115,7 @@ impl RuntimeOwner {let curl_job = CurlMultiJob {easy,origin: context.job.origin_key.clone(),+ deadline: curl_runtime_deadline(&context.job.request, &self.config),dns_resolution,priority: request_fetch_priority_rank(&context.job.request),label,@@ -1303,6 +1314,7 @@ impl RuntimeOwner {let curl_job = CurlMultiJob {easy,origin: context.job.origin_key.clone(),+ deadline: curl_runtime_deadline(&context.job.request, &self.config),dns_resolution,priority: request_fetch_priority_rank(&context.job.request),label,diff --git a/moli-renderer-v8/src/worker/thread/tests/network.rs b/moli-renderer-v8/src/worker/thread/tests/network.rsindex cb60df6a0..7be4e3b20 100644--- a/moli-renderer-v8/src/worker/thread/tests/network.rs+++ b/moli-renderer-v8/src/worker/thread/tests/network.rs@@ -4973,9 +4973,8 @@ async fn worker_fetch_dns_failure_rejects_and_reports_subresource_failure() {record.outcome());};- let lower_error = error_text.to_ascii_lowercase();assert!(- lower_error.contains("resolv") || lower_error.contains("timed out"),+ error_text.to_ascii_lowercase().contains("resolv"),"expected DNS-resolution error text, got {error_text:?}");assert_eq!(