okx-client 0.1.2

Async Rust client for the OKX exchange API v5
Documentation
use std::time::Duration;

use tokio::sync::{mpsc, watch};
use tracing::{debug, warn};

use crate::types::ws::events::{WsConnectionType, WsMessage};

pub async fn heartbeat_loop(
    tx: mpsc::UnboundedSender<String>,
    interval: Duration,
    pong_timeout: Duration,
    mut pong_rx: mpsc::UnboundedReceiver<()>,
    event_tx: mpsc::UnboundedSender<WsMessage>,
    conn_type: WsConnectionType,
    mut stop_rx: watch::Receiver<bool>,
) {
    let mut ticker = tokio::time::interval(interval);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    ticker.tick().await;

    loop {
        tokio::select! {
            _ = ticker.tick() => {}
            result = stop_rx.changed() => {
                if result.is_err() || *stop_rx.borrow() {
                    break;
                }
                continue;
            }
        }

        while pong_rx.try_recv().is_ok() {}

        debug!("Sending WS ping");
        if tx.send("ping".to_string()).is_err() {
            let _ = event_tx.send(WsMessage::Disconnected(conn_type));
            break;
        }

        tokio::select! {
            pong = pong_rx.recv() => {
                if pong.is_none() {
                    break;
                }
            }
            _ = tokio::time::sleep(pong_timeout) => {
                warn!("WS {conn_type} pong timed out");
                let _ = event_tx.send(WsMessage::Disconnected(conn_type));
                break;
            }
            result = stop_rx.changed() => {
                if result.is_err() || *stop_rx.borrow() {
                    break;
                }
            }
        }
    }

    debug!("Heartbeat stopped");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test(start_paused = true)]
    async fn pong_prevents_timeout() {
        let (write_tx, mut write_rx) = mpsc::unbounded_channel();
        let (pong_tx, pong_rx) = mpsc::unbounded_channel();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let (stop_tx, stop_rx) = watch::channel(false);

        let heartbeat = tokio::spawn(heartbeat_loop(
            write_tx,
            Duration::from_secs(10),
            Duration::from_secs(5),
            pong_rx,
            event_tx,
            WsConnectionType::Public,
            stop_rx,
        ));

        tokio::task::yield_now().await;
        tokio::time::advance(Duration::from_secs(10)).await;
        tokio::task::yield_now().await;
        assert_eq!(write_rx.try_recv().unwrap(), "ping");

        pong_tx.send(()).unwrap();
        tokio::time::advance(Duration::from_secs(5)).await;
        tokio::task::yield_now().await;
        assert!(event_rx.try_recv().is_err());

        stop_tx.send(true).unwrap();
        heartbeat.await.unwrap();
    }

    #[tokio::test(start_paused = true)]
    async fn missing_pong_disconnects() {
        let (write_tx, mut write_rx) = mpsc::unbounded_channel();
        let (_pong_tx, pong_rx) = mpsc::unbounded_channel();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let (_stop_tx, stop_rx) = watch::channel(false);

        let heartbeat = tokio::spawn(heartbeat_loop(
            write_tx,
            Duration::from_secs(10),
            Duration::from_secs(5),
            pong_rx,
            event_tx,
            WsConnectionType::Private,
            stop_rx,
        ));

        tokio::task::yield_now().await;
        tokio::time::advance(Duration::from_secs(10)).await;
        tokio::task::yield_now().await;
        assert_eq!(write_rx.try_recv().unwrap(), "ping");

        tokio::time::advance(Duration::from_secs(5)).await;
        tokio::task::yield_now().await;
        assert!(matches!(
            event_rx.try_recv(),
            Ok(WsMessage::Disconnected(WsConnectionType::Private))
        ));
        heartbeat.await.unwrap();
    }

    #[tokio::test(start_paused = true)]
    async fn stop_cancels_heartbeat() {
        let (write_tx, mut write_rx) = mpsc::unbounded_channel();
        let (_pong_tx, pong_rx) = mpsc::unbounded_channel();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let (stop_tx, stop_rx) = watch::channel(false);

        let heartbeat = tokio::spawn(heartbeat_loop(
            write_tx,
            Duration::from_secs(10),
            Duration::from_secs(5),
            pong_rx,
            event_tx,
            WsConnectionType::Business,
            stop_rx,
        ));

        stop_tx.send(true).unwrap();
        tokio::task::yield_now().await;
        tokio::time::advance(Duration::from_secs(20)).await;
        heartbeat.await.unwrap();

        assert!(write_rx.try_recv().is_err());
        assert!(event_rx.try_recv().is_err());
    }
}