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