BlueGit

ict rusty-teams

Files

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

backend.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
backend.rs 22.0 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 {
310 let activity_engine = engine.clone();
311 tokio::spawn(
312 async move { activity_engine.refresh_activity().await },
313 );
314 }
315 tokio::spawn(async move {
316 receipt_engine.handle_receipt_event(&receipt_event).await
317 });
318 tokio::spawn(handle_message_event(
319 engine.clone(),
320 nudge.clone(),
321 message,
322 ));
323 }
324 RealtimeEvent::Typing(typing) => {
325 let _ = events.send(BackendEvent::Typing(typing));
326 }
327 RealtimeEvent::Status(status) => {
328 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
329 if let Some(signal) = link_signal_for(status.kind) {
330 let _ = link.send(signal);
331 }
332 let receipt_engine = engine.clone();
333 let receipt_status = status.clone();
334 tokio::spawn(async move {
335 receipt_engine.handle_receipt_status(&receipt_status).await
336 });
337 }
338 RealtimeEvent::Presence(updates) => {
339 engine.apply_presence(&updates);
340 if engine.concerns_me(&updates) {
341 let engine = engine.clone();
342 tokio::spawn(async move { engine.refresh_own_status().await });
343 }
344 }
345 RealtimeEvent::Endpoint(endpoint) => {
346 let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
347 let engine = engine.clone();
348 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
349 }
350 }
351 }
352 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
353 let _ = link.send(LinkSignal::Disconnected);
354 }
355 Err(_) => {
356 let _ = events.send(BackendEvent::Live(LiveState::Failed));
357 let _ = link.send(LinkSignal::Disconnected);
358 }
359 }
360 tokio::select! {
361 _ = tokio::time::sleep(REALTIME_RETRY) => {}
362 _ = live_retry.notified() => {}
363 }
364 }
365}
366
367async fn presence_resubscribe_loop(engine: Arc<Engine>) {
368 let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE);
369 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
370 interval.tick().await;
371 loop {
372 interval.tick().await;
373 let _ = engine.resubscribe_presence().await;
374 }
375}
376
377/// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message).
378pub fn thread_signal(event: &MessageEvent) -> Option<String> {
379 match event.kind {
380 EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(),
381 _ => None,
382 }
383}
384
385pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
386 let conversation_id = event.conversation_id.clone()?;
387 match event.kind {
388 EventKind::MessageUpdate => Some(match event.message_id.clone() {
389 Some(message_id) => RefreshPlan::Message {
390 conversation_id,
391 message_id,
392 },
393 None => RefreshPlan::Newer { conversation_id },
394 }),
395 EventKind::NewMessage => Some(match event.message_id.clone() {
396 Some(message_id) => RefreshPlan::Arrival {
397 conversation_id,
398 message_id,
399 },
400 None => RefreshPlan::Newer { conversation_id },
401 }),
402 _ => None,
403 }
404}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub enum RefreshPlan {
408 Newer {
409 conversation_id: String,
410 },
411 Arrival {
412 conversation_id: String,
413 message_id: String,
414 },
415 Message {
416 conversation_id: String,
417 message_id: String,
418 },
419}
420
421async fn handle_message_event(
422 engine: Arc<Engine>,
423 nudge: mpsc::UnboundedSender<()>,
424 event: MessageEvent,
425) {
426 let Some(plan) = refresh_plan(&event) else {
427 return;
428 };
429 let outcome = match &plan {
430 RefreshPlan::Newer { conversation_id }
431 | RefreshPlan::Arrival {
432 conversation_id, ..
433 } => engine.fetch_newer(conversation_id).await.map(|_| ()),
434 RefreshPlan::Message {
435 conversation_id,
436 message_id,
437 } => engine
438 .refresh_message(conversation_id, message_id)
439 .await
440 .map(|_| ()),
441 };
442 let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_)));
443 if unknown || event.kind == EventKind::NewMessage {
444 let _ = nudge.send(());
445 }
446 if let (
447 Ok(()),
448 RefreshPlan::Arrival {
449 conversation_id,
450 message_id,
451 },
452 ) = (outcome, &plan)
453 {
454 let _ = engine
455 .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
456 .await;
457 }
458}
459
460async fn calendar_loop(session: Session, events: EventSender) {
461 let calendar = Calendar::new(&session);
462 let (nudge, mut nudges) = mpsc::unbounded_channel();
463 let _ = events.send(BackendEvent::CalendarNudge(nudge));
464 let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
465 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
466 let mut last_fetch: Option<tokio::time::Instant> = None;
467 let mut deferred_fetch: Option<tokio::time::Instant> = None;
468 loop {
469 tokio::select! {
470 _ = interval.tick() => {}
471 _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {}
472 nudge = nudges.recv() => {
473 if nudge.is_none() {
474 return;
475 }
476 while nudges.try_recv().is_ok() {}
477 if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
478 deferred_fetch = Some(fetched + CALENDAR_MIN_GAP);
479 continue;
480 }
481 }
482 }
483 deferred_fetch = None;
484 last_fetch = Some(tokio::time::Instant::now());
485 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
486 match calendar.calendar_view(start, end).await {
487 Ok(fetched) => {
488 if events.send(BackendEvent::Calendar(fetched)).is_err() {
489 return;
490 }
491 }
492 Err(error) => crate::diagnostics::record(format!(
493 "calls: calendar not loaded: {}",
494 shorten(&error.to_string())
495 )),
496 }
497 }
498}
499
500async fn pins_loop(session: Session, events: EventSender) {
501 let pins = Pins::new(&session);
502 let mut chat_ids: Vec<String> = Vec::new();
503 let mut channel_ids: Vec<String> = Vec::new();
504 let mut interval = tokio::time::interval(PINS_INTERVAL);
505 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
506 loop {
507 interval.tick().await;
508 if let Ok(pinned) = pins.pinned_chats().await {
509 chat_ids = pinned.chat_ids;
510 }
511 if let Ok(pinned) = pins.pinned_channels().await {
512 channel_ids = pinned.channel_ids;
513 }
514 let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect();
515 if events.send(BackendEvent::Favorites(combined)).is_err() {
516 return;
517 }
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524
525 fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent {
526 MessageEvent {
527 resource_type: "x".into(),
528 kind,
529 conversation_id: conversation.map(str::to_owned),
530 message_id: message.map(str::to_owned),
531 received_at: Utc::now(),
532 }
533 }
534
535 #[test]
536 fn new_message_waits_for_its_arrival() {
537 assert_eq!(
538 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
539 Some(RefreshPlan::Arrival {
540 conversation_id: "c".into(),
541 message_id: "m".into()
542 })
543 );
544 assert_eq!(
545 refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
546 Some(RefreshPlan::Newer {
547 conversation_id: "c".into()
548 })
549 );
550 }
551
552 #[test]
553 fn update_refreshes_one_message() {
554 assert_eq!(
555 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))),
556 Some(RefreshPlan::Message {
557 conversation_id: "c".into(),
558 message_id: "m".into()
559 })
560 );
561 assert_eq!(
562 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)),
563 Some(RefreshPlan::Newer {
564 conversation_id: "c".into()
565 })
566 );
567 }
568
569 #[test]
570 fn thread_updates_and_new_messages_signal_a_possible_meeting_change() {
571 assert_eq!(
572 thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(),
573 Some("c")
574 );
575 assert_eq!(
576 thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
577 Some("c")
578 );
579 assert_eq!(
580 thread_signal(&event(EventKind::Typing, Some("c"), None)),
581 None
582 );
583 assert_eq!(
584 thread_signal(&event(EventKind::ThreadUpdate, None, None)),
585 None
586 );
587 }
588
589 #[test]
590 fn typing_and_missing_conversation_are_ignored() {
591 assert_eq!(
592 refresh_plan(&event(EventKind::Typing, Some("c"), None)),
593 None
594 );
595 assert_eq!(
596 refresh_plan(&event(EventKind::NewMessage, None, None)),
597 None
598 );
599 }
600
601 #[test]
602 fn session_errors_map_to_states() {
603 assert_eq!(
604 classify_session_error(&session::Error::NoAppTab),
605 ConnectionState::NoAppTab
606 );
607 assert_eq!(
608 classify_session_error(&session::Error::LoginRequired("x".into())),
609 ConnectionState::LoginRequired
610 );
611 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
612 }
613
614 #[test]
615 fn only_connect_and_disconnect_move_the_link() {
616 assert_eq!(
617 link_signal_for(StatusKind::Connected),
618 Some(LinkSignal::Connected)
619 );
620 assert_eq!(
621 link_signal_for(StatusKind::Disconnected),
622 Some(LinkSignal::Disconnected)
623 );
624 assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
625 assert_eq!(link_signal_for(StatusKind::Error), None);
626 }
627}