ek-api 0.1.2

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! 事件推送枢纽(M6):订阅表 + 每连接有界队列 + 合并批量写。
//!
//! 线程模型:
//! - 事件线程(EventEngine)→ [`Hub::publish`]:只持表锁 + `send`,**零阻塞**;
//! - 每连接一个写线程([`spawn_writer`]):收帧 → 有界队列 → 批量 flush;
//! - tick / bar_update 在 flush 时按 `symbol` 合并(只留最新一条),
//!   掉队的 tick 丢给 `ev.dropped` 计数。

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;

/// 单连接出站队列上限(超出丢最旧帧,计 `ev.dropped`)。
pub const QUEUE_CAP: usize = 4096;
/// 攒够这么多帧立即 flush。
pub const FLUSH_BATCH: usize = 64;
/// 空闲合并窗口(毫秒)。
pub const FLUSH_MS: u64 = 20;

/// 可订阅的事件 type(精确名;与 `EventEngine::register` 的语义一致)。
pub const EV_TOPICS: &[&str] = &[
    "ePlugUp",
    "ePlugDown",
    "eLog",
    "eTick.",
    "eBar.",
    "eBarUpdate.",
    "eOrder.",
    "eTrade.",
    "ePosition.",
    "eAccount.",
    "eContract.",
    "eContractFinish",
    "eStrategy.",
    "eStrategyMeta",
    "eStatus.",
];

/// API 自产心跳主题(不是总线事件;由 ek-server 每秒推送)。
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),
        }
    }

    /// 登记一条连接(`tx` = 该连接写线程的入口),返回连接 id。
    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()
    }

    /// 广播(事件线程调用;只做非阻塞 send)。
    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()
    }
}

/// 每连接写线程:收帧 → 有界队列 → 批量 flush。
///
/// `stream` 与连接线程共享(`Arc<Mutex<TcpStream>>`),保证推帧与应答帧
/// 不会在同一 socket 上交错。
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());
    }
    // tick 与 bar_update 按 symbol 合并(只留最新一条)。
    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());
    }
}