simulator-client 0.21.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! Ergonomic async client for the simulator backtest WebSocket API.
//!
//! This wraps the `simulator-api` request/response protocol with helpers for common
//! workflows (create session, wait ready, continue/advance, close), while still allowing full
//! access to raw `BacktestRequest` / `BacktestResponse` when needed.
//!
//! The crate has two layers, and picking the right one matters:
//!
//! - [`ManagedBacktestSession`] (and [`managed::ManagedParallelSession`]) own the
//!   control and subscription WebSockets, keepalives, and — critically —
//!   **reconnect and reattach**. Use this layer.
//! - [`BacktestClient`] / [`BacktestSession`] are one raw WebSocket with no
//!   reconnect and no reattach. A dropped connection ends the run. Reach for it
//!   only when driving the protocol by hand.
//!
//! A backtest session outlives its WebSocket, but only if something reattaches
//! to it — see [Reconnects and session handoff](#reconnects-and-session-handoff).
//!
//! ## Quickstart
//! ```no_run
//! use simulator_client::{Continue, CreateSession, ManagedBacktestSession, managed::ManagedEvent};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let create = CreateSession::builder()
//!     .start_slot(100)
//!     .slot_count(10)
//!     .build()
//!     .into_request()?;
//!
//! let mut session = ManagedBacktestSession::start(
//!     "wss://simulator.termina.technology/backtest".to_string(),
//!     "my-api-key".to_string(),
//!     create,
//! )
//! .await?;
//!
//! loop {
//!     match session.next_event().await? {
//!         ManagedEvent::ReadyForContinue => {
//!             let advance = Continue::builder().advance_count(1).build().into_params();
//!             session.send_continue(advance).await?;
//!         }
//!         ManagedEvent::Completed { .. } => break,
//!         _ => {}
//!     }
//! }
//!
//! session.shutdown().await;
//! # Ok(()) }
//! ```
//!
//! ## Reconnects and session handoff
//!
//! The management service is a proxy: the session itself runs on a separate
//! host and survives the loss of your control WebSocket. What it does *not*
//! survive is nobody coming back for it.
//!
//! The management service is redeployed routinely. On shutdown it pauses each
//! live session, records it as handed off, and closes the control WebSocket
//! with code `1012` (`management handoff`). The session then waits to be
//! claimed. A client that reconnects and sends `AttachBacktestSession` +
//! `ResumeAttachedSession` picks it up where it left off, replaying any
//! responses it missed from `last_sequence`. A client that treats the close as
//! fatal loses the run: the server reclaims the unclaimed session once
//! `disconnect_timeout_secs` elapses.
//!
//! Not every disconnect is that graceful — a load balancer draining a target
//! can reset the socket with no close frame at all — so treat *any* transport
//! error as "reconnect and reattach", not as a failed run.
//!
//! [`ManagedBacktestSession`] does all of this for you: its control task
//! reconnects with backoff ([`managed::RECONNECT_MAX_ATTEMPTS`] attempts within
//! [`managed::RECONNECT_MAX_TOTAL`]) and re-handshakes with attach + resume. It
//! also defaults `disconnect_timeout_secs` to
//! [`managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`] so the server holds the session
//! for at least as long as the client will keep trying.
//!
//! On the raw [`BacktestSession`] this is yours to implement: reconnect with
//! [`BacktestClient::attach_session`], passing the last sequence number you
//! observed, then [`BacktestSession::resume_attached_session`]. Set
//! `disconnect_timeout_secs` on the create request to a window that covers your
//! retry policy — the server's own default is deliberately short (tens of
//! seconds).
//!
//! ## Low-level lifecycle notes
//! These describe [`BacktestClient`] / [`BacktestSession`]; the managed layer
//! handles all of it internally.
//! - `BacktestClient::create_session` sends `CreateBacktestSession` and waits for
//!   `SessionCreated`, buffering other responses until the session is ready.
//! - `BacktestSession::close` sends `CloseBacktestSession` and then closes the WebSocket.
//! - Dropping `BacktestSession` sends a best-effort WebSocket close frame if a Tokio runtime
//!   is available. Call `close` explicitly to ensure server-side session cleanup.
//! - `connect_timeout` governs the initial handshake; `request_timeout` applies to send/receive
//!   operations and can be overridden per call.
//! - For streaming workflows, use `BacktestSession::responses` (consumes the session) or
//!   `next_event` to keep readiness state in sync while consuming responses.
//!
//! ## Subscribe options
//! [`SubscribeConfig`] carries the cross-cutting options every subscribe accepts
//! (`replayFromSlot`, `compression`, `intraSlotUpdates`); merge it into a raw
//! subscribe's params with [`SubscribeConfig::apply_to`]. This crate leaves every
//! field it doesn't itself need unset, so those follow the server's defaults —
//! notably `accountSubscribe` / `programSubscribe` deliver Agave-parity one
//! notification per account per slot unless you set `intra_slot_updates`.
//!
//! ```no_run
//! use simulator_client::SubscribeConfig;
//!
//! let mut params = serde_json::json!([ "<pubkey>", { "encoding": "base64" } ]);
//! SubscribeConfig {
//!     intra_slot_updates: true,
//!     ..SubscribeConfig::default()
//! }
//! .apply_to(&mut params);
//! ```

#![forbid(unsafe_code)]

mod builders;
mod client;
mod error;
pub mod geyser;
pub mod injection;
pub mod managed;
mod ranges;
pub mod reroute_report;
pub mod rpc;
mod session;
pub mod subscriptions;
mod transaction_step;
pub mod urls;

pub use builders::{Continue, CreateSession, SerializeEncodeError};
pub use client::BacktestClient;
pub use error::{BacktestClientError, BacktestClientResult};
pub use geyser::SessionGeyserChannel;
pub use injection::{ProgramModError, build_program_injection, modify_program_via_rpc};
pub use managed::{ControlEvent, ManagedBacktestSession, ManagedEvent, ManagedSessionError};
pub use ranges::{RangeBound, filter_ranges};
pub use session::{
    AdvanceState, BacktestSession, ContinueResult, CoverageError, ReadyOutcome, SessionCoverage,
};
pub use simulator_api::{
    AvailableRange, BundleKind, DiscoveryFilter, SnapshotSlotResponse,
    route_plan::{self, FULL_PERCENT, RouteHop, RoutePlan},
    split_range,
    subscribe_config::{Compression, SubscribeConfig},
    usage::{ComputeTotals, SessionCounts, UsageBucket, UsageReport},
};
pub use subscriptions::{
    AccountDiffContext, AccountDiffNotification, AccountDiffSubscriptionHandle,
    ActionResultContext, ActionResultNotification, ActionSubscriptionHandle,
    ActionTransactionOutcome, LogSubscriptionHandle, RerouteContext, RerouteLegNotification,
    RerouteNotification, RoutedAccountDiffNotification, SubscriptionError, SubscriptionHandle,
    SubscriptionRuntimeError, UiAccountConversionError, account_data_from_ui,
    subscribe_account_diffs, subscribe_account_diffs_many, subscribe_actions,
    subscribe_program_diffs, subscribe_program_logs, subscribe_reroutes,
};
pub use transaction_step::{DiscoveryPause, DiscoveryStepResult};
pub use urls::{UrlError, backtest_ws_url, http_to_ws_url};