Skip to main content

chromiumoxide/handler/
mod.rs

1use crate::listeners::{EventListenerRequest, EventListeners};
2use chromiumoxide_cdp::cdp::browser_protocol::browser::*;
3use chromiumoxide_cdp::cdp::browser_protocol::target::*;
4use chromiumoxide_cdp::cdp::events::CdpEvent;
5use chromiumoxide_cdp::cdp::events::CdpEventMessage;
6use chromiumoxide_types::{CallId, Message, Method, Response};
7use chromiumoxide_types::{MethodId, Request as CdpRequest};
8use fnv::FnvHashMap;
9use futures_util::Stream;
10use hashbrown::{HashMap, HashSet};
11use spider_network_blocker::intercept_manager::NetworkInterceptManager;
12use std::pin::Pin;
13use std::task::{Context, Poll};
14use std::time::{Duration, Instant};
15use tokio::sync::mpsc::Receiver;
16use tokio::sync::oneshot::Sender as OneshotSender;
17use tokio_tungstenite::tungstenite::error::ProtocolError;
18use tokio_tungstenite::tungstenite::Error;
19
20use std::sync::Arc;
21use tokio::sync::Notify;
22
23use crate::cmd::{to_command_response, CommandMessage};
24use crate::conn::Connection;
25use crate::error::{CdpError, Result};
26use crate::handler::browser::BrowserContext;
27use crate::handler::frame::FrameRequestedNavigation;
28use crate::handler::frame::{NavigationError, NavigationId, NavigationOk};
29use crate::handler::job::PeriodicJob;
30use crate::handler::session::Session;
31use crate::handler::target::TargetEvent;
32use crate::handler::target::{Target, TargetConfig};
33use crate::handler::viewport::Viewport;
34use crate::page::Page;
35pub(crate) use page::PageInner;
36
37/// Standard timeout in MS
38pub const REQUEST_TIMEOUT: u64 = 30_000;
39
40pub mod blockers;
41pub mod browser;
42pub mod commandfuture;
43pub mod domworld;
44pub mod emulation;
45pub mod frame;
46pub mod http;
47pub mod httpfuture;
48mod job;
49pub mod network;
50pub mod network_utils;
51pub mod page;
52#[cfg(feature = "parallel-handler")]
53pub mod parallel;
54pub mod sender;
55mod session;
56pub mod target;
57pub mod target_message_future;
58pub mod viewport;
59
60/// The handler that monitors the state of the chromium browser and drives all
61/// the requests and events.
62#[must_use = "streams do nothing unless polled"]
63#[derive(Debug)]
64pub struct Handler {
65    pub default_browser_context: BrowserContext,
66    pub browser_contexts: HashSet<BrowserContext>,
67    /// Commands that are being processed and awaiting a response from the
68    /// chromium instance together with the timestamp when the request
69    /// started.
70    pending_commands: FnvHashMap<CallId, (PendingRequest, MethodId, Instant)>,
71    /// Connection to the browser instance
72    from_browser: Receiver<HandlerMessage>,
73    /// Used to loop over all targets in a consistent manner
74    target_ids: Vec<TargetId>,
75    /// The created and attached targets
76    targets: HashMap<TargetId, Target>,
77    /// Currently queued in navigations for targets
78    navigations: FnvHashMap<NavigationId, NavigationRequest>,
79    /// Keeps track of all the current active sessions
80    ///
81    /// There can be multiple sessions per target.
82    sessions: HashMap<SessionId, Session>,
83    /// The websocket connection to the chromium instance.
84    /// `Option` so that `run()` can `.take()` it for splitting.
85    conn: Option<Connection<CdpEventMessage>>,
86    /// Evicts timed out requests periodically
87    evict_command_timeout: PeriodicJob,
88    /// The internal identifier for a specific navigation
89    next_navigation_id: usize,
90    /// How this handler will configure targets etc,
91    config: HandlerConfig,
92    /// All registered event subscriptions
93    event_listeners: EventListeners,
94    /// Keeps track is the browser is closing
95    closing: bool,
96    /// Track the bytes remainder until network request will be blocked.
97    remaining_bytes: Option<u64>,
98    /// The budget is exhausted.
99    budget_exhausted: bool,
100    /// Tracks which targets we've already attached to, to avoid multiple sessions per target.
101    attached_targets: HashSet<TargetId>,
102    /// Optional notify for waking `Handler::run()`'s `tokio::select!` loop
103    /// when a page sends a message.  `None` when using the `Stream` API.
104    page_wake: Option<Arc<Notify>>,
105}
106
107lazy_static::lazy_static! {
108    /// Set the discovery ID target.
109    static ref DISCOVER_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
110        let discover = SetDiscoverTargetsParams::new(true);
111        (discover.identifier(), serde_json::to_value(discover).expect("valid discover target params"))
112    };
113    /// Targets params id.
114    static ref TARGET_PARAMS_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
115        let msg = GetTargetsParams { filter: None };
116        (msg.identifier(), serde_json::to_value(msg).expect("valid paramtarget"))
117    };
118    /// Set the close targets.
119    static ref CLOSE_PARAMS_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
120        let close_msg = CloseParams::default();
121        (close_msg.identifier(), serde_json::to_value(close_msg).expect("valid close params"))
122    };
123}
124
125fn maybe_store_attach_session_id(target: &mut Target, method: &MethodId, resp: &Response) {
126    if method.as_ref() != AttachToTargetParams::IDENTIFIER {
127        return;
128    }
129
130    if let Ok(resp) = to_command_response::<AttachToTargetParams>(resp.clone(), method.clone()) {
131        target.set_session_id(resp.result.session_id);
132    }
133}
134
135impl Handler {
136    /// Create a new `Handler` that drives the connection and listens for
137    /// messages on the receiver `rx`.
138    pub(crate) fn new(
139        mut conn: Connection<CdpEventMessage>,
140        rx: Receiver<HandlerMessage>,
141        config: HandlerConfig,
142    ) -> Self {
143        let discover = DISCOVER_ID.clone();
144        let _ = conn.submit_command(discover.0, None, discover.1);
145        let conn = Some(conn);
146
147        let browser_contexts = config
148            .context_ids
149            .iter()
150            .map(|id| BrowserContext::from(id.clone()))
151            .collect();
152
153        Self {
154            pending_commands: Default::default(),
155            from_browser: rx,
156            default_browser_context: Default::default(),
157            browser_contexts,
158            target_ids: Default::default(),
159            targets: Default::default(),
160            navigations: Default::default(),
161            sessions: Default::default(),
162            conn,
163            evict_command_timeout: PeriodicJob::new(config.request_timeout),
164            next_navigation_id: 0,
165            config,
166            event_listeners: Default::default(),
167            closing: false,
168            remaining_bytes: None,
169            budget_exhausted: false,
170            attached_targets: Default::default(),
171            page_wake: None,
172        }
173    }
174
175    /// Borrow the WebSocket connection, returning an error if it has been
176    /// consumed by [`Handler::run()`].
177    #[inline]
178    fn conn(&mut self) -> Result<&mut Connection<CdpEventMessage>> {
179        self.conn
180            .as_mut()
181            .ok_or_else(|| CdpError::msg("connection consumed by Handler::run()"))
182    }
183
184    /// Return the target with the matching `target_id`
185    pub fn get_target(&self, target_id: &TargetId) -> Option<&Target> {
186        self.targets.get(target_id)
187    }
188
189    /// Iterator over all currently attached targets
190    pub fn targets(&self) -> impl Iterator<Item = &Target> + '_ {
191        self.targets.values()
192    }
193
194    /// The default Browser context
195    pub fn default_browser_context(&self) -> &BrowserContext {
196        &self.default_browser_context
197    }
198
199    /// Iterator over all currently available browser contexts
200    pub fn browser_contexts(&self) -> impl Iterator<Item = &BrowserContext> + '_ {
201        self.browser_contexts.iter()
202    }
203
204    /// received a response to a navigation request like `Page.navigate`
205    fn on_navigation_response(&mut self, id: NavigationId, resp: Response) {
206        if let Some(nav) = self.navigations.remove(&id) {
207            match nav {
208                NavigationRequest::Navigate(mut nav) => {
209                    if nav.navigated {
210                        let _ = nav.tx.send(Ok(resp));
211                    } else {
212                        nav.set_response(resp);
213                        self.navigations
214                            .insert(id, NavigationRequest::Navigate(nav));
215                    }
216                }
217            }
218        }
219    }
220
221    /// A navigation has finished.
222    fn on_navigation_lifecycle_completed(&mut self, res: Result<NavigationOk, NavigationError>) {
223        match res {
224            Ok(ok) => {
225                let id = *ok.navigation_id();
226                if let Some(nav) = self.navigations.remove(&id) {
227                    match nav {
228                        NavigationRequest::Navigate(mut nav) => {
229                            if let Some(resp) = nav.response.take() {
230                                let _ = nav.tx.send(Ok(resp));
231                            } else {
232                                nav.set_navigated();
233                                self.navigations
234                                    .insert(id, NavigationRequest::Navigate(nav));
235                            }
236                        }
237                    }
238                }
239            }
240            Err(err) => {
241                if let Some(nav) = self.navigations.remove(err.navigation_id()) {
242                    match nav {
243                        NavigationRequest::Navigate(nav) => {
244                            let _ = nav.tx.send(Err(err.into()));
245                        }
246                    }
247                }
248            }
249        }
250    }
251
252    /// Received a response to a request.
253    fn on_response(&mut self, resp: Response) {
254        if let Some((req, method, _)) = self.pending_commands.remove(&resp.id) {
255            match req {
256                PendingRequest::CreateTarget(tx) => {
257                    match to_command_response::<CreateTargetParams>(resp, method) {
258                        Ok(resp) => {
259                            if let Some(target) = self.targets.get_mut(&resp.target_id) {
260                                target.set_initiator(tx);
261                            } else {
262                                let _ = tx.send(Err(CdpError::NotFound)).ok();
263                            }
264                        }
265                        Err(err) => {
266                            let _ = tx.send(Err(err)).ok();
267                        }
268                    }
269                }
270                PendingRequest::GetTargets(tx) => {
271                    match to_command_response::<GetTargetsParams>(resp, method) {
272                        Ok(resp) => {
273                            let targets = resp.result.target_infos;
274                            let results = targets.clone();
275
276                            for target_info in targets {
277                                let event: EventTargetCreated = EventTargetCreated { target_info };
278                                self.on_target_created(event);
279                            }
280
281                            let _ = tx.send(Ok(results)).ok();
282                        }
283                        Err(err) => {
284                            let _ = tx.send(Err(err)).ok();
285                        }
286                    }
287                }
288                PendingRequest::Navigate(id) => {
289                    self.on_navigation_response(id, resp);
290                    if self.config.only_html && !self.config.created_first_target {
291                        self.config.created_first_target = true;
292                    }
293                }
294                PendingRequest::ExternalCommand { tx, .. } => {
295                    let _ = tx.send(Ok(resp)).ok();
296                }
297                PendingRequest::InternalCommand(target_id) => {
298                    if let Some(target) = self.targets.get_mut(&target_id) {
299                        maybe_store_attach_session_id(target, &method, &resp);
300                        target.on_response(resp, method.as_ref());
301                    }
302                }
303                PendingRequest::CloseBrowser(tx) => {
304                    self.closing = true;
305                    let _ = tx.send(Ok(CloseReturns {})).ok();
306                }
307            }
308        }
309    }
310
311    /// Submit a command initiated via channel
312    pub(crate) fn submit_external_command(
313        &mut self,
314        msg: CommandMessage,
315        now: Instant,
316    ) -> Result<()> {
317        // Resolve session_id → target_id before `submit_command`
318        // consumes `msg.session_id`. `None` when the session hasn't
319        // landed in `self.sessions` yet; that command then relies on
320        // the normal request_timeout path if the target later crashes.
321        let target_id = msg
322            .session_id
323            .as_ref()
324            .and_then(|sid| self.sessions.get(sid.as_ref()))
325            .map(|s| s.target_id().clone());
326        let call_id =
327            self.conn()?
328                .submit_command(msg.method.clone(), msg.session_id, msg.params)?;
329        self.pending_commands.insert(
330            call_id,
331            (
332                PendingRequest::ExternalCommand {
333                    tx: msg.sender,
334                    target_id,
335                },
336                msg.method,
337                now,
338            ),
339        );
340        Ok(())
341    }
342
343    pub(crate) fn submit_internal_command(
344        &mut self,
345        target_id: TargetId,
346        req: CdpRequest,
347        now: Instant,
348    ) -> Result<()> {
349        let call_id = self.conn()?.submit_command(
350            req.method.clone(),
351            req.session_id.map(Into::into),
352            req.params,
353        )?;
354        self.pending_commands.insert(
355            call_id,
356            (PendingRequest::InternalCommand(target_id), req.method, now),
357        );
358        Ok(())
359    }
360
361    fn submit_fetch_targets(&mut self, tx: OneshotSender<Result<Vec<TargetInfo>>>, now: Instant) {
362        let msg = TARGET_PARAMS_ID.clone();
363
364        if let Some(conn) = self.conn.as_mut() {
365            if let Ok(call_id) = conn.submit_command(msg.0.clone(), None, msg.1) {
366                self.pending_commands
367                    .insert(call_id, (PendingRequest::GetTargets(tx), msg.0, now));
368            }
369        }
370    }
371
372    /// Send the Request over to the server and store its identifier to handle
373    /// the response once received.
374    fn submit_navigation(&mut self, id: NavigationId, req: CdpRequest, now: Instant) {
375        if let Some(conn) = self.conn.as_mut() {
376            if let Ok(call_id) = conn.submit_command(
377                req.method.clone(),
378                req.session_id.map(Into::into),
379                req.params,
380            ) {
381                self.pending_commands
382                    .insert(call_id, (PendingRequest::Navigate(id), req.method, now));
383            }
384        }
385    }
386
387    fn submit_close(&mut self, tx: OneshotSender<Result<CloseReturns>>, now: Instant) {
388        let close_msg = CLOSE_PARAMS_ID.clone();
389
390        if let Some(conn) = self.conn.as_mut() {
391            if let Ok(call_id) = conn.submit_command(close_msg.0.clone(), None, close_msg.1) {
392                self.pending_commands.insert(
393                    call_id,
394                    (PendingRequest::CloseBrowser(tx), close_msg.0, now),
395                );
396            }
397        }
398    }
399
400    /// Process a message received by the target's page via channel
401    fn on_target_message(&mut self, target: &mut Target, msg: CommandMessage, now: Instant) {
402        if msg.is_navigation() {
403            let (req, tx) = msg.split();
404            let id = self.next_navigation_id();
405
406            target.goto(FrameRequestedNavigation::new(
407                id,
408                req,
409                self.config.request_timeout,
410            ));
411
412            self.navigations.insert(
413                id,
414                NavigationRequest::Navigate(NavigationInProgress::new(tx)),
415            );
416        } else {
417            let _ = self.submit_external_command(msg, now);
418        }
419    }
420
421    /// An identifier for queued `NavigationRequest`s.
422    fn next_navigation_id(&mut self) -> NavigationId {
423        let id = NavigationId(self.next_navigation_id);
424        self.next_navigation_id = self.next_navigation_id.wrapping_add(1);
425        id
426    }
427
428    /// Create a new page and send it to the receiver when ready
429    ///
430    /// First a `CreateTargetParams` is send to the server, this will trigger
431    /// `EventTargetCreated` which results in a new `Target` being created.
432    /// Once the response to the request is received the initialization process
433    /// of the target kicks in. This triggers a queue of initialization requests
434    /// of the `Target`, once those are all processed and the `url` fo the
435    /// `CreateTargetParams` has finished loading (The `Target`'s `Page` is
436    /// ready and idle), the `Target` sends its newly created `Page` as response
437    /// to the initiator (`tx`) of the `CreateTargetParams` request.
438    fn create_page(&mut self, params: CreateTargetParams, tx: OneshotSender<Result<Page>>) {
439        let about_blank = params.url == "about:blank";
440        let http_check =
441            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
442
443        if about_blank || http_check {
444            let method = params.identifier();
445
446            let Some(conn) = self.conn.as_mut() else {
447                let _ = tx.send(Err(CdpError::msg("connection consumed"))).ok();
448                return;
449            };
450            match serde_json::to_value(params) {
451                Ok(params) => match conn.submit_command(method.clone(), None, params) {
452                    Ok(call_id) => {
453                        self.pending_commands.insert(
454                            call_id,
455                            (PendingRequest::CreateTarget(tx), method, Instant::now()),
456                        );
457                    }
458                    Err(err) => {
459                        let _ = tx.send(Err(err.into())).ok();
460                    }
461                },
462                Err(err) => {
463                    let _ = tx.send(Err(err.into())).ok();
464                }
465            }
466        } else {
467            let _ = tx.send(Err(CdpError::NotFound)).ok();
468        }
469    }
470
471    /// Process an incoming event read from the websocket
472    fn on_event(&mut self, event: CdpEventMessage) {
473        if let Some(session_id) = &event.session_id {
474            if let Some(session) = self.sessions.get(session_id.as_str()) {
475                if let Some(target) = self.targets.get_mut(session.target_id()) {
476                    return target.on_event(event);
477                }
478            }
479        }
480        let CdpEventMessage { params, method, .. } = event;
481
482        match params {
483            CdpEvent::TargetTargetCreated(ref ev) => self.on_target_created((**ev).clone()),
484            CdpEvent::TargetAttachedToTarget(ref ev) => self.on_attached_to_target(ev.clone()),
485            CdpEvent::TargetTargetDestroyed(ref ev) => self.on_target_destroyed(ev.clone()),
486            CdpEvent::TargetTargetCrashed(ref ev) => self.on_target_crashed(ev.clone()),
487            CdpEvent::TargetDetachedFromTarget(ref ev) => self.on_detached_from_target(ev.clone()),
488            _ => {}
489        }
490
491        chromiumoxide_cdp::consume_event!(match params {
492            |ev| self.event_listeners.start_send(ev),
493            |json| { let _ = self.event_listeners.try_send_custom(&method, json);}
494        });
495    }
496
497    /// Fired when a new target was created on the chromium instance
498    ///
499    /// Creates a new `Target` instance and keeps track of it
500    fn on_target_created(&mut self, event: EventTargetCreated) {
501        if !self.browser_contexts.is_empty() {
502            if let Some(ref context_id) = event.target_info.browser_context_id {
503                let bc = BrowserContext {
504                    id: Some(context_id.clone()),
505                };
506                if !self.browser_contexts.contains(&bc) {
507                    return;
508                }
509            }
510        }
511        let browser_ctx = event
512            .target_info
513            .browser_context_id
514            .clone()
515            .map(BrowserContext::from)
516            .unwrap_or_else(|| self.default_browser_context.clone());
517        let target = Target::new(
518            event.target_info,
519            TargetConfig {
520                ignore_https_errors: self.config.ignore_https_errors,
521                request_timeout: self.config.request_timeout,
522                viewport: self.config.viewport.clone(),
523                request_intercept: self.config.request_intercept,
524                cache_enabled: self.config.cache_enabled,
525                service_worker_enabled: self.config.service_worker_enabled,
526                ignore_visuals: self.config.ignore_visuals,
527                ignore_stylesheets: self.config.ignore_stylesheets,
528                ignore_javascript: self.config.ignore_javascript,
529                ignore_analytics: self.config.ignore_analytics,
530                ignore_prefetch: self.config.ignore_prefetch,
531                extra_headers: self.config.extra_headers.clone(),
532                only_html: self.config.only_html && self.config.created_first_target,
533                intercept_manager: self.config.intercept_manager,
534                max_bytes_allowed: self.config.max_bytes_allowed,
535                max_redirects: self.config.max_redirects,
536                max_main_frame_navigations: self.config.max_main_frame_navigations,
537                whitelist_patterns: self.config.whitelist_patterns.clone(),
538                blacklist_patterns: self.config.blacklist_patterns.clone(),
539                #[cfg(feature = "adblock")]
540                adblock_filter_rules: self.config.adblock_filter_rules.clone(),
541                page_wake: self.page_wake.clone(),
542                page_channel_capacity: self.config.page_channel_capacity,
543            },
544            browser_ctx,
545        );
546
547        let tid = target.target_id().clone();
548        self.target_ids.push(tid.clone());
549        self.targets.insert(tid, target);
550    }
551
552    /// A new session is attached to a target
553    fn on_attached_to_target(&mut self, event: Box<EventAttachedToTarget>) {
554        let session = Session::new(event.session_id.clone(), event.target_info.target_id);
555        if let Some(target) = self.targets.get_mut(session.target_id()) {
556            target.set_session_id(session.session_id().clone())
557        }
558        self.sessions.insert(event.session_id, session);
559    }
560
561    /// The session was detached from target.
562    /// Can be issued multiple times per target if multiple session have been
563    /// attached to it.
564    fn on_detached_from_target(&mut self, event: EventDetachedFromTarget) {
565        // remove the session
566        if let Some(session) = self.sessions.remove(&event.session_id) {
567            if let Some(target) = self.targets.get_mut(session.target_id()) {
568                target.session_id_mut().take();
569            }
570        }
571    }
572
573    /// Fired when the target was destroyed in the browser
574    fn on_target_destroyed(&mut self, event: EventTargetDestroyed) {
575        self.attached_targets.remove(&event.target_id);
576
577        if let Some(target) = self.targets.remove(&event.target_id) {
578            // TODO shutdown?
579            if let Some(session) = target.session_id() {
580                self.sessions.remove(session);
581            }
582        }
583    }
584
585    /// Fired when a target has crashed (`Target.targetCrashed`).
586    ///
587    /// Unlike `targetDestroyed` (clean teardown), a crash means any
588    /// in-flight commands on that target will never receive a
589    /// response. Without explicit cancellation those commands sit in
590    /// `pending_commands` until the `request_timeout` evicts them,
591    /// which surfaces to callers as long latency tails on what is
592    /// really an immediate failure.
593    ///
594    /// Cancellation policy:
595    /// * `ExternalCommand { target_id: Some(crashed), .. }` — the
596    ///   caller's oneshot resolves with an error carrying the
597    ///   termination `status` + `errorCode` from the crash event.
598    /// * `InternalCommand(crashed)` — dropped silently; these are
599    ///   target-init commands whose caller is the target itself,
600    ///   which we're about to remove.
601    /// * `ExternalCommand { target_id: None, .. }` — left alone;
602    ///   browser-level or pre-attach-race commands aren't bound to
603    ///   this target.
604    /// * `Navigate(_)` and entries in `self.navigations` — left to
605    ///   the normal timeout path; `on_navigation_response` drops
606    ///   late responses once the target is removed below.
607    fn on_target_crashed(&mut self, event: EventTargetCrashed) {
608        let crashed_id = event.target_id.clone();
609        let status = event.status.clone();
610        let error_code = event.error_code;
611
612        // Two-pass cancellation: collect matching call-ids, then
613        // remove + signal. Can't signal inside `iter()` because
614        // `OneshotSender::send` consumes the sender, and the
615        // borrow checker disallows taking ownership from inside
616        // the iterator.
617        let to_cancel: Vec<CallId> = self
618            .pending_commands
619            .iter()
620            .filter_map(|(&call_id, (req, _, _))| match req {
621                PendingRequest::ExternalCommand {
622                    target_id: Some(tid),
623                    ..
624                } if *tid == crashed_id => Some(call_id),
625                PendingRequest::InternalCommand(tid) if *tid == crashed_id => Some(call_id),
626                _ => None,
627            })
628            .collect();
629
630        for call_id in to_cancel {
631            if let Some((req, _, _)) = self.pending_commands.remove(&call_id) {
632                match req {
633                    PendingRequest::ExternalCommand { tx, .. } => {
634                        let _ = tx.send(Err(CdpError::msg(format!(
635                            "target {:?} crashed: {} (errorCode={})",
636                            crashed_id, status, error_code
637                        ))));
638                    }
639                    PendingRequest::InternalCommand(_) => {
640                        // Target-init command — the target is gone,
641                        // nobody is waiting on a user-facing reply.
642                    }
643                    _ => {}
644                }
645            }
646        }
647
648        // Same map cleanup as `on_target_destroyed`.
649        self.attached_targets.remove(&crashed_id);
650        if let Some(target) = self.targets.remove(&crashed_id) {
651            if let Some(session) = target.session_id() {
652                self.sessions.remove(session);
653            }
654        }
655    }
656
657    /// House keeping of commands
658    ///
659    /// Remove all commands where `now` > `timestamp of command starting point +
660    /// request timeout` and notify the senders that their request timed out.
661    fn evict_timed_out_commands(&mut self, now: Instant) {
662        let deadline = match now.checked_sub(self.config.request_timeout) {
663            Some(d) => d,
664            None => return,
665        };
666
667        let timed_out: Vec<_> = self
668            .pending_commands
669            .iter()
670            .filter(|(_, (_, _, timestamp))| *timestamp < deadline)
671            .map(|(k, _)| *k)
672            .collect();
673
674        for call in timed_out {
675            if let Some((req, _, _)) = self.pending_commands.remove(&call) {
676                match req {
677                    PendingRequest::CreateTarget(tx) => {
678                        let _ = tx.send(Err(CdpError::Timeout));
679                    }
680                    PendingRequest::GetTargets(tx) => {
681                        let _ = tx.send(Err(CdpError::Timeout));
682                    }
683                    PendingRequest::Navigate(nav) => {
684                        if let Some(nav) = self.navigations.remove(&nav) {
685                            match nav {
686                                NavigationRequest::Navigate(nav) => {
687                                    let _ = nav.tx.send(Err(CdpError::Timeout));
688                                }
689                            }
690                        }
691                    }
692                    PendingRequest::ExternalCommand { tx, .. } => {
693                        let _ = tx.send(Err(CdpError::Timeout));
694                    }
695                    PendingRequest::InternalCommand(_) => {}
696                    PendingRequest::CloseBrowser(tx) => {
697                        let _ = tx.send(Err(CdpError::Timeout));
698                    }
699                }
700            }
701        }
702    }
703
704    pub fn event_listeners_mut(&mut self) -> &mut EventListeners {
705        &mut self.event_listeners
706    }
707
708    // ------------------------------------------------------------------
709    //  Tokio-native async entry point
710    // ------------------------------------------------------------------
711
712    /// Run the handler as a fully async tokio task.
713    ///
714    /// This is the high-performance alternative to polling `Handler` as a
715    /// `Stream`.  Internally it:
716    ///
717    /// * Splits the WebSocket into independent read/write halves — the
718    ///   writer runs in its own tokio task with natural batching.
719    /// * Uses `tokio::select!` to multiplex the browser channel, page
720    ///   notifications, WebSocket reads, the eviction timer, and writer
721    ///   health.
722    /// * Drains every target's page channel via `try_recv()` (non-blocking)
723    ///   after each event, with an `Arc<Notify>` ensuring the select loop
724    ///   wakes up whenever a page sends a message.
725    ///
726    /// # Usage
727    ///
728    /// ```rust,no_run
729    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
730    /// use chromiumoxide::Browser;
731    /// let (browser, handler) = Browser::launch(Default::default()).await?;
732    /// let handler_task = tokio::spawn(handler.run());
733    /// // … use browser …
734    /// # Ok(())
735    /// # }
736    /// ```
737    pub async fn run(mut self) -> Result<()> {
738        use chromiumoxide_types::Message;
739        use tokio::time::MissedTickBehavior;
740        use tokio_tungstenite::tungstenite::{self, error::ProtocolError};
741
742        // --- set up page notification ---
743        let page_wake = Arc::new(Notify::new());
744        self.page_wake = Some(page_wake.clone());
745
746        // --- split WebSocket ---
747        let conn = self
748            .conn
749            .take()
750            .ok_or_else(|| CdpError::msg("Handler::run() called with no connection"))?;
751        let async_conn = conn.into_async();
752        let mut ws_reader = async_conn.reader;
753        let ws_tx = async_conn.cmd_tx;
754        let mut writer_handle = async_conn.writer_handle;
755        let reader_handle = async_conn.reader_handle;
756        let mut next_call_id = async_conn.next_id;
757
758        // Helper to mint call-ids without &mut self.conn.
759        let mut alloc_call_id = || {
760            let id = chromiumoxide_types::CallId::new(next_call_id);
761            next_call_id = next_call_id.wrapping_add(1);
762            id
763        };
764
765        // --- eviction timer ---
766        let mut evict_timer = tokio::time::interval_at(
767            tokio::time::Instant::now() + self.config.request_timeout,
768            self.config.request_timeout,
769        );
770        evict_timer.set_missed_tick_behavior(MissedTickBehavior::Delay);
771
772        // Helper closure: submit a MethodCall through the WS writer.
773        macro_rules! ws_submit {
774            ($method:expr, $session_id:expr, $params:expr) => {{
775                let id = alloc_call_id();
776                let call = chromiumoxide_types::MethodCall {
777                    id,
778                    method: $method,
779                    session_id: $session_id,
780                    params: $params,
781                };
782                match ws_tx.try_send(call) {
783                    Ok(()) => Ok::<_, CdpError>(id),
784                    Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
785                        tracing::warn!("WS command channel full — dropping command");
786                        Err(CdpError::msg("WS command channel full"))
787                    }
788                    Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
789                        Err(CdpError::msg("WS writer closed"))
790                    }
791                }
792            }};
793        }
794
795        // ---- main event loop ----
796        //
797        // Modeled as an expression-loop producing `Result<()>` so that every
798        // exit path falls through to the graceful-shutdown block below
799        // (drop ws_tx → writer drains queue + sends WS Close → reader
800        // aborted). This matters for remote browsers (`Browser::connect`)
801        // where there is no child process whose death closes the socket.
802        let run_result: Result<()> = loop {
803            let now = std::time::Instant::now();
804
805            // 1. Drain all target page channels (non-blocking) & advance
806            //    state machines.
807            //
808            // Budget: drain at most 128 messages per target per iteration
809            // so a single chatty page cannot starve the rest.
810            const PER_TARGET_DRAIN_BUDGET: usize = 128;
811
812            for n in (0..self.target_ids.len()).rev() {
813                let target_id = self.target_ids.swap_remove(n);
814
815                if let Some((id, mut target)) = self.targets.remove_entry(&target_id) {
816                    // Drain page channel (non-blocking — waker is the Notify).
817                    {
818                        let mut msgs = Vec::new();
819                        if let Some(handle) = target.page_mut() {
820                            while msgs.len() < PER_TARGET_DRAIN_BUDGET {
821                                match handle.rx.try_recv() {
822                                    Ok(msg) => msgs.push(msg),
823                                    Err(_) => break,
824                                }
825                            }
826                        }
827                        for msg in msgs {
828                            target.on_page_message(msg);
829                        }
830                    }
831
832                    // Advance target state machine & process events.
833                    while let Some(event) = target.advance(now) {
834                        match event {
835                            TargetEvent::Request(req) => {
836                                if let Ok(call_id) =
837                                    ws_submit!(req.method.clone(), req.session_id, req.params)
838                                {
839                                    self.pending_commands.insert(
840                                        call_id,
841                                        (
842                                            PendingRequest::InternalCommand(
843                                                target.target_id().clone(),
844                                            ),
845                                            req.method,
846                                            now,
847                                        ),
848                                    );
849                                }
850                            }
851                            TargetEvent::Command(msg) => {
852                                if msg.is_navigation() {
853                                    let (req, tx) = msg.split();
854                                    let nav_id = self.next_navigation_id();
855                                    target.goto(FrameRequestedNavigation::new(
856                                        nav_id,
857                                        req.clone(),
858                                        self.config.request_timeout,
859                                    ));
860                                    if let Ok(call_id) =
861                                        ws_submit!(req.method.clone(), req.session_id, req.params)
862                                    {
863                                        self.pending_commands.insert(
864                                            call_id,
865                                            (PendingRequest::Navigate(nav_id), req.method, now),
866                                        );
867                                    }
868                                    self.navigations.insert(
869                                        nav_id,
870                                        NavigationRequest::Navigate(NavigationInProgress::new(tx)),
871                                    );
872                                } else if let Ok(call_id) = ws_submit!(
873                                    msg.method.clone(),
874                                    msg.session_id.map(Into::into),
875                                    msg.params
876                                ) {
877                                    // `target` is in scope here, so bind
878                                    // the pending command to its target_id
879                                    // directly.
880                                    let target_id = Some(target.target_id().clone());
881                                    self.pending_commands.insert(
882                                        call_id,
883                                        (
884                                            PendingRequest::ExternalCommand {
885                                                tx: msg.sender,
886                                                target_id,
887                                            },
888                                            msg.method,
889                                            now,
890                                        ),
891                                    );
892                                }
893                            }
894                            TargetEvent::NavigationRequest(nav_id, req) => {
895                                if let Ok(call_id) =
896                                    ws_submit!(req.method.clone(), req.session_id, req.params)
897                                {
898                                    self.pending_commands.insert(
899                                        call_id,
900                                        (PendingRequest::Navigate(nav_id), req.method, now),
901                                    );
902                                }
903                            }
904                            TargetEvent::NavigationResult(res) => {
905                                self.on_navigation_lifecycle_completed(res);
906                            }
907                            TargetEvent::BytesConsumed(n) => {
908                                if let Some(rem) = self.remaining_bytes.as_mut() {
909                                    *rem = rem.saturating_sub(n);
910                                    if *rem == 0 {
911                                        self.budget_exhausted = true;
912                                    }
913                                }
914                            }
915                        }
916                    }
917
918                    // Flush event listeners (no Context needed).
919                    target.event_listeners_mut().flush();
920
921                    self.targets.insert(id, target);
922                    self.target_ids.push(target_id);
923                }
924            }
925
926            // Flush handler-level event listeners.
927            self.event_listeners.flush();
928
929            if self.budget_exhausted {
930                for t in self.targets.values_mut() {
931                    t.network_manager.set_block_all(true);
932                }
933            }
934
935            if self.closing {
936                break Ok(());
937            }
938
939            // 2. Multiplex all event sources via tokio::select!
940            tokio::select! {
941                msg = self.from_browser.recv() => {
942                    match msg {
943                        Some(msg) => {
944                            match msg {
945                                HandlerMessage::Command(cmd) => {
946                                    // See `submit_external_command` for
947                                    // the session_id → target_id resolve.
948                                    let target_id = cmd
949                                        .session_id
950                                        .as_ref()
951                                        .and_then(|sid| self.sessions.get(sid.as_ref()))
952                                        .map(|s| s.target_id().clone());
953                                    if let Ok(call_id) = ws_submit!(
954                                        cmd.method.clone(),
955                                        cmd.session_id.map(Into::into),
956                                        cmd.params
957                                    ) {
958                                        self.pending_commands.insert(
959                                            call_id,
960                                            (
961                                                PendingRequest::ExternalCommand {
962                                                    tx: cmd.sender,
963                                                    target_id,
964                                                },
965                                                cmd.method,
966                                                now,
967                                            ),
968                                        );
969                                    }
970                                }
971                                HandlerMessage::FetchTargets(tx) => {
972                                    let msg = TARGET_PARAMS_ID.clone();
973                                    if let Ok(call_id) = ws_submit!(msg.0.clone(), None, msg.1) {
974                                        self.pending_commands.insert(
975                                            call_id,
976                                            (PendingRequest::GetTargets(tx), msg.0, now),
977                                        );
978                                    }
979                                }
980                                HandlerMessage::CloseBrowser(tx) => {
981                                    let close_msg = CLOSE_PARAMS_ID.clone();
982                                    if let Ok(call_id) = ws_submit!(close_msg.0.clone(), None, close_msg.1) {
983                                        self.pending_commands.insert(
984                                            call_id,
985                                            (PendingRequest::CloseBrowser(tx), close_msg.0, now),
986                                        );
987                                    }
988                                }
989                                HandlerMessage::CreatePage(params, tx) => {
990                                    if let Some(ref id) = params.browser_context_id {
991                                        self.browser_contexts.insert(BrowserContext::from(id.clone()));
992                                    }
993                                    self.create_page_async(params, tx, &mut alloc_call_id, &ws_tx, now);
994                                }
995                                HandlerMessage::GetPages(tx) => {
996                                    let pages: Vec<_> = self.targets.values_mut()
997                                        .filter(|p| p.is_page())
998                                        .filter_map(|target| target.get_or_create_page())
999                                        .map(|page| Page::from(page.clone()))
1000                                        .collect();
1001                                    let _ = tx.send(pages);
1002                                }
1003                                HandlerMessage::InsertContext(ctx) => {
1004                                    if self.default_browser_context.id().is_none() {
1005                                        self.default_browser_context = ctx.clone();
1006                                    }
1007                                    self.browser_contexts.insert(ctx);
1008                                }
1009                                HandlerMessage::DisposeContext(ctx) => {
1010                                    self.browser_contexts.remove(&ctx);
1011                                    self.attached_targets.retain(|tid| {
1012                                        self.targets.get(tid)
1013                                            .and_then(|t| t.browser_context_id())
1014                                            .map(|id| Some(id) != ctx.id())
1015                                            .unwrap_or(true)
1016                                    });
1017                                    self.closing = true;
1018                                }
1019                                HandlerMessage::GetPage(target_id, tx) => {
1020                                    let page = self.targets.get_mut(&target_id)
1021                                        .and_then(|target| target.get_or_create_page())
1022                                        .map(|page| Page::from(page.clone()));
1023                                    let _ = tx.send(page);
1024                                }
1025                                HandlerMessage::AddEventListener(req) => {
1026                                    self.event_listeners.add_listener(req);
1027                                }
1028                            }
1029                        }
1030                        None => break Ok(()), // browser handle dropped
1031                    }
1032                }
1033
1034                frame = ws_reader.next_message() => {
1035                    match frame {
1036                        Some(Ok(boxed_msg)) => match *boxed_msg {
1037                            Message::Response(resp) => {
1038                                self.on_response(resp);
1039                            }
1040                            Message::Event(ev) => {
1041                                self.on_event(ev);
1042                            }
1043                        },
1044                        Some(Err(err)) => {
1045                            tracing::error!("WS Connection error: {:?}", err);
1046                            if let CdpError::Ws(ref ws_error) = err {
1047                                match ws_error {
1048                                    tungstenite::Error::AlreadyClosed => break Ok(()),
1049                                    tungstenite::Error::Protocol(detail)
1050                                        if detail == &ProtocolError::ResetWithoutClosingHandshake =>
1051                                    {
1052                                        break Ok(());
1053                                    }
1054                                    _ => break Err(err),
1055                                }
1056                            } else {
1057                                break Err(err);
1058                            }
1059                        }
1060                        None => break Ok(()), // WS closed
1061                    }
1062                }
1063
1064                _ = page_wake.notified() => {
1065                    // A page sent a message — loop back to drain targets.
1066                }
1067
1068                _ = evict_timer.tick() => {
1069                    self.evict_timed_out_commands(now);
1070                    for t in self.targets.values_mut() {
1071                        t.network_manager.evict_stale_entries(now);
1072                        t.frame_manager_mut().evict_stale_context_ids();
1073                    }
1074                }
1075
1076                result = &mut writer_handle => {
1077                    // WS writer exited — propagate error or break.
1078                    match result {
1079                        Ok(Ok(())) => break Ok(()),
1080                        Ok(Err(e)) => break Err(e),
1081                        Err(e) => break Err(CdpError::msg(format!("WS writer panicked: {e}"))),
1082                    }
1083                }
1084            }
1085        };
1086
1087        // ---- graceful shutdown ----
1088        //
1089        // Drop the WS command sender so the writer task's `rx.recv()`
1090        // returns `None`. The writer drains any queued commands, sends a
1091        // WebSocket Close frame to Chrome, and exits. For remote browsers
1092        // this is the only mechanism that closes the WS — there's no child
1093        // process whose death would close the socket.
1094        drop(ws_tx);
1095
1096        // Wait briefly for the writer to send the Close frame. If it's
1097        // already done (e.g. exited via the writer-handle select arm),
1098        // skip the wait. Polling a finished `JoinHandle` again would
1099        // panic.
1100        if !writer_handle.is_finished() {
1101            let _ = tokio::time::timeout(std::time::Duration::from_millis(500), &mut writer_handle)
1102                .await;
1103            if !writer_handle.is_finished() {
1104                writer_handle.abort();
1105            }
1106        }
1107
1108        // Reader may be parked on `stream.next().await` waiting for
1109        // frames from Chrome. Its output channel receiver (`ws_reader`)
1110        // is dropped at function exit, so there is no consumer either
1111        // way — abort directly rather than waiting for the remote to
1112        // ack the Close frame.
1113        reader_handle.abort();
1114
1115        run_result
1116    }
1117
1118    /// `create_page` variant for the `run()` path that submits via `ws_tx`.
1119    fn create_page_async(
1120        &mut self,
1121        params: CreateTargetParams,
1122        tx: OneshotSender<Result<Page>>,
1123        alloc_call_id: &mut impl FnMut() -> chromiumoxide_types::CallId,
1124        ws_tx: &tokio::sync::mpsc::Sender<chromiumoxide_types::MethodCall>,
1125        now: std::time::Instant,
1126    ) {
1127        let about_blank = params.url == "about:blank";
1128        let http_check =
1129            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
1130
1131        if about_blank || http_check {
1132            let method = params.identifier();
1133            match serde_json::to_value(params) {
1134                Ok(params) => {
1135                    let id = alloc_call_id();
1136                    let call = chromiumoxide_types::MethodCall {
1137                        id,
1138                        method: method.clone(),
1139                        session_id: None,
1140                        params,
1141                    };
1142                    match ws_tx.try_send(call) {
1143                        Ok(()) => {
1144                            self.pending_commands
1145                                .insert(id, (PendingRequest::CreateTarget(tx), method, now));
1146                        }
1147                        Err(_) => {
1148                            let _ = tx
1149                                .send(Err(CdpError::msg("WS command channel full or closed")))
1150                                .ok();
1151                        }
1152                    }
1153                }
1154                Err(err) => {
1155                    let _ = tx.send(Err(err.into())).ok();
1156                }
1157            }
1158        } else {
1159            let _ = tx.send(Err(CdpError::NotFound)).ok();
1160        }
1161    }
1162
1163    /// Run the handler with one task per attached page (parallel handler).
1164    ///
1165    /// Opt-in via the `parallel-handler` Cargo feature. The single-task
1166    /// `Handler::run()` path is unchanged. See `src/handler/parallel/mod.rs`
1167    /// for the architectural notes and current scope limits.
1168    #[cfg(feature = "parallel-handler")]
1169    pub async fn run_parallel(mut self) -> Result<()> {
1170        // Reuse the existing setup that `run()` did inline: split the WS
1171        // connection, kick the boot `Target.setDiscoverTargets` command,
1172        // and hand everything to the Router.
1173        let conn = self
1174            .conn
1175            .take()
1176            .ok_or_else(|| CdpError::msg("Handler::run_parallel() called with no connection"))?;
1177        let async_conn = conn.into_async();
1178
1179        // The boot command has already been pushed by `Handler::new`; it
1180        // sits at call_id `next_id - 1`.
1181        let next_id = async_conn.next_id;
1182        let boot_call_id = chromiumoxide_types::CallId::new(next_id.saturating_sub(1));
1183        let boot_method = DISCOVER_ID.0.clone();
1184
1185        let router = parallel::Router::new(
1186            self.config,
1187            self.default_browser_context,
1188            self.from_browser,
1189            async_conn.reader,
1190            async_conn.cmd_tx,
1191            boot_call_id,
1192            boot_method,
1193            next_id,
1194        );
1195        let result = router.run().await;
1196
1197        // Make sure the writer drains and the reader task exits cleanly.
1198        async_conn.writer_handle.abort();
1199        async_conn.reader_handle.abort();
1200
1201        result
1202    }
1203}
1204
1205impl Stream for Handler {
1206    type Item = Result<()>;
1207
1208    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1209        // Budgets prevent a single chatty target or WS flood from
1210        // starving other futures on the runtime. Mirror the caps
1211        // used in `Handler::run()`; on exhaustion, self-wake and
1212        // return Pending so the executor gets a chance to schedule
1213        // other work before we resume.
1214        const BROWSER_MSG_BUDGET: usize = 128;
1215        const PER_TARGET_DRAIN_BUDGET: usize = 128;
1216        const WS_MSG_BUDGET: usize = 512;
1217
1218        let pin = self.get_mut();
1219
1220        let mut dispose = false;
1221        let mut budget_hit = false;
1222
1223        let now = Instant::now();
1224
1225        loop {
1226            // temporary pinning of the browser receiver should be safe as we are pinning
1227            // through the already pinned self. with the receivers we can also
1228            // safely ignore exhaustion as those are fused.
1229            let mut browser_msgs = 0usize;
1230            while let Poll::Ready(Some(msg)) = pin.from_browser.poll_recv(cx) {
1231                match msg {
1232                    HandlerMessage::Command(cmd) => {
1233                        pin.submit_external_command(cmd, now)?;
1234                    }
1235                    HandlerMessage::FetchTargets(tx) => {
1236                        pin.submit_fetch_targets(tx, now);
1237                    }
1238                    HandlerMessage::CloseBrowser(tx) => {
1239                        pin.submit_close(tx, now);
1240                    }
1241                    HandlerMessage::CreatePage(params, tx) => {
1242                        if let Some(ref id) = params.browser_context_id {
1243                            pin.browser_contexts
1244                                .insert(BrowserContext::from(id.clone()));
1245                        }
1246                        pin.create_page(params, tx);
1247                    }
1248                    HandlerMessage::GetPages(tx) => {
1249                        let pages: Vec<_> = pin
1250                            .targets
1251                            .values_mut()
1252                            .filter(|p: &&mut Target| p.is_page())
1253                            .filter_map(|target| target.get_or_create_page())
1254                            .map(|page| Page::from(page.clone()))
1255                            .collect();
1256                        let _ = tx.send(pages);
1257                    }
1258                    HandlerMessage::InsertContext(ctx) => {
1259                        if pin.default_browser_context.id().is_none() {
1260                            pin.default_browser_context = ctx.clone();
1261                        }
1262                        pin.browser_contexts.insert(ctx);
1263                    }
1264                    HandlerMessage::DisposeContext(ctx) => {
1265                        pin.browser_contexts.remove(&ctx);
1266                        pin.attached_targets.retain(|tid| {
1267                            pin.targets
1268                                .get(tid)
1269                                .and_then(|t| t.browser_context_id()) // however you expose it
1270                                .map(|id| Some(id) != ctx.id())
1271                                .unwrap_or(true)
1272                        });
1273                        pin.closing = true;
1274                        dispose = true;
1275                    }
1276                    HandlerMessage::GetPage(target_id, tx) => {
1277                        let page = pin
1278                            .targets
1279                            .get_mut(&target_id)
1280                            .and_then(|target| target.get_or_create_page())
1281                            .map(|page| Page::from(page.clone()));
1282                        let _ = tx.send(page);
1283                    }
1284                    HandlerMessage::AddEventListener(req) => {
1285                        pin.event_listeners.add_listener(req);
1286                    }
1287                }
1288                browser_msgs += 1;
1289                if browser_msgs >= BROWSER_MSG_BUDGET {
1290                    budget_hit = true;
1291                    break;
1292                }
1293            }
1294
1295            for n in (0..pin.target_ids.len()).rev() {
1296                let target_id = pin.target_ids.swap_remove(n);
1297
1298                if let Some((id, mut target)) = pin.targets.remove_entry(&target_id) {
1299                    let mut drained = 0usize;
1300                    while let Some(event) = target.poll(cx, now) {
1301                        match event {
1302                            TargetEvent::Request(req) => {
1303                                let _ = pin.submit_internal_command(
1304                                    target.target_id().clone(),
1305                                    req,
1306                                    now,
1307                                );
1308                            }
1309                            TargetEvent::Command(msg) => {
1310                                pin.on_target_message(&mut target, msg, now);
1311                            }
1312                            TargetEvent::NavigationRequest(id, req) => {
1313                                pin.submit_navigation(id, req, now);
1314                            }
1315                            TargetEvent::NavigationResult(res) => {
1316                                pin.on_navigation_lifecycle_completed(res)
1317                            }
1318                            TargetEvent::BytesConsumed(n) => {
1319                                if let Some(rem) = pin.remaining_bytes.as_mut() {
1320                                    *rem = rem.saturating_sub(n);
1321                                    if *rem == 0 {
1322                                        pin.budget_exhausted = true;
1323                                    }
1324                                }
1325                            }
1326                        }
1327                        drained += 1;
1328                        if drained >= PER_TARGET_DRAIN_BUDGET {
1329                            budget_hit = true;
1330                            break;
1331                        }
1332                    }
1333
1334                    // poll the target's event listeners
1335                    target.event_listeners_mut().poll(cx);
1336
1337                    pin.targets.insert(id, target);
1338                    pin.target_ids.push(target_id);
1339                }
1340            }
1341
1342            // poll the handler-level event listeners once per iteration,
1343            // not once per target.
1344            pin.event_listeners_mut().poll(cx);
1345
1346            let mut done = true;
1347
1348            // Read WS messages into a temporary buffer so the conn borrow
1349            // is released before we process them (which needs &mut pin).
1350            let mut ws_msgs = Vec::new();
1351            let mut ws_err = None;
1352            {
1353                let Some(conn) = pin.conn.as_mut() else {
1354                    return Poll::Ready(Some(Err(CdpError::msg(
1355                        "connection consumed by Handler::run()",
1356                    ))));
1357                };
1358                while let Poll::Ready(Some(ev)) = Pin::new(&mut *conn).poll_next(cx) {
1359                    match ev {
1360                        Ok(msg) => ws_msgs.push(msg),
1361                        Err(err) => {
1362                            ws_err = Some(err);
1363                            break;
1364                        }
1365                    }
1366                    if ws_msgs.len() >= WS_MSG_BUDGET {
1367                        budget_hit = true;
1368                        break;
1369                    }
1370                }
1371            }
1372
1373            for boxed_msg in ws_msgs {
1374                match *boxed_msg {
1375                    Message::Response(resp) => {
1376                        pin.on_response(resp);
1377                        if pin.closing {
1378                            return Poll::Ready(None);
1379                        }
1380                    }
1381                    Message::Event(ev) => {
1382                        pin.on_event(ev);
1383                    }
1384                }
1385                done = false;
1386            }
1387
1388            if let Some(err) = ws_err {
1389                tracing::error!("WS Connection error: {:?}", err);
1390                if let CdpError::Ws(ref ws_error) = err {
1391                    match ws_error {
1392                        Error::AlreadyClosed => {
1393                            pin.closing = true;
1394                            dispose = true;
1395                        }
1396                        Error::Protocol(detail)
1397                            if detail == &ProtocolError::ResetWithoutClosingHandshake =>
1398                        {
1399                            pin.closing = true;
1400                            dispose = true;
1401                        }
1402                        _ => return Poll::Ready(Some(Err(err))),
1403                    }
1404                } else {
1405                    return Poll::Ready(Some(Err(err)));
1406                }
1407            }
1408
1409            if pin.evict_command_timeout.poll_ready(cx) {
1410                // evict all commands that timed out
1411                pin.evict_timed_out_commands(now);
1412                // evict stale network race-condition buffers and
1413                // orphaned context_ids / frame entries
1414                for t in pin.targets.values_mut() {
1415                    t.network_manager.evict_stale_entries(now);
1416                    t.frame_manager_mut().evict_stale_context_ids();
1417                }
1418            }
1419
1420            if pin.budget_exhausted {
1421                for t in pin.targets.values_mut() {
1422                    t.network_manager.set_block_all(true);
1423                }
1424            }
1425
1426            if dispose {
1427                return Poll::Ready(None);
1428            }
1429
1430            if budget_hit {
1431                // yield to the scheduler; self-wake so the remaining
1432                // work resumes on the next tick without waiting for
1433                // a WS event.
1434                cx.waker().wake_by_ref();
1435                return Poll::Pending;
1436            }
1437
1438            if done {
1439                // no events/responses were read from the websocket
1440                return Poll::Pending;
1441            }
1442        }
1443    }
1444}
1445
1446/// How to configure the handler
1447#[derive(Debug, Clone)]
1448pub struct HandlerConfig {
1449    /// Whether the `NetworkManager`s should ignore https errors
1450    pub ignore_https_errors: bool,
1451    /// Window and device settings
1452    pub viewport: Option<Viewport>,
1453    /// Context ids to set from the get go
1454    pub context_ids: Vec<BrowserContextId>,
1455    /// default request timeout to use
1456    pub request_timeout: Duration,
1457    /// Whether to enable request interception
1458    pub request_intercept: bool,
1459    /// Whether to enable cache
1460    pub cache_enabled: bool,
1461    /// Whether to enable Service Workers
1462    pub service_worker_enabled: bool,
1463    /// Whether to ignore visuals.
1464    pub ignore_visuals: bool,
1465    /// Whether to ignore stylesheets.
1466    pub ignore_stylesheets: bool,
1467    /// Whether to ignore Javascript only allowing critical framework or lib based rendering.
1468    pub ignore_javascript: bool,
1469    /// Whether to ignore analytics.
1470    pub ignore_analytics: bool,
1471    /// Ignore prefetch request. Defaults to true.
1472    pub ignore_prefetch: bool,
1473    /// Whether to ignore ads.
1474    pub ignore_ads: bool,
1475    /// Extra headers.
1476    pub extra_headers: Option<std::collections::HashMap<String, String>>,
1477    /// Only Html.
1478    pub only_html: bool,
1479    /// Created the first target.
1480    pub created_first_target: bool,
1481    /// The network intercept manager.
1482    pub intercept_manager: NetworkInterceptManager,
1483    /// The max bytes to receive.
1484    pub max_bytes_allowed: Option<u64>,
1485    /// Cap on main-frame Document redirect hops (per navigation).
1486    ///
1487    /// `None` disables enforcement (default); `Some(n)` aborts once the chain length
1488    /// exceeds `n` by emitting `net::ERR_TOO_MANY_REDIRECTS` and calling
1489    /// `Page.stopLoading`. Preserves the accumulated `redirect_chain` on the failed
1490    /// request so consumers can inspect it.
1491    pub max_redirects: Option<usize>,
1492    /// Cap on main-frame cross-document navigations per `goto`. Defends against
1493    /// JS / meta-refresh loops that bypass the HTTP redirect guard. `None`
1494    /// disables the guard.
1495    pub max_main_frame_navigations: Option<u32>,
1496    /// Optional per-run/per-site whitelist of URL substrings (scripts/resources).
1497    pub whitelist_patterns: Option<Vec<String>>,
1498    /// Optional per-run/per-site blacklist of URL substrings (scripts/resources).
1499    pub blacklist_patterns: Option<Vec<String>>,
1500    /// Extra ABP/uBO filter rules for the adblock engine.
1501    #[cfg(feature = "adblock")]
1502    pub adblock_filter_rules: Option<Vec<String>>,
1503    /// Capacity of the channel between browser handle and handler.
1504    /// Defaults to 1000.
1505    pub channel_capacity: usize,
1506    /// Capacity of the per-page mpsc channel carrying `TargetMessage`s
1507    /// from each `Page` to the handler.
1508    ///
1509    /// Defaults to `DEFAULT_PAGE_CHANNEL_CAPACITY` (2048) — the previous
1510    /// hard-coded value. Tune upward for pages that burst many commands
1511    /// (heavy `evaluate`/selector use, high-concurrency tasks sharing
1512    /// one page) to avoid pushing each extra command onto the
1513    /// `CommandFuture` async-send fallback path on `TrySendError::Full`.
1514    /// Tune downward to apply back-pressure sooner. Values of `0` are
1515    /// clamped to `1` at channel creation.
1516    pub page_channel_capacity: usize,
1517    /// Number of WebSocket connection retry attempts with exponential backoff.
1518    /// Defaults to 4.
1519    pub connection_retries: u32,
1520}
1521
1522impl Default for HandlerConfig {
1523    fn default() -> Self {
1524        Self {
1525            ignore_https_errors: true,
1526            viewport: Default::default(),
1527            context_ids: Vec::new(),
1528            request_timeout: Duration::from_millis(REQUEST_TIMEOUT),
1529            request_intercept: false,
1530            cache_enabled: true,
1531            service_worker_enabled: true,
1532            ignore_visuals: false,
1533            ignore_stylesheets: false,
1534            ignore_ads: false,
1535            ignore_javascript: false,
1536            ignore_analytics: true,
1537            ignore_prefetch: true,
1538            only_html: false,
1539            extra_headers: Default::default(),
1540            created_first_target: false,
1541            intercept_manager: NetworkInterceptManager::Unknown,
1542            max_bytes_allowed: None,
1543            max_redirects: None,
1544            max_main_frame_navigations: None,
1545            whitelist_patterns: None,
1546            blacklist_patterns: None,
1547            #[cfg(feature = "adblock")]
1548            adblock_filter_rules: None,
1549            channel_capacity: 4096,
1550            page_channel_capacity: crate::handler::page::DEFAULT_PAGE_CHANNEL_CAPACITY,
1551            connection_retries: crate::conn::DEFAULT_CONNECTION_RETRIES,
1552        }
1553    }
1554}
1555
1556/// Wraps the sender half of the channel who requested a navigation
1557#[derive(Debug)]
1558pub struct NavigationInProgress<T> {
1559    /// Marker to indicate whether a navigation lifecycle has completed
1560    navigated: bool,
1561    /// The response of the issued navigation request
1562    response: Option<Response>,
1563    /// Sender who initiated the navigation request
1564    tx: OneshotSender<T>,
1565}
1566
1567impl<T> NavigationInProgress<T> {
1568    pub(crate) fn new(tx: OneshotSender<T>) -> Self {
1569        Self {
1570            navigated: false,
1571            response: None,
1572            tx,
1573        }
1574    }
1575
1576    /// The response to the cdp request has arrived
1577    pub(crate) fn set_response(&mut self, resp: Response) {
1578        self.response = Some(resp);
1579    }
1580
1581    /// The navigation process has finished, the page finished loading.
1582    pub(crate) fn set_navigated(&mut self) {
1583        self.navigated = true;
1584    }
1585
1586    /// Used by the parallel handler when reconciling Page.navigate response
1587    /// vs. lifecycle completion order — the existing serial handler reads
1588    /// the field directly so these accessors are otherwise inert.
1589    #[cfg_attr(not(feature = "parallel-handler"), allow(dead_code))]
1590    pub(crate) fn is_navigated(&self) -> bool {
1591        self.navigated
1592    }
1593
1594    #[cfg_attr(not(feature = "parallel-handler"), allow(dead_code))]
1595    pub(crate) fn take_response(&mut self) -> Option<Response> {
1596        self.response.take()
1597    }
1598
1599    #[cfg_attr(not(feature = "parallel-handler"), allow(dead_code))]
1600    pub(crate) fn into_tx(self) -> OneshotSender<T> {
1601        self.tx
1602    }
1603}
1604
1605/// Request type for navigation
1606#[derive(Debug)]
1607enum NavigationRequest {
1608    /// Represents a simple `NavigateParams` ("Page.navigate")
1609    Navigate(NavigationInProgress<Result<Response>>),
1610    // TODO are there more?
1611}
1612
1613/// Different kind of submitted request submitted from the  `Handler` to the
1614/// `Connection` and being waited on for the response.
1615#[derive(Debug)]
1616enum PendingRequest {
1617    /// A Request to create a new `Target` that results in the creation of a
1618    /// `Page` that represents a browser page.
1619    CreateTarget(OneshotSender<Result<Page>>),
1620    /// A Request to fetch old `Target`s created before connection
1621    GetTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1622    /// A Request to navigate a specific `Target`.
1623    ///
1624    /// Navigation requests are not automatically completed once the response to
1625    /// the raw cdp navigation request (like `NavigateParams`) arrives, but only
1626    /// after the `Target` notifies the `Handler` that the `Page` has finished
1627    /// loading, which comes after the response.
1628    Navigate(NavigationId),
1629    /// A common request received via a channel (`Page`).
1630    ///
1631    /// `target_id` is resolved at submit time from the caller's
1632    /// `session_id` against `self.sessions`, so `on_target_crashed`
1633    /// can cancel in-flight user commands immediately. `None` when
1634    /// the command has no session (browser-level) or was sent
1635    /// before the attach event arrived — those fall back to the
1636    /// normal `request_timeout` eviction.
1637    ExternalCommand {
1638        tx: OneshotSender<Result<Response>>,
1639        target_id: Option<TargetId>,
1640    },
1641    /// Requests that are initiated directly from a `Target` (all the
1642    /// initialization commands).
1643    InternalCommand(TargetId),
1644    // A Request to close the browser.
1645    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1646}
1647
1648/// Events used internally to communicate with the handler, which are executed
1649/// in the background
1650// TODO rename to BrowserMessage
1651#[derive(Debug)]
1652pub(crate) enum HandlerMessage {
1653    CreatePage(CreateTargetParams, OneshotSender<Result<Page>>),
1654    FetchTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1655    InsertContext(BrowserContext),
1656    DisposeContext(BrowserContext),
1657    GetPages(OneshotSender<Vec<Page>>),
1658    Command(CommandMessage),
1659    GetPage(TargetId, OneshotSender<Option<Page>>),
1660    AddEventListener(EventListenerRequest),
1661    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1662}
1663
1664#[cfg(test)]
1665mod tests {
1666    use super::*;
1667    use chromiumoxide_cdp::cdp::browser_protocol::target::{AttachToTargetReturns, TargetInfo};
1668
1669    #[test]
1670    fn attach_to_target_response_sets_session_id_before_event_arrives() {
1671        let info = TargetInfo::builder()
1672            .target_id("target-1".to_string())
1673            .r#type("page")
1674            .title("")
1675            .url("about:blank")
1676            .attached(false)
1677            .can_access_opener(false)
1678            .build()
1679            .expect("target info");
1680        let mut target = Target::new(info, TargetConfig::default(), BrowserContext::default());
1681        let method: MethodId = AttachToTargetParams::IDENTIFIER.into();
1682        let result = serde_json::to_value(AttachToTargetReturns::new("session-1".to_string()))
1683            .expect("attach result");
1684        let resp = Response {
1685            id: CallId::new(1),
1686            result: Some(result),
1687            error: None,
1688        };
1689
1690        maybe_store_attach_session_id(&mut target, &method, &resp);
1691
1692        assert_eq!(
1693            target.session_id().map(AsRef::as_ref),
1694            Some("session-1"),
1695            "attach response should seed the flat session id even before Target.attachedToTarget"
1696        );
1697    }
1698
1699    /// Regression guard: `page_channel_capacity` must default to 2048
1700    /// everywhere, so existing callers see identical behavior to the
1701    /// previous hard-coded value. If this test ever fails, every caller
1702    /// that relied on the implicit 2048-slot channel silently changed.
1703    #[test]
1704    fn page_channel_capacity_defaults_to_2048_across_configs() {
1705        use crate::browser::BrowserConfigBuilder;
1706        use crate::handler::page::DEFAULT_PAGE_CHANNEL_CAPACITY;
1707        use crate::handler::target::TargetConfig;
1708
1709        assert_eq!(DEFAULT_PAGE_CHANNEL_CAPACITY, 2048);
1710        assert_eq!(
1711            HandlerConfig::default().page_channel_capacity,
1712            DEFAULT_PAGE_CHANNEL_CAPACITY,
1713            "HandlerConfig default must match the historical 2048 slot count"
1714        );
1715        assert_eq!(
1716            TargetConfig::default().page_channel_capacity,
1717            DEFAULT_PAGE_CHANNEL_CAPACITY,
1718            "TargetConfig default must match the historical 2048 slot count"
1719        );
1720        // BrowserConfigBuilder default → build a builder (no executable
1721        // check needed: we only inspect the numeric field, not `build()`).
1722        let builder = BrowserConfigBuilder::default();
1723        let bc = format!("{:?}", builder);
1724        assert!(
1725            bc.contains("page_channel_capacity: 2048"),
1726            "BrowserConfigBuilder must default page_channel_capacity to 2048, got: {bc}",
1727        );
1728    }
1729}