1use std::{
2 borrow::Cow,
3 collections::{BTreeMap, VecDeque},
4 future::Future,
5 time::Duration,
6};
7
8use futures::{SinkExt, StreamExt, stream};
9use simulator_api::{
10 AccountData, AccountModifications, AgentStatsReport, BacktestError, BacktestRequest,
11 BacktestResponse, BacktestStatus, ContinueParams, CreateBacktestSessionRequest,
12 CreateBacktestSessionRequestV1, SequencedResponse, SessionId, SessionSummary,
13};
14use solana_address::Address;
15use solana_client::{
16 nonblocking::rpc_client::RpcClient,
17 rpc_response::{Response, RpcLogsResponse},
18};
19use solana_commitment_config::CommitmentConfig;
20use thiserror::Error;
21use tokio::net::TcpStream;
22use tokio_tungstenite::{
23 MaybeTlsStream, WebSocketStream,
24 tungstenite::{
25 Error as WsError, Message,
26 error::ProtocolError,
27 protocol::{CloseFrame, frame::coding::CloseCode},
28 },
29};
30
31use crate::{
32 BacktestClientError, BacktestClientResult, Continue,
33 injection::ProgramModError,
34 subscriptions::{
35 AccountDiffNotification, AccountDiffSubscriptionHandle, LogSubscriptionHandle,
36 SubscriptionError,
37 },
38};
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ReadyOutcome {
43 Ready,
45 Completed,
47}
48
49impl ReadyOutcome {
50 pub fn is_completed(&self) -> bool {
51 matches!(self, Self::Completed)
52 }
53}
54
55#[derive(Debug, Default)]
57pub struct ContinueResult {
58 pub slot_notifications: u64,
60 pub last_slot: Option<u64>,
62 pub statuses: Vec<BacktestStatus>,
64 pub ready_for_continue: bool,
66 pub completed: bool,
68}
69
70#[derive(Debug)]
72pub struct AdvanceState {
73 pub expected_slots: u64,
75 pub slot_notifications: u64,
77 pub last_slot: Option<u64>,
79 pub statuses: Vec<BacktestStatus>,
81 pub ready_for_continue: bool,
83 pub completed: bool,
85 pub summary: Option<SessionSummary>,
87 pub agent_stats: Option<Vec<AgentStatsReport>>,
89}
90
91impl AdvanceState {
92 pub fn new(expected_slots: u64) -> Self {
94 Self {
95 expected_slots,
96 slot_notifications: 0,
97 last_slot: None,
98 statuses: Vec::new(),
99 ready_for_continue: false,
100 completed: false,
101 summary: None,
102 agent_stats: None,
103 }
104 }
105
106 pub fn is_done(&self, wait_for_slots: bool) -> bool {
108 if self.completed {
109 return true;
110 }
111
112 if !self.ready_for_continue {
113 return false;
114 }
115
116 !wait_for_slots || self.slot_notifications >= self.expected_slots
117 }
118}
119
120#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
122pub struct SessionCoverage {
123 completed: bool,
124 highest_slot_seen: Option<u64>,
125}
126
127impl SessionCoverage {
128 pub fn observe_slot(&mut self, slot: u64) {
130 self.highest_slot_seen = Some(
131 self.highest_slot_seen
132 .map_or(slot, |current| current.max(slot)),
133 );
134 }
135
136 pub fn mark_completed(&mut self) {
138 self.completed = true;
139 }
140
141 pub fn observe_response(&mut self, response: &BacktestResponse) {
143 match response {
144 BacktestResponse::SlotNotification(slot) => self.observe_slot(*slot),
145 BacktestResponse::Completed { .. } => self.mark_completed(),
146 _ => {}
147 }
148 }
149
150 pub fn is_completed(&self) -> bool {
152 self.completed
153 }
154
155 pub fn highest_slot_seen(&self) -> Option<u64> {
157 self.highest_slot_seen
158 }
159
160 pub fn validate_end_slot(&self, expected_end_slot: u64) -> Result<(), CoverageError> {
162 if !self.completed {
163 return Err(CoverageError::NotCompleted);
164 }
165
166 let Some(actual_end_slot) = self.highest_slot_seen else {
167 return Err(CoverageError::NoSlotsObserved);
168 };
169
170 if actual_end_slot < expected_end_slot {
171 return Err(CoverageError::RangeNotReached {
172 actual_end_slot,
173 expected_end_slot,
174 });
175 }
176
177 Ok(())
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
183pub enum CoverageError {
184 #[error("ended before completion")]
185 NotCompleted,
186 #[error("completed without slot notifications")]
187 NoSlotsObserved,
188 #[error("completed at slot {actual_end_slot} but expected at least {expected_end_slot}")]
189 RangeNotReached {
190 actual_end_slot: u64,
191 expected_end_slot: u64,
192 },
193}
194
195pub struct BacktestSession {
208 ws: Option<WebSocketStream<MaybeTlsStream<TcpStream>>>,
209 session_id: Option<SessionId>,
210 rpc_endpoint: Option<String>,
211 task_id: Option<String>,
212 rpc: Option<RpcClient>,
213 last_sequence: Option<u64>,
214 pub(crate) ready_for_continue: bool,
215 request_timeout: Option<Duration>,
216 log_raw: bool,
217 backlog: VecDeque<(Option<u64>, BacktestResponse)>,
218}
219
220impl BacktestSession {
221 pub(crate) fn new(
222 ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
223 request_timeout: Option<Duration>,
224 log_raw: bool,
225 ) -> Self {
226 Self {
227 ws: Some(ws),
228 session_id: None,
229 rpc_endpoint: None,
230 task_id: None,
231 rpc: None,
232 last_sequence: None,
233 ready_for_continue: false,
234 request_timeout,
235 log_raw,
236 backlog: VecDeque::new(),
237 }
238 }
239
240 pub fn session_id(&self) -> Option<SessionId> {
242 self.session_id
243 }
244
245 pub fn rpc_endpoint(&self) -> Option<&str> {
247 self.rpc_endpoint.as_deref()
248 }
249
250 pub fn task_id(&self) -> Option<&str> {
253 self.task_id.as_deref()
254 }
255
256 pub fn last_sequence(&self) -> Option<u64> {
258 self.last_sequence
259 }
260
261 pub fn rpc(&self) -> &RpcClient {
265 self.rpc
266 .as_ref()
267 .expect("rpc is set during session creation")
268 }
269
270 pub fn is_ready_for_continue(&self) -> bool {
272 self.ready_for_continue
273 }
274
275 pub fn apply_response(&mut self, response: &BacktestResponse) {
277 match response {
278 BacktestResponse::ReadyForContinue | BacktestResponse::Paused(_) => {
279 self.ready_for_continue = true;
280 }
281 BacktestResponse::Completed { .. } => {
282 self.ready_for_continue = false;
283 }
284 _ => {}
285 }
286 }
287
288 fn ws_mut(&mut self) -> BacktestClientResult<&mut WebSocketStream<MaybeTlsStream<TcpStream>>> {
289 self.ws.as_mut().ok_or_else(|| BacktestClientError::Closed {
290 reason: "websocket closed".to_string(),
291 })
292 }
293
294 pub(crate) async fn create_with_request(
295 &mut self,
296 request: CreateBacktestSessionRequest,
297 rpc_base_url: String,
298 mut on_parallel_session_created: Option<&mut (dyn FnMut(SessionId) + Send)>,
299 ) -> BacktestClientResult<CreateRequestResult> {
300 let expect_parallel = matches!(
301 &request,
302 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { parallel: true, .. })
303 );
304 self.send(&BacktestRequest::CreateBacktestSession(request), None)
305 .await?;
306 let mut streamed_parallel_session_ids = Vec::new();
307 let mut streamed_parallel_task_ids: Vec<Option<String>> = Vec::new();
308 let mut pending: Vec<(Option<u64>, BacktestResponse)> = Vec::new();
312
313 loop {
314 let response =
315 self.next_response(None)
316 .await?
317 .ok_or_else(|| BacktestClientError::Closed {
318 reason: "websocket ended before SessionCreated".to_string(),
319 })?;
320
321 match response {
322 BacktestResponse::SessionCreated {
323 session_id,
324 rpc_endpoint,
325 task_id,
326 } => {
327 if expect_parallel {
328 if let Some(callback) = on_parallel_session_created.as_mut() {
329 (**callback)(session_id);
330 }
331 streamed_parallel_session_ids.push(session_id);
332 streamed_parallel_task_ids.push(task_id);
333 continue;
334 }
335 let created_session_id = session_id;
336 let created_task_id = task_id.clone();
337 self.session_id = Some(session_id);
338 self.task_id = task_id;
339 let resolved = resolve_rpc_url(&rpc_base_url, &rpc_endpoint);
340 self.rpc = Some(RpcClient::new_with_commitment(
341 resolved.clone(),
342 CommitmentConfig::confirmed(),
343 ));
344 self.rpc_endpoint = Some(resolved);
345 self.backlog.extend(pending);
346 return Ok(CreateRequestResult::Single {
347 session_id: created_session_id,
348 task_id: created_task_id,
349 });
350 }
351 BacktestResponse::SessionsCreatedV2 {
352 session_ids,
353 task_ids,
354 ..
355 } => {
356 if expect_parallel && session_ids.is_empty() {
357 self.backlog.extend(pending);
358 return Ok(CreateRequestResult::Parallel {
359 session_ids: streamed_parallel_session_ids,
360 task_ids: streamed_parallel_task_ids,
361 });
362 }
363 let task_ids = align_task_ids(task_ids, session_ids.len());
364 self.backlog.extend(pending);
365 return Ok(CreateRequestResult::Parallel {
366 session_ids,
367 task_ids,
368 });
369 }
370 BacktestResponse::ReadyForContinue => {
371 self.ready_for_continue = true;
372 }
373 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
374 other => {
375 pending.push((self.last_sequence, other));
376 }
377 }
378 }
379 }
380
381 pub(crate) async fn attach(
382 &mut self,
383 session_id: SessionId,
384 last_sequence: Option<u64>,
385 rpc_base_url: String,
386 ) -> BacktestClientResult<()> {
387 self.send(
388 &BacktestRequest::AttachBacktestSession {
389 session_id,
390 last_sequence,
391 },
392 None,
393 )
394 .await?;
395
396 self.wait_for_response(
397 || BacktestClientError::Closed {
398 reason: "websocket ended before SessionAttached".to_string(),
399 },
400 move |session, response| match response {
401 BacktestResponse::SessionAttached {
402 session_id,
403 rpc_endpoint,
404 task_id,
405 } => {
406 session.session_id = Some(session_id);
407 session.task_id = task_id;
408 let resolved = resolve_rpc_url(&rpc_base_url, &rpc_endpoint);
409 session.rpc = Some(RpcClient::new_with_commitment(
410 resolved.clone(),
411 CommitmentConfig::confirmed(),
412 ));
413 session.rpc_endpoint = Some(resolved);
414 Ok(Some(()))
415 }
416 BacktestResponse::ReadyForContinue => {
417 session.ready_for_continue = true;
418 Ok(None)
419 }
420 BacktestResponse::Error(err) => Err(BacktestClientError::Remote(err)),
421 other => {
422 session.backlog.push_back((session.last_sequence, other));
423 Ok(None)
424 }
425 },
426 )
427 .await
428 }
429
430 pub async fn resume_attached_session(&mut self) -> BacktestClientResult<()> {
433 self.send(&BacktestRequest::ResumeAttachedSession, None)
434 .await?;
435
436 self.wait_for_response(
437 || BacktestClientError::Closed {
438 reason: "websocket ended before ResumeAttachedSession acknowledgement".to_string(),
439 },
440 |session, response| match response {
441 BacktestResponse::Success => Ok(Some(())),
442 BacktestResponse::Error(err) => Err(BacktestClientError::Remote(err)),
443 other => {
444 session.backlog.push_back((session.last_sequence, other));
445 Ok(None)
446 }
447 },
448 )
449 .await
450 }
451
452 async fn wait_for_response<T, E, F>(
453 &mut self,
454 closed_error: E,
455 mut handle_response: F,
456 ) -> BacktestClientResult<T>
457 where
458 E: FnOnce() -> BacktestClientError,
459 F: FnMut(&mut Self, BacktestResponse) -> BacktestClientResult<Option<T>>,
460 {
461 let mut closed_error = Some(closed_error);
462
463 loop {
464 let response = self
465 .next_response(None)
466 .await?
467 .ok_or_else(|| closed_error.take().expect("closed error set")())?;
468
469 if let Some(result) = handle_response(self, response)? {
470 return Ok(result);
471 }
472 }
473 }
474
475 pub async fn send(
477 &mut self,
478 request: &BacktestRequest,
479 timeout: Option<Duration>,
480 ) -> BacktestClientResult<()> {
481 let text = serde_json::to_string(request)
482 .map_err(|source| BacktestClientError::SerializeRequest { source })?;
483
484 let request_timeout = self.request_timeout;
485 let timeout = timeout.or(request_timeout);
486
487 let send_fut = self.ws_mut()?.send(Message::Text(text));
488 let send_result = match timeout {
489 Some(duration) => tokio::time::timeout(duration, send_fut)
490 .await
491 .map_err(|_| BacktestClientError::Timeout {
492 action: "sending",
493 duration,
494 })?,
495 None => send_fut.await,
496 };
497
498 send_result.map_err(|source| BacktestClientError::WebSocket {
499 action: "sending",
500 source: Box::new(source),
501 })?;
502
503 Ok(())
504 }
505
506 pub async fn next_response(
508 &mut self,
509 timeout: Option<Duration>,
510 ) -> BacktestClientResult<Option<BacktestResponse>> {
511 if let Some((sequence, response)) = self.backlog.pop_front() {
512 self.last_sequence = sequence.or(self.last_sequence);
513 return Ok(Some(response));
514 }
515
516 let text = match self.next_text(timeout).await? {
517 Some(text) => text,
518 None => return Ok(None),
519 };
520
521 let (sequence, response) = match serde_json::from_str::<SequencedResponse>(&text) {
522 Ok(sequenced) => (Some(sequenced.seq_id), sequenced.response),
523 Err(_) => {
524 let response =
525 serde_json::from_str::<BacktestResponse>(&text).map_err(|source| {
526 BacktestClientError::DeserializeResponse {
527 raw: text.clone(),
528 source,
529 }
530 })?;
531 (None, response)
532 }
533 };
534 self.last_sequence = sequence.or(self.last_sequence);
535
536 Ok(Some(response))
537 }
538
539 pub async fn next_event(
541 &mut self,
542 timeout: Option<Duration>,
543 ) -> BacktestClientResult<Option<BacktestResponse>> {
544 let response = self.next_response(timeout).await?;
545 if let Some(ref response) = response {
546 self.apply_response(response);
547 }
548 Ok(response)
549 }
550
551 pub fn responses(
555 self,
556 timeout: Option<Duration>,
557 ) -> impl futures::Stream<Item = BacktestClientResult<BacktestResponse>> {
558 stream::unfold(Some(self), move |state| async move {
559 let mut session = match state {
560 Some(session) => session,
561 None => return None,
562 };
563
564 match session.next_response(timeout).await {
565 Ok(Some(response)) => {
566 session.apply_response(&response);
567 Some((Ok(response), Some(session)))
568 }
569 Ok(None) => None,
570 Err(err) => Some((Err(err), None)),
571 }
572 })
573 }
574
575 pub async fn ensure_ready(
577 &mut self,
578 timeout: Option<Duration>,
579 ) -> BacktestClientResult<ReadyOutcome> {
580 if self.ready_for_continue {
581 return Ok(ReadyOutcome::Ready);
582 }
583
584 loop {
585 let response =
586 self.next_response(timeout)
587 .await?
588 .ok_or_else(|| BacktestClientError::Closed {
589 reason: "websocket ended while waiting for ReadyForContinue".to_string(),
590 })?;
591
592 match response {
593 BacktestResponse::ReadyForContinue => {
594 self.ready_for_continue = true;
595 return Ok(ReadyOutcome::Ready);
596 }
597 BacktestResponse::Completed { .. } => return Ok(ReadyOutcome::Completed),
598 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
599 _ => {}
600 }
601 }
602 }
603
604 pub async fn wait_for_status(
606 &mut self,
607 desired: BacktestStatus,
608 timeout: Option<Duration>,
609 ) -> BacktestClientResult<()> {
610 let desired = std::mem::discriminant(&desired);
611
612 loop {
613 let response =
614 self.next_response(timeout)
615 .await?
616 .ok_or_else(|| BacktestClientError::Closed {
617 reason: "websocket ended while waiting for status".to_string(),
618 })?;
619
620 match response {
621 BacktestResponse::Status { status }
622 if std::mem::discriminant(&status) == desired =>
623 {
624 return Ok(());
625 }
626 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
627 BacktestResponse::Completed {
628 summary,
629 agent_stats,
630 } => {
631 return Err(BacktestClientError::UnexpectedResponse {
632 context: "waiting for status",
633 response: Box::new(BacktestResponse::Completed {
634 summary,
635 agent_stats,
636 }),
637 });
638 }
639 _ => {}
640 }
641 }
642 }
643
644 pub(crate) fn push_backlog(&mut self, response: BacktestResponse) {
646 self.backlog.push_back((None, response));
647 }
648
649 pub async fn send_continue(
651 &mut self,
652 params: ContinueParams,
653 timeout: Option<Duration>,
654 ) -> BacktestClientResult<()> {
655 self.ready_for_continue = false;
656 self.send(&BacktestRequest::Continue(params), timeout).await
657 }
658
659 pub async fn advance_step<F>(
661 &mut self,
662 state: &mut AdvanceState,
663 wait_for_slots: bool,
664 timeout: Option<Duration>,
665 on_event: &mut F,
666 ) -> BacktestClientResult<()>
667 where
668 F: FnMut(&BacktestResponse),
669 {
670 let Some(response) = self.next_response(timeout).await? else {
671 return Err(BacktestClientError::Closed {
672 reason: "websocket ended while awaiting continue responses".to_string(),
673 });
674 };
675
676 if self.log_raw {
677 tracing::debug!("<- {response:?}");
678 }
679
680 on_event(&response);
681
682 match response {
683 BacktestResponse::ReadyForContinue => {
684 self.ready_for_continue = true;
685 state.ready_for_continue = true;
686 }
687 BacktestResponse::SlotNotification(slot) => {
688 state.slot_notifications += 1;
689 state.last_slot = Some(slot);
690 }
691 BacktestResponse::Status { status } => {
692 state.statuses.push(status);
693 }
694 BacktestResponse::Success => {}
695 BacktestResponse::Completed {
696 summary,
697 agent_stats,
698 } => {
699 state.completed = true;
700 state.summary = summary;
701 state.agent_stats = agent_stats;
702 }
703 BacktestResponse::Error(err @ BacktestError::SimulationError { .. }) => {
704 tracing::warn!(error = %crate::error::err_chain(&err), "simulation error");
705 }
706 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
707 BacktestResponse::SessionCreated { .. }
708 | BacktestResponse::SessionAttached { .. }
709 | BacktestResponse::SessionsCreatedV2 { .. }
710 | BacktestResponse::ParallelSessionAttachedV2 { .. }
711 | BacktestResponse::SessionEventV2 { .. }
712 | BacktestResponse::Paused(_)
713 | BacktestResponse::DiscoveryBatch(_) => {
714 return Err(BacktestClientError::UnexpectedResponse {
715 context: "continuing",
716 response: Box::new(response),
717 });
718 }
719 }
720
721 if wait_for_slots && state.slot_notifications > state.expected_slots {
722 tracing::warn!(
723 "received {} slot notifications (expected {})",
724 state.slot_notifications,
725 state.expected_slots
726 );
727 }
728
729 Ok(())
730 }
731
732 pub async fn continue_until_ready<F>(
734 &mut self,
735 cont: Continue,
736 timeout: Option<Duration>,
737 mut on_event: F,
738 ) -> BacktestClientResult<ContinueResult>
739 where
740 F: FnMut(&BacktestResponse),
741 {
742 let expected_slots = cont.advance_count;
743 self.advance_internal(
744 cont.into_params(),
745 expected_slots,
746 false,
747 timeout,
748 &mut on_event,
749 )
750 .await
751 }
752
753 pub async fn advance<F>(
755 &mut self,
756 cont: Continue,
757 timeout: Option<Duration>,
758 mut on_event: F,
759 ) -> BacktestClientResult<ContinueResult>
760 where
761 F: FnMut(&BacktestResponse),
762 {
763 let expected_slots = cont.advance_count;
764 self.advance_internal(
765 cont.into_params(),
766 expected_slots,
767 true,
768 timeout,
769 &mut on_event,
770 )
771 .await
772 }
773
774 async fn advance_internal<F>(
775 &mut self,
776 params: ContinueParams,
777 expected_slots: u64,
778 wait_for_slots: bool,
779 timeout: Option<Duration>,
780 on_event: &mut F,
781 ) -> BacktestClientResult<ContinueResult>
782 where
783 F: FnMut(&BacktestResponse),
784 {
785 self.send_continue(params, timeout).await?;
786
787 let mut state = AdvanceState::new(expected_slots);
788 while !state.is_done(wait_for_slots) {
789 self.advance_step(&mut state, wait_for_slots, timeout, on_event)
790 .await?;
791 }
792
793 Ok(ContinueResult {
794 slot_notifications: state.slot_notifications,
795 last_slot: state.last_slot,
796 statuses: state.statuses,
797 ready_for_continue: state.ready_for_continue,
798 completed: state.completed,
799 })
800 }
801
802 pub async fn modify_program(
811 &self,
812 program_id: &str,
813 elf: &[u8],
814 ) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
815 let rpc = self.rpc.as_ref().ok_or(ProgramModError::NoRpcEndpoint)?;
816 crate::injection::modify_program_via_rpc(rpc, program_id, elf).await
817 }
818
819 pub async fn modify_accounts(
823 &self,
824 modifications: &AccountModifications,
825 ) -> BacktestClientResult<usize> {
826 let rpc_endpoint =
827 self.rpc_endpoint
828 .as_deref()
829 .ok_or_else(|| BacktestClientError::Closed {
830 reason: "no RPC endpoint available".to_string(),
831 })?;
832
833 crate::rpc::modify_accounts(rpc_endpoint, modifications).await
834 }
835
836 pub async fn subscribe_program_logs<F, Fut>(
842 &self,
843 program_id: &str,
844 commitment: CommitmentConfig,
845 on_notification: F,
846 ) -> Result<LogSubscriptionHandle, SubscriptionError>
847 where
848 F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
849 Fut: Future<Output = ()> + Send + 'static,
850 {
851 let rpc_endpoint = self
852 .rpc_endpoint
853 .as_deref()
854 .ok_or(SubscriptionError::NoRpcEndpoint)?;
855 crate::subscriptions::subscribe_program_logs(
856 rpc_endpoint,
857 program_id,
858 commitment,
859 on_notification,
860 )
861 .await
862 }
863
864 pub async fn subscribe_account_diffs<F, Fut>(
870 &self,
871 account: &str,
872 on_notification: F,
873 ) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
874 where
875 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
876 Fut: Future<Output = ()> + Send + 'static,
877 {
878 let rpc_endpoint = self
879 .rpc_endpoint
880 .as_deref()
881 .ok_or(SubscriptionError::NoRpcEndpoint)?;
882 crate::subscriptions::subscribe_account_diffs(rpc_endpoint, account, on_notification).await
883 }
884
885 pub async fn close(&mut self, timeout: Option<Duration>) -> BacktestClientResult<()> {
889 self.close_with_frame(timeout, None).await
890 }
891
892 pub async fn close_with_frame(
894 &mut self,
895 timeout: Option<Duration>,
896 frame: Option<CloseFrame<'static>>,
897 ) -> BacktestClientResult<()> {
898 if self.ws.is_none() {
899 return Ok(());
900 }
901
902 let mut sent = false;
903 match self
904 .send(&BacktestRequest::CloseBacktestSession, timeout)
905 .await
906 {
907 Ok(()) => sent = true,
908 Err(err) if is_close_ok(&err) => {}
909 Err(err) => return Err(err),
910 }
911
912 if sent {
913 let response = match self.next_response(timeout).await {
914 Ok(Some(r)) => r,
915 Ok(None) => {
916 self.ws.take();
917 return Ok(());
918 }
919 Err(BacktestClientError::Closed { .. }) => {
920 self.ws.take();
921 return Ok(());
922 }
923 Err(BacktestClientError::WebSocket {
924 action: "receiving",
925 source,
926 }) if is_reset_without_close(&source) => {
927 self.ws.take();
928 return Ok(());
929 }
930 Err(err) => return Err(err),
931 };
932
933 match response {
934 BacktestResponse::Success | BacktestResponse::Completed { .. } => {}
935 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
936 other => {
937 return Err(BacktestClientError::UnexpectedResponse {
938 context: "closing session",
939 response: Box::new(other),
940 });
941 }
942 }
943 }
944
945 if let Some(mut ws) = self.ws.take()
948 && let Err(source) = ws.close(frame).await
949 && !is_ws_closed_error(&source)
950 {
951 return Err(BacktestClientError::WebSocket {
952 action: "closing",
953 source: Box::new(source),
954 });
955 }
956 Ok(())
957 }
958
959 pub async fn close_with_reason(
961 &mut self,
962 timeout: Option<Duration>,
963 code: CloseCode,
964 reason: impl Into<String>,
965 ) -> BacktestClientResult<()> {
966 let frame = CloseFrame {
967 code,
968 reason: Cow::Owned(reason.into()),
969 };
970 self.close_with_frame(timeout, Some(frame)).await
971 }
972
973 pub fn abort(mut self) {
980 let _ws = self.ws.take();
981 }
982
983 async fn next_text(
984 &mut self,
985 timeout: Option<Duration>,
986 ) -> BacktestClientResult<Option<String>> {
987 loop {
988 let request_timeout = self.request_timeout;
989 let timeout = timeout.or(request_timeout);
990
991 let next_fut = self.ws_mut()?.next();
992 let msg = match timeout {
993 Some(duration) => tokio::time::timeout(duration, next_fut)
994 .await
995 .map_err(|_| BacktestClientError::Timeout {
996 action: "receiving",
997 duration,
998 })?,
999 None => next_fut.await,
1000 };
1001
1002 let Some(msg) = msg else {
1003 return Ok(None);
1004 };
1005
1006 let msg = match msg {
1007 Ok(msg) => msg,
1008 Err(source) => {
1009 return Err(BacktestClientError::WebSocket {
1010 action: "receiving",
1011 source: Box::new(source),
1012 });
1013 }
1014 };
1015
1016 match msg {
1017 Message::Text(text) => {
1018 if self.log_raw {
1019 tracing::debug!("<- raw: {text}");
1020 }
1021 return Ok(Some(text));
1022 }
1023 Message::Binary(bin) => match String::from_utf8(bin) {
1024 Ok(text) => {
1025 if self.log_raw {
1026 tracing::debug!("<- raw(bin): {text}");
1027 }
1028 return Ok(Some(text));
1029 }
1030 Err(err) => {
1031 tracing::warn!("discarding non-utf8 binary message: {err}");
1032 continue;
1033 }
1034 },
1035 Message::Close(frame) => {
1036 let reason = close_reason(frame);
1037 return Err(BacktestClientError::Closed { reason });
1038 }
1039 Message::Ping(_) | Message::Pong(_) => continue,
1040 Message::Frame(_) => continue,
1041 }
1042 }
1043 }
1044}
1045
1046impl std::fmt::Debug for BacktestSession {
1047 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1048 f.debug_struct("BacktestSession")
1049 .field("session_id", &self.session_id)
1050 .field("rpc_endpoint", &self.rpc_endpoint)
1051 .field(
1052 "rpc",
1053 &self
1054 .rpc
1055 .as_ref()
1056 .map(|_| "<RpcClient>")
1057 .unwrap_or("<not set>"),
1058 )
1059 .field("ready_for_continue", &self.ready_for_continue)
1060 .field("request_timeout", &self.request_timeout)
1061 .finish_non_exhaustive()
1062 }
1063}
1064
1065#[derive(Debug)]
1066pub(crate) enum CreateRequestResult {
1067 Single {
1068 session_id: SessionId,
1069 task_id: Option<String>,
1070 },
1071 Parallel {
1072 session_ids: Vec<SessionId>,
1073 task_ids: Vec<Option<String>>,
1074 },
1075}
1076
1077fn align_task_ids(mut task_ids: Vec<Option<String>>, expected_len: usize) -> Vec<Option<String>> {
1080 if task_ids.len() < expected_len {
1081 task_ids.resize(expected_len, None);
1082 } else if task_ids.len() > expected_len {
1083 task_ids.truncate(expected_len);
1084 }
1085 task_ids
1086}
1087
1088impl Drop for BacktestSession {
1089 fn drop(&mut self) {
1090 let Some(ws) = self.ws.take() else {
1091 return;
1092 };
1093
1094 if let Ok(handle) = tokio::runtime::Handle::try_current() {
1095 handle.spawn(async move {
1096 let mut ws = ws;
1097 let _ = ws.close(None).await;
1098 });
1099 }
1100 }
1101}
1102
1103fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
1104 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
1105 endpoint.to_string()
1106 } else {
1107 format!("{}/{}", base, endpoint.trim_start_matches('/'))
1108 }
1109}
1110
1111fn close_reason(frame: Option<CloseFrame<'static>>) -> String {
1112 match frame {
1113 Some(frame) => format!("{:?}: {}", frame.code, frame.reason),
1114 None => "no close frame".to_string(),
1115 }
1116}
1117
1118fn is_reset_without_close(err: &WsError) -> bool {
1119 matches!(
1120 err,
1121 WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
1122 )
1123}
1124
1125fn is_ws_closed_error(err: &WsError) -> bool {
1126 matches!(
1127 err,
1128 WsError::ConnectionClosed
1129 | WsError::AlreadyClosed
1130 | WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
1131 )
1132}
1133
1134fn is_close_ok(err: &BacktestClientError) -> bool {
1135 match err {
1136 BacktestClientError::Closed { .. } => true,
1137 BacktestClientError::WebSocket { source, .. } => is_ws_closed_error(source),
1138 _ => false,
1139 }
1140}
1141
1142#[cfg(test)]
1143mod tests {
1144 use super::*;
1145
1146 #[test]
1147 fn coverage_tracks_slot_and_completion_from_responses() {
1148 let mut coverage = SessionCoverage::default();
1149 coverage.observe_response(&BacktestResponse::SlotNotification(10));
1150 coverage.observe_response(&BacktestResponse::SlotNotification(12));
1151 coverage.observe_response(&BacktestResponse::Completed {
1152 summary: None,
1153 agent_stats: None,
1154 });
1155
1156 assert!(coverage.is_completed());
1157 assert_eq!(coverage.highest_slot_seen(), Some(12));
1158 }
1159
1160 #[test]
1161 fn coverage_validate_end_slot_checks_completion_and_range() {
1162 let mut coverage = SessionCoverage::default();
1163 assert_eq!(
1164 coverage.validate_end_slot(5),
1165 Err(CoverageError::NotCompleted)
1166 );
1167
1168 coverage.mark_completed();
1169 assert_eq!(
1170 coverage.validate_end_slot(5),
1171 Err(CoverageError::NoSlotsObserved)
1172 );
1173
1174 coverage.observe_slot(4);
1175 assert_eq!(
1176 coverage.validate_end_slot(5),
1177 Err(CoverageError::RangeNotReached {
1178 actual_end_slot: 4,
1179 expected_end_slot: 5,
1180 })
1181 );
1182
1183 coverage.observe_slot(6);
1184 assert_eq!(coverage.validate_end_slot(5), Ok(()));
1185 }
1186}