| 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::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult}; |
| 14 | use crate::scope::Scope; |
| 15 | use crate::transport::{CdpTransport, Transport}; |
| 16 | |
| 17 | pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222"; |
| 18 | pub(crate) const FETCH_SCRIPT: &str = include_str!("../assets/fetch.js"); |
| 19 | pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted"; |
| 20 | const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024; |
| 21 | const DEFAULT_CONCURRENCY: usize = 6; |
| 22 | |
| 23 | #[derive(Debug, Clone)] |
| 24 | pub struct SessionConfig { |
| 25 | pub refresh_margin: Duration, |
| 26 | pub token_wait: Duration, |
| 27 | pub token_poll: Duration, |
| 28 | pub evaluate_timeout: Duration, |
| 29 | pub max_throttle_retries: usize, |
| 30 | pub max_retry_wait: Duration, |
| 31 | pub default_retry_wait: Duration, |
| 32 | pub unauthorized_reload_wait: Duration, |
| 33 | } |
| 34 | |
| 35 | impl Default for SessionConfig { |
| 36 | fn default() -> Self { |
| 37 | SessionConfig { |
| 38 | refresh_margin: Duration::from_secs(120), |
| 39 | token_wait: Duration::from_secs(60), |
| 40 | token_poll: Duration::from_secs(3), |
| 41 | evaluate_timeout: Duration::from_secs(60), |
| 42 | max_throttle_retries: 3, |
| 43 | max_retry_wait: Duration::from_secs(30), |
| 44 | default_retry_wait: Duration::from_secs(2), |
| 45 | unauthorized_reload_wait: Duration::from_secs(5), |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #[derive(Default)] |
| 51 | struct TokenSearch { |
| 52 | refresh_error: Option<String>, |
| 53 | ungranted: HashSet<App>, |
| 54 | } |
| 55 | |
| 56 | #[derive(Clone)] |
| 57 | pub struct Session { |
| 58 | pub(crate) transport: Arc<dyn Transport>, |
| 59 | pub(crate) config: SessionConfig, |
| 60 | tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>, |
| 61 | force_refresh: Arc<AtomicBool>, |
| 62 | } |
| 63 | |
| 64 | impl Session { |
| 65 | pub async fn connect(endpoint: &str) -> Result<Self> { |
| 66 | Self::connect_with(endpoint, SessionConfig::default()).await |
| 67 | } |
| 68 | |
| 69 | pub async fn connect_with(endpoint: &str, config: SessionConfig) -> Result<Self> { |
| 70 | Self::with_transport(Arc::new(CdpTransport::new(endpoint)), config).await |
| 71 | } |
| 72 | |
| 73 | pub async fn with_transport(transport: Arc<dyn Transport>, config: SessionConfig) -> Result<Self> { |
| 74 | transport.check().await?; |
| 75 | Ok(Session { |
| 76 | transport, |
| 77 | config, |
| 78 | tabs: Arc::new(App::ALL.into_iter().map(|app| (app, Mutex::new(None))).collect()), |
| 79 | force_refresh: Arc::new(AtomicBool::new(false)), |
| 80 | }) |
| 81 | } |
| 82 | |
| 83 | pub async fn request(&self, method: Method, url: &str, scope: &Scope, body: Option<Value>) -> Result<ApiResponse> { |
| 84 | let request = Request { |
| 85 | method, |
| 86 | body, |
| 87 | ..Request::get(url) |
| 88 | }; |
| 89 | self.send(request, scope).await |
| 90 | } |
| 91 | |
| 92 | pub async fn send(&self, request: Request, scope: &Scope) -> Result<ApiResponse> { |
| 93 | let url = request.url.clone(); |
| 94 | let response = self.batch(&[request], scope).await?.remove(0); |
| 95 | if response.status >= 400 || response.status == 0 { |
| 96 | return Err(Error::api(response.status, &url, response.body)); |
| 97 | } |
| 98 | Ok(response) |
| 99 | } |
| 100 | |
| 101 | pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> { |
| 102 | let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()]; |
| 103 | let mut pending: Vec<usize> = (0..requests.len()).collect(); |
| 104 | for attempt in 0..=self.config.max_throttle_retries { |
| 105 | let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect(); |
| 106 | let answers = self.run_with_fresh_token(&batch, scope).await?; |
| 107 | let unauthorized_first_try = attempt == 0 && answers.iter().any(|answer| answer.status == 401); |
| 108 | if unauthorized_first_try { |
| 109 | // A CAE-revoked token stays unexpired in the app cache, so only a refresh-token grant replaces it. |
| 110 | self.force_refresh.store(true, Ordering::SeqCst); |
| 111 | self.reload_all().await; |
| 112 | sleep(self.config.unauthorized_reload_wait).await; |
| 113 | self.drop_all().await; |
| 114 | } |
| 115 | let mut retry = Vec::new(); |
| 116 | for (&index, answer) in pending.iter().zip(answers) { |
| 117 | let throttled = answer.status == 429 || (attempt == 0 && answer.status == 401); |
| 118 | results[index] = Some(answer); |
| 119 | if throttled { |
| 120 | retry.push(index); |
| 121 | } |
| 122 | } |
| 123 | if !unauthorized_first_try { |
| 124 | self.force_refresh.store(false, Ordering::SeqCst); |
| 125 | } |
| 126 | if retry.is_empty() || attempt == self.config.max_throttle_retries { |
| 127 | break; |
| 128 | } |
| 129 | let wait = retry |
| 130 | .iter() |
| 131 | .filter_map(|&index| results[index].as_ref()) |
| 132 | .map(|answer| retry_wait(answer.retry_after.as_deref(), self.config.default_retry_wait)) |
| 133 | .max() |
| 134 | .unwrap_or_default(); |
| 135 | sleep(wait.min(self.config.max_retry_wait)).await; |
| 136 | pending = retry; |
| 137 | } |
| 138 | Ok(results.into_iter().flatten().collect()) |
| 139 | } |
| 140 | |
| 141 | pub async fn close(&self) { |
| 142 | self.drop_all().await; |
| 143 | } |
| 144 | |
| 145 | async fn run_with_fresh_token(&self, requests: &[&Request], scope: &Scope) -> Result<Vec<ApiResponse>> { |
| 146 | let mut search = TokenSearch::default(); |
| 147 | if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? { |
| 148 | return Ok(results); |
| 149 | } |
| 150 | if search.ungranted.len() == App::ALL.len() { |
| 151 | return Err(Error::LoginRequired(format!( |
| 152 | "neither the Teams nor the Outlook web app is granted {scope}" |
| 153 | ))); |
| 154 | } |
| 155 | self.reload_all().await; |
| 156 | let deadline = Instant::now() + self.config.token_wait; |
| 157 | while Instant::now() < deadline { |
| 158 | sleep(self.config.token_poll).await; |
| 159 | self.drop_all().await; |
| 160 | if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? { |
| 161 | return Ok(results); |
| 162 | } |
| 163 | } |
| 164 | let diagnosis = self.transport.diagnose().await?; |
| 165 | if diagnosis.login_pending { |
| 166 | return Err(Error::LoginRequired("sign in in the browser window".into())); |
| 167 | } |
| 168 | if !diagnosis.app_tab_open { |
| 169 | return Err(Error::NoAppTab); |
| 170 | } |
| 171 | let detail = search |
| 172 | .refresh_error |
| 173 | .map(|reason| format!(" (token refresh failed in {reason})")) |
| 174 | .unwrap_or_default(); |
| 175 | Err(Error::NoFreshToken { |
| 176 | scope: scope.to_string(), |
| 177 | detail, |
| 178 | }) |
| 179 | } |
| 180 | |
| 181 | async fn run_in_any_tab( |
| 182 | &self, |
| 183 | requests: &[&Request], |
| 184 | scope: &Scope, |
| 185 | search: &mut TokenSearch, |
| 186 | ) -> Result<Option<Vec<ApiResponse>>> { |
| 187 | let payload = self.payload(requests, scope); |
| 188 | let expression = format!("({FETCH_SCRIPT})({payload})"); |
| 189 | let has_write = requests.iter().any(|request| request.method != Method::Get); |
| 190 | for app in scope.tab_order() { |
| 191 | let outcome = match self.evaluate_in(app, &expression).await { |
| 192 | Ok(Some(value)) => value, |
| 193 | Ok(None) => continue, |
| 194 | Err(error) => { |
| 195 | self.drop_connection(app).await; |
| 196 | if has_write { |
| 197 | return Err(Error::WriteInterrupted(error.to_string())); |
| 198 | } |
| 199 | continue; |
| 200 | } |
| 201 | }; |
| 202 | let outcome: Outcome = |
| 203 | serde_json::from_value(outcome).map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?; |
| 204 | if let Some(results) = outcome.results { |
| 205 | return Ok(Some(results.into_iter().map(WireResult::into).collect())); |
| 206 | } |
| 207 | if let Some(reason) = outcome.refresh_error { |
| 208 | if reason.starts_with(NOT_GRANTED_PREFIX) { |
| 209 | search.ungranted.insert(app); |
| 210 | } |
| 211 | search.refresh_error.get_or_insert_with(|| format!("{app}: {reason}")); |
| 212 | } |
| 213 | } |
| 214 | Ok(None) |
| 215 | } |
| 216 | |
| 217 | fn payload(&self, requests: &[&Request], scope: &Scope) -> String { |
| 218 | let wire: Vec<WireRequest> = requests.iter().map(|&request| request.into()).collect(); |
| 219 | json!({ |
| 220 | "requests": wire, |
| 221 | "resource": scope.resource, |
| 222 | "scope": scope.name, |
| 223 | "marginMs": self.config.refresh_margin.as_millis() as u64, |
| 224 | "concurrency": DEFAULT_CONCURRENCY, |
| 225 | "maxBytes": MAX_DOWNLOAD_BYTES, |
| 226 | "forceRefresh": self.force_refresh.load(Ordering::SeqCst), |
| 227 | }) |
| 228 | .to_string() |
| 229 | } |
| 230 | |
| 231 | pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> { |
| 232 | let mut slot = self.tabs[&app].lock().await; |
| 233 | if slot.is_none() { |
| 234 | let Some((control, _)) = self.transport.open(app, false).await? else { |
| 235 | return Ok(None); |
| 236 | }; |
| 237 | *slot = Some(control); |
| 238 | } |
| 239 | let control = slot.as_ref().expect("connection set above"); |
| 240 | let outcome = control.evaluate_within(expression, self.config.evaluate_timeout).await; |
| 241 | if outcome.is_err() { |
| 242 | *slot = None; |
| 243 | } |
| 244 | outcome.map(Some) |
| 245 | } |
| 246 | |
| 247 | async fn drop_connection(&self, app: App) { |
| 248 | *self.tabs[&app].lock().await = None; |
| 249 | } |
| 250 | |
| 251 | async fn drop_all(&self) { |
| 252 | for app in App::ALL { |
| 253 | self.drop_connection(app).await; |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | async fn reload_all(&self) { |
| 258 | for app in App::ALL { |
| 259 | let _ = self.transport.wake(app).await; |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration { |
| 265 | header |
| 266 | .and_then(|value| value.trim().parse::<f64>().ok()) |
| 267 | .filter(|seconds| seconds.is_finite() && *seconds >= 0.0) |
| 268 | .map(Duration::from_secs_f64) |
| 269 | .unwrap_or(default) |
| 270 | } |
| 271 | |
| 272 | #[cfg(test)] |
| 273 | mod tests { |
| 274 | use super::*; |
| 275 | |
| 276 | #[test] |
| 277 | fn retry_after_seconds_parse() { |
| 278 | let default = Duration::from_secs(2); |
| 279 | assert_eq!(retry_wait(Some("7"), default), Duration::from_secs(7)); |
| 280 | assert_eq!(retry_wait(Some(" 1.5 "), default), Duration::from_millis(1500)); |
| 281 | } |
| 282 | |
| 283 | #[test] |
| 284 | fn retry_after_falls_back() { |
| 285 | let default = Duration::from_secs(2); |
| 286 | assert_eq!(retry_wait(None, default), default); |
| 287 | assert_eq!(retry_wait(Some("Wed, 21 Oct 2026 07:28:00 GMT"), default), default); |
| 288 | assert_eq!(retry_wait(Some("-3"), default), default); |
| 289 | } |
| 290 | } |