| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use futures_util::{SinkExt, StreamExt}; |
| 6 | use serde::Serialize; |
| 7 | use serde_json::{Value, json}; |
| 8 | use tokio::sync::Mutex; |
| 9 | use tokio_tungstenite::tungstenite::Message; |
| 10 | |
| 11 | use crate::config::Config; |
| 12 | use crate::error::BrowserError; |
| 13 | use crate::http; |
| 14 | use crate::launch::{LaunchRequest, Launcher, SystemLauncher}; |
| 15 | use crate::targets::{self, APPS, App, LoginState, Mode, Tab, VersionInfo}; |
| 16 | |
| 17 | const HTTP_TIMEOUT: Duration = Duration::from_secs(5); |
| 18 | const OPEN_TAB_TIMEOUT: Duration = Duration::from_secs(10); |
| 19 | const CDP_TIMEOUT: Duration = Duration::from_secs(5); |
| 20 | |
| 21 | #[derive(Debug, Clone, Serialize)] |
| 22 | pub struct Status { |
| 23 | pub running: bool, |
| 24 | pub mode: Mode, |
| 25 | pub tabs: Vec<Tab>, |
| 26 | pub login_state: LoginState, |
| 27 | } |
| 28 | |
| 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 30 | pub enum RendererState { |
| 31 | Ok, |
| 32 | Hung, |
| 33 | NoTab, |
| 34 | } |
| 35 | |
| 36 | impl RendererState { |
| 37 | pub fn label(self) -> &'static str { |
| 38 | match self { |
| 39 | RendererState::Ok => "ok", |
| 40 | RendererState::Hung => "hung", |
| 41 | RendererState::NoTab => "no tab", |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | #[derive(Debug, Clone)] |
| 47 | pub struct Timeouts { |
| 48 | pub start: Duration, |
| 49 | pub stop: Duration, |
| 50 | pub probe: Duration, |
| 51 | pub poll: Duration, |
| 52 | pub profile_release: Duration, |
| 53 | pub jitter_min: Duration, |
| 54 | pub jitter_max: Duration, |
| 55 | } |
| 56 | |
| 57 | impl Default for Timeouts { |
| 58 | fn default() -> Self { |
| 59 | Timeouts { |
| 60 | start: Duration::from_secs(20), |
| 61 | stop: Duration::from_secs(15), |
| 62 | probe: Duration::from_secs(5), |
| 63 | poll: Duration::from_millis(500), |
| 64 | profile_release: Duration::from_secs(2), |
| 65 | jitter_min: Duration::from_millis(500), |
| 66 | jitter_max: Duration::from_secs(2), |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | struct Inner { |
| 72 | config: Config, |
| 73 | launcher: Arc<dyn Launcher>, |
| 74 | timeouts: Timeouts, |
| 75 | operation: Mutex<()>, |
| 76 | wanted: AtomicBool, |
| 77 | } |
| 78 | |
| 79 | #[derive(Clone)] |
| 80 | pub struct Browser { |
| 81 | inner: Arc<Inner>, |
| 82 | } |
| 83 | |
| 84 | pub(crate) fn start_urls_for(headless: bool) -> Vec<String> { |
| 85 | let urls = APPS.iter().map(|app| app.start_url().to_owned()); |
| 86 | if headless { urls.take(1).collect() } else { urls.collect() } |
| 87 | } |
| 88 | |
| 89 | pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration { |
| 90 | let span = max.saturating_sub(min).as_millis() as u64; |
| 91 | if span == 0 { min } else { min + Duration::from_millis(random % (span + 1)) } |
| 92 | } |
| 93 | |
| 94 | fn random_u64() -> u64 { |
| 95 | use std::hash::{BuildHasher, Hasher, RandomState}; |
| 96 | RandomState::new().build_hasher().finish() |
| 97 | } |
| 98 | |
| 99 | impl Browser { |
| 100 | pub fn detect() -> Result<Browser, BrowserError> { |
| 101 | Ok(Browser::new(Config::detect()?)) |
| 102 | } |
| 103 | |
| 104 | pub fn new(config: Config) -> Browser { |
| 105 | let launcher = Arc::new(SystemLauncher::new(config.clone())); |
| 106 | Browser::with_launcher(config, launcher, Timeouts::default()) |
| 107 | } |
| 108 | |
| 109 | pub fn with_launcher(config: Config, launcher: Arc<dyn Launcher>, timeouts: Timeouts) -> Browser { |
| 110 | Browser { |
| 111 | inner: Arc::new(Inner { |
| 112 | config, |
| 113 | launcher, |
| 114 | timeouts, |
| 115 | operation: Mutex::new(()), |
| 116 | wanted: AtomicBool::new(false), |
| 117 | }), |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | pub fn config(&self) -> &Config { |
| 122 | &self.inner.config |
| 123 | } |
| 124 | |
| 125 | pub async fn status(&self) -> Result<Status, BrowserError> { |
| 126 | let Some(_) = self.version().await else { |
| 127 | return Ok(Status { running: false, mode: Mode::Visible, tabs: Vec::new(), login_state: LoginState::Unknown }); |
| 128 | }; |
| 129 | let tabs = self.tabs().await?; |
| 130 | Ok(Status { running: true, mode: self.mode(), login_state: targets::login_state(&tabs), tabs }) |
| 131 | } |
| 132 | |
| 133 | pub async fn is_running(&self) -> bool { |
| 134 | self.version().await.is_some() |
| 135 | } |
| 136 | |
| 137 | pub async fn probe_renderer(&self) -> RendererState { |
| 138 | let Ok(tabs) = self.tabs().await else { return RendererState::NoTab }; |
| 139 | let Some(tab) = targets::app_tab(&tabs, App::Teams) else { return RendererState::NoTab }; |
| 140 | let url = format!("ws://127.0.0.1:{}/devtools/page/{}", self.inner.config.port, tab.id); |
| 141 | let params = json!({ "expression": "1+1" }); |
| 142 | match cdp_call(&url, "Runtime.evaluate", params, self.inner.timeouts.probe).await { |
| 143 | Ok(_) => RendererState::Ok, |
| 144 | Err(_) => RendererState::Hung, |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub(crate) async fn restart_hung(&self) -> Result<(), BrowserError> { |
| 149 | let _guard = self.inner.operation.lock().await; |
| 150 | let headless = self.mode() == Mode::Headless; |
| 151 | self.stop_locked(true).await?; |
| 152 | self.launch_locked(headless).await |
| 153 | } |
| 154 | |
| 155 | pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> { |
| 156 | let response = http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?; |
| 157 | targets::parse_tabs(&response.body) |
| 158 | } |
| 159 | |
| 160 | pub async fn ensure_running(&self) -> Result<(), BrowserError> { |
| 161 | let _guard = self.inner.operation.lock().await; |
| 162 | self.inner.wanted.store(true, Ordering::SeqCst); |
| 163 | if self.is_running().await { |
| 164 | return self.ensure_tabs_locked().await; |
| 165 | } |
| 166 | match self.launch_locked(true).await { |
| 167 | Ok(()) => {} |
| 168 | Err(BrowserError::PortBusy(_)) => self.ensure_tabs_locked().await?, |
| 169 | Err(error) => return Err(error), |
| 170 | } |
| 171 | self.dedupe_app_tabs_locked().await; |
| 172 | Ok(()) |
| 173 | } |
| 174 | |
| 175 | pub async fn wake(&self, app: App) -> Result<(), BrowserError> { |
| 176 | let _guard = self.inner.operation.lock().await; |
| 177 | let tabs = self.tabs().await?; |
| 178 | let candidates = tabs.iter().filter(|tab| tab.app == Some(app)); |
| 179 | let Some(tab) = candidates.clone().find(|tab| tab.parked).or_else(|| candidates.clone().next()) else { |
| 180 | return self.open_tab(app).await; |
| 181 | }; |
| 182 | let url = format!("ws://127.0.0.1:{}/devtools/page/{}", self.inner.config.port, tab.id); |
| 183 | cdp_call(&url, "Page.navigate", json!({ "url": app.start_url() }), CDP_TIMEOUT).await.map(|_| ()) |
| 184 | } |
| 185 | |
| 186 | pub async fn ensure_tabs(&self) -> Result<(), BrowserError> { |
| 187 | let _guard = self.inner.operation.lock().await; |
| 188 | self.ensure_tabs_locked().await |
| 189 | } |
| 190 | |
| 191 | pub async fn login_window(&self) -> Result<(), BrowserError> { |
| 192 | self.relaunch(false).await |
| 193 | } |
| 194 | |
| 195 | pub async fn headless(&self) -> Result<(), BrowserError> { |
| 196 | self.relaunch(true).await |
| 197 | } |
| 198 | |
| 199 | pub async fn stop(&self) -> Result<(), BrowserError> { |
| 200 | let _guard = self.inner.operation.lock().await; |
| 201 | self.inner.wanted.store(false, Ordering::SeqCst); |
| 202 | self.stop_locked(false).await |
| 203 | } |
| 204 | |
| 205 | pub(crate) fn is_wanted(&self) -> bool { |
| 206 | self.inner.wanted.load(Ordering::SeqCst) |
| 207 | } |
| 208 | |
| 209 | pub(crate) fn set_wanted(&self, wanted: bool) { |
| 210 | self.inner.wanted.store(wanted, Ordering::SeqCst); |
| 211 | } |
| 212 | |
| 213 | pub(crate) fn is_busy(&self) -> bool { |
| 214 | self.inner.operation.try_lock().is_err() |
| 215 | } |
| 216 | |
| 217 | async fn relaunch(&self, headless: bool) -> Result<(), BrowserError> { |
| 218 | let _guard = self.inner.operation.lock().await; |
| 219 | self.inner.wanted.store(true, Ordering::SeqCst); |
| 220 | self.stop_locked(false).await?; |
| 221 | self.launch_locked(headless).await |
| 222 | } |
| 223 | |
| 224 | async fn version(&self) -> Option<VersionInfo> { |
| 225 | let response = http::request(self.inner.config.port, "GET", "/json/version", Duration::from_secs(2)) |
| 226 | .await |
| 227 | .ok()?; |
| 228 | targets::parse_version(&response.body).ok() |
| 229 | } |
| 230 | |
| 231 | fn mode(&self) -> Mode { |
| 232 | std::fs::read_to_string(&self.inner.config.mode_file) |
| 233 | .map(|content| Mode::from_mode_file(&content)) |
| 234 | .unwrap_or(Mode::Visible) |
| 235 | } |
| 236 | |
| 237 | async fn ensure_tabs_locked(&self) -> Result<(), BrowserError> { |
| 238 | let tabs = self.tabs().await?; |
| 239 | let login_open = tabs.iter().any(|tab| tab.login); |
| 240 | for app in APPS { |
| 241 | if targets::app_tab(&tabs, app).is_none() && !login_open { |
| 242 | self.open_tab(app).await?; |
| 243 | } |
| 244 | } |
| 245 | Ok(()) |
| 246 | } |
| 247 | |
| 248 | pub(crate) fn jitter(&self) -> Duration { |
| 249 | let timeouts = &self.inner.timeouts; |
| 250 | jitter_between(timeouts.jitter_min, timeouts.jitter_max, random_u64()) |
| 251 | } |
| 252 | |
| 253 | async fn dedupe_app_tabs_locked(&self) { |
| 254 | let _ = self.try_dedupe_app_tabs().await; |
| 255 | } |
| 256 | |
| 257 | async fn try_dedupe_app_tabs(&self) -> Result<(), BrowserError> { |
| 258 | let tabs = self.tabs().await?; |
| 259 | let info = self.version().await.ok_or_else(|| BrowserError::NoBrowser(self.inner.config.port.to_string()))?; |
| 260 | let result = cdp_call(&info.websocket_url, "Target.getTargets", json!({}), CDP_TIMEOUT).await?; |
| 261 | let attached = targets::attached_target_ids(&result); |
| 262 | for id in targets::duplicate_app_tab_ids(&tabs, &attached) { |
| 263 | let path = format!("/json/close/{id}"); |
| 264 | http::request(self.inner.config.port, "GET", &path, HTTP_TIMEOUT).await?; |
| 265 | } |
| 266 | Ok(()) |
| 267 | } |
| 268 | |
| 269 | async fn open_tab(&self, app: App) -> Result<(), BrowserError> { |
| 270 | let path = format!("/json/new?{}", app.start_url()); |
| 271 | let response = http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?; |
| 272 | if response.status != 200 { |
| 273 | return Err(BrowserError::Http(format!("PUT /json/new returned {}", response.status))); |
| 274 | } |
| 275 | Ok(()) |
| 276 | } |
| 277 | |
| 278 | async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> { |
| 279 | let config = &self.inner.config; |
| 280 | tokio::time::sleep(self.jitter()).await; |
| 281 | if self.is_running().await { |
| 282 | return Err(BrowserError::PortBusy(config.port)); |
| 283 | } |
| 284 | let request = LaunchRequest { headless, start_urls: start_urls_for(headless) }; |
| 285 | self.inner.launcher.spawn(&request)?; |
| 286 | let mode = if headless { Mode::Headless } else { Mode::Visible }; |
| 287 | if let Some(parent) = config.mode_file.parent() { |
| 288 | std::fs::create_dir_all(parent)?; |
| 289 | } |
| 290 | std::fs::write(&config.mode_file, mode.file_content())?; |
| 291 | self.wait_until_running().await?; |
| 292 | if headless { |
| 293 | for app in APPS.into_iter().skip(1) { |
| 294 | self.open_tab(app).await?; |
| 295 | } |
| 296 | } |
| 297 | Ok(()) |
| 298 | } |
| 299 | |
| 300 | async fn wait_until_stopped(&self) -> bool { |
| 301 | let timeouts = &self.inner.timeouts; |
| 302 | let deadline = tokio::time::Instant::now() + timeouts.stop; |
| 303 | while tokio::time::Instant::now() < deadline && self.is_running().await { |
| 304 | tokio::time::sleep(timeouts.poll).await; |
| 305 | } |
| 306 | !self.is_running().await |
| 307 | } |
| 308 | |
| 309 | async fn wait_until_running(&self) -> Result<(), BrowserError> { |
| 310 | let timeouts = &self.inner.timeouts; |
| 311 | let deadline = tokio::time::Instant::now() + timeouts.start; |
| 312 | while tokio::time::Instant::now() < deadline { |
| 313 | if self.is_running().await { |
| 314 | return Ok(()); |
| 315 | } |
| 316 | tokio::time::sleep(timeouts.poll).await; |
| 317 | } |
| 318 | Err(BrowserError::StartTimeout { port: self.inner.config.port, seconds: timeouts.start.as_secs() }) |
| 319 | } |
| 320 | |
| 321 | async fn stop_locked(&self, kill_fallback: bool) -> Result<(), BrowserError> { |
| 322 | let Some(info) = self.version().await else { return Ok(()) }; |
| 323 | close_over_cdp(&info.websocket_url).await; |
| 324 | let timeouts = &self.inner.timeouts; |
| 325 | if !self.wait_until_stopped().await && kill_fallback { |
| 326 | let launcher = self.inner.launcher.clone(); |
| 327 | let port = self.inner.config.port; |
| 328 | let _ = tokio::task::spawn_blocking(move || launcher.kill_listener(port)).await; |
| 329 | self.wait_until_stopped().await; |
| 330 | } |
| 331 | if self.is_running().await { |
| 332 | return Err(BrowserError::StopTimeout { |
| 333 | port: self.inner.config.port, |
| 334 | seconds: timeouts.stop.as_secs(), |
| 335 | }); |
| 336 | } |
| 337 | // the profile lock is released a moment after the debugging port closes |
| 338 | tokio::time::sleep(timeouts.profile_release).await; |
| 339 | Ok(()) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | async fn cdp_call( |
| 344 | websocket_url: &str, |
| 345 | method: &str, |
| 346 | params: Value, |
| 347 | timeout: Duration, |
| 348 | ) -> Result<Value, BrowserError> { |
| 349 | let exchange = async { |
| 350 | let (mut socket, _) = tokio_tungstenite::connect_async(websocket_url) |
| 351 | .await |
| 352 | .map_err(|error| BrowserError::Cdp(error.to_string()))?; |
| 353 | let request = json!({ "id": 1, "method": method, "params": params }); |
| 354 | socket |
| 355 | .send(Message::text(request.to_string())) |
| 356 | .await |
| 357 | .map_err(|error| BrowserError::Cdp(error.to_string()))?; |
| 358 | while let Some(message) = socket.next().await { |
| 359 | let Message::Text(text) = message.map_err(|error| BrowserError::Cdp(error.to_string()))? else { |
| 360 | continue; |
| 361 | }; |
| 362 | let Ok(reply) = serde_json::from_str::<Value>(&text) else { continue }; |
| 363 | if reply["id"] != 1 { |
| 364 | continue; |
| 365 | } |
| 366 | if let Some(error) = reply.get("error") { |
| 367 | return Err(BrowserError::Cdp(format!("{method}: {}", error["message"].as_str().unwrap_or("error")))); |
| 368 | } |
| 369 | return Ok(reply["result"].clone()); |
| 370 | } |
| 371 | Err(BrowserError::Cdp(format!("{method}: connection closed"))) |
| 372 | }; |
| 373 | tokio::time::timeout(timeout, exchange) |
| 374 | .await |
| 375 | .map_err(|_| BrowserError::Cdp(format!("{method} timed out")))? |
| 376 | } |
| 377 | |
| 378 | async fn close_over_cdp(websocket_url: &str) { |
| 379 | let Ok(Ok((mut socket, _))) = |
| 380 | tokio::time::timeout(Duration::from_secs(3), tokio_tungstenite::connect_async(websocket_url)).await |
| 381 | else { |
| 382 | return; |
| 383 | }; |
| 384 | let _ = socket.send(Message::text(r#"{"id":1,"method":"Browser.close"}"#)).await; |
| 385 | let _ = tokio::time::timeout(Duration::from_secs(2), futures_util::StreamExt::next(&mut socket)).await; |
| 386 | } |
| 387 | |
| 388 | #[cfg(test)] |
| 389 | mod tests { |
| 390 | use super::*; |
| 391 | |
| 392 | #[test] |
| 393 | fn jitter_stays_in_range() { |
| 394 | let (min, max) = (Duration::from_millis(500), Duration::from_secs(2)); |
| 395 | assert_eq!(jitter_between(min, max, 0), min); |
| 396 | assert_eq!(jitter_between(min, max, 1500), max); |
| 397 | assert_eq!(jitter_between(min, max, 1501), Duration::from_millis(500)); |
| 398 | assert_eq!(jitter_between(min, min, 99), min); |
| 399 | assert!((0..50).all(|seed| (min..=max).contains(&jitter_between(min, max, random_u64().wrapping_add(seed))))); |
| 400 | } |
| 401 | |
| 402 | #[test] |
| 403 | fn headless_gets_one_start_url_visible_gets_both() { |
| 404 | assert_eq!(start_urls_for(true), ["https://teams.cloud.microsoft/"]); |
| 405 | assert_eq!( |
| 406 | start_urls_for(false), |
| 407 | ["https://teams.cloud.microsoft/", "https://outlook.office.com/mail/"] |
| 408 | ); |
| 409 | } |
| 410 | } |