ek-api 0.1.2

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! profile —— "下次启动清单"(落 `api` 段:`kind.<工厂名>=on/off` + `autostart`)。
//!
//! 读取在 bin(装配方直读 Store,合法);写入由 API 插件 ask `cfg.save`
//! (配置写面唯一在 cfg 收件壳)。profile 逻辑由 bin 与 API 共用本模块。

use ek_cfg::Store;
use ek_cfg::store::LoadOutcome;
use ek_core::section::{Field, SectionMap};
use serde_json::{json, Map, Value};

/// profile 所在配置段。
pub const API_NS: &str = "api";

/// 解析后的清单。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Profile {
    /// `(工厂名, 是否启用)`,保持段内键序。
    pub plugins: Vec<(String, bool)>,
    /// 守护自动连接开关(`autostart=1`)。
    pub autostart: bool,
}

impl Profile {
    /// 启用的工厂名(装配清单)。
    #[must_use]
    pub fn enabled(&self) -> Vec<String> {
        self.plugins
            .iter()
            .filter(|(_, on)| *on)
            .map(|(n, _)| n.clone())
            .collect()
    }

    /// 该工厂是否显式登记为 off(用于"停用"判定)。
    #[must_use]
    pub fn is_off(&self, factory: &str) -> bool {
        self.plugins
            .iter()
            .any(|(n, on)| n == factory && !*on)
    }

    /// 该工厂是否显式登记(on 或 off)。
    #[must_use]
    pub fn contains(&self, factory: &str) -> bool {
        self.plugins.iter().any(|(n, _)| n == factory)
    }
}

/// 从 Store 读 profile(无段 = 空清单)。
#[must_use]
pub fn read(store: &Store) -> Profile {
    let mut p = Profile::default();
    let Ok(LoadOutcome::Loaded { map, .. }) = store.load(API_NS) else {
        return p;
    };
    for (k, f) in map.iter() {
        let Some(v) = f.plain_value() else { continue };
        let v = v.trim();
        if let Some(factory) = k.strip_prefix("kind.") {
            p.plugins
                .push((factory.to_string(), matches!(v, "on" | "1" | "true")));
        } else if k == "autostart" {
            p.autostart = matches!(v, "1" | "on" | "true");
        }
    }
    p
}

/// 转为对外 JSON。
#[must_use]
pub fn to_json(p: &Profile) -> Value {
    let mut plugins = Map::new();
    for (factory, on) in &p.plugins {
        plugins.insert(
            format!("kind.{factory}"),
            Value::from(if *on { "on" } else { "off" }),
        );
    }
    json!({
        "plugins": plugins,
        "autostart": if p.autostart { "on" } else { "off" },
    })
}

/// 转为可落盘的段。
#[must_use]
pub fn to_map(p: &Profile) -> SectionMap {
    let mut m = SectionMap::new(0);
    for (factory, on) in &p.plugins {
        m = m.set(
            format!("kind.{factory}"),
            Field::plain(if *on { "on" } else { "off" }),
        );
    }
    m = m.set("autostart", Field::plain(if p.autostart { "1" } else { "0" }));
    m
}

/// 从请求 params 解析(`plugins` 为对象:`kind.<名>` 或裸名 → on/off/1/0/true/false)。
pub fn from_params(v: &Value) -> Result<Profile, String> {
    let obj = v.as_object().ok_or("profile 参数必须是对象")?;
    let mut p = Profile::default();
    if let Some(plugins) = obj.get("plugins") {
        let m = plugins
            .as_object()
            .ok_or("plugins 必须是对象(kind.<工厂名> → on/off)")?;
        for (k, v) in m {
            let Some(s) = v.as_str() else {
                return Err(format!("plugins.{k} 必须是字符串"));
            };
            let on = matches!(s.trim(), "on" | "1" | "true");
            p.plugins
                .push((k.strip_prefix("kind.").unwrap_or(k).to_string(), on));
        }
    }
    if let Some(a) = obj.get("autostart") {
        p.autostart = match a {
            Value::Bool(b) => *b,
            Value::String(s) => matches!(s.trim(), "on" | "1" | "true"),
            _ => false,
        };
    }
    Ok(p)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn params_roundtrip_via_map() {
        let p = from_params(&json!({
            "plugins": {"kind.cfg": "on", "kind.dm": "on", "kind.ctp": "off"},
            "autostart": "1"
        }))
        .unwrap();
        assert_eq!(p.enabled(), vec!["cfg", "dm"]);
        assert!(p.is_off("ctp"));
        assert!(p.autostart);

        let map = to_map(&p);
        assert_eq!(map.get_plain("kind.cfg"), Some("on"));
        assert_eq!(map.get_plain("kind.ctp"), Some("off"));
        assert_eq!(map.get_plain("autostart"), Some("1"));

        let back = to_json(&p);
        assert_eq!(back["plugins"]["kind.dm"], "on");
    }

    #[test]
    fn rejects_non_object_plugins() {
        assert!(from_params(&json!({"plugins": []})).is_err());
        assert!(from_params(&json!({"plugins": {"kind.cfg": 1}})).is_err());
    }
}