Skip to main content

eggfetch_core/
trace.rs

1//! Core trace observer abstraction for HTTPX-compatible request tracing.
2//!
3//! This module defines a typed event vocabulary derived from httpcore 1.0.9,
4//! plus a callback trait that transports use to emit lifecycle events.
5//! The Python binding implements this trait and bridges to user-supplied
6//! trace callables without holding the GIL during network waits.
7//!
8//! # Reconciliation with metrics and metadata
9//!
10//! Trace covers request/response lifecycle (`send_request_headers`,
11//! `receive_response_headers`) consistently across direct, proxy, SOCKS,
12//! UDS, and H3 paths. Connector-level observations (DNS/connect/TLS
13//! attempts, H3 creations/evictions, proxy CONNECT outcomes, 101 upgrades)
14//! are counted in [`crate::TransportMetrics`] instead of duplicating the
15//! event taxonomy: metrics are cheap, always-on, and atomic, while trace
16//! callbacks are per-request, synchronous, and user-controlled.
17//!
18//! `ConnectTcp`, `ConnectUnixSocket`, `StartTls`, `Retry`, `Close`, and
19//! body/close events remain part of the httpcore-compatible vocabulary
20//! for facade compatibility, but only request/response header events are
21//! emitted today. Emitting DNS/connect/TLS trace events consistently
22//! across all five transport families would require plumbing observers
23//! into tower connectors; until that is done uniformly, those phases are
24//! observed via metrics to avoid contradictory duplicate lifecycle events.
25//! Existing event names and phases remain compatible.
26
27use std::collections::HashMap;
28use std::fmt;
29use std::sync::Arc;
30
31/// Typed lifecycle events emitted by the transport layer.
32///
33/// Event names and phases match httpcore 1.0.9's `Trace` context manager
34/// vocabulary. Each event has a phase (`Started`, `Complete`, `Failed`)
35/// and carries structured metadata as a map of string keys to opaque values.
36///
37/// The Python compatibility layer maps these to the dotted event names
38/// that HTTPX's `trace` extension expects (e.g. `connect_tcp.started`).
39#[derive(Debug, Clone)]
40pub enum TraceEvent {
41    /// TCP connection to the target host.
42    ConnectTcp {
43        /// Lifecycle phase.
44        phase: TracePhase,
45        /// Target hostname or IP address.
46        host: String,
47        /// Target port number.
48        port: u16,
49    },
50    /// Unix domain socket connection.
51    ConnectUnixSocket {
52        /// Lifecycle phase.
53        phase: TracePhase,
54        /// Path to the Unix domain socket.
55        path: String,
56    },
57    /// TLS handshake (client hello through finished).
58    StartTls {
59        /// Lifecycle phase.
60        phase: TracePhase,
61        /// Hostname used for TLS Server Name Indication.
62        server_hostname: String,
63    },
64    /// Connection retry with backoff delay.
65    Retry {
66        /// Lifecycle phase.
67        phase: TracePhase,
68        /// Delay in milliseconds before the retry attempt.
69        delay_ms: u64,
70    },
71    /// Connection closed.
72    Close {
73        /// Lifecycle phase.
74        phase: TracePhase,
75    },
76    /// HTTP/1.1 or HTTP/2 request headers sent.
77    SendRequestHeaders {
78        /// Lifecycle phase.
79        phase: TracePhase,
80        /// HTTP method (e.g. `"GET"`).
81        method: String,
82        /// Request target (e.g. `"/path"`).
83        target: String,
84    },
85    /// HTTP/1.1 or HTTP/2 request body chunks sent.
86    SendRequestBody {
87        /// Lifecycle phase.
88        phase: TracePhase,
89    },
90    /// HTTP/1.1 or HTTP/2 response status/headers received.
91    ReceiveResponseHeaders {
92        /// Lifecycle phase.
93        phase: TracePhase,
94        /// HTTP status code.
95        status: u16,
96    },
97    /// HTTP/1.1 or HTTP/2 response body chunks received.
98    ReceiveResponseBody {
99        /// Lifecycle phase.
100        phase: TracePhase,
101    },
102    /// Response stream closed; connection returned to pool or dropped.
103    ResponseClosed {
104        /// Lifecycle phase.
105        phase: TracePhase,
106    },
107}
108
109/// Lifecycle phase of a trace event.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub enum TracePhase {
112    /// Operation started.
113    Started,
114    /// Operation completed successfully.
115    Complete,
116    /// Operation failed with an error.
117    Failed,
118}
119
120impl fmt::Display for TracePhase {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        match self {
123            Self::Started => write!(f, "started"),
124            Self::Complete => write!(f, "complete"),
125            Self::Failed => write!(f, "failed"),
126        }
127    }
128}
129
130/// Map a [`TraceEvent`] to the httpcore 1.0.9 dotted event name.
131///
132/// Returns `(prefix, event_name)` where `prefix` is the httpcore
133/// logger name suffix (e.g. `"http11"`, `"connection"`) and
134/// `event_name` is the full dotted name (e.g. `"send_request_headers.started"`).
135#[must_use]
136pub fn event_to_httpcore_name(event: &TraceEvent) -> (&'static str, String) {
137    match event {
138        TraceEvent::ConnectTcp { phase, .. } => ("connection", format!("connect_tcp.{phase}")),
139        TraceEvent::ConnectUnixSocket { phase, .. } => {
140            ("connection", format!("connect_unix_socket.{phase}"))
141        }
142        TraceEvent::StartTls { phase, .. } => ("connection", format!("start_tls.{phase}")),
143        TraceEvent::Retry { phase, .. } => ("connection", format!("retry.{phase}")),
144        TraceEvent::Close { phase } => ("connection", format!("close.{phase}")),
145        TraceEvent::SendRequestHeaders { phase, .. } => {
146            ("http11", format!("send_request_headers.{phase}"))
147        }
148        TraceEvent::SendRequestBody { phase } => ("http11", format!("send_request_body.{phase}")),
149        TraceEvent::ReceiveResponseHeaders { phase, .. } => {
150            ("http11", format!("receive_response_headers.{phase}"))
151        }
152        TraceEvent::ReceiveResponseBody { phase } => {
153            ("http11", format!("receive_response_body.{phase}"))
154        }
155        TraceEvent::ResponseClosed { phase } => ("http11", format!("response_closed.{phase}")),
156    }
157}
158
159/// Convert a [`TraceEvent`] into the flat dictionary representation
160/// that httpcore's trace callback receives.
161pub fn event_to_info(event: &TraceEvent) -> HashMap<String, EventValue> {
162    let mut info = HashMap::new();
163    match event {
164        TraceEvent::ConnectTcp { host, port, .. } => {
165            info.insert("host".into(), EventValue::String(host.clone()));
166            info.insert("port".into(), EventValue::U16(*port));
167        }
168        TraceEvent::ConnectUnixSocket { path, .. } => {
169            info.insert("path".into(), EventValue::String(path.clone()));
170        }
171        TraceEvent::StartTls {
172            server_hostname, ..
173        } => {
174            info.insert(
175                "server_hostname".into(),
176                EventValue::String(server_hostname.clone()),
177            );
178        }
179        TraceEvent::Retry { delay_ms, .. } => {
180            info.insert("delay_ms".into(), EventValue::U64(*delay_ms));
181        }
182        TraceEvent::SendRequestHeaders { method, target, .. } => {
183            info.insert("method".into(), EventValue::String(method.clone()));
184            info.insert("target".into(), EventValue::String(target.clone()));
185        }
186        TraceEvent::ReceiveResponseHeaders { status, .. } => {
187            info.insert("status".into(), EventValue::U16(*status));
188        }
189        _ => {}
190    }
191    info
192}
193
194/// Opaque value type for trace event info dictionaries.
195#[derive(Debug, Clone, PartialEq)]
196pub enum EventValue {
197    /// A string value.
198    String(String),
199    /// A u16 value (e.g. status code, port).
200    U16(u16),
201    /// A u64 value (e.g. delay in milliseconds).
202    U64(u64),
203}
204
205/// Callback trait for receiving trace events from the transport layer.
206///
207/// Implementations must be `Send + Sync` because trace observers are
208/// stored on requests that may be sent across tokio tasks. The callback
209/// is invoked synchronously within the transport's async context; it
210/// must not block or perform I/O.
211///
212/// For Python bindings, the implementation acquires the GIL only at
213/// callback delivery points, never across network waits.
214///
215/// The return value controls whether the transport should continue or
216/// abort.  On `Abort`, the transport should short-circuit and return
217/// an error; the binding layer checks the error slot and surfaces the
218/// original callback exception.
219pub trait TraceObserver: Send + Sync + fmt::Debug {
220    /// Called when a trace event occurs.
221    ///
222    /// Returns `Continue` to let the transport proceed, or `Abort` to
223    /// signal that the transport should stop immediately.
224    fn on_event(&self, event: &TraceEvent) -> OnEventAction;
225}
226
227/// Control result returned by [`TraceObserver::on_event`].
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum OnEventAction {
230    /// The transport should continue processing.
231    Continue,
232    /// The transport should abort immediately.  The observer has
233    /// recorded an error in its binding-owned slot; the caller should
234    /// surface that error after stopping.
235    Abort,
236}
237
238/// A no-op trace observer that silently discards all events.
239#[derive(Debug)]
240pub struct NoopTraceObserver;
241
242impl TraceObserver for NoopTraceObserver {
243    fn on_event(&self, _event: &TraceEvent) -> OnEventAction {
244        OnEventAction::Continue
245    }
246}
247
248/// A trace observer that collects events into a shared vector.
249///
250/// Primarily used for testing and debugging.
251#[derive(Debug, Clone)]
252pub struct CollectingTraceObserver {
253    events: Arc<std::sync::Mutex<Vec<TraceEvent>>>,
254}
255
256impl Default for CollectingTraceObserver {
257    fn default() -> Self {
258        Self::new()
259    }
260}
261
262impl CollectingTraceObserver {
263    /// Create a new collecting observer.
264    #[must_use]
265    pub fn new() -> Self {
266        Self {
267            events: Arc::new(std::sync::Mutex::new(Vec::new())),
268        }
269    }
270
271    /// Drain and return all collected events.
272    ///
273    /// The collector protects a plain vector with no invariants, so lock
274    /// poisoning is recovered from instead of cascading panics.
275    pub fn drain(&self) -> Vec<TraceEvent> {
276        std::mem::take(
277            &mut *self
278                .events
279                .lock()
280                .unwrap_or_else(std::sync::PoisonError::into_inner),
281        )
282    }
283
284    /// Return the number of collected events without consuming them.
285    #[must_use]
286    pub fn len(&self) -> usize {
287        self.events
288            .lock()
289            .unwrap_or_else(std::sync::PoisonError::into_inner)
290            .len()
291    }
292
293    /// Returns `true` if no events have been collected.
294    #[must_use]
295    pub fn is_empty(&self) -> bool {
296        self.len() == 0
297    }
298}
299
300impl TraceObserver for CollectingTraceObserver {
301    fn on_event(&self, event: &TraceEvent) -> OnEventAction {
302        self.events
303            .lock()
304            .unwrap_or_else(std::sync::PoisonError::into_inner)
305            .push(event.clone());
306        OnEventAction::Continue
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    #[test]
315    fn event_to_httpcore_name_connect_tcp() {
316        let event = TraceEvent::ConnectTcp {
317            phase: TracePhase::Started,
318            host: "example.com".into(),
319            port: 443,
320        };
321        let (prefix, name) = event_to_httpcore_name(&event);
322        assert_eq!(prefix, "connection");
323        assert_eq!(name, "connect_tcp.started");
324    }
325
326    #[test]
327    fn event_to_httpcore_name_send_headers() {
328        let event = TraceEvent::SendRequestHeaders {
329            phase: TracePhase::Complete,
330            method: "GET".into(),
331            target: "/".into(),
332        };
333        let (prefix, name) = event_to_httpcore_name(&event);
334        assert_eq!(prefix, "http11");
335        assert_eq!(name, "send_request_headers.complete");
336    }
337
338    #[test]
339    fn event_to_info_connect_tcp() {
340        let event = TraceEvent::ConnectTcp {
341            phase: TracePhase::Started,
342            host: "example.com".into(),
343            port: 443,
344        };
345        let info = event_to_info(&event);
346        assert_eq!(
347            info.get("host"),
348            Some(&EventValue::String("example.com".into()))
349        );
350        assert_eq!(info.get("port"), Some(&EventValue::U16(443)));
351    }
352
353    #[test]
354    fn collecting_observer_stores_events() {
355        let observer = CollectingTraceObserver::new();
356        let action = observer.on_event(&TraceEvent::Close {
357            phase: TracePhase::Started,
358        });
359        assert_eq!(action, OnEventAction::Continue);
360        observer.on_event(&TraceEvent::Close {
361            phase: TracePhase::Complete,
362        });
363        assert_eq!(observer.len(), 2);
364        let events = observer.drain();
365        assert_eq!(events.len(), 2);
366        assert!(observer.is_empty());
367    }
368}