1use std::{collections::VecDeque, sync::Arc, time::Duration};
2
3use simulator_api::{
4 AgentStatsReport, BacktestError, BacktestStatus, ContinueParams, ContinueToParams,
5 CreateBacktestSessionRequest, 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, ReconnectCoordinator, SessionInfo,
15 StartSessionParams, SubscriptionDiagnostics, SubscriptionHandle, SubscriptionNotification,
16 spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
17 spawn_control_manager, spawn_transaction_subscription_manager,
18};
19use crate::subscriptions::{AccountDiffNotification, ActionResultNotification};
20
21#[derive(Debug, Error)]
23pub enum ManagedSessionError {
24 #[error("session create failed: {0}")]
25 Create(String),
26
27 #[error("control channel closed")]
28 ControlClosed,
29
30 #[error("control failed: {0}")]
31 ControlFailed(String),
32
33 #[error("subscription failed: {0}")]
34 SubscriptionFailed(String),
35
36 #[error("cancelled")]
37 Cancelled,
38
39 #[error("control closed while sending continue: {0}")]
40 ContinueSend(String),
41}
42
43#[derive(Debug)]
44pub enum ManagedEvent {
45 ReadyForContinue,
46 Paused(PausedEvent),
49 DiscoveryBatch(DiscoveryBatchEvent),
53 Slot(u64),
54 Status(BacktestStatus),
55 Completed {
58 summary: Option<SessionSummary>,
59 agent_stats: Option<Vec<AgentStatsReport>>,
60 },
61 Error(BacktestError),
62 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
63 AccountDiff(AccountDiffNotification),
64 ActionResult(ActionResultNotification),
65}
66
67const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
72
73pub(super) enum DrainOutcome {
75 Complete(Vec<ManagedEvent>),
78 Stalled(Vec<ManagedEvent>),
82}
83
84pub struct ManagedBacktestSession {
90 session_info: SessionInfo,
91 control: Option<ControlHandle>,
92 subscriptions: Vec<SubscriptionHandle>,
93 session_cancel: CancellationToken,
94 post_completion: Option<VecDeque<ManagedEvent>>,
97 post_completion_error: Option<ManagedSessionError>,
101 completion_drain_timeout: Duration,
102 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
105 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
106}
107
108impl ManagedBacktestSession {
109 pub async fn start(
112 url: String,
113 api_key: String,
114 create: CreateBacktestSessionRequest,
115 ) -> Result<Self, ManagedSessionError> {
116 Self::start_with_params(
117 StartSessionParams::builder()
118 .url(url)
119 .api_key(api_key)
120 .create(create)
121 .build(),
122 None,
123 )
124 .await
125 }
126
127 pub async fn start_with_params(
135 params: StartSessionParams,
136 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
137 ) -> Result<Self, ManagedSessionError> {
138 let StartSessionParams {
139 url,
140 api_key,
141 create,
142 parent_cancel,
143 subscription_diagnostics,
144 } = params;
145 let session_cancel = parent_cancel.child_token();
146 let mut control = spawn_control_manager(url, api_key, create, session_cancel.clone());
147
148 let session_info = tokio::select! {
149 biased;
150 _ = parent_cancel.cancelled() => {
151 session_cancel.cancel();
152 control.join().await;
153 return Err(ManagedSessionError::Cancelled);
154 }
155 result = control.wait_for_session() => {
156 result.map_err(ManagedSessionError::Create)?
157 }
158 };
159
160 Ok(Self {
161 session_info,
162 control: Some(control),
163 subscriptions: Vec::new(),
164 session_cancel,
165 post_completion: None,
166 post_completion_error: None,
167 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
168 reconnect_coordinator,
169 subscription_diagnostics,
170 })
171 }
172
173 pub fn session_info(&self) -> &SessionInfo {
175 &self.session_info
176 }
177
178 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
182 self.completion_drain_timeout = idle_timeout;
183 }
184
185 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
187 self.subscriptions
188 .push(spawn_transaction_subscription_manager(
189 self.session_info.rpc_endpoint.clone(),
190 program_ids,
191 self.session_cancel.clone(),
192 self.reconnect_coordinator.clone(),
193 self.subscription_diagnostics.clone(),
194 ));
195 }
196
197 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
199 self.subscriptions
200 .push(spawn_account_diff_subscription_manager(
201 self.session_info.rpc_endpoint.clone(),
202 program_ids,
203 self.session_cancel.clone(),
204 self.reconnect_coordinator.clone(),
205 self.subscription_diagnostics.clone(),
206 ));
207 }
208
209 pub fn subscribe_actions(&mut self) {
212 self.subscriptions.push(spawn_action_subscription_manager(
213 self.session_info.rpc_endpoint.clone(),
214 self.session_cancel.clone(),
215 self.reconnect_coordinator.clone(),
216 self.subscription_diagnostics.clone(),
217 ));
218 }
219
220 async fn drain_until_subscriptions_complete(
225 &mut self,
226 idle_timeout: std::time::Duration,
227 ) -> DrainOutcome {
228 drain_subscriptions_until_complete(
229 &mut self.subscriptions,
230 &self.session_cancel,
231 idle_timeout,
232 )
233 .await
234 }
235
236 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
241 if let Some(buffered) = self.post_completion.as_mut() {
244 if let Some(event) = buffered.pop_front() {
245 return Ok(event);
246 }
247 return Err(self
250 .post_completion_error
251 .take()
252 .unwrap_or(ManagedSessionError::ControlClosed));
253 }
254
255 if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
256 return Ok(event);
257 }
258
259 let event = {
262 let cancel = self.session_cancel.clone();
263 let control = self
264 .control
265 .as_mut()
266 .ok_or(ManagedSessionError::ControlClosed)?;
267 let subscriptions = &mut self.subscriptions;
268 tokio::select! {
269 biased;
270 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
271 event = control.events.recv() => {
272 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
273 }
274 event = wait_any_subscription_event(subscriptions) => event,
275 }
276 };
277
278 let ManagedEvent::Completed {
280 summary,
281 agent_stats,
282 } = event
283 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(),
295 Ok(ManagedEvent::Completed {
296 summary,
297 agent_stats,
298 }),
299 ),
300 DrainOutcome::Stalled(events) => (
305 events.into(),
306 Err(ManagedSessionError::SubscriptionFailed(
307 "completion drain stalled: subscriptions did not deliver their \
308 end-of-stream terminals; the captured stream is incomplete"
309 .to_string(),
310 )),
311 ),
312 };
313 match terminal {
314 Ok(completed) => buffered.push_back(completed),
315 Err(err) => self.post_completion_error = Some(err),
316 }
317 let first = buffered.pop_front();
318 self.post_completion = Some(buffered);
319 match first {
320 Some(event) => Ok(event),
321 None => Err(self
323 .post_completion_error
324 .take()
325 .unwrap_or(ManagedSessionError::ControlClosed)),
326 }
327 }
328
329 pub async fn send_continue(
336 &mut self,
337 params: ContinueParams,
338 ) -> Result<(), ManagedSessionError> {
339 self.wait_all_up().await?;
340 self.control_mut()?
341 .send_continue(params)
342 .await
343 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
344 }
345
346 pub async fn send_continue_to(
354 &mut self,
355 params: ContinueToParams,
356 ) -> Result<(), ManagedSessionError> {
357 self.wait_all_up().await?;
358 self.control_mut()?
359 .send_continue_to(params)
360 .await
361 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
362 }
363
364 pub async fn shutdown(mut self) {
366 self.session_cancel.cancel();
367 if let Some(control) = self.control.take() {
368 control.join().await;
369 }
370 for sub in std::mem::take(&mut self.subscriptions) {
371 let _ = sub.join.await;
372 }
373 }
374
375 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
376 self.control
377 .as_mut()
378 .ok_or(ManagedSessionError::ControlClosed)
379 }
380
381 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
382 let control = self
383 .control
384 .as_ref()
385 .ok_or(ManagedSessionError::ControlClosed)?
386 .status
387 .clone();
388 let subscriptions = self
389 .subscriptions
390 .iter()
391 .map(|s| s.status.clone())
392 .collect();
393 wait_connections_up(control, subscriptions, &self.session_cancel).await
394 }
395}
396
397pub(super) async fn wait_connections_up(
401 mut control: watch::Receiver<ConnectionStatus>,
402 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
403 cancel: &CancellationToken,
404) -> Result<(), ManagedSessionError> {
405 loop {
406 let control_status = control.borrow().clone();
407 if let ConnectionStatus::Failed(why) = &control_status {
408 return Err(ManagedSessionError::ControlFailed(why.clone()));
409 }
410
411 let mut all_subscriptions_up = true;
412 for subscription in &subscriptions {
413 match &*subscription.borrow() {
414 ConnectionStatus::Failed(why) => {
415 return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
416 }
417 ConnectionStatus::Up => {}
418 _ => all_subscriptions_up = false,
419 }
420 }
421
422 if control_status == ConnectionStatus::Up && all_subscriptions_up {
423 return Ok(());
424 }
425
426 tokio::select! {
427 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
428 _ = control.changed() => {}
429 _ = wait_any_subscription_change(&mut subscriptions) => {}
430 }
431 }
432}
433
434pub(super) async fn drain_subscriptions_until_complete(
449 subscriptions: &mut [SubscriptionHandle],
450 cancel: &CancellationToken,
451 idle_timeout: std::time::Duration,
452) -> DrainOutcome {
453 let mut events = Vec::new();
454 if subscriptions.is_empty() {
455 return DrainOutcome::Complete(events);
456 }
457 loop {
458 while let Some(event) = try_next_subscription_event(subscriptions) {
459 events.push(event);
460 }
461 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
462 let any_failed = subscriptions
463 .iter()
464 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
465 return if any_failed {
466 DrainOutcome::Stalled(events)
467 } else {
468 DrainOutcome::Complete(events)
469 };
470 }
471 tokio::select! {
472 biased;
473 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
475 _ = tokio::time::sleep(idle_timeout) => {
480 let any_up = subscriptions.iter().any(|s| {
481 !s.notifications.is_closed()
482 && matches!(*s.status.borrow(), ConnectionStatus::Up)
483 });
484 if any_up {
485 return DrainOutcome::Stalled(events);
486 }
487 }
488 received = recv_any_open_subscription(subscriptions) => {
489 if let Some(event) = received {
491 events.push(event);
492 }
493 }
494 }
495 }
496}
497
498impl Drop for ManagedBacktestSession {
499 fn drop(&mut self) {
500 self.session_cancel.cancel();
501 }
502}
503
504pub(super) async fn wait_any_subscription_change(
505 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
506) {
507 if subscriptions.is_empty() {
508 std::future::pending::<()>().await;
509 return;
510 }
511 let _ =
512 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
513}
514
515pub(super) async fn wait_any_subscription_event(
516 subscriptions: &mut [SubscriptionHandle],
517) -> ManagedEvent {
518 loop {
519 if let Some(event) = try_next_subscription_event(subscriptions) {
520 return event;
521 }
522
523 let futures: Vec<_> = subscriptions
524 .iter_mut()
525 .filter(|s| !s.notifications.is_closed())
526 .map(|s| Box::pin(s.notifications.recv()))
527 .collect();
528
529 if futures.is_empty() {
530 std::future::pending::<()>().await;
531 }
532
533 let (notification, _, _) = futures::future::select_all(futures).await;
534 if let Some(notification) = notification {
535 return notification.into();
536 }
537 }
538}
539
540pub(super) async fn recv_any_open_subscription(
545 subscriptions: &mut [SubscriptionHandle],
546) -> Option<ManagedEvent> {
547 let futures: Vec<_> = subscriptions
548 .iter_mut()
549 .filter(|s| !s.notifications.is_closed())
550 .map(|s| Box::pin(s.notifications.recv()))
551 .collect();
552
553 if futures.is_empty() {
554 return None;
555 }
556
557 let (notification, _, _) = futures::future::select_all(futures).await;
558 notification.map(Into::into)
559}
560
561pub(super) fn try_next_subscription_event(
562 subscriptions: &mut [SubscriptionHandle],
563) -> Option<ManagedEvent> {
564 for subscription in subscriptions {
565 if let Ok(notification) = subscription.notifications.try_recv() {
566 return Some(notification.into());
567 }
568 }
569 None
570}
571
572impl From<ControlEvent> for ManagedEvent {
573 fn from(event: ControlEvent) -> Self {
574 match event {
575 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
576 ControlEvent::Paused(event) => Self::Paused(event),
577 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
578 ControlEvent::Slot(slot) => Self::Slot(slot),
579 ControlEvent::Status(status) => Self::Status(status),
580 ControlEvent::Completed {
581 summary,
582 agent_stats,
583 } => Self::Completed {
584 summary,
585 agent_stats,
586 },
587 ControlEvent::Error(error) => Self::Error(error),
588 }
589 }
590}
591
592impl From<SubscriptionNotification> for ManagedEvent {
593 fn from(notification: SubscriptionNotification) -> Self {
594 match notification {
595 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
596 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
597 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
598 }
599 }
600}