| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Arc; |
| 3 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use serde_json::{Value, json}; |
| 7 | use tokio::sync::Mutex; |
| 8 | use tokio::time::{Instant, sleep}; |
| 9 | |
| 10 | use crate::app::App; |
| 11 | use crate::error::{Error, Result}; |
| 12 | use crate::events::TabControl; |
| 13 | use crate::native::NativeHttp; |
| 14 | use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult}; |
| 15 | use crate::scope::Scope; |
| 16 | use crate::transport::{CdpTransport, Transport}; |
| 17 | |
| 18 | pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222"; |
| 19 | pub(crate) const FETCH_SCRIPT: &str = include_str!("../assets/fetch.js"); |
| 20 | pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted"; |
| 21 | const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024; |
| 22 | const DEFAULT_CONCURRENCY: usize = 6; |
| 23 | |
| 24 | #[derive(Debug, Clone)] |
| 25 | pub struct SessionConfig { |
| 26 | pub refresh_margin: Duration, |
| 27 | pub token_wait: Duration, |
| 28 | pub token_poll: Duration, |
| 29 | pub evaluate_timeout: Duration, |
| 30 | pub max_throttle_retries: usize, |
| 31 | pub max_retry_wait: Duration, |
| 32 | pub default_retry_wait: Duration, |
| 33 | pub unauthorized_reload_wait: Duration, |
| 34 | pub native_http: bool, |
| 35 | } |
| 36 | |
| 37 | impl Default for SessionConfig { |
| 38 | fn default() -> Self { |
| 39 | SessionConfig { |
| 40 | refresh_margin: Duration::from_secs(120), |
| 41 | token_wait: Duration::from_secs(60), |
| 42 | token_poll: Duration::from_secs(3), |
| 43 | evaluate_timeout: Duration::from_secs(60), |
| 44 | max_throttle_retries: 3, |
| 45 | max_retry_wait: Duration::from_secs(30), |
| 46 | default_retry_wait: Duration::from_secs(2), |
| 47 | unauthorized_reload_wait: Duration::from_secs(5), |
| 48 | native_http: false, |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl SessionConfig { |
| 54 | /// The app's settings: requests go out from Rust unless TEAMS_PAGE_FETCH is set. |
| 55 | pub fn for_app() -> Self { |
| 56 | SessionConfig { |
| 57 | native_http: std::env::var_os("TEAMS_PAGE_FETCH").is_none(), |
| 58 | ..SessionConfig::default() |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | #[derive(Default)] |
| 64 | struct TokenSearch { |
| 65 | refresh_error: Option<String>, |
| 66 | pages: Vec<String>, |
| 67 | ungranted: HashSet<App>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Clone)] |
| 71 | pub struct Session { |
| 72 | pub(crate) transport: Arc<dyn Transport>, |
| 73 | pub(crate) config: SessionConfig, |
| 74 | tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>, |
| 75 | force_refresh: Arc<AtomicBool>, |
| 76 | native: Option<Arc<NativeHttp>>, |
| 77 | } |
| 78 | |
| 79 | impl Session { |
| 80 | pub async fn connect(endpoint: &str) -> Result<Self> { |
| 81 | Self::connect_with(endpoint, SessionConfig::default()).await |
| 82 | } |
| 83 | |
| 84 | pub async fn connect_with(endpoint: &str, config: SessionConfig) -> Result<Self> { |
| 85 | Self::with_transport(Arc::new(CdpTransport::new(endpoint)), config).await |
| 86 | } |
| 87 | |
| 88 | pub async fn with_transport( |
| 89 | transport: Arc<dyn Transport>, |
| 90 | config: SessionConfig, |
| 91 | ) -> Result<Self> { |
| 92 | transport.check().await?; |
| 93 | let native = config |
| 94 | .native_http |
| 95 | .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES)) |
| 96 | .flatten() |
| 97 | .map(Arc::new); |
| 98 | Ok(Session { |
| 99 | native, |
| 100 | transport, |
| 101 | config, |
| 102 | tabs: Arc::new( |
| 103 | App::ALL |
| 104 | .into_iter() |
| 105 | .map(|app| (app, Mutex::new(None))) |
| 106 | .collect(), |
| 107 | ), |
| 108 | force_refresh: Arc::new(AtomicBool::new(false)), |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | pub async fn request( |
| 113 | &self, |
| 114 | method: Method, |
| 115 | url: &str, |
| 116 | scope: &Scope, |
| 117 | body: Option<Value>, |
| 118 | ) -> Result<ApiResponse> { |
| 119 | let request = Request { |
| 120 | method, |
| 121 | body, |
| 122 | ..Request::get(url) |
| 123 | }; |
| 124 | self.send(request, scope).await |
| 125 | } |
| 126 | |
| 127 | pub async fn send(&self, request: Request, scope: &Scope) -> Result<ApiResponse> { |
| 128 | let url = request.url.clone(); |
| 129 | let response = self.batch(&[request], scope).await?.remove(0); |
| 130 | if response.status >= 400 || response.status == 0 { |
| 131 | return Err(Error::api(response.status, &url, response.body)); |
| 132 | } |
| 133 | Ok(response) |
| 134 | } |
| 135 | |
| 136 | pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> { |
| 137 | let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()]; |
| 138 | let mut pending: Vec<usize> = (0..requests.len()).collect(); |
| 139 | for attempt in 0..=self.config.max_throttle_retries { |
| 140 | let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect(); |
| 141 | let answers = self.run_with_fresh_token(&batch, scope).await?; |
| 142 | let unauthorized_first_try = |
| 143 | attempt == 0 && answers.iter().any(|answer| answer.status == 401); |
| 144 | if unauthorized_first_try { |
| 145 | // A CAE-revoked token stays unexpired in the app cache, so only a refresh-token grant replaces it. |
| 146 | self.force_refresh.store(true, Ordering::SeqCst); |
| 147 | self.reload_all().await; |
| 148 | sleep(self.config.unauthorized_reload_wait).await; |
| 149 | self.drop_all().await; |
| 150 | } |
| 151 | let mut retry = Vec::new(); |
| 152 | for (&index, answer) in pending.iter().zip(answers) { |
| 153 | let throttled = answer.status == 429 || (attempt == 0 && answer.status == 401); |
| 154 | results[index] = Some(answer); |
| 155 | if throttled { |
| 156 | retry.push(index); |
| 157 | } |
| 158 | } |
| 159 | if !unauthorized_first_try { |
| 160 | self.force_refresh.store(false, Ordering::SeqCst); |
| 161 | } |
| 162 | if retry.is_empty() || attempt == self.config.max_throttle_retries { |
| 163 | break; |
| 164 | } |
| 165 | let wait = retry |
| 166 | .iter() |
| 167 | .filter_map(|&index| results[index].as_ref()) |
| 168 | .map(|answer| { |
| 169 | retry_wait( |
| 170 | answer.retry_after.as_deref(), |
| 171 | self.config.default_retry_wait, |
| 172 | ) |
| 173 | }) |
| 174 | .max() |
| 175 | .unwrap_or_default(); |
| 176 | sleep(wait.min(self.config.max_retry_wait)).await; |
| 177 | pending = retry; |
| 178 | } |
| 179 | Ok(results.into_iter().flatten().collect()) |
| 180 | } |
| 181 | |
| 182 | /// Keeps the app tab where it is until the guard drops, e.g. for the length of a call. |
| 183 | pub fn hold_tab(&self, app: App) -> TabHold { |
| 184 | self.transport.hold(app, true); |
| 185 | TabHold { |
| 186 | transport: self.transport.clone(), |
| 187 | app, |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | pub async fn close(&self) { |
| 192 | self.drop_all().await; |
| 193 | } |
| 194 | |
| 195 | async fn run_with_fresh_token( |
| 196 | &self, |
| 197 | requests: &[&Request], |
| 198 | scope: &Scope, |
| 199 | ) -> Result<Vec<ApiResponse>> { |
| 200 | if let Some(native) = &self.native |
| 201 | && let Some(results) = native |
| 202 | .run( |
| 203 | self, |
| 204 | requests, |
| 205 | scope, |
| 206 | self.force_refresh.load(Ordering::SeqCst), |
| 207 | ) |
| 208 | .await |
| 209 | { |
| 210 | return Ok(results); |
| 211 | } |
| 212 | let mut search = TokenSearch::default(); |
| 213 | if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? { |
| 214 | return Ok(results); |
| 215 | } |
| 216 | if search.ungranted.len() == App::ALL.len() { |
| 217 | return Err(Error::LoginRequired(format!( |
| 218 | "the Teams web app is not granted {scope}" |
| 219 | ))); |
| 220 | } |
| 221 | self.reload_all().await; |
| 222 | let deadline = Instant::now() + self.config.token_wait; |
| 223 | while Instant::now() < deadline { |
| 224 | sleep(self.config.token_poll).await; |
| 225 | self.drop_all().await; |
| 226 | if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? { |
| 227 | return Ok(results); |
| 228 | } |
| 229 | } |
| 230 | let diagnosis = self.transport.diagnose().await?; |
| 231 | if diagnosis.login_pending { |
| 232 | return Err(Error::LoginRequired("sign in in the browser window".into())); |
| 233 | } |
| 234 | if !diagnosis.app_tab_open { |
| 235 | return Err(Error::NoAppTab); |
| 236 | } |
| 237 | let mut detail = search |
| 238 | .refresh_error |
| 239 | .map(|reason| format!(" (token refresh failed in {reason})")) |
| 240 | .unwrap_or_default(); |
| 241 | if !search.pages.is_empty() { |
| 242 | detail.push_str(&format!(" [{}]", search.pages.join("; "))); |
| 243 | } |
| 244 | Err(Error::NoFreshToken { |
| 245 | scope: scope.to_string(), |
| 246 | detail, |
| 247 | }) |
| 248 | } |
| 249 | |
| 250 | async fn run_in_any_tab( |
| 251 | &self, |
| 252 | requests: &[&Request], |
| 253 | scope: &Scope, |
| 254 | search: &mut TokenSearch, |
| 255 | ) -> Result<Option<Vec<ApiResponse>>> { |
| 256 | let payload = self.payload(requests, scope); |
| 257 | let expression = format!("({FETCH_SCRIPT})({payload})"); |
| 258 | let has_write = requests.iter().any(|request| request.method != Method::Get); |
| 259 | for app in App::ALL { |
| 260 | let outcome = match self.evaluate_in(app, &expression).await { |
| 261 | Ok(Some(value)) => value, |
| 262 | Ok(None) => continue, |
| 263 | Err(error) => { |
| 264 | self.drop_connection(app).await; |
| 265 | if has_write { |
| 266 | return Err(Error::WriteInterrupted(error.to_string())); |
| 267 | } |
| 268 | continue; |
| 269 | } |
| 270 | }; |
| 271 | let outcome: Outcome = serde_json::from_value(outcome) |
| 272 | .map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?; |
| 273 | if let Some(results) = outcome.results { |
| 274 | return Ok(Some(results.into_iter().map(WireResult::into).collect())); |
| 275 | } |
| 276 | if let Some(page) = &outcome.page { |
| 277 | let line = format!("{app}: {page}"); |
| 278 | search |
| 279 | .pages |
| 280 | .retain(|seen| !seen.starts_with(&format!("{app}:"))); |
| 281 | search.pages.push(line); |
| 282 | } |
| 283 | if let Some(reason) = outcome.refresh_error { |
| 284 | if reason.starts_with(NOT_GRANTED_PREFIX) { |
| 285 | search.ungranted.insert(app); |
| 286 | } |
| 287 | search |
| 288 | .refresh_error |
| 289 | .get_or_insert_with(|| format!("{app}: {reason}")); |
| 290 | } |
| 291 | } |
| 292 | Ok(None) |
| 293 | } |
| 294 | |
| 295 | fn payload(&self, requests: &[&Request], scope: &Scope) -> String { |
| 296 | let wire: Vec<WireRequest> = requests.iter().map(|&request| request.into()).collect(); |
| 297 | json!({ |
| 298 | "requests": wire, |
| 299 | "resource": scope.resource, |
| 300 | "scope": scope.name, |
| 301 | "nestedApp": scope.nested_app_json(), |
| 302 | "marginMs": self.config.refresh_margin.as_millis() as u64, |
| 303 | "concurrency": DEFAULT_CONCURRENCY, |
| 304 | "maxBytes": MAX_DOWNLOAD_BYTES, |
| 305 | "forceRefresh": self.force_refresh.load(Ordering::SeqCst), |
| 306 | }) |
| 307 | .to_string() |
| 308 | } |
| 309 | |
| 310 | pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> { |
| 311 | let mut slot = self.tabs[&app].lock().await; |
| 312 | if slot.is_none() { |
| 313 | let Some((control, _)) = self.transport.open(app, false).await? else { |
| 314 | return Ok(None); |
| 315 | }; |
| 316 | *slot = Some(control); |
| 317 | } |
| 318 | let control = slot.as_ref().expect("connection set above"); |
| 319 | let outcome = control |
| 320 | .evaluate_within(expression, self.config.evaluate_timeout) |
| 321 | .await; |
| 322 | if outcome.is_err() { |
| 323 | *slot = None; |
| 324 | } |
| 325 | outcome.map(Some) |
| 326 | } |
| 327 | |
| 328 | async fn drop_connection(&self, app: App) { |
| 329 | *self.tabs[&app].lock().await = None; |
| 330 | } |
| 331 | |
| 332 | async fn drop_all(&self) { |
| 333 | for app in App::ALL { |
| 334 | self.drop_connection(app).await; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | async fn reload_all(&self) { |
| 339 | for app in App::ALL { |
| 340 | let _ = self.transport.wake(app).await; |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | pub struct TabHold { |
| 346 | transport: Arc<dyn Transport>, |
| 347 | app: App, |
| 348 | } |
| 349 | |
| 350 | impl Drop for TabHold { |
| 351 | fn drop(&mut self) { |
| 352 | self.transport.hold(self.app, false); |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration { |
| 357 | header |
| 358 | .and_then(|value| value.trim().parse::<f64>().ok()) |
| 359 | .filter(|seconds| seconds.is_finite() && *seconds >= 0.0) |
| 360 | .map(Duration::from_secs_f64) |
| 361 | .unwrap_or(default) |
| 362 | } |
| 363 | |
| 364 | #[cfg(test)] |
| 365 | mod tests { |
| 366 | use std::sync::Mutex as StdMutex; |
| 367 | |
| 368 | use super::*; |
| 369 | use crate::transport::{BoxFuture, Diagnosis, OpenedTab}; |
| 370 | |
| 371 | #[derive(Default)] |
| 372 | struct HoldRecorder { |
| 373 | holds: StdMutex<Vec<(App, bool)>>, |
| 374 | } |
| 375 | |
| 376 | impl Transport for HoldRecorder { |
| 377 | fn check(&self) -> BoxFuture<'_, Result<()>> { |
| 378 | Box::pin(async { Ok(()) }) |
| 379 | } |
| 380 | |
| 381 | fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> { |
| 382 | Box::pin(async { Ok(None) }) |
| 383 | } |
| 384 | |
| 385 | fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> { |
| 386 | Box::pin(async { Ok(()) }) |
| 387 | } |
| 388 | |
| 389 | fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> { |
| 390 | Box::pin(async { Ok(Diagnosis::default()) }) |
| 391 | } |
| 392 | |
| 393 | fn hold(&self, app: App, held: bool) { |
| 394 | self.holds.lock().unwrap().push((app, held)); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | #[tokio::test] |
| 399 | async fn tab_hold_releases_the_tab_when_dropped() { |
| 400 | let recorder = Arc::new(HoldRecorder::default()); |
| 401 | let session = Session::with_transport(recorder.clone(), SessionConfig::default()) |
| 402 | .await |
| 403 | .unwrap(); |
| 404 | let hold = session.hold_tab(App::Teams); |
| 405 | assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]); |
| 406 | drop(hold); |
| 407 | assert_eq!( |
| 408 | *recorder.holds.lock().unwrap(), |
| 409 | vec![(App::Teams, true), (App::Teams, false)] |
| 410 | ); |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn retry_after_seconds_parse() { |
| 415 | let default = Duration::from_secs(2); |
| 416 | assert_eq!(retry_wait(Some("7"), default), Duration::from_secs(7)); |
| 417 | assert_eq!( |
| 418 | retry_wait(Some(" 1.5 "), default), |
| 419 | Duration::from_millis(1500) |
| 420 | ); |
| 421 | } |
| 422 | |
| 423 | #[test] |
| 424 | fn retry_after_falls_back() { |
| 425 | let default = Duration::from_secs(2); |
| 426 | assert_eq!(retry_wait(None, default), default); |
| 427 | assert_eq!( |
| 428 | retry_wait(Some("Wed, 21 Oct 2026 07:28:00 GMT"), default), |
| 429 | default |
| 430 | ); |
| 431 | assert_eq!(retry_wait(Some("-3"), default), default); |
| 432 | } |
| 433 | } |