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
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Field, LitStr};
use super::{Request, RequestField};
use crate::api::{auth_scheme::AuthScheme, util};
impl Request {
pub fn expand_outgoing(&self, ruma_common: &TokenStream) -> TokenStream {
let bytes = quote! { #ruma_common::exports::bytes };
let http = quote! { #ruma_common::exports::http };
let percent_encoding = quote! { #ruma_common::exports::percent_encoding };
let method = &self.method;
let error_ty = &self.error_ty;
let (unstable_path, r0_path, stable_path) = if self.has_path_fields() {
let path_format_args_call_with_percent_encoding = |s: &LitStr| -> TokenStream {
util::path_format_args_call(s.value(), &percent_encoding)
};
(
self.unstable_path.as_ref().map(path_format_args_call_with_percent_encoding),
self.r0_path.as_ref().map(path_format_args_call_with_percent_encoding),
self.stable_path.as_ref().map(path_format_args_call_with_percent_encoding),
)
} else {
(
self.unstable_path.as_ref().map(|path| quote! { format_args!(#path) }),
self.r0_path.as_ref().map(|path| quote! { format_args!(#path) }),
self.stable_path.as_ref().map(|path| quote! { format_args!(#path) }),
)
};
let unstable_path = util::map_option_literal(&unstable_path);
let r0_path = util::map_option_literal(&r0_path);
let stable_path = util::map_option_literal(&stable_path);
let request_query_string = if let Some(field) = self.query_map_field() {
let field_name = field.ident.as_ref().expect("expected field to have identifier");
quote! {{
fn assert_trait_impl<T>(_: &T)
where
T: ::std::iter::IntoIterator<
Item = (::std::string::String, ::std::string::String),
>,
{}
let request_query = RequestQuery(self.#field_name);
assert_trait_impl(&request_query.0);
format_args!(
"?{}",
#ruma_common::serde::urlencoded::to_string(request_query)?
)
}}
} else if self.has_query_fields() {
let request_query_init_fields = struct_init_fields(
self.fields.iter().filter_map(RequestField::as_query_field),
quote! { self },
);
quote! {{
let request_query = RequestQuery {
#request_query_init_fields
};
format_args!(
"?{}",
#ruma_common::serde::urlencoded::to_string(request_query)?
)
}}
} else {
quote! { "" }
};
let mut header_kvs = if self.raw_body_field().is_some() || self.has_body_fields() {
quote! {
req_headers.insert(
#http::header::CONTENT_TYPE,
#http::header::HeaderValue::from_static("application/json"),
);
}
} else {
TokenStream::new()
};
header_kvs.extend(self.header_fields().map(|request_field| {
let (field, header_name) = match request_field {
RequestField::Header(field, header_name) => (field, header_name),
_ => unreachable!("expected request field to be header variant"),
};
let field_name = &field.ident;
match &field.ty {
syn::Type::Path(syn::TypePath { path: syn::Path { segments, .. }, .. })
if segments.last().unwrap().ident == "Option" =>
{
quote! {
if let Some(header_val) = self.#field_name.as_ref() {
req_headers.insert(
#http::header::#header_name,
#http::header::HeaderValue::from_str(header_val)?,
);
}
}
}
_ => quote! {
req_headers.insert(
#http::header::#header_name,
#http::header::HeaderValue::from_str(self.#field_name.as_ref())?,
);
},
}
}));
header_kvs.extend(match self.authentication {
AuthScheme::AccessToken(_) => quote! {
req_headers.insert(
#http::header::AUTHORIZATION,
::std::convert::TryFrom::<_>::try_from(::std::format!(
"Bearer {}",
access_token
.get_required_for_endpoint()
.ok_or(#ruma_common::api::error::IntoHttpError::NeedsAuthentication)?,
))?,
);
},
AuthScheme::None(_) => quote! {
if let Some(access_token) = access_token.get_not_required_for_endpoint() {
req_headers.insert(
#http::header::AUTHORIZATION,
::std::convert::TryFrom::<_>::try_from(
::std::format!("Bearer {}", access_token),
)?
);
}
},
AuthScheme::QueryOnlyAccessToken(_) | AuthScheme::ServerSignatures(_) => quote! {},
});
let request_body = if let Some(field) = self.raw_body_field() {
let field_name = field.ident.as_ref().expect("expected field to have an identifier");
quote! { #ruma_common::serde::slice_to_buf(&self.#field_name) }
} else if self.has_body_fields() {
let initializers = struct_init_fields(self.body_fields(), quote! { self });
quote! {
#ruma_common::serde::json_to_buf(&RequestBody { #initializers })?
}
} else if method == "GET" {
quote! { <T as ::std::default::Default>::default() }
} else {
quote! { #ruma_common::serde::slice_to_buf(b"{}") }
};
let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
let non_auth_impl = matches!(self.authentication, AuthScheme::None(_)).then(|| {
quote! {
#[automatically_derived]
#[cfg(feature = "client")]
impl #impl_generics #ruma_common::api::OutgoingNonAuthRequest
for Request #ty_generics #where_clause {}
}
});
quote! {
#[automatically_derived]
#[cfg(feature = "client")]
impl #impl_generics #ruma_common::api::OutgoingRequest for Request #ty_generics #where_clause {
type EndpointError = #error_ty;
type IncomingResponse = Response;
const METADATA: #ruma_common::api::Metadata = self::METADATA;
fn try_into_http_request<T: ::std::default::Default + #bytes::BufMut>(
self,
base_url: &::std::primitive::str,
access_token: #ruma_common::api::SendAccessToken<'_>,
considering_versions: &'_ [#ruma_common::api::MatrixVersion],
) -> ::std::result::Result<#http::Request<T>, #ruma_common::api::error::IntoHttpError> {
let metadata = self::METADATA;
let mut req_builder = #http::Request::builder()
.method(#http::Method::#method)
.uri(::std::format!(
"{}{}{}",
base_url.strip_suffix('/').unwrap_or(base_url),
#ruma_common::api::select_path(considering_versions, &metadata, #unstable_path, #r0_path, #stable_path)?,
#request_query_string,
));
if let Some(mut req_headers) = req_builder.headers_mut() {
#header_kvs
}
let http_request = req_builder.body(#request_body)?;
Ok(http_request)
}
}
#non_auth_impl
}
}
}
fn struct_init_fields<'a>(
fields: impl IntoIterator<Item = &'a Field>,
src: TokenStream,
) -> TokenStream {
fields
.into_iter()
.map(|field| {
let field_name = field.ident.as_ref().expect("expected field to have an identifier");
let cfg_attrs =
field.attrs.iter().filter(|a| a.path.is_ident("cfg")).collect::<Vec<_>>();
quote! {
#( #cfg_attrs )*
#field_name: #src.#field_name,
}
})
.collect()
}