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 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 pub fn subscribe_events(&self) -> Result<ConnectionEvents> {
128 self.runtime.lifecycle.subscribe_events()
129 }
130 pub fn subscribe_tasks(&self, options: TaskEventOptions) -> Result<TaskEvents> {
132 self.runtime.tasks.subscribe(options)
133 }
134 pub fn watch_state(&self) -> Result<StateReceiver<ConnectionSnapshot>> {
136 self.runtime.lifecycle.watch_state()
137 }
138 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 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 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 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 pub fn state(&self) -> Result<ConnectionSnapshot> {
177 self.runtime.lifecycle.snapshot()
178 }
179 pub async fn wait_connected(&self) -> Result<ConnectionInfo> {
181 self.runtime.lifecycle.wait_connected().await
182 }
183 pub async fn closed(&self) -> Result<SessionEnd> {
187 self.inner.wait_session_closed(&self.runtime).await
188 }
189 pub fn notify_network_available(&self) {
194 if !self.runtime.is_closed() {
195 self.inner.notify_network_available();
196 }
197 }
198 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 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 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}