Skip to main content

simulator_client/managed/
parallel.rs

1//! A parallel run: one create, then one session for each part of the split range.
2
3use std::sync::Arc;
4
5use futures::{StreamExt, future::join_all, stream::FuturesUnordered};
6use simulator_api::{
7    ContinueParams, ControlSessionId, SlotRange,
8    session_endpoint::{ParallelGrant, SessionGrant},
9};
10use solana_address::Address;
11use solana_client::nonblocking::rpc_client::RpcClient;
12use tokio_util::sync::CancellationToken;
13
14use super::{
15    ManagedBacktestSession, ManagedEvent, ManagedSessionError, ReconnectCoordinator, SessionInfo,
16    StartSessionParams, SubscriptionDiagnostics,
17    grant::{LivenessCheck, ManagementTarget, ParallelCreate, request_parallel_grant},
18};
19
20/// A parallel run: one session for each part of the split range.
21///
22/// ```no_run
23/// use simulator_client::{
24///     Continue, CreateSession, ManagedEvent, ManagedSessionError,
25///     managed::{ManagedParallelSession, StartSessionParams},
26/// };
27/// use tokio::task::JoinSet;
28///
29/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
30/// let create = CreateSession::builder()
31///     .start_slot(380_000_000)
32///     .end_slot(380_050_000)
33///     .parallel(true)
34///     .capacity_wait_timeout_secs(300)
35///     .build()
36///     .into_request()?;
37///
38/// let mut parallel = ManagedParallelSession::start_with_params(
39///     StartSessionParams::builder()
40///         .url("simulator.termina.technology")
41///         .api_key(std::env::var("SIMULATOR_API_KEY")?)
42///         .create(create)
43///         .build(),
44/// )
45/// .await?;
46///
47/// let step = Continue::builder().advance_count(100).build().into_params();
48/// let mut tasks = JoinSet::new();
49/// for mut sub in parallel.take_sub_sessions() {
50///     let step = step.clone();
51///     tasks.spawn(async move {
52///         loop {
53///             match sub.next_event().await? {
54///                 ManagedEvent::ReadyForContinue => sub.send_continue(step.clone()).await?,
55///                 ManagedEvent::Completed { .. } => break,
56///                 ManagedEvent::Error(err) if err.is_terminal() => {
57///                     return Err(ManagedSessionError::Remote(err));
58///                 }
59///                 _ => {}
60///             }
61///         }
62///         sub.shutdown().await;
63///         Ok::<(), ManagedSessionError>(())
64///     });
65/// }
66/// while let Some(res) = tasks.join_next().await {
67///     res??;
68/// }
69/// parallel.shutdown().await;
70/// # Ok(())
71/// # }
72/// ```
73pub struct ManagedParallelSession {
74    control_session_id: ControlSessionId,
75    control_session_name: Option<String>,
76    sub_sessions: Vec<ParallelSubSession>,
77    session_cancel: CancellationToken,
78}
79
80impl ManagedParallelSession {
81    /// Start a parallel session from explicit [`StartSessionParams`].
82    ///
83    /// `params.subscription_diagnostics` is shared by every session, so its counters aggregate the
84    /// whole run.
85    ///
86    /// Returns once this client is attached to every session. If one attach fails, the sessions
87    /// already attached are closed and that error is returned. A child that is not yet attached
88    /// when a sibling fails keeps running until it times out.
89    ///
90    /// # Errors
91    ///
92    /// - [`ManagedSessionError::ApiKeyRejected`] if the server refuses the API key.
93    /// - [`ManagedSessionError::Create`] if the server rejects the create request, the
94    ///   connection fails past the retry budget, a session's endpoint is not reachable
95    ///   ([`CreateError::EndpointUnreachable`](super::CreateError::EndpointUnreachable)), or the
96    ///   request does not set `parallel`
97    ///   ([`CreateError::SingleRequest`](super::CreateError::SingleRequest)).
98    /// - [`ManagedSessionError::SessionTokenRejected`] if a session's endpoint refuses its token.
99    /// - [`ManagedSessionError::Cancelled`] if `params.parent_cancel` fires first.
100    pub async fn start_with_params(
101        params: StartSessionParams,
102    ) -> Result<Self, ManagedSessionError> {
103        let StartSessionParams {
104            url,
105            api_key,
106            extra_headers,
107            create,
108            parent_cancel,
109            subscription_diagnostics,
110        } = params;
111        let management = ManagementTarget::managed(url, api_key, extra_headers);
112        let create = ParallelCreate::try_from(create).map_err(ManagedSessionError::Create)?;
113        let ParallelGrant {
114            control_session_id,
115            control_session_name,
116            sessions,
117        } = parent_cancel
118            .run_until_cancelled(request_parallel_grant(&management, create))
119            .await
120            .ok_or(ManagedSessionError::Cancelled)??;
121
122        let session_cancel = parent_cancel.child_token();
123        // One coordinator shared across the sub-sessions: their data planes share
124        // the client's link, so a dropped subscription parks until its streaming
125        // siblings finish before reconnecting into the freed bandwidth.
126        let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
127        // Attach all at once: each session's first-attach timer is already running.
128        let attached: Vec<_> = sessions
129            .into_iter()
130            .map(|grant| {
131                let check = LivenessCheck::child(management.clone(), control_session_id, &grant);
132                attach_child(
133                    grant,
134                    check,
135                    &session_cancel,
136                    Arc::clone(&reconnect_coordinator),
137                    Arc::clone(&subscription_diagnostics),
138                )
139            })
140            .collect::<FuturesUnordered<_>>()
141            .collect()
142            .await;
143        // In completion order, so the first error is the one that cancelled the others.
144        let mut sub_sessions = Vec::new();
145        let mut failure = None;
146        for attached in attached {
147            match attached {
148                Ok(sub) => sub_sessions.push(sub),
149                Err(error) => failure = failure.or(Some(error)),
150            }
151        }
152        if let Some(error) = failure {
153            join_all(sub_sessions.into_iter().map(ParallelSubSession::shutdown)).await;
154            return Err(error);
155        }
156        sub_sessions.sort_by_key(|sub| sub.session_info().grant.slots.start());
157
158        Ok(Self {
159            control_session_id,
160            control_session_name: control_session_name.map(|name| name.as_str().to_owned()),
161            sub_sessions,
162            session_cancel,
163        })
164    }
165
166    /// The server's id for this run.
167    pub fn control_session_id(&self) -> ControlSessionId {
168        self.control_session_id
169    }
170
171    /// The run's name, if the server reported one.
172    pub fn control_session_name(&self) -> Option<&str> {
173        self.control_session_name.as_deref()
174    }
175
176    /// Take the sessions for driving. Returns them once; subsequent calls
177    /// yield an empty vec.
178    pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
179        std::mem::take(&mut self.sub_sessions)
180    }
181
182    /// Cancel the run and close every session on the server. Sessions still being driven get
183    /// [`ManagedSessionError::Cancelled`].
184    pub async fn shutdown(mut self) {
185        self.session_cancel.cancel();
186        join_all(
187            std::mem::take(&mut self.sub_sessions)
188                .into_iter()
189                .map(ParallelSubSession::shutdown),
190        )
191        .await;
192    }
193}
194
195impl Drop for ManagedParallelSession {
196    fn drop(&mut self) {
197        self.session_cancel.cancel();
198    }
199}
200
201/// A failure cancels `run_cancel`, so the siblings' attaches stop.
202async fn attach_child(
203    grant: SessionGrant,
204    check: LivenessCheck,
205    run_cancel: &CancellationToken,
206    reconnect_coordinator: Arc<ReconnectCoordinator>,
207    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
208) -> Result<ParallelSubSession, ManagedSessionError> {
209    let attached = ManagedBacktestSession::attach_granted(
210        grant,
211        check,
212        run_cancel,
213        Some(reconnect_coordinator),
214        subscription_diagnostics,
215    )
216    .await;
217    if attached.is_err() {
218        run_cancel.cancel();
219    }
220    attached.map(|session| ParallelSubSession { session })
221}
222
223/// One session of a parallel run, driven like a [`ManagedBacktestSession`] with a subset of its
224/// methods: `subscribe_transactions`, `subscribe_account_diffs`, `subscribe_actions`,
225/// `next_event`, `send_continue`, `rpc` and `shutdown`.
226pub struct ParallelSubSession {
227    session: ManagedBacktestSession,
228}
229
230impl ParallelSubSession {
231    /// What the server reported when it created this session.
232    pub fn session_info(&self) -> &SessionInfo {
233        self.session.session_info()
234    }
235
236    /// This session's slot range.
237    pub fn range(&self) -> SlotRange {
238        self.session_info().grant.slots
239    }
240
241    /// As [`ManagedBacktestSession::subscribe_transactions`].
242    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
243        self.session.subscribe_transactions(program_ids);
244    }
245
246    /// As [`ManagedBacktestSession::subscribe_account_diffs`].
247    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
248        self.session.subscribe_account_diffs(program_ids);
249    }
250
251    /// As [`ManagedBacktestSession::subscribe_actions`].
252    pub fn subscribe_actions(&mut self) {
253        self.session.subscribe_actions();
254    }
255
256    /// As [`ManagedBacktestSession::next_event`].
257    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
258        self.session.next_event().await
259    }
260
261    /// As [`ManagedBacktestSession::rpc`].
262    pub fn rpc(&self) -> &RpcClient {
263        self.session.rpc()
264    }
265
266    /// As [`ManagedBacktestSession::send_continue`].
267    pub async fn send_continue(
268        &mut self,
269        params: ContinueParams,
270    ) -> Result<(), ManagedSessionError> {
271        self.session.send_continue(params).await
272    }
273
274    /// Close this session on the server and wait until it has stopped.
275    pub async fn shutdown(self) {
276        self.session.shutdown().await;
277    }
278}