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