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::channel::mpsc::Receiver;
10use futures::channel::oneshot::Sender as OneshotSender;
11use futures::stream::{Fuse, Stream, StreamExt};
12use futures::task::{Context, Poll};
13use hashbrown::{HashMap, HashSet};
14pub(crate) use page::PageInner;
15use spider_network_blocker::intercept_manager::NetworkInterceptManager;
16use std::pin::Pin;
17use std::time::{Duration, Instant};
18use tokio_tungstenite::tungstenite::error::ProtocolError;
19use tokio_tungstenite::tungstenite::Error;
20
21use crate::cmd::{to_command_response, CommandMessage};
22use crate::conn::Connection;
23use crate::error::{CdpError, Result};
24use crate::handler::browser::BrowserContext;
25use crate::handler::frame::FrameRequestedNavigation;
26use crate::handler::frame::{NavigationError, NavigationId, NavigationOk};
27use crate::handler::job::PeriodicJob;
28use crate::handler::session::Session;
29use crate::handler::target::TargetEvent;
30use crate::handler::target::{Target, TargetConfig};
31use crate::handler::viewport::Viewport;
32use crate::page::Page;
33
34/// Standard timeout in MS
35pub const REQUEST_TIMEOUT: u64 = 30_000;
36
37pub mod blockers;
38pub mod browser;
39pub mod commandfuture;
40pub mod domworld;
41pub mod emulation;
42pub mod frame;
43pub mod http;
44pub mod httpfuture;
45mod job;
46pub mod network;
47mod page;
48mod session;
49pub mod target;
50pub mod target_message_future;
51pub mod viewport;
52
53/// The handler that monitors the state of the chromium browser and drives all
54/// the requests and events.
55#[must_use = "streams do nothing unless polled"]
56#[derive(Debug)]
57pub struct Handler {
58    pub default_browser_context: BrowserContext,
59    pub browser_contexts: HashSet<BrowserContext>,
60    /// Commands that are being processed and awaiting a response from the
61    /// chromium instance together with the timestamp when the request
62    /// started.
63    pending_commands: FnvHashMap<CallId, (PendingRequest, MethodId, Instant)>,
64    /// Connection to the browser instance
65    from_browser: Fuse<Receiver<HandlerMessage>>,
66    /// Used to loop over all targets in a consistent manner
67    target_ids: Vec<TargetId>,
68    /// The created and attached targets
69    targets: HashMap<TargetId, Target>,
70    /// Currently queued in navigations for targets
71    navigations: FnvHashMap<NavigationId, NavigationRequest>,
72    /// Keeps track of all the current active sessions
73    ///
74    /// There can be multiple sessions per target.
75    sessions: HashMap<SessionId, Session>,
76    /// The websocket connection to the chromium instance
77    conn: Connection<CdpEventMessage>,
78    /// Evicts timed out requests periodically
79    evict_command_timeout: PeriodicJob,
80    /// The internal identifier for a specific navigation
81    next_navigation_id: usize,
82    /// How this handler will configure targets etc,
83    config: HandlerConfig,
84    /// All registered event subscriptions
85    event_listeners: EventListeners,
86    /// Keeps track is the browser is closing
87    closing: bool,
88}
89
90lazy_static::lazy_static! {
91    /// Set the discovery ID target.
92    static ref DISCOVER_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
93        let discover = SetDiscoverTargetsParams::new(true);
94        (discover.identifier(), serde_json::to_value(discover).expect("valid discover target params"))
95    };
96    /// Targets params id.
97    static ref TARGET_PARAMS_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
98        let msg = GetTargetsParams { filter: None };
99        (msg.identifier(), serde_json::to_value(msg).expect("valid paramtarget"))
100    };
101    /// Set the close targets.
102    static ref CLOSE_PARAMS_ID: (std::borrow::Cow<'static, str>, serde_json::Value) = {
103        let close_msg = CloseParams::default();
104        (close_msg.identifier(), serde_json::to_value(close_msg).expect("valid close params"))
105    };
106}
107
108impl Handler {
109    /// Create a new `Handler` that drives the connection and listens for
110    /// messages on the receiver `rx`.
111    pub(crate) fn new(
112        mut conn: Connection<CdpEventMessage>,
113        rx: Receiver<HandlerMessage>,
114        config: HandlerConfig,
115    ) -> Self {
116        let discover = DISCOVER_ID.clone();
117        let _ = conn.submit_command(discover.0, None, discover.1);
118
119        let browser_contexts = config
120            .context_ids
121            .iter()
122            .map(|id| BrowserContext::from(id.clone()))
123            .collect();
124
125        Self {
126            pending_commands: Default::default(),
127            from_browser: rx.fuse(),
128            default_browser_context: Default::default(),
129            browser_contexts,
130            target_ids: Default::default(),
131            targets: Default::default(),
132            navigations: Default::default(),
133            sessions: Default::default(),
134            conn,
135            evict_command_timeout: PeriodicJob::new(config.request_timeout),
136            next_navigation_id: 0,
137            config,
138            event_listeners: Default::default(),
139            closing: false,
140        }
141    }
142
143    /// Return the target with the matching `target_id`
144    pub fn get_target(&self, target_id: &TargetId) -> Option<&Target> {
145        self.targets.get(target_id)
146    }
147
148    /// Iterator over all currently attached targets
149    pub fn targets(&self) -> impl Iterator<Item = &Target> + '_ {
150        self.targets.values()
151    }
152
153    /// The default Browser context
154    pub fn default_browser_context(&self) -> &BrowserContext {
155        &self.default_browser_context
156    }
157
158    /// Iterator over all currently available browser contexts
159    pub fn browser_contexts(&self) -> impl Iterator<Item = &BrowserContext> + '_ {
160        self.browser_contexts.iter()
161    }
162
163    /// received a response to a navigation request like `Page.navigate`
164    fn on_navigation_response(&mut self, id: NavigationId, resp: Response) {
165        if let Some(nav) = self.navigations.remove(&id) {
166            match nav {
167                NavigationRequest::Navigate(mut nav) => {
168                    if nav.navigated {
169                        let _ = nav.tx.send(Ok(resp));
170                    } else {
171                        nav.set_response(resp);
172                        self.navigations
173                            .insert(id, NavigationRequest::Navigate(nav));
174                    }
175                }
176            }
177        }
178    }
179
180    /// A navigation has finished.
181    fn on_navigation_lifecycle_completed(&mut self, res: Result<NavigationOk, NavigationError>) {
182        match res {
183            Ok(ok) => {
184                let id = *ok.navigation_id();
185                if let Some(nav) = self.navigations.remove(&id) {
186                    match nav {
187                        NavigationRequest::Navigate(mut nav) => {
188                            if let Some(resp) = nav.response.take() {
189                                let _ = nav.tx.send(Ok(resp));
190                            } else {
191                                nav.set_navigated();
192                                self.navigations
193                                    .insert(id, NavigationRequest::Navigate(nav));
194                            }
195                        }
196                    }
197                }
198            }
199            Err(err) => {
200                if let Some(nav) = self.navigations.remove(err.navigation_id()) {
201                    match nav {
202                        NavigationRequest::Navigate(nav) => {
203                            let _ = nav.tx.send(Err(err.into()));
204                        }
205                    }
206                }
207            }
208        }
209    }
210
211    /// Received a response to a request.
212    fn on_response(&mut self, resp: Response) {
213        if let Some((req, method, _)) = self.pending_commands.remove(&resp.id) {
214            match req {
215                PendingRequest::CreateTarget(tx) => {
216                    match to_command_response::<CreateTargetParams>(resp, method) {
217                        Ok(resp) => {
218                            if let Some(target) = self.targets.get_mut(&resp.target_id) {
219                                // move the sender to the target that sends its page once
220                                // initialized
221                                target.set_initiator(tx);
222                            }
223                        }
224                        Err(err) => {
225                            let _ = tx.send(Err(err)).ok();
226                        }
227                    }
228                }
229                PendingRequest::GetTargets(tx) => {
230                    match to_command_response::<GetTargetsParams>(resp, method) {
231                        Ok(resp) => {
232                            let targets: Vec<TargetInfo> = resp.result.target_infos;
233                            let results = targets.clone();
234                            for target_info in targets {
235                                let target_id = target_info.target_id.clone();
236                                let event: EventTargetCreated = EventTargetCreated { target_info };
237                                self.on_target_created(event);
238                                let attach = AttachToTargetParams::new(target_id);
239
240                                let _ = self.conn.submit_command(
241                                    attach.identifier(),
242                                    None,
243                                    serde_json::to_value(attach).unwrap_or_default(),
244                                );
245                            }
246
247                            let _ = tx.send(Ok(results)).ok();
248                        }
249                        Err(err) => {
250                            let _ = tx.send(Err(err)).ok();
251                        }
252                    }
253                }
254                PendingRequest::Navigate(id) => {
255                    self.on_navigation_response(id, resp);
256                    if self.config.only_html && !self.config.created_first_target {
257                        self.config.created_first_target = true;
258                    }
259                }
260                PendingRequest::ExternalCommand(tx) => {
261                    let _ = tx.send(Ok(resp)).ok();
262                }
263                PendingRequest::InternalCommand(target_id) => {
264                    if let Some(target) = self.targets.get_mut(&target_id) {
265                        target.on_response(resp, method.as_ref());
266                    }
267                }
268                PendingRequest::CloseBrowser(tx) => {
269                    self.closing = true;
270                    let _ = tx.send(Ok(CloseReturns {})).ok();
271                }
272            }
273        }
274    }
275
276    /// Submit a command initiated via channel
277    pub(crate) fn submit_external_command(
278        &mut self,
279        msg: CommandMessage,
280        now: Instant,
281    ) -> Result<()> {
282        let call_id = self
283            .conn
284            .submit_command(msg.method.clone(), msg.session_id, msg.params)?;
285        self.pending_commands.insert(
286            call_id,
287            (PendingRequest::ExternalCommand(msg.sender), msg.method, now),
288        );
289        Ok(())
290    }
291
292    pub(crate) fn submit_internal_command(
293        &mut self,
294        target_id: TargetId,
295        req: CdpRequest,
296        now: Instant,
297    ) -> Result<()> {
298        let call_id = self.conn.submit_command(
299            req.method.clone(),
300            req.session_id.map(Into::into),
301            req.params,
302        )?;
303        self.pending_commands.insert(
304            call_id,
305            (PendingRequest::InternalCommand(target_id), req.method, now),
306        );
307        Ok(())
308    }
309
310    fn submit_fetch_targets(&mut self, tx: OneshotSender<Result<Vec<TargetInfo>>>, now: Instant) {
311        let msg = TARGET_PARAMS_ID.clone();
312
313        if let Ok(call_id) = self.conn.submit_command(msg.0.clone(), None, msg.1) {
314            self.pending_commands
315                .insert(call_id, (PendingRequest::GetTargets(tx), msg.0, now));
316        }
317    }
318
319    /// Send the Request over to the server and store its identifier to handle
320    /// the response once received.
321    fn submit_navigation(&mut self, id: NavigationId, req: CdpRequest, now: Instant) {
322        if let Ok(call_id) = self.conn.submit_command(
323            req.method.clone(),
324            req.session_id.map(Into::into),
325            req.params,
326        ) {
327            self.pending_commands
328                .insert(call_id, (PendingRequest::Navigate(id), req.method, now));
329        }
330    }
331
332    fn submit_close(&mut self, tx: OneshotSender<Result<CloseReturns>>, now: Instant) {
333        let close_msg = CLOSE_PARAMS_ID.clone();
334
335        if let Ok(call_id) = self
336            .conn
337            .submit_command(close_msg.0.clone(), None, close_msg.1)
338        {
339            self.pending_commands.insert(
340                call_id,
341                (PendingRequest::CloseBrowser(tx), close_msg.0, now),
342            );
343        }
344    }
345
346    /// Process a message received by the target's page via channel
347    fn on_target_message(&mut self, target: &mut Target, msg: CommandMessage, now: Instant) {
348        if msg.is_navigation() {
349            let (req, tx) = msg.split();
350            let id = self.next_navigation_id();
351
352            target.goto(FrameRequestedNavigation::new(id, req));
353
354            self.navigations.insert(
355                id,
356                NavigationRequest::Navigate(NavigationInProgress::new(tx)),
357            );
358        } else {
359            let _ = self.submit_external_command(msg, now);
360        }
361    }
362
363    /// An identifier for queued `NavigationRequest`s.
364    fn next_navigation_id(&mut self) -> NavigationId {
365        let id = NavigationId(self.next_navigation_id);
366        self.next_navigation_id = self.next_navigation_id.wrapping_add(1);
367        id
368    }
369
370    /// Create a new page and send it to the receiver when ready
371    ///
372    /// First a `CreateTargetParams` is send to the server, this will trigger
373    /// `EventTargetCreated` which results in a new `Target` being created.
374    /// Once the response to the request is received the initialization process
375    /// of the target kicks in. This triggers a queue of initialization requests
376    /// of the `Target`, once those are all processed and the `url` fo the
377    /// `CreateTargetParams` has finished loading (The `Target`'s `Page` is
378    /// ready and idle), the `Target` sends its newly created `Page` as response
379    /// to the initiator (`tx`) of the `CreateTargetParams` request.
380    fn create_page(&mut self, params: CreateTargetParams, tx: OneshotSender<Result<Page>>) {
381        let about_blank = params.url == "about:blank";
382        let http_check =
383            !about_blank && params.url.starts_with("http") || params.url.starts_with("file://");
384
385        if about_blank || http_check {
386            let method = params.identifier();
387
388            match serde_json::to_value(params) {
389                Ok(params) => match self.conn.submit_command(method.clone(), None, params) {
390                    Ok(call_id) => {
391                        self.pending_commands.insert(
392                            call_id,
393                            (PendingRequest::CreateTarget(tx), method, Instant::now()),
394                        );
395                    }
396                    Err(err) => {
397                        let _ = tx.send(Err(err.into())).ok();
398                    }
399                },
400                Err(err) => {
401                    let _ = tx.send(Err(err.into())).ok();
402                }
403            }
404        } else {
405            let _ = tx.send(Err(CdpError::NotFound)).ok();
406        }
407    }
408
409    /// Process an incoming event read from the websocket
410    fn on_event(&mut self, event: CdpEventMessage) {
411        if let Some(ref session_id) = event.session_id {
412            if let Some(session) = self.sessions.get(session_id.as_str()) {
413                if let Some(target) = self.targets.get_mut(session.target_id()) {
414                    return target.on_event(event);
415                }
416            }
417        }
418        let CdpEventMessage { params, method, .. } = event;
419
420        match params {
421            CdpEvent::TargetTargetCreated(ref ev) => self.on_target_created(ev.clone()),
422            CdpEvent::TargetAttachedToTarget(ref ev) => self.on_attached_to_target(ev.clone()),
423            CdpEvent::TargetTargetDestroyed(ref ev) => self.on_target_destroyed(ev.clone()),
424            CdpEvent::TargetDetachedFromTarget(ref ev) => self.on_detached_from_target(ev.clone()),
425            _ => {}
426        }
427
428        chromiumoxide_cdp::consume_event!(match params {
429            |ev| self.event_listeners.start_send(ev),
430            |json| { let _ = self.event_listeners.try_send_custom(&method, json);}
431        });
432    }
433
434    /// Fired when a new target was created on the chromium instance
435    ///
436    /// Creates a new `Target` instance and keeps track of it
437    fn on_target_created(&mut self, event: EventTargetCreated) {
438        let browser_ctx = match event.target_info.browser_context_id {
439            Some(ref context_id) => {
440                let browser_context = BrowserContext {
441                    id: Some(context_id.clone()),
442                };
443                if self.default_browser_context.id.is_none() {
444                    self.default_browser_context = browser_context.clone();
445                };
446                self.browser_contexts.insert(browser_context.clone());
447
448                browser_context
449            }
450            _ => event
451                .target_info
452                .browser_context_id
453                .clone()
454                .map(BrowserContext::from)
455                .filter(|id| self.browser_contexts.contains(id))
456                .unwrap_or_else(|| self.default_browser_context.clone()),
457        };
458
459        let target = Target::new(
460            event.target_info,
461            TargetConfig {
462                ignore_https_errors: self.config.ignore_https_errors,
463                request_timeout: self.config.request_timeout,
464                viewport: self.config.viewport.clone(),
465                request_intercept: self.config.request_intercept,
466                cache_enabled: self.config.cache_enabled,
467                service_worker_enabled: self.config.service_worker_enabled,
468                ignore_visuals: self.config.ignore_visuals,
469                ignore_stylesheets: self.config.ignore_stylesheets,
470                ignore_javascript: self.config.ignore_javascript,
471                ignore_analytics: self.config.ignore_analytics,
472                extra_headers: self.config.extra_headers.clone(),
473                only_html: self.config.only_html && self.config.created_first_target,
474                intercept_manager: self.config.intercept_manager,
475            },
476            browser_ctx,
477        );
478
479        self.target_ids.push(target.target_id().clone());
480        self.targets.insert(target.target_id().clone(), target);
481    }
482
483    /// A new session is attached to a target
484    fn on_attached_to_target(&mut self, event: Box<EventAttachedToTarget>) {
485        let session = Session::new(event.session_id.clone(), event.target_info.target_id);
486        if let Some(target) = self.targets.get_mut(session.target_id()) {
487            target.set_session_id(session.session_id().clone())
488        }
489        self.sessions.insert(event.session_id, session);
490    }
491
492    /// The session was detached from target.
493    /// Can be issued multiple times per target if multiple session have been
494    /// attached to it.
495    fn on_detached_from_target(&mut self, event: EventDetachedFromTarget) {
496        // remove the session
497        if let Some(session) = self.sessions.remove(&event.session_id) {
498            if let Some(target) = self.targets.get_mut(session.target_id()) {
499                target.session_id().take();
500            }
501        }
502    }
503
504    /// Fired when the target was destroyed in the browser
505    fn on_target_destroyed(&mut self, event: EventTargetDestroyed) {
506        if let Some(target) = self.targets.remove(&event.target_id) {
507            // TODO shutdown?
508            if let Some(session) = target.session_id() {
509                self.sessions.remove(session);
510            }
511        }
512    }
513
514    /// House keeping of commands
515    ///
516    /// Remove all commands where `now` > `timestamp of command starting point +
517    /// request timeout` and notify the senders that their request timed out.
518    fn evict_timed_out_commands(&mut self, now: Instant) {
519        let timed_out = self
520            .pending_commands
521            .iter()
522            .filter(|(_, (_, _, timestamp))| now > (*timestamp + self.config.request_timeout))
523            .map(|(k, _)| *k)
524            .collect::<Vec<_>>();
525
526        for call in timed_out {
527            if let Some((req, _, _)) = self.pending_commands.remove(&call) {
528                match req {
529                    PendingRequest::CreateTarget(tx) => {
530                        let _ = tx.send(Err(CdpError::Timeout));
531                    }
532                    PendingRequest::GetTargets(tx) => {
533                        let _ = tx.send(Err(CdpError::Timeout));
534                    }
535                    PendingRequest::Navigate(nav) => {
536                        if let Some(nav) = self.navigations.remove(&nav) {
537                            match nav {
538                                NavigationRequest::Navigate(nav) => {
539                                    let _ = nav.tx.send(Err(CdpError::Timeout));
540                                }
541                            }
542                        }
543                    }
544                    PendingRequest::ExternalCommand(tx) => {
545                        let _ = tx.send(Err(CdpError::Timeout));
546                    }
547                    PendingRequest::InternalCommand(_) => {}
548                    PendingRequest::CloseBrowser(tx) => {
549                        let _ = tx.send(Err(CdpError::Timeout));
550                    }
551                }
552            }
553        }
554    }
555
556    pub fn event_listeners_mut(&mut self) -> &mut EventListeners {
557        &mut self.event_listeners
558    }
559}
560
561impl Stream for Handler {
562    type Item = Result<()>;
563
564    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
565        let pin = self.get_mut();
566
567        let mut dispose = false;
568
569        loop {
570            let now = Instant::now();
571            // temporary pinning of the browser receiver should be safe as we are pinning
572            // through the already pinned self. with the receivers we can also
573            // safely ignore exhaustion as those are fused.
574            while let Poll::Ready(Some(msg)) = Pin::new(&mut pin.from_browser).poll_next(cx) {
575                match msg {
576                    HandlerMessage::Command(cmd) => {
577                        pin.submit_external_command(cmd, now)?;
578                    }
579                    HandlerMessage::FetchTargets(tx) => {
580                        pin.submit_fetch_targets(tx, now);
581                    }
582                    HandlerMessage::CloseBrowser(tx) => {
583                        pin.submit_close(tx, now);
584                    }
585                    HandlerMessage::CreatePage(params, tx) => {
586                        pin.create_page(params, tx);
587                    }
588                    HandlerMessage::GetPages(tx) => {
589                        let pages: Vec<_> = pin
590                            .targets
591                            .values_mut()
592                            .filter(|p: &&mut Target| p.is_page())
593                            .filter_map(|target| target.get_or_create_page())
594                            .map(|page| Page::from(page.clone()))
595                            .collect();
596                        let _ = tx.send(pages);
597                    }
598                    HandlerMessage::InsertContext(ctx) => {
599                        pin.default_browser_context = ctx.clone();
600                        pin.browser_contexts.insert(ctx);
601                    }
602                    HandlerMessage::DisposeContext(ctx) => {
603                        pin.browser_contexts.remove(&ctx);
604                        pin.closing = true;
605                        dispose = true;
606                    }
607                    HandlerMessage::GetPage(target_id, tx) => {
608                        let page = pin
609                            .targets
610                            .get_mut(&target_id)
611                            .and_then(|target| target.get_or_create_page())
612                            .map(|page| Page::from(page.clone()));
613                        let _ = tx.send(page);
614                    }
615                    HandlerMessage::AddEventListener(req) => {
616                        pin.event_listeners.add_listener(req);
617                    }
618                }
619            }
620
621            for n in (0..pin.target_ids.len()).rev() {
622                let target_id = pin.target_ids.swap_remove(n);
623
624                if let Some((id, mut target)) = pin.targets.remove_entry(&target_id) {
625                    while let Some(event) = target.poll(cx, now) {
626                        match event {
627                            TargetEvent::Request(req) => {
628                                let _ = pin.submit_internal_command(
629                                    target.target_id().clone(),
630                                    req,
631                                    now,
632                                );
633                            }
634                            TargetEvent::Command(msg) => {
635                                pin.on_target_message(&mut target, msg, now);
636                            }
637                            TargetEvent::NavigationRequest(id, req) => {
638                                pin.submit_navigation(id, req, now);
639                            }
640                            TargetEvent::NavigationResult(res) => {
641                                pin.on_navigation_lifecycle_completed(res)
642                            }
643                        }
644                    }
645
646                    // poll the target's event listeners
647                    target.event_listeners_mut().poll(cx);
648                    // poll the handler's event listeners
649                    pin.event_listeners_mut().poll(cx);
650
651                    pin.targets.insert(id, target);
652                    pin.target_ids.push(target_id);
653                }
654            }
655
656            let mut done = true;
657
658            while let Poll::Ready(Some(ev)) = Pin::new(&mut pin.conn).poll_next(cx) {
659                match ev {
660                    Ok(Message::Response(resp)) => {
661                        pin.on_response(resp);
662                        if pin.closing {
663                            // handler should stop processing
664                            return Poll::Ready(None);
665                        }
666                    }
667                    Ok(Message::Event(ev)) => {
668                        pin.on_event(ev);
669                    }
670                    Err(err) => {
671                        tracing::error!("WS Connection error: {:?}", err);
672                        match err {
673                            CdpError::Ws(ref ws_error) => match ws_error {
674                                Error::AlreadyClosed => {
675                                    pin.closing = true;
676                                    dispose = true;
677                                    break;
678                                }
679                                Error::Protocol(detail)
680                                    if detail == &ProtocolError::ResetWithoutClosingHandshake =>
681                                {
682                                    pin.closing = true;
683                                    dispose = true;
684                                    break;
685                                }
686                                _ => {}
687                            },
688                            _ => {}
689                        };
690                        return Poll::Ready(Some(Err(err)));
691                    }
692                }
693                done = false;
694            }
695
696            if pin.evict_command_timeout.poll_ready(cx) {
697                // evict all commands that timed out
698                pin.evict_timed_out_commands(now);
699            }
700
701            if dispose {
702                return Poll::Ready(None);
703            }
704
705            if done {
706                // no events/responses were read from the websocket
707                return Poll::Pending;
708            }
709        }
710    }
711}
712
713/// How to configure the handler
714#[derive(Debug, Clone)]
715pub struct HandlerConfig {
716    /// Whether the `NetworkManager`s should ignore https errors
717    pub ignore_https_errors: bool,
718    /// Window and device settings
719    pub viewport: Option<Viewport>,
720    /// Context ids to set from the get go
721    pub context_ids: Vec<BrowserContextId>,
722    /// default request timeout to use
723    pub request_timeout: Duration,
724    /// Whether to enable request interception
725    pub request_intercept: bool,
726    /// Whether to enable cache
727    pub cache_enabled: bool,
728    /// Whether to enable Service Workers
729    pub service_worker_enabled: bool,
730    /// Whether to ignore visuals.
731    pub ignore_visuals: bool,
732    /// Whether to ignore stylesheets.
733    pub ignore_stylesheets: bool,
734    /// Whether to ignore Javascript only allowing critical framework or lib based rendering.
735    pub ignore_javascript: bool,
736    /// Whether to ignore analytics.
737    pub ignore_analytics: bool,
738    /// Whether to ignore ads.
739    pub ignore_ads: bool,
740    /// Extra headers.
741    pub extra_headers: Option<std::collections::HashMap<String, String>>,
742    /// Only Html.
743    pub only_html: bool,
744    /// Created the first target.
745    pub created_first_target: bool,
746    /// The network intercept manager.
747    pub intercept_manager: NetworkInterceptManager,
748}
749
750impl Default for HandlerConfig {
751    fn default() -> Self {
752        Self {
753            ignore_https_errors: true,
754            viewport: Default::default(),
755            context_ids: Vec::new(),
756            request_timeout: Duration::from_millis(REQUEST_TIMEOUT),
757            request_intercept: false,
758            cache_enabled: true,
759            service_worker_enabled: true,
760            ignore_visuals: false,
761            ignore_stylesheets: false,
762            ignore_ads: false,
763            ignore_javascript: false,
764            ignore_analytics: true,
765            only_html: false,
766            extra_headers: Default::default(),
767            created_first_target: false,
768            intercept_manager: NetworkInterceptManager::Unknown,
769        }
770    }
771}
772
773/// Wraps the sender half of the channel who requested a navigation
774#[derive(Debug)]
775pub struct NavigationInProgress<T> {
776    /// Marker to indicate whether a navigation lifecycle has completed
777    navigated: bool,
778    /// The response of the issued navigation request
779    response: Option<Response>,
780    /// Sender who initiated the navigation request
781    tx: OneshotSender<T>,
782}
783
784impl<T> NavigationInProgress<T> {
785    fn new(tx: OneshotSender<T>) -> Self {
786        Self {
787            navigated: false,
788            response: None,
789            tx,
790        }
791    }
792
793    /// The response to the cdp request has arrived
794    fn set_response(&mut self, resp: Response) {
795        self.response = Some(resp);
796    }
797
798    /// The navigation process has finished, the page finished loading.
799    fn set_navigated(&mut self) {
800        self.navigated = true;
801    }
802}
803
804/// Request type for navigation
805#[derive(Debug)]
806enum NavigationRequest {
807    /// Represents a simple `NavigateParams` ("Page.navigate")
808    Navigate(NavigationInProgress<Result<Response>>),
809    // TODO are there more?
810}
811
812/// Different kind of submitted request submitted from the  `Handler` to the
813/// `Connection` and being waited on for the response.
814#[derive(Debug)]
815enum PendingRequest {
816    /// A Request to create a new `Target` that results in the creation of a
817    /// `Page` that represents a browser page.
818    CreateTarget(OneshotSender<Result<Page>>),
819    /// A Request to fetch old `Target`s created before connection
820    GetTargets(OneshotSender<Result<Vec<TargetInfo>>>),
821    /// A Request to navigate a specific `Target`.
822    ///
823    /// Navigation requests are not automatically completed once the response to
824    /// the raw cdp navigation request (like `NavigateParams`) arrives, but only
825    /// after the `Target` notifies the `Handler` that the `Page` has finished
826    /// loading, which comes after the response.
827    Navigate(NavigationId),
828    /// A common request received via a channel (`Page`).
829    ExternalCommand(OneshotSender<Result<Response>>),
830    /// Requests that are initiated directly from a `Target` (all the
831    /// initialization commands).
832    InternalCommand(TargetId),
833    // A Request to close the browser.
834    CloseBrowser(OneshotSender<Result<CloseReturns>>),
835}
836
837/// Events used internally to communicate with the handler, which are executed
838/// in the background
839// TODO rename to BrowserMessage
840#[derive(Debug)]
841pub(crate) enum HandlerMessage {
842    CreatePage(CreateTargetParams, OneshotSender<Result<Page>>),
843    FetchTargets(OneshotSender<Result<Vec<TargetInfo>>>),
844    InsertContext(BrowserContext),
845    DisposeContext(BrowserContext),
846    GetPages(OneshotSender<Vec<Page>>),
847    Command(CommandMessage),
848    GetPage(TargetId, OneshotSender<Option<Page>>),
849    AddEventListener(EventListenerRequest),
850    CloseBrowser(OneshotSender<Result<CloseReturns>>),
851}