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