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