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