Skip to main content

simulator_client/
lib.rs

1//! Ergonomic async client for the simulator backtest WebSocket API.
2//!
3//! This wraps the `simulator-api` request/response protocol with helpers for common
4//! workflows (create session, wait ready, continue/advance, close), while still allowing full
5//! access to raw `BacktestRequest` / `BacktestResponse` when needed.
6//!
7//! The crate has two layers, and picking the right one matters:
8//!
9//! - [`ManagedBacktestSession`] (and [`managed::ManagedParallelSession`]) own the
10//!   control and subscription WebSockets, keepalives, and — critically —
11//!   **reconnect and reattach**. Use this layer.
12//! - [`BacktestClient`] / [`BacktestSession`] are one raw WebSocket with no
13//!   reconnect and no reattach. A dropped connection ends the run. Reach for it
14//!   only when driving the protocol by hand.
15//!
16//! A backtest session outlives its WebSocket, but only if something reattaches
17//! to it — see [Reconnects and session handoff](#reconnects-and-session-handoff).
18//!
19//! ## Quickstart
20//! ```no_run
21//! use simulator_client::{Continue, CreateSession, ManagedBacktestSession, managed::ManagedEvent};
22//!
23//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
24//! let create = CreateSession::builder()
25//!     .start_slot(100)
26//!     .slot_count(10)
27//!     .build()
28//!     .into_request()?;
29//!
30//! let mut session = ManagedBacktestSession::start(
31//!     "wss://simulator.termina.technology/backtest".to_string(),
32//!     "my-api-key".to_string(),
33//!     create,
34//! )
35//! .await?;
36//!
37//! loop {
38//!     match session.next_event().await? {
39//!         ManagedEvent::ReadyForContinue => {
40//!             let advance = Continue::builder().advance_count(1).build().into_params();
41//!             session.send_continue(advance).await?;
42//!         }
43//!         ManagedEvent::Completed { .. } => break,
44//!         _ => {}
45//!     }
46//! }
47//!
48//! session.shutdown().await;
49//! # Ok(()) }
50//! ```
51//!
52//! ## Reconnects and session handoff
53//!
54//! The management service is a proxy: the session itself runs on a separate
55//! host and survives the loss of your control WebSocket. What it does *not*
56//! survive is nobody coming back for it.
57//!
58//! The management service is redeployed routinely. On shutdown it pauses each
59//! live session, records it as handed off, and closes the control WebSocket
60//! with code `1012` (`management handoff`). The session then waits to be
61//! claimed. A client that reconnects and sends `AttachBacktestSession` +
62//! `ResumeAttachedSession` picks it up where it left off, replaying any
63//! responses it missed from `last_sequence`. A client that treats the close as
64//! fatal loses the run: the server reclaims the unclaimed session once
65//! `disconnect_timeout_secs` elapses.
66//!
67//! Not every disconnect is that graceful — a load balancer draining a target
68//! can reset the socket with no close frame at all — so treat *any* transport
69//! error as "reconnect and reattach", not as a failed run.
70//!
71//! [`ManagedBacktestSession`] does all of this for you: its control task
72//! reconnects with backoff ([`managed::RECONNECT_MAX_ATTEMPTS`] attempts within
73//! [`managed::RECONNECT_MAX_TOTAL`]) and re-handshakes with attach + resume. It
74//! also defaults `disconnect_timeout_secs` to
75//! [`managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`] so the server holds the session
76//! for at least as long as the client will keep trying.
77//!
78//! On the raw [`BacktestSession`] this is yours to implement: reconnect with
79//! [`BacktestClient::attach_session`], passing the last sequence number you
80//! observed, then [`BacktestSession::resume_attached_session`]. Set
81//! `disconnect_timeout_secs` on the create request to a window that covers your
82//! retry policy — the server's own default is deliberately short (tens of
83//! seconds).
84//!
85//! ## Low-level lifecycle notes
86//! These describe [`BacktestClient`] / [`BacktestSession`]; the managed layer
87//! handles all of it internally.
88//! - `BacktestClient::create_session` sends `CreateBacktestSession` and waits for
89//!   `SessionCreated`, buffering other responses until the session is ready.
90//! - `BacktestSession::close` sends `CloseBacktestSession` and then closes the WebSocket.
91//! - Dropping `BacktestSession` sends a best-effort WebSocket close frame if a Tokio runtime
92//!   is available. Call `close` explicitly to ensure server-side session cleanup.
93//! - `connect_timeout` governs the initial handshake; `request_timeout` applies to send/receive
94//!   operations and can be overridden per call.
95//! - For streaming workflows, use `BacktestSession::responses` (consumes the session) or
96//!   `next_event` to keep readiness state in sync while consuming responses.
97//!
98//! ## Subscribe options
99//! [`SubscribeConfig`] carries the cross-cutting options every subscribe accepts
100//! (`replayFromSlot`, `compression`, `intraSlotUpdates`); merge it into a raw
101//! subscribe's params with [`SubscribeConfig::apply_to`]. This crate leaves every
102//! field it doesn't itself need unset, so those follow the server's defaults —
103//! notably `accountSubscribe` / `programSubscribe` deliver Agave-parity one
104//! notification per account per slot unless you set `intra_slot_updates`.
105//!
106//! ```no_run
107//! use simulator_client::SubscribeConfig;
108//!
109//! let mut params = serde_json::json!([ "<pubkey>", { "encoding": "base64" } ]);
110//! SubscribeConfig {
111//!     intra_slot_updates: true,
112//!     ..SubscribeConfig::default()
113//! }
114//! .apply_to(&mut params);
115//! ```
116
117#![forbid(unsafe_code)]
118
119mod builders;
120mod client;
121mod error;
122pub mod geyser;
123pub mod injection;
124pub mod managed;
125mod ranges;
126pub mod recipes;
127pub mod reroute_report;
128pub mod rpc;
129mod session;
130pub mod subscriptions;
131mod transaction_step;
132pub mod urls;
133
134pub use builders::{Continue, CreateSession, SerializeEncodeError};
135pub use client::BacktestClient;
136pub use error::{BacktestClientError, BacktestClientResult};
137pub use geyser::SessionGeyserChannel;
138pub use injection::{ProgramModError, build_program_injection, modify_program_via_rpc};
139pub use managed::{ControlEvent, ManagedBacktestSession, ManagedEvent, ManagedSessionError};
140pub use ranges::{RangeBound, filter_ranges};
141pub use session::{
142    AdvanceState, BacktestSession, ContinueResult, CoverageError, ReadyOutcome, SessionCoverage,
143};
144pub use simulator_api::{
145    AvailableRange, BundleBuildStatus, BundleKind, DepthCoverageResponse, DepthRequest,
146    DepthSource, DepthStatusResponse, DirectFillTemplate, DiscoveryFilter, SnapshotSlotResponse,
147    SwapMode, TakerSlots, TemplateAccount, TemplateInstruction,
148    route_plan::{self, FULL_PERCENT, RouteHop, RoutePlan},
149    split_range,
150    subscribe_config::{Compression, SubscribeConfig},
151    usage::{
152        ComputeTotals, SessionCounts, SessionUsage, SessionUsagePage, UsageBucket, UsageReport,
153    },
154};
155pub use subscriptions::{
156    AccountDiffContext, AccountDiffNotification, AccountDiffSubscriptionHandle,
157    ActionResultContext, ActionResultNotification, ActionSubscriptionHandle,
158    ActionTransactionOutcome, DiagnosticContext, DiagnosticNotification,
159    DiagnosticSubscriptionHandle, DirectFillNotification, LogSubscriptionHandle,
160    OriginalNotification, ReplacementContext, ReplacementCore, ReplacementNotification,
161    RequoteNotification, RerouteLegNotification, RoutedAccountDiffNotification, SubscriptionError,
162    SubscriptionHandle, SubscriptionRuntimeError, UiAccountConversionError, account_data_from_ui,
163    subscribe_account_diffs, subscribe_account_diffs_many, subscribe_actions,
164    subscribe_diagnostics, subscribe_program_diffs, subscribe_program_logs, subscribe_replacements,
165};
166pub use transaction_step::{DiscoveryPause, DiscoveryStepResult};
167pub use urls::{UrlError, backtest_ws_url, http_to_ws_url};