use std::{
collections::{hash_map, HashMap, VecDeque},
fmt,
ops::Deref,
sync::Arc,
};
use crate::Error;
use super::{track, Watch};
pub fn new(name: &str) -> (Publisher, Subscriber, Unknown) {
let state = Watch::new(State::default());
let info = Arc::new(Info { name: name.to_string() });
let dropped = Arc::new(Dropped::new(state.clone()));
let publisher = Publisher::new(state.clone(), info.clone(), dropped.clone());
let subscriber = Subscriber::new(state.clone(), info.clone());
let unknown = Unknown::new(state, info, dropped);
(publisher, subscriber, unknown)
}
#[derive(Debug)]
pub struct Info {
pub name: String,
}
#[derive(Debug)]
struct State {
tracks: HashMap<String, track::Subscriber>,
requested: Option<VecDeque<track::Publisher>>, closed: Result<(), Error>,
}
impl State {
pub fn get(&self, name: &str) -> Result<Option<track::Subscriber>, Error> {
self.closed?;
Ok(self.tracks.get(name).cloned())
}
pub fn insert(&mut self, track: track::Subscriber) -> Result<(), Error> {
self.closed?;
match self.tracks.entry(track.name.clone()) {
hash_map::Entry::Occupied(_) => return Err(Error::Duplicate),
hash_map::Entry::Vacant(v) => v.insert(track),
};
Ok(())
}
pub fn request(&mut self, name: &str) -> Result<track::Subscriber, Error> {
self.closed?;
let requested = self.requested.as_mut().ok_or(Error::NotFound)?;
let (publisher, subscriber) = track::new(name);
self.tracks.insert(name.to_string(), subscriber.clone());
requested.push_back(publisher);
Ok(subscriber)
}
pub fn has_next(&self) -> Result<bool, Error> {
if self.requested.as_ref().filter(|q| !q.is_empty()).is_some() {
return Ok(true);
}
self.closed?;
Ok(false)
}
pub fn next(&mut self) -> track::Publisher {
self.requested
.as_mut()
.expect("queue closed")
.pop_front()
.expect("no entry in queue")
}
pub fn close(&mut self, err: Error) -> Result<(), Error> {
self.closed?;
self.closed = Err(err);
Ok(())
}
}
impl Default for State {
fn default() -> Self {
Self {
tracks: HashMap::new(),
closed: Ok(()),
requested: Some(VecDeque::new()),
}
}
}
#[derive(Clone)]
pub struct Publisher {
state: Watch<State>,
info: Arc<Info>,
_dropped: Arc<Dropped>,
}
impl Publisher {
fn new(state: Watch<State>, info: Arc<Info>, _dropped: Arc<Dropped>) -> Self {
Self { state, info, _dropped }
}
pub fn create_track(&mut self, name: &str) -> Result<track::Publisher, Error> {
let (publisher, subscriber) = track::new(name);
self.state.lock_mut().insert(subscriber)?;
Ok(publisher)
}
pub fn insert_track(&mut self, track: track::Subscriber) -> Result<(), Error> {
self.state.lock_mut().insert(track)
}
pub fn close(self, err: Error) -> Result<(), Error> {
self.state.lock_mut().close(err)
}
}
impl fmt::Debug for Publisher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Publisher")
.field("name", &self.name)
.field("state", &self.state)
.finish()
}
}
impl Deref for Publisher {
type Target = Info;
fn deref(&self) -> &Self::Target {
&self.info
}
}
#[derive(Clone)]
pub struct Subscriber {
state: Watch<State>,
info: Arc<Info>,
_dropped: Arc<Dropped>,
}
impl Subscriber {
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
let _dropped = Arc::new(Dropped::new(state.clone()));
Self { state, info, _dropped }
}
pub fn get_track(&self, name: &str) -> Result<track::Subscriber, Error> {
let state = self.state.lock();
if let Some(track) = state.get(name)? {
return Ok(track);
}
state.into_mut().request(name)
}
}
impl Deref for Subscriber {
type Target = Info;
fn deref(&self) -> &Self::Target {
&self.info
}
}
impl fmt::Debug for Subscriber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Subscriber")
.field("name", &self.name)
.field("state", &self.state)
.finish()
}
}
pub struct Unknown {
state: Watch<State>,
info: Arc<Info>,
_dropped: Arc<Dropped>,
}
impl Unknown {
fn new(state: Watch<State>, info: Arc<Info>, _dropped: Arc<Dropped>) -> Self {
Self { state, info, _dropped }
}
pub async fn next_track(&mut self) -> Result<Option<track::Publisher>, Error> {
loop {
let notify = {
let state = self.state.lock();
if state.has_next()? {
return Ok(Some(state.into_mut().next()));
}
state.changed()
};
notify.await;
}
}
}
impl Deref for Unknown {
type Target = Info;
fn deref(&self) -> &Self::Target {
&self.info
}
}
impl Drop for Unknown {
fn drop(&mut self) {
let mut state = self.state.lock_mut();
while let Ok(true) = state.has_next() {
state.next().close(Error::NotFound).ok();
}
state.requested = None;
}
}
impl fmt::Debug for Unknown {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Unknown")
.field("name", &self.name)
.field("state", &self.state)
.finish()
}
}
struct Dropped {
state: Watch<State>,
}
impl Dropped {
fn new(state: Watch<State>) -> Self {
Self { state }
}
}
impl Drop for Dropped {
fn drop(&mut self) {
self.state.lock_mut().close(Error::Closed).ok();
}
}