ek-api 0.1.2

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! API 插件:镜像全部已装配插件的执行面(服务/配置/状态),只读为主;
//! M6 起兼事件推送枢纽(直接挂 EventEngine 的通用 handler,零阻塞转发)。

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

use ek_core::context::PluginContext;
use ek_core::plugin::Plugin;
use ek_event::{Event, EventEngine};

use crate::audit::AuditLog;
use crate::hub::{self, Hub};

/// 宿主里的 `api` 插件(单实例,注册名固定 "api")。
pub struct ApiPlugin {
    ctx: Mutex<Option<PluginContext>>,
    store: ek_cfg::Store,
    profile: String,
    log_path: Mutex<PathBuf>,
    audit: AuditLog,
    hub: Arc<Hub>,
    dropped: Arc<AtomicU64>,
    /// 交易幂等键(client_order_id → 已受理结果;进程内,重启即清空)。
    orders: Mutex<HashMap<String, serde_json::Value>>,
    conns: AtomicU64,
    started_ms: u64,
}

impl ApiPlugin {
    /// 构造;`log_path` = ek-server 自身日志文件(log.tail 用;同目录放审计)。
    ///
    /// `event` = 宿主 EventEngine:这里挂通用 handler,把
    /// [`crate::hub::EV_TOPICS`] 里的事件转成 JSON 帧投给订阅连接。
    #[must_use]
    pub fn new(
        store: ek_cfg::Store,
        profile: String,
        log_path: PathBuf,
        event: &Arc<EventEngine>,
    ) -> Self {
        let audit_dir = log_path
            .parent()
            .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
        let hub = Arc::new(Hub::new());
        let dropped = Arc::new(AtomicU64::new(0));
        let h = Arc::clone(&hub);
        event.register_general(Arc::new(move |e: &Event| {
            if let Some(frame) = crate::event_json::event_frame(e) {
                h.publish(e.event_type.as_str(), frame);
            }
        }));
        Self {
            ctx: Mutex::new(None),
            store,
            profile,
            log_path: Mutex::new(log_path),
            audit: AuditLog::new(&audit_dir),
            hub,
            dropped,
            orders: Mutex::new(HashMap::new()),
            conns: AtomicU64::new(0),
            started_ms: now_ms(),
        }
    }

    /// 幂等键查询(命中 = 该 client_order_id 已受理过)。
    #[must_use]
    pub fn order_result(&self, client_id: &str) -> Option<serde_json::Value> {
        self.orders
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .get(client_id)
            .cloned()
    }

    /// 记一条幂等结果(上限 4096,超出清空;重启即清空)。
    pub fn store_order_result(&self, client_id: String, result: serde_json::Value) {
        let mut g = self.orders.lock().unwrap_or_else(|p| p.into_inner());
        if g.len() >= 4096 {
            g.clear();
        }
        g.insert(client_id, result);
    }

    /// 审计器。
    #[must_use]
    pub fn audit(&self) -> &AuditLog {
        &self.audit
    }

    /// 推送枢纽。
    #[must_use]
    pub fn hub(&self) -> &Arc<Hub> {
        &self.hub
    }

    /// 掉帧计数(每连接写线程共享)。
    #[must_use]
    pub fn dropped(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.dropped)
    }

    /// 主引擎上下文(on_init 后可用)。
    #[must_use]
    pub fn ctx(&self) -> Option<PluginContext> {
        self.ctx.lock().unwrap_or_else(|p| p.into_inner()).clone()
    }

    #[must_use]
    pub fn store(&self) -> &ek_cfg::Store {
        &self.store
    }

    #[must_use]
    pub fn profile(&self) -> &str {
        &self.profile
    }

    #[must_use]
    pub fn log_path(&self) -> PathBuf {
        self.log_path
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .clone()
    }

    #[must_use]
    pub fn conns(&self) -> u64 {
        self.conns.load(Ordering::Relaxed)
    }

    pub fn conn_open(&self) {
        self.conns.fetch_add(1, Ordering::Relaxed);
    }

    pub fn conn_close(&self) {
        self.conns.fetch_sub(1, Ordering::Relaxed);
    }

    #[must_use]
    pub fn started_ms(&self) -> u64 {
        self.started_ms
    }

    /// 已运行毫秒(心跳用)。
    #[must_use]
    pub fn uptime_ms(&self) -> u64 {
        now_ms().saturating_sub(self.started_ms)
    }
}

impl Plugin for ApiPlugin {
    fn name(&self) -> &str {
        "api"
    }

    fn version(&self) -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed(env!("CARGO_PKG_VERSION"))
    }

    /// 订阅面声明 = 可推送事件线(实际投递走通用 handler,见 `new`)。
    fn routes(&self) -> Vec<std::borrow::Cow<'static, str>> {
        hub::EV_TOPICS
            .iter()
            .map(|t| std::borrow::Cow::Borrowed(*t))
            .collect()
    }

    fn on_init(&self, ctx: &PluginContext) {
        *self.ctx.lock().unwrap_or_else(|p| p.into_inner()) = Some(ctx.clone());
    }

    fn on_mail(&self, _event: &Event) {
        // 推送走 EventEngine 通用 handler(`new` 里注册);这里不重复转发。
    }
}

fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// 供 bin 共享的包(Server 与 ApiPlugin 各持一份)。
pub type SharedApi = Arc<ApiPlugin>;