Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0410582
DEFI-2565: Add support for batched JSON-RPC requests
lpahlavi Dec 18, 2025
bcc612d
Add `JsonRpcPayload` trait
lpahlavi Dec 22, 2025
05829f5
Refactor into `JsonRpcCall` trait
lpahlavi Dec 22, 2025
dc4d0bb
Revert to generic types for `Request` and `Response`
lpahlavi Dec 22, 2025
dce5081
Remove `JsonRpcCall` trait
lpahlavi Jan 5, 2026
e72299a
Cleanup example
lpahlavi Jan 6, 2026
b924dd3
Make heterogeneous batch JSON-RPC request in example
lpahlavi Jan 16, 2026
5cf6e80
Use `Display` in `ConsistentResponseIdFilterError`
lpahlavi Jan 16, 2026
ec447ba
Panic if request IDs are not unique
lpahlavi Jan 16, 2026
bc85a04
Make `ConsistentJsonRpcIdFilter::request_ids` always a `BTreeSet`
lpahlavi Jan 16, 2026
af0a625
Correlate responses with request IDs in `ConsistentJsonRpcIdFilter`
lpahlavi Jan 20, 2026
026c4c9
Use `BTreeSet` instead of `itertools::dedup` to check for duplicates
lpahlavi Jan 26, 2026
a8d4d14
Check that batch is non-empty and document panics
lpahlavi Jan 26, 2026
8ab87b9
Rename `correlate_response_ids` and change return type
lpahlavi Jan 26, 2026
cc78666
Use defend-style programming
lpahlavi Jan 26, 2026
66209dd
Use `partition_map` to clean-up iterations
lpahlavi Jan 26, 2026
c86f4f7
Clippy
lpahlavi Jan 26, 2026
51e286f
Assert response IDs are correctly ordered
lpahlavi Jan 26, 2026
d14af61
Shuffle responses instead of reversing
lpahlavi Jan 27, 2026
3326bcb
Fix swapped test names and comments
lpahlavi Jan 27, 2026
9696907
Remove unused imports
lpahlavi Jan 27, 2026
6b79b86
Generate index randomly
lpahlavi Jan 27, 2026
4bf2766
Use `prop_assert` instead of `assert` in `proptest!`
lpahlavi Jan 27, 2026
c295e66
Use `ic_cdk::println!` in example
lpahlavi Jan 27, 2026
5b0af47
Return `Invalid Request` error responses with `Id::Null`
lpahlavi Jan 28, 2026
0cde722
Expand `http/json/tests.rs` with JSON-RPC batch tests
lpahlavi Jan 28, 2026
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
74 changes: 56 additions & 18 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ async-trait = "0.1.88"
candid = { version = "0.10.13" }
canhttp = { version = "0.4.0", path = "canhttp" }
ciborium = "0.2.2"
derive_more = { version = "2.0.1", features = ["from", "try_unwrap", "unwrap"] }
futures-channel = "0.3.31"
futures-util = "0.3.31"
http = "1.3.1"
Expand Down
4 changes: 3 additions & 1 deletion canhttp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@ documentation = "https://docs.rs/canhttp"
[features]
default = ["http"]
http = ["dep:http", "dep:num-traits", "dep:tower-layer"]
json = ["http", "dep:serde", "dep:serde_json"]
json = ["dep:derive_more", "dep:http", "dep:serde", "dep:serde_json"]
multi = ["dep:ciborium", "dep:sha2", "dep:futures-channel", "dep:serde"]

[dependencies]
assert_matches = { workspace = true }
ciborium = { workspace = true, optional = true }
derive_more = { workspace = true, optional = true }
futures-channel = { workspace = true, optional = true }
futures-util = { workspace = true }
http = { workspace = true, optional = true }
ic-cdk = { workspace = true }
ic-error-types = { workspace = true }
itertools = { workspace = true }
num-traits = { workspace = true, optional = true }
pin-project = { workspace = true }
serde = { workspace = true, optional = true }
Expand Down
10 changes: 6 additions & 4 deletions canhttp/src/http/json/id.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::num::ParseIntError;
use std::str::FromStr;
use std::{
fmt::{Display, Formatter},
num::ParseIntError,
str::FromStr,
};

/// An identifier established by the Client that MUST contain a String, Number, or NULL value if included.
///
/// If it is not included it is assumed to be a notification.
/// The value SHOULD normally not be Null.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Id {
/// Numeric ID.
Expand Down
99 changes: 79 additions & 20 deletions canhttp/src/http/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
//! ```
//!
//! [`Service`]: tower::Service

use crate::convert::CreateResponseFilter;
use crate::{
convert::{
ConvertRequest, ConvertRequestLayer, ConvertResponse, ConvertResponseLayer,
Expand All @@ -61,15 +61,16 @@ use crate::{
};
pub use id::{ConstantSizeId, Id};
pub use request::{
HttpJsonRpcRequest, JsonRequestConversionError, JsonRequestConverter, JsonRpcRequest,
BatchJsonRpcRequest, HttpBatchJsonRpcRequest, HttpJsonRpcRequest, JsonRequestConversionError,
JsonRequestConverter, JsonRpcRequest,
};
pub use response::{
ConsistentJsonRpcIdFilter, ConsistentResponseIdFilterError, CreateJsonRpcIdFilter,
HttpJsonRpcResponse, JsonResponseConversionError, JsonResponseConverter, JsonRpcError,
JsonRpcResponse, JsonRpcResult,
BatchJsonRpcResponse, ConsistentJsonRpcIdFilter, ConsistentResponseIdFilterError,
CreateJsonRpcIdFilter, HttpBatchJsonRpcResponse, HttpJsonRpcResponse,
JsonResponseConversionError, JsonResponseConverter, JsonRpcError, JsonRpcResponse,
};
use serde::{de::DeserializeOwned, Serialize};
use std::marker::PhantomData;
use std::{fmt::Debug, marker::PhantomData};
use tower_layer::{Layer, Stack};
pub use version::Version;

Expand Down Expand Up @@ -132,21 +133,77 @@ where
}
}

/// Middleware that combines a [`HttpConversionLayer`], a [`JsonConversionLayer`] to create
/// an JSON-RPC over HTTP [`Service`].
/// Middleware that combines an [`HttpConversionLayer`] and a [`JsonConversionLayer`] to create
/// a JSON-RPC over HTTP [`Service`].
///
/// This middleware can be used either with regular JSON-RPC requests and responses (i.e.
/// [`JsonRpcRequest`] and [`JsonRpcResponse`]) or with batch JSON-RPC requests and responses
/// (i.e. [`BatchJsonRpcRequest`] and [`BatchJsonRpcResponse`]).
///
/// This middleware includes a [`ConsistentJsonRpcIdFilter`], which ensures that each response
/// carries a valid JSON-RPC ID matching the corresponding request ID. This guarantees that the
/// [`Service`] complies with the [JSON-RPC 2.0 specification].
///
/// # Examples
///
/// Create a simple JSON-RPC over HTTP client.
/// ```
/// use canhttp::{
/// Client,
/// http::json::{HttpJsonRpcRequest, HttpJsonRpcResponse, JsonRpcHttpLayer}
/// };
/// use serde::{de::DeserializeOwned, Serialize};
/// use std::fmt::Debug;
/// use tower::{BoxError, Service, ServiceBuilder};
///
/// fn client<Params, Result>() -> impl Service<
/// HttpJsonRpcRequest<Params>,
/// Response = HttpJsonRpcResponse<Result>,
/// Error = BoxError
/// >
/// where
/// Params: Debug + Serialize,
/// Result: Debug + DeserializeOwned,
/// {
/// ServiceBuilder::new()
/// .layer(JsonRpcHttpLayer::new())
/// .service(Client::new_with_box_error())
/// }
/// ```
///
/// Create a simple batch JSON-RPC over HTTP client.
/// ```
/// use canhttp::{
/// Client,
/// http::json::{HttpBatchJsonRpcRequest, HttpBatchJsonRpcResponse, JsonRpcHttpLayer}
/// };
/// use serde::{de::DeserializeOwned, Serialize};
/// use std::fmt::Debug;
/// use tower::{BoxError, Service, ServiceBuilder};
///
/// fn client<Params, Result>() -> impl Service<
/// HttpBatchJsonRpcRequest<Params>,
/// Response = HttpBatchJsonRpcResponse<Result>,
/// Error = BoxError
/// >
/// where
/// Params: Debug + Serialize,
/// Result: Debug + DeserializeOwned,
/// {
/// ServiceBuilder::new()
/// .layer(JsonRpcHttpLayer::new())
/// .service(Client::new_with_box_error())
/// }
/// ```
///
/// [`Service`]: tower::Service
/// [JSON-RPC 2.0 specification]: https://www.jsonrpc.org/specification
#[derive(Debug)]
pub struct JsonRpcHttpLayer<Params, Result> {
_marker: PhantomData<(Params, Result)>,
pub struct JsonRpcHttpLayer<Request, Response> {
_marker: PhantomData<(Request, Response)>,
}

impl<Params, Result> JsonRpcHttpLayer<Params, Result> {
impl<Request, Response> JsonRpcHttpLayer<Request, Response> {
/// Returns a new [`JsonRpcHttpLayer`].
pub fn new() -> Self {
Self {
Expand All @@ -155,40 +212,42 @@ impl<Params, Result> JsonRpcHttpLayer<Params, Result> {
}
}

impl<Params, Result> Clone for JsonRpcHttpLayer<Params, Result> {
impl<Request, Response> Clone for JsonRpcHttpLayer<Request, Response> {
fn clone(&self) -> Self {
Self {
_marker: self._marker,
}
}
}

impl<Params, Result> Default for JsonRpcHttpLayer<Params, Result> {
impl<Request, Response> Default for JsonRpcHttpLayer<Request, Response> {
fn default() -> Self {
Self::new()
}
}

impl<Params, Result, S> Layer<S> for JsonRpcHttpLayer<Params, Result>
impl<Request, Response, S> Layer<S> for JsonRpcHttpLayer<Request, Response>
where
Params: Serialize,
Result: DeserializeOwned,
Request: Serialize,
Response: DeserializeOwned,
CreateJsonRpcIdFilter<Request, Response>:
CreateResponseFilter<http::Request<Request>, http::Response<Response>>,
{
type Service = FilterResponse<
ConvertResponse<
ConvertRequest<
ConvertResponse<ConvertRequest<S, HttpRequestConverter>, HttpResponseConverter>,
JsonRequestConverter<JsonRpcRequest<Params>>,
JsonRequestConverter<Request>,
>,
JsonResponseConverter<JsonRpcResponse<Result>>,
JsonResponseConverter<Response>,
>,
CreateJsonRpcIdFilter<Params, Result>,
CreateJsonRpcIdFilter<Request, Response>,
>;

fn layer(&self, inner: S) -> Self::Service {
stack(
HttpConversionLayer,
JsonConversionLayer::<JsonRpcRequest<Params>, JsonRpcResponse<Result>>::new(),
JsonConversionLayer::<Request, Response>::new(),
CreateResponseFilterLayer::new(CreateJsonRpcIdFilter::new()),
)
.layer(inner)
Expand Down
Loading