binary_option_tools_core/pocketoption/ws/
connect.rs1use async_trait::async_trait;
2use tokio::net::TcpStream;
3use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
4use tracing::warn;
5
6use crate::{
7 error::BinaryOptionsResult,
8 general::traits::Connect,
9 pocketoption::{error::PocketOptionError, utils::connect::try_connect},
10};
11
12use super::ssid::Ssid;
13
14#[derive(Clone)]
15pub struct PocketConnect;
16
17#[async_trait]
18impl Connect for PocketConnect {
19 type Creds = Ssid;
20
21 async fn connect(
22 &self,
23 creds: Self::Creds,
24 ) -> BinaryOptionsResult<WebSocketStream<MaybeTlsStream<TcpStream>>> {
25 let urls = creds.servers().await?;
26 let mut error = None;
27 for url in urls.clone() {
28 match try_connect(creds.clone(), url).await {
29 Ok(connect) => return Ok(connect),
30 Err(e) => {
31 warn!("Failed to connect to server, {e}");
32 error = Some(e);
33 }
34 }
35 }
36 if let Some(error) = error {
37 Err(error.into())
38 } else {
39 Err(
40 PocketOptionError::WebsocketMultipleAttemptsConnectionError(format!(
41 "Couldn't connect to server after {} attempts.",
42 urls.len()
43 ))
44 .into(),
45 )
46 }
47 }
48}