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