feat(fetch): retain native connection setup observations

Carry shared DNS start/completion through the curl scheduler, preserving the
resolver clock across owner delivery, queue retirement and active completion.
Record TLS setup and request-preparation callbacks on each transfer's own
progress token; preserve curl-rust's default TLS certificate initialization.

Capture unrounded curl statistics once at terminal completion and reuse them
for logging. Expose partial typed observations to buffered, raw and HTML
consumers, keeping unavailable data distinct from native zero and from the
Web Resource Timing projection.

Cover DNS provenance, cache/redirect isolation, delayed consumption, HTTP/2
multiplexing and proxy tunnel ordering.
This commit is contained in:
ldm0
2026-11-21 20:03:35 +08:00
parent 996cf49033
commit 91bd2efc29
15 changed files with 581 additions and 23 deletions
+58 -1
View File
@@ -23,6 +23,14 @@ pub struct CurlDnsResolution {
endpoint: Option<Box<CurlDnsEndpointResolution>>,
}
/// Monotonic observations of one lookup submitted to the shared resolver.
/// This includes resolver queue/cache work, but not later curl-owner delivery.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CurlDnsTiming {
pub started_at: Instant,
pub completed_at: Instant,
}
#[derive(Debug)]
struct CurlDnsEndpointResolution {
target: DnsTarget,
@@ -143,11 +151,13 @@ impl CurlDnsResolution {
pub(crate) struct CurlDnsOwnerCompletion<I> {
request_id: I,
result: DnsLookupResult,
timing: CurlDnsTiming,
}
pub(crate) struct CurlDnsReady<P> {
pub(crate) pending: P,
pub(crate) result: DnsLookupResult,
pub(crate) timing: CurlDnsTiming,
}
/// Curl-owner residence for transfers parked on shared DNS resolution.
@@ -201,15 +211,28 @@ where
);
let completion_tx = self.completion_tx.clone();
let started_at = Instant::now();
match DnsResolverService::shared() {
Ok(service) => service.resolve(self.partition, target, move |result| {
let _ = completion_tx.send(CurlDnsOwnerCompletion { request_id, result });
let timing = CurlDnsTiming {
started_at,
completed_at: Instant::now(),
};
let _ = completion_tx.send(CurlDnsOwnerCompletion {
request_id,
result,
timing,
});
let _ = owner_waker.wakeup();
}),
Err(error) => {
let _ = self.completion_tx.send(CurlDnsOwnerCompletion {
request_id,
result: Err(error),
timing: CurlDnsTiming {
started_at,
completed_at: Instant::now(),
},
});
let _ = owner_waker.wakeup();
}
@@ -224,6 +247,7 @@ where
Some(CurlDnsReady {
pending,
result: completion.result,
timing: completion.timing,
})
}
@@ -299,6 +323,14 @@ mod tests {
impl Handler for TestHandler {}
fn test_timing() -> CurlDnsTiming {
let now = Instant::now();
CurlDnsTiming {
started_at: now,
completed_at: now,
}
}
fn test_result() -> DnsLookupResult {
Ok(Arc::from([IpAddr::from([127, 0, 0, 1])]))
}
@@ -354,6 +386,7 @@ mod tests {
.claim(CurlDnsOwnerCompletion {
request_id,
result: test_result(),
timing: test_timing(),
})
.expect("exact pending request should be claimed");
assert_eq!(ready.pending, "pending");
@@ -362,12 +395,33 @@ mod tests {
.claim(CurlDnsOwnerCompletion {
request_id,
result: test_result(),
timing: test_timing(),
})
.is_none(),
"late duplicate completion must not recover retired work"
);
}
#[test]
fn delayed_claim_preserves_the_resolver_completion_clock() {
let mut residence = CurlDnsOwnerResidence::<u64, _>::default();
residence.waiting.insert(7, "pending");
let completed_at = Instant::now();
let timing = CurlDnsTiming {
started_at: completed_at - std::time::Duration::from_millis(8),
completed_at,
};
let ready = residence
.claim(CurlDnsOwnerCompletion {
request_id: 7,
result: test_result(),
timing,
})
.expect("the exact lookup should complete");
assert_eq!(ready.timing, timing);
assert!(ready.timing.completed_at <= Instant::now());
}
#[test]
fn expired_dns_residence_rejects_a_late_completion() {
let mut residence = CurlDnsOwnerResidence::<u64, _>::default();
@@ -385,6 +439,7 @@ mod tests {
.claim(CurlDnsOwnerCompletion {
request_id,
result: test_result(),
timing: test_timing(),
})
.is_none(),
"a resolver completion must not recover a timed-out transfer"
@@ -402,6 +457,7 @@ mod tests {
.send(CurlDnsOwnerCompletion {
request_id: stale_id,
result: test_result(),
timing: test_timing(),
})
.expect("stale completion should enter the test queue");
residence
@@ -409,6 +465,7 @@ mod tests {
.send(CurlDnsOwnerCompletion {
request_id: ready_id,
result: test_result(),
timing: test_timing(),
})
.expect("ready completion should enter the test queue");
+4 -1
View File
@@ -5,7 +5,7 @@ pub(crate) mod registry;
mod scheduling;
use crate::{
CurlDnsResolution, CurlTransferId,
CurlDnsResolution, CurlDnsTiming, CurlTransferId,
runtime::{CurlRuntimeCommand, identity::next_transfer_id},
};
use anyhow::{Result, anyhow};
@@ -73,6 +73,8 @@ pub struct CurlMultiCompletion<H: Handler, C> {
pub easy: Option<Easy2<H>>,
pub context: C,
pub result: Result<()>,
/// Shared DNS observations for this exact transfer, if it performed a lookup.
pub dns_timing: Option<CurlDnsTiming>,
}
impl<H: Handler, C> fmt::Debug for CurlMultiCompletion<H, C> {
@@ -80,6 +82,7 @@ impl<H: Handler, C> fmt::Debug for CurlMultiCompletion<H, C> {
f.debug_struct("CurlMultiCompletion")
.field("transfer_id", &self.transfer_id)
.field("has_easy", &self.easy.is_some())
.field("dns_timing", &self.dns_timing)
.field("result", &self.result.as_ref().map(|_| ()))
.finish_non_exhaustive()
}
+84 -6
View File
@@ -113,6 +113,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing: None,
result: Err(anyhow!("curl multi runtime is shutting down")),
});
return;
@@ -145,23 +146,31 @@ impl<H: Handler, C> HttpRegistry<H, C> {
self.closed = true;
while let Some(pending) = self.pending.pop_front() {
let CurlPendingJob {
transfer_id, job, ..
transfer_id,
job,
dns_timing,
..
} = pending;
self.send_completion(CurlMultiCompletion {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(anyhow!("curl multi runtime is shutting down")),
});
}
for pending in self.dns.drain() {
let CurlPendingJob {
transfer_id, job, ..
transfer_id,
job,
dns_timing,
..
} = pending;
let _ = self.completion_tx.send(CurlMultiCompletion {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(anyhow!(
"curl multi runtime DNS request cancelled during shutdown"
)),
@@ -173,6 +182,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy,
context: active.context,
dns_timing: active.dns_timing,
result: Err(anyhow!(
"curl multi runtime request cancelled during shutdown"
)),
@@ -227,14 +237,19 @@ impl<H: Handler, C> HttpRegistry<H, C> {
fn handle_dns_completion(&mut self, ready: CurlDnsReady<CurlPendingJob<H, C>>) {
let mut pending = ready.pending;
pending.dns_timing = Some(ready.timing);
if self.closed {
let CurlPendingJob {
transfer_id, job, ..
transfer_id,
job,
dns_timing,
..
} = pending;
self.send_completion(CurlMultiCompletion {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(anyhow!("curl multi runtime is shutting down")),
});
return;
@@ -251,12 +266,16 @@ impl<H: Handler, C> HttpRegistry<H, C> {
.install(&mut pending.job.easy, addresses.as_ref())
{
let CurlPendingJob {
transfer_id, job, ..
transfer_id,
job,
dns_timing,
..
} = pending;
self.send_completion(CurlMultiCompletion {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(error),
});
return;
@@ -268,12 +287,16 @@ impl<H: Handler, C> HttpRegistry<H, C> {
// outside the Multi. Do not requeue it: that would let curl
// resolve or connect independently of the failed shared lookup.
let CurlPendingJob {
transfer_id, job, ..
transfer_id,
job,
dns_timing,
..
} = pending;
self.send_completion(CurlMultiCompletion {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(anyhow!(error.to_string())),
});
}
@@ -286,6 +309,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
return;
}
let transfer_id = pending.transfer_id;
let dns_timing = pending.dns_timing;
let queued_for = pending.enqueued_at.elapsed();
let mut job = pending.job;
let label = job.label.clone();
@@ -295,6 +319,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(curl_runtime_timeout_error("while waiting to start")),
});
return;
@@ -304,6 +329,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(error).context("failed to apply remaining curl request deadline"),
});
return;
@@ -351,6 +377,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
CurlActiveTransfer {
handle,
context: job.context,
dns_timing,
origin: job.origin,
priority: job.priority,
label,
@@ -364,6 +391,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy: None,
context: job.context,
dns_timing,
result: Err(error),
}),
}
@@ -381,12 +409,16 @@ impl<H: Handler, C> HttpRegistry<H, C> {
fn complete_timed_out_job(&self, pending: CurlPendingJob<H, C>, stage: &'static str) {
let CurlPendingJob {
transfer_id, job, ..
transfer_id,
job,
dns_timing,
..
} = pending;
self.send_completion(CurlMultiCompletion {
transfer_id,
easy: Some(job.easy),
context: job.context,
dns_timing,
result: Err(curl_runtime_timeout_error(stage)),
});
}
@@ -405,6 +437,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy: None,
context: active.context,
dns_timing: active.dns_timing,
result: Err(anyhow!(
"failed to remove curl easy handle for {}: {error}",
active.label
@@ -479,6 +512,7 @@ impl<H: Handler, C> HttpRegistry<H, C> {
transfer_id,
easy,
context: active.context,
dns_timing: active.dns_timing,
result,
});
}
@@ -544,6 +578,50 @@ mod tests {
CurlTransferId::from_token(sequence).expect("test transfer ID is non-zero")
}
#[test]
fn dns_observations_survive_queue_retirement_and_active_completion() {
let completed_at = Instant::now();
let timing = crate::CurlDnsTiming {
started_at: completed_at - Duration::from_millis(2),
completed_at,
};
for terminal in [
"pending-shutdown",
"pending-timeout",
"active-complete",
"active-shutdown",
] {
let (completion_tx, completed) = crossbeam_channel::unbounded();
let mut registry = HttpRegistry::new(CurlMultiRuntimeConfig::default(), completion_tx);
let mut multi = Multi::new();
let id = test_transfer_id(1);
let mut job = test_job(terminal, 1, None);
if terminal == "pending-timeout" {
job.deadline = Some(Instant::now());
}
registry.admit(id, job);
registry.pending.front_mut().unwrap().dns_timing = Some(timing);
match terminal {
"pending-shutdown" => registry.shutdown(&mut multi),
"pending-timeout" => registry.expire_waiting_jobs(),
"active-complete" => {
registry.advance(&mut multi);
registry.complete(&mut multi, vec![(id, Ok(()))]);
}
_ => {
registry.advance(&mut multi);
registry.shutdown(&mut multi);
}
}
let completion = completed.try_recv().expect("the exact transfer completes");
assert_eq!(completion.transfer_id, id);
assert_eq!(completion.context, terminal);
assert_eq!(completion.dns_timing, Some(timing));
assert_eq!(completion.result.is_ok(), terminal == "active-complete");
registry.shutdown(&mut multi);
}
}
#[test]
fn eligible_jobs_respect_global_and_origin_capacity_after_completions() {
let config = CurlMultiRuntimeConfig {
+5
View File
@@ -10,6 +10,7 @@ use std::{
use curl::{easy::Handler, multi::Easy2Handle};
use super::{CurlMultiJob, CurlOriginKey, CurlTransferId};
use crate::CurlDnsTiming;
pub(super) struct CurlActiveTransfer<H: Handler, C> {
pub(super) handle: Easy2Handle<H>,
@@ -19,12 +20,14 @@ pub(super) struct CurlActiveTransfer<H: Handler, C> {
pub(super) label: String,
pub(super) started_at: Instant,
pub(super) queued_for: Duration,
pub(super) dns_timing: Option<CurlDnsTiming>,
}
pub(super) struct CurlPendingJob<H: Handler, C> {
pub(super) transfer_id: CurlTransferId,
pub(super) job: CurlMultiJob<H, C>,
pub(super) enqueued_at: Instant,
pub(super) dns_timing: Option<CurlDnsTiming>,
}
impl<H: Handler, C> CurlPendingJob<H, C> {
@@ -61,6 +64,7 @@ pub(super) fn enqueue_pending_job<H: Handler, C>(
transfer_id,
job,
enqueued_at: Instant::now(),
dns_timing: None,
},
);
}
@@ -303,6 +307,7 @@ mod tests {
label: "active".to_owned(),
started_at: Instant::now(),
queued_for: Duration::ZERO,
dns_timing: None,
};
let active = HashMap::from([(test_transfer_id(1), active)]);
let cap = NonZeroUsize::new(1);
+1 -1
View File
@@ -9,7 +9,7 @@ mod runtime;
mod tls;
pub mod websocket;
pub use dns_adapter::CurlDnsResolution;
pub use dns_adapter::{CurlDnsResolution, CurlDnsTiming};
pub use host_resolve::{HostResolveOverrides, validate_http_host_resolve_entries};
pub use http::{CurlHttpSender, CurlMultiCompletion, CurlMultiJob, CurlOriginKey, CurlSubmitError};
pub use network_policy::NetworkAddressPolicy;
+7 -5
View File
@@ -55,6 +55,7 @@ pub(crate) struct RequestTransferMetrics {
pub(crate) fn transfer_metrics_from_easy<H: Handler>(
easy: &Easy2<H>,
headers: &[(String, Vec<u8>)],
timing: Option<crate::FetchCurlTiming>,
) -> RequestTransferMetrics {
let content_encoding =
response_header_value(headers, "content-encoding").map(std::borrow::Cow::into_owned);
@@ -67,12 +68,13 @@ pub(crate) fn transfer_metrics_from_easy<H: Handler>(
.map(|size| size.max(0.0) as u64)
.zip(easy.header_size().ok())
.map(|(download_size, header_size)| download_size.saturating_add(header_size));
let namelookup_ms = easy.namelookup_time().ok().map(duration_to_ms);
let connect_ms = easy.connect_time().ok().map(duration_to_ms);
let appconnect_ms = easy.appconnect_time().ok().map(duration_to_ms);
let pretransfer_ms = easy.pretransfer_time().ok().map(duration_to_ms);
let timing = timing.unwrap_or_default();
let namelookup_ms = timing.name_lookup.map(duration_to_ms);
let connect_ms = timing.connect.map(duration_to_ms);
let appconnect_ms = timing.app_connect.map(duration_to_ms);
let pretransfer_ms = timing.pretransfer.map(duration_to_ms);
let starttransfer_ms = easy.starttransfer_time().ok().map(duration_to_ms);
let total_ms = easy.total_time().ok().map(duration_to_ms);
let total_ms = timing.total.map(duration_to_ms);
RequestTransferMetrics {
content_encoding,
+129 -3
View File
@@ -9,6 +9,8 @@ use std::{
use parking_lot::Mutex;
use tokio_util::sync::CancellationToken;
use crate::{FetchConnectionTiming, FetchCurlTiming};
const RESPONSE_PENDING: u8 = 0;
const RESPONSE_COMMITTED: u8 = 1;
const RESPONSE_CANCELLED: u8 = 2;
@@ -39,11 +41,47 @@ impl ResponseProgress {
}
pub(crate) fn mark_request_started(&self) {
let now = Instant::now();
let mut timing = self.inner.timing.lock();
timing.request_started_at.get_or_insert(now);
timing
.connection_timing
.get_or_insert_with(Default::default)
.request_prepared_at = Some(now);
}
pub(crate) fn mark_tls_context_started(&self) {
let now = Instant::now();
self.inner
.timing
.lock()
.request_started_at
.get_or_insert_with(Instant::now);
.connection_timing
.get_or_insert_with(Default::default)
.tls_context_started_at = Some(now);
}
pub(crate) fn record_connection_timing(
&self,
dns: Option<moli_curl::CurlDnsTiming>,
curl: Option<FetchCurlTiming>,
) {
if dns.is_none() && curl.is_none() {
return;
}
let mut timing = self.inner.timing.lock();
let connection = timing
.connection_timing
.get_or_insert_with(Default::default);
connection.shared_dns = dns;
connection.curl = curl;
}
pub(crate) fn curl_timing(&self) -> Option<FetchCurlTiming> {
self.inner
.timing
.lock()
.connection_timing
.and_then(|connection| connection.curl)
}
pub(crate) fn mark_interim_response_started(&self) {
@@ -147,6 +185,7 @@ pub struct FetchResponseTiming {
body_bytes_received: bool,
response_started_at: Option<Instant>,
response_end_at: Option<Instant>,
connection_timing: Option<FetchConnectionTiming>,
}
impl FetchResponseTiming {
@@ -170,6 +209,13 @@ impl FetchResponseTiming {
pub fn response_end_at(self) -> Option<Instant> {
self.response_end_at
}
/// Observations from the selected transfer only. Callback timestamps may
/// precede final statistics; streaming consumers await `finish()` for the
/// terminal result before relying on the completed curl statistics.
pub fn connection_timing(self) -> Option<FetchConnectionTiming> {
self.connection_timing
}
}
pub(crate) struct CachedResponseBodyTiming(ResponseProgress);
@@ -341,7 +387,87 @@ impl FetchCancelHandle {
#[cfg(test)]
mod tests {
use super::{FetchCancelHandle, FetchResponseBodySizes};
use std::time::Instant;
use crate::FetchCurlTiming;
use std::time::{Duration, Instant};
#[test]
fn connection_observations_cannot_follow_response_selection_or_reset() {
let selected = FetchCancelHandle::new();
let first = selected.response_progress();
let completed_at = Instant::now();
let dns = moli_curl::CurlDnsTiming {
started_at: completed_at - Duration::from_millis(1),
completed_at,
};
first.mark_tls_context_started();
first.mark_request_started();
let curl = FetchCurlTiming {
name_lookup: Some(Duration::from_micros(17)),
connect: Some(Duration::from_micros(213)),
pretransfer: Some(Duration::from_micros(817)),
total: Some(Duration::from_micros(1421)),
new_connections: Some(1),
..Default::default()
};
first.record_connection_timing(Some(dns), Some(curl));
let observed = selected.response_timing().connection_timing().unwrap();
assert_eq!(observed.shared_dns, Some(dns));
assert_eq!(observed.curl, Some(curl));
assert!(observed.tls_context_started_at.is_some());
assert!(observed.request_prepared_at.is_some());
let second = selected.begin_response_progress();
assert!(selected.response_timing().connection_timing().is_none());
first.mark_request_started();
first.record_connection_timing(Some(dns), Some(curl));
assert!(selected.response_timing().connection_timing().is_none());
let tee = FetchCancelHandle::new();
tee.adopt_response_progress(&selected);
second.record_connection_timing(None, Some(curl));
assert_eq!(
tee.response_timing().connection_timing(),
selected.response_timing().connection_timing()
);
assert!(
tee.response_timing()
.connection_timing()
.unwrap()
.shared_dns
.is_none()
);
assert_eq!(
first
.inner
.timing
.lock()
.connection_timing
.unwrap()
.shared_dns,
Some(dns)
);
}
#[test]
fn later_preparation_keeps_the_first_request_boundary() {
let handle = FetchCancelHandle::new();
let progress = handle.response_progress();
progress.mark_request_started();
let first = handle.response_timing().request_started_at().unwrap();
let second_before = Instant::now();
progress.mark_request_started();
let timing = handle.response_timing();
assert_eq!(timing.request_started_at(), Some(first));
assert!(
timing
.connection_timing()
.unwrap()
.request_prepared_at
.unwrap()
>= second_before
);
assert!(timing.connection_timing().unwrap().curl.is_none());
}
#[test]
fn response_completion_commit_is_shared_and_resettable() {
+53
View File
@@ -0,0 +1,53 @@
//! Native connection observations. These are not Web-exposed timestamps.
use std::time::{Duration, Instant};
use curl::easy::{Easy2, Handler};
use moli_curl::CurlDnsTiming;
/// Connection setup observations owned by one transport attempt.
///
/// The shared resolver runs before libcurl. Its clock must not be inferred from
/// libcurl's name-lookup duration or from when the owner receives a completion.
/// Callback observations can be available before the terminal curl statistics.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct FetchConnectionTiming {
pub shared_dns: Option<CurlDnsTiming>,
/// Last TLS context setup callback, when supported by the TLS backend.
/// Absence does not establish that the request used plaintext transport.
pub tls_context_started_at: Option<Instant>,
/// Last prereq callback. Authentication can prepare several exchanges on
/// one easy handle; the fetch's first request boundary is kept separately.
pub request_prepared_at: Option<Instant>,
pub curl: Option<FetchCurlTiming>,
}
/// Unrounded libcurl statistics, relative to libcurl's own transfer start.
///
/// These durations exclude Moli's preceding shared DNS lookup. A native zero is
/// retained as zero; an unavailable statistic is `None`. They are not durations
/// of individual phases, and must not be added to the logical fetch start.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct FetchCurlTiming {
pub name_lookup: Option<Duration>,
pub connect: Option<Duration>,
pub app_connect: Option<Duration>,
pub pretransfer: Option<Duration>,
pub total: Option<Duration>,
/// New connections made by this transfer. Zero can also mean that setup
/// failed before establishing a connection, rather than a reused socket.
pub new_connections: Option<u64>,
}
impl FetchCurlTiming {
pub(crate) fn from_easy<H: Handler>(easy: &Easy2<H>) -> Self {
Self {
name_lookup: easy.namelookup_time().ok(),
connect: easy.connect_time().ok(),
app_connect: easy.appconnect_time().ok(),
pretransfer: easy.pretransfer_time().ok(),
total: easy.total_time().ok(),
new_connections: easy.num_connects().ok(),
}
}
}
+2
View File
@@ -11,6 +11,7 @@ mod client;
mod client_hints;
mod compression_dictionary;
mod config;
mod connection_timing;
mod content_coding;
mod content_decoding;
mod cors;
@@ -47,6 +48,7 @@ pub use cancellation::{FetchCancelHandle, FetchResponseBodySizes, FetchResponseT
pub use client::{FetchClient, FetchClientHandle};
pub use compression_dictionary::cache_vary_header_names;
pub use config::FetchConfig;
pub use connection_timing::{FetchConnectionTiming, FetchCurlTiming};
pub use content_coding::resource_timing_content_encoding;
pub use cors::validate_cors_response_for_origin;
pub use cross_origin_resource_policy::CrossOriginResourcePolicy;
+40 -3
View File
@@ -1559,6 +1559,16 @@ impl RuntimeOwner {
state: &mut OwnerState,
mut completion: RuntimeCurlCompletion,
) {
completion
.context
.response_progress()
.record_connection_timing(
completion.dns_timing,
completion
.easy
.as_ref()
.map(crate::FetchCurlTiming::from_easy),
);
if let Some(easy) = completion.easy.as_mut() {
if let Some(error) = easy.get_mut().content_decoding_error.take() {
completion.result = Err(anyhow!(error));
@@ -2028,7 +2038,8 @@ impl RuntimeOwner {
)
};
let negotiated_http_version = negotiated_http_version.or(collector_http_version);
let transfer_metrics = transfer_metrics_from_easy(&easy, &headers);
let transfer_metrics =
transfer_metrics_from_easy(&easy, &headers, easy.get_ref().curl_timing());
log_request_completion(
&job.request.method,
&job.current_url,
@@ -2353,7 +2364,8 @@ impl RuntimeOwner {
)
};
let negotiated_http_version = negotiated_http_version.or(collector_http_version);
let transfer_metrics = transfer_metrics_from_easy(&easy, &headers);
let transfer_metrics =
transfer_metrics_from_easy(&easy, &headers, easy.get_ref().curl_timing());
log_request_completion(
&job.request.method,
&job.current_url,
@@ -2880,6 +2892,14 @@ enum ActiveTransferContext {
}
impl ActiveTransferContext {
fn response_progress(&self) -> &ResponseProgress {
match self {
Self::Buffered(context) => &context.job.response_progress,
Self::Streaming(context) => &context.job.response_progress,
Self::StreamingRaw(context) => &context.job.response_progress,
}
}
fn is_cancelled(&self) -> bool {
match self {
Self::Buffered(context) => context.job.cancel_handle.is_cancelled(),
@@ -2953,6 +2973,11 @@ enum FetchResponseCollector {
}
impl FetchTransferHandler {
fn curl_timing(&self) -> Option<crate::FetchCurlTiming> {
self.response_progress()
.and_then(ResponseProgress::curl_timing)
}
fn mark_response_body_received(&mut self) {
if !self.response_body_observed
&& let Some(timing) = self.response_progress()
@@ -3089,6 +3114,18 @@ impl FetchTransferHandler {
}
impl Handler for FetchTransferHandler {
fn ssl_ctx(&mut self, context: *mut std::ffi::c_void) -> Result<(), curl::Error> {
if let Some(timing) = self.response_progress() {
timing.mark_tls_context_started();
}
// Preserve curl-rust's platform certificate-store initialization.
match &mut self.response {
FetchResponseCollector::Buffered(collector) => collector.ssl_ctx(context),
FetchResponseCollector::Streaming(collector) => collector.ssl_ctx(context),
FetchResponseCollector::StreamingRaw(collector) => collector.ssl_ctx(context),
}
}
fn prereq(
&mut self,
_primary_ip: &str,
@@ -4225,7 +4262,7 @@ fn collect_buffered_response(
let status_text = collector.status_text().map(str::to_owned);
let headers = collector.headers().to_vec();
let body = collector.body().to_vec();
let transfer_metrics = transfer_metrics_from_easy(easy, &headers);
let transfer_metrics = transfer_metrics_from_easy(easy, &headers, easy.get_ref().curl_timing());
Ok((
RawResponse::from_head_and_body(
@@ -108,8 +108,15 @@ async fn html_response_timing_finishes_without_consumer_polling() -> Result<()>
assert!(headers.response_end_at().is_none());
release_body.send(())?;
// Keep the consumer's executor occupied while native threads finish.
// Body completion can commit before curl publishes terminal statistics.
let deadline = Instant::now() + Duration::from_secs(5);
while !cancel.response_completion_is_committed() {
while !cancel.response_completion_is_committed()
|| cancel
.response_timing()
.connection_timing()
.and_then(|connection| connection.curl)
.is_none()
{
anyhow::ensure!(
Instant::now() < deadline,
"HTML transfer did not record completion"
@@ -117,6 +124,7 @@ async fn html_response_timing_finishes_without_consumer_polling() -> Result<()>
thread::sleep(Duration::from_millis(1));
}
let native = cancel.response_timing();
assert!(native.connection_timing().unwrap().curl.is_some());
assert!(native.body_bytes_received());
assert!(native.response_started_at().unwrap() <= native.response_end_at().unwrap());
assert!(cancel.response_completion_is_committed());
+5
View File
@@ -41,6 +41,11 @@ pub struct StreamingHtmlResponse {
}
impl StreamingHtmlResponse {
/// Native observations from this response's selected transport attempt.
pub fn response_timing(&self) -> crate::FetchResponseTiming {
self.cancel_handle.response_timing()
}
pub fn new(
final_url: Url,
status: u16,
+126
View File
@@ -0,0 +1,126 @@
use super::*;
#[tokio::test]
async fn native_connection_timing_covers_all_shared_dns_transports() -> Result<()> {
let server = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("timed"); 3]);
let port = Url::parse(&server.url())?.port().context("server port")?;
for transport in ["buffered", "html", "raw"] {
let mut config = FetchConfig::default();
config.set_http_proxy(Some(String::new()));
let owner = FetchRuntimeOwner::new(&config, new_shared_browser_cookie_store());
let handle = owner.handle();
let cancel = FetchCancelHandle::new();
let request = Request::get(&format!("http://localhost:{port}/{transport}"))?;
let before = Instant::now();
let timing = match transport {
"buffered" => {
let response = handle
.submit_with_cancel(request, cancel.clone())?
.await??;
assert_eq!(response.body_text(), "timed");
cancel.response_timing()
}
"html" => {
let mut response = handle.submit_html_stream(request)?.into_response().await?;
let mut body = String::new();
while let Some(chunk) = response.next_chunk().await {
body.push_str(&chunk);
}
response.finish().await?;
assert_eq!(body, "timed");
response.response_timing()
}
_ => {
let mut response = handle
.submit_raw_stream(request, cancel.clone())?
.into_response()
.await?;
let mut body = Vec::new();
while let Some(chunk) = response.next_chunk().await {
body.extend_from_slice(&chunk);
}
response.finish().await?;
assert_eq!(body, b"timed");
response.response_timing()
}
};
let after = Instant::now();
let connection = timing
.connection_timing()
.context("native connection observations")?;
let dns = connection.shared_dns.context("shared DNS observations")?;
let prepared = connection
.request_prepared_at
.context("request preparation")?;
assert!(before <= dns.started_at);
assert!(dns.started_at <= dns.completed_at);
assert!(dns.completed_at <= prepared);
assert!(prepared <= timing.response_started_at().unwrap());
assert!(timing.response_end_at().unwrap() <= after);
assert!(connection.tls_context_started_at.is_none());
let curl = connection.curl.context("terminal curl statistics")?;
assert_eq!(curl.new_connections, Some(1));
assert_eq!(curl.app_connect, Some(Duration::ZERO));
assert!(curl.name_lookup.unwrap() <= curl.connect.unwrap());
assert!(curl.connect.unwrap() <= curl.pretransfer.unwrap());
assert!(curl.pretransfer.unwrap() <= curl.total.unwrap());
}
assert_eq!(server.hits(), 3);
server.shutdown();
Ok(())
}
#[tokio::test]
async fn native_connection_timing_does_not_leak_across_redirects_or_cache_hits() -> Result<()> {
let cache_dir = unique_test_cache_dir();
let server = ScriptedHttpServer::spawn(vec![
ScriptedResponse::ok("network"),
ScriptedResponse::ok("cached").with_header("Cache-Control", "max-age=60"),
]);
let redirect = ScriptedHttpServer::spawn(vec![
ScriptedResponse::status(302, "Found").with_header("Location", &server.url()),
]);
let mut source_url = Url::parse(&redirect.url())?;
source_url.set_host(Some("localhost"))?;
let mut config = FetchConfig::default();
config.set_http_proxy(Some(String::new()));
config.set_http_cache_dir(Some(cache_dir.display().to_string()));
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
let cancel = FetchCancelHandle::new();
let first = client
.fetch_with_cancel(Request::get(source_url.as_str())?, cancel.clone())
.await?;
assert_eq!(first.body_text(), "network");
let connection = cancel
.response_timing()
.connection_timing()
.context("final redirect attempt")?;
assert!(connection.shared_dns.is_none());
assert!(connection.curl.is_some());
let url = format!("{}/cached", server.url());
let response = client
.fetch_with_cancel(Request::get(&url)?, cancel.clone())
.await?;
assert_eq!(response.body_text(), "cached");
assert!(
cancel
.response_timing()
.connection_timing()
.unwrap()
.curl
.is_some()
);
let response = client
.fetch_with_cancel(Request::get(&url)?, cancel.clone())
.await?;
assert_eq!(response.body_text(), "cached");
assert_eq!(response.cache_state, crate::ResponseCacheState::Local);
assert!(cancel.response_timing().connection_timing().is_none());
assert_eq!(server.hits(), 2);
assert_eq!(redirect.hits(), 1);
drop(client);
server.shutdown();
redirect.shutdown();
fs::remove_dir_all(cache_dir)?;
Ok(())
}
+1
View File
@@ -4,6 +4,7 @@ mod cache_request_directives;
mod cache_request_modes;
mod cache_vary_encoding;
mod compression_dictionary;
mod connection_timing;
mod cookie_context;
mod cookie_store;
mod corp;
+57 -2
View File
@@ -241,7 +241,13 @@ async fn raw_response_timing_is_native_even_when_the_consumer_does_not_poll() ->
// Intentionally keep this Tokio thread occupied: the curl semantic owner
// must capture completion without the response consumer being polled.
let deadline = Instant::now() + Duration::from_secs(5);
while cancel.response_timing().response_end_at().is_none() {
while cancel.response_timing().response_end_at().is_none()
|| cancel
.response_timing()
.connection_timing()
.and_then(|connection| connection.curl)
.is_none()
{
assert!(
Instant::now() < deadline,
"native transfer did not complete"
@@ -249,6 +255,7 @@ async fn raw_response_timing_is_native_even_when_the_consumer_does_not_poll() ->
thread::sleep(Duration::from_millis(1));
}
let native = cancel.response_timing();
assert!(native.connection_timing().unwrap().curl.is_some());
let observed_at = Instant::now();
assert_eq!(native.response_started_at(), headers.response_started_at());
assert!(native.response_end_at().unwrap() >= native.response_started_at().unwrap());
@@ -312,12 +319,38 @@ async fn native_request_timing_is_transfer_scoped_on_multiplexed_http2() -> Resu
};
tokio::time::timeout(Duration::from_secs(5), requests).await??;
let after = Instant::now();
let mut new_connections = 0;
let mut tls_observations = 0;
for cancel in [buffered_cancel, raw_cancel] {
let timing = cancel.response_timing();
assert!(timing.request_started_at().unwrap() >= before);
assert!(timing.request_started_at().unwrap() <= timing.response_started_at().unwrap());
assert!(timing.response_started_at().unwrap() <= timing.response_end_at().unwrap());
assert!(timing.response_end_at().unwrap() <= after);
let connection = timing
.connection_timing()
.context("HTTP/2 connection timing")?;
let prepared = connection
.request_prepared_at
.context("HTTP/2 preparation")?;
assert!(before <= prepared && prepared <= after);
assert!(
connection.shared_dns.is_none(),
"the fixture uses an IP literal"
);
let curl = connection.curl.context("HTTP/2 transfer statistics")?;
new_connections += curl.new_connections.context("new connections statistic")?;
if let Some(tls_started) = connection.tls_context_started_at {
tls_observations += 1;
assert!(before <= tls_started && tls_started <= prepared);
}
}
assert_eq!(new_connections, 1);
if curl::Version::get()
.ssl_version()
.is_some_and(|version| version.starts_with("OpenSSL/"))
{
assert_eq!(tls_observations, 1);
}
// The barrier withholds all responses until both streams have arrived.
// A single connection therefore proves concurrent multiplexing, not just
@@ -378,6 +411,7 @@ async fn native_request_timing_waits_for_the_proxy_tunnel() -> Result<()> {
Ok::<_, anyhow::Error>(released_at)
};
let (response, released_at) = tokio::join!(fetch, release);
let released_at = released_at?;
let mut response = response?;
assert_eq!(
response.negotiated_http_version,
@@ -390,8 +424,29 @@ async fn native_request_timing_waits_for_the_proxy_tunnel() -> Result<()> {
response.finish().await?;
assert_eq!(body, b"tunneled");
let timing = cancel.response_timing();
assert!(timing.request_started_at().unwrap() >= released_at?);
assert!(timing.request_started_at().unwrap() >= released_at);
assert!(timing.request_started_at().unwrap() <= timing.response_started_at().unwrap());
let connection = timing
.connection_timing()
.context("tunnel connection timing")?;
let prepared = connection
.request_prepared_at
.context("tunnel request preparation")?;
if let Some(tls_started) = connection.tls_context_started_at {
assert!(released_at <= tls_started && tls_started <= prepared);
} else if curl::Version::get()
.ssl_version()
.is_some_and(|version| version.starts_with("OpenSSL/"))
{
panic!("OpenSSL should observe TLS setup after the proxy tunnel is established");
}
assert!(
connection
.curl
.context("tunnel curl statistics")?
.app_connect
.is_some()
);
drop(response);
drop(client);
proxy.join().unwrap()?;