/
HttpBindingProtocolGenerator.java
1554 lines (1378 loc) · 71.5 KB
/
HttpBindingProtocolGenerator.java
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 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.go.codegen.integration;
import static software.amazon.smithy.go.codegen.integration.ProtocolUtils.requiresDocumentSerdeFunction;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.logging.Logger;
import java.util.stream.Collectors;
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.go.codegen.ApplicationProtocol;
import software.amazon.smithy.go.codegen.CodegenUtils;
import software.amazon.smithy.go.codegen.GoEventStreamIndex;
import software.amazon.smithy.go.codegen.GoStackStepMiddlewareGenerator;
import software.amazon.smithy.go.codegen.GoValueAccessUtils;
import software.amazon.smithy.go.codegen.GoWriter;
import software.amazon.smithy.go.codegen.SmithyGoDependency;
import software.amazon.smithy.go.codegen.SymbolUtils;
import software.amazon.smithy.go.codegen.knowledge.GoPointableIndex;
import software.amazon.smithy.go.codegen.trait.NoSerializeTrait;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.EventStreamIndex;
import software.amazon.smithy.model.knowledge.EventStreamInfo;
import software.amazon.smithy.model.knowledge.HttpBinding;
import software.amazon.smithy.model.knowledge.HttpBindingIndex;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.CollectionShape;
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.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.ShapeType;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.ToShapeId;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.EnumTrait;
import software.amazon.smithy.model.traits.HttpTrait;
import software.amazon.smithy.model.traits.MediaTypeTrait;
import software.amazon.smithy.model.traits.StreamingTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.utils.OptionalUtils;
/**
* Abstract implementation useful for all protocols that use HTTP bindings.
*/
public abstract class HttpBindingProtocolGenerator implements ProtocolGenerator {
private static final Logger LOGGER = Logger.getLogger(HttpBindingProtocolGenerator.class.getName());
private final boolean isErrorCodeInBody;
private final Set<Shape> serializeDocumentBindingShapes = new TreeSet<>();
private final Set<Shape> deserializeDocumentBindingShapes = new TreeSet<>();
private final Set<StructureShape> deserializingErrorShapes = new TreeSet<>();
/**
* Creates a Http binding protocol generator.
*
* @param isErrorCodeInBody A boolean that indicates if the error code for the implementing protocol is located in
* the error response body, meaning this generator will parse the body before attempting to
* load an error code.
*/
public HttpBindingProtocolGenerator(boolean isErrorCodeInBody) {
this.isErrorCodeInBody = isErrorCodeInBody;
}
@Override
public ApplicationProtocol getApplicationProtocol() {
return ApplicationProtocol.createDefaultHttpApplicationProtocol();
}
@Override
public void generateSharedSerializerComponents(GenerationContext context) {
serializeDocumentBindingShapes.addAll(ProtocolUtils.resolveRequiredDocumentShapeSerde(
context.getModel(), serializeDocumentBindingShapes));
generateDocumentBodyShapeSerializers(context, serializeDocumentBindingShapes);
}
/**
* Get the operations with HTTP Bindings.
*
* @param context the generation context
* @return the list of operation shapes
*/
public Set<OperationShape> getHttpBindingOperations(GenerationContext context) {
TopDownIndex topDownIndex = context.getModel().getKnowledge(TopDownIndex.class);
Set<OperationShape> containedOperations = new TreeSet<>();
for (OperationShape operation : topDownIndex.getContainedOperations(context.getService())) {
OptionalUtils.ifPresentOrElse(
operation.getTrait(HttpTrait.class),
httpTrait -> containedOperations.add(operation),
() -> LOGGER.warning(String.format(
"Unable to fetch %s protocol request bindings for %s because it does not have an "
+ "http binding trait", getProtocol(), operation.getId()))
);
}
return containedOperations;
}
@Override
public void generateRequestSerializers(GenerationContext context) {
Set<OperationShape> operations = getHttpBindingOperations(context);
for (OperationShape operation : operations) {
generateOperationSerializer(context, operation);
}
GoEventStreamIndex goEventStreamIndex = GoEventStreamIndex.of(context.getModel());
goEventStreamIndex.getInputEventStreams(context.getService()).ifPresent(shapeIdSetMap ->
shapeIdSetMap.forEach((shapeId, eventStreamInfos) -> {
generateEventStreamSerializers(context, context.getModel().expectShape(shapeId, UnionShape.class),
eventStreamInfos);
}));
}
/**
* Generate the event stream serializers for the given event stream target and associated operations.
*
* @param context the generation context
* @param eventUnion the event stream union
* @param eventStreamInfos the event stream infos
*/
protected abstract void generateEventStreamSerializers(
GenerationContext context,
UnionShape eventUnion,
Set<EventStreamInfo> eventStreamInfos
);
/**
* Generate the event stream deserializers for the given event stream target and asscioated operations.
*
* @param context the generation context
* @param eventUnion the event stream union
* @param eventStreamInfos the event stream infos
*/
protected abstract void generateEventStreamDeserializers(
GenerationContext context,
UnionShape eventUnion,
Set<EventStreamInfo> eventStreamInfos
);
/**
* Gets the default serde format for timestamps.
*
* @return Returns the default format.
*/
protected abstract Format getDocumentTimestampFormat();
/**
* Gets the default content-type when a document is synthesized in the body.
*
* @return Returns the default content-type.
*/
protected abstract String getDocumentContentType();
private void generateOperationSerializer(GenerationContext context, OperationShape operation) {
generateOperationSerializerMiddleware(context, operation);
generateOperationHttpBindingSerializer(context, operation);
Optional<EventStreamInfo> streamInfo = EventStreamIndex.of(context.getModel()).getInputInfo(operation);
if (!CodegenUtils.isStubSyntheticClone(ProtocolUtils.expectInput(context.getModel(), operation))
&& streamInfo.isEmpty()) {
generateOperationDocumentSerializer(context, operation);
addOperationDocumentShapeBindersForSerializer(context, operation);
}
}
/**
* Generates the operation document serializer function.
*
* @param context the generation context
* @param operation the operation shape being generated
*/
protected abstract void generateOperationDocumentSerializer(GenerationContext context, OperationShape operation);
/**
* Adds the top-level shapes from the operation that bind to the body document that require serializer functions.
*
* @param context the generator context
* @param operation the operation to add document binders from
*/
private void addOperationDocumentShapeBindersForSerializer(GenerationContext context, OperationShape operation) {
Model model = context.getModel();
// Walk and add members shapes to the list that will require serializer functions
Collection<HttpBinding> bindings = HttpBindingIndex.of(model)
.getRequestBindings(operation).values();
for (HttpBinding binding : bindings) {
MemberShape memberShape = binding.getMember();
Shape targetShape = model.expectShape(memberShape.getTarget());
// Check if the input shape has a members that target the document or payload and require serializers.
// If an operation has an input event stream it will have seperate serializers generated.
if (requiresDocumentSerdeFunction(targetShape)
&& (binding.getLocation() == HttpBinding.Location.DOCUMENT
|| binding.getLocation() == HttpBinding.Location.PAYLOAD)) {
serializeDocumentBindingShapes.add(targetShape);
}
}
}
private void generateOperationSerializerMiddleware(GenerationContext context, OperationShape operation) {
SymbolProvider symbolProvider = context.getSymbolProvider();
Model model = context.getModel();
ServiceShape service = context.getService();
Shape inputShape = model.expectShape(operation.getInput()
.orElseThrow(() -> new CodegenException("expect input shape for operation: " + operation.getId())));
Symbol inputSymbol = symbolProvider.toSymbol(inputShape);
ApplicationProtocol applicationProtocol = getApplicationProtocol();
Symbol requestType = applicationProtocol.getRequestType();
HttpTrait httpTrait = operation.expectTrait(HttpTrait.class);
GoStackStepMiddlewareGenerator middleware = GoStackStepMiddlewareGenerator.createSerializeStepMiddleware(
ProtocolGenerator.getSerializeMiddlewareName(operation.getId(), service, getProtocolName()),
ProtocolUtils.OPERATION_SERIALIZER_MIDDLEWARE_ID);
middleware.writeMiddleware(context.getWriter().get(), (generator, writer) -> {
writer.addUseImports(SmithyGoDependency.FMT);
writer.addUseImports(SmithyGoDependency.SMITHY);
writer.addUseImports(SmithyGoDependency.SMITHY_HTTP_BINDING);
// cast input request to smithy transport type, check for failures
writer.write("request, ok := in.Request.($P)", requestType);
writer.openBlock("if !ok {", "}", () -> {
writer.write("return out, metadata, "
+ "&smithy.SerializationError{Err: fmt.Errorf(\"unknown transport type %T\", in.Request)}"
);
});
writer.write("");
// cast input parameters type to the input type of the operation
writer.write("input, ok := in.Parameters.($P)", inputSymbol);
writer.write("_ = input");
writer.openBlock("if !ok {", "}", () -> {
writer.write("return out, metadata, "
+ "&smithy.SerializationError{Err: fmt.Errorf(\"unknown input parameters type %T\","
+ " in.Parameters)}");
});
writer.write("");
writer.write("opPath, opQuery := httpbinding.SplitURI($S)", httpTrait.getUri());
writer.write("request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath)");
writer.write("request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery)");
writer.write("request.Method = $S", httpTrait.getMethod());
writer.write("restEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, "
+ "request.Header)");
writer.openBlock("if err != nil {", "}", () -> {
writer.write("return out, metadata, &smithy.SerializationError{Err: err}");
});
writer.write("");
// we only generate an operations http bindings function if there are bindings
if (isOperationWithRestRequestBindings(model, operation)) {
String serFunctionName = ProtocolGenerator.getOperationHttpBindingsSerFunctionName(
inputShape, service, getProtocolName());
writer.openBlock("if err := $L(input, restEncoder); err != nil {", "}", serFunctionName, () -> {
writer.write("return out, metadata, &smithy.SerializationError{Err: err}");
});
writer.write("");
}
// Don't consider serializing the body if the input shape is a stubbed synthetic clone, without an
// archetype.
if (!CodegenUtils.isStubSyntheticClone(ProtocolUtils.expectInput(model, operation))) {
Optional<EventStreamInfo> eventStreamInfo = EventStreamIndex.of(model).getInputInfo(operation);
// document bindings vs payload bindings vs event streams
HttpBindingIndex httpBindingIndex = HttpBindingIndex.of(model);
boolean hasDocumentBindings = httpBindingIndex
.getRequestBindings(operation, HttpBinding.Location.DOCUMENT)
.stream().anyMatch(httpBinding -> eventStreamInfo.map(streamInfo ->
!streamInfo.getEventStreamMember().equals(httpBinding.getMember())).orElse(true));
Optional<HttpBinding> payloadBinding = httpBindingIndex.getRequestBindings(operation,
HttpBinding.Location.PAYLOAD).stream()
.filter(httpBinding -> eventStreamInfo.map(streamInfo ->
!streamInfo.getEventStreamMember().equals(httpBinding.getMember())).orElse(true))
.findFirst();
if (eventStreamInfo.isPresent() && (hasDocumentBindings || payloadBinding.isPresent())) {
throw new CodegenException("HTTP Binding Protocol unexpected document or payload bindings with "
+ "input event stream");
}
if (eventStreamInfo.isPresent()) {
writeOperationSerializerMiddlewareEventStreamSetup(context, eventStreamInfo.get());
} else if (hasDocumentBindings) {
// delegate the setup and usage of the document serializer function for the protocol
writeMiddlewareDocumentSerializerDelegator(context, operation, generator);
} else if (payloadBinding.isPresent()) {
// delegate the setup and usage of the payload serializer function for the protocol
MemberShape memberShape = payloadBinding.get().getMember();
writeMiddlewarePayloadSerializerDelegator(context, memberShape);
}
writer.write("");
}
// Serialize HTTP request with payload, if set.
writer.openBlock("if request.Request, err = restEncoder.Encode(request.Request); err != nil {", "}", () -> {
writer.write("return out, metadata, &smithy.SerializationError{Err: err}");
});
writer.write("in.Request = request");
writer.write("");
writer.write("return next.$L(ctx, in)", generator.getHandleMethodName());
});
}
protected abstract void writeOperationSerializerMiddlewareEventStreamSetup(
GenerationContext context,
EventStreamInfo eventStreamInfo
);
// Generates operation deserializer middleware that delegates to appropriate deserializers for the error,
// output shapes for the operation.
private void generateOperationDeserializerMiddleware(GenerationContext context, OperationShape operation) {
SymbolProvider symbolProvider = context.getSymbolProvider();
Model model = context.getModel();
ServiceShape service = context.getService();
ApplicationProtocol applicationProtocol = getApplicationProtocol();
Symbol responseType = applicationProtocol.getResponseType();
GoWriter goWriter = context.getWriter().get();
GoStackStepMiddlewareGenerator middleware = GoStackStepMiddlewareGenerator.createDeserializeStepMiddleware(
ProtocolGenerator.getDeserializeMiddlewareName(operation.getId(), service, getProtocolName()),
ProtocolUtils.OPERATION_DESERIALIZER_MIDDLEWARE_ID);
String errorFunctionName = ProtocolGenerator.getOperationErrorDeserFunctionName(
operation, service, context.getProtocolName());
middleware.writeMiddleware(goWriter, (generator, writer) -> {
writer.addUseImports(SmithyGoDependency.FMT);
writer.write("out, metadata, err = next.$L(ctx, in)", generator.getHandleMethodName());
writer.write("if err != nil { return out, metadata, err }");
writer.write("");
writer.write("response, ok := out.RawResponse.($P)", responseType);
writer.openBlock("if !ok {", "}", () -> {
writer.addUseImports(SmithyGoDependency.SMITHY);
writer.write(String.format("return out, metadata, &smithy.DeserializationError{Err: %s}",
"fmt.Errorf(\"unknown transport type %T\", out.RawResponse)"));
});
writer.write("");
writer.openBlock("if response.StatusCode < 200 || response.StatusCode >= 300 {", "}", () -> {
writer.write("return out, metadata, $L(response, &metadata)", errorFunctionName);
});
Shape outputShape = model.expectShape(operation.getOutput()
.orElseThrow(() -> new CodegenException("expect output shape for operation: " + operation.getId()))
);
Symbol outputSymbol = symbolProvider.toSymbol(outputShape);
// initialize out.Result as output structure shape
writer.write("output := &$T{}", outputSymbol);
writer.write("out.Result = output");
writer.write("");
// Output shape HTTP binding middleware generation
if (isShapeWithRestResponseBindings(model, operation)) {
String deserFuncName = ProtocolGenerator.getOperationHttpBindingsDeserFunctionName(
outputShape, service, getProtocolName());
writer.write("err= $L(output, response)", deserFuncName);
writer.openBlock("if err != nil {", "}", () -> {
writer.addUseImports(SmithyGoDependency.SMITHY);
writer.write(String.format("return out, metadata, &smithy.DeserializationError{Err: %s}",
"fmt.Errorf(\"failed to decode response with invalid Http bindings, %w\", err)"));
});
writer.write("");
}
Optional<EventStreamInfo> streamInfoOptional = EventStreamIndex.of(model).getOutputInfo(operation);
// Discard without deserializing the response if the input shape is a stubbed synthetic clone
// without an archetype.
if (CodegenUtils.isStubSyntheticClone(ProtocolUtils.expectOutput(model, operation))
&& streamInfoOptional.isEmpty()) {
writer.addUseImports(SmithyGoDependency.IOUTIL);
writer.openBlock("if _, err = io.Copy(ioutil.Discard, response.Body); err != nil {", "}", () -> {
writer.openBlock("return out, metadata, &smithy.DeserializationError{", "}", () -> {
writer.write("Err: fmt.Errorf(\"failed to discard response body, %w\", err),");
});
});
} else {
boolean hasBodyBinding = HttpBindingIndex.of(model).getResponseBindings(operation).values().stream()
.filter(httpBinding -> httpBinding.getLocation() == HttpBinding.Location.DOCUMENT
|| httpBinding.getLocation() == HttpBinding.Location.PAYLOAD)
.anyMatch(httpBinding -> streamInfoOptional.map(esi -> !esi.getEventStreamMember()
.equals(httpBinding.getMember())).orElse(true));
if (hasBodyBinding && streamInfoOptional.isPresent()) {
throw new CodegenException("HTTP Binding Protocol unexpected document or payload bindings with "
+ "output event stream");
}
if (hasBodyBinding) {
// Output Shape Document Binding middleware generation
writeMiddlewareDocumentDeserializerDelegator(context, operation, generator);
}
}
writer.write("");
writer.write("return out, metadata, err");
});
goWriter.write("");
Set<StructureShape> errorShapes = HttpProtocolGeneratorUtils.generateErrorDispatcher(
context, operation, responseType, this::writeErrorMessageCodeDeserializer,
this::getOperationErrors);
deserializingErrorShapes.addAll(errorShapes);
deserializeDocumentBindingShapes.addAll(errorShapes);
}
/**
* Writes a code snippet that gets the error code and error message.
*
* <p>Four parameters will be available in scope:
* <ul>
* <li>{@code response: smithyhttp.HTTPResponse}: the HTTP response received.</li>
* <li>{@code errorBody: bytes.BytesReader}: the HTTP response body.</li>
* <li>{@code errorMessage: string}: the error message initialized to a default value.</li>
* <li>{@code errorCode: string}: the error code initialized to a default value.</li>
* </ul>
*
* @param context the generation context.
*/
protected abstract void writeErrorMessageCodeDeserializer(GenerationContext context);
/**
* Generate the document serializer logic for the serializer middleware body.
*
* @param context the generation context
* @param operation the operation
* @param generator middleware generator definition
*/
protected abstract void writeMiddlewareDocumentSerializerDelegator(
GenerationContext context,
OperationShape operation,
GoStackStepMiddlewareGenerator generator
);
/**
* Writes a payload content-type header setter.
*
* @param writer the {@link GoWriter}.
* @param payloadShape the payload shape.
*/
protected void writeSetPayloadShapeHeader(GoWriter writer, Shape payloadShape) {
writer.pushState();
writer.putContext("withIsDefaultContentType", SymbolUtils.createValueSymbolBuilder(
"SetIsContentTypeDefaultValue", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build());
writer.putContext("payloadMediaType", getPayloadShapeMediaType(payloadShape));
writer.write("""
if !restEncoder.HasHeader("Content-Type") {
ctx = $withIsDefaultContentType:T(ctx, true)
restEncoder.SetHeader("Content-Type").String($payloadMediaType:S)
}
""");
writer.popState();
}
/**
* Writes the stream setter that set the operand as the HTTP body.
*
* @param writer the {@link GoWriter}.
* @param operand the operand for the value to be set as the HTTP body.
*/
protected void writeSetStream(GoWriter writer, String operand) {
writer.write("""
if request, err = request.SetStream($L); err != nil {
return out, metadata, &smithy.SerializationError{Err: err}
}""", operand);
}
/**
* Generate the payload serializer logic for the serializer middleware body.
*
* @param context the generation context
* @param memberShape the payload target member
*/
protected void writeMiddlewarePayloadSerializerDelegator(
GenerationContext context,
MemberShape memberShape
) {
GoWriter writer = context.getWriter().get();
Model model = context.getModel();
Shape payloadShape = model.expectShape(memberShape.getTarget());
if (payloadShape.hasTrait(StreamingTrait.class)) {
writeSetPayloadShapeHeader(writer, payloadShape);
GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer,
memberShape, "input", (s) -> {
writer.write("payload := $L", s);
writeSetStream(writer, "payload");
});
} else if (payloadShape.isBlobShape()) {
writeSetPayloadShapeHeader(writer, payloadShape);
GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer,
memberShape, "input", (s) -> {
writer.addUseImports(SmithyGoDependency.BYTES);
writer.write("payload := bytes.NewReader($L)", s);
writeSetStream(writer, "payload");
});
} else if (payloadShape.isStringShape()) {
writeSetPayloadShapeHeader(writer, payloadShape);
GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer,
memberShape, "input", (s) -> {
writer.addUseImports(SmithyGoDependency.STRINGS);
if (payloadShape.hasTrait(EnumTrait.class)) {
writer.write("payload := strings.NewReader(string($L))", s);
} else {
writer.write("payload := strings.NewReader(*$L)", s);
}
writeSetStream(writer, "payload");
});
} else {
writeMiddlewarePayloadAsDocumentSerializerDelegator(context, memberShape, "input");
}
}
/**
* Returns the MediaType for the payload shape derived from the MediaTypeTrait, shape type, or
* document content type.
*
* @param payloadShape shape bound to the payload.
* @return string for media type.
*/
private String getPayloadShapeMediaType(Shape payloadShape) {
Optional<MediaTypeTrait> mediaTypeTrait = payloadShape.getTrait(MediaTypeTrait.class);
if (mediaTypeTrait.isPresent()) {
return mediaTypeTrait.get().getValue();
}
if (payloadShape.isBlobShape()) {
return "application/octet-stream";
}
if (payloadShape.isStringShape()) {
return "text/plain";
}
return getDocumentContentType();
}
/**
* Generate the payload serializers with document serializer logic for the serializer middleware body.
*
* @param context the generation context
* @param memberShape the payload target member
* @param operand the operand that is used to access the member value
*/
protected abstract void writeMiddlewarePayloadAsDocumentSerializerDelegator(
GenerationContext context,
MemberShape memberShape,
String operand
);
/**
* Generate the document deserializer logic for the deserializer middleware body.
*
* @param context the generation context
* @param operation the operation
* @param generator middleware generator definition
*/
protected abstract void writeMiddlewareDocumentDeserializerDelegator(
GenerationContext context,
OperationShape operation,
GoStackStepMiddlewareGenerator generator
);
private boolean isRestBinding(HttpBinding.Location location) {
return location == HttpBinding.Location.HEADER
|| location == HttpBinding.Location.PREFIX_HEADERS
|| location == HttpBinding.Location.LABEL
|| location == HttpBinding.Location.QUERY
|| location == HttpBinding.Location.QUERY_PARAMS
|| location == HttpBinding.Location.RESPONSE_CODE;
}
// returns whether an operation shape has Rest Request Bindings
private boolean isOperationWithRestRequestBindings(Model model, OperationShape operationShape) {
Collection<HttpBinding> bindings = HttpBindingIndex.of(model)
.getRequestBindings(operationShape).values();
for (HttpBinding binding : bindings) {
if (isRestBinding(binding.getLocation())) {
return true;
}
}
return false;
}
/**
* Returns whether a shape has rest response bindings.
* The shape can be an operation shape, error shape or an output shape.
*
* @param model the model
* @param shape the shape with possible presence of rest response bindings
* @return boolean indicating presence of rest response bindings in the shape
*/
protected boolean isShapeWithRestResponseBindings(Model model, Shape shape) {
Collection<HttpBinding> bindings = HttpBindingIndex.of(model).getResponseBindings(shape).values();
for (HttpBinding binding : bindings) {
if (isRestBinding(binding.getLocation())) {
return true;
}
}
return false;
}
private void generateOperationHttpBindingSerializer(GenerationContext context, OperationShape operation) {
SymbolProvider symbolProvider = context.getSymbolProvider();
Model model = context.getModel();
GoWriter writer = context.getWriter().get();
Shape inputShape = model.expectShape(operation.getInput()
.orElseThrow(() -> new CodegenException("missing input shape for operation: " + operation.getId())));
HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class);
List<HttpBinding> bindings = bindingIndex.getRequestBindings(operation).values().stream()
.filter(httpBinding -> isRestBinding(httpBinding.getLocation()))
.sorted(Comparator.comparing(HttpBinding::getMember))
.collect(Collectors.toList());
Symbol httpBindingEncoder = getHttpBindingEncoderSymbol();
Symbol inputSymbol = symbolProvider.toSymbol(inputShape);
String functionName = ProtocolGenerator.getOperationHttpBindingsSerFunctionName(
inputShape, context.getService(), getProtocolName());
writer.addUseImports(SmithyGoDependency.FMT);
writer.openBlock("func $L(v $P, encoder $P) error {", "}", functionName, inputSymbol, httpBindingEncoder,
() -> {
writer.openBlock("if v == nil {", "}", () -> {
writer.write("return fmt.Errorf(\"unsupported serialization of nil %T\", v)");
});
writer.write("");
for (HttpBinding binding : bindings.stream()
.filter(NoSerializeTrait.excludeNoSerializeHttpBindingMembers())
.collect(Collectors.toList())) {
writeHttpBindingMember(context, binding);
writer.write("");
}
writer.write("return nil");
});
writer.write("");
}
private Symbol getHttpBindingEncoderSymbol() {
return SymbolUtils.createPointableSymbolBuilder("Encoder", SmithyGoDependency.SMITHY_HTTP_BINDING).build();
}
private void generateHttpBindingTimestampSerializer(
Model model,
GoWriter writer,
MemberShape memberShape,
HttpBinding.Location location,
String operand,
BiConsumer<GoWriter, String> locationEncoder
) {
writer.addUseImports(SmithyGoDependency.SMITHY_TIME);
TimestampFormatTrait.Format format = model.getKnowledge(HttpBindingIndex.class).determineTimestampFormat(
memberShape, location, getDocumentTimestampFormat());
switch (format) {
case DATE_TIME:
locationEncoder.accept(writer, "String(smithytime.FormatDateTime(" + operand + "))");
break;
case HTTP_DATE:
locationEncoder.accept(writer, "String(smithytime.FormatHTTPDate(" + operand + "))");
break;
case EPOCH_SECONDS:
locationEncoder.accept(writer, "Double(smithytime.FormatEpochSeconds(" + operand + "))");
break;
default:
throw new CodegenException("Unknown timestamp format");
}
}
private boolean isHttpDateTimestamp(Model model, HttpBinding.Location location, MemberShape memberShape) {
Shape targetShape = model.expectShape(memberShape.getTarget().toShapeId());
if (targetShape.getType() != ShapeType.TIMESTAMP) {
return false;
}
TimestampFormatTrait.Format format = HttpBindingIndex.of(model).determineTimestampFormat(
memberShape, location, getDocumentTimestampFormat());
return format == Format.HTTP_DATE;
}
private void writeHttpBindingSetter(
GenerationContext context,
GoWriter writer,
MemberShape memberShape,
HttpBinding.Location location,
String operand,
BiConsumer<GoWriter, String> locationEncoder
) {
Model model = context.getModel();
Shape targetShape = model.expectShape(memberShape.getTarget());
// We only need to dereference if we pass the shape around as reference in Go.
// Note we make two exceptions here: big.Int and big.Float should still be passed as reference to the helper
// method as they can be arbitrarily large.
operand = CodegenUtils.getAsValueIfDereferencable(GoPointableIndex.of(context.getModel()), memberShape,
operand);
switch (targetShape.getType()) {
case BOOLEAN:
locationEncoder.accept(writer, "Boolean(" + operand + ")");
break;
case STRING:
operand = targetShape.hasTrait(EnumTrait.class) ? "string(" + operand + ")" : operand;
locationEncoder.accept(writer, "String(" + operand + ")");
break;
case TIMESTAMP:
generateHttpBindingTimestampSerializer(model, writer, memberShape, location, operand, locationEncoder);
break;
case BYTE:
locationEncoder.accept(writer, "Byte(" + operand + ")");
break;
case SHORT:
locationEncoder.accept(writer, "Short(" + operand + ")");
break;
case INTEGER:
locationEncoder.accept(writer, "Integer(" + operand + ")");
break;
case LONG:
locationEncoder.accept(writer, "Long(" + operand + ")");
break;
case FLOAT:
locationEncoder.accept(writer, "Float(" + operand + ")");
break;
case DOUBLE:
locationEncoder.accept(writer, "Double(" + operand + ")");
break;
case BIG_INTEGER:
locationEncoder.accept(writer, "BigInteger(" + operand + ")");
break;
case BIG_DECIMAL:
locationEncoder.accept(writer, "BigDecimal(" + operand + ")");
break;
default:
throw new CodegenException("unexpected shape type " + targetShape.getType());
}
}
private void writeHttpBindingMember(
GenerationContext context,
HttpBinding binding
) {
GoWriter writer = context.getWriter().get();
Model model = context.getModel();
MemberShape memberShape = binding.getMember();
Shape targetShape = model.expectShape(memberShape.getTarget());
HttpBinding.Location location = binding.getLocation();
// return an error if member shape targets location label, but is unset.
if (location.equals(HttpBinding.Location.LABEL)) {
// labels must always be set to be serialized on URI, and non empty strings,
GoValueAccessUtils.writeIfZeroValueMember(context.getModel(), context.getSymbolProvider(), writer,
memberShape, "v", false, true, operand -> {
writer.addUseImports(SmithyGoDependency.SMITHY);
writer.write("return &smithy.SerializationError { "
+ "Err: fmt.Errorf(\"input member $L must not be empty\")}",
memberShape.getMemberName());
});
}
boolean allowZeroStrings = location != HttpBinding.Location.HEADER;
GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer,
memberShape, "v", allowZeroStrings, memberShape.isRequired(), (operand) -> {
final String locationName = binding.getLocationName().isEmpty()
? memberShape.getMemberName() : binding.getLocationName();
switch (location) {
case HEADER:
writer.write("locationName := $S", getCanonicalHeader(locationName));
writeHeaderBinding(context, memberShape, operand, location, "locationName", "encoder");
break;
case PREFIX_HEADERS:
MemberShape valueMemberShape = model.expectShape(targetShape.getId(),
MapShape.class).getValue();
Shape valueMemberTarget = model.expectShape(valueMemberShape.getTarget());
if (targetShape.getType() != ShapeType.MAP) {
throw new CodegenException("Unexpected prefix headers target shape "
+ valueMemberTarget.getType() + ", "
+ valueMemberShape.getId());
}
writer.write("hv := encoder.Headers($S)", getCanonicalHeader(locationName));
writer.addUseImports(SmithyGoDependency.NET_HTTP);
writer.openBlock("for mapKey, mapVal := range $L {", "}", operand, () -> {
GoValueAccessUtils.writeIfNonZeroValue(context.getModel(), writer, valueMemberShape,
"mapVal", false, false, () -> {
writeHeaderBinding(context, valueMemberShape, "mapVal", location,
"http.CanonicalHeaderKey(mapKey)", "hv");
});
});
break;
case LABEL:
writeHttpBindingSetter(context, writer, memberShape, location, operand, (w, s) -> {
w.openBlock("if err := encoder.SetURI($S).$L; err != nil {", "}", locationName, s,
() -> {
w.write("return err");
});
});
break;
case QUERY:
writeQueryBinding(context, memberShape, targetShape, operand,
location, locationName, "encoder", false);
break;
case QUERY_PARAMS:
MemberShape queryMapValueMemberShape = CodegenUtils.expectMapShape(targetShape).getValue();
Shape queryMapValueTargetShape = model.expectShape(queryMapValueMemberShape.getTarget());
MemberShape queryMapKeyMemberShape = CodegenUtils.expectMapShape(targetShape).getKey();
writer.openBlock("for qkey, qvalue := range $L {", "}", operand, () -> {
writer.write("if encoder.HasQuery(qkey) { continue }");
writeQueryBinding(context, queryMapKeyMemberShape, queryMapValueTargetShape,
"qvalue", location, "qkey", "encoder", true);
});
break;
default:
throw new CodegenException("unexpected http binding found");
}
});
}
/**
* Writes query bindings, as per the target shape. This method is shared
* between members modeled with Location.Query and Location.QueryParams.
* Precedence across Location.Query and Location.QueryParams is handled
* outside the scope of this function.
*
* @param context is the generation context
* @param memberShape is the member shape for which query is serialized
* @param targetShape is the target shape of the query member.
* This can either be string, or a list/set of string.
* @param operand is the member value accessor .
* @param location is the location of the member - can be Location.Query
* or Location.QueryParams.
* @param locationName is the key for which query is encoded.
* @param dest is the query encoder destination.
* @param isQueryParams boolean representing if Location used for query binding is
* QUERY_PARAMS.
*/
private void writeQueryBinding(
GenerationContext context,
MemberShape memberShape,
Shape targetShape,
String operand,
HttpBinding.Location location,
String locationName,
String dest,
boolean isQueryParams
) {
GoWriter writer = context.getWriter().get();
if (targetShape instanceof CollectionShape) {
MemberShape collectionMember = CodegenUtils.expectCollectionShape(targetShape)
.getMember();
writer.openBlock("for i := range $L {", "}", operand, () -> {
GoValueAccessUtils.writeIfZeroValue(context.getModel(), writer, collectionMember,
operand + "[i]", () -> writer.write("continue"));
String addQuery = String.format("$L.AddQuery(%s).$L", isQueryParams ? "$L" : "$S");
writeHttpBindingSetter(context, writer, collectionMember, location, operand + "[i]",
(w, s) -> w.writeInline(addQuery, dest, locationName, s));
});
return;
}
String setQuery = String.format("$L.SetQuery(%s).$L", isQueryParams ? "$L" : "$S");
writeHttpBindingSetter(context, writer, memberShape, location, operand,
(w, s) -> w.writeInline(setQuery, dest, locationName, s));
}
private void writeHeaderBinding(
GenerationContext context,
MemberShape memberShape,
String operand,
HttpBinding.Location location,
String locationName,
String dest
) {
GoWriter writer = context.getWriter().get();
Model model = context.getModel();
Shape targetShape = model.expectShape(memberShape.getTarget());
if (!(targetShape instanceof CollectionShape)) {
String op = conditionallyBase64Encode(context, writer, targetShape, operand);
writeHttpBindingSetter(context, writer, memberShape, location, op, (w, s) -> {
w.writeInline("$L.SetHeader($L).$L", dest, locationName, s);
});
return;
}
MemberShape collectionMemberShape = CodegenUtils.expectCollectionShape(targetShape).getMember();
writer.openBlock("for i := range $L {", "}", operand, () -> {
// Only set non-empty non-nil header values
String indexedOperand = operand + "[i]";
GoValueAccessUtils.writeIfNonZeroValue(context.getModel(), writer, collectionMemberShape, indexedOperand,
false, false, () -> {
String op = conditionallyEscapeHeader(context, writer, collectionMemberShape, indexedOperand);
writeHttpBindingSetter(context, writer, collectionMemberShape, location, op,
(w, s) -> {
w.writeInline("$L.AddHeader($L).$L", dest, locationName, s);
});
});
});
}
private String conditionallyEscapeHeader(
GenerationContext context,
GoWriter writer,
MemberShape memberShape,
String operand
) {
var targetShape = context.getModel().expectShape(memberShape.getTarget());
if (!targetShape.isStringShape()) {
return operand;
}
if (targetShape.hasTrait(MediaTypeTrait.class)) {
return conditionallyBase64Encode(context, writer, targetShape, operand);
}
writer.pushState();
var returnVar = "escaped";
var pointableIndex = GoPointableIndex.of(context.getModel());
var shouldDereference = pointableIndex.isDereferencable(memberShape);
if (shouldDereference) {
operand = CodegenUtils.getAsValueIfDereferencable(pointableIndex, memberShape, operand);
writer.putContext("escapedVar", "escapedVal");
returnVar = "escapedPtr";
} else {
writer.putContext("escapedVar", returnVar);
}
writer.putContext("returnVar", returnVar);
if (targetShape.hasTrait(EnumTrait.class)) {
operand = "string(" + operand + ")";
}
writer.putContext("value", operand);
writer.putContext("quoteValue", SymbolUtils.createValueSymbolBuilder(
"Quote", SmithyGoDependency.STRCONV).build());
writer.putContext("indexOf", SymbolUtils.createValueSymbolBuilder(
"Index", SmithyGoDependency.STRINGS).build());
writer.putContext("ptrString", SymbolUtils.createValueSymbolBuilder(
"String", SmithyGoDependency.SMITHY_PTR).build());
writer.write("""
$escapedVar:L := $value:L
if $indexOf:T($value:L, `,`) != -1 || $indexOf:T($value:L, `"`) != -1 {
$escapedVar:L = $quoteValue:T($value:L)
}
""");