1pub mod route;
36
37use std::collections::{BTreeMap, VecDeque};
38use std::fmt;
39
40use serde::{Deserialize, Serialize};
41
42pub const VERSION: u32 = 1;
44
45pub mod points {
48 pub const RAISED: &str = "pop.notice.raised";
50 pub const RESOLVED: &str = "pop.notice.resolved";
52 pub const SEEN: &str = "pop.notice.seen";
55 pub const DISMISSED: &str = "pop.notice.dismissed";
57}
58
59#[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 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 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#[derive(
105 Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
106)]
107#[serde(rename_all = "lowercase")]
108pub enum Severity {
109 #[default]
111 Info,
112 Success,
114 Warning,
116 Error,
118}
119
120#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
122#[serde(rename_all = "lowercase")]
123pub enum Kind {
124 #[default]
126 Event,
127 Condition,
130 Ask,
132}
133
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(rename_all = "lowercase")]
137pub enum Origin {
138 #[default]
140 User,
141 Background,
143 Node,
145 System,
147}
148
149#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
153#[non_exhaustive]
154pub struct NoticeAction {
155 pub id: String,
156 pub label: String,
157 #[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 pub fn with_args(mut self, args: serde_json::Value) -> Self {
173 self.args = args;
174 self
175 }
176}
177
178#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180#[non_exhaustive]
181#[must_use]
182pub struct Notice {
183 #[serde(default = "version")]
185 pub v: u32,
186 #[serde(default, skip_serializing_if = "NoticeId::is_empty")]
188 pub id: NoticeId,
189 #[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 pub headline: String,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub reason: Option<String>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub hint: Option<String>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub details: Option<String>,
209 #[serde(default, skip_serializing_if = "Vec::is_empty")]
211 pub actions: Vec<NoticeAction>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub subject: Option<String>,
215 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub place: Option<String>,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub node: Option<String>,
222}
223
224fn version() -> u32 {
225 VERSION
226}
227
228fn 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 pub fn id(mut self, id: impl Into<NoticeId>) -> Self {
271 self.id = id.into();
272 self
273 }
274
275 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 pub fn condition(self) -> Self {
289 self.kind(Kind::Condition)
290 }
291
292 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 pub fn reason(mut self, reason: impl Into<String>) -> Self {
304 self.reason = some(reason);
305 self
306 }
307
308 pub fn hint(mut self, hint: impl Into<String>) -> Self {
310 self.hint = some(hint);
311 self
312 }
313
314 pub fn details(mut self, details: impl Into<String>) -> Self {
316 self.details = some(details);
317 self
318 }
319
320 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 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 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 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#[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 pub fn one(id: impl Into<NoticeId>) -> Self {
390 Self {
391 ids: vec![id.into()],
392 }
393 }
394}
395
396#[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#[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
429fn kept_anyway(k: &Kept) -> bool {
431 !k.seen && k.notice.severity == Severity::Error
432}
433
434impl NoticeStore {
435 pub const DEFAULT_BOUND: usize = 500;
437
438 pub const DEFAULT_MAX_AGE_MS: u64 = 30 * 24 * 60 * 60 * 1000;
441
442 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 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 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 pub fn max_age_ms(&self) -> u64 {
474 self.max_age_ms
475 }
476
477 pub fn rev(&self) -> u64 {
480 self.rev
481 }
482
483 pub fn next_id(&mut self) -> NoticeId {
485 let id = NoticeId::nth(self.next);
486 self.next += 1;
487 id
488 }
489
490 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 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 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 pub fn resolve(&mut self, ids: &[NoticeId]) -> usize {
545 self.mark(ids, |k| k.resolved = true)
546 }
547
548 pub fn see(&mut self, ids: &[NoticeId]) -> usize {
550 let n = self.mark(ids, |k| k.seen = true);
551 self.trim();
553 n
554 }
555
556 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 pub fn get(&self, id: &NoticeId) -> Option<&Kept> {
581 self.kept.iter().find(|k| &k.notice.id == id)
582 }
583
584 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 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 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
637#[non_exhaustive]
638pub struct NoticesDoc {
639 #[serde(default)]
640 pub notices: Vec<Kept>,
641 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
643 pub routes: BTreeMap<NoticeId, route::Route>,
644 #[serde(default)]
646 pub next: u64,
647}
648
649pub fn notices_schema() -> crate::doc::Schema {
652 crate::doc::Schema::new("notices", 1).migration(0, crate::doc::same)
653}