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 {
200 ws: Option<WebSocketStream<MaybeTlsStream<TcpStream>>>,
201 session_id: Option<SessionId>,
202 rpc_endpoint: Option<String>,
203 task_id: Option<String>,
204 rpc: Option<RpcClient>,
205 last_sequence: Option<u64>,
206 pub(crate) ready_for_continue: bool,
207 request_timeout: Option<Duration>,
208 log_raw: bool,
209 backlog: VecDeque<(Option<u64>, BacktestResponse)>,
210}
211
212impl BacktestSession {
213 pub(crate) fn new(
214 ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
215 request_timeout: Option<Duration>,
216 log_raw: bool,
217 ) -> Self {
218 Self {
219 ws: Some(ws),
220 session_id: None,
221 rpc_endpoint: None,
222 task_id: None,
223 rpc: None,
224 last_sequence: None,
225 ready_for_continue: false,
226 request_timeout,
227 log_raw,
228 backlog: VecDeque::new(),
229 }
230 }
231
232 pub fn session_id(&self) -> Option<SessionId> {
234 self.session_id
235 }
236
237 pub fn rpc_endpoint(&self) -> Option<&str> {
239 self.rpc_endpoint.as_deref()
240 }
241
242 pub fn task_id(&self) -> Option<&str> {
245 self.task_id.as_deref()
246 }
247
248 pub fn last_sequence(&self) -> Option<u64> {
250 self.last_sequence
251 }
252
253 pub fn rpc(&self) -> &RpcClient {
257 self.rpc
258 .as_ref()
259 .expect("rpc is set during session creation")
260 }
261
262 pub fn is_ready_for_continue(&self) -> bool {
264 self.ready_for_continue
265 }
266
267 pub fn apply_response(&mut self, response: &BacktestResponse) {
269 match response {
270 BacktestResponse::ReadyForContinue | BacktestResponse::Paused(_) => {
271 self.ready_for_continue = true;
272 }
273 BacktestResponse::Completed { .. } => {
274 self.ready_for_continue = false;
275 }
276 _ => {}
277 }
278 }
279
280 fn ws_mut(&mut self) -> BacktestClientResult<&mut WebSocketStream<MaybeTlsStream<TcpStream>>> {
281 self.ws.as_mut().ok_or_else(|| BacktestClientError::Closed {
282 reason: "websocket closed".to_string(),
283 })
284 }
285
286 pub(crate) async fn create_with_request(
287 &mut self,
288 request: CreateBacktestSessionRequest,
289 rpc_base_url: String,
290 mut on_parallel_session_created: Option<&mut (dyn FnMut(SessionId) + Send)>,
291 ) -> BacktestClientResult<CreateRequestResult> {
292 let expect_parallel = matches!(
293 &request,
294 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { parallel: true, .. })
295 );
296 self.send(&BacktestRequest::CreateBacktestSession(request), None)
297 .await?;
298 let mut streamed_parallel_session_ids = Vec::new();
299 let mut streamed_parallel_task_ids: Vec<Option<String>> = Vec::new();
300 let mut pending: Vec<(Option<u64>, BacktestResponse)> = Vec::new();
304
305 loop {
306 let response =
307 self.next_response(None)
308 .await?
309 .ok_or_else(|| BacktestClientError::Closed {
310 reason: "websocket ended before SessionCreated".to_string(),
311 })?;
312
313 match response {
314 BacktestResponse::SessionCreated {
315 session_id,
316 rpc_endpoint,
317 task_id,
318 } => {
319 if expect_parallel {
320 if let Some(callback) = on_parallel_session_created.as_mut() {
321 (**callback)(session_id);
322 }
323 streamed_parallel_session_ids.push(session_id);
324 streamed_parallel_task_ids.push(task_id);
325 continue;
326 }
327 let created_session_id = session_id;
328 let created_task_id = task_id.clone();
329 self.session_id = Some(session_id);
330 self.task_id = task_id;
331 let resolved = resolve_rpc_url(&rpc_base_url, &rpc_endpoint);
332 self.rpc = Some(RpcClient::new_with_commitment(
333 resolved.clone(),
334 CommitmentConfig::confirmed(),
335 ));
336 self.rpc_endpoint = Some(resolved);
337 self.backlog.extend(pending);
338 return Ok(CreateRequestResult::Single {
339 session_id: created_session_id,
340 task_id: created_task_id,
341 });
342 }
343 BacktestResponse::SessionsCreatedV2 {
344 session_ids,
345 task_ids,
346 ..
347 } => {
348 if expect_parallel && session_ids.is_empty() {
349 self.backlog.extend(pending);
350 return Ok(CreateRequestResult::Parallel {
351 session_ids: streamed_parallel_session_ids,
352 task_ids: streamed_parallel_task_ids,
353 });
354 }
355 let task_ids = align_task_ids(task_ids, session_ids.len());
356 self.backlog.extend(pending);
357 return Ok(CreateRequestResult::Parallel {
358 session_ids,
359 task_ids,
360 });
361 }
362 BacktestResponse::ReadyForContinue => {
363 self.ready_for_continue = true;
364 }
365 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
366 other => {
367 pending.push((self.last_sequence, other));
368 }
369 }
370 }
371 }
372
373 pub(crate) async fn attach(
374 &mut self,
375 session_id: SessionId,
376 last_sequence: Option<u64>,
377 rpc_base_url: String,
378 ) -> BacktestClientResult<()> {
379 self.send(
380 &BacktestRequest::AttachBacktestSession {
381 session_id,
382 last_sequence,
383 },
384 None,
385 )
386 .await?;
387
388 self.wait_for_response(
389 || BacktestClientError::Closed {
390 reason: "websocket ended before SessionAttached".to_string(),
391 },
392 move |session, response| match response {
393 BacktestResponse::SessionAttached {
394 session_id,
395 rpc_endpoint,
396 task_id,
397 } => {
398 session.session_id = Some(session_id);
399 session.task_id = task_id;
400 let resolved = resolve_rpc_url(&rpc_base_url, &rpc_endpoint);
401 session.rpc = Some(RpcClient::new_with_commitment(
402 resolved.clone(),
403 CommitmentConfig::confirmed(),
404 ));
405 session.rpc_endpoint = Some(resolved);
406 Ok(Some(()))
407 }
408 BacktestResponse::ReadyForContinue => {
409 session.ready_for_continue = true;
410 Ok(None)
411 }
412 BacktestResponse::Error(err) => Err(BacktestClientError::Remote(err)),
413 other => {
414 session.backlog.push_back((session.last_sequence, other));
415 Ok(None)
416 }
417 },
418 )
419 .await
420 }
421
422 pub async fn resume_attached_session(&mut self) -> BacktestClientResult<()> {
425 self.send(&BacktestRequest::ResumeAttachedSession, None)
426 .await?;
427
428 self.wait_for_response(
429 || BacktestClientError::Closed {
430 reason: "websocket ended before ResumeAttachedSession acknowledgement".to_string(),
431 },
432 |session, response| match response {
433 BacktestResponse::Success => Ok(Some(())),
434 BacktestResponse::Error(err) => Err(BacktestClientError::Remote(err)),
435 other => {
436 session.backlog.push_back((session.last_sequence, other));
437 Ok(None)
438 }
439 },
440 )
441 .await
442 }
443
444 async fn wait_for_response<T, E, F>(
445 &mut self,
446 closed_error: E,
447 mut handle_response: F,
448 ) -> BacktestClientResult<T>
449 where
450 E: FnOnce() -> BacktestClientError,
451 F: FnMut(&mut Self, BacktestResponse) -> BacktestClientResult<Option<T>>,
452 {
453 let mut closed_error = Some(closed_error);
454
455 loop {
456 let response = self
457 .next_response(None)
458 .await?
459 .ok_or_else(|| closed_error.take().expect("closed error set")())?;
460
461 if let Some(result) = handle_response(self, response)? {
462 return Ok(result);
463 }
464 }
465 }
466
467 pub async fn send(
469 &mut self,
470 request: &BacktestRequest,
471 timeout: Option<Duration>,
472 ) -> BacktestClientResult<()> {
473 let text = serde_json::to_string(request)
474 .map_err(|source| BacktestClientError::SerializeRequest { source })?;
475
476 let request_timeout = self.request_timeout;
477 let timeout = timeout.or(request_timeout);
478
479 let send_fut = self.ws_mut()?.send(Message::Text(text));
480 let send_result = match timeout {
481 Some(duration) => tokio::time::timeout(duration, send_fut)
482 .await
483 .map_err(|_| BacktestClientError::Timeout {
484 action: "sending",
485 duration,
486 })?,
487 None => send_fut.await,
488 };
489
490 send_result.map_err(|source| BacktestClientError::WebSocket {
491 action: "sending",
492 source: Box::new(source),
493 })?;
494
495 Ok(())
496 }
497
498 pub async fn next_response(
500 &mut self,
501 timeout: Option<Duration>,
502 ) -> BacktestClientResult<Option<BacktestResponse>> {
503 if let Some((sequence, response)) = self.backlog.pop_front() {
504 self.last_sequence = sequence.or(self.last_sequence);
505 return Ok(Some(response));
506 }
507
508 let text = match self.next_text(timeout).await? {
509 Some(text) => text,
510 None => return Ok(None),
511 };
512
513 let (sequence, response) = match serde_json::from_str::<SequencedResponse>(&text) {
514 Ok(sequenced) => (Some(sequenced.seq_id), sequenced.response),
515 Err(_) => {
516 let response =
517 serde_json::from_str::<BacktestResponse>(&text).map_err(|source| {
518 BacktestClientError::DeserializeResponse {
519 raw: text.clone(),
520 source,
521 }
522 })?;
523 (None, response)
524 }
525 };
526 self.last_sequence = sequence.or(self.last_sequence);
527
528 Ok(Some(response))
529 }
530
531 pub async fn next_event(
533 &mut self,
534 timeout: Option<Duration>,
535 ) -> BacktestClientResult<Option<BacktestResponse>> {
536 let response = self.next_response(timeout).await?;
537 if let Some(ref response) = response {
538 self.apply_response(response);
539 }
540 Ok(response)
541 }
542
543 pub fn responses(
547 self,
548 timeout: Option<Duration>,
549 ) -> impl futures::Stream<Item = BacktestClientResult<BacktestResponse>> {
550 stream::unfold(Some(self), move |state| async move {
551 let mut session = match state {
552 Some(session) => session,
553 None => return None,
554 };
555
556 match session.next_response(timeout).await {
557 Ok(Some(response)) => {
558 session.apply_response(&response);
559 Some((Ok(response), Some(session)))
560 }
561 Ok(None) => None,
562 Err(err) => Some((Err(err), None)),
563 }
564 })
565 }
566
567 pub async fn ensure_ready(
569 &mut self,
570 timeout: Option<Duration>,
571 ) -> BacktestClientResult<ReadyOutcome> {
572 if self.ready_for_continue {
573 return Ok(ReadyOutcome::Ready);
574 }
575
576 loop {
577 let response =
578 self.next_response(timeout)
579 .await?
580 .ok_or_else(|| BacktestClientError::Closed {
581 reason: "websocket ended while waiting for ReadyForContinue".to_string(),
582 })?;
583
584 match response {
585 BacktestResponse::ReadyForContinue => {
586 self.ready_for_continue = true;
587 return Ok(ReadyOutcome::Ready);
588 }
589 BacktestResponse::Completed { .. } => return Ok(ReadyOutcome::Completed),
590 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
591 _ => {}
592 }
593 }
594 }
595
596 pub async fn wait_for_status(
598 &mut self,
599 desired: BacktestStatus,
600 timeout: Option<Duration>,
601 ) -> BacktestClientResult<()> {
602 let desired = std::mem::discriminant(&desired);
603
604 loop {
605 let response =
606 self.next_response(timeout)
607 .await?
608 .ok_or_else(|| BacktestClientError::Closed {
609 reason: "websocket ended while waiting for status".to_string(),
610 })?;
611
612 match response {
613 BacktestResponse::Status { status }
614 if std::mem::discriminant(&status) == desired =>
615 {
616 return Ok(());
617 }
618 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
619 BacktestResponse::Completed {
620 summary,
621 agent_stats,
622 } => {
623 return Err(BacktestClientError::UnexpectedResponse {
624 context: "waiting for status",
625 response: Box::new(BacktestResponse::Completed {
626 summary,
627 agent_stats,
628 }),
629 });
630 }
631 _ => {}
632 }
633 }
634 }
635
636 pub(crate) fn push_backlog(&mut self, response: BacktestResponse) {
638 self.backlog.push_back((None, response));
639 }
640
641 pub async fn send_continue(
643 &mut self,
644 params: ContinueParams,
645 timeout: Option<Duration>,
646 ) -> BacktestClientResult<()> {
647 self.ready_for_continue = false;
648 self.send(&BacktestRequest::Continue(params), timeout).await
649 }
650
651 pub async fn advance_step<F>(
653 &mut self,
654 state: &mut AdvanceState,
655 wait_for_slots: bool,
656 timeout: Option<Duration>,
657 on_event: &mut F,
658 ) -> BacktestClientResult<()>
659 where
660 F: FnMut(&BacktestResponse),
661 {
662 let Some(response) = self.next_response(timeout).await? else {
663 return Err(BacktestClientError::Closed {
664 reason: "websocket ended while awaiting continue responses".to_string(),
665 });
666 };
667
668 if self.log_raw {
669 tracing::debug!("<- {response:?}");
670 }
671
672 on_event(&response);
673
674 match response {
675 BacktestResponse::ReadyForContinue => {
676 self.ready_for_continue = true;
677 state.ready_for_continue = true;
678 }
679 BacktestResponse::SlotNotification(slot) => {
680 state.slot_notifications += 1;
681 state.last_slot = Some(slot);
682 }
683 BacktestResponse::Status { status } => {
684 state.statuses.push(status);
685 }
686 BacktestResponse::Success => {}
687 BacktestResponse::Completed {
688 summary,
689 agent_stats,
690 } => {
691 state.completed = true;
692 state.summary = summary;
693 state.agent_stats = agent_stats;
694 }
695 BacktestResponse::Error(err @ BacktestError::SimulationError { .. }) => {
696 tracing::warn!(error = %crate::error::err_chain(&err), "simulation error");
697 }
698 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
699 BacktestResponse::SessionCreated { .. }
700 | BacktestResponse::SessionAttached { .. }
701 | BacktestResponse::SessionsCreatedV2 { .. }
702 | BacktestResponse::ParallelSessionAttachedV2 { .. }
703 | BacktestResponse::SessionEventV2 { .. }
704 | BacktestResponse::Paused(_)
705 | BacktestResponse::DiscoveryBatch(_) => {
706 return Err(BacktestClientError::UnexpectedResponse {
707 context: "continuing",
708 response: Box::new(response),
709 });
710 }
711 }
712
713 if wait_for_slots && state.slot_notifications > state.expected_slots {
714 tracing::warn!(
715 "received {} slot notifications (expected {})",
716 state.slot_notifications,
717 state.expected_slots
718 );
719 }
720
721 Ok(())
722 }
723
724 pub async fn continue_until_ready<F>(
726 &mut self,
727 cont: Continue,
728 timeout: Option<Duration>,
729 mut on_event: F,
730 ) -> BacktestClientResult<ContinueResult>
731 where
732 F: FnMut(&BacktestResponse),
733 {
734 let expected_slots = cont.advance_count;
735 self.advance_internal(
736 cont.into_params(),
737 expected_slots,
738 false,
739 timeout,
740 &mut on_event,
741 )
742 .await
743 }
744
745 pub async fn advance<F>(
747 &mut self,
748 cont: Continue,
749 timeout: Option<Duration>,
750 mut on_event: F,
751 ) -> BacktestClientResult<ContinueResult>
752 where
753 F: FnMut(&BacktestResponse),
754 {
755 let expected_slots = cont.advance_count;
756 self.advance_internal(
757 cont.into_params(),
758 expected_slots,
759 true,
760 timeout,
761 &mut on_event,
762 )
763 .await
764 }
765
766 async fn advance_internal<F>(
767 &mut self,
768 params: ContinueParams,
769 expected_slots: u64,
770 wait_for_slots: bool,
771 timeout: Option<Duration>,
772 on_event: &mut F,
773 ) -> BacktestClientResult<ContinueResult>
774 where
775 F: FnMut(&BacktestResponse),
776 {
777 self.send_continue(params, timeout).await?;
778
779 let mut state = AdvanceState::new(expected_slots);
780 while !state.is_done(wait_for_slots) {
781 self.advance_step(&mut state, wait_for_slots, timeout, on_event)
782 .await?;
783 }
784
785 Ok(ContinueResult {
786 slot_notifications: state.slot_notifications,
787 last_slot: state.last_slot,
788 statuses: state.statuses,
789 ready_for_continue: state.ready_for_continue,
790 completed: state.completed,
791 })
792 }
793
794 pub async fn modify_program(
803 &self,
804 program_id: &str,
805 elf: &[u8],
806 ) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
807 let rpc = self.rpc.as_ref().ok_or(ProgramModError::NoRpcEndpoint)?;
808 crate::injection::modify_program_via_rpc(rpc, program_id, elf).await
809 }
810
811 pub async fn modify_accounts(
815 &self,
816 modifications: &AccountModifications,
817 ) -> BacktestClientResult<usize> {
818 let rpc_endpoint =
819 self.rpc_endpoint
820 .as_deref()
821 .ok_or_else(|| BacktestClientError::Closed {
822 reason: "no RPC endpoint available".to_string(),
823 })?;
824
825 crate::rpc::modify_accounts(rpc_endpoint, modifications).await
826 }
827
828 pub async fn subscribe_program_logs<F, Fut>(
834 &self,
835 program_id: &str,
836 commitment: CommitmentConfig,
837 on_notification: F,
838 ) -> Result<LogSubscriptionHandle, SubscriptionError>
839 where
840 F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
841 Fut: Future<Output = ()> + Send + 'static,
842 {
843 let rpc_endpoint = self
844 .rpc_endpoint
845 .as_deref()
846 .ok_or(SubscriptionError::NoRpcEndpoint)?;
847 crate::subscriptions::subscribe_program_logs(
848 rpc_endpoint,
849 program_id,
850 commitment,
851 on_notification,
852 )
853 .await
854 }
855
856 pub async fn subscribe_account_diffs<F, Fut>(
862 &self,
863 account: &str,
864 on_notification: F,
865 ) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
866 where
867 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
868 Fut: Future<Output = ()> + Send + 'static,
869 {
870 let rpc_endpoint = self
871 .rpc_endpoint
872 .as_deref()
873 .ok_or(SubscriptionError::NoRpcEndpoint)?;
874 crate::subscriptions::subscribe_account_diffs(rpc_endpoint, account, on_notification).await
875 }
876
877 pub async fn close(&mut self, timeout: Option<Duration>) -> BacktestClientResult<()> {
881 self.close_with_frame(timeout, None).await
882 }
883
884 pub async fn close_with_frame(
886 &mut self,
887 timeout: Option<Duration>,
888 frame: Option<CloseFrame<'static>>,
889 ) -> BacktestClientResult<()> {
890 if self.ws.is_none() {
891 return Ok(());
892 }
893
894 let mut sent = false;
895 match self
896 .send(&BacktestRequest::CloseBacktestSession, timeout)
897 .await
898 {
899 Ok(()) => sent = true,
900 Err(err) if is_close_ok(&err) => {}
901 Err(err) => return Err(err),
902 }
903
904 if sent {
905 let response = match self.next_response(timeout).await {
906 Ok(Some(r)) => r,
907 Ok(None) => {
908 self.ws.take();
909 return Ok(());
910 }
911 Err(BacktestClientError::Closed { .. }) => {
912 self.ws.take();
913 return Ok(());
914 }
915 Err(BacktestClientError::WebSocket {
916 action: "receiving",
917 source,
918 }) if is_reset_without_close(&source) => {
919 self.ws.take();
920 return Ok(());
921 }
922 Err(err) => return Err(err),
923 };
924
925 match response {
926 BacktestResponse::Success | BacktestResponse::Completed { .. } => {}
927 BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
928 other => {
929 return Err(BacktestClientError::UnexpectedResponse {
930 context: "closing session",
931 response: Box::new(other),
932 });
933 }
934 }
935 }
936
937 if let Some(mut ws) = self.ws.take()
940 && let Err(source) = ws.close(frame).await
941 && !is_ws_closed_error(&source)
942 {
943 return Err(BacktestClientError::WebSocket {
944 action: "closing",
945 source: Box::new(source),
946 });
947 }
948 Ok(())
949 }
950
951 pub async fn close_with_reason(
953 &mut self,
954 timeout: Option<Duration>,
955 code: CloseCode,
956 reason: impl Into<String>,
957 ) -> BacktestClientResult<()> {
958 let frame = CloseFrame {
959 code,
960 reason: Cow::Owned(reason.into()),
961 };
962 self.close_with_frame(timeout, Some(frame)).await
963 }
964
965 pub fn abort(mut self) {
972 let _ws = self.ws.take();
973 }
974
975 async fn next_text(
976 &mut self,
977 timeout: Option<Duration>,
978 ) -> BacktestClientResult<Option<String>> {
979 loop {
980 let request_timeout = self.request_timeout;
981 let timeout = timeout.or(request_timeout);
982
983 let next_fut = self.ws_mut()?.next();
984 let msg = match timeout {
985 Some(duration) => tokio::time::timeout(duration, next_fut)
986 .await
987 .map_err(|_| BacktestClientError::Timeout {
988 action: "receiving",
989 duration,
990 })?,
991 None => next_fut.await,
992 };
993
994 let Some(msg) = msg else {
995 return Ok(None);
996 };
997
998 let msg = match msg {
999 Ok(msg) => msg,
1000 Err(source) => {
1001 return Err(BacktestClientError::WebSocket {
1002 action: "receiving",
1003 source: Box::new(source),
1004 });
1005 }
1006 };
1007
1008 match msg {
1009 Message::Text(text) => {
1010 if self.log_raw {
1011 tracing::debug!("<- raw: {text}");
1012 }
1013 return Ok(Some(text));
1014 }
1015 Message::Binary(bin) => match String::from_utf8(bin) {
1016 Ok(text) => {
1017 if self.log_raw {
1018 tracing::debug!("<- raw(bin): {text}");
1019 }
1020 return Ok(Some(text));
1021 }
1022 Err(err) => {
1023 tracing::warn!("discarding non-utf8 binary message: {err}");
1024 continue;
1025 }
1026 },
1027 Message::Close(frame) => {
1028 let reason = close_reason(frame);
1029 return Err(BacktestClientError::Closed { reason });
1030 }
1031 Message::Ping(_) | Message::Pong(_) => continue,
1032 Message::Frame(_) => continue,
1033 }
1034 }
1035 }
1036}
1037
1038impl std::fmt::Debug for BacktestSession {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 f.debug_struct("BacktestSession")
1041 .field("session_id", &self.session_id)
1042 .field("rpc_endpoint", &self.rpc_endpoint)
1043 .field(
1044 "rpc",
1045 &self
1046 .rpc
1047 .as_ref()
1048 .map(|_| "<RpcClient>")
1049 .unwrap_or("<not set>"),
1050 )
1051 .field("ready_for_continue", &self.ready_for_continue)
1052 .field("request_timeout", &self.request_timeout)
1053 .finish_non_exhaustive()
1054 }
1055}
1056
1057#[derive(Debug)]
1058pub(crate) enum CreateRequestResult {
1059 Single {
1060 session_id: SessionId,
1061 task_id: Option<String>,
1062 },
1063 Parallel {
1064 session_ids: Vec<SessionId>,
1065 task_ids: Vec<Option<String>>,
1066 },
1067}
1068
1069fn align_task_ids(mut task_ids: Vec<Option<String>>, expected_len: usize) -> Vec<Option<String>> {
1072 if task_ids.len() < expected_len {
1073 task_ids.resize(expected_len, None);
1074 } else if task_ids.len() > expected_len {
1075 task_ids.truncate(expected_len);
1076 }
1077 task_ids
1078}
1079
1080impl Drop for BacktestSession {
1081 fn drop(&mut self) {
1082 let Some(ws) = self.ws.take() else {
1083 return;
1084 };
1085
1086 if let Ok(handle) = tokio::runtime::Handle::try_current() {
1087 handle.spawn(async move {
1088 let mut ws = ws;
1089 let _ = ws.close(None).await;
1090 });
1091 }
1092 }
1093}
1094
1095fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
1096 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
1097 endpoint.to_string()
1098 } else {
1099 format!("{}/{}", base, endpoint.trim_start_matches('/'))
1100 }
1101}
1102
1103fn close_reason(frame: Option<CloseFrame<'static>>) -> String {
1104 match frame {
1105 Some(frame) => format!("{:?}: {}", frame.code, frame.reason),
1106 None => "no close frame".to_string(),
1107 }
1108}
1109
1110fn is_reset_without_close(err: &WsError) -> bool {
1111 matches!(
1112 err,
1113 WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
1114 )
1115}
1116
1117fn is_ws_closed_error(err: &WsError) -> bool {
1118 matches!(
1119 err,
1120 WsError::ConnectionClosed
1121 | WsError::AlreadyClosed
1122 | WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
1123 )
1124}
1125
1126fn is_close_ok(err: &BacktestClientError) -> bool {
1127 match err {
1128 BacktestClientError::Closed { .. } => true,
1129 BacktestClientError::WebSocket { source, .. } => is_ws_closed_error(source),
1130 _ => false,
1131 }
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136 use super::*;
1137
1138 #[test]
1139 fn coverage_tracks_slot_and_completion_from_responses() {
1140 let mut coverage = SessionCoverage::default();
1141 coverage.observe_response(&BacktestResponse::SlotNotification(10));
1142 coverage.observe_response(&BacktestResponse::SlotNotification(12));
1143 coverage.observe_response(&BacktestResponse::Completed {
1144 summary: None,
1145 agent_stats: None,
1146 });
1147
1148 assert!(coverage.is_completed());
1149 assert_eq!(coverage.highest_slot_seen(), Some(12));
1150 }
1151
1152 #[test]
1153 fn coverage_validate_end_slot_checks_completion_and_range() {
1154 let mut coverage = SessionCoverage::default();
1155 assert_eq!(
1156 coverage.validate_end_slot(5),
1157 Err(CoverageError::NotCompleted)
1158 );
1159
1160 coverage.mark_completed();
1161 assert_eq!(
1162 coverage.validate_end_slot(5),
1163 Err(CoverageError::NoSlotsObserved)
1164 );
1165
1166 coverage.observe_slot(4);
1167 assert_eq!(
1168 coverage.validate_end_slot(5),
1169 Err(CoverageError::RangeNotReached {
1170 actual_end_slot: 4,
1171 expected_end_slot: 5,
1172 })
1173 );
1174
1175 coverage.observe_slot(6);
1176 assert_eq!(coverage.validate_end_slot(5), Ok(()));
1177 }
1178}