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::{RfqV2View, 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 Self::with_view(channel, symbols, expiry, option_type, None)
288 }
289
290 fn with_view(
294 channel: &str,
295 symbols: Option<Vec<String>>,
296 expiry: Option<String>,
297 option_type: Option<String>,
298 view: Option<RfqV2View>,
299 ) -> Result<Self> {
300 let subscribe = sonic_rs::to_string(&WsMessage::Subscribe {
301 channel: channel.to_string(),
302 symbols: symbols.clone(),
303 expiry: expiry.clone(),
304 option_type: option_type.clone(),
305 view,
306 })?;
307 let unsubscribe = sonic_rs::to_string(&WsMessage::Unsubscribe {
308 channel: channel.to_string(),
309 symbols: symbols.clone(),
310 expiry: expiry.clone(),
311 option_type: option_type.clone(),
312 })?;
313 Ok(Self {
314 channel: channel.to_string(),
315 symbols,
316 expiry,
317 option_type,
318 logical_indicative: false,
319 direct: false,
320 subscribe,
321 unsubscribe,
322 })
323 }
324}
325
326struct WsClientShared {
327 messages: Arc<Mutex<Vec<sonic_rs::Value>>>,
328 pongs: Arc<Mutex<Vec<Vec<u8>>>>,
329 tx: StdMutex<Option<mpsc::Sender<tungstenite::Message>>>,
330 subscriptions: RwLock<BTreeMap<String, DesiredSubscription>>,
331 state: StdMutex<WsConnectionState>,
332 state_tx: watch::Sender<WsConnectionState>,
333 last_disconnect: StdMutex<Option<WsDisconnectReason>>,
334 started: AtomicBool,
335 batched_indicative: AtomicBool,
337 v2_unsupported: AtomicBool,
340 v2_fallback_pending: AtomicBool,
343 #[cfg(feature = "rfq-v2")]
346 rfq_v2_grant: StdMutex<Option<RfqV2SocketGrant>>,
347}
348
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
351enum Release {
352 Keep,
353 Remove,
354}
355
356#[derive(Debug, Clone, Copy)]
358struct ConnectOptions {
359 permessage_deflate: bool,
360}
361
362pub struct WsClient {
364 shared: Arc<WsClientShared>,
365 config: WsClientConfig,
366 options: ConnectOptions,
367 shutdown_tx: StdMutex<Option<watch::Sender<bool>>>,
368}
369
370#[cfg(feature = "rfq-v2")]
371#[derive(Clone)]
372struct RfqV2SocketGrant {
373 token: String,
374 account: String,
375 expires_at_ms: u64,
376}
377
378struct SessionCredentials {
382 wallet: Option<String>,
383}
384
385impl SessionCredentials {
386 fn wallet(wallet: Option<String>) -> Self {
387 Self { wallet }
388 }
389}
390
391#[cfg(feature = "rfq-v2")]
392fn current_rfq_v2_grant(shared: &WsClientShared) -> Option<RfqV2SocketGrant> {
393 shared
394 .rfq_v2_grant
395 .lock()
396 .expect("WebSocket RFQ grant mutex poisoned")
397 .clone()
398}
399
400fn rfq_v2_expires_at_ms(shared: &WsClientShared) -> Option<u64> {
402 #[cfg(feature = "rfq-v2")]
403 {
404 current_rfq_v2_grant(shared).map(|grant| grant.expires_at_ms)
405 }
406 #[cfg(not(feature = "rfq-v2"))]
407 {
408 let _ = shared;
409 None
410 }
411}
412
413fn current_unix_ms() -> Option<u64> {
414 std::time::SystemTime::now()
415 .duration_since(std::time::UNIX_EPOCH)
416 .ok()
417 .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok())
418}
419
420impl WsClient {
421 pub fn new() -> Self {
423 Self::with_config(WsClientConfig::default())
424 }
425
426 pub fn with_config(config: WsClientConfig) -> Self {
428 let (state_tx, _) = watch::channel(WsConnectionState::Disconnected);
429 Self {
430 shared: Arc::new(WsClientShared {
431 messages: Arc::new(Mutex::new(Vec::new())),
432 pongs: Arc::new(Mutex::new(Vec::new())),
433 tx: StdMutex::new(None),
434 subscriptions: RwLock::new(BTreeMap::new()),
435 state: StdMutex::new(WsConnectionState::Disconnected),
436 state_tx,
437 last_disconnect: StdMutex::new(None),
438 started: AtomicBool::new(false),
439 batched_indicative: AtomicBool::new(true),
440 v2_unsupported: AtomicBool::new(false),
441 v2_fallback_pending: AtomicBool::new(false),
442 #[cfg(feature = "rfq-v2")]
443 rfq_v2_grant: StdMutex::new(None),
444 }),
445 config,
446 options: ConnectOptions {
447 permessage_deflate: true,
448 },
449 shutdown_tx: StdMutex::new(None),
450 }
451 }
452
453 pub fn with_permessage_deflate(mut self, enabled: bool) -> Self {
461 self.options.permessage_deflate = enabled;
462 self
463 }
464
465 pub fn with_batched_indicative(self, enabled: bool) -> Self {
472 self.shared
473 .batched_indicative
474 .store(enabled, Ordering::Release);
475 self
476 }
477
478 pub fn indicative_batched(&self) -> bool {
481 self.shared.batched_indicative.load(Ordering::Acquire)
482 && !self.shared.v2_unsupported.load(Ordering::Acquire)
483 }
484
485 pub async fn connect(&self, base_url: &str, wallet: Option<&AccountAddress>) -> Result<()> {
493 self.start_session(
494 base_url,
495 SessionCredentials::wallet(wallet.map(ToString::to_string)),
496 )
497 .await
498 }
499
500 #[cfg(feature = "rfq-v2")]
511 pub async fn connect_rfq_v2(&self, base_url: &str, grant: &RfqV2ReadGrant) -> Result<()> {
512 let socket_grant = RfqV2SocketGrant {
513 token: encode_rfq_v2_read_grant(grant)?,
514 account: grant.account.to_string(),
515 expires_at_ms: grant.expires_at_ms,
516 };
517 if self.shared.started.load(Ordering::Acquire) {
518 return Err(ClientError::WebSocket(
519 "WebSocket client is already connected or connecting".to_string(),
520 ));
521 }
522 *self
523 .shared
524 .rfq_v2_grant
525 .lock()
526 .expect("WebSocket RFQ grant mutex poisoned") = Some(socket_grant);
527 let result = self
528 .start_session(base_url, SessionCredentials { wallet: None })
529 .await;
530 if result.is_err() {
531 *self
532 .shared
533 .rfq_v2_grant
534 .lock()
535 .expect("WebSocket RFQ grant mutex poisoned") = None;
536 }
537 result
538 }
539
540 #[cfg(feature = "rfq-v2")]
546 pub async fn reauthenticate_rfq_v2(&self, grant: &RfqV2ReadGrant) -> Result<()> {
547 let socket_grant = RfqV2SocketGrant {
548 token: encode_rfq_v2_read_grant(grant)?,
549 account: grant.account.to_string(),
550 expires_at_ms: grant.expires_at_ms,
551 };
552 {
553 let mut current = self
554 .shared
555 .rfq_v2_grant
556 .lock()
557 .expect("WebSocket RFQ grant mutex poisoned");
558 match current.as_ref() {
559 None => {
560 return Err(ClientError::WebSocket(
561 "not an RFQ V2 session; use connect_rfq_v2".to_string(),
562 ))
563 }
564 Some(existing) if !existing.account.eq_ignore_ascii_case(&socket_grant.account) => {
565 return Err(ClientError::InvalidInput(
566 "RFQ read grant is for a different account than the session".to_string(),
567 ))
568 }
569 Some(_) => {}
570 }
571 *current = Some(socket_grant.clone());
572 }
573 let frame = sonic_rs::to_string(&WsMessage::AuthenticateRfqV2 {
574 token: socket_grant.token,
575 })?;
576 let tx = self
577 .shared
578 .tx
579 .lock()
580 .expect("WebSocket sender mutex poisoned")
581 .clone();
582 if let Some(tx) = tx {
583 tx.send(tungstenite::Message::Text(frame))
584 .await
585 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
586 }
587 Ok(())
588 }
589
590 async fn start_session(&self, base_url: &str, credentials: SessionCredentials) -> Result<()> {
591 self.config.validate()?;
592 let ws_url = websocket_url(base_url)?;
593 if self
594 .shared
595 .started
596 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
597 .is_err()
598 {
599 return Err(ClientError::WebSocket(
600 "WebSocket client is already connected or connecting".to_string(),
601 ));
602 }
603
604 let (shutdown_tx, shutdown_rx) = watch::channel(false);
605 *self
606 .shutdown_tx
607 .lock()
608 .expect("WebSocket shutdown mutex poisoned") = Some(shutdown_tx);
609 let (initial_tx, initial_rx) = oneshot::channel();
610 let shared = self.shared.clone();
611 let config = self.config;
612 let options = self.options;
613 tokio::spawn(async move {
614 run_ws_session(
615 shared,
616 config,
617 ws_url,
618 options,
619 credentials,
620 shutdown_rx,
621 initial_tx,
622 )
623 .await;
624 });
625
626 initial_rx.await.map_err(|_| {
627 ClientError::WebSocket("WebSocket connection task stopped before startup".to_string())
628 })?
629 }
630
631 fn validate_control_payload(payload: &[u8]) -> Result<()> {
632 if payload.len() > MAX_CONTROL_FRAME_PAYLOAD_LEN {
633 return Err(ClientError::WebSocket(format!(
634 "WebSocket control frame payload exceeds {} bytes",
635 MAX_CONTROL_FRAME_PAYLOAD_LEN
636 )));
637 }
638
639 Ok(())
640 }
641
642 async fn send_control_frame(&self, msg: tungstenite::Message) -> Result<()> {
643 let tx = self
644 .shared
645 .tx
646 .lock()
647 .expect("WebSocket sender mutex poisoned")
648 .clone()
649 .ok_or(ClientError::WebSocket("Not connected".to_string()))?;
650
651 tx.send(msg)
652 .await
653 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))
654 }
655
656 pub async fn ping(&self) -> Result<()> {
658 self.ping_with_payload(Vec::new()).await
659 }
660
661 pub async fn ping_with_payload(&self, payload: impl Into<Vec<u8>>) -> Result<()> {
665 let payload = payload.into();
666 Self::validate_control_payload(&payload)?;
667 self.send_control_frame(tungstenite::Message::Ping(payload))
668 .await
669 }
670
671 pub async fn pong_with_payload(&self, payload: impl Into<Vec<u8>>) -> Result<()> {
676 let payload = payload.into();
677 Self::validate_control_payload(&payload)?;
678 self.send_control_frame(tungstenite::Message::Pong(payload))
679 .await
680 }
681
682 pub async fn subscribe(&self, channels: Vec<&str>) -> Result<()> {
684 for channel in channels {
685 self.subscribe_with_options(channel, None, None, None)
686 .await?;
687 }
688
689 Ok(())
690 }
691
692 #[cfg(feature = "rfq-v2")]
697 pub async fn subscribe_rfq_v2(&self) -> Result<()> {
698 self.subscribe_with_options("rfq_v2", None, None, None)
699 .await
700 }
701
702 #[cfg(feature = "rfq-v2")]
710 pub async fn subscribe_rfq_v2_with_view(&self, view: RfqV2View) -> Result<()> {
711 let desired = DesiredSubscription::with_view("rfq_v2", None, None, None, Some(view))?;
712 self.subscribe_entry(desired, false).await
713 }
714
715 #[cfg(feature = "rfq-v2")]
717 pub async fn unsubscribe_rfq_v2(&self) -> Result<()> {
718 self.unsubscribe(vec!["rfq_v2"]).await
719 }
720
721 pub async fn subscribe_with_options(
723 &self,
724 channel: &str,
725 symbols: Option<Vec<String>>,
726 expiry: Option<String>,
727 option_type: Option<String>,
728 ) -> Result<()> {
729 self.subscribe_desired(channel, symbols, expiry, option_type)
730 .await
731 }
732
733 pub async fn subscribe_indicative_market_data(
750 &self,
751 symbols: Option<Vec<String>>,
752 ) -> Result<()> {
753 let channel = if self.indicative_batched() {
754 INDICATIVE_V2_CHANNEL
755 } else {
756 INDICATIVE_CHANNEL
757 };
758 self.subscribe_desired_with(channel, symbols, None, None, true)
759 .await
760 }
761
762 pub async fn unsubscribe_indicative_market_data(&self) -> Result<()> {
768 self.release_where(|subscription| {
769 if !subscription.logical_indicative {
770 return Release::Keep;
771 }
772 subscription.logical_indicative = false;
773 if subscription.direct {
774 Release::Keep
775 } else {
776 Release::Remove
777 }
778 })
779 .await
780 }
781
782 async fn subscribe_desired(
783 &self,
784 channel: &str,
785 symbols: Option<Vec<String>>,
786 expiry: Option<String>,
787 option_type: Option<String>,
788 ) -> Result<()> {
789 self.subscribe_desired_with(channel, symbols, expiry, option_type, false)
790 .await
791 }
792
793 async fn subscribe_desired_with(
794 &self,
795 channel: &str,
796 symbols: Option<Vec<String>>,
797 expiry: Option<String>,
798 option_type: Option<String>,
799 logical_indicative: bool,
800 ) -> Result<()> {
801 if !self.shared.started.load(Ordering::Acquire) {
802 return Err(ClientError::WebSocket("Not connected".to_string()));
803 }
804
805 let desired = DesiredSubscription::new(channel, symbols, expiry, option_type)?;
806 self.subscribe_entry(desired, logical_indicative).await
807 }
808
809 async fn subscribe_entry(
810 &self,
811 mut desired: DesiredSubscription,
812 logical_indicative: bool,
813 ) -> Result<()> {
814 if !self.shared.started.load(Ordering::Acquire) {
815 return Err(ClientError::WebSocket("Not connected".to_string()));
816 }
817 let channel = desired.channel.clone();
818 desired.logical_indicative = logical_indicative;
819 desired.direct = !logical_indicative;
820 let frame = tungstenite::Message::Text(desired.subscribe.clone());
821 {
822 let mut subscriptions = self.shared.subscriptions.write().await;
823 for existing in subscriptions.values() {
828 if desired.same_filter(existing) {
829 desired.absorb(existing);
830 }
831 }
832 subscriptions.retain(|_, existing| !desired.same_filter(existing));
833 subscriptions.insert(desired.subscribe.clone(), desired);
834 }
835
836 let tx = self
837 .shared
838 .tx
839 .lock()
840 .expect("WebSocket sender mutex poisoned")
841 .clone();
842 if let Some(tx) = tx {
843 debug!("Subscribing to: {}", channel);
844 tx.send(frame)
845 .await
846 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
847 }
848
849 Ok(())
850 }
851
852 pub async fn unsubscribe(&self, channels: Vec<&str>) -> Result<()> {
862 for channel in channels {
863 self.release_where(|subscription| {
866 if subscription.channel != channel {
867 return Release::Keep;
868 }
869 subscription.direct = false;
870 if subscription.logical_indicative {
871 Release::Keep
872 } else {
873 Release::Remove
874 }
875 })
876 .await?;
877 }
878 Ok(())
879 }
880
881 async fn release_where(
884 &self,
885 release: impl Fn(&mut DesiredSubscription) -> Release,
886 ) -> Result<()> {
887 if !self.shared.started.load(Ordering::Acquire) {
888 return Err(ClientError::WebSocket("Not connected".to_string()));
889 }
890
891 let removed = {
892 let mut subscriptions = self.shared.subscriptions.write().await;
893 let keys = subscriptions
894 .iter_mut()
895 .filter_map(|(key, subscription)| {
896 (release(subscription) == Release::Remove).then(|| key.clone())
897 })
898 .collect::<Vec<_>>();
899 keys.into_iter()
900 .filter_map(|key| subscriptions.remove(&key))
901 .collect::<Vec<_>>()
902 };
903 for removed in removed {
904 let tx = self
905 .shared
906 .tx
907 .lock()
908 .expect("WebSocket sender mutex poisoned")
909 .clone();
910 if let Some(tx) = tx {
911 tx.send(tungstenite::Message::Text(removed.unsubscribe))
912 .await
913 .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
914 }
915 }
916 Ok(())
917 }
918
919 pub async fn disconnect(&self) {
921 let _ = self
922 .send_control_frame(tungstenite::Message::Close(None))
923 .await;
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 pub fn connection_state(&self) -> WsConnectionState {
936 self.shared
937 .state
938 .lock()
939 .expect("WebSocket state mutex poisoned")
940 .clone()
941 }
942
943 pub fn connection_state_receiver(&self) -> watch::Receiver<WsConnectionState> {
945 self.shared.state_tx.subscribe()
946 }
947
948 pub fn last_disconnect_reason(&self) -> Option<WsDisconnectReason> {
950 self.shared
951 .last_disconnect
952 .lock()
953 .expect("WebSocket disconnect mutex poisoned")
954 .clone()
955 }
956
957 pub fn mark_recovered(&self) -> Result<()> {
959 let mut state = self
960 .shared
961 .state
962 .lock()
963 .expect("WebSocket state mutex poisoned");
964 if !matches!(*state, WsConnectionState::RecoveryRequired(_)) {
965 return Err(ClientError::WebSocket(
966 "No WebSocket recovery is currently required".to_string(),
967 ));
968 }
969 *state = WsConnectionState::Ready;
970 self.shared.state_tx.send_replace(WsConnectionState::Ready);
971 Ok(())
972 }
973
974 pub async fn get_pongs(&self) -> Vec<Vec<u8>> {
976 self.shared.pongs.lock().await.clone()
977 }
978
979 pub async fn clear_pongs(&self) {
981 self.shared.pongs.lock().await.clear();
982 }
983
984 pub async fn wait_for_pong<F>(&self, check: F, timeout_ms: u64) -> Option<Vec<u8>>
986 where
987 F: Fn(&[u8]) -> bool,
988 {
989 let start = std::time::Instant::now();
990 let timeout = Duration::from_millis(timeout_ms);
991
992 while start.elapsed() < timeout {
993 let pongs = self.get_pongs().await;
994 if let Some(pong) = pongs.iter().find(|payload| check(payload)) {
995 return Some(pong.clone());
996 }
997 tokio::time::sleep(Duration::from_millis(50)).await;
998 }
999
1000 None
1001 }
1002
1003 pub async fn get_messages(&self) -> Vec<sonic_rs::Value> {
1005 self.shared.messages.lock().await.clone()
1006 }
1007
1008 pub async fn clear_messages(&self) {
1010 self.shared.messages.lock().await.clear();
1011 }
1012
1013 pub async fn wait_for_message<F>(&self, check: F, timeout_ms: u64) -> Option<sonic_rs::Value>
1015 where
1016 F: Fn(&sonic_rs::Value) -> bool,
1017 {
1018 let start = std::time::Instant::now();
1019 let timeout = Duration::from_millis(timeout_ms);
1020
1021 while start.elapsed() < timeout {
1022 let messages = self.get_messages().await;
1023 if let Some(msg) = messages.iter().find(|m| check(m)) {
1024 return Some(msg.clone());
1025 }
1026 tokio::time::sleep(Duration::from_millis(50)).await;
1027 }
1028
1029 None
1030 }
1031
1032 pub async fn count_messages<F>(&self, check: F) -> usize
1034 where
1035 F: Fn(&sonic_rs::Value) -> bool,
1036 {
1037 self.get_messages()
1038 .await
1039 .iter()
1040 .filter(|msg| check(msg))
1041 .count()
1042 }
1043}
1044
1045impl Drop for WsClient {
1046 fn drop(&mut self) {
1047 if let Some(shutdown_tx) = self
1048 .shutdown_tx
1049 .lock()
1050 .expect("WebSocket shutdown mutex poisoned")
1051 .take()
1052 {
1053 let _ = shutdown_tx.send(true);
1054 }
1055 }
1056}
1057
1058#[derive(Debug, Clone)]
1059enum SessionStop {
1060 Shutdown,
1061 Disconnected(WsDisconnectReason),
1062 NonReconnectable(WsDisconnectReason),
1063}
1064
1065impl SessionStop {
1066 fn websocket_error(&self, context: &str) -> ClientError {
1067 match self {
1068 Self::Shutdown => ClientError::WebSocket(format!("{}: client stopped", context)),
1069 Self::Disconnected(reason) | Self::NonReconnectable(reason) => {
1070 ClientError::WebSocket(format!("{}: {:?}", context, reason))
1071 }
1072 }
1073 }
1074}
1075
1076fn websocket_url(base_url: &str) -> Result<String> {
1077 let base_url = base_url.trim_end_matches('/');
1078 let ws_origin = if let Some(rest) = base_url.strip_prefix("https://") {
1079 format!("wss://{}", rest)
1080 } else if let Some(rest) = base_url.strip_prefix("http://") {
1081 format!("ws://{}", rest)
1082 } else if base_url.starts_with("wss://") || base_url.starts_with("ws://") {
1083 base_url.to_string()
1084 } else {
1085 return Err(ClientError::InvalidInput(
1086 "WebSocket base URL must use http, https, ws, or wss".to_string(),
1087 ));
1088 };
1089
1090 if ws_origin.ends_with("/ws") {
1091 Ok(ws_origin)
1092 } else {
1093 Ok(format!("{}/ws", ws_origin))
1094 }
1095}
1096
1097#[derive(Debug, thiserror::Error)]
1100#[displaystr::display]
1101enum ConnectError {
1102 Url(#[source] tungstenite::Error) = "invalid WebSocket URL: {_0}",
1103 MissingHost = "WebSocket URL has no host",
1104 UnsupportedScheme = "WebSocket URL must use ws or wss",
1105 Tcp(#[source] std::io::Error) = "IO error: {_0}",
1106 Tls(#[source] tokio_native_tls::native_tls::Error) = "TLS error: {_0}",
1107 Handshake(#[source] tungstenite::Error) = "{_0}",
1110}
1111
1112async fn connect_socket(
1115 ws_url: &str,
1116 options: ConnectOptions,
1117) -> std::result::Result<(ClientSocket, tungstenite::handshake::client::Response), ConnectError> {
1118 let permessage_deflate = options.permessage_deflate;
1119 let mut request = ws_url.into_client_request().map_err(ConnectError::Url)?;
1120 if permessage_deflate {
1121 request.headers_mut().insert(
1122 "Sec-WebSocket-Extensions",
1123 HeaderValue::from_static(PERMESSAGE_DEFLATE_OFFER),
1124 );
1125 }
1126 let uri = request.uri();
1127 let host = uri.host().ok_or(ConnectError::MissingHost)?.to_string();
1128 let tls = match uri.scheme_str() {
1129 Some("wss") => true,
1130 Some("ws") => false,
1131 _ => return Err(ConnectError::UnsupportedScheme),
1132 };
1133 let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
1134 let tcp = TcpStream::connect(format!("{host}:{port}"))
1135 .await
1136 .map_err(ConnectError::Tcp)?;
1137
1138 let io: Box<dyn ClientIo> = if tls {
1139 let domain = host.trim_start_matches('[').trim_end_matches(']');
1140 let connector =
1141 tokio_native_tls::native_tls::TlsConnector::new().map_err(ConnectError::Tls)?;
1142 let stream = tokio_native_tls::TlsConnector::from(connector)
1143 .connect(domain, tcp)
1144 .await
1145 .map_err(ConnectError::Tls)?;
1146 Box::new(stream)
1147 } else {
1148 Box::new(tcp)
1149 };
1150
1151 let stream = InflatingStream::new(io, permessage_deflate, MAX_FRAME_LEN, MAX_MESSAGE_LEN);
1152 client_async(request, stream)
1153 .await
1154 .map_err(ConnectError::Handshake)
1155}
1156
1157fn reconnect_delay(config: WsClientConfig, attempt: u32) -> Duration {
1158 let multiplier = 1_u32 << attempt.min(31);
1159 let ceiling = config
1160 .reconnect_initial_delay
1161 .saturating_mul(multiplier)
1162 .min(config.reconnect_max_delay);
1163 ceiling.mul_f64(0.5 + rand::random::<f64>() * 0.5)
1164}
1165
1166fn set_state(shared: &WsClientShared, next: WsConnectionState) {
1167 *shared.state.lock().expect("WebSocket state mutex poisoned") = next.clone();
1168 shared.state_tx.send_replace(next);
1169}
1170
1171fn finish_session(shared: &WsClientShared) {
1172 *shared.tx.lock().expect("WebSocket sender mutex poisoned") = None;
1173 #[cfg(feature = "rfq-v2")]
1174 {
1175 *shared
1176 .rfq_v2_grant
1177 .lock()
1178 .expect("WebSocket RFQ grant mutex poisoned") = None;
1179 }
1180 shared.started.store(false, Ordering::Release);
1181 set_state(shared, WsConnectionState::Disconnected);
1182}
1183
1184fn record_disconnect(shared: &WsClientShared, reason: WsDisconnectReason) {
1185 *shared
1186 .last_disconnect
1187 .lock()
1188 .expect("WebSocket disconnect mutex poisoned") = Some(reason);
1189}
1190
1191async fn record_text(shared: &WsClientShared, text: &str) -> Option<sonic_rs::Value> {
1192 debug!("WS received: {}", text);
1193 let json = sonic_rs::from_str::<sonic_rs::Value>(text).ok()?;
1194 if is_unbatched_v2_confirmation(&json) {
1195 warn!("server lacks indicative_market_data_v2; falling back to indicative_market_data");
1198 shared.v2_unsupported.store(true, Ordering::Release);
1199 shared.v2_fallback_pending.store(true, Ordering::Release);
1200 }
1201 shared.messages.lock().await.push(json.clone());
1202 Some(json)
1203}
1204
1205fn is_unbatched_v2_confirmation(json: &sonic_rs::Value) -> bool {
1209 let channel_is_v2 =
1210 json.get("channel").and_then(|value| value.as_str()) == Some(INDICATIVE_V2_CHANNEL);
1211 match json.get("type").and_then(|value| value.as_str()) {
1212 Some("Subscribed") => {
1213 channel_is_v2 && json.get("batch").and_then(|value| value.as_bool()) != Some(true)
1214 }
1215 Some("Error") => {
1216 channel_is_v2
1217 && json.get("code").and_then(|value| value.as_str())
1218 == Some(hypercall_ws_protocol::UNKNOWN_CHANNEL_CODE)
1219 }
1220 _ => false,
1221 }
1222}
1223
1224async fn take_v2_fallback(
1231 shared: &WsClientShared,
1232) -> std::result::Result<(Vec<String>, BTreeMap<String, DesiredSubscription>), SessionStop> {
1233 let mut subscriptions = shared.subscriptions.write().await;
1234 take_v2_fallback_locked(shared, &mut subscriptions)
1235}
1236
1237fn take_v2_fallback_locked(
1240 shared: &WsClientShared,
1241 subscriptions: &mut BTreeMap<String, DesiredSubscription>,
1242) -> std::result::Result<(Vec<String>, BTreeMap<String, DesiredSubscription>), SessionStop> {
1243 let mut unsubscribes = Vec::new();
1244 let mut replacements = BTreeMap::new();
1245 if !shared.v2_fallback_pending.swap(false, Ordering::AcqRel) {
1246 return Ok((unsubscribes, replacements));
1247 }
1248 let v2_keys: Vec<String> = subscriptions
1249 .iter()
1250 .filter(|(_, desired)| {
1251 desired.channel == INDICATIVE_V2_CHANNEL && desired.logical_indicative
1252 })
1253 .map(|(key, _)| key.clone())
1254 .collect();
1255 for key in v2_keys {
1256 let Some(mut v2) = subscriptions.remove(&key) else {
1257 continue;
1258 };
1259 if v2.direct {
1260 v2.logical_indicative = false;
1264 subscriptions.insert(key, v2.clone());
1265 } else {
1266 unsubscribes.push(v2.unsubscribe.clone());
1267 }
1268 let mut v1 = DesiredSubscription::new(
1269 INDICATIVE_CHANNEL,
1270 v2.symbols.clone(),
1271 v2.expiry.clone(),
1272 v2.option_type.clone(),
1273 )
1274 .map_err(|error| {
1275 SessionStop::Disconnected(WsDisconnectReason::Protocol(error.to_string()))
1276 })?;
1277 v1.logical_indicative = true;
1278 for existing in subscriptions.values() {
1281 if v1.same_filter(existing) {
1282 v1.absorb(existing);
1283 }
1284 }
1285 subscriptions.retain(|_, existing| !v1.same_filter(existing));
1286 subscriptions.insert(v1.subscribe.clone(), v1.clone());
1287 replacements.insert(v1.subscribe.clone(), v1);
1288 }
1289 Ok((unsubscribes, replacements))
1290}
1291
1292async fn apply_v2_fallback<S>(
1295 socket: &mut S,
1296 shared: &WsClientShared,
1297) -> std::result::Result<(), SessionStop>
1298where
1299 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error> + Unpin,
1300{
1301 let (unsubscribes, replacements) = take_v2_fallback(shared).await?;
1302 let frames = unsubscribes.into_iter().chain(
1303 replacements
1304 .into_values()
1305 .map(|replacement| replacement.subscribe),
1306 );
1307 for frame in frames {
1308 socket
1309 .send(tungstenite::Message::Text(frame))
1310 .await
1311 .map_err(|error| {
1312 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1313 })?;
1314 }
1315 Ok(())
1316}
1317
1318fn disconnect_reason_from_close(
1319 frame: Option<tungstenite::protocol::CloseFrame<'_>>,
1320) -> WsDisconnectReason {
1321 let Some(frame) = frame else {
1322 return WsDisconnectReason::EndOfStream;
1323 };
1324 let reason = frame.reason.into_owned();
1325 if let Ok(slow_consumer) = serde_json::from_str::<WsSlowConsumerCloseReason>(&reason) {
1326 return WsDisconnectReason::SlowConsumer(slow_consumer);
1327 }
1328
1329 WsDisconnectReason::CloseFrame {
1330 code: frame.code.into(),
1331 reason,
1332 }
1333}
1334
1335async fn authenticate_socket<S>(
1336 socket: &mut S,
1337 shared: &WsClientShared,
1338 wallet: &str,
1339 shutdown_rx: &mut watch::Receiver<bool>,
1340 timeout: Duration,
1341) -> std::result::Result<(), SessionStop>
1342where
1343 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1344 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1345 + Unpin,
1346{
1347 let auth_msg = sonic_rs::to_string(&WsMessage::Authenticate {
1348 wallet: wallet.to_string(),
1349 })
1350 .map_err(|error| {
1351 SessionStop::Disconnected(WsDisconnectReason::Protocol(format!(
1352 "failed to serialize authentication: {}",
1353 error
1354 )))
1355 })?;
1356 socket
1357 .send(tungstenite::Message::Text(auth_msg))
1358 .await
1359 .map_err(|error| {
1360 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1361 })?;
1362
1363 let deadline = tokio::time::sleep(timeout);
1364 tokio::pin!(deadline);
1365 loop {
1366 tokio::select! {
1367 changed = shutdown_rx.changed() => {
1368 if changed.is_err() || *shutdown_rx.borrow() {
1369 return Err(SessionStop::Shutdown);
1370 }
1371 }
1372 _ = &mut deadline => {
1373 return Err(SessionStop::Disconnected(WsDisconnectReason::Protocol(
1374 "timed out waiting for authentication response".to_string(),
1375 )));
1376 }
1377 incoming = socket.next() => {
1378 match incoming {
1379 Some(Ok(tungstenite::Message::Text(text))) => {
1380 let Some(json) = record_text(shared, &text).await else {
1381 continue;
1382 };
1383 match json.get("type").and_then(|value| value.as_str()) {
1384 Some("Authenticated") => {
1385 let authenticated_wallet = json
1386 .get("wallet")
1387 .and_then(|value| value.as_str())
1388 .ok_or_else(|| SessionStop::Disconnected(
1389 WsDisconnectReason::Protocol(
1390 "authentication response omitted wallet".to_string(),
1391 )
1392 ))?;
1393 if !authenticated_wallet.eq_ignore_ascii_case(wallet) {
1394 return Err(SessionStop::Disconnected(
1395 WsDisconnectReason::Protocol(format!(
1396 "authenticated wallet mismatch: expected {}, received {}",
1397 wallet, authenticated_wallet
1398 )),
1399 ));
1400 }
1401 return Ok(());
1402 }
1403 Some("Error") => {
1404 let message = json
1405 .get("message")
1406 .and_then(|value| value.as_str())
1407 .unwrap_or("authentication failed");
1408 return Err(SessionStop::Disconnected(
1409 WsDisconnectReason::Protocol(message.to_string()),
1410 ));
1411 }
1412 _ => {}
1413 }
1414 }
1415 Some(Ok(tungstenite::Message::Ping(payload))) => {
1416 socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
1417 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1418 })?;
1419 }
1420 Some(Ok(tungstenite::Message::Pong(payload))) => {
1421 shared.pongs.lock().await.push(payload);
1422 }
1423 Some(Ok(tungstenite::Message::Close(frame))) => {
1424 return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
1425 }
1426 Some(Err(error)) => {
1427 return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(
1428 error.to_string(),
1429 )));
1430 }
1431 None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
1432 _ => {}
1433 }
1434 }
1435 }
1436 }
1437}
1438
1439#[cfg(feature = "rfq-v2")]
1440async fn authenticate_rfq_v2_socket<S>(
1441 socket: &mut S,
1442 shared: &WsClientShared,
1443 grant: &RfqV2SocketGrant,
1444 shutdown_rx: &mut watch::Receiver<bool>,
1445 timeout: Duration,
1446) -> std::result::Result<(), SessionStop>
1447where
1448 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1449 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1450 + Unpin,
1451{
1452 let auth_msg = sonic_rs::to_string(&WsMessage::AuthenticateRfqV2 {
1453 token: grant.token.clone(),
1454 })
1455 .map_err(|error| {
1456 SessionStop::NonReconnectable(WsDisconnectReason::Protocol(format!(
1457 "failed to serialize RFQ authentication: {error}"
1458 )))
1459 })?;
1460 socket
1461 .send(tungstenite::Message::Text(auth_msg))
1462 .await
1463 .map_err(|error| {
1464 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1465 })?;
1466
1467 let deadline = tokio::time::sleep(timeout);
1468 tokio::pin!(deadline);
1469 loop {
1470 tokio::select! {
1471 changed = shutdown_rx.changed() => {
1472 if changed.is_err() || *shutdown_rx.borrow() {
1473 return Err(SessionStop::Shutdown);
1474 }
1475 }
1476 _ = &mut deadline => {
1477 return Err(SessionStop::Disconnected(WsDisconnectReason::Protocol(
1478 "timed out waiting for RFQ authentication response".to_string(),
1479 )));
1480 }
1481 incoming = socket.next() => {
1482 match incoming {
1483 Some(Ok(tungstenite::Message::Text(text))) => {
1484 let Some(json) = record_text(shared, &text).await else {
1485 continue;
1486 };
1487 match json.get("type").and_then(|value| value.as_str()) {
1488 Some("RfqV2Authenticated") => {
1489 let account = json
1490 .get("account")
1491 .and_then(|value| value.as_str())
1492 .ok_or_else(|| SessionStop::NonReconnectable(
1493 WsDisconnectReason::Protocol(
1494 "RFQ authentication response omitted account".to_string(),
1495 )
1496 ))?;
1497 if !account.eq_ignore_ascii_case(&grant.account) {
1498 return Err(SessionStop::NonReconnectable(
1499 WsDisconnectReason::Protocol(
1500 "RFQ authenticated account does not match signed grant".to_string(),
1501 ),
1502 ));
1503 }
1504 return Ok(());
1505 }
1506 Some("Error") => {
1507 let message = json
1508 .get("message")
1509 .and_then(|value| value.as_str())
1510 .unwrap_or("RFQ authentication failed");
1511 return Err(SessionStop::NonReconnectable(
1512 WsDisconnectReason::Protocol(message.to_string()),
1513 ));
1514 }
1515 _ => {}
1516 }
1517 }
1518 Some(Ok(tungstenite::Message::Ping(payload))) => {
1519 socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
1520 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1521 })?;
1522 }
1523 Some(Ok(tungstenite::Message::Pong(payload))) => {
1524 shared.pongs.lock().await.push(payload);
1525 }
1526 Some(Ok(tungstenite::Message::Close(frame))) => {
1527 return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
1528 }
1529 Some(Err(error)) => {
1530 return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string())));
1531 }
1532 None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
1533 _ => {}
1534 }
1535 }
1536 }
1537 }
1538}
1539
1540async fn replay_subscriptions<S>(
1541 socket: &mut S,
1542 shared: &WsClientShared,
1543 subscriptions: &BTreeMap<String, DesiredSubscription>,
1544 shutdown_rx: &mut watch::Receiver<bool>,
1545 timeout: Duration,
1546) -> std::result::Result<(), SessionStop>
1547where
1548 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1549 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1550 + Unpin,
1551{
1552 let mut pending = BTreeMap::<String, usize>::new();
1553 for subscription in subscriptions.values() {
1554 socket
1555 .send(tungstenite::Message::Text(subscription.subscribe.clone()))
1556 .await
1557 .map_err(|error| {
1558 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1559 })?;
1560 *pending.entry(subscription.channel.clone()).or_default() += 1;
1561 }
1562
1563 let deadline = tokio::time::sleep(timeout);
1564 tokio::pin!(deadline);
1565 while !pending.is_empty() {
1566 tokio::select! {
1567 changed = shutdown_rx.changed() => {
1568 if changed.is_err() || *shutdown_rx.borrow() {
1569 return Err(SessionStop::Shutdown);
1570 }
1571 }
1572 _ = &mut deadline => {
1573 return Err(SessionStop::NonReconnectable(WsDisconnectReason::Protocol(format!(
1574 "timed out restoring subscriptions: {}",
1575 pending
1576 .into_iter()
1577 .map(|(channel, count)| format!("{} ({})", channel, count))
1578 .collect::<Vec<_>>()
1579 .join(", ")
1580 ))));
1581 }
1582 incoming = socket.next() => {
1583 match incoming {
1584 Some(Ok(tungstenite::Message::Text(text))) => {
1585 let Some(json) = record_text(shared, &text).await else {
1586 continue;
1587 };
1588 let v2_refusal = is_unbatched_v2_confirmation(&json);
1593 let v2_all_logical = subscriptions
1594 .values()
1595 .filter(|desired| desired.channel == INDICATIVE_V2_CHANNEL)
1596 .all(|desired| desired.logical_indicative && !desired.direct);
1597 if v2_refusal && !v2_all_logical {
1598 return Err(SessionStop::NonReconnectable(
1599 WsDisconnectReason::Protocol(format!(
1600 "server does not support {INDICATIVE_V2_CHANNEL}; \
1601 direct subscriptions to it cannot be restored"
1602 )),
1603 ));
1604 }
1605 match json.get("type").and_then(|value| value.as_str()) {
1606 Some("Subscribed") => {
1607 if let Some(channel) = json.get("channel").and_then(|value| value.as_str()) {
1608 if let Some(count) = pending.get_mut(channel) {
1609 *count -= 1;
1610 if *count == 0 {
1611 pending.remove(channel);
1612 }
1613 }
1614 }
1615 }
1616 Some("Error") if v2_refusal => {
1619 if let Some(count) = pending.get_mut(INDICATIVE_V2_CHANNEL) {
1620 *count -= 1;
1621 if *count == 0 {
1622 pending.remove(INDICATIVE_V2_CHANNEL);
1623 }
1624 }
1625 }
1626 Some("Error") => {
1627 let message = json
1628 .get("message")
1629 .and_then(|value| value.as_str())
1630 .unwrap_or("subscription restoration failed");
1631 return Err(SessionStop::NonReconnectable(
1632 WsDisconnectReason::Protocol(message.to_string()),
1633 ));
1634 }
1635 _ => {}
1636 }
1637 }
1638 Some(Ok(tungstenite::Message::Ping(payload))) => {
1639 socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
1640 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1641 })?;
1642 }
1643 Some(Ok(tungstenite::Message::Pong(payload))) => {
1644 shared.pongs.lock().await.push(payload);
1645 }
1646 Some(Ok(tungstenite::Message::Close(frame))) => {
1647 return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
1648 }
1649 Some(Err(error)) => {
1650 return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(
1651 error.to_string(),
1652 )));
1653 }
1654 None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
1655 _ => {}
1656 }
1657 }
1658 }
1659 }
1660 Ok(())
1661}
1662
1663async fn run_connected_socket<S>(
1664 socket: &mut S,
1665 shared: &WsClientShared,
1666 outbound_rx: &mut mpsc::Receiver<tungstenite::Message>,
1667 shutdown_rx: &mut watch::Receiver<bool>,
1668) -> SessionStop
1669where
1670 S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
1671 + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
1672 + Unpin,
1673{
1674 loop {
1678 tokio::select! {
1679 changed = shutdown_rx.changed() => {
1680 if changed.is_err() || *shutdown_rx.borrow() {
1681 let _ = socket.send(tungstenite::Message::Close(None)).await;
1682 return SessionStop::Shutdown;
1683 }
1684 }
1685 outbound = outbound_rx.recv() => {
1686 let Some(outbound) = outbound else {
1687 return SessionStop::Shutdown;
1688 };
1689 if let Err(error) = socket.send(outbound).await {
1690 return SessionStop::Disconnected(WsDisconnectReason::Transport(
1691 error.to_string(),
1692 ));
1693 }
1694 }
1695 incoming = socket.next() => {
1696 match incoming {
1697 Some(Ok(tungstenite::Message::Text(text))) => {
1698 let _ = record_text(shared, &text).await;
1699 if let Err(stop) = apply_v2_fallback(socket, shared).await {
1700 return stop;
1701 }
1702 }
1703 Some(Ok(tungstenite::Message::Ping(payload))) => {
1704 if let Err(error) = socket.send(tungstenite::Message::Pong(payload)).await {
1705 return SessionStop::Disconnected(WsDisconnectReason::Transport(
1706 error.to_string(),
1707 ));
1708 }
1709 }
1710 Some(Ok(tungstenite::Message::Pong(payload))) => {
1711 shared.pongs.lock().await.push(payload);
1712 }
1713 Some(Ok(tungstenite::Message::Close(frame))) => {
1714 return SessionStop::Disconnected(disconnect_reason_from_close(frame));
1715 }
1716 Some(Err(error)) => {
1717 return SessionStop::Disconnected(WsDisconnectReason::Transport(
1718 error.to_string(),
1719 ));
1720 }
1721 None => return SessionStop::Disconnected(WsDisconnectReason::EndOfStream),
1722 _ => {}
1723 }
1724 }
1725 }
1726 }
1727}
1728
1729#[expect(clippy::too_many_lines, reason = "pre-existing; split pending")]
1730async fn run_ws_session(
1731 shared: Arc<WsClientShared>,
1732 config: WsClientConfig,
1733 ws_url: String,
1734 options: ConnectOptions,
1735 credentials: SessionCredentials,
1736 mut shutdown_rx: watch::Receiver<bool>,
1737 initial_tx: oneshot::Sender<Result<()>>,
1738) {
1739 let mut initial_tx = Some(initial_tx);
1740 let mut reconnecting = false;
1741 let mut attempt = 0_u32;
1742
1743 loop {
1744 if reconnecting {
1745 let delay = reconnect_delay(config, attempt);
1746 set_state(&shared, WsConnectionState::Reconnecting { attempt, delay });
1747 tokio::select! {
1748 changed = shutdown_rx.changed() => {
1749 if changed.is_err() || *shutdown_rx.borrow() {
1750 finish_session(&shared);
1751 return;
1752 }
1753 }
1754 _ = tokio::time::sleep(delay) => {}
1755 }
1756 }
1757
1758 if rfq_v2_expires_at_ms(&shared)
1759 .is_some_and(|expires_at_ms| current_unix_ms().is_none_or(|now| now >= expires_at_ms))
1760 {
1761 let reason = WsDisconnectReason::Protocol(
1762 "RFQ V2 read grant expired; sign a fresh grant".to_string(),
1763 );
1764 record_disconnect(&shared, reason.clone());
1765 finish_session(&shared);
1766 if let Some(initial_tx) = initial_tx.take() {
1767 let _ = initial_tx.send(Err(ClientError::WebSocket(format!("{reason:?}"))));
1768 }
1769 return;
1770 }
1771
1772 set_state(&shared, WsConnectionState::Connecting { attempt });
1773 debug!("Connecting to WebSocket: {}", ws_url);
1774 let connect_result = tokio::select! {
1775 changed = shutdown_rx.changed() => {
1776 if changed.is_err() || *shutdown_rx.borrow() {
1777 finish_session(&shared);
1778 if let Some(initial_tx) = initial_tx.take() {
1779 let _ = initial_tx.send(Err(ClientError::WebSocket(
1780 "WebSocket connection stopped before startup".to_string(),
1781 )));
1782 }
1783 return;
1784 }
1785 continue;
1786 }
1787 result = connect_socket(&ws_url, options) => result,
1788 };
1789
1790 let (mut socket, response) = match connect_result {
1791 Ok(connection) => connection,
1792 Err(error) => {
1793 let reason = WsDisconnectReason::Transport(error.to_string());
1794 record_disconnect(&shared, reason.clone());
1795 if !reconnecting {
1796 finish_session(&shared);
1797 if let Some(initial_tx) = initial_tx.take() {
1798 let _ = initial_tx.send(Err(ClientError::WebSocket(format!(
1799 "Failed to connect: {}",
1800 error
1801 ))));
1802 }
1803 return;
1804 }
1805 attempt = attempt.saturating_add(1);
1806 continue;
1807 }
1808 };
1809 info!(
1810 permessage_deflate = socket.get_ref().deflate_negotiated(),
1811 "WebSocket connected, status: {}",
1812 response.status()
1813 );
1814
1815 let handshake_result = async {
1816 if let Some(wallet) = credentials.wallet.as_deref() {
1817 set_state(&shared, WsConnectionState::Authenticating);
1818 authenticate_socket(
1819 &mut socket,
1820 &shared,
1821 wallet,
1822 &mut shutdown_rx,
1823 config.authentication_timeout,
1824 )
1825 .await?;
1826 info!("WebSocket authenticated as wallet: {}", wallet);
1827 }
1828
1829 #[cfg(feature = "rfq-v2")]
1830 if let Some(grant) = current_rfq_v2_grant(&shared).as_ref() {
1831 set_state(&shared, WsConnectionState::Authenticating);
1832 authenticate_rfq_v2_socket(
1833 &mut socket,
1834 &shared,
1835 grant,
1836 &mut shutdown_rx,
1837 config.authentication_timeout,
1838 )
1839 .await?;
1840 }
1841
1842 let mut subscriptions = shared.subscriptions.write().await;
1847 if !subscriptions.is_empty() {
1848 set_state(
1849 &shared,
1850 WsConnectionState::Resubscribing {
1851 channels: subscriptions.len(),
1852 },
1853 );
1854 replay_subscriptions(
1855 &mut socket,
1856 &shared,
1857 &subscriptions,
1858 &mut shutdown_rx,
1859 config.subscription_timeout,
1860 )
1861 .await?;
1862 }
1863 let (unsubscribes, replacements) =
1867 take_v2_fallback_locked(&shared, &mut subscriptions)?;
1868 for frame in unsubscribes {
1869 socket
1870 .send(tungstenite::Message::Text(frame))
1871 .await
1872 .map_err(|error| {
1873 SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
1874 })?;
1875 }
1876 if !replacements.is_empty() {
1877 replay_subscriptions(
1878 &mut socket,
1879 &shared,
1880 &replacements,
1881 &mut shutdown_rx,
1882 config.subscription_timeout,
1883 )
1884 .await?;
1885 }
1886
1887 let mut recovery_plan = WsRecoveryPlan::default();
1888 for subscription in subscriptions.values() {
1889 recovery_plan.include_channel(&subscription.channel);
1890 }
1891 let (tx, outbound_rx) = mpsc::channel(OUTBOUND_CONTROL_CAPACITY);
1892 *shared.tx.lock().expect("WebSocket sender mutex poisoned") = Some(tx);
1893 if reconnecting && !recovery_plan.is_empty() {
1894 set_state(&shared, WsConnectionState::RecoveryRequired(recovery_plan));
1895 } else {
1896 set_state(&shared, WsConnectionState::Ready);
1897 }
1898 drop(subscriptions);
1899 Ok::<_, SessionStop>(outbound_rx)
1900 }
1901 .await;
1902
1903 let mut outbound_rx = match handshake_result {
1904 Ok(outbound_rx) => outbound_rx,
1905 Err(SessionStop::Shutdown) => {
1906 finish_session(&shared);
1907 if let Some(initial_tx) = initial_tx.take() {
1908 let _ = initial_tx.send(Err(ClientError::WebSocket(
1909 "WebSocket connection stopped before startup".to_string(),
1910 )));
1911 }
1912 return;
1913 }
1914 Err(SessionStop::NonReconnectable(reason)) => {
1915 record_disconnect(&shared, reason.clone());
1916 finish_session(&shared);
1917 if let Some(initial_tx) = initial_tx.take() {
1918 let _ = initial_tx.send(Err(ClientError::WebSocket(format!(
1919 "WebSocket handshake failed: {:?}",
1920 reason
1921 ))));
1922 }
1923 return;
1924 }
1925 Err(stop) => {
1926 if let SessionStop::Disconnected(reason) = &stop {
1927 record_disconnect(&shared, reason.clone());
1928 }
1929 if !reconnecting {
1930 finish_session(&shared);
1931 if let Some(initial_tx) = initial_tx.take() {
1932 let _ = initial_tx
1933 .send(Err(stop.websocket_error("WebSocket handshake failed")));
1934 }
1935 return;
1936 }
1937 attempt = attempt.saturating_add(1);
1938 continue;
1939 }
1940 };
1941
1942 let was_reconnect = reconnecting;
1943 if let Some(initial_tx) = initial_tx.take() {
1944 let _ = initial_tx.send(Ok(()));
1945 }
1946 reconnecting = true;
1947 let connected_at = tokio::time::Instant::now();
1948
1949 match run_connected_socket(&mut socket, &shared, &mut outbound_rx, &mut shutdown_rx).await {
1950 SessionStop::Shutdown => {
1951 finish_session(&shared);
1952 return;
1953 }
1954 SessionStop::NonReconnectable(reason) => {
1955 record_disconnect(&shared, reason);
1956 finish_session(&shared);
1957 return;
1958 }
1959 SessionStop::Disconnected(reason) => {
1960 warn!(?reason, "WebSocket disconnected; scheduling reconnect");
1961 record_disconnect(&shared, reason);
1962 *shared.tx.lock().expect("WebSocket sender mutex poisoned") = None;
1963 if !was_reconnect || connected_at.elapsed() >= config.reconnect_reset_after {
1964 attempt = 0;
1965 } else {
1966 attempt = attempt.saturating_add(1);
1967 }
1968 }
1969 }
1970 }
1971}
1972
1973impl Default for WsClient {
1974 fn default() -> Self {
1975 Self::new()
1976 }
1977}
1978
1979#[cfg(test)]
1980#[path = "websocket_reconnect_test.rs"]
1981mod reconnect_tests;
1982
1983#[cfg(test)]
1984#[path = "websocket_deflate_test.rs"]
1985mod deflate_tests;
1986
1987#[cfg(test)]
1988#[path = "websocket_test.rs"]
1989mod tests;