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        // Set headless / headed mode on the chromiumoxide builder.
88        // - headed: with_head()
89        // - headless new (default): new_headless_mode() → --headless=new
90        // - headless legacy: default (chromiumoxide defaults to old --headless)
91        if !config.headless {
92            builder = builder.with_head();
93        } else if config.headless_mode == crate::config::HeadlessMode::New {
94            builder = builder.new_headless_mode();
95        }
96
97        if let Some(path) = &config.chrome_path {
98            builder = builder.chrome_executable(path);
99        }
100
101        // Use the caller-supplied profile dir, or generate a unique temp dir
102        // per instance so concurrent pools never race on SingletonLock.
103        let data_dir = config
104            .user_data_dir
105            .clone()
106            .unwrap_or_else(|| std::env::temp_dir().join(format!("stygian-{id}")));
107        builder = builder.user_data_dir(&data_dir);
108
109        for arg in &args {
110            // chromiumoxide's ArgsBuilder prepends "--" when formatting args, so
111            // we strip any existing "--" prefix first to avoid "----arg" in Chrome.
112            let stripped = arg.strip_prefix("--").unwrap_or(arg.as_str());
113            builder = builder.arg(stripped);
114        }
115
116        if let Some((w, h)) = config.window_size {
117            builder = builder.window_size(w, h);
118        }
119
120        let cdp_cfg = builder
121            .build()
122            .map_err(|e| BrowserError::LaunchFailed { reason: e })?;
123
124        let (browser, mut handler) = timeout(launch_timeout, Browser::launch(cdp_cfg))
125            .await
126            .map_err(|_| BrowserError::Timeout {
127                operation: "browser.launch".to_string(),
128                duration_ms: u64::try_from(launch_timeout.as_millis()).unwrap_or(u64::MAX),
129            })?
130            .map_err(|e| BrowserError::LaunchFailed {
131                reason: e.to_string(),
132            })?;
133
134        // Spawn the chromiumoxide message handler; it must run for the browser
135        // to remain responsive.
136        tokio::spawn(async move { while handler.next().await.is_some() {} });
137
138        info!(browser_id = %id, "Browser launched successfully");
139
140        Ok(Self {
141            browser,
142            config,
143            launched_at: Instant::now(),
144            healthy: true,
145            id,
146        })
147    }
148
149    // ─── Health ───────────────────────────────────────────────────────────────
150
151    /// Returns `true` if the browser is currently considered healthy.
152    ///
153    /// This is a cached value updated by [`BrowserInstance::health_check`].
154    pub const fn is_healthy_cached(&self) -> bool {
155        self.healthy
156    }
157
158    /// Actively probe the browser with a CDP request.
159    ///
160    /// Sends `Browser.getVersion` and waits up to `cdp_timeout`.  Updates the
161    /// internal healthy flag and returns the result.
162    ///
163    /// # Example
164    ///
165    /// ```no_run
166    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
167    ///
168    /// # async fn run() -> stygian_browser::error::Result<()> {
169    /// let mut instance = BrowserInstance::launch(BrowserConfig::default()).await?;
170    /// assert!(instance.is_healthy().await);
171    /// # Ok(())
172    /// # }
173    /// ```
174    pub async fn is_healthy(&mut self) -> bool {
175        match self.health_check().await {
176            Ok(()) => true,
177            Err(e) => {
178                warn!(browser_id = %self.id, error = %e, "Health check failed");
179                false
180            }
181        }
182    }
183
184    /// Run a health check and return a structured [`Result`].
185    ///
186    /// Pings the browser with the CDP `Browser.getVersion` RPC.
187    pub async fn health_check(&mut self) -> Result<()> {
188        let op_timeout = self.config.cdp_timeout;
189
190        timeout(op_timeout, self.browser.version())
191            .await
192            .map_err(|_| {
193                self.healthy = false;
194                BrowserError::Timeout {
195                    operation: "Browser.getVersion".to_string(),
196                    duration_ms: u64::try_from(op_timeout.as_millis()).unwrap_or(u64::MAX),
197                }
198            })?
199            .map_err(|e| {
200                self.healthy = false;
201                BrowserError::CdpError {
202                    operation: "Browser.getVersion".to_string(),
203                    message: e.to_string(),
204                }
205            })?;
206
207        self.healthy = true;
208        Ok(())
209    }
210
211    // ─── Accessors ────────────────────────────────────────────────────────────
212
213    /// Access the underlying `chromiumoxide` [`Browser`].
214    pub const fn browser(&self) -> &Browser {
215        &self.browser
216    }
217
218    /// Mutable access to the underlying `chromiumoxide` [`Browser`].
219    pub const fn browser_mut(&mut self) -> &mut Browser {
220        &mut self.browser
221    }
222
223    /// Instance ID (ULID) for log correlation.
224    pub fn id(&self) -> &str {
225        &self.id
226    }
227
228    /// How long has this instance been alive.
229    pub fn uptime(&self) -> Duration {
230        self.launched_at.elapsed()
231    }
232
233    /// The config snapshot used at launch.
234    pub const fn config(&self) -> &BrowserConfig {
235        &self.config
236    }
237
238    // ─── Shutdown ─────────────────────────────────────────────────────────────
239
240    /// Gracefully close the browser.
241    ///
242    /// Sends `Browser.close` and waits up to `cdp_timeout`.  Any errors during
243    /// tear-down are logged but not propagated so the caller can always clean up.
244    ///
245    /// # Example
246    ///
247    /// ```no_run
248    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
249    ///
250    /// # async fn run() -> stygian_browser::error::Result<()> {
251    /// let mut instance = BrowserInstance::launch(BrowserConfig::default()).await?;
252    /// instance.shutdown().await?;
253    /// # Ok(())
254    /// # }
255    /// ```
256    pub async fn shutdown(mut self) -> Result<()> {
257        info!(browser_id = %self.id, "Shutting down browser");
258
259        let op_timeout = self.config.cdp_timeout;
260
261        if let Err(e) = timeout(op_timeout, self.browser.close()).await {
262            // Timeout — log and continue cleanup
263            warn!(
264                browser_id = %self.id,
265                "Browser.close timed out after {}ms: {e}",
266                op_timeout.as_millis()
267            );
268        }
269
270        self.healthy = false;
271        info!(browser_id = %self.id, "Browser shut down");
272        Ok(())
273    }
274
275    /// Open a new tab and return a [`crate::page::PageHandle`].
276    ///
277    /// The handle closes the tab automatically when dropped.
278    ///
279    /// # Errors
280    ///
281    /// Returns [`BrowserError::CdpError`] if a new page cannot be created.
282    ///
283    /// # Example
284    ///
285    /// ```no_run
286    /// use stygian_browser::{BrowserConfig, browser::BrowserInstance};
287    ///
288    /// # async fn run() -> stygian_browser::error::Result<()> {
289    /// let mut instance = BrowserInstance::launch(BrowserConfig::default()).await?;
290    /// let page = instance.new_page().await?;
291    /// drop(page);
292    /// instance.shutdown().await?;
293    /// # Ok(())
294    /// # }
295    /// ```
296    pub async fn new_page(&self) -> crate::error::Result<crate::page::PageHandle> {
297        use tokio::time::timeout;
298
299        let cdp_timeout = self.config.cdp_timeout;
300
301        let page = timeout(cdp_timeout, self.browser.new_page("about:blank"))
302            .await
303            .map_err(|_| crate::error::BrowserError::Timeout {
304                operation: "Browser.newPage".to_string(),
305                duration_ms: u64::try_from(cdp_timeout.as_millis()).unwrap_or(u64::MAX),
306            })?
307            .map_err(|e| crate::error::BrowserError::CdpError {
308                operation: "Browser.newPage".to_string(),
309                message: e.to_string(),
310            })?;
311
312        // Apply stealth injection scripts for all active stealth levels.
313        #[cfg(feature = "stealth")]
314        crate::stealth::apply_stealth_to_page(&page, &self.config).await?;
315
316        Ok(crate::page::PageHandle::new(page, cdp_timeout))
317    }
318}
319
320// ─── Tests ────────────────────────────────────────────────────────────────────
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    /// Verify `BrowserConfig` `effective_args` includes anti-detection flags.
327    ///
328    /// This is a unit test that doesn't require a real Chrome binary.
329    #[test]
330    fn effective_args_contain_automation_flag() {
331        let config = BrowserConfig::default();
332        let args = config.effective_args();
333        assert!(
334            args.iter().any(|a| a.contains("AutomationControlled")),
335            "Expected --disable-blink-features=AutomationControlled in args: {args:?}"
336        );
337    }
338
339    #[test]
340    fn proxy_arg_injected_when_set() {
341        let config = BrowserConfig::builder()
342            .proxy("http://proxy.example.com:8080".to_string())
343            .build();
344        let args = config.effective_args();
345        assert!(
346            args.iter().any(|a| a.contains("proxy.example.com")),
347            "Expected proxy arg in {args:?}"
348        );
349    }
350
351    #[test]
352    fn window_size_arg_injected() {
353        let config = BrowserConfig::builder().window_size(1280, 720).build();
354        let args = config.effective_args();
355        assert!(
356            args.iter().any(|a| a.contains("1280")),
357            "Expected window-size arg in {args:?}"
358        );
359    }
360
361    #[test]
362    fn browser_instance_is_send_sync() {
363        fn assert_send<T: Send>() {}
364        fn assert_sync<T: Sync>() {}
365        assert_send::<BrowserInstance>();
366        assert_sync::<BrowserInstance>();
367    }
368
369    #[test]
370    fn no_sandbox_absent_by_default_on_non_linux() {
371        // On non-Linux (macOS, Windows) is_containerized() always returns false,
372        // so --no-sandbox must NOT appear in the default args unless overridden.
373        // On Linux in CI/Docker the STYGIAN_DISABLE_SANDBOX env var or /.dockerenv
374        // controls this — skip the assertion there to avoid false failures.
375        #[cfg(not(target_os = "linux"))]
376        {
377            let cfg = BrowserConfig::default();
378            let args = cfg.effective_args();
379            assert!(!args.iter().any(|a| a == "--no-sandbox"));
380        }
381    }
382
383    #[test]
384    fn effective_args_include_disable_dev_shm() {
385        let cfg = BrowserConfig::default();
386        let args = cfg.effective_args();
387        assert!(args.iter().any(|a| a.contains("disable-dev-shm-usage")));
388    }
389
390    #[test]
391    fn no_window_size_arg_when_none() {
392        let cfg = BrowserConfig {
393            window_size: None,
394            ..BrowserConfig::default()
395        };
396        let args = cfg.effective_args();
397        assert!(!args.iter().any(|a| a.contains("--window-size")));
398    }
399
400    #[test]
401    fn custom_arg_appended() {
402        let cfg = BrowserConfig::builder()
403            .arg("--user-agent=MyCustomBot/1.0".to_string())
404            .build();
405        let args = cfg.effective_args();
406        assert!(args.iter().any(|a| a.contains("MyCustomBot")));
407    }
408
409    #[test]
410    fn proxy_bypass_list_arg_injected() {
411        let cfg = BrowserConfig::builder()
412            .proxy("http://proxy:8080".to_string())
413            .proxy_bypass_list("<local>,localhost".to_string())
414            .build();
415        let args = cfg.effective_args();
416        assert!(args.iter().any(|a| a.contains("proxy-bypass-list")));
417    }
418
419    #[test]
420    fn headless_mode_preserved_in_config() {
421        let cfg = BrowserConfig::builder().headless(false).build();
422        assert!(!cfg.headless);
423        let cfg2 = BrowserConfig::builder().headless(true).build();
424        assert!(cfg2.headless);
425    }
426
427    #[test]
428    fn launch_timeout_default_is_non_zero() {
429        let cfg = BrowserConfig::default();
430        assert!(!cfg.launch_timeout.is_zero());
431    }
432
433    #[test]
434    fn cdp_timeout_default_is_non_zero() {
435        let cfg = BrowserConfig::default();
436        assert!(!cfg.cdp_timeout.is_zero());
437    }
438}