1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/server-sent-events/src/broadcast.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

2022-08-07 02:24:40 +02:00
use std::{sync::Arc, time::Duration};
use actix_web::rt::time::interval;
2022-08-08 00:12:52 +02:00
use actix_web_lab::sse::{sse, Sse, SseData, SseMessage, SseSender};
2022-08-07 02:24:40 +02:00
use futures_util::future;
2022-02-14 02:37:51 +01:00
use parking_lot::Mutex;
pub struct Broadcaster {
inner: Mutex<BroadcasterInner>,
}
2022-08-07 02:24:40 +02:00
#[derive(Debug, Clone, Default)]
struct BroadcasterInner {
2022-08-07 02:24:40 +02:00
clients: Vec<SseSender>,
2022-02-14 02:37:51 +01:00
}
impl Broadcaster {
2022-08-07 02:24:40 +02:00
/// Constructs new broadcaster and spawns ping loop.
pub fn create() -> Arc<Self> {
let this = Arc::new(Broadcaster {
inner: Mutex::new(BroadcasterInner::default()),
});
2022-02-14 02:37:51 +01:00
2022-08-07 02:24:40 +02:00
Broadcaster::spawn_ping(Arc::clone(&this));
2022-02-14 02:37:51 +01:00
2022-08-07 02:24:40 +02:00
this
2022-02-14 02:37:51 +01:00
}
2022-08-07 02:24:40 +02:00
/// Pings clients every 10 seconds to see if they are alive and remove them from the broadcast
/// list if not.
fn spawn_ping(this: Arc<Self>) {
2022-02-14 02:37:51 +01:00
actix_web::rt::spawn(async move {
2022-08-07 02:24:40 +02:00
let mut interval = interval(Duration::from_secs(10));
2022-02-14 02:37:51 +01:00
loop {
interval.tick().await;
2022-08-07 02:24:40 +02:00
this.remove_stale_clients().await;
2022-02-14 02:37:51 +01:00
}
});
}
2022-08-07 02:24:40 +02:00
/// Removes all non-responsive clients from broadcast list.
async fn remove_stale_clients(&self) {
let clients = self.inner.lock().clients.clone();
2022-02-14 02:37:51 +01:00
let mut ok_clients = Vec::new();
2022-08-07 02:24:40 +02:00
for client in clients {
2022-08-08 00:12:52 +02:00
if client
.send(SseMessage::Comment("ping".into()))
.await
.is_ok()
{
2022-02-14 02:37:51 +01:00
ok_clients.push(client.clone());
}
}
2022-08-07 02:24:40 +02:00
self.inner.lock().clients = ok_clients;
}
2022-02-14 02:37:51 +01:00
2022-08-07 02:24:40 +02:00
/// Registers client with broadcaster, returning an SSE response body.
pub async fn new_client(&self) -> Sse {
let (tx, rx) = sse(10);
2022-08-08 00:12:52 +02:00
tx.send(SseData::new("connected")).await.unwrap();
2022-02-14 02:37:51 +01:00
2022-08-07 02:24:40 +02:00
self.inner.lock().clients.push(tx);
2022-02-14 02:37:51 +01:00
2022-08-07 02:24:40 +02:00
rx
2022-02-14 02:37:51 +01:00
}
2022-08-07 02:24:40 +02:00
/// Broadcasts `msg` to all clients.
pub async fn broadcast(&self, msg: &str) {
let clients = self.inner.lock().clients.clone();
2022-02-14 02:37:51 +01:00
2022-08-08 00:12:52 +02:00
let send_futures = clients.iter().map(|client| client.send(SseData::new(msg)));
2022-02-14 02:37:51 +01:00
2022-08-07 02:24:40 +02:00
// try to send to all clients, ignoring failures
// disconnected clients will get swept up by `remove_stale_clients`
let _ = future::join_all(send_futures).await;
2022-02-14 02:37:51 +01:00
}
}