Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
68 commits
Select commit Hold shift + click to select a range
33ad778
feat: client rpc middleware
niklasad1 Jan 15, 2025
401dfc1
PoC works
niklasad1 Jan 29, 2025
11d7b4d
cargo fmt
niklasad1 Jan 29, 2025
622bffd
more refactoring
niklasad1 Feb 25, 2025
56be708
Merge remote-tracking branch 'origin/master' into na-client-rpc-middl…
niklasad1 Feb 26, 2025
93c9b6f
use Cow in Notification to avoid alloc
niklasad1 Feb 26, 2025
5929436
cleanup some todos
niklasad1 Feb 26, 2025
946afee
Merge remote-tracking branch 'origin/master' into na-client-rpc-middl…
niklasad1 Mar 10, 2025
ff64b91
rpc trait: return Result<MethodResponse, Err>
niklasad1 Mar 11, 2025
9515e40
remove infallible err
niklasad1 Mar 12, 2025
062ead3
make it compile
niklasad1 Mar 12, 2025
d52740b
fix tests
niklasad1 Mar 12, 2025
b508470
introduce client method response type
niklasad1 Mar 19, 2025
dec873f
fix faulty imports
niklasad1 Mar 20, 2025
3aa828d
minor cleanup
niklasad1 Mar 20, 2025
b1e3b41
introduce Batch/BatchEntry for middleware
niklasad1 Mar 21, 2025
46ef085
remove ignore for batch test
niklasad1 Mar 21, 2025
5759407
fix rustdocs
niklasad1 Mar 22, 2025
ee75d58
add rpc middleware for the async client
niklasad1 Mar 25, 2025
79216b5
remove serialize specific types
niklasad1 Mar 25, 2025
8849af5
commit missing file
niklasad1 Mar 25, 2025
6a6e3aa
no serde_json::Value
niklasad1 Mar 26, 2025
02fb917
more nit fixing
niklasad1 Mar 27, 2025
09b4e0b
more cleanup
niklasad1 Mar 27, 2025
763cad6
refactor method response client
niklasad1 Mar 28, 2025
0e2adb0
fix some nits
niklasad1 Mar 28, 2025
6b80964
add client middleware rpc
niklasad1 Mar 31, 2025
631d7c0
fix wasm build
niklasad1 Apr 1, 2025
4ddee29
Merge remote-tracking branch 'origin/master' into na-client-rpc-middl…
niklasad1 Apr 1, 2025
a7324d3
add client middleware example
niklasad1 Apr 1, 2025
38b5261
Update examples/examples/rpc_middleware_client.rs
niklasad1 Apr 1, 2025
9640517
ToJson -> RawValue
niklasad1 Apr 2, 2025
100bda0
Merge remote-tracking branch 'origin/master' into na-client-rpc-middl…
niklasad1 Apr 2, 2025
b051bd6
replace Future type with impl Trait
niklasad1 Apr 2, 2025
f03371a
revert changelog
niklasad1 Apr 2, 2025
cc08ebf
remove logger response future
niklasad1 Apr 2, 2025
9936607
some cleanup
niklasad1 Apr 3, 2025
4149181
move request timeout from transport to client
niklasad1 Apr 3, 2025
8161e01
more nit fixing
niklasad1 Apr 3, 2025
1f73b97
have pass over examples
niklasad1 Apr 4, 2025
de1461d
show proper batch middleware example
niklasad1 Apr 4, 2025
a148135
middleware: clean up batch type
niklasad1 Apr 4, 2025
5285fc4
fix wasm build
niklasad1 Apr 4, 2025
54c7fe3
Update Cargo.toml
niklasad1 Apr 5, 2025
cc7807e
doc: fix typo
niklasad1 Apr 5, 2025
f722acd
core: remove tracing mod
niklasad1 Apr 5, 2025
ed4fb5b
fix more clippy
niklasad1 Apr 5, 2025
76d56c5
refactor: use json rawvalue
niklasad1 Apr 7, 2025
9671152
replace StringError with SubscriptionErr
niklasad1 Apr 8, 2025
cdc8465
Merge remote-tracking branch 'origin/master' into na-json-raw-value
niklasad1 Apr 11, 2025
822b7ba
cleanup json APIs with RawValue
niklasad1 Apr 12, 2025
ebcd810
cleanup and fix tests
niklasad1 Apr 12, 2025
6088a06
remove from_json api
niklasad1 Apr 12, 2025
50ce885
revert faulty change in types
niklasad1 Apr 12, 2025
f1448aa
revert faulty change in types v2
niklasad1 Apr 12, 2025
b995cfd
fix rustdocs
niklasad1 Apr 12, 2025
add0baf
use explicit JSON null value instead of default
niklasad1 Apr 12, 2025
f9b3117
Merge remote-tracking branch 'origin/master' into na-json-raw-value
niklasad1 Apr 14, 2025
0039e3a
cleanup Rawvalue::from_string usage
niklasad1 Apr 14, 2025
03603e0
fix tests
niklasad1 Apr 14, 2025
cccd706
Update core/src/traits.rs
niklasad1 Apr 14, 2025
c0e8a34
Update benches/bench.rs
niklasad1 Apr 14, 2025
01f76fd
Update core/src/params.rs
niklasad1 Apr 14, 2025
601d623
cleanup expects on RawValue
niklasad1 Apr 15, 2025
dfd6df3
improve docs
niklasad1 Apr 15, 2025
51ce03f
replace manual serialization with to_raw_value
niklasad1 Apr 15, 2025
ca3e5bf
fix clippy
niklasad1 Apr 15, 2025
097f084
fix nit
niklasad1 Apr 15, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub fn jsonrpsee_types_v2(crit: &mut Criterion) {
// Construct the serialized array request using the `RawValue` directly.
crit.bench_function("jsonrpsee_types_array_params_baseline", |b| {
b.iter(|| {
let params = serde_json::value::RawValue::from_string("[1, 2]".to_string()).unwrap();
let params = serde_json::value::to_raw_value("[1, 2]").unwrap();

let request = Request::borrowed("say_hello", Some(&params), Id::Number(0));
v2_serialize(request);
Expand All @@ -136,8 +136,7 @@ pub fn jsonrpsee_types_v2(crit: &mut Criterion) {
// Construct the serialized object request using the `RawValue` directly.
crit.bench_function("jsonrpsee_types_object_params_baseline", |b| {
b.iter(|| {
let params = serde_json::value::RawValue::from_string(r#"{"key": 1}"#.to_string()).unwrap();

let params = serde_json::value::to_raw_value(r#"{"key": 1}"#).unwrap();
let request = Request::borrowed("say_hello", Some(&params), Id::Number(0));
v2_serialize(request);
})
Expand Down
3 changes: 1 addition & 2 deletions benches/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ pub async fn http_server(handle: tokio::runtime::Handle) -> (String, jsonrpsee::
#[cfg(not(feature = "jsonrpc-crate"))]
pub async fn ws_server(handle: tokio::runtime::Handle) -> (String, jsonrpsee::server::ServerHandle) {
use jsonrpsee::server::{ServerBuilder, ServerConfig};
use serde_json::value::RawValue;

let config = ServerConfig::builder()
.max_request_body_size(u32::MAX)
Expand All @@ -151,7 +150,7 @@ pub async fn ws_server(handle: tokio::runtime::Handle) -> (String, jsonrpsee::se
UNSUB_METHOD_NAME,
|_params, pending, _ctx, _| async move {
let sink = pending.accept().await?;
let json = RawValue::from_string("\"Hello\")".to_string()).unwrap();
let json = serde_json::value::to_raw_value(&"Hello").unwrap();
sink.send(json).await?;

Ok(())
Expand Down
14 changes: 7 additions & 7 deletions client/http-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,13 +387,13 @@ where
let id = self.id_manager.next_request_id();
let params = params.to_rpc_params()?;

let method_response = run_future_until_timeout(
self.service.call(Request::borrowed(method, params.as_deref(), id.clone())),
self.request_timeout,
)
.await?
.into_method_call()
.expect("Method call must return a method call response; qed");
let method_response = run_future_until_timeout(
self.service.call(Request::borrowed(method, params.as_deref(), id.clone())),
self.request_timeout,
)
.await?
.into_method_call()
.expect("Method call must return a method call reponse; qed");

let rp = ResponseSuccess::try_from(method_response.into_inner())?;

Expand Down
10 changes: 6 additions & 4 deletions core/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use serde_json::value::RawValue;
/// Helper module for building parameters.
mod params_builder {
use serde::Serialize;
use serde_json::value::RawValue;

/// Initial number of bytes for a parameter length.
const PARAM_BYTES_CAPACITY: usize = 128;
Expand Down Expand Up @@ -107,7 +108,7 @@ mod params_builder {
}

/// Finish the building process and return a JSON compatible string.
pub(crate) fn build(mut self) -> Option<String> {
pub(crate) fn build(mut self) -> Option<Box<RawValue>> {
if self.bytes.is_empty() {
return None;
}
Expand All @@ -120,7 +121,8 @@ mod params_builder {
}

// Safety: This is safe because JSON does not emit invalid UTF-8.
Some(unsafe { String::from_utf8_unchecked(self.bytes) })
let json_str = unsafe { String::from_utf8_unchecked(self.bytes) };
Some(RawValue::from_string(json_str).expect("Valid JSON; qed"))
}
}
}
Expand Down Expand Up @@ -164,7 +166,7 @@ impl Default for ObjectParams {

impl ToRpcParams for ObjectParams {
fn to_rpc_params(self) -> Result<Option<Box<RawValue>>, serde_json::Error> {
if let Some(json) = self.0.build() { RawValue::from_string(json).map(Some) } else { Ok(None) }
Ok(self.0.build())
}
}

Expand Down Expand Up @@ -206,7 +208,7 @@ impl Default for ArrayParams {

impl ToRpcParams for ArrayParams {
fn to_rpc_params(self) -> Result<Option<Box<RawValue>>, serde_json::Error> {
if let Some(json) = self.0.build() { RawValue::from_string(json).map(Some) } else { Ok(None) }
Ok(self.0.build())
}
}

Expand Down
8 changes: 4 additions & 4 deletions core/src/server/rpc_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,15 +325,15 @@ impl Methods {
/// async fn main() {
/// use jsonrpsee::{RpcModule, SubscriptionMessage};
/// use jsonrpsee::types::{response::Success, Response};
/// use jsonrpsee::core::JsonRawValue;
/// use jsonrpsee::core::to_json_raw_value;
/// use futures_util::StreamExt;
///
/// let mut module = RpcModule::new(());
/// module.register_subscription("hi", "hi", "goodbye", |_, pending, _, _| async {
/// let sink = pending.accept().await?;
///
/// // see comment above.
/// let msg = JsonRawValue::from_string("\"one answer\"".into()).unwrap();
/// let msg = to_json_raw_value(&"one answer").unwrap();
/// sink.send(msg).await?;
///
/// Ok(())
Expand Down Expand Up @@ -423,12 +423,12 @@ impl Methods {
/// #[tokio::main]
/// async fn main() {
/// use jsonrpsee::{RpcModule, SubscriptionMessage};
/// use jsonrpsee::core::{EmptyServerParams, RpcResult, JsonRawValue};
/// use jsonrpsee::core::{EmptyServerParams, RpcResult, to_json_raw_value};
///
/// let mut module = RpcModule::new(());
/// module.register_subscription("hi", "hi", "goodbye", |_, pending, _, _| async move {
/// let sink = pending.accept().await?;
/// let msg = JsonRawValue::from_string("\"one answer\"".into()).unwrap();
/// let msg = to_json_raw_value(&"one answer").unwrap();
/// sink.send(msg).await?;
/// Ok(())
/// }).unwrap();
Expand Down
6 changes: 3 additions & 3 deletions core/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use serde_json::value::RawValue;
/// impl ToRpcParams for ManualParam {
/// fn to_rpc_params(self) -> Result<Option<Box<RawValue>>, serde_json::Error> {
/// // Manually define a valid JSONRPC parameter.
/// RawValue::from_string("[1, \"2\", 3]".to_string()).map(Some)
/// serde_json::value::to_raw_value("[1,2,3]").map(Some)
/// }
/// }
/// ```
Expand Down Expand Up @@ -85,8 +85,8 @@ pub trait ToRpcParams {
macro_rules! to_rpc_params_impl {
() => {
fn to_rpc_params(self) -> Result<Option<Box<RawValue>>, serde_json::Error> {
let json = serde_json::to_string(&self)?;
RawValue::from_string(json).map(Some)
let json = serde_json::value::to_raw_value(&self)?;
Ok(Some(json))
}
};
}
Expand Down
13 changes: 6 additions & 7 deletions proc-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@
/// - `namespace`: add a prefix to all the methods and subscriptions in this RPC. For example, with namespace `foo` and
/// method `spam`, the resulting method name will be `foo_spam`.
/// - `namespace_separator`: customize the separator used between namespace and method name. Defaults to `_`.
/// For example, `namespace = "foo", namespace_separator = "."` results in method names like `foo.bar` instead of `foo_bar`.

Check warning on line 151 in proc-macros/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

using tabs in doc comments is not recommended

warning: using tabs in doc comments is not recommended --> proc-macros/src/lib.rs:151:4 | 151 | /// For example, `namespace = "foo", namespace_separator = "."` results in method names like `foo.bar` instead of `foo_bar`. | ^^^^^^^^ help: consider using four spaces per tab | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#tabs_in_doc_comments = note: `#[warn(clippy::tabs_in_doc_comments)]` on by default

Check warning on line 151 in proc-macros/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

using tabs in doc comments is not recommended

warning: using tabs in doc comments is not recommended --> proc-macros/src/lib.rs:151:4 | 151 | /// For example, `namespace = "foo", namespace_separator = "."` results in method names like `foo.bar` instead of `foo_bar`. | ^^^^^^^^ help: consider using four spaces per tab | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#tabs_in_doc_comments = note: `#[warn(clippy::tabs_in_doc_comments)]` on by default

Check warning on line 151 in proc-macros/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

using tabs in doc comments is not recommended

warning: using tabs in doc comments is not recommended --> proc-macros/src/lib.rs:151:4 | 151 | /// For example, `namespace = "foo", namespace_separator = "."` results in method names like `foo.bar` instead of `foo_bar`. | ^^^^^^^^ help: consider using four spaces per tab | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#tabs_in_doc_comments = note: `#[warn(clippy::tabs_in_doc_comments)]` on by default
/// - `server_bounds`: replace *all* auto-generated trait bounds with the user-defined ones for the server
/// implementation.
/// - `client_bounds`: replace *all* auto-generated trait bounds with the user-defined ones for the client
Expand Down Expand Up @@ -233,7 +233,7 @@
/// mod rpc_impl {
/// use jsonrpsee::{proc_macros::rpc, Extensions};
/// use jsonrpsee::server::{PendingSubscriptionSink, SubscriptionMessage, IntoSubscriptionCloseResponse, SubscriptionCloseResponse};
/// use jsonrpsee::core::{async_trait, RpcResult, SubscriptionResult, JsonRawValue};
/// use jsonrpsee::core::{async_trait, RpcResult, SubscriptionResult, to_json_raw_value};
///
/// enum CloseResponse {
/// None,
Expand All @@ -248,8 +248,7 @@
/// // Send a close response as an ordinary subscription notification
/// // when the subscription is terminated.
/// CloseResponse::Failed => {
/// const FAILED: &str = "\"Failed\"";
/// let err = JsonRawValue::from_string(FAILED.to_string()).unwrap();
/// let err = to_json_raw_value(&"Failed").unwrap();
/// SubscriptionCloseResponse::Notif(err.into())
/// }
/// }
Expand Down Expand Up @@ -336,7 +335,7 @@
/// // as subscription responses.
/// async fn sub_override_notif_method(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
/// let mut sink = pending.accept().await?;
/// let msg = JsonRawValue::from_string("\"Response_A\"".into()).unwrap();
/// let msg = to_json_raw_value(&"Response_A").unwrap();
/// sink.send(msg).await?;
/// Ok(())
/// }
Expand All @@ -345,8 +344,8 @@
/// async fn sub(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
/// let sink = pending.accept().await?;
///
/// let msg1 = JsonRawValue::from_string("\"Response_A\"".into()).unwrap();
/// let msg2 = JsonRawValue::from_string("\"Response_B\"".into()).unwrap();
/// let msg1 = to_json_raw_value(&"Response_A").unwrap();
/// let msg2 = to_json_raw_value(&"Response_B").unwrap();
///
/// sink.send(msg1).await?;
/// sink.send(msg2).await?;
Expand All @@ -362,7 +361,7 @@
/// return CloseResponse::None;
/// };
///
/// let msg = JsonRawValue::from_string("\"Response_A\"".into()).unwrap();
/// let msg = to_json_raw_value(&"Response_A").unwrap();
///
/// if sink.send(msg).await.is_ok() {
/// CloseResponse::Failed
Expand Down
10 changes: 5 additions & 5 deletions proc-macros/tests/ui/correct/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::net::SocketAddr;

use jsonrpsee::core::client::ClientT;
use jsonrpsee::core::params::ArrayParams;
use jsonrpsee::core::{JsonRawValue, RpcResult, SubscriptionResult, async_trait};
use jsonrpsee::core::{RpcResult, SubscriptionResult, async_trait, to_json_raw_value};
use jsonrpsee::proc_macros::rpc;
use jsonrpsee::types::ErrorObject;
use jsonrpsee::ws_client::*;
Expand Down Expand Up @@ -96,11 +96,11 @@ impl RpcServer for RpcServerImpl {
async fn sub(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
let sink = pending.accept().await?;

let response_a = JsonRawValue::from_string("\"Response_A\"".into()).unwrap();
let response_b = JsonRawValue::from_string("\"Response_B\"".into()).unwrap();
let msg1 = to_json_raw_value(&"Response_A").unwrap();
let msg2 = to_json_raw_value(&"Response_B").unwrap();

sink.send(response_a).await?;
sink.send(response_b).await?;
sink.send(msg1).await?;
sink.send(msg2).await?;

Ok(())
}
Expand Down
11 changes: 5 additions & 6 deletions proc-macros/tests/ui/correct/only_server.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::net::SocketAddr;

use jsonrpsee::core::{JsonRawValue, RpcResult, SubscriptionResult, async_trait};
use jsonrpsee::core::{RpcResult, SubscriptionResult, async_trait, to_json_raw_value};
use jsonrpsee::proc_macros::rpc;
use jsonrpsee::server::{PendingSubscriptionSink, ServerBuilder};

Expand Down Expand Up @@ -31,11 +31,10 @@ impl RpcServer for RpcServerImpl {
async fn sub(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
let sink = pending.accept().await?;

let response_a = JsonRawValue::from_string("\"Response_A\"".into()).unwrap();
let response_b = JsonRawValue::from_string("\"Response_B\"".into()).unwrap();

sink.send(response_a).await?;
sink.send(response_b).await?;
let msg1 = to_json_raw_value(&"Response_A").unwrap();
let msg2 = to_json_raw_value(&"Response_B").unwrap();
sink.send(msg1).await?;
sink.send(msg2).await?;

Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions tests/proc-macro-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Test module for the proc-macro API to make sure that it compiles with the core features.

use jsonrpsee::PendingSubscriptionSink;
use jsonrpsee::core::{JsonRawValue, SubscriptionResult, async_trait};
use jsonrpsee::core::{SubscriptionResult, async_trait, to_json_raw_value};
use jsonrpsee::proc_macros::rpc;
use jsonrpsee::types::ErrorObjectOwned;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -52,7 +52,7 @@ impl ApiServer for () {

async fn sub(&self, pending: PendingSubscriptionSink, _: PubSubKind, _: PubSubParams) -> SubscriptionResult {
let sink = pending.accept().await?;
let msg = JsonRawValue::from_string("\"msg\"".into())?;
let msg = to_json_raw_value("msg")?;
sink.send(msg).await?;
Ok(())
}
Expand Down
5 changes: 2 additions & 3 deletions tests/tests/proc_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ mod rpc_impl {
use jsonrpsee::core::{SubscriptionResult, async_trait};
use jsonrpsee::proc_macros::rpc;
use jsonrpsee::types::{ErrorObject, ErrorObjectOwned};
use serde_json::value::RawValue;

pub struct CustomSubscriptionRet;

Expand Down Expand Up @@ -178,7 +177,7 @@ mod rpc_impl {

async fn sub_not_result(&self, pending: PendingSubscriptionSink) {
let sink = pending.accept().await.unwrap();
let msg = RawValue::from_string("\"lo\"".into()).unwrap();
let msg = serde_json::value::to_raw_value("lo").unwrap();
sink.send(msg).await.unwrap();
}

Expand All @@ -189,7 +188,7 @@ mod rpc_impl {
fn sync_sub(&self, pending: PendingSubscriptionSink) {
tokio::spawn(async move {
let sink = pending.accept().await.unwrap();
let msg = RawValue::from_string("\"hello\"".into()).unwrap();
let msg = serde_json::value::to_raw_value("hello").unwrap();
sink.send(msg).await.unwrap();
});
}
Expand Down
2 changes: 1 addition & 1 deletion tests/tests/rpc_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ async fn close_test_subscribing_without_server() {
module
.register_subscription("my_sub", "my_sub", "my_unsub", |_, pending, _, _| async move {
let sink = pending.accept().await?;
let msg = RawValue::from_string("\"lo\"".into())?;
let msg = serde_json::value::to_raw_value("lo")?;

// make sure to only send one item
sink.send(msg.clone()).await?;
Expand Down
2 changes: 1 addition & 1 deletion types/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ mod test {
fn serialize_call() {
let method = "subtract";
let id = Id::Number(1); // It's enough to check one variant, since the type itself also has tests.
let params = Some(RawValue::from_string("[42,23]".into()).unwrap());
let params = Some(serde_json::value::to_raw_value("[42,23]").unwrap());

let test_vector: &[(&'static str, Option<_>, Option<_>, &'static str)] = &[
// With all fields set.
Expand Down
Loading