Skip to content

The headless browser for AI agents and web scraping

serve: recycle workers by connections, RSS or age

flolep26070f27e69b7b31
diff --git a/Cargo.lock b/Cargo.lock
index 767d6170..9fac37f4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2031,6 +2031,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"clap",
+ "futures-util",
"image",
"libc",
"obscura-browser",
@@ -2042,6 +2043,7 @@ dependencies = [
"serde",
"serde_json",
"tokio",
+ "tokio-tungstenite",
"tracing",
"tracing-subscriber",
"url",
diff --git a/crates/obscura-cli/Cargo.toml b/crates/obscura-cli/Cargo.toml
index bebc7403..e50b06e7 100644
--- a/crates/obscura-cli/Cargo.toml
+++ b/crates/obscura-cli/Cargo.toml
@@ -39,3 +39,5 @@ libc = "0.2"
[dev-dependencies]
image = { version = "0.25", default-features = false, features = ["png"] }
+tokio-tungstenite = { workspace = true }
+futures-util = "0.3"
diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rs
index e895aff1..a55207fb 100644
--- a/crates/obscura-cli/src/main.rs
+++ b/crates/obscura-cli/src/main.rs
@@ -1,6 +1,8 @@
use std::sync::Arc;
use std::time::Instant;
+mod pool;
+
use clap::{Parser, Subcommand};
use obscura_browser::{BrowserContext, Page};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
@@ -88,6 +90,27 @@ enum Command {
#[arg(long, default_value_t = obscura_cdp::DEFAULT_MAX_CONNECTIONS)]
max_connections: usize,
+ /// Recycle a worker after it has served this many CDP connections
+ /// (/json discovery requests do not count). Needs --workers > 1. The
+ /// worker drains and a replacement takes its place; off by default.
+ #[arg(long, value_name = "N")]
+ worker_max_connections: Option<usize>,
+
+ /// Recycle a worker whose resident memory exceeds this many MB,
+ /// sampled every 2s from /proc (Linux only). Needs --workers > 1.
+ #[arg(long, value_name = "MB")]
+ worker_max_rss: Option<u64>,
+
+ /// Recycle a worker after it has run this many seconds. Needs
+ /// --workers > 1.
+ #[arg(long, value_name = "SECS")]
+ worker_max_age: Option<u64>,
+
+ /// Seconds a replaced worker may keep serving its live connections
+ /// before it is killed.
+ #[arg(long, value_name = "SECS", default_value_t = 120)]
+ worker_drain_timeout: u64,
+
/// Atomically publish the bound address after V8 initialization.
#[arg(long, value_name = "PATH")]
ready_file: Option<std::path::PathBuf>,
@@ -426,12 +449,27 @@ async fn run_cli() -> anyhow::Result<()> {
user_agent,
workers,
max_connections,
+ worker_max_connections,
+ worker_max_rss,
+ worker_max_age,
+ worker_drain_timeout,
ready_file,
allow_file_access,
storage_dir,
font_dirs,
quiet: _,
}) => {
+ let policy = pool::RecyclePolicy {
+ max_connections: worker_max_connections,
+ max_rss_mb: worker_max_rss,
+ max_age: worker_max_age.map(Duration::from_secs),
+ };
+ if policy.enabled() && workers <= 1 {
+ anyhow::bail!("--worker-max-* options require --workers > 1");
+ }
+ if policy.max_rss_mb.is_some() && !cfg!(target_os = "linux") {
+ tracing::warn!("--worker-max-rss is only supported on Linux and is ignored");
+ }
// Fall back to OBSCURA_PROXY so a proxy can be supplied without
// putting credentials on the command line. The multi-worker load
// balancer passes the proxy to each worker this way (issue #366).
@@ -479,6 +517,8 @@ async fn run_cli() -> anyhow::Result<()> {
user_agent,
font_dirs,
max_connections,
+ policy,
+ Duration::from_secs(worker_drain_timeout),
)
.await?;
} else {
@@ -637,6 +677,164 @@ async fn wait_for_serve_worker(
}
}
+/// How often each supervisor re-checks its recycle policy (RSS and age have no
+/// event to wait on; the connection limit also wakes it directly).
+const RECYCLE_POLL: Duration = Duration::from_secs(2);
+
+fn free_port() -> std::io::Result<u16> {
+ Ok(std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
+}
+
+type WorkerCommand = Arc<dyn Fn(u16) -> TokioCommand + Send + Sync>;
+
+/// Replace a dead worker, retrying until one starts. Always picks a fresh port.
+/// Returns `None` once the balancer is shutting down.
+async fn respawn_worker(
+ slot: &pool::Slot,
+ make_cmd: &WorkerCommand,
+ max_connections: Option<usize>,
+ stop: &tokio::sync::watch::Receiver<()>,
+) -> Option<tokio::process::Child> {
+ loop {
+ // ponytail: fixed retry bounds crash loops; add backoff if
+ // persistently failing worker configurations need it.
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ if stop.has_changed().unwrap_or(true) {
+ return None;
+ }
+ let port = match free_port() {
+ Ok(port) => port,
+ Err(error) => {
+ tracing::warn!("worker port allocation failed: {}", error);
+ continue;
+ }
+ };
+ match make_cmd(port).spawn() {
+ Ok(mut replacement) => {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ match wait_for_serve_worker(&mut replacement, port, deadline).await {
+ Ok(()) => {
+ slot.replace(pool::Worker::new(port, max_connections, slot.wake.clone()));
+ return Some(replacement);
+ }
+ Err(error) => tracing::warn!("worker {} restart failed: {}", port, error),
+ }
+ }
+ Err(error) => tracing::warn!("worker {} spawn failed: {}", port, error),
+ }
+ }
+}
+
+/// Let a replaced worker finish its live connections, then kill it. On
+/// shutdown it is stopped like the active workers.
+async fn drain_worker(
+ mut child: tokio::process::Child,
+ old: Arc<pool::Worker>,
+ timeout: Duration,
+ mut stop: tokio::sync::watch::Receiver<()>,
+) {
+ let deadline = tokio::time::Instant::now() + timeout;
+ let outcome = loop {
+ if old.active() == 0 {
+ break "drained".to_string();
+ }
+ if tokio::time::Instant::now() >= deadline {
+ break format!("drain timeout, dropping {} live connections", old.active());
+ }
+ tokio::select! {
+ _ = child.wait() => break "exited while draining".to_string(),
+ _ = stop.changed() => {
+ stop_worker(&mut child).await;
+ break "stopped at shutdown".to_string();
+ }
+ _ = tokio::time::sleep(Duration::from_millis(100)) => {}
+ }
+ };
+ let _ = child.kill().await;
+ tracing::info!("worker on port {} retired: {}", old.port, outcome);
+}
+
+async fn supervise_worker(
+ slot: Arc<pool::Slot>,
+ mut child: tokio::process::Child,
+ make_cmd: WorkerCommand,
+ policy: pool::RecyclePolicy,
+ drain_timeout: Duration,
+ recycles: Arc<tokio::sync::Semaphore>,
+ mut stop: tokio::sync::watch::Receiver<()>,
+) {
+ // Replaced workers still draining; awaited at shutdown so they are stopped
+ // gracefully too.
+ let mut drains = tokio::task::JoinSet::new();
+ let mut tick = tokio::time::interval(RECYCLE_POLL);
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ while drains.try_join_next().is_some() {}
+ let worker = slot.current();
+ tokio::select! {
+ _ = stop.changed() => {
+ tokio::join!(stop_worker(&mut child), async {
+ while drains.join_next().await.is_some() {}
+ });
+ return;
+ }
+ status = child.wait() => {
+ worker.set_ready(false);
+ tracing::warn!("worker on port {} exited: {:?}", worker.port, status);
+ let Some(replacement) =
+ respawn_worker(&slot, &make_cmd, policy.max_connections, &stop).await
+ else {
+ while drains.join_next().await.is_some() {}
+ return;
+ };
+ child = replacement;
+ continue;
+ }
+ _ = slot.wake.notified() => {}
+ _ = tick.tick() => {}
+ }
+ if !policy.enabled() {
+ continue;
+ }
+ let rss = policy.max_rss_mb.and(child.id()).and_then(pool::rss_mb);
+ let Some(reason) = policy.reason(worker.served(), rss, worker.born.elapsed()) else {
+ continue;
+ };
+ // Bound concurrent replacement startups (not draining); if no permit
+ // is free, retry on the next tick and keep serving meanwhile.
+ let Ok(permit) = recycles.clone().try_acquire_owned() else { continue };
+ let started = Instant::now();
+ let spawned = free_port().and_then(|port| make_cmd(port).spawn().map(|c| (port, c)));
+ let (port, mut next) = match spawned {
+ Ok(spawned) => spawned,
+ Err(error) => {
+ tracing::warn!("recycle of worker on port {} failed to spawn: {}", worker.port, error);
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ continue;
+ }
+ };
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
+ if let Err(error) = wait_for_serve_worker(&mut next, port, deadline).await {
+ tracing::warn!(
+ "recycle of worker on port {} aborted, replacement failed: {}",
+ worker.port, error
+ );
+ let _ = next.kill().await;
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ continue;
+ }
+ let old = slot.replace(pool::Worker::new(port, policy.max_connections, slot.wake.clone()));
+ tracing::info!(
+ "recycling worker on port {} (pid {:?}, served {}, live {}, age {}s): {}; replacement on port {} ready in {} ms",
+ old.port, child.id(), old.served(), old.active(), old.born.elapsed().as_secs(),
+ reason, port, started.elapsed().as_millis()
+ );
+ let retired = std::mem::replace(&mut child, next);
+ drop(permit);
+ drains.spawn(drain_worker(retired, old, drain_timeout, stop.clone()));
+ }
+}
+
async fn run_multi_worker_serve(
port: u16,
host: String,
@@ -646,10 +844,11 @@ async fn run_multi_worker_serve(
user_agent: Option<String>,
font_dirs: Vec<std::path::PathBuf>,
max_connections: usize,
+ policy: pool::RecyclePolicy,
+ drain_timeout: Duration,
) -> anyhow::Result<()> {
use tokio::io::AsyncWriteExt as _;
use tokio::net::TcpListener;
- use std::sync::atomic::{AtomicBool, Ordering};
let exe = std::env::current_exe()?;
// Register before spawning workers so an early SIGTERM is not fatal to the
@@ -668,11 +867,8 @@ async fn run_multi_worker_serve(
let worker_port = reservation.local_addr()?.port();
reservations.push((worker_port, reservation));
}
- let mut children = Vec::new();
- let mut worker_ports = Vec::with_capacity(workers as usize);
-
- for (index, (worker_port, reservation)) in reservations.into_iter().enumerate() {
- drop(reservation);
+ let host_for_workers = host.clone();
+ let make_cmd: WorkerCommand = Arc::new(move |worker_port: u16| {
let mut cmd = TokioCommand::new(&exe);
cmd.kill_on_drop(true);
cmd.arg("serve").arg("--port").arg(worker_port.to_string());
@@ -682,7 +878,7 @@ async fn run_multi_worker_serve(
// Workers receive the client-facing Host header through the TCP
// load balancer. Let their CDP security gate accept that public port
// while it continues to reject foreign hosts and browser origins.
- cmd.env("OBSCURA_CDP_FORWARDED_HOST", &host);
+ cmd.env("OBSCURA_CDP_FORWARDED_HOST", &host_for_workers);
cmd.env("OBSCURA_CDP_FORWARDED_PORT", port.to_string());
if let Some(ref p) = proxy {
// Pass the proxy (which may embed credentials) via the environment,
@@ -702,63 +898,46 @@ async fn run_multi_worker_serve(
}
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::inherit());
+ cmd
+ });
+ let mut children = Vec::new();
- let child = cmd.spawn()?;
+ for (index, (worker_port, reservation)) in reservations.into_iter().enumerate() {
+ drop(reservation);
+ let child = make_cmd(worker_port).spawn()?;
tracing::info!("Worker {} on port {}", index + 1, worker_port);
- children.push((child, cmd));
- worker_ports.push(worker_port);
+ children.push((child, worker_port));
}
// Wait only until every worker has bound its control port. The old fixed
// 500 ms sleep dominated multi-worker startup even when workers were ready
// in a few milliseconds.
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
- for ((child, _), &worker_port) in children.iter_mut().zip(&worker_ports) {
- wait_for_serve_worker(child, worker_port, deadline).await?;
+ for (child, worker_port) in children.iter_mut() {
+ wait_for_serve_worker(child, *worker_port, deadline).await?;
}
- let mut availability = Vec::with_capacity(workers as usize);
+ // At most a tenth of the pool (minimum one) starts a replacement at a
+ // time, so a fleet that reaches its limit together does not stampede the
+ // CPU with simultaneous V8 startups.
+ let recycles = Arc::new(tokio::sync::Semaphore::new((workers as usize / 10).max(1)));
+ let mut slots = Vec::with_capacity(workers as usize);
let mut supervisors = tokio::task::JoinSet::new();
let (stop_tx, stop_rx) = tokio::sync::watch::channel(());
- for ((mut child, mut cmd), &worker_port) in children.into_iter().zip(&worker_ports) {
- let ready = Arc::new(AtomicBool::new(true));
- availability.push(ready.clone());
- let mut stop = stop_rx.clone();
- supervisors.spawn(async move {
- loop {
- let status = tokio::select! {
- status = child.wait() => status,
- _ = stop.changed() => {
- stop_worker(&mut child).await;
- return;
- }
- };
- ready.store(false, Ordering::Relaxed);
- tracing::warn!("worker on port {} exited: {:?}", worker_port, status);
- loop {
- // ponytail: fixed retry bounds crash loops; add backoff if
- // persistently failing worker configurations need it.
- tokio::time::sleep(Duration::from_millis(100)).await;
- if stop.has_changed().unwrap_or(true) {
- return;
- }
- match cmd.spawn() {
- Ok(mut replacement) => {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
- match wait_for_serve_worker(&mut replacement, worker_port, deadline).await {
- Ok(()) => {
- child = replacement;
- ready.store(true, Ordering::Relaxed);
- break;
- }
- Err(error) => tracing::warn!("worker {} restart failed: {}", worker_port, error),
- }
- }
- Err(error) => tracing::warn!("worker {} spawn failed: {}", worker_port, error),
- }
- }
- }
- });
+ for (child, worker_port) in children {
+ let wake = Arc::new(tokio::sync::Notify::new());
+ let first = pool::Worker::new(worker_port, policy.max_connections, wake.clone());
+ let slot = pool::Slot::new(first, wake);
+ slots.push(slot.clone());
+ supervisors.spawn(supervise_worker(
+ slot,
+ child,
+ make_cmd.clone(),
+ policy,
+ drain_timeout,
+ recycles.clone(),
+ stop_rx.clone(),
+ ));
}
// The load balancer is bound to the requested host, not hardcoded loopback.
@@ -767,6 +946,9 @@ async fn run_multi_worker_serve(
// refused from outside the container (issue #336). Workers stay on loopback
// and are only reached by the balancer.
tracing::info!("Load balancer on {}:{}, {} workers", host, port, workers);
+ if policy.enabled() {
+ tracing::info!("Worker recycling: {:?}, drain timeout {}s", policy, drain_timeout.as_secs());
+ }
let mut next_worker = 0usize;
@@ -778,12 +960,7 @@ async fn run_multi_worker_serve(
if let Err(error) = client_stream.set_nodelay(true) {
tracing::warn!("client {} TCP_NODELAY failed: {}", peer_addr, error);
}
- let worker_port = (0..worker_ports.len()).find_map(|_| {
- let index = next_worker % worker_ports.len();
- next_worker = next_worker.wrapping_add(1);
- availability[index].load(Ordering::Relaxed).then_some(worker_ports[index])
- });
- let Some(worker_port) = worker_port else {
+ let Some(conn) = pool::pick(&slots, &mut next_worker) else {
tokio::spawn(async move {
let mut client = client_stream;
let _ = client.write_all(b"HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n").await;
@@ -792,6 +969,7 @@ async fn run_multi_worker_serve(
continue;
};
+ let worker_port = conn.port();
tracing::debug!("Routing {} to worker port {}", peer_addr, worker_port);
let mut peek_buf = [0u8; 4];
@@ -827,6 +1005,8 @@ async fn run_multi_worker_serve(
);
}
tokio::spawn(async move {
+ // Held while proxying so a draining worker waits for it.
+ let _conn = conn;
let std_stream = match client_stream.into_std() {
Ok(s) => s,
Err(e) => {
@@ -867,7 +1047,9 @@ async fn run_multi_worker_serve(
}
let worker_addr = format!("127.0.0.1:{}", worker_port);
+ conn.count_session();
tokio::spawn(async move {
+ let _conn = conn;
match tokio::net::TcpStream::connect(&worker_addr).await {
Ok(mut worker_stream) => {
if let Err(error) = worker_stream.set_nodelay(true) {
diff --git a/crates/obscura-cli/src/pool.rs b/crates/obscura-cli/src/pool.rs
new file mode 100644
index 00000000..d7342a8d
--- /dev/null
+++ b/crates/obscura-cli/src/pool.rs
@@ -0,0 +1,267 @@
+//! Worker pool state for the multi-worker `serve` load balancer: routing,
+//! per-worker connection accounting, and the recycle policy.
+
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use tokio::sync::Notify;
+
+/// When a worker should be replaced. Every limit is off by default.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct RecyclePolicy {
+ pub max_connections: Option<usize>,
+ pub max_rss_mb: Option<u64>,
+ pub max_age: Option<Duration>,
+}
+
+impl RecyclePolicy {
+ pub fn enabled(&self) -> bool {
+ self.max_connections.is_some() || self.max_rss_mb.is_some() || self.max_age.is_some()
+ }
+
+ /// The first threshold that is exceeded, if any. `rss_mb` is `None` when it
+ /// could not be sampled (non-Linux, process gone), which never recycles.
+ pub fn reason(&self, served: usize, rss_mb: Option<u64>, age: Duration) -> Option<String> {
+ if let Some(max) = self.max_connections {
+ if served >= max {
+ return Some(format!("served {served} connections (limit {max})"));
+ }
+ }
+ if let (Some(max), Some(rss)) = (self.max_rss_mb, rss_mb) {
+ if rss >= max {
+ return Some(format!("rss {rss} MB (limit {max} MB)"));
+ }
+ }
+ if let Some(max) = self.max_age {
+ if age >= max {
+ return Some(format!("age {}s (limit {}s)", age.as_secs(), max.as_secs()));
+ }
+ }
+ None
+ }
+}
+
+/// Resident set size of `pid` in MB. Linux only; `None` elsewhere.
+pub fn rss_mb(pid: u32) -> Option<u64> {
+ let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
+ let kb: u64 = status
+ .lines()
+ .find_map(|line| line.strip_prefix("VmRSS:"))?
+ .split_whitespace()
+ .next()?
+ .parse()
+ .ok()?;
+ Some(kb / 1024)
+}
+
+/// One worker process generation: the port it listens on and its live load.
+pub struct Worker {
+ pub port: u16,
+ pub born: Instant,
+ ready: AtomicBool,
+ active: AtomicUsize,
+ served: AtomicUsize,
+ max_connections: Option<usize>,
+ wake: Arc<Notify>,
+}
+
+impl Worker {
+ pub fn new(port: u16, max_connections: Option<usize>, wake: Arc<Notify>) -> Arc<Self> {
+ Arc::new(Worker {
+ port,
+ born: Instant::now(),
+ ready: AtomicBool::new(true),
+ active: AtomicUsize::new(0),
+ served: AtomicUsize::new(0),
+ max_connections,
+ wake,
+ })
+ }
+
+ pub fn set_ready(&self, ready: bool) {
+ self.ready.store(ready, Ordering::Relaxed);
+ }
+
+ pub fn active(&self) -> usize {
+ self.active.load(Ordering::Relaxed)
+ }
+
+ pub fn served(&self) -> usize {
+ self.served.load(Ordering::Relaxed)
+ }
+
+ /// Live proxied connection; released on drop.
+ pub fn connection(self: &Arc<Self>) -> Connection {
+ self.active.fetch_add(1, Ordering::Relaxed);
+ Connection(self.clone())
+ }
+}
+
+pub struct Connection(Arc<Worker>);
+
+impl Connection {
+ pub fn port(&self) -> u16 {
+ self.0.port
+ }
+
+ /// Count this as a CDP session (not a /json discovery request) and wake
+ /// the supervisor when the connection limit is reached.
+ pub fn count_session(&self) {
+ let served = self.0.served.fetch_add(1, Ordering::Relaxed) + 1;
+ if self.0.max_connections.is_some_and(|max| served >= max) {
+ self.0.wake.notify_one();
+ }
+ }
+}
+
+impl Drop for Connection {
+ fn drop(&mut self) {
+ self.0.active.fetch_sub(1, Ordering::Relaxed);
+ }
+}
+
+/// One pool position. It always holds the worker that takes new connections;
+/// a replaced worker is no longer reachable from here, which is what drains it.
+pub struct Slot {
+ current: Mutex<Arc<Worker>>,
+ pub wake: Arc<Notify>,
+}
+
+impl Slot {
+ pub fn new(first: Arc<Worker>, wake: Arc<Notify>) -> Arc<Self> {
+ Arc::new(Slot { current: Mutex::new(first), wake })
+ }
+
+ pub fn current(&self) -> Arc<Worker> {
+ self.current.lock().unwrap().clone()
+ }
+
+ /// Route new connections to `next`; returns the worker that now drains.
+ pub fn replace(&self, next: Arc<Worker>) -> Arc<Worker> {
+ std::mem::replace(&mut *self.current.lock().unwrap(), next)
+ }
+}
+
+/// Round-robin over ready workers, skipping crashed ones.
+pub fn pick(slots: &[Arc<Slot>], next: &mut usize) -> Option<Connection> {
+ (0..slots.len()).find_map(|_| {
+ let worker = slots[*next % slots.len()].current();
+ *next = next.wrapping_add(1);
+ worker.ready.load(Ordering::Relaxed).then(|| worker.connection())
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const S: Duration = Duration::from_secs(1);
+
+ #[test]
+ fn default_policy_never_recycles() {
+ let policy = RecyclePolicy::default();
+ assert!(!policy.enabled());
+ assert!(policy.reason(usize::MAX, Some(u64::MAX), S * 100_000).is_none());
+ }
+
+ #[test]
+ fn thresholds_trigger_at_the_limit() {
+ let policy = RecyclePolicy {
+ max_connections: Some(3),
+ max_rss_mb: Some(500),
+ max_age: Some(S * 60),
+ };
+ assert!(policy.reason(2, Some(499), S * 59).is_none());
+ assert!(policy.reason(3, Some(0), S).unwrap().contains("connections"));
+ assert!(policy.reason(0, Some(500), S).unwrap().contains("rss"));
+ assert!(policy.reason(0, Some(0), S * 60).unwrap().contains("age"));
+ // An unreadable RSS never triggers the RSS limit.
+ assert!(policy.reason(0, None, S).is_none());
+ }
+
+ fn pool(n: u16, max: Option<usize>) -> Vec<Arc<Slot>> {
+ (0..n)
+ .map(|i| {
+ let wake = Arc::new(Notify::new());
+ Slot::new(Worker::new(9000 + i, max, wake.clone()), wake)
+ })
+ .collect()
+ }
+
+ #[test]
+ fn pick_round_robins_and_skips_unready() {
+ let slots = pool(3, None);
+ let mut next = 0;
+ let ports: Vec<u16> = (0..3).map(|_| pick(&slots, &mut next).unwrap().port()).collect();
+ assert_eq!(ports, [9000, 9001, 9002]);
+ slots[1].current().set_ready(false);
+ for _ in 0..6 {
+ assert_ne!(pick(&slots, &mut next).unwrap().port(), 9001);
+ }
+ for slot in &slots {
+ slot.current().set_ready(false);
+ }
+ assert!(pick(&slots, &mut next).is_none());
+ }
+
+ #[test]
+ fn replaced_worker_drains_and_gets_no_new_connections() {
+ let slots = pool(2, Some(2));
+ let mut next = 0;
+ let held = pick(&slots, &mut next).unwrap();
+ let old = slots[0].current();
+ assert_eq!(old.active(), 1);
+
+ let wake = slots[0].wake.clone();
+ let fresh = Worker::new(9100, Some(2), wake);
+ let draining = slots[0].replace(fresh);
+ assert!(Arc::ptr_eq(&draining, &old));
+ for _ in 0..8 {
+ assert_ne!(pick(&slots, &mut next).unwrap().port(), 9000);
+ }
+ // The live connection keeps the old worker busy until it finishes.
+ assert_eq!(draining.active(), 1);
+ drop(held);
+ assert_eq!(draining.active(), 0);
+ // Capacity stays at two ready slots.
+ assert_eq!(slots.len(), 2);
+ assert!(slots.iter().all(|slot| slot.current().port != 9000));
+ }
+
+ #[test]
+ fn session_count_wakes_supervisor_at_limit_only() {
+ let slots = pool(1, Some(2));
+ let mut next = 0;
+ let first = pick(&slots, &mut next).unwrap();
+ first.count_session();
+ let wake = slots[0].wake.clone();
+ // Not woken yet: a stored permit would complete the notified future.
+ assert!(notified_now(&wake).is_none());
+ let second = pick(&slots, &mut next).unwrap();
+ second.count_session();
+ assert!(notified_now(&wake).is_some());
+ assert_eq!(slots[0].current().served(), 2);
+ // Discovery connections are active but never counted.
+ let discovery = pick(&slots, &mut next).unwrap();
+ assert_eq!(slots[0].current().active(), 3);
+ drop(discovery);
+ assert_eq!(slots[0].current().served(), 2);
+ }
+
+ fn notified_now(wake: &Notify) -> Option<()> {
+ let rt = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
+ rt.block_on(async {
+ tokio::time::timeout(Duration::from_millis(20), wake.notified()).await.ok()
+ })
+ }
+
+ #[test]
+ fn rss_of_self_is_readable_on_linux() {
+ if cfg!(target_os = "linux") {
+ assert!(rss_mb(std::process::id()).unwrap() > 0);
+ } else {
+ assert!(rss_mb(std::process::id()).is_none());
+ }
+ }
+}
diff --git a/crates/obscura-cli/tests/serve_worker_recycle.rs b/crates/obscura-cli/tests/serve_worker_recycle.rs
new file mode 100644
index 00000000..ae079d32
--- /dev/null
+++ b/crates/obscura-cli/tests/serve_worker_recycle.rs
@@ -0,0 +1,244 @@
+//! `serve --workers N --worker-max-*` replaces workers that pass a threshold
+//! without failing any session: replacements keep the pool at N, and a replaced
+//! worker keeps serving the connections it already had until they close.
+#![cfg(target_os = "linux")]
+
+use std::collections::HashSet;
+use std::net::TcpListener;
+use std::os::unix::process::CommandExt;
+use std::process::{Child, Command, Stdio};
+use std::time::{Duration, Instant};
+
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+struct Server(Child, u16);
+
+impl Server {
+ fn start(extra: &[&str]) -> Server {
+ let port = TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
+ let child = Command::new(env!("CARGO_BIN_EXE_obscura"))
+ .args(["serve", "--host", "127.0.0.1", "--port", &port.to_string(), "--workers", "2"])
+ .args(extra)
+ .process_group(0)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ let server = Server(child, port);
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while server.workers().len() != 2 || std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
+ assert!(Instant::now() < deadline, "balancer did not become ready");
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ server
+ }
+
+ fn workers(&self) -> Vec<u32> {
+ let mut children = Vec::new();
+ for task in std::fs::read_dir(format!("/proc/{}/task", self.0.id())).unwrap() {
+ if let Ok(ids) = std::fs::read_to_string(task.unwrap().path().join("children")) {
+ children.extend(ids.split_whitespace().map(|id| id.parse::<u32>().unwrap()));
+ }
+ }
+ children.sort_unstable();
+ children.dedup();
+ children
+ }
+
+ /// Wait until exactly `count` workers exist and none of `gone` is alive.
+ fn settle(&self, count: usize, gone: &[u32], within: Duration) {
+ let deadline = Instant::now() + within;
+ loop {
+ let now = self.workers();
+ if now.len() == count && gone.iter().all(|pid| !now.contains(pid)) {
+ return;
+ }
+ assert!(Instant::now() < deadline, "workers {now:?}, expected {count} without {gone:?}");
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+}
+
+impl Drop for Server {
+ fn drop(&mut self) {
+ let _ = Command::new("kill")
+ .args(["-TERM", "--", &format!("-{}", self.0.id())])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+ let _ = self.0.wait();
+ }
+}
+
+type Ws = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+struct Session {
+ ws: Ws,
+ id: u64,
+ sid: String,
+}
+
+impl Session {
+ async fn call(&mut self, method: &str, params: Value, with_session: bool) -> Value {
+ self.id += 1;
+ let mut msg = json!({"id": self.id, "method": method, "params": params});
+ if with_session {
+ msg["sessionId"] = json!(self.sid);
+ }
+ self.ws.send(Message::Text(msg.to_string().into())).await.expect("send");
+ loop {
+ let frame = tokio::time::timeout(Duration::from_secs(20), self.ws.next())
+ .await
+ .expect("reply timeout")
+ .expect("ws closed")
+ .expect("ws error");
+ if let Message::Text(text) = frame {
+ let reply: Value = serde_json::from_str(&text).unwrap();
+ if reply["id"] == self.id {
+ assert!(reply.get("error").is_none(), "{method}: {reply}");
+ return reply;
+ }
+ }
+ }
+ }
+
+ /// A full CDP session: connect, open a page, navigate to `url`.
+ async fn open(port: u16, url: &str) -> Session {
+ let (ws, _) = connect_async(format!("ws://127.0.0.1:{port}/devtools/browser"))
+ .await
+ .expect("connect");
+ let mut s = Session { ws, id: 0, sid: String::new() };
+ let target = s.call("Target.createTarget", json!({"url": "about:blank"}), false).await;
+ let attached = s
+ .call(
+ "Target.attachToTarget",
+ json!({"targetId": target["result"]["targetId"], "flatten": true}),
+ false,
+ )
+ .await;
+ s.sid = attached["result"]["sessionId"].as_str().unwrap().to_string();
+ s.call("Page.enable", json!({}), true).await;
+ s.call("Page.navigate", json!({"url": url}), true).await;
+ s
+ }
+
+ async fn eval(&mut self, expression: &str) -> Value {
+ let reply = self
+ .call("Runtime.evaluate", json!({"expression": expression, "returnByValue": true}), true)
+ .await;
+ reply["result"]["result"]["value"].clone()
+ }
+}
+
+const PAGE: &str = "data:text/html,<title>recycle</title><body>ok</body>";
+
+#[tokio::test(flavor = "multi_thread")]
+async fn connection_limit_replaces_workers_without_failing_sessions() {
+ let server = Server::start(&["--worker-max-connections", "3"]);
+ let original = server.workers();
+ let mut seen: HashSet<u32> = original.iter().copied().collect();
+
+ // A long-lived session on one worker: it must survive that worker being
+ // recycled underneath it.
+ let mut held = Session::open(server.1, PAGE).await;
+
+ // Sessions arrive faster than a replacement starts, so keep going until
+ // several generations of workers have come and gone.
+ let deadline = Instant::now() + Duration::from_secs(30);
+ let mut i = 0;
+ while seen.len() < 8 {
+ i += 1;
+ assert!(Instant::now() < deadline, "workers were not replaced: {seen:?}");
+ let mut s = Session::open(server.1, PAGE).await;
+ assert_eq!(s.eval("document.title").await, json!("recycle"), "session {i}");
+ drop(s);
+ seen.extend(server.workers());
+ }
+ assert_eq!(held.eval("document.title").await, json!("recycle"), "held session survived");
+
+ // The worker that carried `held` outlives its replacement until it closes.
+ let now = server.workers();
+ let draining: Vec<u32> = original.iter().copied().filter(|pid| now.contains(pid)).collect();
+ assert!(!draining.is_empty(), "the held session's worker was killed: {now:?}");
+ drop(held);
+ // Pool capacity is unchanged and the replaced originals are gone.
+ server.settle(2, &original, Duration::from_secs(5));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn rss_limit_replaces_a_bloated_worker_and_keeps_its_session() {
+ let server = Server::start(&["--worker-max-rss", "150"]);
+ let original = server.workers();
+ // ~200 MB held live by the page's isolate, well over the 150 MB limit.
+ let bloat = "data:text/html,<title>big</title><script>window.keep=new Uint8Array(200*1024*1024).fill(7)</script>";
+ let mut held = Session::open(server.1, bloat).await;
+
+ let deadline = Instant::now() + Duration::from_secs(15);
+ let replaced = loop {
+ let now = server.workers();
+ if let Some(pid) = original.iter().find(|pid| !now.contains(pid)) {
+ panic!("worker {pid} was killed while its session was live");
+ }
+ if now.len() == 3 {
+ break now;
+ }
+ assert!(Instant::now() < deadline, "bloated worker was not replaced: {now:?}");
+ std::thread::sleep(Duration::from_millis(100));
+ };
+ // Draining: the replacement exists, the bloated worker still answers.
+ assert_eq!(held.eval("window.keep[1000]").await, json!(7.0));
+ // New sessions work and never land on the draining worker's limit.
+ for _ in 0..4 {
+ let mut s = Session::open(server.1, PAGE).await;
+ assert_eq!(s.eval("document.title").await, json!("recycle"));
+ }
+ drop(held);
+ let bloated: Vec<u32> = replaced.into_iter().filter(|pid| original.contains(pid)).collect();
+ assert_eq!(bloated.len(), 2, "both originals alive while one drains");
+ // Exactly one original (the bloated one) leaves; capacity returns to two.
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ let now = server.workers();
+ if now.len() == 2 && original.iter().filter(|pid| now.contains(pid)).count() == 1 {
+ break;
+ }
+ assert!(Instant::now() < deadline, "drained worker not retired: {now:?}");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn shutdown_stops_a_worker_that_is_still_draining() {
+ let mut server = Server::start(&["--worker-max-connections", "1", "--worker-drain-timeout", "300"]);
+ let original = server.workers();
+ // The held session's worker reaches its limit and is replaced, but keeps
+ // running for up to 300 s while the session stays open.
+ let mut held = Session::open(server.1, PAGE).await;
+ let deadline = Instant::now() + Duration::from_secs(15);
+ let all = loop {
+ let now = server.workers();
+ if now.len() == 3 {
+ break now;
+ }
+ assert!(Instant::now() < deadline, "worker was not replaced: {now:?}");
+ std::thread::sleep(Duration::from_millis(20));
+ };
+ assert!(original.iter().all(|pid| all.contains(pid)), "draining worker was killed: {all:?}");
+ assert_eq!(held.eval("document.title").await, json!("recycle"));
+
+ // Signal only the balancer: every worker, the draining one included, must go.
+ assert!(Command::new("kill").args(["-TERM", &server.0.id().to_string()]).status().unwrap().success());
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while server.0.try_wait().unwrap().is_none() {
+ assert!(Instant::now() < deadline, "balancer ignored SIGTERM");
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while all.iter().any(|pid| std::path::Path::new(&format!("/proc/{pid}")).exists()) {
+ assert!(Instant::now() < deadline, "workers survived SIGTERM: {all:?}");
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ drop(held);
+}