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