ek-api 0.1.1

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! 参数解析(手写,零依赖;与设计文档 §2 参数表一一对应)。

use std::path::PathBuf;

/// 日志级别。
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    Error,
    Warn,
    Info,
    Debug,
}

impl Level {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "error" => Some(Self::Error),
            "warn" => Some(Self::Warn),
            "info" => Some(Self::Info),
            "debug" => Some(Self::Debug),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warn => "warn",
            Self::Info => "info",
            Self::Debug => "debug",
        }
    }
}

/// 启动参数。
#[derive(Debug, Clone)]
pub struct Args {
    pub port: u16,
    /// 显式 `--bind` 地址(缺省 `127.0.0.1`;`--lan` 时强制 `0.0.0.0`)。
    pub bind: String,
    /// 局域网模式:绑 `0.0.0.0`。
    pub lan: bool,
    pub profile: String,
    /// 只装内核三件(cfg/svctl/api),忽略 profile 清单。
    pub minimal: bool,
    /// 恢复旧的演示缺省(cfg+dm),忽略 profile 清单。
    pub demo: bool,
    pub token_file: PathBuf,
    pub lock_file: PathBuf,
    pub ready_file: Option<PathBuf>,
    pub log_level: Level,
    /// 不起健康检查线程(测试用)。
    pub no_probe: bool,
}

impl Default for Args {
    fn default() -> Self {
        Self {
            port: 8737,
            bind: "127.0.0.1".to_string(),
            lan: false,
            profile: "default".to_string(),
            minimal: false,
            demo: false,
            token_file: default_token_file(),
            lock_file: default_lock_file(),
            ready_file: None,
            log_level: Level::Info,
            no_probe: false,
        }
    }
}

/// `%APPDATA%\ek\api\token`(无 APPDATA 时回落当前目录)。
pub fn default_token_file() -> PathBuf {
    data_dir().join("api").join("token")
}

/// `%APPDATA%\ek\api\server.lock`。
pub fn default_lock_file() -> PathBuf {
    data_dir().join("api").join("server.lock")
}

/// `%APPDATA%\ek`(日志/配置根)。
pub fn data_dir() -> PathBuf {
    match std::env::var("APPDATA") {
        Ok(v) if !v.is_empty() => PathBuf::from(v).join("ek"),
        _ => PathBuf::from(".").join("ek"),
    }
}

/// 解析命令行(不含程序名)。`--help`/`--version` 由调用方先处理。
pub fn parse(argv: &[String]) -> Result<Args, String> {
    let mut a = Args::default();
    let mut i = 0usize;
    while i < argv.len() {
        let arg = argv[i].as_str();
        match arg {
            "--port" => {
                let v = take(argv, &mut i, "--port")?;
                a.port = v
                    .parse()
                    .map_err(|_| format!("--port 需要 0..=65535 的整数,收到「{v}」"))?;
            }
            "--bind" => a.bind = take(argv, &mut i, "--bind")?,
            "--lan" => a.lan = true,
            "--profile" => a.profile = take(argv, &mut i, "--profile")?,
            "--minimal" => a.minimal = true,
            "--demo" => a.demo = true,
            "--token-file" => a.token_file = PathBuf::from(take(argv, &mut i, "--token-file")?),
            "--lock-file" => a.lock_file = PathBuf::from(take(argv, &mut i, "--lock-file")?),
            "--ready-file" => {
                a.ready_file = Some(PathBuf::from(take(argv, &mut i, "--ready-file")?));
            }
            "--log-level" => {
                let v = take(argv, &mut i, "--log-level")?;
                a.log_level = Level::parse(&v)
                    .ok_or_else(|| format!("--log-level 只收 error/warn/info/debug,收到「{v}」"))?;
            }
            "--no-probe" => a.no_probe = true,
            other => return Err(format!("未知参数「{other}」(--help 看用法)")),
        }
        i += 1;
    }
    if a.minimal && a.demo {
        return Err("--minimal 与 --demo 不能同时使用".to_string());
    }
    Ok(a)
}

/// 取下一个参数值并推进游标。
fn take(argv: &[String], i: &mut usize, name: &str) -> Result<String, String> {
    *i += 1;
    if *i >= argv.len() {
        return Err(format!("{name} 缺少取值"));
    }
    Ok(argv[*i].clone())
}

/// 帮助文本。
#[must_use]
pub fn help_text() -> String {
    let mut s = String::new();
    s.push_str("ek-server —— ek 生态无界面 API 服务\n\n");
    s.push_str("用法: ek-server [选项]\n\n");
    s.push_str("选项:\n");
    s.push_str("  --port <n>           监听端口(默认 8737;0 = 随机)\n");
    s.push_str("  --bind <addr>        绑定地址(默认 127.0.0.1)\n");
    s.push_str("  --lan                局域网模式:绑 0.0.0.0(仅内网,不做 TLS)\n");
    s.push_str("  --profile <name>     启动清单名(默认 default)\n");
    s.push_str("  --minimal            只装内核三件(cfg/svctl/api),忽略清单\n");
    s.push_str("  --demo               旧演示缺省(cfg+dm),忽略清单\n");
    s.push_str("  --token-file <path>  token 文件(默认 %APPDATA%\\ek\\api\\token)\n");
    s.push_str("  --lock-file <path>   单宿主锁(默认 %APPDATA%\\ek\\api\\server.lock)\n");
    s.push_str("  --ready-file <path>  监听成功后写就绪标记\n");
    s.push_str("  --log-level <lvl>    error/warn/info/debug(默认 info)\n");
    s.push_str("  --no-probe           不起健康检查线程(测试用)\n");
    s.push_str("  --help / --version   本帮助 / 版本\n");
    s
}

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

    fn v(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn defaults_match_design() {
        let a = parse(&[]).expect("empty args ok");
        assert_eq!(a.port, 8737);
        assert_eq!(a.bind, "127.0.0.1");
        assert_eq!(a.profile, "default");
        assert_eq!(a.log_level, Level::Info);
        assert!(!a.lan);
        assert!(!a.minimal);
        assert!(!a.demo);
        assert_eq!(a.token_file.file_name().and_then(|n| n.to_str()), Some("token"));
        assert_eq!(
            a.token_file.parent().and_then(|p| p.file_name()).and_then(|n| n.to_str()),
            Some("api")
        );
    }

    #[test]
    fn parses_all_options() {
        let a = parse(&v(&[
            "--port",
            "9000",
            "--bind",
            "10.0.0.2",
            "--lan",
            "--profile",
            "sim",
            "--token-file",
            "C:\\t\\tok",
            "--lock-file",
            "C:\\t\\lock",
            "--ready-file",
            "C:\\t\\ready",
            "--log-level",
            "debug",
            "--no-probe",
        ]))
        .expect("all options ok");
        assert_eq!(a.port, 9000);
        assert_eq!(a.bind, "10.0.0.2");
        assert!(a.lan);
        assert_eq!(a.profile, "sim");
        assert_eq!(a.ready_file.as_deref(), Some(std::path::Path::new("C:\\t\\ready")));
        assert_eq!(a.log_level, Level::Debug);
        assert!(a.no_probe);
    }

    #[test]
    fn parses_minimal_and_demo() {
        assert!(parse(&v(&["--minimal"])).unwrap().minimal);
        assert!(parse(&v(&["--demo"])).unwrap().demo);
        assert!(parse(&v(&["--minimal", "--demo"])).is_err());
    }

    #[test]
    fn rejects_bad_values() {
        assert!(parse(&v(&["--port", "70000"])).is_err());
        assert!(parse(&v(&["--port"])).is_err());
        assert!(parse(&v(&["--log-level", "trace"])).is_err());
        assert!(parse(&v(&["--nope"])).is_err());
    }

    #[test]
    fn help_lists_every_flag() {
        let h = help_text();
        for f in [
            "--port",
            "--bind",
            "--lan",
            "--profile",
            "--token-file",
            "--lock-file",
            "--ready-file",
            "--log-level",
            "--no-probe",
            "--minimal",
            "--demo",
        ] {
            assert!(h.contains(f), "help missing {f}");
        }
    }
}