BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / realtime / runner.rs

runner.rs

8a314dbb History
runner.rs 14.9 KiB Download Raw
1use std::sync::Arc;
2use std::time::Duration;
3
4use serde_json::{Value, json};
5use session::{App, Session, TabControl, TabEvents};
6use tokio::sync::{Notify, mpsc, oneshot, watch};
7use tokio::time::{MissedTickBehavior, interval, sleep};
8
9use super::RealtimeConfig;
10use super::callback::{CallbackReply, TrouterCallback, decode_callback, reply_expression};
11use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload};
12use super::host::ic3_scope;
13
14pub(super) const DEFAULT_GLOBAL_NAME: &str = "__chatsvcTrouter";
15pub(super) const DEFAULT_BINDING_NAME: &str = "__chatsvcRealtime";
16pub(super) const DEFAULT_EPID_KEY: &str = "__chatsvcEpid";
17const WORKER_TEMPLATE: &str = include_str!("../../assets/trouter.js");
18const FORWARD_CALLBACKS_OFF: &str = "const FORWARD_CALLBACKS = false;";
19const REGISTRATION_OFF: &str = "const RINGABLE = false;";
20const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
21
22/// The page worker with this instance's names baked in.
23#[derive(Clone)]
24pub(super) struct PageScript {
25 pub global_name: String,
26 pub binding_name: String,
27 pub worker_source: String,
28}
29
30impl 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(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
37 .replace(
38 &quoted(DEFAULT_EPID_KEY),
39 &quoted(&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
85pub(super) struct CallbackPipes {
86 pub output: mpsc::UnboundedSender<TrouterCallback>,
87 pub replies: mpsc::UnboundedReceiver<CallbackReply>,
88}
89
90pub(super) struct Attached {
91 control: TabControl,
92 events: TabEvents,
93 script_identifier: String,
94 stop_expression: String,
95}
96
97pub(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
113impl 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
128enum DriveEnd {
129 Stopped(Option<oneshot::Sender<()>>),
130 TabLost,
131}
132
133pub(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
146impl 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 loop {
197 let current = match attached.take() {
198 Some(current) => current,
199 None => match attach(&self.session, &self.script).await {
200 Ok(current) => {
201 backoff = Duration::from_secs(1);
202 current
203 }
204 Err(error) => {
205 self.report_error(format!("reattach_failed: {error}"));
206 tokio::select! {
207 _ = sleep(backoff) => {}
208 _ = &mut stop => return,
209 _ = self.output.closed() => return,
210 }
211 backoff = (backoff * 2).min(self.config.max_reattach_backoff);
212 continue;
213 }
214 },
215 };
216 match self.drive(current, &mut stop).await {
217 DriveEnd::Stopped(done) => {
218 if let Some(done) = done {
219 let _ = done.send(());
220 }
221 return;
222 }
223 DriveEnd::TabLost => {
224 self.send(RealtimeEvent::Status(StatusEvent {
225 kind: StatusKind::Disconnected,
226 detail: "tab_connection_lost".into(),
227 }));
228 sleep(Duration::from_secs(1)).await;
229 }
230 }
231 }
232 }
233
234 async fn drive(
235 &mut self,
236 mut attached: Attached,
237 stop: &mut oneshot::Receiver<oneshot::Sender<()>>,
238 ) -> DriveEnd {
239 let mut tick = interval(self.config.ensure_interval);
240 tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
241 tick.tick().await;
242 self.ensure_and_report().await;
243 loop {
244 tokio::select! {
245 event = attached.events.recv() => {
246 let Some(event) = event else { return DriveEnd::TabLost };
247 if let Some(payload) = event.binding_payload(&self.script.binding_name) {
248 self.forward_payload(payload);
249 } else if is_main_frame_navigation(&event.method, &event.params) {
250 sleep(self.config.navigation_settle).await;
251 self.ensure_and_report().await;
252 }
253 }
254 _ = tick.tick() => self.ensure_and_report().await,
255 _ = self.resend.notified() => {
256 let expression = self.script.resend_activity_expression();
257 let _ = attached.control.evaluate(&expression).await;
258 }
259 changed = self.activity.changed() => {
260 if changed.is_ok() {
261 let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
262 let _ = attached.control.evaluate(&expression).await;
263 }
264 }
265 Some(reply) = self.callbacks.replies.recv() => {
266 let expression = reply_expression(&self.script.global_name, &reply);
267 let _ = attached.control.evaluate(&expression).await;
268 }
269 done = &mut *stop => {
270 attached.shutdown().await;
271 return DriveEnd::Stopped(done.ok());
272 }
273 _ = self.output.closed() => {
274 attached.shutdown().await;
275 return DriveEnd::Stopped(None);
276 }
277 }
278 }
279 }
280
281 fn forward_payload(&mut self, payload: &str) {
282 if let Some(callback) = decode_callback(payload) {
283 let _ = self.callbacks.output.send(callback);
284 return;
285 }
286 let Ok(event) = decode_payload(payload) else {
287 return;
288 };
289 if let RealtimeEvent::Status(status) = &event
290 && status.kind == StatusKind::Error
291 && is_auth_failure(&status.detail)
292 {
293 self.force_refresh = true;
294 }
295 self.send(event);
296 }
297
298 async fn ensure_and_report(&mut self) {
299 match self.ensure().await {
300 Ok(_) => self.last_error = None,
301 Err(error) => self.report_error(format!("ensure_failed: {error}")),
302 }
303 }
304
305 fn report_error(&mut self, detail: String) {
306 if self.last_error.as_deref() == Some(detail.as_str()) {
307 return;
308 }
309 self.last_error = Some(detail.clone());
310 self.send(RealtimeEvent::Status(StatusEvent {
311 kind: StatusKind::Error,
312 detail,
313 }));
314 }
315
316 fn send(&self, event: RealtimeEvent) {
317 let _ = self.output.send(event);
318 }
319}
320
321fn activity_label(active: bool) -> &'static str {
322 if active { "active" } else { "inactive" }
323}
324
325fn is_main_frame_navigation(method: &str, params: &Value) -> bool {
326 method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()
327}
328
329fn is_auth_failure(detail: &str) -> bool {
330 detail == "registrar_http_401" || detail == "registrar_http_403"
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 #[test]
338 fn only_top_level_navigations_trigger_ensure() {
339 assert!(is_main_frame_navigation(
340 "Page.frameNavigated",
341 &json!({"frame": {"id": "a"}})
342 ));
343 assert!(!is_main_frame_navigation(
344 "Page.frameNavigated",
345 &json!({"frame": {"id": "b", "parentId": "a"}})
346 ));
347 assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));
348 }
349
350 #[test]
351 fn activity_is_labelled_and_set_through_the_page_global() {
352 assert_eq!(activity_label(true), "active");
353 assert_eq!(activity_label(false), "inactive");
354 let script = PageScript::new(&RealtimeConfig::default());
355 assert_eq!(
356 script.set_activity_expression(false),
357 "window.__chatsvcTrouter ? window.__chatsvcTrouter.setActivity('inactive') : null"
358 );
359 }
360
361 #[test]
362 fn resend_goes_through_the_page_global() {
363 let script = PageScript::new(&RealtimeConfig::default());
364 assert_eq!(
365 script.resend_activity_expression(),
366 "window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"
367 );
368 }
369
370 #[test]
371 fn worker_reports_activity_on_change_only() {
372 let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
373 assert!(!worker.contains("activity();"));
374 assert_eq!(worker.matches("'user.activity'").count(), 1);
375 }
376
377 #[test]
378 fn rejected_bearer_forces_token_refresh() {
379 assert!(is_auth_failure("registrar_http_401"));
380 assert!(!is_auth_failure("registrar_http_500"));
381 assert!(!is_auth_failure("registrar_failed"));
382 }
383
384 #[test]
385 fn ensure_body_embeds_the_worker_once_before_the_call() {
386 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
387 assert!(ensure_body.starts_with("(() => {"));
388 assert!(ensure_body.trim_end().ends_with(
389 "window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"
390 ));
391 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
392 }
393
394 #[test]
395 fn second_instance_gets_its_own_page_names_and_callbacks() {
396 let config = RealtimeConfig {
397 instance: super::super::InstanceNames {
398 global: "__callingTrouter".into(),
399 binding: "__callingRealtime".into(),
400 endpoint_storage_key: "__callingEpid".into(),
401 },
402 forward_callbacks: true,
403 ..RealtimeConfig::default()
404 };
405 let script = PageScript::new(&config);
406 assert!(!script.worker_source.contains("__chatsvc"));
407 assert!(
408 script
409 .worker_source
410 .contains("const GLOBAL_NAME = '__callingTrouter';")
411 );
412 assert!(
413 script
414 .worker_source
415 .contains("const FORWARD_CALLBACKS = true;")
416 );
417 assert_eq!(
418 script.stop_expression(),
419 "window.__callingTrouter ? window.__callingTrouter.stop() : null"
420 );
421 let default_script = PageScript::new(&RealtimeConfig::default());
422 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
423 }
424
425 #[test]
426 fn only_the_ringable_instance_registers_for_calls() {
427 let ringable = PageScript::new(&RealtimeConfig {
428 ringable: true,
429 ..RealtimeConfig::default()
430 });
431 assert!(ringable.worker_source.contains("const RINGABLE = true;"));
432 let quiet = PageScript::new(&RealtimeConfig::default());
433 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
434 for script in [ringable, quiet] {
435 assert!(
436 script
437 .worker_source
438 .contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")
439 );
440 assert!(
441 script
442 .worker_source
443 .contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")
444 );
445 assert!(
446 script
447 .worker_source
448 .contains("RINGABLE ? {productContext: ''} : {}")
449 );
450 }
451 }
452}