1use std::time::Instant;
13
14use futures::StreamExt;
15use simulator_api::{
16 BacktestError, BacktestRequest, BacktestResponse, BacktestStatus, ContinueParams,
17 ContinueToParams, CreateBacktestSessionRequest, DiscoveryBatchEvent, PausedEvent,
18 SequencedResponse, SessionId, SessionSummary,
19};
20use tokio::{
21 sync::{mpsc, oneshot, watch},
22 task::JoinHandle,
23};
24use tokio_tungstenite::tungstenite::Message;
25use tokio_util::sync::CancellationToken;
26use tracing::{debug, info, warn};
27
28use super::{
29 ConnectionStatus, ControlConnection, HANDSHAKE_RESPONSE_TIMEOUT, HandshakeError, InboundFrame,
30 KEEPALIVE_INTERVAL, MessageLoopExit, SessionInfo, Ws, classify_inbound, graceful_close,
31 handshake_error_for_response, resolve_rpc_url, run_control_loop, send_keepalive_ping,
32 send_request,
33};
34use crate::{error::err_chain, urls::http_base_from_ws_url};
35
36#[derive(Debug)]
41pub enum ControlEvent {
42 ReadyForContinue,
43 Paused(PausedEvent),
46 DiscoveryBatch(DiscoveryBatchEvent),
50 Slot(u64),
51 Status(BacktestStatus),
55 Completed {
56 summary: Option<SessionSummary>,
57 },
58 Error(BacktestError),
59}
60
61pub struct ControlHandle {
63 continues: mpsc::Sender<ContinueParams>,
64 continue_tos: mpsc::Sender<ContinueToParams>,
65 pub events: mpsc::Receiver<ControlEvent>,
66 pub status: watch::Receiver<ConnectionStatus>,
67 session_info: Option<oneshot::Receiver<Result<SessionInfo, String>>>,
68 join: JoinHandle<()>,
69}
70
71impl ControlHandle {
72 pub async fn wait_for_session(&mut self) -> Result<SessionInfo, String> {
75 let rx = self
76 .session_info
77 .take()
78 .ok_or_else(|| "session_info already consumed".to_string())?;
79 rx.await
80 .map_err(|_| "control manager exited before creating session".to_string())?
81 }
82
83 pub async fn send_continue(
86 &self,
87 params: ContinueParams,
88 ) -> Result<(), mpsc::error::SendError<ContinueParams>> {
89 self.continues.send(params).await
90 }
91
92 pub async fn send_continue_to(
96 &self,
97 params: ContinueToParams,
98 ) -> Result<(), mpsc::error::SendError<ContinueToParams>> {
99 self.continue_tos.send(params).await
100 }
101
102 pub async fn join(self) {
107 drop(self.continues);
108 drop(self.continue_tos);
109 let _ = self.join.await;
110 }
111}
112
113pub fn spawn_control_manager(
119 url: String,
120 api_key: String,
121 create: CreateBacktestSessionRequest,
122 cancel: CancellationToken,
123) -> ControlHandle {
124 let (continues_tx, continues_rx) = mpsc::channel::<ContinueParams>(1);
125 let (continue_tos_tx, continue_tos_rx) = mpsc::channel::<ContinueToParams>(1);
126 let (events_tx, events_rx) = mpsc::channel::<ControlEvent>(256);
127 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
128 let (session_tx, session_rx) = oneshot::channel::<Result<SessionInfo, String>>();
129
130 let manager = ControlTask {
131 url,
132 api_key,
133 create: Some(create),
134 session_info: None,
135 session_tx: Some(session_tx),
136 last_sequence: None,
137 continues_rx,
138 continue_tos_rx,
139 events_tx,
140 status_tx,
141 cancel,
142 };
143
144 let join = tokio::spawn(run_control_loop(manager));
145
146 ControlHandle {
147 continues: continues_tx,
148 continue_tos: continue_tos_tx,
149 events: events_rx,
150 status: status_rx,
151 session_info: Some(session_rx),
152 join,
153 }
154}
155
156struct ControlTask {
157 url: String,
158 api_key: String,
159 create: Option<CreateBacktestSessionRequest>,
161 session_info: Option<SessionInfo>,
163 session_tx: Option<oneshot::Sender<Result<SessionInfo, String>>>,
165 last_sequence: Option<u64>,
167 continues_rx: mpsc::Receiver<ContinueParams>,
168 continue_tos_rx: mpsc::Receiver<ContinueToParams>,
169 events_tx: mpsc::Sender<ControlEvent>,
170 status_tx: watch::Sender<ConnectionStatus>,
171 cancel: CancellationToken,
172}
173
174impl ControlConnection for ControlTask {
175 fn url(&self) -> &str {
176 &self.url
177 }
178 fn api_key(&self) -> &str {
179 &self.api_key
180 }
181 fn cancel(&self) -> &CancellationToken {
182 &self.cancel
183 }
184 fn label(&self) -> &'static str {
185 "control"
186 }
187 fn status_tx(&self) -> &watch::Sender<ConnectionStatus> {
188 &self.status_tx
189 }
190
191 fn fail_pending(&mut self, reason: String) {
192 if let Some(tx) = self.session_tx.take() {
193 let _ = tx.send(Err(reason));
194 }
195 }
196
197 async fn handshake(&mut self, mut ws: Ws) -> Result<Ws, HandshakeError> {
198 if let Some(info) = &self.session_info {
199 let info = info.clone();
200 attach(
201 &mut ws,
202 &info.session_id,
203 self.last_sequence,
204 &mut self.events_tx,
205 &mut self.last_sequence,
206 )
207 .await?;
208 resume(&mut ws, &mut self.events_tx, &mut self.last_sequence).await?;
209 debug!(session_id = %info.session_id, "control reattached");
210 } else if let Some(create) = self.create.take() {
211 let info = create_session(
212 &mut ws,
213 create,
214 &self.url,
215 &mut self.events_tx,
216 &mut self.last_sequence,
217 )
218 .await?;
219 info!(session_id = %info.session_id, "control session created");
220 self.session_info = Some(info.clone());
221 if let Some(tx) = self.session_tx.take() {
222 let _ = tx.send(Ok(info));
223 }
224 } else {
225 return Err(HandshakeError::Fatal(
226 "no create request and no session_id".into(),
227 ));
228 }
229
230 Ok(ws)
231 }
232
233 async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
234 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
235 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
236 let mut last_inbound = Instant::now();
237
238 let exit = loop {
239 tokio::select! {
240 biased;
241 _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
242
243 _ = ping_timer.tick() => {
244 if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
245 break MessageLoopExit::ConnectionLost(why);
246 }
247 }
248
249 msg = ws.next() => {
250 last_inbound = Instant::now();
251 match classify_inbound(msg) {
252 InboundFrame::Text(t) => {
253 if let Err(exit) = self.handle_text(&t).await {
254 break exit;
255 }
256 }
257 InboundFrame::Ignore => {}
258 InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
259 }
260 }
261
262 req = self.continues_rx.recv() => {
263 match req {
264 Some(params) => {
265 if let Err(e) = send_request(&mut ws, &BacktestRequest::Continue(params)).await {
266 break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
267 }
268 }
269 None => break MessageLoopExit::SessionEnded,
270 }
271 }
272
273 req = self.continue_tos_rx.recv() => {
274 match req {
275 Some(params) => {
276 if let Err(e) = send_request(&mut ws, &BacktestRequest::ContinueTo(params)).await {
277 break MessageLoopExit::ConnectionLost(format!("continue_to send: {e}"));
278 }
279 }
280 None => break MessageLoopExit::SessionEnded,
281 }
282 }
283 }
284 };
285
286 if matches!(
287 exit,
288 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
289 ) {
290 graceful_close(&mut ws).await;
291 }
292 exit
293 }
294}
295
296impl ControlTask {
297 async fn handle_text(&mut self, text: &str) -> Result<(), MessageLoopExit> {
299 let (seq, response) = match serde_json::from_str::<SequencedResponse>(text) {
300 Ok(s) => (Some(s.seq_id), s.response),
301 Err(_) => match serde_json::from_str::<BacktestResponse>(text) {
302 Ok(r) => (None, r),
303 Err(e) => {
304 warn!(error = %err_chain(&e), "discarding undeserializable control message");
305 return Ok(());
306 }
307 },
308 };
309
310 if let Some(s) = seq {
311 self.last_sequence = Some(s);
312 }
313
314 match response {
315 BacktestResponse::ReadyForContinue => {
316 let _ = self.events_tx.send(ControlEvent::ReadyForContinue).await;
317 }
318 BacktestResponse::Paused(event) => {
319 let _ = self.events_tx.send(ControlEvent::Paused(event)).await;
320 }
321 BacktestResponse::DiscoveryBatch(event) => {
322 let _ = self
323 .events_tx
324 .send(ControlEvent::DiscoveryBatch(event))
325 .await;
326 }
327 BacktestResponse::SlotNotification(slot) => {
328 let _ = self.events_tx.send(ControlEvent::Slot(slot)).await;
329 }
330 BacktestResponse::Completed { summary } => {
331 let _ = self
332 .events_tx
333 .send(ControlEvent::Completed { summary })
334 .await;
335 return Err(MessageLoopExit::SessionEnded);
336 }
337 BacktestResponse::Error(err) => {
338 if matches!(&err, BacktestError::SimulationError { .. }) {
340 warn!(error = %err_chain(&err), "simulation error");
341 return Ok(());
342 }
343 let terminal = err.is_terminal();
344 let _ = self.events_tx.send(ControlEvent::Error(err)).await;
345 if terminal {
346 return Err(MessageLoopExit::Terminal(
347 "server reported terminal error".into(),
348 ));
349 }
350 }
351 BacktestResponse::Status { status } => {
352 let _ = self.events_tx.send(ControlEvent::Status(status)).await;
353 }
354 BacktestResponse::Success => {
355 }
357 other => {
358 debug!(?other, "ignoring unexpected control response");
360 }
361 }
362
363 Ok(())
364 }
365}
366
367async fn create_session(
368 ws: &mut Ws,
369 request: CreateBacktestSessionRequest,
370 url: &str,
371 events: &mut mpsc::Sender<ControlEvent>,
372 last_sequence: &mut Option<u64>,
373) -> Result<SessionInfo, HandshakeError> {
374 send_request(ws, &BacktestRequest::CreateBacktestSession(request))
375 .await
376 .map_err(HandshakeError::Transient)?;
377
378 let rpc_base = http_base_from_ws_url(url);
379
380 loop {
381 let response = next_response_with_timeout(ws, events, last_sequence)
382 .await
383 .map_err(HandshakeError::Transient)?;
384 match response {
385 BacktestResponse::SessionCreated {
386 session_id,
387 rpc_endpoint,
388 task_id,
389 } => {
390 let rpc_endpoint = resolve_rpc_url(&rpc_base, &rpc_endpoint);
391 return Ok(SessionInfo {
392 session_id,
393 rpc_endpoint,
394 task_id,
395 });
396 }
397 BacktestResponse::Error(err) => {
398 return Err(HandshakeError::Fatal(format!(
399 "server error: {}",
400 err_chain(&err)
401 )));
402 }
403 _ => {
404 }
407 }
408 }
409}
410
411async fn attach(
412 ws: &mut Ws,
413 session_id: &SessionId,
414 last_sequence: Option<u64>,
415 events: &mut mpsc::Sender<ControlEvent>,
416 last_seq_state: &mut Option<u64>,
417) -> Result<(), HandshakeError> {
418 send_request(
419 ws,
420 &BacktestRequest::AttachBacktestSession {
421 session_id: *session_id,
422 last_sequence,
423 },
424 )
425 .await
426 .map_err(HandshakeError::Transient)?;
427
428 loop {
429 let response = next_response_with_timeout(ws, events, last_seq_state)
430 .await
431 .map_err(HandshakeError::Transient)?;
432 match response {
433 BacktestResponse::SessionAttached { .. } => return Ok(()),
434 BacktestResponse::Error(err) => {
435 return Err(handshake_error_for_response("attach", err));
436 }
437 _ => {}
438 }
439 }
440}
441
442async fn resume(
443 ws: &mut Ws,
444 events: &mut mpsc::Sender<ControlEvent>,
445 last_seq_state: &mut Option<u64>,
446) -> Result<(), HandshakeError> {
447 send_request(ws, &BacktestRequest::ResumeAttachedSession)
448 .await
449 .map_err(HandshakeError::Transient)?;
450
451 loop {
452 let response = next_response_with_timeout(ws, events, last_seq_state)
453 .await
454 .map_err(HandshakeError::Transient)?;
455 match response {
456 BacktestResponse::Success => return Ok(()),
457 BacktestResponse::Error(err) => {
458 return Err(handshake_error_for_response("resume", err));
459 }
460 _ => {}
461 }
462 }
463}
464
465async fn next_response_with_timeout(
470 ws: &mut Ws,
471 events: &mut mpsc::Sender<ControlEvent>,
472 last_sequence: &mut Option<u64>,
473) -> Result<BacktestResponse, String> {
474 let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
475 loop {
476 let msg = tokio::time::timeout_at(deadline, ws.next())
477 .await
478 .map_err(|_| format!("handshake timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;
479
480 let Some(msg) = msg else {
481 return Err("ws ended during handshake".into());
482 };
483 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
484
485 let text = match msg {
486 Message::Text(t) => t,
487 Message::Binary(b) => match std::str::from_utf8(&b) {
488 Ok(t) => t.to_string(),
489 Err(_) => continue,
490 },
491 Message::Close(frame) => {
492 return Err(format!("remote close during handshake: {frame:?}"));
493 }
494 _ => continue,
495 };
496
497 let (seq, response) = match serde_json::from_str::<SequencedResponse>(&text) {
498 Ok(s) => (Some(s.seq_id), s.response),
499 Err(_) => (
500 None,
501 serde_json::from_str::<BacktestResponse>(&text)
502 .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)))?,
503 ),
504 };
505 if let Some(s) = seq {
506 *last_sequence = Some(s);
507 }
508
509 match response {
512 BacktestResponse::SlotNotification(slot) => {
513 let _ = events.send(ControlEvent::Slot(slot)).await;
514 }
515 BacktestResponse::ReadyForContinue => {
516 let _ = events.send(ControlEvent::ReadyForContinue).await;
517 }
518 BacktestResponse::Paused(event) => {
519 let _ = events.send(ControlEvent::Paused(event)).await;
520 }
521 BacktestResponse::DiscoveryBatch(event) => {
522 let _ = events.send(ControlEvent::DiscoveryBatch(event)).await;
523 }
524 BacktestResponse::Completed { summary } => {
525 let _ = events.send(ControlEvent::Completed { summary }).await;
526 }
527 other => return Ok(other),
528 }
529 }
530}