Skip to main content

capsule_core/notify/
class.rs

1//! The closed alert-class enum, its severity, and the [`Alert`] record the predicate emits.
2//!
3//! SSoT: [Notifications — Alert Classes]. The class list is closed here; each class's *trigger
4//! predicate and thresholds* stay owned by the doc that defines the condition, and are
5//! implemented in [`super::evaluate()`] against those citations.
6//!
7//! [Notifications — Alert Classes]: https://docs/design/notifications/#alert-classes
8
9use std::collections::BTreeMap;
10
11use jiff::Timestamp;
12use serde::{Deserialize, Serialize};
13
14/// Every alert Capsule can raise. **A closed enum**: an unknown wire value is a structural
15/// error, like every other closed enum in the schema rules — which is what the `serde` derive
16/// without `#[serde(other)]` gives.
17///
18/// The variant order is the delivery order [`super::evaluate()`] emits in, and matches the
19/// SSoT's own table so a reader can diff the two.
20///
21/// `Ord` is derived because the suppression map ([`super::NotifyInput::suppressed`]) is keyed on
22/// this type and must iterate deterministically.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum AlertClass {
26    /// Two weeks without a completed sync while changes remain un-synced. Trigger owner:
27    /// [Sync — Notifications](https://docs/design/sync/#notifications).
28    SyncStale,
29    /// A recovery-secret verification check is due. Trigger owner:
30    /// [Backup — Schedule and Triggers](https://docs/design/backup-recovery/#schedule-and-triggers).
31    RecoveryCheckDue,
32    /// Storage crossed the soft limit and is below the hard limit. Trigger owner:
33    /// [Quota — Thresholds and States](https://docs/design/quota/#thresholds-and-states).
34    QuotaSoft,
35    /// Storage is over the hard limit — the grace window is counting, or has closed. Trigger
36    /// owner: [Quota — Thresholds and States](https://docs/design/quota/#thresholds-and-states).
37    QuotaGraceExpiring,
38    /// Items are sitting on a quarantine surface awaiting a human. Trigger owner:
39    /// [Threat Model — Quarantine Surfaces](https://docs/design/threat-model/scenarios/#quarantine-surfaces).
40    QuarantinePending,
41    /// Guest drops are awaiting review and adoption. Trigger owner:
42    /// [Web Upload — Drop and Adoption Lifecycle](https://docs/design/web-upload/#drop-and-adoption-lifecycle).
43    DropPending,
44}
45
46impl AlertClass {
47    /// Every class, in delivery order. Iterating this rather than a hand-written list is what
48    /// makes "the enum is closed" a property a reader can check: adding a variant without
49    /// extending this array fails to compile, because the array's length is declared.
50    pub const ALL: [Self; 6] = [
51        Self::SyncStale,
52        Self::RecoveryCheckDue,
53        Self::QuotaSoft,
54        Self::QuotaGraceExpiring,
55        Self::QuarantinePending,
56        Self::DropPending,
57    ];
58
59    /// The stable wire name — identical to the `serde` representation, so a log line, a
60    /// [`Alert::params`] value, and the serialized form never disagree.
61    #[must_use]
62    pub const fn as_str(self) -> &'static str {
63        match self {
64            Self::SyncStale => "sync_stale",
65            Self::RecoveryCheckDue => "recovery_check_due",
66            Self::QuotaSoft => "quota_soft",
67            Self::QuotaGraceExpiring => "quota_grace_expiring",
68            Self::QuarantinePending => "quarantine_pending",
69            Self::DropPending => "drop_pending",
70        }
71    }
72
73    /// The inverse of [`as_str`](Self::as_str): parse a wire name, rejecting anything that is
74    /// not one of the six.
75    ///
76    /// The enum is closed, so an unrecognized name is `None` — a structural error for the
77    /// caller to report, never a class that is silently dropped. This exists so a boundary that
78    /// carries the name as a plain string (the app FFI's suppression map, a persisted
79    /// client preference) has one table to parse against rather than its own copy.
80    #[must_use]
81    pub fn from_wire(name: &str) -> Option<Self> {
82        Self::ALL.into_iter().find(|class| class.as_str() == name)
83    }
84
85    /// How loudly a client should present this class. A property of the class, not of the
86    /// instant it fired, so it lives here rather than being decided per-[`Alert`].
87    #[must_use]
88    pub const fn severity(self) -> AlertSeverity {
89        match self {
90            // The library is silently falling out of date — the case the alert exists for.
91            Self::SyncStale
92            // Writes beyond the originals are now being refused.
93            | Self::QuotaGraceExpiring
94            // Items are neither applied nor dropped; they are waiting on a human.
95            | Self::QuarantinePending => AlertSeverity::Warning,
96            // Advisory: nothing is failing yet.
97            Self::RecoveryCheckDue | Self::QuotaSoft | Self::DropPending => AlertSeverity::Advisory,
98        }
99    }
100
101    /// Whether this class's trigger is a deadline the device can compute alone, and can
102    /// therefore be pre-armed as a scheduled local notification.
103    ///
104    /// `false` for the three server-state classes (`quota_*`, `quarantine_pending`,
105    /// `drop_pending`): their condition lives on the server, so on a device that never runs
106    /// they cannot fire at all. That gap is real and v1 accepts it — those three surface at
107    /// next app launch. Closing it is what the post-v1 wake tier is for.
108    #[must_use]
109    pub const fn pre_armable(self) -> bool {
110        matches!(self, Self::SyncStale | Self::RecoveryCheckDue)
111    }
112}
113
114/// How prominently a client presents an alert.
115///
116/// Two variants deliberately, and **neither gates anything** — see
117/// [`Alert::blocks_critical_flow`].
118#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
119#[serde(rename_all = "snake_case")]
120pub enum AlertSeverity {
121    /// Informational: nothing is failing, and nothing is about to.
122    Advisory,
123    /// Something is already degraded or is being refused.
124    Warning,
125}
126
127/// One alert that is true at an instant.
128///
129/// Pure data: a class, its severity, the deadline that produced it (for the pre-armable classes),
130/// and the parameters a client interpolates into its own catalog string. **Never a localized
131/// string** — the copy is a `notification.*` catalog key the client owns.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct Alert {
134    /// Which alert this is.
135    pub class: AlertClass,
136    /// [`AlertClass::severity`] for [`class`](Self::class), carried so a consumer that only
137    /// deserializes the record does not have to re-derive it.
138    pub severity: AlertSeverity,
139    /// The instant whose passing made this alert true, for the pre-armable classes; `None` for
140    /// the three whose condition is server-held and has no device-computable deadline.
141    pub deadline: Option<Timestamp>,
142    /// Parameters for the client's catalog string — plain strings, deterministically ordered.
143    ///
144    /// The keys in use are `count` (`sync_stale`, `quarantine_pending`, `drop_pending`),
145    /// `days_behind` (`sync_stale`), `grace` (`quota_grace_expiring`), and `snooze_budget`
146    /// (`available` / `spent`) plus `recovery` (`check` / `rewrap`), both of which
147    /// `recovery_check_due` always carries. Each is documented at the predicate that sets it.
148    pub params: BTreeMap<String, String>,
149}
150
151impl Alert {
152    /// An alert of `class` with its severity filled in, no deadline, and no parameters.
153    pub(crate) fn new(class: AlertClass) -> Self {
154        Self {
155            class,
156            severity: class.severity(),
157            deadline: None,
158            params: BTreeMap::new(),
159        }
160    }
161
162    /// Attach the deadline whose passing made this alert true.
163    pub(crate) fn with_deadline(mut self, deadline: Timestamp) -> Self {
164        self.deadline = Some(deadline);
165        self
166    }
167
168    /// Attach one catalog parameter.
169    pub(crate) fn with_param(mut self, key: &str, value: impl Into<String>) -> Self {
170        self.params.insert(key.to_owned(), value.into());
171        self
172    }
173
174    /// Alerts are advisory by construction: **no** alert blocks sync, unlock, upload, or any
175    /// critical flow. `const false` for every alert, so the "never blocks" rule is a
176    /// compile-time property of the type rather than a convention reviewers have to police —
177    /// the same trick
178    /// [`VerificationState::blocks_critical_flow`](https://docs/design/backup-recovery/) uses
179    /// for the recovery prompt.
180    #[must_use]
181    pub const fn blocks_critical_flow(&self) -> bool {
182        false
183    }
184}
185
186#[cfg(test)]
187mod tests;