Skip to main content

simulator_client/managed/
control.rs

1//! ControlManager — owns the backtest control WebSocket.
2//!
3//! Responsibilities:
4//! - Establish the WS with a bounded connect timeout
5//! - Perform the correct handshake (`Create` the first time, `Attach`+`Resume`
6//!   on reconnect) with a bounded per-response timeout
7//! - Bridge inbound `BacktestResponse` ↔ outbound `Continue` via channels
8//! - Keep the connection alive with WebSocket ping/pong
9//! - Reconnect with bounded backoff; publish `ConnectionStatus` transitions
10//! - On total-budget exhaustion, publish `Failed(reason)` and exit
11
12use std::time::Instant;
13
14use futures::StreamExt;
15use http::HeaderMap;
16use simulator_api::{
17    BacktestError, BacktestRequest, BacktestResponse, BacktestStatus, ContinueParams,
18    ContinueToParams, CreateBacktestSessionRequest, DiscoveryBatchEvent, PausedEvent,
19    SequencedResponse, SessionId, SessionSummary,
20};
21use tokio::{
22    sync::{mpsc, oneshot, watch},
23    task::JoinHandle,
24};
25use tokio_tungstenite::tungstenite::Message;
26use tokio_util::sync::CancellationToken;
27use tracing::{debug, info, warn};
28
29use super::{
30    ConnectionStatus, ControlConnection, CreateError, HANDSHAKE_RESPONSE_TIMEOUT, HandshakeError,
31    InboundFrame, KEEPALIVE_INTERVAL, ManagedSessionError, MessageLoopExit, SessionInfo, Ws,
32    classify_inbound, graceful_close, handshake_error_for_response, resolve_rpc_url,
33    run_control_loop, send_keepalive_ping, send_request,
34};
35use crate::{error::err_chain, urls::http_base_from_ws_url};
36
37/// An event from the session control channel. [`ManagedEvent`](super::ManagedEvent) wraps each
38/// one in the variant of the same name; see it for the ordering contract.
39///
40/// Responses to create, reattach and close are handled internally and never arrive here.
41#[derive(Debug)]
42pub enum ControlEvent {
43    /// The session is waiting for your next continue.
44    ReadyForContinue,
45    /// Server paused at a `ContinueTo` target. The session is ready for
46    /// another `Continue` or `ContinueTo` from this point.
47    Paused(PausedEvent),
48    /// Server discovered an upcoming batch matching a registered
49    /// `DiscoveryFilter`. Send `ContinueTo(slot, batch_index)` to pause
50    /// immediately before it executes.
51    DiscoveryBatch(DiscoveryBatchEvent),
52    /// The slot that just executed.
53    Slot(u64),
54    /// A progress update, while the session starts (e.g. `StartingRuntime`) and during each
55    /// continue.
56    Status(BacktestStatus),
57    /// The session replayed its last slot.
58    Completed {
59        /// `None` unless the session was created with `send_summary`.
60        summary: Option<SessionSummary>,
61    },
62    /// The server reported an error. Per-transaction `SimulationError`s are logged instead.
63    Error(BacktestError),
64}
65
66/// Handle to a running `ControlManager` task.
67#[doc(hidden)]
68pub struct ControlHandle {
69    continues: mpsc::Sender<ContinueParams>,
70    continue_tos: mpsc::Sender<ContinueToParams>,
71    pub events: mpsc::Receiver<ControlEvent>,
72    pub status: watch::Receiver<ConnectionStatus>,
73    session_info: Option<oneshot::Receiver<Result<SessionInfo, ManagedSessionError>>>,
74    join: JoinHandle<()>,
75}
76
77impl ControlHandle {
78    /// Resolve once the session has been created (or the control task has failed
79    /// before reaching that point). Consumes the one-shot; callable only once.
80    pub async fn wait_for_session(&mut self) -> Result<SessionInfo, ManagedSessionError> {
81        let rx = self
82            .session_info
83            .take()
84            .ok_or(ManagedSessionError::ControlClosed)?;
85        rx.await.map_err(|_| ManagedSessionError::ControlClosed)?
86    }
87
88    /// Send a `Continue` request to the control task. Errors if the task has
89    /// exited.
90    pub async fn send_continue(
91        &self,
92        params: ContinueParams,
93    ) -> Result<(), mpsc::error::SendError<ContinueParams>> {
94        self.continues.send(params).await
95    }
96
97    /// Send a `ContinueTo` request to step to a specific slot/batch boundary.
98    /// Pair with `ControlEvent::DiscoveryBatch` to pause before each
99    /// discovered batch.
100    pub async fn send_continue_to(
101        &self,
102        params: ContinueToParams,
103    ) -> Result<(), mpsc::error::SendError<ContinueToParams>> {
104        self.continue_tos.send(params).await
105    }
106
107    /// Await the control task's exit. The task exits on its own when the
108    /// server reports `Completed`, the cancel token fires, or it hits a
109    /// terminal error; dropping the request channels here nudges it in the
110    /// case where the driver is giving up without having seen `Completed`,
111    /// and dropping the event queue frees it if it is parked delivering an
112    /// event nobody will now read.
113    pub async fn join(self) {
114        drop(self.continues);
115        drop(self.continue_tos);
116        drop(self.events);
117        let _ = self.join.await;
118    }
119}
120
121/// Spawn a `ControlManager` task and return a handle.
122///
123/// The `continues` channel has a bounded capacity of 1: we only ever have one
124/// Continue in flight, and backpressuring the driver is the correct behavior
125/// if the connection is temporarily down.
126#[doc(hidden)]
127pub fn spawn_control_manager(
128    url: String,
129    api_key: String,
130    extra_headers: HeaderMap,
131    create: CreateBacktestSessionRequest,
132    cancel: CancellationToken,
133) -> ControlHandle {
134    let (continues_tx, continues_rx) = mpsc::channel::<ContinueParams>(1);
135    let (continue_tos_tx, continue_tos_rx) = mpsc::channel::<ContinueToParams>(1);
136    let (events_tx, events_rx) = mpsc::channel::<ControlEvent>(256);
137    let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
138    let (session_tx, session_rx) = oneshot::channel::<Result<SessionInfo, ManagedSessionError>>();
139
140    let manager = ControlTask {
141        url,
142        api_key,
143        extra_headers,
144        create: Some(create),
145        session_info: None,
146        session_tx: Some(session_tx),
147        last_sequence: None,
148        continues_rx,
149        continue_tos_rx,
150        events_tx,
151        status_tx,
152        cancel,
153    };
154
155    let join = tokio::spawn(run_control_loop(manager));
156
157    ControlHandle {
158        continues: continues_tx,
159        continue_tos: continue_tos_tx,
160        events: events_rx,
161        status: status_rx,
162        session_info: Some(session_rx),
163        join,
164    }
165}
166
167struct ControlTask {
168    url: String,
169    api_key: String,
170    extra_headers: HeaderMap,
171    /// Set on first connect; consumed and cleared after `Create` succeeds.
172    create: Option<CreateBacktestSessionRequest>,
173    /// Populated after `Create` succeeds. On reconnect, used to build `Attach`.
174    session_info: Option<SessionInfo>,
175    /// One-shot result to the handle; fired exactly once.
176    session_tx: Option<oneshot::Sender<Result<SessionInfo, ManagedSessionError>>>,
177    /// Highest sequence number observed from the server.
178    last_sequence: Option<u64>,
179    continues_rx: mpsc::Receiver<ContinueParams>,
180    continue_tos_rx: mpsc::Receiver<ContinueToParams>,
181    events_tx: mpsc::Sender<ControlEvent>,
182    status_tx: watch::Sender<ConnectionStatus>,
183    cancel: CancellationToken,
184}
185
186impl ControlConnection for ControlTask {
187    fn url(&self) -> &str {
188        &self.url
189    }
190    fn api_key(&self) -> &str {
191        &self.api_key
192    }
193    fn extra_headers(&self) -> &HeaderMap {
194        &self.extra_headers
195    }
196    fn cancel(&self) -> &CancellationToken {
197        &self.cancel
198    }
199    fn label(&self) -> &'static str {
200        "control"
201    }
202    fn status_tx(&self) -> &watch::Sender<ConnectionStatus> {
203        &self.status_tx
204    }
205
206    fn fail_pending(&mut self, error: ManagedSessionError) {
207        if let Some(tx) = self.session_tx.take() {
208            let _ = tx.send(Err(error));
209        }
210    }
211
212    async fn handshake(&mut self, mut ws: Ws) -> Result<Ws, HandshakeError> {
213        if let Some(info) = &self.session_info {
214            let info = info.clone();
215            attach(
216                &mut ws,
217                &info.session_id,
218                self.last_sequence,
219                &mut self.events_tx,
220                &mut self.last_sequence,
221            )
222            .await?;
223            resume(&mut ws, &mut self.events_tx, &mut self.last_sequence).await?;
224            debug!(session_id = %info.session_id, "control reattached");
225        } else if let Some(create) = self.create.take() {
226            let info = create_session(
227                &mut ws,
228                create,
229                &self.url,
230                &mut self.events_tx,
231                &mut self.last_sequence,
232            )
233            .await?;
234            info!(session_id = %info.session_id, "control session created");
235            self.session_info = Some(info.clone());
236            if let Some(tx) = self.session_tx.take() {
237                let _ = tx.send(Ok(info));
238            }
239        } else {
240            return Err(HandshakeError::Fatal(CreateError::Protocol(
241                "no create request and no session_id".into(),
242            )));
243        }
244
245        Ok(ws)
246    }
247
248    async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
249        let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
250        ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
251        let mut last_inbound = Instant::now();
252
253        let exit = loop {
254            tokio::select! {
255                biased;
256                _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
257
258                _ = ping_timer.tick() => {
259                    if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
260                        break MessageLoopExit::ConnectionLost(why);
261                    }
262                }
263
264                msg = ws.next() => {
265                    last_inbound = Instant::now();
266                    match classify_inbound(msg) {
267                        InboundFrame::Text(t) => {
268                            if let Err(exit) = self.handle_text(&t).await {
269                                break exit;
270                            }
271                        }
272                        InboundFrame::Ignore => {}
273                        InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
274                    }
275                }
276
277                req = self.continues_rx.recv() => {
278                    match req {
279                        Some(params) => {
280                            if let Err(e) = send_request(&mut ws, &BacktestRequest::Continue(params)).await {
281                                break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
282                            }
283                        }
284                        None => break MessageLoopExit::SessionEnded,
285                    }
286                }
287
288                req = self.continue_tos_rx.recv() => {
289                    match req {
290                        Some(params) => {
291                            if let Err(e) = send_request(&mut ws, &BacktestRequest::ContinueTo(params)).await {
292                                break MessageLoopExit::ConnectionLost(format!("continue_to send: {e}"));
293                            }
294                        }
295                        None => break MessageLoopExit::SessionEnded,
296                    }
297                }
298            }
299        };
300
301        if matches!(
302            exit,
303            MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
304        ) {
305            graceful_close(&mut ws).await;
306        }
307        exit
308    }
309}
310
311impl ControlTask {
312    /// Returns `Err(MessageLoopExit)` if the message signals we should exit the loop.
313    async fn handle_text(&mut self, text: &str) -> Result<(), MessageLoopExit> {
314        let (seq, response) = match serde_json::from_str::<SequencedResponse>(text) {
315            Ok(s) => (Some(s.seq_id), s.response),
316            Err(_) => match serde_json::from_str::<BacktestResponse>(text) {
317                Ok(r) => (None, r),
318                Err(e) => {
319                    warn!(error = %err_chain(&e), "discarding undeserializable control message");
320                    return Ok(());
321                }
322            },
323        };
324
325        if let Some(s) = seq {
326            self.last_sequence = Some(s);
327        }
328
329        match response {
330            BacktestResponse::ReadyForContinue => {
331                let _ = self.events_tx.send(ControlEvent::ReadyForContinue).await;
332            }
333            BacktestResponse::Paused(event) => {
334                let _ = self.events_tx.send(ControlEvent::Paused(event)).await;
335            }
336            BacktestResponse::DiscoveryBatch(event) => {
337                let _ = self
338                    .events_tx
339                    .send(ControlEvent::DiscoveryBatch(event))
340                    .await;
341            }
342            BacktestResponse::SlotNotification(slot) => {
343                let _ = self.events_tx.send(ControlEvent::Slot(slot)).await;
344            }
345            BacktestResponse::Completed { summary } => {
346                let _ = self
347                    .events_tx
348                    .send(ControlEvent::Completed { summary })
349                    .await;
350                return Err(MessageLoopExit::SessionEnded);
351            }
352            BacktestResponse::Error(err) => {
353                // Per-slot simulation errors are non-fatal: log and keep going.
354                if matches!(&err, BacktestError::SimulationError { .. }) {
355                    warn!(error = %err_chain(&err), "simulation error");
356                    return Ok(());
357                }
358                let terminal = err.is_terminal();
359                let _ = self.events_tx.send(ControlEvent::Error(err)).await;
360                if terminal {
361                    return Err(MessageLoopExit::Terminal(
362                        "server reported terminal error".into(),
363                    ));
364                }
365            }
366            BacktestResponse::Status { status } => {
367                let _ = self.events_tx.send(ControlEvent::Status(status)).await;
368            }
369            BacktestResponse::Success => {
370                // Ack for Close or similar; nothing to forward.
371            }
372            other => {
373                // SessionCreated/Attached/etc. during the message loop are unexpected.
374                debug!(?other, "ignoring unexpected control response");
375            }
376        }
377
378        Ok(())
379    }
380}
381
382async fn create_session(
383    ws: &mut Ws,
384    request: CreateBacktestSessionRequest,
385    url: &str,
386    events: &mut mpsc::Sender<ControlEvent>,
387    last_sequence: &mut Option<u64>,
388) -> Result<SessionInfo, HandshakeError> {
389    send_request(ws, &BacktestRequest::CreateBacktestSession(request))
390        .await
391        .map_err(HandshakeError::Transient)?;
392
393    let rpc_base = http_base_from_ws_url(url);
394
395    loop {
396        let response = next_response_with_timeout(ws, events, last_sequence)
397            .await
398            .map_err(HandshakeError::Transient)?;
399        match response {
400            BacktestResponse::SessionCreated {
401                session_id,
402                session_name,
403                rpc_endpoint,
404                task_id,
405            } => {
406                let rpc_endpoint = resolve_rpc_url(&rpc_base, &rpc_endpoint);
407                return Ok(SessionInfo {
408                    session_id,
409                    session_name,
410                    rpc_endpoint,
411                    task_id,
412                });
413            }
414            BacktestResponse::Error(err) => {
415                return Err(HandshakeError::Fatal(CreateError::Rejected(err)));
416            }
417            _ => {
418                // Any unexpected response before SessionCreated — ignore and
419                // keep waiting. (e.g. statuses, early events.)
420            }
421        }
422    }
423}
424
425async fn attach(
426    ws: &mut Ws,
427    session_id: &SessionId,
428    last_sequence: Option<u64>,
429    events: &mut mpsc::Sender<ControlEvent>,
430    last_seq_state: &mut Option<u64>,
431) -> Result<(), HandshakeError> {
432    send_request(
433        ws,
434        &BacktestRequest::AttachBacktestSession {
435            session_id: *session_id,
436            last_sequence,
437        },
438    )
439    .await
440    .map_err(HandshakeError::Transient)?;
441
442    loop {
443        let response = next_response_with_timeout(ws, events, last_seq_state)
444            .await
445            .map_err(HandshakeError::Transient)?;
446        match response {
447            BacktestResponse::SessionAttached { .. } => return Ok(()),
448            BacktestResponse::Error(err) => {
449                return Err(handshake_error_for_response("attach", err));
450            }
451            _ => {}
452        }
453    }
454}
455
456async fn resume(
457    ws: &mut Ws,
458    events: &mut mpsc::Sender<ControlEvent>,
459    last_seq_state: &mut Option<u64>,
460) -> Result<(), HandshakeError> {
461    send_request(ws, &BacktestRequest::ResumeAttachedSession)
462        .await
463        .map_err(HandshakeError::Transient)?;
464
465    loop {
466        let response = next_response_with_timeout(ws, events, last_seq_state)
467            .await
468            .map_err(HandshakeError::Transient)?;
469        match response {
470            BacktestResponse::Success => return Ok(()),
471            BacktestResponse::Error(err) => {
472                return Err(handshake_error_for_response("resume", err));
473            }
474            _ => {}
475        }
476    }
477}
478
479/// Read the next response during a handshake, with a bounded timeout.
480///
481/// Any non-handshake responses observed during the wait are forwarded to the
482/// driver (slot notifications, errors) so we don't lose them.
483async fn next_response_with_timeout(
484    ws: &mut Ws,
485    events: &mut mpsc::Sender<ControlEvent>,
486    last_sequence: &mut Option<u64>,
487) -> Result<BacktestResponse, String> {
488    let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
489    loop {
490        let msg = tokio::time::timeout_at(deadline, ws.next())
491            .await
492            .map_err(|_| format!("handshake timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;
493
494        let Some(msg) = msg else {
495            return Err("ws ended during handshake".into());
496        };
497        let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
498
499        let text = match msg {
500            Message::Text(t) => t,
501            Message::Binary(b) => match std::str::from_utf8(&b) {
502                Ok(t) => t.to_string(),
503                Err(_) => continue,
504            },
505            Message::Close(frame) => {
506                return Err(format!("remote close during handshake: {frame:?}"));
507            }
508            _ => continue,
509        };
510
511        let (seq, response) = match serde_json::from_str::<SequencedResponse>(&text) {
512            Ok(s) => (Some(s.seq_id), s.response),
513            Err(_) => (
514                None,
515                serde_json::from_str::<BacktestResponse>(&text)
516                    .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)))?,
517            ),
518        };
519        if let Some(s) = seq {
520            *last_sequence = Some(s);
521        }
522
523        // Forward noisy event kinds to the driver so nothing is lost while we
524        // wait for the handshake response.
525        match response {
526            BacktestResponse::SlotNotification(slot) => {
527                let _ = events.send(ControlEvent::Slot(slot)).await;
528            }
529            BacktestResponse::ReadyForContinue => {
530                let _ = events.send(ControlEvent::ReadyForContinue).await;
531            }
532            BacktestResponse::Paused(event) => {
533                let _ = events.send(ControlEvent::Paused(event)).await;
534            }
535            BacktestResponse::DiscoveryBatch(event) => {
536                let _ = events.send(ControlEvent::DiscoveryBatch(event)).await;
537            }
538            BacktestResponse::Completed { summary } => {
539                let _ = events.send(ControlEvent::Completed { summary }).await;
540            }
541            other => return Ok(other),
542        }
543    }
544}