ek-core 0.4.3

Business-agnostic plugin host and actor-over-bus runtime on top of ek-event: capability index with runtime service discovery, per-plugin actor workers, dynamic add/remove with lifecycle broadcasts, one-shot ask/ask_service with contract gates, panic quarantine, five-step close.
Documentation
//! 通用插件自检闸(结构自检 + 装配自检;零业务;GUIDE §16 双跑纪律)。
//!
//! 用法(两层闸,任何插件通用):
//! 1. **骨架期(业务零)先跑一次**:结构自检 + 装配自检全绿 = 框架件达标;
//! 2. **业务加入后再跑一次**:同样两绿 = 结构未被业务破坏。
//!
//! 本模块**只读**,不触碰业务状态;判据与 GUIDE 纪律一一对应(锚点见各条注释)。

use crate::envelope::{Envelope, ReplyErr, e_req_type};
use crate::main_engine::MainEngine;
use crate::plugin::Plugin;
use crate::section::valid_config_ns;
use ek_event::{Event, EventEngine};
use std::any::Any;
use std::sync::Arc;
use std::time::Duration;

/// 判定等级(只报 Fail;Warn 预留)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Severity {
    /// 不合格。
    Fail,
}

/// 单条判定(id 稳定,可对账;文本点名原因)。
#[derive(Debug, Clone)]
pub struct Finding {
    /// 稳定 id(如 `Q1`);跨版本只增不减。
    pub id: &'static str,
    /// 等级。
    pub severity: Severity,
    /// 判定说明。
    pub text: String,
}

/// 自检报告(`is_ok` = 全绿)。
#[derive(Debug, Default)]
pub struct ShapeReport {
    /// 全部判定(空 = 无发现)。
    pub findings: Vec<Finding>,
}

impl ShapeReport {
    fn fail(&mut self, id: &'static str, text: impl Into<String>) {
        self.findings.push(Finding {
            id,
            severity: Severity::Fail,
            text: text.into(),
        });
    }

    /// 全绿判定。
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.findings.is_empty()
    }
}

/// 结构自检(不装配、不起宿主;对插件契约逐项判定;§5 F4/§7)。
///
/// `expected_version` = 调用方(插件 crate)显式传 `env!("CARGO_PKG_VERSION")` ——
/// **Q1 不能在 audit 内自取 env!**:audit 的宏展开是 ek-core 自己的版本,
/// 而未覆写 version() 的插件缺省值恰好也是 ek-core 版本,会把假匹配放行。
///
/// 判定面:Q1 version 显式覆写;Q2 routes 非空/去重(**服务面件**才必含请求线);
/// Q3 services 目录唯一且全名合法;Q4 目录面有描述;Q5 配置面 namespace 合法。
///
/// **服务面形态挂钩**(0.4.3):`services()` 非空 = 面向服务的个体 → routes 必须
/// 自报 `eReq.<名>`(否则服务请求永远进不来);`services()` 为空 = **纯订阅观察件**
/// (ui 一类)→ 请求线自报与活体探针全部豁免(Q2/D4;写上只是死线)。
///
/// **配置面是可选件**(§9.1):`as_configurable()` 返回 None = 「无配置面」,
/// 这是合法形态 —— Q5 仅在有面时生效,无面插件整类跳过,不产生任何 finding。
/// 同理 §14.2 的配置面测试组也是**有面才要求**,无面插件整体豁免。
#[must_use]
pub fn shape_audit(plugin: &dyn Plugin, expected_version: &str) -> ShapeReport {
    let mut rep = ShapeReport::default();
    let name = plugin.name().to_string();

    // Q1 version 覆写:七律 6(缺省实现会错填 ek-core 版本)。
    if plugin.version().as_ref() != expected_version {
        rep.fail(
            "Q1",
            format!(
                "version() 必须显式覆写为本 crate 版本(七律 6);期望 {expected_version},实得 {}",
                plugin.version()
            ),
        );
    }

    // Q2 routes:非空/去重;**服务面件**必含 eReq.<name>。
    //
    // 0.4.3(语义修正):`services()` 为空的**纯订阅观察件**(ui 一类,零服务面,
    // 无人能 ask)合法跳过请求线自报 —— 写上是一条永远空驶的死线。判定挂钩:
    // **有服务面才要求自报请求线**;零服务面 = 纯监听件,Q2 只判非空/去重。
    let svcs = plugin.services();
    let routes: Vec<String> = plugin.routes().iter().map(|c| c.to_string()).collect();
    if routes.is_empty() {
        rep.fail("Q2", "routes() 为空 = 无订阅面(至少自报请求线)");
    } else {
        let mut seen = std::collections::BTreeSet::new();
        for r in &routes {
            if !seen.insert(r.clone()) {
                rep.fail("Q2", format!("routes() 重复订阅 {r}"));
            }
        }
        if !svcs.is_empty() {
            let req_line = e_req_type(&name);
            if !routes.iter().any(|r| r == &req_line) {
                rep.fail(
                    "Q2",
                    format!("routes() 必须自报请求线 {req_line};漏报 = 服务请求永远进不来"),
                );
            }
        }
    }

    // Q3 services:目录唯一 + 全名 = `<实例名>.<后缀>`(§3 命名纪律)。
    let mut ids = std::collections::BTreeSet::new();
    for s in &svcs {
        let id: &String = &s.id;
        if !ids.insert(id.clone()) {
            rep.fail("Q3", format!("服务目录重复 {id}"));
        }
        let expected = format!("{name}.");
        if !id.starts_with(&expected) {
            rep.fail("Q3", format!("服务全名未挂实例名前缀: {id}"));
        }
    }

    // Q4 描述非空(消费方目录可读性)。
    for s in &svcs {
        if s.doc.trim().is_empty() {
            rep.fail("Q4", format!("服务 {} 描述为空", s.id));
        }
    }

    // Q5 配置面 namespace 合法(§9.2)。**None = 无配置面 = 合法(可选件),不判。**
    if let Some(cfg) = plugin.as_configurable() {
        if !valid_config_ns(cfg.config_ns()) {
            rep.fail("Q5", format!("config_ns 非法: {}", cfg.config_ns()));
        }
    }

    rep
}

/// 装配自检探针载荷(故意未注册类型;预期全体 miss → InvalidPayload)。
struct AuditProbeReq;

/// 装配自检报告(装配期逐项;列同 ShapeReport 的 findings)。
#[derive(Debug, Default)]
pub struct DeployReport {
    /// 全部判定。
    pub findings: Vec<Finding>,
}

impl DeployReport {
    fn fail(&mut self, id: &'static str, text: impl Into<String>) {
        self.findings.push(Finding {
            id,
            severity: Severity::Fail,
            text: text.into(),
        });
    }

    /// 全绿判定。
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.findings.is_empty()
    }
}

/// 装配自检:最小宿主真实装配 → 起停 → 服务目录可见 → 请求线活体探测。
///
/// 探测语义:向 `eReq.<名>` 投一个**故意未注册**的载荷,插件方 arm 全 miss
/// 必回 `Err(ReplyErr::InvalidPayload)`(契约错型显形,`ENV` 侧语义对齐 §7)。
/// 返回 [`DeployReport`];探针超时即判坏(请求线未自报/未装配/宿主路由断)。
///
/// 0.4.3(语义修正,与 shape Q2 挂钩):`services()` 为空的纯订阅观察件
/// **免探针**(无服务面 = 无可被 ask 的口,探针超时对它不是缺陷)——只判
/// D1 装配 / D2 起动 / D3 在册。
pub fn deploy_audit<T: Plugin + 'static>(plugin: Arc<T>) -> DeployReport {
    let mut rep = DeployReport::default();
    let name = plugin.name().to_string();
    let has_service_face = !plugin.services().is_empty();
    let ev = Arc::new(EventEngine::new());
    let host = MainEngine::new(Some(ev.clone()));
    if let Err(e) = host.add_plugin(plugin) {
        rep.fail("D1", format!("add_plugin 失败: {e}"));
        return rep;
    }
    if let Err(e) = host.start() {
        rep.fail("D2", format!("host.start 失败: {e}"));
        return rep;
    }

    // D3 实例在册(装配期登记簿点名; PluginInfo 无目录字段,目录可见性走 D4)。
    if host.get_state(&name).is_none() {
        rep.fail("D3", "实例未在册(装配失败)");
    }

    // D4 请求线活体探测(**仅有服务面时**)。
    if has_service_face {
        let (env, rx) = Envelope::new(Arc::new(AuditProbeReq) as Arc<dyn Any + Send + Sync>);
        let put = ev.put(Event::with_data(e_req_type(&name), Arc::new(env)));
        if let Err(e) = put {
            rep.fail("D4", format!("总线投递失败: {e:?}"));
        } else {
            match rx.recv_timeout(Duration::from_secs(10)) {
                Ok(boxed) => {
                    let typed = boxed.downcast::<Result<(), ReplyErr>>();
                    match typed {
                        Ok(inner) => {
                            if matches!(*inner, Err(ReplyErr::InvalidPayload)) {
                                // 期望形态:InvalidPayload = arm 全 miss 显形 = 请求线活。
                            } else {
                                rep.fail(
                                    "D4",
                                    "探针未注册载荷竟然回了非 InvalidPayload 形态(契约应答面失真)",
                                );
                            }
                        }
                        Err(_) => {
                            // 剥包错型=同样 InvalidPayload 语义(允许实现走 Box 擦除路径)。
                        }
                    }
                }
                Err(_) => rep.fail("D4", "请求探针超时:请求线未自报(routes 漏报)或分派断"),
            }
        }
        // has_service_face 收口(零服务面纯订阅件:D1-D3 即封顶)
    }
    // 收尾:静默撤下(五步;不判成败,只保证不悬挂)。
    host.close(Duration::from_secs(2));
    rep
}