2 个版本

0.1.1 2019年7月14日
0.1.0 2019年6月22日

#19 in #stateless

MIT 许可证

27KB
602 代码行

minirpc

MINI-RPC 是一个无状态的轻量级远程过程调用 (RPC) 协议。受 JSON-RPC 2.0 规范 启发,这个用 Rust 编写的实现选择了其核心部分,以尽可能减少进程间的通信。

示例

语法

--> data sent to Server
<-- data sent to Client

基本用法

--> {"id":1,"method":"sum","params":[1,2,3]}
<-- {"id":1,"result":6}
use minirpc::*;
use serde_json::*;

// --> Request.
let input = r#"{"id":1,"method":"sum","params":[1,2,3]}"#;
let expected = Request::Single(RequestPayload::Call(Call {
    id: Id::Number(1),
    method: Method::String("sum".to_owned()),
    params: Params::Array(vec![Value::from(1), Value::from(2), Value::from(3)]),
}));

let result: Request = serde_json::from_str(input).unwrap();
assert_eq!(result, expected);

// <-- Response.
let input = r#"{"id":1,"result":6}"#;
let expected = Response::Single(ResponsePayload::Success(Success {
    id: Id::Number(1),
    result: Value::Bool(true),
}));

let result: Response = serde_json::from_str(input).unwrap();
assert_eq!(result, expected);

批量通知

--> [{"method":"log","params":{"level":"info"}},{"method":"log","params":{"level":"warn"}}]
// --> Batch Request.
let input = r#"[{"method":"log","params":{"level":"info"}},{"method":"log","params":{"level":"warn"}}]"#;

let mut params_1 = Map::new();
params_1.insert("level".to_string(), "info".into());

let mut params_2 = Map::new();
params_2.insert("level".to_string(), "warn".into());

let expected = Request::Batch(vec![
    RequestPayload::Notification(Notification {
        method: Method::String("log".to_owned()),
        params: Params::Object(params_1),
    }),
    RequestPayload::Notification(Notification {
        method: Method::String("log".to_owned()),
        params: Params::Object(params_2),
    }),
]);

let result: Request = serde_json::from_str(input).unwrap();
assert_eq!(result, expected);

依赖项

~0.6–1.4MB
~31K SLoC