forked from smithy-lang/smithy-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpBindingGenerator.kt
773 lines (733 loc) · 34.1 KB
/
HttpBindingGenerator.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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rust.codegen.core.smithy.generators.http
import software.amazon.smithy.codegen.core.CodegenException
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.codegen.core.SymbolProvider
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.knowledge.HttpBinding
import software.amazon.smithy.model.knowledge.HttpBindingIndex
import software.amazon.smithy.model.shapes.BlobShape
import software.amazon.smithy.model.shapes.CollectionShape
import software.amazon.smithy.model.shapes.DocumentShape
import software.amazon.smithy.model.shapes.ListShape
import software.amazon.smithy.model.shapes.MapShape
import software.amazon.smithy.model.shapes.MemberShape
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.shapes.SimpleShape
import software.amazon.smithy.model.shapes.StringShape
import software.amazon.smithy.model.shapes.StructureShape
import software.amazon.smithy.model.shapes.UnionShape
import software.amazon.smithy.model.traits.EnumTrait
import software.amazon.smithy.model.traits.MediaTypeTrait
import software.amazon.smithy.model.traits.TimestampFormatTrait
import software.amazon.smithy.rust.codegen.core.rustlang.RustModule
import software.amazon.smithy.rust.codegen.core.rustlang.RustType
import software.amazon.smithy.rust.codegen.core.rustlang.RustWriter
import software.amazon.smithy.rust.codegen.core.rustlang.Writable
import software.amazon.smithy.rust.codegen.core.rustlang.asOptional
import software.amazon.smithy.rust.codegen.core.rustlang.render
import software.amazon.smithy.rust.codegen.core.rustlang.rust
import software.amazon.smithy.rust.codegen.core.rustlang.rustBlock
import software.amazon.smithy.rust.codegen.core.rustlang.rustBlockTemplate
import software.amazon.smithy.rust.codegen.core.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.core.rustlang.stripOuter
import software.amazon.smithy.rust.codegen.core.rustlang.withBlock
import software.amazon.smithy.rust.codegen.core.smithy.CodegenContext
import software.amazon.smithy.rust.codegen.core.smithy.CodegenTarget
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.core.smithy.customize.NamedCustomization
import software.amazon.smithy.rust.codegen.core.smithy.customize.Section
import software.amazon.smithy.rust.codegen.core.smithy.generators.OperationBuildError
import software.amazon.smithy.rust.codegen.core.smithy.generators.operationBuildError
import software.amazon.smithy.rust.codegen.core.smithy.isOptional
import software.amazon.smithy.rust.codegen.core.smithy.makeOptional
import software.amazon.smithy.rust.codegen.core.smithy.mapRustType
import software.amazon.smithy.rust.codegen.core.smithy.protocols.HttpBindingDescriptor
import software.amazon.smithy.rust.codegen.core.smithy.protocols.HttpLocation
import software.amazon.smithy.rust.codegen.core.smithy.protocols.Protocol
import software.amazon.smithy.rust.codegen.core.smithy.protocols.parse.EventStreamUnmarshallerGenerator
import software.amazon.smithy.rust.codegen.core.smithy.protocols.serialize.ValueExpression
import software.amazon.smithy.rust.codegen.core.smithy.rustType
import software.amazon.smithy.rust.codegen.core.util.UNREACHABLE
import software.amazon.smithy.rust.codegen.core.util.dq
import software.amazon.smithy.rust.codegen.core.util.hasTrait
import software.amazon.smithy.rust.codegen.core.util.inputShape
import software.amazon.smithy.rust.codegen.core.util.isPrimitive
import software.amazon.smithy.rust.codegen.core.util.isStreaming
import software.amazon.smithy.rust.codegen.core.util.outputShape
import software.amazon.smithy.rust.codegen.core.util.redactIfNecessary
import software.amazon.smithy.rust.codegen.core.util.toSnakeCase
/**
* The type of HTTP message from which we are (de)serializing the HTTP-bound data.
* We are either:
* - deserializing data from an HTTP request (we are a server),
* - deserializing data from an HTTP response (we are a client),
* - serializing data to an HTTP request (we are a client),
* - serializing data to an HTTP response (we are a server),
*/
enum class HttpMessageType {
REQUEST, RESPONSE
}
/**
* Class describing an HTTP binding (de)serialization section that can be used in a customization.
*/
sealed class HttpBindingSection(name: String) : Section(name) {
data class BeforeIteratingOverMapShapeBoundWithHttpPrefixHeaders(val variableName: String, val shape: MapShape) :
HttpBindingSection("BeforeIteratingOverMapShapeBoundWithHttpPrefixHeaders")
data class BeforeRenderingHeaderValue(var context: HttpBindingGenerator.HeaderValueSerializationContext) :
HttpBindingSection("BeforeRenderingHeaderValue")
data class AfterDeserializingIntoAHashMapOfHttpPrefixHeaders(val memberShape: MemberShape) :
HttpBindingSection("AfterDeserializingIntoAHashMapOfHttpPrefixHeaders")
}
typealias HttpBindingCustomization = NamedCustomization<HttpBindingSection>
/**
* This class generates Rust functions that (de)serialize data from/to an HTTP message.
* They are useful for *both*:
* - servers (that deserialize HTTP requests and serialize HTTP responses); and
* - clients (that deserialize HTTP responses and serialize HTTP requests)
* because the (de)serialization logic is entirely similar. In the cases where they _slightly_ differ,
* the [HttpMessageType] enum is used to distinguish.
*
* For deserialization logic that is wholly different among clients and servers, use the classes:
* - [ServerRequestBindingGenerator] from the `codegen-server` project for servers; and
* - [ResponseBindingGenerator] from this project for clients
* instead.
*
* For serialization logic that is wholly different among clients and servers, use the classes:
* - [ServerResponseBindingGenerator] from the `codegen-server` project for servers; and
* - [RequestBindingGenerator] from this project for clients
* instead.
*/
class HttpBindingGenerator(
private val protocol: Protocol,
private val codegenContext: CodegenContext,
private val symbolProvider: SymbolProvider,
private val operationShape: OperationShape,
/** Function that maps a StructureShape into its builder symbol */
private val builderSymbol: (StructureShape) -> Symbol,
private val customizations: List<HttpBindingCustomization> = listOf(),
) {
private val runtimeConfig = codegenContext.runtimeConfig
private val codegenTarget = codegenContext.target
private val model = codegenContext.model
private val service = codegenContext.serviceShape
private val index = HttpBindingIndex.of(model)
private val headerUtil = RuntimeType.smithyHttp(runtimeConfig).resolve("header")
private val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS
private val dateTime = RuntimeType.dateTime(runtimeConfig).toSymbol().rustType()
private val httpSerdeModule = RustModule.private("http_serde")
/**
* Generate a function to deserialize [binding] from HTTP headers.
*
* The name of the resulting function is returned as a String.
*
* Generates a function like:
* ```rust
* fn parse_foo(headers: &http::HeaderMap) -> Result<Option<String>, ParseError> {
* ...
* }
* ```
*/
fun generateDeserializeHeaderFn(binding: HttpBindingDescriptor): RuntimeType {
check(binding.location == HttpLocation.HEADER)
val outputT = symbolProvider.toSymbol(binding.member).makeOptional()
val fnName = "deser_header_${fnName(operationShape, binding)}"
return RuntimeType.forInlineFun(fnName, httpSerdeModule) {
rustBlock(
"pub(crate) fn $fnName(header_map: &#T::HeaderMap) -> std::result::Result<#T, #T::ParseError>",
RuntimeType.Http,
outputT,
headerUtil,
) {
rust("let headers = header_map.get_all(${binding.locationName.dq()}).iter();")
deserializeFromHeader(model.expectShape(binding.member.target), binding.member)
}
}
}
fun generateDeserializePrefixHeaderFn(binding: HttpBindingDescriptor): RuntimeType {
check(binding.location == HttpBinding.Location.PREFIX_HEADERS)
val outputSymbol = symbolProvider.toSymbol(binding.member)
val target = model.expectShape(binding.member.target)
check(target is MapShape)
val fnName = "deser_prefix_header_${fnName(operationShape, binding)}"
val inner = RuntimeType.forInlineFun("${fnName}_inner", httpSerdeModule) {
rustBlock(
"pub fn ${fnName}_inner(headers: #T::header::ValueIter<http::HeaderValue>) -> std::result::Result<Option<#T>, #T::ParseError>",
RuntimeType.Http,
symbolProvider.toSymbol(model.expectShape(target.value.target)),
headerUtil,
) {
deserializeFromHeader(model.expectShape(target.value.target), binding.member)
}
}
val returnTypeSymbol = outputSymbol.mapRustType { it.asOptional() }
return RuntimeType.forInlineFun(fnName, httpSerdeModule) {
rustBlock(
"pub(crate) fn $fnName(header_map: &#T::HeaderMap) -> std::result::Result<#T, #T::ParseError>",
RuntimeType.Http,
returnTypeSymbol,
headerUtil,
) {
rust(
"""
let headers = #T::headers_for_prefix(header_map, ${binding.locationName.dq()});
let out: std::result::Result<_, _> = headers.map(|(key, header_name)| {
let values = header_map.get_all(header_name);
#T(values.iter()).map(|v| (key.to_string(), v.expect(
"we have checked there is at least one value for this header name; please file a bug report under https://github.com/awslabs/smithy-rs/issues"
)))
}).collect();
""",
headerUtil, inner,
)
for (customization in customizations) {
customization.section(
HttpBindingSection.AfterDeserializingIntoAHashMapOfHttpPrefixHeaders(binding.member),
)(this)
}
rust("out.map(Some)")
}
}
}
/**
* Generate a function to deserialize `[binding]` from the request / response payload.
*/
fun generateDeserializePayloadFn(
binding: HttpBindingDescriptor,
errorT: RuntimeType,
// Deserialize a single structure, union or document member marked as a payload
payloadParser: RustWriter.(String) -> Unit,
httpMessageType: HttpMessageType = HttpMessageType.RESPONSE,
): RuntimeType {
check(binding.location == HttpBinding.Location.PAYLOAD)
val fnName = "deser_payload_${fnName(operationShape, binding)}"
return RuntimeType.forInlineFun(fnName, httpSerdeModule) {
if (binding.member.isStreaming(model)) {
val outputT = symbolProvider.toSymbol(binding.member)
rustBlock(
"pub fn $fnName(body: &mut #T) -> std::result::Result<#T, #T>",
RuntimeType.sdkBody(runtimeConfig),
outputT,
errorT,
) {
// Streaming unions are Event Streams and should be handled separately
val target = model.expectShape(binding.member.target)
if (target is UnionShape) {
bindEventStreamOutput(operationShape, target)
} else {
deserializeStreamingBody(binding)
}
}
} else {
// The output needs to be Optional when deserializing the payload body or the caller signature
// will not match.
val outputT = symbolProvider.toSymbol(binding.member).makeOptional()
rustBlock("pub fn $fnName(body: &[u8]) -> std::result::Result<#T, #T>", outputT, errorT) {
deserializePayloadBody(
binding,
errorT,
structuredHandler = payloadParser,
httpMessageType,
)
}
}
}
}
private fun RustWriter.bindEventStreamOutput(operationShape: OperationShape, targetShape: UnionShape) {
val unmarshallerConstructorFn = EventStreamUnmarshallerGenerator(
protocol,
codegenContext,
operationShape,
targetShape,
builderSymbol,
).render()
rustTemplate(
"""
let unmarshaller = #{unmarshallerConstructorFn}();
let body = std::mem::replace(body, #{SdkBody}::taken());
Ok(#{Receiver}::new(unmarshaller, body))
""",
"SdkBody" to RuntimeType.sdkBody(runtimeConfig),
"unmarshallerConstructorFn" to unmarshallerConstructorFn,
"Receiver" to RuntimeType.eventStreamReceiver(runtimeConfig),
)
}
private fun RustWriter.deserializeStreamingBody(binding: HttpBindingDescriptor) {
val member = binding.member
val targetShape = model.expectShape(member.target)
check(targetShape is BlobShape)
rustTemplate(
"""
// replace the body with an empty body
let body = std::mem::replace(body, #{SdkBody}::taken());
Ok(#{ByteStream}::new(body))
""",
"ByteStream" to symbolProvider.toSymbol(member), "SdkBody" to RuntimeType.sdkBody(runtimeConfig),
)
}
private fun RustWriter.deserializePayloadBody(
binding: HttpBindingDescriptor,
errorSymbol: RuntimeType,
structuredHandler: RustWriter.(String) -> Unit,
httpMessageType: HttpMessageType = HttpMessageType.RESPONSE,
) {
val member = binding.member
val targetShape = model.expectShape(member.target)
// There is an unfortunate bit of dual behavior caused by an empty body causing the output to be `None` instead
// of an empty instance of the response type.
withBlock("(!body.is_empty()).then(||{", "}).transpose()") {
when (targetShape) {
is StructureShape, is UnionShape, is DocumentShape -> this.structuredHandler("body")
is StringShape -> {
when (httpMessageType) {
HttpMessageType.RESPONSE -> {
rustTemplate(
"let body_str = std::str::from_utf8(body).map_err(#{error_symbol}::unhandled)?;",
"error_symbol" to errorSymbol,
)
}
HttpMessageType.REQUEST -> {
rust("let body_str = std::str::from_utf8(body)?;")
}
}
if (targetShape.hasTrait<EnumTrait>()) {
if (codegenTarget == CodegenTarget.SERVER) {
rust(
"Ok(#T::try_from(body_str)?)",
symbolProvider.toSymbol(targetShape),
)
} else {
rust(
"Ok(#T::from(body_str))",
symbolProvider.toSymbol(targetShape),
)
}
} else {
rust("Ok(body_str.to_string())")
}
}
is BlobShape -> rust(
"Ok(#T::new(body))",
symbolProvider.toSymbol(targetShape),
)
// `httpPayload` can be applied to set/map/list shapes.
// However, none of the AWS protocols support it.
// Smithy CLI will refuse to build the model if you apply the trait to these shapes, so this branch
// remains unreachable.
else -> UNREACHABLE("unexpected shape: $targetShape")
}
}
}
/**
* Parse a value from a header.
* This function produces an expression which produces the precise type required by the target shape.
*/
private fun RustWriter.deserializeFromHeader(targetShape: Shape, memberShape: MemberShape) {
val rustType = symbolProvider.toSymbol(targetShape).rustType().stripOuter<RustType.Option>()
// Normally, we go through a flow that looks for `,`s but that's wrong if the output
// is just a single string (which might include `,`s.).
// MediaType doesn't include `,` since it's base64, send that through the normal path
if (targetShape is StringShape && !targetShape.hasTrait<MediaTypeTrait>()) {
rust("#T::one_or_none(headers)", headerUtil)
return
}
val (coreType, coreShape) = if (targetShape is CollectionShape) {
val coreShape = model.expectShape(targetShape.member.target)
symbolProvider.toSymbol(coreShape).rustType() to coreShape
} else {
rustType to targetShape
}
val parsedValue = safeName()
if (coreType == dateTime) {
val timestampFormat =
index.determineTimestampFormat(
memberShape,
HttpBinding.Location.HEADER,
defaultTimestampFormat,
)
val timestampFormatType = RuntimeType.timestampFormat(runtimeConfig, timestampFormat)
rust(
"let $parsedValue: Vec<${coreType.render()}> = #T::many_dates(headers, #T)?;",
headerUtil,
timestampFormatType,
)
} else if (coreShape.isPrimitive()) {
rust(
"let $parsedValue = #T::read_many_primitive::<${coreType.render()}>(headers)?;",
headerUtil,
)
} else {
rust(
"let $parsedValue: Vec<${coreType.render()}> = #T::read_many_from_str(headers)?;",
headerUtil,
)
if (coreShape.hasTrait<MediaTypeTrait>()) {
rustTemplate(
"""
let $parsedValue: std::result::Result<Vec<_>, _> = $parsedValue
.iter().map(|s|
#{base_64_decode}(s).map_err(|_|#{header}::ParseError::new("failed to decode base64"))
.and_then(|bytes|String::from_utf8(bytes).map_err(|_|#{header}::ParseError::new("base64 encoded data was not valid utf-8")))
).collect();
""",
"base_64_decode" to RuntimeType.base64Decode(runtimeConfig),
"header" to headerUtil,
)
rust("let $parsedValue = $parsedValue?;")
}
}
when (rustType) {
is RustType.Vec ->
rust(
"""
Ok(if !$parsedValue.is_empty() {
Some($parsedValue)
} else {
None
})
""",
)
is RustType.HashSet ->
rust(
"""
Ok(if !$parsedValue.is_empty() {
Some($parsedValue.into_iter().collect())
} else {
None
})
""",
)
else -> {
if (targetShape is ListShape) {
// This is a constrained list shape and we must therefore be generating a server SDK.
check(codegenTarget == CodegenTarget.SERVER)
check(rustType is RustType.Opaque)
rust(
"""
Ok(if !$parsedValue.is_empty() {
Some(#T($parsedValue))
} else {
None
})
""",
symbolProvider.toSymbol(targetShape),
)
} else {
check(targetShape is SimpleShape)
rustTemplate(
"""
if $parsedValue.len() > 1 {
Err(#{header_util}::ParseError::new(format!("expected one item but found {}", $parsedValue.len())))
} else {
let mut $parsedValue = $parsedValue;
Ok($parsedValue.pop())
}
""",
"header_util" to headerUtil,
)
}
}
}
}
/**
* Generate a unique name for the deserializer function for a given [operationShape] and HTTP binding.
*/
// Rename here technically not required, operations and members cannot be renamed.
private fun fnName(operationShape: OperationShape, binding: HttpBindingDescriptor) =
"${
operationShape.id.getName(service).toSnakeCase()
}_${binding.member.container.name.toSnakeCase()}_${binding.memberName.toSnakeCase()}"
/**
* Returns a function to set headers on an HTTP message for the given [shape].
* Returns null if no headers need to be set.
*
* [shape] can either be:
* - an [OperationShape], in which case the header-bound data is in its input or output shape; or
* - an error shape (i.e. a [StructureShape] with the `error` trait), in which case the header-bound data is in the shape itself.
*/
fun generateAddHeadersFn(
shape: Shape,
httpMessageType: HttpMessageType = HttpMessageType.REQUEST,
): RuntimeType? {
val (headerBindings, prefixHeaderBinding) = when (httpMessageType) {
// Only a single structure member can be bound by `httpPrefixHeaders`, hence the `getOrNull(0)`.
HttpMessageType.REQUEST -> index.getRequestBindings(shape, HttpLocation.HEADER) to
index.getRequestBindings(shape, HttpLocation.PREFIX_HEADERS).getOrNull(0)
HttpMessageType.RESPONSE -> index.getResponseBindings(shape, HttpLocation.HEADER) to
index.getResponseBindings(shape, HttpLocation.PREFIX_HEADERS).getOrNull(0)
}
if (headerBindings.isEmpty() && prefixHeaderBinding == null) {
return null
}
val fnName = "add_headers_${shape.id.getName(service).toSnakeCase()}"
return RuntimeType.forInlineFun(fnName, httpSerdeModule) {
// If the shape is an operation shape, the input symbol of the generated function is the input or output
// shape, which is the shape holding the header-bound data.
val shapeSymbol = symbolProvider.toSymbol(
if (shape is OperationShape) {
when (httpMessageType) {
HttpMessageType.REQUEST -> shape.inputShape(model)
HttpMessageType.RESPONSE -> shape.outputShape(model)
}
} else {
shape
},
)
val codegenScope = arrayOf(
"BuildError" to runtimeConfig.operationBuildError(),
HttpMessageType.REQUEST.name to RuntimeType.HttpRequestBuilder,
HttpMessageType.RESPONSE.name to RuntimeType.HttpResponseBuilder,
"Shape" to shapeSymbol,
)
rustBlockTemplate(
"""
pub fn $fnName(
input: &#{Shape},
mut builder: #{${httpMessageType.name}}
) -> std::result::Result<#{${httpMessageType.name}}, #{BuildError}>
""",
*codegenScope,
) {
headerBindings.forEach { httpBinding -> renderHeaders(httpBinding) }
if (prefixHeaderBinding != null) {
renderPrefixHeader(prefixHeaderBinding)
}
rust("Ok(builder)")
}
}
}
private fun RustWriter.renderHeaders(httpBinding: HttpBinding) {
check(httpBinding.location == HttpLocation.HEADER)
val memberShape = httpBinding.member
val targetShape = model.expectShape(memberShape.target)
val memberName = symbolProvider.toMemberName(memberShape)
val headerName = httpBinding.locationName
val timestampFormat =
index.determineTimestampFormat(memberShape, HttpBinding.Location.HEADER, defaultTimestampFormat)
val renderErrorMessage = { headerValueVariableName: String ->
OperationBuildError(runtimeConfig).invalidField(memberName) {
rust(
"""
format!(
"`{}` cannot be used as a header value: {}",
&${memberShape.redactIfNecessary(model, headerValueVariableName)},
err
)
""",
)
}
}
val memberSymbol = symbolProvider.toSymbol(memberShape)
// If a header is of a primitive type and required (e.g. `bool`), we do not serialize it on the
// wire if it's set to the default value for that primitive type (e.g. `false` for `bool`).
// If the header is optional, instead, we want to serialize it if it has been set by the user to the
// default value for that primitive type (e.g. `Some(false)` for an `Option<bool>` header).
// If a header is multivalued, we always want to serialize its primitive members, regardless of their
// values.
val serializePrimitiveValuesIfDefault = memberSymbol.isOptional() || (targetShape is CollectionShape)
ifSome(memberSymbol, ValueExpression.Reference("&input.$memberName")) { variableName ->
if (targetShape is CollectionShape) {
renderMultiValuedHeader(
model,
headerName,
variableName,
targetShape,
timestampFormat,
renderErrorMessage,
)
} else {
renderHeaderValue(
headerName,
variableName,
targetShape,
false,
timestampFormat,
renderErrorMessage,
serializePrimitiveValuesIfDefault,
)
}
}
}
private fun RustWriter.renderMultiValuedHeader(
model: Model,
headerName: String,
value: ValueExpression,
shape: CollectionShape,
timestampFormat: TimestampFormatTrait.Format,
renderErrorMessage: (String) -> Writable,
) {
val loopVariable = ValueExpression.Reference(safeName("inner"))
val context = HeaderValueSerializationContext(value, shape)
for (customization in customizations) {
customization.section(
HttpBindingSection.BeforeRenderingHeaderValue(context),
)(this)
}
rustBlock("for ${loopVariable.name} in ${context.valueExpression.asRef()}") {
this.renderHeaderValue(
headerName,
loopVariable,
model.expectShape(shape.member.target),
isMultiValuedHeader = true,
timestampFormat,
renderErrorMessage,
serializeIfDefault = true,
)
}
}
data class HeaderValueSerializationContext(
/** Expression representing the value to write to the JsonValueWriter */
var valueExpression: ValueExpression,
/** Path in the JSON to get here, used for errors */
val shape: Shape,
)
private fun RustWriter.renderHeaderValue(
headerName: String,
value: ValueExpression,
shape: Shape,
isMultiValuedHeader: Boolean,
timestampFormat: TimestampFormatTrait.Format,
renderErrorMessage: (String) -> Writable,
serializeIfDefault: Boolean,
) {
val context = HeaderValueSerializationContext(value, shape)
for (customization in customizations) {
customization.section(
HttpBindingSection.BeforeRenderingHeaderValue(context),
)(this)
}
val block: RustWriter.(value: ValueExpression) -> Unit = { variableName ->
if (shape.isPrimitive()) {
val encoder = RuntimeType.smithyTypes(runtimeConfig).resolve("primitive::Encoder")
rust("let mut encoder = #T::from(${variableName.asValue()});", encoder)
}
val formatted = headerFmtFun(
this,
shape,
timestampFormat,
context.valueExpression.name,
isMultiValuedHeader = isMultiValuedHeader,
)
val safeName = safeName("formatted")
rustTemplate(
"""
let $safeName = $formatted;
if !$safeName.is_empty() {
let header_value = $safeName;
let header_value: #{HeaderValue} = header_value.parse().map_err(|err| {
#{invalid_field_error:W}
})?;
builder = builder.header("$headerName", header_value);
}
""",
"HeaderValue" to RuntimeType.Http.resolve("HeaderValue"),
"invalid_field_error" to renderErrorMessage("header_value"),
)
}
if (serializeIfDefault) {
block(context.valueExpression)
} else {
ifNotDefault(context.shape, context.valueExpression, block)
}
}
private fun RustWriter.renderPrefixHeader(httpBinding: HttpBinding) {
check(httpBinding.location == HttpLocation.PREFIX_HEADERS)
val memberShape = httpBinding.member
val targetShape = model.expectShape(memberShape.target, MapShape::class.java)
val memberSymbol = symbolProvider.toSymbol(memberShape)
val memberName = symbolProvider.toMemberName(memberShape)
val valueTargetShape = model.expectShape(targetShape.value.target)
val timestampFormat =
index.determineTimestampFormat(memberShape, HttpBinding.Location.HEADER, defaultTimestampFormat)
ifSet(targetShape, memberSymbol, ValueExpression.Reference("&input.$memberName")) { local ->
for (customization in customizations) {
customization.section(
HttpBindingSection.BeforeIteratingOverMapShapeBoundWithHttpPrefixHeaders(local.name, targetShape),
)(this)
}
rustTemplate(
"""
for (k, v) in ${local.asRef()} {
use std::str::FromStr;
let header_name = http::header::HeaderName::from_str(&format!("{}{}", "${httpBinding.locationName}", &k)).map_err(|err| {
#{invalid_header_name:W}
})?;
let header_value = ${
headerFmtFun(
this,
valueTargetShape,
timestampFormat,
"v",
isMultiValuedHeader = false,
)
};
let header_value: #{HeaderValue} = header_value.parse().map_err(|err| {
#{invalid_header_value:W}
})?;
builder = builder.header(header_name, header_value);
}
""",
"HeaderValue" to RuntimeType.Http.resolve("HeaderValue"),
"invalid_header_name" to OperationBuildError(runtimeConfig).invalidField(memberName) {
rust("""format!("`{k}` cannot be used as a header name: {err}")""")
},
"invalid_header_value" to OperationBuildError(runtimeConfig).invalidField(memberName) {
rust(
"""
format!(
"`{}` cannot be used as a header value: {}",
${memberShape.redactIfNecessary(model, "v")},
err
)
""",
)
},
)
}
}
/**
* Format [member] when used as an HTTP header.
*/
private fun headerFmtFun(
writer: RustWriter,
target: Shape,
timestampFormat: TimestampFormatTrait.Format,
targetName: String,
isMultiValuedHeader: Boolean,
): String {
fun quoteValue(value: String): String {
// Timestamp shapes are not quoted in header lists
return if (isMultiValuedHeader && !target.isTimestampShape) {
val quoteFn = writer.format(headerUtil.resolve("quote_header_value"))
"$quoteFn($value)"
} else {
value
}
}
return when {
target.isStringShape -> {
if (target.hasTrait<MediaTypeTrait>()) {
val func = writer.format(RuntimeType.base64Encode(runtimeConfig))
"$func(&$targetName)"
} else {
quoteValue("$targetName.as_str()")
}
}
target.isTimestampShape -> {
val timestampFormatType = RuntimeType.timestampFormat(runtimeConfig, timestampFormat)
quoteValue("$targetName.fmt(${writer.format(timestampFormatType)})?")
}
target.isListShape || target.isMemberShape -> {
throw IllegalArgumentException("lists should be handled at a higher level")
}
target.isPrimitive() -> {
"encoder.encode()"
}
else -> throw CodegenException("unexpected shape: $target")
}
}
}