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
extern crate proc_macro;

use crate::Body::{Form, Json};
use darling::FromMeta;
use proc_macro::TokenStream;
use proc_macro_error::{abort, proc_macro_error};
use quote::quote;
use syn::spanned::Spanned;
use syn::{parse_macro_input, FnArg, Pat};

/// Make a restful http client
///
/// # Examlples
///
/// ```
/// #[client(host = "http://127.0.0.1:3000", path = "/user")]
/// pub trait UserClient {
///     #[get(path = "/find_by_id/<id>")]
///     async fn find_by_id(&self, #[path] id: i64) -> ClientResult<Option<User>>;
///    #[post(path = "/new_user")]
///     async fn new_user(&self, #[json] user: &User) -> Result<Option<String>, Box<dyn std::error::Error>>;
/// }
/// ```
///
#[proc_macro_error(proc_macro_hack)]
#[proc_macro_attribute]
pub fn client(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as syn::AttributeArgs);
    let input = parse_macro_input!(input as syn::ItemTrait);
    let args: ClientArgs = match ClientArgs::from_list(&args) {
        Ok(v) => v,
        Err(e) => return TokenStream::from(e.write_errors()),
    };

    let vis = &input.vis;
    let name = &input.ident;
    let base_host = &match args.host {
        None => String::from(""),
        Some(value) => value,
    };
    let base_path = &args.path;

    let methods = input
        .items
        .iter()
        .filter_map(|item| match item {
            syn::TraitItem::Method(m) => Some(m),
            _ => None,
        })
        .map(|m| gen_method(m));

    let tokens = quote! {
        #vis struct #name {
            host: tokio::sync::Mutex<String>,
            path: String,
        }

        impl #name {

            fn new() -> Self{
                Self{
                    host: tokio::sync::Mutex::new(String::from(#base_host)),
                    path: String::from(#base_path),
                }
            }

            async fn configure_host(&self, host: String) {
                let mut lock = self.host.lock().await;
                *lock = host;
            }

            async fn context(&self) -> String {
                format!("{}{}", self.host.lock().await, self.path)
            }

            #(#methods)*
        }
    };

    tokens.into()
}

/// Gen feign methods
fn gen_method(method: &syn::TraitItemMethod) -> proc_macro2::TokenStream {
    if method.sig.asyncness.is_none() {
        abort!(
            &method.sig.span(),
            "Non-asynchronous calls are not currently supported"
        )
    }

    let name = &method.sig.ident;
    let inputs = &method.sig.inputs;
    let output = &method.sig.output;
    let attr = method.attrs.iter().next();
    let http_method_ident = match attr.map(|a| a.path.get_ident()).flatten() {
        Some(ident) => ident,
        None => {
            abort!(&method.span(), "Expects an http method")
        }
    };

    let _http_method = if let Some(m) = HttpMethod::from_ident(http_method_ident) {
        m
    } else {
        abort!(
            &http_method_ident.span(),
            "Expect one of get, post, put, patch, delete, head."
        )
    };

    let request: Request = match Request::from_meta(&match attr.unwrap().parse_meta() {
        Ok(a) => a,
        Err(err) => return err.into_compile_error(),
    }) {
        Ok(v) => v,
        Err(err) => return TokenStream::from(err.write_errors()).into(),
    };

    let req_path = &request.path;

    let mut path_variables = Vec::new();
    let mut querys = Vec::new();
    let mut body = None;

    match inputs.first() {
        Some(FnArg::Receiver(_)) => {}
        _ => abort!(&method.sig.span(), "first arg must be &self"),
    };

    inputs
        .iter()
        .filter_map(|fn_arg| match fn_arg {
            FnArg::Receiver(_) => None,
            FnArg::Typed(ty) => Some((ty, &ty.attrs.first()?.path.segments.first()?.ident)),
        })
        .for_each(|(ty, p)| match &*p.to_string() {
            "path" => path_variables.push(&ty.pat),
            "query" => querys.push(&ty.pat),
            "json" => match body {
                None => body = Some(Json(&ty.pat)),
                _ => abort!(&method.sig.span(), "json or form only once"),
            },
            "form" => match body {
                None => body = Some(Form(&ty.pat)),
                _ => abort!(&method.sig.span(), "json or form only once"),
            },
            other => abort!(
                &method.sig.span(),
                format!("not allowed param type : {}", other).as_str()
            ),
        });

    let path_variables = if path_variables.is_empty() {
        quote! {}
    } else {
        let mut stream = proc_macro2::TokenStream::new();
        for pv in path_variables {
            let id = format!("<{}>", quote! {#pv});
            stream.extend(quote! {
                .replace(#id, format!("{}", #pv).as_str())
            });
        }
        stream
    };

    let query = if querys.is_empty() {
        quote! {}
    } else {
        quote! {
            .query(&[#(#querys),*])
        }
    };

    let body = match body {
        None => quote! {},
        Some(Form(form)) => quote! {
            .form(#form)
        },
        Some(Json(json)) => quote! {
            .json(#json)
        },
    };

    let params = quote! {
        #query
        #body
    };

    let inputs = inputs
        .iter()
        .filter_map(|fn_arg| match fn_arg {
            FnArg::Receiver(_) => None,
            FnArg::Typed(a) => {
                let mut a = a.clone();
                a.attrs.clear();
                Some(FnArg::Typed(a))
            }
        })
        .collect::<syn::punctuated::Punctuated<_, syn::Token![,]>>();

    quote! {
        pub async fn #name(&self, #inputs) #output {
            let path = String::from(#req_path)#path_variables;
            let url = format!("{}{}", self.context().await, path);
            Ok(reqwest::ClientBuilder::new()
                .build()?
                .#http_method_ident(url.as_str())
                #params
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?)
        }
    }
}

/// http methods enumed
enum HttpMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
    Head,
}

impl HttpMethod {
    fn from_ident(ident: &syn::Ident) -> Option<Self> {
        Some(match &*ident.to_string() {
            "get" => HttpMethod::Get,
            "post" => HttpMethod::Post,
            "put" => HttpMethod::Put,
            "patch" => HttpMethod::Patch,
            "delete" => HttpMethod::Delete,
            "head" => HttpMethod::Head,
            _ => return None,
        })
    }
}

/// body types
enum Body<'a> {
    Form(&'a Box<Pat>),
    Json(&'a Box<Pat>),
}

/// Args of client
#[derive(Debug, FromMeta)]
struct ClientArgs {
    #[darling(default)]
    pub host: Option<String>,
    pub path: String,
}

/// Args of request
#[derive(Debug, FromMeta)]
struct Request {
    pub path: String,
}