viewpoint_core/context/routing_impl/
mod.rs

1//! Context-level network routing implementation.
2
3use std::future::Future;
4use std::sync::Arc;
5
6use crate::error::NetworkError;
7use crate::network::{HarReplayOptions, Route, UrlPattern};
8
9use super::BrowserContext;
10
11impl BrowserContext {
12    /// Register a route handler that applies to all pages in this context.
13    ///
14    /// Routes registered at the context level are applied to all pages,
15    /// including new pages created after the route is registered.
16    /// Context routes are checked before page-level routes.
17    ///
18    /// # Example
19    ///
20    /// ```no_run
21    /// use viewpoint_core::{Browser, network::Route};
22    ///
23    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
24    /// let browser = Browser::launch().headless(true).launch().await?;
25    /// let context = browser.new_context().await?;
26    ///
27    /// // Block all analytics requests for all pages
28    /// context.route("**/analytics/**", |route: Route| async move {
29    ///     route.abort().await
30    /// }).await?;
31    ///
32    /// // Mock an API for all pages
33    /// context.route("**/api/users", |route: Route| async move {
34    ///     route.fulfill()
35    ///         .status(200)
36    ///         .json(&serde_json::json!({"users": []}))
37    ///         .send()
38    ///         .await
39    /// }).await?;
40    /// # Ok(())
41    /// # }
42    /// ```
43    ///
44    /// # Errors
45    ///
46    /// Returns an error if the context is closed.
47    pub async fn route<M, H, Fut>(&self, pattern: M, handler: H) -> Result<(), NetworkError>
48    where
49        M: Into<UrlPattern>,
50        H: Fn(Route) -> Fut + Send + Sync + 'static,
51        Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,
52    {
53        if self.is_closed() {
54            return Err(NetworkError::Aborted);
55        }
56        self.route_registry.route(pattern, handler).await
57    }
58
59    /// Register a route handler with a predicate function.
60    ///
61    /// # Example
62    ///
63    /// ```no_run
64    /// use viewpoint_core::{Browser, network::Route};
65    ///
66    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
67    /// let browser = Browser::launch().headless(true).launch().await?;
68    /// let context = browser.new_context().await?;
69    ///
70    /// // Block POST requests to any API endpoint
71    /// context.route_predicate(
72    ///     |url| url.contains("/api/"),
73    ///     |route: Route| async move {
74    ///         if route.request().method() == "POST" {
75    ///             route.abort().await
76    ///         } else {
77    ///             route.continue_().await
78    ///         }
79    ///     }
80    /// ).await?;
81    /// # Ok(())
82    /// # }
83    /// ```
84    ///
85    /// # Errors
86    ///
87    /// Returns an error if the context is closed.
88    pub async fn route_predicate<P, H, Fut>(
89        &self,
90        predicate: P,
91        handler: H,
92    ) -> Result<(), NetworkError>
93    where
94        P: Fn(&str) -> bool + Send + Sync + 'static,
95        H: Fn(Route) -> Fut + Send + Sync + 'static,
96        Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,
97    {
98        if self.is_closed() {
99            return Err(NetworkError::Aborted);
100        }
101        self.route_registry.route_predicate(predicate, handler).await
102    }
103
104    /// Unregister handlers matching the given pattern.
105    ///
106    /// This removes handlers registered with `route()` that match the pattern.
107    pub async fn unroute(&self, pattern: &str) {
108        self.route_registry.unroute(pattern).await;
109    }
110
111    /// Unregister all route handlers.
112    ///
113    /// This removes all handlers registered with `route()`.
114    pub async fn unroute_all(&self) {
115        self.route_registry.unroute_all().await;
116    }
117
118    /// Route requests from a HAR file for all pages in this context.
119    ///
120    /// Requests that match entries in the HAR file will be fulfilled with the
121    /// recorded responses. Requests that don't match will continue normally
122    /// unless strict mode is enabled.
123    ///
124    /// # Example
125    ///
126    /// ```no_run
127    /// use viewpoint_core::{Browser, network::HarReplayOptions};
128    ///
129    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
130    /// let browser = Browser::launch().headless(true).launch().await?;
131    /// let context = browser.new_context().await?;
132    ///
133    /// // Simple HAR routing for all pages
134    /// context.route_from_har("recordings/api.har").await?;
135    ///
136    /// // With options
137    /// context.route_from_har_with_options(
138    ///     "recordings/api.har",
139    ///     HarReplayOptions::new()
140    ///         .url("**/api/**")
141    ///         .strict(true)
142    /// ).await?;
143    /// # Ok(())
144    /// # }
145    /// ```
146    ///
147    /// # Errors
148    ///
149    /// Returns an error if:
150    /// - The HAR file cannot be read or parsed
151    /// - The context is closed
152    pub async fn route_from_har(&self, path: impl AsRef<std::path::Path>) -> Result<(), NetworkError> {
153        self.route_from_har_with_options(path, HarReplayOptions::default()).await
154    }
155
156    /// Route requests from a HAR file with options for all pages in this context.
157    ///
158    /// # Example
159    ///
160    /// ```no_run
161    /// use viewpoint_core::{Browser, network::HarReplayOptions};
162    ///
163    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
164    /// let browser = Browser::launch().headless(true).launch().await?;
165    /// let context = browser.new_context().await?;
166    ///
167    /// // Strict mode: fail if no match found
168    /// context.route_from_har_with_options(
169    ///     "api.har",
170    ///     HarReplayOptions::new().strict(true)
171    /// ).await?;
172    /// # Ok(())
173    /// # }
174    /// ```
175    ///
176    /// ```no_run
177    /// use viewpoint_core::{Browser, network::HarReplayOptions};
178    ///
179    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
180    /// let browser = Browser::launch().headless(true).launch().await?;
181    /// let context = browser.new_context().await?;
182    ///
183    /// // URL filter: only match specific URLs
184    /// context.route_from_har_with_options(
185    ///     "api.har",
186    ///     HarReplayOptions::new().url("**/api/**")
187    /// ).await?;
188    /// # Ok(())
189    /// # }
190    /// ```
191    ///
192    /// ```no_run
193    /// use viewpoint_core::{Browser, network::HarReplayOptions};
194    ///
195    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
196    /// let browser = Browser::launch().headless(true).launch().await?;
197    /// let context = browser.new_context().await?;
198    ///
199    /// // Simulate original timing
200    /// context.route_from_har_with_options(
201    ///     "api.har",
202    ///     HarReplayOptions::new().use_original_timing(true)
203    /// ).await?;
204    /// # Ok(())
205    /// # }
206    /// ```
207    ///
208    /// # Errors
209    ///
210    /// Returns an error if:
211    /// - The HAR file cannot be read or parsed
212    /// - The context is closed
213    pub async fn route_from_har_with_options(
214        &self,
215        path: impl AsRef<std::path::Path>,
216        options: HarReplayOptions,
217    ) -> Result<(), NetworkError> {
218        if self.is_closed() {
219            return Err(NetworkError::Aborted);
220        }
221
222        let handler = Arc::new(
223            crate::network::HarReplayHandler::from_file(path)
224                .await?
225                .with_options(options)
226        );
227
228        // Route all requests through the HAR handler
229        let route_handler = crate::network::har_replay::create_har_route_handler(handler);
230        self.route_registry.route("**/*", route_handler).await
231    }
232}