Skip to main content

stygian_browser/
browser.rs

1//! Browser instance lifecycle management
2//!
3//! Provides a thin wrapper around a `chromiumoxide` [`Browser`] that adds:
4//!
5//! - Anti-detection launch arguments from [`BrowserConfig`]
6//! - Configurable launch and per-operation timeouts via `tokio::time::timeout`
7//! - Health checks using the CDP `Browser.getVersion` command
8//! - PID-based zombie process detection and forced cleanup
9//! - Graceful shutdown (close all pages ➞ send `Browser.close`)
10//!
11//! # Example
12//!
13//! ```no_run
14//! use stygian_browser::{BrowserConfig, browser::BrowserInstance};
15//!
16//! # async fn run() -> stygian_browser::error::Result<()> {
17//! let config = BrowserConfig::default();
18//! let mut instance = BrowserInstance::launch(config).await?;
19//!
20//! assert!(instance.is_healthy().await);
21//! instance.shutdown().await?;
22//! # Ok(())
23//! # }
24//! ```
25
26use std::time::{Duration, Instant};
27
28use chromiumoxide::Browser;
29use futures::StreamExt;
30use tokio::time::timeout;
31use tracing::{debug, info, warn};
32
33use crate::{
34    BrowserConfig,
35    error::{BrowserError, Result},
36};
37
38// ─── BrowserInstance ──────────────────────────────────────────────────────────
39
40/// A managed browser instance with health tracking.
41///
42/// Wraps a `chromiumoxide` [`Browser`] and an async handler task.  Always call
43/// [`BrowserInstance::shutdown`] (or drop) after use to release OS resources.
44pub struct BrowserInstance {
45    browser: Browser,
46    config: BrowserConfig,
47    launched_at: Instant,
48    /// Set to `false` after a failed health check so callers know to discard.
49    healthy: bool,
50    /// Convenience ID for log correlation.
51    id: String,
52}
53
54impl BrowserInstance {
55    /// Launch a new browser instance using the provided [`BrowserConfig`].
56    ///
57    /// All configured anti-detection arguments (see
58    /// [`BrowserConfig::effective_args`]) are passed at launch time.
59    ///
60    /// # Errors
61    ///
62    /// - [`BrowserError::LaunchFailed`] if the process does not start within
63    ///   `config.launch_timeout`.
64    /// - [`BrowserError::Timeout`] if the browser doesn't respond in time.
65    ///
66    /// # Example
67    ///
68    /// ```no_run
69    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
70    ///
71    /// # async fn run() -> stygian_browser::error::Result<()> {
72    /// let instance = BrowserInstance::launch(BrowserConfig::default()).await?;
73    /// # Ok(())
74    /// # }
75    /// ```
76    pub async fn launch(config: BrowserConfig) -> Result<Self> {
77        let id = ulid::Ulid::new().to_string();
78        let launch_timeout = config.launch_timeout;
79
80        info!(browser_id = %id, "Launching browser");
81
82        let args = config.effective_args();
83        debug!(browser_id = %id, ?args, "Chrome launch arguments");
84
85        let mut builder = chromiumoxide::BrowserConfig::builder();
86
87        // chromiumoxide defaults to headless; call with_head() only for headed mode
88        if !config.headless {
89            builder = builder.with_head();
90        }
91
92        if let Some(path) = &config.chrome_path {
93            builder = builder.chrome_executable(path);
94        }
95
96        if let Some(dir) = &config.user_data_dir {
97            builder = builder.user_data_dir(dir);
98        }
99
100        for arg in &args {
101            builder = builder.arg(arg.as_str());
102        }
103
104        if let Some((w, h)) = config.window_size {
105            builder = builder.window_size(w, h);
106        }
107
108        let cdp_cfg = builder
109            .build()
110            .map_err(|e| BrowserError::LaunchFailed { reason: e })?;
111
112        let (browser, mut handler) = timeout(launch_timeout, Browser::launch(cdp_cfg))
113            .await
114            .map_err(|_| BrowserError::Timeout {
115                operation: "browser.launch".to_string(),
116                duration_ms: u64::try_from(launch_timeout.as_millis()).unwrap_or(u64::MAX),
117            })?
118            .map_err(|e| BrowserError::LaunchFailed {
119                reason: e.to_string(),
120            })?;
121
122        // Spawn the chromiumoxide message handler; it must run for the browser
123        // to remain responsive.
124        tokio::spawn(async move { while handler.next().await.is_some() {} });
125
126        info!(browser_id = %id, "Browser launched successfully");
127
128        Ok(Self {
129            browser,
130            config,
131            launched_at: Instant::now(),
132            healthy: true,
133            id,
134        })
135    }
136
137    // ─── Health ───────────────────────────────────────────────────────────────
138
139    /// Returns `true` if the browser is currently considered healthy.
140    ///
141    /// This is a cached value updated by [`BrowserInstance::health_check`].
142    pub const fn is_healthy_cached(&self) -> bool {
143        self.healthy
144    }
145
146    /// Actively probe the browser with a CDP request.
147    ///
148    /// Sends `Browser.getVersion` and waits up to `cdp_timeout`.  Updates the
149    /// internal healthy flag and returns the result.
150    ///
151    /// # Example
152    ///
153    /// ```no_run
154    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
155    ///
156    /// # async fn run() -> stygian_browser::error::Result<()> {
157    /// let mut instance = BrowserInstance::launch(BrowserConfig::default()).await?;
158    /// assert!(instance.is_healthy().await);
159    /// # Ok(())
160    /// # }
161    /// ```
162    pub async fn is_healthy(&mut self) -> bool {
163        match self.health_check().await {
164            Ok(()) => true,
165            Err(e) => {
166                warn!(browser_id = %self.id, error = %e, "Health check failed");
167                false
168            }
169        }
170    }
171
172    /// Run a health check and return a structured [`Result`].
173    ///
174    /// Pings the browser with the CDP `Browser.getVersion` RPC.
175    pub async fn health_check(&mut self) -> Result<()> {
176        let op_timeout = self.config.cdp_timeout;
177
178        timeout(op_timeout, self.browser.version())
179            .await
180            .map_err(|_| {
181                self.healthy = false;
182                BrowserError::Timeout {
183                    operation: "Browser.getVersion".to_string(),
184                    duration_ms: u64::try_from(op_timeout.as_millis()).unwrap_or(u64::MAX),
185                }
186            })?
187            .map_err(|e| {
188                self.healthy = false;
189                BrowserError::CdpError {
190                    operation: "Browser.getVersion".to_string(),
191                    message: e.to_string(),
192                }
193            })?;
194
195        self.healthy = true;
196        Ok(())
197    }
198
199    // ─── Accessors ────────────────────────────────────────────────────────────
200
201    /// Access the underlying `chromiumoxide` [`Browser`].
202    pub const fn browser(&self) -> &Browser {
203        &self.browser
204    }
205
206    /// Mutable access to the underlying `chromiumoxide` [`Browser`].
207    pub const fn browser_mut(&mut self) -> &mut Browser {
208        &mut self.browser
209    }
210
211    /// Instance ID (ULID) for log correlation.
212    pub fn id(&self) -> &str {
213        &self.id
214    }
215
216    /// How long has this instance been alive.
217    pub fn uptime(&self) -> Duration {
218        self.launched_at.elapsed()
219    }
220
221    /// The config snapshot used at launch.
222    pub const fn config(&self) -> &BrowserConfig {
223        &self.config
224    }
225
226    // ─── Shutdown ─────────────────────────────────────────────────────────────
227
228    /// Gracefully close the browser.
229    ///
230    /// Sends `Browser.close` and waits up to `cdp_timeout`.  Any errors during
231    /// tear-down are logged but not propagated so the caller can always clean up.
232    ///
233    /// # Example
234    ///
235    /// ```no_run
236    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
237    ///
238    /// # async fn run() -> stygian_browser::error::Result<()> {
239    /// let mut instance = BrowserInstance::launch(BrowserConfig::default()).await?;
240    /// instance.shutdown().await?;
241    /// # Ok(())
242    /// # }
243    /// ```
244    pub async fn shutdown(mut self) -> Result<()> {
245        info!(browser_id = %self.id, "Shutting down browser");
246
247        let op_timeout = self.config.cdp_timeout;
248
249        if let Err(e) = timeout(op_timeout, self.browser.close()).await {
250            // Timeout — log and continue cleanup
251            warn!(
252                browser_id = %self.id,
253                "Browser.close timed out after {}ms: {e}",
254                op_timeout.as_millis()
255            );
256        }
257
258        self.healthy = false;
259        info!(browser_id = %self.id, "Browser shut down");
260        Ok(())
261    }
262
263    /// Open a new tab and return a [`crate::page::PageHandle`].
264    ///
265    /// The handle closes the tab automatically when dropped.
266    ///
267    /// # Errors
268    ///
269    /// Returns [`BrowserError::CdpError`] if a new page cannot be created.
270    ///
271    /// # Example
272    ///
273    /// ```no_run
274    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
275    ///
276    /// # async fn run() -> stygian_browser::error::Result<()> {
277    /// let mut instance = BrowserInstance::launch(BrowserConfig::default()).await?;
278    /// let page = instance.new_page().await?;
279    /// drop(page);
280    /// instance.shutdown().await?;
281    /// # Ok(())
282    /// # }
283    /// ```
284    pub async fn new_page(&self) -> crate::error::Result<crate::page::PageHandle> {
285        use tokio::time::timeout;
286
287        let cdp_timeout = self.config.cdp_timeout;
288
289        let page = timeout(cdp_timeout, self.browser.new_page("about:blank"))
290            .await
291            .map_err(|_| crate::error::BrowserError::Timeout {
292                operation: "Browser.newPage".to_string(),
293                duration_ms: u64::try_from(cdp_timeout.as_millis()).unwrap_or(u64::MAX),
294            })?
295            .map_err(|e| crate::error::BrowserError::CdpError {
296                operation: "Browser.newPage".to_string(),
297                message: e.to_string(),
298            })?;
299
300        // Apply stealth injection scripts for all active stealth levels.
301        #[cfg(feature = "stealth")]
302        crate::stealth::apply_stealth_to_page(&page, &self.config).await?;
303
304        Ok(crate::page::PageHandle::new(page, cdp_timeout))
305    }
306}
307
308// ─── Tests ────────────────────────────────────────────────────────────────────
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    /// Verify `BrowserConfig` `effective_args` includes anti-detection flags.
315    ///
316    /// This is a unit test that doesn't require a real Chrome binary.
317    #[test]
318    fn effective_args_contain_automation_flag() {
319        let config = BrowserConfig::default();
320        let args = config.effective_args();
321        assert!(
322            args.iter().any(|a| a.contains("AutomationControlled")),
323            "Expected --disable-blink-features=AutomationControlled in args: {args:?}"
324        );
325    }
326
327    #[test]
328    fn proxy_arg_injected_when_set() {
329        let config = BrowserConfig::builder()
330            .proxy("http://proxy.example.com:8080".to_string())
331            .build();
332        let args = config.effective_args();
333        assert!(
334            args.iter().any(|a| a.contains("proxy.example.com")),
335            "Expected proxy arg in {args:?}"
336        );
337    }
338
339    #[test]
340    fn window_size_arg_injected() {
341        let config = BrowserConfig::builder().window_size(1280, 720).build();
342        let args = config.effective_args();
343        assert!(
344            args.iter().any(|a| a.contains("1280")),
345            "Expected window-size arg in {args:?}"
346        );
347    }
348
349    #[test]
350    fn browser_instance_is_send_sync() {
351        fn assert_send<T: Send>() {}
352        fn assert_sync<T: Sync>() {}
353        assert_send::<BrowserInstance>();
354        assert_sync::<BrowserInstance>();
355    }
356
357    #[test]
358    fn no_sandbox_absent_by_default_on_non_linux() {
359        // On non-Linux (macOS, Windows) is_containerized() always returns false,
360        // so --no-sandbox must NOT appear in the default args unless overridden.
361        // On Linux in CI/Docker the STYGIAN_DISABLE_SANDBOX env var or /.dockerenv
362        // controls this — skip the assertion there to avoid false failures.
363        #[cfg(not(target_os = "linux"))]
364        {
365            let cfg = BrowserConfig::default();
366            let args = cfg.effective_args();
367            assert!(!args.iter().any(|a| a == "--no-sandbox"));
368        }
369    }
370
371    #[test]
372    fn effective_args_include_disable_dev_shm() {
373        let cfg = BrowserConfig::default();
374        let args = cfg.effective_args();
375        assert!(args.iter().any(|a| a.contains("disable-dev-shm-usage")));
376    }
377
378    #[test]
379    fn no_window_size_arg_when_none() {
380        let cfg = BrowserConfig {
381            window_size: None,
382            ..BrowserConfig::default()
383        };
384        let args = cfg.effective_args();
385        assert!(!args.iter().any(|a| a.contains("--window-size")));
386    }
387
388    #[test]
389    fn custom_arg_appended() {
390        let cfg = BrowserConfig::builder()
391            .arg("--user-agent=MyCustomBot/1.0".to_string())
392            .build();
393        let args = cfg.effective_args();
394        assert!(args.iter().any(|a| a.contains("MyCustomBot")));
395    }
396
397    #[test]
398    fn proxy_bypass_list_arg_injected() {
399        let cfg = BrowserConfig::builder()
400            .proxy("http://proxy:8080".to_string())
401            .proxy_bypass_list("<local>,localhost".to_string())
402            .build();
403        let args = cfg.effective_args();
404        assert!(args.iter().any(|a| a.contains("proxy-bypass-list")));
405    }
406
407    #[test]
408    fn headless_mode_preserved_in_config() {
409        let cfg = BrowserConfig::builder().headless(false).build();
410        assert!(!cfg.headless);
411        let cfg2 = BrowserConfig::builder().headless(true).build();
412        assert!(cfg2.headless);
413    }
414
415    #[test]
416    fn launch_timeout_default_is_non_zero() {
417        let cfg = BrowserConfig::default();
418        assert!(!cfg.launch_timeout.is_zero());
419    }
420
421    #[test]
422    fn cdp_timeout_default_is_non_zero() {
423        let cfg = BrowserConfig::default();
424        assert!(!cfg.cdp_timeout.is_zero());
425    }
426}