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        let tid = target.target_id().clone();
526        self.target_ids.push(tid.clone());
527        self.targets.insert(tid, target);
528    }
529
530    /// A new session is attached to a target
531    fn on_attached_to_target(&mut self, event: Box<EventAttachedToTarget>) {
532        let session = Session::new(event.session_id.clone(), event.target_info.target_id);
533        if let Some(target) = self.targets.get_mut(session.target_id()) {
534            target.set_session_id(session.session_id().clone())
535        }
536        self.sessions.insert(event.session_id, session);
537    }
538
539    /// The session was detached from target.
540    /// Can be issued multiple times per target if multiple session have been
541    /// attached to it.
542    fn on_detached_from_target(&mut self, event: EventDetachedFromTarget) {
543        // remove the session
544        if let Some(session) = self.sessions.remove(&event.session_id) {
545            if let Some(target) = self.targets.get_mut(session.target_id()) {
546                target.session_id_mut().take();
547            }
548        }
549    }
550
551    /// Fired when the target was destroyed in the browser
552    fn on_target_destroyed(&mut self, event: EventTargetDestroyed) {
553        self.attached_targets.remove(&event.target_id);
554
555        if let Some(target) = self.targets.remove(&event.target_id) {
556            // TODO shutdown?
557            if let Some(session) = target.session_id() {
558                self.sessions.remove(session);
559            }
560        }
561    }
562
563    /// House keeping of commands
564    ///
565    /// Remove all commands where `now` > `timestamp of command starting point +
566    /// request timeout` and notify the senders that their request timed out.
567    fn evict_timed_out_commands(&mut self, now: Instant) {
568        let deadline = match now.checked_sub(self.config.request_timeout) {
569            Some(d) => d,
570            None => return,
571        };
572
573        let timed_out: Vec<_> = self
574            .pending_commands
575            .iter()
576            .filter(|(_, (_, _, timestamp))| *timestamp < deadline)
577            .map(|(k, _)| *k)
578            .collect();
579
580        for call in timed_out {
581            if let Some((req, _, _)) = self.pending_commands.remove(&call) {
582                match req {
583                    PendingRequest::CreateTarget(tx) => {
584                        let _ = tx.send(Err(CdpError::Timeout));
585                    }
586                    PendingRequest::GetTargets(tx) => {
587                        let _ = tx.send(Err(CdpError::Timeout));
588                    }
589                    PendingRequest::Navigate(nav) => {
590                        if let Some(nav) = self.navigations.remove(&nav) {
591                            match nav {
592                                NavigationRequest::Navigate(nav) => {
593                                    let _ = nav.tx.send(Err(CdpError::Timeout));
594                                }
595                            }
596                        }
597                    }
598                    PendingRequest::ExternalCommand(tx) => {
599                        let _ = tx.send(Err(CdpError::Timeout));
600                    }
601                    PendingRequest::InternalCommand(_) => {}
602                    PendingRequest::CloseBrowser(tx) => {
603                        let _ = tx.send(Err(CdpError::Timeout));
604                    }
605                }
606            }
607        }
608    }
609
610    pub fn event_listeners_mut(&mut self) -> &mut EventListeners {
611        &mut self.event_listeners
612    }
613
614    // ------------------------------------------------------------------
615    //  Tokio-native async entry point
616    // ------------------------------------------------------------------
617
618    /// Run the handler as a fully async tokio task.
619    ///
620    /// This is the high-performance alternative to polling `Handler` as a
621    /// `Stream`.  Internally it:
622    ///
623    /// * Splits the WebSocket into independent read/write halves — the
624    ///   writer runs in its own tokio task with natural batching.
625    /// * Uses `tokio::select!` to multiplex the browser channel, page
626    ///   notifications, WebSocket reads, the eviction timer, and writer
627    ///   health.
628    /// * Drains every target's page channel via `try_recv()` (non-blocking)
629    ///   after each event, with an `Arc<Notify>` ensuring the select loop
630    ///   wakes up whenever a page sends a message.
631    ///
632    /// # Usage
633    ///
634    /// ```rust,no_run
635    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
636    /// use chromiumoxide::Browser;
637    /// let (browser, handler) = Browser::launch(Default::default()).await?;
638    /// let handler_task = tokio::spawn(handler.run());
639    /// // … use browser …
640    /// # Ok(())
641    /// # }
642    /// ```
643    pub async fn run(mut self) -> Result<()> {
644        use chromiumoxide_types::Message;
645        use tokio::time::MissedTickBehavior;
646        use tokio_tungstenite::tungstenite::{self, error::ProtocolError};
647
648        // --- set up page notification ---
649        let page_wake = Arc::new(Notify::new());
650        self.page_wake = Some(page_wake.clone());
651
652        // --- split WebSocket ---
653        let conn = self
654            .conn
655            .take()
656            .ok_or_else(|| CdpError::msg("Handler::run() called with no connection"))?;
657        let async_conn = conn.into_async();
658        let mut ws_reader = async_conn.reader;
659        let ws_tx = async_conn.cmd_tx;
660        let mut writer_handle = async_conn.writer_handle;
661        let mut next_call_id = async_conn.next_id;
662
663        // Helper to mint call-ids without &mut self.conn.
664        let mut alloc_call_id = || {
665            let id = chromiumoxide_types::CallId::new(next_call_id);
666            next_call_id = next_call_id.wrapping_add(1);
667            id
668        };
669
670        // --- eviction timer ---
671        let mut evict_timer = tokio::time::interval_at(
672            tokio::time::Instant::now() + self.config.request_timeout,
673            self.config.request_timeout,
674        );
675        evict_timer.set_missed_tick_behavior(MissedTickBehavior::Delay);
676
677        // Helper closure: submit a MethodCall through the WS writer.
678        macro_rules! ws_submit {
679            ($method:expr, $session_id:expr, $params:expr) => {{
680                let id = alloc_call_id();
681                let call = chromiumoxide_types::MethodCall {
682                    id,
683                    method: $method,
684                    session_id: $session_id,
685                    params: $params,
686                };
687                match ws_tx.try_send(call) {
688                    Ok(()) => Ok::<_, CdpError>(id),
689                    Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
690                        tracing::warn!("WS command channel full — dropping command");
691                        Err(CdpError::msg("WS command channel full"))
692                    }
693                    Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
694                        Err(CdpError::msg("WS writer closed"))
695                    }
696                }
697            }};
698        }
699
700        // ---- main event loop ----
701        loop {
702            let now = std::time::Instant::now();
703
704            // 1. Drain all target page channels (non-blocking) & advance
705            //    state machines.
706            //
707            // Budget: drain at most 128 messages per target per iteration
708            // so a single chatty page cannot starve the rest.
709            const PER_TARGET_DRAIN_BUDGET: usize = 128;
710
711            for n in (0..self.target_ids.len()).rev() {
712                let target_id = self.target_ids.swap_remove(n);
713
714                if let Some((id, mut target)) = self.targets.remove_entry(&target_id) {
715                    // Drain page channel (non-blocking — waker is the Notify).
716                    {
717                        let mut msgs = Vec::new();
718                        if let Some(handle) = target.page_mut() {
719                            while msgs.len() < PER_TARGET_DRAIN_BUDGET {
720                                match handle.rx.try_recv() {
721                                    Ok(msg) => msgs.push(msg),
722                                    Err(_) => break,
723                                }
724                            }
725                        }
726                        for msg in msgs {
727                            target.on_page_message(msg);
728                        }
729                    }
730
731                    // Advance target state machine & process events.
732                    while let Some(event) = target.advance(now) {
733                        match event {
734                            TargetEvent::Request(req) => {
735                                if let Ok(call_id) =
736                                    ws_submit!(req.method.clone(), req.session_id, req.params)
737                                {
738                                    self.pending_commands.insert(
739                                        call_id,
740                                        (
741                                            PendingRequest::InternalCommand(
742                                                target.target_id().clone(),
743                                            ),
744                                            req.method,
745                                            now,
746                                        ),
747                                    );
748                                }
749                            }
750                            TargetEvent::Command(msg) => {
751                                if msg.is_navigation() {
752                                    let (req, tx) = msg.split();
753                                    let nav_id = self.next_navigation_id();
754                                    target.goto(FrameRequestedNavigation::new(
755                                        nav_id,
756                                        req.clone(),
757                                        self.config.request_timeout,
758                                    ));
759                                    if let Ok(call_id) =
760                                        ws_submit!(req.method.clone(), req.session_id, req.params)
761                                    {
762                                        self.pending_commands.insert(
763                                            call_id,
764                                            (PendingRequest::Navigate(nav_id), req.method, now),
765                                        );
766                                    }
767                                    self.navigations.insert(
768                                        nav_id,
769                                        NavigationRequest::Navigate(NavigationInProgress::new(tx)),
770                                    );
771                                } else if let Ok(call_id) = ws_submit!(
772                                    msg.method.clone(),
773                                    msg.session_id.map(Into::into),
774                                    msg.params
775                                ) {
776                                    self.pending_commands.insert(
777                                        call_id,
778                                        (
779                                            PendingRequest::ExternalCommand(msg.sender),
780                                            msg.method,
781                                            now,
782                                        ),
783                                    );
784                                }
785                            }
786                            TargetEvent::NavigationRequest(nav_id, req) => {
787                                if let Ok(call_id) =
788                                    ws_submit!(req.method.clone(), req.session_id, req.params)
789                                {
790                                    self.pending_commands.insert(
791                                        call_id,
792                                        (PendingRequest::Navigate(nav_id), req.method, now),
793                                    );
794                                }
795                            }
796                            TargetEvent::NavigationResult(res) => {
797                                self.on_navigation_lifecycle_completed(res);
798                            }
799                            TargetEvent::BytesConsumed(n) => {
800                                if let Some(rem) = self.remaining_bytes.as_mut() {
801                                    *rem = rem.saturating_sub(n);
802                                    if *rem == 0 {
803                                        self.budget_exhausted = true;
804                                    }
805                                }
806                            }
807                        }
808                    }
809
810                    // Flush event listeners (no Context needed).
811                    target.event_listeners_mut().flush();
812
813                    self.targets.insert(id, target);
814                    self.target_ids.push(target_id);
815                }
816            }
817
818            // Flush handler-level event listeners.
819            self.event_listeners.flush();
820
821            if self.budget_exhausted {
822                for t in self.targets.values_mut() {
823                    t.network_manager.set_block_all(true);
824                }
825            }
826
827            if self.closing {
828                break;
829            }
830
831            // 2. Multiplex all event sources via tokio::select!
832            tokio::select! {
833                msg = self.from_browser.recv() => {
834                    match msg {
835                        Some(msg) => {
836                            match msg {
837                                HandlerMessage::Command(cmd) => {
838                                    if let Ok(call_id) = ws_submit!(
839                                        cmd.method.clone(),
840                                        cmd.session_id.map(Into::into),
841                                        cmd.params
842                                    ) {
843                                        self.pending_commands.insert(
844                                            call_id,
845                                            (PendingRequest::ExternalCommand(cmd.sender), cmd.method, now),
846                                        );
847                                    }
848                                }
849                                HandlerMessage::FetchTargets(tx) => {
850                                    let msg = TARGET_PARAMS_ID.clone();
851                                    if let Ok(call_id) = ws_submit!(msg.0.clone(), None, msg.1) {
852                                        self.pending_commands.insert(
853                                            call_id,
854                                            (PendingRequest::GetTargets(tx), msg.0, now),
855                                        );
856                                    }
857                                }
858                                HandlerMessage::CloseBrowser(tx) => {
859                                    let close_msg = CLOSE_PARAMS_ID.clone();
860                                    if let Ok(call_id) = ws_submit!(close_msg.0.clone(), None, close_msg.1) {
861                                        self.pending_commands.insert(
862                                            call_id,
863                                            (PendingRequest::CloseBrowser(tx), close_msg.0, now),
864                                        );
865                                    }
866                                }
867                                HandlerMessage::CreatePage(params, tx) => {
868                                    if let Some(ref id) = params.browser_context_id {
869                                        self.browser_contexts.insert(BrowserContext::from(id.clone()));
870                                    }
871                                    self.create_page_async(params, tx, &mut alloc_call_id, &ws_tx, now);
872                                }
873                                HandlerMessage::GetPages(tx) => {
874                                    let pages: Vec<_> = self.targets.values_mut()
875                                        .filter(|p| p.is_page())
876                                        .filter_map(|target| target.get_or_create_page())
877                                        .map(|page| Page::from(page.clone()))
878                                        .collect();
879                                    let _ = tx.send(pages);
880                                }
881                                HandlerMessage::InsertContext(ctx) => {
882                                    if self.default_browser_context.id().is_none() {
883                                        self.default_browser_context = ctx.clone();
884                                    }
885                                    self.browser_contexts.insert(ctx);
886                                }
887                                HandlerMessage::DisposeContext(ctx) => {
888                                    self.browser_contexts.remove(&ctx);
889                                    self.attached_targets.retain(|tid| {
890                                        self.targets.get(tid)
891                                            .and_then(|t| t.browser_context_id())
892                                            .map(|id| Some(id) != ctx.id())
893                                            .unwrap_or(true)
894                                    });
895                                    self.closing = true;
896                                }
897                                HandlerMessage::GetPage(target_id, tx) => {
898                                    let page = self.targets.get_mut(&target_id)
899                                        .and_then(|target| target.get_or_create_page())
900                                        .map(|page| Page::from(page.clone()));
901                                    let _ = tx.send(page);
902                                }
903                                HandlerMessage::AddEventListener(req) => {
904                                    self.event_listeners.add_listener(req);
905                                }
906                            }
907                        }
908                        None => break, // browser handle dropped
909                    }
910                }
911
912                frame = ws_reader.next_message() => {
913                    match frame {
914                        Some(Ok(boxed_msg)) => match *boxed_msg {
915                            Message::Response(resp) => {
916                                self.on_response(resp);
917                            }
918                            Message::Event(ev) => {
919                                self.on_event(ev);
920                            }
921                        },
922                        Some(Err(err)) => {
923                            tracing::error!("WS Connection error: {:?}", err);
924                            if let CdpError::Ws(ref ws_error) = err {
925                                match ws_error {
926                                    tungstenite::Error::AlreadyClosed => break,
927                                    tungstenite::Error::Protocol(detail)
928                                        if detail == &ProtocolError::ResetWithoutClosingHandshake =>
929                                    {
930                                        break;
931                                    }
932                                    _ => return Err(err),
933                                }
934                            } else {
935                                return Err(err);
936                            }
937                        }
938                        None => break, // WS closed
939                    }
940                }
941
942                _ = page_wake.notified() => {
943                    // A page sent a message — loop back to drain targets.
944                }
945
946                _ = evict_timer.tick() => {
947                    self.evict_timed_out_commands(now);
948                    for t in self.targets.values_mut() {
949                        t.network_manager.evict_stale_entries(now);
950                        t.frame_manager_mut().evict_stale_context_ids();
951                    }
952                }
953
954                result = &mut writer_handle => {
955                    // WS writer exited — propagate error or break.
956                    match result {
957                        Ok(Ok(())) => break,
958                        Ok(Err(e)) => return Err(e),
959                        Err(e) => return Err(CdpError::msg(format!("WS writer panicked: {e}"))),
960                    }
961                }
962            }
963        }
964
965        writer_handle.abort();
966        Ok(())
967    }
968
969    /// `create_page` variant for the `run()` path that submits via `ws_tx`.
970    fn create_page_async(
971        &mut self,
972        params: CreateTargetParams,
973        tx: OneshotSender<Result<Page>>,
974        alloc_call_id: &mut impl FnMut() -> chromiumoxide_types::CallId,
975        ws_tx: &tokio::sync::mpsc::Sender<chromiumoxide_types::MethodCall>,
976        now: std::time::Instant,
977    ) {
978        let about_blank = params.url == "about:blank";
979        let http_check =
980            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
981
982        if about_blank || http_check {
983            let method = params.identifier();
984            match serde_json::to_value(params) {
985                Ok(params) => {
986                    let id = alloc_call_id();
987                    let call = chromiumoxide_types::MethodCall {
988                        id,
989                        method: method.clone(),
990                        session_id: None,
991                        params,
992                    };
993                    match ws_tx.try_send(call) {
994                        Ok(()) => {
995                            self.pending_commands
996                                .insert(id, (PendingRequest::CreateTarget(tx), method, now));
997                        }
998                        Err(_) => {
999                            let _ = tx
1000                                .send(Err(CdpError::msg("WS command channel full or closed")))
1001                                .ok();
1002                        }
1003                    }
1004                }
1005                Err(err) => {
1006                    let _ = tx.send(Err(err.into())).ok();
1007                }
1008            }
1009        } else {
1010            let _ = tx.send(Err(CdpError::NotFound)).ok();
1011        }
1012    }
1013}
1014
1015impl Stream for Handler {
1016    type Item = Result<()>;
1017
1018    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1019        let pin = self.get_mut();
1020
1021        let mut dispose = false;
1022
1023        let now = Instant::now();
1024
1025        loop {
1026            // temporary pinning of the browser receiver should be safe as we are pinning
1027            // through the already pinned self. with the receivers we can also
1028            // safely ignore exhaustion as those are fused.
1029            while let Poll::Ready(Some(msg)) = pin.from_browser.poll_recv(cx) {
1030                match msg {
1031                    HandlerMessage::Command(cmd) => {
1032                        pin.submit_external_command(cmd, now)?;
1033                    }
1034                    HandlerMessage::FetchTargets(tx) => {
1035                        pin.submit_fetch_targets(tx, now);
1036                    }
1037                    HandlerMessage::CloseBrowser(tx) => {
1038                        pin.submit_close(tx, now);
1039                    }
1040                    HandlerMessage::CreatePage(params, tx) => {
1041                        if let Some(ref id) = params.browser_context_id {
1042                            pin.browser_contexts
1043                                .insert(BrowserContext::from(id.clone()));
1044                        }
1045                        pin.create_page(params, tx);
1046                    }
1047                    HandlerMessage::GetPages(tx) => {
1048                        let pages: Vec<_> = pin
1049                            .targets
1050                            .values_mut()
1051                            .filter(|p: &&mut Target| p.is_page())
1052                            .filter_map(|target| target.get_or_create_page())
1053                            .map(|page| Page::from(page.clone()))
1054                            .collect();
1055                        let _ = tx.send(pages);
1056                    }
1057                    HandlerMessage::InsertContext(ctx) => {
1058                        if pin.default_browser_context.id().is_none() {
1059                            pin.default_browser_context = ctx.clone();
1060                        }
1061                        pin.browser_contexts.insert(ctx);
1062                    }
1063                    HandlerMessage::DisposeContext(ctx) => {
1064                        pin.browser_contexts.remove(&ctx);
1065                        pin.attached_targets.retain(|tid| {
1066                            pin.targets
1067                                .get(tid)
1068                                .and_then(|t| t.browser_context_id()) // however you expose it
1069                                .map(|id| Some(id) != ctx.id())
1070                                .unwrap_or(true)
1071                        });
1072                        pin.closing = true;
1073                        dispose = true;
1074                    }
1075                    HandlerMessage::GetPage(target_id, tx) => {
1076                        let page = pin
1077                            .targets
1078                            .get_mut(&target_id)
1079                            .and_then(|target| target.get_or_create_page())
1080                            .map(|page| Page::from(page.clone()));
1081                        let _ = tx.send(page);
1082                    }
1083                    HandlerMessage::AddEventListener(req) => {
1084                        pin.event_listeners.add_listener(req);
1085                    }
1086                }
1087            }
1088
1089            for n in (0..pin.target_ids.len()).rev() {
1090                let target_id = pin.target_ids.swap_remove(n);
1091
1092                if let Some((id, mut target)) = pin.targets.remove_entry(&target_id) {
1093                    while let Some(event) = target.poll(cx, now) {
1094                        match event {
1095                            TargetEvent::Request(req) => {
1096                                let _ = pin.submit_internal_command(
1097                                    target.target_id().clone(),
1098                                    req,
1099                                    now,
1100                                );
1101                            }
1102                            TargetEvent::Command(msg) => {
1103                                pin.on_target_message(&mut target, msg, now);
1104                            }
1105                            TargetEvent::NavigationRequest(id, req) => {
1106                                pin.submit_navigation(id, req, now);
1107                            }
1108                            TargetEvent::NavigationResult(res) => {
1109                                pin.on_navigation_lifecycle_completed(res)
1110                            }
1111                            TargetEvent::BytesConsumed(n) => {
1112                                if let Some(rem) = pin.remaining_bytes.as_mut() {
1113                                    *rem = rem.saturating_sub(n);
1114                                    if *rem == 0 {
1115                                        pin.budget_exhausted = true;
1116                                    }
1117                                }
1118                            }
1119                        }
1120                    }
1121
1122                    // poll the target's event listeners
1123                    target.event_listeners_mut().poll(cx);
1124
1125                    pin.targets.insert(id, target);
1126                    pin.target_ids.push(target_id);
1127                }
1128            }
1129
1130            // poll the handler-level event listeners once per iteration,
1131            // not once per target.
1132            pin.event_listeners_mut().poll(cx);
1133
1134            let mut done = true;
1135
1136            // Read WS messages into a temporary buffer so the conn borrow
1137            // is released before we process them (which needs &mut pin).
1138            let mut ws_msgs = Vec::new();
1139            let mut ws_err = None;
1140            {
1141                let Some(conn) = pin.conn.as_mut() else {
1142                    return Poll::Ready(Some(Err(CdpError::msg(
1143                        "connection consumed by Handler::run()",
1144                    ))));
1145                };
1146                while let Poll::Ready(Some(ev)) = Pin::new(&mut *conn).poll_next(cx) {
1147                    match ev {
1148                        Ok(msg) => ws_msgs.push(msg),
1149                        Err(err) => {
1150                            ws_err = Some(err);
1151                            break;
1152                        }
1153                    }
1154                }
1155            }
1156
1157            for boxed_msg in ws_msgs {
1158                match *boxed_msg {
1159                    Message::Response(resp) => {
1160                        pin.on_response(resp);
1161                        if pin.closing {
1162                            return Poll::Ready(None);
1163                        }
1164                    }
1165                    Message::Event(ev) => {
1166                        pin.on_event(ev);
1167                    }
1168                }
1169                done = false;
1170            }
1171
1172            if let Some(err) = ws_err {
1173                tracing::error!("WS Connection error: {:?}", err);
1174                if let CdpError::Ws(ref ws_error) = err {
1175                    match ws_error {
1176                        Error::AlreadyClosed => {
1177                            pin.closing = true;
1178                            dispose = true;
1179                        }
1180                        Error::Protocol(detail)
1181                            if detail == &ProtocolError::ResetWithoutClosingHandshake =>
1182                        {
1183                            pin.closing = true;
1184                            dispose = true;
1185                        }
1186                        _ => return Poll::Ready(Some(Err(err))),
1187                    }
1188                } else {
1189                    return Poll::Ready(Some(Err(err)));
1190                }
1191            }
1192
1193            if pin.evict_command_timeout.poll_ready(cx) {
1194                // evict all commands that timed out
1195                pin.evict_timed_out_commands(now);
1196                // evict stale network race-condition buffers and
1197                // orphaned context_ids / frame entries
1198                for t in pin.targets.values_mut() {
1199                    t.network_manager.evict_stale_entries(now);
1200                    t.frame_manager_mut().evict_stale_context_ids();
1201                }
1202            }
1203
1204            if pin.budget_exhausted {
1205                for t in pin.targets.values_mut() {
1206                    t.network_manager.set_block_all(true);
1207                }
1208            }
1209
1210            if dispose {
1211                return Poll::Ready(None);
1212            }
1213
1214            if done {
1215                // no events/responses were read from the websocket
1216                return Poll::Pending;
1217            }
1218        }
1219    }
1220}
1221
1222/// How to configure the handler
1223#[derive(Debug, Clone)]
1224pub struct HandlerConfig {
1225    /// Whether the `NetworkManager`s should ignore https errors
1226    pub ignore_https_errors: bool,
1227    /// Window and device settings
1228    pub viewport: Option<Viewport>,
1229    /// Context ids to set from the get go
1230    pub context_ids: Vec<BrowserContextId>,
1231    /// default request timeout to use
1232    pub request_timeout: Duration,
1233    /// Whether to enable request interception
1234    pub request_intercept: bool,
1235    /// Whether to enable cache
1236    pub cache_enabled: bool,
1237    /// Whether to enable Service Workers
1238    pub service_worker_enabled: bool,
1239    /// Whether to ignore visuals.
1240    pub ignore_visuals: bool,
1241    /// Whether to ignore stylesheets.
1242    pub ignore_stylesheets: bool,
1243    /// Whether to ignore Javascript only allowing critical framework or lib based rendering.
1244    pub ignore_javascript: bool,
1245    /// Whether to ignore analytics.
1246    pub ignore_analytics: bool,
1247    /// Ignore prefetch request. Defaults to true.
1248    pub ignore_prefetch: bool,
1249    /// Whether to ignore ads.
1250    pub ignore_ads: bool,
1251    /// Extra headers.
1252    pub extra_headers: Option<std::collections::HashMap<String, String>>,
1253    /// Only Html.
1254    pub only_html: bool,
1255    /// Created the first target.
1256    pub created_first_target: bool,
1257    /// The network intercept manager.
1258    pub intercept_manager: NetworkInterceptManager,
1259    /// The max bytes to receive.
1260    pub max_bytes_allowed: Option<u64>,
1261    /// Optional per-run/per-site whitelist of URL substrings (scripts/resources).
1262    pub whitelist_patterns: Option<Vec<String>>,
1263    /// Optional per-run/per-site blacklist of URL substrings (scripts/resources).
1264    pub blacklist_patterns: Option<Vec<String>>,
1265    /// Extra ABP/uBO filter rules for the adblock engine.
1266    #[cfg(feature = "adblock")]
1267    pub adblock_filter_rules: Option<Vec<String>>,
1268    /// Capacity of the channel between browser handle and handler.
1269    /// Defaults to 1000.
1270    pub channel_capacity: usize,
1271    /// Number of WebSocket connection retry attempts with exponential backoff.
1272    /// Defaults to 4.
1273    pub connection_retries: u32,
1274}
1275
1276impl Default for HandlerConfig {
1277    fn default() -> Self {
1278        Self {
1279            ignore_https_errors: true,
1280            viewport: Default::default(),
1281            context_ids: Vec::new(),
1282            request_timeout: Duration::from_millis(REQUEST_TIMEOUT),
1283            request_intercept: false,
1284            cache_enabled: true,
1285            service_worker_enabled: true,
1286            ignore_visuals: false,
1287            ignore_stylesheets: false,
1288            ignore_ads: false,
1289            ignore_javascript: false,
1290            ignore_analytics: true,
1291            ignore_prefetch: true,
1292            only_html: false,
1293            extra_headers: Default::default(),
1294            created_first_target: false,
1295            intercept_manager: NetworkInterceptManager::Unknown,
1296            max_bytes_allowed: None,
1297            whitelist_patterns: None,
1298            blacklist_patterns: None,
1299            #[cfg(feature = "adblock")]
1300            adblock_filter_rules: None,
1301            channel_capacity: 4096,
1302            connection_retries: crate::conn::DEFAULT_CONNECTION_RETRIES,
1303        }
1304    }
1305}
1306
1307/// Wraps the sender half of the channel who requested a navigation
1308#[derive(Debug)]
1309pub struct NavigationInProgress<T> {
1310    /// Marker to indicate whether a navigation lifecycle has completed
1311    navigated: bool,
1312    /// The response of the issued navigation request
1313    response: Option<Response>,
1314    /// Sender who initiated the navigation request
1315    tx: OneshotSender<T>,
1316}
1317
1318impl<T> NavigationInProgress<T> {
1319    fn new(tx: OneshotSender<T>) -> Self {
1320        Self {
1321            navigated: false,
1322            response: None,
1323            tx,
1324        }
1325    }
1326
1327    /// The response to the cdp request has arrived
1328    fn set_response(&mut self, resp: Response) {
1329        self.response = Some(resp);
1330    }
1331
1332    /// The navigation process has finished, the page finished loading.
1333    fn set_navigated(&mut self) {
1334        self.navigated = true;
1335    }
1336}
1337
1338/// Request type for navigation
1339#[derive(Debug)]
1340enum NavigationRequest {
1341    /// Represents a simple `NavigateParams` ("Page.navigate")
1342    Navigate(NavigationInProgress<Result<Response>>),
1343    // TODO are there more?
1344}
1345
1346/// Different kind of submitted request submitted from the  `Handler` to the
1347/// `Connection` and being waited on for the response.
1348#[derive(Debug)]
1349enum PendingRequest {
1350    /// A Request to create a new `Target` that results in the creation of a
1351    /// `Page` that represents a browser page.
1352    CreateTarget(OneshotSender<Result<Page>>),
1353    /// A Request to fetch old `Target`s created before connection
1354    GetTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1355    /// A Request to navigate a specific `Target`.
1356    ///
1357    /// Navigation requests are not automatically completed once the response to
1358    /// the raw cdp navigation request (like `NavigateParams`) arrives, but only
1359    /// after the `Target` notifies the `Handler` that the `Page` has finished
1360    /// loading, which comes after the response.
1361    Navigate(NavigationId),
1362    /// A common request received via a channel (`Page`).
1363    ExternalCommand(OneshotSender<Result<Response>>),
1364    /// Requests that are initiated directly from a `Target` (all the
1365    /// initialization commands).
1366    InternalCommand(TargetId),
1367    // A Request to close the browser.
1368    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1369}
1370
1371/// Events used internally to communicate with the handler, which are executed
1372/// in the background
1373// TODO rename to BrowserMessage
1374#[derive(Debug)]
1375pub(crate) enum HandlerMessage {
1376    CreatePage(CreateTargetParams, OneshotSender<Result<Page>>),
1377    FetchTargets(OneshotSender<Result<Vec<TargetInfo>>>),
1378    InsertContext(BrowserContext),
1379    DisposeContext(BrowserContext),
1380    GetPages(OneshotSender<Vec<Page>>),
1381    Command(CommandMessage),
1382    GetPage(TargetId, OneshotSender<Option<Page>>),
1383    AddEventListener(EventListenerRequest),
1384    CloseBrowser(OneshotSender<Result<CloseReturns>>),
1385}
1386
1387#[cfg(test)]
1388mod tests {
1389    use super::*;
1390    use chromiumoxide_cdp::cdp::browser_protocol::target::{AttachToTargetReturns, TargetInfo};
1391
1392    #[test]
1393    fn attach_to_target_response_sets_session_id_before_event_arrives() {
1394        let info = TargetInfo::builder()
1395            .target_id("target-1".to_string())
1396            .r#type("page")
1397            .title("")
1398            .url("about:blank")
1399            .attached(false)
1400            .can_access_opener(false)
1401            .build()
1402            .expect("target info");
1403        let mut target = Target::new(info, TargetConfig::default(), BrowserContext::default());
1404        let method: MethodId = AttachToTargetParams::IDENTIFIER.into();
1405        let result = serde_json::to_value(AttachToTargetReturns::new("session-1".to_string()))
1406            .expect("attach result");
1407        let resp = Response {
1408            id: CallId::new(1),
1409            result: Some(result),
1410            error: None,
1411        };
1412
1413        maybe_store_attach_session_id(&mut target, &method, &resp);
1414
1415        assert_eq!(
1416            target.session_id().map(AsRef::as_ref),
1417            Some("session-1"),
1418            "attach response should seed the flat session id even before Target.attachedToTarget"
1419        );
1420    }
1421}