Skip to main content

jsonrpsee_proc_macros/
rpc_macro.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//! Declaration of the JSON RPC generator procedural macros.
28
29use std::borrow::Cow;
30
31use crate::{
32    attributes::{optional, Aliases, Argument, AttributeMeta, MissingArgument, NameMapping},
33    helpers::extract_doc_comments,
34};
35use proc_macro2::TokenStream as TokenStream2;
36use quote::quote;
37use syn::{punctuated::Punctuated, spanned::Spanned, Attribute, Token};
38
39/// Represents a single argument in a RPC call.
40///
41/// stores modifications based on attributes
42#[derive(Debug, Clone)]
43pub struct RpcFnArg {
44    pub(crate) arg_pat: syn::PatIdent,
45    pub(crate) ty: syn::Type,
46}
47
48impl RpcFnArg {
49    /// Return the pattern identifier of the argument.
50    pub fn arg_pat(&self) -> &syn::PatIdent {
51        &self.arg_pat
52    }
53}
54
55#[derive(Debug, Clone)]
56pub struct RpcMethod {
57    pub name: String,
58    pub blocking: bool,
59    pub streaming: bool,
60    pub docs: TokenStream2,
61    pub params: Vec<RpcFnArg>,
62    pub signature: syn::TraitItemFn,
63    pub aliases: Vec<String>,
64}
65
66impl RpcMethod {
67    pub fn from_item(attr: Attribute, mut method: syn::TraitItemFn) -> syn::Result<Self> {
68        let [aliases, blocking, name, streaming] =
69            AttributeMeta::parse(attr)?.retain(["aliases", "blocking", "name", "streaming"])?;
70
71        let aliases = parse_aliases(aliases)?;
72        let blocking = optional(blocking, Argument::flag)?.is_some();
73        let name = name?.string()?;
74        let streaming = optional(streaming, Argument::flag)?.is_some();
75
76        let docs = extract_doc_comments(&method.attrs);
77
78        if blocking && method.sig.asyncness.is_some() {
79            return Err(syn::Error::new(method.sig.span(), "Blocking method must be synchronous"));
80        }
81        if streaming && method.sig.asyncness.is_none() {
82            return Err(syn::Error::new(method.sig.span(), "Streaming method must be asynchronous"));
83        }
84
85        let params: Vec<_> = method
86            .sig
87            .inputs
88            .iter()
89            .filter_map(|arg| match arg {
90                syn::FnArg::Receiver(_) => None,
91                syn::FnArg::Typed(arg) => match &*arg.pat {
92                    syn::Pat::Ident(name) => {
93                        Some(Ok(RpcFnArg { arg_pat: name.clone(), ty: (*arg.ty).clone() }))
94                    }
95                    syn::Pat::Wild(wild) => Some(Err(syn::Error::new(
96                        wild.underscore_token.span(),
97                        "Method argument names must be valid Rust identifiers; got `_` instead",
98                    ))),
99                    _ => Some(Err(syn::Error::new(
100                        arg.span(),
101                        format!("Unexpected method signature input; got {:?} ", *arg.pat),
102                    ))),
103                },
104            })
105            .collect::<Result<_, _>>()?;
106
107        // We've analyzed attributes and don't need them anymore.
108        method.attrs.clear();
109
110        Ok(Self { aliases, blocking, streaming, name, params, signature: method, docs })
111    }
112}
113
114#[derive(Debug, Clone)]
115pub struct RpcSubscription {
116    pub name: String,
117    /// When subscribing to an RPC, users can override the content of the `method` field
118    /// in the JSON data sent to subscribers.
119    /// Each subscription thus has one method name to set up the subscription,
120    /// one to unsubscribe and, optionally, a third method name used to describe the
121    /// payload (aka "notification") sent back from the server to subscribers.
122    /// If no override is provided, the subscription method name is used.
123    pub notif_name_override: Option<String>,
124    pub docs: TokenStream2,
125    pub unsubscribe: String,
126    pub params: Vec<RpcFnArg>,
127    pub item: syn::Type,
128    pub signature: syn::TraitItemFn,
129    pub aliases: Vec<String>,
130    pub unsubscribe_aliases: Vec<String>,
131}
132
133impl RpcSubscription {
134    pub fn from_item(attr: syn::Attribute, mut sub: syn::TraitItemFn) -> syn::Result<Self> {
135        let [aliases, item, name, unsubscribe, unsubscribe_aliases] = AttributeMeta::parse(attr)?
136            .retain([
137            "aliases",
138            "item",
139            "name",
140            "unsubscribe",
141            "unsubscribe_aliases",
142        ])?;
143
144        let aliases = parse_aliases(aliases)?;
145        let map = name?.value::<NameMapping>()?;
146        let name = map.name;
147        let notif_name_override = map.mapped;
148        let item = item?.value()?;
149        let unsubscribe_aliases = parse_aliases(unsubscribe_aliases)?;
150
151        let docs = extract_doc_comments(&sub.attrs);
152        let unsubscribe = match parse_subscribe(unsubscribe)? {
153            Some(unsub) => unsub,
154            None => build_unsubscribe_method(&name).unwrap_or_else(||
155                panic!("Could not generate the unsubscribe method with name '{name}'. You need to provide the name manually using the `unsubscribe` attribute in your RPC API definition"),
156            ),
157        };
158
159        let params: Vec<_> = sub
160            .sig
161            .inputs
162            .iter()
163            .filter_map(|arg| match arg {
164                syn::FnArg::Receiver(_) => None,
165                syn::FnArg::Typed(arg) => match &*arg.pat {
166                    syn::Pat::Ident(name) => {
167                        Some(RpcFnArg { arg_pat: name.clone(), ty: (*arg.ty).clone() })
168                    }
169                    _ => panic!("Identifier in signature must be an ident"),
170                },
171            })
172            .collect();
173
174        // We've analyzed attributes and don't need them anymore.
175        sub.attrs.clear();
176
177        Ok(Self {
178            name,
179            notif_name_override,
180            unsubscribe,
181            unsubscribe_aliases,
182            params,
183            item,
184            signature: sub,
185            aliases,
186            docs,
187        })
188    }
189}
190
191#[derive(Debug)]
192pub struct RpcDescription {
193    /// Path to the `jsonrpsee` server types part.
194    pub(crate) jsonrpsee_server_path: TokenStream2,
195    /// Optional prefix for RPC namespace.
196    pub(crate) namespace: Option<String>,
197    /// Optional separator between namespace and method name. Defaults to `_`.
198    pub(crate) namespace_separator: Option<String>,
199    /// Trait definition in which all the attributes were stripped.
200    pub(crate) trait_def: syn::ItemTrait,
201    /// List of RPC methods defined in the trait.
202    pub(crate) methods: Vec<RpcMethod>,
203    /// List of RPC subscriptions defined in the trait.
204    pub(crate) subscriptions: Vec<RpcSubscription>,
205    /// Optional user defined trait bounds for the server implementation.
206    pub(crate) server_bounds: Option<Punctuated<syn::WherePredicate, Token![,]>>,
207}
208
209impl RpcDescription {
210    pub fn from_item(attr: Attribute, mut item: syn::ItemTrait) -> syn::Result<Self> {
211        let [server, namespace, namespace_separator, server_bounds] = AttributeMeta::parse(attr)?
212            .retain([
213            "server",
214            "namespace",
215            "namespace_separator",
216            "server_bounds",
217        ])?;
218
219        // Only the server trait is generated, but the flag stays required so that the attribute
220        // spells out what it produces.
221        if optional(server, Argument::flag)?.is_none() {
222            return Err(syn::Error::new_spanned(
223                &item.ident,
224                "The 'server' attribute must be applied",
225            ));
226        }
227        let namespace = optional(namespace, Argument::string)?;
228        let namespace_separator = optional(namespace_separator, Argument::string)?;
229        let server_bounds = optional(server_bounds, Argument::group)?;
230
231        let Ok(jsonrpsee_server_path) = crate::helpers::find_jsonrpsee_server_crate() else {
232            return Err(syn::Error::new_spanned(
233                &item.ident,
234                "Unable to locate 'jsonrpsee' server dependency",
235            ));
236        };
237
238        item.attrs.clear(); // Remove RPC attributes.
239
240        let mut methods = Vec::new();
241        let mut subscriptions = Vec::new();
242
243        // Go through all the methods in the trait and collect methods and
244        // subscriptions.
245        for entry in item.items.iter() {
246            if let syn::TraitItem::Fn(method) = entry {
247                if method.sig.receiver().is_none() {
248                    return Err(syn::Error::new_spanned(
249                        &method.sig,
250                        "First argument of the trait must be '&self'",
251                    ));
252                }
253
254                let mut is_method = false;
255                let mut is_sub = false;
256                if let Some(attr) = find_attr(&method.attrs, "method") {
257                    is_method = true;
258
259                    let method_data = RpcMethod::from_item(attr.clone(), method.clone())?;
260
261                    methods.push(method_data);
262                }
263                if let Some(attr) = find_attr(&method.attrs, "subscription") {
264                    is_sub = true;
265                    if is_method {
266                        return Err(syn::Error::new_spanned(
267                            method,
268                            "Element cannot be both subscription and method at the same time",
269                        ));
270                    }
271
272                    let sub_data = RpcSubscription::from_item(attr.clone(), method.clone())?;
273                    subscriptions.push(sub_data);
274                }
275
276                if !is_method && !is_sub {
277                    return Err(syn::Error::new_spanned(
278                        method,
279                        "Methods must have either 'method' or 'subscription' attribute",
280                    ));
281                }
282            } else {
283                return Err(syn::Error::new_spanned(entry, "Only methods allowed in RPC traits"));
284            }
285        }
286
287        if methods.is_empty() && subscriptions.is_empty() {
288            return Err(syn::Error::new_spanned(&item, "RPC cannot be empty"));
289        }
290
291        Ok(Self {
292            jsonrpsee_server_path,
293            namespace,
294            namespace_separator,
295            trait_def: item,
296            methods,
297            subscriptions,
298            server_bounds,
299        })
300    }
301
302    pub fn render(self) -> Result<TokenStream2, syn::Error> {
303        self.render_server()
304    }
305
306    /// Formats the identifier as a path relative to the resolved
307    /// `jsonrpsee` server path.
308    pub(crate) fn jrps_server_item(&self, item: impl quote::ToTokens) -> TokenStream2 {
309        let jsonrpsee = &self.jsonrpsee_server_path;
310        quote! { #jsonrpsee::#item }
311    }
312
313    /// Based on the namespace and separator, renders the full name of the RPC method/subscription.
314    /// Examples:
315    /// For namespace `foo`, method `makeSpam`, and separator `_`, result will be `foo_makeSpam`.
316    /// For separator `.`, result will be `foo.makeSpam`.
317    /// For no namespace, returns just `makeSpam`.
318    pub(crate) fn rpc_identifier<'a>(&self, method: &'a str) -> Cow<'a, str> {
319        if let Some(ns) = &self.namespace {
320            let sep = self.namespace_separator.as_deref().unwrap_or("_");
321            format!("{ns}{sep}{method}").into()
322        } else {
323            Cow::Borrowed(method)
324        }
325    }
326}
327
328fn parse_aliases(arg: Result<Argument, MissingArgument>) -> syn::Result<Vec<String>> {
329    let aliases = optional(arg, Argument::value::<Aliases>)?;
330
331    Ok(aliases.map(|a| a.list.into_iter().map(|lit| lit.value()).collect()).unwrap_or_default())
332}
333
334fn parse_subscribe(arg: Result<Argument, MissingArgument>) -> syn::Result<Option<String>> {
335    let unsub = optional(arg, Argument::string)?;
336
337    Ok(unsub)
338}
339
340fn find_attr<'a>(attrs: &'a [Attribute], ident: &str) -> Option<&'a Attribute> {
341    attrs.iter().find(|a| a.path().is_ident(ident))
342}
343
344fn build_unsubscribe_method(method: &str) -> Option<String> {
345    method.strip_prefix("subscribe").map(|s| format!("unsubscribe{s}"))
346}