1use std::{
17 collections::{HashMap, VecDeque},
18 sync::Arc,
19};
20
21use futures::StreamExt;
22use simulator_api::{
23 BacktestError, BacktestRequest, BacktestResponse, ContinueParams, ContinueSessionRequestV1,
24 ControlSessionId, CreateBacktestSessionRequest, SessionEventKind, SessionId,
25};
26use solana_address::Address;
27use tokio::{
28 sync::{mpsc, oneshot, watch},
29 task::JoinHandle,
30};
31use tokio_tungstenite::tungstenite::Message;
32use tokio_util::sync::CancellationToken;
33use tracing::{debug, info, warn};
34
35use super::{
36 ConnectionStatus, ControlConnection, ControlEvent, HANDSHAKE_RESPONSE_TIMEOUT, HandshakeError,
37 InboundFrame, KEEPALIVE_INTERVAL, ManagedEvent, ManagedSessionError, MessageLoopExit,
38 ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
39 SubscriptionHandle, Ws, classify_inbound, graceful_close, handshake_error_for_response,
40 resolve_rpc_url, run_control_loop, send_keepalive_ping, send_request,
41 session::{
42 DrainOutcome, drain_subscriptions_until_complete, try_next_subscription_event,
43 wait_any_subscription_event, wait_connections_up,
44 },
45 spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
46 spawn_transaction_subscription_manager,
47};
48use crate::{error::err_chain, urls::http_base_from_ws_url};
49
50const CREATE_RESPONSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(900);
53const CONTINUE_CHANNEL_CAPACITY: usize = 256;
56const COMPLETION_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
59
60type TaggedContinue = (SessionId, ContinueParams);
62
63struct ParallelCreated {
65 control_session_id: ControlSessionId,
66 sessions: Vec<CreatedSubSession>,
67}
68
69struct CreatedSubSession {
70 info: SessionInfo,
71 events: mpsc::UnboundedReceiver<ControlEvent>,
72 start_slot: u64,
76 end_slot: u64,
77}
78
79struct ParallelControlHandle {
81 continues: mpsc::Sender<TaggedContinue>,
82 status: watch::Receiver<ConnectionStatus>,
83 created: Option<oneshot::Receiver<Result<ParallelCreated, String>>>,
84 join: JoinHandle<()>,
85}
86
87impl ParallelControlHandle {
88 async fn wait_created(&mut self) -> Result<ParallelCreated, String> {
91 let rx = self
92 .created
93 .take()
94 .ok_or_else(|| "parallel create already consumed".to_string())?;
95 rx.await
96 .map_err(|_| "control manager exited before creating sessions".to_string())?
97 }
98
99 async fn join(self) {
102 drop(self.continues);
103 let _ = self.join.await;
104 }
105}
106
107fn spawn_parallel_control_manager(
108 url: String,
109 api_key: String,
110 create: CreateBacktestSessionRequest,
111 cancel: CancellationToken,
112) -> ParallelControlHandle {
113 let (continues_tx, continues_rx) = mpsc::channel::<TaggedContinue>(CONTINUE_CHANNEL_CAPACITY);
114 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
115 let (created_tx, created_rx) = oneshot::channel::<Result<ParallelCreated, String>>();
116
117 let task = ParallelControlTask {
118 url,
119 api_key,
120 create: Some(create),
121 control_session_id: None,
122 event_txs: HashMap::new(),
123 last_sequences: HashMap::new(),
124 completed: std::collections::HashSet::new(),
125 continues_rx,
126 status_tx,
127 created_tx: Some(created_tx),
128 cancel,
129 };
130
131 let join = tokio::spawn(run_control_loop(task));
132
133 ParallelControlHandle {
134 continues: continues_tx,
135 status: status_rx,
136 created: Some(created_rx),
137 join,
138 }
139}
140
141struct ParallelControlTask {
142 url: String,
143 api_key: String,
144 create: Option<CreateBacktestSessionRequest>,
146 control_session_id: Option<ControlSessionId>,
148 event_txs: HashMap<SessionId, mpsc::UnboundedSender<ControlEvent>>,
151 last_sequences: HashMap<SessionId, u64>,
154 completed: std::collections::HashSet<String>,
157 continues_rx: mpsc::Receiver<TaggedContinue>,
158 status_tx: watch::Sender<ConnectionStatus>,
159 created_tx: Option<oneshot::Sender<Result<ParallelCreated, String>>>,
160 cancel: CancellationToken,
161}
162
163impl ControlConnection for ParallelControlTask {
164 fn url(&self) -> &str {
165 &self.url
166 }
167 fn api_key(&self) -> &str {
168 &self.api_key
169 }
170 fn cancel(&self) -> &CancellationToken {
171 &self.cancel
172 }
173 fn label(&self) -> &'static str {
174 "parallel control"
175 }
176 fn status_tx(&self) -> &watch::Sender<ConnectionStatus> {
177 &self.status_tx
178 }
179
180 fn fail_pending(&mut self, reason: String) {
181 if let Some(tx) = self.created_tx.take() {
182 let _ = tx.send(Err(reason));
183 }
184 }
185
186 async fn handshake(&mut self, ws: Ws) -> Result<Ws, HandshakeError> {
187 if let Some(control_session_id) = self.control_session_id {
188 self.attach(ws, &control_session_id).await
189 } else if let Some(create) = self.create.clone() {
190 self.create_sessions(ws, create).await
195 } else {
196 Err(HandshakeError::Fatal(
197 "no create request and no control_session_id".into(),
198 ))
199 }
200 }
201
202 async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
203 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
204 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
205 let mut last_inbound = std::time::Instant::now();
206
207 let exit = loop {
208 tokio::select! {
209 biased;
210 _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
211
212 _ = ping_timer.tick() => {
213 if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
214 break MessageLoopExit::ConnectionLost(why);
215 }
216 }
217
218 msg = ws.next() => {
219 last_inbound = std::time::Instant::now();
220 match classify_inbound(msg) {
221 InboundFrame::Text(t) => {
222 if let Some(exit) = self.handle_text(&t) {
223 break exit;
224 }
225 }
226 InboundFrame::Ignore => {}
227 InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
228 }
229 }
230
231 req = self.continues_rx.recv() => {
232 match req {
233 Some((session_id, request)) => {
234 let msg = BacktestRequest::ContinueSessionV1(ContinueSessionRequestV1 { session_id, request });
235 if let Err(e) = send_request(&mut ws, &msg).await {
236 break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
237 }
238 }
239 None => break MessageLoopExit::SessionEnded,
240 }
241 }
242 }
243 };
244
245 if matches!(
246 exit,
247 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
248 ) {
249 graceful_close(&mut ws).await;
250 }
251 exit
252 }
253}
254
255impl ParallelControlTask {
256 async fn create_sessions(
260 &mut self,
261 mut ws: Ws,
262 create: CreateBacktestSessionRequest,
263 ) -> Result<Ws, HandshakeError> {
264 send_request(&mut ws, &BacktestRequest::CreateBacktestSession(create))
265 .await
266 .map_err(HandshakeError::Transient)?;
267
268 let rpc_base = http_base_from_ws_url(&self.url);
269 let mut sessions: Vec<CreatedSubSession> = Vec::new();
270
271 loop {
272 let response = next_response(&mut ws, CREATE_RESPONSE_TIMEOUT)
273 .await
274 .map_err(HandshakeError::Transient)?;
275 match response {
276 BacktestResponse::SessionCreated {
277 session_id,
278 rpc_endpoint,
279 task_id,
280 } => {
281 let (event_tx, event_rx) = mpsc::unbounded_channel::<ControlEvent>();
282 self.event_txs.insert(session_id, event_tx);
283 sessions.push(CreatedSubSession {
284 info: SessionInfo {
285 rpc_endpoint: resolve_rpc_url(&rpc_base, &rpc_endpoint),
286 session_id,
287 task_id,
288 },
289 events: event_rx,
290 start_slot: 0,
291 end_slot: 0,
292 });
293 }
294 BacktestResponse::SessionEventV2 {
295 session_id,
296 seq_id,
297 event,
298 } => {
299 self.route_event(&session_id, seq_id, event);
300 }
301 BacktestResponse::SessionsCreatedV2 {
302 control_session_id,
303 session_ids,
304 start_slots,
305 end_slots,
306 ..
307 } => {
308 info!(
309 %control_session_id,
310 sessions = sessions.len(),
311 "parallel sessions created"
312 );
313 if session_ids.len() != start_slots.len()
320 || session_ids.len() != end_slots.len()
321 {
322 return Err(HandshakeError::Fatal(format!(
323 "server did not report per-sub-session ranges \
324 (session_ids={}, start_slots={}, end_slots={}); \
325 server is too old for the multiplexed parallel client",
326 session_ids.len(),
327 start_slots.len(),
328 end_slots.len(),
329 )));
330 }
331 for ((id, start), end) in session_ids.iter().zip(&start_slots).zip(&end_slots) {
332 if let Some(s) = sessions.iter_mut().find(|s| s.info.session_id == *id) {
333 s.start_slot = *start;
334 s.end_slot = *end;
335 }
336 }
337 self.control_session_id = Some(control_session_id);
338 self.create = None;
341 if let Some(tx) = self.created_tx.take() {
342 let _ = tx.send(Ok(ParallelCreated {
343 control_session_id,
344 sessions,
345 }));
346 }
347 return Ok(ws);
348 }
349 BacktestResponse::Error(err) => {
350 return Err(HandshakeError::Fatal(format!(
351 "server error: {}",
352 err_chain(&err)
353 )));
354 }
355 _ => {}
356 }
357 }
358 }
359
360 async fn attach(
364 &mut self,
365 mut ws: Ws,
366 control_session_id: &ControlSessionId,
367 ) -> Result<Ws, HandshakeError> {
368 send_request(
369 &mut ws,
370 &BacktestRequest::AttachParallelControlSessionV2 {
371 control_session_id: *control_session_id,
372 last_sequences: self.last_sequences.clone().into_iter().collect(),
373 },
374 )
375 .await
376 .map_err(HandshakeError::Transient)?;
377
378 loop {
379 let response = next_response(&mut ws, HANDSHAKE_RESPONSE_TIMEOUT)
380 .await
381 .map_err(HandshakeError::Transient)?;
382 match response {
383 BacktestResponse::ParallelSessionAttachedV2 { .. } => {
384 debug!(%control_session_id, "parallel control reattached");
385 return Ok(ws);
386 }
387 BacktestResponse::SessionEventV2 {
388 session_id,
389 seq_id,
390 event,
391 } => {
392 self.route_event(&session_id, seq_id, event);
393 }
394 BacktestResponse::Error(err) => {
395 return Err(handshake_error_for_response("attach", err));
396 }
397 _ => {}
398 }
399 }
400 }
401
402 fn handle_text(&mut self, text: &str) -> Option<MessageLoopExit> {
405 let response = match serde_json::from_str::<BacktestResponse>(text) {
406 Ok(r) => r,
407 Err(e) => {
408 warn!(error = %err_chain(&e), "discarding undeserializable parallel control message");
409 return None;
410 }
411 };
412
413 match response {
414 BacktestResponse::SessionEventV2 {
415 session_id,
416 seq_id,
417 event,
418 } => {
419 self.route_event(&session_id, seq_id, event);
420 if self.completed.len() == self.event_txs.len() && !self.event_txs.is_empty() {
421 return Some(MessageLoopExit::SessionEnded);
422 }
423 }
424 BacktestResponse::Error(err) => {
425 if err.is_terminal() {
426 return Some(MessageLoopExit::Terminal(format!(
427 "control session error: {}",
428 err_chain(&err)
429 )));
430 }
431 warn!(error = %err_chain(&err), "non-terminal parallel control error");
432 }
433 other => {
434 debug!(?other, "ignoring unexpected parallel control response");
435 }
436 }
437 None
438 }
439
440 fn route_event(&mut self, session_id: &SessionId, seq_id: u64, event: SessionEventKind) {
443 match self.last_sequences.get_mut(session_id) {
447 Some(last) if seq_id <= *last => return,
448 Some(last) => *last = seq_id,
449 None => {
450 self.last_sequences.insert(*session_id, seq_id);
451 }
452 }
453
454 let is_completed = matches!(event, SessionEventKind::Completed { .. });
455 let Some(control_event) = session_event_to_control(event) else {
456 return;
457 };
458 if let Some(tx) = self.event_txs.get(session_id) {
459 let _ = tx.send(control_event);
461 }
462 if is_completed {
463 self.completed.insert(session_id.to_string());
464 }
465 }
466}
467
468fn session_event_to_control(event: SessionEventKind) -> Option<ControlEvent> {
471 Some(match event {
472 SessionEventKind::ReadyForContinue => ControlEvent::ReadyForContinue,
473 SessionEventKind::SlotNotification(slot) => ControlEvent::Slot(slot),
474 SessionEventKind::Paused(event) => ControlEvent::Paused(event),
475 SessionEventKind::DiscoveryBatch(event) => ControlEvent::DiscoveryBatch(event),
476 SessionEventKind::Error(error)
479 if matches!(error, BacktestError::SimulationError { .. }) =>
480 {
481 warn!(error = %err_chain(&error), "simulation error");
482 return None;
483 }
484 SessionEventKind::Error(error) => ControlEvent::Error(error),
485 SessionEventKind::Completed { summary } => ControlEvent::Completed {
486 summary,
487 agent_stats: None,
488 },
489 SessionEventKind::Status { status } => ControlEvent::Status(status),
490 SessionEventKind::Success => return None,
491 })
492}
493
494async fn next_response(
496 ws: &mut Ws,
497 timeout: std::time::Duration,
498) -> Result<BacktestResponse, String> {
499 let deadline = tokio::time::Instant::now() + timeout;
500 loop {
501 let msg = tokio::time::timeout_at(deadline, ws.next())
502 .await
503 .map_err(|_| format!("handshake timeout after {timeout:?}"))?;
504
505 let Some(msg) = msg else {
506 return Err("ws ended during handshake".into());
507 };
508 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
509
510 let text = match msg {
511 Message::Text(t) => t,
512 Message::Binary(b) => match String::from_utf8(b) {
513 Ok(t) => t,
514 Err(_) => continue,
515 },
516 Message::Close(frame) => {
517 return Err(format!("remote close during handshake: {frame:?}"));
518 }
519 _ => continue,
520 };
521
522 return serde_json::from_str::<BacktestResponse>(&text)
523 .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)));
524 }
525}
526
527pub struct ManagedParallelSession {
531 control_session_id: ControlSessionId,
532 control: Option<ParallelControlHandle>,
533 sub_sessions: Vec<ParallelSubSession>,
534 session_cancel: CancellationToken,
535}
536
537impl ManagedParallelSession {
538 pub async fn start_with_params(
543 params: StartSessionParams,
544 ) -> Result<Self, ManagedSessionError> {
545 let StartSessionParams {
546 url,
547 api_key,
548 create,
549 parent_cancel,
550 subscription_diagnostics,
551 } = params;
552 let session_cancel = parent_cancel.child_token();
553 let mut control =
554 spawn_parallel_control_manager(url, api_key, create, session_cancel.clone());
555
556 let created = tokio::select! {
557 biased;
558 _ = parent_cancel.cancelled() => {
559 session_cancel.cancel();
560 control.join().await;
561 return Err(ManagedSessionError::Cancelled);
562 }
563 result = control.wait_created() => {
564 result.map_err(ManagedSessionError::Create)?
565 }
566 };
567
568 let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
572 let sub_sessions = created
573 .sessions
574 .into_iter()
575 .map(|s| ParallelSubSession {
576 session_info: s.info,
577 events: s.events,
578 continues: control.continues.clone(),
579 status: control.status.clone(),
580 subscriptions: Vec::new(),
581 session_cancel: session_cancel.child_token(),
582 post_completion: None,
583 post_completion_error: None,
584 reconnect_coordinator: Some(reconnect_coordinator.clone()),
585 subscription_diagnostics: subscription_diagnostics.clone(),
586 start_slot: s.start_slot,
587 end_slot: s.end_slot,
588 })
589 .collect();
590
591 Ok(Self {
592 control_session_id: created.control_session_id,
593 control: Some(control),
594 sub_sessions,
595 session_cancel,
596 })
597 }
598
599 pub fn control_session_id(&self) -> ControlSessionId {
601 self.control_session_id
602 }
603
604 pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
607 std::mem::take(&mut self.sub_sessions)
608 }
609
610 pub async fn shutdown(mut self) {
612 self.session_cancel.cancel();
613 if let Some(control) = self.control.take() {
614 control.join().await;
615 }
616 }
617}
618
619impl Drop for ManagedParallelSession {
620 fn drop(&mut self) {
621 self.session_cancel.cancel();
622 }
623}
624
625pub struct ParallelSubSession {
630 session_info: SessionInfo,
631 events: mpsc::UnboundedReceiver<ControlEvent>,
632 continues: mpsc::Sender<TaggedContinue>,
633 status: watch::Receiver<ConnectionStatus>,
634 subscriptions: Vec<SubscriptionHandle>,
635 session_cancel: CancellationToken,
636 post_completion: Option<VecDeque<ManagedEvent>>,
639 post_completion_error: Option<ManagedSessionError>,
642 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
645 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
646 start_slot: u64,
649 end_slot: u64,
650}
651
652impl ParallelSubSession {
653 pub fn session_info(&self) -> &SessionInfo {
654 &self.session_info
655 }
656
657 pub fn range(&self) -> (u64, u64) {
659 (self.start_slot, self.end_slot)
660 }
661
662 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
663 self.subscriptions
664 .push(spawn_transaction_subscription_manager(
665 self.session_info.rpc_endpoint.clone(),
666 program_ids,
667 self.session_cancel.clone(),
668 self.reconnect_coordinator.clone(),
669 self.subscription_diagnostics.clone(),
670 ));
671 }
672
673 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
674 self.subscriptions
675 .push(spawn_account_diff_subscription_manager(
676 self.session_info.rpc_endpoint.clone(),
677 program_ids,
678 self.session_cancel.clone(),
679 self.reconnect_coordinator.clone(),
680 self.subscription_diagnostics.clone(),
681 ));
682 }
683
684 pub fn subscribe_actions(&mut self) {
686 self.subscriptions.push(spawn_action_subscription_manager(
687 self.session_info.rpc_endpoint.clone(),
688 self.session_cancel.clone(),
689 self.reconnect_coordinator.clone(),
690 self.subscription_diagnostics.clone(),
691 ));
692 }
693
694 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
698 if let Some(buffered) = self.post_completion.as_mut() {
701 if let Some(event) = buffered.pop_front() {
702 return Ok(event);
703 }
704 return Err(self
707 .post_completion_error
708 .take()
709 .unwrap_or(ManagedSessionError::ControlClosed));
710 }
711
712 if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
713 return Ok(event);
714 }
715
716 let event = {
719 let cancel = &self.session_cancel;
720 let subscriptions = &mut self.subscriptions;
721 tokio::select! {
722 biased;
723 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
724 event = self.events.recv() => {
725 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
726 }
727 event = wait_any_subscription_event(subscriptions) => event,
728 }
729 };
730
731 let ManagedEvent::Completed {
733 summary,
734 agent_stats,
735 } = event
736 else {
737 return Ok(event);
738 };
739
740 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
744 .drain_until_subscriptions_complete(COMPLETION_DRAIN_TIMEOUT)
745 .await
746 {
747 DrainOutcome::Complete(events) => (
748 events.into(),
749 Ok(ManagedEvent::Completed {
750 summary,
751 agent_stats,
752 }),
753 ),
754 DrainOutcome::Stalled(events) => (
758 events.into(),
759 Err(ManagedSessionError::SubscriptionFailed(
760 "completion drain stalled: subscriptions did not deliver their \
761 end-of-stream terminals; the captured stream is incomplete"
762 .to_string(),
763 )),
764 ),
765 };
766 match terminal {
767 Ok(completed) => buffered.push_back(completed),
768 Err(err) => self.post_completion_error = Some(err),
769 }
770 let first = buffered.pop_front();
771 self.post_completion = Some(buffered);
772 match first {
773 Some(event) => Ok(event),
774 None => Err(self
775 .post_completion_error
776 .take()
777 .unwrap_or(ManagedSessionError::ControlClosed)),
778 }
779 }
780
781 pub async fn send_continue(
784 &mut self,
785 params: ContinueParams,
786 ) -> Result<(), ManagedSessionError> {
787 self.wait_all_up().await?;
788 self.continues
789 .send((self.session_info.session_id, params))
790 .await
791 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
792 }
793
794 async fn drain_until_subscriptions_complete(
796 &mut self,
797 idle_timeout: std::time::Duration,
798 ) -> DrainOutcome {
799 drain_subscriptions_until_complete(
800 &mut self.subscriptions,
801 &self.session_cancel,
802 idle_timeout,
803 )
804 .await
805 }
806
807 pub async fn shutdown(mut self) {
810 self.session_cancel.cancel();
811 for sub in std::mem::take(&mut self.subscriptions) {
812 let _ = sub.join.await;
813 }
814 }
815
816 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
817 let subscriptions = self
818 .subscriptions
819 .iter()
820 .map(|s| s.status.clone())
821 .collect();
822 wait_connections_up(self.status.clone(), subscriptions, &self.session_cancel).await
823 }
824}
825
826impl Drop for ParallelSubSession {
827 fn drop(&mut self) {
828 self.session_cancel.cancel();
829 }
830}