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#[must_use]
22pub struct Session {
23 inner: Arc<WSClientInner>,
26 runtime: Arc<SessionRuntime>,
28 journal: Option<ConnectionJournal>,
31 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 pub fn id(&self) -> SessionId {
50 self.runtime.id
51 }
52 pub fn client_id(&self) -> ClientId {
54 self.runtime.client_id
55 }
56 pub fn metadata(&self) -> &Metadata {
58 &self.metadata
59 }
60 pub fn sender(&self) -> Sender {
65 Sender {
66 runtime: self.runtime.clone(),
67 }
68 }
69 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 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 pub fn take_messages(&mut self) -> Option<MessageReceiver> {
92 self.runtime.messages.take_initial()
93 }
94 pub fn take_journal(&mut self) -> Option<ConnectionJournal> {
97 self.journal.take()
98 }
99 pub fn subscribe_messages(&self, options: ReceiveOptions) -> Result<MessageReceiver> {
101 self.runtime.messages.subscribe(options)
102 }
103 pub fn start_application_heartbeat(
111 &self,
112 config: ApplicationHeartbeatConfig,
113 ) -> Result<ApplicationHeartbeatHandle> {
114 self.start_heartbeat(config, None)
115 }
116 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 pub fn subscribe_events(&self) -> Result<ConnectionEvents> {
159 self.runtime.lifecycle.subscribe_events()
160 }
161 pub fn subscribe_tasks(&self, options: TaskEventOptions) -> Result<TaskEvents> {
163 self.runtime.tasks.subscribe(options)
164 }
165 pub fn watch_state(&self) -> Result<StateReceiver<ConnectionSnapshot>> {
167 self.runtime.lifecycle.watch_state()
168 }
169 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 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 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 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 pub fn state(&self) -> Result<ConnectionSnapshot> {
208 self.runtime.lifecycle.snapshot()
209 }
210 pub async fn wait_connected(&self) -> Result<ConnectionInfo> {
212 self.runtime.lifecycle.wait_connected().await
213 }
214 pub async fn closed(&self) -> Result<SessionEnd> {
218 self.inner.wait_session_closed(&self.runtime).await
219 }
220 pub fn notify_network_available(&self) {
225 if !self.runtime.is_closed() {
226 self.inner.notify_network_available();
227 }
228 }
229 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 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 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 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}