Skip to content

Commit

Permalink
minirpc
Browse files Browse the repository at this point in the history
  • Loading branch information
broucz committed Jun 16, 2019
0 parents commit 8ac1bd6
Show file tree
Hide file tree
Showing 16 changed files with 778 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
**/*.rs.bk
Cargo.lock
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[workspace]
members = [
"minirpc"
]
21 changes: 21 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Pierre Brouca

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# minirpc
17 changes: 17 additions & 0 deletions minirpc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "minirpc"
version = "0.1.0"
authors = ["broucz <[email protected]>"]
edition = "2018"
description = "A minimalist RPC framework."
documentation = "https://docs.rs/minirpc/"
homepage = "https://github.com/broucz/minirpc"
repository = "https://github.com/broucz/minirpc"
keywords = ["rpc"]
readme = "README.md"
license = "MIT"

[dependencies]
serde = "1.0.92"
serde_derive = "1.0.92"
serde_json = "1.0.39"
41 changes: 41 additions & 0 deletions minirpc/src/call.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use crate::{Id, Method, Params};

#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Call {
pub id: Id,
pub method: Method,
pub params: Params,
}

#[cfg(test)]
mod tests {
use super::*;
use serde_json::{self, Value};

#[test]
fn call_deserialization() {
let input = r#"{"id":1,"method":"test_method","params":[1,2,3]}"#;
let expected = Call {
id: Id::Number(1),
method: Method::String("test_method".to_owned()),
params: Params::Array(vec![Value::from(1), Value::from(2), Value::from(3)]),
};

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

#[test]
fn call_serialization() {
let input = Call {
id: Id::Number(1),
method: Method::String("test_method".to_owned()),
params: Params::Array(vec![Value::from(1), Value::from(2), Value::from(3)]),
};
let expected = r#"{"id":1,"method":"test_method","params":[1,2,3]}"#;

let result = serde_json::to_string(&input).unwrap();
assert_eq!(result, expected);
}
}
223 changes: 223 additions & 0 deletions minirpc/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use std::fmt;

#[derive(Debug, PartialEq)]
pub enum Code {
ParseError,
InvalidRequest,
MethodNotFound,
InvalidParams,
InternalError,
ServerError(i64),
}

impl Code {
pub fn message(&self) -> &str {
match *self {
Code::ParseError => "Parse error",
Code::InvalidRequest => "Invalid request",
Code::MethodNotFound => "Method not found",
Code::InvalidParams => "Invalid params",
Code::InternalError => "Internal error",
Code::ServerError(_) => "Server error",
}
}
}

impl<'a> Deserialize<'a> for Code {
fn deserialize<D>(deserializer: D) -> Result<Code, D::Error>
where
D: Deserializer<'a>,
{
Ok(match i64::deserialize(deserializer)? {
-32700 => Code::ParseError,
-32600 => Code::InvalidRequest,
-32601 => Code::MethodNotFound,
-32602 => Code::InvalidParams,
-32603 => Code::InternalError,
code => Code::ServerError(code),
})
}
}

impl Serialize for Code {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i64(match *self {
Code::ParseError => -32700,
Code::InvalidRequest => -32600,
Code::MethodNotFound => -32601,
Code::InvalidParams => -32602,
Code::InternalError => -32603,
Code::ServerError(code) => code,
})
}
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Error {
pub code: Code,
pub message: String,
}

impl Error {
pub fn new(code: Code) -> Self {
let message = code.message().to_owned();
Self { code, message }
}

pub fn new_parse_error() -> Self {
Self::new(Code::ParseError)
}

pub fn new_invalid_request() -> Self {
Self::new(Code::InvalidRequest)
}

pub fn new_method_not_found() -> Self {
Self::new(Code::MethodNotFound)
}

pub fn new_invalid_params() -> Self {
Self::new(Code::InvalidParams)
}

pub fn new_internal_error() -> Self {
Self::new(Code::InternalError)
}

pub fn new_server_error(code: i64, message: &str) -> Self {
Self {
code: Code::ServerError(code),
message: message.to_owned()
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message)
}
}

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

#[test]
fn code_deserialization() {
let input = r#"-32700"#;
let expected = Code::ParseError;

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

#[test]
fn code_serialization() {
let input = Code::ParseError;
let expected = r#"-32700"#;

let result = serde_json::to_string(&input).unwrap();
assert_eq!(result, expected);
}

#[test]
fn error_deserialization() {
let input = r#"{"code":-32700,"message":"Parse error"}"#;
let expected = Error::new(Code::ParseError);

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

#[test]
fn error_serialization() {
let input = Error::new(Code::ParseError);
let expected = r#"{"code":-32700,"message":"Parse error"}"#;

let result = serde_json::to_string(&input).unwrap();
assert_eq!(result, expected);
}

#[test]
fn error_new() {
let result = Error::new(Code::ParseError);
let expected = Error {
code: Code::ParseError,
message: "Parse error".to_owned()
};

assert_eq!(result, expected);
}

#[test]
fn error_new_parse_error() {
let result = Error::new_parse_error();
let expected = Error {
code: Code::ParseError,
message: "Parse error".to_owned()
};

assert_eq!(result, expected);
}

#[test]
fn error_new_invalid_request() {
let result = Error::new_invalid_request();
let expected = Error {
code: Code::InvalidRequest,
message: "Invalid request".to_owned()
};

assert_eq!(result, expected);
}

#[test]
fn error_new_method_not_found() {
let result = Error::new_method_not_found();
let expected = Error {
code: Code::MethodNotFound,
message: "Method not found".to_owned()
};

assert_eq!(result, expected);
}

#[test]
fn error_new_invalid_params() {
let result = Error::new_invalid_params();
let expected = Error {
code: Code::InvalidParams,
message: "Invalid params".to_owned()
};

assert_eq!(result, expected);
}

#[test]
fn error_new_internal_error() {
let result = Error::new_internal_error();
let expected = Error {
code: Code::InternalError,
message: "Internal error".to_owned()
};

assert_eq!(result, expected);
}

#[test]
fn error_new_server_error() {
let result = Error::new_server_error(-32000, "Test error");
let expected = Error {
code: Code::ServerError(-32000),
message: "Test error".to_owned()
};

assert_eq!(result, expected);
}
}
38 changes: 38 additions & 0 deletions minirpc/src/failure.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use crate::{Error, Id};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Failure {
pub error: Error,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Id>,
}

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

#[test]
fn failure_deserialization() {
let input = r#"{"error":{"code":-32700,"message":"Parse error"},"id":1}"#;
let expected = Failure {
error: Error::new_parse_error(),
id: Some(Id::Number(1)),
};

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

#[test]
fn failure_serialization() {
let input = Failure {
error: Error::new_parse_error(),
id: Some(Id::Number(1)),
};
let expected = r#"{"error":{"code":-32700,"message":"Parse error"},"id":1}"#;

let result = serde_json::to_string(&input).unwrap();
assert_eq!(result, expected);
}
}
29 changes: 29 additions & 0 deletions minirpc/src/id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Id {
Number(u64),
}

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

#[test]
fn id_deserialization() {
let input = r#"1"#;
let expected = Id::Number(1);

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

#[test]
fn id_serialization() {
let input = Id::Number(1);
let expected = r#"1"#;

let result = serde_json::to_string(&input).unwrap();
assert_eq!(result, expected);
}
}
Loading

0 comments on commit 8ac1bd6

Please sign in to comment.