| 1 | //! One WebDriver BiDi session for the whole app. Firefox allows a single session per browser and |
| 2 | //! keeps it after the socket closes, so every caller shares this connection. |
| 3 | |
| 4 | use std::collections::HashMap; |
| 5 | use std::sync::Arc; |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | use futures_util::{SinkExt, StreamExt}; |
| 9 | use serde_json::{Map, Value, json}; |
| 10 | use tokio::sync::{Mutex, broadcast, mpsc, oneshot}; |
| 11 | use tokio_tungstenite::tungstenite::Message; |
| 12 | |
| 13 | use crate::error::BrowserError; |
| 14 | use crate::targets::{self, Tab}; |
| 15 | |
| 16 | const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); |
| 17 | const EVENT_BUFFER: usize = 1024; |
| 18 | /// Subscribed once per session; tab channels filter by context. |
| 19 | const EVENTS: [&str; 2] = ["script.message", "browsingContext.load"]; |
| 20 | |
| 21 | struct Call { |
| 22 | method: String, |
| 23 | params: Value, |
| 24 | reply: oneshot::Sender<Result<Value, BrowserError>>, |
| 25 | } |
| 26 | |
| 27 | /// A BiDi event as `{method, params}`. |
| 28 | pub type Event = Value; |
| 29 | |
| 30 | #[derive(Clone)] |
| 31 | pub struct Bidi { |
| 32 | port: u16, |
| 33 | connection: Arc<Mutex<Option<Connection>>>, |
| 34 | } |
| 35 | |
| 36 | struct Connection { |
| 37 | commands: mpsc::UnboundedSender<Call>, |
| 38 | /// Kept only to hand out receivers. The pump owns the sender, so receivers close with the socket. |
| 39 | events: broadcast::Receiver<Event>, |
| 40 | } |
| 41 | |
| 42 | /// A top-level browsing context, the BiDi word for a tab. |
| 43 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 44 | pub struct Context { |
| 45 | pub id: String, |
| 46 | pub url: String, |
| 47 | } |
| 48 | |
| 49 | impl Bidi { |
| 50 | pub fn new(port: u16) -> Bidi { |
| 51 | Bidi { |
| 52 | port, |
| 53 | connection: Arc::new(Mutex::new(None)), |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /// Events of every tab on the current connection, from the moment of the call. The stream |
| 58 | /// ends when the connection does, for example when the browser restarts. |
| 59 | pub async fn events(&self) -> Result<broadcast::Receiver<Event>, BrowserError> { |
| 60 | self.connected(|connection| connection.events.resubscribe()) |
| 61 | .await |
| 62 | } |
| 63 | |
| 64 | pub async fn call(&self, method: &str, params: Value) -> Result<Value, BrowserError> { |
| 65 | let commands = self |
| 66 | .connected(|connection| connection.commands.clone()) |
| 67 | .await?; |
| 68 | send(&commands, method, params).await |
| 69 | } |
| 70 | |
| 71 | /// Opens the session if there is none. [`BrowserError::SessionTaken`] when a session another |
| 72 | /// process left behind blocks it: only a browser restart frees that. |
| 73 | pub async fn connect(&self) -> Result<(), BrowserError> { |
| 74 | self.connected(|_| ()).await |
| 75 | } |
| 76 | |
| 77 | async fn connected<T>(&self, read: impl FnOnce(&Connection) -> T) -> Result<T, BrowserError> { |
| 78 | let mut connection = self.connection.lock().await; |
| 79 | if let Some(open) = connection |
| 80 | .as_ref() |
| 81 | .filter(|open| !open.commands.is_closed()) |
| 82 | { |
| 83 | return Ok(read(open)); |
| 84 | } |
| 85 | *connection = None; |
| 86 | let url = format!("ws://127.0.0.1:{}/session", self.port); |
| 87 | let (stream, _) = |
| 88 | tokio::time::timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(&url)) |
| 89 | .await |
| 90 | .map_err(|_| BrowserError::NoBrowser(format!("{url}: connect timed out")))? |
| 91 | .map_err(|error| BrowserError::NoBrowser(format!("{url}: {error}")))?; |
| 92 | let (commands, receiver) = mpsc::unbounded_channel(); |
| 93 | let (events_sender, events) = broadcast::channel(EVENT_BUFFER); |
| 94 | tokio::spawn(pump(stream, receiver, events_sender)); |
| 95 | let opened = tokio::time::timeout( |
| 96 | CONNECT_TIMEOUT, |
| 97 | send(&commands, "session.new", json!({"capabilities": {}})), |
| 98 | ) |
| 99 | .await |
| 100 | .map_err(|_| BrowserError::Cdp("session.new timed out".into()))?; |
| 101 | match opened { |
| 102 | Err(BrowserError::Cdp(text)) if text.contains("session not created") => { |
| 103 | return Err(BrowserError::SessionTaken(self.port)); |
| 104 | } |
| 105 | outcome => outcome?, |
| 106 | }; |
| 107 | send(&commands, "session.subscribe", json!({"events": EVENTS})).await?; |
| 108 | let open = Connection { commands, events }; |
| 109 | let value = read(&open); |
| 110 | *connection = Some(open); |
| 111 | Ok(value) |
| 112 | } |
| 113 | |
| 114 | pub async fn contexts(&self) -> Result<Vec<Context>, BrowserError> { |
| 115 | let tree = self |
| 116 | .call("browsingContext.getTree", json!({"maxDepth": 0})) |
| 117 | .await?; |
| 118 | Ok(contexts_of(&tree)) |
| 119 | } |
| 120 | |
| 121 | pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> { |
| 122 | Ok(self |
| 123 | .contexts() |
| 124 | .await? |
| 125 | .into_iter() |
| 126 | .map(|context| targets::tab_from_url(context.id, &context.url)) |
| 127 | .collect()) |
| 128 | } |
| 129 | |
| 130 | /// Evaluates `expression` in the tab and answers its value as JSON. |
| 131 | pub async fn evaluate(&self, context: &str, expression: &str) -> Result<Value, BrowserError> { |
| 132 | let params = json!({ |
| 133 | "expression": expression, |
| 134 | "target": {"context": context}, |
| 135 | "awaitPromise": true, |
| 136 | "resultOwnership": "none", |
| 137 | }); |
| 138 | let result = self.call("script.evaluate", params).await?; |
| 139 | evaluation_value(&result).map_err(BrowserError::Cdp) |
| 140 | } |
| 141 | |
| 142 | pub async fn navigate(&self, context: &str, url: &str) -> Result<(), BrowserError> { |
| 143 | let params = json!({"context": context, "url": url, "wait": "none"}); |
| 144 | self.call("browsingContext.navigate", params) |
| 145 | .await |
| 146 | .map(drop) |
| 147 | } |
| 148 | |
| 149 | pub async fn open_tab(&self, url: &str) -> Result<(), BrowserError> { |
| 150 | let created = self |
| 151 | .call("browsingContext.create", json!({"type": "tab"})) |
| 152 | .await?; |
| 153 | let context = created["context"].as_str().unwrap_or_default().to_owned(); |
| 154 | self.navigate(&context, url).await |
| 155 | } |
| 156 | |
| 157 | pub async fn close_tab(&self, context: &str) -> Result<(), BrowserError> { |
| 158 | self.call("browsingContext.close", json!({"context": context})) |
| 159 | .await |
| 160 | .map(drop) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | async fn send( |
| 165 | commands: &mpsc::UnboundedSender<Call>, |
| 166 | method: &str, |
| 167 | params: Value, |
| 168 | ) -> Result<Value, BrowserError> { |
| 169 | let (reply, answer) = oneshot::channel(); |
| 170 | let closed = || BrowserError::Cdp(format!("{method}: BiDi connection closed")); |
| 171 | commands |
| 172 | .send(Call { |
| 173 | method: method.to_owned(), |
| 174 | params, |
| 175 | reply, |
| 176 | }) |
| 177 | .map_err(|_| closed())?; |
| 178 | answer.await.map_err(|_| closed())? |
| 179 | } |
| 180 | |
| 181 | async fn pump<S>( |
| 182 | mut stream: S, |
| 183 | mut commands: mpsc::UnboundedReceiver<Call>, |
| 184 | events: broadcast::Sender<Event>, |
| 185 | ) where |
| 186 | S: futures_util::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> |
| 187 | + futures_util::Sink<Message> |
| 188 | + Unpin, |
| 189 | { |
| 190 | let mut pending: HashMap<u64, (String, oneshot::Sender<Result<Value, BrowserError>>)> = |
| 191 | HashMap::new(); |
| 192 | let mut next_id: u64 = 1; |
| 193 | loop { |
| 194 | tokio::select! { |
| 195 | call = commands.recv() => { |
| 196 | let Some(call) = call else { break }; |
| 197 | let id = next_id; |
| 198 | next_id += 1; |
| 199 | let frame = json!({"id": id, "method": call.method, "params": call.params}); |
| 200 | if stream.send(Message::text(frame.to_string())).await.is_err() { |
| 201 | let _ = call.reply.send(Err(BrowserError::Cdp("BiDi send failed".into()))); |
| 202 | break; |
| 203 | } |
| 204 | pending.insert(id, (call.method, call.reply)); |
| 205 | } |
| 206 | message = stream.next() => { |
| 207 | let Some(Ok(message)) = message else { break }; |
| 208 | let Message::Text(text) = message else { |
| 209 | if matches!(message, Message::Close(_)) { |
| 210 | break; |
| 211 | } |
| 212 | continue; |
| 213 | }; |
| 214 | let Ok(frame) = serde_json::from_str::<Value>(text.as_str()) else { continue }; |
| 215 | if let Some(id) = frame.get("id").and_then(Value::as_u64) { |
| 216 | if let Some((method, reply)) = pending.remove(&id) { |
| 217 | let _ = reply.send(answer_of(&method, &frame)); |
| 218 | } |
| 219 | } else if frame["type"] == "event" { |
| 220 | let _ = events.send(json!({"method": frame["method"], "params": frame["params"]})); |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | for (method, reply) in pending.into_values() { |
| 226 | let _ = reply.send(Err(BrowserError::Cdp(format!( |
| 227 | "{method}: BiDi connection closed" |
| 228 | )))); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | fn answer_of(method: &str, frame: &Value) -> Result<Value, BrowserError> { |
| 233 | if frame["type"] == "error" { |
| 234 | let error = frame["error"].as_str().unwrap_or("error"); |
| 235 | let message = frame["message"].as_str().unwrap_or_default(); |
| 236 | return Err(BrowserError::Cdp(format!("{method}: {error}: {message}"))); |
| 237 | } |
| 238 | Ok(frame.get("result").cloned().unwrap_or(Value::Null)) |
| 239 | } |
| 240 | |
| 241 | pub(crate) fn contexts_of(tree: &Value) -> Vec<Context> { |
| 242 | tree["contexts"] |
| 243 | .as_array() |
| 244 | .into_iter() |
| 245 | .flatten() |
| 246 | .filter_map(|context| { |
| 247 | Some(Context { |
| 248 | id: context["context"].as_str()?.to_owned(), |
| 249 | url: context["url"].as_str().unwrap_or_default().to_owned(), |
| 250 | }) |
| 251 | }) |
| 252 | .collect() |
| 253 | } |
| 254 | |
| 255 | /// The value of a `script.evaluate` result, or the exception text. |
| 256 | pub fn evaluation_value(result: &Value) -> Result<Value, String> { |
| 257 | if result["type"] == "exception" { |
| 258 | let text = result |
| 259 | .pointer("/exceptionDetails/text") |
| 260 | .and_then(Value::as_str) |
| 261 | .unwrap_or("unknown"); |
| 262 | return Err(text.to_owned()); |
| 263 | } |
| 264 | Ok(remote_value_to_json(&result["result"])) |
| 265 | } |
| 266 | |
| 267 | /// Turns a BiDi remote value into the JSON CDP's `returnByValue` would give. Values JSON cannot |
| 268 | /// hold (NaN, functions, nodes) become null. |
| 269 | pub fn remote_value_to_json(remote: &Value) -> Value { |
| 270 | let value = &remote["value"]; |
| 271 | match remote["type"].as_str().unwrap_or_default() { |
| 272 | "string" | "boolean" => value.clone(), |
| 273 | "number" if value.is_number() => value.clone(), |
| 274 | "number" if value == "-0" => json!(0), |
| 275 | "bigint" | "date" => value.clone(), |
| 276 | "array" | "set" => Value::Array( |
| 277 | value |
| 278 | .as_array() |
| 279 | .into_iter() |
| 280 | .flatten() |
| 281 | .map(remote_value_to_json) |
| 282 | .collect(), |
| 283 | ), |
| 284 | "object" | "map" => Value::Object( |
| 285 | value |
| 286 | .as_array() |
| 287 | .into_iter() |
| 288 | .flatten() |
| 289 | .filter_map(|pair| { |
| 290 | let key = match &pair[0] { |
| 291 | Value::String(key) => key.clone(), |
| 292 | other => remote_value_to_json(other).as_str()?.to_owned(), |
| 293 | }; |
| 294 | Some((key, remote_value_to_json(&pair[1]))) |
| 295 | }) |
| 296 | .collect::<Map<String, Value>>(), |
| 297 | ), |
| 298 | _ => Value::Null, |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | #[cfg(test)] |
| 303 | mod tests { |
| 304 | use super::*; |
| 305 | |
| 306 | #[test] |
| 307 | fn remote_values_become_plain_json() { |
| 308 | let remote = json!({"type": "object", "value": [ |
| 309 | ["a", {"type": "array", "value": [ |
| 310 | {"type": "number", "value": 1}, |
| 311 | {"type": "number", "value": "NaN"}, |
| 312 | {"type": "undefined"}, |
| 313 | {"type": "string", "value": "x"}, |
| 314 | ]}], |
| 315 | ["b", {"type": "object", "value": [["c", {"type": "boolean", "value": true}]]}], |
| 316 | ["d", {"type": "null"}], |
| 317 | ["e", {"type": "function"}], |
| 318 | ]}); |
| 319 | assert_eq!( |
| 320 | remote_value_to_json(&remote), |
| 321 | json!({"a": [1, null, null, "x"], "b": {"c": true}, "d": null, "e": null}) |
| 322 | ); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn evaluation_answers_value_or_exception_text() { |
| 327 | let success = json!({"type": "success", "result": {"type": "number", "value": 2}}); |
| 328 | assert_eq!(evaluation_value(&success), Ok(json!(2))); |
| 329 | let exception = json!({"type": "exception", "exceptionDetails": {"text": "Error: boom"}}); |
| 330 | assert_eq!(evaluation_value(&exception), Err("Error: boom".to_owned())); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn reads_top_level_contexts() { |
| 335 | let tree = json!({"contexts": [ |
| 336 | {"context": "a", "url": "about:blank", "children": []}, |
| 337 | {"context": "b", "url": "https://teams.cloud.microsoft/", "children": []}, |
| 338 | ]}); |
| 339 | assert_eq!( |
| 340 | contexts_of(&tree), |
| 341 | [ |
| 342 | Context { |
| 343 | id: "a".into(), |
| 344 | url: "about:blank".into() |
| 345 | }, |
| 346 | Context { |
| 347 | id: "b".into(), |
| 348 | url: "https://teams.cloud.microsoft/".into() |
| 349 | }, |
| 350 | ] |
| 351 | ); |
| 352 | } |
| 353 | } |