deribit_websocket/session/
ws_session.rs

1//! WebSocket session management
2
3use crate::config::WebSocketConfig;
4use crate::model::ConnectionState;
5use crate::model::subscription::SubscriptionManager;
6use std::sync::Arc;
7use tokio::sync::Mutex;
8
9/// WebSocket session manager
10#[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    /// Create a new WebSocket session
19    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    /// Get the current connection state
28    pub async fn state(&self) -> ConnectionState {
29        self.state.lock().await.clone()
30    }
31
32    /// Set the connection state
33    pub async fn set_state(&self, new_state: ConnectionState) {
34        *self.state.lock().await = new_state;
35    }
36
37    /// Get the configuration
38    pub fn config(&self) -> &WebSocketConfig {
39        &self.config
40    }
41
42    /// Get the subscription manager
43    pub fn subscription_manager(&self) -> Arc<Mutex<SubscriptionManager>> {
44        Arc::clone(&self.subscription_manager)
45    }
46
47    /// Check if session is connected
48    pub async fn is_connected(&self) -> bool {
49        matches!(
50            *self.state.lock().await,
51            ConnectionState::Connected | ConnectionState::Authenticated
52        )
53    }
54
55    /// Check if session is authenticated
56    pub async fn is_authenticated(&self) -> bool {
57        matches!(*self.state.lock().await, ConnectionState::Authenticated)
58    }
59
60    /// Mark session as authenticated
61    pub async fn mark_authenticated(&self) {
62        self.set_state(ConnectionState::Authenticated).await;
63    }
64
65    /// Mark session as disconnected
66    pub async fn mark_disconnected(&self) {
67        self.set_state(ConnectionState::Disconnected).await;
68        // Deactivate all subscriptions
69        self.subscription_manager.lock().await.clear();
70    }
71
72    /// Reactivate subscriptions after reconnection
73    pub async fn reactivate_subscriptions(&self) {
74        self.subscription_manager.lock().await.reactivate_all();
75    }
76}