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 injection;
123pub mod managed;
124mod ranges;
125pub mod rpc;
126mod session;
127pub mod subscriptions;
128mod transaction_step;
129pub mod urls;
130
131pub use builders::{Continue, CreateSession, SerializeEncodeError};
132pub use client::BacktestClient;
133pub use error::{BacktestClientError, BacktestClientResult};
134pub use injection::{ProgramModError, build_program_injection, modify_program_via_rpc};
135pub use managed::{ControlEvent, ManagedBacktestSession, ManagedEvent, ManagedSessionError};
136pub use ranges::{RangeBound, filter_ranges};
137pub use session::{
138 AdvanceState, BacktestSession, ContinueResult, CoverageError, ReadyOutcome, SessionCoverage,
139};
140pub use simulator_api::{
141 AvailableRange, BundleKind, DiscoveryFilter, SnapshotSlotResponse, split_range,
142 subscribe_config::{Compression, SubscribeConfig},
143 usage::{ComputeTotals, SessionCounts, UsageReport},
144};
145pub use subscriptions::{
146 AccountDiffContext, AccountDiffNotification, AccountDiffSubscriptionHandle,
147 ActionResultContext, ActionResultNotification, ActionSubscriptionHandle,
148 ActionTransactionOutcome, LogSubscriptionHandle, RerouteContext, RerouteLegNotification,
149 RerouteNotification, RoutedAccountDiffNotification, SubscriptionError, SubscriptionHandle,
150 SubscriptionRuntimeError, UiAccountConversionError, account_data_from_ui,
151 subscribe_account_diffs, subscribe_account_diffs_many, subscribe_actions,
152 subscribe_program_diffs, subscribe_program_logs, subscribe_reroutes,
153};
154pub use transaction_step::{DiscoveryPause, DiscoveryStepResult};
155pub use urls::{UrlError, backtest_ws_url, http_to_ws_url};