Skip to main content

simulator_client/managed/
session.rs

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