Skip to main content

binary_options_tools_core_pre/
connector.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4use thiserror::Error;
5use tokio::net::TcpStream;
6use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
7
8use crate::traits::AppState;
9
10#[derive(Error, Debug)]
11pub enum ConnectorError {
12    #[error("WebSocket connection failed: {0}")]
13    ConnectionFailed(Box<tokio_tungstenite::tungstenite::Error>),
14    #[error("Connection timeout")]
15    Timeout,
16    #[error(
17        "Could not connect to the server after multiple attempts: {attempts} attempts on platform {platform}"
18    )]
19    MultipleAttemptsConnection { attempts: usize, platform: String },
20    #[error("Connection is closed")]
21    ConnectionClosed,
22    #[error("Custom: {0}")]
23    Custom(String),
24    #[error("Tls error: {0}")]
25    Tls(String),
26    #[error("Url parsing error, {0} is not a valid url")]
27    UrlParsing(String),
28    #[error("Failed to build http request: {0}")]
29    HttpRequestBuild(String),
30    #[error("Core error: {0}")]
31    Core(String),
32}
33
34pub type ConnectorResult<T> = std::result::Result<T, ConnectorError>;
35pub type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
36
37#[async_trait]
38pub trait Connector<S: AppState>: Send + Sync {
39    /// Connect to the WebSocket server and return the stream
40    async fn connect(&self, state: Arc<S>) -> ConnectorResult<WsStream>;
41
42    /// Disconnect from the WebSocket server
43    async fn disconnect(&self) -> ConnectorResult<()>;
44
45    /// Reconnect to the WebSocket server with automatic retry logic and return the stream
46    async fn reconnect(&self, state: Arc<S>) -> ConnectorResult<WsStream> {
47        self.disconnect().await?;
48
49        // Retry logic can be implemented here if needed
50        self.connect(state).await
51    }
52}