Skip to main content

capsule_core/notify/
evaluate.rs

1//! The trigger predicates: [`evaluate()`] (which classes are true now) and [`next_deadline()`]
2//! (the one instant to arm an OS timer for).
3//!
4//! Each predicate cites the doc that owns its threshold. This module owns none of them — it owns
5//! only the *composition*, which is the thing that must not be reimplemented per platform.
6//!
7//! # Boundary convention
8//!
9//! Every threshold in this module **fires at the boundary instant**: `now >= deadline`, never
10//! `>`. That matches the recovery cadence's own `now >= next_due`, so a client that renders both
11//! never sees them disagree by a second. Suppression is the mirror image and is exclusive
12//! (`until > now`), so a class snoozed to exactly `now` is due at `now`.
13
14use std::collections::BTreeMap;
15
16use jiff::Timestamp;
17
18use super::class::{Alert, AlertClass};
19use super::input::{NotifyInput, QuotaAdvisory, RecoveryFacts, SyncFacts};
20
21/// One day, in seconds — the unit the staleness threshold is expressed in.
22pub const DAY_SECS: i64 = 86_400;
23
24/// The staleness threshold: **two weeks** without a completed sync while changes remain
25/// un-synced. From [Download & Sync — Notifications], which owns the predicate; this module owns
26/// only its evaluation.
27///
28/// [Download & Sync — Notifications]: https://docs/design/sync/#notifications
29pub const SYNC_STALE_SECS: i64 = 14 * DAY_SECS;
30
31/// Every alert that is true at `now`, in [`AlertClass::ALL`] order.
32///
33/// Pure: `now` is an argument, nothing is read from the environment, and equal inputs give
34/// equal outputs. A suppressed class is skipped before its predicate runs, so suppression can
35/// never be observed as "fired but hidden".
36///
37/// Absent facts emit nothing: `None` sync facts, `None` quota facts and zero counts are all
38/// silence, not an error.
39#[must_use]
40pub fn evaluate(input: &NotifyInput, now: Timestamp) -> Vec<Alert> {
41    let mut alerts = Vec::new();
42    for class in AlertClass::ALL {
43        if input.is_suppressed(class, now) {
44            continue;
45        }
46        if let Some(alert) = evaluate_class(input, class, now) {
47            alerts.push(alert);
48        }
49    }
50    // The whole point of one shared decision function is that a field report says which
51    // classes a device decided were true, without the device having to explain itself.
52    tracing::debug!(
53        now = %now,
54        classes = ?alerts.iter().map(|a| a.class.as_str()).collect::<Vec<_>>(),
55        "notify: evaluated the alert classes"
56    );
57    alerts
58}
59
60/// The instant an OS timer must be armed for, **per class** — the arm half of the
61/// arm / re-arm / cancel rule.
62///
63/// A class present in the map should have exactly one live timer, set to the returned instant.
64/// A class *absent* from it should have no timer: cancel whatever it holds. Because the answer
65/// is a pure function of state, the whole client-side protocol is "recompute after any state
66/// change, then reconcile your timers against this map" — and one entry per class from one
67/// function is why two live timers for one class is structurally impossible.
68///
69/// It is keyed per class rather than collapsed to a single instant because the timers are
70/// independent: with a staleness deadline two weeks out and a recovery check ninety days out,
71/// arming only the earlier one loses the later alert entirely on a device the app never runs on
72/// again — which is the exact case pre-arming exists for. A client also needs the class to pick
73/// its `notification.*` catalog key for the notification it is arming.
74///
75/// This is deliberately **narrower** than [`evaluate()`]. An armed notification fires from the
76/// OS's own timer with the app not running, so it cannot be re-checked when it arrives: an
77/// instant is returned only when the alert is certain to be true on arrival. Three things
78/// therefore withhold one:
79///
80/// - the class is not [pre-armable](AlertClass::pre_armable) — its condition is server-held, so
81///   the device cannot compute a deadline for it at all;
82/// - the resulting instant is not strictly after `now` (it has already passed, so there is
83///   nothing left to schedule) — including a class the alert has already fired for;
84/// - the class would arrive as something other than a notification: `sync_stale` with nothing
85///   un-synced (only a sync can change that, and a sync re-arms), `recovery_check_due` with its
86///   snooze budget spent (a badge, which is in-app), and any class the user has
87///   [disabled](NotifyInput::disabled).
88///
89/// A [snooze](NotifyInput::suppressed) **defers** the armed instant rather than cancelling it: a
90/// class snoozed after it fired must re-fire when the snooze ends, and the snooze end is a
91/// deadline the device can compute.
92#[must_use]
93pub fn pre_arm_deadlines(input: &NotifyInput, now: Timestamp) -> BTreeMap<AlertClass, Timestamp> {
94    let mut armed = BTreeMap::new();
95    for class in AlertClass::ALL {
96        if !class.pre_armable() {
97            continue;
98        }
99        if let Some(at) = pre_arm_deadline(input, class)
100            && at > now
101        {
102            armed.insert(class, at);
103        }
104    }
105    // A timer armed for the wrong instant, or cancelled when it should not have been, is
106    // otherwise invisible until an alert fails to arrive weeks later.
107    tracing::debug!(
108        now = %now,
109        armed = ?armed
110            .iter()
111            .map(|(class, at)| (class.as_str(), at.to_string()))
112            .collect::<Vec<_>>(),
113        "notify: computed the pre-arm deadlines"
114    );
115    armed
116}
117
118/// The earliest instant in [`pre_arm_deadlines()`], or `None` when nothing is to be armed.
119///
120/// A convenience for a caller that holds a single timer — a desktop scheduler, a CLI, a status
121/// line. **A client that pre-arms per class wants [`pre_arm_deadlines()`]**: collapsing the map
122/// to its minimum discards the later class's timer, which on a device the app never runs on
123/// again loses that alert.
124#[must_use]
125pub fn next_deadline(input: &NotifyInput, now: Timestamp) -> Option<Timestamp> {
126    pre_arm_deadlines(input, now).into_values().min()
127}
128
129/// The predicate for one class. Separated per class rather than per fact so the emission order
130/// is the enum's and the two quota classes stay independently suppressible.
131fn evaluate_class(input: &NotifyInput, class: AlertClass, now: Timestamp) -> Option<Alert> {
132    match class {
133        AlertClass::SyncStale => sync_stale(input.sync.as_ref()?, now),
134        AlertClass::RecoveryCheckDue => recovery_check_due(input.recovery.as_ref()?, now),
135        AlertClass::QuotaSoft => {
136            (input.quota?.state == QuotaAdvisory::SoftWarning).then(|| Alert::new(class))
137        }
138        AlertClass::QuotaGraceExpiring => quota_grace_expiring(input.quota?.state),
139        AlertClass::QuarantinePending => counted(class, input.quarantine_pending),
140        AlertClass::DropPending => counted(class, input.drops_pending),
141    }
142}
143
144/// A class that fires on any non-zero count and carries it as the `count` parameter.
145///
146/// A quarantined item is never silently dropped and never silently applied, so any non-zero
147/// count is reported. The two counts are **disjoint**: a pending drop is a quarantine surface in
148/// the threat model's inventory, but it has its own class here, so
149/// [`NotifyInput::quarantine_pending`] excludes drops and only
150/// [`NotifyInput::drops_pending`] counts them.
151fn counted(class: AlertClass, count: u64) -> Option<Alert> {
152    (count > 0).then(|| Alert::new(class).with_param("count", count.to_string()))
153}
154
155/// "After two weeks without a completed sync *while changes remain un-synced*."
156///
157/// Both halves are load-bearing: with nothing un-synced the library is not behind, so a device
158/// that simply has not needed to sync raises nothing.
159fn sync_stale(facts: &SyncFacts, now: Timestamp) -> Option<Alert> {
160    if facts.unsynced_changes == 0 {
161        return None;
162    }
163    let deadline = sync_stale_deadline(facts);
164    if now < deadline {
165        return None;
166    }
167    // Clock skew backwards is not a fire: `now < deadline` already returned above, so the
168    // subtraction here cannot go negative — but it saturates regardless rather than trusting it.
169    let days_behind = now
170        .as_second()
171        .saturating_sub(facts.last_completed_sync.as_second())
172        / DAY_SECS;
173    Some(
174        Alert::new(AlertClass::SyncStale)
175            .with_deadline(deadline)
176            .with_param("count", facts.unsynced_changes.to_string())
177            .with_param("days_behind", days_behind.to_string()),
178    )
179}
180
181/// When the staleness alert becomes true, given the sync epoch.
182fn sync_stale_deadline(facts: &SyncFacts) -> Timestamp {
183    add_secs(facts.last_completed_sync, SYNC_STALE_SECS)
184}
185
186/// The verification prompt is due, and no active snooze is holding it back.
187///
188/// The cadence ladder and the snooze accounting stay with the scheduler; this consumes
189/// `next_due` as given. `snooze_budget_spent` does not change *whether* the class is reported —
190/// a client cannot render a badge for a condition it was not told about — only how, which is
191/// delivery and therefore the client's. It is carried as the `snooze_budget` parameter.
192///
193/// The reported `deadline` is the **later** of `next_due` and an expired `snoozed_until`,
194/// because that is the instant whose passing actually made the alert true — and it is the same
195/// instant [`pre_arm_deadline`] armed, so what a client scheduled and what it is handed on
196/// arrival agree.
197fn recovery_check_due(facts: &RecoveryFacts, now: Timestamp) -> Option<Alert> {
198    if facts.snoozed_until.is_some_and(|until| until > now) {
199        return None;
200    }
201    if now < facts.next_due {
202        return None;
203    }
204    let became_true_at = facts
205        .snoozed_until
206        .map_or(facts.next_due, |until| until.max(facts.next_due));
207    Some(
208        Alert::new(AlertClass::RecoveryCheckDue)
209            .with_deadline(became_true_at)
210            .with_param(
211                "snooze_budget",
212                if facts.snooze_budget_spent {
213                    "spent"
214                } else {
215                    "available"
216                },
217            )
218            // Without this the alert for "you told us you lost your recovery secret" is
219            // byte-identical to the routine ninety-day check, and a client rendering from the
220            // class alone would say "time for your periodic check" at the worst moment.
221            .with_param(
222                "recovery",
223                if facts.rewrap_due { "rewrap" } else { "check" },
224            ),
225    )
226}
227
228/// "Entering the grace window raises `quota_grace_expiring`."
229///
230/// `GraceExpired` raises the same class with `grace = "expired"` rather than going silent: it is
231/// strictly additive to `HardExceeded` (metadata-growth writes are now refused too), so a device
232/// that first polls after the window closed must still hear about it, and the class set is closed
233/// — there is no `quota_grace_expired` to escalate into.
234fn quota_grace_expiring(state: QuotaAdvisory) -> Option<Alert> {
235    let grace = match state {
236        QuotaAdvisory::HardExceeded => "counting",
237        QuotaAdvisory::GraceExpired => "expired",
238        // `Ok`/`SoftWarning` are below the hard limit; `Suspended` is an admin or billing
239        // action owned by moderation, not a quota threshold.
240        QuotaAdvisory::Ok | QuotaAdvisory::SoftWarning | QuotaAdvisory::Suspended => return None,
241    };
242    Some(Alert::new(AlertClass::QuotaGraceExpiring).with_param("grace", grace))
243}
244
245/// The instant to arm for one pre-armable class, if it has one that will certainly fire.
246///
247/// Two composition rules, both of which exist because an armed notification cannot be
248/// re-checked when it fires:
249///
250/// - the class's own condition instant is the **later** of every gate on it — a recovery check
251///   snoozed to a date *before* its due date is still not due until `next_due`, so arming the
252///   snooze end alone would fire into no alert;
253/// - a [snooze](NotifyInput::suppressed) **defers** that instant instead of cancelling it, so a
254///   class snoozed after firing re-fires when the snooze ends. Only a
255///   [disable](NotifyInput::disabled) cancels.
256fn pre_arm_deadline(input: &NotifyInput, class: AlertClass) -> Option<Timestamp> {
257    let condition_at = match class {
258        AlertClass::SyncStale => input
259            .sync
260            .as_ref()
261            .filter(|facts| facts.unsynced_changes > 0)
262            .map(sync_stale_deadline),
263        AlertClass::RecoveryCheckDue => input
264            .recovery
265            .as_ref()
266            .filter(|facts| !facts.snooze_budget_spent)
267            .map(|facts| {
268                facts
269                    .snoozed_until
270                    .map_or(facts.next_due, |until| until.max(facts.next_due))
271            }),
272        // Not pre-armable; `pre_arm_deadlines` filters these out before asking.
273        AlertClass::QuotaSoft
274        | AlertClass::QuotaGraceExpiring
275        | AlertClass::QuarantinePending
276        | AlertClass::DropPending => None,
277    }?;
278    if input.disabled.contains(&class) {
279        // Disabled: nothing is ever armed again for this class.
280        return None;
281    }
282    // Snoozed: re-fire when the snooze ends, if that outlasts the condition itself.
283    Some(match input.suppressed.get(&class) {
284        Some(&until) => condition_at.max(until),
285        None => condition_at,
286    })
287}
288
289/// Add a signed second offset to a timestamp, saturating at the representable bounds. Nothing
290/// here operates near them; saturation just keeps the arithmetic total, so a disabled class
291/// pinned at [`Timestamp::MAX`] can never panic the predicate.
292fn add_secs(base: Timestamp, secs: i64) -> Timestamp {
293    let target = base.as_second().saturating_add(secs);
294    Timestamp::from_second(target).unwrap_or(if target < 0 {
295        Timestamp::MIN
296    } else {
297        Timestamp::MAX
298    })
299}
300
301#[cfg(test)]
302mod tests;