1use std::{collections::HashSet, marker::PhantomData, sync::Arc, time::Instant};
17
18use futures::{SinkExt, StreamExt};
19use serde::{Deserialize, de::DeserializeOwned};
20use simulator_api::{
21 subscribe_config::{Compression, SubscribeConfig},
22 ws_compression::WsStreamDecompressor,
23};
24use solana_address::Address;
25use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
26use tokio::{
27 net::TcpStream,
28 sync::{mpsc, watch},
29 task::JoinHandle,
30};
31use tokio_tungstenite::{
32 MaybeTlsStream, WebSocketStream, connect_async,
33 tungstenite::{Message, client::IntoClientRequest},
34};
35use tokio_util::sync::CancellationToken;
36use tracing::{debug, warn};
37
38use super::{
39 CONNECT_TIMEOUT, ConnectionStatus, HANDSHAKE_RESPONSE_TIMEOUT, KEEPALIVE_INTERVAL,
40 KEEPALIVE_MISS_DEADLINE, RECONNECT_UNGATED_ATTEMPTS, RECONNECT_UPTIME_RESET, ReconnectBudget,
41 ReconnectCoordinator, SubscriptionDiagnostics, cancellable_sleep,
42};
43use crate::{
44 error::err_chain,
45 subscriptions::{AccountDiffNotification, ActionResultNotification, DiagnosticNotification},
46 urls::http_to_ws_url,
47};
48
49pub struct SubscriptionHandle {
51 pub status: watch::Receiver<ConnectionStatus>,
52 pub notifications: mpsc::Receiver<SubscriptionNotification>,
53 pub join: JoinHandle<()>,
54}
55
56#[derive(Debug)]
57pub enum SubscriptionNotification {
58 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
59 AccountDiff(AccountDiffNotification),
60 ActionResult(ActionResultNotification),
61 Diagnostic(DiagnosticNotification),
62}
63
64trait SubKind: Send + Sync + 'static {
66 type Notification: DeserializeOwned + Send + 'static;
67 const LABEL: &'static str;
68 const SUBSCRIBE_METHOD: &'static str;
69 const NOTIFICATION_METHOD: &'static str;
70 fn subscribe_params(program_id: &str) -> serde_json::Value;
71 fn into_notification(notification: Self::Notification) -> SubscriptionNotification;
72 fn slot_of(notification: &Self::Notification) -> u64;
76}
77
78struct AccountDiff;
79impl SubKind for AccountDiff {
80 type Notification = AccountDiffNotification;
81 const LABEL: &'static str = "account-diff";
82 const SUBSCRIBE_METHOD: &'static str = "accountDiffSubscribe";
83 const NOTIFICATION_METHOD: &'static str = "accountDiffNotification";
84 fn subscribe_params(program_id: &str) -> serde_json::Value {
85 serde_json::json!([program_id, {"address_type": "program"}])
86 }
87 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
88 SubscriptionNotification::AccountDiff(notification)
89 }
90 fn slot_of(notification: &Self::Notification) -> u64 {
91 notification.context.slot
92 }
93}
94
95struct Transaction;
96impl SubKind for Transaction {
97 type Notification = EncodedConfirmedTransactionWithStatusMeta;
101 const LABEL: &'static str = "transaction";
102 const SUBSCRIBE_METHOD: &'static str = "transactionSubscribe";
103 const NOTIFICATION_METHOD: &'static str = "transactionNotification";
104 fn subscribe_params(program_id: &str) -> serde_json::Value {
105 serde_json::json!([{"mentions": [program_id]}, {"commitment": "confirmed"}])
106 }
107 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
108 SubscriptionNotification::Transaction(Box::new(notification))
109 }
110 fn slot_of(notification: &Self::Notification) -> u64 {
111 notification.slot
112 }
113}
114
115struct Diagnostic;
116impl SubKind for Diagnostic {
117 type Notification = DiagnosticNotification;
118 const LABEL: &'static str = "diagnostic";
119 const SUBSCRIBE_METHOD: &'static str = "diagnosticSubscribe";
120 const NOTIFICATION_METHOD: &'static str = "diagnosticNotification";
121 fn subscribe_params(_program_id: &str) -> serde_json::Value {
122 serde_json::json!([serde_json::Value::Null, {}])
124 }
125 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
126 SubscriptionNotification::Diagnostic(notification)
127 }
128 fn slot_of(notification: &Self::Notification) -> u64 {
129 notification.context.slot
130 }
131}
132
133struct ActionResult;
134impl SubKind for ActionResult {
135 type Notification = ActionResultNotification;
136 const LABEL: &'static str = "action";
137 const SUBSCRIBE_METHOD: &'static str = "actionSubscribe";
138 const NOTIFICATION_METHOD: &'static str = "actionNotification";
139 fn subscribe_params(_program_id: &str) -> serde_json::Value {
140 serde_json::json!([serde_json::Value::Null, {}])
143 }
144 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
145 SubscriptionNotification::ActionResult(notification)
146 }
147 fn slot_of(notification: &Self::Notification) -> u64 {
148 notification.context.slot
149 }
150}
151
152pub fn spawn_transaction_subscription_manager(
153 rpc_endpoint: String,
154 program_ids: Vec<Address>,
155 cancel: CancellationToken,
156 coordinator: Option<Arc<ReconnectCoordinator>>,
157 diagnostics: Arc<SubscriptionDiagnostics>,
158) -> SubscriptionHandle {
159 spawn_subscription_manager::<Transaction>(
160 rpc_endpoint,
161 render(program_ids),
162 cancel,
163 coordinator,
164 diagnostics,
165 )
166}
167
168pub fn spawn_action_subscription_manager(
170 rpc_endpoint: String,
171 cancel: CancellationToken,
172 coordinator: Option<Arc<ReconnectCoordinator>>,
173 diagnostics: Arc<SubscriptionDiagnostics>,
174) -> SubscriptionHandle {
175 spawn_subscription_manager::<ActionResult>(
176 rpc_endpoint,
177 vec![String::new()],
178 cancel,
179 coordinator,
180 diagnostics,
181 )
182}
183
184pub fn spawn_diagnostic_subscription_manager(
185 rpc_endpoint: String,
186 cancel: CancellationToken,
187 coordinator: Option<Arc<ReconnectCoordinator>>,
188 diagnostics: Arc<SubscriptionDiagnostics>,
189) -> SubscriptionHandle {
190 spawn_subscription_manager::<Diagnostic>(
191 rpc_endpoint,
192 vec![String::new()],
193 cancel,
194 coordinator,
195 diagnostics,
196 )
197}
198
199pub fn spawn_account_diff_subscription_manager(
200 rpc_endpoint: String,
201 program_ids: Vec<Address>,
202 cancel: CancellationToken,
203 coordinator: Option<Arc<ReconnectCoordinator>>,
204 diagnostics: Arc<SubscriptionDiagnostics>,
205) -> SubscriptionHandle {
206 spawn_subscription_manager::<AccountDiff>(
207 rpc_endpoint,
208 render(program_ids),
209 cancel,
210 coordinator,
211 diagnostics,
212 )
213}
214
215fn render(program_ids: Vec<Address>) -> Vec<String> {
219 program_ids.iter().map(ToString::to_string).collect()
220}
221
222fn spawn_subscription_manager<K>(
223 rpc_endpoint: String,
224 program_ids: Vec<String>,
225 cancel: CancellationToken,
226 coordinator: Option<Arc<ReconnectCoordinator>>,
227 diagnostics: Arc<SubscriptionDiagnostics>,
228) -> SubscriptionHandle
229where
230 K: SubKind,
231{
232 let (notifications_tx, notifications_rx) = mpsc::channel(1024);
233 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
234 let task = Task::<K> {
235 rpc_endpoint,
236 program_ids,
237 notifications_tx,
238 status_tx,
239 cancel,
240 coordinator,
241 diagnostics,
242 _marker: PhantomData,
243 };
244 let join = tokio::spawn(task.run());
245 SubscriptionHandle {
246 status: status_rx,
247 notifications: notifications_rx,
248 join,
249 }
250}
251
252type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
253type Subs = HashSet<u64>;
254
255struct Task<K: SubKind> {
256 rpc_endpoint: String,
257 program_ids: Vec<String>,
258 notifications_tx: mpsc::Sender<SubscriptionNotification>,
259 status_tx: watch::Sender<ConnectionStatus>,
260 cancel: CancellationToken,
263 coordinator: Option<Arc<ReconnectCoordinator>>,
268 diagnostics: Arc<SubscriptionDiagnostics>,
269 _marker: PhantomData<fn() -> K>,
270}
271
272impl<K: SubKind> Task<K> {
273 async fn run(self) {
274 let mut budget = ReconnectBudget::new();
275 let mut replay_from_slot: Option<u64> = None;
279 let mut connected_before = false;
280
281 loop {
282 if self.cancel.is_cancelled() {
283 break;
284 }
285 publish(&self.status_tx, ConnectionStatus::Down);
286
287 let reconnect_slot = match &self.coordinator {
297 Some(coord) if budget.attempt() >= RECONNECT_UNGATED_ATTEMPTS => {
298 let parked_at = Instant::now();
299 let Some(slot) = coord.reconnect_slot(&self.cancel).await else {
300 break; };
302 budget.discount_parked(parked_at.elapsed());
304 Some(slot)
305 }
306 _ => None,
307 };
308
309 let connect_result = tokio::select! {
312 biased;
313 _ = self.cancel.cancelled() => None,
314 result = async {
315 let ws = connect_ws(&self.rpc_endpoint).await?;
316 subscribe::<K>(ws, &self.program_ids, replay_from_slot).await
317 } => Some(result),
318 };
319 let Some(connect_result) = connect_result else {
320 break;
321 };
322
323 let Subscribed { ws, subs, pending } = match connect_result {
324 Ok(v) => v,
325 Err(why) => {
326 drop(reconnect_slot);
327 if retry_or_fail::<K>(
328 "connect",
329 why,
330 &mut budget,
331 &self.cancel,
332 &self.status_tx,
333 )
334 .await
335 {
336 continue;
337 }
338 break;
339 }
340 };
341
342 if connected_before {
343 warn!(
346 kind = K::LABEL,
347 replay_from_slot = ?replay_from_slot,
348 "subscription reconnected, resuming from inclusive replay cursor"
349 );
350 self.diagnostics.record_reconnect();
351 }
352 connected_before = true;
353
354 let streaming = self.coordinator.as_ref().map(|coord| coord.enter());
360 drop(reconnect_slot);
361 publish(&self.status_tx, ConnectionStatus::Up);
362 let connected_at = Instant::now();
363
364 let exit = message_loop::<K>(
365 ws,
366 subs,
367 pending,
368 &self.notifications_tx,
369 &self.cancel,
370 &mut replay_from_slot,
371 )
372 .await;
373
374 drop(streaming);
375
376 match exit {
377 MessageLoopExit::Cancelled | MessageLoopExit::Completed => break,
378 MessageLoopExit::ConnectionLost(why) => {
379 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
380 budget.reset();
381 }
382 if retry_or_fail::<K>(
383 "connection lost",
384 why,
385 &mut budget,
386 &self.cancel,
387 &self.status_tx,
388 )
389 .await
390 {
391 continue;
392 }
393 break;
394 }
395 }
396 }
397 }
398}
399
400enum MessageLoopExit {
401 Cancelled,
402 ConnectionLost(String),
403 Completed,
406}
407
408async fn message_loop<K: SubKind>(
409 mut ws: Ws,
410 subs: Subs,
411 pending: Vec<Message>,
412 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
413 cancel: &CancellationToken,
414 replay_from_slot: &mut Option<u64>,
415) -> MessageLoopExit {
416 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
417 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
418 let mut last_inbound = Instant::now();
419 let mut completed: HashSet<u64> = HashSet::new();
422 let mut decompressor = match WsStreamDecompressor::new() {
428 Ok(decompressor) => decompressor,
429 Err(e) => return MessageLoopExit::ConnectionLost(format!("zstd decoder init: {e}")),
430 };
431
432 for msg in pending {
435 let outcome = process_data_frame::<K>(
436 msg,
437 &subs,
438 notifications_tx,
439 &mut completed,
440 replay_from_slot,
441 &mut decompressor,
442 )
443 .await;
444 if let Some(exit) = frame_outcome_to_exit(outcome) {
445 return exit;
446 }
447 }
448
449 loop {
450 tokio::select! {
451 biased;
452 _ = cancel.cancelled() => return MessageLoopExit::Cancelled,
453
454 _ = ping_timer.tick() => {
455 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
456 return MessageLoopExit::ConnectionLost(format!(
457 "no traffic for {:?}", last_inbound.elapsed()
458 ));
459 }
460 if let Err(e) = ws.send(Message::Ping(vec![])).await {
461 return MessageLoopExit::ConnectionLost(format!("ping send: {}", err_chain(&e)));
462 }
463 }
464
465 msg = ws.next() => {
466 last_inbound = Instant::now();
467 match msg {
468 Some(Ok(frame @ (Message::Text(_) | Message::Binary(_)))) => {
469 let outcome = process_data_frame::<K>(
470 frame,
471 &subs,
472 notifications_tx,
473 &mut completed,
474 replay_from_slot,
475 &mut decompressor,
476 )
477 .await;
478 if let Some(exit) = frame_outcome_to_exit(outcome) {
479 return exit;
480 }
481 }
482 Some(Ok(Message::Pong(_))) | Some(Ok(Message::Ping(_))) => {}
483 Some(Ok(Message::Close(frame))) => {
484 return MessageLoopExit::ConnectionLost(format!("remote close: {frame:?}"));
485 }
486 Some(Ok(Message::Frame(_))) => {}
487 Some(Err(e)) => return MessageLoopExit::ConnectionLost(format!("ws read: {}", err_chain(&e))),
488 None => return MessageLoopExit::ConnectionLost("ws stream ended".into()),
489 }
490 }
491 }
492 }
493}
494
495fn frame_outcome_to_exit(outcome: Result<TextOutcome, String>) -> Option<MessageLoopExit> {
497 match outcome {
498 Ok(TextOutcome::Continue) => None,
499 Ok(TextOutcome::AllComplete) => Some(MessageLoopExit::Completed),
500 Ok(TextOutcome::ChannelClosed) => Some(MessageLoopExit::Cancelled),
501 Err(why) => Some(MessageLoopExit::ConnectionLost(why)),
502 }
503}
504
505async fn process_data_frame<K: SubKind>(
510 msg: Message,
511 subs: &Subs,
512 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
513 completed: &mut HashSet<u64>,
514 replay_from_slot: &mut Option<u64>,
515 decompressor: &mut WsStreamDecompressor,
516) -> Result<TextOutcome, String> {
517 match msg {
518 Message::Text(t) => {
519 Ok(handle_text::<K>(&t, subs, notifications_tx, completed, replay_from_slot).await)
520 }
521 Message::Binary(b) => {
523 let decoded = decompressor
524 .decompress(&b)
525 .map_err(|e| format!("ws decompress: {e}"))?;
526 match std::str::from_utf8(&decoded) {
527 Ok(t) => {
528 Ok(
529 handle_text::<K>(t, subs, notifications_tx, completed, replay_from_slot)
530 .await,
531 )
532 }
533 Err(_) => Ok(TextOutcome::Continue),
534 }
535 }
536 _ => Ok(TextOutcome::Continue),
537 }
538}
539
540async fn retry_or_fail<K: SubKind>(
543 phase: &'static str,
544 reason: String,
545 budget: &mut ReconnectBudget,
546 cancel: &CancellationToken,
547 status_tx: &watch::Sender<ConnectionStatus>,
548) -> bool {
549 if let Some(delay) = budget.next_backoff() {
550 warn!(
551 kind = K::LABEL,
552 attempt = budget.attempt(),
553 reason = %reason,
554 ?delay,
555 "subscription {phase}, retrying",
556 );
557 cancellable_sleep(delay, cancel).await
558 } else {
559 publish(
560 status_tx,
561 ConnectionStatus::Failed(format!("{phase}: {reason}")),
562 );
563 false
564 }
565}
566
567fn publish(tx: &watch::Sender<ConnectionStatus>, status: ConnectionStatus) {
568 tx.send_if_modified(|current| {
569 if *current == status {
570 false
571 } else {
572 *current = status;
573 true
574 }
575 });
576}
577
578async fn connect_ws(rpc_endpoint: &str) -> Result<Ws, String> {
579 let ws_url = http_to_ws_url(rpc_endpoint).map_err(|e| err_chain(&e))?;
580 let request = ws_url
581 .into_client_request()
582 .map_err(|e| format!("build request: {}", err_chain(&e)))?;
583
584 let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
585 .await
586 .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
587 .map_err(|e| format!("connect: {}", err_chain(&e)))?;
588 Ok(connect.0)
589}
590
591struct Subscribed {
593 ws: Ws,
594 subs: Subs,
596 pending: Vec<Message>,
599}
600
601async fn subscribe<K: SubKind>(
602 mut ws: Ws,
603 program_ids: &[String],
604 replay_from_slot: Option<u64>,
605) -> Result<Subscribed, String> {
606 let mut subs = Subs::new();
607 let mut pending = Vec::new();
610 for (i, program_id) in program_ids.iter().enumerate() {
611 let id = (i + 1) as u64;
612 let mut params = K::subscribe_params(program_id);
613 SubscribeConfig {
620 replay_from_slot: replay_from_slot.map(|slot| slot as i64),
621 compression: Some(Compression::Zstd),
622 ..SubscribeConfig::default()
623 }
624 .apply_to(&mut params);
625 let req = serde_json::json!({
626 "jsonrpc": "2.0",
627 "id": id,
628 "method": K::SUBSCRIBE_METHOD,
629 "params": params,
630 });
631 ws.send(Message::Text(req.to_string()))
632 .await
633 .map_err(|e| format!("subscribe send: {}", err_chain(&e)))?;
634 subs.insert(read_sub_ack(&mut ws, id, &mut pending).await?);
635 }
636 debug!(
637 kind = K::LABEL,
638 count = subs.len(),
639 "subscriptions established"
640 );
641 Ok(Subscribed { ws, subs, pending })
642}
643
644#[derive(Deserialize)]
645struct SubAck {
646 id: u64,
647 result: Option<u64>,
648 #[serde(default)]
649 error: Option<serde_json::Value>,
650}
651
652async fn read_sub_ack(
658 ws: &mut Ws,
659 expected_id: u64,
660 pending: &mut Vec<Message>,
661) -> Result<u64, String> {
662 let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
663 loop {
664 let msg = tokio::time::timeout_at(deadline, ws.next())
665 .await
666 .map_err(|_| format!("subscribe ack timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;
667
668 let Some(msg) = msg else {
669 return Err("ws ended during subscribe".into());
670 };
671 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
672
673 if let Message::Text(t) = &msg
675 && let Ok(ack) = serde_json::from_str::<SubAck>(t)
676 {
677 if ack.id != expected_id {
678 continue;
679 }
680 if let Some(err) = ack.error {
681 return Err(format!("subscribe rejected: {err}"));
682 }
683 return ack
684 .result
685 .ok_or_else(|| "subscribe ack missing result".to_string());
686 }
687 if matches!(msg, Message::Text(_) | Message::Binary(_)) {
688 pending.push(msg);
689 }
690 }
691}
692
693enum TextOutcome {
695 Continue,
697 AllComplete,
699 ChannelClosed,
701}
702
703async fn handle_text<K: SubKind>(
707 text: &str,
708 subs: &Subs,
709 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
710 completed: &mut HashSet<u64>,
711 replay_from_slot: &mut Option<u64>,
712) -> TextOutcome {
713 if let Some(n) = parse_notification::<K>(text, subs) {
716 let slot = K::slot_of(&n);
725 if notifications_tx
726 .send(K::into_notification(n))
727 .await
728 .is_err()
729 {
730 return TextOutcome::ChannelClosed;
731 }
732 *replay_from_slot = Some(replay_from_slot.map_or(slot, |prev| prev.max(slot)));
733 return TextOutcome::Continue;
734 }
735
736 if let Some(sub_id) = parse_completion(text)
738 && subs.contains(&sub_id)
739 {
740 completed.insert(sub_id);
741 if subs.iter().all(|id| completed.contains(id)) {
742 return TextOutcome::AllComplete;
743 }
744 }
745 TextOutcome::Continue
746}
747
748fn parse_completion(text: &str) -> Option<u64> {
751 #[derive(Deserialize)]
752 struct Msg {
753 method: String,
754 params: Params,
755 }
756 #[derive(Deserialize)]
757 struct Params {
758 subscription: u64,
759 }
760
761 let msg: Msg = serde_json::from_str(text).ok()?;
762 (msg.method == "subscriptionComplete").then_some(msg.params.subscription)
763}
764
765fn parse_notification<K: SubKind>(text: &str, subs: &Subs) -> Option<K::Notification> {
766 #[derive(Deserialize)]
767 #[serde(bound = "T: DeserializeOwned")]
768 struct Msg<T> {
769 method: String,
770 params: Params<T>,
771 }
772 #[derive(Deserialize)]
773 #[serde(bound = "T: DeserializeOwned")]
774 struct Params<T> {
775 subscription: u64,
776 result: T,
777 }
778
779 let msg: Msg<K::Notification> = serde_json::from_str(text).ok()?;
780 if msg.method != K::NOTIFICATION_METHOD {
781 return None;
782 }
783 if !subs.contains(&msg.params.subscription) {
784 return None;
785 }
786 Some(msg.params.result)
787}
788
789#[cfg(test)]
790mod tests {
791 use super::parse_completion;
792
793 #[test]
794 fn parse_completion_extracts_subscription_id() {
795 let text =
796 r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7}}"#;
797 assert_eq!(parse_completion(text), Some(7));
798 }
799
800 #[test]
801 fn parse_completion_tolerates_unknown_fields() {
802 let text = r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7,"future":"field"},"extra":true}"#;
803 assert_eq!(parse_completion(text), Some(7));
804 }
805
806 #[test]
807 fn parse_completion_ignores_other_messages() {
808 let notification = r#"{"jsonrpc":"2.0","method":"transactionNotification","params":{"subscription":7,"result":{}}}"#;
809 assert_eq!(parse_completion(notification), None);
810 assert_eq!(parse_completion("not json"), None);
811 }
812}