pub(crate) use super::event_registration::EventPublication;
use super::event_registration::{Entry, EventRegistration};
use super::*;
use crate::error::{ReceiveError, TryReceiveError};
use std::collections::VecDeque;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
#[derive(Clone, Copy, Debug)]
pub(crate) struct EventQueueLimit {
pub(crate) max_items: usize,
pub(crate) max_bytes: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum EventOverflow {
Disconnect,
DropOldest,
Wait,
}
#[derive(Default)]
pub(crate) struct EventResources {
pub(crate) items: Option<OwnedSemaphorePermit>,
pub(crate) bytes: Option<OwnedSemaphorePermit>,
pub(crate) shared_bytes: Option<Arc<OwnedSemaphorePermit>>,
}
pub(crate) struct EventSeed<T> {
pub(crate) entries: VecDeque<(T, usize)>,
pub(crate) lagged: u64,
pub(crate) source_closed: bool,
pub(crate) failure: Option<NetError>,
}
pub(crate) fn event_channel<T>(
limit: EventQueueLimit,
overflow: EventOverflow,
executor: Arc<dyn CallbackExecutor>,
permit: Option<OwnedSemaphorePermit>,
) -> Result<(EventPublisher<T>, EventReceiver<T>)> {
if limit.max_items == 0 || limit.max_items > Semaphore::MAX_PERMITS {
return Err(NetError::config(
"subscription.max_items",
"must be a positive supported capacity",
));
}
if limit.max_bytes == 0
|| limit.max_bytes > Semaphore::MAX_PERMITS
|| limit.max_bytes > u32::MAX as usize
{
return Err(NetError::config(
"subscription.max_bytes",
"must be a positive supported byte allowance",
));
}
let mut queue = VecDeque::new();
queue
.try_reserve_exact(limit.max_items)
.map_err(|error| NetError::with_source(ErrorKind::ResourceExhausted, error))?;
let registration = Arc::new(EventRegistration::new(
source::allocate_id()?,
limit,
overflow,
executor,
permit,
queue,
));
Ok((
EventPublisher {
owner: Arc::new(PublisherOwner {
registration: registration.clone(),
}),
},
EventReceiver {
registration,
owns_subscription: true,
},
))
}
pub(crate) struct EventPublisher<T> {
owner: Arc<PublisherOwner<T>>,
}
struct PublisherOwner<T> {
registration: Arc<EventRegistration<T>>,
}
impl<T> Clone for EventPublisher<T> {
fn clone(&self) -> Self {
Self {
owner: self.owner.clone(),
}
}
}
impl<T> EventPublisher<T> {
#[cfg(test)]
pub(crate) fn try_publish(&self, value: T, bytes: usize) -> Result<()> {
self.prepare_try_publish(value, bytes).dispatch()
}
#[cfg(test)]
pub(crate) async fn publish(&self, value: T, bytes: usize) -> Result<()> {
self.publish_with_resources(value, bytes, EventResources::default())
.await
}
#[cfg(test)]
pub(crate) async fn publish_with_resources(
&self,
value: T,
bytes: usize,
resources: EventResources,
) -> Result<()> {
let mut entry = Entry::new(value, bytes, resources);
loop {
let notified = self.owner.registration.capacity_available.notified();
tokio::pin!(notified);
notified.as_mut().enable();
let (result, pending) = self
.owner
.registration
.prepare_publish(entry)
.dispatch_with_entry();
if result? {
return Ok(());
}
entry = pending.ok_or_else(|| NetError::from(ErrorKind::Internal))?;
notified.await;
}
}
pub(crate) fn finish(&self) -> Result<()> {
self.prepare_finish().dispatch()
}
pub(crate) fn fail(&self, error: NetError) -> Result<()> {
self.prepare_fail(error).dispatch()
}
pub(crate) fn prepare_try_publish(&self, value: T, bytes: usize) -> EventPublication<T> {
self.prepare_try_publish_with_resources(value, bytes, EventResources::default())
}
pub(crate) fn prepare_try_publish_with_resources(
&self,
value: T,
bytes: usize,
resources: EventResources,
) -> EventPublication<T> {
self.owner
.registration
.prepare_publish(Entry::new(value, bytes, resources))
}
pub(crate) fn prepare_try_publish_with_retained(
&self,
value: T,
bytes: usize,
resources: EventResources,
retained: Box<dyn Send + Sync>,
) -> EventPublication<T> {
self.owner
.registration
.prepare_publish(Entry::new(value, bytes, resources).with_retained(retained))
}
pub(crate) fn on_receiver_closed(&self, hook: Arc<dyn Fn() + Send + Sync>) -> Result<()> {
self.owner.registration.on_receiver_closed(hook)
}
pub(crate) fn prepare_skip(&self, skipped: u64) -> EventPublication<T> {
self.owner.registration.prepare_skip(skipped)
}
pub(crate) fn prepare_evict_oldest(&self) -> Option<EventPublication<T>> {
self.owner.registration.prepare_evict_oldest()
}
pub(crate) fn prepare_finish(&self) -> EventPublication<T> {
self.owner.registration.prepare_finish(None)
}
pub(crate) fn prepare_fail(&self, error: NetError) -> EventPublication<T> {
self.owner.registration.prepare_finish(Some(error))
}
pub(crate) fn prepare_seed(&self, seed: EventSeed<T>) -> EventPublication<T> {
self.owner.registration.prepare_seed(seed)
}
pub(crate) fn is_active(&self) -> bool {
self.owner.registration.is_active()
}
pub(crate) async fn receiver_closed(&self) {
loop {
let notified = self.owner.registration.receiver_closed.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if !self.owner.registration.is_active() {
return;
}
notified.await;
}
}
}
impl<T> Drop for PublisherOwner<T> {
fn drop(&mut self) {
if let Err(error) = self.registration.prepare_finish(None).dispatch() {
crate::log_e!(crate::common::log::log_def::LogType::Common;
"event_publisher_drop", "id|kind", self.registration.id.as_u64(), format!("{:?}", error.kind()));
}
}
}
#[must_use]
pub struct EventReceiver<T> {
pub(super) registration: Arc<EventRegistration<T>>,
owns_subscription: bool,
}
impl<T> fmt::Debug for EventReceiver<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("EventReceiver")
.field("id", &self.registration.id)
.finish_non_exhaustive()
}
}
impl<T> EventReceiver<T> {
pub fn id(&self) -> SubscriptionId {
self.registration.id
}
pub async fn recv(&mut self) -> std::result::Result<Option<T>, ReceiveError> {
std::future::poll_fn(|cx| self.registration.poll_next(cx))
.await
.transpose()
}
pub fn try_recv(&mut self) -> std::result::Result<T, TryReceiveError> {
self.registration.try_recv()
}
pub fn unsubscribe(&self) -> bool {
self.registration.unsubscribe()
}
#[cfg(feature = "net-status")]
pub(crate) fn control(&self) -> Arc<dyn SubscriptionControl>
where
T: Send + Sync + 'static,
{
self.registration.clone()
}
pub fn into_callback<F>(mut self, callback: F) -> Result<Subscription>
where
T: Send + Sync + 'static,
F: Fn(CallbackContext, std::result::Result<T, ReceiveError>) + Send + Sync + 'static,
{
self.try_into_callback(callback)
}
pub(crate) fn try_into_callback<F>(&mut self, callback: F) -> Result<Subscription>
where
T: Send + Sync + 'static,
F: Fn(CallbackContext, std::result::Result<T, ReceiveError>) + Send + Sync + 'static,
{
self.registration.install_callback(callback)?;
self.owns_subscription = false;
Ok(Subscription {
id: self.registration.id,
control: self.registration.clone(),
})
}
}
impl<T> futures_util::Stream for EventReceiver<T> {
type Item = std::result::Result<T, ReceiveError>;
fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.registration.poll_next(cx)
}
}
impl<T> Drop for EventReceiver<T> {
fn drop(&mut self) {
if self.owns_subscription {
self.registration.unsubscribe();
}
}
}
#[cfg(test)]
#[path = "event_resource_tests.rs"]
mod resource_tests;
#[cfg(test)]
#[path = "event_detach_regression_tests.rs"]
mod detach_regression_tests;