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},
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}
62
63trait SubKind: Send + Sync + 'static {
65 type Notification: DeserializeOwned + Send + 'static;
66 const LABEL: &'static str;
67 const SUBSCRIBE_METHOD: &'static str;
68 const NOTIFICATION_METHOD: &'static str;
69 fn subscribe_params(program_id: &str) -> serde_json::Value;
70 fn into_notification(notification: Self::Notification) -> SubscriptionNotification;
71 fn slot_of(notification: &Self::Notification) -> u64;
75}
76
77struct AccountDiff;
78impl SubKind for AccountDiff {
79 type Notification = AccountDiffNotification;
80 const LABEL: &'static str = "account-diff";
81 const SUBSCRIBE_METHOD: &'static str = "accountDiffSubscribe";
82 const NOTIFICATION_METHOD: &'static str = "accountDiffNotification";
83 fn subscribe_params(program_id: &str) -> serde_json::Value {
84 serde_json::json!([program_id, {"address_type": "program"}])
85 }
86 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
87 SubscriptionNotification::AccountDiff(notification)
88 }
89 fn slot_of(notification: &Self::Notification) -> u64 {
90 notification.context.slot
91 }
92}
93
94struct Transaction;
95impl SubKind for Transaction {
96 type Notification = EncodedConfirmedTransactionWithStatusMeta;
100 const LABEL: &'static str = "transaction";
101 const SUBSCRIBE_METHOD: &'static str = "transactionSubscribe";
102 const NOTIFICATION_METHOD: &'static str = "transactionNotification";
103 fn subscribe_params(program_id: &str) -> serde_json::Value {
104 serde_json::json!([{"mentions": [program_id]}, {"commitment": "confirmed"}])
105 }
106 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
107 SubscriptionNotification::Transaction(Box::new(notification))
108 }
109 fn slot_of(notification: &Self::Notification) -> u64 {
110 notification.slot
111 }
112}
113
114struct ActionResult;
115impl SubKind for ActionResult {
116 type Notification = ActionResultNotification;
117 const LABEL: &'static str = "action";
118 const SUBSCRIBE_METHOD: &'static str = "actionSubscribe";
119 const NOTIFICATION_METHOD: &'static str = "actionNotification";
120 fn subscribe_params(_program_id: &str) -> serde_json::Value {
121 serde_json::json!([serde_json::Value::Null, {}])
124 }
125 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
126 SubscriptionNotification::ActionResult(notification)
127 }
128 fn slot_of(notification: &Self::Notification) -> u64 {
129 notification.context.slot
130 }
131}
132
133pub fn spawn_transaction_subscription_manager(
134 rpc_endpoint: String,
135 program_ids: Vec<Address>,
136 cancel: CancellationToken,
137 coordinator: Option<Arc<ReconnectCoordinator>>,
138 diagnostics: Arc<SubscriptionDiagnostics>,
139) -> SubscriptionHandle {
140 spawn_subscription_manager::<Transaction>(
141 rpc_endpoint,
142 render(program_ids),
143 cancel,
144 coordinator,
145 diagnostics,
146 )
147}
148
149pub fn spawn_action_subscription_manager(
151 rpc_endpoint: String,
152 cancel: CancellationToken,
153 coordinator: Option<Arc<ReconnectCoordinator>>,
154 diagnostics: Arc<SubscriptionDiagnostics>,
155) -> SubscriptionHandle {
156 spawn_subscription_manager::<ActionResult>(
157 rpc_endpoint,
158 vec![String::new()],
159 cancel,
160 coordinator,
161 diagnostics,
162 )
163}
164
165pub fn spawn_account_diff_subscription_manager(
166 rpc_endpoint: String,
167 program_ids: Vec<Address>,
168 cancel: CancellationToken,
169 coordinator: Option<Arc<ReconnectCoordinator>>,
170 diagnostics: Arc<SubscriptionDiagnostics>,
171) -> SubscriptionHandle {
172 spawn_subscription_manager::<AccountDiff>(
173 rpc_endpoint,
174 render(program_ids),
175 cancel,
176 coordinator,
177 diagnostics,
178 )
179}
180
181fn render(program_ids: Vec<Address>) -> Vec<String> {
185 program_ids.iter().map(ToString::to_string).collect()
186}
187
188fn spawn_subscription_manager<K>(
189 rpc_endpoint: String,
190 program_ids: Vec<String>,
191 cancel: CancellationToken,
192 coordinator: Option<Arc<ReconnectCoordinator>>,
193 diagnostics: Arc<SubscriptionDiagnostics>,
194) -> SubscriptionHandle
195where
196 K: SubKind,
197{
198 let (notifications_tx, notifications_rx) = mpsc::channel(1024);
199 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
200 let task = Task::<K> {
201 rpc_endpoint,
202 program_ids,
203 notifications_tx,
204 status_tx,
205 cancel,
206 coordinator,
207 diagnostics,
208 _marker: PhantomData,
209 };
210 let join = tokio::spawn(task.run());
211 SubscriptionHandle {
212 status: status_rx,
213 notifications: notifications_rx,
214 join,
215 }
216}
217
218type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
219type Subs = HashSet<u64>;
220
221struct Task<K: SubKind> {
222 rpc_endpoint: String,
223 program_ids: Vec<String>,
224 notifications_tx: mpsc::Sender<SubscriptionNotification>,
225 status_tx: watch::Sender<ConnectionStatus>,
226 cancel: CancellationToken,
229 coordinator: Option<Arc<ReconnectCoordinator>>,
234 diagnostics: Arc<SubscriptionDiagnostics>,
235 _marker: PhantomData<fn() -> K>,
236}
237
238impl<K: SubKind> Task<K> {
239 async fn run(self) {
240 let mut budget = ReconnectBudget::new();
241 let mut replay_from_slot: Option<u64> = None;
245 let mut connected_before = false;
246
247 loop {
248 if self.cancel.is_cancelled() {
249 break;
250 }
251 publish(&self.status_tx, ConnectionStatus::Down);
252
253 let reconnect_slot = match &self.coordinator {
263 Some(coord) if budget.attempt() >= RECONNECT_UNGATED_ATTEMPTS => {
264 let parked_at = Instant::now();
265 let Some(slot) = coord.reconnect_slot(&self.cancel).await else {
266 break; };
268 budget.discount_parked(parked_at.elapsed());
270 Some(slot)
271 }
272 _ => None,
273 };
274
275 let connect_result = tokio::select! {
278 biased;
279 _ = self.cancel.cancelled() => None,
280 result = async {
281 let ws = connect_ws(&self.rpc_endpoint).await?;
282 subscribe::<K>(ws, &self.program_ids, replay_from_slot).await
283 } => Some(result),
284 };
285 let Some(connect_result) = connect_result else {
286 break;
287 };
288
289 let Subscribed { ws, subs, pending } = match connect_result {
290 Ok(v) => v,
291 Err(why) => {
292 drop(reconnect_slot);
293 if retry_or_fail::<K>(
294 "connect",
295 why,
296 &mut budget,
297 &self.cancel,
298 &self.status_tx,
299 )
300 .await
301 {
302 continue;
303 }
304 break;
305 }
306 };
307
308 if connected_before {
309 warn!(
312 kind = K::LABEL,
313 replay_from_slot = ?replay_from_slot,
314 "subscription reconnected, resuming from inclusive replay cursor"
315 );
316 self.diagnostics.record_reconnect();
317 }
318 connected_before = true;
319
320 let streaming = self.coordinator.as_ref().map(|coord| coord.enter());
326 drop(reconnect_slot);
327 publish(&self.status_tx, ConnectionStatus::Up);
328 let connected_at = Instant::now();
329
330 let exit = message_loop::<K>(
331 ws,
332 subs,
333 pending,
334 &self.notifications_tx,
335 &self.cancel,
336 &mut replay_from_slot,
337 )
338 .await;
339
340 drop(streaming);
341
342 match exit {
343 MessageLoopExit::Cancelled | MessageLoopExit::Completed => break,
344 MessageLoopExit::ConnectionLost(why) => {
345 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
346 budget.reset();
347 }
348 if retry_or_fail::<K>(
349 "connection lost",
350 why,
351 &mut budget,
352 &self.cancel,
353 &self.status_tx,
354 )
355 .await
356 {
357 continue;
358 }
359 break;
360 }
361 }
362 }
363 }
364}
365
366enum MessageLoopExit {
367 Cancelled,
368 ConnectionLost(String),
369 Completed,
372}
373
374async fn message_loop<K: SubKind>(
375 mut ws: Ws,
376 subs: Subs,
377 pending: Vec<Message>,
378 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
379 cancel: &CancellationToken,
380 replay_from_slot: &mut Option<u64>,
381) -> MessageLoopExit {
382 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
383 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
384 let mut last_inbound = Instant::now();
385 let mut completed: HashSet<u64> = HashSet::new();
388 let mut decompressor = match WsStreamDecompressor::new() {
394 Ok(decompressor) => decompressor,
395 Err(e) => return MessageLoopExit::ConnectionLost(format!("zstd decoder init: {e}")),
396 };
397
398 for msg in pending {
401 let outcome = process_data_frame::<K>(
402 msg,
403 &subs,
404 notifications_tx,
405 &mut completed,
406 replay_from_slot,
407 &mut decompressor,
408 )
409 .await;
410 if let Some(exit) = frame_outcome_to_exit(outcome) {
411 return exit;
412 }
413 }
414
415 loop {
416 tokio::select! {
417 biased;
418 _ = cancel.cancelled() => return MessageLoopExit::Cancelled,
419
420 _ = ping_timer.tick() => {
421 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
422 return MessageLoopExit::ConnectionLost(format!(
423 "no traffic for {:?}", last_inbound.elapsed()
424 ));
425 }
426 if let Err(e) = ws.send(Message::Ping(vec![])).await {
427 return MessageLoopExit::ConnectionLost(format!("ping send: {}", err_chain(&e)));
428 }
429 }
430
431 msg = ws.next() => {
432 last_inbound = Instant::now();
433 match msg {
434 Some(Ok(frame @ (Message::Text(_) | Message::Binary(_)))) => {
435 let outcome = process_data_frame::<K>(
436 frame,
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 Some(Ok(Message::Pong(_))) | Some(Ok(Message::Ping(_))) => {}
449 Some(Ok(Message::Close(frame))) => {
450 return MessageLoopExit::ConnectionLost(format!("remote close: {frame:?}"));
451 }
452 Some(Ok(Message::Frame(_))) => {}
453 Some(Err(e)) => return MessageLoopExit::ConnectionLost(format!("ws read: {}", err_chain(&e))),
454 None => return MessageLoopExit::ConnectionLost("ws stream ended".into()),
455 }
456 }
457 }
458 }
459}
460
461fn frame_outcome_to_exit(outcome: Result<TextOutcome, String>) -> Option<MessageLoopExit> {
463 match outcome {
464 Ok(TextOutcome::Continue) => None,
465 Ok(TextOutcome::AllComplete) => Some(MessageLoopExit::Completed),
466 Ok(TextOutcome::ChannelClosed) => Some(MessageLoopExit::Cancelled),
467 Err(why) => Some(MessageLoopExit::ConnectionLost(why)),
468 }
469}
470
471async fn process_data_frame<K: SubKind>(
476 msg: Message,
477 subs: &Subs,
478 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
479 completed: &mut HashSet<u64>,
480 replay_from_slot: &mut Option<u64>,
481 decompressor: &mut WsStreamDecompressor,
482) -> Result<TextOutcome, String> {
483 match msg {
484 Message::Text(t) => {
485 Ok(handle_text::<K>(&t, subs, notifications_tx, completed, replay_from_slot).await)
486 }
487 Message::Binary(b) => {
489 let decoded = decompressor
490 .decompress(&b)
491 .map_err(|e| format!("ws decompress: {e}"))?;
492 match std::str::from_utf8(&decoded) {
493 Ok(t) => {
494 Ok(
495 handle_text::<K>(t, subs, notifications_tx, completed, replay_from_slot)
496 .await,
497 )
498 }
499 Err(_) => Ok(TextOutcome::Continue),
500 }
501 }
502 _ => Ok(TextOutcome::Continue),
503 }
504}
505
506async fn retry_or_fail<K: SubKind>(
509 phase: &'static str,
510 reason: String,
511 budget: &mut ReconnectBudget,
512 cancel: &CancellationToken,
513 status_tx: &watch::Sender<ConnectionStatus>,
514) -> bool {
515 if let Some(delay) = budget.next_backoff() {
516 warn!(
517 kind = K::LABEL,
518 attempt = budget.attempt(),
519 reason = %reason,
520 ?delay,
521 "subscription {phase}, retrying",
522 );
523 cancellable_sleep(delay, cancel).await
524 } else {
525 publish(
526 status_tx,
527 ConnectionStatus::Failed(format!("{phase}: {reason}")),
528 );
529 false
530 }
531}
532
533fn publish(tx: &watch::Sender<ConnectionStatus>, status: ConnectionStatus) {
534 tx.send_if_modified(|current| {
535 if *current == status {
536 false
537 } else {
538 *current = status;
539 true
540 }
541 });
542}
543
544async fn connect_ws(rpc_endpoint: &str) -> Result<Ws, String> {
545 let ws_url = http_to_ws_url(rpc_endpoint).map_err(|e| err_chain(&e))?;
546 let request = ws_url
547 .into_client_request()
548 .map_err(|e| format!("build request: {}", err_chain(&e)))?;
549
550 let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
551 .await
552 .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
553 .map_err(|e| format!("connect: {}", err_chain(&e)))?;
554 Ok(connect.0)
555}
556
557struct Subscribed {
559 ws: Ws,
560 subs: Subs,
562 pending: Vec<Message>,
565}
566
567async fn subscribe<K: SubKind>(
568 mut ws: Ws,
569 program_ids: &[String],
570 replay_from_slot: Option<u64>,
571) -> Result<Subscribed, String> {
572 let mut subs = Subs::new();
573 let mut pending = Vec::new();
576 for (i, program_id) in program_ids.iter().enumerate() {
577 let id = (i + 1) as u64;
578 let mut params = K::subscribe_params(program_id);
579 SubscribeConfig {
586 replay_from_slot: replay_from_slot.map(|slot| slot as i64),
587 compression: Some(Compression::Zstd),
588 ..SubscribeConfig::default()
589 }
590 .apply_to(&mut params);
591 let req = serde_json::json!({
592 "jsonrpc": "2.0",
593 "id": id,
594 "method": K::SUBSCRIBE_METHOD,
595 "params": params,
596 });
597 ws.send(Message::Text(req.to_string()))
598 .await
599 .map_err(|e| format!("subscribe send: {}", err_chain(&e)))?;
600 subs.insert(read_sub_ack(&mut ws, id, &mut pending).await?);
601 }
602 debug!(
603 kind = K::LABEL,
604 count = subs.len(),
605 "subscriptions established"
606 );
607 Ok(Subscribed { ws, subs, pending })
608}
609
610#[derive(Deserialize)]
611struct SubAck {
612 id: u64,
613 result: Option<u64>,
614 #[serde(default)]
615 error: Option<serde_json::Value>,
616}
617
618async fn read_sub_ack(
624 ws: &mut Ws,
625 expected_id: u64,
626 pending: &mut Vec<Message>,
627) -> Result<u64, String> {
628 let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
629 loop {
630 let msg = tokio::time::timeout_at(deadline, ws.next())
631 .await
632 .map_err(|_| format!("subscribe ack timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;
633
634 let Some(msg) = msg else {
635 return Err("ws ended during subscribe".into());
636 };
637 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
638
639 if let Message::Text(t) = &msg
641 && let Ok(ack) = serde_json::from_str::<SubAck>(t)
642 {
643 if ack.id != expected_id {
644 continue;
645 }
646 if let Some(err) = ack.error {
647 return Err(format!("subscribe rejected: {err}"));
648 }
649 return ack
650 .result
651 .ok_or_else(|| "subscribe ack missing result".to_string());
652 }
653 if matches!(msg, Message::Text(_) | Message::Binary(_)) {
654 pending.push(msg);
655 }
656 }
657}
658
659enum TextOutcome {
661 Continue,
663 AllComplete,
665 ChannelClosed,
667}
668
669async fn handle_text<K: SubKind>(
673 text: &str,
674 subs: &Subs,
675 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
676 completed: &mut HashSet<u64>,
677 replay_from_slot: &mut Option<u64>,
678) -> TextOutcome {
679 if let Some(n) = parse_notification::<K>(text, subs) {
682 let slot = K::slot_of(&n);
691 if notifications_tx
692 .send(K::into_notification(n))
693 .await
694 .is_err()
695 {
696 return TextOutcome::ChannelClosed;
697 }
698 *replay_from_slot = Some(replay_from_slot.map_or(slot, |prev| prev.max(slot)));
699 return TextOutcome::Continue;
700 }
701
702 if let Some(sub_id) = parse_completion(text)
704 && subs.contains(&sub_id)
705 {
706 completed.insert(sub_id);
707 if subs.iter().all(|id| completed.contains(id)) {
708 return TextOutcome::AllComplete;
709 }
710 }
711 TextOutcome::Continue
712}
713
714fn parse_completion(text: &str) -> Option<u64> {
717 #[derive(Deserialize)]
718 struct Msg {
719 method: String,
720 params: Params,
721 }
722 #[derive(Deserialize)]
723 struct Params {
724 subscription: u64,
725 }
726
727 let msg: Msg = serde_json::from_str(text).ok()?;
728 (msg.method == "subscriptionComplete").then_some(msg.params.subscription)
729}
730
731fn parse_notification<K: SubKind>(text: &str, subs: &Subs) -> Option<K::Notification> {
732 #[derive(Deserialize)]
733 #[serde(bound = "T: DeserializeOwned")]
734 struct Msg<T> {
735 method: String,
736 params: Params<T>,
737 }
738 #[derive(Deserialize)]
739 #[serde(bound = "T: DeserializeOwned")]
740 struct Params<T> {
741 subscription: u64,
742 result: T,
743 }
744
745 let msg: Msg<K::Notification> = serde_json::from_str(text).ok()?;
746 if msg.method != K::NOTIFICATION_METHOD {
747 return None;
748 }
749 if !subs.contains(&msg.params.subscription) {
750 return None;
751 }
752 Some(msg.params.result)
753}
754
755#[cfg(test)]
756mod tests {
757 use super::parse_completion;
758
759 #[test]
760 fn parse_completion_extracts_subscription_id() {
761 let text =
762 r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7}}"#;
763 assert_eq!(parse_completion(text), Some(7));
764 }
765
766 #[test]
767 fn parse_completion_tolerates_unknown_fields() {
768 let text = r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7,"future":"field"},"extra":true}"#;
769 assert_eq!(parse_completion(text), Some(7));
770 }
771
772 #[test]
773 fn parse_completion_ignores_other_messages() {
774 let notification = r#"{"jsonrpc":"2.0","method":"transactionNotification","params":{"subscription":7,"result":{}}}"#;
775 assert_eq!(parse_completion(notification), None);
776 assert_eq!(parse_completion("not json"), None);
777 }
778}