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        self.start_heartbeat(config, None)
115    }
116    /// Starts a heartbeat that requests session recovery after consecutive response
117    /// timeouts on the same physical connection. A successful local write starts
118    /// each response wait. A matched reply or another kind of failure resets the streak.
119    ///
120    /// At the configured threshold the task waits for a different connection, then
121    /// continues using the same handle. Other failures (such as a write or matcher
122    /// error) retain the configured failure action. A response matcher, response
123    /// timeout and an enabled session reconnect policy are required.
124    ///
125    /// The matcher uses the same dedicated subscription as
126    /// [`Self::start_application_heartbeat`].
127    pub fn start_application_heartbeat_with_reconnect(
128        &self,
129        config: ApplicationHeartbeatConfig,
130    ) -> Result<ApplicationHeartbeatHandle> {
131        self.runtime.ensure_reconnect_enabled()?;
132        if config.matcher.is_none() {
133            return Err(NetError::config(
134                "application_heartbeat.matcher",
135                "is required to reconnect after missed responses",
136            ));
137        }
138        self.start_heartbeat(config, Some(Arc::downgrade(&self.inner)))
139    }
140    fn start_heartbeat(
141        &self,
142        config: ApplicationHeartbeatConfig,
143        reconnect: Option<std::sync::Weak<WSClientInner>>,
144    ) -> Result<ApplicationHeartbeatHandle> {
145        config.validate()?;
146        let receiver = if config.matcher.is_some() {
147            Some(
148                self.runtime
149                    .messages
150                    .subscribe(config.receive_options.clone())?,
151            )
152        } else {
153            None
154        };
155        ApplicationHeartbeatHandle::new(self.sender(), receiver, config, reconnect)
156    }
157    /// Subscribes to connection lifecycle events.
158    pub fn subscribe_events(&self) -> Result<ConnectionEvents> {
159        self.runtime.lifecycle.subscribe_events()
160    }
161    /// Subscribes to task events using the supplied bounded delivery options.
162    pub fn subscribe_tasks(&self, options: TaskEventOptions) -> Result<TaskEvents> {
163        self.runtime.tasks.subscribe(options)
164    }
165    /// Creates a state receiver that observes the latest connection snapshot.
166    pub fn watch_state(&self) -> Result<StateReceiver<ConnectionSnapshot>> {
167        self.runtime.lifecycle.watch_state()
168    }
169    /// Registers a callback for incoming messages on the initial message lane.
170    pub fn on_message<F>(&mut self, callback: F) -> Result<Subscription>
171    where
172        F: Fn(CallbackContext, std::result::Result<IncomingMessage, ReceiveError>)
173            + Send
174            + Sync
175            + 'static,
176    {
177        self.runtime.messages.on_initial_message(callback)
178    }
179    /// Registers a callback for connection lifecycle events.
180    pub fn on_event<F>(&self, callback: F) -> Result<Subscription>
181    where
182        F: Fn(CallbackContext, std::result::Result<ConnectionEvent, ReceiveError>)
183            + Send
184            + Sync
185            + 'static,
186    {
187        self.subscribe_events()?.into_callback(callback)
188    }
189    /// Registers a callback for task events with the supplied delivery options.
190    pub fn on_task<F>(&self, options: TaskEventOptions, callback: F) -> Result<Subscription>
191    where
192        F: Fn(CallbackContext, std::result::Result<TaskEvent, ReceiveError>)
193            + Send
194            + Sync
195            + 'static,
196    {
197        self.subscribe_tasks(options)?.into_callback(callback)
198    }
199    /// Registers a callback for connection-state changes.
200    pub fn on_state<F>(&self, callback: F) -> Result<Subscription>
201    where
202        F: Fn(CallbackContext, Result<ConnectionSnapshot>) + Send + Sync + 'static,
203    {
204        self.watch_state()?.into_callback(callback)
205    }
206    /// Reads the current connection snapshot without waiting for a transition.
207    pub fn state(&self) -> Result<ConnectionSnapshot> {
208        self.runtime.lifecycle.snapshot()
209    }
210    /// Waits until a physical connection is established and returns its info.
211    pub async fn wait_connected(&self) -> Result<ConnectionInfo> {
212        self.runtime.lifecycle.wait_connected().await
213    }
214    /// Waits for lifecycle publication and cleanup to complete, then returns the
215    /// immutable terminal result. A cancelled session may return an error and
216    /// still permit a new session on a live client. Client shutdown is permanent.
217    pub async fn closed(&self) -> Result<SessionEnd> {
218        self.inner.wait_session_closed(&self.runtime).await
219    }
220    /// Notifies the client that network access may have returned.
221    ///
222    /// The notification is advisory; it does not create a connection or alter
223    /// the configured reconnect policy.
224    pub fn notify_network_available(&self) {
225        if !self.runtime.is_closed() {
226            self.inner.notify_network_available();
227        }
228    }
229    /// Requests recovery if `expected` is still this session's active connection.
230    ///
231    /// Pass the ID observed on this session when the problem occurred. Returns
232    /// `true` when the worker accepts the request, or `false` if the physical
233    /// connection has already changed or recovery is in progress. The same
234    /// senders and subscriptions continue across recovery. Observe a new
235    /// [`Established`](super::ConnectionEventKind::Established) event for success.
236    ///
237    /// With [`ReconnectPolicy::Disabled`](super::ReconnectPolicy::Disabled), a
238    /// matching active connection is preserved and the result is
239    /// [`ErrorKind::InvalidPolicy`]. Closing or cancelled sessions return an error.
240    pub async fn reconnect_if_current(&self, expected: super::ConnectionId) -> Result<bool> {
241        self.inner
242            .reconnect_if_current(&self.runtime, expected, None)
243            .await
244    }
245    /// Requests cancellation and returns whether this call won the request race.
246    ///
247    /// Cancellation is cooperative. The session's terminal result is reported by
248    /// [`Self::closed`]; existing send or request operations may complete with a
249    /// cancellation or delivery-unknown outcome.
250    pub fn cancel(&self) -> bool {
251        let requested = self.runtime.lifecycle.request_cancel();
252        if requested {
253            crate::log_t!(crate::LogType::WSC; "ws.session.cancel",
254                "client_id|session_id", self.client_id().as_u64(), self.id().as_u64());
255        }
256        if self.runtime.lifecycle.completion_token().is_cancelled() {
257            self.runtime.end(
258                NetError::from(ErrorKind::Cancelled),
259                super::TaskEndCause::Cancelled,
260            );
261        }
262        requested
263    }
264    /// Gracefully closes the session using the protocol's default close frame.
265    pub async fn close(&self) -> Result<SessionEnd> {
266        crate::log_t!(crate::LogType::WSC; "ws.session.close",
267            "client_id|session_id|with_frame", self.client_id().as_u64(), self.id().as_u64(), false);
268        self.inner.close_session(&self.runtime, None).await
269    }
270    /// Gracefully closes the session with an application-supplied close frame.
271    ///
272    /// The returned value describes session termination; it does not guarantee
273    /// that a peer has processed the close frame.
274    pub async fn close_with(&self, frame: CloseFrame) -> Result<SessionEnd> {
275        crate::log_t!(crate::LogType::WSC; "ws.session.close_with",
276            "client_id|session_id|with_frame|close_code", self.client_id().as_u64(), self.id().as_u64(), true, frame.code());
277        self.inner.close_session(&self.runtime, Some(frame)).await
278    }
279}
280impl Drop for Session {
281    fn drop(&mut self) {
282        drop(self.runtime.messages.take_initial());
283        self.runtime.lifecycle.request_cancel();
284        self.runtime.end(
285            NetError::from(ErrorKind::Cancelled),
286            super::TaskEndCause::Cancelled,
287        );
288    }
289}
290impl fmt::Debug for Session {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        f.debug_struct("Session")
293            .field("id", &self.id())
294            .field("client_id", &self.client_id())
295            .field("state", &self.state())
296            .finish_non_exhaustive()
297    }
298}