Skip to main content

open_net/api/subscription/
event.rs

1pub(crate) use super::event_registration::EventPublication;
2use super::event_registration::{Entry, EventRegistration};
3use super::*;
4use crate::error::{ReceiveError, TryReceiveError};
5use std::collections::VecDeque;
6use tokio::sync::{OwnedSemaphorePermit, Semaphore};
7
8#[derive(Clone, Copy, Debug)]
9pub(crate) struct EventQueueLimit {
10    pub(crate) max_items: usize,
11    pub(crate) max_bytes: usize,
12}
13
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub(crate) enum EventOverflow {
16    Disconnect,
17    DropOldest,
18    Wait,
19}
20
21/// Queue-owned reservations, independent of the value delivered to application
22/// code and of the subscription permit retained by callback jobs.
23#[derive(Default)]
24pub(crate) struct EventResources {
25    pub(crate) items: Option<OwnedSemaphorePermit>,
26    pub(crate) bytes: Option<OwnedSemaphorePermit>,
27    pub(crate) shared_bytes: Option<Arc<OwnedSemaphorePermit>>,
28}
29
30/// A complete initial cursor, installed before its receiver is exposed.
31pub(crate) struct EventSeed<T> {
32    pub(crate) entries: VecDeque<(T, usize)>,
33    pub(crate) lagged: u64,
34    pub(crate) source_closed: bool,
35    pub(crate) failure: Option<NetError>,
36}
37
38pub(crate) fn event_channel<T>(
39    limit: EventQueueLimit,
40    overflow: EventOverflow,
41    executor: Arc<dyn CallbackExecutor>,
42    permit: Option<OwnedSemaphorePermit>,
43) -> Result<(EventPublisher<T>, EventReceiver<T>)> {
44    if limit.max_items == 0 || limit.max_items > Semaphore::MAX_PERMITS {
45        return Err(NetError::config(
46            "subscription.max_items",
47            "must be a positive supported capacity",
48        ));
49    }
50    if limit.max_bytes == 0
51        || limit.max_bytes > Semaphore::MAX_PERMITS
52        || limit.max_bytes > u32::MAX as usize
53    {
54        return Err(NetError::config(
55            "subscription.max_bytes",
56            "must be a positive supported byte allowance",
57        ));
58    }
59    let mut queue = VecDeque::new();
60    queue
61        .try_reserve_exact(limit.max_items)
62        .map_err(|error| NetError::with_source(ErrorKind::ResourceExhausted, error))?;
63    let registration = Arc::new(EventRegistration::new(
64        source::allocate_id()?,
65        limit,
66        overflow,
67        executor,
68        permit,
69        queue,
70    ));
71    Ok((
72        EventPublisher {
73            owner: Arc::new(PublisherOwner {
74                registration: registration.clone(),
75            }),
76        },
77        EventReceiver {
78            registration,
79            owns_subscription: true,
80        },
81    ))
82}
83
84pub(crate) struct EventPublisher<T> {
85    owner: Arc<PublisherOwner<T>>,
86}
87struct PublisherOwner<T> {
88    registration: Arc<EventRegistration<T>>,
89}
90impl<T> Clone for EventPublisher<T> {
91    fn clone(&self) -> Self {
92        Self {
93            owner: self.owner.clone(),
94        }
95    }
96}
97impl<T> EventPublisher<T> {
98    #[cfg(test)]
99    pub(crate) fn try_publish(&self, value: T, bytes: usize) -> Result<()> {
100        self.prepare_try_publish(value, bytes).dispatch()
101    }
102    #[cfg(test)]
103    pub(crate) async fn publish(&self, value: T, bytes: usize) -> Result<()> {
104        self.publish_with_resources(value, bytes, EventResources::default())
105            .await
106    }
107    #[cfg(test)]
108    pub(crate) async fn publish_with_resources(
109        &self,
110        value: T,
111        bytes: usize,
112        resources: EventResources,
113    ) -> Result<()> {
114        let mut entry = Entry::new(value, bytes, resources);
115        loop {
116            let notified = self.owner.registration.capacity_available.notified();
117            tokio::pin!(notified);
118            // Register before checking capacity: dequeue/close cannot be lost
119            // between that check and the first pending poll.
120            notified.as_mut().enable();
121            let (result, pending) = self
122                .owner
123                .registration
124                .prepare_publish(entry)
125                .dispatch_with_entry();
126            if result? {
127                return Ok(());
128            }
129            entry = pending.ok_or_else(|| NetError::from(ErrorKind::Internal))?;
130            notified.await;
131        }
132    }
133    pub(crate) fn finish(&self) -> Result<()> {
134        self.prepare_finish().dispatch()
135    }
136    pub(crate) fn fail(&self, error: NetError) -> Result<()> {
137        self.prepare_fail(error).dispatch()
138    }
139    pub(crate) fn prepare_try_publish(&self, value: T, bytes: usize) -> EventPublication<T> {
140        self.prepare_try_publish_with_resources(value, bytes, EventResources::default())
141    }
142    pub(crate) fn prepare_try_publish_with_resources(
143        &self,
144        value: T,
145        bytes: usize,
146        resources: EventResources,
147    ) -> EventPublication<T> {
148        self.owner
149            .registration
150            .prepare_publish(Entry::new(value, bytes, resources))
151    }
152    /// Retain an additional internal reservation until dequeue or unsubscribe,
153    /// without making the application-owned value keep the reservation alive.
154    pub(crate) fn prepare_try_publish_with_retained(
155        &self,
156        value: T,
157        bytes: usize,
158        resources: EventResources,
159        retained: Box<dyn Send + Sync>,
160    ) -> EventPublication<T> {
161        self.owner
162            .registration
163            .prepare_publish(Entry::new(value, bytes, resources).with_retained(retained))
164    }
165    pub(crate) fn on_receiver_closed(&self, hook: Arc<dyn Fn() + Send + Sync>) -> Result<()> {
166        self.owner.registration.on_receiver_closed(hook)
167    }
168    pub(crate) fn prepare_skip(&self, skipped: u64) -> EventPublication<T> {
169        self.owner.registration.prepare_skip(skipped)
170    }
171    pub(crate) fn prepare_evict_oldest(&self) -> Option<EventPublication<T>> {
172        self.owner.registration.prepare_evict_oldest()
173    }
174    pub(crate) fn prepare_finish(&self) -> EventPublication<T> {
175        self.owner.registration.prepare_finish(None)
176    }
177    pub(crate) fn prepare_fail(&self, error: NetError) -> EventPublication<T> {
178        self.owner.registration.prepare_finish(Some(error))
179    }
180    pub(crate) fn prepare_seed(&self, seed: EventSeed<T>) -> EventPublication<T> {
181        self.owner.registration.prepare_seed(seed)
182    }
183    pub(crate) fn is_active(&self) -> bool {
184        self.owner.registration.is_active()
185    }
186    /// Waits for consumer detach, including EOF consumption. Finishing the source
187    /// alone does not detach a receiver that still owns buffered entries.
188    pub(crate) async fn receiver_closed(&self) {
189        loop {
190            let notified = self.owner.registration.receiver_closed.notified();
191            tokio::pin!(notified);
192            notified.as_mut().enable();
193            if !self.owner.registration.is_active() {
194                return;
195            }
196            notified.await;
197        }
198    }
199}
200impl<T> Drop for PublisherOwner<T> {
201    fn drop(&mut self) {
202        if let Err(error) = self.registration.prepare_finish(None).dispatch() {
203            crate::log_e!(crate::common::log::log_def::LogType::Common;
204                "event_publisher_drop", "id|kind", self.registration.id.as_u64(), format!("{:?}", error.kind()));
205        }
206    }
207}
208
209#[must_use]
210/// Receives values from an event source in publication order.
211///
212/// Event streams retain a bounded queue measured by both item count and byte
213/// cost. Depending on the source policy, a full queue either waits for the
214/// consumer, drops the oldest entries and reports [`ReceiveError::Lagged`], or
215/// terminates with [`ReceiveError::Failed`]. Dropping this receiver
216/// unsubscribes it and releases queued values and capacity reservations.
217pub struct EventReceiver<T> {
218    pub(super) registration: Arc<EventRegistration<T>>,
219    owns_subscription: bool,
220}
221impl<T> fmt::Debug for EventReceiver<T> {
222    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
223        formatter
224            .debug_struct("EventReceiver")
225            .field("id", &self.registration.id)
226            .finish_non_exhaustive()
227    }
228}
229impl<T> EventReceiver<T> {
230    /// Return the identifier of this event subscription.
231    pub fn id(&self) -> SubscriptionId {
232        self.registration.id
233    }
234    /// Await the next event.
235    ///
236    /// `Ok(Some(value))` is a delivered item, `Ok(None)` is end of stream, and
237    /// `Err` reports lag or a source failure. The receive future is cancellation
238    /// safe: polling it does not remove an item unless the item is returned.
239    pub async fn recv(&mut self) -> std::result::Result<Option<T>, ReceiveError> {
240        std::future::poll_fn(|cx| self.registration.poll_next(cx))
241            .await
242            .transpose()
243    }
244    /// Try to receive one event without waiting.
245    ///
246    /// [`TryReceiveError::Empty`] means no event is currently ready. Lag and
247    /// source failures are reported as distinct variants so callers can choose
248    /// whether to continue, resynchronize, or terminate.
249    pub fn try_recv(&mut self) -> std::result::Result<T, TryReceiveError> {
250        self.registration.try_recv()
251    }
252    /// Detach the receiver and release its queue reservation.
253    ///
254    /// Returns `true` only for the first call that deactivates this receiver.
255    /// Calling it while a callback is running does not block that callback.
256    pub fn unsubscribe(&self) -> bool {
257        self.registration.unsubscribe()
258    }
259    /// Internal cancellation authority without transferring receiver ownership.
260    #[cfg(feature = "net-status")]
261    pub(crate) fn control(&self) -> Arc<dyn SubscriptionControl>
262    where
263        T: Send + Sync + 'static,
264    {
265        self.registration.clone()
266    }
267    /// Consume the receiver and deliver subsequent events to a callback.
268    ///
269    /// The callback receives a [`CallbackContext`] plus either an event value,
270    /// a lag notification, or a source failure. The callback must be `Send`,
271    /// `Sync`, and `'static` because it may run on the engine's callback pool.
272    /// If setup fails, the receiver remains usable and keeps its buffered
273    /// cursor; on success, the returned [`Subscription`] owns the registration.
274    pub fn into_callback<F>(mut self, callback: F) -> Result<Subscription>
275    where
276        T: Send + Sync + 'static,
277        F: Fn(CallbackContext, std::result::Result<T, ReceiveError>) + Send + Sync + 'static,
278    {
279        self.try_into_callback(callback)
280    }
281    /// Preserve the receiver and its buffered cursor if callback setup fails.
282    pub(crate) fn try_into_callback<F>(&mut self, callback: F) -> Result<Subscription>
283    where
284        T: Send + Sync + 'static,
285        F: Fn(CallbackContext, std::result::Result<T, ReceiveError>) + Send + Sync + 'static,
286    {
287        self.registration.install_callback(callback)?;
288        self.owns_subscription = false;
289        Ok(Subscription {
290            id: self.registration.id,
291            control: self.registration.clone(),
292        })
293    }
294}
295impl<T> futures_util::Stream for EventReceiver<T> {
296    type Item = std::result::Result<T, ReceiveError>;
297    fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
298        self.registration.poll_next(cx)
299    }
300}
301impl<T> Drop for EventReceiver<T> {
302    fn drop(&mut self) {
303        if self.owns_subscription {
304            self.registration.unsubscribe();
305        }
306    }
307}
308
309#[cfg(test)]
310#[path = "event_resource_tests.rs"]
311mod resource_tests;
312
313#[cfg(test)]
314#[path = "event_detach_regression_tests.rs"]
315mod detach_regression_tests;