Skip to main content

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