| 1 | use std::sync::Arc; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use serde_json::{Value, json}; |
| 5 | use session::{App, Session, TabControl, TabEvents}; |
| 6 | use tokio::sync::{Notify, mpsc, oneshot, watch}; |
| 7 | use tokio::time::{MissedTickBehavior, interval, sleep}; |
| 8 | |
| 9 | use super::RealtimeConfig; |
| 10 | use super::callback::{CallbackReply, TrouterCallback, decode_callback, reply_expression}; |
| 11 | use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload}; |
| 12 | use super::host::ic3_scope; |
| 13 | |
| 14 | pub(super) const DEFAULT_GLOBAL_NAME: &str = "__chatsvcTrouter"; |
| 15 | pub(super) const DEFAULT_BINDING_NAME: &str = "__chatsvcRealtime"; |
| 16 | pub(super) const DEFAULT_EPID_KEY: &str = "__chatsvcEpid"; |
| 17 | const WORKER_TEMPLATE: &str = include_str!("../../assets/trouter.js"); |
| 18 | const FORWARD_CALLBACKS_OFF: &str = "const FORWARD_CALLBACKS = false;"; |
| 19 | const REGISTRATION_OFF: &str = "const RINGABLE = false;"; |
| 20 | const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10); |
| 21 | |
| 22 | /// The page worker with this instance's names baked in. |
| 23 | #[derive(Clone)] |
| 24 | pub(super) struct PageScript { |
| 25 | pub global_name: String, |
| 26 | pub binding_name: String, |
| 27 | pub worker_source: String, |
| 28 | } |
| 29 | |
| 30 | impl PageScript { |
| 31 | pub(super) fn new(config: &RealtimeConfig) -> Self { |
| 32 | let names = &config.instance; |
| 33 | let quoted = |name: &str| format!("'{name}'"); |
| 34 | let mut worker_source = WORKER_TEMPLATE |
| 35 | .replace("ed(DEFAULT_GLOBAL_NAME), "ed(&names.global)) |
| 36 | .replace("ed(DEFAULT_BINDING_NAME), "ed(&names.binding)) |
| 37 | .replace("ed(DEFAULT_EPID_KEY), "ed(&names.endpoint_storage_key)); |
| 38 | if config.forward_callbacks { |
| 39 | worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;"); |
| 40 | } |
| 41 | if config.ringable { |
| 42 | worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;"); |
| 43 | } |
| 44 | PageScript { |
| 45 | global_name: names.global.clone(), |
| 46 | binding_name: names.binding.clone(), |
| 47 | worker_source, |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | fn ensure_body(&self) -> String { |
| 52 | format!( |
| 53 | "{}\nreturn window.{}.ensure({{token, host: args.host, activity: args.activity}});", |
| 54 | self.worker_source, self.global_name |
| 55 | ) |
| 56 | } |
| 57 | |
| 58 | fn set_activity_expression(&self, active: bool) -> String { |
| 59 | format!( |
| 60 | "window.{name} ? window.{name}.setActivity('{state}') : null", |
| 61 | name = self.global_name, |
| 62 | state = activity_label(active) |
| 63 | ) |
| 64 | } |
| 65 | |
| 66 | fn resend_activity_expression(&self) -> String { |
| 67 | format!( |
| 68 | "window.{name} ? window.{name}.resendActivity() : null", |
| 69 | name = self.global_name |
| 70 | ) |
| 71 | } |
| 72 | |
| 73 | fn stop_expression(&self) -> String { |
| 74 | format!( |
| 75 | "window.{name} ? window.{name}.stop() : null", |
| 76 | name = self.global_name |
| 77 | ) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | pub(super) struct CallbackPipes { |
| 82 | pub output: mpsc::UnboundedSender<TrouterCallback>, |
| 83 | pub replies: mpsc::UnboundedReceiver<CallbackReply>, |
| 84 | } |
| 85 | |
| 86 | pub(super) struct Attached { |
| 87 | control: TabControl, |
| 88 | events: TabEvents, |
| 89 | script_identifier: String, |
| 90 | stop_expression: String, |
| 91 | } |
| 92 | |
| 93 | pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> { |
| 94 | let (control, events) = session.subscribe(App::Teams).await?; |
| 95 | control.enable_events().await?; |
| 96 | control.add_binding(&script.binding_name).await?; |
| 97 | let script_identifier = control.inject_script(&script.worker_source).await?; |
| 98 | Ok(Attached { |
| 99 | control, |
| 100 | events, |
| 101 | script_identifier, |
| 102 | stop_expression: script.stop_expression(), |
| 103 | }) |
| 104 | } |
| 105 | |
| 106 | impl Attached { |
| 107 | pub(super) async fn shutdown(self) { |
| 108 | let _ = tokio::time::timeout( |
| 109 | STOP_STEP_TIMEOUT, |
| 110 | self.control.evaluate(&self.stop_expression), |
| 111 | ) |
| 112 | .await; |
| 113 | let _ = tokio::time::timeout( |
| 114 | STOP_STEP_TIMEOUT, |
| 115 | self.control.remove_injected_script(&self.script_identifier), |
| 116 | ) |
| 117 | .await; |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | enum DriveEnd { |
| 122 | Stopped(Option<oneshot::Sender<()>>), |
| 123 | TabLost, |
| 124 | } |
| 125 | |
| 126 | pub(super) struct Runner { |
| 127 | session: Session, |
| 128 | config: RealtimeConfig, |
| 129 | script: PageScript, |
| 130 | callbacks: CallbackPipes, |
| 131 | host: String, |
| 132 | output: mpsc::UnboundedSender<RealtimeEvent>, |
| 133 | activity: watch::Receiver<bool>, |
| 134 | resend: Arc<Notify>, |
| 135 | force_refresh: bool, |
| 136 | last_error: Option<String>, |
| 137 | } |
| 138 | |
| 139 | impl Runner { |
| 140 | pub(super) fn new( |
| 141 | session: Session, |
| 142 | config: RealtimeConfig, |
| 143 | script: PageScript, |
| 144 | host: String, |
| 145 | output: mpsc::UnboundedSender<RealtimeEvent>, |
| 146 | callbacks: CallbackPipes, |
| 147 | activity: watch::Receiver<bool>, |
| 148 | resend: Arc<Notify>, |
| 149 | ) -> Self { |
| 150 | Runner { |
| 151 | session, |
| 152 | config, |
| 153 | script, |
| 154 | callbacks, |
| 155 | host, |
| 156 | output, |
| 157 | activity, |
| 158 | resend, |
| 159 | force_refresh: false, |
| 160 | last_error: None, |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | pub(super) async fn ensure(&mut self) -> session::Result<Value> { |
| 165 | let args = json!({"host": self.host, "activity": activity_label(*self.activity.borrow())}); |
| 166 | let outcome = self |
| 167 | .session |
| 168 | .run_with_token( |
| 169 | App::Teams, |
| 170 | &ic3_scope(), |
| 171 | &self.script.ensure_body(), |
| 172 | &args, |
| 173 | self.force_refresh, |
| 174 | ) |
| 175 | .await; |
| 176 | if outcome.is_ok() { |
| 177 | self.force_refresh = false; |
| 178 | } |
| 179 | outcome |
| 180 | } |
| 181 | |
| 182 | pub(super) async fn run( |
| 183 | mut self, |
| 184 | first: Attached, |
| 185 | mut stop: oneshot::Receiver<oneshot::Sender<()>>, |
| 186 | ) { |
| 187 | let mut attached = Some(first); |
| 188 | let mut backoff = Duration::from_secs(1); |
| 189 | loop { |
| 190 | let current = match attached.take() { |
| 191 | Some(current) => current, |
| 192 | None => match attach(&self.session, &self.script).await { |
| 193 | Ok(current) => { |
| 194 | backoff = Duration::from_secs(1); |
| 195 | current |
| 196 | } |
| 197 | Err(error) => { |
| 198 | self.report_error(format!("reattach_failed: {error}")); |
| 199 | tokio::select! { |
| 200 | _ = sleep(backoff) => {} |
| 201 | _ = &mut stop => return, |
| 202 | _ = self.output.closed() => return, |
| 203 | } |
| 204 | backoff = (backoff * 2).min(self.config.max_reattach_backoff); |
| 205 | continue; |
| 206 | } |
| 207 | }, |
| 208 | }; |
| 209 | match self.drive(current, &mut stop).await { |
| 210 | DriveEnd::Stopped(done) => { |
| 211 | if let Some(done) = done { |
| 212 | let _ = done.send(()); |
| 213 | } |
| 214 | return; |
| 215 | } |
| 216 | DriveEnd::TabLost => { |
| 217 | self.send(RealtimeEvent::Status(StatusEvent { |
| 218 | kind: StatusKind::Disconnected, |
| 219 | detail: "tab_connection_lost".into(), |
| 220 | })); |
| 221 | sleep(Duration::from_secs(1)).await; |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | async fn drive( |
| 228 | &mut self, |
| 229 | mut attached: Attached, |
| 230 | stop: &mut oneshot::Receiver<oneshot::Sender<()>>, |
| 231 | ) -> DriveEnd { |
| 232 | let mut tick = interval(self.config.ensure_interval); |
| 233 | tick.set_missed_tick_behavior(MissedTickBehavior::Delay); |
| 234 | tick.tick().await; |
| 235 | self.ensure_and_report().await; |
| 236 | loop { |
| 237 | tokio::select! { |
| 238 | event = attached.events.recv() => { |
| 239 | let Some(event) = event else { return DriveEnd::TabLost }; |
| 240 | if let Some(payload) = event.binding_payload(&self.script.binding_name) { |
| 241 | self.forward_payload(payload); |
| 242 | } else if is_main_frame_navigation(&event.method, &event.params) { |
| 243 | sleep(self.config.navigation_settle).await; |
| 244 | self.ensure_and_report().await; |
| 245 | } |
| 246 | } |
| 247 | _ = tick.tick() => self.ensure_and_report().await, |
| 248 | _ = self.resend.notified() => { |
| 249 | let expression = self.script.resend_activity_expression(); |
| 250 | let _ = attached.control.evaluate(&expression).await; |
| 251 | } |
| 252 | changed = self.activity.changed() => { |
| 253 | if changed.is_ok() { |
| 254 | let expression = self.script.set_activity_expression(*self.activity.borrow_and_update()); |
| 255 | let _ = attached.control.evaluate(&expression).await; |
| 256 | } |
| 257 | } |
| 258 | Some(reply) = self.callbacks.replies.recv() => { |
| 259 | let expression = reply_expression(&self.script.global_name, &reply); |
| 260 | let _ = attached.control.evaluate(&expression).await; |
| 261 | } |
| 262 | done = &mut *stop => { |
| 263 | attached.shutdown().await; |
| 264 | return DriveEnd::Stopped(done.ok()); |
| 265 | } |
| 266 | _ = self.output.closed() => { |
| 267 | attached.shutdown().await; |
| 268 | return DriveEnd::Stopped(None); |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | fn forward_payload(&mut self, payload: &str) { |
| 275 | if let Some(callback) = decode_callback(payload) { |
| 276 | let _ = self.callbacks.output.send(callback); |
| 277 | return; |
| 278 | } |
| 279 | let Ok(event) = decode_payload(payload) else { |
| 280 | return; |
| 281 | }; |
| 282 | if let RealtimeEvent::Status(status) = &event |
| 283 | && status.kind == StatusKind::Error |
| 284 | && is_auth_failure(&status.detail) |
| 285 | { |
| 286 | self.force_refresh = true; |
| 287 | } |
| 288 | self.send(event); |
| 289 | } |
| 290 | |
| 291 | async fn ensure_and_report(&mut self) { |
| 292 | match self.ensure().await { |
| 293 | Ok(_) => self.last_error = None, |
| 294 | Err(error) => self.report_error(format!("ensure_failed: {error}")), |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | fn report_error(&mut self, detail: String) { |
| 299 | if self.last_error.as_deref() == Some(detail.as_str()) { |
| 300 | return; |
| 301 | } |
| 302 | self.last_error = Some(detail.clone()); |
| 303 | self.send(RealtimeEvent::Status(StatusEvent { |
| 304 | kind: StatusKind::Error, |
| 305 | detail, |
| 306 | })); |
| 307 | } |
| 308 | |
| 309 | fn send(&self, event: RealtimeEvent) { |
| 310 | let _ = self.output.send(event); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | fn activity_label(active: bool) -> &'static str { |
| 315 | if active { "active" } else { "inactive" } |
| 316 | } |
| 317 | |
| 318 | fn is_main_frame_navigation(method: &str, params: &Value) -> bool { |
| 319 | method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none() |
| 320 | } |
| 321 | |
| 322 | fn is_auth_failure(detail: &str) -> bool { |
| 323 | detail == "registrar_http_401" || detail == "registrar_http_403" |
| 324 | } |
| 325 | |
| 326 | #[cfg(test)] |
| 327 | mod tests { |
| 328 | use super::*; |
| 329 | |
| 330 | #[test] |
| 331 | fn only_top_level_navigations_trigger_ensure() { |
| 332 | assert!(is_main_frame_navigation( |
| 333 | "Page.frameNavigated", |
| 334 | &json!({"frame": {"id": "a"}}) |
| 335 | )); |
| 336 | assert!(!is_main_frame_navigation( |
| 337 | "Page.frameNavigated", |
| 338 | &json!({"frame": {"id": "b", "parentId": "a"}}) |
| 339 | )); |
| 340 | assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({}))); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn activity_is_labelled_and_set_through_the_page_global() { |
| 345 | assert_eq!(activity_label(true), "active"); |
| 346 | assert_eq!(activity_label(false), "inactive"); |
| 347 | let script = PageScript::new(&RealtimeConfig::default()); |
| 348 | assert_eq!( |
| 349 | script.set_activity_expression(false), |
| 350 | "window.__chatsvcTrouter ? window.__chatsvcTrouter.setActivity('inactive') : null" |
| 351 | ); |
| 352 | } |
| 353 | |
| 354 | #[test] |
| 355 | fn resend_goes_through_the_page_global() { |
| 356 | let script = PageScript::new(&RealtimeConfig::default()); |
| 357 | assert_eq!( |
| 358 | script.resend_activity_expression(), |
| 359 | "window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null" |
| 360 | ); |
| 361 | } |
| 362 | |
| 363 | #[test] |
| 364 | fn worker_reports_activity_on_change_only() { |
| 365 | let worker = PageScript::new(&RealtimeConfig::default()).worker_source; |
| 366 | assert!(!worker.contains("activity();")); |
| 367 | assert_eq!(worker.matches("'user.activity'").count(), 1); |
| 368 | } |
| 369 | |
| 370 | #[test] |
| 371 | fn rejected_bearer_forces_token_refresh() { |
| 372 | assert!(is_auth_failure("registrar_http_401")); |
| 373 | assert!(!is_auth_failure("registrar_http_500")); |
| 374 | assert!(!is_auth_failure("registrar_failed")); |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn ensure_body_embeds_the_worker_once_before_the_call() { |
| 379 | let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body(); |
| 380 | assert!(ensure_body.starts_with("(() => {")); |
| 381 | assert!( |
| 382 | ensure_body |
| 383 | .trim_end() |
| 384 | .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});") |
| 385 | ); |
| 386 | assert_eq!(ensure_body.matches("const VERSION").count(), 1); |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn second_instance_gets_its_own_page_names_and_callbacks() { |
| 391 | let config = RealtimeConfig { |
| 392 | instance: super::super::InstanceNames { |
| 393 | global: "__callingTrouter".into(), |
| 394 | binding: "__callingRealtime".into(), |
| 395 | endpoint_storage_key: "__callingEpid".into(), |
| 396 | }, |
| 397 | forward_callbacks: true, |
| 398 | ..RealtimeConfig::default() |
| 399 | }; |
| 400 | let script = PageScript::new(&config); |
| 401 | assert!(!script.worker_source.contains("__chatsvc")); |
| 402 | assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';")); |
| 403 | assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;")); |
| 404 | assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null"); |
| 405 | let default_script = PageScript::new(&RealtimeConfig::default()); |
| 406 | assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF)); |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn only_the_ringable_instance_registers_for_calls() { |
| 411 | let ringable = PageScript::new(&RealtimeConfig { |
| 412 | ringable: true, |
| 413 | ..RealtimeConfig::default() |
| 414 | }); |
| 415 | assert!(ringable.worker_source.contains("const RINGABLE = true;")); |
| 416 | let quiet = PageScript::new(&RealtimeConfig::default()); |
| 417 | assert!(quiet.worker_source.contains(REGISTRATION_OFF)); |
| 418 | for script in [ringable, quiet] { |
| 419 | assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")); |
| 420 | assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")); |
| 421 | assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}")); |
| 422 | } |
| 423 | } |
| 424 | } |