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                allow_first_party_stylesheets: self.config.allow_first_party_stylesheets,
532                allow_first_party_javascript: self.config.allow_first_party_javascript,
533                allow_first_party_visuals: self.config.allow_first_party_visuals,
534                extra_headers: self.config.extra_headers.clone(),
535                only_html: self.config.only_html && self.config.created_first_target,
536                intercept_manager: self.config.intercept_manager,
537                max_bytes_allowed: self.config.max_bytes_allowed,
538                max_redirects: self.config.max_redirects,
539                max_main_frame_navigations: self.config.max_main_frame_navigations,
540                whitelist_patterns: self.config.whitelist_patterns.clone(),
541                blacklist_patterns: self.config.blacklist_patterns.clone(),
542                #[cfg(feature = "adblock")]
543                adblock_filter_rules: self.config.adblock_filter_rules.clone(),
544                page_wake: self.page_wake.clone(),
545                page_channel_capacity: self.config.page_channel_capacity,
546            },
547            browser_ctx,
548        );
549
550        let tid = target.target_id().clone();
551        self.target_ids.push(tid.clone());
552        self.targets.insert(tid, target);
553    }
554
555    /// A new session is attached to a target
556    fn on_attached_to_target(&mut self, event: Box<EventAttachedToTarget>) {
557        let session = Session::new(event.session_id.clone(), event.target_info.target_id);
558        if let Some(target) = self.targets.get_mut(session.target_id()) {
559            target.set_session_id(session.session_id().clone())
560        }
561        self.sessions.insert(event.session_id, session);
562    }
563
564    /// The session was detached from target.
565    /// Can be issued multiple times per target if multiple session have been
566    /// attached to it.
567    fn on_detached_from_target(&mut self, event: EventDetachedFromTarget) {
568        // remove the session
569        if let Some(session) = self.sessions.remove(&event.session_id) {
570            if let Some(target) = self.targets.get_mut(session.target_id()) {
571                target.session_id_mut().take();
572            }
573        }
574    }
575
576    /// Fired when the target was destroyed in the browser
577    fn on_target_destroyed(&mut self, event: EventTargetDestroyed) {
578        self.attached_targets.remove(&event.target_id);
579
580        if let Some(target) = self.targets.remove(&event.target_id) {
581            // TODO shutdown?
582            if let Some(session) = target.session_id() {
583                self.sessions.remove(session);
584            }
585        }
586    }
587
588    /// Fired when a target has crashed (`Target.targetCrashed`).
589    ///
590    /// Unlike `targetDestroyed` (clean teardown), a crash means any
591    /// in-flight commands on that target will never receive a
592    /// response. Without explicit cancellation those commands sit in
593    /// `pending_commands` until the `request_timeout` evicts them,
594    /// which surfaces to callers as long latency tails on what is
595    /// really an immediate failure.
596    ///
597    /// Cancellation policy:
598    /// * `ExternalCommand { target_id: Some(crashed), .. }` — the
599    ///   caller's oneshot resolves with an error carrying the
600    ///   termination `status` + `errorCode` from the crash event.
601    /// * `InternalCommand(crashed)` — dropped silently; these are
602    ///   target-init commands whose caller is the target itself,
603    ///   which we're about to remove.
604    /// * `ExternalCommand { target_id: None, .. }` — left alone;
605    ///   browser-level or pre-attach-race commands aren't bound to
606    ///   this target.
607    /// * `Navigate(_)` and entries in `self.navigations` — left to
608    ///   the normal timeout path; `on_navigation_response` drops
609    ///   late responses once the target is removed below.
610    fn on_target_crashed(&mut self, event: EventTargetCrashed) {
611        let crashed_id = event.target_id.clone();
612        let status = event.status.clone();
613        let error_code = event.error_code;
614
615        // Two-pass cancellation: collect matching call-ids, then
616        // remove + signal. Can't signal inside `iter()` because
617        // `OneshotSender::send` consumes the sender, and the
618        // borrow checker disallows taking ownership from inside
619        // the iterator.
620        let to_cancel: Vec<CallId> = self
621            .pending_commands
622            .iter()
623            .filter_map(|(&call_id, (req, _, _))| match req {
624                PendingRequest::ExternalCommand {
625                    target_id: Some(tid),
626                    ..
627                } if *tid == crashed_id => Some(call_id),
628                PendingRequest::InternalCommand(tid) if *tid == crashed_id => Some(call_id),
629                _ => None,
630            })
631            .collect();
632
633        for call_id in to_cancel {
634            if let Some((req, _, _)) = self.pending_commands.remove(&call_id) {
635                match req {
636                    PendingRequest::ExternalCommand { tx, .. } => {
637                        let _ = tx.send(Err(CdpError::msg(format!(
638                            "target {:?} crashed: {} (errorCode={})",
639                            crashed_id, status, error_code
640                        ))));
641                    }
642                    PendingRequest::InternalCommand(_) => {
643                        // Target-init command — the target is gone,
644                        // nobody is waiting on a user-facing reply.
645                    }
646                    _ => {}
647                }
648            }
649        }
650
651        // Same map cleanup as `on_target_destroyed`.
652        self.attached_targets.remove(&crashed_id);
653        if let Some(target) = self.targets.remove(&crashed_id) {
654            if let Some(session) = target.session_id() {
655                self.sessions.remove(session);
656            }
657        }
658    }
659
660    /// House keeping of commands
661    ///
662    /// Remove all commands where `now` > `timestamp of command starting point +
663    /// request timeout` and notify the senders that their request timed out.
664    fn evict_timed_out_commands(&mut self, now: Instant) {
665        let deadline = match now.checked_sub(self.config.request_timeout) {
666            Some(d) => d,
667            None => return,
668        };
669
670        let timed_out: Vec<_> = self
671            .pending_commands
672            .iter()
673            .filter(|(_, (_, _, timestamp))| *timestamp < deadline)
674            .map(|(k, _)| *k)
675            .collect();
676
677        for call in timed_out {
678            if let Some((req, _, _)) = self.pending_commands.remove(&call) {
679                match req {
680                    PendingRequest::CreateTarget(tx) => {
681                        let _ = tx.send(Err(CdpError::Timeout));
682                    }
683                    PendingRequest::GetTargets(tx) => {
684                        let _ = tx.send(Err(CdpError::Timeout));
685                    }
686                    PendingRequest::Navigate(nav) => {
687                        if let Some(nav) = self.navigations.remove(&nav) {
688                            match nav {
689                                NavigationRequest::Navigate(nav) => {
690                                    let _ = nav.tx.send(Err(CdpError::Timeout));
691                                }
692                            }
693                        }
694                    }
695                    PendingRequest::ExternalCommand { tx, .. } => {
696                        let _ = tx.send(Err(CdpError::Timeout));
697                    }
698                    PendingRequest::InternalCommand(_) => {}
699                    PendingRequest::CloseBrowser(tx) => {
700                        let _ = tx.send(Err(CdpError::Timeout));
701                    }
702                }
703            }
704        }
705    }
706
707    pub fn event_listeners_mut(&mut self) -> &mut EventListeners {
708        &mut self.event_listeners
709    }
710
711    // ------------------------------------------------------------------
712    //  Tokio-native async entry point
713    // ------------------------------------------------------------------
714
715    /// Run the handler as a fully async tokio task.
716    ///
717    /// This is the high-performance alternative to polling `Handler` as a
718    /// `Stream`.  Internally it:
719    ///
720    /// * Splits the WebSocket into independent read/write halves — the
721    ///   writer runs in its own tokio task with natural batching.
722    /// * Uses `tokio::select!` to multiplex the browser channel, page
723    ///   notifications, WebSocket reads, the eviction timer, and writer
724    ///   health.
725    /// * Drains every target's page channel via `try_recv()` (non-blocking)
726    ///   after each event, with an `Arc<Notify>` ensuring the select loop
727    ///   wakes up whenever a page sends a message.
728    ///
729    /// # Usage
730    ///
731    /// ```rust,no_run
732    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
733    /// use chromiumoxide::Browser;
734    /// let (browser, handler) = Browser::launch(Default::default()).await?;
735    /// let handler_task = tokio::spawn(handler.run());
736    /// // … use browser …
737    /// # Ok(())
738    /// # }
739    /// ```
740    pub async fn run(mut self) -> Result<()> {
741        use chromiumoxide_types::Message;
742        use tokio::time::MissedTickBehavior;
743        use tokio_tungstenite::tungstenite::{self, error::ProtocolError};
744
745        // --- set up page notification ---
746        let page_wake = Arc::new(Notify::new());
747        self.page_wake = Some(page_wake.clone());
748
749        // --- split WebSocket ---
750        let conn = self
751            .conn
752            .take()
753            .ok_or_else(|| CdpError::msg("Handler::run() called with no connection"))?;
754        let async_conn = conn.into_async();
755        let mut ws_reader = async_conn.reader;
756        let ws_tx = async_conn.cmd_tx;
757        let mut writer_handle = async_conn.writer_handle;
758        let reader_handle = async_conn.reader_handle;
759        let mut next_call_id = async_conn.next_id;
760
761        // Helper to mint call-ids without &mut self.conn.
762        let mut alloc_call_id = || {
763            let id = chromiumoxide_types::CallId::new(next_call_id);
764            next_call_id = next_call_id.wrapping_add(1);
765            id
766        };
767
768        // --- eviction timer ---
769        let mut evict_timer = tokio::time::interval_at(
770            tokio::time::Instant::now() + self.config.request_timeout,
771            self.config.request_timeout,
772        );
773        evict_timer.set_missed_tick_behavior(MissedTickBehavior::Delay);
774
775        // Helper closure: submit a MethodCall through the WS writer.
776        macro_rules! ws_submit {
777            ($method:expr, $session_id:expr, $params:expr) => {{
778                let id = alloc_call_id();
779                let call = chromiumoxide_types::MethodCall {
780                    id,
781                    method: $method,
782                    session_id: $session_id,
783                    params: $params,
784                };
785                match ws_tx.try_send(call) {
786                    Ok(()) => Ok::<_, CdpError>(id),
787                    Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
788                        tracing::warn!("WS command channel full — dropping command");
789                        Err(CdpError::msg("WS command channel full"))
790                    }
791                    Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
792                        Err(CdpError::msg("WS writer closed"))
793                    }
794                }
795            }};
796        }
797
798        // ---- main event loop ----
799        //
800        // Modeled as an expression-loop producing `Result<()>` so that every
801        // exit path falls through to the graceful-shutdown block below
802        // (drop ws_tx → writer drains queue + sends WS Close → reader
803        // aborted). This matters for remote browsers (`Browser::connect`)
804        // where there is no child process whose death closes the socket.
805        let run_result: Result<()> = loop {
806            let now = std::time::Instant::now();
807
808            // 1. Drain all target page channels (non-blocking) & advance
809            //    state machines.
810            //
811            // Budget: drain at most 128 messages per target per iteration
812            // so a single chatty page cannot starve the rest.
813            const PER_TARGET_DRAIN_BUDGET: usize = 128;
814
815            for n in (0..self.target_ids.len()).rev() {
816                let target_id = self.target_ids.swap_remove(n);
817
818                if let Some((id, mut target)) = self.targets.remove_entry(&target_id) {
819                    // Drain page channel (non-blocking — waker is the Notify).
820                    {
821                        let mut msgs = Vec::new();
822                        if let Some(handle) = target.page_mut() {
823                            while msgs.len() < PER_TARGET_DRAIN_BUDGET {
824                                match handle.rx.try_recv() {
825                                    Ok(msg) => msgs.push(msg),
826                                    Err(_) => break,
827                                }
828                            }
829                        }
830                        for msg in msgs {
831                            target.on_page_message(msg);
832                        }
833                    }
834
835                    // Advance target state machine & process events.
836                    while let Some(event) = target.advance(now) {
837                        match event {
838                            TargetEvent::Request(req) => {
839                                if let Ok(call_id) =
840                                    ws_submit!(req.method.clone(), req.session_id, req.params)
841                                {
842                                    self.pending_commands.insert(
843                                        call_id,
844                                        (
845                                            PendingRequest::InternalCommand(
846                                                target.target_id().clone(),
847                                            ),
848                                            req.method,
849                                            now,
850                                        ),
851                                    );
852                                }
853                            }
854                            TargetEvent::Command(msg) => {
855                                if msg.is_navigation() {
856                                    let (req, tx) = msg.split();
857                                    let nav_id = self.next_navigation_id();
858                                    target.goto(FrameRequestedNavigation::new(
859                                        nav_id,
860                                        req.clone(),
861                                        self.config.request_timeout,
862                                    ));
863                                    if let Ok(call_id) =
864                                        ws_submit!(req.method.clone(), req.session_id, req.params)
865                                    {
866                                        self.pending_commands.insert(
867                                            call_id,
868                                            (PendingRequest::Navigate(nav_id), req.method, now),
869                                        );
870                                    }
871                                    self.navigations.insert(
872                                        nav_id,
873                                        NavigationRequest::Navigate(NavigationInProgress::new(tx)),
874                                    );
875                                } else if let Ok(call_id) = ws_submit!(
876                                    msg.method.clone(),
877                                    msg.session_id.map(Into::into),
878                                    msg.params
879                                ) {
880                                    // `target` is in scope here, so bind
881                                    // the pending command to its target_id
882                                    // directly.
883                                    let target_id = Some(target.target_id().clone());
884                                    self.pending_commands.insert(
885                                        call_id,
886                                        (
887                                            PendingRequest::ExternalCommand {
888                                                tx: msg.sender,
889                                                target_id,
890                                            },
891                                            msg.method,
892                                            now,
893                                        ),
894                                    );
895                                }
896                            }
897                            TargetEvent::NavigationRequest(nav_id, req) => {
898                                if let Ok(call_id) =
899                                    ws_submit!(req.method.clone(), req.session_id, req.params)
900                                {
901                                    self.pending_commands.insert(
902                                        call_id,
903                                        (PendingRequest::Navigate(nav_id), req.method, now),
904                                    );
905                                }
906                            }
907                            TargetEvent::NavigationResult(res) => {
908                                self.on_navigation_lifecycle_completed(res);
909                            }
910                            TargetEvent::BytesConsumed(n) => {
911                                if let Some(rem) = self.remaining_bytes.as_mut() {
912                                    *rem = rem.saturating_sub(n);
913                                    if *rem == 0 {
914                                        self.budget_exhausted = true;
915                                    }
916                                }
917                            }
918                        }
919                    }
920
921                    // Flush event listeners (no Context needed).
922                    target.event_listeners_mut().flush();
923
924                    self.targets.insert(id, target);
925                    self.target_ids.push(target_id);
926                }
927            }
928
929            // Flush handler-level event listeners.
930            self.event_listeners.flush();
931
932            if self.budget_exhausted {
933                for t in self.targets.values_mut() {
934                    t.network_manager.set_block_all(true);
935                }
936            }
937
938            if self.closing {
939                break Ok(());
940            }
941
942            // 2. Multiplex all event sources via tokio::select!
943            tokio::select! {
944                msg = self.from_browser.recv() => {
945                    match msg {
946                        Some(msg) => {
947                            match msg {
948                                HandlerMessage::Command(cmd) => {
949                                    // See `submit_external_command` for
950                                    // the session_id → target_id resolve.
951                                    let target_id = cmd
952                                        .session_id
953                                        .as_ref()
954                                        .and_then(|sid| self.sessions.get(sid.as_ref()))
955                                        .map(|s| s.target_id().clone());
956                                    if let Ok(call_id) = ws_submit!(
957                                        cmd.method.clone(),
958                                        cmd.session_id.map(Into::into),
959                                        cmd.params
960                                    ) {
961                                        self.pending_commands.insert(
962                                            call_id,
963                                            (
964                                                PendingRequest::ExternalCommand {
965                                                    tx: cmd.sender,
966                                                    target_id,
967                                                },
968                                                cmd.method,
969                                                now,
970                                            ),
971                                        );
972                                    }
973                                }
974                                HandlerMessage::FetchTargets(tx) => {
975                                    let msg = TARGET_PARAMS_ID.clone();
976                                    if let Ok(call_id) = ws_submit!(msg.0.clone(), None, msg.1) {
977                                        self.pending_commands.insert(
978                                            call_id,
979                                            (PendingRequest::GetTargets(tx), msg.0, now),
980                                        );
981                                    }
982                                }
983                                HandlerMessage::CloseBrowser(tx) => {
984                                    let close_msg = CLOSE_PARAMS_ID.clone();
985                                    if let Ok(call_id) = ws_submit!(close_msg.0.clone(), None, close_msg.1) {
986                                        self.pending_commands.insert(
987                                            call_id,
988                                            (PendingRequest::CloseBrowser(tx), close_msg.0, now),
989                                        );
990                                    }
991                                }
992                                HandlerMessage::CreatePage(params, tx) => {
993                                    if let Some(ref id) = params.browser_context_id {
994                                        self.browser_contexts.insert(BrowserContext::from(id.clone()));
995                                    }
996                                    self.create_page_async(params, tx, &mut alloc_call_id, &ws_tx, now);
997                                }
998                                HandlerMessage::GetPages(tx) => {
999                                    let pages: Vec<_> = self.targets.values_mut()
1000                                        .filter(|p| p.is_page())
1001                                        .filter_map(|target| target.get_or_create_page())
1002                                        .map(|page| Page::from(page.clone()))
1003                                        .collect();
1004                                    let _ = tx.send(pages);
1005                                }
1006                                HandlerMessage::InsertContext(ctx) => {
1007                                    if self.default_browser_context.id().is_none() {
1008                                        self.default_browser_context = ctx.clone();
1009                                    }
1010                                    self.browser_contexts.insert(ctx);
1011                                }
1012                                HandlerMessage::DisposeContext(ctx) => {
1013                                    self.browser_contexts.remove(&ctx);
1014                                    self.attached_targets.retain(|tid| {
1015                                        self.targets.get(tid)
1016                                            .and_then(|t| t.browser_context_id())
1017                                            .map(|id| Some(id) != ctx.id())
1018                                            .unwrap_or(true)
1019                                    });
1020                                    self.closing = true;
1021                                }
1022                                HandlerMessage::GetPage(target_id, tx) => {
1023                                    let page = self.targets.get_mut(&target_id)
1024                                        .and_then(|target| target.get_or_create_page())
1025                                        .map(|page| Page::from(page.clone()));
1026                                    let _ = tx.send(page);
1027                                }
1028                                HandlerMessage::AddEventListener(req) => {
1029                                    self.event_listeners.add_listener(req);
1030                                }
1031                            }
1032                        }
1033                        None => break Ok(()), // browser handle dropped
1034                    }
1035                }
1036
1037                frame = ws_reader.next_message() => {
1038                    match frame {
1039                        Some(Ok(boxed_msg)) => match *boxed_msg {
1040                            Message::Response(resp) => {
1041                                self.on_response(resp);
1042                            }
1043                            Message::Event(ev) => {
1044                                self.on_event(ev);
1045                            }
1046                        },
1047                        Some(Err(err)) => {
1048                            tracing::error!("WS Connection error: {:?}", err);
1049                            if let CdpError::Ws(ref ws_error) = err {
1050                                match ws_error {
1051                                    tungstenite::Error::AlreadyClosed => break Ok(()),
1052                                    tungstenite::Error::Protocol(detail)
1053                                        if detail == &ProtocolError::ResetWithoutClosingHandshake =>
1054                                    {
1055                                        break Ok(());
1056                                    }
1057                                    _ => break Err(err),
1058                                }
1059                            } else {
1060                                break Err(err);
1061                            }
1062                        }
1063                        None => break Ok(()), // WS closed
1064                    }
1065                }
1066
1067                _ = page_wake.notified() => {
1068                    // A page sent a message — loop back to drain targets.
1069                }
1070
1071                _ = evict_timer.tick() => {
1072                    self.evict_timed_out_commands(now);
1073                    for t in self.targets.values_mut() {
1074                        t.network_manager.evict_stale_entries(now);
1075                        t.frame_manager_mut().evict_stale_context_ids();
1076                    }
1077                }
1078
1079                result = &mut writer_handle => {
1080                    // WS writer exited — propagate error or break.
1081                    match result {
1082                        Ok(Ok(())) => break Ok(()),
1083                        Ok(Err(e)) => break Err(e),
1084                        Err(e) => break Err(CdpError::msg(format!("WS writer panicked: {e}"))),
1085                    }
1086                }
1087            }
1088        };
1089
1090        // ---- graceful shutdown ----
1091        //
1092        // Drop the WS command sender so the writer task's `rx.recv()`
1093        // returns `None`. The writer drains any queued commands, sends a
1094        // WebSocket Close frame to Chrome, and exits. For remote browsers
1095        // this is the only mechanism that closes the WS — there's no child
1096        // process whose death would close the socket.
1097        drop(ws_tx);
1098
1099        // Wait briefly for the writer to send the Close frame. If it's
1100        // already done (e.g. exited via the writer-handle select arm),
1101        // skip the wait. Polling a finished `JoinHandle` again would
1102        // panic.
1103        if !writer_handle.is_finished() {
1104            let _ = tokio::time::timeout(std::time::Duration::from_millis(500), &mut writer_handle)
1105                .await;
1106            if !writer_handle.is_finished() {
1107                writer_handle.abort();
1108            }
1109        }
1110
1111        // Reader may be parked on `stream.next().await` waiting for
1112        // frames from Chrome. Its output channel receiver (`ws_reader`)
1113        // is dropped at function exit, so there is no consumer either
1114        // way — abort directly rather than waiting for the remote to
1115        // ack the Close frame.
1116        reader_handle.abort();
1117
1118        run_result
1119    }
1120
1121    /// `create_page` variant for the `run()` path that submits via `ws_tx`.
1122    fn create_page_async(
1123        &mut self,
1124        params: CreateTargetParams,
1125        tx: OneshotSender<Result<Page>>,
1126        alloc_call_id: &mut impl FnMut() -> chromiumoxide_types::CallId,
1127        ws_tx: &tokio::sync::mpsc::Sender<chromiumoxide_types::MethodCall>,
1128        now: std::time::Instant,
1129    ) {
1130        let about_blank = params.url == "about:blank";
1131        let http_check =
1132            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
1133
1134        if about_blank || http_check {
1135            let method = params.identifier();
1136            match serde_json::to_value(params) {
1137                Ok(params) => {
1138                    let id = alloc_call_id();
1139                    let call = chromiumoxide_types::MethodCall {
1140                        id,
1141                        method: method.clone(),
1142                        session_id: None,
1143                        params,
1144                    };
1145                    match ws_tx.try_send(call) {
1146                        Ok(()) => {
1147                            self.pending_commands
1148                                .insert(id, (PendingRequest::CreateTarget(tx), method, now));
1149                        }
1150                        Err(_) => {
1151                            let _ = tx
1152                                .send(Err(CdpError::msg("WS command channel full or closed")))
1153                                .ok();
1154                        }
1155                    }
1156                }
1157                Err(err) => {
1158                    let _ = tx.send(Err(err.into())).ok();
1159                }
1160            }
1161        } else {
1162            let _ = tx.send(Err(CdpError::NotFound)).ok();
1163        }
1164    }
1165
1166    /// Run the handler with one task per attached page (parallel handler).
1167    ///
1168    /// Opt-in via the `parallel-handler` Cargo feature. The single-task
1169    /// `Handler::run()` path is unchanged. See `src/handler/parallel/mod.rs`
1170    /// for the architectural notes and current scope limits.
1171    #[cfg(feature = "parallel-handler")]
1172    pub async fn run_parallel(mut self) -> Result<()> {
1173        // Reuse the existing setup that `run()` did inline: split the WS
1174        // connection, kick the boot `Target.setDiscoverTargets` command,
1175        // and hand everything to the Router.
1176        let conn = self
1177            .conn
1178            .take()
1179            .ok_or_else(|| CdpError::msg("Handler::run_parallel() called with no connection"))?;
1180        let async_conn = conn.into_async();
1181
1182        // The boot command has already been pushed by `Handler::new`; it
1183        // sits at call_id `next_id - 1`.
1184        let next_id = async_conn.next_id;
1185        let boot_call_id = chromiumoxide_types::CallId::new(next_id.saturating_sub(1));
1186        let boot_method = DISCOVER_ID.0.clone();
1187
1188        let router = parallel::Router::new(
1189            self.config,
1190            self.default_browser_context,
1191            self.from_browser,
1192            async_conn.reader,
1193            async_conn.cmd_tx,
1194            boot_call_id,
1195            boot_method,
1196            next_id,
1197        );
1198        let result = router.run().await;
1199
1200        // Make sure the writer drains and the reader task exits cleanly.
1201        async_conn.writer_handle.abort();
1202        async_conn.reader_handle.abort();
1203
1204        result
1205    }
1206}
1207
1208impl Stream for Handler {
1209    type Item = Result<()>;
1210
1211    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1212        // Budgets prevent a single chatty target or WS flood from
1213        // starving other futures on the runtime. Mirror the caps
1214        // used in `Handler::run()`; on exhaustion, self-wake and
1215        // return Pending so the executor gets a chance to schedule
1216        // other work before we resume.
1217        const BROWSER_MSG_BUDGET: usize = 128;
1218        const PER_TARGET_DRAIN_BUDGET: usize = 128;
1219        const WS_MSG_BUDGET: usize = 512;
1220
1221        let pin = self.get_mut();
1222
1223        let mut dispose = false;
1224        let mut budget_hit = false;
1225
1226        let now = Instant::now();
1227
1228        loop {
1229            // temporary pinning of the browser receiver should be safe as we are pinning
1230            // through the already pinned self. with the receivers we can also
1231            // safely ignore exhaustion as those are fused.
1232            let mut browser_msgs = 0usize;
1233            while let Poll::Ready(Some(msg)) = pin.from_browser.poll_recv(cx) {
1234                match msg {
1235                    HandlerMessage::Command(cmd) => {
1236                        pin.submit_external_command(cmd, now)?;
1237                    }
1238                    HandlerMessage::FetchTargets(tx) => {
1239                        pin.submit_fetch_targets(tx, now);
1240                    }
1241                    HandlerMessage::CloseBrowser(tx) => {
1242                        pin.submit_close(tx, now);
1243                    }
1244                    HandlerMessage::CreatePage(params, tx) => {
1245                        if let Some(ref id) = params.browser_context_id {
1246                            pin.browser_contexts
1247                                .insert(BrowserContext::from(id.clone()));
1248                        }
1249                        pin.create_page(params, tx);
1250                    }
1251                    HandlerMessage::GetPages(tx) => {
1252                        let pages: Vec<_> = pin
1253                            .targets
1254                            .values_mut()
1255                            .filter(|p: &&mut Target| p.is_page())
1256                            .filter_map(|target| target.get_or_create_page())
1257                            .map(|page| Page::from(page.clone()))
1258                            .collect();
1259                        let _ = tx.send(pages);
1260                    }
1261                    HandlerMessage::InsertContext(ctx) => {
1262                        if pin.default_browser_context.id().is_none() {
1263                            pin.default_browser_context = ctx.clone();
1264                        }
1265                        pin.browser_contexts.insert(ctx);
1266                    }
1267                    HandlerMessage::DisposeContext(ctx) => {
1268                        pin.browser_contexts.remove(&ctx);
1269                        pin.attached_targets.retain(|tid| {
1270                            pin.targets
1271                                .get(tid)
1272                                .and_then(|t| t.browser_context_id()) // however you expose it
1273                                .map(|id| Some(id) != ctx.id())
1274                                .unwrap_or(true)
1275                        });
1276                        pin.closing = true;
1277                        dispose = true;
1278                    }
1279                    HandlerMessage::GetPage(target_id, tx) => {
1280                        let page = pin
1281                            .targets
1282                            .get_mut(&target_id)
1283                            .and_then(|target| target.get_or_create_page())
1284                            .map(|page| Page::from(page.clone()));
1285                        let _ = tx.send(page);
1286                    }
1287                    HandlerMessage::AddEventListener(req) => {
1288                        pin.event_listeners.add_listener(req);
1289                    }
1290                }
1291                browser_msgs += 1;
1292                if browser_msgs >= BROWSER_MSG_BUDGET {
1293                    budget_hit = true;
1294                    break;
1295                }
1296            }
1297
1298            for n in (0..pin.target_ids.len()).rev() {
1299                let target_id = pin.target_ids.swap_remove(n);
1300
1301                if let Some((id, mut target)) = pin.targets.remove_entry(&target_id) {
1302                    let mut drained = 0usize;
1303                    while let Some(event) = target.poll(cx, now) {
1304                        match event {
1305                            TargetEvent::Request(req) => {
1306                                let _ = pin.submit_internal_command(
1307                                    target.target_id().clone(),
1308                                    req,
1309                                    now,
1310                                );
1311                            }
1312                            TargetEvent::Command(msg) => {
1313                                pin.on_target_message(&mut target, msg, now);
1314                            }
1315                            TargetEvent::NavigationRequest(id, req) => {
1316                                pin.submit_navigation(id, req, now);
1317                            }
1318                            TargetEvent::NavigationResult(res) => {
1319                                pin.on_navigation_lifecycle_completed(res)
1320                            }
1321                            TargetEvent::BytesConsumed(n) => {
1322                                if let Some(rem) = pin.remaining_bytes.as_mut() {
1323                                    *rem = rem.saturating_sub(n);
1324                                    if *rem == 0 {
1325                                        pin.budget_exhausted = true;
1326                                    }
1327                                }
1328                            }
1329                        }
1330                        drained += 1;
1331                        if drained >= PER_TARGET_DRAIN_BUDGET {
1332                            budget_hit = true;
1333                            break;
1334                        }
1335                    }
1336
1337                    // poll the target's event listeners
1338                    target.event_listeners_mut().poll(cx);
1339
1340                    pin.targets.insert(id, target);
1341                    pin.target_ids.push(target_id);
1342                }
1343            }
1344
1345            // poll the handler-level event listeners once per iteration,
1346            // not once per target.
1347            pin.event_listeners_mut().poll(cx);
1348
1349            let mut done = true;
1350
1351            // Read WS messages into a temporary buffer so the conn borrow
1352            // is released before we process them (which needs &mut pin).
1353            let mut ws_msgs = Vec::new();
1354            let mut ws_err = None;
1355            {
1356                let Some(conn) = pin.conn.as_mut() else {
1357                    return Poll::Ready(Some(Err(CdpError::msg(
1358                        "connection consumed by Handler::run()",
1359                    ))));
1360                };
1361                while let Poll::Ready(Some(ev)) = Pin::new(&mut *conn).poll_next(cx) {
1362                    match ev {
1363                        Ok(msg) => ws_msgs.push(msg),
1364                        Err(err) => {
1365                            ws_err = Some(err);
1366                            break;
1367                        }
1368                    }
1369                    if ws_msgs.len() >= WS_MSG_BUDGET {
1370                        budget_hit = true;
1371                        break;
1372                    }
1373                }
1374            }
1375
1376            for boxed_msg in ws_msgs {
1377                match *boxed_msg {
1378                    Message::Response(resp) => {
1379                        pin.on_response(resp);
1380                        if pin.closing {
1381                            return Poll::Ready(None);
1382                        }
1383                    }
1384                    Message::Event(ev) => {
1385                        pin.on_event(ev);
1386                    }
1387                }
1388                done = false;
1389            }
1390
1391            if let Some(err) = ws_err {
1392                tracing::error!("WS Connection error: {:?}", err);
1393                if let CdpError::Ws(ref ws_error) = err {
1394                    match ws_error {
1395                        Error::AlreadyClosed => {
1396                            pin.closing = true;
1397                            dispose = true;
1398                        }
1399                        Error::Protocol(detail)
1400                            if detail == &ProtocolError::ResetWithoutClosingHandshake =>
1401                        {
1402                            pin.closing = true;
1403                            dispose = true;
1404                        }
1405                        _ => return Poll::Ready(Some(Err(err))),
1406                    }
1407                } else {
1408                    return Poll::Ready(Some(Err(err)));
1409                }
1410            }
1411
1412            if pin.evict_command_timeout.poll_ready(cx) {
1413                // evict all commands that timed out
1414                pin.evict_timed_out_commands(now);
1415                // evict stale network race-condition buffers and
1416                // orphaned context_ids / frame entries
1417                for t in pin.targets.values_mut() {
1418                    t.network_manager.evict_stale_entries(now);
1419                    t.frame_manager_mut().evict_stale_context_ids();
1420                }
1421            }
1422
1423            if pin.budget_exhausted {
1424                for t in pin.targets.values_mut() {
1425                    t.network_manager.set_block_all(true);
1426                }
1427            }
1428
1429            if dispose {
1430                return Poll::Ready(None);
1431            }
1432
1433            if budget_hit {
1434                // yield to the scheduler; self-wake so the remaining
1435                // work resumes on the next tick without waiting for
1436                // a WS event.
1437                cx.waker().wake_by_ref();
1438                return Poll::Pending;
1439            }
1440
1441            if done {
1442                // no events/responses were read from the websocket
1443                return Poll::Pending;
1444            }
1445        }
1446    }
1447}
1448
1449/// How to configure the handler
1450#[derive(Debug, Clone)]
1451pub struct HandlerConfig {
1452    /// Whether the `NetworkManager`s should ignore https errors
1453    pub ignore_https_errors: bool,
1454    /// Window and device settings
1455    pub viewport: Option<Viewport>,
1456    /// Context ids to set from the get go
1457    pub context_ids: Vec<BrowserContextId>,
1458    /// default request timeout to use
1459    pub request_timeout: Duration,
1460    /// Whether to enable request interception
1461    pub request_intercept: bool,
1462    /// Whether to enable cache
1463    pub cache_enabled: bool,
1464    /// Whether to enable Service Workers
1465    pub service_worker_enabled: bool,
1466    /// Whether to ignore visuals.
1467    pub ignore_visuals: bool,
1468    /// Whether to ignore stylesheets.
1469    pub ignore_stylesheets: bool,
1470    /// Whether to ignore Javascript only allowing critical framework or lib based rendering.
1471    pub ignore_javascript: bool,
1472    /// When `ignore_stylesheets` would skip a stylesheet, allow it through if
1473    /// the request URL is first-party (registrable domain matches the page's
1474    /// primary frame). Default `true` so SPAs that load their own CSS via
1475    /// dynamic imports still hydrate. Set `false` for strict block-all.
1476    pub allow_first_party_stylesheets: bool,
1477    /// When a downstream blocker (intercept manager / adblock / blocklists)
1478    /// would skip a script, allow it through if first-party. Default `true`
1479    /// so SPA bootloaders are not collateral damage from third-party rules.
1480    pub allow_first_party_javascript: bool,
1481    /// When `ignore_visuals` would skip an image/media/font, allow it through
1482    /// if the request URL is first-party. Default `true`. Set `false` for
1483    /// strict bandwidth-minimal crawls that drop ALL visuals.
1484    pub allow_first_party_visuals: bool,
1485    /// Whether to ignore analytics.
1486    pub ignore_analytics: bool,
1487    /// Ignore prefetch request. Defaults to true.
1488    pub ignore_prefetch: bool,
1489    /// Whether to ignore ads.
1490    pub ignore_ads: bool,
1491    /// Extra headers.
1492    pub extra_headers: Option<std::collections::HashMap<String, String>>,
1493    /// Only Html.
1494    pub only_html: bool,
1495    /// Created the first target.
1496    pub created_first_target: bool,
1497    /// The network intercept manager.
1498    pub intercept_manager: NetworkInterceptManager,
1499    /// The max bytes to receive.
1500    pub max_bytes_allowed: Option<u64>,
1501    /// Cap on main-frame Document redirect hops (per navigation).
1502    ///
1503    /// `None` disables enforcement (default); `Some(n)` aborts once the chain length
1504    /// exceeds `n` by emitting `net::ERR_TOO_MANY_REDIRECTS` and calling
1505    /// `Page.stopLoading`. Preserves the accumulated `redirect_chain` on the failed
1506    /// request so consumers can inspect it.
1507    pub max_redirects: Option<usize>,
1508    /// Cap on main-frame cross-document navigations per `goto`. Defends against
1509    /// JS / meta-refresh loops that bypass the HTTP redirect guard. `None`
1510    /// disables the guard.
1511    pub max_main_frame_navigations: Option<u32>,
1512    /// Optional per-run/per-site whitelist of URL substrings (scripts/resources).
1513    pub whitelist_patterns: Option<Vec<String>>,
1514    /// Optional per-run/per-site blacklist of URL substrings (scripts/resources).
1515    pub blacklist_patterns: Option<Vec<String>>,
1516    /// Extra ABP/uBO filter rules for the adblock engine.
1517    #[cfg(feature = "adblock")]
1518    pub adblock_filter_rules: Option<Vec<String>>,
1519    /// Capacity of the channel between browser handle and handler.
1520    /// Defaults to 1000.
1521    pub channel_capacity: usize,
1522    /// Capacity of the per-page mpsc channel carrying `TargetMessage`s
1523    /// from each `Page` to the handler.
1524    ///
1525    /// Defaults to `DEFAULT_PAGE_CHANNEL_CAPACITY` (2048) — the previous
1526    /// hard-coded value. Tune upward for pages that burst many commands
1527    /// (heavy `evaluate`/selector use, high-concurrency tasks sharing
1528    /// one page) to avoid pushing each extra command onto the
1529    /// `CommandFuture` async-send fallback path on `TrySendError::Full`.
1530    /// Tune downward to apply back-pressure sooner. Values of `0` are
1531    /// clamped to `1` at channel creation.
1532    pub page_channel_capacity: usize,
1533    /// Number of WebSocket connection retry attempts with exponential backoff.
1534    /// Defaults to 4.
1535    pub connection_retries: u32,
1536}
1537
1538impl Default for HandlerConfig {
1539    fn default() -> Self {
1540        Self {
1541            ignore_https_errors: true,
1542            viewport: Default::default(),
1543            context_ids: Vec::new(),
1544            request_timeout: Duration::from_millis(REQUEST_TIMEOUT),
1545            request_intercept: false,
1546            cache_enabled: true,
1547            service_worker_enabled: true,
1548            ignore_visuals: false,
1549            ignore_stylesheets: false,
1550            ignore_ads: false,
1551            ignore_javascript: false,
1552            allow_first_party_stylesheets: true,
1553            allow_first_party_javascript: true,
1554            allow_first_party_visuals: true,
1555            ignore_analytics: true,
1556            ignore_prefetch: true,
1557            only_html: false,
1558            extra_headers: Default::default(),
1559            created_first_target: false,
1560            intercept_manager: NetworkInterceptManager::Unknown,
1561            max_bytes_allowed: None,
1562            max_redirects: None,
1563            max_main_frame_navigations: None,
1564            whitelist_patterns: None,
1565            blacklist_patterns: None,
1566            #[cfg(feature = "adblock")]
1567            adblock_filter_rules: None,
1568            channel_capacity: 4096,
1569            page_channel_capacity: crate::handler::page::DEFAULT_PAGE_CHANNEL_CAPACITY,
1570            connection_retries: crate::conn::DEFAULT_CONNECTION_RETRIES,
1571        }
1572    }
1573}
1574
1575/// Wraps the sender half of the channel who requested a navigation
1576#[derive(Debug)]
1577pub struct NavigationInProgress<T> {
1578    /// Marker to indicate whether a navigation lifecycle has completed
1579    navigated: bool,
1580    /// The response of the issued navigation request
1581    response: Option<Response>,
1582    /// Sender who initiated the navigation request
1583    tx: OneshotSender<T>,
1584}
1585
1586impl<T> NavigationInProgress<T> {
1587    pub(crate) fn new(tx: OneshotSender<T>) -> Self {
1588        Self {
1589            navigated: false,
1590            response: None,
1591            tx,
1592        }
1593    }
1594
1595    /// The response to the cdp request has arrived
1596    pub(crate) fn set_response(&mut self, resp: Response) {
1597        self.response = Some(resp);
1598    }
1599
1600    /// The navigation process has finished, the page finished loading.
1601    pub(crate) fn set_navigated(&mut self) {
1602        self.navigated = true;
1603    }
1604
1605    /// Used by the parallel handler when reconciling Page.navigate response
1606    /// vs. lifecycle completion order — the existing serial handler reads
1607    /// the field directly so these accessors are otherwise inert.
1608    #[cfg_attr(not(feature = "parallel-handler"), allow(dead_code))]
1609    pub(crate) fn is_navigated(&self) -> bool {
1610        self.navigated
1611    }
1612
1613    #[cfg_attr(not(feature = "parallel-handler"), allow(dead_code))]
1614    pub(crate) fn take_response(&mut self) -> Option<Response> {
1615        self.response.take()
1616    }
1617
1618    #[cfg_attr(not(feature = "parallel-handler"), allow(dead_code))]
1619    pub(crate) fn into_tx(self) -> OneshotSender<T> {
1620        self.tx
1621    }
1622}
1623
1624/// Request type for navigation
1625#[derive(Debug)]
1626enum NavigationRequest {
1627    /// Represents a simple `NavigateParams` ("Page.navigate")
1628    Navigate(NavigationInProgress<Result<Response>>),
1629    // TODO are there more?
1630}
1631
1632/// Different kind of submitted request submitted from the  `Handler` to the
1633/// `Connection` and being waited on for the response.
1634#[derive(Debug)]
1635enum PendingRequest {
1636    /// A Request to create a new `Target` that results in the creation of a
1637    /// `Page` that represents a browser page.
1638    CreateTarget(OneshotSender<Result<Page>>),
1639    /// A Request to fetch old `Target`s created before connection
1640    GetTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1641    /// A Request to navigate a specific `Target`.
1642    ///
1643    /// Navigation requests are not automatically completed once the response to
1644    /// the raw cdp navigation request (like `NavigateParams`) arrives, but only
1645    /// after the `Target` notifies the `Handler` that the `Page` has finished
1646    /// loading, which comes after the response.
1647    Navigate(NavigationId),
1648    /// A common request received via a channel (`Page`).
1649    ///
1650    /// `target_id` is resolved at submit time from the caller's
1651    /// `session_id` against `self.sessions`, so `on_target_crashed`
1652    /// can cancel in-flight user commands immediately. `None` when
1653    /// the command has no session (browser-level) or was sent
1654    /// before the attach event arrived — those fall back to the
1655    /// normal `request_timeout` eviction.
1656    ExternalCommand {
1657        tx: OneshotSender<Result<Response>>,
1658        target_id: Option<TargetId>,
1659    },
1660    /// Requests that are initiated directly from a `Target` (all the
1661    /// initialization commands).
1662    InternalCommand(TargetId),
1663    // A Request to close the browser.
1664    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1665}
1666
1667/// Events used internally to communicate with the handler, which are executed
1668/// in the background
1669// TODO rename to BrowserMessage
1670#[derive(Debug)]
1671pub(crate) enum HandlerMessage {
1672    CreatePage(CreateTargetParams, OneshotSender<Result<Page>>),
1673    FetchTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1674    InsertContext(BrowserContext),
1675    DisposeContext(BrowserContext),
1676    GetPages(OneshotSender<Vec<Page>>),
1677    Command(CommandMessage),
1678    GetPage(TargetId, OneshotSender<Option<Page>>),
1679    AddEventListener(EventListenerRequest),
1680    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1681}
1682
1683#[cfg(test)]
1684mod tests {
1685    use super::*;
1686    use chromiumoxide_cdp::cdp::browser_protocol::target::{AttachToTargetReturns, TargetInfo};
1687
1688    #[test]
1689    fn attach_to_target_response_sets_session_id_before_event_arrives() {
1690        let info = TargetInfo::builder()
1691            .target_id("target-1".to_string())
1692            .r#type("page")
1693            .title("")
1694            .url("about:blank")
1695            .attached(false)
1696            .can_access_opener(false)
1697            .build()
1698            .expect("target info");
1699        let mut target = Target::new(info, TargetConfig::default(), BrowserContext::default());
1700        let method: MethodId = AttachToTargetParams::IDENTIFIER.into();
1701        let result = serde_json::to_value(AttachToTargetReturns::new("session-1".to_string()))
1702            .expect("attach result");
1703        let resp = Response {
1704            id: CallId::new(1),
1705            result: Some(result),
1706            error: None,
1707        };
1708
1709        maybe_store_attach_session_id(&mut target, &method, &resp);
1710
1711        assert_eq!(
1712            target.session_id().map(AsRef::as_ref),
1713            Some("session-1"),
1714            "attach response should seed the flat session id even before Target.attachedToTarget"
1715        );
1716    }
1717
1718    /// Regression guard: `page_channel_capacity` must default to 2048
1719    /// everywhere, so existing callers see identical behavior to the
1720    /// previous hard-coded value. If this test ever fails, every caller
1721    /// that relied on the implicit 2048-slot channel silently changed.
1722    #[test]
1723    fn page_channel_capacity_defaults_to_2048_across_configs() {
1724        use crate::browser::BrowserConfigBuilder;
1725        use crate::handler::page::DEFAULT_PAGE_CHANNEL_CAPACITY;
1726        use crate::handler::target::TargetConfig;
1727
1728        assert_eq!(DEFAULT_PAGE_CHANNEL_CAPACITY, 2048);
1729        assert_eq!(
1730            HandlerConfig::default().page_channel_capacity,
1731            DEFAULT_PAGE_CHANNEL_CAPACITY,
1732            "HandlerConfig default must match the historical 2048 slot count"
1733        );
1734        assert_eq!(
1735            TargetConfig::default().page_channel_capacity,
1736            DEFAULT_PAGE_CHANNEL_CAPACITY,
1737            "TargetConfig default must match the historical 2048 slot count"
1738        );
1739        // BrowserConfigBuilder default → build a builder (no executable
1740        // check needed: we only inspect the numeric field, not `build()`).
1741        let builder = BrowserConfigBuilder::default();
1742        let bc = format!("{:?}", builder);
1743        assert!(
1744            bc.contains("page_channel_capacity: 2048"),
1745            "BrowserConfigBuilder must default page_channel_capacity to 2048, got: {bc}",
1746        );
1747    }
1748}