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