1use std::{collections::VecDeque, sync::Arc, time::Duration};
2
3use simulator_api::{
4 BacktestError, BacktestStatus, ContinueParams, ContinueToParams, CreateBacktestSessionRequest,
5 CreateBacktestSessionRequestV1, DiscoveryBatchEvent, PausedEvent, SessionSummary,
6};
7use solana_address::Address;
8use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
9use thiserror::Error;
10use tokio::sync::watch;
11use tokio_util::sync::CancellationToken;
12
13use super::{
14 ConnectionStatus, ControlEvent, ControlHandle, DEFAULT_DISCONNECT_TIMEOUT_SECS,
15 ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
16 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
17 spawn_action_subscription_manager, spawn_control_manager,
18 spawn_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
19 spawn_transaction_subscription_manager,
20};
21use crate::subscriptions::{
22 AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
23 ReplacementNotification,
24};
25
26#[derive(Debug, Error)]
28pub enum ManagedSessionError {
29 #[error("session create failed: {0}")]
30 Create(String),
31
32 #[error("control channel closed")]
33 ControlClosed,
34
35 #[error("control failed: {0}")]
36 ControlFailed(String),
37
38 #[error("subscription failed: {0}")]
39 SubscriptionFailed(String),
40
41 #[error("cancelled")]
42 Cancelled,
43
44 #[error("control closed while sending continue: {0}")]
45 ContinueSend(String),
46}
47
48#[derive(Debug)]
49pub enum ManagedEvent {
50 ReadyForContinue,
51 Paused(PausedEvent),
54 DiscoveryBatch(DiscoveryBatchEvent),
58 Slot(u64),
59 Status(BacktestStatus),
60 Completed {
61 summary: Option<SessionSummary>,
62 },
63 Error(BacktestError),
64 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
65 AccountDiff(AccountDiffNotification),
66 ActionResult(ActionResultNotification),
67 Diagnostic(DiagnosticNotification),
68 Replacement(Box<ReplacementNotification>),
69}
70
71const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
76
77pub(super) enum DrainOutcome {
79 Complete(Vec<ManagedEvent>),
82 Stalled(Vec<ManagedEvent>),
86}
87
88pub struct ManagedBacktestSession {
94 session_info: SessionInfo,
95 control: Option<ControlHandle>,
96 subscriptions: Vec<SubscriptionHandle>,
97 session_cancel: CancellationToken,
98 post_completion: Option<VecDeque<ManagedEvent>>,
101 post_completion_error: Option<ManagedSessionError>,
105 completion_drain_timeout: Duration,
106 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
109 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
110}
111
112impl ManagedBacktestSession {
113 pub async fn start(
116 url: String,
117 api_key: String,
118 create: CreateBacktestSessionRequest,
119 ) -> Result<Self, ManagedSessionError> {
120 Self::start_with_params(
121 StartSessionParams::builder()
122 .url(url)
123 .api_key(api_key)
124 .create(create)
125 .build(),
126 None,
127 )
128 .await
129 }
130
131 pub async fn start_with_params(
144 params: StartSessionParams,
145 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
146 ) -> Result<Self, ManagedSessionError> {
147 let StartSessionParams {
148 url,
149 api_key,
150 mut create,
151 parent_cancel,
152 subscription_diagnostics,
153 } = params;
154 set_default_disconnect_timeout(&mut create);
155 let session_cancel = parent_cancel.child_token();
156 let mut control = spawn_control_manager(url, api_key, create, session_cancel.clone());
157
158 let session_info = tokio::select! {
159 biased;
160 _ = parent_cancel.cancelled() => {
161 session_cancel.cancel();
162 control.join().await;
163 return Err(ManagedSessionError::Cancelled);
164 }
165 result = control.wait_for_session() => {
166 result.map_err(ManagedSessionError::Create)?
167 }
168 };
169
170 Ok(Self {
171 session_info,
172 control: Some(control),
173 subscriptions: Vec::new(),
174 session_cancel,
175 post_completion: None,
176 post_completion_error: None,
177 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
178 reconnect_coordinator,
179 subscription_diagnostics,
180 })
181 }
182
183 pub fn session_info(&self) -> &SessionInfo {
185 &self.session_info
186 }
187
188 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
192 self.completion_drain_timeout = idle_timeout;
193 }
194
195 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
197 self.subscriptions
198 .push(spawn_transaction_subscription_manager(
199 self.session_info.rpc_endpoint.clone(),
200 program_ids,
201 self.session_cancel.clone(),
202 self.reconnect_coordinator.clone(),
203 self.subscription_diagnostics.clone(),
204 ));
205 }
206
207 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
209 self.subscriptions
210 .push(spawn_account_diff_subscription_manager(
211 self.session_info.rpc_endpoint.clone(),
212 program_ids,
213 self.session_cancel.clone(),
214 self.reconnect_coordinator.clone(),
215 self.subscription_diagnostics.clone(),
216 ));
217 }
218
219 pub fn subscribe_actions(&mut self) {
222 self.subscriptions.push(spawn_action_subscription_manager(
223 self.session_info.rpc_endpoint.clone(),
224 self.session_cancel.clone(),
225 self.reconnect_coordinator.clone(),
226 self.subscription_diagnostics.clone(),
227 ));
228 }
229
230 pub fn subscribe_replacements(&mut self) {
233 self.subscriptions
234 .push(spawn_replacement_subscription_manager(
235 self.session_info.rpc_endpoint.clone(),
236 self.session_cancel.clone(),
237 self.reconnect_coordinator.clone(),
238 self.subscription_diagnostics.clone(),
239 ));
240 }
241
242 pub fn subscribe_diagnostics(&mut self) {
245 self.subscriptions
246 .push(spawn_diagnostic_subscription_manager(
247 self.session_info.rpc_endpoint.clone(),
248 self.session_cancel.clone(),
249 self.reconnect_coordinator.clone(),
250 self.subscription_diagnostics.clone(),
251 ));
252 }
253
254 async fn drain_until_subscriptions_complete(
259 &mut self,
260 idle_timeout: std::time::Duration,
261 ) -> DrainOutcome {
262 drain_subscriptions_until_complete(
263 &mut self.subscriptions,
264 &self.session_cancel,
265 idle_timeout,
266 )
267 .await
268 }
269
270 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
275 if let Some(buffered) = self.post_completion.as_mut() {
278 if let Some(event) = buffered.pop_front() {
279 return Ok(event);
280 }
281 return Err(self
284 .post_completion_error
285 .take()
286 .unwrap_or(ManagedSessionError::ControlClosed));
287 }
288
289 tokio::task::coop::consume_budget().await;
292
293 let event = {
296 let cancel = self.session_cancel.clone();
297 let control = self
298 .control
299 .as_mut()
300 .ok_or(ManagedSessionError::ControlClosed)?;
301 let subscriptions = &mut self.subscriptions;
302 match control.events.try_recv() {
306 Ok(event) => ManagedEvent::from(event),
307 Err(_) => {
308 if let Some(event) = try_next_subscription_event(subscriptions) {
309 return Ok(event);
310 }
311 tokio::select! {
312 biased;
313 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
314 event = control.events.recv() => {
315 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
316 }
317 event = wait_any_subscription_event(subscriptions) => event,
318 }
319 }
320 }
321 };
322
323 let ManagedEvent::Completed { summary } = event else {
325 return Ok(event);
326 };
327
328 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
331 .drain_until_subscriptions_complete(self.completion_drain_timeout)
332 .await
333 {
334 DrainOutcome::Complete(events) => {
335 (events.into(), Ok(ManagedEvent::Completed { summary }))
336 }
337 DrainOutcome::Stalled(events) => (
342 events.into(),
343 Err(ManagedSessionError::SubscriptionFailed(
344 "completion drain stalled: subscriptions did not deliver their \
345 end-of-stream terminals; the captured stream is incomplete"
346 .to_string(),
347 )),
348 ),
349 };
350 match terminal {
351 Ok(completed) => buffered.push_back(completed),
352 Err(err) => self.post_completion_error = Some(err),
353 }
354 let first = buffered.pop_front();
355 self.post_completion = Some(buffered);
356 match first {
357 Some(event) => Ok(event),
358 None => Err(self
360 .post_completion_error
361 .take()
362 .unwrap_or(ManagedSessionError::ControlClosed)),
363 }
364 }
365
366 pub async fn send_continue(
373 &mut self,
374 params: ContinueParams,
375 ) -> Result<(), ManagedSessionError> {
376 self.wait_all_up().await?;
377 self.control_mut()?
378 .send_continue(params)
379 .await
380 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
381 }
382
383 pub async fn send_continue_to(
391 &mut self,
392 params: ContinueToParams,
393 ) -> Result<(), ManagedSessionError> {
394 self.wait_all_up().await?;
395 self.control_mut()?
396 .send_continue_to(params)
397 .await
398 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
399 }
400
401 pub async fn shutdown(mut self) {
403 self.session_cancel.cancel();
404 if let Some(control) = self.control.take() {
405 control.join().await;
406 }
407 for sub in std::mem::take(&mut self.subscriptions) {
408 drop(sub.notifications);
410 let _ = sub.join.await;
411 }
412 }
413
414 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
415 self.control
416 .as_mut()
417 .ok_or(ManagedSessionError::ControlClosed)
418 }
419
420 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
421 let control = self
422 .control
423 .as_ref()
424 .ok_or(ManagedSessionError::ControlClosed)?
425 .status
426 .clone();
427 let subscriptions = self
428 .subscriptions
429 .iter()
430 .map(|s| s.status.clone())
431 .collect();
432 wait_connections_up(control, subscriptions, &self.session_cancel).await
433 }
434}
435
436fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
441 let params = match create {
442 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
443 parallel: true, ..
444 }) => return,
445 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
446 | CreateBacktestSessionRequest::V0(request) => request,
447 };
448 params
449 .disconnect_timeout_secs
450 .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
451}
452
453pub(super) async fn wait_connections_up(
457 mut control: watch::Receiver<ConnectionStatus>,
458 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
459 cancel: &CancellationToken,
460) -> Result<(), ManagedSessionError> {
461 loop {
462 let control_status = control.borrow().clone();
463 if let ConnectionStatus::Failed(why) = &control_status {
464 return Err(ManagedSessionError::ControlFailed(why.clone()));
465 }
466
467 let mut all_subscriptions_up = true;
468 for subscription in &subscriptions {
469 match &*subscription.borrow() {
470 ConnectionStatus::Failed(why) => {
471 return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
472 }
473 ConnectionStatus::Up => {}
474 _ => all_subscriptions_up = false,
475 }
476 }
477
478 if control_status == ConnectionStatus::Up && all_subscriptions_up {
479 return Ok(());
480 }
481
482 tokio::select! {
483 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
484 _ = control.changed() => {}
485 _ = wait_any_subscription_change(&mut subscriptions) => {}
486 }
487 }
488}
489
490pub(super) async fn drain_subscriptions_until_complete(
505 subscriptions: &mut [SubscriptionHandle],
506 cancel: &CancellationToken,
507 idle_timeout: std::time::Duration,
508) -> DrainOutcome {
509 let mut events = Vec::new();
510 if subscriptions.is_empty() {
511 return DrainOutcome::Complete(events);
512 }
513 loop {
514 while let Some(event) = try_next_subscription_event(subscriptions) {
515 events.push(event);
516 }
517 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
518 let any_failed = subscriptions
519 .iter()
520 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
521 return if any_failed {
522 DrainOutcome::Stalled(events)
523 } else {
524 DrainOutcome::Complete(events)
525 };
526 }
527 tokio::select! {
528 biased;
529 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
531 _ = tokio::time::sleep(idle_timeout) => {
536 let any_up = subscriptions.iter().any(|s| {
537 !s.notifications.is_closed()
538 && matches!(*s.status.borrow(), ConnectionStatus::Up)
539 });
540 if any_up {
541 return DrainOutcome::Stalled(events);
542 }
543 }
544 received = recv_any_open_subscription(subscriptions) => {
545 if let Some(event) = received {
547 events.push(event);
548 }
549 }
550 }
551 }
552}
553
554impl Drop for ManagedBacktestSession {
555 fn drop(&mut self) {
556 self.session_cancel.cancel();
557 }
558}
559
560pub(super) async fn wait_any_subscription_change(
561 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
562) {
563 if subscriptions.is_empty() {
564 std::future::pending::<()>().await;
565 return;
566 }
567 let _ =
568 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
569}
570
571pub(super) async fn wait_any_subscription_event(
572 subscriptions: &mut [SubscriptionHandle],
573) -> ManagedEvent {
574 loop {
575 if let Some(event) = try_next_subscription_event(subscriptions) {
576 return event;
577 }
578
579 let futures: Vec<_> = subscriptions
580 .iter_mut()
581 .filter(|s| !s.notifications.is_closed())
582 .map(|s| Box::pin(s.notifications.recv()))
583 .collect();
584
585 if futures.is_empty() {
586 std::future::pending::<()>().await;
587 }
588
589 let (notification, _, _) = futures::future::select_all(futures).await;
590 if let Some(notification) = notification {
591 return notification.into();
592 }
593 }
594}
595
596pub(super) async fn recv_any_open_subscription(
601 subscriptions: &mut [SubscriptionHandle],
602) -> Option<ManagedEvent> {
603 let futures: Vec<_> = subscriptions
604 .iter_mut()
605 .filter(|s| !s.notifications.is_closed())
606 .map(|s| Box::pin(s.notifications.recv()))
607 .collect();
608
609 if futures.is_empty() {
610 return None;
611 }
612
613 let (notification, _, _) = futures::future::select_all(futures).await;
614 notification.map(Into::into)
615}
616
617pub(super) fn try_next_subscription_event(
618 subscriptions: &mut [SubscriptionHandle],
619) -> Option<ManagedEvent> {
620 for subscription in subscriptions {
621 if let Ok(notification) = subscription.notifications.try_recv() {
622 return Some(notification.into());
623 }
624 }
625 None
626}
627
628impl From<ControlEvent> for ManagedEvent {
629 fn from(event: ControlEvent) -> Self {
630 match event {
631 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
632 ControlEvent::Paused(event) => Self::Paused(event),
633 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
634 ControlEvent::Slot(slot) => Self::Slot(slot),
635 ControlEvent::Status(status) => Self::Status(status),
636 ControlEvent::Completed { summary } => Self::Completed { summary },
637 ControlEvent::Error(error) => Self::Error(error),
638 }
639 }
640}
641
642impl From<SubscriptionNotification> for ManagedEvent {
643 fn from(notification: SubscriptionNotification) -> Self {
644 match notification {
645 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
646 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
647 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
648 SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
649 SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
650 }
651 }
652}
653
654#[cfg(test)]
655mod tests {
656 use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};
657
658 use super::*;
659 use crate::{CreateSession, managed::RECONNECT_MAX_TOTAL};
660
661 fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
662 CreateSession::builder()
663 .start_slot(1)
664 .slot_count(1)
665 .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
666 .build()
667 .into_params()
668 .expect("valid create params")
669 }
670
671 #[test]
672 fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
673 let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
674 (
675 "v0 unset",
676 CreateBacktestSessionRequest::V0(params(None)),
677 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
678 ),
679 (
680 "v0 explicit",
681 CreateBacktestSessionRequest::V0(params(Some(42))),
682 Some(42),
683 ),
684 (
685 "v1 single unset",
686 CreateBacktestSessionRequestV1 {
687 request: params(None),
688 parallel: false,
689 }
690 .into(),
691 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
692 ),
693 (
694 "v1 parallel unset keeps the server's parallel default",
695 CreateBacktestSessionRequestV1 {
696 request: params(None),
697 parallel: true,
698 }
699 .into(),
700 None,
701 ),
702 ];
703
704 for (name, mut create, expected) in cases {
705 set_default_disconnect_timeout(&mut create);
706 let (request, _) = create.into_request_and_parallel();
707 assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
708 }
709 }
710
711 #[test]
712 fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
713 assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
714 const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
715 }
716}