use std::collections::{HashMap, VecDeque};
use std::net::TcpStream;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use serde_json::{Value, json};
use crate::proto;
pub const QUEUE_CAP: usize = 4096;
pub const FLUSH_BATCH: usize = 64;
pub const FLUSH_MS: u64 = 20;
pub const EV_TOPICS: &[&str] = &[
"ePlugUp",
"ePlugDown",
"eLog",
"eTick.",
"eBar.",
"eBarUpdate.",
"eOrder.",
"eTrade.",
"ePosition.",
"eAccount.",
"eContract.",
"eContractFinish",
"eStrategy.",
"eStrategyMeta",
"eStatus.",
];
pub const TOPIC_STATUS: &str = "sys.status";
#[must_use]
pub fn is_topic(t: &str) -> bool {
EV_TOPICS.contains(&t) || t == TOPIC_STATUS
}
pub struct Hub {
inner: Mutex<HashMap<u64, ConnSub>>,
next: AtomicU64,
}
struct ConnSub {
topics: Vec<String>,
tx: mpsc::Sender<Value>,
}
impl Hub {
#[must_use]
pub fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
next: AtomicU64::new(1),
}
}
pub fn register(&self, tx: mpsc::Sender<Value>) -> u64 {
let id = self.next.fetch_add(1, Ordering::Relaxed);
self.inner
.lock()
.unwrap()
.insert(id, ConnSub { topics: Vec::new(), tx });
id
}
pub fn unregister(&self, id: u64) {
self.inner.lock().unwrap().remove(&id);
}
pub fn subscribe(&self, id: u64, topics: &[String]) -> Vec<String> {
let mut g = self.inner.lock().unwrap();
let Some(s) = g.get_mut(&id) else {
return Vec::new();
};
for t in topics {
if !s.topics.contains(t) {
s.topics.push(t.clone());
}
}
s.topics.clone()
}
pub fn unsubscribe(&self, id: u64, topics: &[String]) -> Vec<String> {
let mut g = self.inner.lock().unwrap();
let Some(s) = g.get_mut(&id) else {
return Vec::new();
};
s.topics.retain(|t| !topics.contains(t));
s.topics.clone()
}
pub fn topics(&self, id: u64) -> Vec<String> {
self.inner
.lock()
.unwrap()
.get(&id)
.map(|s| s.topics.clone())
.unwrap_or_default()
}
pub fn publish(&self, topic: &str, frame: Value) {
let g = self.inner.lock().unwrap();
for s in g.values() {
if s.topics.iter().any(|t| t == topic) {
let _ = s.tx.send(frame.clone());
}
}
}
pub fn conns(&self) -> usize {
self.inner.lock().unwrap().len()
}
}
impl Default for Hub {
fn default() -> Self {
Self::new()
}
}
pub fn spawn_writer(
stream: Arc<Mutex<TcpStream>>,
rx: mpsc::Receiver<Value>,
dropped: Arc<AtomicU64>,
) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
let mut q: VecDeque<Value> = VecDeque::new();
loop {
match rx.recv_timeout(Duration::from_millis(FLUSH_MS)) {
Ok(v) => {
if q.len() >= QUEUE_CAP {
q.pop_front();
dropped.fetch_add(1, Ordering::Relaxed);
}
q.push_back(v);
if q.len() < FLUSH_BATCH {
continue;
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
flush(&stream, &mut q, &dropped);
break;
}
}
flush(&stream, &mut q, &dropped);
}
})
}
fn flush(stream: &Arc<Mutex<TcpStream>>, q: &mut VecDeque<Value>, dropped: &AtomicU64) {
if q.is_empty() {
return;
}
let mut w = stream.lock().unwrap_or_else(|p| p.into_inner());
let n = dropped.swap(0, Ordering::Relaxed);
if n > 0 {
let frame =
json!({"jsonrpc":"2.0","method":"ev","params":{"topic":"ev.dropped","count":n}});
let _ = proto::write_frame(&mut *w, &frame.to_string());
}
let mut ticks: HashMap<String, Value> = HashMap::new();
let mut bars: HashMap<String, Value> = HashMap::new();
let mut others: Vec<Value> = Vec::new();
for v in q.drain(..) {
let topic = v["params"]["topic"].as_str().unwrap_or("");
let key = v["params"]["data"]["symbol"]
.as_str()
.unwrap_or("")
.to_string();
match topic {
"eTick." => {
ticks.insert(key, v);
}
"eBarUpdate." => {
bars.insert(key, v);
}
_ => others.push(v),
}
}
for v in others
.into_iter()
.chain(ticks.into_values())
.chain(bars.into_values())
{
let _ = proto::write_frame(&mut *w, &v.to_string());
}
}