Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
287 lines (257 loc) · 10.6 KB
/
Copy pathmod.rs
File metadata and controls
287 lines (257 loc) · 10.6 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
pub mod lighter_helpers;
pub mod extended_helpers;
#[allow(unused_imports)]
pub use std::time::Duration;
/// Exchange endpoint URLs for integration tests. Thin wrapper around the
/// compile-time constants in `arb_common::constants::*`. Kept as a struct
/// instead of raw `&'static str` consts so test files stay uncoupled from
/// the exact constant names (e.g. switching from mainnet to a future
/// testnet URL set requires one change here, not per-test).
pub struct TestUrls {
pub lighter_rest: String,
pub lighter_ws: String,
pub extended_rest: String,
pub extended_ws_orderbook: String,
pub extended_ws_account: String,
pub extended_ws_public_trades: String,
}
impl TestUrls {
pub fn load() -> Self {
Self {
lighter_rest: arb_common::constants::LIGHTER_REST_URL.to_string(),
lighter_ws: arb_common::constants::LIGHTER_WS_URL.to_string(),
extended_rest: arb_common::constants::EXTENDED_REST_URL.to_string(),
extended_ws_orderbook: arb_common::constants::EXTENDED_WS_ORDERBOOK_URL.to_string(),
extended_ws_account: arb_common::constants::EXTENDED_WS_ACCOUNT_URL.to_string(),
extended_ws_public_trades: arb_common::constants::EXTENDED_WS_PUBLIC_TRADES_URL.to_string(),
}
}
}
pub fn load_env() {
// Ensure working directory is the project root (parent of bot/) so that
// relative paths like "db/arb_bot.db" and "config/" resolve correctly,
// regardless of where `cargo test` sets cwd.
let manifest = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let project_root = manifest.parent().unwrap_or(&manifest);
let _ = std::env::set_current_dir(project_root);
let path = std::path::Path::new(".env");
if !path.exists() {
panic!(".env file not found at {} — cannot run integration tests", project_root.display());
}
let path = path.to_path_buf();
for line in std::fs::read_to_string(path).unwrap().lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((key, val)) = line.split_once('=')
&& std::env::var(key.trim()).is_err() {
unsafe { std::env::set_var(key.trim(), val.trim()) };
}
}
}
/// Load native root certificates with retry (macOS keychain can transiently fail).
fn build_test_root_store() -> tokio_rustls::rustls::RootCertStore {
let mut root_store = tokio_rustls::rustls::RootCertStore::empty();
let mut certs = None;
for attempt in 1..=3 {
match rustls_native_certs::load_native_certs() {
Ok(c) => { certs = Some(c); break; }
Err(e) => {
eprintln!("load_native_certs attempt {attempt}/3 failed: {e}");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
}
for cert in certs.expect("load_native_certs failed after 3 attempts") {
root_store.add(cert).ok();
}
root_store
}
pub fn build_test_tls_connector() -> tokio_rustls::TlsConnector {
let root_store = build_test_root_store();
let config = tokio_rustls::rustls::ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth();
tokio_rustls::TlsConnector::from(std::sync::Arc::new(config))
}
pub async fn connect_test_wss(
url: &str,
extra_headers: &[(&str, &str)],
connector: &tokio_rustls::TlsConnector,
) -> anyhow::Result<fastwebsockets::FragmentCollector<hyper_util::rt::TokioIo<hyper::upgrade::Upgraded>>> {
let parsed = url::Url::parse(url).map_err(|e| anyhow::anyhow!("bad url: {e}"))?;
let host = parsed.host_str().ok_or_else(|| anyhow::anyhow!("no host"))?;
let port = parsed.port().unwrap_or(443);
let tcp = tokio::net::TcpStream::connect(format!("{host}:{port}")).await?;
tcp.set_nodelay(true)?;
let server_name = tokio_rustls::rustls::pki_types::ServerName::try_from(host.to_string())?;
let tls = connector.connect(server_name, tcp).await?;
let mut req = hyper::Request::builder()
.method("GET")
.uri(url)
.header("Host", host)
.header("Connection", "Upgrade")
.header("Upgrade", "websocket")
.header("Sec-WebSocket-Version", "13")
.header("Sec-WebSocket-Key", fastwebsockets::handshake::generate_key())
.header("User-Agent", "arb_bot/test");
for (name, value) in extra_headers {
req = req.header(*name, *value);
}
struct Exec;
impl<F: std::future::Future<Output = ()> + Send + 'static> hyper::rt::Executor<F> for Exec {
fn execute(&self, fut: F) { tokio::spawn(fut); }
}
let (ws, _) = fastwebsockets::handshake::client(
&Exec,
req.body(http_body_util::Empty::<bytes::Bytes>::new())?,
Box::pin(tls),
).await?;
Ok(fastwebsockets::FragmentCollector::new(ws))
}
pub fn build_test_https_client() -> hyper_util::client::legacy::Client<
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
http_body_util::Full<bytes::Bytes>,
> {
// Reuse root store with retry logic from build_test_tls_connector
let root_store = build_test_root_store();
let config = tokio_rustls::rustls::ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth();
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(config)
.https_only()
.enable_http1()
.build();
hyper_util::client::legacy::Client::builder(
hyper_util::rt::TokioExecutor::new(),
).build(https)
}
pub async fn http_get_test(
url: &str,
headers: &[(&str, &str)],
connector: &tokio_rustls::TlsConnector,
) -> anyhow::Result<Vec<u8>> {
let parsed = url::Url::parse(url).map_err(|e| anyhow::anyhow!("bad url: {e}"))?;
let host = parsed.host_str().ok_or_else(|| anyhow::anyhow!("no host"))?;
let port = parsed.port().unwrap_or(443);
let path = if parsed.query().is_some() {
format!("{}?{}", parsed.path(), parsed.query().unwrap())
} else {
parsed.path().to_string()
};
let tcp = tokio::net::TcpStream::connect(format!("{host}:{port}")).await?;
tcp.set_nodelay(true)?;
let server_name = tokio_rustls::rustls::pki_types::ServerName::try_from(host.to_string())?;
let tls = connector.connect(server_name, tcp).await?;
let io = hyper_util::rt::TokioIo::new(Box::pin(tls));
let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?;
tokio::spawn(async move { let _ = conn.await; });
let mut req = hyper::Request::builder()
.method("GET")
.uri(&path)
.header("Host", host)
.header("User-Agent", "arb_bot/test");
for (name, value) in headers {
req = req.header(*name, *value);
}
use http_body_util::BodyExt;
let resp = sender.send_request(req.body(http_body_util::Empty::<bytes::Bytes>::new())?).await?;
let body = resp.into_body().collect().await?.to_bytes();
Ok(body.to_vec())
}
/// POST with JSON body for testing. Used by Hyperliquid `/info` probes.
pub async fn http_post_json_test(
url: &str,
json_body: &str,
connector: &tokio_rustls::TlsConnector,
) -> anyhow::Result<Vec<u8>> {
let parsed = url::Url::parse(url).map_err(|e| anyhow::anyhow!("bad url: {e}"))?;
let host = parsed.host_str().ok_or_else(|| anyhow::anyhow!("no host"))?;
let port = parsed.port().unwrap_or(443);
let path = parsed.path().to_string();
let tcp = tokio::net::TcpStream::connect(format!("{host}:{port}")).await?;
tcp.set_nodelay(true)?;
let server_name = tokio_rustls::rustls::pki_types::ServerName::try_from(host.to_string())?;
let tls = connector.connect(server_name, tcp).await?;
let io = hyper_util::rt::TokioIo::new(Box::pin(tls));
let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?;
tokio::spawn(async move { let _ = conn.await; });
let req = hyper::Request::builder()
.method("POST")
.uri(&path)
.header("Host", host)
.header("User-Agent", "arb_bot/test")
.header("Content-Type", "application/json")
.body(http_body_util::Full::new(bytes::Bytes::from(json_body.to_string())))?;
use http_body_util::BodyExt;
let resp = sender.send_request(req).await?;
let body = resp.into_body().collect().await?.to_bytes();
Ok(body.to_vec())
}
pub async fn extended_api_get(
client: &hyper_util::client::legacy::Client<
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
http_body_util::Full<bytes::Bytes>,
>,
rest_url: &str,
path: &str,
api_key: &str,
) -> Vec<u8> {
let url = format!("{rest_url}{path}");
let req = hyper::Request::builder()
.method("GET")
.uri(&url)
.header("X-Api-Key", api_key)
.header("User-Agent", "arb_bot/test")
.body(http_body_util::Full::new(bytes::Bytes::new()))
.unwrap();
let resp = client.request(req).await.expect("GET request failed");
use http_body_util::BodyExt;
resp.into_body().collect().await.unwrap().to_bytes().to_vec()
}
pub async fn extended_api_post(
client: &hyper_util::client::legacy::Client<
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
http_body_util::Full<bytes::Bytes>,
>,
rest_url: &str,
path: &str,
api_key: &str,
body: &str,
) -> Vec<u8> {
let url = format!("{rest_url}{path}");
let req = hyper::Request::builder()
.method("POST")
.uri(&url)
.header("X-Api-Key", api_key)
.header("Content-Type", "application/json")
.header("User-Agent", "arb_bot/test")
.body(http_body_util::Full::new(bytes::Bytes::from(body.to_owned())))
.unwrap();
let resp = client.request(req).await.expect("POST request failed");
use http_body_util::BodyExt;
resp.into_body().collect().await.unwrap().to_bytes().to_vec()
}
pub async fn extended_api_delete(
client: &hyper_util::client::legacy::Client<
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
http_body_util::Full<bytes::Bytes>,
>,
rest_url: &str,
path: &str,
api_key: &str,
) -> Vec<u8> {
let url = format!("{rest_url}{path}");
let req = hyper::Request::builder()
.method("DELETE")
.uri(&url)
.header("X-Api-Key", api_key)
.header("User-Agent", "arb_bot/test")
.body(http_body_util::Full::new(bytes::Bytes::new()))
.unwrap();
let resp = client.request(req).await.expect("DELETE request failed");
use http_body_util::BodyExt;
resp.into_body().collect().await.unwrap().to_bytes().to_vec()
}