simulator-client 0.8.0

Async WebSocket client for the Solana simulator backtest 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
//! SubscriptionManager — owns subscription WebSockets and keeps them alive.
//!
//! Two variants:
//! - account-diff subscription (`accountDiffSubscribe`) — account state capture
//! - transaction subscription (`transactionSubscribe`) — full transaction
//!   capture, delivers what `getTransaction` would return in one push so the
//!   client can skip the per-tx fetch entirely
//!
//! Both follow the same reconnect + keepalive pattern. On reconnect, all
//! configured subscriptions are re-established from scratch; we do not attempt
//! to replay notifications missed during the gap.

use std::{collections::HashSet, marker::PhantomData, time::Instant};

use futures::{SinkExt, StreamExt};
use serde::{Deserialize, de::DeserializeOwned};
use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
use tokio::{
    net::TcpStream,
    sync::{mpsc, watch},
    task::JoinHandle,
};
use tokio_tungstenite::{
    MaybeTlsStream, WebSocketStream, connect_async,
    tungstenite::{Message, client::IntoClientRequest},
};
use tokio_util::sync::CancellationToken;
use tracing::{debug, warn};

use super::{
    CONNECT_TIMEOUT, ConnectionStatus, HANDSHAKE_RESPONSE_TIMEOUT, KEEPALIVE_INTERVAL,
    KEEPALIVE_MISS_DEADLINE, RECONNECT_UPTIME_RESET, ReconnectBudget, cancellable_sleep,
};
use crate::{error::err_chain, subscriptions::AccountDiffNotification, urls::http_to_ws_url};

/// Handle to a running subscription manager task.
pub struct SubscriptionHandle {
    pub status: watch::Receiver<ConnectionStatus>,
    pub notifications: mpsc::Receiver<SubscriptionNotification>,
    pub join: JoinHandle<()>,
}

#[derive(Debug)]
pub enum SubscriptionNotification {
    Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
    AccountDiff(AccountDiffNotification),
}

/// Per-flavor differences between `accountDiffSubscribe` and `transactionSubscribe`.
trait SubKind: Send + Sync + 'static {
    type Notification: DeserializeOwned + Send + 'static;
    const LABEL: &'static str;
    const SUBSCRIBE_METHOD: &'static str;
    const NOTIFICATION_METHOD: &'static str;
    fn subscribe_params(program_id: &str) -> serde_json::Value;
    fn into_notification(notification: Self::Notification) -> SubscriptionNotification;
}

struct AccountDiff;
impl SubKind for AccountDiff {
    type Notification = AccountDiffNotification;
    const LABEL: &'static str = "account-diff";
    const SUBSCRIBE_METHOD: &'static str = "accountDiffSubscribe";
    const NOTIFICATION_METHOD: &'static str = "accountDiffNotification";
    fn subscribe_params(program_id: &str) -> serde_json::Value {
        serde_json::json!([program_id, {"address_type": "program"}])
    }
    fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
        SubscriptionNotification::AccountDiff(notification)
    }
}

struct Transaction;
impl SubKind for Transaction {
    /// Wire shape is identical to the `getTransaction` RPC response, so we can
    /// reuse `transaction_from_encoded` to build the output record directly
    /// from the push notification — no follow-up fetch required.
    type Notification = EncodedConfirmedTransactionWithStatusMeta;
    const LABEL: &'static str = "transaction";
    const SUBSCRIBE_METHOD: &'static str = "transactionSubscribe";
    const NOTIFICATION_METHOD: &'static str = "transactionNotification";
    fn subscribe_params(program_id: &str) -> serde_json::Value {
        serde_json::json!([{"mentions": [program_id]}, {"commitment": "confirmed"}])
    }
    fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
        SubscriptionNotification::Transaction(Box::new(notification))
    }
}

pub fn spawn_transaction_subscription_manager(
    rpc_endpoint: String,
    program_ids: Vec<String>,
    cancel: CancellationToken,
) -> SubscriptionHandle {
    spawn_subscription_manager::<Transaction>(rpc_endpoint, program_ids, cancel)
}

pub fn spawn_account_diff_subscription_manager(
    rpc_endpoint: String,
    program_ids: Vec<String>,
    cancel: CancellationToken,
) -> SubscriptionHandle {
    spawn_subscription_manager::<AccountDiff>(rpc_endpoint, program_ids, cancel)
}

fn spawn_subscription_manager<K>(
    rpc_endpoint: String,
    program_ids: Vec<String>,
    cancel: CancellationToken,
) -> SubscriptionHandle
where
    K: SubKind,
{
    let (notifications_tx, notifications_rx) = mpsc::channel(1024);
    let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
    let task = Task::<K> {
        rpc_endpoint,
        program_ids,
        notifications_tx,
        status_tx,
        cancel,
        _marker: PhantomData,
    };
    let join = tokio::spawn(task.run());
    SubscriptionHandle {
        status: status_rx,
        notifications: notifications_rx,
        join,
    }
}

type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
type Subs = HashSet<u64>;

struct Task<K: SubKind> {
    rpc_endpoint: String,
    program_ids: Vec<String>,
    notifications_tx: mpsc::Sender<SubscriptionNotification>,
    status_tx: watch::Sender<ConnectionStatus>,
    /// Session-scoped cancel; fires both on user Ctrl-C *and* on normal
    /// session completion. Stops the connect/message loop either way.
    cancel: CancellationToken,
    _marker: PhantomData<fn() -> K>,
}

impl<K: SubKind> Task<K> {
    async fn run(self) {
        let mut budget = ReconnectBudget::new();

        loop {
            if self.cancel.is_cancelled() {
                break;
            }
            publish(&self.status_tx, ConnectionStatus::Down);

            let connect_result = async {
                let ws = connect_ws(&self.rpc_endpoint).await?;
                subscribe::<K>(ws, &self.program_ids).await
            }
            .await;

            let (ws, subs) = match connect_result {
                Ok(v) => v,
                Err(why) => {
                    if retry_or_fail::<K>(
                        "connect",
                        why,
                        &mut budget,
                        &self.cancel,
                        &self.status_tx,
                    )
                    .await
                    {
                        continue;
                    }
                    break;
                }
            };

            publish(&self.status_tx, ConnectionStatus::Up);
            let connected_at = Instant::now();

            let exit = message_loop::<K>(ws, subs, &self.notifications_tx, &self.cancel).await;

            match exit {
                MessageLoopExit::Cancelled | MessageLoopExit::Completed => break,
                MessageLoopExit::ConnectionLost(why) => {
                    if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
                        budget.reset();
                    }
                    if retry_or_fail::<K>(
                        "connection lost",
                        why,
                        &mut budget,
                        &self.cancel,
                        &self.status_tx,
                    )
                    .await
                    {
                        continue;
                    }
                    break;
                }
            }
        }
    }
}

enum MessageLoopExit {
    Cancelled,
    ConnectionLost(String),
    /// Every subscription on this connection delivered its end-of-stream
    /// terminal. Stop cleanly without reconnecting.
    Completed,
}

async fn message_loop<K: SubKind>(
    mut ws: Ws,
    subs: Subs,
    notifications_tx: &mpsc::Sender<SubscriptionNotification>,
    cancel: &CancellationToken,
) -> MessageLoopExit {
    let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
    ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    let mut last_inbound = Instant::now();
    // Subscriptions whose terminal `subscriptionComplete` marker has arrived.
    // Once this covers every entry in `subs`, the stream is fully drained.
    let mut completed: HashSet<u64> = HashSet::new();

    loop {
        tokio::select! {
            biased;
            _ = cancel.cancelled() => return MessageLoopExit::Cancelled,

            _ = ping_timer.tick() => {
                if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
                    return MessageLoopExit::ConnectionLost(format!(
                        "no traffic for {:?}", last_inbound.elapsed()
                    ));
                }
                if let Err(e) = ws.send(Message::Ping(vec![])).await {
                    return MessageLoopExit::ConnectionLost(format!("ping send: {}", err_chain(&e)));
                }
            }

            msg = ws.next() => {
                last_inbound = Instant::now();
                match msg {
                    Some(Ok(Message::Text(t))) => {
                        match handle_text::<K>(&t, &subs, notifications_tx, &mut completed).await {
                            TextOutcome::Continue => {}
                            TextOutcome::AllComplete => return MessageLoopExit::Completed,
                            TextOutcome::ChannelClosed => return MessageLoopExit::Cancelled,
                        }
                    }
                    Some(Ok(Message::Binary(b))) => {
                        if let Ok(t) = std::str::from_utf8(&b) {
                            match handle_text::<K>(t, &subs, notifications_tx, &mut completed).await {
                                TextOutcome::Continue => {}
                                TextOutcome::AllComplete => return MessageLoopExit::Completed,
                                TextOutcome::ChannelClosed => return MessageLoopExit::Cancelled,
                            }
                        }
                    }
                    Some(Ok(Message::Pong(_))) | Some(Ok(Message::Ping(_))) => {}
                    Some(Ok(Message::Close(frame))) => {
                        return MessageLoopExit::ConnectionLost(format!("remote close: {frame:?}"));
                    }
                    Some(Ok(Message::Frame(_))) => {}
                    Some(Err(e)) => return MessageLoopExit::ConnectionLost(format!("ws read: {}", err_chain(&e))),
                    None => return MessageLoopExit::ConnectionLost("ws stream ended".into()),
                }
            }
        }
    }
}

/// Sleep for the next backoff interval, or publish `Failed` and return false if
/// the retry budget is exhausted. Returns true if the caller should retry.
async fn retry_or_fail<K: SubKind>(
    phase: &'static str,
    reason: String,
    budget: &mut ReconnectBudget,
    cancel: &CancellationToken,
    status_tx: &watch::Sender<ConnectionStatus>,
) -> bool {
    if let Some(delay) = budget.next_backoff() {
        warn!(
            kind = K::LABEL,
            attempt = budget.attempt(),
            reason = %reason,
            ?delay,
            "subscription {phase}, retrying",
        );
        cancellable_sleep(delay, cancel).await
    } else {
        publish(
            status_tx,
            ConnectionStatus::Failed(format!("{phase}: {reason}")),
        );
        false
    }
}

fn publish(tx: &watch::Sender<ConnectionStatus>, status: ConnectionStatus) {
    tx.send_if_modified(|current| {
        if *current == status {
            false
        } else {
            *current = status;
            true
        }
    });
}

async fn connect_ws(rpc_endpoint: &str) -> Result<Ws, String> {
    let ws_url = http_to_ws_url(rpc_endpoint).map_err(|e| err_chain(&e))?;
    let request = ws_url
        .into_client_request()
        .map_err(|e| format!("build request: {}", err_chain(&e)))?;

    let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
        .await
        .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
        .map_err(|e| format!("connect: {}", err_chain(&e)))?;
    Ok(connect.0)
}

async fn subscribe<K: SubKind>(mut ws: Ws, program_ids: &[String]) -> Result<(Ws, Subs), String> {
    let mut subs = Subs::new();
    for (i, program_id) in program_ids.iter().enumerate() {
        let id = (i + 1) as u64;
        let req = serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": K::SUBSCRIBE_METHOD,
            "params": K::subscribe_params(program_id),
        });
        ws.send(Message::Text(req.to_string()))
            .await
            .map_err(|e| format!("subscribe send: {}", err_chain(&e)))?;
        subs.insert(read_sub_ack(&mut ws, id).await?);
    }
    debug!(
        kind = K::LABEL,
        count = subs.len(),
        "subscriptions established"
    );
    Ok((ws, subs))
}

#[derive(Deserialize)]
struct SubAck {
    id: u64,
    result: Option<u64>,
    #[serde(default)]
    error: Option<serde_json::Value>,
}

async fn read_sub_ack(ws: &mut Ws, expected_id: u64) -> Result<u64, String> {
    let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
    loop {
        let msg = tokio::time::timeout_at(deadline, ws.next())
            .await
            .map_err(|_| format!("subscribe ack timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;

        let Some(msg) = msg else {
            return Err("ws ended during subscribe".into());
        };
        let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;

        if let Message::Text(t) = msg
            && let Ok(ack) = serde_json::from_str::<SubAck>(&t)
        {
            if ack.id != expected_id {
                continue;
            }
            if let Some(err) = ack.error {
                return Err(format!("subscribe rejected: {err}"));
            }
            if let Some(sub_id) = ack.result {
                return Ok(sub_id);
            }
            return Err("subscribe ack missing result".into());
        }
    }
}

/// Result of feeding one inbound text frame to the message loop.
enum TextOutcome {
    /// Keep reading (notification handled, or frame ignored).
    Continue,
    /// Every subscription on this connection has delivered its terminal marker.
    AllComplete,
    /// The downstream notifications channel closed — caller is gone.
    ChannelClosed,
}

/// Handle one inbound text frame: forward a matching notification, or record a
/// terminal `subscriptionComplete` marker. Returns [`TextOutcome::AllComplete`]
/// once a terminal has been seen for every subscription in `subs`.
async fn handle_text<K: SubKind>(
    text: &str,
    subs: &Subs,
    notifications_tx: &mpsc::Sender<SubscriptionNotification>,
    completed: &mut HashSet<u64>,
) -> TextOutcome {
    // Try a data notification first — that's the overwhelmingly common frame,
    // so the hot path parses the payload once.
    if let Some(n) = parse_notification::<K>(text, subs) {
        if notifications_tx
            .send(K::into_notification(n))
            .await
            .is_err()
        {
            return TextOutcome::ChannelClosed;
        }
        return TextOutcome::Continue;
    }

    // Otherwise it may be the terminal end-of-stream marker.
    if let Some(sub_id) = parse_completion(text)
        && subs.contains(&sub_id)
    {
        completed.insert(sub_id);
        if subs.iter().all(|id| completed.contains(id)) {
            return TextOutcome::AllComplete;
        }
    }
    TextOutcome::Continue
}

/// Parse a terminal end-of-stream marker, returning the subscription id it
/// targets. Shape: `{"method":"subscriptionComplete","params":{"subscription":N}}`.
fn parse_completion(text: &str) -> Option<u64> {
    #[derive(Deserialize)]
    struct Msg {
        method: String,
        params: Params,
    }
    #[derive(Deserialize)]
    struct Params {
        subscription: u64,
    }

    let msg: Msg = serde_json::from_str(text).ok()?;
    (msg.method == "subscriptionComplete").then_some(msg.params.subscription)
}

fn parse_notification<K: SubKind>(text: &str, subs: &Subs) -> Option<K::Notification> {
    #[derive(Deserialize)]
    #[serde(bound = "T: DeserializeOwned")]
    struct Msg<T> {
        method: String,
        params: Params<T>,
    }
    #[derive(Deserialize)]
    #[serde(bound = "T: DeserializeOwned")]
    struct Params<T> {
        subscription: u64,
        result: T,
    }

    let msg: Msg<K::Notification> = serde_json::from_str(text).ok()?;
    if msg.method != K::NOTIFICATION_METHOD {
        return None;
    }
    if !subs.contains(&msg.params.subscription) {
        return None;
    }
    Some(msg.params.result)
}

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

    #[test]
    fn parse_completion_extracts_subscription_id() {
        let text =
            r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7}}"#;
        assert_eq!(parse_completion(text), Some(7));
    }

    #[test]
    fn parse_completion_ignores_other_messages() {
        let notification = r#"{"jsonrpc":"2.0","method":"transactionNotification","params":{"subscription":7,"result":{}}}"#;
        assert_eq!(parse_completion(notification), None);
        assert_eq!(parse_completion("not json"), None);
    }
}