1#![expect(
3 clippy::result_large_err,
4 reason = "websocket methods preserve the established unboxed public ClientError contract"
5)]
6use std::collections::BTreeMap;
64use std::sync::{
65 atomic::{AtomicBool, Ordering},
66 Arc, Mutex as StdMutex,
67};
68
69use futures::{SinkExt, StreamExt};
70use sonic_rs::JsonValueTrait;
71use tokio::io::{AsyncRead, AsyncWrite};
72use tokio::net::TcpStream;
73use tokio::sync::{mpsc, oneshot, watch, Mutex, RwLock};
74use tokio::time::Duration;
75use tokio_tungstenite::tungstenite::client::IntoClientRequest;
76use tokio_tungstenite::tungstenite::http::HeaderValue;
77use tokio_tungstenite::{client_async, tungstenite, WebSocketStream};
78use tracing::{debug, info, warn};
79
80use crate::error::{ClientError, Result};
81#[cfg(feature = "rfq-v2")]
82use crate::rfq_v2::encode_rfq_v2_read_grant;
83use crate::wallet::AccountAddress;
84#[cfg(feature = "rfq-v2")]
85use hypercall_sdk_types::rfq_v2::RfqV2ReadGrant;
86use hypercall_sdk_types::ws_protocol::WsMessage;
87use hypercall_ws_protocol::{WsChannel, WsSlowConsumerCloseReason};
88
89const INDICATIVE_CHANNEL: &str = WsChannel::IndicativeMarketData.as_str();
91const INDICATIVE_V2_CHANNEL: &str = WsChannel::IndicativeMarketDataV2.as_str();
93
94#[path = "websocket_deflate_io.rs"]
95mod deflate_io;
96
97use deflate_io::{InflatingStream, PERMESSAGE_DEFLATE_OFFER};
98
99const MAX_CONTROL_FRAME_PAYLOAD_LEN: usize = 125;
100const OUTBOUND_CONTROL_CAPACITY: usize = 256;
101const MAX_FRAME_LEN: usize = 16 << 20;
104const MAX_MESSAGE_LEN: usize = 64 << 20;
106
107trait ClientIo: AsyncRead + AsyncWrite + Send + Unpin {}
109
110impl<T: AsyncRead + AsyncWrite + Send + Unpin> ClientIo for T {}
111
112type ClientSocket = WebSocketStream<InflatingStream<Box<dyn ClientIo>>>;
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct WsClientConfig {
117 pub reconnect_initial_delay: Duration,
118 pub reconnect_max_delay: Duration,
119 pub reconnect_reset_after: Duration,
120 pub authentication_timeout: Duration,
121 pub subscription_timeout: Duration,
122}
123
124impl Default for WsClientConfig {
125 fn default() -> Self {
126 Self {
127 reconnect_initial_delay: Duration::from_millis(500),
128 reconnect_max_delay: Duration::from_secs(30),
129 reconnect_reset_after: Duration::from_secs(30),
130 authentication_timeout: Duration::from_secs(5),
131 subscription_timeout: Duration::from_secs(5),
132 }
133 }
134}
135
136impl WsClientConfig {
137 fn validate(self) -> Result<()> {
138 if self.reconnect_initial_delay.is_zero() {
139 return Err(ClientError::InvalidInput(
140 "reconnect_initial_delay must be positive".to_string(),
141 ));
142 }
143 if self.reconnect_max_delay < self.reconnect_initial_delay {
144 return Err(ClientError::InvalidInput(
145 "reconnect_max_delay must be at least reconnect_initial_delay".to_string(),
146 ));
147 }
148 if self.reconnect_reset_after.is_zero() {
149 return Err(ClientError::InvalidInput(
150 "reconnect_reset_after must be positive".to_string(),
151 ));
152 }
153 if self.authentication_timeout.is_zero() || self.subscription_timeout.is_zero() {
154 return Err(ClientError::InvalidInput(
155 "WebSocket handshake timeouts must be positive".to_string(),
156 ));
157 }
158 Ok(())
159 }
160}
161
162#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
164pub struct WsRecoveryPlan {
165 pub snapshot_resubscribe: bool,
167 pub rest_reconcile: bool,
169 pub portfolio_refetch: bool,
171 pub application_reconcile: bool,
173}
174
175impl WsRecoveryPlan {
176 pub const fn is_empty(self) -> bool {
177 !self.snapshot_resubscribe
178 && !self.rest_reconcile
179 && !self.portfolio_refetch
180 && !self.application_reconcile
181 }
182
183 fn include_channel(&mut self, channel: &str) {
184 match channel {
185 "orderbook" | "trades" | "options_chain" => self.snapshot_resubscribe = true,
186 "portfolio" => {
187 self.portfolio_refetch = true;
188 self.rest_reconcile = true;
189 }
190 "order_updates" | "fills" | "liquidation" | "rfq" => self.rest_reconcile = true,
191 #[cfg(feature = "rfq-v2")]
192 "rfq_v2" => self.rest_reconcile = true,
193 "indicative_market_data"
194 | "indicative_market_data_v2"
195 | "index_prices"
196 | "market_updates" => {}
197 channel if channel.starts_with("candles") => {}
198 _ => self.application_reconcile = true,
199 }
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
205pub enum WsDisconnectReason {
206 SlowConsumer(WsSlowConsumerCloseReason),
207 CloseFrame { code: u16, reason: String },
208 Transport(String),
209 Protocol(String),
210 EndOfStream,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub enum WsConnectionState {
216 Disconnected,
217 Connecting { attempt: u32 },
218 Authenticating,
219 Resubscribing { channels: usize },
220 Reconnecting { attempt: u32, delay: Duration },
221 RecoveryRequired(WsRecoveryPlan),
222 Ready,
223}
224
225impl WsConnectionState {
226 pub const fn transport_connected(&self) -> bool {
227 matches!(self, Self::Ready | Self::RecoveryRequired(_))
228 }
229
230 pub const fn state_recovered(&self) -> bool {
231 matches!(self, Self::Ready)
232 }
233}
234
235#[derive(Debug, Clone)]
236struct DesiredSubscription {
237 channel: String,
238 symbols: Option<Vec<String>>,
239 expiry: Option<String>,
240 option_type: Option<String>,
241 logical_indicative: bool,
245 direct: bool,
249 subscribe: String,
250 unsubscribe: String,
251}
252
253fn canonical_symbols(symbols: Option<&[String]>) -> Option<std::collections::BTreeSet<String>> {
254 let set: std::collections::BTreeSet<String> = symbols?
255 .iter()
256 .map(|symbol| symbol.trim().to_uppercase())
257 .filter(|symbol| !symbol.is_empty())
258 .collect();
259 (!set.is_empty()).then_some(set)
260}
261
262impl DesiredSubscription {
263 fn absorb(&mut self, other: &Self) {
265 self.logical_indicative |= other.logical_indicative;
266 self.direct |= other.direct;
267 }
268
269 fn same_filter(&self, other: &Self) -> bool {
274 self.channel == other.channel
275 && canonical_symbols(self.symbols.as_deref())
276 == canonical_symbols(other.symbols.as_deref())
277 && self.expiry == other.expiry
278 && self.option_type == other.option_type
279 }
280
281 fn new(
282 channel: &str,
283 symbols: Option<Vec<String>>,
284 expiry: Option<String>,
285 option_type: Option<String>,
286 ) -> Result<Self> {
287 let subscribe = sonic_rs::to_string(&WsMessage::Subscribe {
288 channel: channel.to_string(),
289 symbols: symbols.clone(),
290 expiry: expiry.clone(),
291 option_type: option_type.clone(),
292 })?;
293 let unsubscribe = sonic_rs::to_string(&WsMessage::Unsubscribe {
294 channel: channel.to_string(),
295 symbols: symbols.clone(),
296 expiry: expiry.clone(),
297 option_type: option_type.clone(),
298 })?;
299 Ok(Self {
300 channel: channel.to_string(),
301 symbols,
302 expiry,
303 option_type,
304 logical_indicative: false,
305 direct: false,
306 subscribe,
307 unsubscribe,
308 })
309 }
310}
311
312struct WsClientShared {
313 messages: Arc<Mutex<Vec<sonic_rs::Value>>>,
314 pongs: Arc<Mutex<Vec<Vec<u8>>>>,
315 tx: StdMutex<Option<mpsc::Sender<tungstenite::Message>>>,
316 subscriptions: RwLock<BTreeMap<String, DesiredSubscription>>,
317 state: StdMutex<WsConnectionState>,
318 state_tx: watch::Sender<WsConnectionState>,
319 last_disconnect: StdMutex<Option<WsDisconnectReason>>,
320 started: AtomicBool,
321 batched_indicative: AtomicBool,
323 v2_unsupported: AtomicBool,
326 v2_fallback_pending: AtomicBool,
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333enum Release {
334 Keep,
335 Remove,
336}
337
338#[derive(Debug, Clone, Copy)]
340struct ConnectOptions {
341 permessage_deflate: bool,
342}
343
344pub struct WsClient {
346 shared: Arc<WsClientShared>,
347 config: WsClientConfig,
348 options: ConnectOptions,
349 shutdown_tx: StdMutex<Option<watch::Sender<bool>>>,
350}
351
352#[cfg(feature = "rfq-v2")]
353struct RfqV2SocketGrant {
354 token: String,
355 account: String,
356 expires_at_ms: u64,
357}
358
359struct SessionCredentials {
361 wallet: Option<String>,
362 #[cfg(feature = "rfq-v2")]
363 rfq_v2_grant: Option<RfqV2SocketGrant>,
364}
365
366impl SessionCredentials {
367 fn wallet(wallet: Option<String>) -> Self {
368 Self {
369 wallet,
370 #[cfg(feature = "rfq-v2")]
371 rfq_v2_grant: None,
372 }
373 }
374
375 fn rfq_v2_expires_at_ms(&self) -> Option<u64> {
377 #[cfg(feature = "rfq-v2")]
378 {
379 self.rfq_v2_grant.as_ref().map(|grant| grant.expires_at_ms)
380 }
381 #[cfg(not(feature = "rfq-v2"))]
382 {
383 None
384 }
385 }
386}
387
388fn current_unix_ms() -> Option<u64> {
389 std::time::SystemTime::now()
390 .duration_since(std::time::UNIX_EPOCH)
391 .ok()
392 .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok())
393}
394
395impl WsClient {
396 pub fn new() -> Self {
398 Self::with_config(WsClientConfig::default())
399 }
400
401 pub fn with_config(config: WsClientConfig) -> Self {
403 let (state_tx, _) = watch::channel(WsConnectionState::Disconnected);
404 Self {
405 shared: Arc::new(WsClientShared {
406 messages: Arc::new(Mutex::new(Vec::new())),
407 pongs: Arc::new(Mutex::new(Vec::new())),
408 tx: StdMutex::new(None),
409 subscriptions: RwLock::new(BTreeMap::new()),
410 state: StdMutex::new(WsConnectionState::Disconnected),
411 state_tx,
412 last_disconnect: StdMutex::new(None),
413 started: AtomicBool::new(false),
414 batched_indicative: AtomicBool::new(true),
415 v2_unsupported: AtomicBool::new(false),
416 v2_fallback_pending: AtomicBool::new(false),
417 }),
418 config,
419 options: ConnectOptions {
420 permessage_deflate: true,
421 },
422 shutdown_tx: StdMutex::new(None),
423 }
424 }
425
426 pub fn with_permessage_deflate(mut self, enabled: bool) -> Self {
434 self.options.permessage_deflate = enabled;
435 self
436 }
437
438 pub fn with_batched_indicative(self, enabled: bool) -> Self {
445 self.shared
446 .batched_indicative
447 .store(enabled, Ordering::Release);
448 self
449 }
450
451 pub fn indicative_batched(&self) -> bool {
454 self.shared.batched_indicative.load(Ordering::Acquire)
455 && !self.shared.v2_unsupported.load(Ordering::Acquire)
456 }
457
458 pub async fn connect(&self, base_url: &str, wallet: Option<&AccountAddress>) -> Result<()> {
466 self.start_session(
467 base_url,
468 SessionCredentials::wallet(wallet.map(ToString::to_string)),
469 )
470 .await
471 }
472
473 #[cfg(feature = "rfq-v2")]
477 pub async fn connect_rfq_v2(&self, base_url: &str, grant: &RfqV2ReadGrant) -> Result<()> {
478 self.start_session(
479 base_url,
480 SessionCredentials {
481 wallet: None,
482 rfq_v2_grant: Some(RfqV2SocketGrant {
483 token: encode_rfq_v2_read_grant(grant)?,
484 account: grant.account.to_string(),
485 expires_at_ms: grant.expires_at_ms,
486 }),
487 },
488 )
489 .await
490 }
491
492 async fn start_session(&self, base_url: &str, credentials: SessionCredentials) -> Result<()> {
493 self.config.validate()?;
494 let ws_url = websocket_url(base_url)?;
495 if self
496 .shared
497 .started
498 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
499 .is_err()
500 {
501 return Err(ClientError::WebSocket(
502 "WebSocket client is already connected or connecting".to_string(),
503 ));
504 }
505
506 let (shutdown_tx, shutdown_rx) = watch::channel(false);
507 *self
508 .shutdown_tx
509 .lock()
510 .expect("WebSocket shutdown mutex poisoned") = Some(shutdown_tx);
511 let (initial_tx, initial_rx) = oneshot::channel();
512 let shared = self.shared.clone();
513 let config = self.config;
514 let options = self.options;
515 tokio::spawn(async move {
516 run_ws_session(
517 shared,
518 config,
519 ws_url,
520 options,
521 credentials,
522 shutdown_rx,
523 initial_tx,
524 )
525 .await;
526 });
527
528 initial_rx.await.map_err(|_| {
529 ClientError::WebSocket("WebSocket connection task stopped before startup".to_string())
530 })?
531 }
532
533 fn validate_control_payload(payload: &[u8]) -> Result<()> {
534 if payload.len() > MAX_CONTROL_FRAME_PAYLOAD_LEN {
535 return Err(ClientError::WebSocket(format!(
536 "WebSocket control frame payload exceeds {} bytes",
537 MAX_CONTROL_FRAME_PAYLOAD_LEN
538 )));
539 }
540
541 Ok(())
542 }
543
544 async fn send_control_frame(&self, msg: tungstenite::Message) -> Result<()> {
545 let tx = self
546 .shared
547 .tx
548 .lock()
549 .expect("WebSocket sender mutex poisoned")
550 .clone()
551 .ok_or(ClientError::WebSocket("Not connected".to_string()))?;
552
553 tx.send(msg)
554 .await
555 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))
556 }
557
558 pub async fn ping(&self) -> Result<()> {
560 self.ping_with_payload(Vec::new()).await
561 }
562
563 pub async fn ping_with_payload(&self, payload: impl Into<Vec<u8>>) -> Result<()> {
567 let payload = payload.into();
568 Self::validate_control_payload(&payload)?;
569 self.send_control_frame(tungstenite::Message::Ping(payload))
570 .await
571 }
572
573 pub async fn pong_with_payload(&self, payload: impl Into<Vec<u8>>) -> Result<()> {
578 let payload = payload.into();
579 Self::validate_control_payload(&payload)?;
580 self.send_control_frame(tungstenite::Message::Pong(payload))
581 .await
582 }
583
584 pub async fn subscribe(&self, channels: Vec<&str>) -> Result<()> {
586 for channel in channels {
587 self.subscribe_with_options(channel, None, None, None)
588 .await?;
589 }
590
591 Ok(())
592 }
593
594 #[cfg(feature = "rfq-v2")]
599 pub async fn subscribe_rfq_v2(&self) -> Result<()> {
600 self.subscribe_with_options("rfq_v2", None, None, None)
601 .await
602 }
603
604 #[cfg(feature = "rfq-v2")]
606 pub async fn unsubscribe_rfq_v2(&self) -> Result<()> {
607 self.unsubscribe(vec!["rfq_v2"]).await
608 }
609
610 pub async fn subscribe_with_options(
612 &self,
613 channel: &str,
614 symbols: Option<Vec<String>>,
615 expiry: Option<String>,
616 option_type: Option<String>,
617 ) -> Result<()> {
618 self.subscribe_desired(channel, symbols, expiry, option_type)
619 .await
620 }
621
622 pub async fn subscribe_indicative_market_data(
639 &self,
640 symbols: Option<Vec<String>>,
641 ) -> Result<()> {
642 let channel = if self.indicative_batched() {
643 INDICATIVE_V2_CHANNEL
644 } else {
645 INDICATIVE_CHANNEL
646 };
647 self.subscribe_desired_with(channel, symbols, None, None, true)
648 .await
649 }
650
651 pub async fn unsubscribe_indicative_market_data(&self) -> Result<()> {
657 self.release_where(|subscription| {
658 if !subscription.logical_indicative {
659 return Release::Keep;
660 }
661 subscription.logical_indicative = false;
662 if subscription.direct {
663 Release::Keep
664 } else {
665 Release::Remove
666 }
667 })
668 .await
669 }
670
671 async fn subscribe_desired(
672 &self,
673 channel: &str,
674 symbols: Option<Vec<String>>,
675 expiry: Option<String>,
676 option_type: Option<String>,
677 ) -> Result<()> {
678 self.subscribe_desired_with(channel, symbols, expiry, option_type, false)
679 .await
680 }
681
682 async fn subscribe_desired_with(
683 &self,
684 channel: &str,
685 symbols: Option<Vec<String>>,
686 expiry: Option<String>,
687 option_type: Option<String>,
688 logical_indicative: bool,
689 ) -> Result<()> {
690 if !self.shared.started.load(Ordering::Acquire) {
691 return Err(ClientError::WebSocket("Not connected".to_string()));
692 }
693
694 let mut desired = DesiredSubscription::new(channel, symbols, expiry, option_type)?;
695 desired.logical_indicative = logical_indicative;
696 desired.direct = !logical_indicative;
697 let frame = tungstenite::Message::Text(desired.subscribe.clone());
698 {
699 let mut subscriptions = self.shared.subscriptions.write().await;
700 for existing in subscriptions.values() {
705 if desired.same_filter(existing) {
706 desired.absorb(existing);
707 }
708 }
709 subscriptions.retain(|_, existing| !desired.same_filter(existing));
710 subscriptions.insert(desired.subscribe.clone(), desired);
711 }
712
713 let tx = self
714 .shared
715 .tx
716 .lock()
717 .expect("WebSocket sender mutex poisoned")
718 .clone();
719 if let Some(tx) = tx {
720 debug!("Subscribing to: {}", channel);
721 tx.send(frame)
722 .await
723 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
724 }
725
726 Ok(())
727 }
728
729 pub async fn unsubscribe(&self, channels: Vec<&str>) -> Result<()> {
739 for channel in channels {
740 self.release_where(|subscription| {
743 if subscription.channel != channel {
744 return Release::Keep;
745 }
746 subscription.direct = false;
747 if subscription.logical_indicative {
748 Release::Keep
749 } else {
750 Release::Remove
751 }
752 })
753 .await?;
754 }
755 Ok(())
756 }
757
758 async fn release_where(
761 &self,
762 release: impl Fn(&mut DesiredSubscription) -> Release,
763 ) -> Result<()> {
764 if !self.shared.started.load(Ordering::Acquire) {
765 return Err(ClientError::WebSocket("Not connected".to_string()));
766 }
767
768 let removed = {
769 let mut subscriptions = self.shared.subscriptions.write().await;
770 let keys = subscriptions
771 .iter_mut()
772 .filter_map(|(key, subscription)| {
773 (release(subscription) == Release::Remove).then(|| key.clone())
774 })
775 .collect::<Vec<_>>();
776 keys.into_iter()
777 .filter_map(|key| subscriptions.remove(&key))
778 .collect::<Vec<_>>()
779 };
780 for removed in removed {
781 let tx = self
782 .shared
783 .tx
784 .lock()
785 .expect("WebSocket sender mutex poisoned")
786 .clone();
787 if let Some(tx) = tx {
788 tx.send(tungstenite::Message::Text(removed.unsubscribe))
789 .await
790 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
791 }
792 }
793 Ok(())
794 }
795
796 pub async fn disconnect(&self) {
798 let _ = self
799 .send_control_frame(tungstenite::Message::Close(None))
800 .await;
801 if let Some(shutdown_tx) = self
802 .shutdown_tx
803 .lock()
804 .expect("WebSocket shutdown mutex poisoned")
805 .take()
806 {
807 let _ = shutdown_tx.send(true);
808 }
809 }
810
811 pub fn connection_state(&self) -> WsConnectionState {
813 self.shared
814 .state
815 .lock()
816 .expect("WebSocket state mutex poisoned")
817 .clone()
818 }
819
820 pub fn connection_state_receiver(&self) -> watch::Receiver<WsConnectionState> {
822 self.shared.state_tx.subscribe()
823 }
824
825 pub fn last_disconnect_reason(&self) -> Option<WsDisconnectReason> {
827 self.shared
828 .last_disconnect
829 .lock()
830 .expect("WebSocket disconnect mutex poisoned")
831 .clone()
832 }
833
834 pub fn mark_recovered(&self) -> Result<()> {
836 let mut state = self
837 .shared
838 .state
839 .lock()
840 .expect("WebSocket state mutex poisoned");
841 if !matches!(*state, WsConnectionState::RecoveryRequired(_)) {
842 return Err(ClientError::WebSocket(
843 "No WebSocket recovery is currently required".to_string(),
844 ));
845 }
846 *state = WsConnectionState::Ready;
847 self.shared.state_tx.send_replace(WsConnectionState::Ready);
848 Ok(())
849 }
850
851 pub async fn get_pongs(&self) -> Vec<Vec<u8>> {
853 self.shared.pongs.lock().await.clone()
854 }
855
856 pub async fn clear_pongs(&self) {
858 self.shared.pongs.lock().await.clear();
859 }
860
861 pub async fn wait_for_pong<F>(&self, check: F, timeout_ms: u64) -> Option<Vec<u8>>
863 where
864 F: Fn(&[u8]) -> bool,
865 {
866 let start = std::time::Instant::now();
867 let timeout = Duration::from_millis(timeout_ms);
868
869 while start.elapsed() < timeout {
870 let pongs = self.get_pongs().await;
871 if let Some(pong) = pongs.iter().find(|payload| check(payload)) {
872 return Some(pong.clone());
873 }
874 tokio::time::sleep(Duration::from_millis(50)).await;
875 }
876
877 None
878 }
879
880 pub async fn get_messages(&self) -> Vec<sonic_rs::Value> {
882 self.shared.messages.lock().await.clone()
883 }
884
885 pub async fn clear_messages(&self) {
887 self.shared.messages.lock().await.clear();
888 }
889
890 pub async fn wait_for_message<F>(&self, check: F, timeout_ms: u64) -> Option<sonic_rs::Value>
892 where
893 F: Fn(&sonic_rs::Value) -> bool,
894 {
895 let start = std::time::Instant::now();
896 let timeout = Duration::from_millis(timeout_ms);
897
898 while start.elapsed() < timeout {
899 let messages = self.get_messages().await;
900 if let Some(msg) = messages.iter().find(|m| check(m)) {
901 return Some(msg.clone());
902 }
903 tokio::time::sleep(Duration::from_millis(50)).await;
904 }
905
906 None
907 }
908
909 pub async fn count_messages<F>(&self, check: F) -> usize
911 where
912 F: Fn(&sonic_rs::Value) -> bool,
913 {
914 self.get_messages()
915 .await
916 .iter()
917 .filter(|msg| check(msg))
918 .count()
919 }
920}
921
922impl Drop for WsClient {
923 fn drop(&mut self) {
924 if let Some(shutdown_tx) = self
925 .shutdown_tx
926 .lock()
927 .expect("WebSocket shutdown mutex poisoned")
928 .take()
929 {
930 let _ = shutdown_tx.send(true);
931 }
932 }
933}
934
935#[derive(Debug, Clone)]
936enum SessionStop {
937 Shutdown,
938 Disconnected(WsDisconnectReason),
939 NonReconnectable(WsDisconnectReason),
940}
941
942impl SessionStop {
943 fn websocket_error(&self, context: &str) -> ClientError {
944 match self {
945 Self::Shutdown => ClientError::WebSocket(format!("{}: client stopped", context)),
946 Self::Disconnected(reason) | Self::NonReconnectable(reason) => {
947 ClientError::WebSocket(format!("{}: {:?}", context, reason))
948 }
949 }
950 }
951}
952
953fn websocket_url(base_url: &str) -> Result<String> {
954 let base_url = base_url.trim_end_matches('/');
955 let ws_origin = if let Some(rest) = base_url.strip_prefix("https://") {
956 format!("wss://{}", rest)
957 } else if let Some(rest) = base_url.strip_prefix("http://") {
958 format!("ws://{}", rest)
959 } else if base_url.starts_with("wss://") || base_url.starts_with("ws://") {
960 base_url.to_string()
961 } else {
962 return Err(ClientError::InvalidInput(
963 "WebSocket base URL must use http, https, ws, or wss".to_string(),
964 ));
965 };
966
967 if ws_origin.ends_with("/ws") {
968 Ok(ws_origin)
969 } else {
970 Ok(format!("{}/ws", ws_origin))
971 }
972}
973
974#[derive(Debug, thiserror::Error)]
977#[displaystr::display]
978enum ConnectError {
979 Url(#[source] tungstenite::Error) = "invalid WebSocket URL: {_0}",
980 MissingHost = "WebSocket URL has no host",
981 UnsupportedScheme = "WebSocket URL must use ws or wss",
982 Tcp(#[source] std::io::Error) = "IO error: {_0}",
983 Tls(#[source] tokio_native_tls::native_tls::Error) = "TLS error: {_0}",
984 Handshake(#[source] tungstenite::Error) = "{_0}",
987}
988
989async fn connect_socket(
992 ws_url: &str,
993 options: ConnectOptions,
994) -> std::result::Result<(ClientSocket, tungstenite::handshake::client::Response), ConnectError> {
995 let permessage_deflate = options.permessage_deflate;
996 let mut request = ws_url.into_client_request().map_err(ConnectError::Url)?;
997 if permessage_deflate {
998 request.headers_mut().insert(
999 "Sec-WebSocket-Extensions",
1000 HeaderValue::from_static(PERMESSAGE_DEFLATE_OFFER),
1001 );
1002 }
1003 let uri = request.uri();
1004 let host = uri.host().ok_or(ConnectError::MissingHost)?.to_string();
1005 let tls = match uri.scheme_str() {
1006 Some("wss") => true,
1007 Some("ws") => false,
1008 _ => return Err(ConnectError::UnsupportedScheme),
1009 };
1010 let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
1011 let tcp = TcpStream::connect(format!("{host}:{port}"))
1012 .await
1013 .map_err(ConnectError::Tcp)?;
1014
1015 let io: Box<dyn ClientIo> = if tls {
1016 let domain = host.trim_start_matches('[').trim_end_matches(']');
1017 let connector =
1018 tokio_native_tls::native_tls::TlsConnector::new().map_err(ConnectError::Tls)?;
1019 let stream = tokio_native_tls::TlsConnector::from(connector)
1020 .connect(domain, tcp)
1021 .await
1022 .map_err(ConnectError::Tls)?;
1023 Box::new(stream)
1024 } else {
1025 Box::new(tcp)
1026 };
1027
1028 let stream = InflatingStream::new(io, permessage_deflate, MAX_FRAME_LEN, MAX_MESSAGE_LEN);
1029 client_async(request, stream)
1030 .await
1031 .map_err(ConnectError::Handshake)
1032}
1033
1034fn reconnect_delay(config: WsClientConfig, attempt: u32) -> Duration {
1035 let multiplier = 1_u32 << attempt.min(31);
1036 let ceiling = config
1037 .reconnect_initial_delay
1038 .saturating_mul(multiplier)
1039 .min(config.reconnect_max_delay);
1040 ceiling.mul_f64(0.5 + rand::random::<f64>() * 0.5)
1041}
1042
1043fn set_state(shared: &WsClientShared, next: WsConnectionState) {
1044 *shared.state.lock().expect("WebSocket state mutex poisoned") = next.clone();
1045 shared.state_tx.send_replace(next);
1046}
1047
1048fn finish_session(shared: &WsClientShared) {
1049 *shared.tx.lock().expect("WebSocket sender mutex poisoned") = None;
1050 shared.started.store(false, Ordering::Release);
1051 set_state(shared, WsConnectionState::Disconnected);
1052}
1053
1054fn record_disconnect(shared: &WsClientShared, reason: WsDisconnectReason) {
1055 *shared
1056 .last_disconnect
1057 .lock()
1058 .expect("WebSocket disconnect mutex poisoned") = Some(reason);
1059}
1060
1061async fn record_text(shared: &WsClientShared, text: &str) -> Option<sonic_rs::Value> {
1062 debug!("WS received: {}", text);
1063 let json = sonic_rs::from_str::<sonic_rs::Value>(text).ok()?;
1064 if is_unbatched_v2_confirmation(&json) {
1065 warn!("server lacks indicative_market_data_v2; falling back to indicative_market_data");
1068 shared.v2_unsupported.store(true, Ordering::Release);
1069 shared.v2_fallback_pending.store(true, Ordering::Release);
1070 }
1071 shared.messages.lock().await.push(json.clone());
1072 Some(json)
1073}
1074
1075fn is_unbatched_v2_confirmation(json: &sonic_rs::Value) -> bool {
1079 let channel_is_v2 =
1080 json.get("channel").and_then(|value| value.as_str()) == Some(INDICATIVE_V2_CHANNEL);
1081 match json.get("type").and_then(|value| value.as_str()) {
1082 Some("Subscribed") => {
1083 channel_is_v2 && json.get("batch").and_then(|value| value.as_bool()) != Some(true)
1084 }
1085 Some("Error") => {
1086 channel_is_v2
1087 && json.get("code").and_then(|value| value.as_str())
1088 == Some(hypercall_ws_protocol::UNKNOWN_CHANNEL_CODE)
1089 }
1090 _ => false,
1091 }
1092}
1093
1094async fn take_v2_fallback(
1101 shared: &WsClientShared,
1102) -> std::result::Result<(Vec<String>, BTreeMap<String, DesiredSubscription>), SessionStop> {
1103 let mut subscriptions = shared.subscriptions.write().await;
1104 take_v2_fallback_locked(shared, &mut subscriptions)
1105}
1106
1107fn take_v2_fallback_locked(
1110 shared: &WsClientShared,
1111 subscriptions: &mut BTreeMap<String, DesiredSubscription>,
1112) -> std::result::Result<(Vec<String>, BTreeMap<String, DesiredSubscription>), SessionStop> {
1113 let mut unsubscribes = Vec::new();
1114 let mut replacements = BTreeMap::new();
1115 if !shared.v2_fallback_pending.swap(false, Ordering::AcqRel) {
1116 return Ok((unsubscribes, replacements));
1117 }
1118 let v2_keys: Vec<String> = subscriptions
1119 .iter()
1120 .filter(|(_, desired)| {
1121 desired.channel == INDICATIVE_V2_CHANNEL && desired.logical_indicative
1122 })
1123 .map(|(key, _)| key.clone())
1124 .collect();
1125 for key in v2_keys {
1126 let Some(mut v2) = subscriptions.remove(&key) else {
1127 continue;
1128 };
1129 if v2.direct {
1130 v2.logical_indicative = false;
1134 subscriptions.insert(key, v2.clone());
1135 } else {
1136 unsubscribes.push(v2.unsubscribe.clone());
1137 }
1138 let mut v1 = DesiredSubscription::new(
1139 INDICATIVE_CHANNEL,
1140 v2.symbols.clone(),
1141 v2.expiry.clone(),
1142 v2.option_type.clone(),
1143 )
1144 .map_err(|error| {
1145 SessionStop::Disconnected(WsDisconnectReason::Protocol(error.to_string()))
1146 })?;
1147 v1.logical_indicative = true;
1148 for existing in subscriptions.values() {
1151 if v1.same_filter(existing) {
1152 v1.absorb(existing);
1153 }
1154 }
1155 subscriptions.retain(|_, existing| !v1.same_filter(existing));
1156 subscriptions.insert(v1.subscribe.clone(), v1.clone());
1157 replacements.insert(v1.subscribe.clone(), v1);
1158 }
1159 Ok((unsubscribes, replacements))
1160}
1161
1162async fn apply_v2_fallback<S>(
1165 socket: &mut S,
1166 shared: &WsClientShared,
1167) -> std::result::Result<(), SessionStop>
1168where
1169 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error> + Unpin,
1170{
1171 let (unsubscribes, replacements) = take_v2_fallback(shared).await?;
1172 let frames = unsubscribes.into_iter().chain(
1173 replacements
1174 .into_values()
1175 .map(|replacement| replacement.subscribe),
1176 );
1177 for frame in frames {
1178 socket
1179 .send(tungstenite::Message::Text(frame))
1180 .await
1181 .map_err(|error| {
1182 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1183 })?;
1184 }
1185 Ok(())
1186}
1187
1188fn disconnect_reason_from_close(
1189 frame: Option<tungstenite::protocol::CloseFrame<'_>>,
1190) -> WsDisconnectReason {
1191 let Some(frame) = frame else {
1192 return WsDisconnectReason::EndOfStream;
1193 };
1194 let reason = frame.reason.into_owned();
1195 if let Ok(slow_consumer) = serde_json::from_str::<WsSlowConsumerCloseReason>(&reason) {
1196 return WsDisconnectReason::SlowConsumer(slow_consumer);
1197 }
1198
1199 WsDisconnectReason::CloseFrame {
1200 code: frame.code.into(),
1201 reason,
1202 }
1203}
1204
1205async fn authenticate_socket<S>(
1206 socket: &mut S,
1207 shared: &WsClientShared,
1208 wallet: &str,
1209 shutdown_rx: &mut watch::Receiver<bool>,
1210 timeout: Duration,
1211) -> std::result::Result<(), SessionStop>
1212where
1213 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1214 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1215 + Unpin,
1216{
1217 let auth_msg = sonic_rs::to_string(&WsMessage::Authenticate {
1218 wallet: wallet.to_string(),
1219 })
1220 .map_err(|error| {
1221 SessionStop::Disconnected(WsDisconnectReason::Protocol(format!(
1222 "failed to serialize authentication: {}",
1223 error
1224 )))
1225 })?;
1226 socket
1227 .send(tungstenite::Message::Text(auth_msg))
1228 .await
1229 .map_err(|error| {
1230 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1231 })?;
1232
1233 let deadline = tokio::time::sleep(timeout);
1234 tokio::pin!(deadline);
1235 loop {
1236 tokio::select! {
1237 changed = shutdown_rx.changed() => {
1238 if changed.is_err() || *shutdown_rx.borrow() {
1239 return Err(SessionStop::Shutdown);
1240 }
1241 }
1242 _ = &mut deadline => {
1243 return Err(SessionStop::Disconnected(WsDisconnectReason::Protocol(
1244 "timed out waiting for authentication response".to_string(),
1245 )));
1246 }
1247 incoming = socket.next() => {
1248 match incoming {
1249 Some(Ok(tungstenite::Message::Text(text))) => {
1250 let Some(json) = record_text(shared, &text).await else {
1251 continue;
1252 };
1253 match json.get("type").and_then(|value| value.as_str()) {
1254 Some("Authenticated") => {
1255 let authenticated_wallet = json
1256 .get("wallet")
1257 .and_then(|value| value.as_str())
1258 .ok_or_else(|| SessionStop::Disconnected(
1259 WsDisconnectReason::Protocol(
1260 "authentication response omitted wallet".to_string(),
1261 )
1262 ))?;
1263 if !authenticated_wallet.eq_ignore_ascii_case(wallet) {
1264 return Err(SessionStop::Disconnected(
1265 WsDisconnectReason::Protocol(format!(
1266 "authenticated wallet mismatch: expected {}, received {}",
1267 wallet, authenticated_wallet
1268 )),
1269 ));
1270 }
1271 return Ok(());
1272 }
1273 Some("Error") => {
1274 let message = json
1275 .get("message")
1276 .and_then(|value| value.as_str())
1277 .unwrap_or("authentication failed");
1278 return Err(SessionStop::Disconnected(
1279 WsDisconnectReason::Protocol(message.to_string()),
1280 ));
1281 }
1282 _ => {}
1283 }
1284 }
1285 Some(Ok(tungstenite::Message::Ping(payload))) => {
1286 socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
1287 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1288 })?;
1289 }
1290 Some(Ok(tungstenite::Message::Pong(payload))) => {
1291 shared.pongs.lock().await.push(payload);
1292 }
1293 Some(Ok(tungstenite::Message::Close(frame))) => {
1294 return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
1295 }
1296 Some(Err(error)) => {
1297 return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(
1298 error.to_string(),
1299 )));
1300 }
1301 None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
1302 _ => {}
1303 }
1304 }
1305 }
1306 }
1307}
1308
1309#[cfg(feature = "rfq-v2")]
1310async fn authenticate_rfq_v2_socket<S>(
1311 socket: &mut S,
1312 shared: &WsClientShared,
1313 grant: &RfqV2SocketGrant,
1314 shutdown_rx: &mut watch::Receiver<bool>,
1315 timeout: Duration,
1316) -> std::result::Result<(), SessionStop>
1317where
1318 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1319 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1320 + Unpin,
1321{
1322 let auth_msg = sonic_rs::to_string(&WsMessage::AuthenticateRfqV2 {
1323 token: grant.token.clone(),
1324 })
1325 .map_err(|error| {
1326 SessionStop::NonReconnectable(WsDisconnectReason::Protocol(format!(
1327 "failed to serialize RFQ authentication: {error}"
1328 )))
1329 })?;
1330 socket
1331 .send(tungstenite::Message::Text(auth_msg))
1332 .await
1333 .map_err(|error| {
1334 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1335 })?;
1336
1337 let deadline = tokio::time::sleep(timeout);
1338 tokio::pin!(deadline);
1339 loop {
1340 tokio::select! {
1341 changed = shutdown_rx.changed() => {
1342 if changed.is_err() || *shutdown_rx.borrow() {
1343 return Err(SessionStop::Shutdown);
1344 }
1345 }
1346 _ = &mut deadline => {
1347 return Err(SessionStop::Disconnected(WsDisconnectReason::Protocol(
1348 "timed out waiting for RFQ authentication response".to_string(),
1349 )));
1350 }
1351 incoming = socket.next() => {
1352 match incoming {
1353 Some(Ok(tungstenite::Message::Text(text))) => {
1354 let Some(json) = record_text(shared, &text).await else {
1355 continue;
1356 };
1357 match json.get("type").and_then(|value| value.as_str()) {
1358 Some("RfqV2Authenticated") => {
1359 let account = json
1360 .get("account")
1361 .and_then(|value| value.as_str())
1362 .ok_or_else(|| SessionStop::NonReconnectable(
1363 WsDisconnectReason::Protocol(
1364 "RFQ authentication response omitted account".to_string(),
1365 )
1366 ))?;
1367 if !account.eq_ignore_ascii_case(&grant.account) {
1368 return Err(SessionStop::NonReconnectable(
1369 WsDisconnectReason::Protocol(
1370 "RFQ authenticated account does not match signed grant".to_string(),
1371 ),
1372 ));
1373 }
1374 return Ok(());
1375 }
1376 Some("Error") => {
1377 let message = json
1378 .get("message")
1379 .and_then(|value| value.as_str())
1380 .unwrap_or("RFQ authentication failed");
1381 return Err(SessionStop::NonReconnectable(
1382 WsDisconnectReason::Protocol(message.to_string()),
1383 ));
1384 }
1385 _ => {}
1386 }
1387 }
1388 Some(Ok(tungstenite::Message::Ping(payload))) => {
1389 socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
1390 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1391 })?;
1392 }
1393 Some(Ok(tungstenite::Message::Pong(payload))) => {
1394 shared.pongs.lock().await.push(payload);
1395 }
1396 Some(Ok(tungstenite::Message::Close(frame))) => {
1397 return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
1398 }
1399 Some(Err(error)) => {
1400 return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string())));
1401 }
1402 None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
1403 _ => {}
1404 }
1405 }
1406 }
1407 }
1408}
1409
1410async fn replay_subscriptions<S>(
1411 socket: &mut S,
1412 shared: &WsClientShared,
1413 subscriptions: &BTreeMap<String, DesiredSubscription>,
1414 shutdown_rx: &mut watch::Receiver<bool>,
1415 timeout: Duration,
1416) -> std::result::Result<(), SessionStop>
1417where
1418 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1419 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1420 + Unpin,
1421{
1422 let mut pending = BTreeMap::<String, usize>::new();
1423 for subscription in subscriptions.values() {
1424 socket
1425 .send(tungstenite::Message::Text(subscription.subscribe.clone()))
1426 .await
1427 .map_err(|error| {
1428 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1429 })?;
1430 *pending.entry(subscription.channel.clone()).or_default() += 1;
1431 }
1432
1433 let deadline = tokio::time::sleep(timeout);
1434 tokio::pin!(deadline);
1435 while !pending.is_empty() {
1436 tokio::select! {
1437 changed = shutdown_rx.changed() => {
1438 if changed.is_err() || *shutdown_rx.borrow() {
1439 return Err(SessionStop::Shutdown);
1440 }
1441 }
1442 _ = &mut deadline => {
1443 return Err(SessionStop::NonReconnectable(WsDisconnectReason::Protocol(format!(
1444 "timed out restoring subscriptions: {}",
1445 pending
1446 .into_iter()
1447 .map(|(channel, count)| format!("{} ({})", channel, count))
1448 .collect::<Vec<_>>()
1449 .join(", ")
1450 ))));
1451 }
1452 incoming = socket.next() => {
1453 match incoming {
1454 Some(Ok(tungstenite::Message::Text(text))) => {
1455 let Some(json) = record_text(shared, &text).await else {
1456 continue;
1457 };
1458 let v2_refusal = is_unbatched_v2_confirmation(&json);
1463 let v2_all_logical = subscriptions
1464 .values()
1465 .filter(|desired| desired.channel == INDICATIVE_V2_CHANNEL)
1466 .all(|desired| desired.logical_indicative && !desired.direct);
1467 if v2_refusal && !v2_all_logical {
1468 return Err(SessionStop::NonReconnectable(
1469 WsDisconnectReason::Protocol(format!(
1470 "server does not support {INDICATIVE_V2_CHANNEL}; \
1471 direct subscriptions to it cannot be restored"
1472 )),
1473 ));
1474 }
1475 match json.get("type").and_then(|value| value.as_str()) {
1476 Some("Subscribed") => {
1477 if let Some(channel) = json.get("channel").and_then(|value| value.as_str()) {
1478 if let Some(count) = pending.get_mut(channel) {
1479 *count -= 1;
1480 if *count == 0 {
1481 pending.remove(channel);
1482 }
1483 }
1484 }
1485 }
1486 Some("Error") if v2_refusal => {
1489 if let Some(count) = pending.get_mut(INDICATIVE_V2_CHANNEL) {
1490 *count -= 1;
1491 if *count == 0 {
1492 pending.remove(INDICATIVE_V2_CHANNEL);
1493 }
1494 }
1495 }
1496 Some("Error") => {
1497 let message = json
1498 .get("message")
1499 .and_then(|value| value.as_str())
1500 .unwrap_or("subscription restoration failed");
1501 return Err(SessionStop::NonReconnectable(
1502 WsDisconnectReason::Protocol(message.to_string()),
1503 ));
1504 }
1505 _ => {}
1506 }
1507 }
1508 Some(Ok(tungstenite::Message::Ping(payload))) => {
1509 socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
1510 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1511 })?;
1512 }
1513 Some(Ok(tungstenite::Message::Pong(payload))) => {
1514 shared.pongs.lock().await.push(payload);
1515 }
1516 Some(Ok(tungstenite::Message::Close(frame))) => {
1517 return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
1518 }
1519 Some(Err(error)) => {
1520 return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(
1521 error.to_string(),
1522 )));
1523 }
1524 None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
1525 _ => {}
1526 }
1527 }
1528 }
1529 }
1530 Ok(())
1531}
1532
1533async fn run_connected_socket<S>(
1534 socket: &mut S,
1535 shared: &WsClientShared,
1536 outbound_rx: &mut mpsc::Receiver<tungstenite::Message>,
1537 shutdown_rx: &mut watch::Receiver<bool>,
1538 rfq_v2_expires_at_ms: Option<u64>,
1539) -> SessionStop
1540where
1541 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1542 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1543 + Unpin,
1544{
1545 let grant_expiry = async {
1546 if let Some(expires_at_ms) = rfq_v2_expires_at_ms {
1547 let remaining_ms = current_unix_ms().map_or(0, |now| expires_at_ms.saturating_sub(now));
1548 tokio::time::sleep(Duration::from_millis(remaining_ms)).await;
1549 } else {
1550 std::future::pending::<()>().await;
1551 }
1552 };
1553 tokio::pin!(grant_expiry);
1554 loop {
1555 tokio::select! {
1556 _ = &mut grant_expiry => {
1557 let _ = socket.send(tungstenite::Message::Close(None)).await;
1558 return SessionStop::NonReconnectable(WsDisconnectReason::Protocol(
1559 "RFQ V2 read grant expired; sign a fresh grant".to_string(),
1560 ));
1561 }
1562 changed = shutdown_rx.changed() => {
1563 if changed.is_err() || *shutdown_rx.borrow() {
1564 let _ = socket.send(tungstenite::Message::Close(None)).await;
1565 return SessionStop::Shutdown;
1566 }
1567 }
1568 outbound = outbound_rx.recv() => {
1569 let Some(outbound) = outbound else {
1570 return SessionStop::Shutdown;
1571 };
1572 if let Err(error) = socket.send(outbound).await {
1573 return SessionStop::Disconnected(WsDisconnectReason::Transport(
1574 error.to_string(),
1575 ));
1576 }
1577 }
1578 incoming = socket.next() => {
1579 match incoming {
1580 Some(Ok(tungstenite::Message::Text(text))) => {
1581 let _ = record_text(shared, &text).await;
1582 if let Err(stop) = apply_v2_fallback(socket, shared).await {
1583 return stop;
1584 }
1585 }
1586 Some(Ok(tungstenite::Message::Ping(payload))) => {
1587 if let Err(error) = socket.send(tungstenite::Message::Pong(payload)).await {
1588 return SessionStop::Disconnected(WsDisconnectReason::Transport(
1589 error.to_string(),
1590 ));
1591 }
1592 }
1593 Some(Ok(tungstenite::Message::Pong(payload))) => {
1594 shared.pongs.lock().await.push(payload);
1595 }
1596 Some(Ok(tungstenite::Message::Close(frame))) => {
1597 return SessionStop::Disconnected(disconnect_reason_from_close(frame));
1598 }
1599 Some(Err(error)) => {
1600 return SessionStop::Disconnected(WsDisconnectReason::Transport(
1601 error.to_string(),
1602 ));
1603 }
1604 None => return SessionStop::Disconnected(WsDisconnectReason::EndOfStream),
1605 _ => {}
1606 }
1607 }
1608 }
1609 }
1610}
1611
1612#[expect(clippy::too_many_lines, reason = "pre-existing; split pending")]
1613async fn run_ws_session(
1614 shared: Arc<WsClientShared>,
1615 config: WsClientConfig,
1616 ws_url: String,
1617 options: ConnectOptions,
1618 credentials: SessionCredentials,
1619 mut shutdown_rx: watch::Receiver<bool>,
1620 initial_tx: oneshot::Sender<Result<()>>,
1621) {
1622 let mut initial_tx = Some(initial_tx);
1623 let mut reconnecting = false;
1624 let mut attempt = 0_u32;
1625
1626 loop {
1627 if reconnecting {
1628 let delay = reconnect_delay(config, attempt);
1629 set_state(&shared, WsConnectionState::Reconnecting { attempt, delay });
1630 tokio::select! {
1631 changed = shutdown_rx.changed() => {
1632 if changed.is_err() || *shutdown_rx.borrow() {
1633 finish_session(&shared);
1634 return;
1635 }
1636 }
1637 _ = tokio::time::sleep(delay) => {}
1638 }
1639 }
1640
1641 if credentials
1642 .rfq_v2_expires_at_ms()
1643 .is_some_and(|expires_at_ms| current_unix_ms().is_none_or(|now| now >= expires_at_ms))
1644 {
1645 let reason = WsDisconnectReason::Protocol(
1646 "RFQ V2 read grant expired; sign a fresh grant".to_string(),
1647 );
1648 record_disconnect(&shared, reason.clone());
1649 finish_session(&shared);
1650 if let Some(initial_tx) = initial_tx.take() {
1651 let _ = initial_tx.send(Err(ClientError::WebSocket(format!("{reason:?}"))));
1652 }
1653 return;
1654 }
1655
1656 set_state(&shared, WsConnectionState::Connecting { attempt });
1657 debug!("Connecting to WebSocket: {}", ws_url);
1658 let connect_result = tokio::select! {
1659 changed = shutdown_rx.changed() => {
1660 if changed.is_err() || *shutdown_rx.borrow() {
1661 finish_session(&shared);
1662 if let Some(initial_tx) = initial_tx.take() {
1663 let _ = initial_tx.send(Err(ClientError::WebSocket(
1664 "WebSocket connection stopped before startup".to_string(),
1665 )));
1666 }
1667 return;
1668 }
1669 continue;
1670 }
1671 result = connect_socket(&ws_url, options) => result,
1672 };
1673
1674 let (mut socket, response) = match connect_result {
1675 Ok(connection) => connection,
1676 Err(error) => {
1677 let reason = WsDisconnectReason::Transport(error.to_string());
1678 record_disconnect(&shared, reason.clone());
1679 if !reconnecting {
1680 finish_session(&shared);
1681 if let Some(initial_tx) = initial_tx.take() {
1682 let _ = initial_tx.send(Err(ClientError::WebSocket(format!(
1683 "Failed to connect: {}",
1684 error
1685 ))));
1686 }
1687 return;
1688 }
1689 attempt = attempt.saturating_add(1);
1690 continue;
1691 }
1692 };
1693 info!(
1694 permessage_deflate = socket.get_ref().deflate_negotiated(),
1695 "WebSocket connected, status: {}",
1696 response.status()
1697 );
1698
1699 let handshake_result = async {
1700 if let Some(wallet) = credentials.wallet.as_deref() {
1701 set_state(&shared, WsConnectionState::Authenticating);
1702 authenticate_socket(
1703 &mut socket,
1704 &shared,
1705 wallet,
1706 &mut shutdown_rx,
1707 config.authentication_timeout,
1708 )
1709 .await?;
1710 info!("WebSocket authenticated as wallet: {}", wallet);
1711 }
1712
1713 #[cfg(feature = "rfq-v2")]
1714 if let Some(grant) = credentials.rfq_v2_grant.as_ref() {
1715 set_state(&shared, WsConnectionState::Authenticating);
1716 authenticate_rfq_v2_socket(
1717 &mut socket,
1718 &shared,
1719 grant,
1720 &mut shutdown_rx,
1721 config.authentication_timeout,
1722 )
1723 .await?;
1724 }
1725
1726 let mut subscriptions = shared.subscriptions.write().await;
1731 if !subscriptions.is_empty() {
1732 set_state(
1733 &shared,
1734 WsConnectionState::Resubscribing {
1735 channels: subscriptions.len(),
1736 },
1737 );
1738 replay_subscriptions(
1739 &mut socket,
1740 &shared,
1741 &subscriptions,
1742 &mut shutdown_rx,
1743 config.subscription_timeout,
1744 )
1745 .await?;
1746 }
1747 let (unsubscribes, replacements) =
1751 take_v2_fallback_locked(&shared, &mut subscriptions)?;
1752 for frame in unsubscribes {
1753 socket
1754 .send(tungstenite::Message::Text(frame))
1755 .await
1756 .map_err(|error| {
1757 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1758 })?;
1759 }
1760 if !replacements.is_empty() {
1761 replay_subscriptions(
1762 &mut socket,
1763 &shared,
1764 &replacements,
1765 &mut shutdown_rx,
1766 config.subscription_timeout,
1767 )
1768 .await?;
1769 }
1770
1771 let mut recovery_plan = WsRecoveryPlan::default();
1772 for subscription in subscriptions.values() {
1773 recovery_plan.include_channel(&subscription.channel);
1774 }
1775 let (tx, outbound_rx) = mpsc::channel(OUTBOUND_CONTROL_CAPACITY);
1776 *shared.tx.lock().expect("WebSocket sender mutex poisoned") = Some(tx);
1777 if reconnecting && !recovery_plan.is_empty() {
1778 set_state(&shared, WsConnectionState::RecoveryRequired(recovery_plan));
1779 } else {
1780 set_state(&shared, WsConnectionState::Ready);
1781 }
1782 drop(subscriptions);
1783 Ok::<_, SessionStop>(outbound_rx)
1784 }
1785 .await;
1786
1787 let mut outbound_rx = match handshake_result {
1788 Ok(outbound_rx) => outbound_rx,
1789 Err(SessionStop::Shutdown) => {
1790 finish_session(&shared);
1791 if let Some(initial_tx) = initial_tx.take() {
1792 let _ = initial_tx.send(Err(ClientError::WebSocket(
1793 "WebSocket connection stopped before startup".to_string(),
1794 )));
1795 }
1796 return;
1797 }
1798 Err(SessionStop::NonReconnectable(reason)) => {
1799 record_disconnect(&shared, reason.clone());
1800 finish_session(&shared);
1801 if let Some(initial_tx) = initial_tx.take() {
1802 let _ = initial_tx.send(Err(ClientError::WebSocket(format!(
1803 "WebSocket handshake failed: {:?}",
1804 reason
1805 ))));
1806 }
1807 return;
1808 }
1809 Err(stop) => {
1810 if let SessionStop::Disconnected(reason) = &stop {
1811 record_disconnect(&shared, reason.clone());
1812 }
1813 if !reconnecting {
1814 finish_session(&shared);
1815 if let Some(initial_tx) = initial_tx.take() {
1816 let _ = initial_tx
1817 .send(Err(stop.websocket_error("WebSocket handshake failed")));
1818 }
1819 return;
1820 }
1821 attempt = attempt.saturating_add(1);
1822 continue;
1823 }
1824 };
1825
1826 let was_reconnect = reconnecting;
1827 if let Some(initial_tx) = initial_tx.take() {
1828 let _ = initial_tx.send(Ok(()));
1829 }
1830 reconnecting = true;
1831 let connected_at = tokio::time::Instant::now();
1832
1833 match run_connected_socket(
1834 &mut socket,
1835 &shared,
1836 &mut outbound_rx,
1837 &mut shutdown_rx,
1838 credentials.rfq_v2_expires_at_ms(),
1839 )
1840 .await
1841 {
1842 SessionStop::Shutdown => {
1843 finish_session(&shared);
1844 return;
1845 }
1846 SessionStop::NonReconnectable(reason) => {
1847 record_disconnect(&shared, reason);
1848 finish_session(&shared);
1849 return;
1850 }
1851 SessionStop::Disconnected(reason) => {
1852 warn!(?reason, "WebSocket disconnected; scheduling reconnect");
1853 record_disconnect(&shared, reason);
1854 *shared.tx.lock().expect("WebSocket sender mutex poisoned") = None;
1855 if !was_reconnect || connected_at.elapsed() >= config.reconnect_reset_after {
1856 attempt = 0;
1857 } else {
1858 attempt = attempt.saturating_add(1);
1859 }
1860 }
1861 }
1862 }
1863}
1864
1865impl Default for WsClient {
1866 fn default() -> Self {
1867 Self::new()
1868 }
1869}
1870
1871#[cfg(test)]
1872#[path = "websocket_reconnect_test.rs"]
1873mod reconnect_tests;
1874
1875#[cfg(test)]
1876#[path = "websocket_deflate_test.rs"]
1877mod deflate_tests;
1878
1879#[cfg(test)]
1880mod tests {
1881 use super::*;
1882 use sonic_rs::JsonValueTrait;
1883
1884 #[test]
1885 fn test_ws_client_new() {
1886 let client = WsClient::new();
1887 assert!(client.shared.messages.try_lock().is_ok());
1889 assert!(client.shared.pongs.try_lock().is_ok());
1890 assert!(client.shared.tx.try_lock().is_ok());
1891 }
1892
1893 #[test]
1894 fn test_ws_client_default() {
1895 let client = WsClient::default();
1896 assert!(client.shared.messages.try_lock().is_ok());
1897 }
1898
1899 #[tokio::test]
1900 async fn test_ws_client_get_messages_empty() {
1901 let client = WsClient::new();
1902 let messages = client.get_messages().await;
1903 assert!(messages.is_empty());
1904 }
1905
1906 #[tokio::test]
1907 async fn test_ws_client_clear_messages() {
1908 let client = WsClient::new();
1909 client
1911 .shared
1912 .messages
1913 .lock()
1914 .await
1915 .push(sonic_rs::json!({"test": "value"}));
1916 assert_eq!(client.get_messages().await.len(), 1);
1917
1918 client.clear_messages().await;
1920 assert!(client.get_messages().await.is_empty());
1921 }
1922
1923 #[tokio::test]
1924 async fn test_ws_client_count_messages() {
1925 let client = WsClient::new();
1926 {
1928 let mut messages = client.shared.messages.lock().await;
1929 messages.push(sonic_rs::json!({"type": "order", "id": 1}));
1930 messages.push(sonic_rs::json!({"type": "trade", "id": 2}));
1931 messages.push(sonic_rs::json!({"type": "order", "id": 3}));
1932 }
1933
1934 let order_count = client
1935 .count_messages(|m| m.get("type").and_then(|t| t.as_str()) == Some("order"))
1936 .await;
1937 assert_eq!(order_count, 2);
1938
1939 let trade_count = client
1940 .count_messages(|m| m.get("type").and_then(|t| t.as_str()) == Some("trade"))
1941 .await;
1942 assert_eq!(trade_count, 1);
1943 }
1944
1945 #[tokio::test]
1946 async fn test_ws_client_subscribe_not_connected() {
1947 let client = WsClient::new();
1948 let result = client.subscribe(vec!["orders"]).await;
1949 assert!(result.is_err());
1950 assert!(matches!(
1951 result.unwrap_err(),
1952 crate::error::ClientError::WebSocket(_)
1953 ));
1954 }
1955
1956 #[tokio::test]
1957 async fn test_ws_client_ping_not_connected() {
1958 let client = WsClient::new();
1959 let result = client.ping().await;
1960 assert!(matches!(
1961 result.unwrap_err(),
1962 crate::error::ClientError::WebSocket(_)
1963 ));
1964 }
1965
1966 #[tokio::test]
1967 async fn test_ws_client_sends_ping_with_payload() {
1968 let client = WsClient::new();
1969 let (tx, mut rx) = mpsc::channel(1);
1970 *client
1971 .shared
1972 .tx
1973 .lock()
1974 .expect("WebSocket sender mutex poisoned") = Some(tx);
1975
1976 client.ping_with_payload(b"health".to_vec()).await.unwrap();
1977
1978 match rx.recv().await.unwrap() {
1979 tungstenite::Message::Ping(payload) => assert_eq!(payload, b"health"),
1980 other => panic!("Expected ping frame, got {other:?}"),
1981 }
1982 }
1983
1984 #[tokio::test]
1985 async fn test_ws_client_rejects_oversized_ping_payload() {
1986 let client = WsClient::new();
1987 let (tx, _rx) = mpsc::channel(1);
1988 *client
1989 .shared
1990 .tx
1991 .lock()
1992 .expect("WebSocket sender mutex poisoned") = Some(tx);
1993
1994 let result = client.ping_with_payload(vec![0; 126]).await;
1995 assert!(matches!(
1996 result.unwrap_err(),
1997 crate::error::ClientError::WebSocket(_)
1998 ));
1999 }
2000
2001 #[tokio::test]
2002 async fn test_ws_client_tracks_received_pongs() {
2003 let client = WsClient::new();
2004 client.shared.pongs.lock().await.push(b"health".to_vec());
2005
2006 let pong = client
2007 .wait_for_pong(|payload| payload == b"health", 100)
2008 .await;
2009 assert_eq!(pong, Some(b"health".to_vec()));
2010
2011 client.clear_pongs().await;
2012 assert!(client.get_pongs().await.is_empty());
2013 }
2014
2015 #[tokio::test]
2016 async fn test_ws_client_responds_to_server_ping() {
2017 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2018 let addr = listener.local_addr().unwrap();
2019
2020 let server = tokio::spawn(async move {
2021 let (stream, _) = listener.accept().await.unwrap();
2022 let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
2023 ws.send(tungstenite::Message::Ping(b"server".to_vec()))
2024 .await
2025 .unwrap();
2026
2027 match tokio::time::timeout(Duration::from_secs(1), ws.next())
2028 .await
2029 .unwrap()
2030 .unwrap()
2031 .unwrap()
2032 {
2033 tungstenite::Message::Pong(payload) => assert_eq!(payload, b"server"),
2034 other => panic!("Expected pong frame, got {other:?}"),
2035 }
2036 });
2037
2038 let client = WsClient::new();
2039 client
2040 .connect(&format!("http://{}", addr), None)
2041 .await
2042 .unwrap();
2043
2044 server.await.unwrap();
2045 }
2046
2047 #[tokio::test]
2048 async fn test_ws_client_wait_for_message_timeout() {
2049 let client = WsClient::new();
2050
2051 let result = client
2053 .wait_for_message(|m| m.get("never").is_some(), 100)
2054 .await;
2055 assert!(result.is_none());
2056 }
2057
2058 #[tokio::test]
2059 async fn test_ws_client_wait_for_message_found() {
2060 let client = WsClient::new();
2061
2062 let messages = client.shared.messages.clone();
2064 tokio::spawn(async move {
2065 tokio::time::sleep(Duration::from_millis(50)).await;
2066 messages.lock().await.push(sonic_rs::json!({"found": true}));
2067 });
2068
2069 let result = client
2070 .wait_for_message(|m| m.get("found").is_some(), 500)
2071 .await;
2072 assert!(result.is_some());
2073 assert_eq!(result.unwrap()["found"], true);
2074 }
2075
2076 #[test]
2077 fn test_ws_message_subscribe_serialize() {
2078 let msg = WsMessage::Subscribe {
2079 channel: "orders".to_string(),
2080 symbols: None,
2081 expiry: None,
2082 option_type: None,
2083 };
2084 let json = sonic_rs::to_string(&msg).unwrap();
2085 assert!(json.contains("Subscribe"));
2086 assert!(json.contains("orders"));
2087 }
2088
2089 #[test]
2090 fn test_ws_message_unsubscribe_serialize() {
2091 let msg = WsMessage::Unsubscribe {
2092 channel: "trades".to_string(),
2093 symbols: None,
2094 expiry: None,
2095 option_type: None,
2096 };
2097 let json = sonic_rs::to_string(&msg).unwrap();
2098 assert!(json.contains("Unsubscribe"));
2099 assert!(json.contains("trades"));
2100 }
2101
2102 #[test]
2103 fn test_ws_message_subscribed_deserialize() {
2104 let json = r#"{"type": "Subscribed", "channel": "orders"}"#;
2105 let msg: WsMessage = sonic_rs::from_str(json).unwrap();
2106 match msg {
2107 WsMessage::Subscribed { channel, .. } => assert_eq!(channel, "orders"),
2108 _ => panic!("Expected Subscribed variant"),
2109 }
2110 }
2111
2112 #[test]
2113 fn test_ws_message_unsubscribed_deserialize() {
2114 let json = r#"{"type": "Unsubscribed", "channel": "trades"}"#;
2115 let msg: WsMessage = sonic_rs::from_str(json).unwrap();
2116 match msg {
2117 WsMessage::Unsubscribed { channel } => assert_eq!(channel, "trades"),
2118 _ => panic!("Expected Unsubscribed variant"),
2119 }
2120 }
2121
2122 #[test]
2123 fn test_ws_message_error_deserialize() {
2124 let json = r#"{"type": "Error", "message": "invalid channel"}"#;
2125 let msg: WsMessage = sonic_rs::from_str(json).unwrap();
2126 match msg {
2127 WsMessage::Error { message, .. } => assert_eq!(message, "invalid channel"),
2128 _ => panic!("Expected Error variant"),
2129 }
2130 }
2131
2132 #[test]
2133 fn test_ws_message_unknown_type_deserialize() {
2134 let json = r#"{"type": "unknown_type", "data": "something"}"#;
2135 let msg: WsMessage = sonic_rs::from_str(json).unwrap();
2136 match msg {
2137 WsMessage::Other => {}
2138 _ => panic!("Expected Other variant"),
2139 }
2140 }
2141
2142 #[test]
2143 fn test_ws_message_debug() {
2144 let msg = WsMessage::Subscribe {
2145 channel: "orders".to_string(),
2146 symbols: None,
2147 expiry: None,
2148 option_type: None,
2149 };
2150 let debug = format!("{:?}", msg);
2151 assert!(debug.contains("Subscribe"));
2152 assert!(debug.contains("orders"));
2153 }
2154
2155 #[test]
2156 fn test_ws_message_clone() {
2157 let msg = WsMessage::Error {
2158 code: None,
2159 channel: None,
2160 message: "test error".to_string(),
2161 };
2162 let cloned = msg.clone();
2163 match cloned {
2164 WsMessage::Error { message, .. } => assert_eq!(message, "test error"),
2165 _ => panic!("Clone failed"),
2166 }
2167 }
2168}