Skip to main content

simulator_client/
urls.rs

1//! Converting between the URL forms the server and the session's RPC endpoint use.
2//!
3//! [`crate::BacktestClient`] and [`crate::ManagedBacktestSession`] accept a bare host or a full
4//! URL and apply these for you; call them yourself only when you open connections by hand.
5
6use thiserror::Error;
7
8/// Error converting a URL scheme.
9#[derive(Debug, Error)]
10#[allow(missing_docs)]
11pub enum UrlError {
12    /// The URL does not start with `http://` or `https://`.
13    #[error("cannot derive WebSocket URL from `{url}`: expected http:// or https:// scheme")]
14    InvalidScheme { url: String },
15}
16
17/// Convert an `http(s)://` RPC endpoint URL to a `ws(s)://` URL.
18///
19/// # Errors
20///
21/// [`UrlError::InvalidScheme`] for any other scheme.
22pub fn http_to_ws_url(url: &str) -> Result<String, UrlError> {
23    let scheme = if url.starts_with("https://") {
24        "wss"
25    } else if url.starts_with("http://") {
26        "ws"
27    } else {
28        return Err(UrlError::InvalidScheme {
29            url: url.to_string(),
30        });
31    };
32    let rest = url.split_once("://").map(|x| x.1).unwrap_or(url);
33    Ok(format!("{scheme}://{rest}"))
34}
35
36/// Build the backtest WebSocket URL from a user-supplied endpoint: a bare
37/// hostname becomes `wss://{host}/backtest`, while an explicit `ws(s)://` URL
38/// keeps its scheme (for local development against plain-`ws://` servers) and
39/// gains the `/backtest` path only if missing. Any other scheme passes
40/// through untouched. Idempotent, so already-normalized URLs survive the
41/// [`crate::BacktestClient`] builder applying this to every `url` input.
42pub fn backtest_ws_url(url: &str) -> String {
43    if url.starts_with("ws://") || url.starts_with("wss://") {
44        let trimmed = url.trim_end_matches('/');
45        if trimmed.ends_with("/backtest") {
46            trimmed.to_string()
47        } else {
48            format!("{trimmed}/backtest")
49        }
50    } else if url.contains("://") {
51        url.to_string()
52    } else {
53        format!("wss://{}/backtest", url.trim_end_matches('/'))
54    }
55}
56
57/// Derive an HTTP base URL from a WebSocket URL, dropping the path:
58/// `wss://host:port/path` → `https://host:port`. The server's HTTP endpoints live under this
59/// base.
60pub fn http_base_from_ws_url(ws_url: &str) -> String {
61    let http = ws_url
62        .replacen("wss://", "https://", 1)
63        .replacen("ws://", "http://", 1);
64    if let Some(start) = http.find("://").map(|i| i + 3)
65        && let Some(slash) = http[start..].find('/')
66    {
67        return http[..start + slash].to_string();
68    }
69    http
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn http_to_ws_converts_http() {
78        assert_eq!(
79            http_to_ws_url("http://localhost:8899").unwrap(),
80            "ws://localhost:8899"
81        );
82    }
83
84    #[test]
85    fn http_to_ws_converts_https() {
86        assert_eq!(
87            http_to_ws_url("https://api.mainnet-beta.solana.com").unwrap(),
88            "wss://api.mainnet-beta.solana.com"
89        );
90    }
91
92    #[test]
93    fn http_to_ws_rejects_other_schemes() {
94        assert!(matches!(
95            http_to_ws_url("ws://example.com"),
96            Err(UrlError::InvalidScheme { .. })
97        ));
98        assert!(matches!(
99            http_to_ws_url("ftp://example.com"),
100            Err(UrlError::InvalidScheme { .. })
101        ));
102        assert!(matches!(
103            http_to_ws_url("example.com"),
104            Err(UrlError::InvalidScheme { .. })
105        ));
106    }
107
108    #[test]
109    fn backtest_ws_url_wraps_bare_hosts() {
110        assert_eq!(
111            backtest_ws_url("simulator.termina.technology"),
112            "wss://simulator.termina.technology/backtest"
113        );
114    }
115
116    #[test]
117    fn backtest_ws_url_keeps_explicit_schemes() {
118        assert_eq!(
119            backtest_ws_url("ws://localhost:8900"),
120            "ws://localhost:8900/backtest"
121        );
122        assert_eq!(
123            backtest_ws_url("wss://staging.simulator.termina.technology/"),
124            "wss://staging.simulator.termina.technology/backtest"
125        );
126    }
127
128    #[test]
129    fn backtest_ws_url_is_idempotent() {
130        for url in [
131            "simulator.termina.technology",
132            "ws://localhost:8900",
133            "wss://staging.simulator.termina.technology/",
134        ] {
135            let normalized = backtest_ws_url(url);
136            assert_eq!(backtest_ws_url(&normalized), normalized);
137        }
138    }
139
140    #[test]
141    fn backtest_ws_url_passes_other_schemes_through() {
142        assert_eq!(
143            backtest_ws_url("http://127.0.0.1:8900"),
144            "http://127.0.0.1:8900"
145        );
146        assert_eq!(
147            backtest_ws_url("https://host/backtest"),
148            "https://host/backtest"
149        );
150    }
151
152    #[test]
153    fn http_base_strips_path() {
154        assert_eq!(
155            http_base_from_ws_url("wss://host:8900/backtest"),
156            "https://host:8900"
157        );
158        assert_eq!(
159            http_base_from_ws_url("ws://localhost:8900/backtest"),
160            "http://localhost:8900"
161        );
162    }
163
164    #[test]
165    fn http_base_no_path() {
166        assert_eq!(
167            http_base_from_ws_url("wss://host:8900"),
168            "https://host:8900"
169        );
170    }
171}