deribit_websocket/session/
ws_session.rs1use crate::config::WebSocketConfig;
4use crate::model::ConnectionState;
5use crate::model::subscription::SubscriptionManager;
6use std::sync::Arc;
7use tokio::sync::Mutex;
8
9#[derive(Debug)]
11pub struct WebSocketSession {
12 config: Arc<WebSocketConfig>,
13 state: Arc<Mutex<ConnectionState>>,
14 subscription_manager: Arc<Mutex<SubscriptionManager>>,
15}
16
17impl WebSocketSession {
18 pub fn new(config: WebSocketConfig) -> Self {
20 Self {
21 config: Arc::new(config),
22 state: Arc::new(Mutex::new(ConnectionState::Disconnected)),
23 subscription_manager: Arc::new(Mutex::new(SubscriptionManager::new())),
24 }
25 }
26
27 pub async fn state(&self) -> ConnectionState {
29 self.state.lock().await.clone()
30 }
31
32 pub async fn set_state(&self, new_state: ConnectionState) {
34 *self.state.lock().await = new_state;
35 }
36
37 pub fn config(&self) -> &WebSocketConfig {
39 &self.config
40 }
41
42 pub fn subscription_manager(&self) -> Arc<Mutex<SubscriptionManager>> {
44 Arc::clone(&self.subscription_manager)
45 }
46
47 pub async fn is_connected(&self) -> bool {
49 matches!(
50 *self.state.lock().await,
51 ConnectionState::Connected | ConnectionState::Authenticated
52 )
53 }
54
55 pub async fn is_authenticated(&self) -> bool {
57 matches!(*self.state.lock().await, ConnectionState::Authenticated)
58 }
59
60 pub async fn mark_authenticated(&self) {
62 self.set_state(ConnectionState::Authenticated).await;
63 }
64
65 pub async fn mark_disconnected(&self) {
67 self.set_state(ConnectionState::Disconnected).await;
68 self.subscription_manager.lock().await.clear();
70 }
71
72 pub async fn reactivate_subscriptions(&self) {
74 self.subscription_manager.lock().await.reactivate_all();
75 }
76}