Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/cli/src/browser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ mod websocket;
use std::{
path::Path,
sync::{Arc, atomic::AtomicBool},
time::Duration,
};

pub use base64::{base64_decode, base64_encode};
Expand Down Expand Up @@ -68,6 +69,10 @@ pub struct LaunchOptions<'a> {
pub height: u32,
/// Device pixels per CSS pixel in every frame, including out-of-process ones (sandboxed renderer frames).
pub scale: f64,
/// How long the browser may take to start and answer its DevTools connection: the caller's own budget. A cold
/// start (the first since boot, its files not yet cached or scanned) takes several times a warm one, and far longer
/// on a loaded machine; a browser that exits fails at once whatever this allows.
pub startup: Duration,
/// Cancels waits (for example on Ctrl+C), so the browser is still stopped.
pub cancel: Arc<AtomicBool>,
}
Expand Down
27 changes: 16 additions & 11 deletions packages/cli/src/browser/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl Browser {
let mut retried = false;
loop {
let (mut browser, pending) = Self::spawn(&options)?;
match browser.connect(pending, options.transport) {
match browser.connect(pending, options.transport, options.startup) {
Ok(()) => return Ok(browser),
Err(_) if !retried && browser.aborted() => retried = true,
Err(error) if retried => return Err(error.context("The browser was started again after it aborted while starting")),
Expand Down Expand Up @@ -182,9 +182,9 @@ impl Browser {
Ok((browser, Pending { pipes, sender }))
}

/// Connects to the started browser and waits until it answers.
fn connect(&mut self, pending: Pending, transport: Transport) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(30);
/// Connects to the started browser and waits, at most `startup`, until it answers.
fn connect(&mut self, pending: Pending, transport: Transport, startup: Duration) -> Result<()> {
let deadline = Instant::now() + startup;
let Pending { pipes, sender } = pending;
#[cfg(not(unix))]
let () = pipes;
Expand All @@ -202,17 +202,21 @@ impl Browser {
#[cfg(not(unix))]
Transport::Pipe => unreachable!(),
Transport::Port => {
let endpoint = self.active_port(deadline)?;
let (stream, reader) = connect_socket(&endpoint)?;
let endpoint = self.active_port(deadline, startup)?;
Comment thread
agorischek marked this conversation as resolved.
Resolved
let (stream, reader) = connect_socket(&endpoint, deadline)?;
let writer = Arc::new(Mutex::new(stream));
let pong = writer.clone();
thread::spawn(move || read_socket(reader, pong, dispatch));
Writer::Socket(writer)
}
};
*self.writer.lock().unwrap_or_else(|error| error.into_inner()) = Some(writer);
self.call("Browser.getVersion", json!({}), None, deadline)
.context("The browser did not answer on its DevTools connection")?;
self.call("Browser.getVersion", json!({}), None, deadline).with_context(|| {
format!(
"The browser did not answer on its DevTools connection within {} s",
startup.as_secs()
)
})?;
Ok(())
}

Expand All @@ -234,7 +238,7 @@ impl Browser {
}

/// The `ws://` endpoint the browser writes to `DevToolsActivePort`.
fn active_port(&mut self, deadline: Instant) -> Result<(u16, String)> {
fn active_port(&mut self, deadline: Instant, startup: Duration) -> Result<(u16, String)> {
let file = self.profile.path().join("DevToolsActivePort");
loop {
if let Ok(text) = std::fs::read_to_string(&file) {
Expand All @@ -252,7 +256,8 @@ impl Browser {
self.check_alive()?;
ensure!(
Instant::now() < deadline,
"The browser did not open its DevTools endpoint{}",
"The browser did not open its DevTools endpoint within {} s{}",
startup.as_secs(),
self.diagnostics()
);
thread::sleep(Duration::from_millis(50));
Expand Down Expand Up @@ -302,7 +307,7 @@ impl Browser {
}
let now = Instant::now();
if now >= deadline {
bail!("The browser did not answer {method} in time");
bail!("The browser did not answer {method} in time{}", self.diagnostics());
}
match self.messages.recv_timeout((deadline - now).min(Duration::from_millis(100))) {
Ok(Ok(value)) if value["id"] == id => {
Expand Down
23 changes: 23 additions & 0 deletions packages/cli/src/browser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ fn launch_fake(executable: &Path) -> anyhow::Result<Browser> {
width: 100,
height: 100,
scale: 1.0,
startup: Duration::from_secs(30),
cancel: Arc::new(AtomicBool::new(false)),
})
}
Expand All @@ -156,6 +157,26 @@ fn a_browser_ended_by_a_signal_while_starting_is_started_once_more() {
assert_eq!(std::fs::read_to_string(&starts).unwrap().lines().count(), 1);
}

#[cfg(unix)]
#[test]
fn a_browser_that_never_answers_fails_after_the_callers_startup_budget_with_its_output() {
let directory = tempfile::tempdir().unwrap();
let (silent, _) = fake_browser(directory.path(), "echo 'still starting' >&2\nexec sleep 60");
let error = Browser::launch(LaunchOptions {
executable: &silent,
transport: Transport::Pipe,
width: 100,
height: 100,
scale: 1.0,
startup: Duration::from_secs(1),
cancel: Arc::new(AtomicBool::new(false)),
})
.err()
.expect("a silent browser fails");
let message = format!("{error:#}");
assert!(message.contains("within 1 s") && message.contains("still starting"), "{message}");
}

/// A stand-in browser that records each start, then answers every DevTools command on the pipe.
#[cfg(unix)]
fn answering_browser(directory: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
Expand Down Expand Up @@ -189,6 +210,7 @@ fn a_pool_reuses_a_browser_launched_the_same_way() {
width,
height: 100,
scale: 1.0,
startup: Duration::from_secs(30),
cancel: Arc::new(AtomicBool::new(false)),
};
let render = |pool: &Pool, width| {
Expand Down Expand Up @@ -223,6 +245,7 @@ fn one_worker_closes_a_kept_browser_once_it_is_idle() {
width: 100,
height: 100,
scale: 1.0,
startup: Duration::from_secs(30),
cancel: Arc::new(AtomicBool::new(false)),
})
.unwrap();
Expand Down
10 changes: 6 additions & 4 deletions packages/cli/src/browser/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
io::{self, BufRead, BufReader, Read, Write},
net::TcpStream,
sync::{Arc, Mutex},
time::Duration,
time::{Duration, Instant},
};

use anyhow::{Context, Result, ensure};
Expand All @@ -15,8 +15,8 @@ use super::{
connection::{Dispatch, parse_message},
};

/// Connects to the browser's WebSocket endpoint on loopback.
pub(super) fn connect_socket((port, path): &(u16, String)) -> Result<(TcpStream, BufReader<TcpStream>)> {
/// Connects to the browser's WebSocket endpoint on loopback, its handshake answered by `deadline`.
pub(super) fn connect_socket((port, path): &(u16, String), deadline: Instant) -> Result<(TcpStream, BufReader<TcpStream>)> {
let stream = TcpStream::connect(("127.0.0.1", *port)).context("Cannot connect to the browser's DevTools port")?;
stream.set_nodelay(true)?;
let mut key = [0u8; 16];
Expand All @@ -26,7 +26,9 @@ pub(super) fn connect_socket((port, path): &(u16, String)) -> Result<(TcpStream,
base64_encode(&key)
);
(&stream).write_all(request.as_bytes())?;
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
// A zero read timeout is an error, so at least a millisecond.
let remaining = deadline.saturating_duration_since(Instant::now()).max(Duration::from_millis(1));
stream.set_read_timeout(Some(remaining))?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut status = String::new();
reader.read_line(&mut status)?;
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/check/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ pub(super) async fn renderer_checks(
width: 1280,
height: 800,
scale: 1.0,
startup: timeout,
cancel,
})?;
// Opening the stage has its own budget, from after any wait for a launch slot; each scenario then gets the
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ fn open(options: &Capture, browsers: &browser::Pool) -> Result<(Browser, Page)>
width: options.width,
height: options.height,
scale: options.scale,
startup: options.timeout,
cancel: options.cancel.clone(),
})?;
// From here: waiting for a launch slot doesn't spend the page's budget.
Expand Down