BlueGit

ict rusty-teams

Files

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

backend.rs

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