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_transaction_subscription_manager,
19};
20use crate::subscriptions::{
21 AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
22};
23
24#[derive(Debug, Error)]
26pub enum ManagedSessionError {
27 #[error("session create failed: {0}")]
28 Create(String),
29
30 #[error("control channel closed")]
31 ControlClosed,
32
33 #[error("control failed: {0}")]
34 ControlFailed(String),
35
36 #[error("subscription failed: {0}")]
37 SubscriptionFailed(String),
38
39 #[error("cancelled")]
40 Cancelled,
41
42 #[error("control closed while sending continue: {0}")]
43 ContinueSend(String),
44}
45
46#[derive(Debug)]
47pub enum ManagedEvent {
48 ReadyForContinue,
49 Paused(PausedEvent),
52 DiscoveryBatch(DiscoveryBatchEvent),
56 Slot(u64),
57 Status(BacktestStatus),
58 Completed {
59 summary: Option<SessionSummary>,
60 },
61 Error(BacktestError),
62 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
63 AccountDiff(AccountDiffNotification),
64 ActionResult(ActionResultNotification),
65 Diagnostic(DiagnosticNotification),
66}
67
68const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
73
74pub(super) enum DrainOutcome {
76 Complete(Vec<ManagedEvent>),
79 Stalled(Vec<ManagedEvent>),
83}
84
85pub struct ManagedBacktestSession {
91 session_info: SessionInfo,
92 control: Option<ControlHandle>,
93 subscriptions: Vec<SubscriptionHandle>,
94 session_cancel: CancellationToken,
95 post_completion: Option<VecDeque<ManagedEvent>>,
98 post_completion_error: Option<ManagedSessionError>,
102 completion_drain_timeout: Duration,
103 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
106 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
107}
108
109impl ManagedBacktestSession {
110 pub async fn start(
113 url: String,
114 api_key: String,
115 create: CreateBacktestSessionRequest,
116 ) -> Result<Self, ManagedSessionError> {
117 Self::start_with_params(
118 StartSessionParams::builder()
119 .url(url)
120 .api_key(api_key)
121 .create(create)
122 .build(),
123 None,
124 )
125 .await
126 }
127
128 pub async fn start_with_params(
141 params: StartSessionParams,
142 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
143 ) -> Result<Self, ManagedSessionError> {
144 let StartSessionParams {
145 url,
146 api_key,
147 mut create,
148 parent_cancel,
149 subscription_diagnostics,
150 } = params;
151 set_default_disconnect_timeout(&mut create);
152 let session_cancel = parent_cancel.child_token();
153 let mut control = spawn_control_manager(url, api_key, create, session_cancel.clone());
154
155 let session_info = tokio::select! {
156 biased;
157 _ = parent_cancel.cancelled() => {
158 session_cancel.cancel();
159 control.join().await;
160 return Err(ManagedSessionError::Cancelled);
161 }
162 result = control.wait_for_session() => {
163 result.map_err(ManagedSessionError::Create)?
164 }
165 };
166
167 Ok(Self {
168 session_info,
169 control: Some(control),
170 subscriptions: Vec::new(),
171 session_cancel,
172 post_completion: None,
173 post_completion_error: None,
174 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
175 reconnect_coordinator,
176 subscription_diagnostics,
177 })
178 }
179
180 pub fn session_info(&self) -> &SessionInfo {
182 &self.session_info
183 }
184
185 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
189 self.completion_drain_timeout = idle_timeout;
190 }
191
192 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
194 self.subscriptions
195 .push(spawn_transaction_subscription_manager(
196 self.session_info.rpc_endpoint.clone(),
197 program_ids,
198 self.session_cancel.clone(),
199 self.reconnect_coordinator.clone(),
200 self.subscription_diagnostics.clone(),
201 ));
202 }
203
204 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
206 self.subscriptions
207 .push(spawn_account_diff_subscription_manager(
208 self.session_info.rpc_endpoint.clone(),
209 program_ids,
210 self.session_cancel.clone(),
211 self.reconnect_coordinator.clone(),
212 self.subscription_diagnostics.clone(),
213 ));
214 }
215
216 pub fn subscribe_actions(&mut self) {
219 self.subscriptions.push(spawn_action_subscription_manager(
220 self.session_info.rpc_endpoint.clone(),
221 self.session_cancel.clone(),
222 self.reconnect_coordinator.clone(),
223 self.subscription_diagnostics.clone(),
224 ));
225 }
226
227 pub fn subscribe_diagnostics(&mut self) {
230 self.subscriptions
231 .push(spawn_diagnostic_subscription_manager(
232 self.session_info.rpc_endpoint.clone(),
233 self.session_cancel.clone(),
234 self.reconnect_coordinator.clone(),
235 self.subscription_diagnostics.clone(),
236 ));
237 }
238
239 async fn drain_until_subscriptions_complete(
244 &mut self,
245 idle_timeout: std::time::Duration,
246 ) -> DrainOutcome {
247 drain_subscriptions_until_complete(
248 &mut self.subscriptions,
249 &self.session_cancel,
250 idle_timeout,
251 )
252 .await
253 }
254
255 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
260 if let Some(buffered) = self.post_completion.as_mut() {
263 if let Some(event) = buffered.pop_front() {
264 return Ok(event);
265 }
266 return Err(self
269 .post_completion_error
270 .take()
271 .unwrap_or(ManagedSessionError::ControlClosed));
272 }
273
274 tokio::task::coop::consume_budget().await;
277
278 let event = {
281 let cancel = self.session_cancel.clone();
282 let control = self
283 .control
284 .as_mut()
285 .ok_or(ManagedSessionError::ControlClosed)?;
286 let subscriptions = &mut self.subscriptions;
287 match control.events.try_recv() {
291 Ok(event) => ManagedEvent::from(event),
292 Err(_) => {
293 if let Some(event) = try_next_subscription_event(subscriptions) {
294 return Ok(event);
295 }
296 tokio::select! {
297 biased;
298 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
299 event = control.events.recv() => {
300 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
301 }
302 event = wait_any_subscription_event(subscriptions) => event,
303 }
304 }
305 }
306 };
307
308 let ManagedEvent::Completed { summary } = event else {
310 return Ok(event);
311 };
312
313 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
316 .drain_until_subscriptions_complete(self.completion_drain_timeout)
317 .await
318 {
319 DrainOutcome::Complete(events) => {
320 (events.into(), Ok(ManagedEvent::Completed { summary }))
321 }
322 DrainOutcome::Stalled(events) => (
327 events.into(),
328 Err(ManagedSessionError::SubscriptionFailed(
329 "completion drain stalled: subscriptions did not deliver their \
330 end-of-stream terminals; the captured stream is incomplete"
331 .to_string(),
332 )),
333 ),
334 };
335 match terminal {
336 Ok(completed) => buffered.push_back(completed),
337 Err(err) => self.post_completion_error = Some(err),
338 }
339 let first = buffered.pop_front();
340 self.post_completion = Some(buffered);
341 match first {
342 Some(event) => Ok(event),
343 None => Err(self
345 .post_completion_error
346 .take()
347 .unwrap_or(ManagedSessionError::ControlClosed)),
348 }
349 }
350
351 pub async fn send_continue(
358 &mut self,
359 params: ContinueParams,
360 ) -> Result<(), ManagedSessionError> {
361 self.wait_all_up().await?;
362 self.control_mut()?
363 .send_continue(params)
364 .await
365 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
366 }
367
368 pub async fn send_continue_to(
376 &mut self,
377 params: ContinueToParams,
378 ) -> Result<(), ManagedSessionError> {
379 self.wait_all_up().await?;
380 self.control_mut()?
381 .send_continue_to(params)
382 .await
383 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
384 }
385
386 pub async fn shutdown(mut self) {
388 self.session_cancel.cancel();
389 if let Some(control) = self.control.take() {
390 control.join().await;
391 }
392 for sub in std::mem::take(&mut self.subscriptions) {
393 drop(sub.notifications);
395 let _ = sub.join.await;
396 }
397 }
398
399 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
400 self.control
401 .as_mut()
402 .ok_or(ManagedSessionError::ControlClosed)
403 }
404
405 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
406 let control = self
407 .control
408 .as_ref()
409 .ok_or(ManagedSessionError::ControlClosed)?
410 .status
411 .clone();
412 let subscriptions = self
413 .subscriptions
414 .iter()
415 .map(|s| s.status.clone())
416 .collect();
417 wait_connections_up(control, subscriptions, &self.session_cancel).await
418 }
419}
420
421fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
426 let params = match create {
427 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
428 parallel: true, ..
429 }) => return,
430 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
431 | CreateBacktestSessionRequest::V0(request) => request,
432 };
433 params
434 .disconnect_timeout_secs
435 .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
436}
437
438pub(super) async fn wait_connections_up(
442 mut control: watch::Receiver<ConnectionStatus>,
443 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
444 cancel: &CancellationToken,
445) -> Result<(), ManagedSessionError> {
446 loop {
447 let control_status = control.borrow().clone();
448 if let ConnectionStatus::Failed(why) = &control_status {
449 return Err(ManagedSessionError::ControlFailed(why.clone()));
450 }
451
452 let mut all_subscriptions_up = true;
453 for subscription in &subscriptions {
454 match &*subscription.borrow() {
455 ConnectionStatus::Failed(why) => {
456 return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
457 }
458 ConnectionStatus::Up => {}
459 _ => all_subscriptions_up = false,
460 }
461 }
462
463 if control_status == ConnectionStatus::Up && all_subscriptions_up {
464 return Ok(());
465 }
466
467 tokio::select! {
468 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
469 _ = control.changed() => {}
470 _ = wait_any_subscription_change(&mut subscriptions) => {}
471 }
472 }
473}
474
475pub(super) async fn drain_subscriptions_until_complete(
490 subscriptions: &mut [SubscriptionHandle],
491 cancel: &CancellationToken,
492 idle_timeout: std::time::Duration,
493) -> DrainOutcome {
494 let mut events = Vec::new();
495 if subscriptions.is_empty() {
496 return DrainOutcome::Complete(events);
497 }
498 loop {
499 while let Some(event) = try_next_subscription_event(subscriptions) {
500 events.push(event);
501 }
502 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
503 let any_failed = subscriptions
504 .iter()
505 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
506 return if any_failed {
507 DrainOutcome::Stalled(events)
508 } else {
509 DrainOutcome::Complete(events)
510 };
511 }
512 tokio::select! {
513 biased;
514 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
516 _ = tokio::time::sleep(idle_timeout) => {
521 let any_up = subscriptions.iter().any(|s| {
522 !s.notifications.is_closed()
523 && matches!(*s.status.borrow(), ConnectionStatus::Up)
524 });
525 if any_up {
526 return DrainOutcome::Stalled(events);
527 }
528 }
529 received = recv_any_open_subscription(subscriptions) => {
530 if let Some(event) = received {
532 events.push(event);
533 }
534 }
535 }
536 }
537}
538
539impl Drop for ManagedBacktestSession {
540 fn drop(&mut self) {
541 self.session_cancel.cancel();
542 }
543}
544
545pub(super) async fn wait_any_subscription_change(
546 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
547) {
548 if subscriptions.is_empty() {
549 std::future::pending::<()>().await;
550 return;
551 }
552 let _ =
553 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
554}
555
556pub(super) async fn wait_any_subscription_event(
557 subscriptions: &mut [SubscriptionHandle],
558) -> ManagedEvent {
559 loop {
560 if let Some(event) = try_next_subscription_event(subscriptions) {
561 return event;
562 }
563
564 let futures: Vec<_> = subscriptions
565 .iter_mut()
566 .filter(|s| !s.notifications.is_closed())
567 .map(|s| Box::pin(s.notifications.recv()))
568 .collect();
569
570 if futures.is_empty() {
571 std::future::pending::<()>().await;
572 }
573
574 let (notification, _, _) = futures::future::select_all(futures).await;
575 if let Some(notification) = notification {
576 return notification.into();
577 }
578 }
579}
580
581pub(super) async fn recv_any_open_subscription(
586 subscriptions: &mut [SubscriptionHandle],
587) -> Option<ManagedEvent> {
588 let futures: Vec<_> = subscriptions
589 .iter_mut()
590 .filter(|s| !s.notifications.is_closed())
591 .map(|s| Box::pin(s.notifications.recv()))
592 .collect();
593
594 if futures.is_empty() {
595 return None;
596 }
597
598 let (notification, _, _) = futures::future::select_all(futures).await;
599 notification.map(Into::into)
600}
601
602pub(super) fn try_next_subscription_event(
603 subscriptions: &mut [SubscriptionHandle],
604) -> Option<ManagedEvent> {
605 for subscription in subscriptions {
606 if let Ok(notification) = subscription.notifications.try_recv() {
607 return Some(notification.into());
608 }
609 }
610 None
611}
612
613impl From<ControlEvent> for ManagedEvent {
614 fn from(event: ControlEvent) -> Self {
615 match event {
616 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
617 ControlEvent::Paused(event) => Self::Paused(event),
618 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
619 ControlEvent::Slot(slot) => Self::Slot(slot),
620 ControlEvent::Status(status) => Self::Status(status),
621 ControlEvent::Completed { summary } => Self::Completed { summary },
622 ControlEvent::Error(error) => Self::Error(error),
623 }
624 }
625}
626
627impl From<SubscriptionNotification> for ManagedEvent {
628 fn from(notification: SubscriptionNotification) -> Self {
629 match notification {
630 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
631 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
632 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
633 SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
634 }
635 }
636}
637
638#[cfg(test)]
639mod tests {
640 use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};
641
642 use super::*;
643 use crate::{CreateSession, managed::RECONNECT_MAX_TOTAL};
644
645 fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
646 CreateSession::builder()
647 .start_slot(1)
648 .slot_count(1)
649 .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
650 .build()
651 .into_params()
652 .expect("valid create params")
653 }
654
655 #[test]
656 fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
657 let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
658 (
659 "v0 unset",
660 CreateBacktestSessionRequest::V0(params(None)),
661 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
662 ),
663 (
664 "v0 explicit",
665 CreateBacktestSessionRequest::V0(params(Some(42))),
666 Some(42),
667 ),
668 (
669 "v1 single unset",
670 CreateBacktestSessionRequestV1 {
671 request: params(None),
672 parallel: false,
673 }
674 .into(),
675 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
676 ),
677 (
678 "v1 parallel unset keeps the server's parallel default",
679 CreateBacktestSessionRequestV1 {
680 request: params(None),
681 parallel: true,
682 }
683 .into(),
684 None,
685 ),
686 ];
687
688 for (name, mut create, expected) in cases {
689 set_default_disconnect_timeout(&mut create);
690 let (request, _) = create.into_request_and_parallel();
691 assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
692 }
693 }
694
695 #[test]
696 fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
697 assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
698 const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
699 }
700}