use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use super::stream::{FailSlot, Stream, lock, queue_source};
use crate::coordination::Queue;
use crate::failure::Never;
use crate::kernel::{Effect, fail, succeed, sync};
use crate::streaming::chunk::Chunk;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackpressurePolicy {
BoundedBlock,
DropNewest,
DropOldest,
Fail,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackpressureDecision {
Enqueue,
Block,
DropNewest,
DropOldest,
Fail,
}
pub fn backpressure_decision(
policy: BackpressurePolicy,
queue_len: usize,
capacity: usize,
) -> BackpressureDecision {
if queue_len < capacity.max(1) {
return BackpressureDecision::Enqueue;
}
match policy {
BackpressurePolicy::BoundedBlock => BackpressureDecision::Block,
BackpressurePolicy::DropNewest => BackpressureDecision::DropNewest,
BackpressurePolicy::DropOldest => BackpressureDecision::DropOldest,
BackpressurePolicy::Fail => BackpressureDecision::Fail,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StreamChannelFull;
impl fmt::Display for StreamChannelFull {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "stream channel is full (backpressure policy Fail)")
}
}
impl std::error::Error for StreamChannelFull {}
struct SenderInner<A: Send + 'static, E> {
queue: Queue<Chunk<A>>,
failure: FailSlot<E>,
policy: BackpressurePolicy,
ended: AtomicBool,
}
impl<A: Send + 'static, E> SenderInner<A, E> {
fn end(&self) -> bool {
let first = !self.ended.swap(true, Ordering::AcqRel);
if first {
self.queue.shutdown_sync();
}
first
}
}
impl<A: Send + 'static, E> Drop for SenderInner<A, E> {
fn drop(&mut self) {
self.end();
}
}
pub struct StreamSender<A: Send + 'static, E> {
inner: Arc<SenderInner<A, E>>,
}
impl<A: Send + 'static, E> Clone for StreamSender<A, E> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}
impl<A: Send + 'static, E> fmt::Debug for StreamSender<A, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StreamSender")
.field("policy", &self.inner.policy)
.field("ended", &self.inner.ended.load(Ordering::Acquire))
.finish()
}
}
impl<A, E> StreamSender<A, E>
where
A: Send + 'static,
E: Send + 'static,
{
pub fn policy(&self) -> BackpressurePolicy {
self.inner.policy
}
pub fn fail(&self, error: E) -> bool {
if self.inner.ended.load(Ordering::Acquire) {
return false;
}
*lock(&self.inner.failure) = Some(error);
if self.inner.end() {
true
} else {
lock(&self.inner.failure).take();
false
}
}
pub fn send<R: Send + Sync + 'static>(
&self,
chunk: Chunk<A>,
) -> Effect<(), StreamChannelFull, R> {
send_chunk(self, chunk)
}
}
pub fn stream_from_channel_with_policy<A, E, R>(
capacity: usize,
policy: BackpressurePolicy,
) -> (Stream<A, E, R>, StreamSender<A, E>)
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
let cap = capacity.max(1);
let queue = match policy {
BackpressurePolicy::BoundedBlock | BackpressurePolicy::Fail => Queue::bounded(cap),
BackpressurePolicy::DropNewest => Queue::dropping(cap),
BackpressurePolicy::DropOldest => Queue::sliding(cap),
};
let failure: FailSlot<E> = Arc::new(Mutex::new(None));
let stream = queue_source(
queue.clone(),
Arc::clone(&failure),
VecDeque::new(),
flatten_chunks,
);
let sender = StreamSender {
inner: Arc::new(SenderInner {
queue,
failure,
policy,
ended: AtomicBool::new(false),
}),
};
(stream, sender)
}
fn flatten_chunks<A>(chunks: Vec<Chunk<A>>) -> Vec<A> {
chunks.into_iter().flat_map(Chunk::into_vec).collect()
}
pub fn stream_from_channel<A, E, R>(capacity: usize) -> (Stream<A, E, R>, StreamSender<A, E>)
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
stream_from_channel_with_policy(capacity, BackpressurePolicy::BoundedBlock)
}
pub fn send_chunk<A, E, R>(
sender: &StreamSender<A, E>,
chunk: Chunk<A>,
) -> Effect<(), StreamChannelFull, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
if chunk.is_empty() {
return succeed(());
}
let inner = Arc::clone(&sender.inner);
let queue = inner.queue.clone();
match inner.policy {
BackpressurePolicy::BoundedBlock => queue.offer(chunk).map(move |_| drop(inner)),
BackpressurePolicy::DropNewest | BackpressurePolicy::DropOldest => {
queue.try_offer(chunk).map(move |_| drop(inner))
}
BackpressurePolicy::Fail => queue.try_offer(chunk).flat_map(move |stored| {
drop(inner);
if stored {
succeed(())
} else {
fail(StreamChannelFull)
}
}),
}
}
pub fn end_stream<A, E, R>(sender: StreamSender<A, E>) -> Effect<(), Never, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
sync(move || {
sender.inner.end();
})
}