pingap_core/notification.rs
1// Copyright 2024-2025 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use async_trait::async_trait;
16use std::fmt::Display;
17
18/// Variants are declared from least to most severe so the derived `Ord`
19/// ranks them: a merged batch reports the highest level in it.
20#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
21pub enum NotificationLevel {
22 #[default]
23 Info,
24 Warn,
25 Error,
26}
27
28impl Display for NotificationLevel {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 let msg = match self {
31 NotificationLevel::Error => "error",
32 NotificationLevel::Warn => "warn",
33 _ => "info",
34 };
35 write!(f, "{msg}")
36 }
37}
38
39#[derive(Default, Clone, Debug)]
40pub struct NotificationData {
41 /// The category of the notification, used for grouping or filtering notifications
42 pub category: String,
43 /// The severity level of the notification (Info, Warn, Error)
44 pub level: NotificationLevel,
45 /// The title or subject of the notification
46 pub title: String,
47 /// The detailed message content of the notification
48 pub message: String,
49}
50
51/// Trait for sending notifications
52///
53/// Implementers of this trait can send notifications with different delivery methods
54/// (email, SMS, push notification, etc.)
55#[async_trait]
56pub trait Notification {
57 async fn notify(&self, data: NotificationData);
58}
59
60/// Type alias for a boxed Notification trait object that can be shared between threads
61pub type NotificationSender = Box<dyn Notification + Send + Sync>;
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_notification_level() {
69 let level = NotificationLevel::Error;
70 assert_eq!(level.to_string(), "error");
71 let level = NotificationLevel::Warn;
72 assert_eq!(level.to_string(), "warn");
73 let level = NotificationLevel::Info;
74 assert_eq!(level.to_string(), "info");
75 }
76}