Code Monkey home page Code Monkey logo

jsonrpc's Introduction

Parity JSON-RPC

NOTE: This crate is no longer actively developed; please have a look at our jsonrpsee crate if you're looking for an actively maintained JSON RPC implementation.

Rust implementation of JSON-RPC 2.0 Specification. Transport-agnostic core and transport servers for http, ipc, websockets and tcp.

New! Support for clients.

Documentation

Sub-projects

Examples

Basic Usage (with HTTP transport)

use jsonrpc_http_server::jsonrpc_core::{IoHandler, Value, Params};
use jsonrpc_http_server::ServerBuilder;

fn main() {
	let mut io = IoHandler::default();
	io.add_method("say_hello", |_params: Params| async {
		Ok(Value::String("hello".to_owned()))
	});

	let server = ServerBuilder::new(io)
		.threads(3)
		.start_http(&"127.0.0.1:3030".parse().unwrap())
		.unwrap();

	server.wait();
}

Basic usage with derive

use jsonrpc_core::Result;
use jsonrpc_derive::rpc;

#[rpc]
pub trait Rpc {
	/// Adds two numbers and returns a result
	#[rpc(name = "add")]
	fn add(&self, a: u64, b: u64) -> Result<u64>;
}

pub struct RpcImpl;
impl Rpc for RpcImpl {
	fn add(&self, a: u64, b: u64) -> Result<u64> {
		Ok(a + b)
	}
}

fn main() {
	let mut io = jsonrpc_core::IoHandler::new();
	io.extend_with(RpcImpl.to_delegate())
}

Client support

use jsonrpc_core_client::transports::local;
use jsonrpc_core::{BoxFuture, IoHandler, Result};
use jsonrpc_core::futures::{self, future, TryFutureExt};
use jsonrpc_derive::rpc;

/// Rpc trait
#[rpc]
pub trait Rpc {
	/// Returns a protocol version
	#[rpc(name = "protocolVersion")]
	fn protocol_version(&self) -> Result<String>;

	/// Adds two numbers and returns a result
	#[rpc(name = "add", alias("callAsyncMetaAlias"))]
	fn add(&self, a: u64, b: u64) -> Result<u64>;

	/// Performs asynchronous operation
	#[rpc(name = "callAsync")]
	fn call(&self, a: u64) -> BoxFuture<Result<String>>;
}

struct RpcImpl;

impl Rpc for RpcImpl {
	fn protocol_version(&self) -> Result<String> {
		Ok("version1".into())
	}

	fn add(&self, a: u64, b: u64) -> Result<u64> {
		Ok(a + b)
	}

	fn call(&self, _: u64) -> BoxFuture<Result<String>> {
		Box::pin(future::ready(Ok("OK".to_owned())))
	}
}

fn main() {
	let mut io = IoHandler::new();
	io.extend_with(RpcImpl.to_delegate());

	let (client, server) = local::connect::<gen_client::Client, _, _>(io);
	let fut = client.add(5, 6).map_ok(|res| println!("5 + 6 = {}", res));
	futures::executor::block_on(async move { futures::join!(fut, server) })
		.0
		.unwrap();
}

jsonrpc's People

Contributors

arkpar avatar ascjones avatar bkchr avatar c0gent avatar cmichi avatar criesofcarrots avatar debris avatar dependabot-preview[bot] avatar dependabot[bot] avatar dvc94ch avatar ebkalderon avatar faern avatar hcastano avatar jstarry avatar koushiro avatar koute avatar lacabra avatar latrasis avatar maciejhirsz avatar marwes avatar niklasad1 avatar nikvolf avatar ordian avatar pinkisemils avatar rphmeier avatar seunlanlege avatar sorpaas avatar svyatonik avatar tomusdrw avatar xanewok avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonrpc's Issues

Use procedural macros

Replace build_rpc_trait macro with custom derive since it starts to get unmaintanable.

migrate to serde 0.9

rust 0.15 was just released and with it custom derive!

Serde released version 0.9, which is now incompatible with this library:

error[E0308]: mismatched types
  --> src/api/handler.rs:40:12
   |
40 |         Ok(value)
   |            ^^^^^ expected enum `jsonrpc_core::Value`, found enum `serde_json::Value`
   |
   = note: expected type `jsonrpc_core::Value`
   = note:    found type `serde_json::Value`

migrating shouldn't be difficult. If you would like, I can open a pull request.

Allow customisation of Access-Control-Allow-Headers

Steps to reproduce:

  1. Expand Access-Control-Request-Headers: Origin, Content-Type, Accept in request with Authorization HTTP header.

What expected:

  • Access-Control-Allow-Headers from response will contain Authorization as accepted HTTP header

What happened by fact:

  • Access-Control-Allow-Headers from response doesn't contain Authorization HTTP header

Environment:

> rustc --version --verbose
rustc 1.18.0-nightly (bbdaad0dc 2017-04-14)
binary: rustc
commit-hash: bbdaad0dc8dc64e036ccee817f90a91876b32a9d
commit-date: 2017-04-14
host: x86_64-pc-windows-msvc
release: 1.18.0-nightly
LLVM version: 3.9
Server: jsonrpc-minihttp-server/7.0.0

Related info:

Macros parameter limitation

Looks like there is a limitation to the number of parameters you can define in build_rpc_trait! macros
So I am looking for a way to circumvent this shortcoming with a generic parameter I could parse myself inside impl but couldn't realize so far, tried this:

use jsonrpc_core::{Error, Params};
use jsonrpc_core::futures::BoxFuture;
use std::collections::BTreeMap;
use serde_json::{self,Value};

build_rpc_trait! {
	/// RPC Interface.
	pub trait Faucet {
    type Metadata;
		#[rpc(meta, name = "faucet_new")]
		fn faucet_new(&self, Self::Metadata, BTreeMap<String, Value>) -> BoxFuture<BTreeMap<String, String>, Error>;
	}
}

Or

use jsonrpc_core::{Error, Params};
use jsonrpc_core::futures::BoxFuture;
use std::collections::BTreeMap;
use serde_json::{self,Value};

build_rpc_trait! {
	/// RPC Interface.
	pub trait Faucet {
    type Metadata;
		#[rpc(meta, name = "faucet_new")]
		fn faucet_new(&self, Self::Metadata, Value) -> BoxFuture<BTreeMap<String, String>, Error>;
	}
}

But I am getting error code -32601 "Method not found", What can be done to receive a serialized Json Object over RPC ?

Maintain 'stable' branch

As it is now, if some urgent fix is required by parity, we will have to create separate branch for it and update parity Cargo.toml to use this new branch. This is because jsonrpc/master usually contains breaking changes and parity cannot be just updated to this latest master.

Implement mising futures::Sink implementations

pubsub::Sink and macros::pubsub::Sink should implement futures::Sink.

Actually instead of using those structures it should be possible to do self.transport.with(Box::new(FnMut)) and just declare those structs as type aliases to futures::sink::With.

idea, use lightweight http server

Currently jsonrpc-http-server uses hyper. And since I remember there were some issues with it (that's why we have forked it). What do you think about replacing hyper with some other / smaller library? eg. tiny-http

jsonrpc-macros should have feature gates

[dependencies]
serde = "0.9"
jsonrpc-core = { version = "7.0", path = "../core" }
jsonrpc-pubsub = { version = "7.0", path = "../pubsub" }

[dev-dependencies]
jsonrpc-tcp-server = { version = "7.0", path = "../tcp" }

jsonrpc-pubsub and jsonrpc-tcp-server should be optional

Pre-process hosts and cors headers

Currently you can supply any string to cors or hosts validation.
We do know however what format the strings should look like. Implement pre-procesing and validation for those.

Don't consume MetaIoHandler until all error handling is done

I have a use case where I want to bind the server to a local port and I don't really care what the port is, I just need to know it when done setting up. So I have a loop where I iterate from port X to Y and try each until ServerBuilder::start returns success or I'm all out of options.

The problem is that ServerBuilder::new consumes my handler. So I have to create a new one for each try. This severely limits how I can implement my handlers and force me to either put stuff behind clonable Arc<Mutex<...>>es or some other weird solution.

Is this a use case you would like to support? If so I have two ideas how to solve it:

  • The error in ServerBuilder::start can contain my handler so I can extract it from a failed try.
  • ServerBuilder::new does not take my handler. Instead the API is rewritten so the handler is given after it is known that the server can be created. To do this ServerBuilder::start could return a Result<IntermediateServerBuilder> with one method: start(handler) -> Server.

License information missing

Hi. The jsonrpc-core crate published on crates.io says it has the MIT license. However, this repository and the Cargo.toml files does not mention any license. Is everything under MIT? Could you please specify the license in these crates?

Don't process requests when invalid cross-origin request is received

Currently http and minihttp servers are processing the request even if Origin header is not allowed to access. The requester will not be able to read the response, but can cause side effects to happen on the node.
We should rather fail fast in such case and avoid even processing the request.

File descriptor transport server

Would there be an interest to implement a file descriptor 'transport server' ?
So you could just use stdin to send json command, and pipe programs together.
Useful for test purposes as well.

PubSub crate

Use Metadata to provide a way to send notifications

Macros: trait definition should support async or sync method impl

We can accommodate old uses of Result with try! using a Carrier implementation and ?.

Until Carrier is stabilized we could just hack around it when porting existing synchronous method implementations

fn previous_sync(&self) -> BoxFuture<Success, Error> {
    let body = move || {
        // previous function body here
    };

    Future::done(body()).boxed()
}

Example/doc for how to talk to a PubSub server

I don't find very much information how to talk to a server using the PubSub feature of this repository. Would it be possible to add an example or some docs on that?

I have followed the example file to set up a server, and it is running. But I don't know what send to it to register my client.

Some help with this would be awesome. Thanks.

Importing from cargo gives trait bound errors

Creating a new project and doing a cut-n-paste of the code in example server.rs fails to compile with error; error.txt

The only way to fix this is to clone the entire jsonrpc repository and then set Cargo.toml to path into the cloned projects subdirectories for core and http. Setting up Cargo the way as instructed in the documentation doesn't work.

I want to be able to just get the jsonrpc-core and jsonrpc-http-server crates from crates.io in my Cargo.toml.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.