use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use axum::body::Bytes;
use axum::extract::ws::Message;
use dashmap::DashMap;
use tokio::sync::{mpsc, watch};
use crate::frame::Frame;
#[derive(Clone)]
pub struct Host {
pub epoch: u64,
pub tx: mpsc::UnboundedSender<Message>,
}
struct Stream {
epoch: u64,
tx: mpsc::UnboundedSender<Bytes>,
}
pub struct Conduit {
next_id: AtomicU32,
next_epoch: AtomicU64,
streams: DashMap<u32, Stream>,
host: watch::Sender<Option<Host>>,
}
impl Conduit {
pub fn new() -> Arc<Self> {
Arc::new(Self {
next_id: AtomicU32::new(1),
next_epoch: AtomicU64::new(1),
streams: DashMap::new(),
host: watch::channel(None).0,
})
}
pub async fn host(&self) -> Option<Host> {
let mut rx = self.host.subscribe();
loop {
if let Some(host) = rx.borrow_and_update().clone() {
return Some(host);
}
rx.changed().await.ok()?;
}
}
pub async fn detached(&self, epoch: u64) {
let mut rx = self.host.subscribe();
while rx
.borrow_and_update()
.as_ref()
.is_some_and(|host| host.epoch == epoch)
{
if rx.changed().await.is_err() {
return;
}
}
}
pub fn attach(&self, tx: mpsc::UnboundedSender<Message>) -> u64 {
let epoch = self.next_epoch.fetch_add(1, Ordering::Relaxed);
self.host.send_replace(Some(Host { epoch, tx }));
epoch
}
pub fn detach(&self, epoch: u64) {
self.host.send_if_modified(|slot| {
if slot.as_ref().is_some_and(|host| host.epoch == epoch) {
*slot = None;
true
} else {
false
}
});
self.streams.retain(|_, stream| stream.epoch != epoch);
}
pub fn open(&self, epoch: u64, tx: mpsc::UnboundedSender<Bytes>) -> u32 {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
self.streams.insert(id, Stream { epoch, tx });
id
}
pub fn close(&self, id: u32) {
self.streams.remove(&id);
}
pub fn route(&self, frame: Frame) {
match frame {
Frame::Data { id, payload } => {
let gone = match self.streams.get(&id) {
Some(stream) => stream.tx.send(payload).is_err(),
None => false,
};
if gone {
self.streams.remove(&id);
}
}
Frame::Close { id } => {
self.streams.remove(&id);
}
Frame::Open { .. } => {}
}
}
}