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