-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathhttp.rs
170 lines (162 loc) · 4.88 KB
/
http.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::{
io,
io::ErrorKind,
time::{Duration, Instant},
};
use anyhow::Error;
use chrono::{DateTime, Utc};
use futures_util::{SinkExt, StreamExt};
use tokio::{
select,
sync::mpsc::{UnboundedSender, unbounded_channel},
};
use tokio_tungstenite::{
connect_async,
tungstenite::{Bytes, Message, Utf8Bytes, client::IntoClientRequest},
};
use tracing::{error, warn};
pub async fn fetch_depth_snapshot(symbol: &str) -> Result<String, reqwest::Error> {
reqwest::Client::new()
.get(format!(
"https://api-cloud-v2.bitmart.com/contract/public/depth?symbol={symbol}"
))
.header("Accept", "application/json")
.send()
.await?
.text()
.await
}
pub async fn connect(
url: &str,
topics: Vec<String>,
ws_tx: UnboundedSender<(DateTime<Utc>, Utf8Bytes)>,
) -> Result<(), anyhow::Error> {
let request = url.into_client_request()?;
let (ws_stream, _) = connect_async(request).await?;
let (mut write, mut read) = ws_stream.split();
let (tx, mut rx) = unbounded_channel::<()>();
let s = format!(
r#"{{"action":"subscribe","args":[{}]}}"#,
topics
.iter()
.map(|s| format!("\"{s}\""))
.collect::<Vec<_>>()
.join(",")
);
write
.send(Message::Text(
format!(
// r#"{{"req_id": "subscribe", "op": "subscribe", "args": [{}]}}"#,
r#"{{"action":"subscribe","args":[{}]}}"#,
topics
.iter()
.map(|s| format!("\"{s}\""))
.collect::<Vec<_>>()
.join(",")
)
.into(),
))
.await?;
tokio::spawn(async move {
let mut ping_interval = tokio::time::interval(Duration::from_secs(30));
loop {
select! {
result = rx.recv() => {
match result {
Some(_) => {
if write.send(Message::Pong(Bytes::default())).await.is_err() {
return;
}
}
None => {
break;
}
}
}
_ = ping_interval.tick() => {
if write.send(
Message::Text(r#"{"action":"ping"}"#.into())
).await.is_err() {
return;
}
}
}
}
});
loop {
match read.next().await {
Some(Ok(Message::Text(text))) => {
let recv_time = Utc::now();
if ws_tx.send((recv_time, text)).is_err() {
break;
}
}
Some(Ok(Message::Binary(_))) => {}
Some(Ok(Message::Ping(_))) => {
tx.send(()).unwrap();
}
Some(Ok(Message::Pong(_))) => {}
Some(Ok(Message::Close(close_frame))) => {
warn!(?close_frame, "closed");
return Err(Error::from(io::Error::new(
ErrorKind::ConnectionAborted,
"closed",
)));
}
Some(Ok(Message::Frame(_))) => {}
Some(Err(e)) => {
return Err(Error::from(e));
}
None => {
break;
}
}
}
Ok(())
}
pub async fn keep_connection(
topics: Vec<String>,
symbol_list: Vec<String>,
ws_tx: UnboundedSender<(DateTime<Utc>, Utf8Bytes)>,
) {
let mut error_count = 0;
loop {
let connect_time = Instant::now();
let topics_ = symbol_list
.iter()
.flat_map(|pair| {
topics
.iter()
.cloned()
.map(|stream| {
stream
.replace("$symbol", pair.to_uppercase().as_str())
.to_string()
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
if let Err(error) = connect(
"wss://openapi-ws-v2.bitmart.com/api?protocol=1.1",
topics_,
ws_tx.clone(),
)
.await
{
error!(?error, "websocket error");
error_count += 1;
if connect_time.elapsed() > Duration::from_secs(30) {
error_count = 0;
}
if error_count > 3 {
tokio::time::sleep(Duration::from_secs(1)).await;
} else if error_count > 10 {
tokio::time::sleep(Duration::from_secs(5)).await;
} else if error_count > 20 {
tokio::time::sleep(Duration::from_secs(10)).await;
}
} else {
break;
}
}
}