capsule_sdk/ffi/notify.rs
1//! The local-alert surface across the FFI boundary (core half): the flattened
2//! mirror of [`capsule_core::notify`] plus the two functions the apps call.
3//!
4//! # Why free functions
5//!
6//! [`evaluate_alerts`], [`pre_arm_deadlines`] and [`next_alert_deadline`] are free
7//! `#[uniffi::export]` functions rather
8//! than methods on
9//! [`FfiWorkspace`](crate::ffi::FfiWorkspace). The workspace holds none of the predicate's
10//! inputs — there is no persisted last-sync instant, no client-side quota type, and no
11//! quarantine table — so a method would take the same [`FfiNotifyInput`] and then lock a mutex
12//! it never reads. The predicate is a pure function of caller-supplied state, and the boundary
13//! says so.
14//!
15//! # Shape
16//!
17//! [`FfiNotifyInput`] is **flat**: uniffi records nest, but a foreign caller assembling five
18//! optional sub-records to ask one question is worse than a struct whose fields are each
19//! independently `None`. Presence is explicit — `last_completed_sync` present means the sync
20//! facts are known, `recovery_next_due` present means recovery is set up, `quota_state` present
21//! means a quota response has been seen.
22//!
23//! Timestamps cross as **RFC 3339 strings**, following the `changed_at` precedent on
24//! [`FfiSyncApplyOutcome`](crate::ffi::FfiSyncApplyOutcome): Kotlin and Swift each have their own
25//! instant type and no shared integer convention worth guessing at. A string that does not parse
26//! is [`FfiError::InvalidArgument`], never a panic.
27
28use std::collections::{BTreeMap, BTreeSet, HashMap};
29
30use capsule_core::notify::{
31 self, Alert, AlertClass, AlertSeverity, NotifyInput, QuotaAdvisory, QuotaFacts, RecoveryFacts,
32 SyncFacts,
33};
34use jiff::Timestamp;
35
36use super::FfiError;
37
38/// Every alert class, flattened for the bindings. A closed enum on both sides of the boundary.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
40pub enum FfiAlertClass {
41 /// Two weeks without a completed sync while changes remain un-synced.
42 SyncStale,
43 /// A recovery-secret verification check is due.
44 RecoveryCheckDue,
45 /// Storage crossed the soft limit and is below the hard limit.
46 QuotaSoft,
47 /// Storage is over the hard limit — the grace window is counting, or has closed.
48 QuotaGraceExpiring,
49 /// Items are sitting on a quarantine surface awaiting a human.
50 QuarantinePending,
51 /// Guest drops are awaiting review and adoption.
52 DropPending,
53}
54
55impl From<AlertClass> for FfiAlertClass {
56 fn from(class: AlertClass) -> Self {
57 match class {
58 AlertClass::SyncStale => Self::SyncStale,
59 AlertClass::RecoveryCheckDue => Self::RecoveryCheckDue,
60 AlertClass::QuotaSoft => Self::QuotaSoft,
61 AlertClass::QuotaGraceExpiring => Self::QuotaGraceExpiring,
62 AlertClass::QuarantinePending => Self::QuarantinePending,
63 AlertClass::DropPending => Self::DropPending,
64 }
65 }
66}
67
68/// How prominently a client presents an alert. **Neither variant gates anything** — no alert
69/// blocks sync, unlock, upload, or any critical flow.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
71pub enum FfiAlertSeverity {
72 /// Informational: nothing is failing, and nothing is about to.
73 Advisory,
74 /// Something is already degraded or is being refused.
75 Warning,
76}
77
78impl From<AlertSeverity> for FfiAlertSeverity {
79 fn from(severity: AlertSeverity) -> Self {
80 match severity {
81 AlertSeverity::Advisory => Self::Advisory,
82 AlertSeverity::Warning => Self::Warning,
83 }
84 }
85}
86
87/// The quota state, as `GET /v1/quota` reports it.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
89pub enum FfiQuotaAdvisory {
90 /// Below the soft limit. All uploads succeed normally.
91 Ok,
92 /// At or above the soft limit and below the hard limit. Uploads succeed; the client warns.
93 SoftWarning,
94 /// At or above the hard limit. New uploads are rejected; the grace window is counting.
95 HardExceeded,
96 /// Over the hard limit for longer than the grace window; metadata-growth writes are
97 /// refused too.
98 GraceExpired,
99 /// An admin or billing action rather than a threshold. Raises no quota alert.
100 Suspended,
101}
102
103impl From<FfiQuotaAdvisory> for QuotaAdvisory {
104 fn from(state: FfiQuotaAdvisory) -> Self {
105 match state {
106 FfiQuotaAdvisory::Ok => Self::Ok,
107 FfiQuotaAdvisory::SoftWarning => Self::SoftWarning,
108 FfiQuotaAdvisory::HardExceeded => Self::HardExceeded,
109 FfiQuotaAdvisory::GraceExpired => Self::GraceExpired,
110 FfiQuotaAdvisory::Suspended => Self::Suspended,
111 }
112 }
113}
114
115/// One alert that is true at an instant.
116///
117/// Never a localized string: `class` selects the app's own `notification.*` catalog key and
118/// `params` are interpolated into it, so a server can neither supply nor influence the words a
119/// user reads.
120#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
121pub struct FfiAlert {
122 /// Which alert this is.
123 pub class: FfiAlertClass,
124 /// How prominently to present it.
125 pub severity: FfiAlertSeverity,
126 /// The instant whose passing made this alert true (RFC 3339), for the two pre-armable
127 /// classes; `None` for the three whose condition is server-held.
128 pub deadline: Option<String>,
129 /// Catalog parameters — `count`, `days_behind`, `grace`, and the pair
130 /// `recovery_check_due` always carries: `snooze_budget` (`available` / `spent`) and
131 /// `recovery` (`check` / `rewrap`).
132 pub params: HashMap<String, String>,
133}
134
135impl From<Alert> for FfiAlert {
136 fn from(alert: Alert) -> Self {
137 Self {
138 class: alert.class.into(),
139 severity: alert.severity.into(),
140 deadline: alert.deadline.map(|d| d.to_string()),
141 params: alert.params.into_iter().collect(),
142 }
143 }
144}
145
146/// One class and the instant its local notification should be armed for.
147///
148/// A class absent from [`pre_arm_deadlines`]'s result has no timer to hold: cancel whatever it
149/// has.
150#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
151pub struct FfiClassDeadline {
152 /// The class whose timer this is — also the `notification.*` catalog key the app renders
153 /// when it fires.
154 pub class: FfiAlertClass,
155 /// When to fire it (RFC 3339).
156 pub deadline: String,
157}
158
159/// The device-held state the predicate decides from, flattened for the bindings.
160///
161/// Counts and instants only — no album id, no title, no asset id. An all-default value (every
162/// `Option` `None`, every count `0`, an empty map) is the "just installed, learned nothing"
163/// input, and yields no alerts and no deadline.
164#[derive(Debug, Clone, Default, uniffi::Record)]
165pub struct FfiNotifyInput {
166 /// When the last **completed** sync finished (RFC 3339). `None` on a device that has never
167 /// completed one — which raises no `sync_stale`, because the alert is about a *stale* sync
168 /// and not a missing one. When `None`, `unsynced_changes` is ignored.
169 #[uniffi(default = None)]
170 pub last_completed_sync: Option<String>,
171 /// Changes still waiting to reach the server, including originals still pending under a
172 /// staged upload policy.
173 #[uniffi(default = 0)]
174 pub unsynced_changes: u64,
175 /// When the next recovery-verification prompt becomes due (RFC 3339). Project it from the
176 /// scheduler with
177 /// [`RecoveryCadence::notify_facts`](crate::recovery::RecoveryCadence::notify_facts) rather
178 /// than computing it here. `None` before recovery is set up, which ignores the other three
179 /// `recovery_*` fields.
180 #[uniffi(default = None)]
181 pub recovery_next_due: Option<String>,
182 /// When an active snooze on the recovery prompt expires (RFC 3339), if one is active. A
183 /// snooze ending *before* `recovery_next_due` does not make the check due earlier. This is
184 /// the canonical place to snooze the recovery check — not
185 /// [`suppressed_until`](Self::suppressed_until), which is for the other five classes.
186 #[uniffi(default = None)]
187 pub recovery_snoozed_until: Option<String>,
188 /// Whether the consecutive-snooze budget is spent — the class has degraded to a persistent,
189 /// non-blocking badge: still reported, no longer pre-armed.
190 #[uniffi(default = false)]
191 pub recovery_snooze_budget_spent: bool,
192 /// Whether the scheduler has escalated to the guided re-wrap (repeated failures, or the user
193 /// declaring the secret lost). Surfaces as the alert's `recovery` parameter, so the app
194 /// routes into the re-wrap flow instead of rendering a routine verification prompt.
195 #[uniffi(default = false)]
196 pub recovery_rewrap_due: bool,
197 /// The state from the last `GET /v1/quota`. `None` before the first one.
198 #[uniffi(default = None)]
199 pub quota_state: Option<FfiQuotaAdvisory>,
200 /// How many items sit on the client's quarantine surfaces awaiting a human. **Excludes
201 /// pending drops** — they have their own class, so counting them here raises both.
202 #[uniffi(default = 0)]
203 pub quarantine_pending: u64,
204 /// How many guest drops are awaiting review and adoption.
205 #[uniffi(default = 0)]
206 pub drops_pending: u64,
207 /// Per-class **snooze**: class wire name (`sync_stale`, …) to the RFC 3339 instant the
208 /// snooze runs until, exclusive. A class snoozed past `now` reports nothing, and its alarm
209 /// is **deferred to the snooze end** rather than cancelled — a class snoozed after it fired
210 /// must fire again when the snooze expires. Use [`disabled`](Self::disabled) to turn a class
211 /// off; do not encode that as a far-future instant here. An unrecognized class name is an
212 /// [`FfiError::InvalidArgument`].
213 ///
214 /// **This map is for the other five classes.** Recovery snoozing belongs in
215 /// [`recovery_snoozed_until`](Self::recovery_snoozed_until), which the cadence scheduler
216 /// owns together with the budget that bounds it. An entry here for `recovery_check_due` is
217 /// honoured as a fallback (the later of the two wins) but is not the canonical channel.
218 #[uniffi(default)]
219 pub suppressed_until: HashMap<String, String>,
220 /// Per-class **disable**: the wire names of the classes the user turned off. They report
221 /// nothing and hold no alarm, at any instant. Disabling suppresses the warning and never
222 /// the behavior. An unrecognized class name is an [`FfiError::InvalidArgument`].
223 #[uniffi(default)]
224 pub disabled: Vec<String>,
225}
226
227impl FfiNotifyInput {
228 /// Parse the foreign record into the core input, rejecting every malformed field rather
229 /// than defaulting past it: a mistyped instant that silently became "never" would suppress
230 /// an alert forever, which is exactly the failure this alert surface exists to prevent.
231 fn parse(self) -> Result<NotifyInput, FfiError> {
232 let sync = self
233 .last_completed_sync
234 .map(|raw| {
235 Ok::<_, FfiError>(SyncFacts {
236 last_completed_sync: parse_instant(&raw, "last_completed_sync")?,
237 unsynced_changes: self.unsynced_changes,
238 })
239 })
240 .transpose()?;
241
242 // Parsed unconditionally, and *before* the `recovery_next_due` branch: a malformed
243 // snooze instant is a malformed field whether or not the due date happens to be present,
244 // and a validation that only runs on one code path is the one that lets a typo through.
245 let snoozed_until = self
246 .recovery_snoozed_until
247 .as_deref()
248 .map(|raw| parse_instant(raw, "recovery_snoozed_until"))
249 .transpose()?;
250 let recovery = self
251 .recovery_next_due
252 .map(|raw| {
253 Ok::<_, FfiError>(RecoveryFacts {
254 next_due: parse_instant(&raw, "recovery_next_due")?,
255 snoozed_until,
256 snooze_budget_spent: self.recovery_snooze_budget_spent,
257 rewrap_due: self.recovery_rewrap_due,
258 })
259 })
260 .transpose()?;
261
262 let mut suppressed = BTreeMap::new();
263 for (name, raw) in self.suppressed_until {
264 suppressed.insert(
265 parse_class(&name, "suppressed_until")?,
266 parse_instant(&raw, "suppressed_until")?,
267 );
268 }
269 let mut disabled = BTreeSet::new();
270 for name in self.disabled {
271 disabled.insert(parse_class(&name, "disabled")?);
272 }
273
274 Ok(NotifyInput {
275 sync,
276 recovery,
277 quota: self.quota_state.map(|state| QuotaFacts {
278 state: state.into(),
279 }),
280 quarantine_pending: self.quarantine_pending,
281 drops_pending: self.drops_pending,
282 suppressed,
283 disabled,
284 })
285 }
286}
287
288/// Parse one alert-class wire name against the closed enum, naming the field it came from.
289fn parse_class(name: &str, field: &str) -> Result<AlertClass, FfiError> {
290 AlertClass::from_wire(name).ok_or_else(|| FfiError::InvalidArgument {
291 detail: format!("{field}: `{name}` is not an alert class"),
292 })
293}
294
295/// Parse one RFC 3339 instant, naming the field so a foreign caller can find its own bug.
296fn parse_instant(raw: &str, field: &str) -> Result<Timestamp, FfiError> {
297 raw.parse::<Timestamp>()
298 .map_err(|err| FfiError::InvalidArgument {
299 detail: format!("{field}: `{raw}` is not an RFC 3339 timestamp: {err}"),
300 })
301}
302
303/// Every alert that is true at `now`, in delivery order.
304///
305/// Pure and offline: no network call, no library open, no clock read — `now` is the caller's, so
306/// the same input always gives the same answer and an app can drive it from a test clock.
307///
308/// # Errors
309///
310/// [`FfiError::InvalidArgument`] if `now` or any instant in `input` is not RFC 3339, or if
311/// `suppressed_until` names something that is not an alert class.
312#[uniffi::export]
313pub fn evaluate_alerts(input: FfiNotifyInput, now: String) -> Result<Vec<FfiAlert>, FfiError> {
314 let now = parse_instant(&now, "now")?;
315 Ok(notify::evaluate(&input.parse()?, now)
316 .into_iter()
317 .map(FfiAlert::from)
318 .collect())
319}
320
321/// The instant to arm a local notification for, **per class** — the call an app schedules its
322/// `UNCalendarNotificationTrigger` / `AlarmManager` alarms from.
323///
324/// Reconcile your timers against the result: a class present here should hold exactly one alarm
325/// at the returned instant, and a class absent from it should hold none. Recompute after **any**
326/// state change; that is the whole of the arm / re-arm / cancel rule on the client side.
327///
328/// Only the two classes whose deadline a device can compute alone ever appear. The other three
329/// depend on server state and surface at next app launch — a real gap the design accepts.
330///
331/// # Errors
332///
333/// As [`evaluate_alerts`].
334#[uniffi::export]
335pub fn pre_arm_deadlines(
336 input: FfiNotifyInput,
337 now: String,
338) -> Result<Vec<FfiClassDeadline>, FfiError> {
339 let now = parse_instant(&now, "now")?;
340 Ok(notify::pre_arm_deadlines(&input.parse()?, now)
341 .into_iter()
342 .map(|(class, deadline)| FfiClassDeadline {
343 class: class.into(),
344 deadline: deadline.to_string(),
345 })
346 .collect())
347}
348
349/// The earliest instant in [`pre_arm_deadlines`] (RFC 3339), or `None` when there is nothing to
350/// arm.
351///
352/// For a host that can hold only one timer. **An app that schedules per class wants
353/// [`pre_arm_deadlines`]**: the minimum discards the later class's alarm, and on a device the app
354/// never runs on again that alert is simply lost.
355///
356/// # Errors
357///
358/// As [`evaluate_alerts`].
359#[uniffi::export]
360pub fn next_alert_deadline(input: FfiNotifyInput, now: String) -> Result<Option<String>, FfiError> {
361 let now = parse_instant(&now, "now")?;
362 Ok(notify::next_deadline(&input.parse()?, now).map(|deadline| deadline.to_string()))
363}
364
365#[cfg(test)]
366mod tests;