-
Notifications
You must be signed in to change notification settings - Fork 49
/
ProtocolGenerator.java
629 lines (573 loc) · 22.7 KB
/
ProtocolGenerator.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
/*
* 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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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.GoDelegator;
import software.amazon.smithy.go.codegen.GoSettings;
import software.amazon.smithy.go.codegen.GoWriter;
import software.amazon.smithy.go.codegen.Synthetic;
import software.amazon.smithy.go.codegen.auth.AuthGenerator;
import software.amazon.smithy.go.codegen.endpoints.EndpointResolutionGenerator;
import software.amazon.smithy.go.codegen.endpoints.FnGenerator;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.ExpectationNotMetException;
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.StructureShape;
import software.amazon.smithy.model.traits.ErrorTrait;
import software.amazon.smithy.model.traits.Trait;
import software.amazon.smithy.rulesengine.language.EndpointRuleSet;
import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait;
import software.amazon.smithy.utils.CaseUtils;
import software.amazon.smithy.utils.SmithyBuilder;
import software.amazon.smithy.utils.StringUtils;
/**
* Smithy protocol code generators.
*/
public interface ProtocolGenerator {
/**
* Sanitizes the name of the protocol so it can be used as a symbol
* in Go.
*
* <p>
* For example, the default implementation converts "." to "_",
* and converts "-" to become camelCase separated words. This means
* that "aws.rest-json-1.1" becomes "Aws_RestJson1_1".
*
* @param name Name of the protocol to sanitize.
* @return Returns the sanitized name.
*/
static String getSanitizedName(String name) {
name = name.replaceAll("(\\s|\\.|-)+", "_");
return CaseUtils.toCamelCase(name, true, '_');
}
/**
* Gets the supported protocol {@link ShapeId}.
*
* @return Returns the protocol supported
*/
ShapeId getProtocol();
default String getProtocolName() {
ShapeId protocol = getProtocol();
String prefix = protocol.getNamespace();
int idx = prefix.indexOf('.');
if (idx != -1) {
prefix = prefix.substring(0, idx);
}
return CaseUtils.toCamelCase(prefix) + getSanitizedName(protocol.getName());
}
/**
* Creates an application protocol for the generator.
*
* @return Returns the created application protocol.
*/
ApplicationProtocol getApplicationProtocol();
/**
* Determines if two protocol generators are compatible at the
* application protocol level, meaning they both use HTTP, or MQTT
* for example.
*
* <p>
* Two protocol implementations are considered compatible if the
* {@link ApplicationProtocol#equals} method of {@link #getApplicationProtocol}
* returns true when called with {@code other}. The default implementation
* should work for most interfaces, but may be overridden for more in-depth
* handling of things like minor version incompatibilities.
*
* <p>
* By default, if the application protocols are considered equal, then
* {@code other} is returned.
*
* @param service Service being generated.
* @param protocolGenerators Other protocol generators that are being generated.
* @param other Protocol generator to resolve against.
* @return Returns the resolved application protocol object.
*/
default ApplicationProtocol resolveApplicationProtocol(
ServiceShape service,
Collection<ProtocolGenerator> protocolGenerators,
ApplicationProtocol other) {
if (!getApplicationProtocol().equals(other)) {
String protocolNames = protocolGenerators.stream()
.map(ProtocolGenerator::getProtocol)
.map(Trait::getIdiomaticTraitName)
.sorted()
.collect(Collectors.joining(", "));
throw new CodegenException(String.format(
"All of the protocols generated for a service must be runtime compatible, but "
+ "protocol `%s` is incompatible with other application protocols: [%s]. Please pick a "
+ "set of compatible protocols using the `protocols` option when generating %s.",
getProtocol(), protocolNames, service.getId()));
}
return other;
}
/**
* Generates any standard code for service request/response serde.
*
* @param context Serde context.
*/
default void generateSharedSerializerComponents(GenerationContext context) {
}
/**
* Generates the code used to serialize the shapes of a service
* for requests.
*
* @param context Serialization context.
*/
void generateRequestSerializers(GenerationContext context);
/**
* Generates any standard code for service response deserialization.
*
* @param context Serde context.
*/
default void generateSharedDeserializerComponents(GenerationContext context) {
}
/**
* Generates the code used to deserialize the shapes of a service
* for responses.
*
* @param context Deserialization context.
*/
void generateResponseDeserializers(GenerationContext context);
/**
* Generates the code for validating the generated protocol's serializers and
* deserializers.
*
* @param context Generation context
*/
default void generateProtocolTests(GenerationContext context) {
}
/**
* Generates the name of a serializer function for shapes of a service.
*
* @param shape The shape the serializer function is being generated for.
* @param service The service shape.
* @param protocol Name of the protocol being generated.
* @return Returns the generated function name.
*/
static String getOperationHttpBindingsSerFunctionName(Shape shape, ServiceShape service, String protocol) {
return protocol
+ "_serializeOpHttpBindings"
+ StringUtils.capitalize(shape.getId().getName(service));
}
/**
* Generates the name of a deserializer function for shapes of a service.
*
* @param shape The shape the deserializer function is being generated for.
* @param service The service shape.
* @param protocol Name of the protocol being generated.
* @return Returns the generated function name.
*/
static String getOperationHttpBindingsDeserFunctionName(Shape shape, ServiceShape service, String protocol) {
return protocol
+ "_deserializeOpHttpBindings"
+ StringUtils.capitalize(shape.getId().getName(service));
}
/**
* Generates the name of a serializer function for shapes of a service.
*
* @param shape The shape the serializer function is being generated for.
* @param service The service shape within which the deserialized shape is
* enclosed.
* @param protocol Name of the protocol being generated.
* @return Returns the generated function name.
*/
static String getDocumentSerializerFunctionName(Shape shape, ServiceShape service, String protocol) {
String name = shape.getId().getName(service);
String extra = "";
if (shape.hasTrait(Synthetic.class)) {
extra = "Op";
}
return protocol + "_serialize" + extra + "Document" + StringUtils.capitalize(name);
}
/**
* Generates the name of a deserializer function for shapes of a service.
*
* @param shape The shape the deserializer function is being generated for.
* @param service The service shape within which the deserialized shape is
* enclosed.
* @param protocol Name of the protocol being generated.
* @return Returns the generated function name.
*/
static String getDocumentDeserializerFunctionName(Shape shape, ServiceShape service, String protocol) {
String name = shape.getId().getName(service);
String extra = "";
if (shape.hasTrait(Synthetic.class)) {
extra = "Op";
}
return protocol + "_deserialize" + extra + "Document" + StringUtils.capitalize(name);
}
static String getOperationErrorDeserFunctionName(OperationShape shape, ServiceShape service, String protocol) {
return protocol + "_deserializeOpError" + StringUtils.capitalize(shape.getId().getName(service));
}
/**
* Generates the name of an error deserializer function for shapes of a service.
*
* @param shape The error structure shape for which deserializer name is
* being generated.
* @param service The service enclosing the service shape.
* @param protocol Name of the protocol being generated.
* @return Returns the generated function name.
*/
static String getErrorDeserFunctionName(StructureShape shape, ServiceShape service, String protocol) {
String name = shape.getId().getName(service);
return protocol + "_deserializeError" + StringUtils.capitalize(name);
}
static String getSerializeMiddlewareName(ShapeId operationShapeId, ServiceShape service, String protocol) {
return protocol
+ "_serializeOp"
+ operationShapeId.getName(service);
}
static String getDeserializeMiddlewareName(ShapeId operationShapeId, ServiceShape service, String protocol) {
return protocol
+ "_deserializeOp"
+ operationShapeId.getName(service);
}
/**
* Returns a map of error names to their {@link ShapeId}.
*
* @param context the generation context
* @param operation the operation shape to retrieve errors for
* @return map of error names to {@link ShapeId}
*/
default Map<String, ShapeId> getOperationErrors(GenerationContext context, OperationShape operation) {
return HttpProtocolGeneratorUtils.getOperationErrors(context, operation);
}
/**
* Generates the UnmarshalSmithyDocument function body of the service's internal
* documentMarshaler type.
* <p>
* The document marshaler type is expected to handle user provided Go types and
* convert them to protocol documents.
* <p>
* The default implementation will throw a {@code CodegenException} if not
* implemented.
*
* <pre>{@code
* type documentMarshaler struct {
* value interface{}
* }
*
* // ...
*
* func (m *documentMarshaler) UnmarshalSmithyDocument(v interface{}) error {
* // Generated code from generateProtocolDocumentMarshalerUnmarshalDocument
* }
* }</pre>
*
* @param context the generation context.
*/
default void generateProtocolDocumentMarshalerUnmarshalDocument(GenerationContext context) {
throw new CodegenException("document types not implemented for " + this.getProtocolName() + " protocol");
}
/**
* Generates the UnmarshalSmithyDocument function body of the service's internal
* documentMarshaler type.
* <p>
* The document marshaler type is expected to handle user provided Go types and
* convert them to protocol documents.
* <p>
* The default implementation will throw a {@code CodegenException} if not
* implemented.
*
* <pre>{@code
* type documentMarshaler struct {
* value interface{}
* }
*
* // ...
*
* func (m *documentMarshaler) MarshalSmithyDocument() ([]byte, error) {
* // Generated code from generateProtocolDocumentMarshalerMarshalDocument
* }
* }</pre>
*
* @param context the generation context.
*/
default void generateProtocolDocumentMarshalerMarshalDocument(GenerationContext context) {
throw new CodegenException("document types not implemented for " + this.getProtocolName() + " protocol");
}
/**
* Generates the UnmarshalSmithyDocument function body of the service's internal
* documentUnmarshaler type.
* <p>
* The document unmarshaler type is expected to handle protocol documents
* received from the service and provide the
* ability to unmarshal or round-trip the document.
* <p>
* The default implementation will throw a {@code CodegenException} if not
* implemented.
*
* <pre>{@code
* type documentUnmarshaler struct {
* value interface{}
* }
*
* // ...
*
* func (m *documentUnmarshaler) UnmarshalSmithyDocument(v interface{}) error {
* // Generated code from generateProtocolDocumentUnmarshalerUnmarshalDocument
* }
* }</pre>
*
* @param context the generation context.
*/
default void generateProtocolDocumentUnmarshalerUnmarshalDocument(GenerationContext context) {
throw new CodegenException("document types not implemented for " + this.getProtocolName() + " protocol");
}
/**
* Generates the MarshalSmithyDocument function body of the service's internal
* documentUnmarshaler type.
* <p>
* The document unmarshaler type is expected to handle protocol documents
* received from the service and provide the
* ability to unmarshal or round-trip the document.
* <p>
* The default implementation will throw a {@code CodegenException} if not
* implemented.
*
* <pre>{@code
* type documentUnmarshaler struct {
* value interface{}
* }
*
* // ...
*
* func (m *documentUnmarshaler) MarshalSmithyDocument() ([]byte, error) {
* // Generated code from generateProtocolDocumentUnmarshalerMarshalDocument
* }
* }</pre>
*
* @param context the generation context.
*/
default void generateProtocolDocumentUnmarshalerMarshalDocument(GenerationContext context) {
throw new CodegenException("document types not implemented for " + this.getProtocolName() + " protocol");
}
/**
* Generate the internal constructor function body for the service's internal
* documentMarshaler type.
*
* <pre>{@code
* func NewDocumentMarshaler(v interface{}) Interface {
* return &documentMarshaler{
* value: v,
* }
* }
* }</pre>
*
* @param context the generation context.
* @param marshalerSymbol the symbol for the {@code documentMarshaler} type.
*/
default void generateNewDocumentMarshaler(GenerationContext context, Symbol marshalerSymbol) {
GoWriter writer = context.getWriter().get();
writer.openBlock("return &$T{", "}", marshalerSymbol, () -> {
writer.write("value: v,");
});
}
/**
* Generate the internal constructor function body for the service's internal
* documentUnmarshaler type.
*
* <pre>{@code
* func NewDocumentUnmarshaler(v interface{}) Interface {
* return &documentUnmarshaler{
* value: v,
* }
* }
* }</pre>
*
* @param context the generation context.
* @param unmarshalerSymbol the symbol for the {@code documentUnmarshaler} type.
*/
default void generateNewDocumentUnmarshaler(GenerationContext context, Symbol unmarshalerSymbol) {
GoWriter writer = context.getWriter().get();
writer.openBlock("return &$T{", "}", unmarshalerSymbol, () -> {
writer.write("value: v,");
});
}
/**
* Returns an error code for an error shape. Defaults to error shape name as
* error code.
*
* @param service the service enclosure for the error shape.
* @param errorShape the error shape for which error code is retrieved.
* @return the error code associated with the provided shape.
* @throws ExpectationNotMetException if provided shape is not modeled with an
* {@link ErrorTrait}.
*/
default String getErrorCode(ServiceShape service, StructureShape errorShape) {
errorShape.expectTrait(ErrorTrait.class);
return errorShape.getId().getName(service);
}
/**
* Generate specific components for the protocol's event stream implementation.
* These components
* types should provide implementations that satisfy the reader and writer event
* stream interfaces.
*
* @param context the generation context.
*/
default void generateEventStreamComponents(GenerationContext context) {
}
/**
* Generate all components necessary for Endpoint Rules Engine endpoint
* resolution.
*
* @param context the generation context.
*/
default void generateEndpointResolution(GenerationContext context) {
var generator = new EndpointResolutionGenerator(new FnGenerator.DefaultFnProvider());
generator.generate(context);
}
/**
* Generate the tests for Endpoint Rules Engine endpoint resolution.
*
* @param context the generation context.
*/
default void generateEndpointResolutionTests(GenerationContext context) {
var generator = new EndpointResolutionGenerator(new FnGenerator.DefaultFnProvider());
generator.generateTests(context);
}
/**
* Generates smithy client auth components.
*
* @param context The generation context.
*/
default void generateAuth(GenerationContext context) {
new AuthGenerator(context).generate();
}
/**
* Context object used for service serialization and deserialization.
*/
class GenerationContext {
private final GoSettings settings;
private final Model model;
private final ServiceShape service;
private final SymbolProvider symbolProvider;
private final GoWriter writer;
private final List<GoIntegration> integrations;
private final String protocolName;
private final GoDelegator delegator;
private GenerationContext(Builder builder) {
this.settings = SmithyBuilder.requiredState("settings", builder.settings);
this.model = SmithyBuilder.requiredState("model", builder.model);
this.service = SmithyBuilder.requiredState("service", builder.service);
this.symbolProvider = SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider);
this.writer = builder.writer;
this.integrations = SmithyBuilder.requiredState("integrations", builder.integrations);
this.protocolName = SmithyBuilder.requiredState("protocolName", builder.protocolName);
this.delegator = SmithyBuilder.requiredState("delegator", builder.delegator);
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return builder()
.settings(this.settings)
.model(this.model)
.service(this.service)
.symbolProvider(this.symbolProvider)
.writer(this.writer)
.integrations(this.integrations)
.protocolName(this.protocolName)
.delegator(this.delegator);
}
public GoSettings getSettings() {
return settings;
}
public Model getModel() {
return model;
}
public ServiceShape getService() {
return service;
}
public EndpointRuleSet getEndpointRules() {
return EndpointRuleSet.fromNode(service.expectTrait(EndpointRuleSetTrait.class).getRuleSet());
}
public SymbolProvider getSymbolProvider() {
return symbolProvider;
}
public Optional<GoWriter> getWriter() {
return Optional.ofNullable(writer);
}
public GoDelegator getDelegator() {
return delegator;
}
public List<GoIntegration> getIntegrations() {
return integrations;
}
public String getProtocolName() {
return protocolName;
}
public static class Builder implements SmithyBuilder<GenerationContext> {
private GoSettings settings;
private Model model;
private ServiceShape service;
private SymbolProvider symbolProvider;
private GoWriter writer;
private final List<GoIntegration> integrations = new ArrayList<>();
private String protocolName;
private GoDelegator delegator;
public Builder settings(GoSettings settings) {
this.settings = settings;
return this;
}
public Builder model(Model model) {
this.model = model;
return this;
}
public Builder service(ServiceShape service) {
this.service = service;
return this;
}
public Builder symbolProvider(SymbolProvider symbolProvider) {
this.symbolProvider = symbolProvider;
return this;
}
public Builder writer(GoWriter writer) {
this.writer = writer;
return this;
}
public Builder integrations(Collection<GoIntegration> integrations) {
this.integrations.clear();
this.integrations.addAll(integrations);
return this;
}
public Builder protocolName(String protocolName) {
this.protocolName = protocolName;
return this;
}
public Builder delegator(GoDelegator delegator) {
this.delegator = delegator;
return this;
}
@Override
public GenerationContext build() {
return new GenerationContext(this);
}
}
}
}