use std::{collections::BinaryHeap, fmt, ops::Deref, sync::Arc, time};
use indexmap::IndexMap;
use super::{segment, Watch};
use crate::{Error, VarInt};
pub fn new(name: &str) -> (Publisher, Subscriber) {
let state = Watch::new(State::default());
let info = Arc::new(Info { name: name.to_string() });
let publisher = Publisher::new(state.clone(), info.clone());
let subscriber = Subscriber::new(state, info);
(publisher, subscriber)
}
#[derive(Debug)]
pub struct Info {
pub name: String,
}
struct State {
lookup: IndexMap<VarInt, Option<segment::Subscriber>>,
expires: BinaryHeap<SegmentExpiration>,
pruned: usize,
closed: Result<(), Error>,
}
impl State {
pub fn close(&mut self, err: Error) -> Result<(), Error> {
self.closed?;
self.closed = Err(err);
Ok(())
}
pub fn insert(&mut self, segment: segment::Subscriber) -> Result<(), Error> {
self.closed?;
let entry = match self.lookup.entry(segment.sequence) {
indexmap::map::Entry::Occupied(_entry) => return Err(Error::Duplicate),
indexmap::map::Entry::Vacant(entry) => entry,
};
if let Some(expires) = segment.expires {
self.expires.push(SegmentExpiration {
sequence: segment.sequence,
expires: time::Instant::now() + expires,
});
}
entry.insert(Some(segment));
self.expire();
Ok(())
}
pub fn expire(&mut self) {
let now = time::Instant::now();
while let Some(segment) = self.expires.peek() {
if segment.expires > now {
break;
}
match self.lookup.entry(segment.sequence) {
indexmap::map::Entry::Occupied(mut entry) => entry.insert(None),
indexmap::map::Entry::Vacant(_) => panic!("expired segment not found"),
};
self.expires.pop();
}
while let Some((_, None)) = self.lookup.get_index(0) {
self.lookup.shift_remove_index(0);
self.pruned += 1;
}
}
}
impl Default for State {
fn default() -> Self {
Self {
lookup: Default::default(),
expires: Default::default(),
pruned: 0,
closed: Ok(()),
}
}
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("State")
.field("lookup", &self.lookup)
.field("pruned", &self.pruned)
.field("closed", &self.closed)
.finish()
}
}
#[derive(Clone)]
pub struct Publisher {
state: Watch<State>,
info: Arc<Info>,
_dropped: Arc<Dropped>,
}
impl Publisher {
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
let _dropped = Arc::new(Dropped::new(state.clone()));
Self { state, info, _dropped }
}
pub fn insert_segment(&mut self, segment: segment::Subscriber) -> Result<(), Error> {
self.state.lock_mut().insert(segment)
}
pub fn create_segment(&mut self, info: segment::Info) -> Result<segment::Publisher, Error> {
let (publisher, subscriber) = segment::new(info);
self.insert_segment(subscriber)?;
Ok(publisher)
}
pub fn close(self, err: Error) -> Result<(), Error> {
self.state.lock_mut().close(err)
}
}
impl Deref for Publisher {
type Target = Info;
fn deref(&self) -> &Self::Target {
&self.info
}
}
impl fmt::Debug for Publisher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Publisher")
.field("state", &self.state)
.field("info", &self.info)
.finish()
}
}
#[derive(Clone)]
pub struct Subscriber {
state: Watch<State>,
info: Arc<Info>,
index: usize,
pending: BinaryHeap<SegmentPriority>,
_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,
index: 0,
pending: Default::default(),
_dropped,
}
}
pub async fn next_segment(&mut self) -> Result<Option<segment::Subscriber>, Error> {
loop {
let notify = {
let state = self.state.lock();
let mut index = self.index.saturating_sub(state.pruned);
while index < state.lookup.len() {
let (_, segment) = state.lookup.get_index(index).unwrap();
if let Some(segment) = segment {
self.pending.push(SegmentPriority(segment.clone()));
}
index += 1;
}
self.index = state.pruned + index;
if let Some(segment) = self.pending.pop() {
return Ok(Some(segment.0));
}
match state.closed {
Err(Error::Closed) => return Ok(None),
Err(err) => return Err(err),
Ok(()) => state.changed(),
}
};
notify.await
}
}
}
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("state", &self.state)
.field("info", &self.info)
.field("index", &self.index)
.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();
}
}
struct SegmentExpiration {
sequence: VarInt,
expires: time::Instant,
}
impl Ord for SegmentExpiration {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.expires.cmp(&self.expires)
}
}
impl PartialOrd for SegmentExpiration {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for SegmentExpiration {
fn eq(&self, other: &Self) -> bool {
self.expires == other.expires
}
}
impl Eq for SegmentExpiration {}
#[derive(Clone)]
struct SegmentPriority(pub segment::Subscriber);
impl Ord for SegmentPriority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.0.priority.cmp(&self.0.priority)
}
}
impl PartialOrd for SegmentPriority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for SegmentPriority {
fn eq(&self, other: &Self) -> bool {
self.0.priority == other.0.priority
}
}
impl Eq for SegmentPriority {}