ek-core 0.1.0

Business-agnostic plugin host and actor-over-bus runtime on top of ek-event: single-registry plugins, explicit deps with topological start, per-plugin actor workers, one-shot request/reply, panic quarantine, five-step close.
Documentation
//! 注册表(内部):单表统一 add / get / typed get / remove;
//! 状态原子 CAS;deps 快照;start 拓扑序。

use crate::error::PluginError;
use crate::main_engine::PluginState;
use ek_event::{Event, HandlerId};
use std::any::Any;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::thread::JoinHandle;

use crossbeam_channel::Sender;

/// 每插件运行统计(供宿主查询/测试断言/告警)。
#[derive(Default)]
pub(crate) struct EntryStats {
    /// forwarder 溢出丢弃累计(邮箱满)。
    pub spilled: AtomicU64,
    /// handler panic 累计。
    pub panics: AtomicU64,
    /// worker 退出标志(join-with-deadline 用,D4)。
    pub done: AtomicBool,
}

/// 注册表的一条记录(内部,不公开)。
pub(crate) struct PluginEntry {
    pub name: String,
    /// 供 worker/on_mail 与生命周期钩子调用的 trait 对象。
    pub plugin: Arc<dyn crate::plugin::Plugin>,
    /// 指向同一分配的 `Arc<dyn Any + Send + Sync>`:get_typed 的 downcast 底座。
    pub any: Arc<dyn Any + Send + Sync>,
    pub state: PluginStateCell,
    pub mailbox_cap: usize,
    pub deps: Vec<String>,
    /// 宿主侧邮箱发端(持有一份;close 第③步置 None → 全部 Sender 消费尽 → 断连)。
    pub mailbox: Mutex<Option<Sender<Event>>>,
    /// start 装配的 forwarder 注册 id(close/remove 第①步逐个卸)。
    pub forwarder_ids: Mutex<Vec<HandlerId>>,
    /// worker 句柄(close 第⑤步 join,超时则弃-剥离)。
    pub worker: Mutex<Option<JoinHandle<()>>>,
    pub stats: Arc<EntryStats>,
}

/// 插件状态(AtomicU8 CAS 迁移,非法迁移拒绝)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginStateCode {
    Ready = 0,
    Running = 1,
    Stopping = 2,
    Exited = 3,
    Quarantined = 4,
}

/// 状态原子单元(锁-free;Clone 共享同一原子底座)。
#[derive(Clone)]
pub(crate) struct PluginStateCell(Arc<AtomicU8>);

impl PluginStateCell {
    pub fn new(s: PluginStateCode) -> Self {
        Self(Arc::new(AtomicU8::new(s as u8)))
    }
    pub fn get(&self) -> PluginState {
        PluginState::from_code(self.0.load(Ordering::Acquire))
    }
    pub(crate) fn cas(&self, from: PluginStateCode, to: PluginStateCode) -> bool {
        self.0
            .compare_exchange(from as u8, to as u8, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
    }
    /// worker 自然结束:Running/Stopping → Exited。
    pub(crate) fn finish(&self) -> bool {
        self.cas(PluginStateCode::Running, PluginStateCode::Exited)
            || self.cas(PluginStateCode::Stopping, PluginStateCode::Exited)
    }
}

/// 内部注册表集中区。
pub(crate) struct RegistryInner {
    pub entries: HashMap<String, Arc<PluginEntry>>,
    /// 注册顺序(确定性、拓扑并列时的排序依据)。
    pub order: Vec<String>,
}

pub(crate) struct Registry {
    pub state_of: RwLock<RegistryInner>,
}

impl Registry {
    pub fn new() -> Self {
        Self { state_of: RwLock::new(RegistryInner { entries: HashMap::new(), order: Vec::new() }) }
    }

    pub fn get(&self, name: &str) -> Option<Arc<PluginEntry>> {
        self.state_of.read().unwrap().entries.get(name).cloned()
    }

    pub fn remove(&self, name: &str) -> Option<Arc<PluginEntry>> {
        let mut w = self.state_of.write().unwrap();
        w.entries.remove(name).inspect(|_| {
            if let Some(i) = w.order.iter().position(|n| n == name) {
                w.order.remove(i);
            }
        })
    }

    pub fn names(&self) -> Vec<String> {
        self.state_of.read().unwrap().order.clone()
    }

    pub fn any_depends_on(&self, target: &str) -> Vec<String> {
        let r = self.state_of.read().unwrap();
        r.order
            .iter()
            .filter_map(|n| r.entries.get(n))
            .filter(|e| e.deps.iter().any(|d| d == target))
            .map(|e| e.name.clone())
            .collect()
    }

    pub fn clear(&self) {
        let mut w = self.state_of.write().unwrap();
        w.entries.clear();
        w.order.clear();
    }

    /// start() 的依赖拓扑序(Kahn;并列按注册序;环 → Err)。
    pub fn topo_order(&self) -> Result<Vec<Arc<PluginEntry>>, PluginError> {
        let r = self.state_of.read().unwrap();
        let mut indeg: HashMap<String, usize> = HashMap::new();
        let mut dependents: HashMap<String, Vec<String>> = HashMap::new();
        for name in &r.order {
            indeg.entry(name.clone()).or_insert(0);
        }
        for name in &r.order {
            let e = &r.entries[name];
            for d in &e.deps {
                // add 期已校验存在;start 前可能被 remove → 悬空依赖按缺失报错
                if !r.entries.contains_key(d) {
                    return Err(PluginError::UnknownDep(d.clone()));
                }
                *indeg.entry(name.clone()).or_insert(0) += 1;
                dependents.entry(d.clone()).or_default().push(name.clone());
            }
        }
        let mut queue: VecDeque<String> = r
            .order
            .iter()
            .filter(|n| indeg[*n] == 0)
            .cloned()
            .collect();
        let mut out = Vec::with_capacity(r.order.len());
        while let Some(n) = queue.pop_front() {
            let e = Arc::clone(&r.entries[&n]);
            out.push(e);
            if let Some(deps_list) = dependents.get(&n) {
                for dep_name in deps_list {
                    let d = indeg.get_mut(dep_name).unwrap();
                    *d -= 1;
                    if *d == 0 {
                        queue.push_back(dep_name.clone());
                    }
                }
            }
        }
        if out.len() < r.order.len() {
            let cycle: Vec<String> = r.order.iter().filter(|n| indeg[*n] > 0).cloned().collect();
            return Err(PluginError::DepCycle(cycle));
        }
        Ok(out)
    }
}