Skip to main content

nautilus_coinbase/websocket/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! WebSocket client for the Coinbase Advanced Trade API.
17//!
18//! Manages connection lifecycle, JWT-authenticated subscriptions, and dispatches
19//! parsed Nautilus messages through the [`FeedHandler`].
20
21use std::{
22    num::NonZeroU32,
23    str::FromStr,
24    sync::{
25        Arc, LazyLock,
26        atomic::{AtomicBool, AtomicU8, Ordering},
27    },
28    time::Duration,
29};
30
31use arc_swap::ArcSwap;
32#[cfg(test)]
33use nautilus_core::string::secret::REDACTED;
34use nautilus_core::{AtomicMap, string::secret::SecretString};
35use nautilus_live::{
36    SocketControl,
37    book::snapshot::SnapshotGate,
38    task::{TaskJoinOutcome, TaskSlot, finish_task},
39};
40use nautilus_model::{
41    data::BarType,
42    identifiers::{AccountId, InstrumentId},
43    instruments::{Instrument, InstrumentAny},
44};
45use nautilus_network::{
46    ConnectionUrl,
47    http::create_standard_nautilus_headers,
48    mode::ConnectionMode,
49    ratelimiter::quota::Quota,
50    websocket::{
51        SubscriptionState, TransportBackend, WebSocketClient, WebSocketConfig,
52        channel_message_handler,
53    },
54};
55use tokio_util::sync::CancellationToken;
56use ustr::Ustr;
57
58use crate::{
59    common::{
60        consts::{
61            RECONNECT_BACKOFF_FACTOR, RECONNECT_BASE_BACKOFF, RECONNECT_JITTER_MS,
62            RECONNECT_MAX_BACKOFF, RECONNECT_TIMEOUT, WS_DISCONNECT_TIMEOUT, WS_HEARTBEAT_SECS,
63        },
64        credential::CoinbaseCredential,
65        enums::CoinbaseWsChannel,
66    },
67    websocket::{
68        error::CoinbaseWsError,
69        handler::{FeedHandler, HandlerCommand, NautilusWsMessage},
70        messages::{CoinbaseWsAction, CoinbaseWsSubscription},
71    },
72};
73
74/// Coinbase WebSocket connection rate limit (8 per second per IP).
75pub static COINBASE_WS_CONNECTION_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
76    Quota::per_second(NonZeroU32::new(8).expect("non-zero")).expect("valid constant")
77});
78
79/// Coinbase WebSocket subscribe/unsubscribe rate limit (8 per second per IP).
80pub static COINBASE_WS_SUBSCRIPTION_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
81    Quota::per_second(NonZeroU32::new(8).expect("non-zero")).expect("valid constant")
82});
83
84/// Rate-limit key for subscribe/unsubscribe operations.
85pub const COINBASE_RATE_LIMIT_KEY_SUBSCRIPTION: &str = "subscription";
86
87/// Pre-interned [`COINBASE_RATE_LIMIT_KEY_SUBSCRIPTION`] slice.
88pub static COINBASE_WS_SUBSCRIPTION_KEYS: LazyLock<[Ustr; 1]> =
89    LazyLock::new(|| [Ustr::from(COINBASE_RATE_LIMIT_KEY_SUBSCRIPTION)]);
90
91/// WebSocket client for Coinbase Advanced Trade market data and user streams.
92///
93/// Manages connection lifecycle, subscription state, and JWT authentication.
94/// Spawns a [`FeedHandler`] task that parses raw messages into Nautilus types.
95#[derive(Debug)]
96pub struct CoinbaseWebSocketClient {
97    url: ConnectionUrl,
98    connection_mode: Arc<ArcSwap<AtomicU8>>,
99    signal: Arc<AtomicBool>,
100    cmd_tx: Arc<tokio::sync::RwLock<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>>,
101    out_rx: Option<tokio::sync::mpsc::UnboundedReceiver<NautilusWsMessage>>,
102    instruments: Arc<AtomicMap<InstrumentId, InstrumentAny>>,
103    /// Maps a canonical wire `product_id` to the `product_id` the caller
104    /// subscribed or submitted with. Coinbase rewrites aliased products to
105    /// their canonical form on the wire (e.g. `BTC-USDC -> BTC-USD`), so
106    /// inbound messages must be re-keyed to the caller's id before parsing.
107    subscription_aliases: Arc<AtomicMap<Ustr, Ustr>>,
108    bar_types: ahash::AHashMap<String, BarType>,
109    subscriptions: SubscriptionState,
110    credential: Option<CoinbaseCredential>,
111    account_id: Option<AccountId>,
112    task_handle: TaskSlot<()>,
113    shutdown_errors: Vec<String>,
114    transport_backend: TransportBackend,
115    proxy_url: Option<SecretString>,
116    socket_control: Option<SocketControl>,
117}
118
119impl Clone for CoinbaseWebSocketClient {
120    fn clone(&self) -> Self {
121        Self {
122            url: self.url.clone(),
123            connection_mode: Arc::clone(&self.connection_mode),
124            signal: Arc::clone(&self.signal),
125            cmd_tx: Arc::clone(&self.cmd_tx),
126            out_rx: None,
127            instruments: Arc::clone(&self.instruments),
128            subscription_aliases: Arc::clone(&self.subscription_aliases),
129            bar_types: self.bar_types.clone(),
130            subscriptions: self.subscriptions.clone(),
131            credential: self.credential.clone(),
132            account_id: self.account_id,
133            task_handle: TaskSlot::new(),
134            shutdown_errors: Vec::new(),
135            transport_backend: self.transport_backend,
136            proxy_url: self.proxy_url.clone(),
137            socket_control: self.socket_control.clone(),
138        }
139    }
140}
141
142impl CoinbaseWebSocketClient {
143    /// Creates a new [`CoinbaseWebSocketClient`] for public market data.
144    pub fn new(url: &str, transport_backend: TransportBackend, proxy_url: Option<String>) -> Self {
145        let (placeholder_tx, _) = tokio::sync::mpsc::unbounded_channel();
146
147        Self {
148            url: url.into(),
149            connection_mode: Arc::new(ArcSwap::from_pointee(AtomicU8::new(
150                ConnectionMode::Closed.as_u8(),
151            ))),
152            signal: Arc::new(AtomicBool::new(false)),
153            cmd_tx: Arc::new(tokio::sync::RwLock::new(placeholder_tx)),
154            out_rx: None,
155            instruments: Arc::new(AtomicMap::new()),
156            subscription_aliases: Arc::new(AtomicMap::new()),
157            bar_types: ahash::AHashMap::new(),
158            subscriptions: SubscriptionState::new('|'),
159            credential: None,
160            account_id: None,
161            task_handle: TaskSlot::new(),
162            shutdown_errors: Vec::new(),
163            transport_backend,
164            proxy_url: proxy_url.map(SecretString::from),
165            socket_control: None,
166        }
167    }
168
169    /// Configures socket state reporting and reconnect control.
170    #[must_use]
171    pub fn with_socket_control(mut self, control: SocketControl) -> Self {
172        self.socket_control = Some(control);
173        self
174    }
175
176    /// Creates a new [`CoinbaseWebSocketClient`] with credentials for authenticated channels.
177    pub fn with_credential(
178        url: &str,
179        credential: CoinbaseCredential,
180        transport_backend: TransportBackend,
181        proxy_url: Option<String>,
182    ) -> Self {
183        let mut client = Self::new(url, transport_backend, proxy_url);
184        client.credential = Some(credential);
185        client
186    }
187
188    /// Sets the account ID used when emitting user-channel execution reports.
189    ///
190    /// Propagates to the feed handler when the connection is active so that
191    /// subsequent user events carry the correct account identifier.
192    pub async fn set_account_id(&mut self, account_id: AccountId) {
193        self.account_id = Some(account_id);
194
195        let cmd_tx = self.cmd_tx.read().await;
196        if let Err(e) = cmd_tx.send(HandlerCommand::SetAccountId(account_id)) {
197            log::debug!("Failed to send SetAccountId: {e}");
198        }
199    }
200
201    /// Bulk-populates the instrument cache.
202    ///
203    /// Safe to call before or after [`Self::connect`]. When called before
204    /// connect, instruments are picked up by the initial `InitializeInstruments`
205    /// command the client sends to the handler; when called after, a fresh
206    /// `InitializeInstruments` command is sent to refresh the handler's cache.
207    pub async fn initialize_instruments(&self, instruments: Vec<InstrumentAny>) {
208        let cmd_tx = self.cmd_tx.read().await;
209
210        if !instruments.is_empty() {
211            self.instruments.rcu(|cache| {
212                for instrument in &instruments {
213                    cache.insert(instrument.id(), instrument.clone());
214                }
215            });
216        }
217
218        if let Err(e) = cmd_tx.send(HandlerCommand::InitializeInstruments(instruments)) {
219            log::debug!("Failed to send InitializeInstruments: {e}");
220        }
221    }
222
223    // Coinbase closes clients that idle without a subscribe inside 5s, and
224    // heartbeats keeps the connection alive when product topics are quiet.
225    // Marking before `resubscribe_all` replays it on every reconnect.
226    fn prime_default_subscriptions(&self) {
227        self.subscriptions
228            .mark_subscribe(CoinbaseWsChannel::Heartbeats.as_ref());
229    }
230
231    /// Establishes the WebSocket connection and spawns the feed handler.
232    pub async fn connect(&mut self) -> anyhow::Result<()> {
233        if self.is_active() || self.is_reconnecting() {
234            log::warn!("WebSocket already connected or reconnecting");
235            return Ok(());
236        }
237
238        if let Some(outcome) = finish_task(
239            &mut self.task_handle,
240            WS_DISCONNECT_TIMEOUT,
241            WS_DISCONNECT_TIMEOUT,
242        )
243        .await
244        {
245            match outcome {
246                TaskJoinOutcome::Completed(()) | TaskJoinOutcome::Aborted => {}
247                TaskJoinOutcome::Failed(error) => {
248                    anyhow::bail!("Coinbase WebSocket handler failed: {error}");
249                }
250                TaskJoinOutcome::Incomplete => {
251                    anyhow::bail!("Coinbase WebSocket handler did not stop after abort");
252                }
253            }
254        }
255
256        // Clear stop signal from any previous disconnect
257        self.signal.store(false, Ordering::Relaxed);
258
259        let (message_handler, raw_rx) = channel_message_handler();
260        let headers = create_standard_nautilus_headers();
261
262        let cfg = WebSocketConfig {
263            url: self.url.expose().to_owned(),
264            headers,
265            // Coinbase uses TCP control-frame pings for transport keep-alive;
266            // application-layer liveness comes from the heartbeats channel.
267            heartbeat_interval_secs: Some(WS_HEARTBEAT_SECS),
268            heartbeat_payload: None,
269            connect_timeout_ms: Some(RECONNECT_TIMEOUT.as_millis() as u64),
270            reconnect_delay_initial_ms: Some(RECONNECT_BASE_BACKOFF.as_millis() as u64),
271            reconnect_delay_max_ms: Some(RECONNECT_MAX_BACKOFF.as_millis() as u64),
272            reconnect_backoff_factor: Some(RECONNECT_BACKOFF_FACTOR),
273            reconnect_jitter_ms: Some(RECONNECT_JITTER_MS),
274            reconnect_max_attempts: None,
275            heartbeat_timeout_secs: None,
276            idle_timeout_ms: None,
277            writer_capacity: None,
278            backend: self.transport_backend,
279            proxy_url: self
280                .proxy_url
281                .as_ref()
282                .map(|value| value.expose_secret().to_owned()),
283            max_message_size_bytes: None,
284            max_frame_size_bytes: None,
285        };
286
287        let keyed_quotas = vec![(
288            COINBASE_RATE_LIMIT_KEY_SUBSCRIPTION.to_string(),
289            *COINBASE_WS_SUBSCRIPTION_QUOTA,
290        )];
291
292        let client = WebSocketClient::builder()
293            .config(cfg)
294            .message_handler(message_handler)
295            .keyed_quotas(keyed_quotas)
296            .default_quota(*COINBASE_WS_CONNECTION_QUOTA)
297            .maybe_state_sink(self.socket_control.as_ref().map(SocketControl::sink))
298            .connect()
299            .await?;
300
301        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
302        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<NautilusWsMessage>();
303
304        self.out_rx = Some(out_rx);
305        let connection_mode = client.connection_mode_atomic();
306        let reconnect_handle = client.reconnect_handle();
307        log::debug!("Coinbase WebSocket connected: {}", self.url.origin());
308
309        if let Err(e) = cmd_tx.send(HandlerCommand::SetClient(client)) {
310            anyhow::bail!("Failed to send SetClient command: {e}");
311        }
312
313        if let Some(control) = &self.socket_control {
314            control.register(move || reconnect_handle.request_reconnect());
315        }
316
317        {
318            let mut command_sender = self.cmd_tx.write().await;
319            let instruments_vec: Vec<InstrumentAny> =
320                self.instruments.load().values().cloned().collect();
321
322            if !instruments_vec.is_empty()
323                && let Err(e) = cmd_tx.send(HandlerCommand::InitializeInstruments(instruments_vec))
324            {
325                log::error!("Failed to send InitializeInstruments: {e}");
326            }
327
328            // Restore bar type registrations from previous session
329            for (key, bar_type) in &self.bar_types {
330                if let Err(e) = cmd_tx.send(HandlerCommand::AddBarType {
331                    key: key.clone(),
332                    bar_type: *bar_type,
333                }) {
334                    log::error!("Failed to restore bar type {key}: {e}");
335                }
336            }
337
338            if let Some(account_id) = self.account_id
339                && let Err(e) = cmd_tx.send(HandlerCommand::SetAccountId(account_id))
340            {
341                log::error!("Failed to restore account_id: {e}");
342            }
343
344            self.prime_default_subscriptions();
345
346            // Replay retained subscriptions from previous session
347            resubscribe_all(
348                &self.subscriptions,
349                &self.credential,
350                &cmd_tx,
351                Some(&out_tx),
352            );
353
354            *command_sender = cmd_tx.clone();
355            self.connection_mode.store(connection_mode);
356        }
357
358        let signal = Arc::clone(&self.signal);
359        let subscriptions = self.subscriptions.clone();
360        let credential = self.credential.clone();
361        let cmd_tx_reconnect = cmd_tx.clone();
362        let aliases_for_handler = Arc::clone(&self.subscription_aliases);
363
364        if let Err(e) = self.task_handle.spawn(async move {
365            let mut handler = FeedHandler::new(signal, cmd_rx, raw_rx, aliases_for_handler);
366
367            loop {
368                match handler.next().await {
369                    Some(NautilusWsMessage::Reconnected) => {
370                        subscriptions.reset_after_reconnect();
371                        resubscribe_all(
372                            &subscriptions,
373                            &credential,
374                            &cmd_tx_reconnect,
375                            Some(&out_tx),
376                        );
377
378                        if let Err(e) = out_tx.send(NautilusWsMessage::Reconnected) {
379                            log::debug!("Output channel closed: {e}");
380                            break;
381                        }
382                    }
383                    Some(msg) => {
384                        if let Err(e) = out_tx.send(msg) {
385                            log::debug!("Output channel closed: {e}");
386                            break;
387                        }
388                    }
389                    None => {
390                        log::debug!("Feed handler stopped");
391                        break;
392                    }
393                }
394            }
395        }) {
396            self.out_rx = None;
397            anyhow::bail!("Failed to start Coinbase WebSocket handler task: {e}");
398        }
399
400        Ok(())
401    }
402
403    /// Subscribes to a channel for the given product IDs.
404    pub async fn subscribe(
405        &self,
406        channel: CoinbaseWsChannel,
407        product_ids: &[Ustr],
408    ) -> anyhow::Result<()> {
409        let jwt = if channel.requires_auth() {
410            let credential = self
411                .credential
412                .as_ref()
413                .ok_or_else(|| anyhow::anyhow!("Credentials required for {channel}"))?;
414            Some(credential.build_ws_jwt()?)
415        } else {
416            self.credential.as_ref().and_then(|c| c.build_ws_jwt().ok())
417        };
418
419        let sub = protect_subscription(CoinbaseWsSubscription {
420            msg_type: CoinbaseWsAction::Subscribe,
421            product_ids: product_ids.to_vec(),
422            channel,
423            jwt,
424        })?;
425
426        let channel_str = channel.as_ref();
427
428        if product_ids.is_empty() {
429            self.subscriptions.mark_subscribe(channel_str);
430        } else {
431            for product_id in product_ids {
432                let topic = format!("{channel_str}|{product_id}");
433                self.subscriptions.mark_subscribe(&topic);
434            }
435        }
436
437        let cmd_tx = self.cmd_tx.read().await;
438        cmd_tx
439            .send(HandlerCommand::Subscribe {
440                channel: sub.channel,
441                product_ids: sub.product_ids,
442                payload: sub.payload,
443            })
444            .map_err(|e| anyhow::anyhow!("Failed to send Subscribe command: {e}"))
445    }
446
447    /// Unsubscribes from a channel for the given product IDs.
448    pub async fn unsubscribe(
449        &self,
450        channel: CoinbaseWsChannel,
451        product_ids: &[Ustr],
452    ) -> anyhow::Result<()> {
453        let jwt = self.credential.as_ref().and_then(|c| c.build_ws_jwt().ok());
454
455        let unsub = protect_subscription(CoinbaseWsSubscription {
456            msg_type: CoinbaseWsAction::Unsubscribe,
457            product_ids: product_ids.to_vec(),
458            channel,
459            jwt,
460        })?;
461
462        let channel_str = channel.as_ref();
463
464        if product_ids.is_empty() {
465            self.subscriptions.mark_unsubscribe(channel_str);
466        } else {
467            for product_id in product_ids {
468                let topic = format!("{channel_str}|{product_id}");
469                self.subscriptions.mark_unsubscribe(&topic);
470            }
471        }
472
473        let cmd_tx = self.cmd_tx.read().await;
474        cmd_tx
475            .send(HandlerCommand::Unsubscribe {
476                channel: unsub.channel,
477                product_ids: unsub.product_ids,
478                payload: unsub.payload,
479            })
480            .map_err(|e| anyhow::anyhow!("Failed to send Unsubscribe command: {e}"))
481    }
482
483    /// Subscribes to the `level2` channel for one product and waits for the write.
484    ///
485    /// `gate` opens once the subscribe frame is written; the book snapshot follows on the stream.
486    ///
487    /// # Errors
488    ///
489    /// Returns an error if the payload cannot be built, the feed handler is unavailable, the
490    /// write fails, or `cancel` ends the write first.
491    pub(crate) async fn subscribe_book(
492        &self,
493        product_id: Ustr,
494        cancel: CancellationToken,
495        gate: SnapshotGate,
496    ) -> Result<(), CoinbaseWsError> {
497        let subscribe = self.book_payload(CoinbaseWsAction::Subscribe, product_id)?;
498        let channel = CoinbaseWsChannel::Level2;
499        self.subscriptions
500            .mark_subscribe(&format!("{}|{product_id}", channel.as_ref()));
501
502        self.send_book_subscription(vec![subscribe], cancel, gate)
503            .await
504    }
505
506    /// Replaces the `level2` subscription for one product with an unsubscribe and subscribe pair.
507    ///
508    /// Coinbase sends a fresh snapshot only for a new subscription, so a duplicate subscribe
509    /// cannot recover a book. The retained subscription state is left unchanged.
510    ///
511    /// # Errors
512    ///
513    /// Returns an error if a payload cannot be built, the feed handler is unavailable, a write
514    /// fails, or `cancel` ends the writes first.
515    pub(crate) async fn resubscribe_book(
516        &self,
517        product_id: Ustr,
518        cancel: CancellationToken,
519        gate: SnapshotGate,
520    ) -> Result<(), CoinbaseWsError> {
521        let unsubscribe = self.book_payload(CoinbaseWsAction::Unsubscribe, product_id)?;
522        let subscribe = self.book_payload(CoinbaseWsAction::Subscribe, product_id)?;
523
524        self.send_book_subscription(vec![unsubscribe, subscribe], cancel, gate)
525            .await
526    }
527
528    fn book_payload(
529        &self,
530        action: CoinbaseWsAction,
531        product_id: Ustr,
532    ) -> Result<SecretString, CoinbaseWsError> {
533        let jwt = self.credential.as_ref().and_then(|c| c.build_ws_jwt().ok());
534
535        protect_subscription(CoinbaseWsSubscription {
536            msg_type: action,
537            product_ids: vec![product_id],
538            channel: CoinbaseWsChannel::Level2,
539            jwt,
540        })
541        .map(|subscription| subscription.payload)
542        .map_err(|e| CoinbaseWsError::MessageSerialization(e.to_string()))
543    }
544
545    async fn send_book_subscription(
546        &self,
547        payloads: Vec<SecretString>,
548        cancel: CancellationToken,
549        gate: SnapshotGate,
550    ) -> Result<(), CoinbaseWsError> {
551        let (completion, receiver) = tokio::sync::oneshot::channel();
552        let cmd_tx = self.cmd_tx.read().await;
553
554        if cancel.is_cancelled() {
555            return Err(CoinbaseWsError::ChannelSend(
556                "book subscription cancelled".to_string(),
557            ));
558        }
559
560        cmd_tx
561            .send(HandlerCommand::BookSubscription {
562                payloads,
563                cancel,
564                gate,
565                completion,
566            })
567            .map_err(|e| CoinbaseWsError::ChannelSend(e.to_string()))?;
568
569        drop(cmd_tx);
570        receiver
571            .await
572            .map_err(|e| CoinbaseWsError::ChannelSend(e.to_string()))?
573    }
574
575    /// Returns the next parsed message from the feed handler.
576    pub async fn next_message(&mut self) -> Option<NautilusWsMessage> {
577        self.out_rx.as_mut()?.recv().await
578    }
579
580    /// Disconnects the WebSocket and stops the feed handler.
581    pub(crate) fn begin_shutdown(&self) {
582        self.signal.store(true, Ordering::Release);
583    }
584
585    /// Disconnects the WebSocket and stops the feed handler.
586    pub async fn disconnect(&mut self) -> anyhow::Result<()> {
587        // Send Disconnect command before setting the signal so the handler
588        // processes it and calls notify_closed() on the inner WebSocket client
589        let cmd_tx = self.cmd_tx.read().await;
590
591        if let Err(e) = cmd_tx.send(HandlerCommand::Disconnect) {
592            log::debug!("Failed to send Disconnect command: {e}");
593        }
594        drop(cmd_tx);
595
596        // Release pairs with the handler's Acquire load; fallback for when
597        // the command channel is full or closed.
598        self.begin_shutdown();
599
600        if let Some(outcome) = finish_task(
601            &mut self.task_handle,
602            WS_DISCONNECT_TIMEOUT,
603            WS_DISCONNECT_TIMEOUT,
604        )
605        .await
606        {
607            match outcome {
608                TaskJoinOutcome::Completed(()) | TaskJoinOutcome::Aborted => {}
609                TaskJoinOutcome::Failed(error) => {
610                    self.shutdown_errors
611                        .push(format!("Coinbase WebSocket handler failed: {error}"));
612                }
613                TaskJoinOutcome::Incomplete => {
614                    self.shutdown_errors
615                        .push("Coinbase WebSocket handler did not stop after abort".to_string());
616                }
617            }
618        }
619
620        // Wait for the inner WebSocket's connection_mode atomic to reach Closed
621        // before returning. Without this, a subsequent connect() can observe a
622        // stale Active/Reconnect state and early-return, leaving out_rx unset
623        // and causing "WebSocket output receiver not available" on take.
624        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
625
626        loop {
627            let mode_ptr = self.connection_mode.load();
628
629            if ConnectionMode::from_u8(mode_ptr.load(Ordering::Relaxed)).is_closed() {
630                break;
631            }
632
633            if tokio::time::Instant::now() >= deadline {
634                self.shutdown_errors
635                    .push("Timed out waiting for WebSocket to reach Closed state".to_string());
636                break;
637            }
638
639            tokio::time::sleep(Duration::from_millis(20)).await;
640        }
641
642        if let Some(control) = &self.socket_control {
643            control.deregister();
644        }
645
646        if self.shutdown_errors.is_empty() {
647            Ok(())
648        } else {
649            let errors = std::mem::take(&mut self.shutdown_errors);
650            anyhow::bail!(errors.join("; "))
651        }
652    }
653
654    /// Returns true if the WebSocket connection is active.
655    #[must_use]
656    pub fn is_active(&self) -> bool {
657        let mode_ptr = self.connection_mode.load();
658        let mode_val = mode_ptr.load(Ordering::Relaxed);
659        ConnectionMode::from_u8(mode_val).is_active()
660    }
661
662    /// Returns true if the WebSocket is reconnecting after a transport drop.
663    #[must_use]
664    pub fn is_reconnecting(&self) -> bool {
665        let mode_ptr = self.connection_mode.load();
666        let mode_val = mode_ptr.load(Ordering::Relaxed);
667        ConnectionMode::from_u8(mode_val).is_reconnect()
668    }
669
670    /// Returns a reference to the instrument cache.
671    #[must_use]
672    pub fn instruments(&self) -> &Arc<AtomicMap<InstrumentId, InstrumentAny>> {
673        &self.instruments
674    }
675
676    /// Returns a reference to the canonical-to-subscribed alias map.
677    #[must_use]
678    pub fn subscription_aliases(&self) -> &Arc<AtomicMap<Ustr, Ustr>> {
679        &self.subscription_aliases
680    }
681
682    /// Records that inbound messages carrying `canonical` should be re-keyed to
683    /// `subscribed`. Caller is the data/exec client at subscribe or submit time
684    /// when the local product id differs from Coinbase's canonical alias.
685    pub fn register_subscription_alias(&self, canonical: Ustr, subscribed: Ustr) {
686        self.subscription_aliases.insert(canonical, subscribed);
687    }
688
689    /// Removes an alias registration. Safe to call if no entry exists.
690    pub fn unregister_subscription_alias(&self, canonical: &Ustr) {
691        self.subscription_aliases.remove(canonical);
692    }
693
694    /// Returns the subscription state.
695    #[must_use]
696    pub fn subscriptions(&self) -> &SubscriptionState {
697        &self.subscriptions
698    }
699
700    /// Updates an instrument in the cache and notifies the handler.
701    pub async fn update_instrument(&self, instrument: InstrumentAny) {
702        let cmd_tx = self.cmd_tx.read().await;
703        let id = instrument.id();
704        self.instruments.insert(id, instrument.clone());
705
706        if let Err(e) = cmd_tx.send(HandlerCommand::UpdateInstrument(Box::new(instrument))) {
707            log::debug!("Failed to send UpdateInstrument: {e}");
708        }
709    }
710
711    pub(crate) async fn update_instruments(&self, instruments: &[InstrumentAny]) {
712        if instruments.is_empty() {
713            return;
714        }
715
716        let cmd_tx = self.cmd_tx.read().await;
717        self.instruments.rcu(|cache| {
718            for instrument in instruments {
719                cache.insert(instrument.id(), instrument.clone());
720            }
721        });
722
723        for instrument in instruments {
724            if let Err(e) = cmd_tx.send(HandlerCommand::UpdateInstrument(Box::new(
725                instrument.clone(),
726            ))) {
727                log::debug!("Failed to send UpdateInstrument: {e}");
728            }
729        }
730    }
731
732    /// Takes the output message receiver, leaving `None` in its place.
733    ///
734    /// Used by the data client to move the receiver into a background consumption task.
735    pub fn take_out_rx(
736        &mut self,
737    ) -> Option<tokio::sync::mpsc::UnboundedReceiver<NautilusWsMessage>> {
738        self.out_rx.take()
739    }
740
741    /// Registers a bar type locally without notifying the handler.
742    ///
743    /// Used by the data client to persist registrations on the original client
744    /// before cloning for async command dispatch.
745    pub fn register_bar_type(&mut self, key: String, bar_type: BarType) {
746        self.bar_types.insert(key, bar_type);
747    }
748
749    /// Registers a bar type for candle parsing.
750    pub async fn add_bar_type(&mut self, key: String, bar_type: BarType) {
751        self.bar_types.insert(key.clone(), bar_type);
752
753        let cmd_tx = self.cmd_tx.read().await;
754
755        if let Err(e) = cmd_tx.send(HandlerCommand::AddBarType { key, bar_type }) {
756            log::debug!("Failed to send AddBarType: {e}");
757        }
758    }
759}
760
761impl Drop for CoinbaseWebSocketClient {
762    fn drop(&mut self) {
763        if let Some(handle) = self.task_handle.as_ref() {
764            self.signal.store(true, Ordering::Release);
765            handle.abort();
766        }
767    }
768}
769
770struct ProtectedSubscription {
771    channel: CoinbaseWsChannel,
772    product_ids: Vec<Ustr>,
773    payload: SecretString,
774}
775
776fn protect_subscription(
777    mut subscription: CoinbaseWsSubscription,
778) -> Result<ProtectedSubscription, serde_json::Error> {
779    let payload = SecretString::from(serde_json::to_string(&subscription)?);
780
781    Ok(ProtectedSubscription {
782        channel: subscription.channel,
783        product_ids: std::mem::take(&mut subscription.product_ids),
784        payload,
785    })
786}
787
788fn resubscribe_all(
789    subscriptions: &SubscriptionState,
790    credential: &Option<CoinbaseCredential>,
791    cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
792    out_tx: Option<&tokio::sync::mpsc::UnboundedSender<NautilusWsMessage>>,
793) {
794    let topics = subscriptions.all_topics();
795
796    if topics.is_empty() {
797        log::debug!("No active subscriptions to restore");
798        return;
799    }
800
801    log::info!(
802        "Resubscribing to {} topics after reconnection",
803        topics.len()
804    );
805
806    for topic in topics {
807        let (channel, product_id) = match topic.split_once('|') {
808            Some((ch, pid)) => (ch, Some(pid)),
809            None => (topic.as_str(), None),
810        };
811
812        let channel_enum = match CoinbaseWsChannel::from_str(channel) {
813            Ok(ch) => ch,
814            Err(_) => {
815                log::warn!("Unknown channel in topic: {topic}");
816                continue;
817            }
818        };
819
820        let jwt = match credential.as_ref() {
821            Some(c) => match c.build_ws_jwt() {
822                Ok(token) => Some(token),
823                Err(e) => {
824                    if channel_enum.requires_auth() {
825                        let msg = format!(
826                            "JWT required for {channel} but build failed: {e}; topic {topic} not restored"
827                        );
828                        log::error!("{msg}");
829                        if let Some(tx) = out_tx {
830                            let _ = tx.send(NautilusWsMessage::Error(msg));
831                        }
832                        continue;
833                    }
834                    None
835                }
836            },
837            None => {
838                if channel_enum.requires_auth() {
839                    let msg = format!(
840                        "JWT required for {channel} but no credentials configured; topic {topic} not restored"
841                    );
842                    log::error!("{msg}");
843                    if let Some(tx) = out_tx {
844                        let _ = tx.send(NautilusWsMessage::Error(msg));
845                    }
846                    continue;
847                }
848                None
849            }
850        };
851
852        let product_ids = match product_id {
853            Some(pid) => vec![Ustr::from(pid)],
854            None => vec![],
855        };
856
857        let sub = CoinbaseWsSubscription {
858            msg_type: CoinbaseWsAction::Subscribe,
859            product_ids,
860            channel: channel_enum,
861            jwt,
862        };
863
864        let sub = match protect_subscription(sub) {
865            Ok(sub) => sub,
866            Err(e) => {
867                log::error!("Failed to serialize subscription for {topic}: {e}");
868                continue;
869            }
870        };
871
872        if let Err(e) = cmd_tx.send(HandlerCommand::Subscribe {
873            channel: sub.channel,
874            product_ids: sub.product_ids,
875            payload: sub.payload,
876        }) {
877            log::error!("Failed to resubscribe {topic}: {e}");
878        }
879    }
880}
881
882#[cfg(test)]
883mod tests {
884    use futures_util::StreamExt;
885    use nautilus_network::websocket::SubscriptionState;
886    use nautilus_testkit::connection::race_command_with_publication;
887    use rstest::rstest;
888
889    use super::*;
890
891    #[rstest]
892    #[case::single(false)]
893    #[case::bulk(true)]
894    #[tokio::test]
895    async fn instrument_updates_wait_for_sender_publication(#[case] bulk: bool) {
896        let ws_client =
897            CoinbaseWebSocketClient::new("wss://test", TransportBackend::default(), None);
898        let instrument = InstrumentAny::CryptoPerpetual(
899            nautilus_model::instruments::stubs::crypto_perpetual_ethusdt(),
900        );
901        let mut sender = ws_client.cmd_tx.write().await;
902
903        let mut update = Box::pin(async {
904            if bulk {
905                ws_client
906                    .initialize_instruments(vec![instrument.clone()])
907                    .await;
908            } else {
909                ws_client.update_instrument(instrument.clone()).await;
910            }
911        });
912
913        assert!(futures_util::poll!(update.as_mut()).is_pending());
914        assert!(ws_client.instruments.load().is_empty());
915        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
916        *sender = cmd_tx;
917        drop(sender);
918        update.await;
919
920        assert_eq!(
921            ws_client.instruments.get_cloned(&instrument.id()),
922            Some(instrument.clone())
923        );
924
925        match (bulk, cmd_rx.try_recv().unwrap()) {
926            (true, HandlerCommand::InitializeInstruments(instruments)) => {
927                assert_eq!(instruments, vec![instrument]);
928            }
929            (false, HandlerCommand::UpdateInstrument(updated)) => assert_eq!(*updated, instrument),
930            (_, command) => panic!("unexpected cache command: {command:?}"),
931        }
932
933        assert!(cmd_rx.try_recv().is_err());
934    }
935
936    #[rstest]
937    #[case::initialize(true)]
938    #[case::update(false)]
939    #[tokio::test]
940    async fn batch_updates_merge_and_keep_command_order(#[case] initialize: bool) {
941        let ws_client =
942            CoinbaseWebSocketClient::new("wss://test", TransportBackend::default(), None);
943        let retained = InstrumentAny::CryptoPerpetual(
944            nautilus_model::instruments::stubs::crypto_perpetual_ethusdt(),
945        );
946
947        let mut first = match retained.clone() {
948            InstrumentAny::CryptoPerpetual(instrument) => instrument,
949            _ => unreachable!(),
950        };
951
952        first.id = "BTCUSDT.COINBASE".into();
953        first.ts_event = 17.into();
954        let mut latest = first.clone();
955        latest.ts_event = 29.into();
956        let batch = vec![
957            InstrumentAny::CryptoPerpetual(first),
958            InstrumentAny::CryptoPerpetual(latest),
959        ];
960        ws_client
961            .initialize_instruments(vec![retained.clone()])
962            .await;
963        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
964        *ws_client.cmd_tx.write().await = sender;
965        if initialize {
966            ws_client.initialize_instruments(batch.clone()).await;
967        } else {
968            ws_client.update_instruments(&batch).await;
969        }
970
971        assert_eq!(ws_client.instruments.len(), 2);
972
973        for expected in [&retained, &batch[1]] {
974            assert_eq!(
975                serde_json::to_value(ws_client.instruments.get_cloned(&expected.id()).unwrap())
976                    .unwrap(),
977                serde_json::to_value(expected).unwrap()
978            );
979        }
980
981        if initialize {
982            let HandlerCommand::InitializeInstruments(actual) = receiver.try_recv().unwrap() else {
983                panic!("expected InitializeInstruments");
984            };
985
986            assert_eq!(
987                serde_json::to_value(actual).unwrap(),
988                serde_json::to_value(&batch).unwrap()
989            );
990        } else {
991            for expected in &batch {
992                let HandlerCommand::UpdateInstrument(actual) = receiver.try_recv().unwrap() else {
993                    panic!("expected UpdateInstrument");
994                };
995
996                assert_eq!(
997                    serde_json::to_value(actual).unwrap(),
998                    serde_json::to_value(expected).unwrap()
999                );
1000            }
1001        }
1002
1003        assert!(receiver.try_recv().is_err());
1004        let before = ws_client.instruments.load();
1005        ws_client.update_instruments(&[]).await;
1006        assert!(Arc::ptr_eq(&before, &ws_client.instruments.load()));
1007        assert!(receiver.try_recv().is_err());
1008    }
1009
1010    #[tokio::test]
1011    async fn command_during_sender_publication_reaches_initialized_handler() {
1012        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1013        let addr = listener.local_addr().unwrap();
1014        let (received_tx, mut received_rx) = tokio::sync::mpsc::unbounded_channel();
1015
1016        let server = tokio::spawn(async move {
1017            let (socket, _) = listener.accept().await.unwrap();
1018            let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
1019            while let Some(Ok(message)) = socket.next().await {
1020                if let tokio_tungstenite::tungstenite::Message::Text(text) = message {
1021                    let payload: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
1022                    let _ = received_tx.send(payload);
1023                }
1024            }
1025        });
1026
1027        let url = format!("ws://{addr}");
1028        let mut ws_client = CoinbaseWebSocketClient::new(&url, TransportBackend::default(), None);
1029        let observer = ws_client.clone();
1030        let expected = serde_json::json!({
1031            "type": "subscribe",
1032            "channel": "market_trades",
1033            "product_ids": [
1034                "BTC-USD"
1035            ]
1036        });
1037
1038        let command = HandlerCommand::Subscribe {
1039            channel: CoinbaseWsChannel::MarketTrades,
1040            product_ids: vec![Ustr::from("BTC-USD")],
1041            payload: SecretString::from(expected.to_string()),
1042        };
1043
1044        race_command_with_publication(
1045            Arc::clone(&ws_client.cmd_tx),
1046            ws_client.connect(),
1047            move || command,
1048            || observer.is_active(),
1049        )
1050        .await
1051        .expect("connect failed");
1052
1053        let received = tokio::time::timeout(Duration::from_secs(2), async {
1054            let heartbeat = received_rx.recv().await.unwrap();
1055            let command = received_rx.recv().await.unwrap();
1056            (heartbeat, command)
1057        })
1058        .await;
1059
1060        ws_client.disconnect().await.expect("disconnect failed");
1061        server.abort();
1062
1063        let (heartbeat, payload) = received.expect("startup command must reach server");
1064        assert_eq!(
1065            heartbeat,
1066            serde_json::json!({
1067                "type": "subscribe",
1068                "channel": "heartbeats"
1069            })
1070        );
1071        assert_eq!(payload, expected);
1072    }
1073
1074    #[rstest]
1075    #[case("wss://stream.example.com/feed", "wss://stream.example.com")]
1076    #[case(
1077        "wss://SYN-user:SYN-password@stream.example.com:9443/SYN-path?token=SYN-query#SYN-fragment",
1078        "wss://stream.example.com:9443"
1079    )]
1080    fn test_debug_preserves_url_origin(#[case] url: &str, #[case] origin: &str) {
1081        let client = CoinbaseWebSocketClient::new(url, TransportBackend::default(), None);
1082        let debug = format!("{client:?}");
1083        assert!(debug.contains(&format!("url: {origin:?}")));
1084        assert!(!debug.contains("SYN-"));
1085        assert_eq!(client.url.expose(), url);
1086    }
1087
1088    #[rstest]
1089    fn test_debug_redacts_proxy_url() {
1090        let proxy_url = "http://user:password@proxy.example:8080";
1091        let client = CoinbaseWebSocketClient::new(
1092            "wss://test",
1093            TransportBackend::default(),
1094            Some(proxy_url.to_string()),
1095        );
1096
1097        let debug = format!("{client:?}");
1098
1099        assert!(debug.contains(REDACTED));
1100        assert!(!debug.contains(proxy_url));
1101    }
1102
1103    #[rstest]
1104    fn test_drop_clone_does_not_signal_handler() {
1105        let client = CoinbaseWebSocketClient::new("wss://test", TransportBackend::default(), None);
1106        let clone = client.clone();
1107
1108        drop(clone);
1109
1110        assert!(!client.signal.load(Ordering::Acquire));
1111    }
1112
1113    #[rstest]
1114    fn test_resubscribe_all_product_level_topic() {
1115        let subs = SubscriptionState::new('|');
1116        subs.mark_subscribe("level2|BTC-USD");
1117
1118        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1119        resubscribe_all(&subs, &None, &tx, None);
1120
1121        let cmd = rx.try_recv().unwrap();
1122
1123        match cmd {
1124            HandlerCommand::Subscribe {
1125                channel,
1126                product_ids,
1127                payload,
1128            } => {
1129                let payload: serde_json::Value =
1130                    serde_json::from_str(payload.expose_secret()).unwrap();
1131                assert_eq!(channel, CoinbaseWsChannel::Level2);
1132                assert_eq!(product_ids, vec![Ustr::from("BTC-USD")]);
1133                assert!(payload.get("jwt").is_none());
1134            }
1135            other => panic!("Expected Subscribe, was {other:?}"),
1136        }
1137    }
1138
1139    #[rstest]
1140    fn test_resubscribe_all_channel_level_topic() {
1141        let subs = SubscriptionState::new('|');
1142        subs.mark_subscribe("heartbeats");
1143
1144        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1145        resubscribe_all(&subs, &None, &tx, None);
1146
1147        let cmd = rx.try_recv().unwrap();
1148
1149        match cmd {
1150            HandlerCommand::Subscribe {
1151                channel,
1152                product_ids,
1153                ..
1154            } => {
1155                assert_eq!(channel, CoinbaseWsChannel::Heartbeats);
1156                assert!(product_ids.is_empty());
1157            }
1158            other => panic!("Expected Subscribe, was {other:?}"),
1159        }
1160    }
1161
1162    #[rstest]
1163    fn test_resubscribe_all_multiple_topics() {
1164        let subs = SubscriptionState::new('|');
1165        subs.mark_subscribe("market_trades|BTC-USD");
1166        subs.mark_subscribe("ticker|ETH-USD");
1167
1168        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1169        resubscribe_all(&subs, &None, &tx, None);
1170
1171        let cmd1 = rx.try_recv().unwrap();
1172        let cmd2 = rx.try_recv().unwrap();
1173
1174        assert!(matches!(cmd1, HandlerCommand::Subscribe { .. }));
1175        assert!(matches!(cmd2, HandlerCommand::Subscribe { .. }));
1176        assert!(rx.try_recv().is_err());
1177    }
1178
1179    #[rstest]
1180    fn test_resubscribe_all_empty_subscriptions() {
1181        let subs = SubscriptionState::new('|');
1182
1183        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1184        resubscribe_all(&subs, &None, &tx, None);
1185
1186        assert!(rx.try_recv().is_err());
1187    }
1188
1189    #[rstest]
1190    fn test_resubscribe_all_unknown_channel_skipped() {
1191        let subs = SubscriptionState::new('|');
1192        subs.mark_subscribe("nonexistent_channel|BTC-USD");
1193
1194        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1195        resubscribe_all(&subs, &None, &tx, None);
1196
1197        assert!(rx.try_recv().is_err());
1198    }
1199
1200    #[rstest]
1201    #[case("level2|BTC-USD", CoinbaseWsChannel::Level2)]
1202    #[case("market_trades|ETH-USD", CoinbaseWsChannel::MarketTrades)]
1203    #[case("ticker|BTC-USD", CoinbaseWsChannel::Ticker)]
1204    #[case("ticker_batch|BTC-USD", CoinbaseWsChannel::TickerBatch)]
1205    #[case("candles|BTC-USD", CoinbaseWsChannel::Candles)]
1206    #[case("heartbeats", CoinbaseWsChannel::Heartbeats)]
1207    #[case("status", CoinbaseWsChannel::Status)]
1208    fn test_resubscribe_all_channel_mapping(
1209        #[case] topic: &str,
1210        #[case] expected_channel: CoinbaseWsChannel,
1211    ) {
1212        let subs = SubscriptionState::new('|');
1213        subs.mark_subscribe(topic);
1214
1215        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1216        resubscribe_all(&subs, &None, &tx, None);
1217
1218        let cmd = rx.try_recv().unwrap();
1219
1220        match cmd {
1221            HandlerCommand::Subscribe { channel, .. } => {
1222                assert_eq!(channel, expected_channel);
1223            }
1224            other => panic!("Expected Subscribe, was {other:?}"),
1225        }
1226    }
1227
1228    #[rstest]
1229    fn test_protected_subscription_preserves_wire_jwt_and_redacts_command_debug() {
1230        let jwt = "jwt-secret-value";
1231        let subscription = CoinbaseWsSubscription {
1232            msg_type: CoinbaseWsAction::Subscribe,
1233            product_ids: vec![Ustr::from("BTC-USD")],
1234            channel: CoinbaseWsChannel::User,
1235            jwt: Some(SecretString::from(jwt)),
1236        };
1237        let subscription_debug = format!("{subscription:?}");
1238        let protected = protect_subscription(subscription).unwrap();
1239        let payload: serde_json::Value =
1240            serde_json::from_str(protected.payload.expose_secret()).unwrap();
1241        let command = HandlerCommand::Subscribe {
1242            channel: protected.channel,
1243            product_ids: protected.product_ids,
1244            payload: protected.payload,
1245        };
1246        let debug = format!("{command:?}");
1247
1248        assert_eq!(payload["jwt"], jwt);
1249        assert!(subscription_debug.contains(REDACTED));
1250        assert!(!subscription_debug.contains(jwt));
1251        assert!(!debug.contains(jwt));
1252    }
1253
1254    #[rstest]
1255    #[case("user|BTC-USD")]
1256    #[case("futures_balance_summary")]
1257    fn test_resubscribe_all_auth_channel_skipped_without_credentials(#[case] topic: &str) {
1258        let subs = SubscriptionState::new('|');
1259        subs.mark_subscribe(topic);
1260
1261        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1262        resubscribe_all(&subs, &None, &tx, None);
1263
1264        // Auth channels should be skipped when no credentials are provided
1265        assert!(rx.try_recv().is_err());
1266    }
1267
1268    #[rstest]
1269    #[case("user|BTC-USD", "user")]
1270    #[case("futures_balance_summary", "futures_balance_summary")]
1271    fn test_resubscribe_all_emits_error_for_auth_channel_without_credentials(
1272        #[case] topic: &str,
1273        #[case] channel: &str,
1274    ) {
1275        let subs = SubscriptionState::new('|');
1276        subs.mark_subscribe(topic);
1277
1278        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
1279        let (out_tx, mut out_rx) = tokio::sync::mpsc::unbounded_channel();
1280        resubscribe_all(&subs, &None, &cmd_tx, Some(&out_tx));
1281
1282        // No subscribe command should be sent for an unauthenticated auth channel.
1283        assert!(cmd_rx.try_recv().is_err());
1284
1285        let msg = out_rx
1286            .try_recv()
1287            .expect("Error event must be emitted when auth channel cannot resubscribe");
1288        match msg {
1289            NautilusWsMessage::Error(text) => {
1290                assert!(
1291                    text.contains(channel),
1292                    "error must mention the channel, was: {text}"
1293                );
1294                assert!(
1295                    text.contains(topic),
1296                    "error must mention the topic, was: {text}"
1297                );
1298            }
1299            other => panic!("expected Error variant, was {other:?}"),
1300        }
1301    }
1302
1303    #[rstest]
1304    fn test_resubscribe_all_emits_error_when_jwt_build_fails() {
1305        let subs = SubscriptionState::new('|');
1306        let topic = "user|BTC-USD";
1307        subs.mark_subscribe(topic);
1308
1309        // A credential with a malformed PEM secret causes build_ws_jwt() to fail
1310        // every time, exercising the JWT-build error branch.
1311        let bad_credential = Some(CoinbaseCredential::new(
1312            "organizations/test/apiKeys/test".to_string(),
1313            "not-a-pem-key".to_string(),
1314        ));
1315
1316        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
1317        let (out_tx, mut out_rx) = tokio::sync::mpsc::unbounded_channel();
1318        resubscribe_all(&subs, &bad_credential, &cmd_tx, Some(&out_tx));
1319
1320        assert!(cmd_rx.try_recv().is_err(), "no subscribe should be sent");
1321        let msg = out_rx
1322            .try_recv()
1323            .expect("Error event must be emitted when JWT build fails for an auth channel");
1324        match msg {
1325            NautilusWsMessage::Error(text) => {
1326                assert!(text.contains("user"), "error must mention channel: {text}");
1327                assert!(text.contains(topic), "error must mention topic: {text}");
1328            }
1329            other => panic!("expected Error variant, was {other:?}"),
1330        }
1331    }
1332
1333    #[rstest]
1334    fn test_prime_default_subscriptions_marks_heartbeats() {
1335        let client = CoinbaseWebSocketClient::new("wss://test", TransportBackend::default(), None);
1336        assert!(client.subscriptions.all_topics().is_empty());
1337
1338        client.prime_default_subscriptions();
1339
1340        let topics = client.subscriptions.all_topics();
1341        assert!(topics.iter().any(|t| t == "heartbeats"), "{topics:?}");
1342    }
1343
1344    #[rstest]
1345    fn test_ws_quotas_match_documented_limits() {
1346        assert_eq!(COINBASE_WS_CONNECTION_QUOTA.burst_size().get(), 8);
1347        assert_eq!(COINBASE_WS_SUBSCRIPTION_QUOTA.burst_size().get(), 8);
1348    }
1349
1350    #[rstest]
1351    fn test_ws_subscription_rate_limit_key_is_stable() {
1352        assert_eq!(COINBASE_RATE_LIMIT_KEY_SUBSCRIPTION, "subscription");
1353        assert_eq!(
1354            COINBASE_WS_SUBSCRIPTION_KEYS[0],
1355            COINBASE_RATE_LIMIT_KEY_SUBSCRIPTION,
1356        );
1357    }
1358}