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 pub(crate) fn try_publish(&self, value: T, bytes: usize) -> Result<()> {
99 self.prepare_try_publish(value, bytes).dispatch()
100 }
101 pub(crate) async fn publish(&self, value: T, bytes: usize) -> Result<()> {
102 self.publish_with_resources(value, bytes, EventResources::default())
103 .await
104 }
105 pub(crate) async fn publish_with_resources(
106 &self,
107 value: T,
108 bytes: usize,
109 resources: EventResources,
110 ) -> Result<()> {
111 let mut entry = Entry::new(value, bytes, resources);
112 loop {
113 let notified = self.owner.registration.capacity_available.notified();
114 tokio::pin!(notified);
115 notified.as_mut().enable();
118 let (result, pending) = self
119 .owner
120 .registration
121 .prepare_publish(entry)
122 .dispatch_with_entry();
123 if result? {
124 return Ok(());
125 }
126 entry = pending.ok_or_else(|| NetError::from(ErrorKind::Internal))?;
127 notified.await;
128 }
129 }
130 pub(crate) fn finish(&self) -> Result<()> {
131 self.prepare_finish().dispatch()
132 }
133 pub(crate) fn fail(&self, error: NetError) -> Result<()> {
134 self.prepare_fail(error).dispatch()
135 }
136 pub(crate) fn prepare_try_publish(&self, value: T, bytes: usize) -> EventPublication<T> {
137 self.prepare_try_publish_with_resources(value, bytes, EventResources::default())
138 }
139 pub(crate) fn prepare_try_publish_with_resources(
140 &self,
141 value: T,
142 bytes: usize,
143 resources: EventResources,
144 ) -> EventPublication<T> {
145 self.owner
146 .registration
147 .prepare_publish(Entry::new(value, bytes, resources))
148 }
149 pub(crate) fn prepare_try_publish_with_retained(
152 &self,
153 value: T,
154 bytes: usize,
155 resources: EventResources,
156 retained: Box<dyn Send + Sync>,
157 ) -> EventPublication<T> {
158 self.owner
159 .registration
160 .prepare_publish(Entry::new(value, bytes, resources).with_retained(retained))
161 }
162 pub(crate) fn on_receiver_closed(&self, hook: Arc<dyn Fn() + Send + Sync>) -> Result<()> {
163 self.owner.registration.on_receiver_closed(hook)
164 }
165 pub(crate) fn prepare_skip(&self, skipped: u64) -> EventPublication<T> {
166 self.owner.registration.prepare_skip(skipped)
167 }
168 pub(crate) fn prepare_evict_oldest(&self) -> Option<EventPublication<T>> {
169 self.owner.registration.prepare_evict_oldest()
170 }
171 pub(crate) fn prepare_finish(&self) -> EventPublication<T> {
172 self.owner.registration.prepare_finish(None)
173 }
174 pub(crate) fn prepare_fail(&self, error: NetError) -> EventPublication<T> {
175 self.owner.registration.prepare_finish(Some(error))
176 }
177 pub(crate) fn prepare_seed(&self, seed: EventSeed<T>) -> EventPublication<T> {
178 self.owner.registration.prepare_seed(seed)
179 }
180 pub(crate) fn is_active(&self) -> bool {
181 self.owner.registration.is_active()
182 }
183 pub(crate) async fn receiver_closed(&self) {
186 loop {
187 let notified = self.owner.registration.receiver_closed.notified();
188 tokio::pin!(notified);
189 notified.as_mut().enable();
190 if !self.owner.registration.is_active() {
191 return;
192 }
193 notified.await;
194 }
195 }
196}
197impl<T> Drop for PublisherOwner<T> {
198 fn drop(&mut self) {
199 if let Err(error) = self.registration.prepare_finish(None).dispatch() {
200 crate::log_e!(crate::common::log::log_def::LogType::Common;
201 "event_publisher_drop", "id|kind", self.registration.id.as_u64(), format!("{:?}", error.kind()));
202 }
203 }
204}
205
206#[must_use]
207pub struct EventReceiver<T> {
215 pub(super) registration: Arc<EventRegistration<T>>,
216 owns_subscription: bool,
217}
218impl<T> fmt::Debug for EventReceiver<T> {
219 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220 formatter
221 .debug_struct("EventReceiver")
222 .field("id", &self.registration.id)
223 .finish_non_exhaustive()
224 }
225}
226impl<T> EventReceiver<T> {
227 pub fn id(&self) -> SubscriptionId {
229 self.registration.id
230 }
231 pub async fn recv(&mut self) -> std::result::Result<Option<T>, ReceiveError> {
237 std::future::poll_fn(|cx| self.registration.poll_next(cx))
238 .await
239 .transpose()
240 }
241 pub fn try_recv(&mut self) -> std::result::Result<T, TryReceiveError> {
247 self.registration.try_recv()
248 }
249 pub fn unsubscribe(&self) -> bool {
254 self.registration.unsubscribe()
255 }
256 #[cfg(feature = "net-status")]
258 pub(crate) fn control(&self) -> Arc<dyn SubscriptionControl>
259 where
260 T: Send + Sync + 'static,
261 {
262 self.registration.clone()
263 }
264 pub fn into_callback<F>(mut self, callback: F) -> Result<Subscription>
272 where
273 T: Send + Sync + 'static,
274 F: Fn(CallbackContext, std::result::Result<T, ReceiveError>) + Send + Sync + 'static,
275 {
276 self.try_into_callback(callback)
277 }
278 pub(crate) fn try_into_callback<F>(&mut self, callback: F) -> Result<Subscription>
280 where
281 T: Send + Sync + 'static,
282 F: Fn(CallbackContext, std::result::Result<T, ReceiveError>) + Send + Sync + 'static,
283 {
284 self.registration.install_callback(callback)?;
285 self.owns_subscription = false;
286 Ok(Subscription {
287 id: self.registration.id,
288 control: self.registration.clone(),
289 })
290 }
291}
292impl<T> futures_util::Stream for EventReceiver<T> {
293 type Item = std::result::Result<T, ReceiveError>;
294 fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
295 self.registration.poll_next(cx)
296 }
297}
298impl<T> Drop for EventReceiver<T> {
299 fn drop(&mut self) {
300 if self.owns_subscription {
301 self.registration.unsubscribe();
302 }
303 }
304}
305
306#[cfg(test)]
307#[path = "event_resource_tests.rs"]
308mod resource_tests;
309
310#[cfg(test)]
311#[path = "event_detach_regression_tests.rs"]
312mod detach_regression_tests;