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#[derive(Default)]
19pub enum NotificationLevel {
20 #[default]
21 Info,
22 Warn,
23 Error,
24}
25
26impl Display for NotificationLevel {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 let msg = match self {
29 NotificationLevel::Error => "error",
30 NotificationLevel::Warn => "warn",
31 _ => "info",
32 };
33 write!(f, "{msg}")
34 }
35}
36
37#[derive(Default)]
38pub struct NotificationData {
39 /// The category of the notification, used for grouping or filtering notifications
40 pub category: String,
41 /// The severity level of the notification (Info, Warn, Error)
42 pub level: NotificationLevel,
43 /// The title or subject of the notification
44 pub title: String,
45 /// The detailed message content of the notification
46 pub message: String,
47}
48
49/// Trait for sending notifications
50///
51/// Implementers of this trait can send notifications with different delivery methods
52/// (email, SMS, push notification, etc.)
53#[async_trait]
54pub trait Notification {
55 async fn notify(&self, data: NotificationData);
56}
57
58/// Type alias for a boxed Notification trait object that can be shared between threads
59pub type NotificationSender = Box<dyn Notification + Send + Sync>;
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn test_notification_level() {
67 let level = NotificationLevel::Error;
68 assert_eq!(level.to_string(), "error");
69 let level = NotificationLevel::Warn;
70 assert_eq!(level.to_string(), "warn");
71 let level = NotificationLevel::Info;
72 assert_eq!(level.to_string(), "info");
73 }
74}