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, DiagnosticNotification},
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    Diagnostic(DiagnosticNotification),
62}
63
64/// Per-flavor differences between `accountDiffSubscribe` and `transactionSubscribe`.
65trait SubKind: Send + Sync + 'static {
66    type Notification: DeserializeOwned + Send + 'static;
67    const LABEL: &'static str;
68    const SUBSCRIBE_METHOD: &'static str;
69    const NOTIFICATION_METHOD: &'static str;
70    fn subscribe_params(program_id: &str) -> serde_json::Value;
71    fn into_notification(notification: Self::Notification) -> SubscriptionNotification;
72    /// Slot a notification belongs to. Used to advance the reconnect replay
73    /// cursor so a resubscribe resumes from the last slot delivered rather
74    /// than restreaming the full session history.
75    fn slot_of(notification: &Self::Notification) -> u64;
76}
77
78struct AccountDiff;
79impl SubKind for AccountDiff {
80    type Notification = AccountDiffNotification;
81    const LABEL: &'static str = "account-diff";
82    const SUBSCRIBE_METHOD: &'static str = "accountDiffSubscribe";
83    const NOTIFICATION_METHOD: &'static str = "accountDiffNotification";
84    fn subscribe_params(program_id: &str) -> serde_json::Value {
85        serde_json::json!([program_id, {"address_type": "program"}])
86    }
87    fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
88        SubscriptionNotification::AccountDiff(notification)
89    }
90    fn slot_of(notification: &Self::Notification) -> u64 {
91        notification.context.slot
92    }
93}
94
95struct Transaction;
96impl SubKind for Transaction {
97    /// Wire shape is identical to the `getTransaction` RPC response, so we can
98    /// reuse `transaction_from_encoded` to build the output record directly
99    /// from the push notification — no follow-up fetch required.
100    type Notification = EncodedConfirmedTransactionWithStatusMeta;
101    const LABEL: &'static str = "transaction";
102    const SUBSCRIBE_METHOD: &'static str = "transactionSubscribe";
103    const NOTIFICATION_METHOD: &'static str = "transactionNotification";
104    fn subscribe_params(program_id: &str) -> serde_json::Value {
105        serde_json::json!([{"mentions": [program_id]}, {"commitment": "confirmed"}])
106    }
107    fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
108        SubscriptionNotification::Transaction(Box::new(notification))
109    }
110    fn slot_of(notification: &Self::Notification) -> u64 {
111        notification.slot
112    }
113}
114
115struct Diagnostic;
116impl SubKind for Diagnostic {
117    type Notification = DiagnosticNotification;
118    const LABEL: &'static str = "diagnostic";
119    const SUBSCRIBE_METHOD: &'static str = "diagnosticSubscribe";
120    const NOTIFICATION_METHOD: &'static str = "diagnosticNotification";
121    fn subscribe_params(_program_id: &str) -> serde_json::Value {
122        // Keyless, like `actionSubscribe`.
123        serde_json::json!([serde_json::Value::Null, {}])
124    }
125    fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
126        SubscriptionNotification::Diagnostic(notification)
127    }
128    fn slot_of(notification: &Self::Notification) -> u64 {
129        notification.context.slot
130    }
131}
132
133struct ActionResult;
134impl SubKind for ActionResult {
135    type Notification = ActionResultNotification;
136    const LABEL: &'static str = "action";
137    const SUBSCRIBE_METHOD: &'static str = "actionSubscribe";
138    const NOTIFICATION_METHOD: &'static str = "actionNotification";
139    fn subscribe_params(_program_id: &str) -> serde_json::Value {
140        // Keyless: index 0 is an unused placeholder; `SubscribeConfig::apply_to`
141        // fills the config object at index 1 (replayFromSlot/compression).
142        serde_json::json!([serde_json::Value::Null, {}])
143    }
144    fn into_notification(notification: Self::Notification) -> SubscriptionNotification {
145        SubscriptionNotification::ActionResult(notification)
146    }
147    fn slot_of(notification: &Self::Notification) -> u64 {
148        notification.context.slot
149    }
150}
151
152pub fn spawn_transaction_subscription_manager(
153    rpc_endpoint: String,
154    program_ids: Vec<Address>,
155    cancel: CancellationToken,
156    coordinator: Option<Arc<ReconnectCoordinator>>,
157    diagnostics: Arc<SubscriptionDiagnostics>,
158) -> SubscriptionHandle {
159    spawn_subscription_manager::<Transaction>(
160        rpc_endpoint,
161        render(program_ids),
162        cancel,
163        coordinator,
164        diagnostics,
165    )
166}
167
168/// Spawn an `actionSubscribe` manager (keyless: a single subscribe).
169pub fn spawn_action_subscription_manager(
170    rpc_endpoint: String,
171    cancel: CancellationToken,
172    coordinator: Option<Arc<ReconnectCoordinator>>,
173    diagnostics: Arc<SubscriptionDiagnostics>,
174) -> SubscriptionHandle {
175    spawn_subscription_manager::<ActionResult>(
176        rpc_endpoint,
177        vec![String::new()],
178        cancel,
179        coordinator,
180        diagnostics,
181    )
182}
183
184pub fn spawn_diagnostic_subscription_manager(
185    rpc_endpoint: String,
186    cancel: CancellationToken,
187    coordinator: Option<Arc<ReconnectCoordinator>>,
188    diagnostics: Arc<SubscriptionDiagnostics>,
189) -> SubscriptionHandle {
190    spawn_subscription_manager::<Diagnostic>(
191        rpc_endpoint,
192        vec![String::new()],
193        cancel,
194        coordinator,
195        diagnostics,
196    )
197}
198
199pub fn spawn_account_diff_subscription_manager(
200    rpc_endpoint: String,
201    program_ids: Vec<Address>,
202    cancel: CancellationToken,
203    coordinator: Option<Arc<ReconnectCoordinator>>,
204    diagnostics: Arc<SubscriptionDiagnostics>,
205) -> SubscriptionHandle {
206    spawn_subscription_manager::<AccountDiff>(
207        rpc_endpoint,
208        render(program_ids),
209        cancel,
210        coordinator,
211        diagnostics,
212    )
213}
214
215/// Subscription keys go on the wire as base58. `actionSubscribe` is keyless
216/// and passes an empty placeholder instead, so the manager itself stays
217/// String-keyed rather than forcing a sentinel `Address`.
218fn render(program_ids: Vec<Address>) -> Vec<String> {
219    program_ids.iter().map(ToString::to_string).collect()
220}
221
222fn spawn_subscription_manager<K>(
223    rpc_endpoint: String,
224    program_ids: Vec<String>,
225    cancel: CancellationToken,
226    coordinator: Option<Arc<ReconnectCoordinator>>,
227    diagnostics: Arc<SubscriptionDiagnostics>,
228) -> SubscriptionHandle
229where
230    K: SubKind,
231{
232    let (notifications_tx, notifications_rx) = mpsc::channel(1024);
233    let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
234    let task = Task::<K> {
235        rpc_endpoint,
236        program_ids,
237        notifications_tx,
238        status_tx,
239        cancel,
240        coordinator,
241        diagnostics,
242        _marker: PhantomData,
243    };
244    let join = tokio::spawn(task.run());
245    SubscriptionHandle {
246        status: status_rx,
247        notifications: notifications_rx,
248        join,
249    }
250}
251
252type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
253type Subs = HashSet<u64>;
254
255struct Task<K: SubKind> {
256    rpc_endpoint: String,
257    program_ids: Vec<String>,
258    notifications_tx: mpsc::Sender<SubscriptionNotification>,
259    status_tx: watch::Sender<ConnectionStatus>,
260    /// Session-scoped cancel; fires both on user Ctrl-C *and* on normal
261    /// session completion. Stops the connect/message loop either way.
262    cancel: CancellationToken,
263    /// Optional coordinator shared across a parallel batch. After the fast
264    /// ungated attempts, a dropped subscription parks here until its streaming
265    /// siblings finish, then reconnects into the freed bandwidth. See
266    /// [`ReconnectCoordinator`].
267    coordinator: Option<Arc<ReconnectCoordinator>>,
268    diagnostics: Arc<SubscriptionDiagnostics>,
269    _marker: PhantomData<fn() -> K>,
270}
271
272impl<K: SubKind> Task<K> {
273    async fn run(self) {
274        let mut budget = ReconnectBudget::new();
275        // Highest slot handed to the notifications channel so far. Seeds the
276        // server's `replayFromSlot` cursor on every reconnect so a resubscribe
277        // resumes from the boundary slot rather than restreaming from the start.
278        let mut replay_from_slot: Option<u64> = None;
279        let mut connected_before = false;
280
281        loop {
282            if self.cancel.is_cancelled() {
283                break;
284            }
285            publish(&self.status_tx, ConnectionStatus::Down);
286
287            // Reconnect bandwidth policy across a parallel batch: the first
288            // `RECONNECT_UNGATED_ATTEMPTS` connects (including the initial one)
289            // fire immediately so a transient drop recovers fast. After that, a
290            // saturated session stops fighting its still-streaming siblings and
291            // parks until they finish (the coordinator goes quiet), then
292            // reconnects into the freed link — resuming losslessly via
293            // `replayFromSlot`. The slot is held across connect + subscribe so
294            // only one parked session reconnects at a time. Parking is raced
295            // against cancellation so shutdown stays prompt.
296            let reconnect_slot = match &self.coordinator {
297                Some(coord) if budget.attempt() >= RECONNECT_UNGATED_ATTEMPTS => {
298                    let parked_at = Instant::now();
299                    let Some(slot) = coord.reconnect_slot(&self.cancel).await else {
300                        break; // cancelled while parked
301                    };
302                    // Don't let deliberate parking burn the reconnect budget.
303                    budget.discount_parked(parked_at.elapsed());
304                    Some(slot)
305                }
306                _ => None,
307            };
308
309            // Race the handshake against cancellation too, so a slot holder bails
310            // immediately on shutdown instead of blocking the next parked sibling.
311            let connect_result = tokio::select! {
312                biased;
313                _ = self.cancel.cancelled() => None,
314                result = async {
315                    let ws = connect_ws(&self.rpc_endpoint).await?;
316                    subscribe::<K>(ws, &self.program_ids, replay_from_slot).await
317                } => Some(result),
318            };
319            let Some(connect_result) = connect_result else {
320                break;
321            };
322
323            let Subscribed { ws, subs, pending } = match connect_result {
324                Ok(v) => v,
325                Err(why) => {
326                    drop(reconnect_slot);
327                    if retry_or_fail::<K>(
328                        "connect",
329                        why,
330                        &mut budget,
331                        &self.cancel,
332                        &self.status_tx,
333                    )
334                    .await
335                    {
336                        continue;
337                    }
338                    break;
339                }
340            };
341
342            if connected_before {
343                // The inclusive cursor decides which slots the new connection
344                // re-streams, so a resume that skips data is traceable to it.
345                warn!(
346                    kind = K::LABEL,
347                    replay_from_slot = ?replay_from_slot,
348                    "subscription reconnected, resuming from inclusive replay cursor"
349                );
350                self.diagnostics.record_reconnect();
351            }
352            connected_before = true;
353
354            // Streaming now: count it so parked siblings see the link as busy,
355            // then release the slot. Entering before the release is what
356            // serializes recovery — the next parked session takes the slot, sees
357            // us streaming, and re-parks until we finish. The guard drops below
358            // (before any backoff), freeing the link for the next sibling.
359            let streaming = self.coordinator.as_ref().map(|coord| coord.enter());
360            drop(reconnect_slot);
361            publish(&self.status_tx, ConnectionStatus::Up);
362            let connected_at = Instant::now();
363
364            let exit = message_loop::<K>(
365                ws,
366                subs,
367                pending,
368                &self.notifications_tx,
369                &self.cancel,
370                &mut replay_from_slot,
371            )
372            .await;
373
374            drop(streaming);
375
376            match exit {
377                MessageLoopExit::Cancelled | MessageLoopExit::Completed => break,
378                MessageLoopExit::ConnectionLost(why) => {
379                    if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
380                        budget.reset();
381                    }
382                    if retry_or_fail::<K>(
383                        "connection lost",
384                        why,
385                        &mut budget,
386                        &self.cancel,
387                        &self.status_tx,
388                    )
389                    .await
390                    {
391                        continue;
392                    }
393                    break;
394                }
395            }
396        }
397    }
398}
399
400enum MessageLoopExit {
401    Cancelled,
402    ConnectionLost(String),
403    /// Every subscription on this connection delivered its end-of-stream
404    /// terminal. Stop cleanly without reconnecting.
405    Completed,
406}
407
408async fn message_loop<K: SubKind>(
409    mut ws: Ws,
410    subs: Subs,
411    pending: Vec<Message>,
412    notifications_tx: &mpsc::Sender<SubscriptionNotification>,
413    cancel: &CancellationToken,
414    replay_from_slot: &mut Option<u64>,
415) -> MessageLoopExit {
416    let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
417    ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
418    let mut last_inbound = Instant::now();
419    // Subscriptions whose terminal `subscriptionComplete` marker has arrived.
420    // Once this covers every entry in `subs`, the stream is fully drained.
421    let mut completed: HashSet<u64> = HashSet::new();
422    // Per-connection streaming zstd decoder for compressed (Binary) notification
423    // frames; created fresh each connection so a reconnect starts a clean stream.
424    // We always request compression, so the decoder is unconditional — a server
425    // that didn't negotiate it just sends `Text` (which never touches the
426    // decoder). A construction failure is a real error, not "no compression".
427    let mut decompressor = match WsStreamDecompressor::new() {
428        Ok(decompressor) => decompressor,
429        Err(e) => return MessageLoopExit::ConnectionLost(format!("zstd decoder init: {e}")),
430    };
431
432    // Notifications buffered during the subscribe handshake are processed first,
433    // in order, so the compressed stream stays in sync before any live frame.
434    for msg in pending {
435        let outcome = process_data_frame::<K>(
436            msg,
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
449    loop {
450        tokio::select! {
451            biased;
452            _ = cancel.cancelled() => return MessageLoopExit::Cancelled,
453
454            _ = ping_timer.tick() => {
455                if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
456                    return MessageLoopExit::ConnectionLost(format!(
457                        "no traffic for {:?}", last_inbound.elapsed()
458                    ));
459                }
460                if let Err(e) = ws.send(Message::Ping(vec![])).await {
461                    return MessageLoopExit::ConnectionLost(format!("ping send: {}", err_chain(&e)));
462                }
463            }
464
465            msg = ws.next() => {
466                last_inbound = Instant::now();
467                match msg {
468                    Some(Ok(frame @ (Message::Text(_) | Message::Binary(_)))) => {
469                        let outcome = process_data_frame::<K>(
470                            frame,
471                            &subs,
472                            notifications_tx,
473                            &mut completed,
474                            replay_from_slot,
475                            &mut decompressor,
476                        )
477                        .await;
478                        if let Some(exit) = frame_outcome_to_exit(outcome) {
479                            return exit;
480                        }
481                    }
482                    Some(Ok(Message::Pong(_))) | Some(Ok(Message::Ping(_))) => {}
483                    Some(Ok(Message::Close(frame))) => {
484                        return MessageLoopExit::ConnectionLost(format!("remote close: {frame:?}"));
485                    }
486                    Some(Ok(Message::Frame(_))) => {}
487                    Some(Err(e)) => return MessageLoopExit::ConnectionLost(format!("ws read: {}", err_chain(&e))),
488                    None => return MessageLoopExit::ConnectionLost("ws stream ended".into()),
489                }
490            }
491        }
492    }
493}
494
495/// Map a [`process_data_frame`] result to a loop exit, or `None` to keep going.
496fn frame_outcome_to_exit(outcome: Result<TextOutcome, String>) -> Option<MessageLoopExit> {
497    match outcome {
498        Ok(TextOutcome::Continue) => None,
499        Ok(TextOutcome::AllComplete) => Some(MessageLoopExit::Completed),
500        Ok(TextOutcome::ChannelClosed) => Some(MessageLoopExit::Cancelled),
501        Err(why) => Some(MessageLoopExit::ConnectionLost(why)),
502    }
503}
504
505/// Process one inbound data frame: decompress a `Binary` frame, then forward the
506/// notification and track completion via [`handle_text`]. `Err` means the
507/// connection should be dropped — a decode failure desynced the stream (the
508/// reconnect then resumes from `replayFromSlot`).
509async fn process_data_frame<K: SubKind>(
510    msg: Message,
511    subs: &Subs,
512    notifications_tx: &mpsc::Sender<SubscriptionNotification>,
513    completed: &mut HashSet<u64>,
514    replay_from_slot: &mut Option<u64>,
515    decompressor: &mut WsStreamDecompressor,
516) -> Result<TextOutcome, String> {
517    match msg {
518        Message::Text(t) => {
519            Ok(handle_text::<K>(&t, subs, notifications_tx, completed, replay_from_slot).await)
520        }
521        // Binary frames are zstd-compressed notifications.
522        Message::Binary(b) => {
523            let decoded = decompressor
524                .decompress(&b)
525                .map_err(|e| format!("ws decompress: {e}"))?;
526            match std::str::from_utf8(&decoded) {
527                Ok(t) => {
528                    Ok(
529                        handle_text::<K>(t, subs, notifications_tx, completed, replay_from_slot)
530                            .await,
531                    )
532                }
533                Err(_) => Ok(TextOutcome::Continue),
534            }
535        }
536        _ => Ok(TextOutcome::Continue),
537    }
538}
539
540/// Sleep for the next backoff interval, or publish `Failed` and return false if
541/// the retry budget is exhausted. Returns true if the caller should retry.
542async fn retry_or_fail<K: SubKind>(
543    phase: &'static str,
544    reason: String,
545    budget: &mut ReconnectBudget,
546    cancel: &CancellationToken,
547    status_tx: &watch::Sender<ConnectionStatus>,
548) -> bool {
549    if let Some(delay) = budget.next_backoff() {
550        warn!(
551            kind = K::LABEL,
552            attempt = budget.attempt(),
553            reason = %reason,
554            ?delay,
555            "subscription {phase}, retrying",
556        );
557        cancellable_sleep(delay, cancel).await
558    } else {
559        publish(
560            status_tx,
561            ConnectionStatus::Failed(format!("{phase}: {reason}")),
562        );
563        false
564    }
565}
566
567fn publish(tx: &watch::Sender<ConnectionStatus>, status: ConnectionStatus) {
568    tx.send_if_modified(|current| {
569        if *current == status {
570            false
571        } else {
572            *current = status;
573            true
574        }
575    });
576}
577
578async fn connect_ws(rpc_endpoint: &str) -> Result<Ws, String> {
579    let ws_url = http_to_ws_url(rpc_endpoint).map_err(|e| err_chain(&e))?;
580    let request = ws_url
581        .into_client_request()
582        .map_err(|e| format!("build request: {}", err_chain(&e)))?;
583
584    let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
585        .await
586        .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
587        .map_err(|e| format!("connect: {}", err_chain(&e)))?;
588    Ok(connect.0)
589}
590
591/// Outcome of a successful subscribe handshake.
592struct Subscribed {
593    ws: Ws,
594    /// Active subscription ids, one per program.
595    subs: Subs,
596    /// Notifications buffered during the handshake, to be processed before any
597    /// live frame.
598    pending: Vec<Message>,
599}
600
601async fn subscribe<K: SubKind>(
602    mut ws: Ws,
603    program_ids: &[String],
604    replay_from_slot: Option<u64>,
605) -> Result<Subscribed, String> {
606    let mut subs = Subs::new();
607    // Notifications that arrived interleaved with acks (multi-subscribe case),
608    // handed to the message loop to process before live frames.
609    let mut pending = Vec::new();
610    for (i, program_id) in program_ids.iter().enumerate() {
611        let id = (i + 1) as u64;
612        let mut params = K::subscribe_params(program_id);
613        // The `replayFromSlot` cursor lets a reconnect resume losslessly (a
614        // client without it gets the full history). Compression is always
615        // requested; a server that doesn't support it ignores the field and
616        // sends uncompressed `Text` frames, which the message loop still handles.
617        // Everything else stays at the server's default — `intra_slot_updates`
618        // in particular is inert here, since none of these kinds coalesce.
619        SubscribeConfig {
620            replay_from_slot: replay_from_slot.map(|slot| slot as i64),
621            compression: Some(Compression::Zstd),
622            ..SubscribeConfig::default()
623        }
624        .apply_to(&mut params);
625        let req = serde_json::json!({
626            "jsonrpc": "2.0",
627            "id": id,
628            "method": K::SUBSCRIBE_METHOD,
629            "params": params,
630        });
631        ws.send(Message::Text(req.to_string()))
632            .await
633            .map_err(|e| format!("subscribe send: {}", err_chain(&e)))?;
634        subs.insert(read_sub_ack(&mut ws, id, &mut pending).await?);
635    }
636    debug!(
637        kind = K::LABEL,
638        count = subs.len(),
639        "subscriptions established"
640    );
641    Ok(Subscribed { ws, subs, pending })
642}
643
644#[derive(Deserialize)]
645struct SubAck {
646    id: u64,
647    result: Option<u64>,
648    #[serde(default)]
649    error: Option<serde_json::Value>,
650}
651
652/// Read the subscribe ack for `expected_id`. Notification frames that arrive
653/// before it (an already-active earlier subscription on the same connection can
654/// stream while a later subscribe is still being acked) are pushed onto
655/// `pending` rather than dropped, so the message loop can process them in order
656/// — losing them would also desync the per-connection zstd stream.
657async fn read_sub_ack(
658    ws: &mut Ws,
659    expected_id: u64,
660    pending: &mut Vec<Message>,
661) -> Result<u64, String> {
662    let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
663    loop {
664        let msg = tokio::time::timeout_at(deadline, ws.next())
665            .await
666            .map_err(|_| format!("subscribe ack timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"))?;
667
668        let Some(msg) = msg else {
669            return Err("ws ended during subscribe".into());
670        };
671        let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
672
673        // An ack is a Text JSON-RPC response; anything else is a notification.
674        if let Message::Text(t) = &msg
675            && let Ok(ack) = serde_json::from_str::<SubAck>(t)
676        {
677            if ack.id != expected_id {
678                continue;
679            }
680            if let Some(err) = ack.error {
681                return Err(format!("subscribe rejected: {err}"));
682            }
683            return ack
684                .result
685                .ok_or_else(|| "subscribe ack missing result".to_string());
686        }
687        if matches!(msg, Message::Text(_) | Message::Binary(_)) {
688            pending.push(msg);
689        }
690    }
691}
692
693/// Result of feeding one inbound text frame to the message loop.
694enum TextOutcome {
695    /// Keep reading (notification handled, or frame ignored).
696    Continue,
697    /// Every subscription on this connection has delivered its terminal marker.
698    AllComplete,
699    /// The downstream notifications channel closed — caller is gone.
700    ChannelClosed,
701}
702
703/// Handle one inbound text frame: forward a matching notification, or record a
704/// terminal `subscriptionComplete` marker. Returns [`TextOutcome::AllComplete`]
705/// once a terminal has been seen for every subscription in `subs`.
706async fn handle_text<K: SubKind>(
707    text: &str,
708    subs: &Subs,
709    notifications_tx: &mpsc::Sender<SubscriptionNotification>,
710    completed: &mut HashSet<u64>,
711    replay_from_slot: &mut Option<u64>,
712) -> TextOutcome {
713    // Try a data notification first — that's the overwhelmingly common frame,
714    // so the hot path parses the payload once.
715    if let Some(n) = parse_notification::<K>(text, subs) {
716        // Resume cursor = the highest slot handed to the channel, set to each
717        // event's *own* slot (never a later one). On reconnect the resubscribe
718        // sends `replayFromSlot = cursor` *inclusively*, so a drop re-streams the
719        // whole boundary slot — including any of its events we hadn't forwarded
720        // yet — and already-delivered ones are deduped downstream by signature /
721        // diff key. (Advancing after the send vs before is immaterial here: the
722        // inclusive resume covers either ordering; we do it after so the cursor
723        // only ever names a slot actually delivered.)
724        let slot = K::slot_of(&n);
725        if notifications_tx
726            .send(K::into_notification(n))
727            .await
728            .is_err()
729        {
730            return TextOutcome::ChannelClosed;
731        }
732        *replay_from_slot = Some(replay_from_slot.map_or(slot, |prev| prev.max(slot)));
733        return TextOutcome::Continue;
734    }
735
736    // Otherwise it may be the terminal end-of-stream marker.
737    if let Some(sub_id) = parse_completion(text)
738        && subs.contains(&sub_id)
739    {
740        completed.insert(sub_id);
741        if subs.iter().all(|id| completed.contains(id)) {
742            return TextOutcome::AllComplete;
743        }
744    }
745    TextOutcome::Continue
746}
747
748/// Parse a terminal end-of-stream marker, returning the subscription id it
749/// targets. Shape: `{"method":"subscriptionComplete","params":{"subscription":N}}`.
750fn parse_completion(text: &str) -> Option<u64> {
751    #[derive(Deserialize)]
752    struct Msg {
753        method: String,
754        params: Params,
755    }
756    #[derive(Deserialize)]
757    struct Params {
758        subscription: u64,
759    }
760
761    let msg: Msg = serde_json::from_str(text).ok()?;
762    (msg.method == "subscriptionComplete").then_some(msg.params.subscription)
763}
764
765fn parse_notification<K: SubKind>(text: &str, subs: &Subs) -> Option<K::Notification> {
766    #[derive(Deserialize)]
767    #[serde(bound = "T: DeserializeOwned")]
768    struct Msg<T> {
769        method: String,
770        params: Params<T>,
771    }
772    #[derive(Deserialize)]
773    #[serde(bound = "T: DeserializeOwned")]
774    struct Params<T> {
775        subscription: u64,
776        result: T,
777    }
778
779    let msg: Msg<K::Notification> = serde_json::from_str(text).ok()?;
780    if msg.method != K::NOTIFICATION_METHOD {
781        return None;
782    }
783    if !subs.contains(&msg.params.subscription) {
784        return None;
785    }
786    Some(msg.params.result)
787}
788
789#[cfg(test)]
790mod tests {
791    use super::parse_completion;
792
793    #[test]
794    fn parse_completion_extracts_subscription_id() {
795        let text =
796            r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7}}"#;
797        assert_eq!(parse_completion(text), Some(7));
798    }
799
800    #[test]
801    fn parse_completion_tolerates_unknown_fields() {
802        let text = r#"{"jsonrpc":"2.0","method":"subscriptionComplete","params":{"subscription":7,"future":"field"},"extra":true}"#;
803        assert_eq!(parse_completion(text), Some(7));
804    }
805
806    #[test]
807    fn parse_completion_ignores_other_messages() {
808        let notification = r#"{"jsonrpc":"2.0","method":"transactionNotification","params":{"subscription":7,"result":{}}}"#;
809        assert_eq!(parse_completion(notification), None);
810        assert_eq!(parse_completion("not json"), None);
811    }
812}