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)]
193pub fn spawn_transaction_subscription_manager(
194 rpc_endpoint: String,
195 program_ids: Vec<Address>,
196 cancel: CancellationToken,
197 coordinator: Option<Arc<ReconnectCoordinator>>,
198 diagnostics: Arc<SubscriptionDiagnostics>,
199) -> SubscriptionHandle {
200 spawn_subscription_manager::<Transaction>(
201 rpc_endpoint,
202 render(program_ids),
203 cancel,
204 coordinator,
205 diagnostics,
206 )
207}
208
209#[doc(hidden)]
211pub fn spawn_action_subscription_manager(
212 rpc_endpoint: String,
213 cancel: CancellationToken,
214 coordinator: Option<Arc<ReconnectCoordinator>>,
215 diagnostics: Arc<SubscriptionDiagnostics>,
216) -> SubscriptionHandle {
217 spawn_subscription_manager::<ActionResult>(
218 rpc_endpoint,
219 vec![String::new()],
220 cancel,
221 coordinator,
222 diagnostics,
223 )
224}
225
226#[doc(hidden)]
228pub fn spawn_replacement_subscription_manager(
229 rpc_endpoint: String,
230 cancel: CancellationToken,
231 coordinator: Option<Arc<ReconnectCoordinator>>,
232 diagnostics: Arc<SubscriptionDiagnostics>,
233) -> SubscriptionHandle {
234 spawn_subscription_manager::<Replacement>(
235 rpc_endpoint,
236 vec![String::new()],
237 cancel,
238 coordinator,
239 diagnostics,
240 )
241}
242
243#[doc(hidden)]
244pub fn spawn_diagnostic_subscription_manager(
245 rpc_endpoint: String,
246 cancel: CancellationToken,
247 coordinator: Option<Arc<ReconnectCoordinator>>,
248 diagnostics: Arc<SubscriptionDiagnostics>,
249) -> SubscriptionHandle {
250 spawn_subscription_manager::<Diagnostic>(
251 rpc_endpoint,
252 vec![String::new()],
253 cancel,
254 coordinator,
255 diagnostics,
256 )
257}
258
259#[doc(hidden)]
260pub fn spawn_account_diff_subscription_manager(
261 rpc_endpoint: String,
262 program_ids: Vec<Address>,
263 cancel: CancellationToken,
264 coordinator: Option<Arc<ReconnectCoordinator>>,
265 diagnostics: Arc<SubscriptionDiagnostics>,
266) -> SubscriptionHandle {
267 spawn_subscription_manager::<AccountDiff>(
268 rpc_endpoint,
269 render(program_ids),
270 cancel,
271 coordinator,
272 diagnostics,
273 )
274}
275
276fn render(program_ids: Vec<Address>) -> Vec<String> {
280 program_ids.iter().map(ToString::to_string).collect()
281}
282
283fn spawn_subscription_manager<K>(
284 rpc_endpoint: String,
285 program_ids: Vec<String>,
286 cancel: CancellationToken,
287 coordinator: Option<Arc<ReconnectCoordinator>>,
288 diagnostics: Arc<SubscriptionDiagnostics>,
289) -> SubscriptionHandle
290where
291 K: SubKind,
292{
293 let (notifications_tx, notifications_rx) = mpsc::channel(1024);
294 let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
295 let task = Task::<K> {
296 rpc_endpoint,
297 program_ids,
298 notifications_tx,
299 status_tx,
300 cancel,
301 coordinator,
302 diagnostics,
303 _marker: PhantomData,
304 };
305 let join = tokio::spawn(task.run());
306 SubscriptionHandle {
307 status: status_rx,
308 notifications: notifications_rx,
309 join,
310 }
311}
312
313type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
314type Subs = HashSet<u64>;
315
316struct Task<K: SubKind> {
317 rpc_endpoint: String,
318 program_ids: Vec<String>,
319 notifications_tx: mpsc::Sender<SubscriptionNotification>,
320 status_tx: watch::Sender<ConnectionStatus>,
321 cancel: CancellationToken,
324 coordinator: Option<Arc<ReconnectCoordinator>>,
329 diagnostics: Arc<SubscriptionDiagnostics>,
330 _marker: PhantomData<fn() -> K>,
331}
332
333impl<K: SubKind> Task<K> {
334 async fn run(self) {
335 let mut budget = ReconnectBudget::new();
336 let mut replay_from_slot: Option<u64> = None;
340 let mut connected_before = false;
341
342 loop {
343 if self.cancel.is_cancelled() {
344 break;
345 }
346 publish(&self.status_tx, ConnectionStatus::Down);
347
348 let reconnect_slot = match &self.coordinator {
358 Some(coord) if budget.attempt() >= RECONNECT_UNGATED_ATTEMPTS => {
359 let parked_at = Instant::now();
360 let Some(slot) = coord.reconnect_slot(&self.cancel).await else {
361 break; };
363 budget.discount_parked(parked_at.elapsed());
365 Some(slot)
366 }
367 _ => None,
368 };
369
370 let connect_result = tokio::select! {
373 biased;
374 _ = self.cancel.cancelled() => None,
375 result = async {
376 let ws = connect_ws(&self.rpc_endpoint).await?;
377 subscribe::<K>(ws, &self.program_ids, replay_from_slot)
378 .await
379 .map_err(ControlConnectError::Failed)
380 } => Some(result),
381 };
382 let Some(connect_result) = connect_result else {
383 break;
384 };
385
386 let Subscribed { ws, subs, pending } = match connect_result {
387 Ok(v) => v,
388 Err(ControlConnectError::TokenRejected) => {
389 publish(
390 &self.status_tx,
391 ConnectionStatus::Failed(ConnectionFailure::TokenRejected),
392 );
393 break;
394 }
395 Err(ControlConnectError::Request(why) | ControlConnectError::Failed(why)) => {
396 drop(reconnect_slot);
397 if retry_or_fail::<K>(
398 "connect",
399 why,
400 &mut budget,
401 &self.cancel,
402 &self.status_tx,
403 )
404 .await
405 {
406 continue;
407 }
408 break;
409 }
410 };
411
412 if connected_before {
413 warn!(
416 kind = K::LABEL,
417 replay_from_slot = ?replay_from_slot,
418 "subscription reconnected, resuming from inclusive replay cursor"
419 );
420 self.diagnostics.record_reconnect();
421 }
422 connected_before = true;
423
424 let streaming = self.coordinator.as_ref().map(|coord| coord.enter());
430 drop(reconnect_slot);
431 publish(&self.status_tx, ConnectionStatus::Up);
432 let connected_at = Instant::now();
433
434 let exit = message_loop::<K>(
435 ws,
436 subs,
437 pending,
438 &self.notifications_tx,
439 &self.cancel,
440 &mut replay_from_slot,
441 )
442 .await;
443
444 drop(streaming);
445
446 match exit {
447 MessageLoopExit::Cancelled | MessageLoopExit::Completed => break,
448 MessageLoopExit::ConnectionLost(why) => {
449 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
450 budget.reset();
451 }
452 if retry_or_fail::<K>(
453 "connection lost",
454 why,
455 &mut budget,
456 &self.cancel,
457 &self.status_tx,
458 )
459 .await
460 {
461 continue;
462 }
463 break;
464 }
465 }
466 }
467 }
468}
469
470enum MessageLoopExit {
471 Cancelled,
472 ConnectionLost(String),
473 Completed,
476}
477
478async fn message_loop<K: SubKind>(
479 mut ws: Ws,
480 subs: Subs,
481 pending: Vec<Message>,
482 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
483 cancel: &CancellationToken,
484 replay_from_slot: &mut Option<u64>,
485) -> MessageLoopExit {
486 let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
487 ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
488 let mut last_inbound = Instant::now();
489 let mut completed: HashSet<u64> = HashSet::new();
492 let mut decompressor = match WsStreamDecompressor::new() {
498 Ok(decompressor) => decompressor,
499 Err(e) => return MessageLoopExit::ConnectionLost(format!("zstd decoder init: {e}")),
500 };
501
502 for msg in pending {
505 let outcome = process_data_frame::<K>(
506 msg,
507 &subs,
508 notifications_tx,
509 &mut completed,
510 replay_from_slot,
511 &mut decompressor,
512 )
513 .await;
514 if let Some(exit) = frame_outcome_to_exit(outcome) {
515 return exit;
516 }
517 }
518
519 loop {
520 tokio::select! {
521 biased;
522 _ = cancel.cancelled() => return MessageLoopExit::Cancelled,
523
524 _ = ping_timer.tick() => {
525 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
526 return MessageLoopExit::ConnectionLost(format!(
527 "no traffic for {:?}", last_inbound.elapsed()
528 ));
529 }
530 if let Err(e) = ws.send(Message::Ping(vec![])).await {
531 return MessageLoopExit::ConnectionLost(format!("ping send: {}", err_chain(&e)));
532 }
533 }
534
535 msg = ws.next() => {
536 last_inbound = Instant::now();
537 match msg {
538 Some(Ok(frame @ (Message::Text(_) | Message::Binary(_)))) => {
539 let outcome = process_data_frame::<K>(
540 frame,
541 &subs,
542 notifications_tx,
543 &mut completed,
544 replay_from_slot,
545 &mut decompressor,
546 )
547 .await;
548 if let Some(exit) = frame_outcome_to_exit(outcome) {
549 return exit;
550 }
551 }
552 Some(Ok(Message::Pong(_))) | Some(Ok(Message::Ping(_))) => {}
553 Some(Ok(Message::Close(frame))) => {
554 return MessageLoopExit::ConnectionLost(format!("remote close: {frame:?}"));
555 }
556 Some(Ok(Message::Frame(_))) => {}
557 Some(Err(e)) => return MessageLoopExit::ConnectionLost(format!("ws read: {}", err_chain(&e))),
558 None => return MessageLoopExit::ConnectionLost("ws stream ended".into()),
559 }
560 }
561 }
562 }
563}
564
565fn frame_outcome_to_exit(outcome: Result<TextOutcome, String>) -> Option<MessageLoopExit> {
567 match outcome {
568 Ok(TextOutcome::Continue) => None,
569 Ok(TextOutcome::AllComplete) => Some(MessageLoopExit::Completed),
570 Ok(TextOutcome::ChannelClosed) => Some(MessageLoopExit::Cancelled),
571 Err(why) => Some(MessageLoopExit::ConnectionLost(why)),
572 }
573}
574
575async fn process_data_frame<K: SubKind>(
580 msg: Message,
581 subs: &Subs,
582 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
583 completed: &mut HashSet<u64>,
584 replay_from_slot: &mut Option<u64>,
585 decompressor: &mut WsStreamDecompressor,
586) -> Result<TextOutcome, String> {
587 match msg {
588 Message::Text(t) => {
589 Ok(handle_text::<K>(&t, subs, notifications_tx, completed, replay_from_slot).await)
590 }
591 Message::Binary(b) => {
593 let decoded = decompressor
594 .decompress(&b)
595 .map_err(|e| format!("ws decompress: {e}"))?;
596 match std::str::from_utf8(&decoded) {
597 Ok(t) => {
598 Ok(
599 handle_text::<K>(t, subs, notifications_tx, completed, replay_from_slot)
600 .await,
601 )
602 }
603 Err(_) => Ok(TextOutcome::Continue),
604 }
605 }
606 _ => Ok(TextOutcome::Continue),
607 }
608}
609
610async fn retry_or_fail<K: SubKind>(
613 phase: &'static str,
614 reason: String,
615 budget: &mut ReconnectBudget,
616 cancel: &CancellationToken,
617 status_tx: &watch::Sender<ConnectionStatus>,
618) -> bool {
619 if let Some(delay) = budget.next_backoff() {
620 warn!(
621 kind = K::LABEL,
622 attempt = budget.attempt(),
623 reason = %reason,
624 ?delay,
625 "subscription {phase}, retrying",
626 );
627 cancellable_sleep(delay, cancel).await
628 } else {
629 publish(
630 status_tx,
631 ConnectionStatus::Failed(ConnectionFailure::RetriesExhausted(format!(
632 "{phase}: {reason}"
633 ))),
634 );
635 false
636 }
637}
638
639fn publish(tx: &watch::Sender<ConnectionStatus>, status: ConnectionStatus) {
640 tx.send_if_modified(|current| {
641 if *current == status {
642 false
643 } else {
644 *current = status;
645 true
646 }
647 });
648}
649
650async fn connect_ws(rpc_endpoint: &str) -> Result<Ws, ControlConnectError> {
651 let ws_url =
652 http_to_ws_url(rpc_endpoint).map_err(|e| ControlConnectError::Request(err_chain(&e)))?;
653 let request = ws_url
654 .into_client_request()
655 .map_err(|e| ControlConnectError::Request(format!("build request: {}", err_chain(&e))))?;
656 connect_session_socket(request, CONNECT_TIMEOUT).await
657}
658
659struct Subscribed {
661 ws: Ws,
662 subs: Subs,
664 pending: Vec<Message>,
667}
668
669async fn subscribe<K: SubKind>(
670 mut ws: Ws,
671 program_ids: &[String],
672 replay_from_slot: Option<u64>,
673) -> Result<Subscribed, String> {
674 let mut subs = Subs::new();
675 let mut pending = Vec::new();
678 for (i, program_id) in program_ids.iter().enumerate() {
679 let id = (i + 1) as u64;
680 let mut params = K::subscribe_params(program_id);
681 SubscribeConfig {
688 replay_from_slot: replay_from_slot.map(|slot| slot as i64),
689 compression: Some(Compression::Zstd),
690 ..SubscribeConfig::default()
691 }
692 .apply_to(&mut params);
693 let req = serde_json::json!({
694 "jsonrpc": "2.0",
695 "id": id,
696 "method": K::SUBSCRIBE_METHOD,
697 "params": params,
698 });
699 ws.send(Message::Text(req.to_string()))
700 .await
701 .map_err(|e| format!("subscribe send: {}", err_chain(&e)))?;
702 subs.insert(read_sub_ack(&mut ws, id, &mut pending).await?);
703 }
704 debug!(
705 kind = K::LABEL,
706 count = subs.len(),
707 "subscriptions established"
708 );
709 Ok(Subscribed { ws, subs, pending })
710}
711
712#[derive(Deserialize)]
713struct SubAck {
714 id: u64,
715 result: Option<u64>,
716 #[serde(default)]
717 error: Option<serde_json::Value>,
718}
719
720async fn read_sub_ack(
726 ws: &mut Ws,
727 expected_id: u64,
728 pending: &mut Vec<Message>,
729) -> Result<u64, String> {
730 let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
731 loop {
732 let msg = tokio::time::timeout_at(deadline, ws.next())
733 .await
734 .map_err(|_| format!("subscribe ack timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;
735
736 let Some(msg) = msg else {
737 return Err("ws ended during subscribe".into());
738 };
739 let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
740
741 if let Message::Text(t) = &msg
743 && let Ok(ack) = serde_json::from_str::<SubAck>(t)
744 {
745 if ack.id != expected_id {
746 continue;
747 }
748 if let Some(err) = ack.error {
749 return Err(format!("subscribe rejected: {err}"));
750 }
751 return ack
752 .result
753 .ok_or_else(|| "subscribe ack missing result".to_string());
754 }
755 if matches!(msg, Message::Text(_) | Message::Binary(_)) {
756 pending.push(msg);
757 }
758 }
759}
760
761enum TextOutcome {
763 Continue,
765 AllComplete,
767 ChannelClosed,
769}
770
771async fn handle_text<K: SubKind>(
775 text: &str,
776 subs: &Subs,
777 notifications_tx: &mpsc::Sender<SubscriptionNotification>,
778 completed: &mut HashSet<u64>,
779 replay_from_slot: &mut Option<u64>,
780) -> TextOutcome {
781 if let Some(n) = parse_notification::<K>(text, subs) {
784 let slot = K::slot_of(&n);
793 if notifications_tx
794 .send(K::into_notification(n))
795 .await
796 .is_err()
797 {
798 return TextOutcome::ChannelClosed;
799 }
800 *replay_from_slot = Some(replay_from_slot.map_or(slot, |prev| prev.max(slot)));
801 return TextOutcome::Continue;
802 }
803
804 if let Some(sub_id) = parse_completion(text)
806 && subs.contains(&sub_id)
807 {
808 completed.insert(sub_id);
809 if subs.iter().all(|id| completed.contains(id)) {
810 return TextOutcome::AllComplete;
811 }
812 }
813 TextOutcome::Continue
814}
815
816fn parse_completion(text: &str) -> Option<u64> {
819 #[derive(Deserialize)]
820 struct Msg {
821 method: String,
822 params: Params,
823 }
824 #[derive(Deserialize)]
825 struct Params {
826 subscription: u64,
827 }
828
829 let msg: Msg = serde_json::from_str(text).ok()?;
830 (msg.method == "subscriptionComplete").then_some(msg.params.subscription)
831}
832
833fn parse_notification<K: SubKind>(text: &str, subs: &Subs) -> Option<K::Notification> {
834 #[derive(Deserialize)]
835 #[serde(bound = "T: DeserializeOwned")]
836 struct Msg<T> {
837 method: String,
838 params: Params<T>,
839 }
840 #[derive(Deserialize)]
841 #[serde(bound = "T: DeserializeOwned")]
842 struct Params<T> {
843 subscription: u64,
844 result: T,
845 }
846
847 let msg: Msg<K::Notification> = serde_json::from_str(text).ok()?;
848 if msg.method != K::NOTIFICATION_METHOD {
849 return None;
850 }
851 if !subs.contains(&msg.params.subscription) {
852 return None;
853 }
854 Some(msg.params.result)
855}
856
857#[cfg(test)]
858mod tests {
859 use super::parse_completion;
860
861 #[test]
862 fn parse_completion_extracts_subscription_id() {
863 let text =
864 r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7}}"#;
865 assert_eq!(parse_completion(text), Some(7));
866 }
867
868 #[test]
869 fn parse_completion_tolerates_unknown_fields() {
870 let text = r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7,"future":"field"},"extra":true}"#;
871 assert_eq!(parse_completion(text), Some(7));
872 }
873
874 #[test]
875 fn parse_completion_ignores_other_messages() {
876 let notification = r#"{"jsonrpc":"2.0","method":"transactionNotification","params":{"subscription":7,"result":{}}}"#;
877 assert_eq!(parse_completion(notification), None);
878 assert_eq!(parse_completion("not json"), None);
879 }
880}