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