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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
use std::{
borrow::Cow,
collections::{BTreeMap, VecDeque},
future::Future,
time::Duration,
};
use futures::{SinkExt, StreamExt, stream};
use simulator_api::{
AccountData, AccountModifications, BacktestError, BacktestRequest, BacktestResponse,
BacktestStatus, ContinueParams, SequencedResponse, SessionId, SessionSummary,
session_endpoint::SessionGrant,
};
use solana_address::Address;
use solana_client::{
nonblocking::rpc_client::RpcClient,
rpc_response::{Response, RpcLogsResponse},
};
use solana_commitment_config::CommitmentConfig;
use thiserror::Error;
use tokio::net::TcpStream;
use tokio_tungstenite::{
MaybeTlsStream, WebSocketStream,
tungstenite::{
Error as WsError, Message,
error::ProtocolError,
protocol::{CloseFrame, frame::coding::CloseCode},
},
};
use crate::{
BacktestClientError, BacktestClientResult, Continue,
endpoint::{self, without_query},
error::err_chain,
injection::ProgramModError,
managed::CreateError,
subscriptions::{
AccountDiffNotification, AccountDiffSubscriptionHandle, LogSubscriptionHandle,
SubscriptionError,
},
};
/// Outcome of waiting for readiness on a session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadyOutcome {
/// The session is ready to accept a `Continue` request.
Ready,
/// The session completed before becoming ready.
Completed,
}
impl ReadyOutcome {
/// Whether the session completed rather than becoming ready.
pub fn is_completed(&self) -> bool {
matches!(self, Self::Completed)
}
}
/// Summary of responses collected while advancing a backtest.
#[derive(Debug, Default)]
pub struct ContinueResult {
/// Number of slot notifications observed.
pub slot_notifications: u64,
/// Last slot received via notification.
pub last_slot: Option<u64>,
/// Status messages received.
pub statuses: Vec<BacktestStatus>,
/// Whether the session became ready for the next `Continue`.
pub ready_for_continue: bool,
/// Whether the session completed while advancing.
pub completed: bool,
}
/// Mutable state for driving a session one response at a time with
/// [`BacktestSession::advance_step`]. [`BacktestSession::advance`] uses it for you.
#[derive(Debug)]
pub struct AdvanceState {
/// Expected number of slot notifications for this step.
pub expected_slots: u64,
/// Count of slot notifications received so far.
pub slot_notifications: u64,
/// Most recent slot notification.
pub last_slot: Option<u64>,
/// Status messages received so far.
pub statuses: Vec<BacktestStatus>,
/// Whether the session is ready for another `Continue`.
pub ready_for_continue: bool,
/// Whether the session completed while advancing.
pub completed: bool,
/// Session summary received on completion (if send_summary was enabled).
pub summary: Option<SessionSummary>,
}
impl AdvanceState {
/// Create new tracking state for a step that expects `expected_slots` notifications.
pub fn new(expected_slots: u64) -> Self {
Self {
expected_slots,
slot_notifications: 0,
last_slot: None,
statuses: Vec::new(),
ready_for_continue: false,
completed: false,
summary: None,
}
}
/// Return true when the step is complete based on readiness and slot count.
pub fn is_done(&self, wait_for_slots: bool) -> bool {
if self.completed {
return true;
}
if !self.ready_for_continue {
return false;
}
!wait_for_slots || self.slot_notifications >= self.expected_slots
}
}
/// Coverage of a session's observed slot notifications and completion state.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SessionCoverage {
completed: bool,
highest_slot_seen: Option<u64>,
}
impl SessionCoverage {
/// Record a slot notification.
pub fn observe_slot(&mut self, slot: u64) {
self.highest_slot_seen = Some(
self.highest_slot_seen
.map_or(slot, |current| current.max(slot)),
);
}
/// Mark the session as completed.
pub fn mark_completed(&mut self) {
self.completed = true;
}
/// Update coverage state from a backtest response.
pub fn observe_response(&mut self, response: &BacktestResponse) {
match response {
BacktestResponse::SlotNotification(slot) => self.observe_slot(*slot),
BacktestResponse::Completed { .. } => self.mark_completed(),
_ => {}
}
}
/// Return whether completion has been observed.
pub fn is_completed(&self) -> bool {
self.completed
}
/// Return the highest slot observed via slot notifications.
pub fn highest_slot_seen(&self) -> Option<u64> {
self.highest_slot_seen
}
/// Validate that the session covered the range ending at `expected_end_slot`.
///
/// Completion is the server's own assertion that it replayed every block in
/// the range, so it is what carries coverage; observed slots cannot add to
/// it, since a skipped tail leaves them below `expected_end_slot` on a
/// complete run. They can still contradict it: a slot past the range
/// belongs to another session, so these events were misrouted.
pub fn validate_end_slot(&self, expected_end_slot: u64) -> Result<(), CoverageError> {
if !self.completed {
return Err(CoverageError::NotCompleted);
}
let Some(actual_end_slot) = self.highest_slot_seen else {
return Err(CoverageError::NoSlotsObserved);
};
if actual_end_slot > expected_end_slot {
return Err(CoverageError::RangeOverrun {
actual_end_slot,
expected_end_slot,
});
}
Ok(())
}
}
/// Coverage validation failures for a session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum CoverageError {
/// The session ended without `completed`, so it may not have replayed the whole range.
#[error("ended before completion")]
NotCompleted,
/// The session completed without a single slot notification.
#[error("completed without slot notifications")]
NoSlotsObserved,
/// A slot notification came from past the range's end, so another session's events reached
/// this one.
#[error("observed slot {actual_end_slot} beyond the requested end slot {expected_end_slot}")]
RangeOverrun {
/// The highest slot observed.
actual_end_slot: u64,
/// The range's last slot.
expected_end_slot: u64,
},
}
/// One session, driven over its session control channel.
///
/// Dropping the session sends a best-effort close frame but does not end the session on the
/// server; call [`Self::close`] for that.
///
/// The connection never reconnects. A close leaves the session running until its
/// `disconnect_timeout_secs` elapses; reclaim it with [`crate::BacktestClient::attach_session`]
/// or use [`crate::ManagedBacktestSession`].
///
/// # Timeouts
///
/// A `timeout: Option<Duration>` applies to each send and each receive, not the whole call.
/// `None` falls back to the client's `request_timeout`, then waits indefinitely. Expiry is
/// [`BacktestClientError::Timeout`].
pub struct BacktestSession {
ws: Option<WebSocketStream<MaybeTlsStream<TcpStream>>>,
grant: SessionGrant,
rpc_endpoint: String,
rpc: RpcClient,
last_sequence: Option<u64>,
pub(crate) ready_for_continue: bool,
request_timeout: Option<Duration>,
log_raw: bool,
backlog: VecDeque<(Option<u64>, BacktestResponse)>,
}
impl BacktestSession {
pub(crate) async fn attached(
ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
grant: SessionGrant,
last_sequence: Option<u64>,
request_timeout: Option<Duration>,
log_raw: bool,
) -> BacktestClientResult<Self> {
let rpc = endpoint::rpc_client(&grant, CommitmentConfig::confirmed())
.map_err(|error| CreateError::Protocol(err_chain(&error)))?;
let mut session = Self {
ws: Some(ws),
rpc,
rpc_endpoint: grant.rpc_url_with_token(),
grant,
last_sequence,
ready_for_continue: false,
request_timeout,
log_raw,
backlog: VecDeque::new(),
};
session.attach(last_sequence).await?;
Ok(session)
}
/// The session id.
pub fn session_id(&self) -> Option<SessionId> {
Some(self.grant.session_id)
}
/// Return the session's name, if the server reported one.
pub fn session_name(&self) -> Option<&str> {
self.grant.session_name.as_ref().map(|name| name.as_str())
}
/// The session's RPC endpoint URL.
pub fn rpc_endpoint(&self) -> Option<&str> {
Some(&self.rpc_endpoint)
}
/// Return the opaque `task_id` reported by the server for this session,
/// if any.
pub fn task_id(&self) -> Option<&str> {
self.grant.task_id.as_deref()
}
/// Keep `grant().session_id` to attach from a new process.
pub fn grant(&self) -> &SessionGrant {
&self.grant
}
/// Return the sequence number of the last sequenced response received so far. Pass it to
/// [`crate::BacktestClient::attach_session`] when you reattach.
pub fn last_sequence(&self) -> Option<u64> {
self.last_sequence
}
/// Return the RPC client for this session's endpoint.
///
/// The client uses `confirmed` commitment.
pub fn rpc(&self) -> &RpcClient {
&self.rpc
}
/// Return whether the session is currently ready to accept `Continue`.
pub fn is_ready_for_continue(&self) -> bool {
self.ready_for_continue
}
/// Update readiness from a response you read yourself. [`Self::next_event`] and
/// [`Self::responses`] call this for you.
pub fn apply_response(&mut self, response: &BacktestResponse) {
match response {
BacktestResponse::ReadyForContinue | BacktestResponse::Paused(_) => {
self.ready_for_continue = true;
}
BacktestResponse::Completed { .. } => {
self.ready_for_continue = false;
}
_ => {}
}
}
fn ws_mut(&mut self) -> BacktestClientResult<&mut WebSocketStream<MaybeTlsStream<TcpStream>>> {
self.ws.as_mut().ok_or_else(|| BacktestClientError::Closed {
reason: "websocket closed".to_string(),
})
}
async fn attach(&mut self, last_sequence: Option<u64>) -> BacktestClientResult<()> {
self.send(
&BacktestRequest::AttachBacktestSession {
session_id: self.grant.session_id,
last_sequence,
},
None,
)
.await?;
let response =
self.next_response(None)
.await?
.ok_or_else(|| BacktestClientError::Closed {
reason: "websocket ended before SessionAttached".to_string(),
})?;
match response {
BacktestResponse::SessionAttached { .. } => Ok(()),
BacktestResponse::Error(err) => Err(BacktestClientError::Remote(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(BacktestClientError::UnexpectedResponse {
context: "attaching to the session",
response: Box::new(response),
})
}
}
}
/// Send a raw request over the session control channel. Prefer the typed methods; this
/// does not track readiness.
pub async fn send(
&mut self,
request: &BacktestRequest,
timeout: Option<Duration>,
) -> BacktestClientResult<()> {
let text = serde_json::to_string(request)
.map_err(|source| BacktestClientError::SerializeRequest { source })?;
let request_timeout = self.request_timeout;
let timeout = timeout.or(request_timeout);
let send_fut = self.ws_mut()?.send(Message::Text(text));
let send_result = match timeout {
Some(duration) => tokio::time::timeout(duration, send_fut)
.await
.map_err(|_| BacktestClientError::Timeout {
action: "sending",
duration,
})?,
None => send_fut.await,
};
send_result.map_err(|source| BacktestClientError::WebSocket {
action: "sending",
source: Box::new(source),
})?;
Ok(())
}
/// Receive the next response, without updating readiness; see [`Self::next_event`].
///
/// Returns `Ok(None)` when the connection ends without a close frame. A close frame is
/// [`BacktestClientError::Closed`].
pub async fn next_response(
&mut self,
timeout: Option<Duration>,
) -> BacktestClientResult<Option<BacktestResponse>> {
if let Some((sequence, response)) = self.backlog.pop_front() {
self.last_sequence = sequence.or(self.last_sequence);
return Ok(Some(response));
}
let text = match self.next_text(timeout).await? {
Some(text) => text,
None => return Ok(None),
};
let (sequence, response) = match serde_json::from_str::<SequencedResponse>(&text) {
Ok(sequenced) => (Some(sequenced.seq_id), sequenced.response),
Err(_) => {
let response =
serde_json::from_str::<BacktestResponse>(&text).map_err(|source| {
BacktestClientError::DeserializeResponse {
raw: text.clone(),
source,
}
})?;
(None, response)
}
};
self.last_sequence = sequence.or(self.last_sequence);
Ok(Some(response))
}
/// Receive the next response and update readiness state. Returns `Ok(None)` when the
/// connection ends without a close frame.
pub async fn next_event(
&mut self,
timeout: Option<Duration>,
) -> BacktestClientResult<Option<BacktestResponse>> {
let response = self.next_response(timeout).await?;
if let Some(ref response) = response {
self.apply_response(response);
}
Ok(response)
}
/// Stream responses, updating readiness state as items arrive.
///
/// This consumes the session and yields responses until the connection ends. The stream
/// ends after the first error.
pub fn responses(
self,
timeout: Option<Duration>,
) -> impl futures::Stream<Item = BacktestClientResult<BacktestResponse>> {
stream::unfold(Some(self), move |state| async move {
let mut session = match state {
Some(session) => session,
None => return None,
};
match session.next_response(timeout).await {
Ok(Some(response)) => {
session.apply_response(&response);
Some((Ok(response), Some(session)))
}
Ok(None) => None,
Err(err) => Some((Err(err), None)),
}
})
}
/// Wait for the session to become ready for a `continue`, or to complete. Responses read
/// on the way are discarded.
///
/// # Errors
///
/// [`BacktestClientError::Remote`] on any error response, and
/// [`BacktestClientError::Closed`] if the connection ends first.
pub async fn ensure_ready(
&mut self,
timeout: Option<Duration>,
) -> BacktestClientResult<ReadyOutcome> {
if self.ready_for_continue {
return Ok(ReadyOutcome::Ready);
}
loop {
let response =
self.next_response(timeout)
.await?
.ok_or_else(|| BacktestClientError::Closed {
reason: "websocket ended while waiting for ReadyForContinue".to_string(),
})?;
match response {
BacktestResponse::ReadyForContinue => {
self.ready_for_continue = true;
return Ok(ReadyOutcome::Ready);
}
BacktestResponse::Completed { .. } => return Ok(ReadyOutcome::Completed),
BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
_ => {}
}
}
}
/// Wait for a status of the same variant as `desired`; responses read on the way are
/// discarded.
///
/// # Errors
///
/// [`BacktestClientError::UnexpectedResponse`] if the session completes first,
/// [`BacktestClientError::Remote`] on any error response, and
/// [`BacktestClientError::Closed`] if the connection ends first.
pub async fn wait_for_status(
&mut self,
desired: BacktestStatus,
timeout: Option<Duration>,
) -> BacktestClientResult<()> {
let desired = std::mem::discriminant(&desired);
loop {
let response =
self.next_response(timeout)
.await?
.ok_or_else(|| BacktestClientError::Closed {
reason: "websocket ended while waiting for status".to_string(),
})?;
match response {
BacktestResponse::Status { status }
if std::mem::discriminant(&status) == desired =>
{
return Ok(());
}
BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
BacktestResponse::Completed { summary } => {
return Err(BacktestClientError::UnexpectedResponse {
context: "waiting for status",
response: Box::new(BacktestResponse::Completed { summary }),
});
}
_ => {}
}
}
}
/// Push a response onto the end of the receive backlog.
pub(crate) fn push_backlog(&mut self, response: BacktestResponse) {
self.backlog.push_back((None, response));
}
/// Send a `continue` without waiting for its responses, and reset readiness. Read them
/// with [`Self::advance_step`] or [`Self::next_event`].
pub async fn send_continue(
&mut self,
params: ContinueParams,
timeout: Option<Duration>,
) -> BacktestClientResult<()> {
self.ready_for_continue = false;
self.send(&BacktestRequest::Continue(params), timeout).await
}
/// Read one response of a step started with [`Self::send_continue`] and record it in
/// `state`, calling `on_event` with it first. Loop until [`AdvanceState::is_done`].
///
/// A `SimulationError` is logged and skipped: the session keeps running.
///
/// # Errors
///
/// - [`BacktestClientError::Remote`] on any other error response.
/// - [`BacktestClientError::UnexpectedResponse`] on a response that has no place in a
/// step, such as `paused` or `discoveryBatch`: use
/// [`Self::advance_to_discovery`] for a session with discovery filters.
/// - [`BacktestClientError::Closed`] if the connection ends first.
pub async fn advance_step<F>(
&mut self,
state: &mut AdvanceState,
wait_for_slots: bool,
timeout: Option<Duration>,
on_event: &mut F,
) -> BacktestClientResult<()>
where
F: FnMut(&BacktestResponse),
{
let Some(response) = self.next_response(timeout).await? else {
return Err(BacktestClientError::Closed {
reason: "websocket ended while awaiting continue responses".to_string(),
});
};
if self.log_raw {
tracing::debug!("<- {response:?}");
}
on_event(&response);
match response {
BacktestResponse::ReadyForContinue => {
self.ready_for_continue = true;
state.ready_for_continue = true;
}
BacktestResponse::SlotNotification(slot) => {
state.slot_notifications += 1;
state.last_slot = Some(slot);
}
BacktestResponse::Status { status } => {
state.statuses.push(status);
}
BacktestResponse::Success => {}
BacktestResponse::Completed { summary } => {
state.completed = true;
state.summary = summary;
}
BacktestResponse::Error(err @ BacktestError::SimulationError { .. }) => {
tracing::warn!(error = %crate::error::err_chain(&err), "simulation error");
}
BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
BacktestResponse::SessionCreated { .. }
| BacktestResponse::SessionAttached { .. }
| BacktestResponse::SessionsCreatedV2 { .. }
| BacktestResponse::ParallelSessionAttachedV2 { .. }
| BacktestResponse::SessionEventV2 { .. }
| BacktestResponse::SessionGranted(_)
| BacktestResponse::SessionsGranted(_)
| BacktestResponse::Paused(_)
| BacktestResponse::DiscoveryBatch(_) => {
return Err(BacktestClientError::UnexpectedResponse {
context: "continuing",
response: Box::new(response),
});
}
}
if wait_for_slots && state.slot_notifications > state.expected_slots {
tracing::warn!(
"received {} slot notifications (expected {})",
state.slot_notifications,
state.expected_slots
);
}
Ok(())
}
/// Send `cont` and read responses until the session is ready for another `continue`, or
/// completes. `on_event` sees every response.
///
/// Unlike [`Self::advance`], this returns as soon as the session is ready, without
/// counting slot notifications.
///
/// # Errors
///
/// As [`Self::advance_step`].
pub async fn continue_until_ready<F>(
&mut self,
cont: Continue,
timeout: Option<Duration>,
mut on_event: F,
) -> BacktestClientResult<ContinueResult>
where
F: FnMut(&BacktestResponse),
{
let expected_slots = cont.advance_count;
self.advance_internal(
cont.into_params(),
expected_slots,
false,
timeout,
&mut on_event,
)
.await
}
/// Send `cont` and read responses until the session is ready again and has sent
/// `advance_count` slot notifications, or completes. `on_event` sees every response.
///
/// Use this when the result must count every slot of the step; use
/// [`Self::continue_until_ready`] when you only need the session ready again.
///
/// # Errors
///
/// As [`Self::advance_step`].
pub async fn advance<F>(
&mut self,
cont: Continue,
timeout: Option<Duration>,
mut on_event: F,
) -> BacktestClientResult<ContinueResult>
where
F: FnMut(&BacktestResponse),
{
let expected_slots = cont.advance_count;
self.advance_internal(
cont.into_params(),
expected_slots,
true,
timeout,
&mut on_event,
)
.await
}
async fn advance_internal<F>(
&mut self,
params: ContinueParams,
expected_slots: u64,
wait_for_slots: bool,
timeout: Option<Duration>,
on_event: &mut F,
) -> BacktestClientResult<ContinueResult>
where
F: FnMut(&BacktestResponse),
{
self.send_continue(params, timeout).await?;
let mut state = AdvanceState::new(expected_slots);
while !state.is_done(wait_for_slots) {
self.advance_step(&mut state, wait_for_slots, timeout, on_event)
.await?;
}
Ok(ContinueResult {
slot_notifications: state.slot_notifications,
last_slot: state.last_slot,
statuses: state.statuses,
ready_for_continue: state.ready_for_continue,
completed: state.completed,
})
}
/// Build a program-data account override from raw ELF bytes.
///
/// Derives the `ProgramData` address from `program_id`, queries the session's RPC endpoint
/// for the current slot and rent-exempt minimum, then returns an account-override map ready to
/// pass to [`Continue::builder().modify_accounts(...)`](crate::Continue).
///
/// The deploy slot is set to `current_slot - 1` so the program appears deployed before the
/// next executed slot. RPC failures are retried; see [`crate::injection`].
///
/// # Errors
///
/// [`ProgramModError`]: an invalid `program_id`, or RPC calls that still fail after the
/// retries.
pub async fn modify_program(
&self,
program_id: &str,
elf: &[u8],
) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
crate::injection::modify_program_via_rpc(&self.rpc, program_id, elf).await
}
/// Modify accounts on the session's RPC endpoint via the custom `modifyAccounts` method.
///
/// Returns the number of accounts modified on success.
///
/// # Errors
///
/// As [`crate::rpc::modify_accounts`].
pub async fn modify_accounts(
&self,
modifications: &AccountModifications,
) -> BacktestClientResult<usize> {
crate::rpc::modify_accounts(&self.rpc_endpoint, modifications).await
}
/// Subscribe to program log notifications using the session's RPC endpoint.
pub async fn subscribe_program_logs<F, Fut>(
&self,
program_id: &str,
commitment: CommitmentConfig,
on_notification: F,
) -> Result<LogSubscriptionHandle, SubscriptionError>
where
F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
crate::subscriptions::subscribe_program_logs(
&self.rpc_endpoint,
program_id,
commitment,
on_notification,
)
.await
}
/// Subscribe to account diff notifications using the session's RPC endpoint.
pub async fn subscribe_account_diffs<F, Fut>(
&self,
account: &str,
on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
crate::subscriptions::subscribe_account_diffs(&self.rpc_endpoint, account, on_notification)
.await
}
/// Request server cleanup and close the underlying WebSocket.
///
/// This is idempotent and will return `Ok(())` if the connection is already closed.
///
/// # Errors
///
/// [`BacktestClientError::Remote`] if the server refuses, and
/// [`BacktestClientError::WebSocket`] if the close itself fails.
pub async fn close(&mut self, timeout: Option<Duration>) -> BacktestClientResult<()> {
self.close_with_frame(timeout, None).await
}
/// [`Self::close`], sending `frame` as the WebSocket close frame.
pub async fn close_with_frame(
&mut self,
timeout: Option<Duration>,
frame: Option<CloseFrame<'static>>,
) -> BacktestClientResult<()> {
if self.ws.is_none() {
return Ok(());
}
let mut sent = false;
match self
.send(&BacktestRequest::CloseBacktestSession, timeout)
.await
{
Ok(()) => sent = true,
Err(err) if is_close_ok(&err) => {}
Err(err) => return Err(err),
}
if sent {
let response = match self.next_response(timeout).await {
Ok(Some(r)) => r,
Ok(None) => {
self.ws.take();
return Ok(());
}
Err(BacktestClientError::Closed { .. }) => {
self.ws.take();
return Ok(());
}
Err(BacktestClientError::WebSocket {
action: "receiving",
source,
}) if is_reset_without_close(&source) => {
self.ws.take();
return Ok(());
}
Err(err) => return Err(err),
};
match response {
BacktestResponse::Success | BacktestResponse::Completed { .. } => {}
BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
other => {
return Err(BacktestClientError::UnexpectedResponse {
context: "closing session",
response: Box::new(other),
});
}
}
}
// Flush our close frame and drop; the server never sends a close frame back after CloseBacktestSession.
if let Some(mut ws) = self.ws.take()
&& let Err(source) = ws.close(frame).await
&& !is_ws_closed_error(&source)
{
return Err(BacktestClientError::WebSocket {
action: "closing",
source: Box::new(source),
});
}
Ok(())
}
/// [`Self::close`], sending a close frame with `code` and `reason`.
pub async fn close_with_reason(
&mut self,
timeout: Option<Duration>,
code: CloseCode,
reason: impl Into<String>,
) -> BacktestClientResult<()> {
let frame = CloseFrame {
code,
reason: Cow::Owned(reason.into()),
};
self.close_with_frame(timeout, Some(frame)).await
}
/// Drop the connection without sending `CloseBacktestSession`, so the server
/// reaps the session via its disconnect timeout (the dropped-connection path)
/// rather than the prompt teardown [`close`](Self::close) requests.
///
/// Consumes the session so [`Drop`] can't run its best-effort close: the taken
/// stream is dropped here, closing the socket with a bare FIN.
pub fn abort(mut self) {
let _ws = self.ws.take();
}
async fn next_text(
&mut self,
timeout: Option<Duration>,
) -> BacktestClientResult<Option<String>> {
loop {
let request_timeout = self.request_timeout;
let timeout = timeout.or(request_timeout);
let next_fut = self.ws_mut()?.next();
let msg = match timeout {
Some(duration) => tokio::time::timeout(duration, next_fut)
.await
.map_err(|_| BacktestClientError::Timeout {
action: "receiving",
duration,
})?,
None => next_fut.await,
};
let Some(msg) = msg else {
return Ok(None);
};
let msg = match msg {
Ok(msg) => msg,
Err(source) => {
return Err(BacktestClientError::WebSocket {
action: "receiving",
source: Box::new(source),
});
}
};
match msg {
Message::Text(text) => {
if self.log_raw {
tracing::debug!("<- raw: {text}");
}
return Ok(Some(text));
}
Message::Binary(bin) => match String::from_utf8(bin) {
Ok(text) => {
if self.log_raw {
tracing::debug!("<- raw(bin): {text}");
}
return Ok(Some(text));
}
Err(err) => {
tracing::warn!("discarding non-utf8 binary message: {err}");
continue;
}
},
Message::Close(frame) => {
let reason = close_reason(frame);
return Err(BacktestClientError::Closed { reason });
}
Message::Ping(_) | Message::Pong(_) => continue,
Message::Frame(_) => continue,
}
}
}
}
impl std::fmt::Debug for BacktestSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BacktestSession")
.field("session_id", &self.grant.session_id)
.field("rpc_endpoint", &without_query(&self.rpc_endpoint))
.field("ready_for_continue", &self.ready_for_continue)
.field("request_timeout", &self.request_timeout)
.finish_non_exhaustive()
}
}
impl Drop for BacktestSession {
fn drop(&mut self) {
let Some(ws) = self.ws.take() else {
return;
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
let mut ws = ws;
let _ = ws.close(None).await;
});
}
}
}
fn close_reason(frame: Option<CloseFrame<'static>>) -> String {
match frame {
Some(frame) => format!("{:?}: {}", frame.code, frame.reason),
None => "no close frame".to_string(),
}
}
fn is_reset_without_close(err: &WsError) -> bool {
matches!(
err,
WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
)
}
fn is_ws_closed_error(err: &WsError) -> bool {
matches!(
err,
WsError::ConnectionClosed
| WsError::AlreadyClosed
| WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
)
}
fn is_close_ok(err: &BacktestClientError) -> bool {
match err {
BacktestClientError::Closed { .. } => true,
BacktestClientError::WebSocket { source, .. } => is_ws_closed_error(source),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coverage_tracks_slot_and_completion_from_responses() {
let mut coverage = SessionCoverage::default();
coverage.observe_response(&BacktestResponse::SlotNotification(10));
coverage.observe_response(&BacktestResponse::SlotNotification(12));
coverage.observe_response(&BacktestResponse::Completed { summary: None });
assert!(coverage.is_completed());
assert_eq!(coverage.highest_slot_seen(), Some(12));
}
#[test]
fn coverage_validate_end_slot_requires_completion_and_observed_slots() {
let mut coverage = SessionCoverage::default();
assert_eq!(
coverage.validate_end_slot(5),
Err(CoverageError::NotCompleted)
);
coverage.mark_completed();
assert_eq!(
coverage.validate_end_slot(5),
Err(CoverageError::NoSlotsObserved)
);
coverage.observe_slot(5);
assert_eq!(coverage.validate_end_slot(5), Ok(()));
}
#[test]
fn coverage_accepts_a_completed_range_whose_trailing_slots_were_skipped() {
// Slot 5 produced no block, so nothing announced it and nothing will.
let mut coverage = SessionCoverage::default();
coverage.observe_slot(4);
coverage.mark_completed();
assert_eq!(coverage.validate_end_slot(5), Ok(()));
}
#[test]
fn coverage_rejects_a_slot_beyond_the_requested_range() {
// Slots past `end_slot` belong to another session.
let mut coverage = SessionCoverage::default();
coverage.observe_slot(6);
coverage.mark_completed();
assert_eq!(
coverage.validate_end_slot(5),
Err(CoverageError::RangeOverrun {
actual_end_slot: 6,
expected_end_slot: 5,
})
);
}
}