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