Releases: paritytech/jsonrpsee
v0.23.1
[v0.23.1] - 2024-06-10
This is a patch release that injects the ConnectionId in
the extensions when using a RpcModule without a server. This impacts
users that are using RpcModule directly (e.g., unit testing) and not the
server itself.
[Changed]
- types: remove anyhow dependency (#1398)
[Fixed]
- rpc module: inject ConnectionId in extensions (#1399)
Full Changelog: v0.23.0...v0.23.1
v0.23.0
[v0.23.0] - 2024-06-07
This is a new breaking release, and let's go through the changes.
hyper v1.0
jsonrpsee has been upgraded to use hyper v1.0 and this mainly impacts users that are using
the low-level API and rely on the hyper::service::make_service_fn
which has been removed, and from now on you need to manage the socket yourself.
The hyper::service::make_service_fn
can be replaced by the following example template:
async fn start_server() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
loop {
let sock = tokio::select! {
res = listener.accept() => {
match res {
Ok((stream, _remote_addr)) => stream,
Err(e) => {
tracing::error!("failed to accept v4 connection: {:?}", e);
continue;
}
}
}
_ = per_conn.stop_handle.clone().shutdown() => break,
};
let svc = tower::service_fn(move |req: hyper::Request<hyper::body::Incoming>| {
let mut jsonrpsee_svc = svc_builder
.set_rpc_middleware(rpc_middleware)
.build(methods, stop_handle);
// https://github.com/rust-lang/rust/issues/102211 the error type can't be inferred
// to be `Box<dyn std::error::Error + Send + Sync>` so we need to convert it to a concrete type
// as workaround.
jsonrpsee_svc
.call(req)
.await
.map_err(|e| anyhow::anyhow!("{:?}", e))
});
tokio::spawn(jsonrpsee::server::serve_with_graceful_shutdown(
sock,
svc,
stop_handle.clone().shutdown(),
));
}
}
Also, be aware that tower::service_fn
and hyper::service::service_fn
are different and it's recommended to use tower::service_fn
from now.
Extensions
Because it was not possible/easy to share state between RPC middleware layers
jsonrpsee has added Extensions
to the Request and Response.
To allow users to inject arbitrary data that can be accessed in the RPC middleware
and RPC handlers.
Please be careful when injecting large amounts of data into the extensions because
It's cloned for each RPC call, which can increase memory usage significantly.
The connection ID from the jsonrpsee-server is injected in the extensions by default.
and it is possible to fetch it as follows:
struct LogConnectionId<S>(S);
impl<'a, S: RpcServiceT<'a>> RpcServiceT<'a> for LogConnectionId<S> {
type Future = S::Future;
fn call(&self, request: jsonrpsee::types::Request<'a>) -> Self::Future {
let conn_id = request.extensions().get::<ConnectionId>().unwrap();
tracing::info!("Connection ID {}", conn_id.0);
self.0.call(request)
}
}
In addition the Extensions
is not added in the proc-macro API by default and
one has to enable with_extensions
attr for that to be available:
#[rpc(client, server)]
pub trait Rpc {
// legacy
#[method(name = "foo"])
async fn async_method(&self) -> u16>;
// with extensions
#[method(name = "with_ext", with_extensions)]
async fn f(&self) -> bool;
}
impl RpcServer for () {
async fn async_method(&self) -> u16 {
12
}
// NOTE: ext is injected just after self in the API
async fn f(&self, ext: &Extensions: b: String) -> {
ext.get::<u32>().is_ok()
}
}
client - TLS certificate store changed
The default TLS certificate store has been changed to
rustls-platform-verifier
to decide the best certificate
store for each platform.
In addition it's now possible to inject a custom certificate store
if one wants need some special certificate store.
client - Subscription API modified
The subscription API has been modified:
- The error type has been changed to
serde_json::Error
to indicate that error can only occur if the decoding of T fails. - It has been some confusion when the subscription is closed which can occur if the client "lagged" or the connection is closed.
Now it's possible to callSubscription::close_reason
after the subscription closed (i.e. has return None) to know why.
If one wants to replace old messages in case of lagging it is recommended to write your own adaptor on top of the subscription:
fn drop_oldest_when_lagging<T: Clone + DeserializeOwned + Send + Sync + 'static>(
mut sub: Subscription<T>,
buffer_size: usize,
) -> impl Stream<Item = Result<T, BroadcastStreamRecvError>> {
let (tx, rx) = tokio::sync::broadcast::channel(buffer_size);
tokio::spawn(async move {
// Poll the subscription which ignores errors
while let Some(n) = sub.next().await {
let msg = match n {
Ok(msg) => msg,
Err(e) => {
tracing::error!("Failed to decode the subscription message: {e}");
continue;
}
};
// Only fails if the receiver has been dropped
if tx.send(msg).is_err() {
return;
}
}
});
BroadcastStream::new(rx)
}
[Added]
- server: add
serve
andserve_with_graceful_shutdown
helpers (#1382) - server: pass
extensions
from http layer (#1389) - macros: add macro attr
with_extensions
(#1380) - server: inject connection id in extensions (#1381)
- feat: add
Extensions
to Request/MethodResponse (#1306) - proc-macros: rename parameter names (#1365)
- client: add
Subscription::close_reason
(#1320)
[Changed]
- chore(deps): tokio ^1.23.1 (#1393)
- server: use
ConnectionId
in subscription APIs (#1392) - server: add logs when connection closed by
ws ping/pong
(#1386) - client: set
authorization header
from the URL (#1384) - client: use rustls-platform-verifier cert store (#1373)
- client: remove MaxSlots limit (#1377)
- upgrade to hyper v1.0 (#1368)
v0.22.5
[v0.22.5] - 2024-04-29
A small bug-fix release, see each commit below for further information.
[Fixed]
v0.22.4
[v0.22.4] - 2024-04-08
Yet another rather small release that fixes a cancel-safety issue that
could cause an unexpected panic when reading disconnect reason from the background task.
Also this makes the API Client::disconnect_reason
cancel-safe.
[Added]
[Changed]
- client: downgrade logs from error/warn -> debug (#1343)
[Fixed]
v0.22.3
[v0.22.3] - 2024-03-20
Another small release that adds a new API for RpcModule if one already has the state in an Arc
and a couple of bug fixes.
[Added]
- add
RpcModule::from_arc
(#1324)
[Fixed]
- Revert "fix(server): return err on WS handshake err (#1288)" (#1326)
- export
AlreadyStoppedError
(#1325)
Thanks to the external contributors @mattsse and @aatifsyed who contributed to this release.
v0.22.2
[v0.22.2] - 2024-03-05
This is a small patch release that exposes the connection details to server methods without breaking changes.
Currently, users can only retrieve the connection ID from these details.
We plan to extend this functionality in jsonrpsee v1.0, although this will necessitate a breaking change.
[Added]
- server: Register raw method with connection ID (#1297)
[Changed]
- Update Syn 1.0 -> 2.0 (#1304)
v0.22.1
[v0.22.1] - 2024-02-19
This is a small patch release that internally changes AtomicU64
to AtomicUsize
to support more targets.
[Fixed]
v0.22.0
[v0.22.0] - 2024-02-07
Another breaking release where a new ResponsePayload
type is introduced in order
to make it possible to determine whether a response has been processed.
Unfortunately, the IntoResponse trait
was modified to enable that
and some minor changes were made to make more fields private to avoid further
breakage.
Example of the async ResponsePayload API
#[rpc(server)]
pub trait Api {
#[method(name = "x")]
fn x(&self) -> ResponsePayload<'static, String>;
}
impl RpcServer for () {
fn x(&self) -> ResponsePayload<'static, String> {
let (rp, rp_done) = ResponsePayload::success("ehheeheh".to_string()).notify_on_completion();
tokio::spawn(async move {
if rp_done.await.is_ok() {
do_task_that_depend_x();
}
});
rp
}
}
Roadmap
We are getting closer to releasing jsonrpsee v1.0 and
the following work is planned:
- Native async traits
- Upgrade hyper to v1.0
- Better subscription API for the client.
Thanks to the external contributor @dan-starkware who contributed to this release.
[Added]
- feat(server): add
TowerService::on_session_close
(#1284) - feat(server): async API when
Response
has been processed. (#1281)
[Changed]
v0.21.0
[v0.21.0] - 2023-12-13
This release contains big changes and let's go over the main ones:
JSON-RPC specific middleware
After getting plenty of feedback regarding a JSON-RPC specific middleware,
this release introduces a composable "tower-like" middleware that applies per JSON-RPC method call.
The new middleware also replaces the old RpcLogger
which may break some use-cases, such as if
JSON-RPC was made on a WebSocket or HTTP transport, but it's possible to implement that by
using jsonrpsee as a tower service
or the low-level server API
.
An example how write such middleware:
#[derive(Clone)]
pub struct ModifyRequestIf<S>(S);
impl<'a, S> RpcServiceT<'a> for ModifyRequestIf<S>
where
S: Send + Sync + RpcServiceT<'a>,
{
type Future = S::Future;
fn call(&self, mut req: Request<'a>) -> Self::Future {
// Example how to modify the params in the call.
if req.method == "say_hello" {
// It's a bit awkward to create new params in the request
// but this shows how to do it.
let raw_value = serde_json::value::to_raw_value("myparams").unwrap();
req.params = Some(StdCow::Owned(raw_value));
}
// Re-direct all calls that isn't `say_hello` to `say_goodbye`
else if req.method != "say_hello" {
req.method = "say_goodbye".into();
}
self.0.call(req)
}
}
async fn run_server() {
// Construct our middleware and build the server.
let rpc_middleware = RpcServiceBuilder::new().layer_fn(|service| ModifyRequestIf(service));
let server = Server::builder().set_rpc_middleware(rpc_middleware).build("127.0.0.1:0").await.unwrap();
// Start the server.
let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _| "lo").unwrap();
module.register_method("say_goodbye", |_, _| "goodbye").unwrap();
let handle = server.start(module);
handle.stopped().await;
}
jsonrpsee server as a tower service
For users who want to get full control of the HTTP request, it's now possible to utilize jsonrpsee as a tower service
example here
jsonrpsee server low-level API
For users who want to get low-level access and for example to disconnect
misbehaving peers that is now possible as well example here
Logging in the server
Logging of RPC calls has been disabled by default,
but it's possible to enable that with the RPC logger middleware or provide
your own middleware for that.
let rpc_middleware = RpcServiceBuilder::new().rpc_logger(1024);
let server = Server::builder().set_rpc_middleware(rpc_middleware).build("127.0.0.1:0").await?;
WebSocket ping/pong API
The WebSocket ping/pong APIs have been refactored to be able
to disconnect inactive connections both by from the server and client-side.
Thanks to the external contributors @oleonardolima
and @venugopv who contributed to this release.
[Changed]
- chore(deps): update tokio-rustls requirement from 0.24 to 0.25 (#1256)
- chore(deps): update gloo-net requirement from 0.4.0 to 0.5.0 (#1260)
- chore(deps): update async-lock requirement from 2.4 to 3.0 (#1226)
- chore(deps): update proc-macro-crate requirement from 1 to 2 (#1211)
- chore(deps): update console-subscriber requirement from 0.1.8 to 0.2.0 (#1210)
- refactor: split client and server errors (#1122)
- refactor(ws client): impl tokio:{AsyncRead, AsyncWrite} for EitherStream (#1249)
- refactor(http client): enable all http versions (#1252)
- refactor(server): change ws ping API (#1248)
- refactor(ws client): generic over data stream (#1168)
- refactor(client): unify ws ping/pong API with the server (#1258
- refactor: set
tcp_nodelay == true
by default ([#1263])(#1263)
[Added]
- feat(client): add
disconnect_reason
API (#1246) - feat(server): jsonrpsee as
service
andlow-level API for more fine-grained API to disconnect peers etc
(#1224) - feat(server): JSON-RPC specific middleware (#1215)
- feat(middleware): add
HostFilterLayer::disable
(#1213)
[Fixed]
- fix(host filtering): support hosts with multiple ports (#1227)
v0.20.3
[v0.20.3] - 2023-10-24
This release fixes a cancel-safety issue in the server's graceful shutdown which could lead to high CPU usage.