ek-api 0.1.1

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! NDJSON 帧 + JSON-RPC 2.0 子集(M1:认证与心跳)。

use std::io::{BufRead, Write};

use serde_json::{Map, Value};

/// 单帧上限(4 MiB;超长 → 错误码 + 断开)。
pub const MAX_FRAME: usize = 4 * 1024 * 1024;

/// JSON-RPC 错误码(设计 §3.3)。
pub const PARSE_ERROR: i64 = -32700;
pub const INVALID_REQUEST: i64 = -32600;
pub const METHOD_NOT_FOUND: i64 = -32601;
pub const INVALID_PARAMS: i64 = -32602;
pub const INTERNAL_ERROR: i64 = -32603;
pub const TIMEOUT: i64 = -32001;
pub const TARGET_GONE: i64 = -32002;
pub const BUS_STOPPED: i64 = -32003;
pub const UNAUTHENTICATED: i64 = -32004;
pub const FORBIDDEN: i64 = -32005;
pub const RATE_LIMITED: i64 = -32006;
pub const CONFIRM_REQUIRED: i64 = -32007;
pub const BUSY: i64 = -32008;
pub const CONFIG_REJECTED: i64 = -32009;

/// 解析后的请求。
#[derive(Debug, Clone)]
pub struct Request {
    pub id: Value,
    pub method: String,
    pub params: Value,
}

/// RPC 错误。
#[derive(Debug, Clone)]
pub struct RpcError {
    pub code: i64,
    pub message: String,
    pub data: Option<Value>,
}

impl RpcError {
    pub fn new(code: i64, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }

    pub fn with_data(mut self, data: Value) -> Self {
        self.data = Some(data);
        self
    }

    pub fn parse(msg: impl Into<String>) -> Self {
        Self::new(PARSE_ERROR, msg)
    }

    pub fn invalid(msg: impl Into<String>) -> Self {
        Self::new(INVALID_REQUEST, msg)
    }

    pub fn invalid_params(msg: impl Into<String>) -> Self {
        Self::new(INVALID_PARAMS, msg)
    }

    pub fn not_found(method: &str) -> Self {
        Self::new(METHOD_NOT_FOUND, format!("方法不存在: {method}"))
    }

    pub fn unauthenticated() -> Self {
        Self::new(UNAUTHENTICATED, "未认证:先 auth.login")
    }

    pub fn rate_limited() -> Self {
        Self::new(RATE_LIMITED, "请求过快").with_data(serde_json::json!({"retry_after_ms": 1000}))
    }

    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("code".into(), Value::from(self.code));
        m.insert("message".into(), Value::from(self.message.clone()));
        if let Some(d) = &self.data {
            m.insert("data".into(), d.clone());
        }
        Value::Object(m)
    }
}

impl std::fmt::Display for RpcError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.code, self.message)
    }
}

/// 解析一行请求。通知(无 id)在 M1 暂不支持,按 invalid request 处理。
pub fn parse_request(line: &str) -> Result<Request, RpcError> {
    let v: Value = serde_json::from_str(line).map_err(|e| RpcError::parse(format!("JSON 解析失败: {e}")))?;
    let obj = v
        .as_object()
        .ok_or_else(|| RpcError::invalid("请求必须是 JSON 对象"))?;
    match obj.get("jsonrpc").and_then(|v| v.as_str()) {
        Some("2.0") => {}
        _ => return Err(RpcError::invalid("jsonrpc 必须是 \"2.0\"")),
    }
    let id = obj
        .get("id")
        .cloned()
        .ok_or_else(|| RpcError::invalid("缺少 id(通知暂不支持)"))?;
    if !(id.is_number() || id.is_string()) {
        return Err(RpcError::invalid("id 必须是数字或字符串"));
    }
    let method = obj
        .get("method")
        .and_then(|v| v.as_str())
        .ok_or_else(|| RpcError::invalid("缺少 method"))?
        .to_string();
    let params = obj.get("params").cloned().unwrap_or(Value::Object(Map::new()));
    if !params.is_object() {
        return Err(RpcError::invalid_params("params 必须是对象"));
    }
    Ok(Request { id, method, params })
}

/// 成功响应行。
pub fn ok_response(id: &Value, result: Value) -> String {
    let mut m = Map::new();
    m.insert("jsonrpc".into(), Value::from("2.0"));
    m.insert("id".into(), id.clone());
    m.insert("result".into(), result);
    serde_json::to_string(&Value::Object(m)).unwrap_or_else(|_| "{}".to_string())
}

/// 错误响应行。
pub fn err_response(id: Option<&Value>, err: &RpcError) -> String {
    let mut m = Map::new();
    m.insert("jsonrpc".into(), Value::from("2.0"));
    m.insert("id".into(), id.cloned().unwrap_or(Value::Null));
    m.insert("error".into(), err.to_json());
    serde_json::to_string(&Value::Object(m)).unwrap_or_else(|_| "{}".to_string())
}

/// 推送帧(无 id 的 notification)。
pub fn event_frame(method: &str, params: Value) -> String {
    let mut m = Map::new();
    m.insert("jsonrpc".into(), Value::from("2.0"));
    m.insert("method".into(), Value::from(method));
    m.insert("params".into(), params);
    serde_json::to_string(&Value::Object(m)).unwrap_or_else(|_| "{}".to_string())
}

/// 读一行(限长;超长返回错误,调用方断开连接)。
///
/// 返回 `Ok(None)` = EOF。
pub fn read_line_limited<R: BufRead>(reader: &mut R, limit: usize) -> Result<Option<String>, String> {
    let mut buf: Vec<u8> = Vec::new();
    loop {
        let mut byte = [0u8; 1];
        match reader.read(&mut byte) {
            Ok(0) => {
                if buf.is_empty() {
                    return Ok(None);
                }
                break;
            }
            Ok(_) => {
                if byte[0] == b'\n' {
                    break;
                }
                if buf.len() >= limit {
                    return Err(format!("帧超过 {limit} 字节上限"));
                }
                buf.push(byte[0]);
            }
            Err(e) => return Err(format!("读失败: {e}")),
        }
    }
    while buf.last() == Some(&b'\r') {
        buf.pop();
    }
    String::from_utf8(buf)
        .map(Some)
        .map_err(|e| format!("帧不是合法 UTF-8: {e}"))
}

/// 写一行。
pub fn write_frame<W: Write>(writer: &mut W, line: &str) -> std::io::Result<()> {
    writer.write_all(line.as_bytes())?;
    writer.write_all(b"\n")?;
    writer.flush()
}

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

    #[test]
    fn parses_valid_request() {
        let r = parse_request(r#"{"jsonrpc":"2.0","id":7,"method":"sys.ping","params":{"x":1}}"#).unwrap();
        assert_eq!(r.method, "sys.ping");
        assert_eq!(r.id, Value::from(7));
        assert_eq!(r.params["x"], Value::from(1));
    }

    #[test]
    fn params_defaults_to_empty_object() {
        let r = parse_request(r#"{"jsonrpc":"2.0","id":1,"method":"sys.ping"}"#).unwrap();
        assert!(r.params.is_object() && r.params.as_object().unwrap().is_empty());
    }

    #[test]
    fn rejects_bad_shapes() {
        assert_eq!(parse_request("not json").unwrap_err().code, PARSE_ERROR);
        assert_eq!(parse_request("[]").unwrap_err().code, INVALID_REQUEST);
        assert_eq!(
            parse_request(r#"{"id":1,"method":"x"}"#).unwrap_err().code,
            INVALID_REQUEST
        );
        assert_eq!(
            parse_request(r#"{"jsonrpc":"2.0","id":[1],"method":"x"}"#)
                .unwrap_err()
                .code,
            INVALID_REQUEST
        );
        assert_eq!(
            parse_request(r#"{"jsonrpc":"2.0","id":1,"method":"x","params":[]}"#)
                .unwrap_err()
                .code,
            INVALID_PARAMS
        );
    }

    #[test]
    fn response_shapes() {
        let ok = ok_response(&Value::from(1), serde_json::json!({"ok":true}));
        let v: Value = serde_json::from_str(&ok).unwrap();
        assert_eq!(v["jsonrpc"], "2.0");
        assert_eq!(v["id"], 1);
        assert_eq!(v["result"]["ok"], true);

        let err = err_response(Some(&Value::from(2)), &RpcError::new(UNAUTHENTICATED, "no"));
        let v: Value = serde_json::from_str(&err).unwrap();
        assert_eq!(v["error"]["code"], UNAUTHENTICATED);
    }

    #[test]
    fn read_line_limited_handles_crlf_eof_and_overflow() {
        let mut c = Cursor::new(b"a\r\nb\n".to_vec());
        assert_eq!(read_line_limited(&mut c, 8).unwrap().as_deref(), Some("a"));
        assert_eq!(read_line_limited(&mut c, 8).unwrap().as_deref(), Some("b"));
        assert_eq!(read_line_limited(&mut c, 8).unwrap(), None);

        let mut c = Cursor::new(b"123456789\n".to_vec());
        let e = read_line_limited(&mut c, 4).unwrap_err();
        assert!(e.contains("上限"), "{e}");
    }
}