Skip to main content

simulator_client/managed/
subscription.rs

1//! SubscriptionManager — owns subscription WebSockets and keeps them alive.
2//!
3//! Two variants:
4//! - account-diff subscription (`accountDiffSubscribe`) — account state capture
5//! - transaction subscription (`transactionSubscribe`) — full transaction
6//!   capture, delivers what `getTransaction` would return in one push so the
7//!   client can skip the per-tx fetch entirely
8//!
9//! Both follow the same reconnect + keepalive pattern. On reconnect, all
10//! configured subscriptions are re-established and resumed from the last slot
11//! delivered via the server's `replayFromSlot` cursor, so a dropped connection
12//! over a slow or lossy link doesn't silently truncate the stream. The cursor
13//! is inclusive of its slot, so the boundary slot is re-delivered; downstream
14//! consumers dedup by transaction signature / diff key.
15
16use 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
49/// Handle to a running subscription manager task.
50pub 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
63/// Per-flavor differences between `accountDiffSubscribe` and `transactionSubscribe`.
64trait 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    /// Slot a notification belongs to. Used to advance the reconnect replay
72    /// cursor so a resubscribe resumes from the last slot delivered rather
73    /// than restreaming the full session history.
74    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    /// Wire shape is identical to the `getTransaction` RPC response, so we can
97    /// reuse `transaction_from_encoded` to build the output record directly
98    /// from the push notification — no follow-up fetch required.
99    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        // Keyless: index 0 is an unused placeholder; `SubscribeConfig::apply_to`
122        // fills the config object at index 1 (replayFromSlot/compression).
123        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
149/// Spawn an `actionSubscribe` manager (keyless: a single subscribe).
150pub 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
181/// Subscription keys go on the wire as base58. `actionSubscribe` is keyless
182/// and passes an empty placeholder instead, so the manager itself stays
183/// String-keyed rather than forcing a sentinel `Address`.
184fn 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    /// Session-scoped cancel; fires both on user Ctrl-C *and* on normal
227    /// session completion. Stops the connect/message loop either way.
228    cancel: CancellationToken,
229    /// Optional coordinator shared across a parallel batch. After the fast
230    /// ungated attempts, a dropped subscription parks here until its streaming
231    /// siblings finish, then reconnects into the freed bandwidth. See
232    /// [`ReconnectCoordinator`].
233    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        // Highest slot handed to the notifications channel so far. Seeds the
242        // server's `replayFromSlot` cursor on every reconnect so a resubscribe
243        // resumes from the boundary slot rather than restreaming from the start.
244        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            // Reconnect bandwidth policy across a parallel batch: the first
254            // `RECONNECT_UNGATED_ATTEMPTS` connects (including the initial one)
255            // fire immediately so a transient drop recovers fast. After that, a
256            // saturated session stops fighting its still-streaming siblings and
257            // parks until they finish (the coordinator goes quiet), then
258            // reconnects into the freed link — resuming losslessly via
259            // `replayFromSlot`. The slot is held across connect + subscribe so
260            // only one parked session reconnects at a time. Parking is raced
261            // against cancellation so shutdown stays prompt.
262            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; // cancelled while parked
267                    };
268                    // Don't let deliberate parking burn the reconnect budget.
269                    budget.discount_parked(parked_at.elapsed());
270                    Some(slot)
271                }
272                _ => None,
273            };
274
275            // Race the handshake against cancellation too, so a slot holder bails
276            // immediately on shutdown instead of blocking the next parked sibling.
277            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                // The inclusive cursor decides which slots the new connection
310                // re-streams, so a resume that skips data is traceable to it.
311                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            // Streaming now: count it so parked siblings see the link as busy,
321            // then release the slot. Entering before the release is what
322            // serializes recovery — the next parked session takes the slot, sees
323            // us streaming, and re-parks until we finish. The guard drops below
324            // (before any backoff), freeing the link for the next sibling.
325            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    /// Every subscription on this connection delivered its end-of-stream
370    /// terminal. Stop cleanly without reconnecting.
371    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    // Subscriptions whose terminal `subscriptionComplete` marker has arrived.
386    // Once this covers every entry in `subs`, the stream is fully drained.
387    let mut completed: HashSet<u64> = HashSet::new();
388    // Per-connection streaming zstd decoder for compressed (Binary) notification
389    // frames; created fresh each connection so a reconnect starts a clean stream.
390    // We always request compression, so the decoder is unconditional — a server
391    // that didn't negotiate it just sends `Text` (which never touches the
392    // decoder). A construction failure is a real error, not "no compression".
393    let mut decompressor = match WsStreamDecompressor::new() {
394        Ok(decompressor) => decompressor,
395        Err(e) => return MessageLoopExit::ConnectionLost(format!("zstd decoder init: {e}")),
396    };
397
398    // Notifications buffered during the subscribe handshake are processed first,
399    // in order, so the compressed stream stays in sync before any live frame.
400    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
461/// Map a [`process_data_frame`] result to a loop exit, or `None` to keep going.
462fn 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
471/// Process one inbound data frame: decompress a `Binary` frame, then forward the
472/// notification and track completion via [`handle_text`]. `Err` means the
473/// connection should be dropped — a decode failure desynced the stream (the
474/// reconnect then resumes from `replayFromSlot`).
475async 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        // Binary frames are zstd-compressed notifications.
488        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
506/// Sleep for the next backoff interval, or publish `Failed` and return false if
507/// the retry budget is exhausted. Returns true if the caller should retry.
508async 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
557/// Outcome of a successful subscribe handshake.
558struct Subscribed {
559    ws: Ws,
560    /// Active subscription ids, one per program.
561    subs: Subs,
562    /// Notifications buffered during the handshake, to be processed before any
563    /// live frame.
564    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    // Notifications that arrived interleaved with acks (multi-subscribe case),
574    // handed to the message loop to process before live frames.
575    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        // The `replayFromSlot` cursor lets a reconnect resume losslessly (a
580        // client without it gets the full history). Compression is always
581        // requested; a server that doesn't support it ignores the field and
582        // sends uncompressed `Text` frames, which the message loop still handles.
583        // Everything else stays at the server's default — `intra_slot_updates`
584        // in particular is inert here, since none of these kinds coalesce.
585        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
618/// Read the subscribe ack for `expected_id`. Notification frames that arrive
619/// before it (an already-active earlier subscription on the same connection can
620/// stream while a later subscribe is still being acked) are pushed onto
621/// `pending` rather than dropped, so the message loop can process them in order
622/// — losing them would also desync the per-connection zstd stream.
623async 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        // An ack is a Text JSON-RPC response; anything else is a notification.
640        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
659/// Result of feeding one inbound text frame to the message loop.
660enum TextOutcome {
661    /// Keep reading (notification handled, or frame ignored).
662    Continue,
663    /// Every subscription on this connection has delivered its terminal marker.
664    AllComplete,
665    /// The downstream notifications channel closed — caller is gone.
666    ChannelClosed,
667}
668
669/// Handle one inbound text frame: forward a matching notification, or record a
670/// terminal `subscriptionComplete` marker. Returns [`TextOutcome::AllComplete`]
671/// once a terminal has been seen for every subscription in `subs`.
672async 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    // Try a data notification first — that's the overwhelmingly common frame,
680    // so the hot path parses the payload once.
681    if let Some(n) = parse_notification::<K>(text, subs) {
682        // Resume cursor = the highest slot handed to the channel, set to each
683        // event's *own* slot (never a later one). On reconnect the resubscribe
684        // sends `replayFromSlot = cursor` *inclusively*, so a drop re-streams the
685        // whole boundary slot — including any of its events we hadn't forwarded
686        // yet — and already-delivered ones are deduped downstream by signature /
687        // diff key. (Advancing after the send vs before is immaterial here: the
688        // inclusive resume covers either ordering; we do it after so the cursor
689        // only ever names a slot actually delivered.)
690        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    // Otherwise it may be the terminal end-of-stream marker.
703    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
714/// Parse a terminal end-of-stream marker, returning the subscription id it
715/// targets. Shape: `{"method":"subscriptionComplete","params":{"subscription":N}}`.
716fn 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}