95 lines
2.5 KiB
Rust
Raw Normal View History

2021-07-21 15:43:05 +08:00
pub mod entities;
mod protobuf;
use crate::entities::SubscribeObject;
use bytes::Bytes;
use lazy_static::lazy_static;
use lib_dispatch::prelude::ToBytes;
use std::sync::RwLock;
2021-09-07 23:30:43 +08:00
lazy_static! {
static ref NOTIFICATION_SENDER: RwLock<Vec<Box<dyn NotificationSender>>> = RwLock::new(vec![]);
}
pub fn register_notification_sender<T: NotificationSender>(sender: T) {
let box_sender = Box::new(sender);
match NOTIFICATION_SENDER.write() {
Ok(mut write_guard) => write_guard.push(box_sender),
Err(err) => tracing::error!("Failed to push notification sender: {:?}", err),
}
}
pub trait NotificationSender: Send + Sync + 'static {
fn send_subject(&self, subject: SubscribeObject) -> Result<(), String>;
}
pub struct NotificationBuilder {
2021-09-07 23:30:43 +08:00
id: String,
payload: Option<Bytes>,
error: Option<Bytes>,
source: String,
2021-09-07 23:30:43 +08:00
ty: i32,
}
impl NotificationBuilder {
pub fn new<T: Into<i32>>(id: &str, ty: T, source: &str) -> Self {
2021-09-07 23:30:43 +08:00
Self {
id: id.to_owned(),
ty: ty.into(),
payload: None,
error: None,
source: source.to_owned(),
2021-09-07 23:30:43 +08:00
}
}
pub fn payload<T>(mut self, payload: T) -> Self
where
T: ToBytes,
{
match payload.into_bytes() {
Ok(bytes) => self.payload = Some(bytes),
Err(e) => {
tracing::error!("Set observable payload failed: {:?}", e);
2022-01-23 12:14:00 +08:00
}
2021-09-07 23:30:43 +08:00
}
self
}
pub fn error<T>(mut self, error: T) -> Self
where
T: ToBytes,
{
match error.into_bytes() {
Ok(bytes) => self.error = Some(bytes),
Err(e) => {
tracing::error!("Set observable error failed: {:?}", e);
2022-01-23 12:14:00 +08:00
}
2021-09-07 23:30:43 +08:00
}
self
}
2021-09-11 14:26:30 +08:00
pub fn send(self) {
2021-11-27 19:19:41 +08:00
let payload = self.payload.map(|bytes| bytes.to_vec());
let error = self.error.map(|bytes| bytes.to_vec());
2021-10-14 14:34:22 +08:00
let subject = SubscribeObject {
source: self.source,
2021-09-07 23:30:43 +08:00
ty: self.ty,
id: self.id,
payload,
error,
};
2021-09-08 18:25:32 +08:00
match NOTIFICATION_SENDER.read() {
Ok(read_guard) => read_guard.iter().for_each(|sender| {
if let Err(e) = sender.send_subject(subject.clone()) {
tracing::error!("Post notification failed: {}", e);
}
}),
Err(err) => {
tracing::error!("Read notification sender failed: {}", err);
}
2021-09-07 23:30:43 +08:00
}
2021-07-21 15:43:05 +08:00
}
}