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_transaction_subscription_manager,
19};
20use crate::subscriptions::{AccountDiffNotification, ActionResultNotification};
21
22#[derive(Debug, Error)]
24pub enum ManagedSessionError {
25 #[error("session create failed: {0}")]
26 Create(String),
27
28 #[error("control channel closed")]
29 ControlClosed,
30
31 #[error("control failed: {0}")]
32 ControlFailed(String),
33
34 #[error("subscription failed: {0}")]
35 SubscriptionFailed(String),
36
37 #[error("cancelled")]
38 Cancelled,
39
40 #[error("control closed while sending continue: {0}")]
41 ContinueSend(String),
42}
43
44#[derive(Debug)]
45pub enum ManagedEvent {
46 ReadyForContinue,
47 Paused(PausedEvent),
50 DiscoveryBatch(DiscoveryBatchEvent),
54 Slot(u64),
55 Status(BacktestStatus),
56 Completed {
57 summary: Option<SessionSummary>,
58 },
59 Error(BacktestError),
60 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
61 AccountDiff(AccountDiffNotification),
62 ActionResult(ActionResultNotification),
63}
64
65const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
70
71pub(super) enum DrainOutcome {
73 Complete(Vec<ManagedEvent>),
76 Stalled(Vec<ManagedEvent>),
80}
81
82pub struct ManagedBacktestSession {
88 session_info: SessionInfo,
89 control: Option<ControlHandle>,
90 subscriptions: Vec<SubscriptionHandle>,
91 session_cancel: CancellationToken,
92 post_completion: Option<VecDeque<ManagedEvent>>,
95 post_completion_error: Option<ManagedSessionError>,
99 completion_drain_timeout: Duration,
100 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
103 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
104}
105
106impl ManagedBacktestSession {
107 pub async fn start(
110 url: String,
111 api_key: String,
112 create: CreateBacktestSessionRequest,
113 ) -> Result<Self, ManagedSessionError> {
114 Self::start_with_params(
115 StartSessionParams::builder()
116 .url(url)
117 .api_key(api_key)
118 .create(create)
119 .build(),
120 None,
121 )
122 .await
123 }
124
125 pub async fn start_with_params(
138 params: StartSessionParams,
139 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
140 ) -> Result<Self, ManagedSessionError> {
141 let StartSessionParams {
142 url,
143 api_key,
144 mut create,
145 parent_cancel,
146 subscription_diagnostics,
147 } = params;
148 set_default_disconnect_timeout(&mut create);
149 let session_cancel = parent_cancel.child_token();
150 let mut control = spawn_control_manager(url, api_key, create, session_cancel.clone());
151
152 let session_info = tokio::select! {
153 biased;
154 _ = parent_cancel.cancelled() => {
155 session_cancel.cancel();
156 control.join().await;
157 return Err(ManagedSessionError::Cancelled);
158 }
159 result = control.wait_for_session() => {
160 result.map_err(ManagedSessionError::Create)?
161 }
162 };
163
164 Ok(Self {
165 session_info,
166 control: Some(control),
167 subscriptions: Vec::new(),
168 session_cancel,
169 post_completion: None,
170 post_completion_error: None,
171 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
172 reconnect_coordinator,
173 subscription_diagnostics,
174 })
175 }
176
177 pub fn session_info(&self) -> &SessionInfo {
179 &self.session_info
180 }
181
182 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
186 self.completion_drain_timeout = idle_timeout;
187 }
188
189 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
191 self.subscriptions
192 .push(spawn_transaction_subscription_manager(
193 self.session_info.rpc_endpoint.clone(),
194 program_ids,
195 self.session_cancel.clone(),
196 self.reconnect_coordinator.clone(),
197 self.subscription_diagnostics.clone(),
198 ));
199 }
200
201 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
203 self.subscriptions
204 .push(spawn_account_diff_subscription_manager(
205 self.session_info.rpc_endpoint.clone(),
206 program_ids,
207 self.session_cancel.clone(),
208 self.reconnect_coordinator.clone(),
209 self.subscription_diagnostics.clone(),
210 ));
211 }
212
213 pub fn subscribe_actions(&mut self) {
216 self.subscriptions.push(spawn_action_subscription_manager(
217 self.session_info.rpc_endpoint.clone(),
218 self.session_cancel.clone(),
219 self.reconnect_coordinator.clone(),
220 self.subscription_diagnostics.clone(),
221 ));
222 }
223
224 async fn drain_until_subscriptions_complete(
229 &mut self,
230 idle_timeout: std::time::Duration,
231 ) -> DrainOutcome {
232 drain_subscriptions_until_complete(
233 &mut self.subscriptions,
234 &self.session_cancel,
235 idle_timeout,
236 )
237 .await
238 }
239
240 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
245 if let Some(buffered) = self.post_completion.as_mut() {
248 if let Some(event) = buffered.pop_front() {
249 return Ok(event);
250 }
251 return Err(self
254 .post_completion_error
255 .take()
256 .unwrap_or(ManagedSessionError::ControlClosed));
257 }
258
259 if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
260 return Ok(event);
261 }
262
263 let event = {
266 let cancel = self.session_cancel.clone();
267 let control = self
268 .control
269 .as_mut()
270 .ok_or(ManagedSessionError::ControlClosed)?;
271 let subscriptions = &mut self.subscriptions;
272 tokio::select! {
273 biased;
274 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
275 event = control.events.recv() => {
276 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
277 }
278 event = wait_any_subscription_event(subscriptions) => event,
279 }
280 };
281
282 let ManagedEvent::Completed { summary } = event else {
284 return Ok(event);
285 };
286
287 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
290 .drain_until_subscriptions_complete(self.completion_drain_timeout)
291 .await
292 {
293 DrainOutcome::Complete(events) => {
294 (events.into(), Ok(ManagedEvent::Completed { summary }))
295 }
296 DrainOutcome::Stalled(events) => (
301 events.into(),
302 Err(ManagedSessionError::SubscriptionFailed(
303 "completion drain stalled: subscriptions did not deliver their \
304 end-of-stream terminals; the captured stream is incomplete"
305 .to_string(),
306 )),
307 ),
308 };
309 match terminal {
310 Ok(completed) => buffered.push_back(completed),
311 Err(err) => self.post_completion_error = Some(err),
312 }
313 let first = buffered.pop_front();
314 self.post_completion = Some(buffered);
315 match first {
316 Some(event) => Ok(event),
317 None => Err(self
319 .post_completion_error
320 .take()
321 .unwrap_or(ManagedSessionError::ControlClosed)),
322 }
323 }
324
325 pub async fn send_continue(
332 &mut self,
333 params: ContinueParams,
334 ) -> Result<(), ManagedSessionError> {
335 self.wait_all_up().await?;
336 self.control_mut()?
337 .send_continue(params)
338 .await
339 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
340 }
341
342 pub async fn send_continue_to(
350 &mut self,
351 params: ContinueToParams,
352 ) -> Result<(), ManagedSessionError> {
353 self.wait_all_up().await?;
354 self.control_mut()?
355 .send_continue_to(params)
356 .await
357 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
358 }
359
360 pub async fn shutdown(mut self) {
362 self.session_cancel.cancel();
363 if let Some(control) = self.control.take() {
364 control.join().await;
365 }
366 for sub in std::mem::take(&mut self.subscriptions) {
367 let _ = sub.join.await;
368 }
369 }
370
371 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
372 self.control
373 .as_mut()
374 .ok_or(ManagedSessionError::ControlClosed)
375 }
376
377 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
378 let control = self
379 .control
380 .as_ref()
381 .ok_or(ManagedSessionError::ControlClosed)?
382 .status
383 .clone();
384 let subscriptions = self
385 .subscriptions
386 .iter()
387 .map(|s| s.status.clone())
388 .collect();
389 wait_connections_up(control, subscriptions, &self.session_cancel).await
390 }
391}
392
393fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
398 let params = match create {
399 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
400 parallel: true, ..
401 }) => return,
402 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
403 | CreateBacktestSessionRequest::V0(request) => request,
404 };
405 params
406 .disconnect_timeout_secs
407 .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
408}
409
410pub(super) async fn wait_connections_up(
414 mut control: watch::Receiver<ConnectionStatus>,
415 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
416 cancel: &CancellationToken,
417) -> Result<(), ManagedSessionError> {
418 loop {
419 let control_status = control.borrow().clone();
420 if let ConnectionStatus::Failed(why) = &control_status {
421 return Err(ManagedSessionError::ControlFailed(why.clone()));
422 }
423
424 let mut all_subscriptions_up = true;
425 for subscription in &subscriptions {
426 match &*subscription.borrow() {
427 ConnectionStatus::Failed(why) => {
428 return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
429 }
430 ConnectionStatus::Up => {}
431 _ => all_subscriptions_up = false,
432 }
433 }
434
435 if control_status == ConnectionStatus::Up && all_subscriptions_up {
436 return Ok(());
437 }
438
439 tokio::select! {
440 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
441 _ = control.changed() => {}
442 _ = wait_any_subscription_change(&mut subscriptions) => {}
443 }
444 }
445}
446
447pub(super) async fn drain_subscriptions_until_complete(
462 subscriptions: &mut [SubscriptionHandle],
463 cancel: &CancellationToken,
464 idle_timeout: std::time::Duration,
465) -> DrainOutcome {
466 let mut events = Vec::new();
467 if subscriptions.is_empty() {
468 return DrainOutcome::Complete(events);
469 }
470 loop {
471 while let Some(event) = try_next_subscription_event(subscriptions) {
472 events.push(event);
473 }
474 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
475 let any_failed = subscriptions
476 .iter()
477 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
478 return if any_failed {
479 DrainOutcome::Stalled(events)
480 } else {
481 DrainOutcome::Complete(events)
482 };
483 }
484 tokio::select! {
485 biased;
486 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
488 _ = tokio::time::sleep(idle_timeout) => {
493 let any_up = subscriptions.iter().any(|s| {
494 !s.notifications.is_closed()
495 && matches!(*s.status.borrow(), ConnectionStatus::Up)
496 });
497 if any_up {
498 return DrainOutcome::Stalled(events);
499 }
500 }
501 received = recv_any_open_subscription(subscriptions) => {
502 if let Some(event) = received {
504 events.push(event);
505 }
506 }
507 }
508 }
509}
510
511impl Drop for ManagedBacktestSession {
512 fn drop(&mut self) {
513 self.session_cancel.cancel();
514 }
515}
516
517pub(super) async fn wait_any_subscription_change(
518 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
519) {
520 if subscriptions.is_empty() {
521 std::future::pending::<()>().await;
522 return;
523 }
524 let _ =
525 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
526}
527
528pub(super) async fn wait_any_subscription_event(
529 subscriptions: &mut [SubscriptionHandle],
530) -> ManagedEvent {
531 loop {
532 if let Some(event) = try_next_subscription_event(subscriptions) {
533 return event;
534 }
535
536 let futures: Vec<_> = subscriptions
537 .iter_mut()
538 .filter(|s| !s.notifications.is_closed())
539 .map(|s| Box::pin(s.notifications.recv()))
540 .collect();
541
542 if futures.is_empty() {
543 std::future::pending::<()>().await;
544 }
545
546 let (notification, _, _) = futures::future::select_all(futures).await;
547 if let Some(notification) = notification {
548 return notification.into();
549 }
550 }
551}
552
553pub(super) async fn recv_any_open_subscription(
558 subscriptions: &mut [SubscriptionHandle],
559) -> Option<ManagedEvent> {
560 let futures: Vec<_> = subscriptions
561 .iter_mut()
562 .filter(|s| !s.notifications.is_closed())
563 .map(|s| Box::pin(s.notifications.recv()))
564 .collect();
565
566 if futures.is_empty() {
567 return None;
568 }
569
570 let (notification, _, _) = futures::future::select_all(futures).await;
571 notification.map(Into::into)
572}
573
574pub(super) fn try_next_subscription_event(
575 subscriptions: &mut [SubscriptionHandle],
576) -> Option<ManagedEvent> {
577 for subscription in subscriptions {
578 if let Ok(notification) = subscription.notifications.try_recv() {
579 return Some(notification.into());
580 }
581 }
582 None
583}
584
585impl From<ControlEvent> for ManagedEvent {
586 fn from(event: ControlEvent) -> Self {
587 match event {
588 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
589 ControlEvent::Paused(event) => Self::Paused(event),
590 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
591 ControlEvent::Slot(slot) => Self::Slot(slot),
592 ControlEvent::Status(status) => Self::Status(status),
593 ControlEvent::Completed { summary } => Self::Completed { summary },
594 ControlEvent::Error(error) => Self::Error(error),
595 }
596 }
597}
598
599impl From<SubscriptionNotification> for ManagedEvent {
600 fn from(notification: SubscriptionNotification) -> Self {
601 match notification {
602 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
603 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
604 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
605 }
606 }
607}
608
609#[cfg(test)]
610mod tests {
611 use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};
612
613 use super::*;
614 use crate::{CreateSession, managed::RECONNECT_MAX_TOTAL};
615
616 fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
617 CreateSession::builder()
618 .start_slot(1)
619 .slot_count(1)
620 .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
621 .build()
622 .into_params()
623 .expect("valid create params")
624 }
625
626 #[test]
627 fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
628 let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
629 (
630 "v0 unset",
631 CreateBacktestSessionRequest::V0(params(None)),
632 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
633 ),
634 (
635 "v0 explicit",
636 CreateBacktestSessionRequest::V0(params(Some(42))),
637 Some(42),
638 ),
639 (
640 "v1 single unset",
641 CreateBacktestSessionRequestV1 {
642 request: params(None),
643 parallel: false,
644 }
645 .into(),
646 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
647 ),
648 (
649 "v1 parallel unset keeps the server's parallel default",
650 CreateBacktestSessionRequestV1 {
651 request: params(None),
652 parallel: true,
653 }
654 .into(),
655 None,
656 ),
657 ];
658
659 for (name, mut create, expected) in cases {
660 set_default_disconnect_timeout(&mut create);
661 let (request, _) = create.into_request_and_parallel();
662 assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
663 }
664 }
665
666 #[test]
667 fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
668 assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
669 const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
670 }
671}