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