capsule_core/notify/input.rs
1//! [`NotifyInput`] — the snapshot of device-held state the predicate is evaluated against.
2//!
3//! Every field is caller-supplied and `Option`/zero where the client has not learned it yet.
4//! Nothing here reads a clock, a socket, or SQLite: this crate holds none of the trigger state
5//! (see the [module docs](super) for why), so the only honest shape is a struct the client
6//! fills.
7//!
8//! The security boundary is the shape itself: counts and instants only. No album id, no title,
9//! no asset id, nothing a server could author.
10
11use std::collections::{BTreeMap, BTreeSet};
12
13use jiff::Timestamp;
14use serde::{Deserialize, Serialize};
15
16use super::class::AlertClass;
17
18/// The state [`super::evaluate()`] and [`super::next_deadline()`] decide from.
19///
20/// [`Default`] is the "a client that has just installed and learned nothing" input, and it
21/// yields no alerts and no deadline.
22#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(default)]
24pub struct NotifyInput {
25 /// Sync progress, persisted by the client at the end of each successful sync. `None` on a
26 /// device that has never completed one — which raises no `sync_stale`, because the alert is
27 /// about a *stale* sync and not a missing one.
28 pub sync: Option<SyncFacts>,
29 /// The recovery-verification cadence, projected into flat facts. `None` before recovery is
30 /// set up.
31 pub recovery: Option<RecoveryFacts>,
32 /// The last quota response the client received. `None` before the first
33 /// `GET /v1/quota` — quota state is server-held, so it is only ever as current as that call.
34 pub quota: Option<QuotaFacts>,
35 /// How many items sit on the client's quarantine surfaces awaiting a human.
36 ///
37 /// **Excludes pending drops.** A pending drop is a quarantine surface in the threat model's
38 /// own inventory, but it has its own alert class here, so a client that filled this field
39 /// from that inventory unfiltered would raise both classes for the same items. Count drops
40 /// in [`drops_pending`](Self::drops_pending) and nowhere else.
41 pub quarantine_pending: u64,
42 /// How many guest drops are awaiting review and adoption.
43 pub drops_pending: u64,
44 /// Per-class **snooze**: the instant a deferred class becomes due again. A class whose entry
45 /// is strictly after `now` emits nothing from [`super::evaluate()`].
46 ///
47 /// This is how a client applies a snooze without this crate owning that state machine — the
48 /// bounded-snooze-then-badge mechanic has one owner already
49 /// ([`RecoveryCadence`](https://docs/design/backup-recovery/#recovery-verification-cadence)),
50 /// and a second copy here would be two owners of one mechanic.
51 ///
52 /// A snooze **defers** the class's pre-arm deadline rather than cancelling it
53 /// ([`super::pre_arm_deadlines()`]): a class snoozed after it fired must fire again when the
54 /// snooze ends, and that end is a deadline the device can compute. Cancelling instead would
55 /// leave the alert reachable only in-app, which for `sync_stale` defeats the entire pre-arm
56 /// rule the class exists under.
57 ///
58 /// **This map is for the other five classes.** Recovery snoozing is owned by
59 /// [`RecoveryFacts::snoozed_until`], because the cadence scheduler already tracks it against
60 /// a bounded budget and this map has no budget to spend. An entry here for
61 /// [`AlertClass::RecoveryCheckDue`] is honoured as a fallback — the armed instant becomes
62 /// the later of the two, and either suppresses the report — but it is not the canonical
63 /// channel, and a client that writes both is expressing one snooze twice.
64 pub suppressed: BTreeMap<AlertClass, Timestamp>,
65 /// Per-class **disable**: the user turned this alert off. Emits nothing and arms nothing, at
66 /// any instant.
67 ///
68 /// A separate field from [`suppressed`](Self::suppressed) rather than a far-future instant in
69 /// it, because they are different mechanics with different effects on the timer — a snooze
70 /// defers, a disable cancels — and because a sentinel instant is exactly the kind of
71 /// convention that does not survive a string-typed FFI boundary: a client writing "the year
72 /// 2999" would mean *disabled* and get a timer armed 975 years out.
73 ///
74 /// **Disabling suppresses the warning, never the behavior.** Turning off `sync_stale` does
75 /// not turn off auto-sync; turning off `recovery_check_due` does not stop the recovery check
76 /// mattering. An alert is a report about a condition, never the mechanism managing it.
77 pub disabled: BTreeSet<AlertClass>,
78}
79
80impl NotifyInput {
81 /// Whether `class` is snoozed or disabled at `now`, and therefore reports nothing.
82 ///
83 /// A snooze entry exactly at `now` has expired: a snooze is `until`, exclusive, so a class
84 /// snoozed to `now` is due again at `now` — the same boundary convention as every other
85 /// threshold in this module. A disable never expires.
86 #[must_use]
87 pub fn is_suppressed(&self, class: AlertClass, now: Timestamp) -> bool {
88 self.disabled.contains(&class)
89 || self
90 .suppressed
91 .get(&class)
92 .is_some_and(|until| *until > now)
93 }
94}
95
96/// What the client knows about its own sync progress.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
98pub struct SyncFacts {
99 /// When the last **completed** sync finished. This is the epoch the two-week deadline is
100 /// measured from, and the instant at which a client re-arms the timer.
101 pub last_completed_sync: Timestamp,
102 /// Changes still waiting to reach the server — including originals still pending under a
103 /// staged upload policy. Zero means nothing is behind, so nothing is stale.
104 pub unsynced_changes: u64,
105}
106
107/// The recovery-verification cadence, flattened to the facts the predicate needs.
108///
109/// The 7 d → 90 d → 180 d ladder, its re-arm triggers, and its snooze accounting stay owned by
110/// the cadence scheduler; this module consumes the already-computed `next_due` and never
111/// recomputes the ladder. `capsule-sdk` depends on this crate and not the reverse, so the
112/// scheduler cannot be named here — the SDK projects into this struct instead.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114pub struct RecoveryFacts {
115 /// When the next verification prompt becomes due.
116 pub next_due: Timestamp,
117 /// When an active snooze expires, if one is active.
118 ///
119 /// **This is where recovery snoozing lives**, rather than
120 /// [`NotifyInput::suppressed`](super::NotifyInput::suppressed): the cadence scheduler owns
121 /// the bounded-snooze-then-badge budget, so the snooze and the budget that bounds it stay
122 /// in one place. The generic map is for the other five classes.
123 ///
124 /// A snooze set *before* the due date does not make the check due earlier: the class is due
125 /// at the later of this and [`next_due`](Self::next_due).
126 pub snoozed_until: Option<Timestamp>,
127 /// Whether the consecutive-snooze budget is spent. When it is, the class has degraded to a
128 /// persistent, non-blocking badge: it is still reported (a client cannot render a badge for
129 /// a condition it was not told about), but it is no longer pre-armed as a notification —
130 /// the badge never escalates back into an alert on its own.
131 pub snooze_budget_spent: bool,
132 /// Whether the scheduler has escalated to the guided re-wrap — repeated verification
133 /// failures, or the user explicitly declaring the secret lost.
134 ///
135 /// Carried because the alert class set is closed and `recovery_check_due` is the only class
136 /// that can report it: without this fact the alert for "you told us you lost your recovery
137 /// secret" would be indistinguishable from the routine ninety-day check. It surfaces as the
138 /// `recovery` parameter (`"rewrap"` / `"check"`) so a client routes into the guided re-wrap
139 /// instead of a verification prompt. `#[serde(default)]` so a snapshot persisted before this
140 /// field existed still loads.
141 #[serde(default)]
142 pub rewrap_due: bool,
143}
144
145/// The last quota answer the client holds.
146///
147/// A one-field struct on purpose: the wire response carries no `over_since` and no grace
148/// deadline, which is exactly why the quota classes are not pre-armable. When it grows one, the
149/// deadline field lands here without changing [`NotifyInput`]'s shape.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
151pub struct QuotaFacts {
152 /// The state the server reported.
153 pub state: QuotaAdvisory,
154}
155
156/// The quota state, as `GET /v1/quota` reports it.
157///
158/// Mirrors the SSoT's state table one-for-one rather than collapsing it, so a client can hand
159/// the server's answer straight through.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
161#[serde(rename_all = "snake_case")]
162pub enum QuotaAdvisory {
163 /// `used < soft_limit`. All uploads succeed normally.
164 Ok,
165 /// `soft_limit <= used < hard_limit`. Uploads succeed; the client warns.
166 SoftWarning,
167 /// `used >= hard_limit`. New uploads are rejected at session creation; the grace window is
168 /// counting.
169 HardExceeded,
170 /// Over the hard limit for longer than the grace window. Additive to
171 /// [`HardExceeded`](Self::HardExceeded): metadata-growth writes are refused too.
172 GraceExpired,
173 /// An admin or billing action, not a threshold. Server-defined and owned by moderation, so
174 /// it raises no quota alert class here.
175 Suspended,
176}
177
178#[cfg(test)]
179mod tests;