Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(deps): update rust crate jsonrpsee to 0.24.0 - autoclosed #247

Closed
wants to merge 1 commit into from

Conversation

renovate[bot]
Copy link
Contributor

@renovate renovate bot commented Jul 8, 2024

Mend Renovate

This PR contains the following updates:

Package Type Update Change
jsonrpsee (source) dependencies minor 0.20.2 -> 0.24.0

Release Notes

paritytech/jsonrpsee (jsonrpsee)

v0.24.0

Compare Source

A breaking release that mainly changes:

  1. tls feature for the client has been divided into tls and tls-platform-verifier where the tls feature
    will only include rustls and no specific certificate store but the default one is still tls-rustls-platform-verifier.
    This is useful if one wants to avoid bring on openssl dependencies.
  2. Remove dependencies anyhow and beef from the codebase.
[Changed]
  • types: serialize id in Response before result/error fields (#​1421)
  • refactor(client+transport)!: split tls into tls and tls-rustls-platform-verifier features (#​1419)
  • chore(deps): update rustc-hash requirement from 1 to 2 (#​1410)
  • deps: remove anyhow (#​1402)
  • deps: remove beef (#​1401)

v0.23.2

Compare Source

This a small patch release that fixes a couple of bugs and adds a couple of new APIs.

The bug fixes are:

  • The server::ws::on_connect was not working properly due to a merge nit when upgrading to hyper v1.0
    This impacts only users that are using the low-level API and not the server itself.
  • WsTransport::build_with_stream shouldn't not resolve the socket addresses and it's fixed now, see #​1411 for further info.
    This impacts users that are inject their own TcpStream directly into the WsTransport.
[Added]
  • server: add RpcModule::remove (#​1416)
  • server: add capacity and max_capacity to the subscription API (#​1414)
  • server: add PendingSubscriptionSink::method_name (#​1413)
[Fixed]
  • server: make ws::on_connect work again (#​1418)
  • client: WsTransport::build_with_stream don't resolve sockaddrs (#​1412)

v0.23.1

Compare Source

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)

v0.23.0

Compare Source

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 call Subscription::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 and serve_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

Compare Source

A small bug-fix release, see each commit below for further information.

[Fixed]
  • proc macros: collision between generated code name and proc macro API (#​1363)
  • proc-macros: feature server-core compiles without feature server (#​1360)
  • client: add check in max_buffer_capacity_per_subscription that the buffer size > (#​1358)
  • types: Response type ignore unknown fields (#​1353)

v0.22.4

Compare Source

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]
  • client: support batched notifications (#​1327)
  • client: support batched subscription notifs (#​1332)
[Changed]
  • client: downgrade logs from error/warn -> debug (#​1343)
[Fixed]
  • Update MSRV to 1.74.1 in Cargo.toml (#​1338)
  • client: disconnect_reason/read_error is now cancel-safe (#​1347)

v0.22.3

Compare Source

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]
[Fixed]

Thanks to the external contributors @​mattsse and @​aatifsyed who contributed to this release.

v0.22.2

Compare Source

This is a small patch release that exposes the connection details in server method implementations without breaking changes.
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]

v0.22.1

Compare Source

This is a small patch release that internally changes AtomicU64 to AtomicUsize
to support more targets.

[Fixed]
  • fix(docs): part of proc-macro documentation not rendering correctly in IDE (#​1294)
  • fix(client): change to AtomicU64 to AtomicUsize (#​1293)
  • fix(server): low-level API return err on WS handshake err (#​1288)

v0.22.0

Compare Source

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]
  • client(error): make display impl less verbose (#​1283)
  • fix: allow application/json-rpc http content type (#​1277)
  • refactor(rpc_module): RpcModule::raw_json_request -> String (#​1287)

v0.21.0

Compare Source

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])(https://github.com/paritytech/jsonrpsee/pull/1263)
[Added]
  • feat(client): add disconnect_reason API (#​1246)
  • feat(server): jsonrpsee as service and low-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)

Configuration

📅 Schedule: Branch creation - "before 6am on Monday" (UTC), Automerge - At any time (no schedule defined).

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

Copy link

github-actions bot commented Jul 8, 2024

Pull Request Test Coverage Report for Build 10342862154

Details

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • 1 unchanged line in 1 file lost coverage.
  • Overall coverage decreased (-0.02%) to 64.592%

Files with Coverage Reduction New Missed Lines %
common/src/tap/checks/deny_list_check.rs 1 92.73%
Totals Coverage Status
Change from base Build 10342843220: -0.02%
Covered Lines: 3882
Relevant Lines: 6010

💛 - Coveralls

@renovate renovate bot force-pushed the renovate/jsonrpsee-0.x branch 2 times, most recently from 19b6b98 to c851682 Compare July 9, 2024 09:40
@renovate renovate bot changed the title chore(deps): update rust crate jsonrpsee to 0.23.0 chore(deps): update rust crate jsonrpsee to 0.24.0 Jul 9, 2024
@renovate renovate bot force-pushed the renovate/jsonrpsee-0.x branch 5 times, most recently from 9fbb775 to f22ccfa Compare August 1, 2024 15:47
@renovate renovate bot force-pushed the renovate/jsonrpsee-0.x branch 6 times, most recently from 488d051 to 12aff0f Compare August 7, 2024 23:29
@renovate renovate bot changed the title chore(deps): update rust crate jsonrpsee to 0.24.0 chore(deps): update rust crate jsonrpsee to 0.24.0 - autoclosed Aug 12, 2024
@renovate renovate bot closed this Aug 12, 2024
@renovate renovate bot deleted the renovate/jsonrpsee-0.x branch August 12, 2024 20:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0 participants