-
Notifications
You must be signed in to change notification settings - Fork 180
/
ServerHttpBoundProtocolGenerator.kt
1180 lines (1111 loc) · 52.7 KB
/
ServerHttpBoundProtocolGenerator.kt
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 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rust.codegen.server.smithy.protocols
import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait
import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait
import software.amazon.smithy.aws.traits.protocols.RestJson1Trait
import software.amazon.smithy.aws.traits.protocols.RestXmlTrait
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.model.knowledge.HttpBindingIndex
import software.amazon.smithy.model.node.ExpectationNotMetException
import software.amazon.smithy.model.shapes.BooleanShape
import software.amazon.smithy.model.shapes.CollectionShape
import software.amazon.smithy.model.shapes.NumberShape
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.shapes.StringShape
import software.amazon.smithy.model.shapes.StructureShape
import software.amazon.smithy.model.traits.ErrorTrait
import software.amazon.smithy.model.traits.HttpErrorTrait
import software.amazon.smithy.model.traits.HttpTrait
import software.amazon.smithy.rust.codegen.rustlang.Attribute
import software.amazon.smithy.rust.codegen.rustlang.CargoDependency
import software.amazon.smithy.rust.codegen.rustlang.RustModule
import software.amazon.smithy.rust.codegen.rustlang.RustType
import software.amazon.smithy.rust.codegen.rustlang.RustWriter
import software.amazon.smithy.rust.codegen.rustlang.Writable
import software.amazon.smithy.rust.codegen.rustlang.asType
import software.amazon.smithy.rust.codegen.rustlang.render
import software.amazon.smithy.rust.codegen.rustlang.rust
import software.amazon.smithy.rust.codegen.rustlang.rustBlock
import software.amazon.smithy.rust.codegen.rustlang.rustBlockTemplate
import software.amazon.smithy.rust.codegen.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.rustlang.withBlock
import software.amazon.smithy.rust.codegen.rustlang.withBlockTemplate
import software.amazon.smithy.rust.codegen.rustlang.writable
import software.amazon.smithy.rust.codegen.server.smithy.ServerCargoDependency
import software.amazon.smithy.rust.codegen.server.smithy.ServerRuntimeType
import software.amazon.smithy.rust.codegen.server.smithy.generators.http.ServerRequestBindingGenerator
import software.amazon.smithy.rust.codegen.server.smithy.generators.http.ServerResponseBindingGenerator
import software.amazon.smithy.rust.codegen.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.smithy.ServerCodegenContext
import software.amazon.smithy.rust.codegen.smithy.customize.OperationCustomization
import software.amazon.smithy.rust.codegen.smithy.extractSymbolFromOption
import software.amazon.smithy.rust.codegen.smithy.generators.CodegenTarget
import software.amazon.smithy.rust.codegen.smithy.generators.StructureGenerator
import software.amazon.smithy.rust.codegen.smithy.generators.builderSymbol
import software.amazon.smithy.rust.codegen.smithy.generators.error.errorSymbol
import software.amazon.smithy.rust.codegen.smithy.generators.http.HttpMessageType
import software.amazon.smithy.rust.codegen.smithy.generators.protocol.MakeOperationGenerator
import software.amazon.smithy.rust.codegen.smithy.generators.protocol.ProtocolGenerator
import software.amazon.smithy.rust.codegen.smithy.generators.protocol.ProtocolTraitImplGenerator
import software.amazon.smithy.rust.codegen.smithy.generators.setterName
import software.amazon.smithy.rust.codegen.smithy.isOptional
import software.amazon.smithy.rust.codegen.smithy.protocols.HttpBindingDescriptor
import software.amazon.smithy.rust.codegen.smithy.protocols.HttpBoundProtocolPayloadGenerator
import software.amazon.smithy.rust.codegen.smithy.protocols.HttpLocation
import software.amazon.smithy.rust.codegen.smithy.protocols.Protocol
import software.amazon.smithy.rust.codegen.smithy.protocols.parse.StructuredDataParserGenerator
import software.amazon.smithy.rust.codegen.smithy.toOptional
import software.amazon.smithy.rust.codegen.smithy.transformers.operationErrors
import software.amazon.smithy.rust.codegen.smithy.wrapOptional
import software.amazon.smithy.rust.codegen.util.dq
import software.amazon.smithy.rust.codegen.util.expectTrait
import software.amazon.smithy.rust.codegen.util.findStreamingMember
import software.amazon.smithy.rust.codegen.util.getTrait
import software.amazon.smithy.rust.codegen.util.hasStreamingMember
import software.amazon.smithy.rust.codegen.util.inputShape
import software.amazon.smithy.rust.codegen.util.isStreaming
import software.amazon.smithy.rust.codegen.util.outputShape
import software.amazon.smithy.rust.codegen.util.toPascalCase
import software.amazon.smithy.rust.codegen.util.toSnakeCase
import java.util.logging.Logger
/*
* Implement operations' input parsing and output serialization. Protocols can plug their own implementations
* and overrides by creating a protocol factory inheriting from this class and feeding it to the [ServerProtocolLoader].
* See `ServerRestJsonFactory.kt` for more info.
*/
class ServerHttpBoundProtocolGenerator(
codegenContext: ServerCodegenContext,
protocol: Protocol,
) : ProtocolGenerator(
codegenContext,
protocol,
MakeOperationGenerator(
codegenContext,
protocol,
HttpBoundProtocolPayloadGenerator(codegenContext, protocol),
public = true,
includeDefaultPayloadHeaders = true,
),
ServerHttpBoundProtocolTraitImplGenerator(codegenContext, protocol),
) {
// Define suffixes for operation input / output / error wrappers
companion object {
const val OPERATION_INPUT_WRAPPER_SUFFIX = "OperationInputWrapper"
const val OPERATION_OUTPUT_WRAPPER_SUFFIX = "OperationOutputWrapper"
}
}
/*
* Generate all operation input parsers and output serializers for streaming and
* non-streaming types.
*/
private class ServerHttpBoundProtocolTraitImplGenerator(
private val codegenContext: ServerCodegenContext,
private val protocol: Protocol,
) : ProtocolTraitImplGenerator {
private val logger = Logger.getLogger(javaClass.name)
private val symbolProvider = codegenContext.symbolProvider
private val model = codegenContext.model
private val runtimeConfig = codegenContext.runtimeConfig
private val httpBindingResolver = protocol.httpBindingResolver
private val operationDeserModule = RustModule.private("operation_deser")
private val operationSerModule = RustModule.private("operation_ser")
private val codegenScope = arrayOf(
"AsyncTrait" to ServerCargoDependency.AsyncTrait.asType(),
"Cow" to ServerRuntimeType.Cow,
"DateTime" to RuntimeType.DateTime(runtimeConfig),
"FormUrlEncoded" to ServerCargoDependency.FormUrlEncoded.asType(),
"HttpBody" to CargoDependency.HttpBody.asType(),
"header_util" to CargoDependency.SmithyHttp(runtimeConfig).asType().member("header"),
"Hyper" to CargoDependency.Hyper.asType(),
"LazyStatic" to CargoDependency.LazyStatic.asType(),
"Mime" to ServerCargoDependency.Mime.asType(),
"Nom" to ServerCargoDependency.Nom.asType(),
"OnceCell" to ServerCargoDependency.OnceCell.asType(),
"PercentEncoding" to CargoDependency.PercentEncoding.asType(),
"Regex" to CargoDependency.Regex.asType(),
"SmithyHttp" to CargoDependency.SmithyHttp(runtimeConfig).asType(),
"SmithyHttpServer" to ServerCargoDependency.SmithyHttpServer(runtimeConfig).asType(),
"RuntimeError" to ServerRuntimeType.RuntimeError(runtimeConfig),
"RequestRejection" to ServerRuntimeType.RequestRejection(runtimeConfig),
"ResponseRejection" to ServerRuntimeType.ResponseRejection(runtimeConfig),
"http" to RuntimeType.http,
)
override fun generateTraitImpls(operationWriter: RustWriter, operationShape: OperationShape, customizations: List<OperationCustomization>) {
val inputSymbol = symbolProvider.toSymbol(operationShape.inputShape(model))
val outputSymbol = symbolProvider.toSymbol(operationShape.outputShape(model))
operationWriter.renderTraits(inputSymbol, outputSymbol, operationShape)
}
/*
* Generation of `from_request` and `into_response`.
* For non-streaming request bodies, that is, models without streaming traits
* (https://awslabs.github.io/smithy/1.0/spec/core/stream-traits.html)
* we require the HTTP body to be fully read in memory before parsing or deserialization.
* From a server perspective we need a way to parse an HTTP request from `Bytes` and serialize
* an HTTP response to `Bytes`.
* These traits are the public entrypoint of the ser/de logic of the `aws-smithy-http-server` server.
*/
private fun RustWriter.renderTraits(
inputSymbol: Symbol,
outputSymbol: Symbol,
operationShape: OperationShape,
) {
val operationName = symbolProvider.toSymbol(operationShape).name
val inputName = "${operationName}${ServerHttpBoundProtocolGenerator.OPERATION_INPUT_WRAPPER_SUFFIX}"
val verifyResponseContentType = writable {
httpBindingResolver.responseContentType(operationShape)?.also { contentType ->
rustTemplate(
"""
if let Some(headers) = req.headers() {
if let Some(accept) = headers.get(#{http}::header::ACCEPT) {
if accept != "$contentType" {
return Err(#{RuntimeError} {
protocol: #{SmithyHttpServer}::protocols::Protocol::${codegenContext.protocol.name.toPascalCase()},
kind: #{SmithyHttpServer}::runtime_error::RuntimeErrorKind::NotAcceptable,
})
}
}
}
""",
*codegenScope,
)
}
}
// Implement `from_request` trait for input types.
rustTemplate(
"""
##[derive(Debug)]
pub(crate) struct $inputName(#{I});
impl $inputName
{
pub async fn from_request<B>(req: &mut #{SmithyHttpServer}::request::RequestParts<B>) -> Result<Self, #{RuntimeError}>
where
B: #{SmithyHttpServer}::body::HttpBody + Send, ${streamingBodyTraitBounds(operationShape)}
B::Data: Send,
#{RequestRejection} : From<<B as #{SmithyHttpServer}::body::HttpBody>::Error>
{
#{verify_response_content_type:W}
#{parse_request}(req)
.await
.map($inputName)
.map_err(
|err| #{RuntimeError} {
protocol: #{SmithyHttpServer}::protocols::Protocol::${codegenContext.protocol.name.toPascalCase()},
kind: err.into()
}
)
}
}
""".trimIndent(),
*codegenScope,
"I" to inputSymbol,
"parse_request" to serverParseRequest(operationShape),
"verify_response_content_type" to verifyResponseContentType,
)
// Implement `into_response` for output types.
val outputName = "${operationName}${ServerHttpBoundProtocolGenerator.OPERATION_OUTPUT_WRAPPER_SUFFIX}"
val errorSymbol = operationShape.errorSymbol(model, symbolProvider, CodegenTarget.SERVER)
if (operationShape.operationErrors(model).isNotEmpty()) {
// The output of fallible operations is a `Result` which we convert into an
// isomorphic `enum` type we control that can in turn be converted into a response.
val intoResponseImpl =
"""
match self {
Self::Output(o) => {
match #{serialize_response}(o) {
Ok(response) => response,
Err(e) => {
#{RuntimeError} {
protocol: #{SmithyHttpServer}::protocols::Protocol::${codegenContext.protocol.name.toPascalCase()},
kind: e.into()
}.into_response()
}
}
},
Self::Error(err) => {
match #{serialize_error}(&err) {
Ok(mut response) => {
response.extensions_mut().insert(#{SmithyHttpServer}::extension::ModeledErrorExtension::new(err.name()));
response
},
Err(e) => {
#{RuntimeError} {
protocol: #{SmithyHttpServer}::protocols::Protocol::${codegenContext.protocol.name.toPascalCase()},
kind: e.into()
}.into_response()
}
}
}
}
"""
rustTemplate(
"""
pub(crate) enum $outputName {
Output(#{O}),
Error(#{E})
}
impl $outputName {
pub fn into_response(self) -> #{SmithyHttpServer}::response::Response {
$intoResponseImpl
}
}
""".trimIndent(),
*codegenScope,
"O" to outputSymbol,
"E" to errorSymbol,
"serialize_response" to serverSerializeResponse(operationShape),
"serialize_error" to serverSerializeError(operationShape),
)
} else {
// The output of non-fallible operations is a model type which we convert into
// a "wrapper" unit `struct` type we control that can in turn be converted into a response.
val intoResponseImpl =
"""
match #{serialize_response}(self.0) {
Ok(response) => response,
Err(e) => {
#{RuntimeError} {
protocol: #{SmithyHttpServer}::protocols::Protocol::${codegenContext.protocol.name.toPascalCase()},
kind: e.into()
}.into_response()
}
}
""".trimIndent()
rustTemplate(
"""
pub(crate) struct $outputName(#{O});
impl $outputName {
pub fn into_response(self) -> #{SmithyHttpServer}::response::Response {
$intoResponseImpl
}
}
""".trimIndent(),
*codegenScope,
"O" to outputSymbol,
"serialize_response" to serverSerializeResponse(operationShape),
)
}
// Implement conversion function to "wrap" from the model operation output types.
if (operationShape.operationErrors(model).isNotEmpty()) {
rustTemplate(
"""
impl #{From}<Result<#{O}, #{E}>> for $outputName {
fn from(res: Result<#{O}, #{E}>) -> Self {
match res {
Ok(v) => Self::Output(v),
Err(e) => Self::Error(e),
}
}
}
""".trimIndent(),
"O" to outputSymbol,
"E" to errorSymbol,
"From" to RuntimeType.From,
)
} else {
rustTemplate(
"""
impl #{From}<#{O}> for $outputName {
fn from(o: #{O}) -> Self {
Self(o)
}
}
""".trimIndent(),
"O" to outputSymbol,
"From" to RuntimeType.From,
)
}
// Implement conversion function to "unwrap" into the model operation input types.
rustTemplate(
"""
impl #{From}<$inputName> for #{I} {
fn from(i: $inputName) -> Self {
i.0
}
}
""".trimIndent(),
"I" to inputSymbol,
"From" to RuntimeType.From,
)
}
private fun serverParseRequest(operationShape: OperationShape): RuntimeType {
val fnName = "parse_${operationShape.id.name.toSnakeCase()}_request"
val inputShape = operationShape.inputShape(model)
val inputSymbol = symbolProvider.toSymbol(inputShape)
return RuntimeType.forInlineFun(fnName, operationDeserModule) {
Attribute.Custom("allow(clippy::unnecessary_wraps)").render(it)
// The last conversion trait bound is needed by the `hyper::body::to_bytes(body).await?` call.
it.rustBlockTemplate(
"""
pub async fn $fnName<B>(
##[allow(unused_variables)] request: &mut #{SmithyHttpServer}::request::RequestParts<B>
) -> std::result::Result<
#{I},
#{RequestRejection}
>
where
B: #{SmithyHttpServer}::body::HttpBody + Send, ${streamingBodyTraitBounds(operationShape)}
B::Data: Send,
#{RequestRejection}: From<<B as #{SmithyHttpServer}::body::HttpBody>::Error>
""".trimIndent(),
*codegenScope,
"I" to inputSymbol,
) {
withBlock("Ok({", "})") {
serverRenderShapeParser(
operationShape,
inputShape,
httpBindingResolver.requestBindings(operationShape),
)
}
}
}
}
private fun serverSerializeResponse(operationShape: OperationShape): RuntimeType {
val fnName = "serialize_${operationShape.id.name.toSnakeCase()}_response"
val outputShape = operationShape.outputShape(model)
val outputSymbol = symbolProvider.toSymbol(outputShape)
return RuntimeType.forInlineFun(fnName, operationSerModule) {
Attribute.Custom("allow(clippy::unnecessary_wraps)").render(it)
// Note we only need to take ownership of the output in the case that it contains streaming members.
// However we currently always take ownership here, but worth noting in case in the future we want
// to generate different signatures for streaming vs non-streaming for some reason.
it.rustBlockTemplate(
"""
pub fn $fnName(
##[allow(unused_variables)] output: #{O}
) -> std::result::Result<
#{SmithyHttpServer}::response::Response,
#{ResponseRejection}
>
""".trimIndent(),
*codegenScope,
"O" to outputSymbol,
) {
withBlock("Ok({", "})") {
serverRenderOutputShapeResponseSerializer(
operationShape,
httpBindingResolver.responseBindings(operationShape),
)
}
}
}
}
private fun serverSerializeError(operationShape: OperationShape): RuntimeType {
val fnName = "serialize_${operationShape.id.name.toSnakeCase()}_error"
val errorSymbol = operationShape.errorSymbol(model, symbolProvider, CodegenTarget.SERVER)
return RuntimeType.forInlineFun(fnName, operationSerModule) {
Attribute.Custom("allow(clippy::unnecessary_wraps)").render(it)
it.rustBlockTemplate(
"pub fn $fnName(error: &#{E}) -> std::result::Result<#{SmithyHttpServer}::response::Response, #{ResponseRejection}>",
*codegenScope,
"E" to errorSymbol,
) {
withBlock("Ok({", "})") {
serverRenderErrorShapeResponseSerializer(
operationShape,
errorSymbol,
)
}
}
}
}
private fun RustWriter.serverRenderErrorShapeResponseSerializer(
operationShape: OperationShape,
errorSymbol: RuntimeType,
) {
val operationName = symbolProvider.toSymbol(operationShape).name
val structuredDataSerializer = protocol.structuredDataSerializer(operationShape)
withBlock("match error {", "}") {
val errors = operationShape.operationErrors(model)
errors.forEach {
val variantShape = model.expectShape(it.id, StructureShape::class.java)
val errorTrait = variantShape.expectTrait<ErrorTrait>()
val variantSymbol = symbolProvider.toSymbol(variantShape)
val serializerSymbol = structuredDataSerializer.serverErrorSerializer(it.id)
rustBlock("#T::${variantSymbol.name}(output) =>", errorSymbol) {
rust(
"""
let payload = #T(output)?;
""",
serializerSymbol,
)
val bindings = httpBindingResolver.errorResponseBindings(it)
Attribute.AllowUnusedMut.render(this)
rustTemplate("let mut builder = #{http}::Response::builder();", *codegenScope)
serverRenderResponseHeaders(operationShape, variantShape)
bindings.forEach { binding ->
when (val location = binding.location) {
HttpLocation.RESPONSE_CODE, HttpLocation.DOCUMENT -> {}
else -> {
logger.warning("[rust-server-codegen] $operationName: error serialization does not currently support $location bindings")
}
}
}
val status =
variantShape.getTrait<HttpErrorTrait>()?.code
?: errorTrait.defaultHttpStatusCode
serverRenderContentLengthHeader()
rustTemplate(
"""
builder.status($status).body(#{SmithyHttpServer}::body::to_boxed(payload))?
""",
*codegenScope,
)
}
}
}
}
/**
* Render an HTTP response (headers, response code, body) for an operation's output and the given [bindings].
*/
private fun RustWriter.serverRenderOutputShapeResponseSerializer(
operationShape: OperationShape,
bindings: List<HttpBindingDescriptor>,
) {
Attribute.AllowUnusedMut.render(this)
rustTemplate("let mut builder = #{http}::Response::builder();", *codegenScope)
serverRenderResponseHeaders(operationShape)
bindings.find { it.location == HttpLocation.RESPONSE_CODE }
?.let {
serverRenderResponseCodeBinding(it)(this)
}
// no binding, use http's
?: operationShape.getTrait<HttpTrait>()?.code?.let {
serverRenderHttpResponseCode(it)(this)
}
// Fallback to the default code of `http::response::Builder`, 200.
operationShape.outputShape(model).findStreamingMember(model)?.let {
val payloadGenerator = HttpBoundProtocolPayloadGenerator(codegenContext, protocol, httpMessageType = HttpMessageType.RESPONSE)
withBlockTemplate("let body = #{SmithyHttpServer}::body::boxed(#{SmithyHttpServer}::body::Body::wrap_stream(", "));", *codegenScope) {
payloadGenerator.generatePayload(this, "output", operationShape)
}
} ?: run {
val payloadGenerator = HttpBoundProtocolPayloadGenerator(codegenContext, protocol, httpMessageType = HttpMessageType.RESPONSE)
withBlockTemplate("let payload = ", ";") {
payloadGenerator.generatePayload(this, "output", operationShape)
}
serverRenderContentLengthHeader()
rustTemplate(
"""
let body = #{SmithyHttpServer}::body::to_boxed(payload);
""",
*codegenScope,
)
}
rustTemplate(
"""
builder.body(body)?
""",
*codegenScope,
)
}
/**
* Sets HTTP response headers for the operation's output shape or the operation's error shape.
* It will generate response headers for the operation's output shape, unless [errorShape] is non-null, in which
* case it will generate response headers for the given error shape.
*
* It sets three groups of headers in order. Headers from one group take precedence over headers in a later group.
* 1. Headers bound by the `httpHeader` and `httpPrefixHeader` traits.
* 2. The protocol-specific `Content-Type` header for the operation.
* 3. Additional protocol-specific headers for errors, if [errorShape] is non-null.
*/
private fun RustWriter.serverRenderResponseHeaders(operationShape: OperationShape, errorShape: StructureShape? = null) {
val bindingGenerator = ServerResponseBindingGenerator(protocol, codegenContext, operationShape)
val addHeadersFn = bindingGenerator.generateAddHeadersFn(errorShape ?: operationShape)
if (addHeadersFn != null) {
// Notice that we need to borrow the output only for output shapes but not for error shapes.
val outputOwnedOrBorrowed = if (errorShape == null) "&output" else "output"
rust(
"""
builder = #{T}($outputOwnedOrBorrowed, builder)?;
""".trimIndent(),
addHeadersFn,
)
}
// Set the `Content-Type` header *after* the response bindings headers have been set,
// to allow operations that bind a member to `Content-Type` (which we set earlier) to take precedence (this is
// because we always use `set_response_header_if_absent`, so the _first_ header value we set for a given
// header name is the one that takes precedence).
val contentType = httpBindingResolver.responseContentType(operationShape)
if (contentType != null) {
rustTemplate(
"""
builder = #{header_util}::set_response_header_if_absent(
builder,
#{http}::header::CONTENT_TYPE,
"$contentType"
);
""",
*codegenScope,
)
}
if (errorShape != null) {
for ((headerName, headerValue) in protocol.additionalErrorResponseHeaders(errorShape)) {
rustTemplate(
"""
builder = #{header_util}::set_response_header_if_absent(
builder,
http::header::HeaderName::from_static("$headerName"),
"$headerValue"
);
""",
*codegenScope,
)
}
}
}
/**
* Adds the `Content-Length` header.
*
* Unlike the headers added in `serverRenderResponseHeaders` the `Content-Length` depends on
* the payload post-serialization.
*/
private fun RustWriter.serverRenderContentLengthHeader() {
rustTemplate(
"""
let content_length = payload.len();
builder = #{header_util}::set_response_header_if_absent(builder, #{http}::header::CONTENT_LENGTH, content_length);
""",
*codegenScope,
)
}
private fun serverRenderHttpResponseCode(
defaultCode: Int,
): Writable {
return writable {
rustTemplate(
"""
let status = $defaultCode;
let http_status: u16 = status.try_into()
.map_err(|_| #{ResponseRejection}::InvalidHttpStatusCode)?;
builder = builder.status(http_status);
""".trimIndent(),
*codegenScope,
)
}
}
private fun serverRenderResponseCodeBinding(
binding: HttpBindingDescriptor,
): Writable {
check(binding.location == HttpLocation.RESPONSE_CODE)
return writable {
val memberName = symbolProvider.toMemberName(binding.member)
rust("let status = output.$memberName")
if (symbolProvider.toSymbol(binding.member).isOptional()) {
rustTemplate(
"""
.ok_or(#{ResponseRejection}::MissingHttpStatusCode)?
""".trimIndent(),
*codegenScope,
)
}
rustTemplate(
"""
;
let http_status: u16 = status.try_into()
.map_err(|_| #{ResponseRejection}::InvalidHttpStatusCode)?;
builder = builder.status(http_status);
""".trimIndent(),
*codegenScope,
)
}
}
private fun RustWriter.serverRenderShapeParser(
operationShape: OperationShape,
inputShape: StructureShape,
bindings: List<HttpBindingDescriptor>,
) {
val httpBindingGenerator = ServerRequestBindingGenerator(protocol, codegenContext, operationShape)
val structuredDataParser = protocol.structuredDataParser(operationShape)
Attribute.AllowUnusedMut.render(this)
rust("let mut input = #T::default();", inputShape.builderSymbol(symbolProvider))
val parser = structuredDataParser.serverInputParser(operationShape)
if (parser != null) {
val expectedRequestContentType = httpBindingResolver.requestContentType(operationShape)
rustTemplate(
"""
let body = request.take_body().ok_or(#{RequestRejection}::BodyAlreadyExtracted)?;
let bytes = #{Hyper}::body::to_bytes(body).await?;
if !bytes.is_empty() {
static EXPECTED_CONTENT_TYPE: #{OnceCell}::sync::Lazy<#{Mime}::Mime> =
#{OnceCell}::sync::Lazy::new(|| "$expectedRequestContentType".parse::<#{Mime}::Mime>().unwrap());
#{SmithyHttpServer}::protocols::check_content_type(request, &EXPECTED_CONTENT_TYPE)?;
input = #{parser}(bytes.as_ref(), input)?;
}
""",
*codegenScope,
"parser" to parser,
)
}
for (binding in bindings) {
val member = binding.member
val parsedValue = serverRenderBindingParser(binding, operationShape, httpBindingGenerator, structuredDataParser)
if (parsedValue != null) {
withBlock("input = input.${member.setterName()}(", ");") {
parsedValue(this)
}
}
}
serverRenderUriPathParser(this, operationShape)
serverRenderQueryStringParser(this, operationShape)
val err = if (StructureGenerator.fallibleBuilder(inputShape, symbolProvider)) {
"?"
} else ""
rustTemplate("input.build()$err", *codegenScope)
}
private fun serverRenderBindingParser(
binding: HttpBindingDescriptor,
operationShape: OperationShape,
httpBindingGenerator: ServerRequestBindingGenerator,
structuredDataParser: StructuredDataParserGenerator,
): Writable? {
return when (binding.location) {
HttpLocation.HEADER -> writable { serverRenderHeaderParser(this, binding, operationShape) }
HttpLocation.PREFIX_HEADERS -> writable { serverRenderPrefixHeadersParser(this, binding, operationShape) }
HttpLocation.PAYLOAD -> {
val structureShapeHandler: RustWriter.(String) -> Unit = { body ->
rust("#T($body)", structuredDataParser.payloadParser(binding.member))
}
val errorSymbol = getDeserializePayloadErrorSymbol(binding)
val deserializer = httpBindingGenerator.generateDeserializePayloadFn(
binding,
errorSymbol,
structuredHandler = structureShapeHandler,
)
return writable {
if (binding.member.isStreaming(model)) {
rustTemplate(
"""
{
let body = request.take_body().ok_or(#{RequestRejection}::BodyAlreadyExtracted)?;
Some(#{Deserializer}(&mut body.into().into_inner())?)
}
""",
"Deserializer" to deserializer,
*codegenScope,
)
} else {
rustTemplate(
"""
{
let body = request.take_body().ok_or(#{RequestRejection}::BodyAlreadyExtracted)?;
let bytes = #{Hyper}::body::to_bytes(body).await?;
#{Deserializer}(&bytes)?
}
""",
"Deserializer" to deserializer,
*codegenScope,
)
}
}
}
HttpLocation.DOCUMENT, HttpLocation.LABEL, HttpLocation.QUERY, HttpLocation.QUERY_PARAMS -> {
// All of these are handled separately.
null
}
else -> {
logger.warning("[rust-server-codegen] ${operationShape.id}: request parsing does not currently support ${binding.location} bindings")
null
}
}
}
private fun serverRenderUriPathParser(writer: RustWriter, operationShape: OperationShape) {
val pathBindings =
httpBindingResolver.requestBindings(operationShape).filter {
it.location == HttpLocation.LABEL
}
if (pathBindings.isEmpty()) {
return
}
val httpTrait = httpBindingResolver.httpTrait(operationShape)
val greedyLabelIndex = httpTrait.uri.segments.indexOfFirst { it.isGreedyLabel }
val segments =
if (greedyLabelIndex >= 0) {
httpTrait.uri.segments.slice(0 until (greedyLabelIndex + 1))
} else {
httpTrait.uri.segments
}
val restAfterGreedyLabel =
if (greedyLabelIndex >= 0) {
httpTrait.uri.segments.slice((greedyLabelIndex + 1) until httpTrait.uri.segments.size).joinToString(prefix = "/", separator = "/")
} else {
""
}
val labeledNames = segments
.mapIndexed { index, segment ->
if (segment.isLabel) { "m$index" } else { "_" }
}
.joinToString(prefix = (if (segments.size > 1) "(" else ""), separator = ",", postfix = (if (segments.size > 1) ")" else ""))
val nomParser = segments
.map { segment ->
if (segment.isGreedyLabel) {
"#{Nom}::combinator::rest::<_, #{Nom}::error::Error<&str>>"
} else if (segment.isLabel) {
"""#{Nom}::branch::alt::<_, _, #{Nom}::error::Error<&str>, _>((#{Nom}::bytes::complete::take_until("/"), #{Nom}::combinator::rest))"""
} else {
"""#{Nom}::bytes::complete::tag::<_, _, #{Nom}::error::Error<&str>>("${segment.content}")"""
}
}
.joinToString(
// TODO(https://github.com/awslabs/smithy-rs/issues/1289): Note we're limited to 21 labels because of `tuple`.
prefix = if (segments.size > 1) "#{Nom}::sequence::tuple::<_, _, #{Nom}::error::Error<&str>, _>((" else "",
postfix = if (segments.size > 1) "))" else "",
transform = { parser ->
"""
#{Nom}::sequence::preceded(#{Nom}::bytes::complete::tag("/"), $parser)
""".trimIndent()
},
)
with(writer) {
rustTemplate("let input_string = request.uri().path();")
if (greedyLabelIndex >= 0 && greedyLabelIndex + 1 < httpTrait.uri.segments.size) {
rustTemplate(
"""
if !input_string.ends_with("$restAfterGreedyLabel") {
return Err(#{RequestRejection}::UriPatternGreedyLabelPostfixNotFound);
}
let input_string = &input_string[..(input_string.len() - "$restAfterGreedyLabel".len())];
""".trimIndent(),
*codegenScope,
)
}
rustTemplate(
"""
let (input_string, $labeledNames) = $nomParser(input_string)?;
debug_assert_eq!("", input_string);
""".trimIndent(),
*codegenScope,
)
segments
.forEachIndexed { index, segment ->
val binding = pathBindings.find { it.memberName == segment.content }
if (binding != null && segment.isLabel) {
val deserializer = generateParseFn(binding, true)
rustTemplate(
"""
input = input.${binding.member.setterName()}(
${symbolProvider.toOptional(binding.member, "#{deserializer}(m$index)?")}
);
""".trimIndent(),
*codegenScope,
"deserializer" to deserializer,
)
}
}
}
}
// The `httpQueryParams` trait can be applied to structure members that target:
// * a map of string,
// * a map of list of string; or
// * a map of set of string.
enum class QueryParamsTargetMapValueType {
STRING, LIST, SET;
fun asRustType(): RustType =
when (this) {
STRING -> RustType.String
LIST -> RustType.Vec(RustType.String)
SET -> RustType.HashSet(RustType.String)
}
}
private fun queryParamsTargetMapValueType(targetMapValue: Shape): QueryParamsTargetMapValueType =
if (targetMapValue.isStringShape) {
QueryParamsTargetMapValueType.STRING
} else if (targetMapValue.isListShape) {
QueryParamsTargetMapValueType.LIST
} else if (targetMapValue.isSetShape) {
QueryParamsTargetMapValueType.SET
} else {
throw ExpectationNotMetException(
"""
@httpQueryParams trait applied to non-supported target
$targetMapValue of type ${targetMapValue.type}
""".trimIndent(),
targetMapValue.sourceLocation,
)
}
private fun serverRenderQueryStringParser(writer: RustWriter, operationShape: OperationShape) {
val queryBindings =
httpBindingResolver.requestBindings(operationShape).filter {
it.location == HttpLocation.QUERY
}
// Only a single structure member can be bound to `httpQueryParams`, hence `find`.
val queryParamsBinding =
httpBindingResolver.requestBindings(operationShape).find {
it.location == HttpLocation.QUERY_PARAMS
}
if (queryBindings.isEmpty() && queryParamsBinding == null) {
return
}
fun HttpBindingDescriptor.queryParamsBindingTargetMapValueType(): QueryParamsTargetMapValueType {
check(this.location == HttpLocation.QUERY_PARAMS)
val queryParamsTarget = model.expectShape(this.member.target)
val mapTarget = queryParamsTarget.asMapShape().get()
return queryParamsTargetMapValueType(model.expectShape(mapTarget.value.target))
}
with(writer) {
rustTemplate(
"""
let query_string = request.uri().query().unwrap_or("");
let pairs = #{FormUrlEncoded}::parse(query_string.as_bytes());
""".trimIndent(),
*codegenScope,
)
if (queryParamsBinding != null) {
rustTemplate(
"let mut query_params: #{HashMap}<String, " +
"${queryParamsBinding.queryParamsBindingTargetMapValueType().asRustType().render()}> = #{HashMap}::new();",
"HashMap" to RustType.HashMap.RuntimeType,
)
}
val (queryBindingsTargettingCollection, queryBindingsTargettingSimple) =
queryBindings.partition { model.expectShape(it.member.target) is CollectionShape }
queryBindingsTargettingSimple.forEach {
rust("let mut seen_${symbolProvider.toMemberName(it.member)} = false;")
}
queryBindingsTargettingCollection.forEach {
rust("let mut ${symbolProvider.toMemberName(it.member)} = Vec::new();")
}
rustBlock("for (k, v) in pairs") {
queryBindingsTargettingSimple.forEach {
val deserializer = generateParseFn(it, false)
val memberName = symbolProvider.toMemberName(it.member)
rustTemplate(
"""
if !seen_$memberName && k == "${it.locationName}" {
input = input.${it.member.setterName()}(
${symbolProvider.toOptional(it.member, "#{deserializer}(&v)?")}
);
seen_$memberName = true;
}
""".trimIndent(),
"deserializer" to deserializer,
)
}
queryBindingsTargettingCollection.forEach {
rustBlock("if k == ${it.locationName.dq()}") {
val targetCollectionShape = model.expectShape(it.member.target, CollectionShape::class.java)
val memberShape = model.expectShape(targetCollectionShape.member.target)
when {
memberShape.isStringShape -> {
// NOTE: This path is traversed with or without @enum applied. The `try_from` is used
// as a common conversion.
rustTemplate(
"""
let v = <#{memberShape}>::try_from(v.as_ref())?;
""",
*codegenScope,
"memberShape" to symbolProvider.toSymbol(memberShape),
)
}
memberShape.isTimestampShape -> {
val index = HttpBindingIndex.of(model)
val timestampFormat =
index.determineTimestampFormat(
it.member,
it.location,
protocol.defaultTimestampFormat,
)
val timestampFormatType = RuntimeType.TimestampFormat(runtimeConfig, timestampFormat)
rustTemplate(
"""
let v = #{DateTime}::from_str(&v, #{format})?;
""".trimIndent(),
*codegenScope,
"format" to timestampFormatType,
)
}
else -> { // Number or boolean.
rust(
"""
let v = <_ as #T>::parse_smithy_primitive(&v)?;
""".trimIndent(),
CargoDependency.SmithyTypes(runtimeConfig).asType().member("primitive::Parse"),
)
}
}
rust("${symbolProvider.toMemberName(it.member)}.push(v);")
}
}
if (queryParamsBinding != null) {
when (queryParamsBinding.queryParamsBindingTargetMapValueType()) {
QueryParamsTargetMapValueType.STRING -> {
rust("query_params.entry(String::from(k)).or_insert_with(|| String::from(v));")
} else -> {
rustTemplate(
"""
let entry = query_params.entry(String::from(k)).or_default();
entry.push(String::from(v));
""".trimIndent(),