1use std::{collections::VecDeque, sync::Arc, time::Duration};
2
3use futures::FutureExt;
4use simulator_api::{
5 BacktestError, BacktestStatus, ContinueParams, ContinueToParams, CreateBacktestSessionRequest,
6 CreateBacktestSessionRequestV1, DiscoveryBatchEvent, PausedEvent, SessionSummary,
7};
8use solana_address::Address;
9use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
10use thiserror::Error;
11use tokio::sync::{mpsc, watch};
12use tokio_util::sync::CancellationToken;
13
14use super::{
15 ConnectionStatus, ControlEvent, ControlHandle, DEFAULT_DISCONNECT_TIMEOUT_SECS,
16 ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
17 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
18 spawn_action_subscription_manager, spawn_control_manager,
19 spawn_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
20 spawn_transaction_subscription_manager,
21};
22use crate::subscriptions::{
23 AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
24 ReplacementNotification,
25};
26
27#[derive(Debug, Error)]
29pub enum ManagedSessionError {
30 #[error("session create failed: {0}")]
31 Create(String),
32
33 #[error("control channel closed")]
34 ControlClosed,
35
36 #[error("control failed: {0}")]
37 ControlFailed(String),
38
39 #[error("subscription failed: {0}")]
40 SubscriptionFailed(String),
41
42 #[error("cancelled")]
43 Cancelled,
44
45 #[error("control closed while sending continue: {0}")]
46 ContinueSend(String),
47}
48
49#[derive(Debug)]
50pub enum ManagedEvent {
51 ReadyForContinue,
52 Paused(PausedEvent),
55 DiscoveryBatch(DiscoveryBatchEvent),
59 Slot(u64),
60 Status(BacktestStatus),
61 Completed {
62 summary: Option<SessionSummary>,
63 },
64 Error(BacktestError),
65 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
66 AccountDiff(AccountDiffNotification),
67 ActionResult(ActionResultNotification),
68 Diagnostic(DiagnosticNotification),
69 Replacement(Box<ReplacementNotification>),
70}
71
72const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
77
78pub(super) enum DrainOutcome {
80 Complete(Vec<ManagedEvent>),
83 Stalled(Vec<ManagedEvent>),
87}
88
89pub struct ManagedBacktestSession {
95 session_info: SessionInfo,
96 control: Option<ControlHandle>,
97 subscriptions: Vec<SubscriptionHandle>,
98 session_cancel: CancellationToken,
99 post_completion: Option<VecDeque<ManagedEvent>>,
102 post_completion_error: Option<ManagedSessionError>,
106 completion_drain_timeout: Duration,
107 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
110 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
111}
112
113impl ManagedBacktestSession {
114 pub async fn start(
117 url: String,
118 api_key: String,
119 create: CreateBacktestSessionRequest,
120 ) -> Result<Self, ManagedSessionError> {
121 Self::start_with_params(
122 StartSessionParams::builder()
123 .url(url)
124 .api_key(api_key)
125 .create(create)
126 .build(),
127 None,
128 )
129 .await
130 }
131
132 pub async fn start_with_params(
145 params: StartSessionParams,
146 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
147 ) -> Result<Self, ManagedSessionError> {
148 let StartSessionParams {
149 url,
150 api_key,
151 extra_headers,
152 mut create,
153 parent_cancel,
154 subscription_diagnostics,
155 } = params;
156 set_default_disconnect_timeout(&mut create);
157 let session_cancel = parent_cancel.child_token();
158 let mut control =
159 spawn_control_manager(url, api_key, extra_headers, create, session_cancel.clone());
160
161 let session_info = tokio::select! {
162 biased;
163 _ = parent_cancel.cancelled() => {
164 session_cancel.cancel();
165 control.join().await;
166 return Err(ManagedSessionError::Cancelled);
167 }
168 result = control.wait_for_session() => {
169 result.map_err(ManagedSessionError::Create)?
170 }
171 };
172
173 Ok(Self {
174 session_info,
175 control: Some(control),
176 subscriptions: Vec::new(),
177 session_cancel,
178 post_completion: None,
179 post_completion_error: None,
180 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
181 reconnect_coordinator,
182 subscription_diagnostics,
183 })
184 }
185
186 pub fn session_info(&self) -> &SessionInfo {
188 &self.session_info
189 }
190
191 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
195 self.completion_drain_timeout = idle_timeout;
196 }
197
198 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
200 self.subscriptions
201 .push(spawn_transaction_subscription_manager(
202 self.session_info.rpc_endpoint.clone(),
203 program_ids,
204 self.session_cancel.clone(),
205 self.reconnect_coordinator.clone(),
206 self.subscription_diagnostics.clone(),
207 ));
208 }
209
210 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
212 self.subscriptions
213 .push(spawn_account_diff_subscription_manager(
214 self.session_info.rpc_endpoint.clone(),
215 program_ids,
216 self.session_cancel.clone(),
217 self.reconnect_coordinator.clone(),
218 self.subscription_diagnostics.clone(),
219 ));
220 }
221
222 pub fn subscribe_actions(&mut self) {
225 self.subscriptions.push(spawn_action_subscription_manager(
226 self.session_info.rpc_endpoint.clone(),
227 self.session_cancel.clone(),
228 self.reconnect_coordinator.clone(),
229 self.subscription_diagnostics.clone(),
230 ));
231 }
232
233 pub fn subscribe_replacements(&mut self) {
236 self.subscriptions
237 .push(spawn_replacement_subscription_manager(
238 self.session_info.rpc_endpoint.clone(),
239 self.session_cancel.clone(),
240 self.reconnect_coordinator.clone(),
241 self.subscription_diagnostics.clone(),
242 ));
243 }
244
245 pub fn subscribe_diagnostics(&mut self) {
248 self.subscriptions
249 .push(spawn_diagnostic_subscription_manager(
250 self.session_info.rpc_endpoint.clone(),
251 self.session_cancel.clone(),
252 self.reconnect_coordinator.clone(),
253 self.subscription_diagnostics.clone(),
254 ));
255 }
256
257 async fn drain_until_subscriptions_complete(
262 &mut self,
263 idle_timeout: std::time::Duration,
264 ) -> DrainOutcome {
265 drain_subscriptions_until_complete(
266 &mut self.subscriptions,
267 &self.session_cancel,
268 idle_timeout,
269 )
270 .await
271 }
272
273 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
278 if let Some(buffered) = self.post_completion.as_mut() {
281 if let Some(event) = buffered.pop_front() {
282 return Ok(event);
283 }
284 return Err(self
287 .post_completion_error
288 .take()
289 .unwrap_or(ManagedSessionError::ControlClosed));
290 }
291
292 tokio::task::coop::consume_budget().await;
295
296 let event = {
299 let cancel = self.session_cancel.clone();
300 let control = self
301 .control
302 .as_mut()
303 .ok_or(ManagedSessionError::ControlClosed)?;
304 let subscriptions = &mut self.subscriptions;
305 match recv_queued(&mut control.events) {
309 Some(event) => ManagedEvent::from(event),
310 None => {
311 if let Some(event) = try_next_subscription_event(subscriptions) {
312 return Ok(event);
313 }
314 tokio::select! {
315 biased;
316 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
317 event = control.events.recv() => {
318 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
319 }
320 event = wait_any_subscription_event(subscriptions) => event,
321 }
322 }
323 }
324 };
325
326 let ManagedEvent::Completed { summary } = event else {
328 return Ok(event);
329 };
330
331 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
334 .drain_until_subscriptions_complete(self.completion_drain_timeout)
335 .await
336 {
337 DrainOutcome::Complete(events) => {
338 (events.into(), Ok(ManagedEvent::Completed { summary }))
339 }
340 DrainOutcome::Stalled(events) => (
345 events.into(),
346 Err(ManagedSessionError::SubscriptionFailed(
347 "completion drain stalled: subscriptions did not deliver their \
348 end-of-stream terminals; the captured stream is incomplete"
349 .to_string(),
350 )),
351 ),
352 };
353 match terminal {
354 Ok(completed) => buffered.push_back(completed),
355 Err(err) => self.post_completion_error = Some(err),
356 }
357 let first = buffered.pop_front();
358 self.post_completion = Some(buffered);
359 match first {
360 Some(event) => Ok(event),
361 None => Err(self
363 .post_completion_error
364 .take()
365 .unwrap_or(ManagedSessionError::ControlClosed)),
366 }
367 }
368
369 pub async fn send_continue(
376 &mut self,
377 params: ContinueParams,
378 ) -> Result<(), ManagedSessionError> {
379 self.wait_all_up().await?;
380 self.control_mut()?
381 .send_continue(params)
382 .await
383 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
384 }
385
386 pub async fn send_continue_to(
394 &mut self,
395 params: ContinueToParams,
396 ) -> Result<(), ManagedSessionError> {
397 self.wait_all_up().await?;
398 self.control_mut()?
399 .send_continue_to(params)
400 .await
401 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
402 }
403
404 pub async fn shutdown(mut self) {
406 self.session_cancel.cancel();
407 if let Some(control) = self.control.take() {
408 control.join().await;
409 }
410 for sub in std::mem::take(&mut self.subscriptions) {
411 drop(sub.notifications);
413 let _ = sub.join.await;
414 }
415 }
416
417 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
418 self.control
419 .as_mut()
420 .ok_or(ManagedSessionError::ControlClosed)
421 }
422
423 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
424 let control = self
425 .control
426 .as_ref()
427 .ok_or(ManagedSessionError::ControlClosed)?
428 .status
429 .clone();
430 let subscriptions = self
431 .subscriptions
432 .iter()
433 .map(|s| s.status.clone())
434 .collect();
435 wait_connections_up(control, subscriptions, &self.session_cancel).await
436 }
437}
438
439fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
444 let params = match create {
445 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
446 parallel: true, ..
447 }) => return,
448 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
449 | CreateBacktestSessionRequest::V0(request) => request,
450 };
451 params
452 .disconnect_timeout_secs
453 .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
454}
455
456pub(super) async fn wait_connections_up(
460 mut control: watch::Receiver<ConnectionStatus>,
461 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
462 cancel: &CancellationToken,
463) -> Result<(), ManagedSessionError> {
464 loop {
465 let control_status = control.borrow().clone();
466 if let ConnectionStatus::Failed(why) = &control_status {
467 return Err(ManagedSessionError::ControlFailed(why.clone()));
468 }
469
470 let mut all_subscriptions_up = true;
471 for subscription in &subscriptions {
472 match &*subscription.borrow() {
473 ConnectionStatus::Failed(why) => {
474 return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
475 }
476 ConnectionStatus::Up => {}
477 _ => all_subscriptions_up = false,
478 }
479 }
480
481 if control_status == ConnectionStatus::Up && all_subscriptions_up {
482 return Ok(());
483 }
484
485 tokio::select! {
486 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
487 _ = control.changed() => {}
488 _ = wait_any_subscription_change(&mut subscriptions) => {}
489 }
490 }
491}
492
493pub(super) async fn drain_subscriptions_until_complete(
508 subscriptions: &mut [SubscriptionHandle],
509 cancel: &CancellationToken,
510 idle_timeout: std::time::Duration,
511) -> DrainOutcome {
512 let mut events = Vec::new();
513 if subscriptions.is_empty() {
514 return DrainOutcome::Complete(events);
515 }
516 loop {
517 while let Some(event) = try_next_subscription_event(subscriptions) {
518 events.push(event);
519 }
520 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
521 let any_failed = subscriptions
522 .iter()
523 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
524 return if any_failed {
525 DrainOutcome::Stalled(events)
526 } else {
527 DrainOutcome::Complete(events)
528 };
529 }
530 tokio::select! {
531 biased;
532 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
534 _ = tokio::time::sleep(idle_timeout) => {
539 let any_up = subscriptions.iter().any(|s| {
540 !s.notifications.is_closed()
541 && matches!(*s.status.borrow(), ConnectionStatus::Up)
542 });
543 if any_up {
544 return DrainOutcome::Stalled(events);
545 }
546 }
547 received = recv_any_open_subscription(subscriptions) => {
548 if let Some(event) = received {
550 events.push(event);
551 }
552 }
553 }
554 }
555}
556
557impl Drop for ManagedBacktestSession {
558 fn drop(&mut self) {
559 self.session_cancel.cancel();
560 }
561}
562
563pub(super) async fn wait_any_subscription_change(
564 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
565) {
566 if subscriptions.is_empty() {
567 std::future::pending::<()>().await;
568 return;
569 }
570 let _ =
571 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
572}
573
574pub(super) async fn wait_any_subscription_event(
575 subscriptions: &mut [SubscriptionHandle],
576) -> ManagedEvent {
577 loop {
578 if let Some(event) = try_next_subscription_event(subscriptions) {
579 return event;
580 }
581
582 let futures: Vec<_> = subscriptions
583 .iter_mut()
584 .filter(|s| !s.notifications.is_closed())
585 .map(|s| Box::pin(s.notifications.recv()))
586 .collect();
587
588 if futures.is_empty() {
589 std::future::pending::<()>().await;
590 }
591
592 let (notification, _, _) = futures::future::select_all(futures).await;
593 if let Some(notification) = notification {
594 return notification.into();
595 }
596 }
597}
598
599pub(super) async fn recv_any_open_subscription(
604 subscriptions: &mut [SubscriptionHandle],
605) -> Option<ManagedEvent> {
606 let futures: Vec<_> = subscriptions
607 .iter_mut()
608 .filter(|s| !s.notifications.is_closed())
609 .map(|s| Box::pin(s.notifications.recv()))
610 .collect();
611
612 if futures.is_empty() {
613 return None;
614 }
615
616 let (notification, _, _) = futures::future::select_all(futures).await;
617 notification.map(Into::into)
618}
619
620pub(super) fn try_next_subscription_event(
621 subscriptions: &mut [SubscriptionHandle],
622) -> Option<ManagedEvent> {
623 for subscription in subscriptions {
624 if let Some(notification) = recv_queued(&mut subscription.notifications) {
625 return Some(notification.into());
626 }
627 }
628 None
629}
630
631fn recv_queued<T>(receiver: &mut mpsc::Receiver<T>) -> Option<T> {
635 tokio::task::coop::unconstrained(receiver.recv())
636 .now_or_never()
637 .flatten()
638}
639
640impl From<ControlEvent> for ManagedEvent {
641 fn from(event: ControlEvent) -> Self {
642 match event {
643 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
644 ControlEvent::Paused(event) => Self::Paused(event),
645 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
646 ControlEvent::Slot(slot) => Self::Slot(slot),
647 ControlEvent::Status(status) => Self::Status(status),
648 ControlEvent::Completed { summary } => Self::Completed { summary },
649 ControlEvent::Error(error) => Self::Error(error),
650 }
651 }
652}
653
654impl From<SubscriptionNotification> for ManagedEvent {
655 fn from(notification: SubscriptionNotification) -> Self {
656 match notification {
657 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
658 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
659 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
660 SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
661 SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
662 }
663 }
664}
665
666#[cfg(test)]
667mod tests {
668 use std::{
669 future::Future,
670 pin::Pin,
671 sync::Mutex,
672 task::{Poll, Waker},
673 };
674
675 use futures::{StreamExt, stream::FuturesUnordered};
676 use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};
677
678 use super::*;
679 use crate::{
680 CreateSession,
681 managed::RECONNECT_MAX_TOTAL,
682 subscriptions::{DiagnosticContext, DiagnosticNotification},
683 };
684
685 fn notification() -> SubscriptionNotification {
686 SubscriptionNotification::Diagnostic(DiagnosticNotification {
687 context: DiagnosticContext { slot: 0 },
688 slot: 0,
689 probe_index: 0,
690 label: None,
691 market: String::new(),
692 usd_value: 0,
693 router_slot: None,
694 results: None,
695 account_hashes: Vec::new(),
696 err: None,
697 })
698 }
699
700 #[test]
703 fn subscription_reads_keep_a_sibling_wakeup_on_the_block_on_thread() {
704 const SENDERS: usize = 4;
705 const ROUNDS: usize = 2_000;
706
707 let runtime = tokio::runtime::Builder::new_multi_thread()
708 .enable_all()
709 .build()
710 .unwrap();
711 let (sender, notifications) = mpsc::channel(1_024);
712 let (_status_tx, status) = watch::channel(ConnectionStatus::Up);
713 let mut subscriptions = vec![SubscriptionHandle {
714 status,
715 notifications,
716 join: runtime.spawn(async {}),
717 }];
718 for _ in 0..SENDERS {
720 let sender = sender.clone();
721 std::thread::spawn(move || {
722 while sender.blocking_send(notification()).is_ok() {
723 std::thread::sleep(Duration::from_micros(20));
724 }
725 });
726 }
727
728 let (done_tx, done) = std::sync::mpsc::channel();
729 std::thread::spawn(move || {
730 let sibling = Arc::new(Mutex::new(None::<Waker>));
731 let driver = {
732 let sibling = sibling.clone();
733 async move {
734 for _ in 0..ROUNDS {
735 while try_next_subscription_event(&mut subscriptions).is_some() {}
736 if let Some(waker) = sibling.lock().unwrap().as_ref() {
737 waker.wake_by_ref();
738 }
739 while try_next_subscription_event(&mut subscriptions).is_none() {}
741 wait_any_subscription_event(&mut subscriptions).await;
742 }
743 }
744 };
745 let sibling = std::future::poll_fn(move |cx| {
746 *sibling.lock().unwrap() = Some(cx.waker().clone());
747 Poll::<()>::Pending
748 });
749 let idle = std::future::pending::<()>();
752 let mut sessions: FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>> =
753 FuturesUnordered::new();
754 sessions.push(Box::pin(driver));
755 sessions.push(Box::pin(sibling));
756 sessions.push(Box::pin(idle));
757 runtime.block_on(sessions.next());
758 let _ = done_tx.send(());
759 });
760
761 assert!(
762 done.recv_timeout(Duration::from_secs(30)).is_ok(),
763 "the sessions stopped: a subscription read consumed the block_on thread's wakeup"
764 );
765 }
766
767 fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
768 CreateSession::builder()
769 .start_slot(1)
770 .slot_count(1)
771 .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
772 .build()
773 .into_params()
774 .expect("valid create params")
775 }
776
777 #[test]
778 fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
779 let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
780 (
781 "v0 unset",
782 CreateBacktestSessionRequest::V0(params(None)),
783 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
784 ),
785 (
786 "v0 explicit",
787 CreateBacktestSessionRequest::V0(params(Some(42))),
788 Some(42),
789 ),
790 (
791 "v1 single unset",
792 CreateBacktestSessionRequestV1 {
793 request: params(None),
794 parallel: false,
795 name: None,
796 create_token: None,
797 }
798 .into(),
799 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
800 ),
801 (
802 "v1 parallel unset keeps the server's parallel default",
803 CreateBacktestSessionRequestV1 {
804 request: params(None),
805 parallel: true,
806 name: None,
807 create_token: None,
808 }
809 .into(),
810 None,
811 ),
812 ];
813
814 for (name, mut create, expected) in cases {
815 set_default_disconnect_timeout(&mut create);
816 let (request, _) = create.into_request_and_parallel();
817 assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
818 }
819 }
820
821 #[test]
822 fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
823 assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
824 const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
825 }
826}