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, from_json},
29};
30
31#[derive(Debug)]
33pub enum ControlEvent {
34 ReadyForContinue,
36 Paused(PausedEvent),
39 DiscoveryBatch(DiscoveryBatchEvent),
43 Slot(u64),
45 Status(BacktestStatus),
48 Completed {
50 summary: Option<SessionSummary>,
52 },
53 Error(BacktestError),
55}
56
57pub(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
74 .map_err(|_recv_err| ManagedSessionError::ControlClosed)?
75 }
76
77 pub async fn send_continue(
80 &self,
81 params: ContinueParams,
82 ) -> Result<(), mpsc::error::SendError<ContinueParams>> {
83 self.continues.send(params).await
84 }
85
86 pub async fn send_continue_to(
90 &self,
91 params: ContinueToParams,
92 ) -> Result<(), mpsc::error::SendError<ContinueToParams>> {
93 self.continue_tos.send(params).await
94 }
95
96 pub async fn join(self) {
103 drop(self.continues);
104 drop(self.continue_tos);
105 drop(self.events);
106 drop(self.join.await);
107 }
108}
109
110pub(super) fn spawn_control_manager(
111 grant: SessionGrant,
112 check: LivenessCheck,
113 cancel: CancellationToken,
114) -> ControlHandle {
115 let (continues_tx, continues_rx) = mpsc::channel::<ContinueParams>(1);
116 let (continue_tos_tx, continue_tos_rx) = mpsc::channel::<ContinueToParams>(1);
117 let (events_tx, events_rx) = mpsc::channel::<ControlEvent>(256);
118 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
119 let (attached_tx, attached_rx) = oneshot::channel::<Result<(), ManagedSessionError>>();
120
121 let manager = ControlTask {
122 grant,
123 last_sequence: None,
124 continues_rx,
125 continue_tos_rx,
126 events_tx,
127 status_tx,
128 cancel,
129 check,
130 };
131
132 let join = tokio::spawn(manager.run(attached_tx));
133
134 ControlHandle {
135 continues: continues_tx,
136 continue_tos: continue_tos_tx,
137 events: events_rx,
138 status: status_rx,
139 attached: Some(attached_rx),
140 join,
141 }
142}
143
144enum AttemptError {
145 Cancelled,
146 Retry(String),
147 TokenRejected,
148 Fatal(CreateError),
149}
150
151struct ControlTask {
152 grant: SessionGrant,
153 last_sequence: Option<u64>,
155 continues_rx: mpsc::Receiver<ContinueParams>,
156 continue_tos_rx: mpsc::Receiver<ContinueToParams>,
157 events_tx: mpsc::Sender<ControlEvent>,
158 status_tx: watch::Sender<ConnectionStatus>,
159 cancel: CancellationToken,
160 check: LivenessCheck,
161}
162
163impl ControlTask {
164 async fn run(mut self, attached: oneshot::Sender<Result<(), ManagedSessionError>>) {
165 let Some(ws) = self.first_attach(attached).await else {
166 return;
167 };
168 info!(session_id = %self.grant.session_id, "control attached to the session");
169 self.run_attached(ws).await;
170 }
171
172 async fn first_attach(
173 &self,
174 attached: oneshot::Sender<Result<(), ManagedSessionError>>,
175 ) -> Option<Ws> {
176 let first = FirstConnect::start(tokio::time::Instant::now());
177 let error = loop {
178 let why = match self.attempt().await {
179 Ok(ws) => {
180 drop(attached.send(Ok(())));
181 return Some(ws);
182 }
183 Err(AttemptError::Retry(why)) => why,
184 Err(AttemptError::Cancelled) => break ManagedSessionError::Cancelled,
185 Err(AttemptError::TokenRejected) => {
186 break ManagedSessionError::SessionTokenRejected;
187 }
188 Err(AttemptError::Fatal(error)) => break ManagedSessionError::Create(error),
189 };
190 let Some(delay) = first.retry_after(tokio::time::Instant::now()) else {
191 break ManagedSessionError::Create(CreateError::EndpointUnreachable {
192 session_id: self.grant.session_id,
193 endpoint: self.grant.endpoint.clone(),
194 reason: why,
195 });
196 };
197 warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control connect failed, retrying");
198 cancellable_sleep(delay, &self.cancel).await;
199 };
200 drop(attached.send(Err(error)));
201 None
202 }
203
204 async fn run_attached(&mut self, mut ws: Ws) {
205 let mut budget = ReconnectBudget::new();
206 loop {
207 publish_status(&self.status_tx, ConnectionStatus::Up);
208 let connected_at = Instant::now();
209 let why = match self.message_loop(ws).await {
210 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
211 MessageLoopExit::Terminal => {
212 publish_status(&self.status_tx, ConnectionStatus::Ended);
213 return;
214 }
215 MessageLoopExit::ConnectionLost(why) => format!("connection lost: {why}"),
216 };
217 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
218 budget.reset();
219 }
220 let Some(reattached) = self.reattach(&mut budget, why).await else {
221 return;
222 };
223 ws = reattached;
224 debug!(session_id = %self.grant.session_id, "control reattached");
225 }
226 }
227
228 async fn reattach(&self, budget: &mut ReconnectBudget, mut why: String) -> Option<Ws> {
229 let Some(delay) = budget.next_backoff() else {
230 self.fail(ConnectionFailure::RetriesExhausted(why));
231 return None;
232 };
233 warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
234 if !cancellable_sleep(delay, &self.cancel).await {
235 return None;
236 }
237 loop {
238 match self.attempt().await {
239 Ok(ws) => return Some(ws),
240 Err(AttemptError::Retry(failed)) => why = format!("connect failed: {failed}"),
241 Err(AttemptError::Cancelled) => return None,
242 Err(AttemptError::TokenRejected) => {
243 self.fail(ConnectionFailure::TokenRejected);
244 return None;
245 }
246 Err(AttemptError::Fatal(error)) => {
247 self.fail(ConnectionFailure::Refused(error.to_string()));
248 return None;
249 }
250 }
251 let Some(delay) = budget.next_backoff() else {
252 self.fail(ConnectionFailure::RetriesExhausted(why));
253 return None;
254 };
255 warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
256 if self.backoff_and_check(delay).await.is_break() {
257 return None;
258 }
259 }
260 }
261
262 async fn backoff_and_check(&self, delay: Duration) -> ControlFlow<()> {
264 let sleep = tokio::time::sleep(delay);
265 let ask = self.check.ask();
266 tokio::pin!(sleep, ask);
267 let liveness = tokio::select! {
268 biased;
269 () = self.cancel.cancelled() => return ControlFlow::Break(()),
270 liveness = &mut ask => liveness,
271 () = &mut sleep => tokio::select! {
273 biased;
274 () = self.cancel.cancelled() => return ControlFlow::Break(()),
275 liveness = &mut ask => liveness,
276 },
277 };
278 match liveness {
279 Liveness::Ended => {
280 info!(session_id = %self.grant.session_id, "management no longer knows the session");
281 self.fail(ConnectionFailure::SessionEnded);
282 return ControlFlow::Break(());
283 }
284 Liveness::Alive => {
285 debug!(session_id = %self.grant.session_id, "management still grants the session");
286 }
287 Liveness::Unknown(unknown) => {
288 warn!(session_id = %self.grant.session_id, error = %unknown, "management could not say whether the session runs");
289 }
290 }
291 tokio::select! {
292 biased;
293 () = self.cancel.cancelled() => ControlFlow::Break(()),
294 () = &mut sleep => ControlFlow::Continue(()),
295 }
296 }
297
298 fn fail(&self, failure: ConnectionFailure) {
299 publish_status(&self.status_tx, ConnectionStatus::Failed(failure));
300 }
301
302 async fn attempt(&self) -> Result<Ws, AttemptError> {
303 if self.cancel.is_cancelled() {
304 return Err(AttemptError::Cancelled);
305 }
306 publish_status(&self.status_tx, ConnectionStatus::Down);
307 tokio::select! {
308 biased;
309 () = self.cancel.cancelled() => Err(AttemptError::Cancelled),
310 attached = self.connect_and_attach() => attached,
311 }
312 }
313
314 async fn connect_and_attach(&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 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 drop(self.events_tx.send(ControlEvent::ReadyForContinue).await);
410 }
411 BacktestResponse::Paused(event) => {
412 drop(self.events_tx.send(ControlEvent::Paused(event)).await);
413 }
414 BacktestResponse::DiscoveryBatch(event) => {
415 drop(
416 self.events_tx
417 .send(ControlEvent::DiscoveryBatch(event))
418 .await,
419 );
420 }
421 BacktestResponse::SlotNotification(slot) => {
422 drop(self.events_tx.send(ControlEvent::Slot(slot)).await);
423 }
424 BacktestResponse::Completed { summary } => {
425 drop(
426 self.events_tx
427 .send(ControlEvent::Completed { summary })
428 .await,
429 );
430 return Err(MessageLoopExit::SessionEnded);
431 }
432 BacktestResponse::Error(err) => {
433 if matches!(&err, BacktestError::SimulationError { .. }) {
435 warn!(error = %err_chain(&err), "simulation error");
436 return Ok(());
437 }
438 let terminal = err.is_terminal();
439 drop(self.events_tx.send(ControlEvent::Error(err)).await);
440 if terminal {
441 return Err(MessageLoopExit::Terminal);
442 }
443 }
444 BacktestResponse::Status { status } => {
445 drop(self.events_tx.send(ControlEvent::Status(status)).await);
446 }
447 BacktestResponse::Success => {
448 }
450 other => {
451 debug!(?other, "ignoring unexpected control response");
453 }
454 }
455
456 Ok(())
457 }
458}
459
460async fn attach(
462 ws: &mut Ws,
463 session_id: SessionId,
464 last_sequence: Option<u64>,
465) -> Result<(), AttemptError> {
466 send_request(
467 ws,
468 &BacktestRequest::AttachBacktestSession {
469 session_id,
470 last_sequence,
471 },
472 )
473 .await
474 .map_err(AttemptError::Retry)?;
475
476 let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
477 let text = loop {
478 let frame = tokio::time::timeout_at(deadline, ws.next())
479 .await
480 .map_err(|_elapsed| {
481 AttemptError::Retry(format!(
482 "attach timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"
483 ))
484 })?;
485 match classify_inbound(frame) {
486 InboundFrame::Text(text) => break text,
487 InboundFrame::Ignore => {}
488 InboundFrame::Lost(why) => return Err(AttemptError::Retry(why)),
489 }
490 };
491 let response = from_json::<BacktestResponse>(text.as_bytes()).map_err(|e| {
492 AttemptError::Fatal(CreateError::Protocol(format!(
493 "the session answered the attach with a frame this client cannot read: {}",
494 err_chain(&e)
495 )))
496 })?;
497 match response {
498 BacktestResponse::SessionAttached { .. } => Ok(()),
499 BacktestResponse::Error(err) => Err(AttemptError::Fatal(CreateError::Rejected(err))),
500 BacktestResponse::Status { .. }
501 | BacktestResponse::SessionCreated { .. }
502 | BacktestResponse::SessionGranted(_)
503 | BacktestResponse::SessionsGranted(_)
504 | BacktestResponse::SessionsCreatedV2 { .. }
505 | BacktestResponse::ParallelSessionAttachedV2 { .. }
506 | BacktestResponse::ReadyForContinue
507 | BacktestResponse::SlotNotification(_)
508 | BacktestResponse::Paused(_)
509 | BacktestResponse::DiscoveryBatch(_)
510 | BacktestResponse::Success
511 | BacktestResponse::Completed { .. }
512 | BacktestResponse::SessionEventV2 { .. } => {
513 Err(AttemptError::Fatal(CreateError::Protocol(
514 "the session answered the attach with neither sessionAttached nor error".to_owned(),
515 )))
516 }
517 }
518}