| 1 | use std::sync::{Arc, OnceLock}; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use chatsvc::cards::CardTransport; |
| 5 | use chatsvc::{ActivityReporting, PresenceService, error_status, is_endpoint_missing}; |
| 6 | use session::Session; |
| 7 | use tokio::sync::{Notify, mpsc, oneshot, watch}; |
| 8 | use tokio::time::{Instant, MissedTickBehavior, interval}; |
| 9 | |
| 10 | const FALLBACK_AFTER: Duration = Duration::from_secs(120); |
| 11 | const FALLBACK_INTERVAL: Duration = Duration::from_secs(120); |
| 12 | const CHECK_INTERVAL: Duration = Duration::from_secs(30); |
| 13 | const RETRY_BASE: Duration = Duration::from_secs(30); |
| 14 | const RETRY_MAX: Duration = Duration::from_secs(240); |
| 15 | const PERMANENT_FAILURE_RETRY: Duration = Duration::from_secs(30 * 60); |
| 16 | |
| 17 | static UNREGISTER: OnceLock<mpsc::UnboundedSender<oneshot::Sender<()>>> = OnceLock::new(); |
| 18 | |
| 19 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | pub enum LinkSignal { |
| 21 | Endpoint(String), |
| 22 | Connected, |
| 23 | Disconnected, |
| 24 | } |
| 25 | |
| 26 | pub fn report_due( |
| 27 | down_for: Option<Duration>, |
| 28 | since_last_report: Option<Duration>, |
| 29 | activity_changed: bool, |
| 30 | ) -> bool { |
| 31 | down_for.is_some_and(|down_for| down_for >= FALLBACK_AFTER) |
| 32 | && (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL)) |
| 33 | } |
| 34 | |
| 35 | pub fn retry_delay(failures: u32) -> Duration { |
| 36 | let doublings = failures.saturating_sub(1).min(8); |
| 37 | (RETRY_BASE * 2u32.pow(doublings)).min(RETRY_MAX) |
| 38 | } |
| 39 | |
| 40 | pub fn is_permanent_failure(status: Option<u16>) -> bool { |
| 41 | matches!(status, Some(400..=499)) && !matches!(status, Some(401 | 404 | 408 | 429)) |
| 42 | } |
| 43 | |
| 44 | pub fn start( |
| 45 | session: &Session, |
| 46 | activity: watch::Receiver<bool>, |
| 47 | resend: Arc<Notify>, |
| 48 | ) -> mpsc::UnboundedSender<LinkSignal> { |
| 49 | let (signals, receiver) = mpsc::unbounded_channel(); |
| 50 | let (unregister, unregisters) = mpsc::unbounded_channel(); |
| 51 | let _ = UNREGISTER.set(unregister); |
| 52 | let link = Link::new(PresenceService::new(session), activity, resend); |
| 53 | tokio::spawn(link.run(receiver, unregisters)); |
| 54 | signals |
| 55 | } |
| 56 | |
| 57 | /// Gives up after `timeout` so quitting is never held back. |
| 58 | pub fn unregister_on_exit(timeout: Duration) { |
| 59 | let Some(unregister) = UNREGISTER.get() else { |
| 60 | return; |
| 61 | }; |
| 62 | let (done, finished) = oneshot::channel(); |
| 63 | if unregister.send(done).is_err() { |
| 64 | return; |
| 65 | } |
| 66 | let _ = crate::runtime::handle() |
| 67 | .block_on(async move { tokio::time::timeout(timeout, finished).await }); |
| 68 | } |
| 69 | |
| 70 | #[derive(Default)] |
| 71 | struct RetryState { |
| 72 | failures: u32, |
| 73 | next_attempt: Option<Instant>, |
| 74 | last_error: Option<String>, |
| 75 | } |
| 76 | |
| 77 | impl RetryState { |
| 78 | fn may_attempt(&self, now: Instant) -> bool { |
| 79 | self.next_attempt.is_none_or(|next| now >= next) |
| 80 | } |
| 81 | |
| 82 | fn succeeded(&mut self) { |
| 83 | *self = RetryState::default(); |
| 84 | } |
| 85 | |
| 86 | fn failed(&mut self, now: Instant, error: &chatsvc::Error) -> Option<String> { |
| 87 | self.failures += 1; |
| 88 | let delay = if is_permanent_failure(error_status(error)) { |
| 89 | PERMANENT_FAILURE_RETRY |
| 90 | } else { |
| 91 | retry_delay(self.failures) |
| 92 | }; |
| 93 | self.next_attempt = Some(now + delay); |
| 94 | let message = error.to_string(); |
| 95 | let is_new = self.last_error.as_deref() != Some(message.as_str()); |
| 96 | self.last_error = Some(message.clone()); |
| 97 | is_new.then_some(message) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | struct Link<T: CardTransport> { |
| 102 | service: PresenceService<T>, |
| 103 | activity: watch::Receiver<bool>, |
| 104 | resend: Arc<Notify>, |
| 105 | endpoint_id: Option<String>, |
| 106 | registered: bool, |
| 107 | applied: ActivityReporting, |
| 108 | down_since: Option<Instant>, |
| 109 | last_report: Option<Instant>, |
| 110 | retry: RetryState, |
| 111 | } |
| 112 | |
| 113 | impl<T: CardTransport> Link<T> { |
| 114 | fn new( |
| 115 | service: PresenceService<T>, |
| 116 | activity: watch::Receiver<bool>, |
| 117 | resend: Arc<Notify>, |
| 118 | ) -> Self { |
| 119 | Link { |
| 120 | service, |
| 121 | activity, |
| 122 | resend, |
| 123 | endpoint_id: None, |
| 124 | registered: false, |
| 125 | applied: ActivityReporting::Transport, |
| 126 | down_since: None, |
| 127 | last_report: None, |
| 128 | retry: RetryState::default(), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | async fn run( |
| 133 | mut self, |
| 134 | mut signals: mpsc::UnboundedReceiver<LinkSignal>, |
| 135 | mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>, |
| 136 | ) { |
| 137 | let mut check = interval(CHECK_INTERVAL); |
| 138 | check.set_missed_tick_behavior(MissedTickBehavior::Delay); |
| 139 | loop { |
| 140 | tokio::select! { |
| 141 | signal = signals.recv() => { |
| 142 | let Some(signal) = signal else { return }; |
| 143 | self.apply(signal).await; |
| 144 | } |
| 145 | Ok(()) = self.activity.changed() => { |
| 146 | self.activity.borrow_and_update(); |
| 147 | self.reconcile(true).await; |
| 148 | } |
| 149 | _ = check.tick() => self.reconcile(false).await, |
| 150 | Some(done) = unregisters.recv() => { |
| 151 | if let Some(endpoint_id) = &self.endpoint_id { |
| 152 | let _ = self.service.unregister_endpoint(endpoint_id).await; |
| 153 | } |
| 154 | let _ = done.send(()); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | async fn apply(&mut self, signal: LinkSignal) { |
| 161 | match signal { |
| 162 | LinkSignal::Endpoint(endpoint_id) => { |
| 163 | if self.endpoint_id.as_deref() == Some(endpoint_id.as_str()) { |
| 164 | return; |
| 165 | } |
| 166 | if let Some(previous) = self.endpoint_id.replace(endpoint_id) { |
| 167 | let _ = self.service.unregister_endpoint(&previous).await; |
| 168 | } |
| 169 | self.registered = false; |
| 170 | self.applied = ActivityReporting::Transport; |
| 171 | self.down_since = None; |
| 172 | self.last_report = None; |
| 173 | self.retry.succeeded(); |
| 174 | } |
| 175 | LinkSignal::Connected => { |
| 176 | if self.down_since.take().is_some() { |
| 177 | self.last_report = None; |
| 178 | self.retry.succeeded(); |
| 179 | } |
| 180 | } |
| 181 | LinkSignal::Disconnected => { |
| 182 | self.down_since.get_or_insert_with(Instant::now); |
| 183 | } |
| 184 | } |
| 185 | self.reconcile(false).await; |
| 186 | } |
| 187 | |
| 188 | async fn reconcile(&mut self, activity_changed: bool) { |
| 189 | let Some(endpoint_id) = self.endpoint_id.clone() else { |
| 190 | return; |
| 191 | }; |
| 192 | let now = Instant::now(); |
| 193 | let down_for = self.down_since.map(|since| now.duration_since(since)); |
| 194 | let wanted = match down_for { |
| 195 | Some(down_for) if down_for >= FALLBACK_AFTER => ActivityReporting::Direct, |
| 196 | _ => ActivityReporting::Transport, |
| 197 | }; |
| 198 | if (!self.registered || self.applied != wanted) && self.retry.may_attempt(now) { |
| 199 | self.register(&endpoint_id, wanted, now).await; |
| 200 | } |
| 201 | if wanted != ActivityReporting::Direct || !self.registered || self.applied != wanted { |
| 202 | return; |
| 203 | } |
| 204 | let since_last_report = self.last_report.map(|last| now.duration_since(last)); |
| 205 | if report_due(down_for, since_last_report, activity_changed) { |
| 206 | self.last_report = Some(now); |
| 207 | let active = *self.activity.borrow(); |
| 208 | self.report_with_recovery(&endpoint_id, active).await; |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | async fn register(&mut self, endpoint_id: &str, reporting: ActivityReporting, now: Instant) { |
| 213 | match self.service.register_endpoint(endpoint_id, reporting).await { |
| 214 | Ok(()) => { |
| 215 | self.registered = true; |
| 216 | self.applied = reporting; |
| 217 | self.retry.succeeded(); |
| 218 | if reporting == ActivityReporting::Transport { |
| 219 | self.resend.notify_one(); |
| 220 | } |
| 221 | } |
| 222 | Err(error) => { |
| 223 | if let Some(message) = self.retry.failed(now, &error) { |
| 224 | crate::diagnostics::record(format!( |
| 225 | "presence: endpoint not registered: {message}" |
| 226 | )); |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | async fn report_with_recovery(&self, endpoint_id: &str, active: bool) { |
| 233 | let Err(error) = self.service.report_activity(endpoint_id, active).await else { |
| 234 | return; |
| 235 | }; |
| 236 | if is_endpoint_missing(&error) |
| 237 | && self |
| 238 | .service |
| 239 | .register_endpoint(endpoint_id, ActivityReporting::Direct) |
| 240 | .await |
| 241 | .is_ok() |
| 242 | && self |
| 243 | .service |
| 244 | .report_activity(endpoint_id, active) |
| 245 | .await |
| 246 | .is_ok() |
| 247 | { |
| 248 | return; |
| 249 | } |
| 250 | crate::diagnostics::record(format!("presence: activity not reported: {error}")); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | #[cfg(test)] |
| 255 | mod tests { |
| 256 | use std::sync::Mutex; |
| 257 | |
| 258 | use chatsvc::Result; |
| 259 | use session::{ApiResponse, Method, Request, Scope}; |
| 260 | |
| 261 | use super::*; |
| 262 | |
| 263 | const PRESENCE: &str = "https://presence.teams.microsoft.com/v1/me"; |
| 264 | |
| 265 | type Sent = Arc<Mutex<Vec<(Method, String, Option<String>)>>>; |
| 266 | |
| 267 | struct Scripted { |
| 268 | statuses: Mutex<Vec<u16>>, |
| 269 | sent: Sent, |
| 270 | } |
| 271 | |
| 272 | impl CardTransport for Scripted { |
| 273 | async fn send(&self, request: Request, _scope: Scope) -> Result<ApiResponse> { |
| 274 | let reporting = request |
| 275 | .body |
| 276 | .as_ref() |
| 277 | .and_then(|body| body["activityReporting"].as_str()) |
| 278 | .map(str::to_owned); |
| 279 | self.sent |
| 280 | .lock() |
| 281 | .unwrap() |
| 282 | .push((request.method, request.url, reporting)); |
| 283 | let mut statuses = self.statuses.lock().unwrap(); |
| 284 | let status = if statuses.is_empty() { |
| 285 | 200 |
| 286 | } else { |
| 287 | statuses.remove(0) |
| 288 | }; |
| 289 | Ok(ApiResponse { |
| 290 | status, |
| 291 | body: serde_json::Value::Null, |
| 292 | retry_after: None, |
| 293 | }) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | fn link(statuses: Vec<u16>) -> (Link<Scripted>, Sent, Arc<Notify>) { |
| 298 | let sent: Sent = Arc::default(); |
| 299 | let resend = Arc::new(Notify::new()); |
| 300 | let (_, activity) = watch::channel(true); |
| 301 | let service = PresenceService::with_transport(Scripted { |
| 302 | statuses: Mutex::new(statuses), |
| 303 | sent: sent.clone(), |
| 304 | }); |
| 305 | (Link::new(service, activity, resend.clone()), sent, resend) |
| 306 | } |
| 307 | |
| 308 | fn calls(sent: &Sent) -> Vec<String> { |
| 309 | sent.lock() |
| 310 | .unwrap() |
| 311 | .iter() |
| 312 | .map(|(method, url, reporting)| { |
| 313 | let path = url.strip_prefix(PRESENCE).unwrap(); |
| 314 | format!( |
| 315 | "{} {path} {}", |
| 316 | method.as_str(), |
| 317 | reporting.as_deref().unwrap_or("-") |
| 318 | ) |
| 319 | }) |
| 320 | .collect() |
| 321 | } |
| 322 | |
| 323 | fn seconds(count: u64) -> Duration { |
| 324 | Duration::from_secs(count) |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn fallback_starts_after_two_minutes_down_and_repeats_every_two_minutes() { |
| 329 | assert!(!report_due(None, None, true)); |
| 330 | assert!(!report_due(Some(seconds(119)), None, true)); |
| 331 | assert!(report_due(Some(seconds(120)), None, false)); |
| 332 | assert!(!report_due(Some(seconds(150)), Some(seconds(30)), false)); |
| 333 | assert!(report_due(Some(seconds(240)), Some(seconds(120)), false)); |
| 334 | assert!(report_due(Some(seconds(150)), Some(seconds(30)), true)); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn retry_delay_doubles_up_to_four_minutes() { |
| 339 | let delays: Vec<u64> = (1..=6) |
| 340 | .map(|failures| retry_delay(failures).as_secs()) |
| 341 | .collect(); |
| 342 | assert_eq!(delays, [30, 60, 120, 240, 240, 240]); |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn only_client_errors_other_than_auth_and_missing_are_permanent() { |
| 347 | assert!(is_permanent_failure(Some(400))); |
| 348 | assert!(is_permanent_failure(Some(403))); |
| 349 | assert!(!is_permanent_failure(Some(401))); |
| 350 | assert!(!is_permanent_failure(Some(404))); |
| 351 | assert!(!is_permanent_failure(Some(429))); |
| 352 | assert!(!is_permanent_failure(Some(500))); |
| 353 | assert!(!is_permanent_failure(None)); |
| 354 | } |
| 355 | |
| 356 | #[tokio::test] |
| 357 | async fn a_repeated_identical_failure_is_logged_once_and_backs_off() { |
| 358 | let error = chatsvc::Error::UnexpectedAnswer("x".into()); |
| 359 | let mut retry = RetryState::default(); |
| 360 | let now = Instant::now(); |
| 361 | assert!(retry.failed(now, &error).is_some()); |
| 362 | assert!(retry.failed(now, &error).is_none()); |
| 363 | assert!(!retry.may_attempt(now + seconds(59))); |
| 364 | assert!(retry.may_attempt(now + seconds(60))); |
| 365 | retry.succeeded(); |
| 366 | assert!(retry.may_attempt(now)); |
| 367 | } |
| 368 | |
| 369 | #[tokio::test] |
| 370 | async fn a_permanent_failure_retries_only_after_half_an_hour_or_a_new_endpoint() { |
| 371 | let (mut link, sent, _) = link(vec![403]); |
| 372 | link.apply(LinkSignal::Endpoint("a".into())).await; |
| 373 | link.reconcile(false).await; |
| 374 | assert_eq!(calls(&sent).len(), 1); |
| 375 | assert!(!link.retry.may_attempt(Instant::now() + seconds(29 * 60))); |
| 376 | assert!(link.retry.may_attempt(Instant::now() + seconds(31 * 60))); |
| 377 | link.apply(LinkSignal::Endpoint("b".into())).await; |
| 378 | assert_eq!(calls(&sent).len(), 3); |
| 379 | } |
| 380 | |
| 381 | #[tokio::test] |
| 382 | async fn the_same_endpoint_announced_again_is_not_registered_again() { |
| 383 | let (mut link, sent, resend) = link(vec![]); |
| 384 | link.apply(LinkSignal::Endpoint("a".into())).await; |
| 385 | link.apply(LinkSignal::Endpoint("a".into())).await; |
| 386 | link.apply(LinkSignal::Connected).await; |
| 387 | assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]); |
| 388 | tokio::time::timeout(Duration::from_millis(500), resend.notified()) |
| 389 | .await |
| 390 | .expect("resend"); |
| 391 | } |
| 392 | |
| 393 | #[tokio::test] |
| 394 | async fn a_new_endpoint_removes_the_old_one_first() { |
| 395 | let (mut link, sent, _) = link(vec![]); |
| 396 | link.apply(LinkSignal::Endpoint("a".into())).await; |
| 397 | link.apply(LinkSignal::Endpoint("b".into())).await; |
| 398 | assert_eq!( |
| 399 | calls(&sent), |
| 400 | [ |
| 401 | "PUT /endpoints/ Transport", |
| 402 | "DELETE /endpoints/a -", |
| 403 | "PUT /endpoints/ Transport" |
| 404 | ] |
| 405 | ); |
| 406 | } |
| 407 | |
| 408 | #[tokio::test] |
| 409 | async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() { |
| 410 | let (mut link, sent, resend) = link(vec![]); |
| 411 | link.apply(LinkSignal::Endpoint("a".into())).await; |
| 412 | tokio::time::timeout(Duration::from_millis(500), resend.notified()) |
| 413 | .await |
| 414 | .expect("resend"); |
| 415 | link.down_since = Some( |
| 416 | Instant::now() |
| 417 | .checked_sub(seconds(130)) |
| 418 | .unwrap_or_else(Instant::now), |
| 419 | ); |
| 420 | link.reconcile(false).await; |
| 421 | link.apply(LinkSignal::Connected).await; |
| 422 | assert_eq!( |
| 423 | calls(&sent), |
| 424 | [ |
| 425 | "PUT /endpoints/ Transport", |
| 426 | "PUT /endpoints/ Direct", |
| 427 | "POST /reportmyactivity/ -", |
| 428 | "PUT /endpoints/ Transport", |
| 429 | ] |
| 430 | ); |
| 431 | tokio::time::timeout(Duration::from_millis(500), resend.notified()) |
| 432 | .await |
| 433 | .expect("resend"); |
| 434 | } |
| 435 | |
| 436 | #[tokio::test] |
| 437 | async fn a_missing_endpoint_is_registered_again_before_the_report_is_repeated() { |
| 438 | let (link, sent, _) = link(vec![404, 200, 200]); |
| 439 | link.report_with_recovery("epid-1", true).await; |
| 440 | assert_eq!( |
| 441 | calls(&sent), |
| 442 | [ |
| 443 | "POST /reportmyactivity/ -", |
| 444 | "PUT /endpoints/ Direct", |
| 445 | "POST /reportmyactivity/ -", |
| 446 | ] |
| 447 | ); |
| 448 | } |
| 449 | } |