|
| 1 | +// Copyright 2019-2021 Parity Technologies (UK) Ltd. |
| 2 | +// |
| 3 | +// Permission is hereby granted, free of charge, to any |
| 4 | +// person obtaining a copy of this software and associated |
| 5 | +// documentation files (the "Software"), to deal in the |
| 6 | +// Software without restriction, including without |
| 7 | +// limitation the rights to use, copy, modify, merge, |
| 8 | +// publish, distribute, sublicense, and/or sell copies of |
| 9 | +// the Software, and to permit persons to whom the Software |
| 10 | +// is furnished to do so, subject to the following |
| 11 | +// conditions: |
| 12 | +// |
| 13 | +// The above copyright notice and this permission notice |
| 14 | +// shall be included in all copies or substantial portions |
| 15 | +// of the Software. |
| 16 | +// |
| 17 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF |
| 18 | +// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED |
| 19 | +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 20 | +// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT |
| 21 | +// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 22 | +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 23 | +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR |
| 24 | +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 25 | +// DEALINGS IN THE SOFTWARE. |
| 26 | + |
| 27 | +use std::net::SocketAddr; |
| 28 | + |
| 29 | +use jsonrpsee::core::{async_trait, client::Subscription}; |
| 30 | +use jsonrpsee::proc_macros::rpc; |
| 31 | +use jsonrpsee::server::{PendingSubscriptionSink, Server, SubscriptionMessage}; |
| 32 | +use jsonrpsee::types::ErrorObjectOwned; |
| 33 | +use jsonrpsee::ws_client::WsClientBuilder; |
| 34 | +use jsonrpsee::ConnectionDetails; |
| 35 | + |
| 36 | +#[rpc(server, client)] |
| 37 | +pub trait Rpc { |
| 38 | + /// Raw method with connection ID. |
| 39 | + #[method(name = "connectionIdMethod", raw_method)] |
| 40 | + async fn raw_method(&self, first_param: usize, second_param: u16) -> Result<usize, ErrorObjectOwned>; |
| 41 | + |
| 42 | + /// Normal method call example. |
| 43 | + #[method(name = "normalMethod")] |
| 44 | + fn normal_method(&self, first_param: usize, second_param: u16) -> Result<usize, ErrorObjectOwned>; |
| 45 | + |
| 46 | + /// Subscriptions expose the connection ID on the subscription sink. |
| 47 | + #[subscription(name = "subscribeSync" => "sync", item = usize)] |
| 48 | + fn sub(&self, first_param: usize); |
| 49 | +} |
| 50 | + |
| 51 | +pub struct RpcServerImpl; |
| 52 | + |
| 53 | +#[async_trait] |
| 54 | +impl RpcServer for RpcServerImpl { |
| 55 | + async fn raw_method( |
| 56 | + &self, |
| 57 | + connection_details: ConnectionDetails, |
| 58 | + _first_param: usize, |
| 59 | + _second_param: u16, |
| 60 | + ) -> Result<usize, ErrorObjectOwned> { |
| 61 | + // Return the connection ID from which this method was called. |
| 62 | + Ok(connection_details.id()) |
| 63 | + } |
| 64 | + |
| 65 | + fn normal_method(&self, _first_param: usize, _second_param: u16) -> Result<usize, ErrorObjectOwned> { |
| 66 | + // The normal method does not have access to the connection ID. |
| 67 | + Ok(usize::MAX) |
| 68 | + } |
| 69 | + |
| 70 | + fn sub(&self, pending: PendingSubscriptionSink, _first_param: usize) { |
| 71 | + tokio::spawn(async move { |
| 72 | + // The connection ID can be obtained before or after accepting the subscription |
| 73 | + let pending_connection_id = pending.connection_id(); |
| 74 | + let sink = pending.accept().await.unwrap(); |
| 75 | + let sink_connection_id = sink.connection_id(); |
| 76 | + |
| 77 | + assert_eq!(pending_connection_id, sink_connection_id); |
| 78 | + |
| 79 | + let msg = SubscriptionMessage::from_json(&sink_connection_id).unwrap(); |
| 80 | + sink.send(msg).await.unwrap(); |
| 81 | + }); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +#[tokio::main] |
| 86 | +async fn main() -> anyhow::Result<()> { |
| 87 | + tracing_subscriber::FmtSubscriber::builder() |
| 88 | + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) |
| 89 | + .try_init() |
| 90 | + .expect("setting default subscriber failed"); |
| 91 | + |
| 92 | + let server_addr = run_server().await?; |
| 93 | + let url = format!("ws://{}", server_addr); |
| 94 | + |
| 95 | + let client = WsClientBuilder::default().build(&url).await?; |
| 96 | + let connection_id_first = client.raw_method(1, 2).await.unwrap(); |
| 97 | + |
| 98 | + // Second call from the same connection ID. |
| 99 | + assert_eq!(client.raw_method(1, 2).await.unwrap(), connection_id_first); |
| 100 | + |
| 101 | + // Second client will increment the connection ID. |
| 102 | + let client_second = WsClientBuilder::default().build(&url).await?; |
| 103 | + let connection_id_second = client_second.raw_method(1, 2).await.unwrap(); |
| 104 | + assert_ne!(connection_id_first, connection_id_second); |
| 105 | + |
| 106 | + let mut sub: Subscription<usize> = RpcClient::sub(&client, 0).await.unwrap(); |
| 107 | + assert_eq!(connection_id_first, sub.next().await.transpose().unwrap().unwrap()); |
| 108 | + |
| 109 | + let mut sub: Subscription<usize> = RpcClient::sub(&client_second, 0).await.unwrap(); |
| 110 | + assert_eq!(connection_id_second, sub.next().await.transpose().unwrap().unwrap()); |
| 111 | + |
| 112 | + Ok(()) |
| 113 | +} |
| 114 | + |
| 115 | +async fn run_server() -> anyhow::Result<SocketAddr> { |
| 116 | + let server = Server::builder().build("127.0.0.1:0").await?; |
| 117 | + |
| 118 | + let addr = server.local_addr()?; |
| 119 | + let handle = server.start(RpcServerImpl.into_rpc()); |
| 120 | + |
| 121 | + // In this example we don't care about doing shutdown so let's it run forever. |
| 122 | + // You may use the `ServerHandle` to shut it down or manage it yourself. |
| 123 | + tokio::spawn(handle.stopped()); |
| 124 | + |
| 125 | + Ok(addr) |
| 126 | +} |
0 commit comments