Skip to main content

open_net/api/ws/
session.rs

1use super::{
2    ApplicationHeartbeatConfig, ApplicationHeartbeatHandle, ClientId, CloseFrame, ConnectionEvent,
3    ConnectionEvents, ConnectionInfo, ConnectionJournal, ConnectionSnapshot, IncomingMessage,
4    MessageReceiver, ReceiveOptions, RequestClient, ResponseResolver, ResponseRouting, Sender,
5    SessionEnd, SessionId, TaskEvent, TaskEventOptions, TaskEvents,
6};
7use crate::error::{ErrorKind, ReceiveError};
8use crate::module::ws_client::{session_runtime::SessionRuntime, ws_client_inner::WSClientInner};
9use crate::subscription::{CallbackContext, StateReceiver, Subscription};
10use crate::{Metadata, NetError, Result};
11use std::{fmt, sync::Arc};
12
13/// Owner of a session's lifecycle.
14///
15/// Dropping the owner requests cancellation and completes the session without
16/// blocking the dropping thread. A sender, request client, or subscription
17/// cloned from the session does not keep the session alive.
18///
19/// Dropping a receiver obtained from the session only removes that subscription;
20/// it does not close the session.
21#[must_use]
22pub struct Session {
23    /// Client implementation that coordinates close requests and network-
24    /// availability notifications.
25    inner: Arc<WSClientInner>,
26    /// Shared runtime state to which senders and request clients are bound.
27    runtime: Arc<SessionRuntime>,
28    /// Optional connection-journal receiver created with the session. It is
29    /// `None` when journaling was disabled or the receiver has been taken.
30    journal: Option<ConnectionJournal>,
31    /// Application metadata supplied when the session was created.
32    metadata: Metadata,
33}
34impl Session {
35    pub(crate) fn new(
36        inner: Arc<WSClientInner>,
37        runtime: Arc<SessionRuntime>,
38        journal: Option<ConnectionJournal>,
39        metadata: Metadata,
40    ) -> Self {
41        Self {
42            inner,
43            runtime,
44            journal,
45            metadata,
46        }
47    }
48    /// Returns this logical session's stable identifier.
49    pub fn id(&self) -> SessionId {
50        self.runtime.id
51    }
52    /// Returns the identifier of the client that created this session.
53    pub fn client_id(&self) -> ClientId {
54        self.runtime.client_id
55    }
56    /// Borrows the application metadata attached to this session.
57    pub fn metadata(&self) -> &Metadata {
58        &self.metadata
59    }
60    /// Creates a sender bound to this session.
61    ///
62    /// Clones remain usable across reconnects, but cannot prevent session
63    /// cancellation after this owner is dropped.
64    pub fn sender(&self) -> Sender {
65        Sender {
66            runtime: self.runtime.clone(),
67        }
68    }
69    /// Creates the request API when response routing is enabled for the session.
70    ///
71    /// Returns [`ErrorKind::RoutingDisabled`](crate::error::ErrorKind::RoutingDisabled)
72    /// when the session was configured for one-way messaging.
73    pub fn requests(&self) -> Result<RequestClient> {
74        if matches!(self.runtime.routing, ResponseRouting::Disabled) {
75            return Err(NetError::from(ErrorKind::RoutingDisabled));
76        }
77        Ok(RequestClient {
78            runtime: self.runtime.clone(),
79        })
80    }
81    /// Creates a manual response resolver when manual routing is configured.
82    ///
83    /// Automatic routing modes return a routing-mode mismatch error.
84    pub fn response_resolver(&self) -> Result<ResponseResolver> {
85        if !matches!(self.runtime.routing, ResponseRouting::Manual) {
86            return Err(NetError::from(ErrorKind::RoutingModeMismatch));
87        }
88        Ok(ResponseResolver::new(Arc::downgrade(&self.runtime.pending)))
89    }
90    /// Takes the session's one-time initial message receiver, if available.
91    pub fn take_messages(&mut self) -> Option<MessageReceiver> {
92        self.runtime.messages.take_initial()
93    }
94    /// Takes the optional connection journal receiver. A receiver can be taken
95    /// only once; subsequent calls return `None`.
96    pub fn take_journal(&mut self) -> Option<ConnectionJournal> {
97        self.journal.take()
98    }
99    /// Subscribes to incoming messages using the supplied bounded receive policy.
100    pub fn subscribe_messages(&self, options: ReceiveOptions) -> Result<MessageReceiver> {
101        self.runtime.messages.subscribe(options)
102    }
103    /// Starts a fixed-interval application-level heartbeat loop.
104    ///
105    /// A response matcher uses a dedicated bounded message subscription. When
106    /// the session keeps the default initial inbox, take that inbox first or
107    /// configure [`InitialMessages::DiscardUnmatched`](super::InitialMessages)
108    /// when creating the session. Write-only heartbeats do not allocate a
109    /// message subscription.
110    pub fn start_application_heartbeat(
111        &self,
112        config: ApplicationHeartbeatConfig,
113    ) -> Result<ApplicationHeartbeatHandle> {
114        config.validate()?;
115        let receiver = if config.matcher.is_some() {
116            Some(
117                self.runtime
118                    .messages
119                    .subscribe(config.receive_options.clone())?,
120            )
121        } else {
122            None
123        };
124        ApplicationHeartbeatHandle::new(self.sender(), receiver, config)
125    }
126    /// Subscribes to connection lifecycle events.
127    pub fn subscribe_events(&self) -> Result<ConnectionEvents> {
128        self.runtime.lifecycle.subscribe_events()
129    }
130    /// Subscribes to task events using the supplied bounded delivery options.
131    pub fn subscribe_tasks(&self, options: TaskEventOptions) -> Result<TaskEvents> {
132        self.runtime.tasks.subscribe(options)
133    }
134    /// Creates a state receiver that observes the latest connection snapshot.
135    pub fn watch_state(&self) -> Result<StateReceiver<ConnectionSnapshot>> {
136        self.runtime.lifecycle.watch_state()
137    }
138    /// Registers a callback for incoming messages on the initial message lane.
139    pub fn on_message<F>(&mut self, callback: F) -> Result<Subscription>
140    where
141        F: Fn(CallbackContext, std::result::Result<IncomingMessage, ReceiveError>)
142            + Send
143            + Sync
144            + 'static,
145    {
146        self.runtime.messages.on_initial_message(callback)
147    }
148    /// Registers a callback for connection lifecycle events.
149    pub fn on_event<F>(&self, callback: F) -> Result<Subscription>
150    where
151        F: Fn(CallbackContext, std::result::Result<ConnectionEvent, ReceiveError>)
152            + Send
153            + Sync
154            + 'static,
155    {
156        self.subscribe_events()?.into_callback(callback)
157    }
158    /// Registers a callback for task events with the supplied delivery options.
159    pub fn on_task<F>(&self, options: TaskEventOptions, callback: F) -> Result<Subscription>
160    where
161        F: Fn(CallbackContext, std::result::Result<TaskEvent, ReceiveError>)
162            + Send
163            + Sync
164            + 'static,
165    {
166        self.subscribe_tasks(options)?.into_callback(callback)
167    }
168    /// Registers a callback for connection-state changes.
169    pub fn on_state<F>(&self, callback: F) -> Result<Subscription>
170    where
171        F: Fn(CallbackContext, Result<ConnectionSnapshot>) + Send + Sync + 'static,
172    {
173        self.watch_state()?.into_callback(callback)
174    }
175    /// Reads the current connection snapshot without waiting for a transition.
176    pub fn state(&self) -> Result<ConnectionSnapshot> {
177        self.runtime.lifecycle.snapshot()
178    }
179    /// Waits until a physical connection is established and returns its info.
180    pub async fn wait_connected(&self) -> Result<ConnectionInfo> {
181        self.runtime.lifecycle.wait_connected().await
182    }
183    /// Waits for lifecycle publication and cleanup to complete, then returns the
184    /// immutable terminal result. A cancelled session may return an error and
185    /// still permit a new session on a live client. Client shutdown is permanent.
186    pub async fn closed(&self) -> Result<SessionEnd> {
187        self.inner.wait_session_closed(&self.runtime).await
188    }
189    /// Notifies the client that network access may have returned.
190    ///
191    /// The notification is advisory; it does not create a connection or alter
192    /// the configured reconnect policy.
193    pub fn notify_network_available(&self) {
194        if !self.runtime.is_closed() {
195            self.inner.notify_network_available();
196        }
197    }
198    /// Requests cancellation and returns whether this call won the request race.
199    ///
200    /// Cancellation is cooperative. The session's terminal result is reported by
201    /// [`Self::closed`]; existing send or request operations may complete with a
202    /// cancellation or delivery-unknown outcome.
203    pub fn cancel(&self) -> bool {
204        let requested = self.runtime.lifecycle.request_cancel();
205        if requested {
206            crate::log_t!(crate::LogType::WSC; "ws.session.cancel",
207                "client_id|session_id", self.client_id().as_u64(), self.id().as_u64());
208        }
209        if self.runtime.lifecycle.completion_token().is_cancelled() {
210            self.runtime.end(
211                NetError::from(ErrorKind::Cancelled),
212                super::TaskEndCause::Cancelled,
213            );
214        }
215        requested
216    }
217    /// Gracefully closes the session using the protocol's default close frame.
218    pub async fn close(&self) -> Result<SessionEnd> {
219        crate::log_t!(crate::LogType::WSC; "ws.session.close",
220            "client_id|session_id|with_frame", self.client_id().as_u64(), self.id().as_u64(), false);
221        self.inner.close_session(&self.runtime, None).await
222    }
223    /// Gracefully closes the session with an application-supplied close frame.
224    ///
225    /// The returned value describes session termination; it does not guarantee
226    /// that a peer has processed the close frame.
227    pub async fn close_with(&self, frame: CloseFrame) -> Result<SessionEnd> {
228        crate::log_t!(crate::LogType::WSC; "ws.session.close_with",
229            "client_id|session_id|with_frame|close_code", self.client_id().as_u64(), self.id().as_u64(), true, frame.code());
230        self.inner.close_session(&self.runtime, Some(frame)).await
231    }
232}
233impl Drop for Session {
234    fn drop(&mut self) {
235        drop(self.runtime.messages.take_initial());
236        self.runtime.lifecycle.request_cancel();
237        self.runtime.end(
238            NetError::from(ErrorKind::Cancelled),
239            super::TaskEndCause::Cancelled,
240        );
241    }
242}
243impl fmt::Debug for Session {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.debug_struct("Session")
246            .field("id", &self.id())
247            .field("client_id", &self.client_id())
248            .field("state", &self.state())
249            .finish_non_exhaustive()
250    }
251}