Skip to main content

agentmux_srv_core/muxbus/wan_presence/
machine.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The presence publisher's decisions, apart from its I/O. Given what just
5//! happened ([`Event`]) and the time ([`Now`]), [`Machine::next`] settles the
6//! state, says what to do ([`Action`]) and how long to wait before the next
7//! [`Event::Due`]. Nothing here reads a clock, a random number or the
8//! network, so every rule is tested with a fake clock; `super::Driver` runs
9//! it against the relay.
10//!
11//! | state | entered on | next try |
12//! |---|---|---|
13//! | `signed_out` | no MuxBus sign-in | a sign-in (a local recheck every minute, no request) |
14//! | `publishing` | the record was stored | a minute, or a change of the snapshot |
15//! | `retrying` | unreachable, 5xx, 429, any other status | 5 s doubling to 5 min, full jitter; a 429's `Retry-After` |
16//! | `unsupported` | 404, no presence route | about 5 min; at once on a sign-in, a network change, a wake, or a new relay version |
17//! | `rejected` | 400 or 410 | 10 min or more |
18//! | `signed_off` | a goodbye was stored at a sign-out | a sign-in |
19//! | `off` | this install doesn't publish (`super::policy`) | turned on |
20//!
21//! Outside `publishing` a change of the snapshot only marks it dirty: the
22//! next try sends the latest one, no sooner. A 409 means the relay already
23//! has a newer record of this install's, which is as good as storing this
24//! one.
25//!
26//! A goodbye (a v3 record, `gone`) is due when something was published and
27//! the relay takes v2 or later ([`Machine::farewell`]): an older relay would
28//! refuse v3, so it gets none. Turning publishing off says it here
29//! ([`Action::Goodbye`]); a sign-out and a quit say it from outside, and a
30//! sign-out tells the machine with [`Event::Goodbye`].
31//!
32//! Two refusals get an immediate second try before `rejected`: a record the
33//! relay can't parse is sent again one version down, v4 then v2 then v1 (an
34//! older relay knows no agent lines, an older one still no states), and the
35//! version it took is then kept for that relay for [`Config::v1_memory`]; a
36//! record whose time the relay refuses is sent again stamped with the
37//! relay's clock, learned from the `Date` of every answer.
38
39use std::collections::HashMap;
40use std::time::Duration;
41
42use crate::muxbus::install_presence::{PRESENCE_VERSION, PRESENCE_VERSION_LINES, PRESENCE_VERSION_V1};
43
44/// The version a fresh try sends to a relay not known to be older.
45pub(crate) const LIVE_VERSION: u32 = PRESENCE_VERSION_LINES;
46
47/// The version to try after `v` was refused as malformed, if any.
48fn step_down(v: u32) -> Option<u32> {
49    match v {
50        PRESENCE_VERSION_LINES => Some(PRESENCE_VERSION),
51        PRESENCE_VERSION => Some(PRESENCE_VERSION_V1),
52        _ => None,
53    }
54}
55
56use crate::backend::rpc_types::{PresenceOffReason, PresenceState, PresenceStatusResult};
57
58/// The relay's `error` for a record it can't parse, which is what a relay
59/// that predates the record's version answers.
60pub(crate) const MALFORMED_RECORD: &str = "Malformed install presence record";
61
62/// A clock further than this from the relay's is shown in the status.
63const CLOCK_NOTE_AFTER_MS: u64 = 2 * 60 * 1000;
64
65/// The waits, apart so tests can shorten them.
66#[derive(Debug, Clone)]
67pub(crate) struct Config {
68    /// Between two publishes of an unchanged record.
69    pub interval: Duration,
70    /// The first retry's ceiling; it doubles per failure.
71    pub backoff_base: Duration,
72    pub backoff_cap: Duration,
73    /// The least wait between retries, so full jitter never spins.
74    pub backoff_floor: Duration,
75    /// The longest `Retry-After` honoured.
76    pub retry_after_cap: Duration,
77    /// After a 404, jittered by a fifth either way.
78    pub unsupported_retry: Duration,
79    /// How often the relay's version is checked while `unsupported`.
80    pub health_every: Duration,
81    /// After a refusal, plus up to a fifth.
82    pub rejected_retry: Duration,
83    /// How often a signed-out publisher looks for a sign-in, locally.
84    pub signed_out_recheck: Duration,
85    /// How long a relay that took only v1 gets v1.
86    pub v1_memory: Duration,
87    /// An outage this long is logged as a warning, once.
88    pub outage_warn_after: Duration,
89}
90
91pub(crate) const LIVE: Config = Config {
92    interval: Duration::from_secs(60),
93    backoff_base: Duration::from_secs(5),
94    backoff_cap: Duration::from_secs(5 * 60),
95    backoff_floor: Duration::from_secs(1),
96    retry_after_cap: Duration::from_secs(60 * 60),
97    unsupported_retry: Duration::from_secs(5 * 60),
98    health_every: Duration::from_secs(60),
99    rejected_retry: Duration::from_secs(10 * 60),
100    signed_out_recheck: Duration::from_secs(60),
101    v1_memory: Duration::from_secs(6 * 60 * 60),
102    outage_warn_after: Duration::from_secs(10 * 60),
103};
104
105/// The time, as the driver read it. `mono_ms` only ever grows and drives the
106/// waits; `wall_ms` is this computer's clock, for the status and the record;
107/// `rand` is uniform in `[0, 1)`, for jitter.
108#[derive(Debug, Clone, Copy)]
109pub(crate) struct Now {
110    pub mono_ms: u64,
111    pub wall_ms: u64,
112    pub rand: f64,
113}
114
115/// What the relay made of one record.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub(crate) enum Answer {
118    /// 2xx.
119    Stored,
120    /// 404: the relay has no presence route.
121    NoRoute,
122    /// 400 [`MALFORMED_RECORD`].
123    Malformed,
124    /// 400 for the record's time: the relay's message.
125    ClockRefused(String),
126    /// Any other 400, a 410, or a record that couldn't be built: why.
127    Refused(String),
128    /// 429.
129    TooMany { retry_after: Option<Duration> },
130    /// Unreachable, 5xx or any other status: a short reason and the detail.
131    Unavailable { reason: String, detail: String },
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub(crate) enum Event {
136    /// The publisher started.
137    Start,
138    /// The last wait ran out.
139    Due,
140    /// The snapshot changed (while publishing: after the debounce).
141    Changed,
142    /// A try found no sign-in; nothing was sent.
143    NoSignIn,
144    /// A record of version `sent_v` was sent. `relay_date_ms` is the answer's
145    /// `Date`, when it had a readable one.
146    Answer { sent_v: u32, answer: Answer, relay_date_ms: Option<u64> },
147    /// The relay's health check: its version, `None` when it failed.
148    Health { version: Option<String>, relay_date_ms: Option<u64> },
149    /// A sign-in, a sign-out or a new account.
150    SignIn,
151    /// This computer's network addresses changed.
152    NetworkChanged,
153    /// This computer woke from sleep.
154    Woke,
155    /// "Publish now": forget the backoff and try at once.
156    PublishNow,
157    /// Whether this install publishes: `None` to publish, else why not.
158    Policy { off: Option<PresenceOffReason> },
159    /// The settings changed: the driver reads the policy again and passes
160    /// it on as [`Event::Policy`]; the machine itself ignores this.
161    SettingsChanged,
162    /// A goodbye went out (from [`Action::Goodbye`], or a sign-out); `stored`
163    /// when the relay took it.
164    Goodbye { stored: bool },
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub(crate) enum Action {
169    /// Nothing; wait [`Step::wait`].
170    Wait,
171    /// Send the latest snapshot as a record of version `v`.
172    Attempt { v: u32 },
173    /// Ask the relay its version.
174    CheckHealth,
175    /// Send the goodbye, stamped `published_at_ms`, then report
176    /// [`Event::Goodbye`].
177    Goodbye { published_at_ms: u64 },
178}
179
180/// A goodbye is due, stamped on the relay's clock as far as it is known.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub(crate) struct Farewell {
183    offset_ms: i64,
184}
185
186impl Farewell {
187    /// `published_at_ms` for a goodbye sent at `wall_ms`.
188    pub(crate) fn stamp(&self, wall_ms: u64) -> u64 {
189        u64::try_from(wall_ms as i64 + self.offset_ms).unwrap_or(0)
190    }
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub(crate) struct Log {
195    pub warn: bool,
196    pub text: String,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub(crate) struct Step {
201    pub action: Action,
202    /// Until the next [`Event::Due`]; meaningful when `action` is `Wait`.
203    pub wait: Duration,
204    pub logs: Vec<Log>,
205}
206
207/// The second tries already spent on the record being sent.
208#[derive(Debug, Default, Clone, Copy)]
209struct Followups {
210    /// The record was sent again one version down at least once.
211    stepped_down: bool,
212    clock: bool,
213}
214
215#[derive(Debug)]
216pub(crate) struct Machine {
217    config: Config,
218    relay: String,
219    /// `None` until the first state is entered.
220    state: Option<PresenceState>,
221    since_wall_ms: u64,
222    reason: Option<String>,
223    last_ok_wall_ms: Option<u64>,
224    failures: u32,
225    due_ms: u64,
226    health_due_ms: Option<u64>,
227    dirty: bool,
228    followups: Followups,
229    /// Relays that took only an older version: which, and until when.
230    older_until_ms: HashMap<String, (u32, u64)>,
231    offset_ms: Option<i64>,
232    relay_version: Option<String>,
233    /// The relay's version just after its 404.
234    version_at_404: Option<String>,
235    outage_since_ms: Option<u64>,
236    outage_warned: bool,
237    /// Why this install doesn't publish; `None` while it does.
238    off: Option<PresenceOffReason>,
239    /// This machine asked for a goodbye ([`Action::Goodbye`]) whose result
240    /// hasn't come back yet. A sign-out reports [`Event::Goodbye`] too, even
241    /// when none was due, so only this says the result is worth logging.
242    goodbye_sent: bool,
243}
244
245fn ms(d: Duration) -> u64 {
246    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
247}
248
249fn scaled(d: Duration, factor: f64) -> u64 {
250    (ms(d) as f64 * factor) as u64
251}
252
253/// "12 min", rounded, at least 1.
254fn minutes(ms: u64) -> u64 {
255    ((ms + 30_000) / 60_000).max(1)
256}
257
258impl Machine {
259    pub(crate) fn new(config: Config, relay: &str) -> Self {
260        Self {
261            config,
262            relay: relay.trim_end_matches('/').to_string(),
263            state: None,
264            since_wall_ms: 0,
265            reason: None,
266            last_ok_wall_ms: None,
267            failures: 0,
268            due_ms: 0,
269            health_due_ms: None,
270            dirty: false,
271            followups: Followups::default(),
272            older_until_ms: HashMap::new(),
273            offset_ms: None,
274            relay_version: None,
275            version_at_404: None,
276            outage_since_ms: None,
277            outage_warned: false,
278            off: None,
279            goodbye_sent: false,
280        }
281    }
282
283    #[cfg(test)]
284    pub(crate) fn state(&self) -> Option<PresenceState> {
285        self.state
286    }
287
288    /// Whether a snapshot change is published (after the debounce), rather
289    /// than only marked dirty.
290    pub(crate) fn follows_changes(&self) -> bool {
291        self.state == Some(PresenceState::Publishing)
292    }
293
294    #[cfg(test)]
295    pub(crate) fn dirty(&self) -> bool {
296        self.dirty
297    }
298
299    #[cfg(test)]
300    pub(crate) fn set_relay(&mut self, relay: &str) {
301        self.relay = relay.trim_end_matches('/').to_string();
302    }
303
304    /// `published_at_ms` for a record sent at `wall_ms`: on the relay's
305    /// clock when an answer has told it, else this computer's.
306    pub(crate) fn stamp(&self, wall_ms: u64) -> u64 {
307        Farewell { offset_ms: self.offset_ms.unwrap_or(0) }.stamp(wall_ms)
308    }
309
310    /// Whether a goodbye is due if this install went away now: something
311    /// was published, publishing is on and no goodbye has been said since,
312    /// and the relay takes v2 or later (one that took only v1 would refuse v3).
313    pub(crate) fn farewell(&self, now: &Now) -> Option<Farewell> {
314        let due = self.off.is_none()
315            && self.state != Some(PresenceState::SignedOff)
316            && self.last_ok_wall_ms.is_some()
317            && self.record_version(now) >= PRESENCE_VERSION;
318        due.then(|| Farewell { offset_ms: self.offset_ms.unwrap_or(0) })
319    }
320
321    /// The version a fresh try sends: an older one while this relay is
322    /// remembered as taking only that.
323    pub(crate) fn record_version(&self, now: &Now) -> u32 {
324        match self.older_until_ms.get(&self.relay) {
325            Some(&(v, until)) if now.mono_ms < until => v,
326            _ => LIVE_VERSION,
327        }
328    }
329
330    pub(crate) fn next(&mut self, event: Event, now: Now) -> Step {
331        let mut logs = Vec::new();
332        let action = if self.off.is_some() {
333            self.next_while_off(event, &now, &mut logs)
334        } else {
335            self.next_while_on(event, now, &mut logs)
336        };
337        self.warn_long_outage(&now, &mut logs);
338        let due = match self.health_due_ms {
339            Some(h) if self.state == Some(PresenceState::Unsupported) => self.due_ms.min(h),
340            _ => self.due_ms,
341        };
342        Step { action, wait: Duration::from_millis(due.saturating_sub(now.mono_ms)), logs }
343    }
344
345    /// Off: nothing is sent until publishing is turned on again; a goodbye
346    /// in flight when it was turned off lands here.
347    fn next_while_off(&mut self, event: Event, now: &Now, logs: &mut Vec<Log>) -> Action {
348        match event {
349            Event::Policy { off: None } => {
350                self.off = None;
351                self.failures = 0;
352                logs.push(Log { warn: false, text: "publishing is on".into() });
353                self.attempt(None, now)
354            }
355            Event::Policy { off: Some(reason) } => {
356                self.enter_off(reason, now, logs);
357                Action::Wait
358            }
359            Event::Goodbye { stored } => {
360                let reason = self.off.unwrap_or(PresenceOffReason::Setting);
361                if std::mem::take(&mut self.goodbye_sent) {
362                    logs.push(Log { warn: false, text: goodbye_text(stored).into() });
363                }
364                self.enter_off(reason, now, logs);
365                Action::Wait
366            }
367            Event::Changed => {
368                self.dirty = true;
369                Action::Wait
370            }
371            // Nothing is due while off, but a deadline left in the past makes the
372            // next wait zero and the driver loop at full speed.
373            Event::Due => {
374                self.due_ms = now.mono_ms + ms(self.config.interval);
375                Action::Wait
376            }
377            _ => Action::Wait,
378        }
379    }
380
381    /// Stop publishing for `reason`; one log line per new reason.
382    fn enter_off(&mut self, reason: PresenceOffReason, now: &Now, logs: &mut Vec<Log>) {
383        let changed = self.off != Some(reason) || self.state != Some(PresenceState::Off);
384        self.off = Some(reason);
385        self.failures = 0;
386        self.dirty = false;
387        let text = format!("off: {}", off_text(reason));
388        let before = logs.len();
389        self.enter(PresenceState::Off, None, &text, now, logs);
390        if changed && logs.len() == before {
391            logs.push(Log { warn: false, text });
392        }
393        self.due_ms = now.mono_ms + ms(self.config.interval);
394    }
395
396    fn next_while_on(&mut self, event: Event, now: Now, logs: &mut Vec<Log>) -> Action {
397        match event {
398            Event::Policy { off: None } | Event::SettingsChanged => {
399                if self.state.is_none() {
400                    self.attempt(None, &now)
401                } else {
402                    Action::Wait
403                }
404            }
405            Event::Policy { off: Some(reason) } => match self.farewell(&now) {
406                Some(farewell) => {
407                    self.off = Some(reason);
408                    self.goodbye_sent = true;
409                    Action::Goodbye { published_at_ms: farewell.stamp(now.wall_ms) }
410                }
411                None => {
412                    self.enter_off(reason, &now, logs);
413                    Action::Wait
414                }
415            },
416            Event::Goodbye { stored: true } => {
417                self.failures = 0;
418                self.enter(PresenceState::SignedOff, None, goodbye_text(true), &now, logs);
419                self.due_ms = now.mono_ms + ms(self.config.signed_out_recheck);
420                Action::Wait
421            }
422            Event::Goodbye { stored: false } => {
423                self.failures = 0;
424                self.attempt(None, &now)
425            }
426            Event::Start => self.attempt(None, &now),
427            Event::PublishNow | Event::SignIn => {
428                self.failures = 0;
429                self.attempt(None, &now)
430            }
431            Event::Due => {
432                let health_first = self.state == Some(PresenceState::Unsupported) && now.mono_ms < self.due_ms;
433                if health_first {
434                    self.health_due_ms = None;
435                    Action::CheckHealth
436                } else {
437                    self.attempt(None, &now)
438                }
439            }
440            Event::Changed => {
441                if self.follows_changes() {
442                    self.attempt(None, &now)
443                } else {
444                    self.dirty = true;
445                    Action::Wait
446                }
447            }
448            Event::NetworkChanged | Event::Woke => match self.state {
449                Some(PresenceState::Publishing | PresenceState::Retrying | PresenceState::Unsupported) => {
450                    self.attempt(None, &now)
451                }
452                _ => Action::Wait,
453            },
454            Event::NoSignIn => {
455                self.failures = 0;
456                // After a goodbye, "signed off" says more than "signed out".
457                if self.state != Some(PresenceState::SignedOff) {
458                    let text = "not signed in to MuxBus, nothing is published";
459                    self.enter(PresenceState::SignedOut, None, text, &now, logs);
460                }
461                self.due_ms = now.mono_ms + ms(self.config.signed_out_recheck);
462                Action::Wait
463            }
464            Event::Health { version, relay_date_ms } => {
465                self.observe_date(relay_date_ms, &now, logs);
466                self.on_health(version, &now, logs)
467            }
468            Event::Answer { sent_v, answer, relay_date_ms } => {
469                self.observe_date(relay_date_ms, &now, logs);
470                self.on_answer(sent_v, answer, &now, logs)
471            }
472        }
473    }
474
475    /// Send the latest snapshot. `v` is set for a second try of the same
476    /// record; a fresh try forgets the second tries spent.
477    fn attempt(&mut self, v: Option<u32>, now: &Now) -> Action {
478        if v.is_none() {
479            self.followups = Followups::default();
480        }
481        self.dirty = false;
482        Action::Attempt { v: v.unwrap_or_else(|| self.record_version(now)) }
483    }
484
485    fn on_answer(&mut self, sent_v: u32, answer: Answer, now: &Now, logs: &mut Vec<Log>) -> Action {
486        match answer {
487            Answer::Stored => {
488                if self.followups.stepped_down {
489                    let until = now.mono_ms + ms(self.config.v1_memory);
490                    self.older_until_ms.insert(self.relay.clone(), (sent_v, until));
491                }
492                self.failures = 0;
493                self.last_ok_wall_ms = Some(now.wall_ms);
494                let text = match sent_v {
495                    PRESENCE_VERSION_V1 => "published, as v1: the relay is on an older version and gets no agent states",
496                    PRESENCE_VERSION => "published, as v2: the relay is on an older version and gets no agent summaries",
497                    _ => "published",
498                };
499                self.enter(PresenceState::Publishing, None, text, now, logs);
500                self.due_ms = now.mono_ms + ms(self.config.interval);
501                Action::Wait
502            }
503            Answer::Malformed if step_down(sent_v).is_some() => {
504                self.followups.stepped_down = true;
505                self.attempt(step_down(sent_v), now)
506            }
507            Answer::ClockRefused(_) if !self.followups.clock => {
508                self.followups.clock = true;
509                self.attempt(Some(sent_v), now)
510            }
511            Answer::Malformed => self.reject(MALFORMED_RECORD.to_string(), now, logs),
512            Answer::ClockRefused(why) | Answer::Refused(why) => self.reject(why, now, logs),
513            Answer::NoRoute => {
514                self.enter(
515                    PresenceState::Unsupported,
516                    Some("the relay has no presence route yet".into()),
517                    "the relay has no presence route yet, checking again within minutes",
518                    now,
519                    logs,
520                );
521                self.due_ms = now.mono_ms + scaled(self.config.unsupported_retry, 0.8 + 0.4 * now.rand);
522                // A version to compare later ones with, read now.
523                self.version_at_404 = None;
524                self.health_due_ms = None;
525                Action::CheckHealth
526            }
527            Answer::TooMany { retry_after } => {
528                self.failures = self.failures.saturating_add(1);
529                let wait = match retry_after {
530                    Some(d) => ms(d.min(self.config.retry_after_cap)).max(ms(self.config.backoff_floor)),
531                    None => self.backoff(now),
532                };
533                let reason = "too many requests".to_string();
534                let text = format!("retrying: {reason}");
535                self.enter(PresenceState::Retrying, Some(reason), &text, now, logs);
536                self.due_ms = now.mono_ms + wait;
537                Action::Wait
538            }
539            Answer::Unavailable { reason, detail } => {
540                self.failures = self.failures.saturating_add(1);
541                let wait = self.backoff(now);
542                let text = format!("retrying: {reason} ({detail})");
543                self.enter(PresenceState::Retrying, Some(reason), &text, now, logs);
544                self.due_ms = now.mono_ms + wait;
545                Action::Wait
546            }
547        }
548    }
549
550    fn reject(&mut self, why: String, now: &Now, logs: &mut Vec<Log>) -> Action {
551        let text = format!("the relay refused the record: {why}");
552        self.enter(PresenceState::Rejected, Some(why), &text, now, logs);
553        self.due_ms = now.mono_ms + scaled(self.config.rejected_retry, 1.0 + 0.2 * now.rand);
554        Action::Wait
555    }
556
557    fn on_health(&mut self, version: Option<String>, now: &Now, logs: &mut Vec<Log>) -> Action {
558        if let Some(v) = &version {
559            self.relay_version = Some(v.clone());
560        }
561        if self.state != Some(PresenceState::Unsupported) {
562            return Action::Wait;
563        }
564        match (version, &self.version_at_404) {
565            (Some(v), Some(before)) if v != *before => {
566                logs.push(Log { warn: false, text: format!("the relay moved from {before} to {v}, trying again") });
567                self.attempt(None, now)
568            }
569            (Some(v), None) => {
570                self.version_at_404 = Some(v);
571                self.health_due_ms = Some(now.mono_ms + ms(self.config.health_every));
572                Action::Wait
573            }
574            _ => {
575                self.health_due_ms = Some(now.mono_ms + ms(self.config.health_every));
576                Action::Wait
577            }
578        }
579    }
580
581    /// Full jitter: anywhere up to `base * 2^(failures - 1)`, capped, but no
582    /// less than the floor.
583    fn backoff(&self, now: &Now) -> u64 {
584        let doublings = self.failures.saturating_sub(1).min(20);
585        let ceiling = ms(self.config.backoff_base).saturating_mul(1 << doublings).min(ms(self.config.backoff_cap));
586        ((ceiling as f64 * now.rand) as u64).max(ms(self.config.backoff_floor))
587    }
588
589    /// Learn the relay's clock from an answer's `Date`.
590    fn observe_date(&mut self, relay_date_ms: Option<u64>, now: &Now, logs: &mut Vec<Log>) {
591        let Some(date) = relay_date_ms else { return };
592        let skewed_before = self.clock_skewed();
593        self.offset_ms = Some(date as i64 - now.wall_ms as i64);
594        if self.clock_skewed() && !skewed_before {
595            let off = self.offset_ms.unwrap_or(0).unsigned_abs();
596            logs.push(Log {
597                warn: false,
598                text: format!("this computer's clock differs from the relay's by {} min; records carry the relay's time", minutes(off)),
599            });
600        }
601    }
602
603    fn clock_skewed(&self) -> bool {
604        self.offset_ms.is_some_and(|o| o.unsigned_abs() > CLOCK_NOTE_AFTER_MS)
605    }
606
607    /// Enter `state` for `reason`; one log line when the state changes.
608    fn enter(&mut self, state: PresenceState, reason: Option<String>, text: &str, now: &Now, logs: &mut Vec<Log>) {
609        let failing = matches!(state, PresenceState::Retrying | PresenceState::Unsupported | PresenceState::Rejected);
610        if failing {
611            self.outage_since_ms.get_or_insert(now.mono_ms);
612        } else {
613            self.outage_since_ms = None;
614            self.outage_warned = false;
615        }
616        if state != PresenceState::Unsupported {
617            self.health_due_ms = None;
618        }
619        self.reason = reason;
620        if self.state != Some(state) {
621            self.state = Some(state);
622            self.since_wall_ms = now.wall_ms;
623            logs.push(Log { warn: false, text: text.to_string() });
624        }
625    }
626
627    fn warn_long_outage(&mut self, now: &Now, logs: &mut Vec<Log>) {
628        let Some(since) = self.outage_since_ms else { return };
629        let lasted = now.mono_ms.saturating_sub(since);
630        if self.outage_warned || lasted < ms(self.config.outage_warn_after) {
631            return;
632        }
633        self.outage_warned = true;
634        let why = self.reason.as_deref().unwrap_or("unknown");
635        logs.push(Log { warn: true, text: format!("not published for {} min: {why}", minutes(lasted)) });
636    }
637
638    /// The status for `presence.status`; `None` before the first state.
639    pub(crate) fn status(&self, now: &Now) -> Option<PresenceStatusResult> {
640        let state = self.state?;
641        let waits_for_nothing =
642            matches!(state, PresenceState::SignedOut | PresenceState::SignedOff | PresenceState::Off);
643        let next_try_ms = (!waits_for_nothing).then(|| now.wall_ms + self.due_ms.saturating_sub(now.mono_ms));
644        let mut notes = Vec::new();
645        if self.clock_skewed() {
646            let off = self.offset_ms.unwrap_or(0).unsigned_abs();
647            notes.push(format!("Your clock differs from the cloud's by {} min", minutes(off)));
648        }
649        let record_version = self.record_version(now);
650        if record_version == PRESENCE_VERSION_V1 {
651            notes.push("The cloud runs an older version, so your devices don't see agent states".to_string());
652        } else if record_version == PRESENCE_VERSION {
653            notes.push("The cloud runs an older version, so your devices don't see agent summaries".to_string());
654        }
655        Some(PresenceStatusResult {
656            state,
657            since_ms: self.since_wall_ms,
658            last_ok_ms: self.last_ok_wall_ms,
659            last_error: self.reason.clone(),
660            next_try_ms,
661            relay_version: self.relay_version.clone(),
662            offset_ms: self.offset_ms,
663            record_version,
664            note: (!notes.is_empty()).then(|| notes.join(". ")),
665            off_reason: if state == PresenceState::Off { self.off } else { None },
666        })
667    }
668}
669
670fn goodbye_text(stored: bool) -> &'static str {
671    if stored {
672        "said goodbye: devices show this computer as offline"
673    } else {
674        "the goodbye didn't reach the relay; devices notice in a few minutes"
675    }
676}
677
678fn off_text(reason: PresenceOffReason) -> &'static str {
679    match reason {
680        PresenceOffReason::Setting => "turned off in Settings",
681        PresenceOffReason::DevBuild => "a dev build doesn't publish",
682        PresenceOffReason::Headless => "a headless install doesn't publish",
683        PresenceOffReason::IsolatedHome => "an isolated home doesn't publish",
684        PresenceOffReason::TestHarness => "an install under test doesn't publish",
685    }
686}
687
688/// What the relay's status and `error` mean for the publisher.
689pub(crate) fn classify(status: u16, error: Option<&str>, retry_after: Option<Duration>) -> Answer {
690    let said = || error.unwrap_or_default().to_string();
691    match status {
692        200..=299 => Answer::Stored,
693        // Newest wins on the relay: it has a newer record of this install's.
694        409 => Answer::Stored,
695        404 => Answer::NoRoute,
696        400 if error == Some(MALFORMED_RECORD) => Answer::Malformed,
697        // The relay names the field when it refuses the record's time.
698        400 if error.is_some_and(|e| e.contains("published_at_ms")) => Answer::ClockRefused(said()),
699        400 | 410 => Answer::Refused(error.map_or_else(|| format!("the relay answered {status}"), str::to_string)),
700        429 => Answer::TooMany { retry_after },
701        _ => Answer::Unavailable { reason: format!("the cloud answered {status}"), detail: said() },
702    }
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    const S: u64 = 1000;
710    const MIN: u64 = 60 * S;
711
712    /// A machine at mono 0, wall `WALL`, that has just stored a record.
713    const WALL: u64 = 1_791_000_000_000;
714
715    fn at(mono_ms: u64) -> Now {
716        Now { mono_ms, wall_ms: WALL + mono_ms, rand: 0.5 }
717    }
718
719    fn at_rand(mono_ms: u64, rand: f64) -> Now {
720        Now { rand, ..at(mono_ms) }
721    }
722
723    fn answer(answer: Answer) -> Event {
724        Event::Answer { sent_v: 4, answer, relay_date_ms: None }
725    }
726
727    fn unreachable() -> Event {
728        answer(Answer::Unavailable { reason: "cloud unreachable".into(), detail: "connection refused".into() })
729    }
730
731    fn machine() -> Machine {
732        Machine::new(LIVE, "https://relay.test")
733    }
734
735    fn publishing() -> Machine {
736        let mut m = machine();
737        assert_eq!(m.next(Event::Start, at(0)).action, Action::Attempt { v: 4 });
738        m.next(answer(Answer::Stored), at(0));
739        m
740    }
741
742    fn secs(d: Duration) -> u64 {
743        d.as_secs()
744    }
745
746    #[test]
747    fn an_off_machine_sleeps_between_looks_instead_of_spinning() {
748        // Off nothing is sent, but the driver still wakes at each Due. If a Due left
749        // the deadline in the past the next wait would be zero and the driver would
750        // loop at full speed, which an isolated home, a dev build, a headless srv or
751        // a user who turned publishing off all paid for.
752        let mut m = machine();
753        let step = m.next(Event::Policy { off: Some(PresenceOffReason::IsolatedHome) }, at(0));
754        assert_eq!((step.action, step.wait), (Action::Wait, Duration::from_secs(60)));
755        for minute in 1..=3 {
756            let step = m.next(Event::Due, at(minute * MIN));
757            assert_eq!(step.action, Action::Wait);
758            assert_eq!(step.wait, Duration::from_secs(60), "after the Due at minute {minute}");
759        }
760    }
761
762    #[test]
763    fn a_stored_record_publishes_again_in_a_minute() {
764        let mut m = machine();
765        let step = m.next(answer(Answer::Stored), at(0));
766        assert_eq!(m.state(), Some(PresenceState::Publishing));
767        assert_eq!((step.action, step.wait), (Action::Wait, Duration::from_secs(60)));
768        assert_eq!(step.logs, vec![Log { warn: false, text: "published".into() }]);
769        assert_eq!(m.next(Event::Due, at(60 * S)).action, Action::Attempt { v: 4 });
770    }
771
772    #[test]
773    fn while_publishing_a_change_is_sent_after_the_drivers_debounce() {
774        let mut m = publishing();
775        assert!(m.follows_changes());
776        assert_eq!(m.next(Event::Changed, at(5 * S)).action, Action::Attempt { v: 4 });
777    }
778
779    #[test]
780    fn no_sign_in_sends_nothing_and_rechecks_locally() {
781        let mut m = machine();
782        let step = m.next(Event::NoSignIn, at(0));
783        assert_eq!(m.state(), Some(PresenceState::SignedOut));
784        assert_eq!((step.action, step.wait), (Action::Wait, Duration::from_secs(60)));
785        assert_eq!(m.status(&at(0)).unwrap().next_try_ms, None, "no try is promised while signed out");
786        assert_eq!(m.next(Event::Changed, at(S)).action, Action::Wait, "a change while signed out sends nothing");
787        assert_eq!(m.next(Event::Woke, at(2 * S)).action, Action::Wait);
788        assert_eq!(m.next(Event::SignIn, at(3 * S)).action, Action::Attempt { v: 4 }, "a sign-in tries at once");
789    }
790
791    #[test]
792    fn failures_back_off_exponentially_to_five_minutes() {
793        let mut m = machine();
794        // rand just under 1: the ceiling itself.
795        let ceilings: Vec<u64> = (0..9).map(|i| secs(m.next(unreachable(), at_rand(i * S, 0.999_999)).wait)).collect();
796        assert_eq!(ceilings, vec![4, 9, 19, 39, 79, 159, 299, 299, 299], "5 s, 10 s, 20 s ... capped at 300 s, less the rounding");
797        assert_eq!(m.state(), Some(PresenceState::Retrying));
798    }
799
800    #[test]
801    fn backoff_is_full_jitter_with_a_floor() {
802        for (rand, expect_ms) in [(0.0, 1000), (0.1, 1000), (0.5, 2500), (0.9, 4500)] {
803            let mut m = machine();
804            assert_eq!(m.next(unreachable(), at_rand(0, rand)).wait, Duration::from_millis(expect_ms), "rand {rand}");
805        }
806        // The fourth failure: every draw inside [floor, 40 s].
807        for i in 0..100 {
808            let mut probe = Machine { failures: 3, ..machine() };
809            let wait = probe.next(unreachable(), at_rand(0, i as f64 / 100.0)).wait;
810            assert!(wait >= Duration::from_secs(1) && wait <= Duration::from_secs(40), "{wait:?}");
811        }
812    }
813
814    #[test]
815    fn a_success_resets_the_backoff() {
816        let mut m = machine();
817        for i in 0..5 {
818            m.next(unreachable(), at(i));
819        }
820        m.next(answer(Answer::Stored), at(10 * S));
821        let wait = m.next(unreachable(), at_rand(20 * S, 0.999_999)).wait;
822        assert_eq!(secs(wait), 4, "back to the first step");
823    }
824
825    #[test]
826    fn a_429_honours_retry_after_and_otherwise_backs_off() {
827        let mut m = machine();
828        let step = m.next(answer(Answer::TooMany { retry_after: Some(Duration::from_secs(90)) }), at(0));
829        assert_eq!(m.state(), Some(PresenceState::Retrying));
830        assert_eq!(step.wait, Duration::from_secs(90), "Retry-After past the backoff ceiling is still honoured");
831        let step = m.next(answer(Answer::TooMany { retry_after: None }), at_rand(0, 0.999_999));
832        assert_eq!(secs(step.wait), 9, "the second failure's backoff");
833        let step = m.next(answer(Answer::TooMany { retry_after: Some(Duration::from_secs(86_400)) }), at(0));
834        assert_eq!(step.wait, Duration::from_secs(3600), "a day is capped");
835        assert_eq!(m.status(&at(0)).unwrap().last_error.as_deref(), Some("too many requests"));
836    }
837
838    #[test]
839    fn a_404_waits_about_five_minutes_not_an_hour() {
840        for rand in [0.0, 0.5, 0.999_999] {
841            let mut m = machine();
842            let step = m.next(answer(Answer::NoRoute), at_rand(0, rand));
843            assert_eq!(m.state(), Some(PresenceState::Unsupported));
844            assert_eq!(step.action, Action::CheckHealth, "the relay's version is read at once");
845            let step = m.next(Event::Health { version: Some("1.0.0".into()), relay_date_ms: None }, at_rand(0, rand));
846            assert_eq!(step.wait, Duration::from_secs(60), "the next version check comes first");
847            // Version checks every minute until the retry is due.
848            let mut t = 0;
849            loop {
850                t += 60 * S;
851                let step = m.next(Event::Due, at(t));
852                if step.action != Action::CheckHealth {
853                    assert_eq!(step.action, Action::Attempt { v: 4 });
854                    break;
855                }
856                m.next(Event::Health { version: Some("1.0.0".into()), relay_date_ms: None }, at(t));
857            }
858        }
859        // The retry itself lands in [4 min, 6 min].
860        for rand in [0.0, 0.25, 0.5, 0.75, 0.999_999] {
861            let mut m = machine();
862            m.next(answer(Answer::NoRoute), at_rand(0, rand));
863            let retry_ms = m.status(&at(0)).unwrap().next_try_ms.unwrap() - WALL;
864            assert!((4 * MIN..=6 * MIN).contains(&retry_ms), "rand {rand}: {retry_ms}");
865        }
866    }
867
868    #[test]
869    fn a_404_is_cut_short_by_a_sign_in_a_network_change_a_wake_or_publish_now() {
870        for event in [Event::SignIn, Event::NetworkChanged, Event::Woke, Event::PublishNow] {
871            let mut m = machine();
872            m.next(answer(Answer::NoRoute), at(0));
873            m.next(Event::Health { version: Some("1.0.0".into()), relay_date_ms: None }, at(0));
874            assert_eq!(m.next(event.clone(), at(5 * S)).action, Action::Attempt { v: 4 }, "{event:?}");
875        }
876    }
877
878    #[test]
879    fn a_404_is_cut_short_by_a_new_relay_version() {
880        let mut m = machine();
881        m.next(answer(Answer::NoRoute), at(0));
882        m.next(Event::Health { version: Some("1.0.0".into()), relay_date_ms: None }, at(0));
883        assert_eq!(m.next(Event::Due, at(60 * S)).action, Action::CheckHealth);
884        let step = m.next(Event::Health { version: Some("1.0.0".into()), relay_date_ms: None }, at(60 * S));
885        assert_eq!(step.action, Action::Wait, "the same version: keep waiting");
886        assert_eq!(m.next(Event::Due, at(120 * S)).action, Action::CheckHealth);
887        let step = m.next(Event::Health { version: None, relay_date_ms: None }, at(120 * S));
888        assert_eq!(step.action, Action::Wait, "a failed check changes nothing");
889        assert_eq!(m.next(Event::Due, at(180 * S)).action, Action::CheckHealth);
890        let step = m.next(Event::Health { version: Some("1.1.0".into()), relay_date_ms: None }, at(180 * S));
891        assert_eq!(step.action, Action::Attempt { v: 4 });
892        assert_eq!(m.status(&at(180 * S)).unwrap().relay_version.as_deref(), Some("1.1.0"));
893        // Still 404 on the new version: that version is the new baseline.
894        assert_eq!(m.next(answer(Answer::NoRoute), at(181 * S)).action, Action::CheckHealth);
895        let step = m.next(Event::Health { version: Some("1.1.0".into()), relay_date_ms: None }, at(181 * S));
896        assert_eq!(step.action, Action::Wait);
897    }
898
899    #[test]
900    fn version_checks_come_at_most_once_a_minute() {
901        let mut m = machine();
902        m.next(answer(Answer::NoRoute), at(0));
903        m.next(Event::Health { version: Some("1".into()), relay_date_ms: None }, at(0));
904        // A change in between brings the next check no closer.
905        assert_eq!(m.next(Event::Changed, at(10 * S)).wait, Duration::from_secs(50));
906    }
907
908    #[test]
909    fn a_change_while_failing_only_marks_the_record_dirty() {
910        for setup in [unreachable(), answer(Answer::NoRoute), answer(Answer::Refused("nope".into()))] {
911            let mut m = machine();
912            m.next(setup.clone(), at(0));
913            let before = m.next(Event::Changed, at(S));
914            assert_eq!(before.action, Action::Wait, "{setup:?}");
915            assert!(m.dirty());
916            let again = m.next(Event::Changed, at(2 * S));
917            assert_eq!(again.wait + Duration::from_secs(1), before.wait, "the wait runs on, not restarted");
918            assert!(!m.follows_changes());
919        }
920        let mut m = machine();
921        m.next(unreachable(), at(0));
922        m.next(Event::Changed, at(100));
923        let step = m.next(Event::Due, at(10 * S));
924        assert_eq!(step.action, Action::Attempt { v: 4 }, "the next try sends the latest");
925        assert!(!m.dirty());
926    }
927
928    #[test]
929    fn a_refusal_is_retried_at_most_every_ten_minutes() {
930        for rand in [0.0, 0.5, 0.999_999] {
931            let mut m = machine();
932            let step = m.next(answer(Answer::Refused("not signed by its instance".into())), at_rand(0, rand));
933            assert_eq!(m.state(), Some(PresenceState::Rejected));
934            assert!(step.wait >= Duration::from_secs(600) && step.wait <= Duration::from_secs(720), "{:?}", step.wait);
935            assert_eq!(m.next(Event::Woke, at(S)).action, Action::Wait, "a wake doesn't fix a refusal");
936            assert_eq!(m.next(Event::NetworkChanged, at(S)).action, Action::Wait);
937            assert_eq!(m.status(&at(S)).unwrap().last_error.as_deref(), Some("not signed by its instance"));
938        }
939        let mut m = machine();
940        m.next(answer(Answer::Refused("x".into())), at(0));
941        assert_eq!(m.next(Event::PublishNow, at(S)).action, Action::Attempt { v: 4 }, "but the user may ask");
942    }
943
944    #[test]
945    fn a_malformed_record_is_sent_again_one_version_down_until_v1() {
946        let mut m = publishing();
947        assert_eq!(m.next(Event::Due, at(60 * S)).action, Action::Attempt { v: 4 });
948        let step = m.next(answer(Answer::Malformed), at(60 * S));
949        assert_eq!(step.action, Action::Attempt { v: 2 });
950        assert_eq!(m.state(), Some(PresenceState::Publishing), "no state change for the second try");
951        let step = m.next(Event::Answer { sent_v: 2, answer: Answer::Malformed, relay_date_ms: None }, at(60 * S));
952        assert_eq!(step.action, Action::Attempt { v: 1 });
953        let step = m.next(Event::Answer { sent_v: 1, answer: Answer::Malformed, relay_date_ms: None }, at(60 * S));
954        assert_eq!(step.action, Action::Wait, "v1 failing too: no third try");
955        assert_eq!(m.state(), Some(PresenceState::Rejected));
956        assert_eq!(m.status(&at(60 * S)).unwrap().record_version, 4, "nothing remembered");
957    }
958
959    #[test]
960    fn a_relay_that_took_v1_gets_v1_for_six_hours() {
961        let mut m = machine();
962        m.next(Event::Start, at(0));
963        assert_eq!(m.next(answer(Answer::Malformed), at(0)).action, Action::Attempt { v: 2 });
964        let malformed_v2 = Event::Answer { sent_v: 2, answer: Answer::Malformed, relay_date_ms: None };
965        assert_eq!(m.next(malformed_v2, at(0)).action, Action::Attempt { v: 1 });
966        let step = m.next(Event::Answer { sent_v: 1, answer: Answer::Stored, relay_date_ms: None }, at(0));
967        assert_eq!(m.state(), Some(PresenceState::Publishing));
968        assert!(step.logs[0].text.contains("as v1"), "{:?}", step.logs);
969        let status = m.status(&at(0)).unwrap();
970        assert_eq!(status.record_version, 1);
971        assert!(status.note.as_deref().unwrap().contains("older version"), "{status:?}");
972
973        assert_eq!(m.next(Event::Due, at(60 * S)).action, Action::Attempt { v: 1 });
974        m.next(Event::Answer { sent_v: 1, answer: Answer::Stored, relay_date_ms: None }, at(60 * S));
975        // Per relay: another one gets v4.
976        m.set_relay("https://other.test/");
977        assert_eq!(m.next(Event::Due, at(120 * S)).action, Action::Attempt { v: 4 });
978        m.set_relay("https://relay.test");
979        assert_eq!(m.next(Event::Due, at(6 * 60 * MIN - 1)).action, Action::Attempt { v: 1 });
980        assert_eq!(m.next(Event::Due, at(6 * 60 * MIN)).action, Action::Attempt { v: 4 }, "forgotten after 6 h");
981        assert_eq!(m.status(&at(6 * 60 * MIN)).unwrap().note, None);
982    }
983
984    #[test]
985    fn a_relay_that_took_v2_gets_v2_and_still_a_goodbye() {
986        let mut m = machine();
987        m.next(Event::Start, at(0));
988        assert_eq!(m.next(answer(Answer::Malformed), at(0)).action, Action::Attempt { v: 2 });
989        let step = m.next(Event::Answer { sent_v: 2, answer: Answer::Stored, relay_date_ms: None }, at(0));
990        assert!(step.logs[0].text.contains("as v2"), "{:?}", step.logs);
991        let status = m.status(&at(0)).unwrap();
992        assert_eq!(status.record_version, 2);
993        assert!(status.note.as_deref().unwrap().contains("agent summaries"), "{status:?}");
994        assert_eq!(m.next(Event::Due, at(60 * S)).action, Action::Attempt { v: 2 });
995        assert!(m.farewell(&at(60 * S)).is_some(), "a relay that takes v2 takes the v3 goodbye");
996    }
997
998    #[test]
999    fn the_v1_memory_is_only_set_by_a_fallback_that_worked() {
1000        let mut m = machine();
1001        m.next(Event::Start, at(0));
1002        m.next(answer(Answer::Malformed), at(0));
1003        m.next(Event::Answer { sent_v: 2, answer: unreachable_answer(), relay_date_ms: None }, at(0));
1004        assert_eq!(m.state(), Some(PresenceState::Retrying));
1005        assert_eq!(m.next(Event::Due, at(MIN)).action, Action::Attempt { v: 4 }, "v4 again: v2 never landed");
1006    }
1007
1008    fn unreachable_answer() -> Answer {
1009        Answer::Unavailable { reason: "cloud unreachable".into(), detail: String::new() }
1010    }
1011
1012    #[test]
1013    fn records_are_stamped_with_the_relays_clock() {
1014        let fast = 15 * MIN; // this computer's clock is 15 min fast
1015        for (skew_label, local_minus_relay) in [("fast", fast as i64), ("slow", -(fast as i64))] {
1016            let mut m = machine();
1017            let now = at(0);
1018            assert_eq!(m.stamp(now.wall_ms), now.wall_ms, "no answer yet: the local clock");
1019            let relay_date = (now.wall_ms as i64 - local_minus_relay) as u64;
1020            let step = m.next(Event::Answer { sent_v: 4, answer: Answer::Stored, relay_date_ms: Some(relay_date) }, now);
1021            assert!(step.logs.iter().any(|l| l.text.contains("differs from the relay's by 15 min")), "{skew_label}");
1022            assert_eq!(m.stamp(now.wall_ms), relay_date, "{skew_label}");
1023            assert_eq!(m.stamp(now.wall_ms + 5_000), relay_date + 5_000);
1024            let status = m.status(&now).unwrap();
1025            assert_eq!(status.offset_ms, Some(-local_minus_relay));
1026            assert_eq!(status.note.as_deref(), Some("Your clock differs from the cloud's by 15 min"), "{skew_label}");
1027        }
1028    }
1029
1030    #[test]
1031    fn a_small_offset_is_used_but_not_shown() {
1032        let mut m = machine();
1033        let now = at(0);
1034        m.next(Event::Answer { sent_v: 4, answer: Answer::Stored, relay_date_ms: Some(now.wall_ms + 90_000) }, now);
1035        assert_eq!(m.stamp(now.wall_ms), now.wall_ms + 90_000);
1036        assert_eq!(m.status(&now).unwrap().note, None);
1037    }
1038
1039    #[test]
1040    fn an_answer_without_a_date_keeps_the_last_offset() {
1041        let mut m = machine();
1042        let now = at(0);
1043        m.next(Event::Health { version: None, relay_date_ms: Some(now.wall_ms - 1000) }, now);
1044        m.next(answer(Answer::Stored), now);
1045        assert_eq!(m.status(&now).unwrap().offset_ms, Some(-1000));
1046    }
1047
1048    #[test]
1049    fn a_clock_refusal_is_sent_again_at_once_with_the_corrected_time() {
1050        let mut m = machine();
1051        m.next(Event::Start, at(0));
1052        let relay_date = WALL - 15 * MIN;
1053        let step = m.next(
1054            Event::Answer {
1055                sent_v: 4,
1056                answer: Answer::ClockRefused("published_at_ms is too far from the relay's clock".into()),
1057                relay_date_ms: Some(relay_date),
1058            },
1059            at(0),
1060        );
1061        assert_eq!(step.action, Action::Attempt { v: 4 });
1062        assert_eq!(m.stamp(WALL), relay_date);
1063        let step = m.next(
1064            answer(Answer::ClockRefused("published_at_ms is too far from the relay's clock".into())),
1065            at(0),
1066        );
1067        assert_eq!(step.action, Action::Wait, "once only");
1068        assert_eq!(m.state(), Some(PresenceState::Rejected));
1069    }
1070
1071    #[test]
1072    fn a_long_outage_warns_once_and_each_state_change_logs_once() {
1073        let mut m = publishing();
1074        let first = m.next(unreachable(), at(MIN));
1075        assert_eq!(first.logs.len(), 1);
1076        assert!(first.logs[0].text.starts_with("retrying: cloud unreachable"), "{:?}", first.logs);
1077        assert!(!first.logs[0].warn);
1078        let mut warnings = 0;
1079        for i in 2..30u64 {
1080            let step = m.next(unreachable(), at(i * MIN));
1081            assert!(step.logs.iter().all(|l| l.warn), "no line per retry: {:?}", step.logs);
1082            warnings += step.logs.len();
1083            if i == 11 {
1084                assert_eq!(warnings, 1, "warned once 10 min in");
1085                assert_eq!(step.logs[0].text, "not published for 10 min: cloud unreachable");
1086            }
1087        }
1088        assert_eq!(warnings, 1);
1089        // A success ends the outage; the next one warns again.
1090        assert_eq!(m.next(answer(Answer::Stored), at(30 * MIN)).logs.len(), 1);
1091        m.next(unreachable(), at(31 * MIN));
1092        assert!(m.next(unreachable(), at(41 * MIN)).logs.iter().any(|l| l.warn));
1093    }
1094
1095    #[test]
1096    fn the_status_says_when_and_why() {
1097        let mut m = machine();
1098        assert_eq!(m.status(&at(0)), None, "nothing to say before the first try");
1099        m.next(answer(Answer::Stored), at(0));
1100        m.next(unreachable(), at_rand(30 * S, 0.5));
1101        let status = m.status(&at(31 * S)).unwrap();
1102        assert_eq!(
1103            status,
1104            PresenceStatusResult {
1105                state: PresenceState::Retrying,
1106                since_ms: WALL + 30 * S,
1107                last_ok_ms: Some(WALL),
1108                last_error: Some("cloud unreachable".into()),
1109                next_try_ms: Some(WALL + 30 * S + 2500),
1110                relay_version: None,
1111                offset_ms: None,
1112                record_version: 4,
1113                note: None,
1114                off_reason: None,
1115            }
1116        );
1117    }
1118
1119    #[test]
1120    fn statuses_and_errors_are_classified() {
1121        assert_eq!(classify(200, None, None), Answer::Stored);
1122        assert_eq!(classify(204, None, None), Answer::Stored);
1123        assert_eq!(classify(409, Some("a newer record is stored"), None), Answer::Stored, "newest wins: as good as stored");
1124        assert_eq!(classify(404, Some("Not Found"), None), Answer::NoRoute);
1125        assert_eq!(classify(400, Some(MALFORMED_RECORD), None), Answer::Malformed);
1126        assert_eq!(
1127            classify(400, Some("published_at_ms is too far from the relay's clock"), None),
1128            Answer::ClockRefused("published_at_ms is too far from the relay's clock".into())
1129        );
1130        assert_eq!(classify(400, Some("bad sig"), None), Answer::Refused("bad sig".into()));
1131        assert_eq!(classify(410, None, None), Answer::Refused("the relay answered 410".into()));
1132        let ra = Some(Duration::from_secs(7));
1133        assert_eq!(classify(429, None, ra), Answer::TooMany { retry_after: ra });
1134        assert_eq!(
1135            classify(503, Some("down"), None),
1136            Answer::Unavailable { reason: "the cloud answered 503".into(), detail: "down".into() }
1137        );
1138        assert!(matches!(classify(401, None, None), Answer::Unavailable { .. }));
1139    }
1140}