open_net/api/subscription/
event.rs1pub(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#[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
30pub(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 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 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 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]
210pub 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 pub fn id(&self) -> SubscriptionId {
232 self.registration.id
233 }
234 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 pub fn try_recv(&mut self) -> std::result::Result<T, TryReceiveError> {
250 self.registration.try_recv()
251 }
252 pub fn unsubscribe(&self) -> bool {
257 self.registration.unsubscribe()
258 }
259 #[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 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 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;