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, CreateError, HANDSHAKE_RESPONSE_TIMEOUT,
38 HandshakeError, InboundFrame, KEEPALIVE_INTERVAL, ManagedEvent, ManagedSessionError,
39 MessageLoopExit, ReconnectCoordinator, SessionInfo, StartSessionParams,
40 SubscriptionDiagnostics, SubscriptionHandle, Ws, classify_inbound, graceful_close,
41 handshake_error_for_response, resolve_rpc_url, run_control_loop, send_keepalive_ping,
42 send_request,
43 session::{
44 DrainOutcome, drain_subscriptions_until_complete, try_next_subscription_event,
45 wait_any_subscription_event, wait_connections_up,
46 },
47 spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
48 spawn_transaction_subscription_manager,
49};
50use crate::{error::err_chain, urls::http_base_from_ws_url};
51
52const CREATE_RESPONSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(900);
55const CONTINUE_CHANNEL_CAPACITY: usize = 256;
58const COMPLETION_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
61
62type TaggedContinue = (SessionId, ContinueParams);
64
65struct ParallelCreated {
67 control_session_id: ControlSessionId,
68 control_session_name: Option<String>,
69 sessions: Vec<CreatedSubSession>,
70}
71
72struct CreatedSubSession {
73 info: SessionInfo,
74 events: mpsc::UnboundedReceiver<ControlEvent>,
75 start_slot: u64,
79 end_slot: u64,
80}
81
82struct ParallelControlHandle {
84 continues: mpsc::Sender<TaggedContinue>,
85 status: watch::Receiver<ConnectionStatus>,
86 created: Option<oneshot::Receiver<Result<ParallelCreated, ManagedSessionError>>>,
87 join: JoinHandle<()>,
88}
89
90impl ParallelControlHandle {
91 async fn wait_created(&mut self) -> Result<ParallelCreated, ManagedSessionError> {
94 let rx = self
95 .created
96 .take()
97 .ok_or(ManagedSessionError::ControlClosed)?;
98 rx.await.map_err(|_| ManagedSessionError::ControlClosed)?
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) =
119 oneshot::channel::<Result<ParallelCreated, ManagedSessionError>>();
120
121 let task = ParallelControlTask {
122 url,
123 api_key,
124 extra_headers,
125 create: Some(create),
126 control_session_id: None,
127 event_txs: HashMap::new(),
128 last_sequences: HashMap::new(),
129 completed: std::collections::HashSet::new(),
130 continues_rx,
131 status_tx,
132 created_tx: Some(created_tx),
133 cancel,
134 };
135
136 let join = tokio::spawn(run_control_loop(task));
137
138 ParallelControlHandle {
139 continues: continues_tx,
140 status: status_rx,
141 created: Some(created_rx),
142 join,
143 }
144}
145
146struct ParallelControlTask {
147 url: String,
148 api_key: String,
149 extra_headers: HeaderMap,
150 create: Option<CreateBacktestSessionRequest>,
152 control_session_id: Option<ControlSessionId>,
154 event_txs: HashMap<SessionId, mpsc::UnboundedSender<ControlEvent>>,
157 last_sequences: HashMap<SessionId, u64>,
160 completed: std::collections::HashSet<String>,
163 continues_rx: mpsc::Receiver<TaggedContinue>,
164 status_tx: watch::Sender<ConnectionStatus>,
165 created_tx: Option<oneshot::Sender<Result<ParallelCreated, ManagedSessionError>>>,
166 cancel: CancellationToken,
167}
168
169impl ControlConnection for ParallelControlTask {
170 fn url(&self) -> &str {
171 &self.url
172 }
173 fn api_key(&self) -> &str {
174 &self.api_key
175 }
176 fn extra_headers(&self) -> &HeaderMap {
177 &self.extra_headers
178 }
179 fn cancel(&self) -> &CancellationToken {
180 &self.cancel
181 }
182 fn label(&self) -> &'static str {
183 "parallel control"
184 }
185 fn status_tx(&self) -> &watch::Sender<ConnectionStatus> {
186 &self.status_tx
187 }
188
189 fn fail_pending(&mut self, error: ManagedSessionError) {
190 if let Some(tx) = self.created_tx.take() {
191 let _ = tx.send(Err(error));
192 }
193 }
194
195 async fn handshake(&mut self, ws: Ws) -> Result<Ws, HandshakeError> {
196 if let Some(control_session_id) = self.control_session_id {
197 self.attach(ws, &control_session_id).await
198 } else if let Some(create) = self.create.clone() {
199 self.create_sessions(ws, create).await
204 } else {
205 Err(HandshakeError::Fatal(CreateError::Protocol(
206 "no create request and no control_session_id".into(),
207 )))
208 }
209 }
210
211 async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
212 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
213 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
214 let mut last_inbound = std::time::Instant::now();
215
216 let exit = loop {
217 tokio::select! {
218 biased;
219 _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
220
221 _ = ping_timer.tick() => {
222 if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
223 break MessageLoopExit::ConnectionLost(why);
224 }
225 }
226
227 msg = ws.next() => {
228 last_inbound = std::time::Instant::now();
229 match classify_inbound(msg) {
230 InboundFrame::Text(t) => {
231 if let Some(exit) = self.handle_text(&t) {
232 break exit;
233 }
234 }
235 InboundFrame::Ignore => {}
236 InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
237 }
238 }
239
240 req = self.continues_rx.recv() => {
241 match req {
242 Some((session_id, request)) => {
243 let msg = BacktestRequest::ContinueSessionV1(ContinueSessionRequestV1 { session_id, request });
244 if let Err(e) = send_request(&mut ws, &msg).await {
245 break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
246 }
247 }
248 None => break MessageLoopExit::SessionEnded,
249 }
250 }
251 }
252 };
253
254 if matches!(
255 exit,
256 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
257 ) {
258 graceful_close(&mut ws).await;
259 }
260 exit
261 }
262}
263
264impl ParallelControlTask {
265 async fn create_sessions(
269 &mut self,
270 mut ws: Ws,
271 create: CreateBacktestSessionRequest,
272 ) -> Result<Ws, HandshakeError> {
273 send_request(&mut ws, &BacktestRequest::CreateBacktestSession(create))
274 .await
275 .map_err(HandshakeError::Transient)?;
276
277 let rpc_base = http_base_from_ws_url(&self.url);
278 let mut sessions: Vec<CreatedSubSession> = Vec::new();
279
280 loop {
281 let response = next_response(&mut ws, CREATE_RESPONSE_TIMEOUT)
282 .await
283 .map_err(HandshakeError::Transient)?;
284 match response {
285 BacktestResponse::SessionCreated {
286 session_id,
287 session_name,
288 rpc_endpoint,
289 task_id,
290 } => {
291 let (event_tx, event_rx) = mpsc::unbounded_channel::<ControlEvent>();
292 self.event_txs.insert(session_id, event_tx);
293 sessions.push(CreatedSubSession {
294 info: SessionInfo {
295 rpc_endpoint: resolve_rpc_url(&rpc_base, &rpc_endpoint),
296 session_id,
297 session_name,
298 task_id,
299 },
300 events: event_rx,
301 start_slot: 0,
302 end_slot: 0,
303 });
304 }
305 BacktestResponse::SessionEventV2 {
306 session_id,
307 seq_id,
308 event,
309 } => {
310 self.route_event(&session_id, seq_id, event);
311 }
312 BacktestResponse::SessionsCreatedV2 {
313 control_session_id,
314 control_session_name,
315 session_ids,
316 start_slots,
317 end_slots,
318 ..
319 } => {
320 info!(
321 %control_session_id,
322 sessions = sessions.len(),
323 "parallel sessions created"
324 );
325 if session_ids.len() != start_slots.len()
332 || session_ids.len() != end_slots.len()
333 {
334 return Err(HandshakeError::Fatal(CreateError::Protocol(format!(
335 "server did not report per-sub-session ranges \
336 (session_ids={}, start_slots={}, end_slots={}); \
337 server is too old for the multiplexed parallel client",
338 session_ids.len(),
339 start_slots.len(),
340 end_slots.len(),
341 ))));
342 }
343 for ((id, start), end) in session_ids.iter().zip(&start_slots).zip(&end_slots) {
344 if let Some(s) = sessions.iter_mut().find(|s| s.info.session_id == *id) {
345 s.start_slot = *start;
346 s.end_slot = *end;
347 }
348 }
349 self.control_session_id = Some(control_session_id);
350 self.create = None;
353 if let Some(tx) = self.created_tx.take() {
354 let _ = tx.send(Ok(ParallelCreated {
355 control_session_id,
356 control_session_name,
357 sessions,
358 }));
359 }
360 return Ok(ws);
361 }
362 BacktestResponse::Error(err) => {
363 return Err(HandshakeError::Fatal(CreateError::Rejected(err)));
364 }
365 _ => {}
366 }
367 }
368 }
369
370 async fn attach(
374 &mut self,
375 mut ws: Ws,
376 control_session_id: &ControlSessionId,
377 ) -> Result<Ws, HandshakeError> {
378 send_request(
379 &mut ws,
380 &BacktestRequest::AttachParallelControlSessionV2 {
381 control_session_id: *control_session_id,
382 last_sequences: self.last_sequences.clone().into_iter().collect(),
383 },
384 )
385 .await
386 .map_err(HandshakeError::Transient)?;
387
388 loop {
389 let response = next_response(&mut ws, HANDSHAKE_RESPONSE_TIMEOUT)
390 .await
391 .map_err(HandshakeError::Transient)?;
392 match response {
393 BacktestResponse::ParallelSessionAttachedV2 { .. } => {
394 debug!(%control_session_id, "parallel control reattached");
395 return Ok(ws);
396 }
397 BacktestResponse::SessionEventV2 {
398 session_id,
399 seq_id,
400 event,
401 } => {
402 self.route_event(&session_id, seq_id, event);
403 }
404 BacktestResponse::Error(err) => {
405 return Err(handshake_error_for_response("attach", err));
406 }
407 _ => {}
408 }
409 }
410 }
411
412 fn handle_text(&mut self, text: &str) -> Option<MessageLoopExit> {
415 let response = match serde_json::from_str::<BacktestResponse>(text) {
416 Ok(r) => r,
417 Err(e) => {
418 warn!(error = %err_chain(&e), "discarding undeserializable parallel control message");
419 return None;
420 }
421 };
422
423 match response {
424 BacktestResponse::SessionEventV2 {
425 session_id,
426 seq_id,
427 event,
428 } => {
429 self.route_event(&session_id, seq_id, event);
430 if self.completed.len() == self.event_txs.len() && !self.event_txs.is_empty() {
431 return Some(MessageLoopExit::SessionEnded);
432 }
433 }
434 BacktestResponse::Error(err) => {
435 if err.is_terminal() {
436 return Some(MessageLoopExit::Terminal(format!(
437 "control session error: {}",
438 err_chain(&err)
439 )));
440 }
441 warn!(error = %err_chain(&err), "non-terminal parallel control error");
442 }
443 other => {
444 debug!(?other, "ignoring unexpected parallel control response");
445 }
446 }
447 None
448 }
449
450 fn route_event(&mut self, session_id: &SessionId, seq_id: u64, event: SessionEventKind) {
453 match self.last_sequences.get_mut(session_id) {
457 Some(last) if seq_id <= *last => return,
458 Some(last) => *last = seq_id,
459 None => {
460 self.last_sequences.insert(*session_id, seq_id);
461 }
462 }
463
464 let is_completed = matches!(event, SessionEventKind::Completed { .. });
465 let Some(control_event) = session_event_to_control(event) else {
466 return;
467 };
468 if let Some(tx) = self.event_txs.get(session_id) {
469 let _ = tx.send(control_event);
471 }
472 if is_completed {
473 self.completed.insert(session_id.to_string());
474 }
475 }
476}
477
478fn session_event_to_control(event: SessionEventKind) -> Option<ControlEvent> {
481 Some(match event {
482 SessionEventKind::ReadyForContinue => ControlEvent::ReadyForContinue,
483 SessionEventKind::SlotNotification(slot) => ControlEvent::Slot(slot),
484 SessionEventKind::Paused(event) => ControlEvent::Paused(event),
485 SessionEventKind::DiscoveryBatch(event) => ControlEvent::DiscoveryBatch(event),
486 SessionEventKind::Error(error)
489 if matches!(error, BacktestError::SimulationError { .. }) =>
490 {
491 warn!(error = %err_chain(&error), "simulation error");
492 return None;
493 }
494 SessionEventKind::Error(error) => ControlEvent::Error(error),
495 SessionEventKind::Completed { summary } => ControlEvent::Completed { summary },
496 SessionEventKind::Status { status } => ControlEvent::Status(status),
497 SessionEventKind::Success => return None,
498 })
499}
500
501async fn next_response(
503 ws: &mut Ws,
504 timeout: std::time::Duration,
505) -> Result<BacktestResponse, String> {
506 let deadline = tokio::time::Instant::now() + timeout;
507 loop {
508 let msg = tokio::time::timeout_at(deadline, ws.next())
509 .await
510 .map_err(|_| format!("handshake timeout after {timeout:?}"))?;
511
512 let Some(msg) = msg else {
513 return Err("ws ended during handshake".into());
514 };
515 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
516
517 let text = match msg {
518 Message::Text(t) => t,
519 Message::Binary(b) => match String::from_utf8(b) {
520 Ok(t) => t,
521 Err(_) => continue,
522 },
523 Message::Close(frame) => {
524 return Err(format!("remote close during handshake: {frame:?}"));
525 }
526 _ => continue,
527 };
528
529 return serde_json::from_str::<BacktestResponse>(&text)
530 .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)));
531 }
532}
533
534pub struct ManagedParallelSession {
594 control_session_id: ControlSessionId,
595 control_session_name: Option<String>,
596 control: Option<ParallelControlHandle>,
597 sub_sessions: Vec<ParallelSubSession>,
598 session_cancel: CancellationToken,
599}
600
601impl ManagedParallelSession {
602 pub async fn start_with_params(
616 params: StartSessionParams,
617 ) -> Result<Self, ManagedSessionError> {
618 let StartSessionParams {
619 url,
620 api_key,
621 extra_headers,
622 create,
623 parent_cancel,
624 subscription_diagnostics,
625 } = params;
626 let session_cancel = parent_cancel.child_token();
627 let mut control = spawn_parallel_control_manager(
628 url,
629 api_key,
630 extra_headers,
631 create,
632 session_cancel.clone(),
633 );
634
635 let created = tokio::select! {
636 biased;
637 _ = parent_cancel.cancelled() => {
638 session_cancel.cancel();
639 control.join().await;
640 return Err(ManagedSessionError::Cancelled);
641 }
642 result = control.wait_created() => result?,
643 };
644
645 let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
649 let sub_sessions = created
650 .sessions
651 .into_iter()
652 .map(|s| ParallelSubSession {
653 session_info: s.info,
654 events: s.events,
655 continues: control.continues.clone(),
656 status: control.status.clone(),
657 subscriptions: Vec::new(),
658 session_cancel: session_cancel.child_token(),
659 post_completion: None,
660 post_completion_error: None,
661 reconnect_coordinator: Some(reconnect_coordinator.clone()),
662 subscription_diagnostics: subscription_diagnostics.clone(),
663 start_slot: s.start_slot,
664 end_slot: s.end_slot,
665 })
666 .collect();
667
668 Ok(Self {
669 control_session_id: created.control_session_id,
670 control_session_name: created.control_session_name,
671 control: Some(control),
672 sub_sessions,
673 session_cancel,
674 })
675 }
676
677 pub fn control_session_id(&self) -> ControlSessionId {
679 self.control_session_id
680 }
681
682 pub fn control_session_name(&self) -> Option<&str> {
684 self.control_session_name.as_deref()
685 }
686
687 pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
690 std::mem::take(&mut self.sub_sessions)
691 }
692
693 pub async fn shutdown(mut self) {
696 self.session_cancel.cancel();
697 if let Some(control) = self.control.take() {
698 control.join().await;
699 }
700 }
701}
702
703impl Drop for ManagedParallelSession {
704 fn drop(&mut self) {
705 self.session_cancel.cancel();
706 }
707}
708
709pub struct ParallelSubSession {
719 session_info: SessionInfo,
720 events: mpsc::UnboundedReceiver<ControlEvent>,
721 continues: mpsc::Sender<TaggedContinue>,
722 status: watch::Receiver<ConnectionStatus>,
723 subscriptions: Vec<SubscriptionHandle>,
724 session_cancel: CancellationToken,
725 post_completion: Option<VecDeque<ManagedEvent>>,
728 post_completion_error: Option<ManagedSessionError>,
731 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
734 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
735 start_slot: u64,
738 end_slot: u64,
739}
740
741impl ParallelSubSession {
742 pub fn session_info(&self) -> &SessionInfo {
744 &self.session_info
745 }
746
747 pub fn range(&self) -> (u64, u64) {
749 (self.start_slot, self.end_slot)
750 }
751
752 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
754 self.subscriptions
755 .push(spawn_transaction_subscription_manager(
756 self.session_info.rpc_endpoint.clone(),
757 program_ids,
758 self.session_cancel.clone(),
759 self.reconnect_coordinator.clone(),
760 self.subscription_diagnostics.clone(),
761 ));
762 }
763
764 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
766 self.subscriptions
767 .push(spawn_account_diff_subscription_manager(
768 self.session_info.rpc_endpoint.clone(),
769 program_ids,
770 self.session_cancel.clone(),
771 self.reconnect_coordinator.clone(),
772 self.subscription_diagnostics.clone(),
773 ));
774 }
775
776 pub fn subscribe_actions(&mut self) {
778 self.subscriptions.push(spawn_action_subscription_manager(
779 self.session_info.rpc_endpoint.clone(),
780 self.session_cancel.clone(),
781 self.reconnect_coordinator.clone(),
782 self.subscription_diagnostics.clone(),
783 ));
784 }
785
786 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
792 if let Some(buffered) = self.post_completion.as_mut() {
795 if let Some(event) = buffered.pop_front() {
796 return Ok(event);
797 }
798 return Err(self
801 .post_completion_error
802 .take()
803 .unwrap_or(ManagedSessionError::ControlClosed));
804 }
805
806 if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
807 return Ok(event);
808 }
809
810 let event = {
813 let cancel = &self.session_cancel;
814 let subscriptions = &mut self.subscriptions;
815 tokio::select! {
816 biased;
817 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
818 event = self.events.recv() => {
819 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
820 }
821 event = wait_any_subscription_event(subscriptions) => event,
822 }
823 };
824
825 let ManagedEvent::Completed { summary } = event else {
827 return Ok(event);
828 };
829
830 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
834 .drain_until_subscriptions_complete(COMPLETION_DRAIN_TIMEOUT)
835 .await
836 {
837 DrainOutcome::Complete(events) => {
838 (events.into(), Ok(ManagedEvent::Completed { summary }))
839 }
840 DrainOutcome::Stalled(events) => (
844 events.into(),
845 Err(ManagedSessionError::SubscriptionFailed(
846 "completion drain stalled: subscriptions did not deliver their \
847 end-of-stream terminals; the captured stream is incomplete"
848 .to_string(),
849 )),
850 ),
851 };
852 match terminal {
853 Ok(completed) => buffered.push_back(completed),
854 Err(err) => self.post_completion_error = Some(err),
855 }
856 let first = buffered.pop_front();
857 self.post_completion = Some(buffered);
858 match first {
859 Some(event) => Ok(event),
860 None => Err(self
861 .post_completion_error
862 .take()
863 .unwrap_or(ManagedSessionError::ControlClosed)),
864 }
865 }
866
867 pub async fn send_continue(
874 &mut self,
875 params: ContinueParams,
876 ) -> Result<(), ManagedSessionError> {
877 self.wait_all_up().await?;
878 self.continues
879 .send((self.session_info.session_id, params))
880 .await
881 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
882 }
883
884 async fn drain_until_subscriptions_complete(
886 &mut self,
887 idle_timeout: std::time::Duration,
888 ) -> DrainOutcome {
889 drain_subscriptions_until_complete(
890 &mut self.subscriptions,
891 &self.session_cancel,
892 idle_timeout,
893 )
894 .await
895 }
896
897 pub async fn shutdown(mut self) {
900 self.session_cancel.cancel();
901 for sub in std::mem::take(&mut self.subscriptions) {
902 drop(sub.notifications);
904 let _ = sub.join.await;
905 }
906 }
907
908 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
909 let subscriptions = self
910 .subscriptions
911 .iter()
912 .map(|s| s.status.clone())
913 .collect();
914 wait_connections_up(self.status.clone(), subscriptions, &self.session_cancel).await
915 }
916}
917
918impl Drop for ParallelSubSession {
919 fn drop(&mut self) {
920 self.session_cancel.cancel();
921 }
922}