1use std::{
19 collections::VecDeque,
20 sync::{
21 Arc,
22 atomic::{AtomicBool, AtomicU64, Ordering},
23 },
24 time::Duration,
25};
26
27use dashmap::DashMap;
28use nautilus_core::string::secret::SecretString;
29use nautilus_live::book::snapshot::SnapshotGate;
30use nautilus_network::{
31 error::SendError,
32 retry::{RetryManager, create_websocket_retry_manager},
33 websocket::{AuthTracker, SubscriptionState, WebSocketClient},
34};
35use serde::Serialize;
36use serde_json::Value;
37use tokio_tungstenite::tungstenite::Message;
38use tokio_util::sync::CancellationToken;
39
40use super::{
41 enums::BybitWsOperation,
42 error::{BybitWsError, BybitWsResult, create_bybit_timeout_error, should_retry_bybit_error},
43 messages::{
44 BybitSubscription, BybitWebSocketError, BybitWsFrame, BybitWsMessage, BybitWsResponse,
45 BybitWsSubscriptionMsg,
46 },
47 parse::parse_bybit_ws_frame,
48};
49use crate::common::{
50 enums::{BybitProductType, BybitWsOrderRequestOp},
51 rate_limit::{
52 BYBIT_RATE_LIMIT_HEADER, BYBIT_RATE_LIMIT_RESET_HEADER, BYBIT_RATE_LIMIT_STATUS_HEADER,
53 BybitRateLimiter,
54 },
55};
56
57#[derive(Debug)]
59pub struct BybitWsOrderCommand {
60 pub(crate) req_id: String,
61 pub(crate) op: BybitWsOrderRequestOp,
62 pub(crate) category: BybitProductType,
63 pub(crate) weight: u32,
64 pub(crate) referer: Option<String>,
65 pub(crate) args: Vec<Value>,
66}
67
68#[derive(Debug, Serialize)]
69#[serde(rename_all = "camelCase")]
70struct BybitWsSignedOrderRequest {
71 req_id: String,
72 op: BybitWsOrderRequestOp,
73 header: BybitWsSignedOrderHeader,
74 args: Vec<Value>,
75}
76
77#[derive(Debug, Serialize)]
78#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
79struct BybitWsSignedOrderHeader {
80 x_bapi_timestamp: String,
81 x_bapi_recv_window: String,
82 #[serde(rename = "Referer", skip_serializing_if = "Option::is_none")]
83 referer: Option<String>,
84}
85
86#[derive(Clone, Copy, Debug)]
87struct PendingRate {
88 endpoint: &'static str,
89 category: BybitProductType,
90}
91
92#[derive(Debug)]
93enum OrderSendFailure {
94 NotSent(BybitWsError),
95 Ambiguous(BybitWsError),
96}
97
98#[derive(Debug)]
100pub enum HandlerCommand {
101 SetClient(WebSocketClient),
102 Disconnect,
103 Authenticate {
104 payload: SecretString,
105 },
106 Subscribe {
107 topics: Vec<String>,
108 },
109 SubscribeBook {
113 payload: String,
114 gate: SnapshotGate,
115 completion: tokio::sync::oneshot::Sender<BybitWsResult<()>>,
116 },
117 Unsubscribe {
118 topics: Vec<String>,
119 },
120 ResubscribeBook {
123 topic: String,
124 cancel: CancellationToken,
125 gate: SnapshotGate,
126 completion: tokio::sync::oneshot::Sender<BybitWsResult<()>>,
127 },
128 SendOrder {
129 command: BybitWsOrderCommand,
130 },
131 SendOrders {
132 commands: Vec<BybitWsOrderCommand>,
133 },
134}
135
136pub(super) struct BybitWsFeedHandler {
137 signal: Arc<AtomicBool>,
138 inner: Option<WebSocketClient>,
139 cmd_rx: tokio::sync::mpsc::UnboundedReceiver<HandlerCommand>,
140 raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
141 auth_tracker: AuthTracker,
142 auth_timeout: Duration,
143 auth_deadline: Option<tokio::time::Instant>,
144 subscriptions: SubscriptionState,
145 rate_limiter: BybitRateLimiter,
146 recv_window_ms: Arc<AtomicU64>,
147 pending_rates: DashMap<String, PendingRate>,
148 pending_orders: VecDeque<BybitWsOrderCommand>,
149 retry_manager: RetryManager<BybitWsError>,
150}
151
152impl BybitWsFeedHandler {
153 #[expect(
155 clippy::too_many_arguments,
156 reason = "handler owns the channels and shared session state"
157 )]
158 pub(super) fn new(
159 signal: Arc<AtomicBool>,
160 cmd_rx: tokio::sync::mpsc::UnboundedReceiver<HandlerCommand>,
161 raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
162 auth_tracker: AuthTracker,
163 auth_timeout: Duration,
164 subscriptions: SubscriptionState,
165 rate_limiter: BybitRateLimiter,
166 recv_window_ms: Arc<AtomicU64>,
167 ) -> Self {
168 Self {
169 signal,
170 inner: None,
171 cmd_rx,
172 raw_rx,
173 auth_tracker,
174 auth_timeout,
175 auth_deadline: None,
176 subscriptions,
177 rate_limiter,
178 recv_window_ms,
179 pending_rates: DashMap::new(),
180 pending_orders: VecDeque::new(),
181 retry_manager: create_websocket_retry_manager(),
182 }
183 }
184
185 pub(super) fn is_stopped(&self) -> bool {
186 self.signal.load(Ordering::Relaxed)
187 }
188
189 async fn send_with_retry(&self, payload: String) -> Result<(), BybitWsError> {
191 self.send_secret_with_retry(payload.into(), None).await
192 }
193
194 async fn send_secret_with_retry(
195 &self,
196 payload: SecretString,
197 connection_epoch: Option<u64>,
198 ) -> Result<(), BybitWsError> {
199 if let Some(client) = &self.inner {
200 self.retry_manager
201 .invocation(
202 "websocket_send",
203 || {
204 let payload = payload.clone();
205 async move {
206 let payload = payload.expose_secret().to_owned();
207
208 let result = match connection_epoch {
209 Some(epoch) => {
210 client.send_text_on_connection(payload, None, epoch).await
211 }
212 None => client.send_text(payload, None).await,
213 };
214
215 result.map_err(|e| match e {
216 SendError::ConnectionChanged => BybitWsError::Authentication(
217 "Connection changed before authentication".to_string(),
218 ),
219 e => BybitWsError::Transport(format!("Send failed: {e}")),
220 })
221 }
222 },
223 should_retry_bybit_error,
224 |e| create_bybit_timeout_error(e.to_string()),
225 )
226 .execute()
227 .await
228 } else {
229 Err(BybitWsError::ClientError(
230 "No active WebSocket client".to_string(),
231 ))
232 }
233 }
234
235 async fn write_book_subscription(&self, payload: String) -> BybitWsResult<()> {
237 let client = self.inner.as_ref().ok_or(BybitWsError::NotConnected)?;
238 let epoch = client.connection_epoch();
239
240 client
241 .send_text_on_connection(payload, None, epoch)
242 .await
243 .map_err(|e| BybitWsError::Transport(e.to_string()))
244 }
245
246 async fn resubscribe_book(&self, topic: &str) -> BybitWsResult<()> {
249 let client = self.inner.as_ref().ok_or(BybitWsError::NotConnected)?;
250 let epoch = client.connection_epoch();
251
252 self.subscriptions.mark_failure(topic);
254
255 let topic = topic.to_string();
256
257 for op in [BybitWsOperation::Unsubscribe, BybitWsOperation::Subscribe] {
258 let request = BybitSubscription {
259 op,
260 args: vec![topic.clone()],
261 req_id: Some(topic.clone()),
262 };
263
264 let payload = serde_json::to_string(&request)?;
265 client.send_text_on_connection(payload, None, epoch).await?;
266 }
267
268 Ok(())
269 }
270
271 async fn send_order(&self, command: &BybitWsOrderCommand) -> Result<bool, OrderSendFailure> {
272 if !self.auth_tracker.is_authenticated() {
273 return Ok(false);
274 }
275
276 let client = self.inner.as_ref().ok_or_else(|| {
277 OrderSendFailure::NotSent(BybitWsError::ClientError(
278 "No active WebSocket client".to_string(),
279 ))
280 })?;
281 let (endpoint, _) = order_operation(command.op);
282
283 self.rate_limiter
284 .acquire_ws_order(endpoint, command.category, command.weight)
285 .await
286 .map_err(|e| OrderSendFailure::NotSent(BybitWsError::ClientError(e)))?;
287
288 if !self.auth_tracker.is_authenticated() {
289 return Ok(false);
290 }
291
292 let connection_epoch = client.connection_epoch();
293 let recv_window_ms = self.recv_window_ms.load(Ordering::Acquire);
294 let request = BybitWsSignedOrderRequest {
295 req_id: command.req_id.clone(),
296 op: command.op,
297 header: BybitWsSignedOrderHeader {
298 x_bapi_timestamp: nautilus_core::time::get_atomic_clock_realtime()
299 .get_time_ms()
300 .to_string(),
301 x_bapi_recv_window: recv_window_ms.to_string(),
302 referer: command.referer.clone(),
303 },
304 args: command.args.clone(),
305 };
306 let payload = serde_json::to_string(&request)
307 .map_err(|e| OrderSendFailure::NotSent(BybitWsError::Json(e.to_string())))?;
308 self.pending_rates.insert(
309 command.req_id.clone(),
310 PendingRate {
311 endpoint,
312 category: command.category,
313 },
314 );
315
316 match client
317 .send_text_on_connection(payload, None, connection_epoch)
318 .await
319 {
320 Ok(()) => Ok(true),
321 Err(e) => self.classify_order_send_error(&command.req_id, e),
322 }
323 }
324
325 fn classify_order_send_error(
326 &self,
327 req_id: &str,
328 error: SendError,
329 ) -> Result<bool, OrderSendFailure> {
330 match error {
331 SendError::ConnectionChanged => {
332 self.pending_rates.remove(req_id);
333 self.auth_tracker.invalidate();
334 Ok(false)
335 }
336 SendError::Timeout => {
337 self.pending_rates.remove(req_id);
338 self.auth_tracker.invalidate();
339 Err(OrderSendFailure::NotSent(BybitWsError::ClientError(
340 "Order command was not written".to_string(),
341 )))
342 }
343 SendError::InvalidInput(_) | SendError::BufferFull | SendError::Closed => {
344 self.pending_rates.remove(req_id);
345 Err(OrderSendFailure::NotSent(BybitWsError::ClientError(
346 "Order command was not written".to_string(),
347 )))
348 }
349 error => Err(OrderSendFailure::Ambiguous(BybitWsError::Send(
350 error.to_string(),
351 ))),
352 }
353 }
354
355 pub(super) async fn next(&mut self) -> Option<BybitWsMessage> {
356 loop {
357 if self.auth_tracker.is_authenticated()
358 && let Some(command) = self.pending_orders.pop_front()
359 {
360 let req_id = command.req_id.clone();
361 match self.send_order(&command).await {
362 Ok(true) => {}
363 Ok(false) => self.pending_orders.push_front(command),
364 Err(OrderSendFailure::NotSent(error)) => {
365 return Some(order_not_sent_message(&command, &error));
366 }
367 Err(OrderSendFailure::Ambiguous(error)) => {
368 log::warn!("Ambiguous order send failure: req_id={req_id}, error={error}");
369 }
370 }
371 continue;
372 }
373
374 tokio::select! {
375 Some(cmd) = self.cmd_rx.recv() => {
376 match cmd {
377 HandlerCommand::SetClient(client) => {
378 log::debug!("WebSocketClient received by handler");
379 self.inner = Some(client);
380 }
381 HandlerCommand::Disconnect => {
382 log::debug!("Disconnect command received");
383
384 if let Some(client) = self.inner.take() {
385 client.disconnect().await;
386 }
387 }
388 HandlerCommand::Authenticate { payload } => {
389 log::debug!("Authenticate command received");
390
391 let epoch = self.inner.as_ref().map(WebSocketClient::connection_epoch);
392 if let Err(e) = self.send_secret_with_retry(payload, epoch).await {
393 log::error!("Failed to send authentication after retries: {e}");
394 }
395 self.auth_deadline = Some(tokio::time::Instant::now() + self.auth_timeout);
396 }
397 HandlerCommand::Subscribe { topics } => {
398 for topic in topics {
399 log::debug!("Subscribing to topic: topic={topic}");
400 if let Err(e) = self.send_with_retry(topic.clone()).await {
401 log::error!("Failed to send subscription after retries: topic={topic}, error={e}");
402 }
403 }
404 }
405 HandlerCommand::SubscribeBook { payload, gate, completion } => {
406 let result = self.write_book_subscription(payload).await;
407
408 if result.is_ok() {
409 gate.open();
410 }
411 let _ = completion.send(result);
412 }
413 HandlerCommand::Unsubscribe { topics } => {
414 for topic in topics {
415 log::debug!("Unsubscribing from topic: topic={topic}");
416 if let Err(e) = self.send_with_retry(topic.clone()).await {
417 log::error!("Failed to send unsubscription after retries: topic={topic}, error={e}");
418 }
419 }
420 }
421 HandlerCommand::ResubscribeBook { topic, cancel, gate, completion } => {
422 if cancel.is_cancelled() {
423 continue;
424 }
425
426 let result = self.resubscribe_book(&topic).await;
427
428 if result.is_ok() {
429 gate.open();
430 }
431 let _ = completion.send(result);
432 }
433 HandlerCommand::SendOrder { command } => {
434 let req_id = command.req_id.clone();
435 match self.send_order(&command).await {
436 Ok(true) => {}
437 Ok(false) => self.pending_orders.push_back(command),
438 Err(OrderSendFailure::NotSent(error)) => {
439 return Some(order_not_sent_message(&command, &error));
440 }
441 Err(OrderSendFailure::Ambiguous(error)) => {
442 log::warn!(
443 "Ambiguous order send failure: req_id={req_id}, error={error}"
444 );
445 }
446 }
447 }
448 HandlerCommand::SendOrders { commands } => {
449 self.pending_orders.extend(commands);
450 }
451 }
452 }
453
454 () = tokio::time::sleep_until(
456 self.auth_deadline.unwrap_or_else(tokio::time::Instant::now),
457 ), if self.auth_deadline.is_some() => {
458 self.auth_deadline = None;
459 log::error!(
460 "WebSocket authentication timed out: timeout={:?}",
461 self.auth_timeout
462 );
463 self.auth_tracker.fail("Authentication timed out");
464 }
465
466 () = tokio::time::sleep(std::time::Duration::from_millis(100)) => {
467 if self.signal.load(Ordering::Relaxed) {
468 log::debug!("Stop signal received during idle period");
469 return None;
470 }
471 }
472
473 msg = self.raw_rx.recv() => {
474 let msg = match msg {
475 Some(msg) => msg,
476 None => {
477 log::debug!("WebSocket stream closed");
478 return None;
479 }
480 };
481
482 if let Message::Ping(data) = &msg {
483 log::trace!("Received ping frame with {} bytes", data.len());
484
485 if let Some(client) = &self.inner
486 && let Err(e) = client.send_pong(data.to_vec()).await
487 {
488 log::warn!("Failed to send pong frame: error={e}");
489 }
490 continue;
491 }
492
493 let frame = match Self::parse_raw_frame(msg) {
494 Some(frame) => frame,
495 None => continue,
496 };
497
498 if self.signal.load(Ordering::Relaxed) {
499 log::debug!("Stop signal received");
500 return None;
501 }
502
503 match frame {
504 BybitWsFrame::Subscription(ref sub_msg) => {
505 self.handle_subscription_ack(sub_msg);
506 }
507 BybitWsFrame::Auth(auth_response) => {
508 self.auth_deadline = None;
509 let is_success = auth_response.success.unwrap_or(false)
510 || (auth_response.ret_code == Some(0));
511
512 if is_success {
513 self.auth_tracker.succeed();
514 log::debug!("WebSocket authenticated");
515 } else {
516 let error_msg = auth_response
517 .ret_msg
518 .as_deref()
519 .unwrap_or("Authentication rejected");
520 self.auth_tracker.fail(error_msg);
521 log::error!("WebSocket authentication failed: error={error_msg}");
522 }
523 return Some(BybitWsMessage::Auth(auth_response));
524 }
525 BybitWsFrame::ErrorResponse(ref resp) => {
526 if resp.op == Some(BybitWsOperation::Auth) {
532 self.auth_deadline = None;
533 let error_msg = resp
534 .ret_msg
535 .as_deref()
536 .unwrap_or("Authentication rejected");
537 self.auth_tracker.fail(error_msg);
538 log::error!("WebSocket authentication failed: error={error_msg}");
539 }
540
541 if let Some(op) = &resp.op {
542 if *op == BybitWsOperation::Subscribe
543 || *op == BybitWsOperation::Unsubscribe
544 {
545 self.handle_subscription_error(resp);
546 } else {
547 let error = BybitWebSocketError::from_response(resp);
548 return Some(BybitWsMessage::Error(error));
549 }
550 } else {
551 let error = BybitWebSocketError::from_response(resp);
552 return Some(BybitWsMessage::Error(error));
553 }
554 }
555 BybitWsFrame::OrderResponse(resp) => {
556 self.observe_order_rate_limit(&resp);
557 return Some(BybitWsMessage::OrderResponse(resp));
558 }
559 BybitWsFrame::Orderbook(msg) => {
560 return Some(BybitWsMessage::Orderbook(msg));
561 }
562 BybitWsFrame::Trade(msg) => {
563 return Some(BybitWsMessage::Trade(msg));
564 }
565 BybitWsFrame::Liquidation(msg) => {
566 return Some(BybitWsMessage::Liquidation(msg));
567 }
568 BybitWsFrame::Kline(msg) => {
569 return Some(BybitWsMessage::Kline(msg));
570 }
571 BybitWsFrame::TickerLinear(msg) => {
572 return Some(BybitWsMessage::TickerLinear(msg));
573 }
574 BybitWsFrame::TickerOption(msg) => {
575 return Some(BybitWsMessage::TickerOption(msg));
576 }
577 BybitWsFrame::AccountOrder(msg) => {
578 return Some(BybitWsMessage::AccountOrder(msg));
579 }
580 BybitWsFrame::AccountExecution(msg) => {
581 return Some(BybitWsMessage::AccountExecution(msg));
582 }
583 BybitWsFrame::AccountExecutionFast(msg) => {
584 return Some(BybitWsMessage::AccountExecutionFast(msg));
585 }
586 BybitWsFrame::AccountWallet(msg) => {
587 return Some(BybitWsMessage::AccountWallet(msg));
588 }
589 BybitWsFrame::AccountPosition(msg) => {
590 return Some(BybitWsMessage::AccountPosition(msg));
591 }
592 BybitWsFrame::Reconnected => {
593 self.auth_deadline = None;
594 self.auth_tracker.invalidate();
595 return Some(BybitWsMessage::Reconnected);
596 }
597 BybitWsFrame::Unknown(value) => {
598 log::debug!("Unknown WebSocket frame: {value}");
599 }
600 }
601 }
602 }
603 }
604 }
605
606 fn observe_order_rate_limit(&self, response: &super::messages::BybitWsOrderResponse) {
607 let Some(req_id) = response.req_id.as_deref() else {
608 return;
609 };
610 let Some((_, pending)) = self.pending_rates.remove(req_id) else {
611 return;
612 };
613 let Some(header) = response.header.as_ref() else {
614 return;
615 };
616 let parse_u32 = |key: &str| {
617 header.get(key).and_then(|value| {
618 value
619 .as_u64()
620 .and_then(|value| u32::try_from(value).ok())
621 .or_else(|| value.as_str()?.parse::<u32>().ok())
622 })
623 };
624 let Some(limit) = parse_u32(BYBIT_RATE_LIMIT_HEADER) else {
625 return;
626 };
627 let Some(remaining) = parse_u32(BYBIT_RATE_LIMIT_STATUS_HEADER) else {
628 return;
629 };
630 let reset_timestamp_ms = header.get(BYBIT_RATE_LIMIT_RESET_HEADER).and_then(|value| {
631 value
632 .as_i64()
633 .or_else(|| value.as_str()?.parse::<i64>().ok())
634 });
635 self.rate_limiter.observe_account(
636 pending.endpoint,
637 Some(pending.category),
638 limit,
639 remaining,
640 reset_timestamp_ms,
641 );
642 }
643
644 fn handle_subscription_ack(&self, sub_msg: &BybitWsSubscriptionMsg) {
645 match sub_msg.op {
646 BybitWsOperation::Subscribe => {
647 if sub_msg.success {
648 if let Some(topic) = &sub_msg.req_id {
649 self.subscriptions.confirm_subscribe(topic);
650 log::debug!("Subscription confirmed: topic={topic}");
651 } else {
652 for topic in self.subscriptions.pending_subscribe_topics() {
654 self.subscriptions.confirm_subscribe(&topic);
655 log::debug!("Subscription confirmed (bulk): topic={topic}");
656 }
657 }
658 } else if let Some(topic) = &sub_msg.req_id {
659 self.subscriptions.mark_failure(topic);
660 log::warn!(
661 "Subscription failed: topic={topic}, error={:?}",
662 sub_msg.ret_msg
663 );
664 } else {
665 for topic in self.subscriptions.pending_subscribe_topics() {
666 self.subscriptions.mark_failure(&topic);
667 log::warn!(
668 "Subscription failed (bulk): topic={topic}, error={:?}",
669 sub_msg.ret_msg
670 );
671 }
672 }
673 }
674 BybitWsOperation::Unsubscribe => {
675 if sub_msg.success {
676 if let Some(topic) = &sub_msg.req_id {
677 self.subscriptions.confirm_unsubscribe(topic);
678 log::debug!("Unsubscription confirmed: topic={topic}");
679 } else {
680 for topic in self.subscriptions.pending_unsubscribe_topics() {
681 self.subscriptions.confirm_unsubscribe(&topic);
682 log::debug!("Unsubscription confirmed (bulk): topic={topic}");
683 }
684 }
685 } else {
686 let topic_desc = sub_msg.req_id.as_deref().unwrap_or("unknown");
687 log::warn!(
688 "Unsubscription failed: topic={topic_desc}, error={:?}",
689 sub_msg.ret_msg
690 );
691 }
692 }
693 _ => {}
694 }
695 }
696
697 fn handle_subscription_error(&self, resp: &BybitWsResponse) {
698 let topic = resp.req_id.as_deref().unwrap_or("unknown");
699 let error_msg = resp.ret_msg.as_deref().unwrap_or("unknown error");
700
701 match resp.op {
702 Some(BybitWsOperation::Subscribe) => {
703 if is_already_subscribed_error(error_msg)
706 && let Some(ref req_id) = resp.req_id
707 {
708 self.subscriptions.confirm_subscribe(req_id);
709 log::debug!("Subscription duplicate ignored: topic={topic}, error={error_msg}");
710 return;
711 }
712
713 if let Some(ref req_id) = resp.req_id {
714 self.subscriptions.mark_failure(req_id);
715 } else {
716 for t in self.subscriptions.pending_subscribe_topics() {
717 self.subscriptions.mark_failure(&t);
718 }
719 }
720 log::warn!("Subscription error: topic={topic}, error={error_msg}");
721 }
722 Some(BybitWsOperation::Unsubscribe) => {
723 log::warn!("Unsubscription error: topic={topic}, error={error_msg}");
724 }
725 _ => {}
726 }
727 }
728
729 fn parse_raw_frame(msg: Message) -> Option<BybitWsFrame> {
730 match msg {
731 Message::Text(text) => {
732 if text == nautilus_network::RECONNECTED {
733 log::debug!("Received WebSocket reconnected signal");
734 return Some(BybitWsFrame::Reconnected);
735 }
736
737 if text.trim().eq_ignore_ascii_case("pong") {
738 return None;
739 }
740
741 log::trace!("Raw websocket message: {text}");
742
743 let value: serde_json::Value = match serde_json::from_str(&text) {
744 Ok(v) => v,
745 Err(e) => {
746 log::error!("Failed to parse WebSocket message: {e}: {text}");
747 return None;
748 }
749 };
750
751 if value
752 .get("op")
753 .and_then(serde_json::Value::as_str)
754 .is_some_and(|op| op == BybitWsOperation::Pong.as_ref())
755 {
756 return None;
757 }
758
759 Some(parse_bybit_ws_frame(value))
760 }
761 Message::Binary(msg) => {
762 log::debug!("Raw binary frame ({} bytes)", msg.len());
763 log::trace!("Raw binary: {msg:?}");
764 None
765 }
766 Message::Close(_) => {
767 log::debug!("Received close message, waiting for reconnection");
768 None
769 }
770 _ => None,
771 }
772 }
773}
774
775fn order_operation(op: BybitWsOrderRequestOp) -> (&'static str, &'static str) {
776 match op {
777 BybitWsOrderRequestOp::Create => ("/v5/order/create", "order.create"),
778 BybitWsOrderRequestOp::Amend => ("/v5/order/amend", "order.amend"),
779 BybitWsOrderRequestOp::Cancel => ("/v5/order/cancel", "order.cancel"),
780 BybitWsOrderRequestOp::CreateBatch => ("/v5/order/create-batch", "order.create-batch"),
781 BybitWsOrderRequestOp::AmendBatch => ("/v5/order/amend-batch", "order.amend-batch"),
782 BybitWsOrderRequestOp::CancelBatch => ("/v5/order/cancel-batch", "order.cancel-batch"),
783 }
784}
785
786fn order_not_sent_message(command: &BybitWsOrderCommand, error: &BybitWsError) -> BybitWsMessage {
787 BybitWsMessage::OrderNotSent {
788 request_id: command.req_id.clone(),
789 reason: error.to_string(),
790 }
791}
792
793fn is_already_subscribed_error(error_msg: &str) -> bool {
794 error_msg
795 .to_ascii_lowercase()
796 .contains("already subscribed")
797}
798
799#[cfg(test)]
800mod tests {
801 use futures_util::{SinkExt, StreamExt};
802 use nautilus_common::testing::wait_until_async;
803 use nautilus_core::string::secret::REDACTED;
804 use nautilus_network::websocket::{WebSocketConfig, auth::AuthState, channel_message_handler};
805 use rstest::rstest;
806 use ustr::Ustr;
807
808 use super::*;
809 use crate::common::{
810 consts::BYBIT_WS_TOPIC_DELIMITER, rate_limit::BybitRateLimiter, testing::load_test_json,
811 };
812
813 fn create_test_handler() -> BybitWsFeedHandler {
814 let signal = Arc::new(AtomicBool::new(false));
815 let (_cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
816 let (_raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
817 let auth_tracker = AuthTracker::new();
818 let subscriptions = SubscriptionState::new(BYBIT_WS_TOPIC_DELIMITER);
819
820 BybitWsFeedHandler::new(
821 signal,
822 cmd_rx,
823 raw_rx,
824 auth_tracker,
825 Duration::from_secs(5),
826 subscriptions,
827 BybitRateLimiter::for_websocket(
828 "wss://bybit-handler-test.invalid",
829 Some("test-key"),
830 None,
831 ),
832 Arc::new(AtomicU64::new(5_000)),
833 )
834 }
835
836 #[tokio::test]
837 async fn test_authentication_with_full_replay_buffer() {
838 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
839 let address = listener.local_addr().unwrap();
840 let (replayed_tx, replayed_rx) = tokio::sync::oneshot::channel();
841
842 let server = tokio::spawn(async move {
843 let (first, _) = listener.accept().await.unwrap();
844 let _first = tokio_tungstenite::accept_async(first).await.unwrap();
845 let (replacement, _) = listener.accept().await.unwrap();
846 let mut replacement = tokio_tungstenite::accept_async(replacement).await.unwrap();
847 assert_eq!(
848 replacement.next().await.unwrap().unwrap(),
849 Message::text("authenticate")
850 );
851 replacement
852 .send(Message::text(load_test_json("ws_auth_success.json")))
853 .await
854 .unwrap();
855 assert_eq!(
856 replacement.next().await.unwrap().unwrap(),
857 Message::text("held")
858 );
859 replayed_tx.send(()).unwrap();
860 std::future::pending::<()>().await;
861 });
862
863 let mut handler = create_test_handler();
864 let tracker = handler.auth_tracker.clone();
865 let (message_handler, raw_rx) = channel_message_handler();
866 handler.raw_rx = raw_rx;
867 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
868 handler.cmd_rx = cmd_rx;
869 let config = WebSocketConfig::builder()
870 .url(format!("ws://{address}"))
871 .writer_capacity(1)
872 .reconnect_delay_initial_ms(1)
873 .reconnect_delay_max_ms(1)
874 .reconnect_jitter_ms(0)
875 .build()
876 .unwrap();
877 let client = WebSocketClient::builder()
878 .config(config)
879 .message_handler(message_handler)
880 .connect()
881 .await
882 .unwrap();
883 client.set_auth_tracker(tracker.clone(), true);
884
885 client.send_text("held".to_string(), None).await.unwrap();
887 assert!(client.request_reconnect());
888 wait_until_async(
889 || async { client.is_active() && client.connection_epoch() == 1 },
890 Duration::from_secs(5),
891 )
892 .await;
893 assert!(matches!(
894 client.send_text("overflow".to_string(), None).await,
895 Err(SendError::BufferFull)
896 ));
897 handler.inner = Some(client);
898 let stale = tokio::time::timeout(
899 Duration::from_secs(5),
900 handler.send_secret_with_retry(SecretString::from("stale-auth".to_string()), Some(0)),
901 )
902 .await
903 .unwrap();
904 assert!(
905 matches!(stale, Err(BybitWsError::Authentication(message)) if message == "Connection changed before authentication")
906 );
907 cmd_tx
908 .send(HandlerCommand::Authenticate {
909 payload: SecretString::from("authenticate".to_string()),
910 })
911 .unwrap();
912
913 tokio::time::timeout(Duration::from_secs(5), async {
914 loop {
915 if let Some(BybitWsMessage::Auth(response)) = handler.next().await {
916 assert_eq!(response.success, Some(true));
917 break;
918 }
919 }
920 })
921 .await
922 .unwrap();
923
924 assert!(tracker.is_authenticated());
925 tokio::time::timeout(Duration::from_secs(5), replayed_rx)
926 .await
927 .unwrap()
928 .unwrap();
929 handler.inner.as_ref().unwrap().disconnect().await;
930 server.abort();
931 }
932
933 #[tokio::test]
934 async fn test_authentication_timeout_discards_replay_buffer() {
935 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
936 let address = listener.local_addr().unwrap();
937 let (received_tx, received_rx) = tokio::sync::oneshot::channel();
938
939 let server = tokio::spawn(async move {
940 let (first, _) = listener.accept().await.unwrap();
941 let _first = tokio_tungstenite::accept_async(first).await.unwrap();
942 let (replacement, _) = listener.accept().await.unwrap();
943 let mut replacement = tokio_tungstenite::accept_async(replacement).await.unwrap();
944 assert_eq!(
945 replacement.next().await.unwrap().unwrap(),
946 Message::text("authenticate")
947 );
948 received_tx
950 .send(replacement.next().await.unwrap().unwrap())
951 .unwrap();
952 std::future::pending::<()>().await;
953 });
954
955 let auth_timeout = Duration::from_millis(200);
956 let mut handler = create_test_handler();
957 handler.auth_timeout = auth_timeout;
958 let tracker = handler.auth_tracker.clone();
959 let (message_handler, raw_rx) = channel_message_handler();
960 handler.raw_rx = raw_rx;
961 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
962 handler.cmd_rx = cmd_rx;
963 let config = WebSocketConfig::builder()
964 .url(format!("ws://{address}"))
965 .writer_capacity(1)
966 .reconnect_delay_initial_ms(1)
967 .reconnect_delay_max_ms(1)
968 .reconnect_jitter_ms(0)
969 .build()
970 .unwrap();
971 let client = WebSocketClient::builder()
972 .config(config)
973 .message_handler(message_handler)
974 .connect()
975 .await
976 .unwrap();
977 client.set_auth_tracker(tracker.clone(), true);
978
979 client.send_text("held".to_string(), None).await.unwrap();
981 assert!(client.request_reconnect());
982 wait_until_async(
983 || async { client.is_active() && client.connection_epoch() == 1 },
984 Duration::from_secs(5),
985 )
986 .await;
987 handler.inner = Some(client);
988 handler.next().await;
990 let pending = tracker.begin();
991 cmd_tx
992 .send(HandlerCommand::Authenticate {
993 payload: SecretString::from("authenticate".to_string()),
994 })
995 .unwrap();
996
997 let started = tokio::time::Instant::now();
998 tokio::select! {
999 message = handler.next() => panic!("unexpected handler message: {message:?}"),
1000 () = wait_until_async(
1001 || async { tracker.auth_state() == AuthState::Failed },
1002 Duration::from_secs(5),
1003 ) => {}
1004 }
1005 let elapsed = started.elapsed();
1006 let client = handler.inner.as_ref().unwrap();
1007 wait_until_async(
1009 || async { client.send_text("released".to_string(), None).await.is_ok() },
1010 Duration::from_secs(5),
1011 )
1012 .await;
1013 let received = tokio::time::timeout(Duration::from_secs(5), received_rx)
1014 .await
1015 .unwrap()
1016 .unwrap();
1017
1018 assert!(elapsed >= auth_timeout);
1019 assert_eq!(
1020 pending.await,
1021 Ok(Err("Authentication timed out".to_string()))
1022 );
1023 assert_eq!(received, Message::text("released"));
1024 client.disconnect().await;
1025 server.abort();
1026 }
1027
1028 #[rstest]
1029 #[case::auth_reply(
1030 load_test_json("ws_auth_success.json"),
1031 AuthState::Authenticated,
1032 Ok(Ok(()))
1033 )]
1034 #[case::auth_rejection(
1035 load_test_json("ws_auth_failure.json"),
1036 AuthState::Failed,
1037 Ok(Err("API key is invalid.".to_string()))
1038 )]
1039 #[case::reconnected(
1040 nautilus_network::RECONNECTED.to_string(),
1041 AuthState::Unauthenticated,
1042 Err(tokio::sync::oneshot::error::TryRecvError::Empty)
1043 )]
1044 #[tokio::test(start_paused = true)]
1045 async fn test_authentication_timeout_cancelled(
1046 #[case] frame: String,
1047 #[case] expected_state: AuthState,
1048 #[case] expected_result: Result<
1049 Result<(), String>,
1050 tokio::sync::oneshot::error::TryRecvError,
1051 >,
1052 ) {
1053 let mut handler = create_test_handler();
1054 let tracker = handler.auth_tracker.clone();
1055 let (raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
1056 handler.raw_rx = raw_rx;
1057 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
1058 handler.cmd_rx = cmd_rx;
1059 let mut pending = tracker.begin();
1060 cmd_tx
1061 .send(HandlerCommand::Authenticate {
1062 payload: SecretString::from("authenticate".to_string()),
1063 })
1064 .unwrap();
1065
1066 let started = tokio::time::timeout(handler.auth_timeout / 2, handler.next()).await;
1068 raw_tx.send(Message::Text(frame.into())).unwrap();
1069 handler.next().await;
1070 let idle = tokio::time::timeout(handler.auth_timeout * 2, handler.next()).await;
1071
1072 assert!(started.is_err());
1073 assert!(idle.is_err());
1074 assert_eq!(tracker.auth_state(), expected_state);
1075 assert_eq!(pending.try_recv(), expected_result);
1076 }
1077
1078 async fn connect_book_handler() -> (
1079 BybitWsFeedHandler,
1080 tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
1081 tokio::sync::mpsc::UnboundedReceiver<Value>,
1082 ) {
1083 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1084 let address = listener.local_addr().unwrap();
1085 let (requests_tx, requests_rx) = tokio::sync::mpsc::unbounded_channel();
1086
1087 tokio::spawn(async move {
1089 let (stream, _) = listener.accept().await.unwrap();
1090 let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
1091
1092 while let Some(Ok(Message::Text(text))) = socket.next().await {
1093 let request = serde_json::from_str::<Value>(&text).unwrap();
1094
1095 if requests_tx.send(request).is_err() {
1096 break;
1097 }
1098 }
1099 });
1100
1101 let mut handler = create_test_handler();
1102 let (message_handler, raw_rx) = channel_message_handler();
1103 handler.raw_rx = raw_rx;
1104 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
1105 handler.cmd_rx = cmd_rx;
1106 let config = WebSocketConfig::builder()
1107 .url(format!("ws://{address}"))
1108 .build()
1109 .unwrap();
1110 let client = WebSocketClient::builder()
1111 .config(config)
1112 .message_handler(message_handler)
1113 .connect()
1114 .await
1115 .unwrap();
1116 handler.inner = Some(client);
1117
1118 (handler, cmd_tx, requests_rx)
1119 }
1120
1121 async fn complete_book_command(
1122 handler: &mut BybitWsFeedHandler,
1123 receiver: tokio::sync::oneshot::Receiver<BybitWsResult<()>>,
1124 ) -> Result<BybitWsResult<()>, tokio::sync::oneshot::error::RecvError> {
1125 let drive = async {
1126 loop {
1127 handler.next().await;
1128 }
1129 };
1130
1131 tokio::time::timeout(Duration::from_secs(5), async {
1132 tokio::select! {
1133 result = receiver => result,
1134 () = drive => unreachable!("handler loop never ends"),
1135 }
1136 })
1137 .await
1138 .unwrap()
1139 }
1140
1141 async fn next_request(requests: &mut tokio::sync::mpsc::UnboundedReceiver<Value>) -> Value {
1142 tokio::time::timeout(Duration::from_secs(5), requests.recv())
1143 .await
1144 .unwrap()
1145 .unwrap()
1146 }
1147
1148 fn subscription_request(op: &str, topic: &str) -> Value {
1149 serde_json::json!({"op": op, "args": [topic], "req_id": topic})
1150 }
1151
1152 fn subscribe_book_command(
1153 topic: &str,
1154 gate: SnapshotGate,
1155 ) -> (
1156 HandlerCommand,
1157 tokio::sync::oneshot::Receiver<BybitWsResult<()>>,
1158 ) {
1159 let payload = subscription_request("subscribe", topic).to_string();
1160 let (completion, receiver) = tokio::sync::oneshot::channel();
1161
1162 let command = HandlerCommand::SubscribeBook {
1163 payload,
1164 gate,
1165 completion,
1166 };
1167
1168 (command, receiver)
1169 }
1170
1171 #[tokio::test]
1172 async fn test_subscribe_book_opens_gate_after_write() {
1173 let (mut handler, cmd_tx, mut requests) = connect_book_handler().await;
1174 let topic = "orderbook.50.BTCUSDT";
1175 let gate = SnapshotGate::default();
1176 gate.lock().close();
1177 let (command, receiver) = subscribe_book_command(topic, gate.clone());
1178
1179 cmd_tx.send(command).unwrap();
1180 let result = complete_book_command(&mut handler, receiver).await;
1181 let request = next_request(&mut requests).await;
1182
1183 assert!(matches!(result, Ok(Ok(()))));
1184 assert!(!gate.lock().is_closed());
1185 assert_eq!(request, subscription_request("subscribe", topic));
1186 handler.inner.as_ref().unwrap().disconnect().await;
1187 }
1188
1189 #[tokio::test]
1190 async fn test_resubscribe_book_replaces_subscription_and_opens_gate() {
1191 let (mut handler, cmd_tx, mut requests) = connect_book_handler().await;
1192 let topic = "orderbook.50.BTCUSDT";
1193 handler.subscriptions.mark_subscribe(topic);
1194 handler.subscriptions.confirm_subscribe(topic);
1195 let gate = SnapshotGate::default();
1196 gate.lock().close();
1197 let (completion, receiver) = tokio::sync::oneshot::channel();
1198
1199 cmd_tx
1200 .send(HandlerCommand::ResubscribeBook {
1201 topic: topic.to_string(),
1202 cancel: CancellationToken::new(),
1203 gate: gate.clone(),
1204 completion,
1205 })
1206 .unwrap();
1207
1208 let result = complete_book_command(&mut handler, receiver).await;
1209 let pending = handler.subscriptions.pending_subscribe_topics();
1210 let unsubscribe = next_request(&mut requests).await;
1211 let subscribe = next_request(&mut requests).await;
1212
1213 assert!(matches!(result, Ok(Ok(()))));
1214 assert!(!gate.lock().is_closed());
1215 assert_eq!(pending, [topic]);
1216 assert_eq!(unsubscribe, subscription_request("unsubscribe", topic));
1217 assert_eq!(subscribe, subscription_request("subscribe", topic));
1218 handler.inner.as_ref().unwrap().disconnect().await;
1219 }
1220
1221 #[tokio::test]
1222 async fn test_subscribe_book_write_failure_keeps_gate_closed() {
1223 let (mut handler, cmd_tx, _requests) = connect_book_handler().await;
1224 handler.inner.as_ref().unwrap().disconnect().await;
1225 let gate = SnapshotGate::default();
1226 gate.lock().close();
1227 let (command, receiver) = subscribe_book_command("orderbook.50.BTCUSDT", gate.clone());
1228
1229 cmd_tx.send(command).unwrap();
1230 let result = complete_book_command(&mut handler, receiver).await;
1231
1232 assert!(matches!(result, Ok(Err(BybitWsError::Transport(_)))));
1233 assert!(gate.lock().is_closed());
1234 }
1235
1236 #[tokio::test]
1238 async fn test_resubscribe_book_cancelled_before_write_sends_nothing() {
1239 let (mut handler, cmd_tx, mut requests) = connect_book_handler().await;
1240 let topic = "orderbook.50.BTCUSDT";
1241 handler.subscriptions.mark_subscribe(topic);
1242 handler.subscriptions.confirm_subscribe(topic);
1243 let gate = SnapshotGate::default();
1244 gate.lock().close();
1245 let cancel = CancellationToken::new();
1246 cancel.cancel();
1247 let (completion, receiver) = tokio::sync::oneshot::channel();
1248 let sentinel = "orderbook.50.ETHUSDT";
1249 let (sentinel_command, sentinel_receiver) =
1250 subscribe_book_command(sentinel, SnapshotGate::default());
1251
1252 cmd_tx
1253 .send(HandlerCommand::ResubscribeBook {
1254 topic: topic.to_string(),
1255 cancel,
1256 gate: gate.clone(),
1257 completion,
1258 })
1259 .unwrap();
1260
1261 let result = complete_book_command(&mut handler, receiver).await;
1262 cmd_tx.send(sentinel_command).unwrap();
1263 let sentinel_result = complete_book_command(&mut handler, sentinel_receiver).await;
1264 let pending = handler.subscriptions.pending_subscribe_topics();
1265 let request = next_request(&mut requests).await;
1266
1267 assert!(result.is_err());
1268 assert!(matches!(sentinel_result, Ok(Ok(()))));
1269 assert!(gate.lock().is_closed());
1270 assert!(pending.is_empty());
1271 assert_eq!(request, subscription_request("subscribe", sentinel));
1272 handler.inner.as_ref().unwrap().disconnect().await;
1273 }
1274
1275 #[rstest]
1276 fn test_authenticate_command_debug_redacts_payload() {
1277 let payload = "authentication-secret";
1278 let command = HandlerCommand::Authenticate {
1279 payload: SecretString::from(payload.to_string()),
1280 };
1281
1282 let debug = format!("{command:?}");
1283
1284 assert!(debug.contains(REDACTED));
1285 assert!(!debug.contains(payload));
1286 }
1287
1288 fn load_value(fixture: &str) -> serde_json::Value {
1289 let json = load_test_json(fixture);
1290 serde_json::from_str(&json).unwrap()
1291 }
1292
1293 #[rstest]
1294 fn test_handler_initializes() {
1295 let _handler = create_test_handler();
1296 }
1297
1298 #[tokio::test]
1299 async fn order_without_writer_produces_correlated_terminal_response() {
1300 let handler = create_test_handler();
1301 handler.auth_tracker.succeed();
1302 let command = BybitWsOrderCommand {
1303 req_id: "not-sent-request".to_string(),
1304 op: BybitWsOrderRequestOp::Create,
1305 category: BybitProductType::Linear,
1306 weight: 1,
1307 referer: None,
1308 args: vec![serde_json::json!({"category": "linear"})],
1309 };
1310
1311 let failure = handler.send_order(&command).await.unwrap_err();
1312 let OrderSendFailure::NotSent(error) = failure else {
1313 panic!("Expected definitive not-sent failure, was {failure:?}");
1314 };
1315
1316 let BybitWsMessage::OrderNotSent { request_id, reason } =
1317 order_not_sent_message(&command, &error)
1318 else {
1319 panic!("Expected order response");
1320 };
1321
1322 assert_eq!(request_id, "not-sent-request");
1323 assert_eq!(reason, "Client error: No active WebSocket client");
1324 }
1325
1326 #[rstest]
1327 fn connection_change_invalidates_authentication_before_requeue() {
1328 let handler = create_test_handler();
1329 handler.auth_tracker.succeed();
1330 handler.pending_rates.insert(
1331 "reconnect-request".to_string(),
1332 PendingRate {
1333 endpoint: "/v5/order/create",
1334 category: BybitProductType::Linear,
1335 },
1336 );
1337
1338 let result = handler
1339 .classify_order_send_error("reconnect-request", SendError::ConnectionChanged)
1340 .unwrap();
1341
1342 assert!(!result);
1343 assert!(!handler.auth_tracker.is_authenticated());
1344 assert!(!handler.pending_rates.contains_key("reconnect-request"));
1345 }
1346
1347 #[rstest]
1348 fn pre_active_timeout_is_terminal_not_sent() {
1349 let handler = create_test_handler();
1350 handler.auth_tracker.succeed();
1351 handler.pending_rates.insert(
1352 "timeout-request".to_string(),
1353 PendingRate {
1354 endpoint: "/v5/order/create",
1355 category: BybitProductType::Linear,
1356 },
1357 );
1358
1359 let failure = handler
1360 .classify_order_send_error("timeout-request", SendError::Timeout)
1361 .unwrap_err();
1362
1363 assert!(matches!(failure, OrderSendFailure::NotSent(_)));
1364 assert!(!handler.auth_tracker.is_authenticated());
1365 assert!(!handler.pending_rates.contains_key("timeout-request"));
1366 }
1367
1368 #[rstest]
1369 fn buffer_full_is_not_sent_and_preserves_authentication() {
1370 let handler = create_test_handler();
1371 handler.auth_tracker.succeed();
1372 handler.pending_rates.insert(
1373 "full-request".to_string(),
1374 PendingRate {
1375 endpoint: "/v5/order/create",
1376 category: BybitProductType::Linear,
1377 },
1378 );
1379
1380 let failure = handler
1381 .classify_order_send_error("full-request", SendError::BufferFull)
1382 .unwrap_err();
1383
1384 assert!(matches!(failure, OrderSendFailure::NotSent(_)));
1385 assert!(handler.auth_tracker.is_authenticated());
1386 assert!(!handler.pending_rates.contains_key("full-request"));
1387 }
1388
1389 #[rstest]
1390 #[case::private_stream(
1391 load_test_json("ws_auth_success.json"),
1392 Some("cejreaspqfm9se7usbrg-2xh"),
1393 None,
1394 Some(""),
1395 Some(true)
1396 )]
1397 #[case::trade_stream(
1398 r#"{"retCode":0,"retMsg":"OK","op":"auth","connId":"cnt5leec0hvan15eukcg-2t"}"#.to_string(),
1399 Some("cnt5leec0hvan15eukcg-2t"),
1400 Some(0),
1401 Some("OK"),
1402 None
1403 )]
1404 fn test_parse_frame_auth_success(
1405 #[case] frame: String,
1406 #[case] conn_id: Option<&str>,
1407 #[case] ret_code: Option<i64>,
1408 #[case] ret_msg: Option<&str>,
1409 #[case] success: Option<bool>,
1410 ) {
1411 let frame = parse_bybit_ws_frame(serde_json::from_str(&frame).unwrap());
1412
1413 match frame {
1414 BybitWsFrame::Auth(auth) => {
1415 assert_eq!(auth.op, BybitWsOperation::Auth);
1416 assert_eq!(auth.conn_id.as_deref(), conn_id);
1417 assert_eq!(auth.ret_code, ret_code);
1418 assert_eq!(auth.ret_msg.as_deref(), ret_msg);
1419 assert_eq!(auth.success, success);
1420 }
1421 other => panic!("Expected Auth, was {other:?}"),
1422 }
1423 }
1424
1425 #[rstest]
1426 #[case::private_stream(
1427 load_test_json("ws_auth_failure.json"),
1428 Some("cejreaspqfm9se7usbrg-3ab"),
1429 None,
1430 Some("API key is invalid."),
1431 Some(false)
1432 )]
1433 #[case::trade_stream(
1434 r#"{"retCode":10004,"retMsg":"invalid sign","op":"auth","connId":"cnt5leec0hvan15eukcg-3c"}"#.to_string(),
1435 Some("cnt5leec0hvan15eukcg-3c"),
1436 Some(10004),
1437 Some("invalid sign"),
1438 None
1439 )]
1440 fn test_parse_frame_auth_failure(
1441 #[case] frame: String,
1442 #[case] conn_id: Option<&str>,
1443 #[case] ret_code: Option<i64>,
1444 #[case] ret_msg: Option<&str>,
1445 #[case] success: Option<bool>,
1446 ) {
1447 let frame = parse_bybit_ws_frame(serde_json::from_str(&frame).unwrap());
1448
1449 match frame {
1450 BybitWsFrame::ErrorResponse(resp) => {
1451 assert_eq!(resp.op, Some(BybitWsOperation::Auth));
1452 assert_eq!(resp.topic, None);
1453 assert_eq!(resp.conn_id.as_deref(), conn_id);
1454 assert_eq!(resp.req_id, None);
1455 assert_eq!(resp.ret_code, ret_code);
1456 assert_eq!(resp.ret_msg.as_deref(), ret_msg);
1457 assert_eq!(resp.success, success);
1458 }
1459 other => panic!("Expected ErrorResponse, was {other:?}"),
1460 }
1461 }
1462
1463 #[rstest]
1464 fn test_parse_frame_subscription_ack() {
1465 let value = load_value("ws_subscription_ack.json");
1466 let frame = parse_bybit_ws_frame(value);
1467 match frame {
1468 BybitWsFrame::Subscription(sub) => {
1469 assert!(sub.success);
1470 assert_eq!(sub.op, BybitWsOperation::Subscribe);
1471 assert_eq!(sub.req_id.as_deref(), Some("sub-orderbook-1"));
1472 }
1473 other => panic!("Expected Subscription, was {other:?}"),
1474 }
1475 }
1476
1477 #[rstest]
1478 fn test_parse_frame_subscription_failure() {
1479 let value = load_value("ws_subscription_failure.json");
1480 let frame = parse_bybit_ws_frame(value);
1481 match frame {
1482 BybitWsFrame::ErrorResponse(resp) => {
1483 assert_eq!(
1484 resp.ret_msg.as_deref(),
1485 Some("Invalid topic: invalid.topic.BTCUSDT")
1486 );
1487 }
1488 other => panic!("Expected ErrorResponse, was {other:?}"),
1489 }
1490 }
1491
1492 #[rstest]
1493 fn test_parse_frame_order_response() {
1494 let value = load_value("ws_order_response.json");
1495 let frame = parse_bybit_ws_frame(value);
1496 match frame {
1497 BybitWsFrame::OrderResponse(resp) => {
1498 assert_eq!(resp.op, "order.create");
1499 assert_eq!(resp.ret_code, 0);
1500 assert_eq!(resp.ret_msg, "OK");
1501 }
1502 other => panic!("Expected OrderResponse, was {other:?}"),
1503 }
1504 }
1505
1506 #[rstest]
1507 fn test_parse_frame_orderbook() {
1508 let value = load_value("ws_orderbook_snapshot.json");
1509 let frame = parse_bybit_ws_frame(value);
1510 assert!(
1511 matches!(frame, BybitWsFrame::Orderbook(_)),
1512 "Expected Orderbook, was {frame:?}"
1513 );
1514 }
1515
1516 #[rstest]
1517 fn test_parse_frame_trade() {
1518 let value = load_value("ws_public_trade.json");
1519 let frame = parse_bybit_ws_frame(value);
1520 assert!(
1521 matches!(frame, BybitWsFrame::Trade(_)),
1522 "Expected Trade, was {frame:?}"
1523 );
1524 }
1525
1526 #[rstest]
1527 fn test_parse_frame_kline() {
1528 let value = load_value("ws_kline.json");
1529 let frame = parse_bybit_ws_frame(value);
1530 assert!(
1531 matches!(frame, BybitWsFrame::Kline(_)),
1532 "Expected Kline, was {frame:?}"
1533 );
1534 }
1535
1536 #[rstest]
1537 fn test_parse_frame_ticker_linear() {
1538 let value = load_value("ws_ticker_linear.json");
1539 let frame = parse_bybit_ws_frame(value);
1540 assert!(
1541 matches!(frame, BybitWsFrame::TickerLinear(_)),
1542 "Expected TickerLinear, was {frame:?}"
1543 );
1544 }
1545
1546 #[rstest]
1547 fn test_parse_frame_ticker_option() {
1548 let value = load_value("ws_ticker_option.json");
1549 let frame = parse_bybit_ws_frame(value);
1550 assert!(
1551 matches!(frame, BybitWsFrame::TickerOption(_)),
1552 "Expected TickerOption, was {frame:?}"
1553 );
1554 }
1555
1556 #[rstest]
1557 fn test_parse_frame_account_order() {
1558 let value = load_value("ws_account_order.json");
1559 let frame = parse_bybit_ws_frame(value);
1560 assert!(
1561 matches!(frame, BybitWsFrame::AccountOrder(_)),
1562 "Expected AccountOrder, was {frame:?}"
1563 );
1564 }
1565
1566 #[rstest]
1567 fn test_parse_frame_account_execution() {
1568 let value = load_value("ws_account_execution.json");
1569 let frame = parse_bybit_ws_frame(value);
1570 assert!(
1571 matches!(frame, BybitWsFrame::AccountExecution(_)),
1572 "Expected AccountExecution, was {frame:?}"
1573 );
1574 }
1575
1576 #[rstest]
1577 fn test_parse_frame_account_wallet() {
1578 let value = load_value("ws_account_wallet.json");
1579 let frame = parse_bybit_ws_frame(value);
1580 assert!(
1581 matches!(frame, BybitWsFrame::AccountWallet(_)),
1582 "Expected AccountWallet, was {frame:?}"
1583 );
1584 }
1585
1586 #[rstest]
1587 fn test_parse_frame_account_position() {
1588 let value = load_value("ws_account_position.json");
1589 let frame = parse_bybit_ws_frame(value);
1590 assert!(
1591 matches!(frame, BybitWsFrame::AccountPosition(_)),
1592 "Expected AccountPosition, was {frame:?}"
1593 );
1594 }
1595
1596 #[rstest]
1597 fn test_parse_frame_unknown_message() {
1598 let value: serde_json::Value = serde_json::json!({"foo": "bar"});
1599 let frame = parse_bybit_ws_frame(value);
1600 assert!(
1601 matches!(frame, BybitWsFrame::Unknown(_)),
1602 "Expected Unknown, was {frame:?}"
1603 );
1604 }
1605
1606 #[rstest]
1607 fn test_parse_raw_reconnected_signal() {
1608 let msg = Message::Text(nautilus_network::RECONNECTED.to_string().into());
1609 let result = BybitWsFeedHandler::parse_raw_frame(msg);
1610 assert!(
1611 matches!(result, Some(BybitWsFrame::Reconnected)),
1612 "Expected Some(Reconnected), was {result:?}"
1613 );
1614 }
1615
1616 #[rstest]
1617 fn test_parse_raw_pong_text() {
1618 let msg = Message::Text("pong".into());
1619 let result = BybitWsFeedHandler::parse_raw_frame(msg);
1620 assert!(result.is_none(), "Expected None for pong, was {result:?}");
1621 }
1622
1623 #[rstest]
1624 fn test_parse_raw_json_pong_message() {
1625 let msg = Message::Text(
1626 r#"{"args":["1777226678908"],"conn_id":"yzr7jz02gws1vh60mk5m-hxqdp","op":"pong"}"#
1627 .into(),
1628 );
1629 let result = BybitWsFeedHandler::parse_raw_frame(msg);
1630 assert!(
1631 result.is_none(),
1632 "Expected None for JSON pong, was {result:?}"
1633 );
1634 }
1635
1636 #[rstest]
1637 fn test_parse_raw_valid_json() {
1638 let json = load_test_json("ws_public_trade.json");
1639 let msg = Message::Text(json.into());
1640 let result = BybitWsFeedHandler::parse_raw_frame(msg);
1641 assert!(
1642 matches!(result, Some(BybitWsFrame::Trade(_))),
1643 "Expected Some(Trade), was {result:?}"
1644 );
1645 }
1646
1647 #[rstest]
1648 fn test_parse_raw_invalid_json() {
1649 let msg = Message::Text("not valid json".into());
1650 let result = BybitWsFeedHandler::parse_raw_frame(msg);
1651 assert!(
1652 result.is_none(),
1653 "Expected None for invalid JSON, was {result:?}"
1654 );
1655 }
1656
1657 #[rstest]
1658 fn test_parse_raw_binary_message() {
1659 let msg = Message::Binary(vec![0x01, 0x02].into());
1660 let result = BybitWsFeedHandler::parse_raw_frame(msg);
1661 assert!(result.is_none(), "Expected None for binary, was {result:?}");
1662 }
1663
1664 #[rstest]
1665 fn test_subscription_ack_with_req_id_confirms_only_that_topic() {
1666 let handler = create_test_handler();
1667 handler.subscriptions.mark_subscribe("orderbook.50.BTCUSDT");
1668 handler.subscriptions.mark_subscribe("publicTrade.BTCUSDT");
1669
1670 let ack = BybitWsSubscriptionMsg {
1671 success: true,
1672 op: BybitWsOperation::Subscribe,
1673 conn_id: None,
1674 req_id: Some("orderbook.50.BTCUSDT".to_string()),
1675 ret_msg: None,
1676 };
1677
1678 handler.handle_subscription_ack(&ack);
1679
1680 assert!(
1682 handler
1683 .subscriptions
1684 .pending_subscribe_topics()
1685 .contains(&"publicTrade.BTCUSDT".to_string())
1686 );
1687 assert!(
1688 !handler
1689 .subscriptions
1690 .pending_subscribe_topics()
1691 .contains(&"orderbook.50.BTCUSDT".to_string())
1692 );
1693 }
1694
1695 #[rstest]
1696 fn test_subscription_failure_with_req_id_marks_only_that_topic() {
1697 let handler = create_test_handler();
1698 handler.subscriptions.mark_subscribe("orderbook.50.BTCUSDT");
1699 handler.subscriptions.mark_subscribe("publicTrade.BTCUSDT");
1700
1701 let ack = BybitWsSubscriptionMsg {
1702 success: false,
1703 op: BybitWsOperation::Subscribe,
1704 conn_id: None,
1705 req_id: Some("orderbook.50.BTCUSDT".to_string()),
1706 ret_msg: Some("Invalid topic".to_string()),
1707 };
1708
1709 handler.handle_subscription_ack(&ack);
1710
1711 let pending = handler.subscriptions.pending_subscribe_topics();
1714 assert!(pending.contains(&"orderbook.50.BTCUSDT".to_string()));
1715 assert!(pending.contains(&"publicTrade.BTCUSDT".to_string()));
1716 }
1717
1718 #[rstest]
1719 fn test_error_response_with_subscribe_op_triggers_mark_failure() {
1720 let handler = create_test_handler();
1721 handler
1722 .subscriptions
1723 .mark_subscribe("invalid.topic.BTCUSDT");
1724
1725 let resp = BybitWsResponse {
1726 op: Some(BybitWsOperation::Subscribe),
1727 topic: None,
1728 success: Some(false),
1729 conn_id: None,
1730 req_id: Some("invalid.topic.BTCUSDT".to_string()),
1731 ret_code: Some(10001),
1732 ret_msg: Some("Invalid topic".to_string()),
1733 };
1734
1735 handler.handle_subscription_error(&resp);
1736
1737 let pending = handler.subscriptions.pending_subscribe_topics();
1739 assert!(pending.contains(&"invalid.topic.BTCUSDT".to_string()));
1740 }
1741
1742 #[rstest]
1743 fn test_already_subscribed_error_confirms_topic() {
1744 let handler = create_test_handler();
1745 handler.subscriptions.mark_subscribe("tickers.ETHUSDT");
1746
1747 let resp = BybitWsResponse {
1748 op: Some(BybitWsOperation::Subscribe),
1749 topic: None,
1750 success: Some(false),
1751 conn_id: None,
1752 req_id: Some("tickers.ETHUSDT".to_string()),
1753 ret_code: Some(10001),
1754 ret_msg: Some("error:already subscribed,topic:tickers.ETHUSDT".to_string()),
1755 };
1756
1757 handler.handle_subscription_error(&resp);
1758
1759 let pending = handler.subscriptions.pending_subscribe_topics();
1760 assert!(!pending.contains(&"tickers.ETHUSDT".to_string()));
1761 let symbols = handler.subscriptions.confirmed();
1762 let entry = symbols
1763 .get(&Ustr::from("tickers"))
1764 .expect("channel present");
1765 assert!(entry.contains(&Ustr::from("ETHUSDT")));
1766 }
1767
1768 #[rstest]
1769 fn test_subscription_ack_without_req_id_confirms_all_pending() {
1770 let handler = create_test_handler();
1771 handler.subscriptions.mark_subscribe("orderbook.50.BTCUSDT");
1772 handler.subscriptions.mark_subscribe("publicTrade.BTCUSDT");
1773
1774 let ack = BybitWsSubscriptionMsg {
1775 success: true,
1776 op: BybitWsOperation::Subscribe,
1777 conn_id: None,
1778 req_id: None,
1779 ret_msg: None,
1780 };
1781
1782 handler.handle_subscription_ack(&ack);
1783
1784 assert!(handler.subscriptions.pending_subscribe_topics().is_empty());
1786 }
1787}