simulator-api 0.31.0

Wire-protocol types for the Solana simulator backtest WebSocket API
Documentation
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! The one mapping between a session id and the DNS name of its endpoint.

use std::{fmt, net::Ipv4Addr, str::FromStr};

use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use http::{Uri, uri::Scheme};
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use subtle::ConstantTimeEq;
use uuid::Uuid;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::{ControlSessionId, SessionId, SlotRange, session_name::SessionName};

/// Header that carries the [`SessionToken`].
pub const SESSION_TOKEN_HEADER: &str = "x-token";
/// Query parameter that carries the [`SessionToken`].
pub const SESSION_TOKEN_QUERY_PARAM: &str = "token";

const TOKEN_BYTES: usize = 32;

/// Admits a client to one session's endpoint. 256 random bits, base64url. No lifetime, not signed.
///
/// No `PartialEq` or `Display`: compare only with `matches`, so a token never compares in variable time or prints.
#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
#[serde(transparent)]
pub struct SessionToken(String);

impl SessionToken {
    /// A new token from the thread-local CSPRNG.
    pub fn generate() -> Self {
        let mut bytes = [0u8; TOKEN_BYTES];
        rand::fill(&mut bytes);
        let token = Self(URL_SAFE_NO_PAD.encode(bytes));
        bytes.zeroize();
        token
    }

    /// The secret.
    pub fn expose(&self) -> &str {
        &self.0
    }

    /// Constant time.
    pub fn matches(&self, presented: &[u8]) -> bool {
        self.0.as_bytes().ct_eq(presented).into()
    }
}

/// The token in one `key=value` pair of a query, when the key is [`SESSION_TOKEN_QUERY_PARAM`].
pub fn token_in_query_pair(pair: &str) -> Option<&str> {
    let (key, value) = pair.split_once('=')?;
    (key == SESSION_TOKEN_QUERY_PARAM).then_some(value)
}

impl fmt::Debug for SessionToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SessionToken(..)")
    }
}

const MAX_HOST_NAME_LEN: usize = 253;
const MAX_LABEL_LEN: usize = 63;
const SESSION_LABEL_LEN: usize = 32;
const SESSION_PREFIX_LEN: usize = SESSION_LABEL_LEN + 1;

/// `<scheme>://<host>[:<port>][/]` only; the scheme is not checked.
pub fn parse_origin(s: &str) -> Option<Uri> {
    let uri: Uri = s.parse().ok()?;
    let is_origin = uri.authority().is_some_and(|a| !a.as_str().contains('@'))
        && uri.path() == "/"
        && uri.query().is_none()
        && !s.contains('#');
    is_origin.then_some(uri)
}

/// The domain of the sessions zone, such as `sessions.simulator.termina.technology`. Lowercase, with no leading or trailing dot.
#[derive(Debug, Clone, PartialEq, Eq, Hash, SerializeDisplay, DeserializeFromStr)]
pub struct SessionsDomain(String);

/// Why a string is not a valid [`SessionsDomain`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("`{0}` is not a lowercase DNS domain")]
pub struct InvalidSessionsDomain(String);

impl SessionsDomain {
    /// The domain, without a trailing dot.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// `*.<domain>`: the one name on the certificate that covers every session.
    pub fn wildcard(&self) -> String {
        format!("*.{}", self.0)
    }
}

fn is_valid_label(label: &str) -> bool {
    let is_label_byte = |b: &u8| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-';
    (1..=MAX_LABEL_LEN).contains(&label.len())
        && label.bytes().all(|b| is_label_byte(&b))
        && !label.starts_with('-')
        && !label.ends_with('-')
}

impl FromStr for SessionsDomain {
    type Err = InvalidSessionsDomain;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let fits = SESSION_PREFIX_LEN + s.len() <= MAX_HOST_NAME_LEN;
        if fits && s.contains('.') && s.split('.').all(is_valid_label) {
            Ok(Self(s.to_owned()))
        } else {
            Err(InvalidSessionsDomain(s.to_owned()))
        }
    }
}

impl fmt::Display for SessionsDomain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// The DNS name of one session's endpoint: `<32 lowercase hex of the session id>.<domain>`. The `backtest_` prefix is left out because `_` is not valid in a host name.
#[derive(Debug, Clone, PartialEq, Eq, Hash, SerializeDisplay, DeserializeFromStr)]
pub struct SessionHostName {
    session_id: SessionId,
    domain: SessionsDomain,
}

/// Why a string is not a valid [`SessionHostName`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum InvalidSessionHostName {
    /// The first label is not 32 lowercase hex characters, or there is no dot.
    #[error("`{0}` does not start with a 32-hex session label")]
    Label(String),
    /// The part after the first dot is not a valid domain.
    #[error(transparent)]
    Domain(#[from] InvalidSessionsDomain),
}

impl SessionHostName {
    /// The host name of `session_id` in `domain`.
    pub fn new(session_id: SessionId, domain: SessionsDomain) -> Self {
        Self { session_id, domain }
    }

    /// The session this host name belongs to.
    pub fn session_id(&self) -> SessionId {
        self.session_id
    }

    /// The domain after the session label.
    pub fn domain(&self) -> &SessionsDomain {
        &self.domain
    }
}

impl fmt::Display for SessionHostName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.session_id.as_uuid().simple(), self.domain)
    }
}

impl FromStr for SessionHostName {
    type Err = InvalidSessionHostName;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let label_error = || InvalidSessionHostName::Label(s.to_owned());
        let (label, domain) = s.split_once('.').ok_or_else(label_error)?;
        let is_lower_hex = |b: u8| b.is_ascii_digit() || (b'a'..=b'f').contains(&b);
        if label.len() != SESSION_LABEL_LEN || !label.bytes().all(is_lower_hex) {
            return Err(label_error());
        }
        #[expect(
            clippy::map_err_ignore,
            reason = "host label error reports the full hostname"
        )]
        let uuid = Uuid::try_parse(label).map_err(|_| label_error())?;
        Ok(Self::new(SessionId::from_uuid(uuid), domain.parse()?))
    }
}

const HTTPS_PORT: u16 = 443;

/// Scheme, host and optional port; no path or query.
#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
pub struct SessionEndpointUrl(String);

/// Why a string is not a valid [`SessionEndpointUrl`].
#[derive(Debug, thiserror::Error)]
pub enum InvalidSessionEndpointUrl {
    /// The scheme is not `http` or `https`, or the text is not a URL.
    #[error("`{0}` is not an http or https URL")]
    NotHttp(String),
    /// The URL has an empty host.
    #[error("`{0}` has no host")]
    NoHost(String),
    /// The URL is plain `http` and its host is not `127.0.0.1`.
    #[error("`{0}` is plain http on a host that is not loopback")]
    PlainHttp(String),
    /// The URL has a path, a query, a fragment or user info.
    #[error("`{0}` has a path or a query")]
    NotAnOrigin(String),
}

impl SessionEndpointUrl {
    /// `https://<host name>`, with `:<port>` unless the port is 443.
    pub fn https(host: &SessionHostName, port: u16) -> Self {
        if port == HTTPS_PORT {
            Self(format!("https://{host}"))
        } else {
            Self(format!("https://{host}:{port}"))
        }
    }

    /// `http://127.0.0.1:<port>`
    pub fn loopback(port: u16) -> Self {
        Self(format!("http://{}:{port}", Ipv4Addr::LOCALHOST))
    }

    /// The origin, without a trailing slash.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for SessionEndpointUrl {
    type Err = InvalidSessionEndpointUrl;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let uri =
            parse_origin(s).ok_or_else(|| InvalidSessionEndpointUrl::NotAnOrigin(s.to_owned()))?;
        if uri.scheme() != Some(&Scheme::HTTP) && uri.scheme() != Some(&Scheme::HTTPS) {
            return Err(InvalidSessionEndpointUrl::NotHttp(s.to_owned()));
        }
        let Some(host) = uri.host().filter(|host| !host.is_empty()) else {
            return Err(InvalidSessionEndpointUrl::NoHost(s.to_owned()));
        };
        let is_loopback = host == Ipv4Addr::LOCALHOST.to_string();
        if uri.scheme() == Some(&Scheme::HTTP) && !is_loopback {
            return Err(InvalidSessionEndpointUrl::PlainHttp(s.to_owned()));
        }
        Ok(Self(s.trim_end_matches('/').to_owned()))
    }
}

impl fmt::Display for SessionEndpointUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Everything a client needs to reach one endpoint session.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionGrant {
    /// Keep it to attach again.
    pub session_id: SessionId,
    /// The parallel run's name, for a session in one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_name: Option<SessionName>,
    /// Quote it when reporting a problem.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
    /// The name can take a few seconds to resolve after the grant; retry a failed lookup.
    pub endpoint: SessionEndpointUrl,
    /// Admits the client to [`Self::endpoint`].
    pub token: SessionToken,
    /// The slots the session replays.
    pub slots: SlotRange,
}

impl SessionGrant {
    /// `ws(s)://<host>/backtest/<its own id>/control`: the session's control socket.
    pub fn control_url(&self) -> String {
        let after_http = self
            .endpoint
            .as_str()
            .strip_prefix(Scheme::HTTP.as_str())
            .unwrap_or_else(|| unreachable!("an endpoint URL is an http or https origin"));
        format!("ws{after_http}/backtest/{}/control", self.session_id)
    }

    /// The session's JSON-RPC endpoint over HTTP, without the token.
    pub fn rpc_url(&self) -> String {
        format!("{}/backtest/{}", self.endpoint, self.session_id)
    }

    /// [`Self::rpc_url`] with the token in the query, for a client that cannot set a header.
    pub fn rpc_url_with_token(&self) -> String {
        format!(
            "{}?{SESSION_TOKEN_QUERY_PARAM}={}",
            self.rpc_url(),
            self.token.expose()
        )
    }
}

/// Every session of a parallel run, as [`SessionGrant`]s.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ParallelGrant {
    /// Keep it to attach again.
    pub control_session_id: ControlSessionId,
    /// The parallel run's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub control_session_name: Option<SessionName>,
    /// In slot order; never empty.
    pub sessions: Vec<SessionGrant>,
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    const PRODUCTION: &str = "sessions.simulator.termina.technology";
    const STAGING: &str = "sessions.staging.simulator.termina.technology";
    const LABEL: &str = "3f9a2c1b4d5e6f708192a3b4c5d6e7f8";

    #[test]
    fn the_example_host_name_round_trips() {
        let text = format!("{LABEL}.{PRODUCTION}");
        let name: SessionHostName = text.parse().expect("parse");
        assert_eq!(name.to_string(), text);
        assert_eq!(name.domain().as_str(), PRODUCTION);
        assert_eq!(
            SessionHostName::new(name.session_id(), PRODUCTION.parse().expect("domain")),
            name
        );
    }

    #[rstest]
    #[case::hyphenated_uuid(
        "3f9a2c1b-4d5e-6f70-8192-a3b4c5d6e7f8.sessions.simulator.termina.technology"
    )]
    #[case::uppercase_label(
        "3F9A2C1B4D5E6F708192A3B4C5D6E7F8.sessions.simulator.termina.technology"
    )]
    #[case::label_31("3f9a2c1b4d5e6f708192a3b4c5d6e7f.sessions.simulator.termina.technology")]
    #[case::label_33("3f9a2c1b4d5e6f708192a3b4c5d6e7f88.sessions.simulator.termina.technology")]
    #[case::prefixed_label(
        "backtest_3f9a2c1b4d5e6f708192a3b4c5d6e7f8.sessions.simulator.termina.technology"
    )]
    #[case::no_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8")]
    #[case::empty_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.")]
    #[case::one_label_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.sessions")]
    #[case::uppercase_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.Sessions.Termina.Technology")]
    fn host_name_rejects(#[case] text: &str) {
        assert!(text.parse::<SessionHostName>().is_err());
    }

    #[rstest]
    #[case::production(PRODUCTION)]
    #[case::staging(STAGING)]
    fn domain_accepts(#[case] text: &str) {
        assert_eq!(
            text.parse::<SessionsDomain>().expect("parse").as_str(),
            text
        );
    }

    #[rstest]
    #[case::uppercase("Sessions.simulator.termina.technology")]
    #[case::leading_dot(".sessions.simulator.termina.technology")]
    #[case::trailing_dot("sessions.simulator.termina.technology.")]
    #[case::one_label("sessions")]
    #[case::empty("")]
    #[case::empty_label("sessions..termina.technology")]
    #[case::label_starts_with_hyphen("-sessions.termina.technology")]
    #[case::label_ends_with_hyphen("sessions-.termina.technology")]
    #[case::label_too_long(&format!("{}.termina.technology", "a".repeat(64)))]
    #[case::name_too_long(&["a".repeat(63).as_str(); 4].join("."))]
    fn domain_rejects(#[case] text: &str) {
        assert!(text.parse::<SessionsDomain>().is_err());
    }

    #[test]
    fn token_debug_hides_the_secret() {
        let token = SessionToken::generate();
        assert!(!format!("{token:?}").contains(token.expose()));
    }

    #[test]
    fn tokens_are_distinct_43_char_base64url() {
        let (a, b) = (SessionToken::generate(), SessionToken::generate());
        assert_ne!(a.expose(), b.expose());
        assert_eq!(a.expose().len(), 43);
        assert!(
            a.expose()
                .bytes()
                .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
        );
    }

    #[rstest]
    #[case::default_port(443, format!("https://{LABEL}.{PRODUCTION}"))]
    #[case::other_port(8443, format!("https://{LABEL}.{PRODUCTION}:8443"))]
    fn https_url_names_the_port_unless_it_is_443(#[case] port: u16, #[case] expected: String) {
        let host: SessionHostName = format!("{LABEL}.{PRODUCTION}").parse().expect("host");
        assert_eq!(SessionEndpointUrl::https(&host, port).as_str(), expected);
    }

    #[test]
    fn loopback_url_is_plain_http_on_127_0_0_1() {
        assert_eq!(
            SessionEndpointUrl::loopback(8899).as_str(),
            "http://127.0.0.1:8899"
        );
    }

    #[rstest]
    #[case::https_without_port(&format!("https://{LABEL}.{PRODUCTION}"))]
    #[case::https_with_port(&format!("https://{LABEL}.{PRODUCTION}:8443"))]
    #[case::loopback("http://127.0.0.1:8899")]
    fn endpoint_url_parse_accepts_an_origin(#[case] text: &str) {
        assert_eq!(
            text.parse::<SessionEndpointUrl>().expect("parse").as_str(),
            text
        );
    }

    #[rstest]
    #[case::path("https://example.com/backtest")]
    #[case::query("https://example.com?token=a")]
    #[case::no_scheme("example.com")]
    fn endpoint_url_parse_rejects_a_path_or_query(#[case] text: &str) {
        assert!(matches!(
            text.parse::<SessionEndpointUrl>(),
            Err(InvalidSessionEndpointUrl::NotAnOrigin(_))
        ));
    }

    #[rstest]
    #[case::named_host("http://example.com")]
    #[case::other_address("http://10.0.0.1:8899")]
    #[case::localhost_name("http://localhost:8899")]
    fn endpoint_url_parse_rejects_plain_http_off_loopback(#[case] text: &str) {
        assert!(matches!(
            text.parse::<SessionEndpointUrl>(),
            Err(InvalidSessionEndpointUrl::PlainHttp(_))
        ));
    }

    #[rstest]
    #[case::ws_scheme("ws://example.com")]
    fn endpoint_url_parse_rejects_a_non_http_scheme(#[case] text: &str) {
        assert!(matches!(
            text.parse::<SessionEndpointUrl>(),
            Err(InvalidSessionEndpointUrl::NotHttp(_))
        ));
    }

    #[rstest]
    #[case::loopback(SessionEndpointUrl::loopback(8899), "ws://127.0.0.1:8899")]
    #[case::https(
        SessionEndpointUrl::https(&format!("{LABEL}.{PRODUCTION}").parse().expect("host"), 443),
        &format!("wss://{LABEL}.{PRODUCTION}"),
    )]
    fn control_url_is_the_websocket_origin_and_the_control_path(
        #[case] endpoint: SessionEndpointUrl,
        #[case] origin: &str,
    ) {
        let session_id = SessionId::new();
        let grant = SessionGrant {
            session_id,
            session_name: None,
            task_id: None,
            endpoint,
            token: SessionToken::generate(),
            slots: SlotRange::new_unchecked(1, 2),
        };
        assert_eq!(
            grant.control_url(),
            format!("{origin}/backtest/{session_id}/control")
        );
    }

    #[rstest]
    #[case::loopback(SessionEndpointUrl::loopback(8899), "http://127.0.0.1:8899")]
    #[case::https(
        SessionEndpointUrl::https(&format!("{LABEL}.{PRODUCTION}").parse().expect("host"), 443),
        &format!("https://{LABEL}.{PRODUCTION}"),
    )]
    fn rpc_url_is_the_origin_and_the_session_path(
        #[case] endpoint: SessionEndpointUrl,
        #[case] origin: &str,
    ) {
        let session_id = SessionId::new();
        let token = SessionToken::generate();
        let grant = SessionGrant {
            session_id,
            session_name: None,
            task_id: None,
            endpoint,
            token: token.clone(),
            slots: SlotRange::new_unchecked(1, 2),
        };
        let rpc_url = format!("{origin}/backtest/{session_id}");
        assert_eq!(grant.rpc_url(), rpc_url);

        let with_token = grant.rpc_url_with_token();
        let query = with_token
            .strip_prefix(&format!("{rpc_url}?"))
            .expect("the token URL extends the RPC URL with a query");
        assert_eq!(token_in_query_pair(query), Some(token.expose()));
    }

    #[test]
    fn wildcard_prefixes_the_domain() {
        let domain: SessionsDomain = PRODUCTION.parse().expect("parse");
        assert_eq!(domain.wildcard(), "*.sessions.simulator.termina.technology");
    }

    #[test]
    fn both_types_serialize_as_plain_strings() {
        let domain: SessionsDomain = PRODUCTION.parse().expect("domain");
        let json = serde_json::to_string(&domain).expect("serialize");
        assert_eq!(json, format!("\"{PRODUCTION}\""));
        assert_eq!(
            serde_json::from_str::<SessionsDomain>(&json).expect("deserialize"),
            domain
        );

        let name = SessionHostName::new(SessionId::new(), domain);
        let json = serde_json::to_string(&name).expect("serialize");
        assert_eq!(json, format!("\"{name}\""));
        assert_eq!(
            serde_json::from_str::<SessionHostName>(&json).expect("deserialize"),
            name
        );
    }
}