1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use std::borrow::Cow;
use crate::attributes::{
optional, parse_param_kind, Aliases, Argument, AttributeMeta, MissingArgument, NameMapping, ParamKind, Resource,
};
use crate::helpers::extract_doc_comments;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::spanned::Spanned;
use syn::{punctuated::Punctuated, Attribute, Token};
#[derive(Debug, Clone)]
pub struct RpcMethod {
pub name: String,
pub blocking: bool,
pub docs: TokenStream2,
pub deprecated: TokenStream2,
pub params: Vec<(syn::PatIdent, syn::Type)>,
pub param_kind: ParamKind,
pub returns: Option<syn::Type>,
pub signature: syn::TraitItemMethod,
pub aliases: Vec<String>,
pub resources: Punctuated<Resource, Token![,]>,
}
impl RpcMethod {
pub fn from_item(attr: Attribute, mut method: syn::TraitItemMethod) -> syn::Result<Self> {
let [aliases, blocking, name, param_kind, resources] =
AttributeMeta::parse(attr)?.retain(["aliases", "blocking", "name", "param_kind", "resources"])?;
let aliases = parse_aliases(aliases)?;
let blocking = optional(blocking, Argument::flag)?.is_some();
let name = name?.string()?;
let param_kind = parse_param_kind(param_kind)?;
let resources = optional(resources, Argument::group)?.unwrap_or_default();
let sig = method.sig.clone();
let docs = extract_doc_comments(&method.attrs);
let deprecated = match find_attr(&method.attrs, "deprecated") {
Some(attr) => quote!(#attr),
None => quote!(),
};
if blocking && sig.asyncness.is_some() {
return Err(syn::Error::new(sig.span(), "Blocking method must be synchronous"));
}
let params: Vec<_> = sig
.inputs
.into_iter()
.filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(arg) => match *arg.pat {
syn::Pat::Ident(name) => Some(Ok((name, *arg.ty))),
syn::Pat::Wild(wild) => Some(Err(syn::Error::new(
wild.underscore_token.span(),
"Method argument names must be valid Rust identifiers; got `_` instead",
))),
_ => Some(Err(syn::Error::new(
arg.span(),
format!("Unexpected method signature input; got {:?} ", *arg.pat),
))),
},
})
.collect::<Result<_, _>>()?;
let returns = match sig.output {
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, output) => Some(*output),
};
method.attrs.clear();
Ok(Self {
aliases,
blocking,
name,
params,
param_kind,
returns,
signature: method,
docs,
resources,
deprecated,
})
}
}
#[derive(Debug, Clone)]
pub struct RpcSubscription {
pub name: String,
pub notif_name_override: Option<String>,
pub docs: TokenStream2,
pub unsubscribe: String,
pub params: Vec<(syn::PatIdent, syn::Type)>,
pub param_kind: ParamKind,
pub item: syn::Type,
pub signature: syn::TraitItemMethod,
pub aliases: Vec<String>,
pub unsubscribe_aliases: Vec<String>,
pub resources: Punctuated<Resource, Token![,]>,
}
impl RpcSubscription {
pub fn from_item(attr: syn::Attribute, mut sub: syn::TraitItemMethod) -> syn::Result<Self> {
let [aliases, item, name, param_kind, unsubscribe, unsubscribe_aliases, resources] =
AttributeMeta::parse(attr)?.retain([
"aliases",
"item",
"name",
"param_kind",
"unsubscribe",
"unsubscribe_aliases",
"resources",
])?;
let aliases = parse_aliases(aliases)?;
let map = name?.value::<NameMapping>()?;
let name = map.name;
let notif_name_override = map.mapped;
let item = item?.value()?;
let param_kind = parse_param_kind(param_kind)?;
let unsubscribe_aliases = parse_aliases(unsubscribe_aliases)?;
let resources = optional(resources, Argument::group)?.unwrap_or_default();
let sig = sub.sig.clone();
let docs = extract_doc_comments(&sub.attrs);
let unsubscribe = match parse_subscribe(unsubscribe)? {
Some(unsub) => unsub,
None => build_unsubscribe_method(&name).unwrap_or_else(||
panic!("Could not generate the unsubscribe method with name '{}'. You need to provide the name manually using the `unsubscribe` attribute in your RPC API definition", name),
),
};
let params: Vec<_> = sig
.inputs
.into_iter()
.filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(arg) => match *arg.pat {
syn::Pat::Ident(name) => Some((name, *arg.ty)),
_ => panic!("Identifier in signature must be an ident"),
},
})
.collect();
sub.attrs.clear();
Ok(Self {
name,
notif_name_override,
unsubscribe,
unsubscribe_aliases,
params,
param_kind,
item,
signature: sub,
aliases,
docs,
resources,
})
}
}
#[derive(Debug)]
pub struct RpcDescription {
pub(crate) jsonrpsee_client_path: Option<TokenStream2>,
pub(crate) jsonrpsee_server_path: Option<TokenStream2>,
pub(crate) needs_server: bool,
pub(crate) needs_client: bool,
pub(crate) namespace: Option<String>,
pub(crate) trait_def: syn::ItemTrait,
pub(crate) methods: Vec<RpcMethod>,
pub(crate) subscriptions: Vec<RpcSubscription>,
pub(crate) client_bounds: Option<Punctuated<syn::WherePredicate, Token![,]>>,
pub(crate) server_bounds: Option<Punctuated<syn::WherePredicate, Token![,]>>,
}
impl RpcDescription {
pub fn from_item(attr: Attribute, mut item: syn::ItemTrait) -> syn::Result<Self> {
let [client, server, namespace, client_bounds, server_bounds] =
AttributeMeta::parse(attr)?.retain(["client", "server", "namespace", "client_bounds", "server_bounds"])?;
let needs_server = optional(server, Argument::flag)?.is_some();
let needs_client = optional(client, Argument::flag)?.is_some();
let namespace = optional(namespace, Argument::string)?;
let client_bounds = optional(client_bounds, Argument::group)?;
let server_bounds = optional(server_bounds, Argument::group)?;
if !needs_server && !needs_client {
return Err(syn::Error::new_spanned(&item.ident, "Either 'server' or 'client' attribute must be applied"));
}
if client_bounds.is_some() && !needs_client {
return Err(syn::Error::new_spanned(
&item.ident,
"Attribute 'client' must be specified with 'client_bounds'",
));
}
if server_bounds.is_some() && !needs_server {
return Err(syn::Error::new_spanned(
&item.ident,
"Attribute 'server' must be specified with 'server_bounds'",
));
}
let jsonrpsee_client_path = crate::helpers::find_jsonrpsee_client_crate().ok();
let jsonrpsee_server_path = crate::helpers::find_jsonrpsee_server_crate().ok();
if needs_client && jsonrpsee_client_path.is_none() {
return Err(syn::Error::new_spanned(&item.ident, "Unable to locate 'jsonrpsee' client dependency"));
}
if needs_server && jsonrpsee_server_path.is_none() {
return Err(syn::Error::new_spanned(&item.ident, "Unable to locate 'jsonrpsee' server dependency"));
}
item.attrs.clear(); let mut methods = Vec::new();
let mut subscriptions = Vec::new();
for entry in item.items.iter() {
if let syn::TraitItem::Method(method) = entry {
if method.sig.receiver().is_none() {
return Err(syn::Error::new_spanned(&method.sig, "First argument of the trait must be '&self'"));
}
let mut is_method = false;
let mut is_sub = false;
if let Some(attr) = find_attr(&method.attrs, "method") {
is_method = true;
let method_data = RpcMethod::from_item(attr.clone(), method.clone())?;
methods.push(method_data);
}
if let Some(attr) = find_attr(&method.attrs, "subscription") {
is_sub = true;
if is_method {
return Err(syn::Error::new_spanned(
&method,
"Element cannot be both subscription and method at the same time",
));
}
if !matches!(method.sig.output, syn::ReturnType::Default) {
return Err(syn::Error::new_spanned(
&method,
"Subscription methods must not return anything; the error must send via subscription via either `SubscriptionSink::reject` or `SubscriptionSink::close`",
));
}
if method.sig.asyncness.is_some() {
return Err(syn::Error::new_spanned(&method, "Subscription methods must not be `async`"));
}
let sub_data = RpcSubscription::from_item(attr.clone(), method.clone())?;
subscriptions.push(sub_data);
}
if !is_method && !is_sub {
return Err(syn::Error::new_spanned(
&method,
"Methods must have either 'method' or 'subscription' attribute",
));
}
} else {
return Err(syn::Error::new_spanned(&entry, "Only methods allowed in RPC traits"));
}
}
if methods.is_empty() && subscriptions.is_empty() {
return Err(syn::Error::new_spanned(&item, "RPC cannot be empty"));
}
Ok(Self {
jsonrpsee_client_path,
jsonrpsee_server_path,
needs_server,
needs_client,
namespace,
trait_def: item,
methods,
subscriptions,
client_bounds,
server_bounds,
})
}
pub fn render(self) -> Result<TokenStream2, syn::Error> {
let server_impl = if self.needs_server { self.render_server()? } else { TokenStream2::new() };
let client_impl = if self.needs_client { self.render_client()? } else { TokenStream2::new() };
Ok(quote! {
#server_impl
#client_impl
})
}
pub(crate) fn jrps_client_item(&self, item: impl quote::ToTokens) -> TokenStream2 {
let jsonrpsee = self.jsonrpsee_client_path.as_ref().unwrap();
quote! { #jsonrpsee::#item }
}
pub(crate) fn jrps_server_item(&self, item: impl quote::ToTokens) -> TokenStream2 {
let jsonrpsee = self.jsonrpsee_server_path.as_ref().unwrap();
quote! { #jsonrpsee::#item }
}
pub(crate) fn rpc_identifier<'a>(&self, method: &'a str) -> Cow<'a, str> {
if let Some(ns) = &self.namespace {
format!("{}_{}", ns, method).into()
} else {
Cow::Borrowed(method)
}
}
}
fn parse_aliases(arg: Result<Argument, MissingArgument>) -> syn::Result<Vec<String>> {
let aliases = optional(arg, Argument::value::<Aliases>)?;
Ok(aliases.map(|a| a.list.into_iter().map(|lit| lit.value()).collect()).unwrap_or_default())
}
fn parse_subscribe(arg: Result<Argument, MissingArgument>) -> syn::Result<Option<String>> {
let unsub = optional(arg, Argument::string)?;
Ok(unsub)
}
fn find_attr<'a>(attrs: &'a [Attribute], ident: &str) -> Option<&'a Attribute> {
attrs.iter().find(|a| a.path.is_ident(ident))
}
fn build_unsubscribe_method(method: &str) -> Option<String> {
method.strip_prefix("subscribe").map(|s| format!("unsubscribe{}", s))
}