Skip to main content

egui_pop_model/
notice.rs

1//! Notices: one message for people (an error, a warning, a success, a
2//! piece of information, a question), raised once and shown by whichever
3//! views an application's policy picks.
4//!
5//! A [`Notice`] is plain data, without egui: a headless process (a
6//! background service, a node on another machine) raises the same fact
7//! an interface does. It is said on the bus as `pop.notice.raised`
8//! ([`points::RAISED`]); a condition that ends is said as
9//! `pop.notice.resolved`, a notice read as `pop.notice.seen` and one put
10//! away by the user as `pop.notice.dismissed`, each a [`NoticeIds`].
11//! [`NoticeStore`] keeps the last notices raised, bounded.
12//!
13//! ```
14//! use egui_pop_model::notice::{Notice, Origin, Severity};
15//!
16//! let n = Notice::error("cloudy was not added")
17//!     .reason("The network found no route to it.")
18//!     .hint("Check that cloudy is on and on the same network.")
19//!     .details("cannot enrol with cloudy: connect: No route to host (os error 113)")
20//!     .origin(Origin::User)
21//!     .subject("node:cloudy")
22//!     .place("settings/storage/nodes")
23//!     .action("nodes.add", "Try again");
24//! assert_eq!(n.severity, Severity::Error);
25//! assert_eq!(n.actions[0].label, "Try again");
26//! ```
27//!
28//! The JSON shape is stable: fields are added, never renamed, and
29//! [`VERSION`] (`v`) rises when a field changes meaning. Empty fields are
30//! left out.
31//!
32//! <div class="warning">Experimental: may change in any release
33//! (docs/stability.md).</div>
34
35pub mod route;
36
37use std::collections::{BTreeMap, VecDeque};
38use std::fmt;
39
40use serde::{Deserialize, Serialize};
41
42/// The version of the notice's JSON shape (`v`).
43pub const VERSION: u32 = 1;
44
45/// The bus points of notices, by name (egui-pop declares them; a process
46/// without egui-pop publishes on them by these names).
47pub mod points {
48    /// A notice is raised: a [`super::Notice`].
49    pub const RAISED: &str = "pop.notice.raised";
50    /// A condition ended: a [`super::NoticeIds`].
51    pub const RESOLVED: &str = "pop.notice.resolved";
52    /// Notices were read (shown to the user and acknowledged): a
53    /// [`super::NoticeIds`].
54    pub const SEEN: &str = "pop.notice.seen";
55    /// Notices were put away by the user: a [`super::NoticeIds`].
56    pub const DISMISSED: &str = "pop.notice.dismissed";
57}
58
59/// A notice's id: unique in the process that raised it (`n42`); a notice
60/// from another node carries that node's name before it (`cloudy/n42`).
61#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
62#[serde(transparent)]
63pub struct NoticeId(String);
64
65impl NoticeId {
66    pub fn new(id: impl Into<String>) -> Self {
67        Self(id.into())
68    }
69
70    /// The `n`th id of a process (`n<seq>`).
71    pub fn nth(seq: u64) -> Self {
72        Self(format!("n{seq}"))
73    }
74
75    pub fn as_str(&self) -> &str {
76        &self.0
77    }
78
79    /// Whether no id was given yet (the store gives one when it is raised).
80    pub fn is_empty(&self) -> bool {
81        self.0.is_empty()
82    }
83}
84
85impl fmt::Display for NoticeId {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(&self.0)
88    }
89}
90
91impl From<&str> for NoticeId {
92    fn from(s: &str) -> Self {
93        Self::new(s)
94    }
95}
96
97impl From<String> for NoticeId {
98    fn from(s: String) -> Self {
99        Self(s)
100    }
101}
102
103/// How serious a notice is.
104#[derive(
105    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
106)]
107#[serde(rename_all = "lowercase")]
108pub enum Severity {
109    /// Worth knowing; nothing to do.
110    #[default]
111    Info,
112    /// An outcome the user waited for.
113    Success,
114    /// Done, but partly or with a risk; the user may act.
115    Warning,
116    /// Not done; the user must act or accept the loss.
117    Error,
118}
119
120/// What kind of fact a notice is.
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
122#[serde(rename_all = "lowercase")]
123pub enum Kind {
124    /// Something happened, once.
125    #[default]
126    Event,
127    /// A state that lasts until it is resolved (a node offline, a disk
128    /// full): `pop.notice.resolved` ends it.
129    Condition,
130    /// A question waiting for the user's answer.
131    Ask,
132}
133
134/// Where a notice comes from.
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(rename_all = "lowercase")]
137pub enum Origin {
138    /// The user's own action: they are looking.
139    #[default]
140    User,
141    /// Background work (jobs, schedulers, watchers).
142    Background,
143    /// Another node (its name in [`Notice::node`]).
144    Node,
145    /// The system: start-up, a crash, the graphics device, a disk.
146    System,
147}
148
149/// A button of a notice: the command or action it runs, by id, its
150/// label, and the arguments the command runs with (`null`, the default,
151/// for none): "Undo *this* restore", "Show *these* photos".
152#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
153#[non_exhaustive]
154pub struct NoticeAction {
155    pub id: String,
156    pub label: String,
157    /// The command's arguments; left out of the JSON when `null`.
158    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
159    pub args: serde_json::Value,
160}
161
162impl NoticeAction {
163    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
164        Self {
165            id: id.into(),
166            label: label.into(),
167            args: serde_json::Value::Null,
168        }
169    }
170
171    /// The arguments its command runs with.
172    pub fn with_args(mut self, args: serde_json::Value) -> Self {
173        self.args = args;
174        self
175    }
176}
177
178/// One message for people: see the [module](self).
179#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180#[non_exhaustive]
181#[must_use]
182pub struct Notice {
183    /// The version of its JSON shape ([`VERSION`]).
184    #[serde(default = "version")]
185    pub v: u32,
186    /// Its id; empty until it is raised (the store gives one).
187    #[serde(default, skip_serializing_if = "NoticeId::is_empty")]
188    pub id: NoticeId,
189    /// When it happened, in milliseconds since 1970 (UTC); 0 until it is
190    /// raised (raising it sets now).
191    #[serde(default)]
192    pub at_ms: u64,
193    pub severity: Severity,
194    #[serde(default)]
195    pub kind: Kind,
196    #[serde(default)]
197    pub origin: Origin,
198    /// What happened, in the user's words: "cloudy was not added".
199    pub headline: String,
200    /// Why, in the user's words, when known.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub reason: Option<String>,
203    /// What the user can do about it.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub hint: Option<String>,
206    /// The technical chain (an error's sources), copyable.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub details: Option<String>,
209    /// Its buttons, in order.
210    #[serde(default, skip_serializing_if = "Vec::is_empty")]
211    pub actions: Vec<NoticeAction>,
212    /// What it is about (a photo, a job, a node: `node:cloudy`).
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub subject: Option<String>,
215    /// Where it happened in the interface (a window, a panel, a page:
216    /// `settings/storage/nodes`).
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub place: Option<String>,
219    /// The node it happened on, for a notice from another node.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub node: Option<String>,
222}
223
224fn version() -> u32 {
225    VERSION
226}
227
228/// A blank text is no text.
229fn some(text: impl Into<String>) -> Option<String> {
230    Some(text.into()).filter(|t| !t.trim().is_empty())
231}
232
233impl Notice {
234    pub fn new(severity: Severity, headline: impl Into<String>) -> Self {
235        Self {
236            v: VERSION,
237            id: NoticeId::default(),
238            at_ms: 0,
239            severity,
240            kind: Kind::Event,
241            origin: Origin::User,
242            headline: headline.into(),
243            reason: None,
244            hint: None,
245            details: None,
246            actions: Vec::new(),
247            subject: None,
248            place: None,
249            node: None,
250        }
251    }
252
253    pub fn info(headline: impl Into<String>) -> Self {
254        Self::new(Severity::Info, headline)
255    }
256
257    pub fn success(headline: impl Into<String>) -> Self {
258        Self::new(Severity::Success, headline)
259    }
260
261    pub fn warning(headline: impl Into<String>) -> Self {
262        Self::new(Severity::Warning, headline)
263    }
264
265    pub fn error(headline: impl Into<String>) -> Self {
266        Self::new(Severity::Error, headline)
267    }
268
269    /// Its id (by default the store gives one when it is raised).
270    pub fn id(mut self, id: impl Into<NoticeId>) -> Self {
271        self.id = id.into();
272        self
273    }
274
275    /// When it happened, in milliseconds since 1970 (by default, when it
276    /// is raised).
277    pub fn at_ms(mut self, at_ms: u64) -> Self {
278        self.at_ms = at_ms;
279        self
280    }
281
282    pub fn kind(mut self, kind: Kind) -> Self {
283        self.kind = kind;
284        self
285    }
286
287    /// A condition: it lasts until it is resolved.
288    pub fn condition(self) -> Self {
289        self.kind(Kind::Condition)
290    }
291
292    /// A question waiting for the user's answer.
293    pub fn ask(self) -> Self {
294        self.kind(Kind::Ask)
295    }
296
297    pub fn origin(mut self, origin: Origin) -> Self {
298        self.origin = origin;
299        self
300    }
301
302    /// Why (left out when blank).
303    pub fn reason(mut self, reason: impl Into<String>) -> Self {
304        self.reason = some(reason);
305        self
306    }
307
308    /// What to do (left out when blank).
309    pub fn hint(mut self, hint: impl Into<String>) -> Self {
310        self.hint = some(hint);
311        self
312    }
313
314    /// The technical chain (left out when blank).
315    pub fn details(mut self, details: impl Into<String>) -> Self {
316        self.details = some(details);
317        self
318    }
319
320    /// The chain of an error and its sources, one per line.
321    pub fn details_from(self, err: &(dyn std::error::Error + 'static)) -> Self {
322        let mut chain = err.to_string();
323        let mut source = err.source();
324        while let Some(s) = source {
325            chain.push('\n');
326            chain.push_str(&s.to_string());
327            source = s.source();
328        }
329        self.details(chain)
330    }
331
332    /// A button, after the others.
333    pub fn action(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
334        self.actions.push(NoticeAction::new(id, label));
335        self
336    }
337
338    /// A button whose command runs with `args`, after the others: "Undo
339    /// this restore" (`{"restore": 7}`). The arguments are kept with the
340    /// notice, saved with it, and given to the command when the button
341    /// runs it, from a toast, a notice site or the Notices panel.
342    pub fn action_with(
343        mut self,
344        id: impl Into<String>,
345        label: impl Into<String>,
346        args: serde_json::Value,
347    ) -> Self {
348        self.actions
349            .push(NoticeAction::new(id, label).with_args(args));
350        self
351    }
352
353    pub fn subject(mut self, subject: impl Into<String>) -> Self {
354        self.subject = some(subject);
355        self
356    }
357
358    pub fn place(mut self, place: impl Into<String>) -> Self {
359        self.place = some(place);
360        self
361    }
362
363    /// The node it happened on; its origin becomes [`Origin::Node`].
364    pub fn node(mut self, node: impl Into<String>) -> Self {
365        self.node = some(node);
366        if self.node.is_some() {
367            self.origin = Origin::Node;
368        }
369        self
370    }
371}
372
373/// The notices a `pop.notice.resolved`, `pop.notice.seen` or
374/// `pop.notice.dismissed` names.
375#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
376#[non_exhaustive]
377pub struct NoticeIds {
378    pub ids: Vec<NoticeId>,
379}
380
381impl NoticeIds {
382    pub fn new(ids: impl IntoIterator<Item = NoticeId>) -> Self {
383        Self {
384            ids: ids.into_iter().collect(),
385        }
386    }
387
388    /// One notice.
389    pub fn one(id: impl Into<NoticeId>) -> Self {
390        Self {
391            ids: vec![id.into()],
392        }
393    }
394}
395
396/// A notice as the store keeps it: whether it was seen, and for a
397/// condition whether it was resolved.
398#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
399#[non_exhaustive]
400pub struct Kept {
401    pub notice: Notice,
402    #[serde(default)]
403    pub seen: bool,
404    #[serde(default)]
405    pub resolved: bool,
406}
407
408/// The last notices raised, oldest first, at most [`NoticeStore::bound`]
409/// and none older than [`NoticeStore::max_age_ms`], whichever keeps
410/// fewer: the oldest goes when a new one comes past the bound, and
411/// [`NoticeStore::prune`] drops the old ones. An error not seen yet stays
412/// until it is seen, past both. Seen and resolved notices are marked;
413/// dismissed ones leave.
414#[derive(Clone, Debug)]
415pub struct NoticeStore {
416    kept: VecDeque<Kept>,
417    bound: usize,
418    max_age_ms: u64,
419    next: u64,
420    rev: u64,
421}
422
423impl Default for NoticeStore {
424    fn default() -> Self {
425        Self::new(NoticeStore::DEFAULT_BOUND)
426    }
427}
428
429/// An error not seen yet: kept past the bound and the age.
430fn kept_anyway(k: &Kept) -> bool {
431    !k.seen && k.notice.severity == Severity::Error
432}
433
434impl NoticeStore {
435    /// How many notices a store keeps by default.
436    pub const DEFAULT_BOUND: usize = 500;
437
438    /// How old a notice a store keeps by default: 30 days, in
439    /// milliseconds.
440    pub const DEFAULT_MAX_AGE_MS: u64 = 30 * 24 * 60 * 60 * 1000;
441
442    /// A store keeping at most `bound` notices (at least one), for
443    /// [`NoticeStore::DEFAULT_MAX_AGE_MS`].
444    pub fn new(bound: usize) -> Self {
445        Self {
446            kept: VecDeque::new(),
447            bound: bound.max(1),
448            max_age_ms: Self::DEFAULT_MAX_AGE_MS,
449            next: 1,
450            rev: 0,
451        }
452    }
453
454    /// Keeping notices for `max_age_ms` milliseconds.
455    pub fn with_max_age(mut self, max_age_ms: u64) -> Self {
456        self.max_age_ms = max_age_ms;
457        self
458    }
459
460    pub fn bound(&self) -> usize {
461        self.bound
462    }
463
464    /// Keeps at most `bound` notices (at least one), none older than
465    /// `max_age_ms` (errors not seen yet aside), from now on.
466    pub fn set_limits(&mut self, bound: usize, max_age_ms: u64) {
467        self.bound = bound.max(1);
468        self.max_age_ms = max_age_ms;
469        self.trim();
470    }
471
472    /// How old a notice it keeps, in milliseconds.
473    pub fn max_age_ms(&self) -> u64 {
474        self.max_age_ms
475    }
476
477    /// A number that changes whenever what it keeps changes (to save it
478    /// when it moved).
479    pub fn rev(&self) -> u64 {
480        self.rev
481    }
482
483    /// The id the next notice raised without one gets.
484    pub fn next_id(&mut self) -> NoticeId {
485        let id = NoticeId::nth(self.next);
486        self.next += 1;
487        id
488    }
489
490    /// Keeps `notice` (one with the same id is replaced, in its place);
491    /// the oldest leaves past the bound, unless it is an error not seen
492    /// yet.
493    pub fn add(&mut self, notice: Notice) {
494        self.rev += 1;
495        if let Some(k) = self.kept.iter_mut().find(|k| k.notice.id == notice.id) {
496            *k = Kept {
497                notice,
498                seen: false,
499                resolved: false,
500            };
501            return;
502        }
503        self.kept.push_back(Kept {
504            notice,
505            seen: false,
506            resolved: false,
507        });
508        self.trim();
509    }
510
511    /// Drops the oldest notices past the bound, errors not seen yet
512    /// aside.
513    fn trim(&mut self) {
514        let mut over = self.kept.len().saturating_sub(self.bound);
515        if over == 0 {
516            return;
517        }
518        self.kept.retain(|k| {
519            if over > 0 && !kept_anyway(k) {
520                over -= 1;
521                false
522            } else {
523                true
524            }
525        });
526    }
527
528    /// Drops the notices older than [`NoticeStore::max_age_ms`] at
529    /// `now_ms` (milliseconds since 1970), errors not seen yet aside; how
530    /// many it dropped.
531    pub fn prune(&mut self, now_ms: u64) -> usize {
532        let since = now_ms.saturating_sub(self.max_age_ms);
533        let before = self.kept.len();
534        self.kept
535            .retain(|k| k.notice.at_ms >= since || kept_anyway(k));
536        let dropped = before - self.kept.len();
537        if dropped > 0 {
538            self.rev += 1;
539        }
540        dropped
541    }
542
543    /// Marks `ids` resolved; how many it held.
544    pub fn resolve(&mut self, ids: &[NoticeId]) -> usize {
545        self.mark(ids, |k| k.resolved = true)
546    }
547
548    /// Marks `ids` seen; how many it held.
549    pub fn see(&mut self, ids: &[NoticeId]) -> usize {
550        let n = self.mark(ids, |k| k.seen = true);
551        // An error seen may go now.
552        self.trim();
553        n
554    }
555
556    /// Drops `ids`; how many it held.
557    pub fn dismiss(&mut self, ids: &[NoticeId]) -> usize {
558        let before = self.kept.len();
559        self.kept.retain(|k| !ids.contains(&k.notice.id));
560        let n = before - self.kept.len();
561        if n > 0 {
562            self.rev += 1;
563        }
564        n
565    }
566
567    fn mark(&mut self, ids: &[NoticeId], f: impl Fn(&mut Kept)) -> usize {
568        let mut n = 0;
569        for k in self.kept.iter_mut().filter(|k| ids.contains(&k.notice.id)) {
570            f(k);
571            n += 1;
572        }
573        if n > 0 {
574            self.rev += 1;
575        }
576        n
577    }
578
579    /// A notice kept, by id.
580    pub fn get(&self, id: &NoticeId) -> Option<&Kept> {
581        self.kept.iter().find(|k| &k.notice.id == id)
582    }
583
584    /// The notices kept, oldest first.
585    pub fn list(&self) -> impl Iterator<Item = &Kept> {
586        self.kept.iter()
587    }
588
589    pub fn len(&self) -> usize {
590        self.kept.len()
591    }
592
593    pub fn is_empty(&self) -> bool {
594        self.kept.is_empty()
595    }
596
597    /// What it keeps, as its document (`routes` left empty).
598    pub fn to_doc(&self) -> NoticesDoc {
599        NoticesDoc {
600            notices: self.kept.iter().cloned().collect(),
601            routes: BTreeMap::new(),
602            next: self.next,
603        }
604    }
605
606    /// Takes back the notices of a document saved before: they come
607    /// first, oldest first, then the ones kept since (a saved one with
608    /// the same id gives way to the one kept since); the next id goes
609    /// past both; then the bound and the age at `now_ms` apply.
610    pub fn restore(&mut self, doc: &NoticesDoc, now_ms: u64) {
611        let since = std::mem::take(&mut self.kept);
612        let mut kept: VecDeque<Kept> = doc
613            .notices
614            .iter()
615            .filter(|k| !since.iter().any(|s| s.notice.id == k.notice.id))
616            .cloned()
617            .collect();
618        kept.extend(since);
619        self.kept = kept;
620        let past = self
621            .kept
622            .iter()
623            .filter_map(|k| k.notice.id.as_str().strip_prefix('n')?.parse::<u64>().ok())
624            .max()
625            .map_or(0, |n| n + 1);
626        self.next = self.next.max(doc.next).max(past);
627        self.rev += 1;
628        self.trim();
629        self.prune(now_ms);
630    }
631}
632
633/// The notices kept, as saved between sessions (the `notices` document,
634/// [`notices_schema`]): each notice with whether it was seen and
635/// resolved, the route each was given, and the next id.
636#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
637#[non_exhaustive]
638pub struct NoticesDoc {
639    #[serde(default)]
640    pub notices: Vec<Kept>,
641    /// The route each notice was given, by id.
642    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
643    pub routes: BTreeMap<NoticeId, route::Route>,
644    /// The id the next notice raised gets (`n<next>`).
645    #[serde(default)]
646    pub next: u64,
647}
648
649/// The `notices` document's schema: version 1; a document without a
650/// version has its shape.
651pub fn notices_schema() -> crate::doc::Schema {
652    crate::doc::Schema::new("notices", 1).migration(0, crate::doc::same)
653}