BlueGit

ict rusty-teams

Files

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

runner.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
runner.rs 8.0 KiB Download Raw
1use std::time::Duration;
2
3use serde_json::{Value, json};
4use session::{App, Session, TabControl, TabEvents};
5use tokio::sync::{mpsc, oneshot};
6use tokio::time::{MissedTickBehavior, interval, sleep};
7
8use super::RealtimeConfig;
9use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload};
10use super::host::ic3_scope;
11
12pub(super) const BINDING_NAME: &str = "__chatsvcRealtime";
13const WORKER_SOURCE: &str = include_str!("../../assets/trouter.js");
14const ENSURE_BODY: &str = concat!(
15 include_str!("../../assets/trouter.js"),
16 "\nreturn window.__chatsvcTrouter.ensure({token, host: args.host, forwardPresence: args.forwardPresence});"
17);
18const STOP_EXPRESSION: &str = "window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null";
19const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
20
21pub(super) struct Attached {
22 control: TabControl,
23 events: TabEvents,
24 script_identifier: String,
25}
26
27pub(super) async fn attach(session: &Session) -> crate::error::Result<Attached> {
28 let (control, events) = session.subscribe(App::Teams).await?;
29 control.enable_events().await?;
30 control.add_binding(BINDING_NAME).await?;
31 let script_identifier = control.inject_script(WORKER_SOURCE).await?;
32 Ok(Attached {
33 control,
34 events,
35 script_identifier,
36 })
37}
38
39impl Attached {
40 pub(super) async fn shutdown(self) {
41 let _ =
42 tokio::time::timeout(STOP_STEP_TIMEOUT, self.control.evaluate(STOP_EXPRESSION)).await;
43 let _ = tokio::time::timeout(
44 STOP_STEP_TIMEOUT,
45 self.control.remove_injected_script(&self.script_identifier),
46 )
47 .await;
48 }
49}
50
51enum DriveEnd {
52 Stopped(Option<oneshot::Sender<()>>),
53 TabLost,
54}
55
56pub(super) struct Runner {
57 session: Session,
58 config: RealtimeConfig,
59 host: String,
60 output: mpsc::UnboundedSender<RealtimeEvent>,
61 force_refresh: bool,
62 last_error: Option<String>,
63}
64
65impl Runner {
66 pub(super) fn new(
67 session: Session,
68 config: RealtimeConfig,
69 host: String,
70 output: mpsc::UnboundedSender<RealtimeEvent>,
71 ) -> Self {
72 Runner {
73 session,
74 config,
75 host,
76 output,
77 force_refresh: false,
78 last_error: None,
79 }
80 }
81
82 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
83 let args = json!({"host": self.host, "forwardPresence": self.config.forward_presence});
84 let outcome = self
85 .session
86 .run_with_token(
87 App::Teams,
88 &ic3_scope(),
89 ENSURE_BODY,
90 &args,
91 self.force_refresh,
92 )
93 .await;
94 if outcome.is_ok() {
95 self.force_refresh = false;
96 }
97 outcome
98 }
99
100 pub(super) async fn run(
101 mut self,
102 first: Attached,
103 mut stop: oneshot::Receiver<oneshot::Sender<()>>,
104 ) {
105 let mut attached = Some(first);
106 let mut backoff = Duration::from_secs(1);
107 loop {
108 let current = match attached.take() {
109 Some(current) => current,
110 None => match attach(&self.session).await {
111 Ok(current) => {
112 backoff = Duration::from_secs(1);
113 current
114 }
115 Err(error) => {
116 self.report_error(format!("reattach_failed: {error}"));
117 tokio::select! {
118 _ = sleep(backoff) => {}
119 _ = &mut stop => return,
120 _ = self.output.closed() => return,
121 }
122 backoff = (backoff * 2).min(self.config.max_reattach_backoff);
123 continue;
124 }
125 },
126 };
127 match self.drive(current, &mut stop).await {
128 DriveEnd::Stopped(done) => {
129 if let Some(done) = done {
130 let _ = done.send(());
131 }
132 return;
133 }
134 DriveEnd::TabLost => {
135 self.send(RealtimeEvent::Status(StatusEvent {
136 kind: StatusKind::Disconnected,
137 detail: "tab_connection_lost".into(),
138 }));
139 sleep(Duration::from_secs(1)).await;
140 }
141 }
142 }
143 }
144
145 async fn drive(
146 &mut self,
147 mut attached: Attached,
148 stop: &mut oneshot::Receiver<oneshot::Sender<()>>,
149 ) -> DriveEnd {
150 let mut tick = interval(self.config.ensure_interval);
151 tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
152 tick.tick().await;
153 self.ensure_and_report().await;
154 loop {
155 tokio::select! {
156 event = attached.events.recv() => {
157 let Some(event) = event else { return DriveEnd::TabLost };
158 if let Some(payload) = event.binding_payload(BINDING_NAME) {
159 self.forward_payload(payload);
160 } else if is_main_frame_navigation(&event.method, &event.params) {
161 sleep(self.config.navigation_settle).await;
162 self.ensure_and_report().await;
163 }
164 }
165 _ = tick.tick() => self.ensure_and_report().await,
166 done = &mut *stop => {
167 attached.shutdown().await;
168 return DriveEnd::Stopped(done.ok());
169 }
170 _ = self.output.closed() => {
171 attached.shutdown().await;
172 return DriveEnd::Stopped(None);
173 }
174 }
175 }
176 }
177
178 fn forward_payload(&mut self, payload: &str) {
179 let Ok(event) = decode_payload(payload) else {
180 return;
181 };
182 if let RealtimeEvent::Status(status) = &event
183 && status.kind == StatusKind::Error
184 && is_auth_failure(&status.detail)
185 {
186 self.force_refresh = true;
187 }
188 self.send(event);
189 }
190
191 async fn ensure_and_report(&mut self) {
192 match self.ensure().await {
193 Ok(_) => self.last_error = None,
194 Err(error) => self.report_error(format!("ensure_failed: {error}")),
195 }
196 }
197
198 fn report_error(&mut self, detail: String) {
199 if self.last_error.as_deref() == Some(detail.as_str()) {
200 return;
201 }
202 self.last_error = Some(detail.clone());
203 self.send(RealtimeEvent::Status(StatusEvent {
204 kind: StatusKind::Error,
205 detail,
206 }));
207 }
208
209 fn send(&self, event: RealtimeEvent) {
210 let _ = self.output.send(event);
211 }
212}
213
214fn is_main_frame_navigation(method: &str, params: &Value) -> bool {
215 method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()
216}
217
218fn is_auth_failure(detail: &str) -> bool {
219 detail == "registrar_http_401" || detail == "registrar_http_403"
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 #[test]
227 fn only_top_level_navigations_trigger_ensure() {
228 assert!(is_main_frame_navigation(
229 "Page.frameNavigated",
230 &json!({"frame": {"id": "a"}})
231 ));
232 assert!(!is_main_frame_navigation(
233 "Page.frameNavigated",
234 &json!({"frame": {"id": "b", "parentId": "a"}})
235 ));
236 assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));
237 }
238
239 #[test]
240 fn rejected_bearer_forces_token_refresh() {
241 assert!(is_auth_failure("registrar_http_401"));
242 assert!(!is_auth_failure("registrar_http_500"));
243 assert!(!is_auth_failure("registrar_failed"));
244 }
245
246 #[test]
247 fn ensure_body_embeds_the_worker_once_before_the_call() {
248 assert!(ENSURE_BODY.starts_with("(() => {"));
249 assert!(
250 ENSURE_BODY
251 .trim_end()
252 .ends_with("forwardPresence: args.forwardPresence});")
253 );
254 assert_eq!(ENSURE_BODY.matches("const VERSION").count(), 1);
255 }
256}