use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::oneshot;
use crate::types::ws::events::{WsApiResponse, WsConnectionType};
use crate::types::ws::requests::WsApiRequest;
static REQUEST_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
pub fn next_request_id() -> String {
REQUEST_ID_COUNTER.fetch_add(1, Ordering::SeqCst).to_string()
}
pub fn build_api_request(op: &str, args: Vec<serde_json::Value>) -> WsApiRequest {
WsApiRequest {
id: next_request_id(),
op: op.to_string(),
args,
}
}
#[derive(Debug)]
struct PendingRequest {
conn_type: WsConnectionType,
response_tx: oneshot::Sender<WsApiResponse>,
}
#[derive(Debug, Default)]
pub struct PendingRequests {
inner: HashMap<String, PendingRequest>,
}
impl PendingRequests {
pub fn new() -> Self {
Self::default()
}
pub fn register(
&mut self,
id: String,
conn_type: WsConnectionType,
) -> oneshot::Receiver<WsApiResponse> {
let (tx, rx) = oneshot::channel();
self.inner.insert(
id,
PendingRequest {
conn_type,
response_tx: tx,
},
);
rx
}
pub fn resolve(&mut self, id: &str, response: WsApiResponse) -> bool {
if let Some(request) = self.inner.remove(id) {
let _ = request.response_tx.send(response);
true
} else {
false
}
}
pub fn remove(&mut self, id: &str) -> bool {
self.inner.remove(id).is_some()
}
pub fn reject_connection(&mut self, conn_type: WsConnectionType) {
self.inner
.retain(|_, request| request.conn_type != conn_type);
}
#[cfg(test)]
pub fn pending_count(&self) -> usize {
self.inner.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_next_request_id_unique() {
let id1 = next_request_id();
let id2 = next_request_id();
assert_ne!(id1, id2);
}
#[test]
fn test_build_api_request() {
let req = build_api_request("order", vec![serde_json::json!({"instId": "BTC-USDT"})]);
assert_eq!(req.op, "order");
assert_eq!(req.args.len(), 1);
assert!(!req.id.is_empty());
}
#[test]
fn test_pending_requests_resolve() {
let mut pending = PendingRequests::new();
let mut rx = pending.register("test-1".to_string(), WsConnectionType::Private);
let response = WsApiResponse {
id: "test-1".to_string(),
op: "order".to_string(),
code: "0".to_string(),
msg: String::new(),
data: vec![],
in_time: None,
out_time: None,
};
assert!(pending.resolve("test-1", response));
let result = rx.try_recv().unwrap();
assert_eq!(result.id, "test-1");
assert_eq!(result.code, "0");
}
#[test]
fn test_pending_requests_resolve_unknown() {
let mut pending = PendingRequests::new();
let response = WsApiResponse {
id: "unknown".to_string(),
op: "order".to_string(),
code: "0".to_string(),
msg: String::new(),
data: vec![],
in_time: None,
out_time: None,
};
assert!(!pending.resolve("unknown", response));
}
#[test]
fn pending_requests_remove_one_request() {
let mut pending = PendingRequests::new();
let mut rx = pending.register("1".to_string(), WsConnectionType::Private);
assert!(pending.remove("1"));
assert!(!pending.remove("1"));
assert!(rx.try_recv().is_err());
assert_eq!(pending.pending_count(), 0);
}
#[test]
fn pending_requests_reject_one_connection() {
let mut pending = PendingRequests::new();
let mut private_rx = pending.register("1".to_string(), WsConnectionType::Private);
let mut business_rx = pending.register("2".to_string(), WsConnectionType::Business);
pending.reject_connection(WsConnectionType::Private);
assert!(private_rx.try_recv().is_err());
assert!(matches!(
business_rx.try_recv(),
Err(oneshot::error::TryRecvError::Empty)
));
assert_eq!(pending.pending_count(), 1);
pending.reject_connection(WsConnectionType::Business);
assert!(business_rx.try_recv().is_err());
assert_eq!(pending.pending_count(), 0);
}
}