BlueGit

ict rusty-teams

Files

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

backend.rs

backend.rs 20.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
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 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
210 let mut forwards_healing = false;
211 loop {
212 tokio::select! {
213 _ = interval.tick() => {}
214 nudge = nudges.recv() => {
215 if nudge.is_none() {
216 return;
217 }
218 tokio::time::sleep(REFRESH_SETTLE).await;
219 while nudges.try_recv().is_ok() {}
220 }
221 }
222 match engine.refresh_sidebar().await {
223 Ok(_) => {
224 if !std::mem::replace(&mut forwards_healing, true) {
225 let engine = engine.clone();
226 tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });
227 }
228 if let Err(error) = engine.refresh_folders().await {
229 crate::diagnostics::record(format!(
230 "sync: chat folders and channel layout not refreshed: {error}"
231 ));
232 }
233 let _ = events.send(BackendEvent::Connection(ConnectionState::Online));
234 let _ = events.send(BackendEvent::Synced(Utc::now()));
235 }
236 Err(error) => {
237 let _ = events.send(BackendEvent::Connection(classify_core_error(&error)));
238 tokio::time::sleep(CONNECT_RETRY).await;
239 }
240 }
241 }
242}
243
244async fn realtime_loop(
245 session: Session,
246 engine: Arc<Engine>,
247 events: EventSender,
248 nudge: mpsc::UnboundedSender<()>,
249 mut activity: watch::Receiver<bool>,
250 resend: Arc<Notify>,
251 link: mpsc::UnboundedSender<LinkSignal>,
252 live_retry: Arc<Notify>,
253) {
254 loop {
255 let _ = events.send(BackendEvent::Live(LiveState::Connecting));
256 let config = RealtimeConfig {
257 initially_active: *activity.borrow(),
258 ..RealtimeConfig::default()
259 };
260 match Realtime::start_with(&session, config).await {
261 Ok(mut realtime) => {
262 loop {
263 let event = tokio::select! {
264 event = realtime.recv() => event,
265 Ok(()) = activity.changed() => {
266 realtime.set_activity(*activity.borrow_and_update());
267 continue;
268 }
269 _ = resend.notified() => {
270 realtime.resend_activity();
271 continue;
272 }
273 };
274 let Some(event) = event else { break };
275 match event {
276 RealtimeEvent::Message(message) => {
277 let _ = events.send(BackendEvent::Live(LiveState::Live));
278 if let Some(conversation_id) = thread_signal(&message) {
279 let _ = events.send(BackendEvent::ThreadChanged(conversation_id));
280 }
281 let receipt_engine = engine.clone();
282 let receipt_event = message.clone();
283 engine.handle_pin_event(&message);
284 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
285 let activity_engine = engine.clone();
286 tokio::spawn(async move { activity_engine.refresh_activity().await });
287 }
288 tokio::spawn(async move {
289 receipt_engine.handle_receipt_event(&receipt_event).await
290 });
291 tokio::spawn(handle_message_event(
292 engine.clone(),
293 nudge.clone(),
294 message,
295 ));
296 }
297 RealtimeEvent::Typing(typing) => {
298 let _ = events.send(BackendEvent::Typing(typing));
299 }
300 RealtimeEvent::Status(status) => {
301 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
302 if let Some(signal) = link_signal_for(status.kind) {
303 let _ = link.send(signal);
304 }
305 let receipt_engine = engine.clone();
306 let receipt_status = status.clone();
307 tokio::spawn(async move {
308 receipt_engine.handle_receipt_status(&receipt_status).await
309 });
310 }
311 RealtimeEvent::Presence(updates) => {
312 engine.apply_presence(&updates);
313 if engine.concerns_me(&updates) {
314 let engine = engine.clone();
315 tokio::spawn(async move { engine.refresh_own_status().await });
316 }
317 }
318 RealtimeEvent::Endpoint(endpoint) => {
319 let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
320 let engine = engine.clone();
321 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
322 }
323 }
324 }
325 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
326 let _ = link.send(LinkSignal::Disconnected);
327 }
328 Err(_) => {
329 let _ = events.send(BackendEvent::Live(LiveState::Failed));
330 let _ = link.send(LinkSignal::Disconnected);
331 }
332 }
333 tokio::select! {
334 _ = tokio::time::sleep(REALTIME_RETRY) => {}
335 _ = live_retry.notified() => {}
336 }
337 }
338}
339
340async fn presence_resubscribe_loop(engine: Arc<Engine>) {
341 let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE);
342 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
343 interval.tick().await;
344 loop {
345 interval.tick().await;
346 let _ = engine.resubscribe_presence().await;
347 }
348}
349
350/// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message).
351pub fn thread_signal(event: &MessageEvent) -> Option<String> {
352 match event.kind {
353 EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(),
354 _ => None,
355 }
356}
357
358pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
359 let conversation_id = event.conversation_id.clone()?;
360 match event.kind {
361 EventKind::MessageUpdate => Some(match event.message_id.clone() {
362 Some(message_id) => RefreshPlan::Message {
363 conversation_id,
364 message_id,
365 },
366 None => RefreshPlan::Newer { conversation_id },
367 }),
368 EventKind::NewMessage => Some(match event.message_id.clone() {
369 Some(message_id) => RefreshPlan::Arrival {
370 conversation_id,
371 message_id,
372 },
373 None => RefreshPlan::Newer { conversation_id },
374 }),
375 _ => None,
376 }
377}
378
379#[derive(Debug, Clone, PartialEq, Eq)]
380pub enum RefreshPlan {
381 Newer {
382 conversation_id: String,
383 },
384 Arrival {
385 conversation_id: String,
386 message_id: String,
387 },
388 Message {
389 conversation_id: String,
390 message_id: String,
391 },
392}
393
394async fn handle_message_event(
395 engine: Arc<Engine>,
396 nudge: mpsc::UnboundedSender<()>,
397 event: MessageEvent,
398) {
399 let Some(plan) = refresh_plan(&event) else {
400 return;
401 };
402 let outcome = match &plan {
403 RefreshPlan::Newer { conversation_id }
404 | RefreshPlan::Arrival {
405 conversation_id, ..
406 } => engine.fetch_newer(conversation_id).await.map(|_| ()),
407 RefreshPlan::Message {
408 conversation_id,
409 message_id,
410 } => engine
411 .refresh_message(conversation_id, message_id)
412 .await
413 .map(|_| ()),
414 };
415 let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_)));
416 if unknown || event.kind == EventKind::NewMessage {
417 let _ = nudge.send(());
418 }
419 if let (
420 Ok(()),
421 RefreshPlan::Arrival {
422 conversation_id,
423 message_id,
424 },
425 ) = (outcome, &plan)
426 {
427 let _ = engine
428 .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
429 .await;
430 }
431}
432
433async fn calendar_loop(session: Session, events: EventSender) {
434 let calendar = Calendar::new(&session);
435 let (nudge, mut nudges) = mpsc::unbounded_channel();
436 let _ = events.send(BackendEvent::CalendarNudge(nudge));
437 let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
438 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
439 let mut last_fetch: Option<tokio::time::Instant> = None;
440 let mut deferred_fetch: Option<tokio::time::Instant> = None;
441 loop {
442 tokio::select! {
443 _ = interval.tick() => {}
444 _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {}
445 nudge = nudges.recv() => {
446 if nudge.is_none() {
447 return;
448 }
449 while nudges.try_recv().is_ok() {}
450 if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
451 deferred_fetch = Some(fetched + CALENDAR_MIN_GAP);
452 continue;
453 }
454 }
455 }
456 deferred_fetch = None;
457 last_fetch = Some(tokio::time::Instant::now());
458 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
459 match calendar.calendar_view(start, end).await {
460 Ok(fetched) => {
461 if events.send(BackendEvent::Calendar(fetched)).is_err() {
462 return;
463 }
464 }
465 Err(error) => crate::diagnostics::record(format!(
466 "calls: calendar not loaded: {}",
467 shorten(&error.to_string())
468 )),
469 }
470 }
471}
472
473async fn pins_loop(session: Session, events: EventSender) {
474 let pins = Pins::new(&session);
475 let mut chat_ids: Vec<String> = Vec::new();
476 let mut channel_ids: Vec<String> = Vec::new();
477 let mut interval = tokio::time::interval(PINS_INTERVAL);
478 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
479 loop {
480 interval.tick().await;
481 if let Ok(pinned) = pins.pinned_chats().await {
482 chat_ids = pinned.chat_ids;
483 }
484 if let Ok(pinned) = pins.pinned_channels().await {
485 channel_ids = pinned.channel_ids;
486 }
487 let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect();
488 if events.send(BackendEvent::Favorites(combined)).is_err() {
489 return;
490 }
491 }
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497
498 fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent {
499 MessageEvent {
500 resource_type: "x".into(),
501 kind,
502 conversation_id: conversation.map(str::to_owned),
503 message_id: message.map(str::to_owned),
504 received_at: Utc::now(),
505 }
506 }
507
508 #[test]
509 fn new_message_waits_for_its_arrival() {
510 assert_eq!(
511 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
512 Some(RefreshPlan::Arrival {
513 conversation_id: "c".into(),
514 message_id: "m".into()
515 })
516 );
517 assert_eq!(
518 refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
519 Some(RefreshPlan::Newer {
520 conversation_id: "c".into()
521 })
522 );
523 }
524
525 #[test]
526 fn update_refreshes_one_message() {
527 assert_eq!(
528 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))),
529 Some(RefreshPlan::Message {
530 conversation_id: "c".into(),
531 message_id: "m".into()
532 })
533 );
534 assert_eq!(
535 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)),
536 Some(RefreshPlan::Newer {
537 conversation_id: "c".into()
538 })
539 );
540 }
541
542 #[test]
543 fn thread_updates_and_new_messages_signal_a_possible_meeting_change() {
544 assert_eq!(
545 thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(),
546 Some("c")
547 );
548 assert_eq!(
549 thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
550 Some("c")
551 );
552 assert_eq!(
553 thread_signal(&event(EventKind::Typing, Some("c"), None)),
554 None
555 );
556 assert_eq!(
557 thread_signal(&event(EventKind::ThreadUpdate, None, None)),
558 None
559 );
560 }
561
562 #[test]
563 fn typing_and_missing_conversation_are_ignored() {
564 assert_eq!(
565 refresh_plan(&event(EventKind::Typing, Some("c"), None)),
566 None
567 );
568 assert_eq!(
569 refresh_plan(&event(EventKind::NewMessage, None, None)),
570 None
571 );
572 }
573
574 #[test]
575 fn session_errors_map_to_states() {
576 assert_eq!(
577 classify_session_error(&session::Error::NoAppTab),
578 ConnectionState::NoAppTab
579 );
580 assert_eq!(
581 classify_session_error(&session::Error::LoginRequired("x".into())),
582 ConnectionState::LoginRequired
583 );
584 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
585 }
586
587 #[test]
588 fn only_connect_and_disconnect_move_the_link() {
589 assert_eq!(
590 link_signal_for(StatusKind::Connected),
591 Some(LinkSignal::Connected)
592 );
593 assert_eq!(
594 link_signal_for(StatusKind::Disconnected),
595 Some(LinkSignal::Disconnected)
596 );
597 assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
598 assert_eq!(link_signal_for(StatusKind::Error), None);
599 }
600}