simulator-client 0.30.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
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
use std::{
    ops::ControlFlow,
    time::{Duration, Instant},
};

use futures::StreamExt;
use simulator_api::{
    BacktestError, BacktestRequest, BacktestResponse, BacktestStatus, ContinueParams,
    ContinueToParams, DiscoveryBatchEvent, PausedEvent, SequencedResponse, SessionId,
    SessionSummary, session_endpoint::SessionGrant,
};
use tokio::{
    sync::{mpsc, oneshot, watch},
    task::JoinHandle,
};
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};

use super::{
    CONNECT_TIMEOUT, ConnectionFailure, ConnectionStatus, CreateError, HANDSHAKE_RESPONSE_TIMEOUT,
    InboundFrame, KEEPALIVE_INTERVAL, ManagedSessionError, MessageLoopExit, RECONNECT_UPTIME_RESET,
    ReconnectBudget, Ws, cancellable_sleep, classify_inbound, graceful_close,
    grant::{Liveness, LivenessCheck},
    managed_user_agent, publish_status, send_keepalive_ping, send_request,
};
use crate::{
    endpoint::{ControlConnectError, FirstConnect, connect_control},
    error::err_chain,
};

/// An event from the session control channel. Responses to reattach and close never arrive here.
#[derive(Debug)]
pub enum ControlEvent {
    /// The session is waiting for your next continue.
    ReadyForContinue,
    /// Server paused at a `ContinueTo` target. The session is ready for
    /// another `Continue` or `ContinueTo` from this point.
    Paused(PausedEvent),
    /// Server discovered an upcoming batch matching a registered
    /// `DiscoveryFilter`. Send `ContinueTo(slot, batch_index)` to pause
    /// immediately before it executes.
    DiscoveryBatch(DiscoveryBatchEvent),
    /// The slot that just executed.
    Slot(u64),
    /// A progress update, while the session starts (e.g. `StartingRuntime`) and during each
    /// continue.
    Status(BacktestStatus),
    /// The session replayed its last slot.
    Completed {
        /// `None` unless the session was created with `send_summary`.
        summary: Option<SessionSummary>,
    },
    /// The server reported an error. Per-transaction `SimulationError`s are logged instead.
    Error(BacktestError),
}

/// Handle to a running `ControlManager` task.
pub(super) struct ControlHandle {
    continues: mpsc::Sender<ContinueParams>,
    continue_tos: mpsc::Sender<ContinueToParams>,
    pub events: mpsc::Receiver<ControlEvent>,
    pub status: watch::Receiver<ConnectionStatus>,
    attached: Option<oneshot::Receiver<Result<(), ManagedSessionError>>>,
    join: JoinHandle<()>,
}

impl ControlHandle {
    pub async fn wait_attached(&mut self) -> Result<(), ManagedSessionError> {
        let rx = self
            .attached
            .take()
            .ok_or(ManagedSessionError::ControlClosed)?;
        rx.await.map_err(|_| ManagedSessionError::ControlClosed)?
    }

    /// Send a `Continue` request to the control task. Errors if the task has
    /// exited.
    pub async fn send_continue(
        &self,
        params: ContinueParams,
    ) -> Result<(), mpsc::error::SendError<ContinueParams>> {
        self.continues.send(params).await
    }

    /// Send a `ContinueTo` request to step to a specific slot/batch boundary.
    /// Pair with `ControlEvent::DiscoveryBatch` to pause before each
    /// discovered batch.
    pub async fn send_continue_to(
        &self,
        params: ContinueToParams,
    ) -> Result<(), mpsc::error::SendError<ContinueToParams>> {
        self.continue_tos.send(params).await
    }

    /// Await the control task's exit. The task exits on its own when the
    /// server reports `Completed`, the cancel token fires, or it hits a
    /// terminal error; dropping the request channels here nudges it in the
    /// case where the driver is giving up without having seen `Completed`,
    /// and dropping the event queue frees it if it is parked delivering an
    /// event nobody will now read.
    pub async fn join(self) {
        drop(self.continues);
        drop(self.continue_tos);
        drop(self.events);
        let _ = self.join.await;
    }
}

pub(super) fn spawn_control_manager(
    grant: SessionGrant,
    check: LivenessCheck,
    cancel: CancellationToken,
) -> ControlHandle {
    let (continues_tx, continues_rx) = mpsc::channel::<ContinueParams>(1);
    let (continue_tos_tx, continue_tos_rx) = mpsc::channel::<ContinueToParams>(1);
    let (events_tx, events_rx) = mpsc::channel::<ControlEvent>(256);
    let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
    let (attached_tx, attached_rx) = oneshot::channel::<Result<(), ManagedSessionError>>();

    let manager = ControlTask {
        grant,
        last_sequence: None,
        continues_rx,
        continue_tos_rx,
        events_tx,
        status_tx,
        cancel,
        check,
    };

    let join = tokio::spawn(manager.run(attached_tx));

    ControlHandle {
        continues: continues_tx,
        continue_tos: continue_tos_tx,
        events: events_rx,
        status: status_rx,
        attached: Some(attached_rx),
        join,
    }
}

enum AttemptError {
    Cancelled,
    Retry(String),
    TokenRejected,
    Fatal(CreateError),
}

struct ControlTask {
    grant: SessionGrant,
    /// Highest sequence number observed from the server.
    last_sequence: Option<u64>,
    continues_rx: mpsc::Receiver<ContinueParams>,
    continue_tos_rx: mpsc::Receiver<ContinueToParams>,
    events_tx: mpsc::Sender<ControlEvent>,
    status_tx: watch::Sender<ConnectionStatus>,
    cancel: CancellationToken,
    check: LivenessCheck,
}

impl ControlTask {
    async fn run(mut self, attached: oneshot::Sender<Result<(), ManagedSessionError>>) {
        let Some(ws) = self.first_attach(attached).await else {
            return;
        };
        info!(session_id = %self.grant.session_id, "control attached to the session");
        self.run_attached(ws).await;
    }

    async fn first_attach(
        &mut self,
        attached: oneshot::Sender<Result<(), ManagedSessionError>>,
    ) -> Option<Ws> {
        let first = FirstConnect::start(tokio::time::Instant::now());
        let error = loop {
            let why = match self.attempt().await {
                Ok(ws) => {
                    let _ = attached.send(Ok(()));
                    return Some(ws);
                }
                Err(AttemptError::Retry(why)) => why,
                Err(AttemptError::Cancelled) => break ManagedSessionError::Cancelled,
                Err(AttemptError::TokenRejected) => {
                    break ManagedSessionError::SessionTokenRejected;
                }
                Err(AttemptError::Fatal(error)) => break ManagedSessionError::Create(error),
            };
            let Some(delay) = first.retry_after(tokio::time::Instant::now()) else {
                break ManagedSessionError::Create(CreateError::EndpointUnreachable {
                    session_id: self.grant.session_id,
                    endpoint: self.grant.endpoint.clone(),
                    reason: why,
                });
            };
            warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control connect failed, retrying");
            cancellable_sleep(delay, &self.cancel).await;
        };
        let _ = attached.send(Err(error));
        None
    }

    async fn run_attached(&mut self, mut ws: Ws) {
        let mut budget = ReconnectBudget::new();
        loop {
            publish_status(&self.status_tx, ConnectionStatus::Up);
            let connected_at = Instant::now();
            let why = match self.message_loop(ws).await {
                MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
                MessageLoopExit::Terminal => {
                    publish_status(&self.status_tx, ConnectionStatus::Ended);
                    return;
                }
                MessageLoopExit::ConnectionLost(why) => format!("connection lost: {why}"),
            };
            if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
                budget.reset();
            }
            let Some(reattached) = self.reattach(&mut budget, why).await else {
                return;
            };
            ws = reattached;
            debug!(session_id = %self.grant.session_id, "control reattached");
        }
    }

    async fn reattach(&mut self, budget: &mut ReconnectBudget, mut why: String) -> Option<Ws> {
        let Some(delay) = budget.next_backoff() else {
            self.fail(ConnectionFailure::RetriesExhausted(why));
            return None;
        };
        warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
        if !cancellable_sleep(delay, &self.cancel).await {
            return None;
        }
        loop {
            match self.attempt().await {
                Ok(ws) => return Some(ws),
                Err(AttemptError::Retry(failed)) => why = format!("connect failed: {failed}"),
                Err(AttemptError::Cancelled) => return None,
                Err(AttemptError::TokenRejected) => {
                    self.fail(ConnectionFailure::TokenRejected);
                    return None;
                }
                Err(AttemptError::Fatal(error)) => {
                    self.fail(ConnectionFailure::Refused(error.to_string()));
                    return None;
                }
            }
            let Some(delay) = budget.next_backoff() else {
                self.fail(ConnectionFailure::RetriesExhausted(why));
                return None;
            };
            warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
            if self.backoff_and_check(delay).await.is_break() {
                return None;
            }
        }
    }

    /// Breaks when the task has stopped: cancelled, or management reported the session gone.
    async fn backoff_and_check(&self, delay: Duration) -> ControlFlow<()> {
        let sleep = tokio::time::sleep(delay);
        let ask = self.check.ask();
        tokio::pin!(sleep, ask);
        let liveness = tokio::select! {
            biased;
            _ = self.cancel.cancelled() => return ControlFlow::Break(()),
            liveness = &mut ask => liveness,
            // Keep waiting for the check, so an `Ended` answer is not lost.
            _ = &mut sleep => tokio::select! {
                biased;
                _ = self.cancel.cancelled() => return ControlFlow::Break(()),
                liveness = &mut ask => liveness,
            },
        };
        match liveness {
            Liveness::Ended => {
                info!(session_id = %self.grant.session_id, "management no longer knows the session");
                self.fail(ConnectionFailure::SessionEnded);
                return ControlFlow::Break(());
            }
            Liveness::Alive => {
                debug!(session_id = %self.grant.session_id, "management still grants the session");
            }
            Liveness::Unknown(unknown) => {
                warn!(session_id = %self.grant.session_id, error = %unknown, "management could not say whether the session runs");
            }
        }
        tokio::select! {
            biased;
            _ = self.cancel.cancelled() => ControlFlow::Break(()),
            _ = &mut sleep => ControlFlow::Continue(()),
        }
    }

    fn fail(&self, failure: ConnectionFailure) {
        publish_status(&self.status_tx, ConnectionStatus::Failed(failure));
    }

    async fn attempt(&mut self) -> Result<Ws, AttemptError> {
        if self.cancel.is_cancelled() {
            return Err(AttemptError::Cancelled);
        }
        publish_status(&self.status_tx, ConnectionStatus::Down);
        let cancel = self.cancel.clone();
        tokio::select! {
            biased;
            _ = cancel.cancelled() => Err(AttemptError::Cancelled),
            attached = self.connect_and_attach() => attached,
        }
    }

    async fn connect_and_attach(&mut self) -> Result<Ws, AttemptError> {
        let mut ws = connect_control(&self.grant, &managed_user_agent(), CONNECT_TIMEOUT)
            .await
            .map_err(|e| match e {
                ControlConnectError::TokenRejected => AttemptError::TokenRejected,
                request @ ControlConnectError::Request(_) => {
                    AttemptError::Fatal(CreateError::Protocol(request.to_string()))
                }
                ControlConnectError::Failed(why) => AttemptError::Retry(why),
            })?;
        attach(&mut ws, self.grant.session_id, self.last_sequence).await?;
        Ok(ws)
    }

    async fn message_loop(&mut self, mut ws: Ws) -> 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();

        let exit = loop {
            tokio::select! {
                biased;
                _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,

                _ = ping_timer.tick() => {
                    if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
                        break MessageLoopExit::ConnectionLost(why);
                    }
                }

                msg = ws.next() => {
                    last_inbound = Instant::now();
                    match classify_inbound(msg) {
                        InboundFrame::Text(t) => {
                            if let Err(exit) = self.handle_text(&t).await {
                                break exit;
                            }
                        }
                        InboundFrame::Ignore => {}
                        InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
                    }
                }

                req = self.continues_rx.recv() => {
                    match req {
                        Some(params) => {
                            if let Err(e) = send_request(&mut ws, &BacktestRequest::Continue(params)).await {
                                break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
                            }
                        }
                        None => break MessageLoopExit::SessionEnded,
                    }
                }

                req = self.continue_tos_rx.recv() => {
                    match req {
                        Some(params) => {
                            if let Err(e) = send_request(&mut ws, &BacktestRequest::ContinueTo(params)).await {
                                break MessageLoopExit::ConnectionLost(format!("continue_to send: {e}"));
                            }
                        }
                        None => break MessageLoopExit::SessionEnded,
                    }
                }
            }
        };

        if matches!(
            exit,
            MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
        ) {
            graceful_close(&mut ws).await;
        }
        exit
    }

    /// Returns `Err(MessageLoopExit)` if the message signals we should exit the loop.
    async fn handle_text(&mut self, text: &str) -> Result<(), MessageLoopExit> {
        let (seq, response) = match serde_json::from_str::<SequencedResponse>(text) {
            Ok(s) => (Some(s.seq_id), s.response),
            Err(_) => match serde_json::from_str::<BacktestResponse>(text) {
                Ok(r) => (None, r),
                Err(e) => {
                    warn!(error = %err_chain(&e), "discarding undeserializable control message");
                    return Ok(());
                }
            },
        };

        if let Some(s) = seq {
            self.last_sequence = Some(s);
        }

        match response {
            BacktestResponse::ReadyForContinue => {
                let _ = self.events_tx.send(ControlEvent::ReadyForContinue).await;
            }
            BacktestResponse::Paused(event) => {
                let _ = self.events_tx.send(ControlEvent::Paused(event)).await;
            }
            BacktestResponse::DiscoveryBatch(event) => {
                let _ = self
                    .events_tx
                    .send(ControlEvent::DiscoveryBatch(event))
                    .await;
            }
            BacktestResponse::SlotNotification(slot) => {
                let _ = self.events_tx.send(ControlEvent::Slot(slot)).await;
            }
            BacktestResponse::Completed { summary } => {
                let _ = self
                    .events_tx
                    .send(ControlEvent::Completed { summary })
                    .await;
                return Err(MessageLoopExit::SessionEnded);
            }
            BacktestResponse::Error(err) => {
                // Per-slot simulation errors are non-fatal: log and keep going.
                if matches!(&err, BacktestError::SimulationError { .. }) {
                    warn!(error = %err_chain(&err), "simulation error");
                    return Ok(());
                }
                let terminal = err.is_terminal();
                let _ = self.events_tx.send(ControlEvent::Error(err)).await;
                if terminal {
                    return Err(MessageLoopExit::Terminal);
                }
            }
            BacktestResponse::Status { status } => {
                let _ = self.events_tx.send(ControlEvent::Status(status)).await;
            }
            BacktestResponse::Success => {
                // Ack for Close or similar; nothing to forward.
            }
            other => {
                // SessionCreated/Attached/etc. during the message loop are unexpected.
                debug!(?other, "ignoring unexpected control response");
            }
        }

        Ok(())
    }
}

/// Sends the attach and reads `sessionAttached` or `error`. Replay follows only after that frame.
async fn attach(
    ws: &mut Ws,
    session_id: SessionId,
    last_sequence: Option<u64>,
) -> Result<(), AttemptError> {
    send_request(
        ws,
        &BacktestRequest::AttachBacktestSession {
            session_id,
            last_sequence,
        },
    )
    .await
    .map_err(AttemptError::Retry)?;

    let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
    let text = loop {
        let frame = tokio::time::timeout_at(deadline, ws.next())
            .await
            .map_err(|_| {
                AttemptError::Retry(format!(
                    "attach timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"
                ))
            })?;
        match classify_inbound(frame) {
            InboundFrame::Text(text) => break text,
            InboundFrame::Ignore => {}
            InboundFrame::Lost(why) => return Err(AttemptError::Retry(why)),
        }
    };
    let response = serde_json::from_str::<BacktestResponse>(&text).map_err(|e| {
        AttemptError::Fatal(CreateError::Protocol(format!(
            "the session answered the attach with a frame this client cannot read: {}",
            err_chain(&e)
        )))
    })?;
    match response {
        BacktestResponse::SessionAttached { .. } => Ok(()),
        BacktestResponse::Error(err) => Err(AttemptError::Fatal(CreateError::Rejected(err))),
        BacktestResponse::Status { .. }
        | BacktestResponse::SessionCreated { .. }
        | BacktestResponse::SessionGranted(_)
        | BacktestResponse::SessionsGranted(_)
        | BacktestResponse::SessionsCreatedV2 { .. }
        | BacktestResponse::ParallelSessionAttachedV2 { .. }
        | BacktestResponse::ReadyForContinue
        | BacktestResponse::SlotNotification(_)
        | BacktestResponse::Paused(_)
        | BacktestResponse::DiscoveryBatch(_)
        | BacktestResponse::Success
        | BacktestResponse::Completed { .. }
        | BacktestResponse::SessionEventV2 { .. } => {
            Err(AttemptError::Fatal(CreateError::Protocol(
                "the session answered the attach with neither sessionAttached nor error".to_owned(),
            )))
        }
    }
}