1use std::{
19 collections::VecDeque,
20 sync::{
21 Arc,
22 atomic::{AtomicBool, Ordering},
23 },
24};
25
26#[cfg(test)]
27use nautilus_core::string::secret::REDACTED;
28use nautilus_core::string::secret::SecretString;
29use nautilus_network::{
30 RECONNECTED,
31 websocket::{SubscriptionState, WebSocketClient},
32};
33use serde::Deserialize;
34use serde_json::{Value, value::RawValue};
35use tokio_tungstenite::tungstenite::Message;
36
37use super::{
38 enums::{KrakenWsChannel, KrakenWsMessageType},
39 messages::{
40 KrakenSpotWsMessage, KrakenWsBookData, KrakenWsExecutionData, KrakenWsOhlcData,
41 KrakenWsRawMessage, KrakenWsResponse, KrakenWsTickerData, KrakenWsTradeData,
42 },
43 parse::parse_order_response,
44};
45use crate::{
46 common::consts::{KRAKEN_RATE_LIMIT_KEY_ORDER, KRAKEN_RATE_LIMIT_KEY_SUBSCRIPTION},
47 websocket::spot_v2::level_3::messages::{KrakenL3Snapshot, KrakenL3UpdateData},
48};
49
50#[derive(Debug)]
52pub enum SpotHandlerCommand {
53 SetClient(WebSocketClient),
54 Disconnect,
55 Subscribe { payload: SecretString },
56 Unsubscribe { payload: SecretString },
57 Ping { payload: SecretString },
58 SendOrderRequest { req_id: u64, payload: SecretString },
59}
60
61pub(super) struct SpotFeedHandler {
63 signal: Arc<AtomicBool>,
64 inner: Option<WebSocketClient>,
65 cmd_rx: tokio::sync::mpsc::UnboundedReceiver<SpotHandlerCommand>,
66 raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
67 subscriptions: SubscriptionState,
68 pending_messages: VecDeque<KrakenSpotWsMessage>,
69}
70
71impl SpotFeedHandler {
72 pub(super) fn new(
74 signal: Arc<AtomicBool>,
75 cmd_rx: tokio::sync::mpsc::UnboundedReceiver<SpotHandlerCommand>,
76 raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
77 subscriptions: SubscriptionState,
78 ) -> Self {
79 Self {
80 signal,
81 inner: None,
82 cmd_rx,
83 raw_rx,
84 subscriptions,
85 pending_messages: VecDeque::new(),
86 }
87 }
88
89 pub(super) fn is_stopped(&self) -> bool {
90 self.signal.load(Ordering::Relaxed)
91 }
92
93 fn is_subscribed(&self, topic: &str) -> bool {
94 self.subscriptions.all_topics().iter().any(|t| t == topic)
95 }
96
97 pub(super) async fn next(&mut self) -> Option<KrakenSpotWsMessage> {
99 if let Some(msg) = self.pending_messages.pop_front() {
100 return Some(msg);
101 }
102
103 loop {
104 tokio::select! {
105 Some(cmd) = self.cmd_rx.recv() => {
106 match cmd {
107 SpotHandlerCommand::SetClient(client) => {
108 log::debug!("WebSocketClient received by handler");
109 self.inner = Some(client);
110 }
111 SpotHandlerCommand::Disconnect => {
112 log::debug!("Disconnect command received");
113
114 if let Some(client) = self.inner.take() {
115 client.disconnect().await;
116 }
117 }
118 SpotHandlerCommand::Subscribe { payload }
119 | SpotHandlerCommand::Unsubscribe { payload } => {
120 if let Some(client) = &self.inner {
121 if let Err(e) = client
122 .send_text(
123 payload.expose_secret().to_owned(),
124 Some(KRAKEN_RATE_LIMIT_KEY_SUBSCRIPTION.as_slice()),
125 )
126 .await
127 {
128 log::error!("Failed to send text: {e}");
129 }
130 } else {
131 log::error!(
132 "Kraken WS subscribe or unsubscribe dropped, no active client"
133 );
134 }
135 }
136 SpotHandlerCommand::Ping { payload } => {
137 if let Some(client) = &self.inner
138 && let Err(e) = client.send_text(payload.expose_secret().to_owned(), None).await
139 {
140 log::error!("Failed to send text: {e}");
141 }
142 }
143 SpotHandlerCommand::SendOrderRequest { req_id, payload } => {
144 if let Some(client) = &self.inner {
145 if let Err(e) = client.send_text(payload.expose_secret().to_owned(), Some(KRAKEN_RATE_LIMIT_KEY_ORDER.as_slice())).await {
146 log::error!(
147 "Kraken WS send_order_request failed req_id={req_id}: {e}"
148 );
149 } else {
150 log::debug!(
151 "Kraken WS send_order_request enqueued req_id={req_id}"
152 );
153 }
154 } else {
155 log::error!(
156 "Kraken WS send_order_request without active client req_id={req_id}"
157 );
158 }
159 }
160 }
161 }
162
163 msg = self.raw_rx.recv() => {
164 let msg = match msg {
165 Some(msg) => msg,
166 None => {
167 log::debug!("WebSocket stream closed");
168 return None;
169 }
170 };
171
172 if let Message::Ping(data) = &msg {
173 log::trace!("Received ping frame with {} bytes", data.len());
174
175 if let Some(client) = &self.inner
176 && let Err(e) = client.send_pong(data.to_vec()).await
177 {
178 log::warn!("Failed to send pong frame: {e}");
179 }
180 continue;
181 }
182
183 if self.signal.load(Ordering::Relaxed) {
184 log::debug!("Stop signal received");
185 return None;
186 }
187
188 let text = match msg {
189 Message::Text(text) => text.to_string(),
190 Message::Binary(data) => {
191 match String::from_utf8(data.to_vec()) {
192 Ok(text) => text,
193 Err(e) => {
194 log::warn!("Failed to decode binary message: {e}");
195 continue;
196 }
197 }
198 }
199 Message::Pong(_) => {
200 log::trace!("Received pong");
201 continue;
202 }
203 Message::Close(_) => {
204 log::debug!("WebSocket connection closed");
205 return None;
206 }
207 Message::Frame(_) => {
208 log::trace!("Received raw frame");
209 continue;
210 }
211 _ => continue,
212 };
213
214 if text == RECONNECTED {
215 log::debug!("Received WebSocket reconnected signal");
216 return Some(KrakenSpotWsMessage::Reconnected);
217 }
218
219 if let Some(msg) = self.parse_message(&text) {
220 return Some(msg);
221 }
222 }
223 }
224 }
225 }
226
227 fn parse_message(&self, text: &str) -> Option<KrakenSpotWsMessage> {
228 if text.len() < 50 && text.starts_with("{\"channel\":\"") {
230 if text.contains("heartbeat") {
231 log::trace!("Received heartbeat");
232 return None;
233 }
234
235 if text.contains("status") {
236 log::debug!("Received status message");
237 return None;
238 }
239 }
240
241 if text.contains("\"level3\"")
242 && let Some(msg) = parse_level3_text(text)
243 {
244 return self.handle_l3_message(msg);
245 }
246
247 let value: Value = match serde_json::from_str(text) {
248 Ok(v) => v,
249 Err(e) => {
250 log::warn!("Failed to parse message: {e}");
251 return None;
252 }
253 };
254
255 if value.get("method").is_some() {
256 match parse_order_response(text) {
257 Ok(Some(msg)) => return Some(msg),
258 Ok(None) => {}
259 Err(e) => log::warn!("Failed to parse order response: {e}"),
260 }
261 return self.handle_control_message(value);
262 }
263
264 if value.get("channel").is_some() && value.get("data").is_some() {
265 match serde_json::from_str::<KrakenWsRawMessage>(text) {
266 Ok(msg) => return self.handle_data_message(msg),
267 Err(e) => {
268 log::debug!("Failed to parse data message: {e}");
269 return None;
270 }
271 }
272 }
273
274 log::debug!("Unhandled message structure: {text}");
275 None
276 }
277
278 fn handle_control_message(&self, value: Value) -> Option<KrakenSpotWsMessage> {
281 match serde_json::from_value::<KrakenWsResponse>(value) {
282 Ok(response) => match response {
283 KrakenWsResponse::Subscribe(sub) => {
284 if sub.success {
285 if let Some(result) = &sub.result {
286 log::debug!(
287 "Subscription confirmed: channel={:?}, req_id={:?}",
288 result.channel,
289 sub.req_id
290 );
291 } else {
292 log::debug!("Subscription confirmed: req_id={:?}", sub.req_id);
293 }
294 } else {
295 log::warn!(
296 "Subscription failed: error={:?}, req_id={:?}, symbol={:?}",
297 sub.error,
298 sub.req_id,
299 sub.symbol
300 );
301 }
302
303 Some(KrakenSpotWsMessage::SubscriptionAck {
304 req_id: sub.req_id,
305 symbol: sub.symbol,
306 success: sub.success,
307 error: sub.error,
308 })
309 }
310 KrakenWsResponse::Unsubscribe(unsub) => {
311 if unsub.success {
312 log::debug!("Unsubscription confirmed: req_id={:?}", unsub.req_id);
313 } else {
314 log::warn!(
315 "Unsubscription failed: error={:?}, req_id={:?}, symbol={:?}",
316 unsub.error,
317 unsub.req_id,
318 unsub.symbol
319 );
320 }
321 None
322 }
323 KrakenWsResponse::Pong(pong) => {
324 log::trace!("Received pong: req_id={:?}", pong.req_id);
325 None
326 }
327 KrakenWsResponse::Other => {
328 log::debug!("Received unknown control response");
329 None
330 }
331 },
332 Err(_) => {
333 log::debug!("Received control message (failed to parse details)");
334 None
335 }
336 }
337 }
338
339 fn handle_data_message(&self, msg: KrakenWsRawMessage) -> Option<KrakenSpotWsMessage> {
340 match msg.channel {
341 KrakenWsChannel::Book => self.handle_book_message(msg),
342 KrakenWsChannel::Ticker => self.handle_ticker_message(msg),
343 KrakenWsChannel::Trade => self.handle_trade_message(msg),
344 KrakenWsChannel::Ohlc => self.handle_ohlc_message(msg),
345 KrakenWsChannel::Executions => self.handle_executions_message(msg),
346 KrakenWsChannel::Level3 => {
347 log::warn!("Dropping malformed level3 message");
350 None
351 }
352 _ => {
353 log::warn!("Unhandled channel: {:?}", msg.channel);
354 None
355 }
356 }
357 }
358
359 fn handle_book_message(&self, msg: KrakenWsRawMessage) -> Option<KrakenSpotWsMessage> {
360 let is_snapshot = msg.event_type == KrakenWsMessageType::Snapshot;
361 let mut book_data = Vec::new();
362
363 for data in msg.data {
364 match serde_json::from_str::<KrakenWsBookData>(data.get()) {
365 Ok(bd) => {
366 if !self.is_subscribed(&format!("book:{}", bd.symbol)) {
367 continue;
368 }
369 book_data.push(bd);
370 }
371 Err(e) => log::error!("Failed to deserialize book data: {e}"),
372 }
373 }
374
375 if book_data.is_empty() {
376 None
377 } else {
378 Some(KrakenSpotWsMessage::Book {
379 data: book_data,
380 is_snapshot,
381 })
382 }
383 }
384
385 fn handle_ticker_message(&self, msg: KrakenWsRawMessage) -> Option<KrakenSpotWsMessage> {
386 let mut tickers = Vec::new();
387
388 for data in msg.data {
389 match serde_json::from_str::<KrakenWsTickerData>(data.get()) {
390 Ok(td) => {
391 let symbol = &td.symbol;
392 let quotes_key = format!("quotes:{symbol}");
393 let ticker_key = format!("ticker:{symbol}");
394 if !self.is_subscribed("es_key) && !self.is_subscribed(&ticker_key) {
395 continue;
396 }
397 tickers.push(td);
398 }
399 Err(e) => log::error!("Failed to deserialize ticker data: {e}"),
400 }
401 }
402
403 if tickers.is_empty() {
404 None
405 } else {
406 Some(KrakenSpotWsMessage::Ticker(tickers))
407 }
408 }
409
410 fn handle_trade_message(&self, msg: KrakenWsRawMessage) -> Option<KrakenSpotWsMessage> {
411 let mut trades = Vec::new();
412
413 for data in msg.data {
414 match serde_json::from_str::<KrakenWsTradeData>(data.get()) {
415 Ok(td) => trades.push(td),
416 Err(e) => log::error!("Failed to deserialize trade data: {e}"),
417 }
418 }
419
420 if trades.is_empty() {
421 None
422 } else {
423 Some(KrakenSpotWsMessage::Trade(trades))
424 }
425 }
426
427 fn handle_ohlc_message(&self, msg: KrakenWsRawMessage) -> Option<KrakenSpotWsMessage> {
428 let mut ohlc_data = Vec::new();
429
430 for data in msg.data {
431 match serde_json::from_str::<KrakenWsOhlcData>(data.get()) {
432 Ok(od) => ohlc_data.push(od),
433 Err(e) => log::error!("Failed to deserialize OHLC data: {e}"),
434 }
435 }
436
437 if ohlc_data.is_empty() {
438 None
439 } else {
440 Some(KrakenSpotWsMessage::Ohlc(ohlc_data))
441 }
442 }
443
444 fn handle_executions_message(&self, msg: KrakenWsRawMessage) -> Option<KrakenSpotWsMessage> {
445 let mut executions = Vec::new();
446
447 for data in msg.data {
448 match serde_json::from_str::<KrakenWsExecutionData>(data.get()) {
449 Ok(ed) => executions.push(ed),
450 Err(e) => log::error!("Failed to deserialize execution data: {e}"),
451 }
452 }
453
454 if executions.is_empty() {
455 None
456 } else {
457 Some(KrakenSpotWsMessage::Execution(executions))
458 }
459 }
460}
461
462#[derive(Deserialize)]
463struct Level3RawMessage<'a> {
464 channel: &'a str,
465 #[serde(rename = "type")]
466 msg_type: &'a str,
467 #[serde(borrow)]
468 data: Vec<&'a RawValue>,
469}
470
471fn parse_level3_text(text: &str) -> Option<KrakenSpotWsMessage> {
472 let msg: Level3RawMessage<'_> = serde_json::from_str(text).ok()?;
473 if msg.channel != "level3" {
474 return None;
475 }
476 let first = msg.data.first()?.get();
477
478 match msg.msg_type {
479 "snapshot" => match serde_json::from_str::<KrakenL3Snapshot>(first) {
480 Ok(snap) => Some(KrakenSpotWsMessage::L3Snapshot(snap)),
481 Err(e) => {
482 log::warn!("Failed to deserialize L3 snapshot: {e}");
483 None
484 }
485 },
486 "update" => match serde_json::from_str::<KrakenL3UpdateData>(first) {
487 Ok(update) => Some(KrakenSpotWsMessage::L3Update(update)),
488 Err(e) => {
489 log::warn!("Failed to deserialize L3 update: {e}");
490 None
491 }
492 },
493 _ => None,
494 }
495}
496
497impl SpotFeedHandler {
498 fn handle_l3_message(&self, msg: KrakenSpotWsMessage) -> Option<KrakenSpotWsMessage> {
499 let symbol = match &msg {
500 KrakenSpotWsMessage::L3Snapshot(s) => &s.symbol,
501 KrakenSpotWsMessage::L3Update(u) => &u.symbol,
502 _ => return None,
503 };
504
505 if !self.is_subscribed(&format!("level3:{symbol}")) {
506 return None;
507 }
508 Some(msg)
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use std::time::Duration;
515
516 use parking_lot::Mutex;
517 use rstest::rstest;
518 use rust_decimal_macros::dec;
519
520 use super::*;
521
522 fn create_test_handler() -> SpotFeedHandler {
523 let signal = Arc::new(AtomicBool::new(false));
524 let (_cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
525 let (_raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
526 let subscriptions = SubscriptionState::new(':');
527
528 SpotFeedHandler::new(signal, cmd_rx, raw_rx, subscriptions)
529 }
530
531 #[rstest]
532 fn test_ticker_message_filtered_without_quotes_subscription() {
533 let handler = create_test_handler();
534
535 let json = r#"{
536 "channel": "ticker",
537 "type": "snapshot",
538 "data": [{
539 "symbol": "BTC/USD",
540 "bid": 105944.20,
541 "bid_qty": 2.5,
542 "ask": 105944.30,
543 "ask_qty": 3.2,
544 "last": 105899.40,
545 "volume": 163.28908096,
546 "vwap": 105904.39279,
547 "low": 104711.00,
548 "high": 106613.10,
549 "change": 250.00,
550 "change_pct": 0.24,
551 "timestamp": "2022-12-25T09:30:59.123456Z"
552 }]
553 }"#;
554
555 let result = handler.parse_message(json);
556 assert!(
557 result.is_none(),
558 "Ticker message should be filtered when no quotes subscription exists"
559 );
560 }
561
562 #[rstest]
563 fn test_ticker_message_passes_with_quotes_subscription() {
564 let handler = create_test_handler();
565 handler.subscriptions.mark_subscribe("quotes:BTC/USD");
566 handler.subscriptions.confirm_subscribe("quotes:BTC/USD");
567
568 let json = r#"{
569 "channel": "ticker",
570 "type": "snapshot",
571 "data": [{
572 "symbol": "BTC/USD",
573 "bid": 105944.20,
574 "bid_qty": 2.5,
575 "ask": 105944.30,
576 "ask_qty": 3.2,
577 "last": 105899.40,
578 "volume": 163.28908096,
579 "vwap": 105904.39279,
580 "low": 104711.00,
581 "high": 106613.10,
582 "change": 250.00,
583 "change_pct": 0.24,
584 "timestamp": "2022-12-25T09:30:59.123456Z"
585 }]
586 }"#;
587
588 let result = handler.parse_message(json);
589 assert!(
590 result.is_some(),
591 "Ticker message should pass with quotes subscription"
592 );
593
594 match result.unwrap() {
595 KrakenSpotWsMessage::Ticker(data) => {
596 assert!(!data.is_empty(), "Should have ticker data");
597 }
598 _ => panic!("Expected Ticker message"),
599 }
600 }
601
602 #[rstest]
603 fn test_ticker_message_passes_with_ticker_subscription() {
604 let handler = create_test_handler();
605 handler.subscriptions.mark_subscribe("ticker:BTC/USD");
606 handler.subscriptions.confirm_subscribe("ticker:BTC/USD");
607
608 let json = r#"{
609 "channel": "ticker",
610 "type": "snapshot",
611 "data": [{
612 "symbol": "BTC/USD",
613 "bid": 105944.20,
614 "bid_qty": 2.5,
615 "ask": 105944.30,
616 "ask_qty": 3.2,
617 "last": 105899.40,
618 "volume": 163.28908096,
619 "vwap": 105904.39279,
620 "low": 104711.00,
621 "high": 106613.10,
622 "change": 250.00,
623 "change_pct": 0.24,
624 "timestamp": "2022-12-25T09:30:59.123456Z"
625 }]
626 }"#;
627
628 let result = handler.parse_message(json);
629 assert!(
630 result.is_some(),
631 "Ticker message should pass with ticker: subscription"
632 );
633
634 match result.unwrap() {
635 KrakenSpotWsMessage::Ticker(data) => {
636 assert!(!data.is_empty(), "Should have ticker data");
637 }
638 _ => panic!("Expected Ticker message"),
639 }
640 }
641
642 #[rstest]
643 fn test_ticker_message_preserves_decimal_precision() {
644 let handler = create_test_handler();
645 handler.subscriptions.mark_subscribe("ticker:BTC/USD");
646 handler.subscriptions.confirm_subscribe("ticker:BTC/USD");
647 let json = include_str!("../../../test_data/ws_ticker_precision.json");
648
649 let message = handler.parse_message(json).unwrap();
650
651 let KrakenSpotWsMessage::Ticker(data) = message else {
652 panic!("Expected Ticker message, was {message:?}");
653 };
654 let ticker = &data[0];
655 assert_eq!(ticker.symbol, "BTC/USD");
656 assert_eq!(ticker.bid, dec!(123456789.123456789));
657 assert_eq!(ticker.bid_qty, dec!(0.1234567890123456789012345678));
658 assert_eq!(ticker.ask, dec!(123456789.223456789));
659 assert_eq!(ticker.ask_qty, dec!(0.2234567890123456789012345678));
660 assert_eq!(ticker.last, dec!(123456789.323456789));
661 assert_eq!(ticker.volume, dec!(123456789.423456789));
662 assert_eq!(ticker.vwap, dec!(123456789.523456789));
663 assert_eq!(ticker.low, dec!(123456789.623456789));
664 assert_eq!(ticker.high, dec!(123456789.723456789));
665 assert_eq!(ticker.change, dec!(123456789.823456789));
666 assert_eq!(ticker.change_pct, dec!(0.9234567890123456789012345678));
667 assert_eq!(
668 ticker.timestamp,
669 "2022-12-25T09:30:59.123456Z"
670 .parse::<jiff::Timestamp>()
671 .unwrap()
672 );
673 }
674
675 #[rstest]
676 fn test_book_message_filtered_without_book_subscription() {
677 let handler = create_test_handler();
678
679 let json = r#"{
680 "channel": "book",
681 "type": "snapshot",
682 "data": [{
683 "symbol": "BTC/USD",
684 "bids": [{"price": 105944.20, "qty": 2.5}],
685 "asks": [{"price": 105944.30, "qty": 3.2}],
686 "checksum": 12345,
687 "timestamp": "2023-10-06T17:35:55.440295Z"
688 }]
689 }"#;
690
691 let result = handler.parse_message(json);
692 assert!(
693 result.is_none(),
694 "Book message should be filtered when no book subscription exists"
695 );
696 }
697
698 #[rstest]
699 fn test_book_message_passes_with_book_subscription() {
700 let handler = create_test_handler();
701 handler.subscriptions.mark_subscribe("book:BTC/USD");
702 handler.subscriptions.confirm_subscribe("book:BTC/USD");
703
704 let json = r#"{
705 "channel": "book",
706 "type": "snapshot",
707 "data": [{
708 "symbol": "BTC/USD",
709 "bids": [{"price": 105944.20, "qty": 2.5}],
710 "asks": [{"price": 105944.30, "qty": 3.2}],
711 "checksum": 12345,
712 "timestamp": "2023-10-06T17:35:55.440295Z"
713 }]
714 }"#;
715
716 let result = handler.parse_message(json);
717 assert!(
718 result.is_some(),
719 "Book message should pass with book subscription"
720 );
721
722 match result.unwrap() {
723 KrakenSpotWsMessage::Book { data, is_snapshot } => {
724 assert!(!data.is_empty());
725 assert!(is_snapshot);
726 }
727 _ => panic!("Expected Book message"),
728 }
729 }
730
731 #[rstest]
732 fn test_send_order_request_variant_construction() {
733 let cmd = SpotHandlerCommand::SendOrderRequest {
734 req_id: 7,
735 payload: SecretString::from(r#"{"method":"add_order","req_id":7}"#.to_string()),
736 };
737
738 match cmd {
739 SpotHandlerCommand::SendOrderRequest { req_id, payload } => {
740 assert_eq!(req_id, 7);
741 assert!(payload.expose_secret().contains("add_order"));
742 }
743 _ => panic!("Expected SendOrderRequest, was a different variant"),
744 }
745 }
746
747 #[rstest]
748 fn test_command_debug_redacts_payload() {
749 let cmd = SpotHandlerCommand::SendOrderRequest {
750 req_id: 7,
751 payload: SecretString::from("auth-token".to_string()),
752 };
753
754 let debug = format!("{cmd:?}");
755
756 assert!(debug.contains(REDACTED));
757 assert!(!debug.contains("auth-token"));
758 }
759
760 #[rstest]
761 #[tokio::test]
762 async fn test_send_order_request_without_active_client_does_not_panic() {
763 let signal = Arc::new(AtomicBool::new(false));
764 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
765 let (raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel::<Message>();
766 let subscriptions = SubscriptionState::new(':');
767
768 let mut handler = SpotFeedHandler::new(signal.clone(), cmd_rx, raw_rx, subscriptions);
769
770 cmd_tx
771 .send(SpotHandlerCommand::SendOrderRequest {
772 req_id: 42,
773 payload: SecretString::from(r#"{"method":"add_order","req_id":42}"#.to_string()),
774 })
775 .unwrap();
776
777 drop(cmd_tx);
778 drop(raw_tx);
779
780 let result = handler.next().await;
781 assert!(
782 result.is_none(),
783 "Handler should return None when streams close"
784 );
785 }
786
787 struct DroppedCommandLogCapture {
788 messages: Mutex<Vec<String>>,
789 }
790
791 static DROPPED_COMMAND_LOG_CAPTURE: DroppedCommandLogCapture = DroppedCommandLogCapture {
792 messages: Mutex::new(Vec::new()),
793 };
794
795 impl log::Log for DroppedCommandLogCapture {
796 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
797 metadata.level() == log::Level::Error
798 && metadata.target() == "nautilus_kraken::websocket::spot_v2::handler"
799 }
800
801 fn log(&self, record: &log::Record<'_>) {
802 if self.enabled(record.metadata()) {
803 self.messages.lock().push(record.args().to_string());
804 }
805 }
806
807 fn flush(&self) {}
808 }
809
810 #[rstest]
813 #[tokio::test]
814 async fn test_subscribe_without_active_client_logs_dropped_command() {
815 log::set_logger(&DROPPED_COMMAND_LOG_CAPTURE).expect("test logger already installed");
816 log::set_max_level(log::LevelFilter::Error);
817
818 let signal = Arc::new(AtomicBool::new(false));
819 let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
820 let (_raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel::<Message>();
823 let subscriptions = SubscriptionState::new(':');
824
825 let mut handler = SpotFeedHandler::new(signal, cmd_rx, raw_rx, subscriptions);
826
827 cmd_tx
828 .send(SpotHandlerCommand::Subscribe {
829 payload: SecretString::from(
830 r#"{"method":"subscribe","token":"SUBSCRIBE_SECRET_MARKER"}"#.to_string(),
831 ),
832 })
833 .unwrap();
834
835 drop(cmd_tx);
836
837 let mut next = std::pin::pin!(handler.next());
838 let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
839
840 while DROPPED_COMMAND_LOG_CAPTURE.messages.lock().is_empty() {
841 assert!(
842 tokio::time::Instant::now() < deadline,
843 "handler never processed the queued subscribe"
844 );
845 let _ = tokio::time::timeout(Duration::from_millis(10), next.as_mut()).await;
846 }
847
848 let messages = DROPPED_COMMAND_LOG_CAPTURE.messages.lock().clone();
849 assert_eq!(
850 messages,
851 vec!["Kraken WS subscribe or unsubscribe dropped, no active client".to_string()],
852 "a subscribe without an active client must log the dropped command"
853 );
854 assert!(
855 !messages.join("\n").contains("SUBSCRIBE_SECRET_MARKER"),
856 "dropped-command log must not leak the payload"
857 );
858 }
859
860 #[rstest]
861 fn test_quotes_and_book_subscriptions_independent() {
862 let handler = create_test_handler();
863 handler.subscriptions.mark_subscribe("quotes:BTC/USD");
864 handler.subscriptions.confirm_subscribe("quotes:BTC/USD");
865
866 let book_json = r#"{
867 "channel": "book",
868 "type": "snapshot",
869 "data": [{
870 "symbol": "BTC/USD",
871 "bids": [{"price": 105944.20, "qty": 2.5}],
872 "asks": [{"price": 105944.30, "qty": 3.2}],
873 "checksum": 12345,
874 "timestamp": "2023-10-06T17:35:55.440295Z"
875 }]
876 }"#;
877
878 let book_result = handler.parse_message(book_json);
879 assert!(
880 book_result.is_none(),
881 "Book message should be filtered without book: subscription"
882 );
883
884 let ticker_json = r#"{
885 "channel": "ticker",
886 "type": "snapshot",
887 "data": [{
888 "symbol": "BTC/USD",
889 "bid": 105944.20,
890 "bid_qty": 2.5,
891 "ask": 105944.30,
892 "ask_qty": 3.2,
893 "last": 105899.40,
894 "volume": 163.28908096,
895 "vwap": 105904.39279,
896 "low": 104711.00,
897 "high": 106613.10,
898 "change": 250.00,
899 "change_pct": 0.24,
900 "timestamp": "2022-12-25T09:30:59.123456Z"
901 }]
902 }"#;
903
904 let ticker_result = handler.parse_message(ticker_json);
905 assert!(
906 ticker_result.is_some(),
907 "Ticker should pass with quotes subscription"
908 );
909 }
910
911 #[rstest]
912 fn test_parse_message_routes_add_order_response_to_order_response_variant() {
913 use super::super::enums::KrakenWsMethod;
914
915 let handler = create_test_handler();
916 let json = r#"{"method":"add_order","req_id":42,"success":true,"time_in":"2026-05-05T10:00:00.123Z","time_out":"2026-05-05T10:00:00.125Z","result":{"order_id":"OABCDE-12345-FGHIJ","cl_ord_id":"O-20260505-000001","order_userref":0}}"#;
917
918 let result = handler.parse_message(json);
919 match result {
920 Some(KrakenSpotWsMessage::OrderResponse(resp)) => {
921 assert_eq!(resp.method, KrakenWsMethod::AddOrder);
922 assert_eq!(resp.req_id, Some(42));
923 assert!(resp.success);
924 }
925 other => panic!("expected OrderResponse, was {other:?}"),
926 }
927 }
928
929 #[rstest]
932 fn test_parse_message_yields_a_subscribe_rejection() {
933 let handler = create_test_handler();
934 let json = r#"{"error":"Currency pair not supported BOGUS/NOPE","method":"subscribe","req_id":7,"success":false,"symbol":"BOGUS/NOPE","time_in":"2026-05-05T10:00:00.123Z","time_out":"2026-05-05T10:00:00.125Z"}"#;
935
936 let result = handler.parse_message(json);
937
938 let Some(KrakenSpotWsMessage::SubscriptionAck {
939 req_id,
940 symbol,
941 success,
942 error,
943 }) = result
944 else {
945 panic!("expected a SubscriptionAck, was {result:?}");
946 };
947 assert_eq!(req_id, Some(7));
948 assert_eq!(symbol, Some(ustr::Ustr::from("BOGUS/NOPE")));
949 assert!(!success);
950 assert_eq!(
951 error.as_deref(),
952 Some("Currency pair not supported BOGUS/NOPE")
953 );
954 }
955
956 #[rstest]
958 fn test_parse_message_yields_a_subscribe_confirmation() {
959 let handler = create_test_handler();
960 let json = r#"{"method":"subscribe","result":{"channel":"book","symbol":"BTC/USD","depth":10,"snapshot":true},"success":true,"time_in":"2026-05-05T10:00:00.123Z","time_out":"2026-05-05T10:00:00.125Z","req_id":3}"#;
961
962 let result = handler.parse_message(json);
963
964 let Some(KrakenSpotWsMessage::SubscriptionAck {
965 req_id,
966 symbol,
967 success,
968 error,
969 }) = result
970 else {
971 panic!("expected a SubscriptionAck, was {result:?}");
972 };
973 assert_eq!(req_id, Some(3));
974 assert_eq!(symbol, None, "a confirmation names the pair in result only");
975 assert!(success);
976 assert!(error.is_none());
977
978 let unsubscribe = r#"{"method":"unsubscribe","result":{"channel":"book","symbol":"BTC/USD"},"success":true,"time_in":"2026-05-05T10:00:00.123Z","time_out":"2026-05-05T10:00:00.125Z","req_id":4}"#;
979 assert!(
980 handler.parse_message(unsubscribe).is_none(),
981 "only subscribe answers reach the stream"
982 );
983 }
984
985 #[rstest]
989 #[tokio::test]
990 async fn test_next_yields_answers_and_book_frames_in_wire_order() {
991 let signal = Arc::new(AtomicBool::new(false));
992 let (_cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
993 let (raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
994 let subscriptions = SubscriptionState::new(':');
995 subscriptions.mark_subscribe("book:BTC/USD");
996 subscriptions.confirm_subscribe("book:BTC/USD");
997 let mut handler = SpotFeedHandler::new(signal, cmd_rx, raw_rx, subscriptions);
998
999 for text in [
1000 r#"{"method":"subscribe","result":{"channel":"book","symbol":"BTC/USD","depth":10,"snapshot":true},"success":true,"time_in":"2026-05-05T10:00:00.123Z","time_out":"2026-05-05T10:00:00.125Z","req_id":3}"#,
1001 r#"{"channel":"book","type":"snapshot","data":[{"symbol":"BTC/USD","bids":[{"price":105944.20,"qty":2.5}],"asks":[{"price":105944.30,"qty":3.2}],"checksum":12345,"timestamp":"2023-10-06T17:35:55.440295Z"}]}"#,
1002 r#"{"channel":"book","type":"update","data":[{"symbol":"BTC/USD","bids":[{"price":105944.20,"qty":2.0}],"asks":[],"checksum":12346,"timestamp":"2023-10-06T17:35:55.540295Z"}]}"#,
1003 r#"{"error":"Subscription with depth 10 not Found BTC/USD","method":"subscribe","req_id":502,"success":false,"symbol":"BTC/USD","time_in":"2026-05-05T10:00:01.123Z","time_out":"2026-05-05T10:00:01.125Z"}"#,
1004 ] {
1005 raw_tx.send(Message::Text(text.into())).unwrap();
1006 }
1007
1008 let Some(KrakenSpotWsMessage::SubscriptionAck {
1009 req_id: Some(3),
1010 success: true,
1011 ..
1012 }) = handler.next().await
1013 else {
1014 panic!("expected the confirmation first");
1015 };
1016 let Some(KrakenSpotWsMessage::Book {
1017 is_snapshot: true, ..
1018 }) = handler.next().await
1019 else {
1020 panic!("expected the snapshot second");
1021 };
1022 let Some(KrakenSpotWsMessage::Book {
1023 is_snapshot: false, ..
1024 }) = handler.next().await
1025 else {
1026 panic!("expected the update third");
1027 };
1028 let failed_unsubscribe = handler.next().await;
1029 let Some(KrakenSpotWsMessage::SubscriptionAck {
1030 req_id: Some(502),
1031 symbol: Some(symbol),
1032 success: false,
1033 ..
1034 }) = failed_unsubscribe
1035 else {
1036 panic!(
1037 "expected the failed unsubscribe as a subscribe answer, was {failed_unsubscribe:?}"
1038 );
1039 };
1040 assert_eq!(symbol, ustr::Ustr::from("BTC/USD"));
1041 }
1042
1043 #[rstest]
1044 fn test_parse_level3_snapshot_with_subscription_passes() {
1045 let handler = create_test_handler();
1046 handler.subscriptions.mark_subscribe("level3:BTC/USD");
1047 handler.subscriptions.confirm_subscribe("level3:BTC/USD");
1048
1049 let json = r#"{
1050 "channel": "level3",
1051 "type": "snapshot",
1052 "data": [{
1053 "symbol": "BTC/USD",
1054 "bids": [],
1055 "asks": [],
1056 "checksum": 0,
1057 "timestamp": "2024-01-01T00:00:00Z"
1058 }]
1059 }"#;
1060
1061 let result = handler.parse_message(json);
1062 assert!(matches!(result, Some(KrakenSpotWsMessage::L3Snapshot(_))));
1063 }
1064
1065 #[rstest]
1066 fn test_parse_level3_update_without_subscription_filtered() {
1067 let handler = create_test_handler();
1068 let json = r#"{
1069 "channel": "level3",
1070 "type": "update",
1071 "data": [{
1072 "symbol": "BTC/USD",
1073 "bids": [],
1074 "asks": [],
1075 "checksum": 0,
1076 "timestamp": "2024-01-01T00:00:00Z"
1077 }]
1078 }"#;
1079
1080 let result = handler.parse_message(json);
1081 assert!(result.is_none());
1082 }
1083
1084 #[rstest]
1085 #[case::empty_data(r#"{"channel":"level3","type":"update","data":[]}"#)]
1086 #[case::snapshot_missing_bids(
1087 r#"{"channel":"level3","type":"snapshot","data":[{"symbol":"BTC/USD","asks":[],"checksum":0,"timestamp":"2024-01-01T00:00:00Z"}]}"#
1088 )]
1089 #[case::unexpected_type(r#"{"channel":"level3","type":"error","data":[{}]}"#)]
1090 fn test_parse_level3_malformed_message_is_dropped(#[case] json: &str) {
1091 let handler = create_test_handler();
1092 handler.subscriptions.mark_subscribe("level3:BTC/USD");
1093 handler.subscriptions.confirm_subscribe("level3:BTC/USD");
1094
1095 let result = handler.parse_message(json);
1096 assert!(result.is_none());
1097 }
1098
1099 #[rstest]
1100 fn test_parse_level3_snapshot_compact_json() {
1101 let handler = create_test_handler();
1102 handler.subscriptions.mark_subscribe("level3:BTC/USD");
1103 handler.subscriptions.confirm_subscribe("level3:BTC/USD");
1104 let json = r#"{"channel":"level3","type":"snapshot","data":[{"symbol":"BTC/USD","bids":[],"asks":[],"checksum":0,"timestamp":"2024-01-01T00:00:00Z"}]}"#;
1105 assert!(matches!(
1106 handler.parse_message(json),
1107 Some(KrakenSpotWsMessage::L3Snapshot(_))
1108 ));
1109 }
1110
1111 #[rstest]
1112 fn test_parse_level3_snapshot_preserves_raw_decimal() {
1113 let handler = create_test_handler();
1114 handler.subscriptions.mark_subscribe("level3:BTC/USD");
1115 handler.subscriptions.confirm_subscribe("level3:BTC/USD");
1116
1117 let json = r#"{
1118 "channel": "level3",
1119 "type": "snapshot",
1120 "data": [{
1121 "symbol": "BTC/USD",
1122 "bids": [{
1123 "order_id": "order-bid-1",
1124 "limit_price": 42000.50000,
1125 "order_qty": 0.01000000,
1126 "timestamp": "2024-01-01T00:00:00Z"
1127 }],
1128 "asks": [],
1129 "checksum": 0,
1130 "timestamp": "2024-01-01T00:00:00Z"
1131 }]
1132 }"#;
1133
1134 let Some(KrakenSpotWsMessage::L3Snapshot(snap)) = handler.parse_message(json) else {
1135 panic!("expected L3 snapshot");
1136 };
1137 assert_eq!(snap.bids[0].limit_price.raw, "42000.50000");
1138 assert_eq!(snap.bids[0].order_qty.raw, "0.01000000");
1139 }
1140}