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