Skip to main content

simulator_client/managed/
control.rs

1use std::{
2    ops::ControlFlow,
3    time::{Duration, Instant},
4};
5
6use futures::StreamExt;
7use simulator_api::{
8    BacktestError, BacktestRequest, BacktestResponse, BacktestStatus, ContinueParams,
9    ContinueToParams, DiscoveryBatchEvent, PausedEvent, SequencedResponse, SessionId,
10    SessionSummary, session_endpoint::SessionGrant,
11};
12use tokio::{
13    sync::{mpsc, oneshot, watch},
14    task::JoinHandle,
15};
16use tokio_util::sync::CancellationToken;
17use tracing::{debug, info, warn};
18
19use super::{
20    CONNECT_TIMEOUT, ConnectionFailure, ConnectionStatus, CreateError, HANDSHAKE_RESPONSE_TIMEOUT,
21    InboundFrame, KEEPALIVE_INTERVAL, ManagedSessionError, MessageLoopExit, RECONNECT_UPTIME_RESET,
22    ReconnectBudget, Ws, cancellable_sleep, classify_inbound, graceful_close,
23    grant::{Liveness, LivenessCheck},
24    managed_user_agent, publish_status, send_keepalive_ping, send_request,
25};
26use crate::{
27    endpoint::{ControlConnectError, FirstConnect, connect_control},
28    error::err_chain,
29};
30
31/// An event from the session control channel. Responses to reattach and close never arrive here.
32#[derive(Debug)]
33pub enum ControlEvent {
34    /// The session is waiting for your next continue.
35    ReadyForContinue,
36    /// Server paused at a `ContinueTo` target. The session is ready for
37    /// another `Continue` or `ContinueTo` from this point.
38    Paused(PausedEvent),
39    /// Server discovered an upcoming batch matching a registered
40    /// `DiscoveryFilter`. Send `ContinueTo(slot, batch_index)` to pause
41    /// immediately before it executes.
42    DiscoveryBatch(DiscoveryBatchEvent),
43    /// The slot that just executed.
44    Slot(u64),
45    /// A progress update, while the session starts (e.g. `StartingRuntime`) and during each
46    /// continue.
47    Status(BacktestStatus),
48    /// The session replayed its last slot.
49    Completed {
50        /// `None` unless the session was created with `send_summary`.
51        summary: Option<SessionSummary>,
52    },
53    /// The server reported an error. Per-transaction `SimulationError`s are logged instead.
54    Error(BacktestError),
55}
56
57/// Handle to a running `ControlManager` task.
58pub(super) struct ControlHandle {
59    continues: mpsc::Sender<ContinueParams>,
60    continue_tos: mpsc::Sender<ContinueToParams>,
61    pub events: mpsc::Receiver<ControlEvent>,
62    pub status: watch::Receiver<ConnectionStatus>,
63    attached: Option<oneshot::Receiver<Result<(), ManagedSessionError>>>,
64    join: JoinHandle<()>,
65}
66
67impl ControlHandle {
68    pub async fn wait_attached(&mut self) -> Result<(), ManagedSessionError> {
69        let rx = self
70            .attached
71            .take()
72            .ok_or(ManagedSessionError::ControlClosed)?;
73        rx.await.map_err(|_| ManagedSessionError::ControlClosed)?
74    }
75
76    /// Send a `Continue` request to the control task. Errors if the task has
77    /// exited.
78    pub async fn send_continue(
79        &self,
80        params: ContinueParams,
81    ) -> Result<(), mpsc::error::SendError<ContinueParams>> {
82        self.continues.send(params).await
83    }
84
85    /// Send a `ContinueTo` request to step to a specific slot/batch boundary.
86    /// Pair with `ControlEvent::DiscoveryBatch` to pause before each
87    /// discovered batch.
88    pub async fn send_continue_to(
89        &self,
90        params: ContinueToParams,
91    ) -> Result<(), mpsc::error::SendError<ContinueToParams>> {
92        self.continue_tos.send(params).await
93    }
94
95    /// Await the control task's exit. The task exits on its own when the
96    /// server reports `Completed`, the cancel token fires, or it hits a
97    /// terminal error; dropping the request channels here nudges it in the
98    /// case where the driver is giving up without having seen `Completed`,
99    /// and dropping the event queue frees it if it is parked delivering an
100    /// event nobody will now read.
101    pub async fn join(self) {
102        drop(self.continues);
103        drop(self.continue_tos);
104        drop(self.events);
105        let _ = self.join.await;
106    }
107}
108
109pub(super) fn spawn_control_manager(
110    grant: SessionGrant,
111    check: LivenessCheck,
112    cancel: CancellationToken,
113) -> ControlHandle {
114    let (continues_tx, continues_rx) = mpsc::channel::<ContinueParams>(1);
115    let (continue_tos_tx, continue_tos_rx) = mpsc::channel::<ContinueToParams>(1);
116    let (events_tx, events_rx) = mpsc::channel::<ControlEvent>(256);
117    let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
118    let (attached_tx, attached_rx) = oneshot::channel::<Result<(), ManagedSessionError>>();
119
120    let manager = ControlTask {
121        grant,
122        last_sequence: None,
123        continues_rx,
124        continue_tos_rx,
125        events_tx,
126        status_tx,
127        cancel,
128        check,
129    };
130
131    let join = tokio::spawn(manager.run(attached_tx));
132
133    ControlHandle {
134        continues: continues_tx,
135        continue_tos: continue_tos_tx,
136        events: events_rx,
137        status: status_rx,
138        attached: Some(attached_rx),
139        join,
140    }
141}
142
143enum AttemptError {
144    Cancelled,
145    Retry(String),
146    TokenRejected,
147    Fatal(CreateError),
148}
149
150struct ControlTask {
151    grant: SessionGrant,
152    /// Highest sequence number observed from the server.
153    last_sequence: Option<u64>,
154    continues_rx: mpsc::Receiver<ContinueParams>,
155    continue_tos_rx: mpsc::Receiver<ContinueToParams>,
156    events_tx: mpsc::Sender<ControlEvent>,
157    status_tx: watch::Sender<ConnectionStatus>,
158    cancel: CancellationToken,
159    check: LivenessCheck,
160}
161
162impl ControlTask {
163    async fn run(mut self, attached: oneshot::Sender<Result<(), ManagedSessionError>>) {
164        let Some(ws) = self.first_attach(attached).await else {
165            return;
166        };
167        info!(session_id = %self.grant.session_id, "control attached to the session");
168        self.run_attached(ws).await;
169    }
170
171    async fn first_attach(
172        &mut self,
173        attached: oneshot::Sender<Result<(), ManagedSessionError>>,
174    ) -> Option<Ws> {
175        let first = FirstConnect::start(tokio::time::Instant::now());
176        let error = loop {
177            let why = match self.attempt().await {
178                Ok(ws) => {
179                    let _ = attached.send(Ok(()));
180                    return Some(ws);
181                }
182                Err(AttemptError::Retry(why)) => why,
183                Err(AttemptError::Cancelled) => break ManagedSessionError::Cancelled,
184                Err(AttemptError::TokenRejected) => {
185                    break ManagedSessionError::SessionTokenRejected;
186                }
187                Err(AttemptError::Fatal(error)) => break ManagedSessionError::Create(error),
188            };
189            let Some(delay) = first.retry_after(tokio::time::Instant::now()) else {
190                break ManagedSessionError::Create(CreateError::EndpointUnreachable {
191                    session_id: self.grant.session_id,
192                    endpoint: self.grant.endpoint.clone(),
193                    reason: why,
194                });
195            };
196            warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control connect failed, retrying");
197            cancellable_sleep(delay, &self.cancel).await;
198        };
199        let _ = attached.send(Err(error));
200        None
201    }
202
203    async fn run_attached(&mut self, mut ws: Ws) {
204        let mut budget = ReconnectBudget::new();
205        loop {
206            publish_status(&self.status_tx, ConnectionStatus::Up);
207            let connected_at = Instant::now();
208            let why = match self.message_loop(ws).await {
209                MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
210                MessageLoopExit::Terminal => {
211                    publish_status(&self.status_tx, ConnectionStatus::Ended);
212                    return;
213                }
214                MessageLoopExit::ConnectionLost(why) => format!("connection lost: {why}"),
215            };
216            if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
217                budget.reset();
218            }
219            let Some(reattached) = self.reattach(&mut budget, why).await else {
220                return;
221            };
222            ws = reattached;
223            debug!(session_id = %self.grant.session_id, "control reattached");
224        }
225    }
226
227    async fn reattach(&mut self, budget: &mut ReconnectBudget, mut why: String) -> Option<Ws> {
228        let Some(delay) = budget.next_backoff() else {
229            self.fail(ConnectionFailure::RetriesExhausted(why));
230            return None;
231        };
232        warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
233        if !cancellable_sleep(delay, &self.cancel).await {
234            return None;
235        }
236        loop {
237            match self.attempt().await {
238                Ok(ws) => return Some(ws),
239                Err(AttemptError::Retry(failed)) => why = format!("connect failed: {failed}"),
240                Err(AttemptError::Cancelled) => return None,
241                Err(AttemptError::TokenRejected) => {
242                    self.fail(ConnectionFailure::TokenRejected);
243                    return None;
244                }
245                Err(AttemptError::Fatal(error)) => {
246                    self.fail(ConnectionFailure::Refused(error.to_string()));
247                    return None;
248                }
249            }
250            let Some(delay) = budget.next_backoff() else {
251                self.fail(ConnectionFailure::RetriesExhausted(why));
252                return None;
253            };
254            warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
255            if self.backoff_and_check(delay).await.is_break() {
256                return None;
257            }
258        }
259    }
260
261    /// Breaks when the task has stopped: cancelled, or management reported the session gone.
262    async fn backoff_and_check(&self, delay: Duration) -> ControlFlow<()> {
263        let sleep = tokio::time::sleep(delay);
264        let ask = self.check.ask();
265        tokio::pin!(sleep, ask);
266        let liveness = tokio::select! {
267            biased;
268            _ = self.cancel.cancelled() => return ControlFlow::Break(()),
269            liveness = &mut ask => liveness,
270            // Keep waiting for the check, so an `Ended` answer is not lost.
271            _ = &mut sleep => tokio::select! {
272                biased;
273                _ = self.cancel.cancelled() => return ControlFlow::Break(()),
274                liveness = &mut ask => liveness,
275            },
276        };
277        match liveness {
278            Liveness::Ended => {
279                info!(session_id = %self.grant.session_id, "management no longer knows the session");
280                self.fail(ConnectionFailure::SessionEnded);
281                return ControlFlow::Break(());
282            }
283            Liveness::Alive => {
284                debug!(session_id = %self.grant.session_id, "management still grants the session");
285            }
286            Liveness::Unknown(unknown) => {
287                warn!(session_id = %self.grant.session_id, error = %unknown, "management could not say whether the session runs");
288            }
289        }
290        tokio::select! {
291            biased;
292            _ = self.cancel.cancelled() => ControlFlow::Break(()),
293            _ = &mut sleep => ControlFlow::Continue(()),
294        }
295    }
296
297    fn fail(&self, failure: ConnectionFailure) {
298        publish_status(&self.status_tx, ConnectionStatus::Failed(failure));
299    }
300
301    async fn attempt(&mut self) -> Result<Ws, AttemptError> {
302        if self.cancel.is_cancelled() {
303            return Err(AttemptError::Cancelled);
304        }
305        publish_status(&self.status_tx, ConnectionStatus::Down);
306        let cancel = self.cancel.clone();
307        tokio::select! {
308            biased;
309            _ = cancel.cancelled() => Err(AttemptError::Cancelled),
310            attached = self.connect_and_attach() => attached,
311        }
312    }
313
314    async fn connect_and_attach(&mut self) -> Result<Ws, AttemptError> {
315        let mut ws = connect_control(&self.grant, &managed_user_agent(), CONNECT_TIMEOUT)
316            .await
317            .map_err(|e| match e {
318                ControlConnectError::TokenRejected => AttemptError::TokenRejected,
319                request @ ControlConnectError::Request(_) => {
320                    AttemptError::Fatal(CreateError::Protocol(request.to_string()))
321                }
322                ControlConnectError::Failed(why) => AttemptError::Retry(why),
323            })?;
324        attach(&mut ws, self.grant.session_id, self.last_sequence).await?;
325        Ok(ws)
326    }
327
328    async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
329        let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
330        ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
331        let mut last_inbound = Instant::now();
332
333        let exit = loop {
334            tokio::select! {
335                biased;
336                _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
337
338                _ = ping_timer.tick() => {
339                    if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
340                        break MessageLoopExit::ConnectionLost(why);
341                    }
342                }
343
344                msg = ws.next() => {
345                    last_inbound = Instant::now();
346                    match classify_inbound(msg) {
347                        InboundFrame::Text(t) => {
348                            if let Err(exit) = self.handle_text(&t).await {
349                                break exit;
350                            }
351                        }
352                        InboundFrame::Ignore => {}
353                        InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
354                    }
355                }
356
357                req = self.continues_rx.recv() => {
358                    match req {
359                        Some(params) => {
360                            if let Err(e) = send_request(&mut ws, &BacktestRequest::Continue(params)).await {
361                                break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
362                            }
363                        }
364                        None => break MessageLoopExit::SessionEnded,
365                    }
366                }
367
368                req = self.continue_tos_rx.recv() => {
369                    match req {
370                        Some(params) => {
371                            if let Err(e) = send_request(&mut ws, &BacktestRequest::ContinueTo(params)).await {
372                                break MessageLoopExit::ConnectionLost(format!("continue_to send: {e}"));
373                            }
374                        }
375                        None => break MessageLoopExit::SessionEnded,
376                    }
377                }
378            }
379        };
380
381        if matches!(
382            exit,
383            MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
384        ) {
385            graceful_close(&mut ws).await;
386        }
387        exit
388    }
389
390    /// Returns `Err(MessageLoopExit)` if the message signals we should exit the loop.
391    async fn handle_text(&mut self, text: &str) -> Result<(), MessageLoopExit> {
392        let (seq, response) = match serde_json::from_str::<SequencedResponse>(text) {
393            Ok(s) => (Some(s.seq_id), s.response),
394            Err(_) => match serde_json::from_str::<BacktestResponse>(text) {
395                Ok(r) => (None, r),
396                Err(e) => {
397                    warn!(error = %err_chain(&e), "discarding undeserializable control message");
398                    return Ok(());
399                }
400            },
401        };
402
403        if let Some(s) = seq {
404            self.last_sequence = Some(s);
405        }
406
407        match response {
408            BacktestResponse::ReadyForContinue => {
409                let _ = self.events_tx.send(ControlEvent::ReadyForContinue).await;
410            }
411            BacktestResponse::Paused(event) => {
412                let _ = self.events_tx.send(ControlEvent::Paused(event)).await;
413            }
414            BacktestResponse::DiscoveryBatch(event) => {
415                let _ = self
416                    .events_tx
417                    .send(ControlEvent::DiscoveryBatch(event))
418                    .await;
419            }
420            BacktestResponse::SlotNotification(slot) => {
421                let _ = self.events_tx.send(ControlEvent::Slot(slot)).await;
422            }
423            BacktestResponse::Completed { summary } => {
424                let _ = self
425                    .events_tx
426                    .send(ControlEvent::Completed { summary })
427                    .await;
428                return Err(MessageLoopExit::SessionEnded);
429            }
430            BacktestResponse::Error(err) => {
431                // Per-slot simulation errors are non-fatal: log and keep going.
432                if matches!(&err, BacktestError::SimulationError { .. }) {
433                    warn!(error = %err_chain(&err), "simulation error");
434                    return Ok(());
435                }
436                let terminal = err.is_terminal();
437                let _ = self.events_tx.send(ControlEvent::Error(err)).await;
438                if terminal {
439                    return Err(MessageLoopExit::Terminal);
440                }
441            }
442            BacktestResponse::Status { status } => {
443                let _ = self.events_tx.send(ControlEvent::Status(status)).await;
444            }
445            BacktestResponse::Success => {
446                // Ack for Close or similar; nothing to forward.
447            }
448            other => {
449                // SessionCreated/Attached/etc. during the message loop are unexpected.
450                debug!(?other, "ignoring unexpected control response");
451            }
452        }
453
454        Ok(())
455    }
456}
457
458/// Sends the attach and reads `sessionAttached` or `error`. Replay follows only after that frame.
459async fn attach(
460    ws: &mut Ws,
461    session_id: SessionId,
462    last_sequence: Option<u64>,
463) -> Result<(), AttemptError> {
464    send_request(
465        ws,
466        &BacktestRequest::AttachBacktestSession {
467            session_id,
468            last_sequence,
469        },
470    )
471    .await
472    .map_err(AttemptError::Retry)?;
473
474    let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
475    let text = loop {
476        let frame = tokio::time::timeout_at(deadline, ws.next())
477            .await
478            .map_err(|_| {
479                AttemptError::Retry(format!(
480                    "attach timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"
481                ))
482            })?;
483        match classify_inbound(frame) {
484            InboundFrame::Text(text) => break text,
485            InboundFrame::Ignore => {}
486            InboundFrame::Lost(why) => return Err(AttemptError::Retry(why)),
487        }
488    };
489    let response = serde_json::from_str::<BacktestResponse>(&text).map_err(|e| {
490        AttemptError::Fatal(CreateError::Protocol(format!(
491            "the session answered the attach with a frame this client cannot read: {}",
492            err_chain(&e)
493        )))
494    })?;
495    match response {
496        BacktestResponse::SessionAttached { .. } => Ok(()),
497        BacktestResponse::Error(err) => Err(AttemptError::Fatal(CreateError::Rejected(err))),
498        BacktestResponse::Status { .. }
499        | BacktestResponse::SessionCreated { .. }
500        | BacktestResponse::SessionGranted(_)
501        | BacktestResponse::SessionsGranted(_)
502        | BacktestResponse::SessionsCreatedV2 { .. }
503        | BacktestResponse::ParallelSessionAttachedV2 { .. }
504        | BacktestResponse::ReadyForContinue
505        | BacktestResponse::SlotNotification(_)
506        | BacktestResponse::Paused(_)
507        | BacktestResponse::DiscoveryBatch(_)
508        | BacktestResponse::Success
509        | BacktestResponse::Completed { .. }
510        | BacktestResponse::SessionEventV2 { .. } => {
511            Err(AttemptError::Fatal(CreateError::Protocol(
512                "the session answered the attach with neither sessionAttached nor error".to_owned(),
513            )))
514        }
515    }
516}