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 { summary },
486 SessionEventKind::Status { status } => ControlEvent::Status(status),
487 SessionEventKind::Success => return None,
488 })
489}
490
491async fn next_response(
493 ws: &mut Ws,
494 timeout: std::time::Duration,
495) -> Result<BacktestResponse, String> {
496 let deadline = tokio::time::Instant::now() + timeout;
497 loop {
498 let msg = tokio::time::timeout_at(deadline, ws.next())
499 .await
500 .map_err(|_| format!("handshake timeout after {timeout:?}"))?;
501
502 let Some(msg) = msg else {
503 return Err("ws ended during handshake".into());
504 };
505 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
506
507 let text = match msg {
508 Message::Text(t) => t,
509 Message::Binary(b) => match String::from_utf8(b) {
510 Ok(t) => t,
511 Err(_) => continue,
512 },
513 Message::Close(frame) => {
514 return Err(format!("remote close during handshake: {frame:?}"));
515 }
516 _ => continue,
517 };
518
519 return serde_json::from_str::<BacktestResponse>(&text)
520 .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)));
521 }
522}
523
524pub struct ManagedParallelSession {
528 control_session_id: ControlSessionId,
529 control: Option<ParallelControlHandle>,
530 sub_sessions: Vec<ParallelSubSession>,
531 session_cancel: CancellationToken,
532}
533
534impl ManagedParallelSession {
535 pub async fn start_with_params(
540 params: StartSessionParams,
541 ) -> Result<Self, ManagedSessionError> {
542 let StartSessionParams {
543 url,
544 api_key,
545 create,
546 parent_cancel,
547 subscription_diagnostics,
548 } = params;
549 let session_cancel = parent_cancel.child_token();
550 let mut control =
551 spawn_parallel_control_manager(url, api_key, create, session_cancel.clone());
552
553 let created = tokio::select! {
554 biased;
555 _ = parent_cancel.cancelled() => {
556 session_cancel.cancel();
557 control.join().await;
558 return Err(ManagedSessionError::Cancelled);
559 }
560 result = control.wait_created() => {
561 result.map_err(ManagedSessionError::Create)?
562 }
563 };
564
565 let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
569 let sub_sessions = created
570 .sessions
571 .into_iter()
572 .map(|s| ParallelSubSession {
573 session_info: s.info,
574 events: s.events,
575 continues: control.continues.clone(),
576 status: control.status.clone(),
577 subscriptions: Vec::new(),
578 session_cancel: session_cancel.child_token(),
579 post_completion: None,
580 post_completion_error: None,
581 reconnect_coordinator: Some(reconnect_coordinator.clone()),
582 subscription_diagnostics: subscription_diagnostics.clone(),
583 start_slot: s.start_slot,
584 end_slot: s.end_slot,
585 })
586 .collect();
587
588 Ok(Self {
589 control_session_id: created.control_session_id,
590 control: Some(control),
591 sub_sessions,
592 session_cancel,
593 })
594 }
595
596 pub fn control_session_id(&self) -> ControlSessionId {
598 self.control_session_id
599 }
600
601 pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
604 std::mem::take(&mut self.sub_sessions)
605 }
606
607 pub async fn shutdown(mut self) {
609 self.session_cancel.cancel();
610 if let Some(control) = self.control.take() {
611 control.join().await;
612 }
613 }
614}
615
616impl Drop for ManagedParallelSession {
617 fn drop(&mut self) {
618 self.session_cancel.cancel();
619 }
620}
621
622pub struct ParallelSubSession {
627 session_info: SessionInfo,
628 events: mpsc::UnboundedReceiver<ControlEvent>,
629 continues: mpsc::Sender<TaggedContinue>,
630 status: watch::Receiver<ConnectionStatus>,
631 subscriptions: Vec<SubscriptionHandle>,
632 session_cancel: CancellationToken,
633 post_completion: Option<VecDeque<ManagedEvent>>,
636 post_completion_error: Option<ManagedSessionError>,
639 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
642 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
643 start_slot: u64,
646 end_slot: u64,
647}
648
649impl ParallelSubSession {
650 pub fn session_info(&self) -> &SessionInfo {
651 &self.session_info
652 }
653
654 pub fn range(&self) -> (u64, u64) {
656 (self.start_slot, self.end_slot)
657 }
658
659 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
660 self.subscriptions
661 .push(spawn_transaction_subscription_manager(
662 self.session_info.rpc_endpoint.clone(),
663 program_ids,
664 self.session_cancel.clone(),
665 self.reconnect_coordinator.clone(),
666 self.subscription_diagnostics.clone(),
667 ));
668 }
669
670 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
671 self.subscriptions
672 .push(spawn_account_diff_subscription_manager(
673 self.session_info.rpc_endpoint.clone(),
674 program_ids,
675 self.session_cancel.clone(),
676 self.reconnect_coordinator.clone(),
677 self.subscription_diagnostics.clone(),
678 ));
679 }
680
681 pub fn subscribe_actions(&mut self) {
683 self.subscriptions.push(spawn_action_subscription_manager(
684 self.session_info.rpc_endpoint.clone(),
685 self.session_cancel.clone(),
686 self.reconnect_coordinator.clone(),
687 self.subscription_diagnostics.clone(),
688 ));
689 }
690
691 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
695 if let Some(buffered) = self.post_completion.as_mut() {
698 if let Some(event) = buffered.pop_front() {
699 return Ok(event);
700 }
701 return Err(self
704 .post_completion_error
705 .take()
706 .unwrap_or(ManagedSessionError::ControlClosed));
707 }
708
709 if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
710 return Ok(event);
711 }
712
713 let event = {
716 let cancel = &self.session_cancel;
717 let subscriptions = &mut self.subscriptions;
718 tokio::select! {
719 biased;
720 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
721 event = self.events.recv() => {
722 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
723 }
724 event = wait_any_subscription_event(subscriptions) => event,
725 }
726 };
727
728 let ManagedEvent::Completed { summary } = event else {
730 return Ok(event);
731 };
732
733 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
737 .drain_until_subscriptions_complete(COMPLETION_DRAIN_TIMEOUT)
738 .await
739 {
740 DrainOutcome::Complete(events) => {
741 (events.into(), Ok(ManagedEvent::Completed { summary }))
742 }
743 DrainOutcome::Stalled(events) => (
747 events.into(),
748 Err(ManagedSessionError::SubscriptionFailed(
749 "completion drain stalled: subscriptions did not deliver their \
750 end-of-stream terminals; the captured stream is incomplete"
751 .to_string(),
752 )),
753 ),
754 };
755 match terminal {
756 Ok(completed) => buffered.push_back(completed),
757 Err(err) => self.post_completion_error = Some(err),
758 }
759 let first = buffered.pop_front();
760 self.post_completion = Some(buffered);
761 match first {
762 Some(event) => Ok(event),
763 None => Err(self
764 .post_completion_error
765 .take()
766 .unwrap_or(ManagedSessionError::ControlClosed)),
767 }
768 }
769
770 pub async fn send_continue(
773 &mut self,
774 params: ContinueParams,
775 ) -> Result<(), ManagedSessionError> {
776 self.wait_all_up().await?;
777 self.continues
778 .send((self.session_info.session_id, params))
779 .await
780 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
781 }
782
783 async fn drain_until_subscriptions_complete(
785 &mut self,
786 idle_timeout: std::time::Duration,
787 ) -> DrainOutcome {
788 drain_subscriptions_until_complete(
789 &mut self.subscriptions,
790 &self.session_cancel,
791 idle_timeout,
792 )
793 .await
794 }
795
796 pub async fn shutdown(mut self) {
799 self.session_cancel.cancel();
800 for sub in std::mem::take(&mut self.subscriptions) {
801 drop(sub.notifications);
803 let _ = sub.join.await;
804 }
805 }
806
807 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
808 let subscriptions = self
809 .subscriptions
810 .iter()
811 .map(|s| s.status.clone())
812 .collect();
813 wait_connections_up(self.status.clone(), subscriptions, &self.session_cancel).await
814 }
815}
816
817impl Drop for ParallelSubSession {
818 fn drop(&mut self) {
819 self.session_cancel.cancel();
820 }
821}