open_net/api/subscription/mod.rs
1//! Owned state observations and callback subscriptions shared by all transports.
2
3use crate::error::{ErrorKind, NetError};
4use crate::Result;
5use std::cell::Cell;
6use std::fmt;
7use std::sync::{Arc, Mutex, MutexGuard, Weak};
8use std::task::{Context, Poll};
9
10pub(crate) mod common_executor;
11mod dispatch;
12#[cfg(feature = "net-status")]
13pub(crate) use dispatch::submit_tracked;
14mod event;
15mod event_registration;
16pub use event::EventReceiver;
17pub(crate) use event::{
18 event_channel, EventOverflow, EventPublisher, EventQueueLimit, EventResources,
19};
20#[cfg(any(feature = "ws-client", feature = "net-status"))]
21pub(crate) use event::{EventPublication, EventSeed};
22mod registration;
23mod source;
24pub(crate) use source::{StatePublication, StatePublisher, StateSource};
25
26/// Uses an existing engine pool. Jobs and their destructors run outside pool locks.
27pub(crate) trait CallbackExecutor: Send + Sync + 'static {
28 fn ensure_ready(&self) -> Result<()>;
29 fn submit(&self, job: Box<dyn FnOnce() + Send + 'static>) -> Result<()>;
30}
31pub(crate) trait SubscriptionControl: Send + Sync {
32 fn is_active(&self) -> bool;
33 fn unsubscribe(&self) -> bool;
34 /// Wait for retirement; the public close entry point checks callback context.
35 fn poll_close(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;
36}
37pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
38 match mutex.lock() {
39 Ok(guard) => guard,
40 Err(poisoned) => {
41 crate::log_e!(crate::common::log::log_def::LogType::Common;
42 "subscription_lock", "kind|reason", format!("{:?}", ErrorKind::Internal), "poisoned mutex recovered");
43 poisoned.into_inner()
44 }
45 }
46}
47
48thread_local! {
49 static CALLBACK_DEPTH: Cell<usize> = const { Cell::new(0) };
50}
51
52/// Marks synchronous subscription callbacks, including callbacks on a test
53/// executor. The public close entry point rejects waits on this thread's
54/// subscription callback stack, regardless of the target subscription or engine.
55pub(crate) struct CallbackScope;
56impl CallbackScope {
57 pub(crate) fn enter() -> Self {
58 CALLBACK_DEPTH.with(|depth| depth.set(depth.get() + 1));
59 Self
60 }
61
62 pub(crate) fn is_current() -> bool {
63 CALLBACK_DEPTH.with(|depth| depth.get() != 0)
64 }
65}
66impl Drop for CallbackScope {
67 fn drop(&mut self) {
68 CALLBACK_DEPTH.with(|depth| depth.set(depth.get() - 1));
69 }
70}
71
72#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
73/// Opaque identifier assigned to a state or event subscription.
74///
75/// IDs are unique within the running process for as long as the counter can
76/// represent another value. They carry no authority and cannot be used to
77/// create, resume, or access a subscription by themselves.
78pub struct SubscriptionId(u64);
79impl SubscriptionId {
80 /// Return the numeric representation of this identifier.
81 ///
82 /// The value is intended for diagnostics, correlation, and logging; it is
83 /// not a stable identifier across process restarts.
84 pub fn as_u64(self) -> u64 {
85 self.0
86 }
87}
88impl fmt::Display for SubscriptionId {
89 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90 self.0.fmt(formatter)
91 }
92}
93
94#[must_use]
95/// Receives the latest values published by a state source.
96///
97/// A state receiver starts with the source's current snapshot and then yields
98/// each newer revision. Dropping or explicitly unsubscribing the receiver
99/// releases its bounded subscription slot. The type also implements
100/// [`futures_util::Stream`] for integrations that prefer polling.
101pub struct StateReceiver<T> {
102 registration: Arc<registration::Registration<T>>,
103 owns_subscription: bool,
104}
105impl<T> fmt::Debug for StateReceiver<T> {
106 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107 formatter
108 .debug_struct("StateReceiver")
109 .field("id", &self.registration.id)
110 .finish_non_exhaustive()
111 }
112}
113impl<T: Clone> StateReceiver<T> {
114 /// Attach SDK observation ownership to this registration. Callback conversion
115 /// keeps the same registration, so it transfers this ownership without a gap.
116 #[cfg_attr(not(any(feature = "http-client", test)), allow(dead_code))]
117 pub(crate) fn bind_lifetime(&self, lifetime: impl Send + Sync + 'static) -> Result<()> {
118 self.registration.bind_lifetime(Box::new(lifetime))
119 }
120 /// Return the subscription identifier associated with this receiver.
121 pub fn id(&self) -> SubscriptionId {
122 self.registration.id
123 }
124 /// Clone and return the most recently committed state value.
125 ///
126 /// This method does not advance the receiver cursor and therefore does not
127 /// consume a pending update.
128 pub fn current(&self) -> T {
129 self.registration.current()
130 }
131 /// Wait for the next state value.
132 ///
133 /// `Ok(Some(value))` is a newly observed value, `Ok(None)` means the source
134 /// has terminated, and `Err` reports a source or callback infrastructure
135 /// failure. The future is cancellation safe: cancelling it does not consume
136 /// a value that has not been returned to the caller.
137 pub async fn recv(&mut self) -> Result<Option<T>> {
138 std::future::poll_fn(|cx| self.registration.poll_next(cx))
139 .await
140 .transpose()
141 }
142 /// Stop receiving values and release this receiver's subscription slot.
143 ///
144 /// Returns `true` only when this call performed the transition from active
145 /// to inactive. Repeated calls are harmless and return `false`.
146 pub fn unsubscribe(&self) -> bool {
147 self.registration.unsubscribe()
148 }
149 /// Replace polling with an asynchronous callback.
150 ///
151 /// The callback receives the subscription context and either a cloned state
152 /// value or the terminal error. Buffered state and the receiver cursor are
153 /// preserved if callback installation fails. On success, ownership of the
154 /// subscription is returned as an RAII [`Subscription`] handle.
155 pub fn into_callback<F>(mut self, callback: F) -> Result<Subscription>
156 where
157 T: Send + Sync + 'static,
158 F: Fn(CallbackContext, Result<T>) + Send + Sync + 'static,
159 {
160 self.registration.install_callback(callback)?;
161 self.owns_subscription = false;
162 Ok(Subscription {
163 id: self.registration.id,
164 control: self.registration.clone(),
165 })
166 }
167}
168impl<T: Clone> futures_util::Stream for StateReceiver<T> {
169 type Item = Result<T>;
170 fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
171 self.registration.poll_next(cx)
172 }
173}
174impl<T> Drop for StateReceiver<T> {
175 fn drop(&mut self) {
176 if self.owns_subscription {
177 self.registration.unsubscribe();
178 }
179 }
180}
181
182#[must_use]
183/// Controls a registered callback subscription.
184///
185/// Dropping this handle unsubscribes immediately and without waiting for a
186/// callback worker. Use [`Subscription::close`] when the caller must await the
187/// retirement of an already running callback and observe any callback fault.
188pub struct Subscription {
189 id: SubscriptionId,
190 control: Arc<dyn SubscriptionControl>,
191}
192impl Subscription {
193 #[cfg(feature = "net-status")]
194 pub(crate) fn from_control(id: SubscriptionId, control: Arc<dyn SubscriptionControl>) -> Self {
195 Self { id, control }
196 }
197 /// Return the identifier of the controlled subscription.
198 pub fn id(&self) -> SubscriptionId {
199 self.id
200 }
201 /// Report whether the subscription is still accepting deliveries.
202 pub fn is_active(&self) -> bool {
203 self.control.is_active()
204 }
205 /// Prevent future deliveries and release the subscription's capacity.
206 ///
207 /// This operation is synchronous and idempotent. It does not wait for a
208 /// callback that is already running to finish.
209 pub fn unsubscribe(&self) -> bool {
210 self.control.unsubscribe()
211 }
212 /// Unsubscribe and wait for callback execution to retire.
213 ///
214 /// When awaited outside subscription callbacks, the returned error preserves
215 /// a callback panic or dispatch failure. A successful result means the callback
216 /// is no longer running; it does not
217 /// imply that a previously delivered callback completed application work
218 /// after returning control to the SDK.
219 ///
220 /// Polling this future on a thread currently executing any synchronous
221 /// subscription callback first unsubscribes, then returns
222 /// [`ErrorKind::InvalidInput`] with field `subscription.close` and stage
223 /// [`crate::error::ErrorStage::Dispatch`]. This also applies when closing a
224 /// different or already idle subscription, to prevent callbacks from waiting
225 /// for each other. This error does not guarantee that the callback has retired.
226 /// Use [`CallbackContext::unsubscribe`] inside a callback and retain the
227 /// subscription handle outside it when retirement must be awaited.
228 ///
229 /// The check runs on every poll, not when the future is created. A future
230 /// created in a callback can be awaited outside it after the callback returns.
231 /// The check only sees the current thread's subscription callback stack; do
232 /// not wait in a callback for another thread or task that is closing it.
233 /// Cancelling this future does not reactivate the subscription or interrupt
234 /// an already running callback.
235 pub async fn close(self) -> Result<()> {
236 self.unsubscribe();
237 std::future::poll_fn(|cx| {
238 if CallbackScope::is_current() {
239 return Poll::Ready(Err(NetError::input(
240 "subscription.close",
241 "await subscription close outside subscription callbacks; use unsubscribe inside callbacks",
242 )
243 .with_stage(crate::error::ErrorStage::Dispatch)));
244 }
245 self.control.poll_close(cx)
246 })
247 .await
248 }
249}
250impl Drop for Subscription {
251 fn drop(&mut self) {
252 self.control.unsubscribe();
253 }
254}
255impl fmt::Debug for Subscription {
256 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
257 formatter
258 .debug_struct("Subscription")
259 .field("id", &self.id)
260 .field("active", &self.is_active())
261 .finish()
262 }
263}
264
265#[derive(Clone)]
266/// Context passed to every callback invocation.
267///
268/// The context contains only a weak control reference, so retaining it does
269/// not keep the subscription or callback alive. It can be used to request
270/// unsubscription from inside the callback.
271pub struct CallbackContext {
272 id: SubscriptionId,
273 control: Weak<dyn SubscriptionControl>,
274}
275impl CallbackContext {
276 #[cfg(feature = "net-status")]
277 pub(crate) fn from_control(id: SubscriptionId, control: &Arc<dyn SubscriptionControl>) -> Self {
278 Self {
279 id,
280 control: Arc::downgrade(control),
281 }
282 }
283 /// Return the identifier of the subscription invoking the callback.
284 pub fn id(&self) -> SubscriptionId {
285 self.id
286 }
287 /// Request unsubscription through this callback context.
288 ///
289 /// Returns `false` when the subscription has already been dropped or
290 /// detached. The request is synchronous and does not wait for the current
291 /// callback invocation to return.
292 pub fn unsubscribe(&self) -> bool {
293 self.control
294 .upgrade()
295 .is_some_and(|control| control.unsubscribe())
296 }
297}
298impl fmt::Debug for CallbackContext {
299 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
300 formatter
301 .debug_struct("CallbackContext")
302 .field("id", &self.id)
303 .finish_non_exhaustive()
304 }
305}
306
307#[cfg(test)]
308mod close_context_tests;
309#[cfg(test)]
310mod lifetime_tests;
311#[cfg(test)]
312mod tests;
313
314#[cfg(test)]
315mod event_regression_tests;
316#[cfg(test)]
317mod event_tests;