use axum::response::sse::{Event, KeepAlive, Sse};
use futures_util::Stream;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
use tokio_stream::StreamExt;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeMessage {
pub topic: String,
pub event: String,
pub data: String,
}
#[derive(Debug, Clone, Default)]
pub struct Realtime {
topics: Arc<RwLock<HashMap<String, broadcast::Sender<RealtimeMessage>>>>,
}
impl Realtime {
#[must_use]
pub fn new() -> Self {
Self::default()
}
fn sender_for(&self, topic: &str) -> broadcast::Sender<RealtimeMessage> {
{
let guard = self.topics.read().expect("realtime rwlock poisoned");
if let Some(tx) = guard.get(topic) {
return tx.clone();
}
}
let mut guard = self.topics.write().expect("realtime rwlock poisoned");
guard
.entry(topic.to_string())
.or_insert_with(|| broadcast::channel(256).0)
.clone()
}
pub fn subscribe(&self, topic: &str) -> broadcast::Receiver<RealtimeMessage> {
self.sender_for(topic).subscribe()
}
pub fn publish_text(&self, topic: &str, event: &str, data: impl Into<String>) -> usize {
let tx = self.sender_for(topic);
let msg = RealtimeMessage {
topic: topic.to_string(),
event: event.to_string(),
data: data.into(),
};
tx.send(msg).unwrap_or(0)
}
pub fn publish_json<T: Serialize>(&self, topic: &str, event: &str, payload: &T) -> usize {
let data = serde_json::to_string(payload).unwrap_or_else(|_| "{}".into());
self.publish_text(topic, event, data)
}
pub fn publish_html(&self, topic: &str, event: &str, html: impl Into<String>) -> usize {
self.publish_text(topic, event, html)
}
pub fn sse_stream(&self, topic: &str) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let rx = self.subscribe(topic);
let stream = BroadcastStream::new(rx).filter_map(|item| match item {
Ok(msg) => Some(Ok(Event::default().event(msg.event).data(msg.data))),
Err(_) => None,
});
Sse::new(stream).keep_alive(
KeepAlive::new()
.interval(Duration::from_secs(15))
.text("ping"),
)
}
}