| 1 | #![allow(dead_code)] |
| 2 | |
| 3 | use std::path::PathBuf; |
| 4 | use std::sync::{Arc, Mutex}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use browser::{ |
| 8 | Browser, BrowserError, Config, ConfigInputs, LaunchRequest, Launcher, Platform, Timeouts, |
| 9 | }; |
| 10 | use futures_util::StreamExt; |
| 11 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 12 | use tokio::net::{TcpListener, TcpStream}; |
| 13 | use tokio::sync::Notify; |
| 14 | use tokio::task::{JoinHandle, JoinSet}; |
| 15 | |
| 16 | #[derive(Default)] |
| 17 | pub struct MockState { |
| 18 | pub tabs: Vec<(String, String)>, |
| 19 | pub requests: Vec<String>, |
| 20 | pub attached: Vec<String>, |
| 21 | pub opened: usize, |
| 22 | pub hung: bool, |
| 23 | pub ignore_close: bool, |
| 24 | } |
| 25 | |
| 26 | fn numbered(urls: &[&str]) -> Vec<(String, String)> { |
| 27 | urls.iter() |
| 28 | .enumerate() |
| 29 | .map(|(index, url)| (format!("P{index}"), (*url).to_owned())) |
| 30 | .collect() |
| 31 | } |
| 32 | |
| 33 | pub struct MockChrome { |
| 34 | pub port: u16, |
| 35 | pub state: Arc<Mutex<MockState>>, |
| 36 | kill: Arc<Notify>, |
| 37 | task: Mutex<Option<JoinHandle<()>>>, |
| 38 | } |
| 39 | |
| 40 | impl MockChrome { |
| 41 | pub async fn new() -> Arc<MockChrome> { |
| 42 | let probe = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 43 | let port = probe.local_addr().unwrap().port(); |
| 44 | drop(probe); |
| 45 | Arc::new(MockChrome { |
| 46 | port, |
| 47 | state: Arc::default(), |
| 48 | kill: Arc::new(Notify::new()), |
| 49 | task: Mutex::new(None), |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | pub async fn start(&self, urls: &[&str]) { |
| 54 | let listener = TcpListener::bind(("127.0.0.1", self.port)).await.unwrap(); |
| 55 | { |
| 56 | let mut state = self.state.lock().unwrap(); |
| 57 | state.tabs = numbered(urls); |
| 58 | state.hung = false; |
| 59 | state.ignore_close = false; |
| 60 | } |
| 61 | let state = self.state.clone(); |
| 62 | let kill = self.kill.clone(); |
| 63 | let port = self.port; |
| 64 | let handle = tokio::spawn(async move { |
| 65 | let accept_loop = async { |
| 66 | let mut connections = JoinSet::new(); |
| 67 | loop { |
| 68 | let (stream, _) = listener.accept().await.unwrap(); |
| 69 | connections.spawn(handle_connection(stream, state.clone(), kill.clone(), port)); |
| 70 | } |
| 71 | }; |
| 72 | tokio::select! { _ = accept_loop => {}, _ = kill.notified() => {} } |
| 73 | }); |
| 74 | *self.task.lock().unwrap() = Some(handle); |
| 75 | } |
| 76 | |
| 77 | pub async fn kill(&self) { |
| 78 | self.kill.notify_one(); |
| 79 | let handle = self.task.lock().unwrap().take(); |
| 80 | if let Some(handle) = handle { |
| 81 | let _ = handle.await; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | pub fn stop_answering(&self, ignore_close: bool) { |
| 86 | let mut state = self.state.lock().unwrap(); |
| 87 | state.hung = true; |
| 88 | state.ignore_close = ignore_close; |
| 89 | } |
| 90 | |
| 91 | pub fn answer_again(&self) { |
| 92 | self.state.lock().unwrap().hung = false; |
| 93 | } |
| 94 | |
| 95 | pub fn kill_now(&self) { |
| 96 | self.kill.notify_one(); |
| 97 | } |
| 98 | |
| 99 | pub fn urls(&self) -> Vec<String> { |
| 100 | self.state |
| 101 | .lock() |
| 102 | .unwrap() |
| 103 | .tabs |
| 104 | .iter() |
| 105 | .map(|(_, url)| url.clone()) |
| 106 | .collect() |
| 107 | } |
| 108 | |
| 109 | pub fn tab_ids(&self) -> Vec<String> { |
| 110 | self.state |
| 111 | .lock() |
| 112 | .unwrap() |
| 113 | .tabs |
| 114 | .iter() |
| 115 | .map(|(id, _)| id.clone()) |
| 116 | .collect() |
| 117 | } |
| 118 | |
| 119 | pub fn set_urls(&self, urls: &[&str]) { |
| 120 | self.state.lock().unwrap().tabs = numbered(urls); |
| 121 | } |
| 122 | |
| 123 | pub fn set_attached(&self, ids: &[&str]) { |
| 124 | self.state.lock().unwrap().attached = ids.iter().map(|id| (*id).to_owned()).collect(); |
| 125 | } |
| 126 | |
| 127 | pub fn requests(&self) -> Vec<String> { |
| 128 | self.state.lock().unwrap().requests.clone() |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | async fn handle_connection( |
| 133 | mut stream: TcpStream, |
| 134 | state: Arc<Mutex<MockState>>, |
| 135 | kill: Arc<Notify>, |
| 136 | port: u16, |
| 137 | ) { |
| 138 | let mut peeked = [0u8; 2048]; |
| 139 | let request_line = loop { |
| 140 | let count = stream.peek(&mut peeked).await.unwrap_or(0); |
| 141 | if count == 0 { |
| 142 | return; |
| 143 | } |
| 144 | let text = String::from_utf8_lossy(&peeked[..count]).into_owned(); |
| 145 | if let Some(line) = text.lines().next().filter(|_| text.contains("\r\n")) { |
| 146 | break line.to_owned(); |
| 147 | } |
| 148 | }; |
| 149 | if request_line.starts_with("GET /devtools/") { |
| 150 | let page_id = request_line |
| 151 | .split_whitespace() |
| 152 | .nth(1) |
| 153 | .and_then(|path| path.strip_prefix("/devtools/page/")) |
| 154 | .map(str::to_owned); |
| 155 | let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap(); |
| 156 | let Some(Ok(message)) = socket.next().await else { |
| 157 | return; |
| 158 | }; |
| 159 | let request: serde_json::Value = |
| 160 | serde_json::from_str(message.to_text().unwrap_or("{}")).unwrap(); |
| 161 | let method = request["method"].as_str().unwrap_or("").to_owned(); |
| 162 | state.lock().unwrap().requests.push(format!("CDP {method}")); |
| 163 | let result = match (method.as_str(), &page_id) { |
| 164 | ("Browser.close", None) => { |
| 165 | if !state.lock().unwrap().ignore_close { |
| 166 | kill.notify_one(); |
| 167 | } |
| 168 | return; |
| 169 | } |
| 170 | ("Runtime.evaluate", Some(_)) => { |
| 171 | if state.lock().unwrap().hung { |
| 172 | std::future::pending::<()>().await; |
| 173 | } |
| 174 | serde_json::json!({"result": {"type": "number", "value": 2}}) |
| 175 | } |
| 176 | ("Target.getTargets", None) => { |
| 177 | let state = state.lock().unwrap(); |
| 178 | let infos: Vec<_> = state |
| 179 | .tabs |
| 180 | .iter() |
| 181 | .map(|(id, _)| serde_json::json!({"targetId": id, "attached": state.attached.contains(id)})) |
| 182 | .collect(); |
| 183 | serde_json::json!({"targetInfos": infos}) |
| 184 | } |
| 185 | ("Page.navigate", Some(id)) => { |
| 186 | let url = request["params"]["url"].as_str().unwrap_or("").to_owned(); |
| 187 | if let Some(tab) = state |
| 188 | .lock() |
| 189 | .unwrap() |
| 190 | .tabs |
| 191 | .iter_mut() |
| 192 | .find(|(tab_id, _)| tab_id == id) |
| 193 | { |
| 194 | tab.1 = url; |
| 195 | } |
| 196 | serde_json::json!({"frameId": "F"}) |
| 197 | } |
| 198 | _ => return, |
| 199 | }; |
| 200 | let reply = serde_json::json!({"id": request["id"], "result": result}); |
| 201 | let _ = futures_util::SinkExt::send( |
| 202 | &mut socket, |
| 203 | tokio_tungstenite::tungstenite::Message::text(reply.to_string()), |
| 204 | ) |
| 205 | .await; |
| 206 | let _ = socket.next().await; |
| 207 | return; |
| 208 | } |
| 209 | let mut raw = Vec::new(); |
| 210 | let mut buffer = [0u8; 2048]; |
| 211 | while !raw.windows(4).any(|window| window == b"\r\n\r\n") { |
| 212 | let count = stream.read(&mut buffer).await.unwrap_or(0); |
| 213 | if count == 0 { |
| 214 | return; |
| 215 | } |
| 216 | raw.extend_from_slice(&buffer[..count]); |
| 217 | } |
| 218 | let mut parts = request_line.split_whitespace(); |
| 219 | let (method, path) = ( |
| 220 | parts.next().unwrap_or(""), |
| 221 | parts.next().unwrap_or("").to_owned(), |
| 222 | ); |
| 223 | state |
| 224 | .lock() |
| 225 | .unwrap() |
| 226 | .requests |
| 227 | .push(format!("{method} {}", path.split('?').next().unwrap_or(""))); |
| 228 | let (status, body) = match (method, path.as_str()) { |
| 229 | ("GET", "/json/version") => ( |
| 230 | 200, |
| 231 | format!( |
| 232 | r#"{{"Browser":"Chrome/154.0.0.1","webSocketDebuggerUrl":"ws://127.0.0.1:{port}/devtools/browser/mock"}}"# |
| 233 | ), |
| 234 | ), |
| 235 | ("GET", "/json/list") => { |
| 236 | let pages: Vec<String> = state |
| 237 | .lock() |
| 238 | .unwrap() |
| 239 | .tabs |
| 240 | .iter() |
| 241 | .map(|(id, url)| format!(r#"{{"id":"{id}","type":"page","url":"{url}"}}"#)) |
| 242 | .collect(); |
| 243 | let extra = |
| 244 | r#"{"id":"W","type":"service_worker","url":"https://teams.cloud.microsoft/sw.js"}"#; |
| 245 | (200, format!("[{},{extra}]", pages.join(","))) |
| 246 | } |
| 247 | ("PUT", path) if path.starts_with("/json/new?") => { |
| 248 | let url = path.trim_start_matches("/json/new?").to_owned(); |
| 249 | let mut state = state.lock().unwrap(); |
| 250 | state.opened += 1; |
| 251 | let id = format!("N{}", state.opened); |
| 252 | state.tabs.push((id.clone(), url.clone())); |
| 253 | ( |
| 254 | 200, |
| 255 | format!(r#"{{"id":"{id}","type":"page","url":"{url}"}}"#), |
| 256 | ) |
| 257 | } |
| 258 | ("GET", path) if path.starts_with("/json/close/") => { |
| 259 | let id = path.trim_start_matches("/json/close/"); |
| 260 | state |
| 261 | .lock() |
| 262 | .unwrap() |
| 263 | .tabs |
| 264 | .retain(|(tab_id, _)| tab_id != id); |
| 265 | (200, "Target is closing".to_owned()) |
| 266 | } |
| 267 | _ => (404, "not found".to_owned()), |
| 268 | }; |
| 269 | let response = format!( |
| 270 | "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nContent-Type: application/json\r\n\r\n{body}", |
| 271 | body.len() |
| 272 | ); |
| 273 | let _ = stream.write_all(response.as_bytes()).await; |
| 274 | // like Chrome, keep the connection open until the client hangs up |
| 275 | let _ = stream.read(&mut buffer).await; |
| 276 | } |
| 277 | |
| 278 | pub struct FakeLauncher { |
| 279 | pub mock: Arc<MockChrome>, |
| 280 | pub requests: Mutex<Vec<LaunchRequest>>, |
| 281 | pub fail: Mutex<bool>, |
| 282 | pub foreign: Mutex<Option<Vec<&'static str>>>, |
| 283 | pub kills: Mutex<usize>, |
| 284 | } |
| 285 | |
| 286 | impl Launcher for FakeLauncher { |
| 287 | fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> { |
| 288 | self.requests.lock().unwrap().push(request.clone()); |
| 289 | if *self.fail.lock().unwrap() { |
| 290 | return Err(BrowserError::ChromeNotFound("fake failure".into())); |
| 291 | } |
| 292 | let mock = self.mock.clone(); |
| 293 | let urls = match self.foreign.lock().unwrap().take() { |
| 294 | Some(foreign) => foreign.into_iter().map(str::to_owned).collect(), |
| 295 | None => request.start_urls.clone(), |
| 296 | }; |
| 297 | tokio::spawn(async move { |
| 298 | let refs: Vec<&str> = urls.iter().map(String::as_str).collect(); |
| 299 | mock.start(&refs).await; |
| 300 | }); |
| 301 | Ok(()) |
| 302 | } |
| 303 | |
| 304 | fn kill_listener(&self, _port: u16) -> Result<(), BrowserError> { |
| 305 | *self.kills.lock().unwrap() += 1; |
| 306 | self.mock.kill_now(); |
| 307 | Ok(()) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | pub struct Harness { |
| 312 | pub browser: Browser, |
| 313 | pub mock: Arc<MockChrome>, |
| 314 | pub launcher: Arc<FakeLauncher>, |
| 315 | pub mode_file: PathBuf, |
| 316 | pub directory: tempfile::TempDir, |
| 317 | } |
| 318 | |
| 319 | pub async fn harness() -> Harness { |
| 320 | let directory = tempfile::tempdir().unwrap(); |
| 321 | let mock = MockChrome::new().await; |
| 322 | let to_local = |path: &str| path.to_owned(); |
| 323 | let inputs = ConfigInputs { |
| 324 | windows_variables: Default::default(), |
| 325 | linux_data_dir: Some(directory.path().to_path_buf()), |
| 326 | home_dir: None, |
| 327 | to_local: &to_local, |
| 328 | }; |
| 329 | let config = Config::resolve(Platform::Linux, mock.port, &inputs).unwrap(); |
| 330 | let mode_file = config.mode_file.clone(); |
| 331 | let launcher = Arc::new(FakeLauncher { |
| 332 | mock: mock.clone(), |
| 333 | requests: Mutex::default(), |
| 334 | fail: Mutex::new(false), |
| 335 | foreign: Mutex::default(), |
| 336 | kills: Mutex::default(), |
| 337 | }); |
| 338 | let timeouts = Timeouts { |
| 339 | start: Duration::from_secs(5), |
| 340 | stop: Duration::from_secs(1), |
| 341 | probe: Duration::from_millis(200), |
| 342 | poll: Duration::from_millis(20), |
| 343 | profile_release: Duration::from_millis(10), |
| 344 | jitter_min: Duration::from_millis(5), |
| 345 | jitter_max: Duration::from_millis(20), |
| 346 | }; |
| 347 | let browser = Browser::with_launcher(config, launcher.clone(), timeouts); |
| 348 | Harness { |
| 349 | browser, |
| 350 | mock, |
| 351 | launcher, |
| 352 | mode_file, |
| 353 | directory, |
| 354 | } |
| 355 | } |