-
Notifications
You must be signed in to change notification settings - Fork 69
/
method.rs
2442 lines (2237 loc) · 89.1 KB
/
method.rs
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024 Oxide Computer Company
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
str::FromStr,
};
use openapiv3::{Components, Parameter, ReferenceOr, Response, StatusCode};
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use typify::{TypeId, TypeSpace};
use crate::{
template::PathTemplate,
util::{items, parameter_map, sanitize, unique_ident_from, Case},
Error, Generator, Result, TagStyle,
};
use crate::{to_schema::ToSchema, util::ReferenceOrExt};
/// The intermediate representation of an operation that will become a method.
pub(crate) struct OperationMethod {
pub operation_id: String,
pub tags: Vec<String>,
pub method: HttpMethod,
pub path: PathTemplate,
pub summary: Option<String>,
pub description: Option<String>,
pub params: Vec<OperationParameter>,
pub responses: Vec<OperationResponse>,
pub dropshot_paginated: Option<DropshotPagination>,
dropshot_websocket: bool,
}
pub enum HttpMethod {
Get,
Put,
Post,
Delete,
Options,
Head,
Patch,
Trace,
}
impl std::str::FromStr for HttpMethod {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"get" => Ok(Self::Get),
"put" => Ok(Self::Put),
"post" => Ok(Self::Post),
"delete" => Ok(Self::Delete),
"options" => Ok(Self::Options),
"head" => Ok(Self::Head),
"patch" => Ok(Self::Patch),
"trace" => Ok(Self::Trace),
_ => Err(Error::InternalError(format!("bad method: {}", s))),
}
}
}
impl HttpMethod {
fn as_str(&self) -> &'static str {
match self {
HttpMethod::Get => "get",
HttpMethod::Put => "put",
HttpMethod::Post => "post",
HttpMethod::Delete => "delete",
HttpMethod::Options => "options",
HttpMethod::Head => "head",
HttpMethod::Patch => "patch",
HttpMethod::Trace => "trace",
}
}
}
struct MethodSigBody {
success: TokenStream,
error: TokenStream,
body: TokenStream,
}
struct BuilderImpl {
doc: String,
sig: TokenStream,
body: TokenStream,
}
pub struct DropshotPagination {
pub item: TypeId,
pub first_page_params: Vec<String>,
}
pub struct OperationParameter {
/// Sanitized parameter name.
pub name: String,
/// Original parameter name provided by the API.
pub api_name: String,
pub description: Option<String>,
pub typ: OperationParameterType,
pub kind: OperationParameterKind,
}
#[derive(Eq, PartialEq)]
pub enum OperationParameterType {
Type(TypeId),
RawBody,
}
#[derive(Debug, PartialEq, Eq)]
pub enum OperationParameterKind {
Path,
Query(bool),
Header(bool),
// TODO bodies may be optional
Body(BodyContentType),
}
impl OperationParameterKind {
fn is_required(&self) -> bool {
match self {
OperationParameterKind::Path => true,
OperationParameterKind::Query(required) => *required,
OperationParameterKind::Header(required) => *required,
// TODO may be optional
OperationParameterKind::Body(_) => true,
}
}
fn is_optional(&self) -> bool {
!self.is_required()
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum BodyContentType {
OctetStream,
Json,
FormUrlencoded,
Text(String),
}
impl FromStr for BodyContentType {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let offset = s.find(';').unwrap_or(s.len());
match &s[..offset] {
"application/octet-stream" => Ok(Self::OctetStream),
"application/json" => Ok(Self::Json),
"application/x-www-form-urlencoded" => Ok(Self::FormUrlencoded),
"text/plain" | "text/x-markdown" => {
Ok(Self::Text(String::from(&s[..offset])))
}
_ => Err(Error::UnexpectedFormat(format!(
"unexpected content type: {}",
s
))),
}
}
}
impl std::fmt::Display for BodyContentType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::OctetStream => "application/octet-stream",
Self::Json => "application/json",
Self::FormUrlencoded => "application/x-www-form-urlencoded",
Self::Text(typ) => typ,
})
}
}
#[derive(Debug)]
pub(crate) struct OperationResponse {
pub status_code: OperationResponseStatus,
pub typ: OperationResponseKind,
// TODO this isn't currently used because dropshot doesn't give us a
// particularly useful message here.
#[allow(dead_code)]
description: Option<String>,
}
impl Eq for OperationResponse {}
impl PartialEq for OperationResponse {
fn eq(&self, other: &Self) -> bool {
self.status_code == other.status_code
}
}
impl Ord for OperationResponse {
fn cmp(&self, other: &Self) -> Ordering {
self.status_code.cmp(&other.status_code)
}
}
impl PartialOrd for OperationResponse {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) enum OperationResponseStatus {
Code(u16),
Range(u16),
Default,
}
impl OperationResponseStatus {
fn to_value(&self) -> u16 {
match self {
OperationResponseStatus::Code(code) => {
assert!(*code < 1000);
*code
}
OperationResponseStatus::Range(range) => {
assert!(*range < 10);
*range * 100
}
OperationResponseStatus::Default => 1000,
}
}
pub fn is_success_or_default(&self) -> bool {
matches!(
self,
OperationResponseStatus::Default
| OperationResponseStatus::Code(101)
| OperationResponseStatus::Code(200..=299)
| OperationResponseStatus::Range(2)
)
}
pub fn is_error_or_default(&self) -> bool {
matches!(
self,
OperationResponseStatus::Default
| OperationResponseStatus::Code(400..=599)
| OperationResponseStatus::Range(4..=5)
)
}
pub fn is_default(&self) -> bool {
matches!(self, OperationResponseStatus::Default)
}
}
impl Ord for OperationResponseStatus {
fn cmp(&self, other: &Self) -> Ordering {
self.to_value().cmp(&other.to_value())
}
}
impl PartialOrd for OperationResponseStatus {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub(crate) enum OperationResponseKind {
Type(TypeId),
None,
Raw,
Upgrade,
}
impl OperationResponseKind {
pub fn into_tokens(self, type_space: &TypeSpace) -> TokenStream {
match self {
OperationResponseKind::Type(ref type_id) => {
let type_name = type_space.get_type(type_id).unwrap().ident();
quote! { #type_name }
}
OperationResponseKind::None => {
quote! { () }
}
OperationResponseKind::Raw => {
quote! { ByteStream }
}
OperationResponseKind::Upgrade => {
quote! { reqwest::Upgraded }
}
}
}
}
impl Generator {
pub(crate) fn process_operation(
&mut self,
operation: &openapiv3::Operation,
components: &Option<Components>,
path: &str,
method: &str,
path_parameters: &[ReferenceOr<Parameter>],
) -> Result<OperationMethod> {
let operation_id = operation.operation_id.as_ref().unwrap();
let mut combined_path_parameters =
parameter_map(path_parameters, components)?;
for operation_param in items(&operation.parameters, components) {
let parameter = operation_param?;
combined_path_parameters
.insert(¶meter.parameter_data_ref().name, parameter);
}
// Filter out any path parameters that have been overridden by an
// operation parameter
let mut params = combined_path_parameters
.values()
.map(|parameter| {
match parameter {
openapiv3::Parameter::Path {
parameter_data,
style: openapiv3::PathStyle::Simple,
} => {
// Path parameters MUST be required.
assert!(parameter_data.required);
let schema = parameter_data.schema()?.to_schema();
let name = sanitize(
&format!(
"{}-{}",
operation_id, ¶meter_data.name
),
Case::Pascal,
);
let typ = self
.type_space
.add_type_with_name(&schema, Some(name))?;
Ok(OperationParameter {
name: sanitize(¶meter_data.name, Case::Snake),
api_name: parameter_data.name.clone(),
description: parameter_data.description.clone(),
typ: OperationParameterType::Type(typ),
kind: OperationParameterKind::Path,
})
}
openapiv3::Parameter::Query {
parameter_data,
allow_reserved: _, // We always encode reserved chars
style: openapiv3::QueryStyle::Form,
allow_empty_value: _, // Irrelevant for this client
} => {
let schema = parameter_data.schema()?.to_schema();
let name = sanitize(
&format!(
"{}-{}",
operation.operation_id.as_ref().unwrap(),
¶meter_data.name,
),
Case::Pascal,
);
let type_id = self
.type_space
.add_type_with_name(&schema, Some(name))?;
let ty = self.type_space.get_type(&type_id).unwrap();
// If the type is itself optional, then we'll treat it
// as optional (irrespective of the `required` field on
// the parameter) and use the "inner" type.
let details = ty.details();
let (type_id, required) =
if let typify::TypeDetails::Option(inner_type_id) =
details
{
(inner_type_id, false)
} else {
(type_id, parameter_data.required)
};
Ok(OperationParameter {
name: sanitize(¶meter_data.name, Case::Snake),
api_name: parameter_data.name.clone(),
description: parameter_data.description.clone(),
typ: OperationParameterType::Type(type_id),
kind: OperationParameterKind::Query(required),
})
}
openapiv3::Parameter::Header {
parameter_data,
style: openapiv3::HeaderStyle::Simple,
} => {
let schema = parameter_data.schema()?.to_schema();
let name = sanitize(
&format!(
"{}-{}",
operation.operation_id.as_ref().unwrap(),
¶meter_data.name,
),
Case::Pascal,
);
let typ = self
.type_space
.add_type_with_name(&schema, Some(name))?;
Ok(OperationParameter {
name: sanitize(¶meter_data.name, Case::Snake),
api_name: parameter_data.name.clone(),
description: parameter_data.description.clone(),
typ: OperationParameterType::Type(typ),
kind: OperationParameterKind::Header(
parameter_data.required,
),
})
}
openapiv3::Parameter::Path { style, .. } => {
Err(Error::UnexpectedFormat(format!(
"unsupported style of path parameter {:#?}",
style,
)))
}
openapiv3::Parameter::Query { style, .. } => {
Err(Error::UnexpectedFormat(format!(
"unsupported style of query parameter {:#?}",
style,
)))
}
cookie @ openapiv3::Parameter::Cookie { .. } => {
Err(Error::UnexpectedFormat(format!(
"cookie parameters are not supported {:#?}",
cookie,
)))
}
}
})
.collect::<Result<Vec<_>>>()?;
let dropshot_websocket =
operation.extensions.get("x-dropshot-websocket").is_some();
if dropshot_websocket {
self.uses_websockets = true;
}
if let Some(body_param) = self.get_body_param(operation, components)? {
params.push(body_param);
}
let tmp = crate::template::parse(path)?;
let names = tmp.names();
sort_params(&mut params, &names);
let mut success = false;
let mut responses = operation
.responses
.default
.iter()
.map(|response_or_ref| {
Ok((
OperationResponseStatus::Default,
response_or_ref.item(components)?,
))
})
.chain(operation.responses.responses.iter().map(
|(status_code, response_or_ref)| {
Ok((
match status_code {
StatusCode::Code(code) => {
OperationResponseStatus::Code(*code)
}
StatusCode::Range(range) => {
OperationResponseStatus::Range(*range)
}
},
response_or_ref.item(components)?,
))
},
))
.map(|v: Result<(OperationResponseStatus, &Response)>| {
let (status_code, response) = v?;
// We categorize responses as "typed" based on the
// "application/json" content type, "upgrade" if it's a
// websocket channel without a meaningful content-type,
// "raw" if there's any other response content type (we don't
// investigate further), or "none" if there is no content.
// TODO if there are multiple response content types we could
// treat those like different response types and create an
// enum; the generated client method would check for the
// content type of the response just as it currently examines
// the status code.
let typ = if let Some(mt) =
response.content.iter().find_map(|(x, v)| {
(x == "application/json"
|| x.starts_with("application/json;"))
.then_some(v)
}) {
assert!(mt.encoding.is_empty());
let typ = if let Some(schema) = &mt.schema {
let schema = schema.to_schema();
let name = sanitize(
&format!(
"{}-response",
operation.operation_id.as_ref().unwrap(),
),
Case::Pascal,
);
self.type_space
.add_type_with_name(&schema, Some(name))?
} else {
todo!("media type encoding, no schema: {:#?}", mt);
};
OperationResponseKind::Type(typ)
} else if dropshot_websocket {
OperationResponseKind::Upgrade
} else if response.content.first().is_some() {
OperationResponseKind::Raw
} else {
OperationResponseKind::None
};
// See if there's a status code that covers success cases.
if matches!(
status_code,
OperationResponseStatus::Default
| OperationResponseStatus::Code(200..=299)
| OperationResponseStatus::Range(2)
) {
success = true;
}
let description = if response.description.is_empty() {
None
} else {
Some(response.description.clone())
};
Ok(OperationResponse {
status_code,
typ,
description,
})
})
.collect::<Result<Vec<_>>>()?;
// If the API has declined to specify the characteristics of a
// successful response, we cons up a generic one. Note that this is
// technically permissible within OpenAPI, but advised against by the
// spec.
if !success {
responses.push(OperationResponse {
status_code: OperationResponseStatus::Range(2),
typ: OperationResponseKind::Raw,
description: None,
});
}
// Must accept HTTP 101 Switching Protocols
if dropshot_websocket {
responses.push(OperationResponse {
status_code: OperationResponseStatus::Code(101),
typ: OperationResponseKind::Upgrade,
description: None,
})
}
let dropshot_paginated =
self.dropshot_pagination_data(operation, ¶ms, &responses);
if dropshot_websocket && dropshot_paginated.is_some() {
return Err(Error::InvalidExtension(format!(
"conflicting extensions in {:?}",
operation_id
)));
}
Ok(OperationMethod {
operation_id: sanitize(operation_id, Case::Snake),
tags: operation.tags.clone(),
method: HttpMethod::from_str(method)?,
path: tmp,
summary: operation.summary.clone().filter(|s| !s.is_empty()),
description: operation
.description
.clone()
.filter(|s| !s.is_empty()),
params,
responses,
dropshot_paginated,
dropshot_websocket,
})
}
pub(crate) fn positional_method(
&mut self,
method: &OperationMethod,
has_inner: bool,
) -> Result<TokenStream> {
let operation_id = format_ident!("{}", method.operation_id);
// Render each parameter as it will appear in the method signature.
let params = method
.params
.iter()
.map(|param| {
let name = format_ident!("{}", param.name);
let typ = match (¶m.typ, param.kind.is_optional()) {
(OperationParameterType::Type(type_id), false) => self
.type_space
.get_type(type_id)
.unwrap()
.parameter_ident_with_lifetime("a"),
(OperationParameterType::Type(type_id), true) => {
let t = self
.type_space
.get_type(type_id)
.unwrap()
.parameter_ident_with_lifetime("a");
quote! { Option<#t> }
}
(OperationParameterType::RawBody, false) => {
match ¶m.kind {
OperationParameterKind::Body(
BodyContentType::OctetStream,
) => {
quote! { B }
}
OperationParameterKind::Body(
BodyContentType::Text(_),
) => {
quote! { String }
}
_ => unreachable!(),
}
}
(OperationParameterType::RawBody, true) => unreachable!(),
};
quote! {
#name: #typ
}
})
.collect::<Vec<_>>();
let raw_body_param = method.params.iter().any(|param| {
param.typ == OperationParameterType::RawBody
&& param.kind
== OperationParameterKind::Body(
BodyContentType::OctetStream,
)
});
let bounds = if raw_body_param {
quote! { <'a, B: Into<reqwest::Body> > }
} else {
quote! { <'a> }
};
let doc_comment = make_doc_comment(method);
let MethodSigBody {
success: success_type,
error: error_type,
body,
} = self.method_sig_body(method, quote! { self }, has_inner)?;
let method_impl = quote! {
#[doc = #doc_comment]
pub async fn #operation_id #bounds (
&'a self,
#(#params),*
) -> Result<
ResponseValue<#success_type>,
Error<#error_type>,
> {
#body
}
};
let stream_impl = method.dropshot_paginated.as_ref().map(|page_data| {
// We're now using futures.
self.uses_futures = true;
let stream_id = format_ident!("{}_stream", method.operation_id);
// The parameters are the same as those to the paged method, but
// without "page_token"
let stream_params = method.params.iter().zip(params).filter_map(
|(param, stream)| {
if param.name.as_str() == "page_token" {
None
} else {
Some(stream)
}
},
);
// The values passed to get the first page are the inputs to the
// stream method with "None" for the page_token.
let first_params = method.params.iter().map(|param| {
if param.api_name.as_str() == "page_token" {
// The page_token is None when getting the first page.
quote! { None }
} else {
// All other parameters are passed through directly.
format_ident!("{}", param.name).to_token_stream()
}
});
// The values passed to get subsequent pages are...
// - the state variable for the page_token
// - None for all other query parameters
// - The initial inputs for non-query parameters
let step_params = method.params.iter().map(|param| {
if param.api_name.as_str() == "page_token" {
quote! { state.as_deref() }
} else if param.api_name.as_str() != "limit"
&& matches!(param.kind, OperationParameterKind::Query(_))
{
// Query parameters (other than "page_token" and "limit")
// are None; having page_token as Some(_) is mutually
// exclusive with other query parameters.
quote! { None }
} else {
// Non-query parameters are passed in; this is necessary
// e.g. to specify the right path. (We don't really expect
// to see a body parameter here, but we pass it through
// regardless.)
format_ident!("{}", param.name).to_token_stream()
}
});
// The item type that we've saved (by picking apart the original
// function's return type) will be the Item type parameter for the
// Stream type we return.
let item = self.type_space.get_type(&page_data.item).unwrap();
let item_type = item.ident();
let doc_comment = make_stream_doc_comment(method);
quote! {
#[doc = #doc_comment]
pub fn #stream_id #bounds (
&'a self,
#(#stream_params),*
) -> impl futures::Stream<Item = Result<
#item_type,
Error<#error_type>,
>> + Unpin + '_ {
use futures::StreamExt;
use futures::TryFutureExt;
use futures::TryStreamExt;
// Execute the operation with the basic parameters
// (omitting page_token) to get the first page.
self.#operation_id( #(#first_params,)* )
.map_ok(move |page| {
let page = page.into_inner();
// Create a stream from the items of the first page.
let first =
futures::stream::iter(page.items).map(Ok);
// We unfold subsequent pages using page.next_page
// as the seed value. Each iteration returns its
// items and the next page token.
let rest = futures::stream::try_unfold(
page.next_page,
move |state| async move {
if state.is_none() {
// The page_token was None so we've
// reached the end.
Ok(None)
} else {
// Get the next page; here we set all
// query parameters to None (except for
// the page_token), and all other
// parameters as specified at the start
// of this method.
self.#operation_id(
#(#step_params,)*
)
.map_ok(|page| {
let page = page.into_inner();
Some((
futures::stream::iter(
page.items
).map(Ok),
page.next_page,
))
})
.await
}
},
)
.try_flatten();
first.chain(rest)
})
.try_flatten_stream()
.boxed()
}
}
});
let all = quote! {
#method_impl
#stream_impl
};
Ok(all)
}
/// Common code generation between positional and builder interface-styles.
/// Returns a struct with the success and error types and the core body
/// implementation that marshals arguments and executes the request.
fn method_sig_body(
&self,
method: &OperationMethod,
client: TokenStream,
has_inner: bool,
) -> Result<MethodSigBody> {
let param_names = method
.params
.iter()
.map(|param| format_ident!("{}", param.name))
.collect::<Vec<_>>();
// Generate a unique Ident for internal variables
let url_ident = unique_ident_from("url", ¶m_names);
let query_ident = unique_ident_from("query", ¶m_names);
let request_ident = unique_ident_from("request", ¶m_names);
let response_ident = unique_ident_from("response", ¶m_names);
let result_ident = unique_ident_from("result", ¶m_names);
// Generate code for query parameters.
let query_items = method
.params
.iter()
.filter_map(|param| match ¶m.kind {
OperationParameterKind::Query(required) => {
let qn = ¶m.api_name;
let qn_ident = format_ident!("{}", ¶m.name);
let res = if *required {
quote! {
#query_ident.push((#qn, #qn_ident .to_string()));
}
} else {
quote! {
if let Some(v) = & #qn_ident {
#query_ident.push((#qn, v.to_string()));
}
}
};
Some(res)
}
_ => None,
})
.collect::<Vec<_>>();
let (query_build, query_use) = if query_items.is_empty() {
(quote! {}, quote! {})
} else {
let size = query_items.len();
let query_build = quote! {
let mut #query_ident = Vec::with_capacity(#size);
#(#query_items)*
};
let query_use = quote! {
.query(&#query_ident)
};
(query_build, query_use)
};
let headers = method
.params
.iter()
.filter_map(|param| match ¶m.kind {
OperationParameterKind::Header(required) => {
let hn = ¶m.api_name;
let hn_ident = format_ident!("{}", ¶m.name);
let res = if *required {
quote! {
header_map.append(#hn, HeaderValue::try_from(#hn_ident)?);
}
} else {
quote! {
if let Some(v) = #hn_ident {
header_map.append(#hn, HeaderValue::try_from(v)?);
}
}
};
Some(res)
}
_ => None,
})
.collect::<Vec<_>>();
let (headers_build, headers_use) = if headers.is_empty() {
(quote! {}, quote! {})
} else {
let size = headers.len();
let headers_build = quote! {
let mut header_map = HeaderMap::with_capacity(#size);
#(#headers)*
};
let headers_use = quote! {
.headers(header_map)
};
(headers_build, headers_use)
};
let websock_hdrs = if method.dropshot_websocket {
quote! {
.header(reqwest::header::CONNECTION, "Upgrade")
.header(reqwest::header::UPGRADE, "websocket")
.header(reqwest::header::SEC_WEBSOCKET_VERSION, "13")
.header(
reqwest::header::SEC_WEBSOCKET_KEY,
base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
rand::random::<[u8; 16]>(),
)
)
}
} else {
quote! {}
};
// Generate the path rename map; then use it to generate code for
// assigning the path parameters to the `url` variable.
let url_renames = method
.params
.iter()
.filter_map(|param| match ¶m.kind {
OperationParameterKind::Path => {
Some((¶m.api_name, ¶m.name))
}
_ => None,
})
.collect();
let url_path = method.path.compile(url_renames, client.clone());
let url_path = quote! {
let #url_ident = #url_path;
};
// Generate code to handle the body param.
let body_func = method.params.iter().filter_map(|param| {
match (¶m.kind, ¶m.typ) {
(
OperationParameterKind::Body(BodyContentType::OctetStream),
OperationParameterType::RawBody,
) => Some(quote! {
// Set the content type (this is handled by helper
// functions for other MIME types).
.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/octet-stream"),
)
.body(body)
}),
(
OperationParameterKind::Body(BodyContentType::Text(mime_type)),
OperationParameterType::RawBody,
) => Some(quote! {
// Set the content type (this is handled by helper
// functions for other MIME types).
.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static(#mime_type),
)
.body(body)
}),
(
OperationParameterKind::Body(BodyContentType::Json),
OperationParameterType::Type(_),
) => Some(quote! {
// Serialization errors are deferred.
.json(&body)
}),
(
OperationParameterKind::Body(
BodyContentType::FormUrlencoded
),
OperationParameterType::Type(_),
) => Some(quote! {
// This uses progenitor_client::RequestBuilderExt which
// returns an error in the case of a serialization failure.
.form_urlencoded(&body)?
}),
(OperationParameterKind::Body(_), _) => {
unreachable!("invalid body kind/type combination")
}
_ => None,
}
});
// ... and there can be at most one body.
assert!(body_func.clone().count() <= 1);