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,
33 tungstenite::{Message, client::IntoClientRequest},
34};
35use tokio_util::sync::CancellationToken;
36use tracing::{debug, warn};
37
38use super::{
39 CONNECT_TIMEOUT, ConnectionFailure, ConnectionStatus, HANDSHAKE_RESPONSE_TIMEOUT,
40 KEEPALIVE_INTERVAL, KEEPALIVE_MISS_DEADLINE, RECONNECT_UNGATED_ATTEMPTS,
41 RECONNECT_UPTIME_RESET, ReconnectBudget, ReconnectCoordinator, SubscriptionDiagnostics,
42 cancellable_sleep,
43};
44use crate::{
45 endpoint::{ControlConnectError, connect_session_socket},
46 error::err_chain,
47 subscriptions::{
48 AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
49 ReplacementNotification,
50 },
51 urls::http_to_ws_url,
52};
53
54pub struct SubscriptionHandle {
57 pub status: watch::Receiver<ConnectionStatus>,
59 pub notifications: mpsc::Receiver<SubscriptionNotification>,
62 pub join: JoinHandle<()>,
64}
65
66#[derive(Debug)]
69pub enum SubscriptionNotification {
70 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
72 AccountDiff(AccountDiffNotification),
74 ActionResult(ActionResultNotification),
76 Diagnostic(DiagnosticNotification),
78 Replacement(Box<ReplacementNotification>),
82}
83
84trait SubKind: Send + Sync + 'static {
86 type Notification: DeserializeOwned + Send + 'static;
87 const LABEL: &'static str;
88 const SUBSCRIBE_METHOD: &'static str;
89 const NOTIFICATION_METHOD: &'static str;
90 fn subscribe_params(program_id: &str) -> serde_json::Value;
91 fn into_notification(notification: Self::Notification) -> SubscriptionNotification;
92 fn slot_of(notification: &Self::Notification) -> u64;
96}
97
98struct AccountDiff;
99impl SubKind for AccountDiff {
100 type Notification = AccountDiffNotification;
101 const LABEL: &'static str = "account-diff";
102 const SUBSCRIBE_METHOD: &'static str = "accountDiffSubscribe";
103 const NOTIFICATION_METHOD: &'static str = "accountDiffNotification";
104 fn subscribe_params(program_id: &str) -> serde_json::Value {
105 serde_json::json!([program_id, {"address_type": "program"}])
106 }
107 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
108 SubscriptionNotification::AccountDiff(notification)
109 }
110 fn slot_of(notification: &Self::Notification) -> u64 {
111 notification.context.slot
112 }
113}
114
115struct Transaction;
116impl SubKind for Transaction {
117 type Notification = EncodedConfirmedTransactionWithStatusMeta;
121 const LABEL: &'static str = "transaction";
122 const SUBSCRIBE_METHOD: &'static str = "transactionSubscribe";
123 const NOTIFICATION_METHOD: &'static str = "transactionNotification";
124 fn subscribe_params(program_id: &str) -> serde_json::Value {
125 serde_json::json!([{"mentions": [program_id]}, {"commitment": "confirmed"}])
126 }
127 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
128 SubscriptionNotification::Transaction(Box::new(notification))
129 }
130 fn slot_of(notification: &Self::Notification) -> u64 {
131 notification.slot
132 }
133}
134
135struct Diagnostic;
136impl SubKind for Diagnostic {
137 type Notification = DiagnosticNotification;
138 const LABEL: &'static str = "diagnostic";
139 const SUBSCRIBE_METHOD: &'static str = "diagnosticSubscribe";
140 const NOTIFICATION_METHOD: &'static str = "diagnosticNotification";
141 fn subscribe_params(_program_id: &str) -> serde_json::Value {
142 serde_json::json!([serde_json::Value::Null, {}])
144 }
145 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
146 SubscriptionNotification::Diagnostic(notification)
147 }
148 fn slot_of(notification: &Self::Notification) -> u64 {
149 notification.context.slot
150 }
151}
152
153struct Replacement;
154impl SubKind for Replacement {
155 type Notification = ReplacementNotification;
156 const LABEL: &'static str = "replacement";
157 const SUBSCRIBE_METHOD: &'static str = "replacementSubscribe";
158 const NOTIFICATION_METHOD: &'static str = "replacementNotification";
159 fn subscribe_params(_program_id: &str) -> serde_json::Value {
160 serde_json::json!([serde_json::Value::Null, {}])
162 }
163 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
164 SubscriptionNotification::Replacement(Box::new(notification))
165 }
166 fn slot_of(notification: &Self::Notification) -> u64 {
167 notification.core().slot
170 }
171}
172
173struct ActionResult;
174impl SubKind for ActionResult {
175 type Notification = ActionResultNotification;
176 const LABEL: &'static str = "action";
177 const SUBSCRIBE_METHOD: &'static str = "actionSubscribe";
178 const NOTIFICATION_METHOD: &'static str = "actionNotification";
179 fn subscribe_params(_program_id: &str) -> serde_json::Value {
180 serde_json::json!([serde_json::Value::Null, {}])
183 }
184 fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
185 SubscriptionNotification::ActionResult(notification)
186 }
187 fn slot_of(notification: &Self::Notification) -> u64 {
188 notification.context.slot
189 }
190}
191
192#[doc(hidden)]
193#[expect(clippy::needless_pass_by_value, reason = "public API")]
194pub fn spawn_transaction_subscription_manager(
195 rpc_endpoint: String,
196 program_ids: Vec<Address>,
197 cancel: CancellationToken,
198 coordinator: Option<Arc<ReconnectCoordinator>>,
199 diagnostics: Arc<SubscriptionDiagnostics>,
200) -> SubscriptionHandle {
201 spawn_subscription_manager::<Transaction>(
202 rpc_endpoint,
203 render(&program_ids),
204 cancel,
205 coordinator,
206 diagnostics,
207 )
208}
209
210#[doc(hidden)]
212pub fn spawn_action_subscription_manager(
213 rpc_endpoint: String,
214 cancel: CancellationToken,
215 coordinator: Option<Arc<ReconnectCoordinator>>,
216 diagnostics: Arc<SubscriptionDiagnostics>,
217) -> SubscriptionHandle {
218 spawn_subscription_manager::<ActionResult>(
219 rpc_endpoint,
220 vec![String::new()],
221 cancel,
222 coordinator,
223 diagnostics,
224 )
225}
226
227#[doc(hidden)]
229pub fn spawn_replacement_subscription_manager(
230 rpc_endpoint: String,
231 cancel: CancellationToken,
232 coordinator: Option<Arc<ReconnectCoordinator>>,
233 diagnostics: Arc<SubscriptionDiagnostics>,
234) -> SubscriptionHandle {
235 spawn_subscription_manager::<Replacement>(
236 rpc_endpoint,
237 vec![String::new()],
238 cancel,
239 coordinator,
240 diagnostics,
241 )
242}
243
244#[doc(hidden)]
245pub fn spawn_diagnostic_subscription_manager(
246 rpc_endpoint: String,
247 cancel: CancellationToken,
248 coordinator: Option<Arc<ReconnectCoordinator>>,
249 diagnostics: Arc<SubscriptionDiagnostics>,
250) -> SubscriptionHandle {
251 spawn_subscription_manager::<Diagnostic>(
252 rpc_endpoint,
253 vec![String::new()],
254 cancel,
255 coordinator,
256 diagnostics,
257 )
258}
259
260#[doc(hidden)]
261#[expect(clippy::needless_pass_by_value, reason = "public API")]
262pub fn spawn_account_diff_subscription_manager(
263 rpc_endpoint: String,
264 program_ids: Vec<Address>,
265 cancel: CancellationToken,
266 coordinator: Option<Arc<ReconnectCoordinator>>,
267 diagnostics: Arc<SubscriptionDiagnostics>,
268) -> SubscriptionHandle {
269 spawn_subscription_manager::<AccountDiff>(
270 rpc_endpoint,
271 render(&program_ids),
272 cancel,
273 coordinator,
274 diagnostics,
275 )
276}
277
278fn render(program_ids: &[Address]) -> Vec<String> {
282 program_ids.iter().map(ToString::to_string).collect()
283}
284
285fn spawn_subscription_manager<K>(
286 rpc_endpoint: String,
287 program_ids: Vec<String>,
288 cancel: CancellationToken,
289 coordinator: Option<Arc<ReconnectCoordinator>>,
290 diagnostics: Arc<SubscriptionDiagnostics>,
291) -> SubscriptionHandle
292where
293 K: SubKind,
294{
295 let (notifications_tx, notifications_rx) = mpsc::channel(1024);
296 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
297 let task = Task::<K> {
298 rpc_endpoint,
299 program_ids,
300 notifications_tx,
301 status_tx,
302 cancel,
303 coordinator,
304 diagnostics,
305 _marker: PhantomData,
306 };
307 let join = tokio::spawn(task.run());
308 SubscriptionHandle {
309 status: status_rx,
310 notifications: notifications_rx,
311 join,
312 }
313}
314
315type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
316type Subs = HashSet<u64>;
317
318struct Task<K: SubKind> {
319 rpc_endpoint: String,
320 program_ids: Vec<String>,
321 notifications_tx: mpsc::Sender<SubscriptionNotification>,
322 status_tx: watch::Sender<ConnectionStatus>,
323 cancel: CancellationToken,
326 coordinator: Option<Arc<ReconnectCoordinator>>,
331 diagnostics: Arc<SubscriptionDiagnostics>,
332 _marker: PhantomData<fn() -> K>,
333}
334
335impl<K: SubKind> Task<K> {
336 async fn run(self) {
337 let mut budget = ReconnectBudget::new();
338 let mut replay_from_slot: Option<u64> = None;
342 let mut connected_before = false;
343
344 loop {
345 if self.cancel.is_cancelled() {
346 break;
347 }
348 publish(&self.status_tx, ConnectionStatus::Down);
349
350 let reconnect_slot = match &self.coordinator {
360 Some(coord) if budget.attempt() >= RECONNECT_UNGATED_ATTEMPTS => {
361 let parked_at = Instant::now();
362 let Some(slot) = coord.reconnect_slot(&self.cancel).await else {
363 break; };
365 budget.discount_parked(parked_at.elapsed());
367 Some(slot)
368 }
369 _ => None,
370 };
371
372 let connect_result = tokio::select! {
375 biased;
376 () = self.cancel.cancelled() => None,
377 result = async {
378 let ws = connect_ws(&self.rpc_endpoint).await?;
379 subscribe::<K>(ws, &self.program_ids, replay_from_slot)
380 .await
381 .map_err(ControlConnectError::Failed)
382 } => Some(result),
383 };
384 let Some(connect_result) = connect_result else {
385 break;
386 };
387
388 let Subscribed { ws, subs, pending } = match connect_result {
389 Ok(v) => v,
390 Err(ControlConnectError::TokenRejected) => {
391 publish(
392 &self.status_tx,
393 ConnectionStatus::Failed(ConnectionFailure::TokenRejected),
394 );
395 break;
396 }
397 Err(ControlConnectError::Request(why) | ControlConnectError::Failed(why)) => {
398 drop(reconnect_slot);
399 if retry_or_fail::<K>(
400 "connect",
401 why,
402 &mut budget,
403 &self.cancel,
404 &self.status_tx,
405 )
406 .await
407 {
408 continue;
409 }
410 break;
411 }
412 };
413
414 if connected_before {
415 warn!(
418 kind = K::LABEL,
419 replay_from_slot = ?replay_from_slot,
420 "subscription reconnected, resuming from inclusive replay cursor"
421 );
422 self.diagnostics.record_reconnect();
423 }
424 connected_before = true;
425
426 let streaming = self.coordinator.as_ref().map(|coord| coord.enter());
432 drop(reconnect_slot);
433 publish(&self.status_tx, ConnectionStatus::Up);
434 let connected_at = Instant::now();
435
436 let exit = message_loop::<K>(
437 ws,
438 subs,
439 pending,
440 &self.notifications_tx,
441 &self.cancel,
442 &mut replay_from_slot,
443 )
444 .await;
445
446 drop(streaming);
447
448 match exit {
449 MessageLoopExit::Cancelled | MessageLoopExit::Completed => break,
450 MessageLoopExit::ConnectionLost(why) => {
451 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
452 budget.reset();
453 }
454 if retry_or_fail::<K>(
455 "connection lost",
456 why,
457 &mut budget,
458 &self.cancel,
459 &self.status_tx,
460 )
461 .await
462 {
463 continue;
464 }
465 break;
466 }
467 }
468 }
469 }
470}
471
472enum MessageLoopExit {
473 Cancelled,
474 ConnectionLost(String),
475 Completed,
478}
479
480async fn message_loop<K: SubKind>(
481 mut ws: Ws,
482 subs: Subs,
483 pending: Vec<Message>,
484 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
485 cancel: &CancellationToken,
486 replay_from_slot: &mut Option<u64>,
487) -> MessageLoopExit {
488 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
489 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
490 let mut last_inbound = Instant::now();
491 let mut completed: HashSet<u64> = HashSet::new();
494 let mut decompressor = match WsStreamDecompressor::new() {
500 Ok(decompressor) => decompressor,
501 Err(e) => return MessageLoopExit::ConnectionLost(format!("zstd decoder init: {e}")),
502 };
503
504 for msg in pending {
507 let outcome = process_data_frame::<K>(
508 msg,
509 &subs,
510 notifications_tx,
511 &mut completed,
512 replay_from_slot,
513 &mut decompressor,
514 )
515 .await;
516 if let Some(exit) = frame_outcome_to_exit(outcome) {
517 return exit;
518 }
519 }
520
521 loop {
522 tokio::select! {
523 biased;
524 () = cancel.cancelled() => return MessageLoopExit::Cancelled,
525
526 _ = ping_timer.tick() => {
527 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
528 return MessageLoopExit::ConnectionLost(format!(
529 "no traffic for {:?}", last_inbound.elapsed()
530 ));
531 }
532 if let Err(e) = ws.send(Message::Ping(vec![])).await {
533 return MessageLoopExit::ConnectionLost(format!("ping send: {}", err_chain(&e)));
534 }
535 }
536
537 msg = ws.next() => {
538 last_inbound = Instant::now();
539 match msg {
540 Some(Ok(frame @ (Message::Text(_) | Message::Binary(_)))) => {
541 let outcome = process_data_frame::<K>(
542 frame,
543 &subs,
544 notifications_tx,
545 &mut completed,
546 replay_from_slot,
547 &mut decompressor,
548 )
549 .await;
550 if let Some(exit) = frame_outcome_to_exit(outcome) {
551 return exit;
552 }
553 }
554 Some(Ok(Message::Pong(_) | Message::Ping(_))) => {}
555 Some(Ok(Message::Close(frame))) => {
556 return MessageLoopExit::ConnectionLost(format!("remote close: {frame:?}"));
557 }
558 Some(Ok(Message::Frame(_))) => {}
559 Some(Err(e)) => return MessageLoopExit::ConnectionLost(format!("ws read: {}", err_chain(&e))),
560 None => return MessageLoopExit::ConnectionLost("ws stream ended".into()),
561 }
562 }
563 }
564 }
565}
566
567fn frame_outcome_to_exit(outcome: Result<TextOutcome, String>) -> Option<MessageLoopExit> {
569 match outcome {
570 Ok(TextOutcome::Continue) => None,
571 Ok(TextOutcome::AllComplete) => Some(MessageLoopExit::Completed),
572 Ok(TextOutcome::ChannelClosed) => Some(MessageLoopExit::Cancelled),
573 Err(why) => Some(MessageLoopExit::ConnectionLost(why)),
574 }
575}
576
577async fn process_data_frame<K: SubKind>(
582 msg: Message,
583 subs: &Subs,
584 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
585 completed: &mut HashSet<u64>,
586 replay_from_slot: &mut Option<u64>,
587 decompressor: &mut WsStreamDecompressor,
588) -> Result<TextOutcome, String> {
589 match msg {
590 Message::Text(t) => {
591 Ok(handle_text::<K>(&t, subs, notifications_tx, completed, replay_from_slot).await)
592 }
593 Message::Binary(b) => {
595 let decoded = decompressor
596 .decompress(&b)
597 .map_err(|e| format!("ws decompress: {e}"))?;
598 match std::str::from_utf8(&decoded) {
599 Ok(t) => {
600 Ok(
601 handle_text::<K>(t, subs, notifications_tx, completed, replay_from_slot)
602 .await,
603 )
604 }
605 Err(_) => Ok(TextOutcome::Continue),
606 }
607 }
608 _ => Ok(TextOutcome::Continue),
609 }
610}
611
612async fn retry_or_fail<K: SubKind>(
615 phase: &'static str,
616 reason: String,
617 budget: &mut ReconnectBudget,
618 cancel: &CancellationToken,
619 status_tx: &watch::Sender<ConnectionStatus>,
620) -> bool {
621 if let Some(delay) = budget.next_backoff() {
622 warn!(
623 kind = K::LABEL,
624 attempt = budget.attempt(),
625 reason = %reason,
626 ?delay,
627 "subscription {phase}, retrying",
628 );
629 cancellable_sleep(delay, cancel).await
630 } else {
631 publish(
632 status_tx,
633 ConnectionStatus::Failed(ConnectionFailure::RetriesExhausted(format!(
634 "{phase}: {reason}"
635 ))),
636 );
637 false
638 }
639}
640
641fn publish(tx: &watch::Sender<ConnectionStatus>, status: ConnectionStatus) {
642 tx.send_if_modified(|current| {
643 if *current == status {
644 false
645 } else {
646 *current = status;
647 true
648 }
649 });
650}
651
652async fn connect_ws(rpc_endpoint: &str) -> Result<Ws, ControlConnectError> {
653 let ws_url =
654 http_to_ws_url(rpc_endpoint).map_err(|e| ControlConnectError::Request(err_chain(&e)))?;
655 let request = ws_url
656 .into_client_request()
657 .map_err(|e| ControlConnectError::Request(format!("build request: {}", err_chain(&e))))?;
658 connect_session_socket(request, CONNECT_TIMEOUT).await
659}
660
661struct Subscribed {
663 ws: Ws,
664 subs: Subs,
666 pending: Vec<Message>,
669}
670
671async fn subscribe<K: SubKind>(
672 mut ws: Ws,
673 program_ids: &[String],
674 replay_from_slot: Option<u64>,
675) -> Result<Subscribed, String> {
676 let mut subs = Subs::new();
677 let mut pending = Vec::new();
680 for (i, program_id) in program_ids.iter().enumerate() {
681 let id = (i + 1) as u64;
682 let mut params = K::subscribe_params(program_id);
683 SubscribeConfig {
690 #[expect(
691 clippy::cast_possible_wrap,
692 reason = "Solana slot numbers fit well within positive i64"
693 )]
694 replay_from_slot: replay_from_slot.map(|slot| slot as i64),
695 compression: Some(Compression::Zstd),
696 ..SubscribeConfig::default()
697 }
698 .apply_to(&mut params);
699 let req = serde_json::json!({
700 "jsonrpc": "2.0",
701 "id": id,
702 "method": K::SUBSCRIBE_METHOD,
703 "params": params,
704 });
705 ws.send(Message::Text(req.to_string()))
706 .await
707 .map_err(|e| format!("subscribe send: {}", err_chain(&e)))?;
708 subs.insert(read_sub_ack(&mut ws, id, &mut pending).await?);
709 }
710 debug!(
711 kind = K::LABEL,
712 count = subs.len(),
713 "subscriptions established"
714 );
715 Ok(Subscribed { ws, subs, pending })
716}
717
718#[derive(Deserialize)]
719struct SubAck {
720 id: u64,
721 result: Option<u64>,
722 #[serde(default)]
723 error: Option<serde_json::Value>,
724}
725
726async fn read_sub_ack(
732 ws: &mut Ws,
733 expected_id: u64,
734 pending: &mut Vec<Message>,
735) -> Result<u64, String> {
736 let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
737 loop {
738 let msg = tokio::time::timeout_at(deadline, ws.next())
739 .await
740 .map_err(|_elapsed| {
741 format!("subscribe ack timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}")
742 })?;
743
744 let Some(msg) = msg else {
745 return Err("ws ended during subscribe".into());
746 };
747 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
748
749 if let Message::Text(t) = &msg
751 && let Ok(ack) = serde_json::from_str::<SubAck>(t)
752 {
753 if ack.id != expected_id {
754 continue;
755 }
756 if let Some(err) = ack.error {
757 return Err(format!("subscribe rejected: {err}"));
758 }
759 return ack
760 .result
761 .ok_or_else(|| "subscribe ack missing result".to_string());
762 }
763 if matches!(msg, Message::Text(_) | Message::Binary(_)) {
764 pending.push(msg);
765 }
766 }
767}
768
769enum TextOutcome {
771 Continue,
773 AllComplete,
775 ChannelClosed,
777}
778
779async fn handle_text<K: SubKind>(
783 text: &str,
784 subs: &Subs,
785 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
786 completed: &mut HashSet<u64>,
787 replay_from_slot: &mut Option<u64>,
788) -> TextOutcome {
789 if let Some(n) = parse_notification::<K>(text, subs) {
792 let slot = K::slot_of(&n);
801 if notifications_tx
802 .send(K::into_notification(n))
803 .await
804 .is_err()
805 {
806 return TextOutcome::ChannelClosed;
807 }
808 *replay_from_slot = Some(replay_from_slot.map_or(slot, |prev| prev.max(slot)));
809 return TextOutcome::Continue;
810 }
811
812 if let Some(sub_id) = parse_completion(text)
814 && subs.contains(&sub_id)
815 {
816 completed.insert(sub_id);
817 if subs.iter().all(|id| completed.contains(id)) {
818 return TextOutcome::AllComplete;
819 }
820 }
821 TextOutcome::Continue
822}
823
824fn parse_completion(text: &str) -> Option<u64> {
827 #[derive(Deserialize)]
828 struct Msg {
829 method: String,
830 params: Params,
831 }
832 #[derive(Deserialize)]
833 struct Params {
834 subscription: u64,
835 }
836
837 let msg: Msg = serde_json::from_str(text).ok()?;
838 (msg.method == "subscriptionComplete").then_some(msg.params.subscription)
839}
840
841fn parse_notification<K: SubKind>(text: &str, subs: &Subs) -> Option<K::Notification> {
842 #[derive(Deserialize)]
843 #[serde(bound = "T: DeserializeOwned")]
844 struct Msg<T> {
845 method: String,
846 params: Params<T>,
847 }
848 #[derive(Deserialize)]
849 #[serde(bound = "T: DeserializeOwned")]
850 struct Params<T> {
851 subscription: u64,
852 result: T,
853 }
854
855 let msg: Msg<K::Notification> = serde_json::from_str(text).ok()?;
856 if msg.method != K::NOTIFICATION_METHOD {
857 return None;
858 }
859 if !subs.contains(&msg.params.subscription) {
860 return None;
861 }
862 Some(msg.params.result)
863}
864
865#[cfg(test)]
866mod tests {
867 use super::parse_completion;
868
869 #[test]
870 fn parse_completion_extracts_subscription_id() {
871 let text =
872 r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7}}"#;
873 assert_eq!(parse_completion(text), Some(7));
874 }
875
876 #[test]
877 fn parse_completion_tolerates_unknown_fields() {
878 let text = r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7,"future":"field"},"extra":true}"#;
879 assert_eq!(parse_completion(text), Some(7));
880 }
881
882 #[test]
883 fn parse_completion_ignores_other_messages() {
884 let notification = r#"{"jsonrpc":"2.0","method":"transactionNotification","params":{"subscription":7,"result":{}}}"#;
885 assert_eq!(parse_completion(notification), None);
886 assert_eq!(parse_completion("not json"), None);
887 }
888}