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;
52pub mod sender;
53mod session;
54pub mod target;
55pub mod target_message_future;
56pub mod viewport;
57
58/// The handler that monitors the state of the chromium browser and drives all
59/// the requests and events.
60#[must_use = "streams do nothing unless polled"]
61#[derive(Debug)]
62pub struct Handler {
63    pub default_browser_context: BrowserContext,
64    pub browser_contexts: HashSet<BrowserContext>,
65    /// Commands that are being processed and awaiting a response from the
66    /// chromium instance together with the timestamp when the request
67    /// started.
68    pending_commands: FnvHashMap<CallId, (PendingRequest, MethodId, Instant)>,
69    /// Connection to the browser instance
70    from_browser: Receiver<HandlerMessage>,
71    /// Used to loop over all targets in a consistent manner
72    target_ids: Vec<TargetId>,
73    /// The created and attached targets
74    targets: HashMap<TargetId, Target>,
75    /// Currently queued in navigations for targets
76    navigations: FnvHashMap<NavigationId, NavigationRequest>,
77    /// Keeps track of all the current active sessions
78    ///
79    /// There can be multiple sessions per target.
80    sessions: HashMap<SessionId, Session>,
81    /// The websocket connection to the chromium instance.
82    /// `Option` so that `run()` can `.take()` it for splitting.
83    conn: Option<Connection<CdpEventMessage>>,
84    /// Evicts timed out requests periodically
85    evict_command_timeout: PeriodicJob,
86    /// The internal identifier for a specific navigation
87    next_navigation_id: usize,
88    /// How this handler will configure targets etc,
89    config: HandlerConfig,
90    /// All registered event subscriptions
91    event_listeners: EventListeners,
92    /// Keeps track is the browser is closing
93    closing: bool,
94    /// Track the bytes remainder until network request will be blocked.
95    remaining_bytes: Option<u64>,
96    /// The budget is exhausted.
97    budget_exhausted: bool,
98    /// Tracks which targets we've already attached to, to avoid multiple sessions per target.
99    attached_targets: HashSet<TargetId>,
100    /// Optional notify for waking `Handler::run()`'s `tokio::select!` loop
101    /// when a page sends a message.  `None` when using the `Stream` API.
102    page_wake: Option<Arc<Notify>>,
103}
104
105lazy_static::lazy_static! {
106    /// Set the discovery ID target.
107    static ref DISCOVER_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
108        let discover = SetDiscoverTargetsParams::new(true);
109        (discover.identifier(), serde_json::to_value(discover).expect("valid discover target params"))
110    };
111    /// Targets params id.
112    static ref TARGET_PARAMS_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
113        let msg = GetTargetsParams { filter: None };
114        (msg.identifier(), serde_json::to_value(msg).expect("valid paramtarget"))
115    };
116    /// Set the close targets.
117    static ref CLOSE_PARAMS_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
118        let close_msg = CloseParams::default();
119        (close_msg.identifier(), serde_json::to_value(close_msg).expect("valid close params"))
120    };
121}
122
123fn maybe_store_attach_session_id(target: &mut Target, method: &MethodId, resp: &Response) {
124    if method.as_ref() != AttachToTargetParams::IDENTIFIER {
125        return;
126    }
127
128    if let Ok(resp) = to_command_response::<AttachToTargetParams>(resp.clone(), method.clone()) {
129        target.set_session_id(resp.result.session_id);
130    }
131}
132
133impl Handler {
134    /// Create a new `Handler` that drives the connection and listens for
135    /// messages on the receiver `rx`.
136    pub(crate) fn new(
137        mut conn: Connection<CdpEventMessage>,
138        rx: Receiver<HandlerMessage>,
139        config: HandlerConfig,
140    ) -> Self {
141        let discover = DISCOVER_ID.clone();
142        let _ = conn.submit_command(discover.0, None, discover.1);
143        let conn = Some(conn);
144
145        let browser_contexts = config
146            .context_ids
147            .iter()
148            .map(|id| BrowserContext::from(id.clone()))
149            .collect();
150
151        Self {
152            pending_commands: Default::default(),
153            from_browser: rx,
154            default_browser_context: Default::default(),
155            browser_contexts,
156            target_ids: Default::default(),
157            targets: Default::default(),
158            navigations: Default::default(),
159            sessions: Default::default(),
160            conn,
161            evict_command_timeout: PeriodicJob::new(config.request_timeout),
162            next_navigation_id: 0,
163            config,
164            event_listeners: Default::default(),
165            closing: false,
166            remaining_bytes: None,
167            budget_exhausted: false,
168            attached_targets: Default::default(),
169            page_wake: None,
170        }
171    }
172
173    /// Borrow the WebSocket connection, returning an error if it has been
174    /// consumed by [`Handler::run()`].
175    #[inline]
176    fn conn(&mut self) -> Result<&mut Connection<CdpEventMessage>> {
177        self.conn
178            .as_mut()
179            .ok_or_else(|| CdpError::msg("connection consumed by Handler::run()"))
180    }
181
182    /// Return the target with the matching `target_id`
183    pub fn get_target(&self, target_id: &TargetId) -> Option<&Target> {
184        self.targets.get(target_id)
185    }
186
187    /// Iterator over all currently attached targets
188    pub fn targets(&self) -> impl Iterator<Item = &Target> + '_ {
189        self.targets.values()
190    }
191
192    /// The default Browser context
193    pub fn default_browser_context(&self) -> &BrowserContext {
194        &self.default_browser_context
195    }
196
197    /// Iterator over all currently available browser contexts
198    pub fn browser_contexts(&self) -> impl Iterator<Item = &BrowserContext> + '_ {
199        self.browser_contexts.iter()
200    }
201
202    /// received a response to a navigation request like `Page.navigate`
203    fn on_navigation_response(&mut self, id: NavigationId, resp: Response) {
204        if let Some(nav) = self.navigations.remove(&id) {
205            match nav {
206                NavigationRequest::Navigate(mut nav) => {
207                    if nav.navigated {
208                        let _ = nav.tx.send(Ok(resp));
209                    } else {
210                        nav.set_response(resp);
211                        self.navigations
212                            .insert(id, NavigationRequest::Navigate(nav));
213                    }
214                }
215            }
216        }
217    }
218
219    /// A navigation has finished.
220    fn on_navigation_lifecycle_completed(&mut self, res: Result<NavigationOk, NavigationError>) {
221        match res {
222            Ok(ok) => {
223                let id = *ok.navigation_id();
224                if let Some(nav) = self.navigations.remove(&id) {
225                    match nav {
226                        NavigationRequest::Navigate(mut nav) => {
227                            if let Some(resp) = nav.response.take() {
228                                let _ = nav.tx.send(Ok(resp));
229                            } else {
230                                nav.set_navigated();
231                                self.navigations
232                                    .insert(id, NavigationRequest::Navigate(nav));
233                            }
234                        }
235                    }
236                }
237            }
238            Err(err) => {
239                if let Some(nav) = self.navigations.remove(err.navigation_id()) {
240                    match nav {
241                        NavigationRequest::Navigate(nav) => {
242                            let _ = nav.tx.send(Err(err.into()));
243                        }
244                    }
245                }
246            }
247        }
248    }
249
250    /// Received a response to a request.
251    fn on_response(&mut self, resp: Response) {
252        if let Some((req, method, _)) = self.pending_commands.remove(&resp.id) {
253            match req {
254                PendingRequest::CreateTarget(tx) => {
255                    match to_command_response::<CreateTargetParams>(resp, method) {
256                        Ok(resp) => {
257                            if let Some(target) = self.targets.get_mut(&resp.target_id) {
258                                target.set_initiator(tx);
259                            } else {
260                                let _ = tx.send(Err(CdpError::NotFound)).ok();
261                            }
262                        }
263                        Err(err) => {
264                            let _ = tx.send(Err(err)).ok();
265                        }
266                    }
267                }
268                PendingRequest::GetTargets(tx) => {
269                    match to_command_response::<GetTargetsParams>(resp, method) {
270                        Ok(resp) => {
271                            let targets = resp.result.target_infos;
272                            let results = targets.clone();
273
274                            for target_info in targets {
275                                let event: EventTargetCreated = EventTargetCreated { target_info };
276                                self.on_target_created(event);
277                            }
278
279                            let _ = tx.send(Ok(results)).ok();
280                        }
281                        Err(err) => {
282                            let _ = tx.send(Err(err)).ok();
283                        }
284                    }
285                }
286                PendingRequest::Navigate(id) => {
287                    self.on_navigation_response(id, resp);
288                    if self.config.only_html && !self.config.created_first_target {
289                        self.config.created_first_target = true;
290                    }
291                }
292                PendingRequest::ExternalCommand(tx) => {
293                    let _ = tx.send(Ok(resp)).ok();
294                }
295                PendingRequest::InternalCommand(target_id) => {
296                    if let Some(target) = self.targets.get_mut(&target_id) {
297                        maybe_store_attach_session_id(target, &method, &resp);
298                        target.on_response(resp, method.as_ref());
299                    }
300                }
301                PendingRequest::CloseBrowser(tx) => {
302                    self.closing = true;
303                    let _ = tx.send(Ok(CloseReturns {})).ok();
304                }
305            }
306        }
307    }
308
309    /// Submit a command initiated via channel
310    pub(crate) fn submit_external_command(
311        &mut self,
312        msg: CommandMessage,
313        now: Instant,
314    ) -> Result<()> {
315        let call_id =
316            self.conn()?
317                .submit_command(msg.method.clone(), msg.session_id, msg.params)?;
318        self.pending_commands.insert(
319            call_id,
320            (PendingRequest::ExternalCommand(msg.sender), msg.method, now),
321        );
322        Ok(())
323    }
324
325    pub(crate) fn submit_internal_command(
326        &mut self,
327        target_id: TargetId,
328        req: CdpRequest,
329        now: Instant,
330    ) -> Result<()> {
331        let call_id = self.conn()?.submit_command(
332            req.method.clone(),
333            req.session_id.map(Into::into),
334            req.params,
335        )?;
336        self.pending_commands.insert(
337            call_id,
338            (PendingRequest::InternalCommand(target_id), req.method, now),
339        );
340        Ok(())
341    }
342
343    fn submit_fetch_targets(&mut self, tx: OneshotSender<Result<Vec<TargetInfo>>>, now: Instant) {
344        let msg = TARGET_PARAMS_ID.clone();
345
346        if let Some(conn) = self.conn.as_mut() {
347            if let Ok(call_id) = conn.submit_command(msg.0.clone(), None, msg.1) {
348                self.pending_commands
349                    .insert(call_id, (PendingRequest::GetTargets(tx), msg.0, now));
350            }
351        }
352    }
353
354    /// Send the Request over to the server and store its identifier to handle
355    /// the response once received.
356    fn submit_navigation(&mut self, id: NavigationId, req: CdpRequest, now: Instant) {
357        if let Some(conn) = self.conn.as_mut() {
358            if let Ok(call_id) = conn.submit_command(
359                req.method.clone(),
360                req.session_id.map(Into::into),
361                req.params,
362            ) {
363                self.pending_commands
364                    .insert(call_id, (PendingRequest::Navigate(id), req.method, now));
365            }
366        }
367    }
368
369    fn submit_close(&mut self, tx: OneshotSender<Result<CloseReturns>>, now: Instant) {
370        let close_msg = CLOSE_PARAMS_ID.clone();
371
372        if let Some(conn) = self.conn.as_mut() {
373            if let Ok(call_id) = conn.submit_command(close_msg.0.clone(), None, close_msg.1) {
374                self.pending_commands.insert(
375                    call_id,
376                    (PendingRequest::CloseBrowser(tx), close_msg.0, now),
377                );
378            }
379        }
380    }
381
382    /// Process a message received by the target's page via channel
383    fn on_target_message(&mut self, target: &mut Target, msg: CommandMessage, now: Instant) {
384        if msg.is_navigation() {
385            let (req, tx) = msg.split();
386            let id = self.next_navigation_id();
387
388            target.goto(FrameRequestedNavigation::new(
389                id,
390                req,
391                self.config.request_timeout,
392            ));
393
394            self.navigations.insert(
395                id,
396                NavigationRequest::Navigate(NavigationInProgress::new(tx)),
397            );
398        } else {
399            let _ = self.submit_external_command(msg, now);
400        }
401    }
402
403    /// An identifier for queued `NavigationRequest`s.
404    fn next_navigation_id(&mut self) -> NavigationId {
405        let id = NavigationId(self.next_navigation_id);
406        self.next_navigation_id = self.next_navigation_id.wrapping_add(1);
407        id
408    }
409
410    /// Create a new page and send it to the receiver when ready
411    ///
412    /// First a `CreateTargetParams` is send to the server, this will trigger
413    /// `EventTargetCreated` which results in a new `Target` being created.
414    /// Once the response to the request is received the initialization process
415    /// of the target kicks in. This triggers a queue of initialization requests
416    /// of the `Target`, once those are all processed and the `url` fo the
417    /// `CreateTargetParams` has finished loading (The `Target`'s `Page` is
418    /// ready and idle), the `Target` sends its newly created `Page` as response
419    /// to the initiator (`tx`) of the `CreateTargetParams` request.
420    fn create_page(&mut self, params: CreateTargetParams, tx: OneshotSender<Result<Page>>) {
421        let about_blank = params.url == "about:blank";
422        let http_check =
423            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
424
425        if about_blank || http_check {
426            let method = params.identifier();
427
428            let Some(conn) = self.conn.as_mut() else {
429                let _ = tx.send(Err(CdpError::msg("connection consumed"))).ok();
430                return;
431            };
432            match serde_json::to_value(params) {
433                Ok(params) => match conn.submit_command(method.clone(), None, params) {
434                    Ok(call_id) => {
435                        self.pending_commands.insert(
436                            call_id,
437                            (PendingRequest::CreateTarget(tx), method, Instant::now()),
438                        );
439                    }
440                    Err(err) => {
441                        let _ = tx.send(Err(err.into())).ok();
442                    }
443                },
444                Err(err) => {
445                    let _ = tx.send(Err(err.into())).ok();
446                }
447            }
448        } else {
449            let _ = tx.send(Err(CdpError::NotFound)).ok();
450        }
451    }
452
453    /// Process an incoming event read from the websocket
454    fn on_event(&mut self, event: CdpEventMessage) {
455        if let Some(session_id) = &event.session_id {
456            if let Some(session) = self.sessions.get(session_id.as_str()) {
457                if let Some(target) = self.targets.get_mut(session.target_id()) {
458                    return target.on_event(event);
459                }
460            }
461        }
462        let CdpEventMessage { params, method, .. } = event;
463
464        match params {
465            CdpEvent::TargetTargetCreated(ref ev) => self.on_target_created((**ev).clone()),
466            CdpEvent::TargetAttachedToTarget(ref ev) => self.on_attached_to_target(ev.clone()),
467            CdpEvent::TargetTargetDestroyed(ref ev) => self.on_target_destroyed(ev.clone()),
468            CdpEvent::TargetDetachedFromTarget(ref ev) => self.on_detached_from_target(ev.clone()),
469            _ => {}
470        }
471
472        chromiumoxide_cdp::consume_event!(match params {
473            |ev| self.event_listeners.start_send(ev),
474            |json| { let _ = self.event_listeners.try_send_custom(&method, json);}
475        });
476    }
477
478    /// Fired when a new target was created on the chromium instance
479    ///
480    /// Creates a new `Target` instance and keeps track of it
481    fn on_target_created(&mut self, event: EventTargetCreated) {
482        if !self.browser_contexts.is_empty() {
483            if let Some(ref context_id) = event.target_info.browser_context_id {
484                let bc = BrowserContext {
485                    id: Some(context_id.clone()),
486                };
487                if !self.browser_contexts.contains(&bc) {
488                    return;
489                }
490            }
491        }
492        let browser_ctx = event
493            .target_info
494            .browser_context_id
495            .clone()
496            .map(BrowserContext::from)
497            .unwrap_or_else(|| self.default_browser_context.clone());
498        let target = Target::new(
499            event.target_info,
500            TargetConfig {
501                ignore_https_errors: self.config.ignore_https_errors,
502                request_timeout: self.config.request_timeout,
503                viewport: self.config.viewport.clone(),
504                request_intercept: self.config.request_intercept,
505                cache_enabled: self.config.cache_enabled,
506                service_worker_enabled: self.config.service_worker_enabled,
507                ignore_visuals: self.config.ignore_visuals,
508                ignore_stylesheets: self.config.ignore_stylesheets,
509                ignore_javascript: self.config.ignore_javascript,
510                ignore_analytics: self.config.ignore_analytics,
511                ignore_prefetch: self.config.ignore_prefetch,
512                extra_headers: self.config.extra_headers.clone(),
513                only_html: self.config.only_html && self.config.created_first_target,
514                intercept_manager: self.config.intercept_manager,
515                max_bytes_allowed: self.config.max_bytes_allowed,
516                whitelist_patterns: self.config.whitelist_patterns.clone(),
517                blacklist_patterns: self.config.blacklist_patterns.clone(),
518                #[cfg(feature = "adblock")]
519                adblock_filter_rules: self.config.adblock_filter_rules.clone(),
520                page_wake: self.page_wake.clone(),
521            },
522            browser_ctx,
523        );
524
525        self.target_ids.push(target.target_id().clone());
526        self.targets.insert(target.target_id().clone(), target);
527    }
528
529    /// A new session is attached to a target
530    fn on_attached_to_target(&mut self, event: Box<EventAttachedToTarget>) {
531        let session = Session::new(event.session_id.clone(), event.target_info.target_id);
532        if let Some(target) = self.targets.get_mut(session.target_id()) {
533            target.set_session_id(session.session_id().clone())
534        }
535        self.sessions.insert(event.session_id, session);
536    }
537
538    /// The session was detached from target.
539    /// Can be issued multiple times per target if multiple session have been
540    /// attached to it.
541    fn on_detached_from_target(&mut self, event: EventDetachedFromTarget) {
542        // remove the session
543        if let Some(session) = self.sessions.remove(&event.session_id) {
544            if let Some(target) = self.targets.get_mut(session.target_id()) {
545                target.session_id_mut().take();
546            }
547        }
548    }
549
550    /// Fired when the target was destroyed in the browser
551    fn on_target_destroyed(&mut self, event: EventTargetDestroyed) {
552        self.attached_targets.remove(&event.target_id);
553
554        if let Some(target) = self.targets.remove(&event.target_id) {
555            // TODO shutdown?
556            if let Some(session) = target.session_id() {
557                self.sessions.remove(session);
558            }
559        }
560    }
561
562    /// House keeping of commands
563    ///
564    /// Remove all commands where `now` > `timestamp of command starting point +
565    /// request timeout` and notify the senders that their request timed out.
566    fn evict_timed_out_commands(&mut self, now: Instant) {
567        let deadline = match now.checked_sub(self.config.request_timeout) {
568            Some(d) => d,
569            None => return,
570        };
571
572        let timed_out: Vec<_> = self
573            .pending_commands
574            .iter()
575            .filter(|(_, (_, _, timestamp))| *timestamp < deadline)
576            .map(|(k, _)| *k)
577            .collect();
578
579        for call in timed_out {
580            if let Some((req, _, _)) = self.pending_commands.remove(&call) {
581                match req {
582                    PendingRequest::CreateTarget(tx) => {
583                        let _ = tx.send(Err(CdpError::Timeout));
584                    }
585                    PendingRequest::GetTargets(tx) => {
586                        let _ = tx.send(Err(CdpError::Timeout));
587                    }
588                    PendingRequest::Navigate(nav) => {
589                        if let Some(nav) = self.navigations.remove(&nav) {
590                            match nav {
591                                NavigationRequest::Navigate(nav) => {
592                                    let _ = nav.tx.send(Err(CdpError::Timeout));
593                                }
594                            }
595                        }
596                    }
597                    PendingRequest::ExternalCommand(tx) => {
598                        let _ = tx.send(Err(CdpError::Timeout));
599                    }
600                    PendingRequest::InternalCommand(_) => {}
601                    PendingRequest::CloseBrowser(tx) => {
602                        let _ = tx.send(Err(CdpError::Timeout));
603                    }
604                }
605            }
606        }
607    }
608
609    pub fn event_listeners_mut(&mut self) -> &mut EventListeners {
610        &mut self.event_listeners
611    }
612
613    // ------------------------------------------------------------------
614    //  Tokio-native async entry point
615    // ------------------------------------------------------------------
616
617    /// Run the handler as a fully async tokio task.
618    ///
619    /// This is the high-performance alternative to polling `Handler` as a
620    /// `Stream`.  Internally it:
621    ///
622    /// * Splits the WebSocket into independent read/write halves — the
623    ///   writer runs in its own tokio task with natural batching.
624    /// * Uses `tokio::select!` to multiplex the browser channel, page
625    ///   notifications, WebSocket reads, the eviction timer, and writer
626    ///   health.
627    /// * Drains every target's page channel via `try_recv()` (non-blocking)
628    ///   after each event, with an `Arc<Notify>` ensuring the select loop
629    ///   wakes up whenever a page sends a message.
630    ///
631    /// # Usage
632    ///
633    /// ```rust,no_run
634    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
635    /// use chromiumoxide::Browser;
636    /// let (browser, handler) = Browser::launch(Default::default()).await?;
637    /// let handler_task = tokio::spawn(handler.run());
638    /// // … use browser …
639    /// # Ok(())
640    /// # }
641    /// ```
642    pub async fn run(mut self) -> Result<()> {
643        use chromiumoxide_types::Message;
644        use tokio::time::MissedTickBehavior;
645        use tokio_tungstenite::tungstenite::{self, error::ProtocolError};
646
647        // --- set up page notification ---
648        let page_wake = Arc::new(Notify::new());
649        self.page_wake = Some(page_wake.clone());
650
651        // --- split WebSocket ---
652        let conn = self
653            .conn
654            .take()
655            .ok_or_else(|| CdpError::msg("Handler::run() called with no connection"))?;
656        let async_conn = conn.into_async();
657        let mut ws_reader = async_conn.reader;
658        let ws_tx = async_conn.cmd_tx;
659        let mut writer_handle = async_conn.writer_handle;
660        let mut next_call_id = async_conn.next_id;
661
662        // Helper to mint call-ids without &mut self.conn.
663        let mut alloc_call_id = || {
664            let id = chromiumoxide_types::CallId::new(next_call_id);
665            next_call_id = next_call_id.wrapping_add(1);
666            id
667        };
668
669        // --- eviction timer ---
670        let mut evict_timer = tokio::time::interval_at(
671            tokio::time::Instant::now() + self.config.request_timeout,
672            self.config.request_timeout,
673        );
674        evict_timer.set_missed_tick_behavior(MissedTickBehavior::Delay);
675
676        // Helper closure: submit a MethodCall through the WS writer.
677        macro_rules! ws_submit {
678            ($method:expr, $session_id:expr, $params:expr) => {{
679                let id = alloc_call_id();
680                let call = chromiumoxide_types::MethodCall {
681                    id,
682                    method: $method,
683                    session_id: $session_id,
684                    params: $params,
685                };
686                match ws_tx.try_send(call) {
687                    Ok(()) => Ok::<_, CdpError>(id),
688                    Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
689                        tracing::warn!("WS command channel full — dropping command");
690                        Err(CdpError::msg("WS command channel full"))
691                    }
692                    Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
693                        Err(CdpError::msg("WS writer closed"))
694                    }
695                }
696            }};
697        }
698
699        // ---- main event loop ----
700        loop {
701            let now = std::time::Instant::now();
702
703            // 1. Drain all target page channels (non-blocking) & advance
704            //    state machines.
705            //
706            // Budget: drain at most 128 messages per target per iteration
707            // so a single chatty page cannot starve the rest.
708            const PER_TARGET_DRAIN_BUDGET: usize = 128;
709
710            for n in (0..self.target_ids.len()).rev() {
711                let target_id = self.target_ids.swap_remove(n);
712
713                if let Some((id, mut target)) = self.targets.remove_entry(&target_id) {
714                    // Drain page channel (non-blocking — waker is the Notify).
715                    {
716                        let mut msgs = Vec::new();
717                        if let Some(handle) = target.page_mut() {
718                            while msgs.len() < PER_TARGET_DRAIN_BUDGET {
719                                match handle.rx.try_recv() {
720                                    Ok(msg) => msgs.push(msg),
721                                    Err(_) => break,
722                                }
723                            }
724                        }
725                        for msg in msgs {
726                            target.on_page_message(msg);
727                        }
728                    }
729
730                    // Advance target state machine & process events.
731                    while let Some(event) = target.advance(now) {
732                        match event {
733                            TargetEvent::Request(req) => {
734                                if let Ok(call_id) = ws_submit!(
735                                    req.method.clone(),
736                                    req.session_id.map(Into::into),
737                                    req.params
738                                ) {
739                                    self.pending_commands.insert(
740                                        call_id,
741                                        (
742                                            PendingRequest::InternalCommand(
743                                                target.target_id().clone(),
744                                            ),
745                                            req.method,
746                                            now,
747                                        ),
748                                    );
749                                }
750                            }
751                            TargetEvent::Command(msg) => {
752                                if msg.is_navigation() {
753                                    let (req, tx) = msg.split();
754                                    let nav_id = self.next_navigation_id();
755                                    target.goto(FrameRequestedNavigation::new(
756                                        nav_id,
757                                        req.clone(),
758                                        self.config.request_timeout,
759                                    ));
760                                    if let Ok(call_id) = ws_submit!(
761                                        req.method.clone(),
762                                        req.session_id.map(Into::into),
763                                        req.params
764                                    ) {
765                                        self.pending_commands.insert(
766                                            call_id,
767                                            (PendingRequest::Navigate(nav_id), req.method, now),
768                                        );
769                                    }
770                                    self.navigations.insert(
771                                        nav_id,
772                                        NavigationRequest::Navigate(NavigationInProgress::new(tx)),
773                                    );
774                                } else {
775                                    if let Ok(call_id) = ws_submit!(
776                                        msg.method.clone(),
777                                        msg.session_id.map(Into::into),
778                                        msg.params
779                                    ) {
780                                        self.pending_commands.insert(
781                                            call_id,
782                                            (
783                                                PendingRequest::ExternalCommand(msg.sender),
784                                                msg.method,
785                                                now,
786                                            ),
787                                        );
788                                    }
789                                }
790                            }
791                            TargetEvent::NavigationRequest(nav_id, req) => {
792                                if let Ok(call_id) = ws_submit!(
793                                    req.method.clone(),
794                                    req.session_id.map(Into::into),
795                                    req.params
796                                ) {
797                                    self.pending_commands.insert(
798                                        call_id,
799                                        (PendingRequest::Navigate(nav_id), req.method, now),
800                                    );
801                                }
802                            }
803                            TargetEvent::NavigationResult(res) => {
804                                self.on_navigation_lifecycle_completed(res);
805                            }
806                            TargetEvent::BytesConsumed(n) => {
807                                if let Some(rem) = self.remaining_bytes.as_mut() {
808                                    *rem = rem.saturating_sub(n);
809                                    if *rem == 0 {
810                                        self.budget_exhausted = true;
811                                    }
812                                }
813                            }
814                        }
815                    }
816
817                    // Flush event listeners (no Context needed).
818                    target.event_listeners_mut().flush();
819
820                    self.targets.insert(id, target);
821                    self.target_ids.push(target_id);
822                }
823            }
824
825            // Flush handler-level event listeners.
826            self.event_listeners.flush();
827
828            if self.budget_exhausted {
829                for t in self.targets.values_mut() {
830                    t.network_manager.set_block_all(true);
831                }
832            }
833
834            if self.closing {
835                break;
836            }
837
838            // 2. Multiplex all event sources via tokio::select!
839            tokio::select! {
840                msg = self.from_browser.recv() => {
841                    match msg {
842                        Some(msg) => {
843                            match msg {
844                                HandlerMessage::Command(cmd) => {
845                                    if let Ok(call_id) = ws_submit!(
846                                        cmd.method.clone(),
847                                        cmd.session_id.map(Into::into),
848                                        cmd.params
849                                    ) {
850                                        self.pending_commands.insert(
851                                            call_id,
852                                            (PendingRequest::ExternalCommand(cmd.sender), cmd.method, now),
853                                        );
854                                    }
855                                }
856                                HandlerMessage::FetchTargets(tx) => {
857                                    let msg = TARGET_PARAMS_ID.clone();
858                                    if let Ok(call_id) = ws_submit!(msg.0.clone(), None, msg.1) {
859                                        self.pending_commands.insert(
860                                            call_id,
861                                            (PendingRequest::GetTargets(tx), msg.0, now),
862                                        );
863                                    }
864                                }
865                                HandlerMessage::CloseBrowser(tx) => {
866                                    let close_msg = CLOSE_PARAMS_ID.clone();
867                                    if let Ok(call_id) = ws_submit!(close_msg.0.clone(), None, close_msg.1) {
868                                        self.pending_commands.insert(
869                                            call_id,
870                                            (PendingRequest::CloseBrowser(tx), close_msg.0, now),
871                                        );
872                                    }
873                                }
874                                HandlerMessage::CreatePage(params, tx) => {
875                                    if let Some(ref id) = params.browser_context_id {
876                                        self.browser_contexts.insert(BrowserContext::from(id.clone()));
877                                    }
878                                    self.create_page_async(params, tx, &mut alloc_call_id, &ws_tx, now);
879                                }
880                                HandlerMessage::GetPages(tx) => {
881                                    let pages: Vec<_> = self.targets.values_mut()
882                                        .filter(|p| p.is_page())
883                                        .filter_map(|target| target.get_or_create_page())
884                                        .map(|page| Page::from(page.clone()))
885                                        .collect();
886                                    let _ = tx.send(pages);
887                                }
888                                HandlerMessage::InsertContext(ctx) => {
889                                    if self.default_browser_context.id().is_none() {
890                                        self.default_browser_context = ctx.clone();
891                                    }
892                                    self.browser_contexts.insert(ctx);
893                                }
894                                HandlerMessage::DisposeContext(ctx) => {
895                                    self.browser_contexts.remove(&ctx);
896                                    self.attached_targets.retain(|tid| {
897                                        self.targets.get(tid)
898                                            .and_then(|t| t.browser_context_id())
899                                            .map(|id| Some(id) != ctx.id())
900                                            .unwrap_or(true)
901                                    });
902                                    self.closing = true;
903                                }
904                                HandlerMessage::GetPage(target_id, tx) => {
905                                    let page = self.targets.get_mut(&target_id)
906                                        .and_then(|target| target.get_or_create_page())
907                                        .map(|page| Page::from(page.clone()));
908                                    let _ = tx.send(page);
909                                }
910                                HandlerMessage::AddEventListener(req) => {
911                                    self.event_listeners.add_listener(req);
912                                }
913                            }
914                        }
915                        None => break, // browser handle dropped
916                    }
917                }
918
919                frame = ws_reader.next_message() => {
920                    match frame {
921                        Some(Ok(boxed_msg)) => match *boxed_msg {
922                            Message::Response(resp) => {
923                                self.on_response(resp);
924                            }
925                            Message::Event(ev) => {
926                                self.on_event(ev);
927                            }
928                        },
929                        Some(Err(err)) => {
930                            tracing::error!("WS Connection error: {:?}", err);
931                            if let CdpError::Ws(ref ws_error) = err {
932                                match ws_error {
933                                    tungstenite::Error::AlreadyClosed => break,
934                                    tungstenite::Error::Protocol(detail)
935                                        if detail == &ProtocolError::ResetWithoutClosingHandshake =>
936                                    {
937                                        break;
938                                    }
939                                    _ => return Err(err),
940                                }
941                            } else {
942                                return Err(err);
943                            }
944                        }
945                        None => break, // WS closed
946                    }
947                }
948
949                _ = page_wake.notified() => {
950                    // A page sent a message — loop back to drain targets.
951                }
952
953                _ = evict_timer.tick() => {
954                    self.evict_timed_out_commands(now);
955                    for t in self.targets.values_mut() {
956                        t.network_manager.evict_stale_entries(now);
957                        t.frame_manager_mut().evict_stale_context_ids();
958                    }
959                }
960
961                result = &mut writer_handle => {
962                    // WS writer exited — propagate error or break.
963                    match result {
964                        Ok(Ok(())) => break,
965                        Ok(Err(e)) => return Err(e),
966                        Err(e) => return Err(CdpError::msg(format!("WS writer panicked: {e}"))),
967                    }
968                }
969            }
970        }
971
972        writer_handle.abort();
973        Ok(())
974    }
975
976    /// `create_page` variant for the `run()` path that submits via `ws_tx`.
977    fn create_page_async(
978        &mut self,
979        params: CreateTargetParams,
980        tx: OneshotSender<Result<Page>>,
981        alloc_call_id: &mut impl FnMut() -> chromiumoxide_types::CallId,
982        ws_tx: &tokio::sync::mpsc::Sender<chromiumoxide_types::MethodCall>,
983        now: std::time::Instant,
984    ) {
985        let about_blank = params.url == "about:blank";
986        let http_check =
987            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
988
989        if about_blank || http_check {
990            let method = params.identifier();
991            match serde_json::to_value(params) {
992                Ok(params) => {
993                    let id = alloc_call_id();
994                    let call = chromiumoxide_types::MethodCall {
995                        id,
996                        method: method.clone(),
997                        session_id: None,
998                        params,
999                    };
1000                    match ws_tx.try_send(call) {
1001                        Ok(()) => {
1002                            self.pending_commands
1003                                .insert(id, (PendingRequest::CreateTarget(tx), method, now));
1004                        }
1005                        Err(_) => {
1006                            let _ = tx
1007                                .send(Err(CdpError::msg("WS command channel full or closed")))
1008                                .ok();
1009                        }
1010                    }
1011                }
1012                Err(err) => {
1013                    let _ = tx.send(Err(err.into())).ok();
1014                }
1015            }
1016        } else {
1017            let _ = tx.send(Err(CdpError::NotFound)).ok();
1018        }
1019    }
1020}
1021
1022impl Stream for Handler {
1023    type Item = Result<()>;
1024
1025    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1026        let pin = self.get_mut();
1027
1028        let mut dispose = false;
1029
1030        let now = Instant::now();
1031
1032        loop {
1033            // temporary pinning of the browser receiver should be safe as we are pinning
1034            // through the already pinned self. with the receivers we can also
1035            // safely ignore exhaustion as those are fused.
1036            while let Poll::Ready(Some(msg)) = pin.from_browser.poll_recv(cx) {
1037                match msg {
1038                    HandlerMessage::Command(cmd) => {
1039                        pin.submit_external_command(cmd, now)?;
1040                    }
1041                    HandlerMessage::FetchTargets(tx) => {
1042                        pin.submit_fetch_targets(tx, now);
1043                    }
1044                    HandlerMessage::CloseBrowser(tx) => {
1045                        pin.submit_close(tx, now);
1046                    }
1047                    HandlerMessage::CreatePage(params, tx) => {
1048                        if let Some(ref id) = params.browser_context_id {
1049                            pin.browser_contexts
1050                                .insert(BrowserContext::from(id.clone()));
1051                        }
1052                        pin.create_page(params, tx);
1053                    }
1054                    HandlerMessage::GetPages(tx) => {
1055                        let pages: Vec<_> = pin
1056                            .targets
1057                            .values_mut()
1058                            .filter(|p: &&mut Target| p.is_page())
1059                            .filter_map(|target| target.get_or_create_page())
1060                            .map(|page| Page::from(page.clone()))
1061                            .collect();
1062                        let _ = tx.send(pages);
1063                    }
1064                    HandlerMessage::InsertContext(ctx) => {
1065                        if pin.default_browser_context.id().is_none() {
1066                            pin.default_browser_context = ctx.clone();
1067                        }
1068                        pin.browser_contexts.insert(ctx);
1069                    }
1070                    HandlerMessage::DisposeContext(ctx) => {
1071                        pin.browser_contexts.remove(&ctx);
1072                        pin.attached_targets.retain(|tid| {
1073                            pin.targets
1074                                .get(tid)
1075                                .and_then(|t| t.browser_context_id()) // however you expose it
1076                                .map(|id| Some(id) != ctx.id())
1077                                .unwrap_or(true)
1078                        });
1079                        pin.closing = true;
1080                        dispose = true;
1081                    }
1082                    HandlerMessage::GetPage(target_id, tx) => {
1083                        let page = pin
1084                            .targets
1085                            .get_mut(&target_id)
1086                            .and_then(|target| target.get_or_create_page())
1087                            .map(|page| Page::from(page.clone()));
1088                        let _ = tx.send(page);
1089                    }
1090                    HandlerMessage::AddEventListener(req) => {
1091                        pin.event_listeners.add_listener(req);
1092                    }
1093                }
1094            }
1095
1096            for n in (0..pin.target_ids.len()).rev() {
1097                let target_id = pin.target_ids.swap_remove(n);
1098
1099                if let Some((id, mut target)) = pin.targets.remove_entry(&target_id) {
1100                    while let Some(event) = target.poll(cx, now) {
1101                        match event {
1102                            TargetEvent::Request(req) => {
1103                                let _ = pin.submit_internal_command(
1104                                    target.target_id().clone(),
1105                                    req,
1106                                    now,
1107                                );
1108                            }
1109                            TargetEvent::Command(msg) => {
1110                                pin.on_target_message(&mut target, msg, now);
1111                            }
1112                            TargetEvent::NavigationRequest(id, req) => {
1113                                pin.submit_navigation(id, req, now);
1114                            }
1115                            TargetEvent::NavigationResult(res) => {
1116                                pin.on_navigation_lifecycle_completed(res)
1117                            }
1118                            TargetEvent::BytesConsumed(n) => {
1119                                if let Some(rem) = pin.remaining_bytes.as_mut() {
1120                                    *rem = rem.saturating_sub(n);
1121                                    if *rem == 0 {
1122                                        pin.budget_exhausted = true;
1123                                    }
1124                                }
1125                            }
1126                        }
1127                    }
1128
1129                    // poll the target's event listeners
1130                    target.event_listeners_mut().poll(cx);
1131
1132                    pin.targets.insert(id, target);
1133                    pin.target_ids.push(target_id);
1134                }
1135            }
1136
1137            // poll the handler-level event listeners once per iteration,
1138            // not once per target.
1139            pin.event_listeners_mut().poll(cx);
1140
1141            let mut done = true;
1142
1143            // Read WS messages into a temporary buffer so the conn borrow
1144            // is released before we process them (which needs &mut pin).
1145            let mut ws_msgs = Vec::new();
1146            let mut ws_err = None;
1147            {
1148                let Some(conn) = pin.conn.as_mut() else {
1149                    return Poll::Ready(Some(Err(CdpError::msg(
1150                        "connection consumed by Handler::run()",
1151                    ))));
1152                };
1153                while let Poll::Ready(Some(ev)) = Pin::new(&mut *conn).poll_next(cx) {
1154                    match ev {
1155                        Ok(msg) => ws_msgs.push(msg),
1156                        Err(err) => {
1157                            ws_err = Some(err);
1158                            break;
1159                        }
1160                    }
1161                }
1162            }
1163
1164            for boxed_msg in ws_msgs {
1165                match *boxed_msg {
1166                    Message::Response(resp) => {
1167                        pin.on_response(resp);
1168                        if pin.closing {
1169                            return Poll::Ready(None);
1170                        }
1171                    }
1172                    Message::Event(ev) => {
1173                        pin.on_event(ev);
1174                    }
1175                }
1176                done = false;
1177            }
1178
1179            if let Some(err) = ws_err {
1180                tracing::error!("WS Connection error: {:?}", err);
1181                if let CdpError::Ws(ref ws_error) = err {
1182                    match ws_error {
1183                        Error::AlreadyClosed => {
1184                            pin.closing = true;
1185                            dispose = true;
1186                        }
1187                        Error::Protocol(detail)
1188                            if detail == &ProtocolError::ResetWithoutClosingHandshake =>
1189                        {
1190                            pin.closing = true;
1191                            dispose = true;
1192                        }
1193                        _ => return Poll::Ready(Some(Err(err))),
1194                    }
1195                } else {
1196                    return Poll::Ready(Some(Err(err)));
1197                }
1198            }
1199
1200            if pin.evict_command_timeout.poll_ready(cx) {
1201                // evict all commands that timed out
1202                pin.evict_timed_out_commands(now);
1203                // evict stale network race-condition buffers and
1204                // orphaned context_ids / frame entries
1205                for t in pin.targets.values_mut() {
1206                    t.network_manager.evict_stale_entries(now);
1207                    t.frame_manager_mut().evict_stale_context_ids();
1208                }
1209            }
1210
1211            if pin.budget_exhausted {
1212                for t in pin.targets.values_mut() {
1213                    t.network_manager.set_block_all(true);
1214                }
1215            }
1216
1217            if dispose {
1218                return Poll::Ready(None);
1219            }
1220
1221            if done {
1222                // no events/responses were read from the websocket
1223                return Poll::Pending;
1224            }
1225        }
1226    }
1227}
1228
1229/// How to configure the handler
1230#[derive(Debug, Clone)]
1231pub struct HandlerConfig {
1232    /// Whether the `NetworkManager`s should ignore https errors
1233    pub ignore_https_errors: bool,
1234    /// Window and device settings
1235    pub viewport: Option<Viewport>,
1236    /// Context ids to set from the get go
1237    pub context_ids: Vec<BrowserContextId>,
1238    /// default request timeout to use
1239    pub request_timeout: Duration,
1240    /// Whether to enable request interception
1241    pub request_intercept: bool,
1242    /// Whether to enable cache
1243    pub cache_enabled: bool,
1244    /// Whether to enable Service Workers
1245    pub service_worker_enabled: bool,
1246    /// Whether to ignore visuals.
1247    pub ignore_visuals: bool,
1248    /// Whether to ignore stylesheets.
1249    pub ignore_stylesheets: bool,
1250    /// Whether to ignore Javascript only allowing critical framework or lib based rendering.
1251    pub ignore_javascript: bool,
1252    /// Whether to ignore analytics.
1253    pub ignore_analytics: bool,
1254    /// Ignore prefetch request. Defaults to true.
1255    pub ignore_prefetch: bool,
1256    /// Whether to ignore ads.
1257    pub ignore_ads: bool,
1258    /// Extra headers.
1259    pub extra_headers: Option<std::collections::HashMap<String, String>>,
1260    /// Only Html.
1261    pub only_html: bool,
1262    /// Created the first target.
1263    pub created_first_target: bool,
1264    /// The network intercept manager.
1265    pub intercept_manager: NetworkInterceptManager,
1266    /// The max bytes to receive.
1267    pub max_bytes_allowed: Option<u64>,
1268    /// Optional per-run/per-site whitelist of URL substrings (scripts/resources).
1269    pub whitelist_patterns: Option<Vec<String>>,
1270    /// Optional per-run/per-site blacklist of URL substrings (scripts/resources).
1271    pub blacklist_patterns: Option<Vec<String>>,
1272    /// Extra ABP/uBO filter rules for the adblock engine.
1273    #[cfg(feature = "adblock")]
1274    pub adblock_filter_rules: Option<Vec<String>>,
1275    /// Capacity of the channel between browser handle and handler.
1276    /// Defaults to 1000.
1277    pub channel_capacity: usize,
1278    /// Number of WebSocket connection retry attempts with exponential backoff.
1279    /// Defaults to 4.
1280    pub connection_retries: u32,
1281}
1282
1283impl Default for HandlerConfig {
1284    fn default() -> Self {
1285        Self {
1286            ignore_https_errors: true,
1287            viewport: Default::default(),
1288            context_ids: Vec::new(),
1289            request_timeout: Duration::from_millis(REQUEST_TIMEOUT),
1290            request_intercept: false,
1291            cache_enabled: true,
1292            service_worker_enabled: true,
1293            ignore_visuals: false,
1294            ignore_stylesheets: false,
1295            ignore_ads: false,
1296            ignore_javascript: false,
1297            ignore_analytics: true,
1298            ignore_prefetch: true,
1299            only_html: false,
1300            extra_headers: Default::default(),
1301            created_first_target: false,
1302            intercept_manager: NetworkInterceptManager::Unknown,
1303            max_bytes_allowed: None,
1304            whitelist_patterns: None,
1305            blacklist_patterns: None,
1306            #[cfg(feature = "adblock")]
1307            adblock_filter_rules: None,
1308            channel_capacity: 4096,
1309            connection_retries: crate::conn::DEFAULT_CONNECTION_RETRIES,
1310        }
1311    }
1312}
1313
1314/// Wraps the sender half of the channel who requested a navigation
1315#[derive(Debug)]
1316pub struct NavigationInProgress<T> {
1317    /// Marker to indicate whether a navigation lifecycle has completed
1318    navigated: bool,
1319    /// The response of the issued navigation request
1320    response: Option<Response>,
1321    /// Sender who initiated the navigation request
1322    tx: OneshotSender<T>,
1323}
1324
1325impl<T> NavigationInProgress<T> {
1326    fn new(tx: OneshotSender<T>) -> Self {
1327        Self {
1328            navigated: false,
1329            response: None,
1330            tx,
1331        }
1332    }
1333
1334    /// The response to the cdp request has arrived
1335    fn set_response(&mut self, resp: Response) {
1336        self.response = Some(resp);
1337    }
1338
1339    /// The navigation process has finished, the page finished loading.
1340    fn set_navigated(&mut self) {
1341        self.navigated = true;
1342    }
1343}
1344
1345/// Request type for navigation
1346#[derive(Debug)]
1347enum NavigationRequest {
1348    /// Represents a simple `NavigateParams` ("Page.navigate")
1349    Navigate(NavigationInProgress<Result<Response>>),
1350    // TODO are there more?
1351}
1352
1353/// Different kind of submitted request submitted from the  `Handler` to the
1354/// `Connection` and being waited on for the response.
1355#[derive(Debug)]
1356enum PendingRequest {
1357    /// A Request to create a new `Target` that results in the creation of a
1358    /// `Page` that represents a browser page.
1359    CreateTarget(OneshotSender<Result<Page>>),
1360    /// A Request to fetch old `Target`s created before connection
1361    GetTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1362    /// A Request to navigate a specific `Target`.
1363    ///
1364    /// Navigation requests are not automatically completed once the response to
1365    /// the raw cdp navigation request (like `NavigateParams`) arrives, but only
1366    /// after the `Target` notifies the `Handler` that the `Page` has finished
1367    /// loading, which comes after the response.
1368    Navigate(NavigationId),
1369    /// A common request received via a channel (`Page`).
1370    ExternalCommand(OneshotSender<Result<Response>>),
1371    /// Requests that are initiated directly from a `Target` (all the
1372    /// initialization commands).
1373    InternalCommand(TargetId),
1374    // A Request to close the browser.
1375    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1376}
1377
1378/// Events used internally to communicate with the handler, which are executed
1379/// in the background
1380// TODO rename to BrowserMessage
1381#[derive(Debug)]
1382pub(crate) enum HandlerMessage {
1383    CreatePage(CreateTargetParams, OneshotSender<Result<Page>>),
1384    FetchTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1385    InsertContext(BrowserContext),
1386    DisposeContext(BrowserContext),
1387    GetPages(OneshotSender<Vec<Page>>),
1388    Command(CommandMessage),
1389    GetPage(TargetId, OneshotSender<Option<Page>>),
1390    AddEventListener(EventListenerRequest),
1391    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1392}
1393
1394#[cfg(test)]
1395mod tests {
1396    use super::*;
1397    use chromiumoxide_cdp::cdp::browser_protocol::target::{AttachToTargetReturns, TargetInfo};
1398
1399    #[test]
1400    fn attach_to_target_response_sets_session_id_before_event_arrives() {
1401        let info = TargetInfo::builder()
1402            .target_id("target-1".to_string())
1403            .r#type("page")
1404            .title("")
1405            .url("about:blank")
1406            .attached(false)
1407            .can_access_opener(false)
1408            .build()
1409            .expect("target info");
1410        let mut target = Target::new(info, TargetConfig::default(), BrowserContext::default());
1411        let method: MethodId = AttachToTargetParams::IDENTIFIER.into();
1412        let result = serde_json::to_value(AttachToTargetReturns::new("session-1".to_string()))
1413            .expect("attach result");
1414        let resp = Response {
1415            id: CallId::new(1),
1416            result: Some(result),
1417            error: None,
1418        };
1419
1420        maybe_store_attach_session_id(&mut target, &method, &resp);
1421
1422        assert_eq!(
1423            target.session_id().map(AsRef::as_ref),
1424            Some("session-1"),
1425            "attach response should seed the flat session id even before Target.attachedToTarget"
1426        );
1427    }
1428}