1use merry_runtime::{
9 BackgroundProcessControl, BackgroundProcessId, BackgroundProcessState, ProcessActionIntent,
10 ProcessEnvPolicy, ProcessExitStatus, ProcessRunner, ProcessRunnerContext,
11};
12use std::{
13 fmt, future::Future, path::PathBuf, pin::Pin, process::Stdio, sync::Arc, time::Duration,
14};
15use tokio::{
16 io::{AsyncBufReadExt, BufReader},
17 process::{Child, ChildStderr, Command},
18};
19
20const BROWSER_STDOUT_LIMIT_BYTES: usize = 16 * 1024;
21const BROWSER_STDERR_LIMIT_BYTES: usize = 64 * 1024;
22const DEVTOOLS_POLL_INTERVAL: Duration = Duration::from_millis(25);
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct BrowserLaunchSpec {
27 pub executable: PathBuf,
29 pub args: Vec<String>,
31 pub profile_dir: Option<PathBuf>,
33}
34
35pub type BrowserLauncherFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
37
38pub trait BrowserProcessHandle: Send {
40 fn wait_for_devtools_ws_url(
42 &mut self,
43 timeout: Duration,
44 ) -> BrowserLauncherFuture<'_, Result<String, String>>;
45
46 fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()>;
48}
49
50pub trait BrowserProcessLauncher: fmt::Debug + Send + Sync {
52 fn launch(
54 &self,
55 spec: BrowserLaunchSpec,
56 ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>>;
57}
58
59pub struct ProcessRunnerBrowserLauncher {
62 runner: Arc<dyn ProcessRunner>,
63}
64
65impl fmt::Debug for ProcessRunnerBrowserLauncher {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 f.debug_struct("ProcessRunnerBrowserLauncher")
68 .finish_non_exhaustive()
69 }
70}
71
72impl ProcessRunnerBrowserLauncher {
73 #[must_use]
76 pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
77 Self { runner }
78 }
79}
80
81impl BrowserProcessLauncher for ProcessRunnerBrowserLauncher {
82 fn launch(
83 &self,
84 spec: BrowserLaunchSpec,
85 ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
86 Box::pin(async move {
87 let executable = spec.executable.to_str().ok_or_else(|| {
88 format!(
89 "Chrome/Chromium executable path is not valid UTF-8: {}",
90 spec.executable.display()
91 )
92 })?;
93 let mut argv = Vec::with_capacity(spec.args.len() + 1);
94 argv.push(executable.to_owned());
95 argv.extend(spec.args);
96
97 let intent = ProcessActionIntent::new(
98 argv,
99 None,
100 ProcessEnvPolicy::Empty,
101 None,
102 BROWSER_STDOUT_LIMIT_BYTES,
103 BROWSER_STDERR_LIMIT_BYTES,
104 )
105 .map_err(|error| format!("invalid browser launch arguments: {error}"))?
106 .with_background(true)
107 .with_display_name(Some("headless-browser".to_owned()));
108
109 let output = self
110 .runner
111 .run(intent, ProcessRunnerContext::default())
112 .await
113 .map_err(|error| {
114 format!("failed spawning Chrome/Chromium through process backend: {error}")
115 })?;
116
117 let initial_stderr = output.stderr_text().to_owned();
118 if output.status() != ProcessExitStatus::Running {
119 return Err(format!(
120 "Chrome/Chromium did not stay running ({:?}): {}",
121 output.status(),
122 summarize_stderr_lines(&initial_stderr)
123 ));
124 }
125 let Some(bg_id) = output.background_process_id().cloned() else {
126 return Err(
127 "configured process backend did not return a background process id for Chrome/Chromium"
128 .to_owned(),
129 );
130 };
131 let Some(control) = self.runner.background_control() else {
132 return Err(
133 "configured process backend does not expose background process control for Chrome/Chromium"
134 .to_owned(),
135 );
136 };
137
138 Ok(Box::new(ProcessRunnerBrowserHandle {
139 bg_id,
140 control,
141 initial_stderr,
142 stopped: false,
143 }) as Box<dyn BrowserProcessHandle>)
144 })
145 }
146}
147
148struct ProcessRunnerBrowserHandle {
149 bg_id: BackgroundProcessId,
150 control: Arc<dyn BackgroundProcessControl>,
151 initial_stderr: String,
152 stopped: bool,
153}
154
155impl ProcessRunnerBrowserHandle {
156 fn stop_now(&mut self) {
157 if !self.stopped {
158 self.stopped = true;
159 let _ = self.control.stop(&self.bg_id);
160 }
161 }
162
163 async fn stop_async(&mut self) {
164 if self.stopped {
165 return;
166 }
167 self.stopped = true;
168 let control = Arc::clone(&self.control);
169 let bg_id = self.bg_id.clone();
170 let _ = tokio::task::spawn_blocking(move || {
171 let _ = control.stop(&bg_id);
172 })
173 .await;
174 }
175}
176
177impl Drop for ProcessRunnerBrowserHandle {
178 fn drop(&mut self) {
179 self.stop_now();
180 }
181}
182
183impl BrowserProcessHandle for ProcessRunnerBrowserHandle {
184 fn wait_for_devtools_ws_url(
185 &mut self,
186 timeout: Duration,
187 ) -> BrowserLauncherFuture<'_, Result<String, String>> {
188 Box::pin(async move {
189 if let Some(url) = extract_devtools_ws_url(&self.initial_stderr) {
190 return Ok(url);
191 }
192 let deadline = tokio::time::Instant::now() + timeout;
193 let mut last_stderr = self.initial_stderr.clone();
194 loop {
195 match self.control.read(&self.bg_id) {
196 Ok(output) => {
197 if let Some(url) = extract_devtools_ws_url(output.stderr()) {
198 return Ok(url);
199 }
200 if !output.stderr().is_empty() {
201 last_stderr = output.stderr().to_owned();
202 }
203 if !matches!(
204 output.summary().state(),
205 BackgroundProcessState::Running { .. }
206 ) {
207 self.stopped = true;
208 return Err(format!(
209 "Chrome exited without reporting DevTools WebSocket URL: {}",
210 summarize_stderr_lines(&last_stderr)
211 ));
212 }
213 }
214 Err(error) => {
215 self.stopped = true;
216 return Err(format!(
217 "Chrome background process disappeared before reporting DevTools URL: {}",
218 error.message()
219 ));
220 }
221 }
222 let now = tokio::time::Instant::now();
223 if now >= deadline {
224 self.stop_async().await;
225 return Err("timed out waiting for Chrome DevTools listening port".to_owned());
226 }
227 let sleep_for = deadline
228 .saturating_duration_since(now)
229 .min(DEVTOOLS_POLL_INTERVAL);
230 tokio::time::sleep(sleep_for).await;
231 }
232 })
233 }
234
235 fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()> {
236 Box::pin(async move {
237 self.stop_async().await;
238 })
239 }
240}
241
242#[derive(Debug, Default)]
245pub(super) struct LocalBrowserProcessLauncher;
246
247impl BrowserProcessLauncher for LocalBrowserProcessLauncher {
248 fn launch(
249 &self,
250 spec: BrowserLaunchSpec,
251 ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
252 Box::pin(async move {
253 let mut cmd = Command::new(&spec.executable);
254 cmd.args(&spec.args)
255 .stdin(Stdio::null())
256 .stdout(Stdio::null())
257 .stderr(Stdio::piped())
258 .kill_on_drop(true);
259
260 let child = cmd.spawn().map_err(|error| {
261 format!(
262 "failed spawning Chrome/Chromium ({}): {error}",
263 spec.executable.display()
264 )
265 })?;
266 child_browser_process_handle(child)
267 })
268 }
269}
270
271pub fn child_browser_process_handle(
274 mut child: Child,
275) -> Result<Box<dyn BrowserProcessHandle>, String> {
276 let stderr = child
277 .stderr
278 .take()
279 .ok_or_else(|| "Chrome/Chromium stderr pipe unavailable".to_owned())?;
280
281 Ok(Box::new(LocalBrowserProcessHandle {
282 child,
283 stderr: Some(stderr),
284 }) as Box<dyn BrowserProcessHandle>)
285}
286
287struct LocalBrowserProcessHandle {
288 child: Child,
289 stderr: Option<ChildStderr>,
290}
291
292impl Drop for LocalBrowserProcessHandle {
293 fn drop(&mut self) {
294 let _ = self.child.start_kill();
295 }
296}
297
298impl BrowserProcessHandle for LocalBrowserProcessHandle {
299 fn wait_for_devtools_ws_url(
300 &mut self,
301 timeout: Duration,
302 ) -> BrowserLauncherFuture<'_, Result<String, String>> {
303 Box::pin(async move {
304 let Some(stderr) = self.stderr.take() else {
305 return Err("Chrome/Chromium stderr pipe already consumed".to_owned());
306 };
307 let result = read_devtools_ws_url_from_pipe(stderr, timeout).await;
308 if result.is_err() {
309 let _ = self.child.start_kill();
310 }
311 result
312 })
313 }
314
315 fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()> {
316 Box::pin(async move {
317 let _ = self.child.start_kill();
318 let _ = tokio::time::timeout(Duration::from_secs(2), self.child.wait()).await;
319 })
320 }
321}
322
323async fn read_devtools_ws_url_from_pipe(
324 stderr: ChildStderr,
325 timeout: Duration,
326) -> Result<String, String> {
327 let mut lines = BufReader::new(stderr).lines();
328 let deadline = tokio::time::Instant::now() + timeout;
329 let mut recent_lines = Vec::new();
330 while tokio::time::Instant::now() < deadline {
331 let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
332 match tokio::time::timeout(remaining, lines.next_line()).await {
333 Ok(Ok(Some(line))) => {
334 if let Some(url) = extract_devtools_ws_url(&line) {
335 return Ok(url);
336 }
337 if recent_lines.len() < 20 {
338 recent_lines.push(line);
339 }
340 }
341 Ok(Ok(None)) => break,
342 Ok(Err(error)) => return Err(format!("error reading Chrome stderr: {error}")),
343 Err(_) => {
344 return Err("timed out waiting for Chrome DevTools listening port".to_owned());
345 }
346 }
347 }
348 Err(format!(
349 "Chrome exited without reporting DevTools WebSocket URL: {}",
350 recent_lines.join(" | ")
351 ))
352}
353
354fn extract_devtools_ws_url(text: &str) -> Option<String> {
355 for line in text.lines() {
356 if let Some(pos) = line.find("ws://") {
357 let ws_part = line[pos..].trim();
358 if !ws_part.is_empty() {
359 return Some(ws_part.to_owned());
360 }
361 }
362 }
363 None
364}
365
366fn summarize_stderr_lines(text: &str) -> String {
367 text.lines().take(20).collect::<Vec<_>>().join(" | ")
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use merry_runtime::{
374 BackgroundProcessLookupError, BackgroundProcessOutput, BackgroundProcessStop,
375 BackgroundProcessSummary, ProcessRunnerError, ProcessRunnerFuture, ProcessRunnerOutput,
376 };
377 use std::sync::Mutex;
378
379 struct FakeBackgroundControl {
380 stderr_reads: Mutex<Vec<String>>,
381 stopped_ids: Mutex<Vec<BackgroundProcessId>>,
382 }
383
384 impl BackgroundProcessControl for FakeBackgroundControl {
385 fn list(&self) -> Vec<BackgroundProcessSummary> {
386 Vec::new()
387 }
388
389 fn read(
390 &self,
391 id: &BackgroundProcessId,
392 ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
393 let mut reads = self.stderr_reads.lock().expect("reads lock");
394 let stderr = if reads.len() > 1 {
395 reads.remove(0)
396 } else {
397 reads.first().cloned().unwrap_or_default()
398 };
399 let summary = BackgroundProcessSummary::new(
400 id.clone(),
401 "chromium",
402 None,
403 BackgroundProcessState::Running { pid: 4242 },
404 );
405 Ok(BackgroundProcessOutput::new(
406 summary, "", stderr, false, false,
407 ))
408 }
409
410 fn stop(
411 &self,
412 id: &BackgroundProcessId,
413 ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
414 self.stopped_ids.lock().expect("stop lock").push(id.clone());
415 let summary = BackgroundProcessSummary::new(
416 id.clone(),
417 "chromium",
418 None,
419 BackgroundProcessState::Killed,
420 );
421 Ok(BackgroundProcessStop::new(summary, true))
422 }
423 }
424
425 struct FakeBrowserRunner {
426 control: Arc<FakeBackgroundControl>,
427 captured_intents: Mutex<Vec<ProcessActionIntent>>,
428 fail_launch: bool,
429 }
430
431 impl ProcessRunner for FakeBrowserRunner {
432 fn run<'a>(
433 &'a self,
434 intent: ProcessActionIntent,
435 _context: ProcessRunnerContext,
436 ) -> ProcessRunnerFuture<'a> {
437 Box::pin(async move {
438 self.captured_intents
439 .lock()
440 .expect("intents lock")
441 .push(intent);
442 if self.fail_launch {
443 return Err(ProcessRunnerError::infrastructure(
444 "process execution disabled",
445 ));
446 }
447 let bg_id = BackgroundProcessId::new("bg-chrome-1").expect("valid id");
448 let intent_ref = self.captured_intents.lock().expect("intents lock");
449 let output = ProcessRunnerOutput::new(
450 &intent_ref[intent_ref.len() - 1],
451 ProcessExitStatus::Running,
452 "",
453 false,
454 "",
455 false,
456 )
457 .expect("valid process output")
458 .with_background_process_id(bg_id);
459 Ok(output)
460 })
461 }
462
463 fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
464 Some(Arc::clone(&self.control) as Arc<dyn BackgroundProcessControl>)
465 }
466 }
467
468 #[tokio::test]
469 async fn process_runner_launcher_routes_chromium_through_runner_and_stops_on_shutdown() {
470 let control = Arc::new(FakeBackgroundControl {
471 stderr_reads: Mutex::new(vec![
472 "starting headless chrome\n".to_owned(),
473 "DevTools listening on ws://127.0.0.1:9222/devtools/browser/test-id\n".to_owned(),
474 ]),
475 stopped_ids: Mutex::new(Vec::new()),
476 });
477 let runner = Arc::new(FakeBrowserRunner {
478 control: Arc::clone(&control),
479 captured_intents: Mutex::new(Vec::new()),
480 fail_launch: false,
481 });
482 let launcher =
483 ProcessRunnerBrowserLauncher::new(Arc::clone(&runner) as Arc<dyn ProcessRunner>);
484
485 let mut handle = launcher
486 .launch(BrowserLaunchSpec {
487 executable: PathBuf::from("/usr/bin/chromium"),
488 args: vec!["--headless=new".to_owned(), "about:blank".to_owned()],
489 profile_dir: None,
490 })
491 .await
492 .expect("launch through process runner should succeed");
493
494 let ws_url = handle
495 .wait_for_devtools_ws_url(Duration::from_secs(2))
496 .await
497 .expect("should parse DevTools URL from background stderr");
498 assert_eq!(ws_url, "ws://127.0.0.1:9222/devtools/browser/test-id");
499
500 {
501 let intents = runner.captured_intents.lock().expect("intents lock");
502 assert_eq!(intents.len(), 1);
503 assert!(intents[0].background());
504 assert_eq!(
505 intents[0].argv(),
506 ["/usr/bin/chromium", "--headless=new", "about:blank"]
507 );
508 }
509
510 handle.shutdown().await;
511 let stopped = control.stopped_ids.lock().expect("stopped lock");
512 assert_eq!(stopped.len(), 1);
513 assert_eq!(stopped[0].as_str(), "bg-chrome-1");
514 }
515
516 #[tokio::test]
517 async fn process_runner_launcher_fails_closed_when_runner_rejects_spawn() {
518 let control = Arc::new(FakeBackgroundControl {
519 stderr_reads: Mutex::new(Vec::new()),
520 stopped_ids: Mutex::new(Vec::new()),
521 });
522 let runner = Arc::new(FakeBrowserRunner {
523 control,
524 captured_intents: Mutex::new(Vec::new()),
525 fail_launch: true,
526 });
527 let launcher = ProcessRunnerBrowserLauncher::new(runner);
528
529 let err = launcher
530 .launch(BrowserLaunchSpec {
531 executable: PathBuf::from("/usr/bin/chromium"),
532 args: vec!["--headless=new".to_owned()],
533 profile_dir: None,
534 })
535 .await
536 .err()
537 .expect("disabled runner must fail closed");
538 assert!(err.contains("process execution disabled"));
539 }
540}