Skip to main content

simulator_client/managed/
session.rs

1use std::{collections::VecDeque, sync::Arc, time::Duration};
2
3use futures::FutureExt;
4use simulator_api::{
5    BacktestError, BacktestStatus, ContinueParams, ContinueToParams, CreateBacktestSessionRequest,
6    CreateBacktestSessionRequestV1, DiscoveryBatchEvent, PausedEvent, SessionSummary,
7};
8use solana_address::Address;
9use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
10use thiserror::Error;
11use tokio::sync::{mpsc, 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_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
20    spawn_transaction_subscription_manager,
21};
22use crate::subscriptions::{
23    AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
24    ReplacementNotification,
25};
26
27/// Error returned by the high-level managed session wrapper.
28#[derive(Debug, Error)]
29pub enum ManagedSessionError {
30    #[error("session create failed: {0}")]
31    Create(String),
32
33    #[error("control channel closed")]
34    ControlClosed,
35
36    #[error("control failed: {0}")]
37    ControlFailed(String),
38
39    #[error("subscription failed: {0}")]
40    SubscriptionFailed(String),
41
42    #[error("cancelled")]
43    Cancelled,
44
45    #[error("control closed while sending continue: {0}")]
46    ContinueSend(String),
47}
48
49#[derive(Debug)]
50pub enum ManagedEvent {
51    ReadyForContinue,
52    /// Server paused at a `ContinueTo` target. The session is ready for
53    /// another `Continue` or `ContinueTo` from this point.
54    Paused(PausedEvent),
55    /// Server discovered an upcoming batch matching a registered
56    /// `DiscoveryFilter`. Send `send_continue_to(slot, batch_index)` to pause
57    /// immediately before it executes.
58    DiscoveryBatch(DiscoveryBatchEvent),
59    Slot(u64),
60    Status(BacktestStatus),
61    Completed {
62        summary: Option<SessionSummary>,
63    },
64    Error(BacktestError),
65    Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
66    AccountDiff(AccountDiffNotification),
67    ActionResult(ActionResultNotification),
68    Diagnostic(DiagnosticNotification),
69    Replacement(Box<ReplacementNotification>),
70}
71
72/// Idle backstop for the completion drain: if no trailing notification arrives
73/// for this long after `Completed`, assume the data plane is stalled and stop
74/// waiting. Bounds the gap *between* notifications, not total drain time, so a
75/// slow-but-flowing stream (large backlog over a slow link) is never truncated.
76const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
77
78/// Result of [`ManagedBacktestSession::drain_until_subscriptions_complete`].
79pub(super) enum DrainOutcome {
80    /// Every subscription delivered its terminal (channels closed), or the
81    /// session was cancelled. The drained events are complete up to the stop.
82    Complete(Vec<ManagedEvent>),
83    /// The idle backstop fired with subscriptions still open — trailing
84    /// notifications never arrived, so the run is incomplete. Carries whatever
85    /// was drained before the stall.
86    Stalled(Vec<ManagedEvent>),
87}
88
89/// High-level managed backtest session.
90///
91/// This wrapper owns the control manager, supported subscription managers,
92/// cancellation, status gating, and shutdown order. Callers only need to react
93/// to [`ManagedEvent`]s and send [`ContinueParams`] after `ReadyForContinue`.
94pub struct ManagedBacktestSession {
95    session_info: SessionInfo,
96    control: Option<ControlHandle>,
97    subscriptions: Vec<SubscriptionHandle>,
98    session_cancel: CancellationToken,
99    /// Notifications drained on `Completed`, followed by `Completed`; served in
100    /// order by `next_event`. `None` until completion.
101    post_completion: Option<VecDeque<ManagedEvent>>,
102    /// Surfaced after `post_completion` drains: set when the completion drain
103    /// stalled (idle backstop fired with subscriptions still open), so a
104    /// silently-truncated run fails loudly instead of reporting `Completed`.
105    post_completion_error: Option<ManagedSessionError>,
106    completion_drain_timeout: Duration,
107    /// Shared across a parallel batch so this session's subscription reconnects
108    /// step aside for still-streaming siblings. `None` for a standalone session.
109    reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
110    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
111}
112
113impl ManagedBacktestSession {
114    /// Start a standalone managed session with an internally owned cancellation
115    /// token and its own diagnostics counters.
116    pub async fn start(
117        url: String,
118        api_key: String,
119        create: CreateBacktestSessionRequest,
120    ) -> Result<Self, ManagedSessionError> {
121        Self::start_with_params(
122            StartSessionParams::builder()
123                .url(url)
124                .api_key(api_key)
125                .create(create)
126                .build(),
127            None,
128        )
129        .await
130    }
131
132    /// Start a managed session from explicit [`StartSessionParams`].
133    ///
134    /// `reconnect_coordinator` is an optional coordinator shared across sibling
135    /// sessions in a parallel batch; a dropped subscription parks on it until
136    /// streaming siblings finish, then reconnects into the freed bandwidth. It
137    /// is handed to the subscription managers spawned by `subscribe_*`. Pass
138    /// `None` for a standalone session.
139    ///
140    /// A create that leaves `disconnect_timeout_secs` unset gets
141    /// [`DEFAULT_DISCONNECT_TIMEOUT_SECS`], so the server outlives this
142    /// session's reconnect budget rather than reclaiming a session the control
143    /// task is still trying to reattach to.
144    pub async fn start_with_params(
145        params: StartSessionParams,
146        reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
147    ) -> Result<Self, ManagedSessionError> {
148        let StartSessionParams {
149            url,
150            api_key,
151            extra_headers,
152            mut create,
153            parent_cancel,
154            subscription_diagnostics,
155        } = params;
156        set_default_disconnect_timeout(&mut create);
157        let session_cancel = parent_cancel.child_token();
158        let mut control =
159            spawn_control_manager(url, api_key, extra_headers, create, session_cancel.clone());
160
161        let session_info = tokio::select! {
162            biased;
163            _ = parent_cancel.cancelled() => {
164                session_cancel.cancel();
165                control.join().await;
166                return Err(ManagedSessionError::Cancelled);
167            }
168            result = control.wait_for_session() => {
169                result.map_err(ManagedSessionError::Create)?
170            }
171        };
172
173        Ok(Self {
174            session_info,
175            control: Some(control),
176            subscriptions: Vec::new(),
177            session_cancel,
178            post_completion: None,
179            post_completion_error: None,
180            completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
181            reconnect_coordinator,
182            subscription_diagnostics,
183        })
184    }
185
186    /// Metadata reported by the server when the session was created.
187    pub fn session_info(&self) -> &SessionInfo {
188        &self.session_info
189    }
190
191    /// Override the completion-drain idle timeout (default
192    /// [`DEFAULT_COMPLETION_DRAIN_TIMEOUT`]). The drain gives up only after this
193    /// long with no trailing notification; it does not cap total drain time.
194    pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
195        self.completion_drain_timeout = idle_timeout;
196    }
197
198    /// Subscribe to transaction notifications for the configured programs.
199    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
200        self.subscriptions
201            .push(spawn_transaction_subscription_manager(
202                self.session_info.rpc_endpoint.clone(),
203                program_ids,
204                self.session_cancel.clone(),
205                self.reconnect_coordinator.clone(),
206                self.subscription_diagnostics.clone(),
207            ));
208    }
209
210    /// Subscribe to account-diff notifications for the configured programs.
211    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
212        self.subscriptions
213            .push(spawn_account_diff_subscription_manager(
214                self.session_info.rpc_endpoint.clone(),
215                program_ids,
216                self.session_cancel.clone(),
217                self.reconnect_coordinator.clone(),
218                self.subscription_diagnostics.clone(),
219            ));
220    }
221
222    /// Subscribe to scheduled-action results. Actions themselves are registered
223    /// in `CreateSessionParams`; this only attaches the result consumer.
224    pub fn subscribe_actions(&mut self) {
225        self.subscriptions.push(spawn_action_subscription_manager(
226            self.session_info.rpc_endpoint.clone(),
227            self.session_cancel.clone(),
228            self.reconnect_coordinator.clone(),
229            self.subscription_diagnostics.clone(),
230        ));
231    }
232
233    /// Subscribe to what stood in for each historical swap: re-quotes, direct-fill probes and
234    /// the originals replayed beside them. Keyless — one stream carries all three.
235    pub fn subscribe_replacements(&mut self) {
236        self.subscriptions
237            .push(spawn_replacement_subscription_manager(
238                self.session_info.rpc_endpoint.clone(),
239                self.session_cancel.clone(),
240                self.reconnect_coordinator.clone(),
241                self.subscription_diagnostics.clone(),
242            ));
243    }
244
245    /// Subscribe to `/diagnostic` samples. The probes themselves are registered in
246    /// `CreateSessionParams`; this only attaches the sample consumer.
247    pub fn subscribe_diagnostics(&mut self) {
248        self.subscriptions
249            .push(spawn_diagnostic_subscription_manager(
250                self.session_info.rpc_endpoint.clone(),
251                self.session_cancel.clone(),
252                self.reconnect_coordinator.clone(),
253                self.subscription_diagnostics.clone(),
254            ));
255    }
256
257    /// Drain trailing notifications until every subscription delivers its
258    /// end-of-stream terminal (closing its channel), the session is cancelled,
259    /// or the data plane is found to have failed. See the `idle_timeout` arm for
260    /// how reconnecting/parked subscriptions are distinguished from a stall.
261    async fn drain_until_subscriptions_complete(
262        &mut self,
263        idle_timeout: std::time::Duration,
264    ) -> DrainOutcome {
265        drain_subscriptions_until_complete(
266            &mut self.subscriptions,
267            &self.session_cancel,
268            idle_timeout,
269        )
270        .await
271    }
272
273    /// Receive the next control or subscription event.
274    ///
275    /// On `Completed`, trailing subscription notifications are drained and
276    /// delivered before the `Completed` event.
277    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
278        // Serve buffered post-completion events (trailing notifications, then
279        // `Completed`); the control stream is gone once they're exhausted.
280        if let Some(buffered) = self.post_completion.as_mut() {
281            if let Some(event) = buffered.pop_front() {
282                return Ok(event);
283            }
284            // Buffer drained: surface a pending stall error so an incomplete
285            // run fails loudly, else the control stream is simply done.
286            return Err(self
287                .post_completion_error
288                .take()
289                .unwrap_or(ManagedSessionError::ControlClosed));
290        }
291
292        // Queued events are served without awaiting, so a caller pumping a
293        // backlog would otherwise never yield.
294        tokio::task::coop::consume_budget().await;
295
296        // Scope the borrows to the `select!` so the completion drain below can
297        // re-borrow `self`.
298        let event = {
299            let cancel = self.session_cancel.clone();
300            let control = self
301                .control
302                .as_mut()
303                .ok_or(ManagedSessionError::ControlClosed)?;
304            let subscriptions = &mut self.subscriptions;
305            // Control first: its task stops reading the socket, keepalive
306            // included, while its queue is full, so a subscription backlog must
307            // never hold control events back.
308            match recv_queued(&mut control.events) {
309                Some(event) => ManagedEvent::from(event),
310                None => {
311                    if let Some(event) = try_next_subscription_event(subscriptions) {
312                        return Ok(event);
313                    }
314                    tokio::select! {
315                        biased;
316                        _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
317                        event = control.events.recv() => {
318                            event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
319                        }
320                        event = wait_any_subscription_event(subscriptions) => event,
321                    }
322                }
323            }
324        };
325
326        // Bind the payload so the re-emitted `Completed` below carries it.
327        let ManagedEvent::Completed { summary } = event else {
328            return Ok(event);
329        };
330
331        // Flush trailing notifications up to each subscription's terminal,
332        // delivering them before `Completed` so none are dropped.
333        let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
334            .drain_until_subscriptions_complete(self.completion_drain_timeout)
335            .await
336        {
337            DrainOutcome::Complete(events) => {
338                (events.into(), Ok(ManagedEvent::Completed { summary }))
339            }
340            // The data plane stalled before every subscription finished:
341            // trailing notifications are missing, so report failure rather
342            // than a silently-truncated `Completed`. Deliver whatever was
343            // drained first, then surface the error once the buffer empties.
344            DrainOutcome::Stalled(events) => (
345                events.into(),
346                Err(ManagedSessionError::SubscriptionFailed(
347                    "completion drain stalled: subscriptions did not deliver their \
348                     end-of-stream terminals; the captured stream is incomplete"
349                        .to_string(),
350                )),
351            ),
352        };
353        match terminal {
354            Ok(completed) => buffered.push_back(completed),
355            Err(err) => self.post_completion_error = Some(err),
356        }
357        let first = buffered.pop_front();
358        self.post_completion = Some(buffered);
359        match first {
360            Some(event) => Ok(event),
361            // Nothing buffered and the run failed: surface the error now.
362            None => Err(self
363                .post_completion_error
364                .take()
365                .unwrap_or(ManagedSessionError::ControlClosed)),
366        }
367    }
368
369    /// Wait until the control connection and all subscription connections are
370    /// up, then send a `Continue` request.
371    ///
372    /// Call this after receiving [`ManagedEvent::ReadyForContinue`] or
373    /// [`ManagedEvent::Paused`]. If there are no subscriptions, only the
374    /// control connection is gated.
375    pub async fn send_continue(
376        &mut self,
377        params: ContinueParams,
378    ) -> Result<(), ManagedSessionError> {
379        self.wait_all_up().await?;
380        self.control_mut()?
381            .send_continue(params)
382            .await
383            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
384    }
385
386    /// Wait until the control connection and all subscription connections are
387    /// up, then send a `ContinueTo` request to step to a specific slot/batch
388    /// boundary.
389    ///
390    /// Pair with [`ManagedEvent::DiscoveryBatch`] to drive a discovery-paced
391    /// loop: receive a discovery event, send `ContinueTo(slot, batch_index)`,
392    /// and wait for [`ManagedEvent::Paused`] before inspecting state.
393    pub async fn send_continue_to(
394        &mut self,
395        params: ContinueToParams,
396    ) -> Result<(), ManagedSessionError> {
397        self.wait_all_up().await?;
398        self.control_mut()?
399            .send_continue_to(params)
400            .await
401            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
402    }
403
404    /// Cancel the session and join all manager tasks.
405    pub async fn shutdown(mut self) {
406        self.session_cancel.cancel();
407        if let Some(control) = self.control.take() {
408            control.join().await;
409        }
410        for sub in std::mem::take(&mut self.subscriptions) {
411            // A manager parked on a full queue exits only once the queue closes.
412            drop(sub.notifications);
413            let _ = sub.join.await;
414        }
415    }
416
417    fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
418        self.control
419            .as_mut()
420            .ok_or(ManagedSessionError::ControlClosed)
421    }
422
423    async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
424        let control = self
425            .control
426            .as_ref()
427            .ok_or(ManagedSessionError::ControlClosed)?
428            .status
429            .clone();
430        let subscriptions = self
431            .subscriptions
432            .iter()
433            .map(|s| s.status.clone())
434            .collect();
435        wait_connections_up(control, subscriptions, &self.session_cancel).await
436    }
437}
438
439/// Give an unset `disconnect_timeout_secs` a window wide enough for this
440/// client's reconnect budget, so a management redeploy is a reattach rather
441/// than a lost session. A parallel create is left alone — the server's parallel
442/// default is already longer, and lowering it would shorten the batch's window.
443fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
444    let params = match create {
445        CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
446            parallel: true, ..
447        }) => return,
448        CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
449        | CreateBacktestSessionRequest::V0(request) => request,
450    };
451    params
452        .disconnect_timeout_secs
453        .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
454}
455
456/// Block until the control connection and every subscription connection report
457/// `Up`, returning an error if any reports `Failed` or the token is cancelled.
458/// Shared by the single-session and parallel sub-session drivers.
459pub(super) async fn wait_connections_up(
460    mut control: watch::Receiver<ConnectionStatus>,
461    mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
462    cancel: &CancellationToken,
463) -> Result<(), ManagedSessionError> {
464    loop {
465        let control_status = control.borrow().clone();
466        if let ConnectionStatus::Failed(why) = &control_status {
467            return Err(ManagedSessionError::ControlFailed(why.clone()));
468        }
469
470        let mut all_subscriptions_up = true;
471        for subscription in &subscriptions {
472            match &*subscription.borrow() {
473                ConnectionStatus::Failed(why) => {
474                    return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
475                }
476                ConnectionStatus::Up => {}
477                _ => all_subscriptions_up = false,
478            }
479        }
480
481        if control_status == ConnectionStatus::Up && all_subscriptions_up {
482            return Ok(());
483        }
484
485        tokio::select! {
486            _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
487            _ = control.changed() => {}
488            _ = wait_any_subscription_change(&mut subscriptions) => {}
489        }
490    }
491}
492
493/// Drain trailing notifications until every subscription delivers its
494/// end-of-stream terminal (closing its channel), `cancel` fires, or the data
495/// plane is found to have stalled. Shared by the single-session and parallel
496/// sub-session drivers. See
497/// [`ManagedBacktestSession::drain_until_subscriptions_complete`].
498///
499/// `idle_timeout` bounds the gap *between* notifications, not total drain time,
500/// so a slow-but-flowing stream (large backlog over a slow link) is never
501/// truncated. A subscription that's `Down` — reconnecting, or parked behind the
502/// reconnect coordinator waiting for siblings to free bandwidth — is *not* a
503/// stall: it resumes via `replayFromSlot` or exhausts its budget and reports
504/// `Failed`. So the idle gap only declares a `Stalled` outcome when an open
505/// subscription is still `Up` (connected but not delivering — a genuinely hung
506/// data plane); a subscription that closed in `Failed` left a truncated stream.
507pub(super) async fn drain_subscriptions_until_complete(
508    subscriptions: &mut [SubscriptionHandle],
509    cancel: &CancellationToken,
510    idle_timeout: std::time::Duration,
511) -> DrainOutcome {
512    let mut events = Vec::new();
513    if subscriptions.is_empty() {
514        return DrainOutcome::Complete(events);
515    }
516    loop {
517        while let Some(event) = try_next_subscription_event(subscriptions) {
518            events.push(event);
519        }
520        if subscriptions.iter().all(|s| s.notifications.is_closed()) {
521            let any_failed = subscriptions
522                .iter()
523                .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
524            return if any_failed {
525                DrainOutcome::Stalled(events)
526            } else {
527                DrainOutcome::Complete(events)
528            };
529        }
530        tokio::select! {
531            biased;
532            // A cancel is an intentional stop, not a data-plane failure.
533            _ = cancel.cancelled() => return DrainOutcome::Complete(events),
534            // Idle gap elapsed. A still-`Up` subscription should be delivering
535            // but isn't — a hung data plane (stall). If the open subscriptions
536            // are all reconnecting/parked (`Down`), keep waiting: the
537            // coordinator is deferring them on purpose, not failing.
538            _ = tokio::time::sleep(idle_timeout) => {
539                let any_up = subscriptions.iter().any(|s| {
540                    !s.notifications.is_closed()
541                        && matches!(*s.status.borrow(), ConnectionStatus::Up)
542                });
543                if any_up {
544                    return DrainOutcome::Stalled(events);
545                }
546            }
547            received = recv_any_open_subscription(subscriptions) => {
548                // `None` means a channel closed; the loop re-checks all-closed.
549                if let Some(event) = received {
550                    events.push(event);
551                }
552            }
553        }
554    }
555}
556
557impl Drop for ManagedBacktestSession {
558    fn drop(&mut self) {
559        self.session_cancel.cancel();
560    }
561}
562
563pub(super) async fn wait_any_subscription_change(
564    subscriptions: &mut [watch::Receiver<ConnectionStatus>],
565) {
566    if subscriptions.is_empty() {
567        std::future::pending::<()>().await;
568        return;
569    }
570    let _ =
571        futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
572}
573
574pub(super) async fn wait_any_subscription_event(
575    subscriptions: &mut [SubscriptionHandle],
576) -> ManagedEvent {
577    loop {
578        if let Some(event) = try_next_subscription_event(subscriptions) {
579            return event;
580        }
581
582        let futures: Vec<_> = subscriptions
583            .iter_mut()
584            .filter(|s| !s.notifications.is_closed())
585            .map(|s| Box::pin(s.notifications.recv()))
586            .collect();
587
588        if futures.is_empty() {
589            std::future::pending::<()>().await;
590        }
591
592        let (notification, _, _) = futures::future::select_all(futures).await;
593        if let Some(notification) = notification {
594            return notification.into();
595        }
596    }
597}
598
599/// Await the next notification from any still-open subscription channel,
600/// returning `None` when one closes. Unlike [`wait_any_subscription_event`],
601/// which never resolves on closure, this lets the completion drain observe
602/// per-channel end-of-stream.
603pub(super) async fn recv_any_open_subscription(
604    subscriptions: &mut [SubscriptionHandle],
605) -> Option<ManagedEvent> {
606    let futures: Vec<_> = subscriptions
607        .iter_mut()
608        .filter(|s| !s.notifications.is_closed())
609        .map(|s| Box::pin(s.notifications.recv()))
610        .collect();
611
612    if futures.is_empty() {
613        return None;
614    }
615
616    let (notification, _, _) = futures::future::select_all(futures).await;
617    notification.map(Into::into)
618}
619
620pub(super) fn try_next_subscription_event(
621    subscriptions: &mut [SubscriptionHandle],
622) -> Option<ManagedEvent> {
623    for subscription in subscriptions {
624        if let Some(notification) = recv_queued(&mut subscription.notifications) {
625            return Some(notification.into());
626        }
627    }
628    None
629}
630
631/// Not `try_recv`, which parks the thread on a message still being written and so consumes a
632/// `block_on` task's pending wakeup. Unconstrained so a spent coop budget never hides a queued
633/// message.
634fn recv_queued<T>(receiver: &mut mpsc::Receiver<T>) -> Option<T> {
635    tokio::task::coop::unconstrained(receiver.recv())
636        .now_or_never()
637        .flatten()
638}
639
640impl From<ControlEvent> for ManagedEvent {
641    fn from(event: ControlEvent) -> Self {
642        match event {
643            ControlEvent::ReadyForContinue => Self::ReadyForContinue,
644            ControlEvent::Paused(event) => Self::Paused(event),
645            ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
646            ControlEvent::Slot(slot) => Self::Slot(slot),
647            ControlEvent::Status(status) => Self::Status(status),
648            ControlEvent::Completed { summary } => Self::Completed { summary },
649            ControlEvent::Error(error) => Self::Error(error),
650        }
651    }
652}
653
654impl From<SubscriptionNotification> for ManagedEvent {
655    fn from(notification: SubscriptionNotification) -> Self {
656        match notification {
657            SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
658            SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
659            SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
660            SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
661            SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
662        }
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use std::{
669        future::Future,
670        pin::Pin,
671        sync::Mutex,
672        task::{Poll, Waker},
673    };
674
675    use futures::{StreamExt, stream::FuturesUnordered};
676    use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};
677
678    use super::*;
679    use crate::{
680        CreateSession,
681        managed::RECONNECT_MAX_TOTAL,
682        subscriptions::{DiagnosticContext, DiagnosticNotification},
683    };
684
685    fn notification() -> SubscriptionNotification {
686        SubscriptionNotification::Diagnostic(DiagnosticNotification {
687            context: DiagnosticContext { slot: 0 },
688            slot: 0,
689            probe_index: 0,
690            label: None,
691            market: String::new(),
692            usd_value: 0,
693            router_slot: None,
694            results: None,
695            account_hashes: Vec::new(),
696            err: None,
697        })
698    }
699
700    /// Driver and sibling under one `FuturesUnordered` on a `block_on` thread, the sibling waking
701    /// mid-poll while senders on other threads write the driver's queue.
702    #[test]
703    fn subscription_reads_keep_a_sibling_wakeup_on_the_block_on_thread() {
704        const SENDERS: usize = 4;
705        const ROUNDS: usize = 2_000;
706
707        let runtime = tokio::runtime::Builder::new_multi_thread()
708            .enable_all()
709            .build()
710            .unwrap();
711        let (sender, notifications) = mpsc::channel(1_024);
712        let (_status_tx, status) = watch::channel(ConnectionStatus::Up);
713        let mut subscriptions = vec![SubscriptionHandle {
714            status,
715            notifications,
716            join: runtime.spawn(async {}),
717        }];
718        // Concurrent writers, so a read often meets a slot claimed but not yet written.
719        for _ in 0..SENDERS {
720            let sender = sender.clone();
721            std::thread::spawn(move || {
722                while sender.blocking_send(notification()).is_ok() {
723                    std::thread::sleep(Duration::from_micros(20));
724                }
725            });
726        }
727
728        let (done_tx, done) = std::sync::mpsc::channel();
729        std::thread::spawn(move || {
730            let sibling = Arc::new(Mutex::new(None::<Waker>));
731            let driver = {
732                let sibling = sibling.clone();
733                async move {
734                    for _ in 0..ROUNDS {
735                        while try_next_subscription_event(&mut subscriptions).is_some() {}
736                        if let Some(waker) = sibling.lock().unwrap().as_ref() {
737                            waker.wake_by_ref();
738                        }
739                        // Spins to meet the next message while it is being written.
740                        while try_next_subscription_event(&mut subscriptions).is_none() {}
741                        wait_any_subscription_event(&mut subscriptions).await;
742                    }
743                }
744            };
745            let sibling = std::future::poll_fn(move |cx| {
746                *sibling.lock().unwrap() = Some(cx.waker().clone());
747                Poll::<()>::Pending
748            });
749            // Never woken, so a pass over the other two ends without the yield that would wake
750            // the task again.
751            let idle = std::future::pending::<()>();
752            let mut sessions: FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>> =
753                FuturesUnordered::new();
754            sessions.push(Box::pin(driver));
755            sessions.push(Box::pin(sibling));
756            sessions.push(Box::pin(idle));
757            runtime.block_on(sessions.next());
758            let _ = done_tx.send(());
759        });
760
761        assert!(
762            done.recv_timeout(Duration::from_secs(30)).is_ok(),
763            "the sessions stopped: a subscription read consumed the block_on thread's wakeup"
764        );
765    }
766
767    fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
768        CreateSession::builder()
769            .start_slot(1)
770            .slot_count(1)
771            .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
772            .build()
773            .into_params()
774            .expect("valid create params")
775    }
776
777    #[test]
778    fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
779        let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
780            (
781                "v0 unset",
782                CreateBacktestSessionRequest::V0(params(None)),
783                Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
784            ),
785            (
786                "v0 explicit",
787                CreateBacktestSessionRequest::V0(params(Some(42))),
788                Some(42),
789            ),
790            (
791                "v1 single unset",
792                CreateBacktestSessionRequestV1 {
793                    request: params(None),
794                    parallel: false,
795                    name: None,
796                    create_token: None,
797                }
798                .into(),
799                Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
800            ),
801            (
802                "v1 parallel unset keeps the server's parallel default",
803                CreateBacktestSessionRequestV1 {
804                    request: params(None),
805                    parallel: true,
806                    name: None,
807                    create_token: None,
808                }
809                .into(),
810                None,
811            ),
812        ];
813
814        for (name, mut create, expected) in cases {
815            set_default_disconnect_timeout(&mut create);
816            let (request, _) = create.into_request_and_parallel();
817            assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
818        }
819    }
820
821    #[test]
822    fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
823        assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
824        const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
825    }
826}