simulator-client 0.30.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! A parallel run: one create, then one session for each part of the split range.

use std::sync::Arc;

use futures::{StreamExt, future::join_all, stream::FuturesUnordered};
use simulator_api::{
    ContinueParams, ControlSessionId, SlotRange,
    session_endpoint::{ParallelGrant, SessionGrant},
};
use solana_address::Address;
use solana_client::nonblocking::rpc_client::RpcClient;
use tokio_util::sync::CancellationToken;

use super::{
    ManagedBacktestSession, ManagedEvent, ManagedSessionError, ReconnectCoordinator, SessionInfo,
    StartSessionParams, SubscriptionDiagnostics,
    grant::{LivenessCheck, ManagementTarget, ParallelCreate, request_parallel_grant},
};

/// A parallel run: one session for each part of the split range.
///
/// ```no_run
/// use simulator_client::{
///     Continue, CreateSession, ManagedEvent, ManagedSessionError,
///     managed::{ManagedParallelSession, StartSessionParams},
/// };
/// use tokio::task::JoinSet;
///
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let create = CreateSession::builder()
///     .start_slot(380_000_000)
///     .end_slot(380_050_000)
///     .parallel(true)
///     .capacity_wait_timeout_secs(300)
///     .build()
///     .into_request()?;
///
/// let mut parallel = ManagedParallelSession::start_with_params(
///     StartSessionParams::builder()
///         .url("simulator.termina.technology")
///         .api_key(std::env::var("SIMULATOR_API_KEY")?)
///         .create(create)
///         .build(),
/// )
/// .await?;
///
/// let step = Continue::builder().advance_count(100).build().into_params();
/// let mut tasks = JoinSet::new();
/// for mut sub in parallel.take_sub_sessions() {
///     let step = step.clone();
///     tasks.spawn(async move {
///         loop {
///             match sub.next_event().await? {
///                 ManagedEvent::ReadyForContinue => sub.send_continue(step.clone()).await?,
///                 ManagedEvent::Completed { .. } => break,
///                 ManagedEvent::Error(err) if err.is_terminal() => {
///                     return Err(ManagedSessionError::Remote(err));
///                 }
///                 _ => {}
///             }
///         }
///         sub.shutdown().await;
///         Ok::<(), ManagedSessionError>(())
///     });
/// }
/// while let Some(res) = tasks.join_next().await {
///     res??;
/// }
/// parallel.shutdown().await;
/// # Ok(())
/// # }
/// ```
pub struct ManagedParallelSession {
    control_session_id: ControlSessionId,
    control_session_name: Option<String>,
    sub_sessions: Vec<ParallelSubSession>,
    session_cancel: CancellationToken,
}

impl ManagedParallelSession {
    /// Start a parallel session from explicit [`StartSessionParams`].
    ///
    /// `params.subscription_diagnostics` is shared by every session, so its counters aggregate the
    /// whole run.
    ///
    /// Returns once this client is attached to every session. If one attach fails, the sessions
    /// already attached are closed and that error is returned. A child that is not yet attached
    /// when a sibling fails keeps running until it times out.
    ///
    /// # Errors
    ///
    /// - [`ManagedSessionError::ApiKeyRejected`] if the server refuses the API key.
    /// - [`ManagedSessionError::Create`] if the server rejects the create request, the
    ///   connection fails past the retry budget, a session's endpoint is not reachable
    ///   ([`CreateError::EndpointUnreachable`](super::CreateError::EndpointUnreachable)), or the
    ///   request does not set `parallel`
    ///   ([`CreateError::SingleRequest`](super::CreateError::SingleRequest)).
    /// - [`ManagedSessionError::SessionTokenRejected`] if a session's endpoint refuses its token.
    /// - [`ManagedSessionError::Cancelled`] if `params.parent_cancel` fires first.
    pub async fn start_with_params(
        params: StartSessionParams,
    ) -> Result<Self, ManagedSessionError> {
        let StartSessionParams {
            url,
            api_key,
            extra_headers,
            create,
            parent_cancel,
            subscription_diagnostics,
        } = params;
        let management = ManagementTarget::managed(url, api_key, extra_headers);
        let create = ParallelCreate::try_from(create).map_err(ManagedSessionError::Create)?;
        let ParallelGrant {
            control_session_id,
            control_session_name,
            sessions,
        } = parent_cancel
            .run_until_cancelled(request_parallel_grant(&management, create))
            .await
            .ok_or(ManagedSessionError::Cancelled)??;

        let session_cancel = parent_cancel.child_token();
        // One coordinator shared across the sub-sessions: their data planes share
        // the client's link, so a dropped subscription parks until its streaming
        // siblings finish before reconnecting into the freed bandwidth.
        let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
        // Attach all at once: each session's first-attach timer is already running.
        let attached: Vec<_> = sessions
            .into_iter()
            .map(|grant| {
                let check = LivenessCheck::child(management.clone(), control_session_id, &grant);
                attach_child(
                    grant,
                    check,
                    &session_cancel,
                    reconnect_coordinator.clone(),
                    subscription_diagnostics.clone(),
                )
            })
            .collect::<FuturesUnordered<_>>()
            .collect()
            .await;
        // In completion order, so the first error is the one that cancelled the others.
        let mut sub_sessions = Vec::new();
        let mut failure = None;
        for attached in attached {
            match attached {
                Ok(sub) => sub_sessions.push(sub),
                Err(error) => failure = failure.or(Some(error)),
            }
        }
        if let Some(error) = failure {
            join_all(sub_sessions.into_iter().map(ParallelSubSession::shutdown)).await;
            return Err(error);
        }
        sub_sessions.sort_by_key(|sub| sub.session_info().grant.slots.start());

        Ok(Self {
            control_session_id,
            control_session_name: control_session_name.map(|name| name.as_str().to_owned()),
            sub_sessions,
            session_cancel,
        })
    }

    /// The server's id for this run.
    pub fn control_session_id(&self) -> ControlSessionId {
        self.control_session_id
    }

    /// The run's name, if the server reported one.
    pub fn control_session_name(&self) -> Option<&str> {
        self.control_session_name.as_deref()
    }

    /// Take the sessions for driving. Returns them once; subsequent calls
    /// yield an empty vec.
    pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
        std::mem::take(&mut self.sub_sessions)
    }

    /// Cancel the run and close every session on the server. Sessions still being driven get
    /// [`ManagedSessionError::Cancelled`].
    pub async fn shutdown(mut self) {
        self.session_cancel.cancel();
        join_all(
            std::mem::take(&mut self.sub_sessions)
                .into_iter()
                .map(ParallelSubSession::shutdown),
        )
        .await;
    }
}

impl Drop for ManagedParallelSession {
    fn drop(&mut self) {
        self.session_cancel.cancel();
    }
}

/// A failure cancels `run_cancel`, so the siblings' attaches stop.
async fn attach_child(
    grant: SessionGrant,
    check: LivenessCheck,
    run_cancel: &CancellationToken,
    reconnect_coordinator: Arc<ReconnectCoordinator>,
    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
) -> Result<ParallelSubSession, ManagedSessionError> {
    let attached = ManagedBacktestSession::attach_granted(
        grant,
        check,
        run_cancel,
        Some(reconnect_coordinator),
        subscription_diagnostics,
    )
    .await;
    if attached.is_err() {
        run_cancel.cancel();
    }
    attached.map(|session| ParallelSubSession { session })
}

/// One session of a parallel run, driven like a [`ManagedBacktestSession`] with a subset of its
/// methods: `subscribe_transactions`, `subscribe_account_diffs`, `subscribe_actions`,
/// `next_event`, `send_continue`, `rpc` and `shutdown`.
pub struct ParallelSubSession {
    session: ManagedBacktestSession,
}

impl ParallelSubSession {
    /// What the server reported when it created this session.
    pub fn session_info(&self) -> &SessionInfo {
        self.session.session_info()
    }

    /// This session's slot range.
    pub fn range(&self) -> SlotRange {
        self.session_info().grant.slots
    }

    /// As [`ManagedBacktestSession::subscribe_transactions`].
    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
        self.session.subscribe_transactions(program_ids);
    }

    /// As [`ManagedBacktestSession::subscribe_account_diffs`].
    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
        self.session.subscribe_account_diffs(program_ids);
    }

    /// As [`ManagedBacktestSession::subscribe_actions`].
    pub fn subscribe_actions(&mut self) {
        self.session.subscribe_actions();
    }

    /// As [`ManagedBacktestSession::next_event`].
    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
        self.session.next_event().await
    }

    /// As [`ManagedBacktestSession::rpc`].
    pub fn rpc(&self) -> &RpcClient {
        self.session.rpc()
    }

    /// As [`ManagedBacktestSession::send_continue`].
    pub async fn send_continue(
        &mut self,
        params: ContinueParams,
    ) -> Result<(), ManagedSessionError> {
        self.session.send_continue(params).await
    }

    /// Close this session on the server and wait until it has stopped.
    pub async fn shutdown(self) {
        self.session.shutdown().await;
    }
}