eoka 0.14.3

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Network Request Capture
//!
//! [`RequestCapture`] (from [`Page::capture_requests`](crate::Page::capture_requests))
//! records one page's HTTP requests and responses. [`NetworkWatcher`] is the
//! lower-level engine for callers that feed it CDP events themselves.

mod capture;
mod store;

pub use capture::{RequestCapture, RequestCaptureOptions, RequestCaptureStats};
use store::RequestStore;

use std::collections::HashMap;
use std::sync::Mutex;

use tokio::sync::mpsc;

use crate::cdp::transport::CdpMessage;
use crate::util::LockExt;

/// A captured HTTP request with its response. `Debug` omits header values, the
/// request body and URL queries.
#[derive(Clone)]
pub struct CapturedRequest {
    /// CDP request ID (use with `get_response_body`).
    pub request_id: String,
    /// Request URL.
    pub url: String,
    /// HTTP method.
    pub method: String,
    /// Request headers.
    pub headers: HashMap<String, String>,
    /// Request body, if present.
    pub post_data: Option<String>,
    /// Resource type (e.g. "Document", "XHR", "Script").
    pub resource_type: Option<String>,
    /// Response status code, once received.
    pub status: Option<i32>,
    /// Response status text, once received.
    pub status_text: Option<String>,
    /// Response headers, once received.
    pub response_headers: Option<HashMap<String, String>>,
    /// Response MIME type, once received.
    pub mime_type: Option<String>,
    /// Time the request was initiated (CDP monotonic timestamp).
    pub timestamp: f64,
    /// Whether the response has finished loading.
    pub complete: bool,
}

impl std::fmt::Debug for CapturedRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CapturedRequest")
            .field("request_id", &self.request_id)
            .field("url", &crate::util::without_query(&self.url))
            .field("method", &self.method)
            .field("header_names", &self.headers.keys())
            .field("post_data_bytes", &self.post_data.as_ref().map(String::len))
            .field("resource_type", &self.resource_type)
            .field("status", &self.status)
            .field("status_text", &self.status_text)
            .field(
                "response_header_names",
                &self.response_headers.as_ref().map(HashMap::keys),
            )
            .field("mime_type", &self.mime_type)
            .field("timestamp", &self.timestamp)
            .field("complete", &self.complete)
            .finish()
    }
}

/// Response body - either text or binary. `Debug` prints only the length.
pub enum ResponseBody {
    /// Textual response body.
    Text(String),
    /// Binary response body.
    Binary(Vec<u8>),
}

impl std::fmt::Debug for ResponseBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (kind, bytes) = match self {
            Self::Text(text) => ("Text", text.len()),
            Self::Binary(bytes) => ("Binary", bytes.len()),
        };
        f.debug_struct("ResponseBody")
            .field("kind", &kind)
            .field("bytes", &bytes)
            .finish()
    }
}

impl ResponseBody {
    /// Get as text, or `None` for a binary response.
    pub fn as_text(&self) -> Option<&str> {
        match self {
            ResponseBody::Text(s) => Some(s),
            ResponseBody::Binary(_) => None,
        }
    }

    /// Get as bytes
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            ResponseBody::Text(s) => s.as_bytes(),
            ResponseBody::Binary(b) => b,
        }
    }
}

/// Network event types. `Debug` omits header values and URL queries.
#[derive(Clone)]
pub enum NetworkEvent {
    /// A new request was initiated
    RequestStarted(CapturedRequest),
    /// Response headers received
    ResponseReceived {
        /// ID of the request this response belongs to.
        request_id: String,
        /// HTTP status code.
        status: i32,
        /// HTTP status text.
        status_text: String,
        /// Response headers.
        headers: HashMap<String, String>,
        /// Response MIME type, if known.
        mime_type: Option<String>,
    },
    /// Request completed successfully
    RequestCompleted {
        /// ID of the completed request.
        request_id: String,
        /// Total bytes received over the wire.
        encoded_data_length: i64,
    },
    /// Request failed
    RequestFailed {
        /// ID of the failed request.
        request_id: String,
        /// Failure reason.
        error_text: String,
        /// Whether the request was canceled.
        canceled: bool,
    },
}

impl std::fmt::Debug for NetworkEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::RequestStarted(request) => {
                f.debug_tuple("RequestStarted").field(request).finish()
            }
            Self::ResponseReceived {
                request_id,
                status,
                status_text,
                headers,
                mime_type,
            } => f
                .debug_struct("ResponseReceived")
                .field("request_id", request_id)
                .field("status", status)
                .field("status_text", status_text)
                .field("header_names", &headers.keys())
                .field("mime_type", mime_type)
                .finish(),
            Self::RequestCompleted {
                request_id,
                encoded_data_length,
            } => f
                .debug_struct("RequestCompleted")
                .field("request_id", request_id)
                .field("encoded_data_length", encoded_data_length)
                .finish(),
            Self::RequestFailed {
                request_id,
                error_text,
                canceled,
            } => f
                .debug_struct("RequestFailed")
                .field("request_id", request_id)
                .field("error_text", error_text)
                .field("canceled", canceled)
                .finish(),
        }
    }
}

/// Default bound for [`NetworkWatcher`]. Long-lived connections (WebSocket,
/// SSE, long-polling) never finish, so every store is bounded.
const MAX_TRACKED_REQUESTS: usize = 10_000;

/// Watches network events and provides a stream of captured requests.
///
/// Feed it events with [`process_event`](Self::process_event). Use
/// [`for_session`](Self::for_session) to ignore events from other CDP sessions;
/// [`new`](Self::new) accepts every session. At most 10,000 requests are kept,
/// evicting the oldest first. Prefer [`Page::capture_requests`](crate::Page::capture_requests),
/// which subscribes and filters for you.
pub struct NetworkWatcher {
    session_id: Option<String>,
    requests: Mutex<RequestStore>,
    event_tx: mpsc::Sender<NetworkEvent>,
    /// Held across `recv().await`, so an async mutex.
    event_rx: tokio::sync::Mutex<mpsc::Receiver<NetworkEvent>>,
}

#[allow(
    clippy::unused_async,
    reason = "public API; removing async breaks callers that await it"
)]
impl NetworkWatcher {
    /// Create a watcher that accepts events from every CDP session.
    pub fn new() -> Self {
        Self::with_filter(None)
    }

    /// Create a watcher that ignores events not tagged with `session_id`
    /// (for example from [`Session::session_id`](crate::cdp::Session::session_id)).
    pub fn for_session(session_id: impl Into<String>) -> Self {
        Self::with_filter(Some(session_id.into()))
    }

    fn with_filter(session_id: Option<String>) -> Self {
        let (event_tx, event_rx) = mpsc::channel(256);
        Self {
            session_id,
            requests: Mutex::new(RequestStore::new(MAX_TRACKED_REQUESTS)),
            event_tx,
            event_rx: tokio::sync::Mutex::new(event_rx),
        }
    }

    /// Process a CDP event.
    /// Returns true if it was a network event for this watcher's session.
    pub async fn process_event(&self, event: &CdpMessage) -> bool {
        let CdpMessage::Event {
            method,
            params,
            session_id,
        } = event
        else {
            return false;
        };
        if self
            .session_id
            .as_ref()
            .is_some_and(|wanted| session_id.as_ref() != Some(wanted))
        {
            return false;
        }
        let Some(emitted) = self.requests.lock_unpoisoned().apply(method, params) else {
            return false;
        };
        if let Some(event) = emitted {
            self.emit(event);
        }
        true
    }

    /// Emit an event to consumers without blocking the pump.
    fn emit(&self, event: NetworkEvent) {
        if let Err(e) = self.event_tx.try_send(event) {
            tracing::warn!("Dropping network event (consumer not draining): {}", e);
        }
    }

    /// Receive the next network event
    pub async fn recv(&self) -> Option<NetworkEvent> {
        let mut rx = self.event_rx.lock().await;
        rx.recv().await
    }

    /// Try to receive a network event without blocking
    pub async fn try_recv(&self) -> Option<NetworkEvent> {
        // Use try_lock so a concurrent recv() doesn't block us.
        let Ok(mut rx) = self.event_rx.try_lock() else {
            return None;
        };
        rx.try_recv().ok()
    }

    /// Get a captured request by ID
    pub async fn get_request(&self, request_id: &str) -> Option<CapturedRequest> {
        self.requests.lock_unpoisoned().get(request_id)
    }

    /// Get all retained requests, oldest first.
    pub async fn get_all_requests(&self) -> Vec<CapturedRequest> {
        self.requests.lock_unpoisoned().all()
    }

    /// Clear all captured requests
    pub async fn clear(&self) {
        self.requests.lock_unpoisoned().clear();
    }
}

impl Default for NetworkWatcher {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_network_watcher_creation() {
        let watcher = NetworkWatcher::new();
        assert!(watcher.get_all_requests().await.is_empty());
    }

    fn event(method: &str, params: serde_json::Value) -> CdpMessage {
        CdpMessage::Event {
            method: method.to_string(),
            params,
            session_id: None,
        }
    }

    fn request_will_be_sent(id: &str, url: &str) -> CdpMessage {
        event(
            "Network.requestWillBeSent",
            serde_json::json!({
                "requestId": id,
                "request": {
                    "url": url,
                    "method": "GET",
                    "headers": {},
                },
                "timestamp": 1.0,
                "type": "Document",
            }),
        )
    }

    /// Regression: a completed request (finished loading) must be retained so
    /// `get_request` still returns it with `complete == true` and the response
    /// status populated. Previously loadingFinished removed the entry.
    #[tokio::test]
    async fn test_completed_request_is_retained() {
        let watcher = NetworkWatcher::new();
        let id = "req-1";

        assert!(
            watcher
                .process_event(&request_will_be_sent(id, "https://example.com/"))
                .await
        );
        assert!(
            watcher
                .process_event(&event(
                    "Network.responseReceived",
                    serde_json::json!({
                        "requestId": id,
                        "response": {
                            "url": "https://example.com/",
                            "status": 200,
                            "statusText": "OK",
                            "headers": {},
                            "mimeType": "text/html",
                        },
                    }),
                ))
                .await
        );
        assert!(
            watcher
                .process_event(&event(
                    "Network.loadingFinished",
                    serde_json::json!({
                        "requestId": id,
                        "timestamp": 2.0,
                        "encodedDataLength": 1234,
                    }),
                ))
                .await
        );

        let req = watcher.get_request(id).await.expect("request retained");
        assert!(req.complete);
        assert_eq!(req.status, Some(200));
        assert_eq!(req.status_text.as_deref(), Some("OK"));
    }

    /// Regression: a redirect re-fires requestWillBeSent with the same
    /// request_id. The original entry (first URL) must be kept and there must
    /// be exactly one stored entry.
    #[tokio::test]
    async fn test_redirect_keeps_original_entry() {
        let watcher = NetworkWatcher::new();
        let id = "req-redirect";

        assert!(
            watcher
                .process_event(&request_will_be_sent(id, "https://first.example/"))
                .await
        );
        assert!(
            watcher
                .process_event(&request_will_be_sent(id, "https://second.example/"))
                .await
        );

        let req = watcher.get_request(id).await.expect("request present");
        assert_eq!(req.url, "https://first.example/");
        assert_eq!(watcher.get_all_requests().await.len(), 1);
    }

    /// A failed request (loadingFailed) must be removed from the store.
    #[tokio::test]
    async fn test_loading_failed_removes_entry() {
        let watcher = NetworkWatcher::new();
        let id = "req-fail";

        assert!(
            watcher
                .process_event(&request_will_be_sent(id, "https://example.com/"))
                .await
        );
        assert!(watcher.get_request(id).await.is_some());

        assert!(
            watcher
                .process_event(&event(
                    "Network.loadingFailed",
                    serde_json::json!({
                        "requestId": id,
                        "errorText": "net::ERR_FAILED",
                        "canceled": false,
                    }),
                ))
                .await
        );

        assert!(watcher.get_request(id).await.is_none());
    }

    /// Regression: the pump must not block when events are never drained.
    /// Feeding well over the channel capacity without ever calling `recv()`
    /// should complete (proving `emit` uses non-blocking `try_send`) and the
    /// store should reflect every request.
    #[tokio::test]
    async fn test_pump_does_not_block_when_events_not_drained() {
        const N: usize = 300;
        let watcher = NetworkWatcher::new();

        for i in 0..N {
            let id = format!("req-{i}");
            let url = format!("https://example.com/{i}");
            assert!(
                watcher
                    .process_event(&request_will_be_sent(&id, &url))
                    .await
            );
        }

        // Reaching here without hanging proves the pump never blocked.
        assert_eq!(watcher.get_all_requests().await.len(), N);
        assert!(watcher.get_request("req-0").await.is_some());
        assert!(watcher
            .get_request(&format!("req-{}", N - 1))
            .await
            .is_some());
    }

    fn on_session(message: CdpMessage, id: &str) -> CdpMessage {
        match message {
            CdpMessage::Event { method, params, .. } => CdpMessage::Event {
                method,
                params,
                session_id: Some(id.to_string()),
            },
            other => other,
        }
    }

    /// Regression: the watcher accepted events from every CDP session.
    #[tokio::test]
    async fn test_for_session_ignores_other_sessions() {
        let watcher = NetworkWatcher::for_session("mine");
        let theirs = on_session(request_will_be_sent("a", "https://a.test/"), "theirs");
        let untagged = request_will_be_sent("b", "https://b.test/");
        let mine = on_session(request_will_be_sent("c", "https://c.test/"), "mine");
        assert!(!watcher.process_event(&theirs).await);
        assert!(!watcher.process_event(&untagged).await);
        assert!(watcher.process_event(&mine).await);
        let ids: Vec<_> = watcher
            .get_all_requests()
            .await
            .into_iter()
            .map(|r| r.request_id)
            .collect();
        assert_eq!(ids, ["c"]);
    }

    /// Regression: eviction removed an arbitrary HashMap entry instead of the
    /// oldest, and completed requests were never removed at all.
    #[test]
    fn test_store_evicts_oldest_first_including_completed() {
        let mut store = RequestStore::new(3);
        let apply = |store: &mut RequestStore, message: CdpMessage| {
            let CdpMessage::Event { method, params, .. } = message else {
                unreachable!()
            };
            store.apply(&method, &params)
        };
        for i in 0..5 {
            let id = format!("r{i}");
            apply(
                &mut store,
                request_will_be_sent(&id, &format!("https://x.test/{i}")),
            );
            apply(
                &mut store,
                event(
                    "Network.loadingFinished",
                    serde_json::json!({"requestId": id, "timestamp": 2.0, "encodedDataLength": 1}),
                ),
            );
        }
        let ids: Vec<_> = store.all().into_iter().map(|r| r.request_id).collect();
        assert_eq!(ids, ["r2", "r3", "r4"]);
        assert_eq!(store.evicted, 2);

        // A failed request frees its slot without disturbing the order.
        apply(
            &mut store,
            event(
                "Network.loadingFailed",
                serde_json::json!({"requestId": "r3", "errorText": "net::ERR_FAILED"}),
            ),
        );
        apply(&mut store, request_will_be_sent("r5", "https://x.test/5"));
        let ids: Vec<_> = store.all().into_iter().map(|r| r.request_id).collect();
        assert_eq!(ids, ["r2", "r4", "r5"]);
        assert_eq!((store.evicted, store.failed), (2, 1));

        let drained: Vec<_> = store
            .drain_completed()
            .into_iter()
            .map(|r| r.request_id)
            .collect();
        assert_eq!(drained, ["r2", "r4"], "r5 is still in flight");
        assert_eq!(store.all().len(), 1);
    }
}