BlueGit

ict rusty-teams

Files

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

backend.rs

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