forked from aws/aws-sdk-go-v2
/
AwsProtocolUtils.java
373 lines (341 loc) · 19.6 KB
/
AwsProtocolUtils.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
/*
* 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.aws.go.codegen;
import java.util.Set;
import java.util.TreeSet;
import software.amazon.smithy.codegen.core.Symbol;
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.integration.HttpProtocolTestGenerator;
import software.amazon.smithy.go.codegen.integration.HttpProtocolUnitTestGenerator;
import software.amazon.smithy.go.codegen.integration.HttpProtocolUnitTestGenerator.ConfigValue;
import software.amazon.smithy.go.codegen.integration.HttpProtocolUnitTestRequestGenerator;
import software.amazon.smithy.go.codegen.integration.HttpProtocolUnitTestResponseErrorGenerator;
import software.amazon.smithy.go.codegen.integration.HttpProtocolUnitTestResponseGenerator;
import software.amazon.smithy.go.codegen.integration.IdempotencyTokenMiddlewareGenerator;
import software.amazon.smithy.go.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.utils.SetUtils;
/**
* Utility methods for generating AWS protocols.
*/
final class AwsProtocolUtils {
private AwsProtocolUtils() {
}
/**
* Generates HTTP protocol tests with all required AWS-specific configuration set.
*
* @param context The generation context.
*/
static void generateHttpProtocolTests(GenerationContext context) {
Set<HttpProtocolUnitTestGenerator.ConfigValue> configValues = new TreeSet<>(SetUtils.of(
HttpProtocolUnitTestGenerator.ConfigValue.builder()
.name(AddAwsConfigFields.REGION_CONFIG_NAME)
.value(writer -> writer.write("$S,", "us-west-2"))
.build(),
HttpProtocolUnitTestGenerator.ConfigValue.builder()
.name(AddAwsConfigFields.ENDPOINT_RESOLVER_CONFIG_NAME)
.value(writer -> {
writer.addUseImports(AwsGoDependency.AWS_CORE);
writer.openBlock("$L(func(region string, options $L) (e aws.Endpoint, err error) {", "}),",
EndpointGenerator.RESOLVER_FUNC_NAME, EndpointGenerator.RESOLVER_OPTIONS, () -> {
writer.write("e.URL = serverURL");
writer.write("e.SigningRegion = \"us-west-2\"");
writer.write("return e, err");
});
})
.build(),
HttpProtocolUnitTestGenerator.ConfigValue.builder()
.name("APIOptions")
.value(writer -> {
Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack",
SmithyGoDependency.SMITHY_MIDDLEWARE).build();
writer.openBlock("[]func($P) error{", "},", stackSymbol, () -> {
writer.openBlock("func(s $P) error {", "},", stackSymbol, () -> {
writer.write("s.Finalize.Clear()");
writer.write("s.Initialize.Remove(`OperationInputValidation`)");
writer.write("return nil");
});
});
})
.build()
));
// TODO can this check be replaced with a lookup into the runtime plugins?
if (IdempotencyTokenMiddlewareGenerator.hasOperationsWithIdempotencyToken(context.getModel(),
context.getService())) {
configValues.add(
HttpProtocolUnitTestGenerator.ConfigValue.builder()
.name(IdempotencyTokenMiddlewareGenerator.IDEMPOTENCY_CONFIG_NAME)
.value(writer -> {
writer.addUseImports(SmithyGoDependency.SMITHY_RAND);
writer.addUseImports(SmithyGoDependency.SMITHY_TESTING);
writer.write("smithyrand.NewUUIDIdempotencyToken(&smithytesting.ByteLoop{}),");
})
.build()
);
}
Set<ConfigValue> inputConfigValues = new TreeSet<>(configValues);
inputConfigValues.add(HttpProtocolUnitTestGenerator.ConfigValue.builder()
.name(AddAwsConfigFields.HTTP_CLIENT_CONFIG_NAME)
.value(writer -> {
writer.addUseImports(AwsGoDependency.AWS_HTTP_TRANSPORT);
writer.write("awshttp.NewBuildableClient(),");
})
.build());
Set<HttpProtocolUnitTestGenerator.SkipTest> inputSkipTests = new TreeSet<>(SetUtils.of(
// Endpoint prefix serialization doesn't work with test runner's handling of request URLs.
// e.g. http://foo.127.0.0.1:59850/ dial fail
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restjson#RestJson"))
.operation(ShapeId.from("aws.protocoltests.restjson#EndpointOperation"))
.addTestName("RestJsonEndpointTrait")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restjson#RestJson"))
.operation(ShapeId.from("aws.protocoltests.restjson#EndpointWithHostLabelOperation"))
.addTestName("RestJsonEndpointTraitWithHostLabel")
.build(),
// Endpoint prefix serialization doesn't work with test runner's handling of request URLs.
// e.g. http://foo.127.0.0.1:59850/ dial fail
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.ec2#AwsEc2"))
.operation(ShapeId.from("aws.protocoltests.ec2#EndpointOperation"))
.addTestName("Ec2QueryEndpointTrait")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.ec2#AwsEc2"))
.operation(ShapeId.from("aws.protocoltests.ec2#EndpointWithHostLabelOperation"))
.addTestName("Ec2QueryEndpointTraitWithHostLabel")
.build(),
// Endpoint prefix serialization doesn't work with test runner's handling of request URLs.
// e.g. http://foo.127.0.0.1:59850/ dial fail
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.json#JsonProtocol"))
.operation(ShapeId.from("aws.protocoltests.json#EndpointOperation"))
.addTestName("AwsJson11EndpointTrait")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.json#JsonProtocol"))
.operation(ShapeId.from("aws.protocoltests.json#EndpointWithHostLabelOperation"))
.addTestName("AwsJson11EndpointTraitWithHostLabel")
.build(),
// Endpoint prefix serialization doesn't work with test runner's handling of request URLs.
// e.g. http://foo.127.0.0.1:59850/ dial fail
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.json10#JsonRpc10"))
.operation(ShapeId.from("aws.protocoltests.json10#EndpointOperation"))
.addTestName("AwsJson10EndpointTrait")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.json10#JsonRpc10"))
.operation(ShapeId.from("aws.protocoltests.json10#EndpointWithHostLabelOperation"))
.addTestName("AwsJson10EndpointTraitWithHostLabel")
.build(),
// Endpoint prefix serialization doesn't work with test runner's handling of request URLs.
// e.g. http://foo.127.0.0.1:59850/ dial fail
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.query#AwsQuery"))
.operation(ShapeId.from("aws.protocoltests.query#EndpointOperation"))
.addTestName("AwsQueryEndpointTrait")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.query#AwsQuery"))
.operation(ShapeId.from("aws.protocoltests.query#EndpointWithHostLabelOperation"))
.addTestName("AwsQueryEndpointTraitWithHostLabel")
.build(),
// Endpoint prefix serialization doesn't work with test runner's handling of request URLs.
// e.g. http://foo.127.0.0.1:59850/ dial fail
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restxml#RestXml"))
.operation(ShapeId.from("aws.protocoltests.restxml#EndpointOperation"))
.addTestName("RestXmlEndpointTrait")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restxml#RestXml"))
.operation(ShapeId.from("aws.protocoltests.restxml#EndpointWithHostLabelHeaderOperation"))
.addTestName("RestXmlEndpointTraitWithHostLabelAndHttpBinding")
.build(),
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restxml#RestXml"))
.operation(ShapeId.from("aws.protocoltests.restxml#EndpointWithHostLabelOperation"))
.addTestName("RestXmlEndpointTraitWithHostLabel")
.build()
));
Set<HttpProtocolUnitTestGenerator.SkipTest> outputSkipTests = new TreeSet<>(SetUtils.of(
// REST-JSON optional (SHOULD) test cases
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restjson#RestJson"))
.operation(ShapeId.from("aws.protocoltests.restjson#JsonMaps"))
.addTestName("RestJsonDeserializesDenseSetMapAndSkipsNull")
.build(),
// REST-XML opinionated test - prefix headers as empty vs nil map
HttpProtocolUnitTestGenerator.SkipTest.builder()
.service(ShapeId.from("aws.protocoltests.restxml#RestXml"))
.operation(ShapeId.from("aws.protocoltests.restxml#HttpPrefixHeaders"))
.addTestName("HttpPrefixHeadersAreNotPresent")
.build()
));
new HttpProtocolTestGenerator(context,
(HttpProtocolUnitTestRequestGenerator.Builder) new HttpProtocolUnitTestRequestGenerator
.Builder()
.settings(context.getSettings())
.addSkipTests(inputSkipTests)
.addClientConfigValues(inputConfigValues),
(HttpProtocolUnitTestResponseGenerator.Builder) new HttpProtocolUnitTestResponseGenerator
.Builder()
.settings(context.getSettings())
.addSkipTests(outputSkipTests)
.addClientConfigValues(configValues),
(HttpProtocolUnitTestResponseErrorGenerator.Builder) new HttpProtocolUnitTestResponseErrorGenerator
.Builder()
.settings(context.getSettings())
.addClientConfigValues(configValues)
).generateProtocolTests();
}
public static void writeJsonErrorMessageCodeDeserializer(GenerationContext context) {
GoWriter writer = context.getWriter().get();
// The error code could be in the headers, even though for this protocol it should be in the body.
writer.write("code := response.Header.Get(\"X-Amzn-ErrorType\")");
writer.write("if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) }");
writer.write("");
initializeJsonDecoder(writer, "errorBody");
writer.addUseImports(AwsGoDependency.AWS_REST_JSON_PROTOCOL);
// This will check various body locations for the error code and error message
writer.write("code, message, err := restjson.GetErrorInfo(decoder)");
handleDecodeError(writer);
writer.addUseImports(SmithyGoDependency.IO);
// Reset the body in case it needs to be used for anything else.
writer.write("errorBody.Seek(0, io.SeekStart)");
// Only set the values if something was found so that we keep the default values.
writer.write("if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) }");
writer.write("if len(message) != 0 { errorMessage = message }");
writer.write("");
}
public static void initializeJsonDecoder(GoWriter writer, String bodyLocation) {
// Use a ring buffer and tee reader to help in pinpointing any deserialization errors.
writer.addUseImports(SmithyGoDependency.SMITHY_IO);
writer.write("var buff [1024]byte");
writer.write("ringBuffer := smithyio.NewRingBuffer(buff[:])");
writer.write("");
writer.addUseImports(SmithyGoDependency.IO);
writer.addUseImports(SmithyGoDependency.JSON);
writer.write("body := io.TeeReader($L, ringBuffer)", bodyLocation);
writer.write("decoder := json.NewDecoder(body)");
writer.write("decoder.UseNumber()");
}
/**
* Decodes JSON into {@code shape} with type {@code interface{}} using the encoding/json decoder
* referenced by {@code decoder}.
*
* @param writer GoWriter to write code to
* @param errorReturnExtras extra parameters to return if an error occurs
*/
public static void decodeJsonIntoInterface(GoWriter writer, String errorReturnExtras) {
writer.write("var shape interface{}");
writer.addUseImports(SmithyGoDependency.IO);
writer.openBlock("if err := decoder.Decode(&shape); err != nil && err != io.EOF {", "}", () -> {
wrapAsDeserializationError(writer);
writer.write("return $Lerr", errorReturnExtras);
});
writer.write("");
}
/**
* Wraps the Go error {@code err} in a {@code DeserializationError} with a snapshot
*
* @param writer
*/
private static void wrapAsDeserializationError(GoWriter writer) {
writer.write("var snapshot bytes.Buffer");
writer.write("io.Copy(&snapshot, ringBuffer)");
writer.openBlock("err = &smithy.DeserializationError {", "}", () -> {
writer.write("Err: fmt.Errorf(\"failed to decode response body, %w\", err),");
writer.write("Snapshot: snapshot.Bytes(),");
});
}
public static void handleDecodeError(GoWriter writer, String returnExtras) {
writer.openBlock("if err != nil {", "}", () -> {
writer.addUseImports(SmithyGoDependency.BYTES);
writer.addUseImports(SmithyGoDependency.SMITHY);
writer.addUseImports(SmithyGoDependency.IO);
wrapAsDeserializationError(writer);
writer.write("return $Lerr", returnExtras);
}).write("");
}
public static void handleDecodeError(GoWriter writer) {
handleDecodeError(writer, "");
}
public static void writeJsonEventMessageSerializerDelegator(
GenerationContext ctx,
String functionName,
String operand,
String contentType
) {
var writer = ctx.getWriter().get();
var stringValue = SymbolUtils.createValueSymbolBuilder("StringValue",
AwsGoDependency.SERVICE_INTERNAL_EVENTSTREAM).build();
var contentTypeHeader = SymbolUtils.createValueSymbolBuilder("ContentTypeHeader",
AwsGoDependency.SERVICE_INTERNAL_EVENTSTREAMAPI).build();
writer.write("msg.Headers.Set($T, $T($S))",
contentTypeHeader, stringValue, contentType);
var newEncoder = SymbolUtils.createValueSymbolBuilder("NewEncoder",
SmithyGoDependency.SMITHY_JSON).build();
writer.write("jsonEncoder := $T()", newEncoder)
.openBlock("if err := $L($L, jsonEncoder.Value); err != nil {", "}", functionName, operand,
() -> writer.write("return err"))
.write("msg.Payload = jsonEncoder.Bytes()")
.write("return nil");
}
public static void initializeJsonEventMessageDeserializer(GenerationContext ctx) {
initializeJsonEventMessageDeserializer(ctx, "");
}
public static void initializeJsonEventMessageDeserializer(GenerationContext ctx, String errorReturnExtras) {
var writer = ctx.getWriter().get();
writer.write("br := $T(msg.Payload)", SymbolUtils.createValueSymbolBuilder(
"NewReader", SmithyGoDependency.BYTES).build());
initializeJsonDecoder(writer, "br");
AwsProtocolUtils.decodeJsonIntoInterface(writer, errorReturnExtras);
}
public static void writeJsonEventStreamUnknownExceptionDeserializer(GenerationContext ctx) {
var writer = ctx.getWriter().get();
writer.write("br := $T(msg.Payload)", SymbolUtils.createValueSymbolBuilder("NewReader",
SmithyGoDependency.BYTES).build());
AwsProtocolUtils.initializeJsonDecoder(writer, "br");
writer.write("""
code, message, err := $T(decoder)
if err != nil {
return err
}
errorCode := "UnknownError"
errorMessage := errorCode
if ev := exceptionType.String(); len(ev) > 0 {
errorCode = ev
} else if ev := code; len(ev) > 0 {
errorCode = ev
}
if ev := message; len(ev) > 0 {
errorMessage = ev
}
return &$T{
Code: errorCode,
Message: errorMessage,
}
""",
SymbolUtils.createValueSymbolBuilder("GetErrorInfo",
AwsGoDependency.AWS_REST_JSON_PROTOCOL).build(),
SymbolUtils.createValueSymbolBuilder("GenericAPIError", SmithyGoDependency.SMITHY).build());
}
}