use merry_runtime::{
BackgroundProcessControl, BackgroundProcessId, BackgroundProcessState, ProcessActionIntent,
ProcessEnvPolicy, ProcessExitStatus, ProcessRunner, ProcessRunnerContext,
};
use std::{
fmt, future::Future, path::PathBuf, pin::Pin, process::Stdio, sync::Arc, time::Duration,
};
use tokio::{
io::{AsyncBufReadExt, BufReader},
process::{Child, ChildStderr, Command},
};
const BROWSER_STDOUT_LIMIT_BYTES: usize = 16 * 1024;
const BROWSER_STDERR_LIMIT_BYTES: usize = 64 * 1024;
const DEVTOOLS_POLL_INTERVAL: Duration = Duration::from_millis(25);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserLaunchSpec {
pub executable: PathBuf,
pub args: Vec<String>,
pub profile_dir: Option<PathBuf>,
}
pub type BrowserLauncherFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait BrowserProcessHandle: Send {
fn wait_for_devtools_ws_url(
&mut self,
timeout: Duration,
) -> BrowserLauncherFuture<'_, Result<String, String>>;
fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()>;
}
pub trait BrowserProcessLauncher: fmt::Debug + Send + Sync {
fn launch(
&self,
spec: BrowserLaunchSpec,
) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>>;
}
pub struct ProcessRunnerBrowserLauncher {
runner: Arc<dyn ProcessRunner>,
}
impl fmt::Debug for ProcessRunnerBrowserLauncher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProcessRunnerBrowserLauncher")
.finish_non_exhaustive()
}
}
impl ProcessRunnerBrowserLauncher {
#[must_use]
pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
Self { runner }
}
}
impl BrowserProcessLauncher for ProcessRunnerBrowserLauncher {
fn launch(
&self,
spec: BrowserLaunchSpec,
) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
Box::pin(async move {
let executable = spec.executable.to_str().ok_or_else(|| {
format!(
"Chrome/Chromium executable path is not valid UTF-8: {}",
spec.executable.display()
)
})?;
let mut argv = Vec::with_capacity(spec.args.len() + 1);
argv.push(executable.to_owned());
argv.extend(spec.args);
let intent = ProcessActionIntent::new(
argv,
None,
ProcessEnvPolicy::Empty,
None,
BROWSER_STDOUT_LIMIT_BYTES,
BROWSER_STDERR_LIMIT_BYTES,
)
.map_err(|error| format!("invalid browser launch arguments: {error}"))?
.with_background(true)
.with_display_name(Some("headless-browser".to_owned()));
let output = self
.runner
.run(intent, ProcessRunnerContext::default())
.await
.map_err(|error| {
format!("failed spawning Chrome/Chromium through process backend: {error}")
})?;
let initial_stderr = output.stderr_text().to_owned();
if output.status() != ProcessExitStatus::Running {
return Err(format!(
"Chrome/Chromium did not stay running ({:?}): {}",
output.status(),
summarize_stderr_lines(&initial_stderr)
));
}
let Some(bg_id) = output.background_process_id().cloned() else {
return Err(
"configured process backend did not return a background process id for Chrome/Chromium"
.to_owned(),
);
};
let Some(control) = self.runner.background_control() else {
return Err(
"configured process backend does not expose background process control for Chrome/Chromium"
.to_owned(),
);
};
Ok(Box::new(ProcessRunnerBrowserHandle {
bg_id,
control,
initial_stderr,
stopped: false,
}) as Box<dyn BrowserProcessHandle>)
})
}
}
struct ProcessRunnerBrowserHandle {
bg_id: BackgroundProcessId,
control: Arc<dyn BackgroundProcessControl>,
initial_stderr: String,
stopped: bool,
}
impl ProcessRunnerBrowserHandle {
fn stop_now(&mut self) {
if !self.stopped {
self.stopped = true;
let _ = self.control.stop(&self.bg_id);
}
}
async fn stop_async(&mut self) {
if self.stopped {
return;
}
self.stopped = true;
let control = Arc::clone(&self.control);
let bg_id = self.bg_id.clone();
let _ = tokio::task::spawn_blocking(move || {
let _ = control.stop(&bg_id);
})
.await;
}
}
impl Drop for ProcessRunnerBrowserHandle {
fn drop(&mut self) {
self.stop_now();
}
}
impl BrowserProcessHandle for ProcessRunnerBrowserHandle {
fn wait_for_devtools_ws_url(
&mut self,
timeout: Duration,
) -> BrowserLauncherFuture<'_, Result<String, String>> {
Box::pin(async move {
if let Some(url) = extract_devtools_ws_url(&self.initial_stderr) {
return Ok(url);
}
let deadline = tokio::time::Instant::now() + timeout;
let mut last_stderr = self.initial_stderr.clone();
loop {
match self.control.read(&self.bg_id) {
Ok(output) => {
if let Some(url) = extract_devtools_ws_url(output.stderr()) {
return Ok(url);
}
if !output.stderr().is_empty() {
last_stderr = output.stderr().to_owned();
}
if !matches!(
output.summary().state(),
BackgroundProcessState::Running { .. }
) {
self.stopped = true;
return Err(format!(
"Chrome exited without reporting DevTools WebSocket URL: {}",
summarize_stderr_lines(&last_stderr)
));
}
}
Err(error) => {
self.stopped = true;
return Err(format!(
"Chrome background process disappeared before reporting DevTools URL: {}",
error.message()
));
}
}
let now = tokio::time::Instant::now();
if now >= deadline {
self.stop_async().await;
return Err("timed out waiting for Chrome DevTools listening port".to_owned());
}
let sleep_for = deadline
.saturating_duration_since(now)
.min(DEVTOOLS_POLL_INTERVAL);
tokio::time::sleep(sleep_for).await;
}
})
}
fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()> {
Box::pin(async move {
self.stop_async().await;
})
}
}
#[derive(Debug, Default)]
pub(super) struct LocalBrowserProcessLauncher;
impl BrowserProcessLauncher for LocalBrowserProcessLauncher {
fn launch(
&self,
spec: BrowserLaunchSpec,
) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
Box::pin(async move {
let mut cmd = Command::new(&spec.executable);
cmd.args(&spec.args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true);
let child = cmd.spawn().map_err(|error| {
format!(
"failed spawning Chrome/Chromium ({}): {error}",
spec.executable.display()
)
})?;
child_browser_process_handle(child)
})
}
}
pub fn child_browser_process_handle(
mut child: Child,
) -> Result<Box<dyn BrowserProcessHandle>, String> {
let stderr = child
.stderr
.take()
.ok_or_else(|| "Chrome/Chromium stderr pipe unavailable".to_owned())?;
Ok(Box::new(LocalBrowserProcessHandle {
child,
stderr: Some(stderr),
}) as Box<dyn BrowserProcessHandle>)
}
struct LocalBrowserProcessHandle {
child: Child,
stderr: Option<ChildStderr>,
}
impl Drop for LocalBrowserProcessHandle {
fn drop(&mut self) {
let _ = self.child.start_kill();
}
}
impl BrowserProcessHandle for LocalBrowserProcessHandle {
fn wait_for_devtools_ws_url(
&mut self,
timeout: Duration,
) -> BrowserLauncherFuture<'_, Result<String, String>> {
Box::pin(async move {
let Some(stderr) = self.stderr.take() else {
return Err("Chrome/Chromium stderr pipe already consumed".to_owned());
};
let result = read_devtools_ws_url_from_pipe(stderr, timeout).await;
if result.is_err() {
let _ = self.child.start_kill();
}
result
})
}
fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()> {
Box::pin(async move {
let _ = self.child.start_kill();
let _ = tokio::time::timeout(Duration::from_secs(2), self.child.wait()).await;
})
}
}
async fn read_devtools_ws_url_from_pipe(
stderr: ChildStderr,
timeout: Duration,
) -> Result<String, String> {
let mut lines = BufReader::new(stderr).lines();
let deadline = tokio::time::Instant::now() + timeout;
let mut recent_lines = Vec::new();
while tokio::time::Instant::now() < deadline {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
match tokio::time::timeout(remaining, lines.next_line()).await {
Ok(Ok(Some(line))) => {
if let Some(url) = extract_devtools_ws_url(&line) {
return Ok(url);
}
if recent_lines.len() < 20 {
recent_lines.push(line);
}
}
Ok(Ok(None)) => break,
Ok(Err(error)) => return Err(format!("error reading Chrome stderr: {error}")),
Err(_) => {
return Err("timed out waiting for Chrome DevTools listening port".to_owned());
}
}
}
Err(format!(
"Chrome exited without reporting DevTools WebSocket URL: {}",
recent_lines.join(" | ")
))
}
fn extract_devtools_ws_url(text: &str) -> Option<String> {
for line in text.lines() {
if let Some(pos) = line.find("ws://") {
let ws_part = line[pos..].trim();
if !ws_part.is_empty() {
return Some(ws_part.to_owned());
}
}
}
None
}
fn summarize_stderr_lines(text: &str) -> String {
text.lines().take(20).collect::<Vec<_>>().join(" | ")
}
#[cfg(test)]
mod tests {
use super::*;
use merry_runtime::{
BackgroundProcessLookupError, BackgroundProcessOutput, BackgroundProcessStop,
BackgroundProcessSummary, ProcessRunnerError, ProcessRunnerFuture, ProcessRunnerOutput,
};
use std::sync::Mutex;
struct FakeBackgroundControl {
stderr_reads: Mutex<Vec<String>>,
stopped_ids: Mutex<Vec<BackgroundProcessId>>,
}
impl BackgroundProcessControl for FakeBackgroundControl {
fn list(&self) -> Vec<BackgroundProcessSummary> {
Vec::new()
}
fn read(
&self,
id: &BackgroundProcessId,
) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
let mut reads = self.stderr_reads.lock().expect("reads lock");
let stderr = if reads.len() > 1 {
reads.remove(0)
} else {
reads.first().cloned().unwrap_or_default()
};
let summary = BackgroundProcessSummary::new(
id.clone(),
"chromium",
None,
BackgroundProcessState::Running { pid: 4242 },
);
Ok(BackgroundProcessOutput::new(
summary, "", stderr, false, false,
))
}
fn stop(
&self,
id: &BackgroundProcessId,
) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
self.stopped_ids.lock().expect("stop lock").push(id.clone());
let summary = BackgroundProcessSummary::new(
id.clone(),
"chromium",
None,
BackgroundProcessState::Killed,
);
Ok(BackgroundProcessStop::new(summary, true))
}
}
struct FakeBrowserRunner {
control: Arc<FakeBackgroundControl>,
captured_intents: Mutex<Vec<ProcessActionIntent>>,
fail_launch: bool,
}
impl ProcessRunner for FakeBrowserRunner {
fn run<'a>(
&'a self,
intent: ProcessActionIntent,
_context: ProcessRunnerContext,
) -> ProcessRunnerFuture<'a> {
Box::pin(async move {
self.captured_intents
.lock()
.expect("intents lock")
.push(intent);
if self.fail_launch {
return Err(ProcessRunnerError::infrastructure(
"process execution disabled",
));
}
let bg_id = BackgroundProcessId::new("bg-chrome-1").expect("valid id");
let intent_ref = self.captured_intents.lock().expect("intents lock");
let output = ProcessRunnerOutput::new(
&intent_ref[intent_ref.len() - 1],
ProcessExitStatus::Running,
"",
false,
"",
false,
)
.expect("valid process output")
.with_background_process_id(bg_id);
Ok(output)
})
}
fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
Some(Arc::clone(&self.control) as Arc<dyn BackgroundProcessControl>)
}
}
#[tokio::test]
async fn process_runner_launcher_routes_chromium_through_runner_and_stops_on_shutdown() {
let control = Arc::new(FakeBackgroundControl {
stderr_reads: Mutex::new(vec![
"starting headless chrome\n".to_owned(),
"DevTools listening on ws://127.0.0.1:9222/devtools/browser/test-id\n".to_owned(),
]),
stopped_ids: Mutex::new(Vec::new()),
});
let runner = Arc::new(FakeBrowserRunner {
control: Arc::clone(&control),
captured_intents: Mutex::new(Vec::new()),
fail_launch: false,
});
let launcher =
ProcessRunnerBrowserLauncher::new(Arc::clone(&runner) as Arc<dyn ProcessRunner>);
let mut handle = launcher
.launch(BrowserLaunchSpec {
executable: PathBuf::from("/usr/bin/chromium"),
args: vec!["--headless=new".to_owned(), "about:blank".to_owned()],
profile_dir: None,
})
.await
.expect("launch through process runner should succeed");
let ws_url = handle
.wait_for_devtools_ws_url(Duration::from_secs(2))
.await
.expect("should parse DevTools URL from background stderr");
assert_eq!(ws_url, "ws://127.0.0.1:9222/devtools/browser/test-id");
{
let intents = runner.captured_intents.lock().expect("intents lock");
assert_eq!(intents.len(), 1);
assert!(intents[0].background());
assert_eq!(
intents[0].argv(),
["/usr/bin/chromium", "--headless=new", "about:blank"]
);
}
handle.shutdown().await;
let stopped = control.stopped_ids.lock().expect("stopped lock");
assert_eq!(stopped.len(), 1);
assert_eq!(stopped[0].as_str(), "bg-chrome-1");
}
#[tokio::test]
async fn process_runner_launcher_fails_closed_when_runner_rejects_spawn() {
let control = Arc::new(FakeBackgroundControl {
stderr_reads: Mutex::new(Vec::new()),
stopped_ids: Mutex::new(Vec::new()),
});
let runner = Arc::new(FakeBrowserRunner {
control,
captured_intents: Mutex::new(Vec::new()),
fail_launch: true,
});
let launcher = ProcessRunnerBrowserLauncher::new(runner);
let err = launcher
.launch(BrowserLaunchSpec {
executable: PathBuf::from("/usr/bin/chromium"),
args: vec!["--headless=new".to_owned()],
profile_dir: None,
})
.await
.err()
.expect("disabled runner must fail closed");
assert!(err.contains("process execution disabled"));
}
}