Expand description
Browser pool with lifecycle management.
This module provides BrowserPool, the main entry point for managing
a pool of headless Chrome browsers with automatic lifecycle management.
§Overview
The browser pool provides:
- Connection Pooling: Reuses browser instances to avoid expensive startup costs
- Health Monitoring: Background thread continuously checks browser health
- TTL Management: Automatically retires old browsers and creates replacements
- Race-Free Design: Careful lock ordering prevents deadlocks
- Graceful Shutdown: Clean termination of all background tasks
- RAII Pattern: Automatic return of browsers to pool via Drop
§Architecture
BrowserPool
├─ BrowserPoolInner (shared state)
│ ├─ available: Vec<TrackedBrowser> (pooled, ready to use)
│ ├─ active: HashMap<id, TrackedBrowser> (in-use, tracked for health)
│ └─ replacement_tasks: Vec<JoinHandle> (async replacement creators)
└─ keep_alive_handle: JoinHandle (health monitoring thread)§Critical Invariants
- Lock Order: Always acquire
activebeforeavailableto prevent deadlocks - Shutdown Flag: Check before all expensive operations
- Health Checks: Never hold locks during I/O operations
§Example
use html2pdf_api::{BrowserPool, BrowserPoolConfigBuilder, ChromeBrowserFactory};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create pool
let mut pool = BrowserPool::builder()
.config(
BrowserPoolConfigBuilder::new()
.max_pool_size(5)
.warmup_count(3)
.build()?
)
.factory(Box::new(ChromeBrowserFactory::with_defaults()))
.build()?;
// Warmup
pool.warmup().await?;
// Use browsers
{
let browser = pool.get()?;
let tab = browser.new_tab()?;
// ... do work ...
} // browser returned to pool automatically
// Shutdown
pool.shutdown_async().await;
Ok(())
}Structs§
- Browser
Pool - Main browser pool with lifecycle management.
- Browser
Pool Builder - Builder for constructing a
BrowserPoolwith validation.
Functions§
- init_
browser_ pool - Initialize browser pool from environment variables.