Skip to main content

jsonrpsee_proc_macros/
lib.rs

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//! # jsonrpsee-proc-macros
28//!
29//! Vendored from [jsonrpsee](https://github.com/paritytech/jsonrpsee), Copyright (c) 2019-2021
30//! Parity Technologies (UK) Ltd., licensed under the MIT License (see
31//! `crates/rpc/jsonrpsee/LICENSE`).
32
33#![cfg_attr(not(test), warn(unused_crate_dependencies))]
34#![cfg_attr(docsrs, feature(doc_cfg))]
35
36use proc_macro::TokenStream;
37use rpc_macro::RpcDescription;
38
39mod attributes;
40mod helpers;
41mod render_server;
42mod rpc_macro;
43pub(crate) mod visitor;
44
45/// Main RPC macro.
46///
47/// ## Description
48///
49/// This macro generates the server implementation of an RPC trait, a trait mostly equivalent to
50/// the input, with the following differences:
51///
52/// - The trait will have one additional (already implemented) method, `into_rpc`, which turns any
53///   object that implements the server trait into an `RpcModule`.
54/// - For subscription methods:
55///   - There will be one additional argument inserted right after `&self`: `subscription_sink:
56///     SubscriptionSink`. It should be used to accept or reject a subscription and send data back
57///     to the subscribers.
58///   - The return type of the subscription method must implement `IntoSubscriptionCloseResponse`.
59///
60/// For the `Foo` trait, the server trait will be named `FooServer`, which must be implemented on
61/// your type.
62///
63/// Note: you need to import the `jsonrpsee` façade crate in your code for the macro to work
64/// properly.
65///
66/// Parameters are positional: they must be sent as a JSON array, like geth expects. Requests with
67/// object (named) parameters are answered with an invalid params error.
68///
69/// ## Prerequisites
70///
71/// - Implementors of the server trait must be `Sync`, `Send`, `Sized` and `'static`. If you want to
72///   implement this trait on some type that is not thread-safe, consider using `Arc<RwLock<..>>`.
73///
74/// ## Examples
75///
76/// Below you can find examples of the macro usage along with the code
77/// that generated for it by the macro.
78///
79/// ```ignore
80/// #[rpc(server, namespace = "foo", namespace_separator = ".")]
81/// pub trait Rpc {
82///     #[method(name = "foo")]
83///     async fn async_method(&self, param_a: u8, param_b: String) -> u16;
84///     #[method(name = "bar")]
85///     fn sync_method(&self) -> String;
86///
87///     #[subscription(name = "subscribe", item = String)]
88///     async fn sub(&self) -> SubscriptionResult;
89/// }
90/// ```
91///
92/// Server code that will be generated:
93///
94/// ```ignore
95/// pub trait RpcServer {
96///     // RPC methods are normal methods and can be either sync or async. Async methods return a
97///     // `Send` future, implementations can use `async fn`.
98///     fn async_method(&self, param_a: u8, param_b: String) -> impl Future<Output = u16> + Send;
99///     fn sync_method(&self) -> String;
100///
101///     // Note that `pending_subscription_sink` was added automatically.
102///     fn sub(&self, pending: PendingSubscriptionSink) -> impl Future<Output = SubscriptionResult> + Send;
103///
104///     fn into_rpc(self) -> Result<Self, jsonrpsee::core::Error> {
105///         // Actual implementation stripped, but inside we will create
106///         // a module with one method and one subscription
107///     }
108/// }
109/// ```
110///
111/// ## Attributes
112///
113/// ### `rpc` attribute
114///
115/// `rpc` attribute is applied to a trait in order to turn it into an RPC implementation.
116///
117/// **Arguments:**
118///
119/// - `server` (mandatory): generate `<Trait>Server` trait for the server implementation.
120/// - `namespace`: add a prefix to all the methods and subscriptions in this RPC. For example, with
121///   namespace `foo` and method `spam`, the resulting method name will be `foo_spam`.
122/// - `namespace_separator`: customize the separator used between namespace and method name.
123///   Defaults to `_`. For example, `namespace = "foo", namespace_separator = "."` results in method
124///   names like `foo.bar` instead of `foo_bar`.
125/// - `server_bounds`: replace *all* auto-generated trait bounds with the user-defined ones for the
126///   server implementation.
127///
128/// **Trait requirements:**
129///
130/// A trait wrapped with the `rpc` attribute **must not**:
131///
132/// - have associated types or constants;
133/// - have Rust methods not marked with either the `method` or `subscription` attribute;
134/// - be empty.
135///
136/// ### `method` attribute
137///
138/// `method` attribute is used to define an RPC method.
139///
140/// **Arguments:**
141///
142/// - `name` (mandatory): name of the RPC method. Does not have to be the same as the Rust method
143///   name.
144/// - `aliases`: list of name aliases for the RPC method as a comma separated string. Aliases are
145///   processed ignoring the namespace, so add the complete name, including the namespace.
146/// - `blocking`: when set method execution will always spawn on a dedicated thread. Only usable
147///   with non-`async` methods.
148/// - `streaming`: when set the result is sent in parts while it is produced. Only usable with
149///   `async` methods that return `RpcResult<ResponseStream>`, see
150///   `RpcModule::register_streaming_method`.
151///
152/// **Method requirements:**
153///
154/// A Rust method marked with the `method` attribute, **may**:
155///
156/// - be either `async` or not;
157/// - have input parameters or not;
158/// - have a return value or not (in the latter case, it will be considered a notification method).
159///
160/// ### `subscription` attribute
161///
162/// `subscription` attribute is used to define a publish/subscribe interface according to the [ethereum pubsub specification](https://geth.ethereum.org/docs/rpc/pubsub)
163///
164/// **Arguments:**
165///
166/// - `name` (mandatory): name of the RPC method. Does not have to be the same as the Rust method
167///   name.
168/// - `unsubscribe` (optional): name of the RPC method to unsubscribe from the subscription. Must
169///   not be the same as `name`. This is generated for you if the subscription name starts with
170///   `subscribe`.
171/// - `aliases` (optional): aliases for `name`. Aliases are processed ignoring the namespace, so add
172///   the complete name, including the namespace.
173/// - `unsubscribe_aliases` (optional): Similar to `aliases` but for `unsubscribe`.
174/// - `item` (mandatory): type of items yielded by the subscription. Note that it must be the type,
175///   not string.
176///
177/// **Method requirements:**
178///
179/// Rust method marked with the `subscription` attribute **must**:
180///
181/// - be asynchronous;
182/// - return a type that implements `jsonrpsee::server::IntoSubscriptionCloseResponse`.
183///
184/// Rust method marked with `subscription` attribute **may**:
185///
186/// - have input parameters or not.
187///
188/// ## Full workflow example
189///
190/// ```rust
191/// //! Example of using proc macro to generate a working server.
192///
193/// use std::net::SocketAddr;
194///
195/// use jsonrpsee::server::ServerBuilder;
196///
197/// // RPC is put into a separate module to clearly show names of generated entities.
198/// mod rpc_impl {
199///     use jsonrpsee::proc_macros::rpc;
200///     use jsonrpsee::server::{PendingSubscriptionSink, SubscriptionMessage, IntoSubscriptionCloseResponse, SubscriptionCloseResponse};
201///     use jsonrpsee::core::{RpcResult, SubscriptionResult, to_json_raw_value};
202///
203///     pub enum CloseResponse {
204///         None,
205///         Failed,
206///     }
207///
208///     impl IntoSubscriptionCloseResponse for CloseResponse {
209///         fn into_response(self) -> SubscriptionCloseResponse {
210///            match self {
211///                // Do not send a close response when the subscription is terminated.
212///                CloseResponse::None => SubscriptionCloseResponse::None,
213///                // Send a close response as an ordinary subscription notification
214///                // when the subscription is terminated.
215///                CloseResponse::Failed => {
216///                     let err = to_json_raw_value(&"Failed").unwrap();
217///                     SubscriptionCloseResponse::Notif(err.into())
218///                }
219///            }
220///         }
221///     }
222///
223///     // Generate the server implementation, prepend all the methods with `foo_` prefix.
224///     #[rpc(server, namespace = "foo")]
225///     pub trait MyRpc {
226///         #[method(name = "foo")]
227///         async fn async_method(
228///             &self,
229///             param_a: u8,
230///             param_b: String
231///         ) -> RpcResult<u16>;
232///
233///         #[method(name = "bar")]
234///         fn sync_method(&self) -> RpcResult<u16>;
235///
236///         /// Methods can have default implementations, which implementors may leave out.
237///         #[method(name = "baz")]
238///         async fn default_method(&self, param: u16) -> RpcResult<u16> {
239///             Ok(param + self.sync_method()?)
240///         }
241///
242///         /// Override the `foo_sub` and use `foo_subNotif` for the notifications.
243///         ///
244///         /// The item field indicates which type goes into result field below.
245///         ///
246///         /// The notification format:
247///         ///
248///         /// ```
249///         /// {
250///         ///     "jsonrpc":"2.0",
251///         ///     "method":"foo_subNotif",
252///         ///     "params":["subscription":"someID", "result":"some string"]
253///         /// }
254///         /// ```
255///         #[subscription(name = "sub" => "subNotif", unsubscribe = "unsub", item = String)]
256///         async fn sub_override_notif_method(&self) -> SubscriptionResult;
257///
258///         /// Use the same method name for both the `subscribe call` and `notifications`
259///         ///
260///         /// The unsubscribe method name is generated here `foo_unsubscribe`
261///         /// Thus the `unsubscribe attribute` is not needed unless a custom unsubscribe method name is wanted.
262///         ///
263///         /// The notification format:
264///         ///
265///         /// ```
266///         /// {
267///         ///     "jsonrpc":"2.0",
268///         ///     "method":"foo_subscribe",
269///         ///     "params":["subscription":"someID", "result":"some string"]
270///         /// }
271///         /// ```
272///         #[subscription(name = "subscribe", item = String)]
273///         async fn sub(&self) -> SubscriptionResult;
274///
275///         #[subscription(name = "sub_custom_close_msg", unsubscribe = "unsub_custom_close_msg", item = String)]
276///         async fn sub_custom_close_msg(&self) -> CloseResponse;
277///     }
278///
279///     // Structure that will implement the `MyRpcServer` trait.
280///     // It can have fields, if required, as long as it's still `Send + Sync + 'static`.
281///     pub struct RpcServerImpl;
282///
283///     // Note that the trait name we use is `MyRpcServer`, not `MyRpc`!
284///     impl MyRpcServer for RpcServerImpl {
285///         async fn async_method(&self, _param_a: u8, _param_b: String) -> RpcResult<u16> {
286///             Ok(42)
287///         }
288///
289///         fn sync_method(&self) -> RpcResult<u16> {
290///             Ok(10)
291///         }
292///
293///         // The stream API can be used to pipe items from the underlying stream
294///         // as subscription responses.
295///         async fn sub_override_notif_method(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
296///             let mut sink = pending.accept().await?;
297///             let msg = to_json_raw_value(&"Response_A").unwrap();
298///             sink.send(msg).await?;
299///             Ok(())
300///         }
301///
302///         // Send out two values on the subscription.
303///         async fn sub(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
304///             let sink = pending.accept().await?;
305///
306///             let msg1 = to_json_raw_value(&"Response_A").unwrap();
307///             let msg2 = to_json_raw_value(&"Response_B").unwrap();
308///
309///             sink.send(msg1).await?;
310///             sink.send(msg2).await?;
311///
312///             Ok(())
313///         }
314///
315///         // If one doesn't want sent out a close message when a subscription terminates or treat
316///         // errors as subscription error notifications then it's possible to implement
317///         // `IntoSubscriptionCloseResponse` for customized behavior.
318///         async fn sub_custom_close_msg(&self, pending: PendingSubscriptionSink) -> CloseResponse {
319///             let Ok(sink) = pending.accept().await else {
320///                 return CloseResponse::None;
321///             };
322///
323///             let msg = to_json_raw_value(&"Response_A").unwrap();
324///
325///             if sink.send(msg).await.is_ok() {
326///                 CloseResponse::Failed
327///             } else {
328///                 CloseResponse::None
329///             }
330///         }
331///     }
332/// }
333///
334/// // Use the generated server implementation.
335/// use rpc_impl::{MyRpcServer, RpcServerImpl};
336///
337/// pub async fn server() -> SocketAddr {
338///     let server = ServerBuilder::default().build("127.0.0.1:0").await.unwrap();
339///     let addr = server.local_addr().unwrap();
340///     let server_handle = server.start(RpcServerImpl.into_rpc());
341///
342///     // `into_rpc()` method was generated inside of the `RpcServer` trait under the hood.
343///     tokio::spawn(server_handle.stopped());
344///
345///     addr
346/// }
347///
348/// #[tokio::main]
349/// async fn main() {
350///     // The generated `RpcModule` can also be called directly without a transport.
351///     let module = RpcServerImpl.into_rpc();
352///     let (res, _) =
353///         module.raw_json_request(r#"{"jsonrpc":"2.0","method":"foo_bar","id":1}"#, 1).await.unwrap();
354///     assert_eq!(res, r#"{"jsonrpc":"2.0","id":1,"result":10}"#);
355///
356///     server().await;
357/// }
358/// ```
359#[proc_macro_attribute]
360pub fn rpc(attr: TokenStream, item: TokenStream) -> TokenStream {
361    let rebuilt_rpc_attribute = syn::Attribute {
362        pound_token: syn::token::Pound::default(),
363        style: syn::AttrStyle::Outer,
364        bracket_token: syn::token::Bracket::default(),
365        meta: syn::Meta::List(syn::MetaList {
366            path: syn::Ident::new("rpc", proc_macro2::Span::call_site()).into(),
367            delimiter: syn::MacroDelimiter::Paren(
368                syn::token::Paren(proc_macro2::Span::call_site()),
369            ),
370            tokens: attr.into(),
371        }),
372    };
373    match rpc_impl(rebuilt_rpc_attribute, item) {
374        Ok(tokens) => tokens,
375        Err(err) => err.to_compile_error(),
376    }
377    .into()
378}
379
380/// Convenience form of `rpc` that may use `?` for error handling to avoid boilerplate.
381fn rpc_impl(
382    attr: syn::Attribute,
383    item: TokenStream,
384) -> Result<proc_macro2::TokenStream, syn::Error> {
385    let trait_data: syn::ItemTrait = syn::parse(item)?;
386    let rpc = RpcDescription::from_item(attr, trait_data)?;
387    rpc.render()
388}