Skip to main content

jsonrpsee_proc_macros/
render_server.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
27use std::collections::HashSet;
28
29use super::RpcDescription;
30use crate::{
31    helpers::{generate_where_clause, is_option, may_borrow},
32    rpc_macro::RpcFnArg,
33};
34use proc_macro2::{Span, TokenStream as TokenStream2};
35use quote::{quote, quote_spanned};
36
37impl RpcDescription {
38    pub(super) fn render_server(&self) -> Result<TokenStream2, syn::Error> {
39        let trait_name = quote::format_ident!("{}Server", &self.trait_def.ident);
40        let generics = self.trait_def.generics.clone();
41        let (impl_generics, _, where_clause) = generics.split_for_impl();
42
43        let method_impls = self.render_methods()?;
44        let into_rpc_impl = self.render_into_rpc()?;
45
46        // Doc-comment to be associated with the server.
47        let doc_comment =
48            format!("Server trait implementation for the `{}` RPC API.", self.trait_def.ident);
49
50        let trait_impl = quote! {
51            #[doc = #doc_comment]
52            pub trait #trait_name #impl_generics: Sized + Send + Sync + 'static #where_clause {
53                #method_impls
54                #into_rpc_impl
55            }
56        };
57
58        Ok(trait_impl)
59    }
60
61    fn render_methods(&self) -> Result<TokenStream2, syn::Error> {
62        let methods = self.methods.iter().map(|method| {
63            let docs = &method.docs;
64            let mut method_sig = method.signature.clone();
65            desugar_async(&mut method_sig);
66
67            quote! {
68                #docs
69                #method_sig
70            }
71        });
72
73        let subscriptions = self.subscriptions.iter().map(|sub| {
74            let docs = &sub.docs;
75            let subscription_sink_ty = self.jrps_server_item(quote! { PendingSubscriptionSink });
76
77            // Add `SubscriptionSink` as the second input parameter to the signature.
78            let subscription_sink: syn::FnArg =
79                syn::parse_quote!(subscription_sink: #subscription_sink_ty);
80            let mut sub_sig = sub.signature.clone();
81            sub_sig.sig.inputs.insert(1, subscription_sink);
82            desugar_async(&mut sub_sig);
83
84            quote! {
85                #docs
86                #sub_sig
87            }
88        });
89
90        Ok(quote! {
91            #(#methods)*
92            #(#subscriptions)*
93        })
94    }
95
96    /// Helper that will ignore results of `register_*` method calls, and panic if there have been
97    /// any errors in debug builds.
98    ///
99    /// The debug assert is a safeguard should the contract that guarantees the method names to
100    /// never conflict in the macro be broken in the future.
101    fn handle_register_result(&self, tokens: TokenStream2) -> TokenStream2 {
102        let reexports = self.jrps_server_item(quote! { core::__reexports });
103        quote! {{
104            let _res = #tokens;
105            #[cfg(debug_assertions)]
106            if _res.is_err() {
107                #reexports::panic_fail_register();
108            }
109        }}
110    }
111
112    fn render_into_rpc(&self) -> Result<TokenStream2, syn::Error> {
113        let rpc_module = self.jrps_server_item(quote! { RpcModule });
114
115        let mut registered = HashSet::new();
116        let mut errors = Vec::new();
117        let mut check_name = |name: &str, span: Span| {
118            if registered.contains(name) {
119                let message = format!("{name:?} is already defined");
120                errors.push(quote_spanned!(span => compile_error!(#message);));
121            } else {
122                registered.insert(name.to_string());
123            }
124        };
125
126        let methods = self
127            .methods
128            .iter()
129            .map(|method| {
130                // Rust method to invoke (e.g. `self.<foo>(...)`).
131                let rust_method_name = &method.signature.sig.ident;
132                // Name of the RPC method (e.g. `foo_makeSpam`).
133                let rpc_method_name = self.rpc_identifier(&method.name);
134                // Async methods decode their params before the future exists, so the future
135                // doesn't need its own copy of them, unless an argument may borrow from them.
136                let decode_before_future = method.signature.sig.asyncness.is_some() &&
137                    !method.params.iter().any(|arg| may_borrow(&arg.ty));
138                let error_ret = if method.streaming || decode_before_future {
139                    quote! { return Err(e); }
140                } else {
141                    let response_payload = self.jrps_server_item(quote! { ResponsePayload });
142                    quote! { return #response_payload::error(e); }
143                };
144                // `parsing` is the code associated with parsing structure from the
145                // provided `Params` object.
146                // `params_seq` is the comma-delimited sequence of parameters we're passing to the
147                // rust function called..
148                let (parsing, params_seq) = self.render_params_decoding(&method.params, error_ret);
149
150                let into_response = self.jrps_server_item(quote! { IntoResponse });
151
152                check_name(&rpc_method_name, rust_method_name.span());
153
154                if method.streaming {
155                    self.handle_register_result(quote! {
156                        rpc.register_streaming_method(#rpc_method_name, |params, context| async move {
157                            #parsing
158                            context.as_ref().#rust_method_name(#params_seq).await
159                        })
160                    })
161                } else if decode_before_future {
162                    self.handle_register_result(quote! {
163                        rpc.register_async_method_raw(#rpc_method_name, |params, context| {
164                            #parsing
165                            Ok(move || async move {
166                                #into_response::into_response(context.as_ref().#rust_method_name(#params_seq).await)
167                            })
168                        })
169                    })
170                } else if method.signature.sig.asyncness.is_some() {
171                    self.handle_register_result(quote! {
172                        rpc.register_async_method(#rpc_method_name, |params, context| async move {
173                            #parsing
174                            #into_response::into_response(context.as_ref().#rust_method_name(#params_seq).await)
175                        })
176                    })
177                } else if method.blocking {
178                    self.handle_register_result(quote! {
179                        rpc.register_blocking_method(#rpc_method_name, |params, context| {
180                            #parsing
181                            #into_response::into_response(context.#rust_method_name(#params_seq))
182                        })
183                    })
184                } else {
185                    self.handle_register_result(quote! {
186                        rpc.register_method(#rpc_method_name, |params, context| {
187                            #parsing
188                            #into_response::into_response(context.#rust_method_name(#params_seq))
189                        })
190                    })
191                }
192            })
193            .collect::<Vec<_>>();
194
195        let subscriptions = self
196            .subscriptions
197            .iter()
198            .map(|sub| {
199                // Rust method to invoke (e.g. `self.<foo>(...)`).
200                let rust_method_name = &sub.signature.sig.ident;
201                // Name of the RPC method to subscribe to (e.g. `foo_sub`).
202                let rpc_sub_name = self.rpc_identifier(&sub.name);
203                // Name of `method` in the subscription response.
204                let rpc_notif_name_override = sub.notif_name_override.as_ref().map(|m| self.rpc_identifier(m));
205                // Name of the RPC method to unsubscribe (e.g. `foo_sub`).
206                let rpc_unsub_name = self.rpc_identifier(&sub.unsubscribe);
207                // `parsing` is the code associated with parsing structure from the
208                // provided `Params` object.
209                // `params_seq` is the comma-delimited sequence of parameters.
210                let pending = proc_macro2::Ident::new("pending", rust_method_name.span());
211                let sub_err = self.jrps_server_item(quote! { SubscriptionCloseResponse });
212                let reexports = self.jrps_server_item(quote! { core::__reexports });
213                let reject = quote! {
214                    #reexports::tokio::spawn(#pending.reject(e));
215                    return #sub_err::None;
216                };
217                let (parsing, params_seq) = self.render_params_decoding(&sub.params, reject);
218                let into_sub_response = self.jrps_server_item(quote! { IntoSubscriptionCloseResponse });
219
220                check_name(&rpc_sub_name, rust_method_name.span());
221                check_name(&rpc_unsub_name, rust_method_name.span());
222
223                let rpc_notif_name = match rpc_notif_name_override {
224                    Some(notif) => {
225                        check_name(&notif, rust_method_name.span());
226                        notif
227                    }
228                    None => rpc_sub_name.clone(),
229                };
230
231                if sub.signature.sig.asyncness.is_some() {
232                    self.handle_register_result(quote! {
233                        rpc.register_subscription(#rpc_sub_name, #rpc_notif_name, #rpc_unsub_name, |params, mut pending, context| async move {
234                            #parsing
235                            #into_sub_response::into_response(context.as_ref().#rust_method_name(pending, #params_seq).await)
236                        })
237                    })
238                } else {
239                    self.handle_register_result(quote! {
240                        rpc.register_subscription_raw(#rpc_sub_name, #rpc_notif_name, #rpc_unsub_name, |params, mut pending, context| {
241                            #parsing
242                            let _ = context.as_ref().#rust_method_name(pending, #params_seq);
243                            #sub_err::None
244                        })
245                    })
246                }
247            })
248            .collect::<Vec<_>>();
249
250        let method_aliases = self
251            .methods
252            .iter()
253            .map(|method| {
254                let rpc_name = self.rpc_identifier(&method.name);
255                let rust_method_name = &method.signature.sig.ident;
256
257                // Rust method to invoke (e.g. `self.<foo>(...)`).
258                let aliases: Vec<TokenStream2> = method
259                    .aliases
260                    .iter()
261                    .map(|alias| {
262                        check_name(alias, rust_method_name.span());
263                        self.handle_register_result(quote! {
264                            rpc.register_alias(#alias, #rpc_name)
265                        })
266                    })
267                    .collect();
268
269                quote!( #(#aliases)* )
270            })
271            .collect::<Vec<_>>();
272
273        let subscription_aliases = self
274            .subscriptions
275            .iter()
276            .map(|method| {
277                let sub_name = self.rpc_identifier(&method.name);
278                let unsub_name = self.rpc_identifier(&method.unsubscribe);
279                let rust_method_name = &method.signature.sig.ident;
280
281                let sub: Vec<TokenStream2> = method
282                    .aliases
283                    .iter()
284                    .map(|alias| {
285                        check_name(alias, rust_method_name.span());
286                        self.handle_register_result(quote! {
287                            rpc.register_alias(#alias, #sub_name)
288                        })
289                    })
290                    .collect();
291                let unsub: Vec<TokenStream2> = method
292                    .unsubscribe_aliases
293                    .iter()
294                    .map(|alias| {
295                        check_name(alias, rust_method_name.span());
296                        self.handle_register_result(quote! {
297                            rpc.register_alias(#alias, #unsub_name)
298                        })
299                    })
300                    .collect();
301
302                quote! (
303                    #(#sub)*
304                    #(#unsub)*
305                )
306            })
307            .collect::<Vec<_>>();
308
309        let doc_comment = "Collects all the methods and subscriptions defined in the trait \
310                                and adds them into a single `RpcModule`.";
311
312        let sub_tys: Vec<syn::Type> =
313            self.subscriptions.clone().into_iter().map(|s| s.item).collect();
314        let where_clause =
315            generate_where_clause(&self.trait_def, &sub_tys, self.server_bounds.as_ref());
316
317        // NOTE(niklasad1): empty where clause is valid rust syntax.
318        Ok(quote! {
319            #[doc = #doc_comment]
320            fn into_rpc(self) -> #rpc_module<Self> where #(#where_clause,)* {
321                let mut rpc = #rpc_module::new(self);
322
323                #(#errors)*
324                #(#methods)*
325                #(#subscriptions)*
326                #(#method_aliases)*
327                #(#subscription_aliases)*
328
329                rpc
330            }
331        })
332    }
333
334    /// `error_ret` is the code that handles an argument that fails to decode, as `e`.
335    fn render_params_decoding(
336        &self,
337        params: &[RpcFnArg],
338        error_ret: TokenStream2,
339    ) -> (TokenStream2, TokenStream2) {
340        if params.is_empty() {
341            return (TokenStream2::default(), TokenStream2::default());
342        }
343
344        let params_fields_seq = params.iter().map(RpcFnArg::arg_pat);
345        let params_fields = quote! { #(#params_fields_seq),* };
346
347        let reexports = self.jrps_server_item(quote! { core::__reexports });
348
349        // Code to decode sequence of parameters from a JSON array.
350        let decode_array = {
351            let decode_fields = params.iter().map(|RpcFnArg { arg_pat, ty, .. }| {
352                let is_option = is_option(ty);
353                let next_method = if is_option { quote!(optional_next) } else { quote!(next) };
354                quote! {
355                    let #arg_pat: #ty = match seq.#next_method() {
356                        Ok(v) => v,
357                        Err(e) => {
358                            #reexports::log_fail_parse(stringify!(#arg_pat), stringify!(#ty), &e, #is_option);
359                            #error_ret
360                        }
361                    };
362                }
363            });
364
365            // Move the raw params into the decoding block so they are freed once decoded, instead
366            // of living as long as a blocking call or subscription future. Arguments that may
367            // borrow from the params need them to outlive the call.
368            let free_params = (!params.iter().any(|arg| may_borrow(&arg.ty)))
369                .then(|| quote! { let params = params; });
370
371            quote! {
372                #free_params
373                let mut seq = params.sequence();
374                #(#decode_fields);*
375                (#params_fields)
376            }
377        };
378
379        // Parameters are positional, like geth: object (named) params fail to parse as an array.
380        let parsing = quote! {
381            let (#params_fields) = {
382                #decode_array
383            };
384        };
385
386        (parsing, params_fields)
387    }
388}
389
390/// Turns `async fn f(..) -> R` into `fn f(..) -> impl Future<Output = R> + Send`.
391///
392/// The server trait stays usable from the `Send` futures that `RpcModule` registers, without boxing
393/// every call the way `async_trait` does. Implementations can still use `async fn`.
394fn desugar_async(method: &mut syn::TraitItemFn) {
395    let sig = &mut method.sig;
396    if sig.asyncness.take().is_none() {
397        return;
398    }
399    let output = match &sig.output {
400        syn::ReturnType::Default => quote! { () },
401        syn::ReturnType::Type(_, ty) => quote! { #ty },
402    };
403    sig.output = syn::parse_quote! {
404        -> impl ::core::future::Future<Output = #output> + ::core::marker::Send
405    };
406    // A default body becomes the body of the returned future.
407    if let Some(body) = &mut method.default {
408        *body = syn::parse_quote!({ async move #body });
409    }
410}