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 DiscoveryBatchEvent, PausedEvent, SessionId, SessionSummary,
7 session_endpoint::{SessionEndpointUrl, SessionGrant},
8};
9use solana_address::Address;
10use solana_client::nonblocking::rpc_client::RpcClient;
11use solana_commitment_config::CommitmentConfig;
12use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
13use thiserror::Error;
14use tokio::sync::{mpsc, watch};
15use tokio_util::sync::CancellationToken;
16
17use super::{
18 ConnectionFailure, ConnectionStatus, ControlEvent, DEFAULT_DISCONNECT_TIMEOUT_SECS,
19 ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
20 SubscriptionHandle, SubscriptionNotification,
21 control::{ControlHandle, spawn_control_manager},
22 grant::{LivenessCheck, ManagementTarget, SingleCreate, request_session_grant},
23 spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
24 spawn_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
25 spawn_transaction_subscription_manager,
26};
27use crate::{
28 endpoint::rpc_client,
29 error::err_chain,
30 subscriptions::{
31 AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
32 ReplacementNotification,
33 },
34};
35
36/// Why `start` could not create a managed session; carried by [`ManagedSessionError::Create`].
37#[derive(Debug, Error)]
38pub enum CreateError {
39 /// The server refused the create request. Retry later when
40 /// [`BacktestError::is_retryable`] is true, as for insufficient capacity
41 /// ([`BacktestError::Internal`]). Otherwise fix what the error names.
42 #[error("server rejected the request: {0}")]
43 Rejected(BacktestError),
44
45 /// Nothing reached the server past the retry budget, or the server refused each create while
46 /// it was draining. No session started. Retry later.
47 #[error("{0}")]
48 Connection(String),
49
50 /// The connection dropped after the create was sent. A session may have started. Not retried.
51 #[error(
52 "the connection to the server dropped after the create was sent ({reason}); a session \
53 may have started, and it ends itself when nobody attaches"
54 )]
55 LostAfterSend {
56 /// Why the connection dropped.
57 reason: String,
58 },
59
60 /// The server's reply does not fit this client, such as a single-session reply to a
61 /// parallel create. Stop: upgrade `simulator-client`.
62 #[error("{0}")]
63 Protocol(String),
64
65 /// The request sets `parallel`. Nothing was sent.
66 #[error("a parallel create needs ManagedParallelSession")]
67 ParallelRequest,
68
69 /// The request does not set `parallel`. Nothing was sent: start it with
70 /// [`ManagedBacktestSession`].
71 #[error("a single create needs ManagedBacktestSession")]
72 SingleRequest,
73
74 /// The session exists, but its endpoint took no connection in time. Not retried.
75 #[error("session {session_id} is not reachable at {endpoint}: {reason}")]
76 EndpointUnreachable {
77 /// The granted session.
78 session_id: SessionId,
79 /// The session's endpoint.
80 endpoint: SessionEndpointUrl,
81 /// Why the last connect failed.
82 reason: String,
83 },
84}
85
86impl CreateError {
87 /// Whether calling `start` again later, with the same request, may succeed.
88 pub fn is_retryable(&self) -> bool {
89 match self {
90 Self::Rejected(err) => err.is_retryable(),
91 Self::Connection(_) => true,
92 Self::LostAfterSend { .. }
93 | Self::EndpointUnreachable { .. }
94 | Self::Protocol(_)
95 | Self::ParallelRequest
96 | Self::SingleRequest => false,
97 }
98 }
99}
100
101/// Why a managed session call failed.
102///
103/// The managed layer has already retried what it could, so none of these is worth retrying on
104/// the same session: each variant says what to do instead. [`Self::is_retryable`] says whether
105/// a new session may succeed.
106#[derive(Debug, Error)]
107pub enum ManagedSessionError {
108 /// `start` could not create the session. Match on [`CreateError`] for why, or call
109 /// [`CreateError::is_retryable`].
110 #[error("session create failed: {0}")]
111 Create(CreateError),
112
113 /// The session is over. `next_event` returns this after `Completed` and after a terminal
114 /// [`ManagedEvent::Error`].
115 #[error("control channel closed")]
116 ControlClosed,
117
118 /// The session control channel gave up: retries ran out or the session has ended. Start a
119 /// new session.
120 #[error("control failed: {0}")]
121 ControlFailed(String),
122
123 /// A subscription gave up, so its notifications are incomplete. `send_continue` returns this
124 /// when a subscription ran out of retries; `next_event` returns it in place of `Completed`
125 /// when a subscription stopped delivering before its stream ended. Rerun the session if you
126 /// need every notification.
127 #[error("subscription failed: {0}")]
128 SubscriptionFailed(String),
129
130 /// The session was cancelled: [`StartSessionParams::parent_cancel`] fired or, for a
131 /// [`ParallelSubSession`](super::ParallelSubSession), its run was shut down. Stop.
132 #[error("cancelled")]
133 Cancelled,
134
135 /// The server refused the API key when the session control channel connected (HTTP 401 or
136 /// 403). Never retried: fix the key.
137 #[error("API key rejected: HTTP {0}")]
138 ApiKeyRejected(http::StatusCode),
139
140 /// The session's endpoint refused the token (HTTP 401). Start a new session.
141 #[error("the session's endpoint rejected the token")]
142 SessionTokenRejected,
143
144 /// The session control channel closed while a continue was being handed to it: the session
145 /// has ended. Call `next_event` to see why, or stop.
146 #[error("control closed while sending continue: {0}")]
147 ContinueSend(String),
148
149 /// The server reported an error. Returned by [`ManagedBacktestSession::wait_until_ready`] and
150 /// [`ManagedBacktestSession::run_to_completion`] on any [`ManagedEvent::Error`], terminal or
151 /// not. Fix what it names and start a new session.
152 #[error("server error: {0}")]
153 Remote(BacktestError),
154
155 /// The session sent `Completed` before its first `ReadyForContinue`. Returned by
156 /// [`ManagedBacktestSession::wait_until_ready`].
157 #[error("session completed before it was ready to continue")]
158 CompletedBeforeReady,
159}
160
161impl ManagedSessionError {
162 /// Whether starting a new session with the same request, after a backoff, may succeed.
163 /// `SessionTokenRejected` is true: a new session gets a new token. `ControlFailed` is true
164 /// also when the session has ended.
165 pub fn is_retryable(&self) -> bool {
166 match self {
167 Self::Create(err) => err.is_retryable(),
168 Self::Remote(err) => err.is_retryable(),
169 Self::ControlFailed(_) | Self::SubscriptionFailed(_) | Self::SessionTokenRejected => {
170 true
171 }
172 Self::ControlClosed
173 | Self::ContinueSend(_)
174 | Self::Cancelled
175 | Self::ApiKeyRejected(_)
176 | Self::CompletedBeforeReady => false,
177 }
178 }
179}
180
181/// An event from a managed session, returned by `next_event`.
182///
183/// One stream carries both the session control channel's events and the notifications of every
184/// `subscribe_*` call.
185///
186/// # Order
187///
188/// - Control events arrive in the order the server sent them, starting with `Status` updates
189/// while the session starts.
190/// - Each subscription's notifications arrive in order. Across subscriptions, and between
191/// notifications and control events, there is no order: a `Transaction` can arrive after the
192/// `Slot` or `ReadyForContinue` that follows it.
193/// - Every notification arrives before `Completed`: on `Completed`, the session waits for each
194/// subscription to finish its stream.
195/// - After `Completed`, `next_event` returns [`ManagedSessionError::ControlClosed`].
196/// - If a subscription stops delivering before its stream ends, `next_event` returns the
197/// notifications it has, then [`ManagedSessionError::SubscriptionFailed`] in place of
198/// `Completed`.
199/// - After a reconnect, a subscription sends the last slot it delivered again. Dedupe
200/// transactions by signature, and account diffs by (signature, account, slot).
201#[derive(Debug)]
202pub enum ManagedEvent {
203 /// The session is waiting for your next [`ManagedBacktestSession::send_continue`] or
204 /// [`ManagedBacktestSession::send_continue_to`]. Read and change state through the session's
205 /// RPC endpoint now.
206 ReadyForContinue,
207 /// The session stopped where a `send_continue_to` asked. Read state now, but do not answer
208 /// it: a `ReadyForContinue` always follows, and that is the event to answer.
209 Paused(PausedEvent),
210 /// An upcoming batch matches a discovery filter from the create request. Send
211 /// `send_continue_to(slot, batch_index)` to pause just before it executes.
212 DiscoveryBatch(DiscoveryBatchEvent),
213 /// The slot that just executed. A skipped slot has no block and sends none.
214 Slot(u64),
215 /// A progress update, while the session starts and during each continue.
216 Status(BacktestStatus),
217 /// The session replayed its last slot. Every notification has arrived before this; the next
218 /// `next_event` returns [`ManagedSessionError::ControlClosed`].
219 Completed {
220 /// `None` unless the session was created with `send_summary`.
221 summary: Option<SessionSummary>,
222 },
223 /// The server reported an error. When [`BacktestError::is_terminal`] is true the session is
224 /// over: stop driving it. Otherwise it keeps running. Per-transaction `SimulationError`s
225 /// never arrive here; they are logged.
226 Error(BacktestError),
227 /// From [`ManagedBacktestSession::subscribe_transactions`]: a transaction in the shape
228 /// `getTransaction` returns. Program logs are in `meta.log_messages`.
229 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
230 /// From [`ManagedBacktestSession::subscribe_account_diffs`]: one changed account.
231 AccountDiff(AccountDiffNotification),
232 /// From [`ManagedBacktestSession::subscribe_actions`]: the result of one pre-scheduled
233 /// action.
234 ActionResult(ActionResultNotification),
235 /// From [`ManagedBacktestSession::subscribe_diagnostics`]: one diagnostic probe sample.
236 Diagnostic(DiagnosticNotification),
237 /// From [`ManagedBacktestSession::subscribe_replacements`]: one reroute result for an
238 /// original swap.
239 Replacement(Box<ReplacementNotification>),
240}
241
242/// Idle backstop for the completion drain: if no trailing notification arrives
243/// for this long after `Completed`, assume the data plane is stalled and stop
244/// waiting. Bounds the gap *between* notifications, not total drain time, so a
245/// slow-but-flowing stream (large backlog over a slow link) is never truncated.
246const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
247
248pub(super) enum DrainOutcome {
249 /// Every subscription delivered its terminal (channels closed), or the
250 /// session was cancelled. The drained events are complete up to the stop.
251 Complete(Vec<ManagedEvent>),
252 /// The idle backstop fired with subscriptions still open — trailing
253 /// notifications never arrived, so the run is incomplete. Carries whatever
254 /// was drained before the stall.
255 Stalled(Vec<ManagedEvent>),
256 /// A subscription's reconnect after the last continue was refused for its token. Carries
257 /// whatever was drained before.
258 TokenRejected(Vec<ManagedEvent>),
259}
260
261/// A session that reconnects on its own.
262///
263/// 1. [`Self::start`] it.
264/// 2. Call `subscribe_*` for the notifications you need.
265/// 3. Drive it: read [`Self::next_event`], and answer each [`ManagedEvent::ReadyForContinue`]
266/// with one [`Self::send_continue`] or [`Self::send_continue_to`]. Never answer
267/// [`ManagedEvent::Paused`]: a `ReadyForContinue` follows it, and answering both sends two
268/// continues. [`Self::run_to_completion`] runs this loop for you.
269/// 4. [`Self::shutdown`] it. Dropping it instead cancels the session without waiting for its
270/// tasks to stop.
271///
272/// See the [module docs](crate::managed) for what happens when a connection drops.
273pub struct ManagedBacktestSession {
274 session_info: SessionInfo,
275 rpc: RpcClient,
276 control: Option<ControlHandle>,
277 subscriptions: Vec<SubscriptionHandle>,
278 session_cancel: CancellationToken,
279 /// Notifications drained on `Completed`, followed by `Completed`; served in
280 /// order by `next_event`. `None` until completion.
281 post_completion: Option<VecDeque<ManagedEvent>>,
282 /// Surfaced after `post_completion` drains: set when the completion drain
283 /// stalled (idle backstop fired with subscriptions still open), so a
284 /// silently-truncated run fails loudly instead of reporting `Completed`.
285 post_completion_error: Option<ManagedSessionError>,
286 completion_drain_timeout: Duration,
287 /// Shared across a parallel batch so this session's subscription reconnects
288 /// step aside for still-streaming siblings. `None` for a standalone session.
289 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
290 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
291}
292
293impl ManagedBacktestSession {
294 /// Create a session and return once this client is attached to it on the session's own
295 /// endpoint.
296 ///
297 /// `url` may be a bare host (see [`StartSessionParams::url`]). Build `create` with
298 /// [`crate::CreateSession`] and `into_request`. Use [`Self::start_with_params`] for extra
299 /// headers or your own cancellation token.
300 ///
301 /// # Errors
302 ///
303 /// - [`ManagedSessionError::ApiKeyRejected`] if the server refuses the API key.
304 /// - [`ManagedSessionError::Create`] if the server rejects the create request, the
305 /// connection fails past the retry budget, or the session's endpoint is not reachable
306 /// ([`CreateError::EndpointUnreachable`]).
307 /// - [`ManagedSessionError::SessionTokenRejected`] if the session's endpoint refuses the
308 /// token.
309 pub async fn start(
310 url: String,
311 api_key: String,
312 create: CreateBacktestSessionRequest,
313 ) -> Result<Self, ManagedSessionError> {
314 Self::start_with_params(
315 StartSessionParams::builder()
316 .url(url)
317 .api_key(api_key)
318 .create(create)
319 .build(),
320 None,
321 )
322 .await
323 }
324
325 /// Like [`Self::start`], from explicit [`StartSessionParams`]. Pass `None` for
326 /// `reconnect_coordinator`; it is internal plumbing for parallel runs.
327 ///
328 /// A create that leaves `disconnect_timeout_secs` unset gets
329 /// [`DEFAULT_DISCONNECT_TIMEOUT_SECS`], so the server keeps the session while the client
330 /// reconnects.
331 ///
332 /// # Errors
333 ///
334 /// As [`Self::start`], plus [`ManagedSessionError::Cancelled`] if
335 /// [`StartSessionParams::parent_cancel`] fires first.
336 pub async fn start_with_params(
337 params: StartSessionParams,
338 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
339 ) -> Result<Self, ManagedSessionError> {
340 let StartSessionParams {
341 url,
342 api_key,
343 extra_headers,
344 create,
345 parent_cancel,
346 subscription_diagnostics,
347 } = params;
348 let create = SingleCreate::try_from(create)
349 .map_err(ManagedSessionError::Create)?
350 .with_default_disconnect_timeout(DEFAULT_DISCONNECT_TIMEOUT_SECS);
351 let management = ManagementTarget::managed(url, api_key, extra_headers);
352 let grant = parent_cancel
353 .run_until_cancelled(request_session_grant(&management, create))
354 .await
355 .ok_or(ManagedSessionError::Cancelled)??;
356 let check = LivenessCheck::session(management, &grant);
357 Self::attach_granted(
358 grant,
359 check,
360 &parent_cancel,
361 reconnect_coordinator,
362 subscription_diagnostics,
363 )
364 .await
365 }
366
367 pub(super) async fn attach_granted(
368 grant: SessionGrant,
369 check: LivenessCheck,
370 parent_cancel: &CancellationToken,
371 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
372 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
373 ) -> Result<Self, ManagedSessionError> {
374 let rpc = rpc_client(&grant, CommitmentConfig::confirmed()).map_err(|e| {
375 ManagedSessionError::Create(CreateError::Protocol(format!(
376 "the grant gives no usable RPC client: {}",
377 err_chain(&e)
378 )))
379 })?;
380 let session_info = SessionInfo::from_grant(grant.clone());
381 let session_cancel = parent_cancel.child_token();
382 let mut control = spawn_control_manager(grant, check, session_cancel.clone());
383
384 tokio::select! {
385 biased;
386 _ = parent_cancel.cancelled() => {
387 session_cancel.cancel();
388 control.join().await;
389 return Err(ManagedSessionError::Cancelled);
390 }
391 result = control.wait_attached() => result?,
392 }
393
394 Ok(Self {
395 session_info,
396 rpc,
397 control: Some(control),
398 subscriptions: Vec::new(),
399 session_cancel,
400 post_completion: None,
401 post_completion_error: None,
402 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
403 reconnect_coordinator,
404 subscription_diagnostics,
405 })
406 }
407
408 /// Metadata reported by the server when the session was created.
409 pub fn session_info(&self) -> &SessionInfo {
410 &self.session_info
411 }
412
413 /// RPC client (`confirmed` commitment) for the session's chain state at its current slot;
414 /// serves from the first `ReadyForContinue` until `Completed`, and 502s after.
415 pub fn rpc(&self) -> &RpcClient {
416 &self.rpc
417 }
418
419 /// Override the completion-drain idle timeout (default 60 s). The drain gives up only after this
420 /// long with no trailing notification; it does not cap total drain time.
421 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
422 self.completion_drain_timeout = idle_timeout;
423 }
424
425 /// Subscribe to every transaction that mentions any of `program_ids`. Each arrives as
426 /// [`ManagedEvent::Transaction`], with program logs in `meta.log_messages`.
427 ///
428 /// Every `subscribe_*` call opens one WebSocket on the session's RPC endpoint; the next
429 /// `send_continue` waits until it is connected.
430 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
431 self.subscriptions
432 .push(spawn_transaction_subscription_manager(
433 self.session_info.rpc_endpoint.clone(),
434 program_ids,
435 self.session_cancel.clone(),
436 self.reconnect_coordinator.clone(),
437 self.subscription_diagnostics.clone(),
438 ));
439 }
440
441 /// Subscribe to changes of every account owned by any of `program_ids`. Each change arrives
442 /// as [`ManagedEvent::AccountDiff`]. To follow single accounts across reconnects, subscribe
443 /// to their owner program and keep the diffs for their addresses.
444 /// [`crate::subscribe_account_diffs`] follows single accounts but does not reconnect.
445 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
446 self.subscriptions
447 .push(spawn_account_diff_subscription_manager(
448 self.session_info.rpc_endpoint.clone(),
449 program_ids,
450 self.session_cancel.clone(),
451 self.reconnect_coordinator.clone(),
452 self.subscription_diagnostics.clone(),
453 ));
454 }
455
456 /// Subscribe to the results of the pre-scheduled actions in the create request. Each arrives
457 /// as [`ManagedEvent::ActionResult`].
458 pub fn subscribe_actions(&mut self) {
459 self.subscriptions.push(spawn_action_subscription_manager(
460 self.session_info.rpc_endpoint.clone(),
461 self.session_cancel.clone(),
462 self.reconnect_coordinator.clone(),
463 self.subscription_diagnostics.clone(),
464 ));
465 }
466
467 /// Subscribe to the reroute results for each original swap: re-quotes, venue probes and the
468 /// original swaps replayed beside them. One stream carries all three, as
469 /// [`ManagedEvent::Replacement`].
470 pub fn subscribe_replacements(&mut self) {
471 self.subscriptions
472 .push(spawn_replacement_subscription_manager(
473 self.session_info.rpc_endpoint.clone(),
474 self.session_cancel.clone(),
475 self.reconnect_coordinator.clone(),
476 self.subscription_diagnostics.clone(),
477 ));
478 }
479
480 /// Subscribe to the samples of the diagnostic probes in the create request. Each arrives as
481 /// [`ManagedEvent::Diagnostic`].
482 pub fn subscribe_diagnostics(&mut self) {
483 self.subscriptions
484 .push(spawn_diagnostic_subscription_manager(
485 self.session_info.rpc_endpoint.clone(),
486 self.session_cancel.clone(),
487 self.reconnect_coordinator.clone(),
488 self.subscription_diagnostics.clone(),
489 ));
490 }
491
492 /// Wait for the next event. See [`ManagedEvent`] for the order events arrive in.
493 ///
494 /// # Errors
495 ///
496 /// - [`ManagedSessionError::ControlClosed`] once the session is over.
497 /// - [`ManagedSessionError::ControlFailed`] once the session control channel gave up.
498 /// - [`ManagedSessionError::SubscriptionFailed`] in place of `Completed` when a subscription's
499 /// stream ended early.
500 /// - [`ManagedSessionError::Cancelled`] if the session was cancelled.
501 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
502 // Serve buffered post-completion events (trailing notifications, then
503 // `Completed`); the control stream is gone once they're exhausted.
504 if let Some(buffered) = self.post_completion.as_mut() {
505 if let Some(event) = buffered.pop_front() {
506 return Ok(event);
507 }
508 // Buffer drained: surface a pending stall error so an incomplete
509 // run fails loudly, else the control stream is simply done.
510 return Err(self
511 .post_completion_error
512 .take()
513 .unwrap_or(ManagedSessionError::ControlClosed));
514 }
515
516 // Queued events are served without awaiting, so a caller pumping a
517 // backlog would otherwise never yield.
518 tokio::task::coop::consume_budget().await;
519
520 // Scope the borrows to the `select!` so the completion drain below can
521 // re-borrow `self`.
522 let event = {
523 let cancel = self.session_cancel.clone();
524 let control = self
525 .control
526 .as_mut()
527 .ok_or(ManagedSessionError::ControlClosed)?;
528 let subscriptions = &mut self.subscriptions;
529 // Control first: its task stops reading the socket, keepalive
530 // included, while its queue is full, so a subscription backlog must
531 // never hold control events back.
532 match recv_queued(&mut control.events) {
533 Some(event) => ManagedEvent::from(event),
534 None => {
535 if let Some(event) = try_next_subscription_event(subscriptions) {
536 return Ok(event);
537 }
538 tokio::select! {
539 biased;
540 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
541 event = control.events.recv() => match event {
542 Some(event) => ManagedEvent::from(event),
543 None => return Err(control_closed(&control.status)),
544 },
545 event = wait_any_subscription_event(subscriptions) => event,
546 }
547 }
548 }
549 };
550
551 // Bind the payload so the re-emitted `Completed` below carries it.
552 let ManagedEvent::Completed { summary } = event else {
553 return Ok(event);
554 };
555
556 // Flush trailing notifications up to each subscription's terminal,
557 // delivering them before `Completed` so none are dropped.
558 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) =
559 match drain_subscriptions_until_complete(
560 &mut self.subscriptions,
561 &self.session_cancel,
562 self.completion_drain_timeout,
563 )
564 .await
565 {
566 DrainOutcome::Complete(events) => {
567 (events.into(), Ok(ManagedEvent::Completed { summary }))
568 }
569 // Report failure rather than a silently truncated `Completed`.
570 DrainOutcome::Stalled(events) => (
571 events.into(),
572 Err(ManagedSessionError::SubscriptionFailed(
573 "completion drain stalled: subscriptions did not deliver their \
574 end-of-stream terminals; the captured stream is incomplete"
575 .to_string(),
576 )),
577 ),
578 DrainOutcome::TokenRejected(events) => (
579 events.into(),
580 Err(ManagedSessionError::SessionTokenRejected),
581 ),
582 };
583 match terminal {
584 Ok(completed) => buffered.push_back(completed),
585 Err(err) => self.post_completion_error = Some(err),
586 }
587 let first = buffered.pop_front();
588 self.post_completion = Some(buffered);
589 match first {
590 Some(event) => Ok(event),
591 // Nothing buffered and the run failed: surface the error now.
592 None => Err(self
593 .post_completion_error
594 .take()
595 .unwrap_or(ManagedSessionError::ControlClosed)),
596 }
597 }
598
599 /// Wait until the session control channel and every subscription are connected, then send
600 /// a continue. Build `params` with [`crate::Continue`].
601 ///
602 /// Call this once per [`ManagedEvent::ReadyForContinue`].
603 ///
604 /// # Errors
605 ///
606 /// - [`ManagedSessionError::ControlFailed`] or [`ManagedSessionError::SubscriptionFailed`]
607 /// if a connection gave up.
608 /// - [`ManagedSessionError::ContinueSend`] if the session has ended.
609 /// - [`ManagedSessionError::Cancelled`] if the session was cancelled.
610 pub async fn send_continue(
611 &mut self,
612 params: ContinueParams,
613 ) -> Result<(), ManagedSessionError> {
614 self.wait_all_up().await?;
615 self.control_mut()?
616 .send_continue(params)
617 .await
618 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
619 }
620
621 /// Wait until the session control channel and every subscription are connected, then send
622 /// a `continueTo`: execute through `params.slot`, or with `batch_index`, up to just before
623 /// that batch of it. Call this once per [`ManagedEvent::ReadyForContinue`].
624 ///
625 /// The session then sends [`ManagedEvent::Paused`], where you can read state, and
626 /// [`ManagedEvent::ReadyForContinue`], which you answer. Rules for `params`:
627 ///
628 /// - `slot` must be after the last executed slot. Otherwise `next_event` returns an
629 /// `InvalidRequest` [`ManagedEvent::Error`] and the session stays where it is.
630 /// - `slot` must have a block. A skipped slot has none, and the session does not stop at
631 /// it: it runs on to the end of the range.
632 /// - With a [`ManagedEvent::DiscoveryBatch`], pass its `slot` and `batch_index` to pause
633 /// just before the matching batch.
634 ///
635 /// To run your transactions just before slot `n`, pause at `n - 1`, then send them with the
636 /// next continue. They run and commit before slot `n`'s block:
637 ///
638 /// ```no_run
639 /// use simulator_client::{Continue, ContinueToParams, ManagedBacktestSession, ManagedEvent};
640 /// use solana_transaction::versioned::VersionedTransaction;
641 ///
642 /// async fn run_before(
643 /// session: &mut ManagedBacktestSession,
644 /// n: u64,
645 /// tx: &VersionedTransaction,
646 /// ) -> Result<(), Box<dyn std::error::Error>> {
647 /// let pause = ContinueToParams { slot: n - 1, batch_index: None };
648 /// session.send_continue_to(pause).await?;
649 /// loop {
650 /// match session.next_event().await? {
651 /// ManagedEvent::ReadyForContinue => break,
652 /// ManagedEvent::Error(err) => return Err(err.into()),
653 /// _ => {}
654 /// }
655 /// }
656 /// let step = Continue::builder().build().push_transaction(tx)?.into_params();
657 /// session.send_continue(step).await?;
658 /// Ok(())
659 /// }
660 /// ```
661 ///
662 /// If slot `n - 1` may be skipped, or to skip the round trip, schedule the transaction
663 /// instead: a [`ScheduledAction`](simulator_api::ScheduledAction) with a `BeforeSlot` anchor
664 /// and [`ActionKind::Send`](simulator_api::ActionKind::Send).
665 ///
666 /// # Errors
667 ///
668 /// As [`Self::send_continue`].
669 pub async fn send_continue_to(
670 &mut self,
671 params: ContinueToParams,
672 ) -> Result<(), ManagedSessionError> {
673 self.wait_all_up().await?;
674 self.control_mut()?
675 .send_continue_to(params)
676 .await
677 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
678 }
679
680 /// Wait for the first `ReadyForContinue`, from which the session's RPC endpoint serves the
681 /// state before the start slot executes (the end of slot `start_slot - 1`). Earlier events
682 /// (only `Status` in practice) are discarded.
683 ///
684 /// # Errors
685 ///
686 /// [`ManagedSessionError::CompletedBeforeReady`], [`ManagedSessionError::Remote`] on an
687 /// `Error` event, or any error of [`Self::next_event`]. The session is not shut down; call
688 /// [`Self::shutdown`].
689 pub async fn wait_until_ready(&mut self) -> Result<(), ManagedSessionError> {
690 loop {
691 match self.next_event().await? {
692 ManagedEvent::ReadyForContinue => return Ok(()),
693 ManagedEvent::Completed { .. } => {
694 return Err(ManagedSessionError::CompletedBeforeReady);
695 }
696 ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
697 _ => {}
698 }
699 }
700 }
701
702 /// On every `ReadyForContinue`, send `step.clone()` until `Completed`; every other event,
703 /// `Paused` included, goes to `on_event`. Any `Error` event, terminal or not, stops the loop
704 /// and returns `Remote`. Always shuts the session down before returning. A caller that already
705 /// consumed a ready (e.g. via [`Self::wait_until_ready`]) sends its first
706 /// [`Self::send_continue`] itself.
707 ///
708 /// Returns the summary carried by `Completed`.
709 ///
710 /// # Errors
711 ///
712 /// [`ManagedSessionError::Remote`] on an `Error` event, or any error of [`Self::next_event`]
713 /// and [`Self::send_continue`].
714 pub async fn run_to_completion(
715 mut self,
716 step: ContinueParams,
717 mut on_event: impl FnMut(ManagedEvent),
718 ) -> Result<Option<SessionSummary>, ManagedSessionError> {
719 let result = async {
720 loop {
721 match self.next_event().await? {
722 ManagedEvent::ReadyForContinue => {
723 self.send_continue(step.clone()).await?;
724 }
725 ManagedEvent::Completed { summary } => return Ok(summary),
726 ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
727 other => on_event(other),
728 }
729 }
730 }
731 .await;
732 self.shutdown().await;
733 result
734 }
735
736 /// Cancel the session, closing it on the server, and wait until its connections have
737 /// stopped.
738 pub async fn shutdown(mut self) {
739 self.session_cancel.cancel();
740 if let Some(control) = self.control.take() {
741 control.join().await;
742 }
743 for sub in std::mem::take(&mut self.subscriptions) {
744 // A manager parked on a full queue exits only once the queue closes.
745 drop(sub.notifications);
746 let _ = sub.join.await;
747 }
748 }
749
750 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
751 self.control
752 .as_mut()
753 .ok_or(ManagedSessionError::ControlClosed)
754 }
755
756 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
757 let control = self
758 .control
759 .as_ref()
760 .ok_or(ManagedSessionError::ControlClosed)?
761 .status
762 .clone();
763 let subscriptions = self
764 .subscriptions
765 .iter()
766 .map(|s| s.status.clone())
767 .collect();
768 wait_connections_up(control, subscriptions, &self.session_cancel).await
769 }
770}
771
772fn failure_error(
773 reason: &ConnectionFailure,
774 failed: fn(String) -> ManagedSessionError,
775) -> ManagedSessionError {
776 match reason {
777 ConnectionFailure::TokenRejected => ManagedSessionError::SessionTokenRejected,
778 ConnectionFailure::RetriesExhausted(_)
779 | ConnectionFailure::SessionEnded
780 | ConnectionFailure::Refused(_) => failed(reason.to_string()),
781 }
782}
783
784/// Block until the control connection and every subscription connection report
785/// `Up`, returning an error if any reports `Failed` or the token is cancelled.
786pub(super) async fn wait_connections_up(
787 mut control: watch::Receiver<ConnectionStatus>,
788 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
789 cancel: &CancellationToken,
790) -> Result<(), ManagedSessionError> {
791 loop {
792 let control_status = control.borrow().clone();
793 match &control_status {
794 ConnectionStatus::Failed(why) => {
795 return Err(failure_error(why, ManagedSessionError::ControlFailed));
796 }
797 ConnectionStatus::Ended => return Err(ManagedSessionError::ControlClosed),
798 ConnectionStatus::Up | ConnectionStatus::Down => {}
799 }
800
801 let mut all_subscriptions_up = true;
802 for subscription in &subscriptions {
803 match &*subscription.borrow() {
804 ConnectionStatus::Failed(why) => {
805 return Err(failure_error(why, ManagedSessionError::SubscriptionFailed));
806 }
807 ConnectionStatus::Up => {}
808 _ => all_subscriptions_up = false,
809 }
810 }
811
812 if control_status == ConnectionStatus::Up && all_subscriptions_up {
813 return Ok(());
814 }
815
816 tokio::select! {
817 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
818 _ = control.changed() => {}
819 _ = wait_any_subscription_change(&mut subscriptions) => {}
820 }
821 }
822}
823
824/// Drain trailing notifications until every subscription closes, `cancel` fires, or an `Up`
825/// subscription delivers nothing for `idle_timeout` (`Stalled`).
826/// A `Down` subscription is reconnecting, not stalled.
827pub(super) async fn drain_subscriptions_until_complete(
828 subscriptions: &mut [SubscriptionHandle],
829 cancel: &CancellationToken,
830 idle_timeout: std::time::Duration,
831) -> DrainOutcome {
832 let mut events = Vec::new();
833 if subscriptions.is_empty() {
834 return DrainOutcome::Complete(events);
835 }
836 loop {
837 while let Some(event) = try_next_subscription_event(subscriptions) {
838 events.push(event);
839 }
840 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
841 let any_rejected = subscriptions.iter().any(|s| {
842 matches!(
843 *s.status.borrow(),
844 ConnectionStatus::Failed(ConnectionFailure::TokenRejected)
845 )
846 });
847 let any_failed = subscriptions
848 .iter()
849 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
850 return match (any_rejected, any_failed) {
851 (true, _) => DrainOutcome::TokenRejected(events),
852 (false, true) => DrainOutcome::Stalled(events),
853 (false, false) => DrainOutcome::Complete(events),
854 };
855 }
856 tokio::select! {
857 biased;
858 // A cancel is an intentional stop, not a data-plane failure.
859 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
860 // Idle gap elapsed. A still-`Up` subscription should be delivering
861 // but isn't — a hung data plane (stall). If the open subscriptions
862 // are all reconnecting/parked (`Down`), keep waiting: the
863 // coordinator is deferring them on purpose, not failing.
864 _ = tokio::time::sleep(idle_timeout) => {
865 let any_up = subscriptions.iter().any(|s| {
866 !s.notifications.is_closed()
867 && matches!(*s.status.borrow(), ConnectionStatus::Up)
868 });
869 if any_up {
870 return DrainOutcome::Stalled(events);
871 }
872 }
873 received = recv_any_open_subscription(subscriptions) => {
874 // `None` means a channel closed; the loop re-checks all-closed.
875 if let Some(event) = received {
876 events.push(event);
877 }
878 }
879 }
880 }
881}
882
883impl Drop for ManagedBacktestSession {
884 fn drop(&mut self) {
885 self.session_cancel.cancel();
886 }
887}
888
889pub(super) async fn wait_any_subscription_change(
890 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
891) {
892 if subscriptions.is_empty() {
893 std::future::pending::<()>().await;
894 return;
895 }
896 let _ =
897 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
898}
899
900pub(super) async fn wait_any_subscription_event(
901 subscriptions: &mut [SubscriptionHandle],
902) -> ManagedEvent {
903 loop {
904 if let Some(event) = try_next_subscription_event(subscriptions) {
905 return event;
906 }
907
908 let futures: Vec<_> = subscriptions
909 .iter_mut()
910 .filter(|s| !s.notifications.is_closed())
911 .map(|s| Box::pin(s.notifications.recv()))
912 .collect();
913
914 if futures.is_empty() {
915 std::future::pending::<()>().await;
916 }
917
918 let (notification, _, _) = futures::future::select_all(futures).await;
919 if let Some(notification) = notification {
920 return notification.into();
921 }
922 }
923}
924
925/// Await the next notification from any still-open subscription channel,
926/// returning `None` when one closes. Unlike [`wait_any_subscription_event`],
927/// which never resolves on closure, this lets the completion drain observe
928/// per-channel end-of-stream.
929pub(super) async fn recv_any_open_subscription(
930 subscriptions: &mut [SubscriptionHandle],
931) -> Option<ManagedEvent> {
932 let futures: Vec<_> = subscriptions
933 .iter_mut()
934 .filter(|s| !s.notifications.is_closed())
935 .map(|s| Box::pin(s.notifications.recv()))
936 .collect();
937
938 if futures.is_empty() {
939 return None;
940 }
941
942 let (notification, _, _) = futures::future::select_all(futures).await;
943 notification.map(Into::into)
944}
945
946pub(super) fn try_next_subscription_event(
947 subscriptions: &mut [SubscriptionHandle],
948) -> Option<ManagedEvent> {
949 for subscription in subscriptions {
950 if let Some(notification) = recv_queued(&mut subscription.notifications) {
951 return Some(notification.into());
952 }
953 }
954 None
955}
956
957/// Not `try_recv`, which parks the thread on a message still being written and so consumes a
958/// `block_on` task's pending wakeup. Unconstrained so a spent coop budget never hides a queued
959/// message.
960fn recv_queued<T>(receiver: &mut mpsc::Receiver<T>) -> Option<T> {
961 tokio::task::coop::unconstrained(receiver.recv())
962 .now_or_never()
963 .flatten()
964}
965
966fn control_closed(status: &watch::Receiver<ConnectionStatus>) -> ManagedSessionError {
967 match &*status.borrow() {
968 ConnectionStatus::Failed(why) => failure_error(why, ManagedSessionError::ControlFailed),
969 ConnectionStatus::Up | ConnectionStatus::Down | ConnectionStatus::Ended => {
970 ManagedSessionError::ControlClosed
971 }
972 }
973}
974
975impl From<ControlEvent> for ManagedEvent {
976 fn from(event: ControlEvent) -> Self {
977 match event {
978 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
979 ControlEvent::Paused(event) => Self::Paused(event),
980 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
981 ControlEvent::Slot(slot) => Self::Slot(slot),
982 ControlEvent::Status(status) => Self::Status(status),
983 ControlEvent::Completed { summary } => Self::Completed { summary },
984 ControlEvent::Error(error) => Self::Error(error),
985 }
986 }
987}
988
989impl From<SubscriptionNotification> for ManagedEvent {
990 fn from(notification: SubscriptionNotification) -> Self {
991 match notification {
992 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
993 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
994 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
995 SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
996 SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
997 }
998 }
999}
1000
1001#[cfg(test)]
1002mod tests {
1003 use std::{
1004 future::Future,
1005 pin::Pin,
1006 sync::Mutex,
1007 task::{Poll, Waker},
1008 };
1009
1010 use futures::{StreamExt, stream::FuturesUnordered};
1011 use simulator_api::MAX_DISCONNECT_TIMEOUT_SECS;
1012
1013 use super::*;
1014 use crate::{
1015 managed::RECONNECT_MAX_TOTAL,
1016 subscriptions::{DiagnosticContext, DiagnosticNotification},
1017 };
1018
1019 #[tokio::test]
1020 async fn drain_reports_a_token_rejected_after_the_last_continue() {
1021 let (_status_tx, status) =
1022 watch::channel(ConnectionStatus::Failed(ConnectionFailure::TokenRejected));
1023 let (sender, notifications) = mpsc::channel(1);
1024 drop(sender);
1025 let mut subscriptions = vec![SubscriptionHandle {
1026 status,
1027 notifications,
1028 join: tokio::spawn(async {}),
1029 }];
1030
1031 let outcome = drain_subscriptions_until_complete(
1032 &mut subscriptions,
1033 &CancellationToken::new(),
1034 Duration::from_secs(1),
1035 )
1036 .await;
1037
1038 assert!(matches!(outcome, DrainOutcome::TokenRejected(_)));
1039 }
1040
1041 fn notification() -> SubscriptionNotification {
1042 SubscriptionNotification::Diagnostic(DiagnosticNotification {
1043 context: DiagnosticContext { slot: 0 },
1044 slot: 0,
1045 probe_index: 0,
1046 label: None,
1047 market: String::new(),
1048 usd_value: 0,
1049 pairs: Vec::new(),
1050 router_slot: None,
1051 results: None,
1052 account_hashes: Vec::new(),
1053 err: None,
1054 })
1055 }
1056
1057 /// Driver and sibling under one `FuturesUnordered` on a `block_on` thread, the sibling waking
1058 /// mid-poll while senders on other threads write the driver's queue.
1059 #[test]
1060 fn subscription_reads_keep_a_sibling_wakeup_on_the_block_on_thread() {
1061 const SENDERS: usize = 4;
1062 const ROUNDS: usize = 2_000;
1063
1064 let runtime = tokio::runtime::Builder::new_multi_thread()
1065 .enable_all()
1066 .build()
1067 .unwrap();
1068 let (sender, notifications) = mpsc::channel(1_024);
1069 let (_status_tx, status) = watch::channel(ConnectionStatus::Up);
1070 let mut subscriptions = vec![SubscriptionHandle {
1071 status,
1072 notifications,
1073 join: runtime.spawn(async {}),
1074 }];
1075 // Concurrent writers, so a read often meets a slot claimed but not yet written.
1076 for _ in 0..SENDERS {
1077 let sender = sender.clone();
1078 std::thread::spawn(move || {
1079 while sender.blocking_send(notification()).is_ok() {
1080 std::thread::sleep(Duration::from_micros(20));
1081 }
1082 });
1083 }
1084
1085 let (done_tx, done) = std::sync::mpsc::channel();
1086 std::thread::spawn(move || {
1087 let sibling = Arc::new(Mutex::new(None::<Waker>));
1088 let driver = {
1089 let sibling = sibling.clone();
1090 async move {
1091 for _ in 0..ROUNDS {
1092 while try_next_subscription_event(&mut subscriptions).is_some() {}
1093 if let Some(waker) = sibling.lock().unwrap().as_ref() {
1094 waker.wake_by_ref();
1095 }
1096 // Spins to meet the next message while it is being written.
1097 while try_next_subscription_event(&mut subscriptions).is_none() {}
1098 wait_any_subscription_event(&mut subscriptions).await;
1099 }
1100 }
1101 };
1102 let sibling = std::future::poll_fn(move |cx| {
1103 *sibling.lock().unwrap() = Some(cx.waker().clone());
1104 Poll::<()>::Pending
1105 });
1106 // Never woken, so a pass over the other two ends without the yield that would wake
1107 // the task again.
1108 let idle = std::future::pending::<()>();
1109 let mut sessions: FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>> =
1110 FuturesUnordered::new();
1111 sessions.push(Box::pin(driver));
1112 sessions.push(Box::pin(sibling));
1113 sessions.push(Box::pin(idle));
1114 runtime.block_on(sessions.next());
1115 let _ = done_tx.send(());
1116 });
1117
1118 assert!(
1119 done.recv_timeout(Duration::from_secs(30)).is_ok(),
1120 "the sessions stopped: a subscription read consumed the block_on thread's wakeup"
1121 );
1122 }
1123
1124 #[test]
1125 fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
1126 assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
1127 const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
1128 }
1129}