BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / backend.rs

backend.rs

backend.rs 20.5 KiB Download Raw
1use std::sync::Arc;
2use std::time::Duration;
3
4use calling::EngineEvent;
5use chatsvc::{
6 Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig,
7 RealtimeEvent, StatusKind, TypingEvent,
8};
9use chrono::{DateTime, Local, Offset, Utc};
10use graph::Graph;
11use session::{Session, SessionConfig, Transport};
12use store::Store;
13use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
14use tokio::sync::{Notify, mpsc, watch};
15
16use crate::call::{CallLauncher, fetch_window};
17use crate::presence_link::{self, LinkSignal};
18
19pub type Engine = SyncEngine<Graph>;
20
21const FORWARD_HEAL_PAUSE: Duration = Duration::from_secs(2);
22const CONNECT_RETRY: Duration = Duration::from_secs(8);
23const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
24const REFRESH_SETTLE: Duration = Duration::from_secs(2);
25const PINS_INTERVAL: Duration = Duration::from_secs(90);
26const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
27const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
28const REALTIME_RETRY: Duration = Duration::from_secs(15);
29const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [
30 Duration::from_secs(1),
31 Duration::from_secs(3),
32 Duration::from_secs(8),
33];
34const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
35const MAX_ERROR_CHARS: usize = 120;
36const IMAGE_DIRECTORY: &str = "images";
37const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024;
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum ConnectionState {
41 Connecting,
42 Online,
43 NoBrowser,
44 NoAppTab,
45 LoginRequired,
46 Failed(String),
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum LiveState {
51 Off,
52 Connecting,
53 Live,
54 Reconnecting,
55 MessageLoss,
56 Failed,
57}
58
59pub enum BackendEvent {
60 Connection(ConnectionState),
61 Engine(Arc<Engine>),
62 Calls(Arc<CallLauncher>),
63 Calendar(Vec<CalendarEvent>),
64 CalendarNudge(mpsc::UnboundedSender<()>),
65 Ring(EngineEvent),
66 ThreadChanged(String),
67 Core(CoreEvent),
68 Live(LiveState),
69 Typing(TypingEvent),
70 Favorites(Vec<String>),
71 Synced(DateTime<Utc>),
72 LiveRetry(Arc<Notify>),
73}
74
75type EventSender = mpsc::UnboundedSender<BackendEvent>;
76
77pub fn classify_session_error(error: &session::Error) -> ConnectionState {
78 match error {
79 session::Error::NoBrowser { .. } => ConnectionState::NoBrowser,
80 session::Error::NoAppTab => ConnectionState::NoAppTab,
81 session::Error::LoginRequired(_) | session::Error::NoFreshToken { .. } => {
82 ConnectionState::LoginRequired
83 }
84 other => ConnectionState::Failed(shorten(&other.to_string())),
85 }
86}
87
88pub fn classify_core_error(error: &teams_core::Error) -> ConnectionState {
89 match error {
90 teams_core::Error::Graph(graph::Error::Session(inner)) => classify_session_error(inner),
91 other => ConnectionState::Failed(shorten(&other.to_string())),
92 }
93}
94
95fn image_directory() -> Option<std::path::PathBuf> {
96 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
97 .map(|directories| directories.data_local_dir().join(IMAGE_DIRECTORY))
98}
99
100fn shorten(text: &str) -> String {
101 text.chars().take(MAX_ERROR_CHARS).collect()
102}
103
104pub fn live_state_for(kind: StatusKind) -> LiveState {
105 match kind {
106 StatusKind::Connected => LiveState::Live,
107 StatusKind::Disconnected => LiveState::Reconnecting,
108 StatusKind::MessageLoss => LiveState::MessageLoss,
109 StatusKind::Error => LiveState::Failed,
110 }
111}
112
113fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {
114 match kind {
115 StatusKind::Connected => Some(LinkSignal::Connected),
116 StatusKind::Disconnected => Some(LinkSignal::Disconnected),
117 StatusKind::MessageLoss | StatusKind::Error => None,
118 }
119}
120
121pub fn start(
122 store: Arc<Store>,
123 transport: Arc<dyn Transport>,
124 ringable: bool,
125 activity: watch::Receiver<bool>,
126) -> mpsc::UnboundedReceiver<BackendEvent> {
127 let (sender, receiver) = mpsc::unbounded_channel();
128 crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));
129 receiver
130}
131
132async fn supervise(
133 store: Arc<Store>,
134 transport: Arc<dyn Transport>,
135 ringable: bool,
136 activity: watch::Receiver<bool>,
137 events: EventSender,
138) {
139 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
140 let session = loop {
141 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
142 Ok(session) => break session,
143 Err(error) => {
144 let _ = events.send(BackendEvent::Connection(classify_session_error(&error)));
145 tokio::time::sleep(CONNECT_RETRY).await;
146 }
147 }
148 };
149 let build = || {
150 SyncEngine::new(Graph::new(session.clone()), store.clone())
151 .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
152 };
153 let engine = image_directory()
154 .and_then(|directory| {
155 build()
156 .with_image_dir(&directory, IMAGE_CACHE_MAX_BYTES)
157 .ok()
158 })
159 .unwrap_or_else(build);
160 let engine = Arc::new(engine);
161 let _ = events.send(BackendEvent::Engine(engine.clone()));
162 let ring_events = events.clone();
163 let launcher = CallLauncher::start(transport, ringable, move |event| {
164 let _ = ring_events.send(BackendEvent::Ring(event));
165 });
166 let _ = events.send(BackendEvent::Calls(launcher));
167 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
168 let (nudge, nudges) = mpsc::unbounded_channel();
169 let resend = Arc::new(Notify::new());
170 let link = presence_link::start(&session, activity.clone(), resend.clone());
171 let live_retry = Arc::new(Notify::new());
172 let _ = events.send(BackendEvent::LiveRetry(live_retry.clone()));
173 tokio::spawn(realtime_loop(
174 session.clone(),
175 engine.clone(),
176 events.clone(),
177 nudge,
178 activity,
179 resend,
180 link,
181 live_retry,
182 ));
183 tokio::spawn(calendar_loop(session.clone(), events.clone()));
184 tokio::spawn(pins_loop(session, events.clone()));
185 tokio::spawn(presence_resubscribe_loop(engine.clone()));
186 refresh_loop(engine, events, nudges).await;
187}
188
189async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {
190 let mut receiver = engine.subscribe();
191 loop {
192 let event = match receiver.recv().await {
193 Ok(event) => event,
194 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => CoreEvent::SidebarChanged,
195 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
196 };
197 if events.send(BackendEvent::Core(event)).is_err() {
198 return;
199 }
200 }
201}
202
203async fn refresh_loop(
204 engine: Arc<Engine>,
205 events: EventSender,
206 mut nudges: mpsc::UnboundedReceiver<()>,
207) {
208 let mut interval = tokio::time::interval(REFRESH_INTERVAL);
209 let mut forwards_healing = false;
210 loop {
211 tokio::select! {
212 _ = interval.tick() => {}
213 nudge = nudges.recv() => {
214 if nudge.is_none() {
215 return;
216 }
217 tokio::time::sleep(REFRESH_SETTLE).await;
218 while nudges.try_recv().is_ok() {}
219 }
220 }
221 match engine.refresh_sidebar().await {
222 Ok(_) => {
223 if !std::mem::replace(&mut forwards_healing, true) {
224 let engine = engine.clone();
225 tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });
226 }
227 if let Err(error) = engine.refresh_folders().await {
228 crate::diagnostics::record(format!(
229 "sync: chat folders and channel layout not refreshed: {error}"
230 ));
231 }
232 let _ = events.send(BackendEvent::Connection(ConnectionState::Online));
233 let _ = events.send(BackendEvent::Synced(Utc::now()));
234 }
235 Err(error) => {
236 let _ = events.send(BackendEvent::Connection(classify_core_error(&error)));
237 tokio::time::sleep(CONNECT_RETRY).await;
238 }
239 }
240 }
241}
242
243async fn realtime_loop(
244 session: Session,
245 engine: Arc<Engine>,
246 events: EventSender,
247 nudge: mpsc::UnboundedSender<()>,
248 mut activity: watch::Receiver<bool>,
249 resend: Arc<Notify>,
250 link: mpsc::UnboundedSender<LinkSignal>,
251 live_retry: Arc<Notify>,
252) {
253 loop {
254 let _ = events.send(BackendEvent::Live(LiveState::Connecting));
255 let config = RealtimeConfig {
256 initially_active: *activity.borrow(),
257 ..RealtimeConfig::default()
258 };
259 match Realtime::start_with(&session, config).await {
260 Ok(mut realtime) => {
261 loop {
262 let event = tokio::select! {
263 event = realtime.recv() => event,
264 Ok(()) = activity.changed() => {
265 realtime.set_activity(*activity.borrow_and_update());
266 continue;
267 }
268 _ = resend.notified() => {
269 realtime.resend_activity();
270 continue;
271 }
272 };
273 let Some(event) = event else { break };
274 match event {
275 RealtimeEvent::Message(message) => {
276 let _ = events.send(BackendEvent::Live(LiveState::Live));
277 if let Some(conversation_id) = thread_signal(&message) {
278 let _ = events.send(BackendEvent::ThreadChanged(conversation_id));
279 }
280 let receipt_engine = engine.clone();
281 let receipt_event = message.clone();
282 engine.handle_pin_event(&message);
283 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
284 let activity_engine = engine.clone();
285 tokio::spawn(async move { activity_engine.refresh_activity().await });
286 }
287 tokio::spawn(async move {
288 receipt_engine.handle_receipt_event(&receipt_event).await
289 });
290 tokio::spawn(handle_message_event(
291 engine.clone(),
292 nudge.clone(),
293 message,
294 ));
295 }
296 RealtimeEvent::Typing(typing) => {
297 let _ = events.send(BackendEvent::Typing(typing));
298 }
299 RealtimeEvent::Status(status) => {
300 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
301 if let Some(signal) = link_signal_for(status.kind) {
302 let _ = link.send(signal);
303 }
304 let receipt_engine = engine.clone();
305 let receipt_status = status.clone();
306 tokio::spawn(async move {
307 receipt_engine.handle_receipt_status(&receipt_status).await
308 });
309 }
310 RealtimeEvent::Presence(updates) => {
311 engine.apply_presence(&updates);
312 if engine.concerns_me(&updates) {
313 let engine = engine.clone();
314 tokio::spawn(async move { engine.refresh_own_status().await });
315 }
316 }
317 RealtimeEvent::Endpoint(endpoint) => {
318 let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
319 let engine = engine.clone();
320 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
321 }
322 }
323 }
324 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
325 let _ = link.send(LinkSignal::Disconnected);
326 }
327 Err(_) => {
328 let _ = events.send(BackendEvent::Live(LiveState::Failed));
329 let _ = link.send(LinkSignal::Disconnected);
330 }
331 }
332 tokio::select! {
333 _ = tokio::time::sleep(REALTIME_RETRY) => {}
334 _ = live_retry.notified() => {}
335 }
336 }
337}
338
339async fn presence_resubscribe_loop(engine: Arc<Engine>) {
340 let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE);
341 interval.tick().await;
342 loop {
343 interval.tick().await;
344 let _ = engine.resubscribe_presence().await;
345 }
346}
347
348/// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message).
349pub fn thread_signal(event: &MessageEvent) -> Option<String> {
350 match event.kind {
351 EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(),
352 _ => None,
353 }
354}
355
356pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
357 let conversation_id = event.conversation_id.clone()?;
358 match event.kind {
359 EventKind::MessageUpdate => Some(match event.message_id.clone() {
360 Some(message_id) => RefreshPlan::Message {
361 conversation_id,
362 message_id,
363 },
364 None => RefreshPlan::Newer { conversation_id },
365 }),
366 EventKind::NewMessage => Some(match event.message_id.clone() {
367 Some(message_id) => RefreshPlan::Arrival {
368 conversation_id,
369 message_id,
370 },
371 None => RefreshPlan::Newer { conversation_id },
372 }),
373 _ => None,
374 }
375}
376
377#[derive(Debug, Clone, PartialEq, Eq)]
378pub enum RefreshPlan {
379 Newer {
380 conversation_id: String,
381 },
382 Arrival {
383 conversation_id: String,
384 message_id: String,
385 },
386 Message {
387 conversation_id: String,
388 message_id: String,
389 },
390}
391
392async fn handle_message_event(
393 engine: Arc<Engine>,
394 nudge: mpsc::UnboundedSender<()>,
395 event: MessageEvent,
396) {
397 let Some(plan) = refresh_plan(&event) else {
398 return;
399 };
400 let outcome = match &plan {
401 RefreshPlan::Newer { conversation_id }
402 | RefreshPlan::Arrival {
403 conversation_id, ..
404 } => engine.fetch_newer(conversation_id).await.map(|_| ()),
405 RefreshPlan::Message {
406 conversation_id,
407 message_id,
408 } => engine
409 .refresh_message(conversation_id, message_id)
410 .await
411 .map(|_| ()),
412 };
413 let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_)));
414 if unknown || event.kind == EventKind::NewMessage {
415 let _ = nudge.send(());
416 }
417 if let (
418 Ok(()),
419 RefreshPlan::Arrival {
420 conversation_id,
421 message_id,
422 },
423 ) = (outcome, &plan)
424 {
425 let _ = engine
426 .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
427 .await;
428 }
429}
430
431async fn calendar_loop(session: Session, events: EventSender) {
432 let calendar = Calendar::new(&session);
433 let (nudge, mut nudges) = mpsc::unbounded_channel();
434 let _ = events.send(BackendEvent::CalendarNudge(nudge));
435 let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
436 let mut last_fetch: Option<tokio::time::Instant> = None;
437 let mut deferred_fetch: Option<tokio::time::Instant> = None;
438 loop {
439 tokio::select! {
440 _ = interval.tick() => {}
441 _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {}
442 nudge = nudges.recv() => {
443 if nudge.is_none() {
444 return;
445 }
446 while nudges.try_recv().is_ok() {}
447 if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
448 deferred_fetch = Some(fetched + CALENDAR_MIN_GAP);
449 continue;
450 }
451 }
452 }
453 deferred_fetch = None;
454 last_fetch = Some(tokio::time::Instant::now());
455 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
456 match calendar.calendar_view(start, end).await {
457 Ok(fetched) => {
458 if events.send(BackendEvent::Calendar(fetched)).is_err() {
459 return;
460 }
461 }
462 Err(error) => crate::diagnostics::record(format!(
463 "calls: calendar not loaded: {}",
464 shorten(&error.to_string())
465 )),
466 }
467 }
468}
469
470async fn pins_loop(session: Session, events: EventSender) {
471 let pins = Pins::new(&session);
472 let mut chat_ids: Vec<String> = Vec::new();
473 let mut channel_ids: Vec<String> = Vec::new();
474 let mut interval = tokio::time::interval(PINS_INTERVAL);
475 loop {
476 interval.tick().await;
477 if let Ok(pinned) = pins.pinned_chats().await {
478 chat_ids = pinned.chat_ids;
479 }
480 if let Ok(pinned) = pins.pinned_channels().await {
481 channel_ids = pinned.channel_ids;
482 }
483 let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect();
484 if events.send(BackendEvent::Favorites(combined)).is_err() {
485 return;
486 }
487 }
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493
494 fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent {
495 MessageEvent {
496 resource_type: "x".into(),
497 kind,
498 conversation_id: conversation.map(str::to_owned),
499 message_id: message.map(str::to_owned),
500 received_at: Utc::now(),
501 }
502 }
503
504 #[test]
505 fn new_message_waits_for_its_arrival() {
506 assert_eq!(
507 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
508 Some(RefreshPlan::Arrival {
509 conversation_id: "c".into(),
510 message_id: "m".into()
511 })
512 );
513 assert_eq!(
514 refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
515 Some(RefreshPlan::Newer {
516 conversation_id: "c".into()
517 })
518 );
519 }
520
521 #[test]
522 fn update_refreshes_one_message() {
523 assert_eq!(
524 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))),
525 Some(RefreshPlan::Message {
526 conversation_id: "c".into(),
527 message_id: "m".into()
528 })
529 );
530 assert_eq!(
531 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)),
532 Some(RefreshPlan::Newer {
533 conversation_id: "c".into()
534 })
535 );
536 }
537
538 #[test]
539 fn thread_updates_and_new_messages_signal_a_possible_meeting_change() {
540 assert_eq!(
541 thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(),
542 Some("c")
543 );
544 assert_eq!(
545 thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
546 Some("c")
547 );
548 assert_eq!(
549 thread_signal(&event(EventKind::Typing, Some("c"), None)),
550 None
551 );
552 assert_eq!(
553 thread_signal(&event(EventKind::ThreadUpdate, None, None)),
554 None
555 );
556 }
557
558 #[test]
559 fn typing_and_missing_conversation_are_ignored() {
560 assert_eq!(
561 refresh_plan(&event(EventKind::Typing, Some("c"), None)),
562 None
563 );
564 assert_eq!(
565 refresh_plan(&event(EventKind::NewMessage, None, None)),
566 None
567 );
568 }
569
570 #[test]
571 fn session_errors_map_to_states() {
572 assert_eq!(
573 classify_session_error(&session::Error::NoAppTab),
574 ConnectionState::NoAppTab
575 );
576 assert_eq!(
577 classify_session_error(&session::Error::LoginRequired("x".into())),
578 ConnectionState::LoginRequired
579 );
580 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
581 }
582
583 #[test]
584 fn only_connect_and_disconnect_move_the_link() {
585 assert_eq!(
586 link_signal_for(StatusKind::Connected),
587 Some(LinkSignal::Connected)
588 );
589 assert_eq!(
590 link_signal_for(StatusKind::Disconnected),
591 Some(LinkSignal::Disconnected)
592 );
593 assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
594 assert_eq!(link_signal_for(StatusKind::Error), None);
595 }
596}