Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Client Option Getters, Refactor Middleware Helpers to not expose interfaces for configuration #788

Merged
merged 5 commits into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
30 changes: 11 additions & 19 deletions aws/retry/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,28 +175,20 @@ func setRetryMetadata(ctx context.Context, metadata retryMetadata) context.Conte
return context.WithValue(ctx, retryMetadataKey{}, metadata)
}

// AwsRetryMiddlewareConfig interface for retry middleware config
type AwsRetryMiddlewareConfig interface {
GetRetryer() Retryer
}

// AwsRetryMiddlewares represents the Aws middleware's for Retry
type AwsRetryMiddlewares struct {
AttemptMiddleware *AttemptMiddleware
MetricsHeaderMiddleware *MetricsHeaderMiddleware
// AddRetryMiddlewaresOptions is the set of options that can be passed to AddRetryMiddlewares for configuring retry
// associated middleware.
type AddRetryMiddlewaresOptions struct {
Retryer Retryer
}

// AddRetryMiddlewares adds retry middleware to operation middleware stack
func AddRetryMiddlewares(stack *smithymiddle.Stack, cfg AwsRetryMiddlewareConfig, optsFn ...func(*AwsRetryMiddlewares)) {
attemptMiddleware := NewAttemptMiddleware(cfg.GetRetryer(), http.RequestCloner)
m := AwsRetryMiddlewares{
AttemptMiddleware: &attemptMiddleware,
MetricsHeaderMiddleware: &MetricsHeaderMiddleware{},
func AddRetryMiddlewares(stack *smithymiddle.Stack, options AddRetryMiddlewaresOptions) error {
attemptMiddleware := NewAttemptMiddleware(options.Retryer, http.RequestCloner)
if err := stack.Finalize.Add(&attemptMiddleware, smithymiddle.After); err != nil {
return err
}
for _, fn := range optsFn {
fn(&m)
if err := stack.Finalize.Add(&MetricsHeaderMiddleware{}, smithymiddle.After); err != nil {
return err
}

stack.Finalize.Add(m.AttemptMiddleware, smithymiddle.After)
stack.Finalize.Add(m.MetricsHeaderMiddleware, smithymiddle.After)
return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ public List<RuntimeClientPlugin> getClientPlugins() {
.build())
.build(),

// Add newAttempt middleware to operation stack
// Add retryer middleware to operation stack
RuntimeClientPlugin.builder()
.registerMiddleware(MiddlewareRegistrar.builder()
.resolvedFunction(SymbolUtils.createValueSymbolBuilder(
"AddRetryMiddlewares", AwsGoDependency.AWS_RETRY)
AwsRetryMiddlewareHelper.ADD_RETRY_MIDDLEWARES_HELPER)
.build())
.useClientOptions()
.build())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* 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 software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
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.SmithyGoDependency;
import software.amazon.smithy.go.codegen.SymbolUtils;
import software.amazon.smithy.go.codegen.integration.GoIntegration;
import software.amazon.smithy.model.Model;

public class AwsRetryMiddlewareHelper implements GoIntegration {
public static final String ADD_RETRY_MIDDLEWARES_HELPER = "addRetryMiddlewares";

@Override
public void writeAdditionalFiles(
GoSettings settings,
Model model,
SymbolProvider symbolProvider,
GoDelegator delegator
) {
delegator.useShapeWriter(settings.getService(model), this::generateRetryMiddlewareHelpers);
}

private void generateRetryMiddlewareHelpers(GoWriter writer) {
Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE)
.build();
Symbol addRetryMiddlewares = SymbolUtils.createValueSymbolBuilder("AddRetryMiddlewares",
AwsGoDependency.AWS_RETRY).build();
Symbol addOptions = SymbolUtils.createValueSymbolBuilder("AddRetryMiddlewaresOptions",
AwsGoDependency.AWS_RETRY).build();

writer.openBlock("func $L(stack $P, o Options) error {", "}", ADD_RETRY_MIDDLEWARES_HELPER, stackSymbol,
() -> {
writer.openBlock("mo := $T{", "}", addOptions, () -> {
writer.write("$L: o.$L,", AddAwsConfigFields.RETRYER_CONFIG_NAME,
AddAwsConfigFields.RETRYER_CONFIG_NAME);
});

writer.write("return $T(stack, mo)", addRetryMiddlewares);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,7 @@ private void writeServiceSignerConfig(Model model, GoWriter writer, ServiceShape
* @return if the SigV4 trait is used by the service.
*/
public static boolean isSupportedAuthentication(Model model, ServiceShape serviceShape) {
return model.getKnowledge(ServiceIndex.class)
.getAuthSchemes(serviceShape).values().stream().anyMatch(trait -> trait.getClass()
return ServiceIndex.of(model).getAuthSchemes(serviceShape).values().stream().anyMatch(trait -> trait.getClass()
.equals(SigV4Trait.class));
}

Expand All @@ -135,8 +134,7 @@ public static boolean isSupportedAuthentication(Model model, ServiceShape servic
* @return if SigV4Trait is an auth scheme for the operation and service.
*/
public static boolean hasSigV4AuthScheme(Model model, ServiceShape service, OperationShape operation) {
ServiceIndex serviceIndex = model.getKnowledge(ServiceIndex.class);
Map<ShapeId, Trait> auth = serviceIndex.getEffectiveAuthSchemes(service.getId(), operation.getId());
Map<ShapeId, Trait> auth = ServiceIndex.of(model).getEffectiveAuthSchemes(service.getId(), operation.getId());
return auth.containsKey(SigV4Trait.ID) && !operation.hasTrait(OptionalAuthTrait.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
*/
final class EndpointGenerator implements Runnable {
public static final String MIDDLEWARE_NAME = "ResolveEndpoint";
public static final String ADD_MIDDLEWARE_HELPER_NAME = String.format("Add%sMiddleware", MIDDLEWARE_NAME);
public static final String ADD_MIDDLEWARE_HELPER_NAME = String.format("add%sMiddleware", MIDDLEWARE_NAME);
public static final String RESOLVER_INTERFACE_NAME = "EndpointResolver";
public static final String RESOLVER_FUNC_NAME = "EndpointResolverFunc";
public static final String RESOLVER_OPTIONS = "ResolverOptions";
Expand Down Expand Up @@ -192,32 +192,22 @@ private void generateMiddleware(GoWriter writer) {

Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE)
.build();
Symbol optionsSymbol = SymbolUtils.createValueSymbolBuilder(String.format("%sMiddlewareOptions",
MIDDLEWARE_NAME)).build();

// Generate Middleware options interface
writer.openBlock("type $T interface {", "}", optionsSymbol, () -> {
writer.write("GetEndpointResolver() $L", RESOLVER_INTERFACE_NAME);
writer.write("GetEndpointOptions() $L", RESOLVER_OPTIONS);
});
writer.write("");

// Generate Middleware Adder Helper
writer.openBlock("func $L(stack $P, options $T) {", "}", ADD_MIDDLEWARE_HELPER_NAME, stackSymbol,
optionsSymbol, () -> {
writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE);
String closeBlock = String.format("}, \"%s\", middleware.Before)",
ProtocolUtils.OPERATION_SERIALIZER_MIDDLEWARE_ID);
writer.openBlock("stack.Serialize.Insert(&$T{", closeBlock,
middleware.getMiddlewareSymbol(),
() -> {
writer.write("Resolver: options.GetEndpointResolver(),");
writer.write("Options: options.GetEndpointOptions(),");
});
});
writer.openBlock("func $L(stack $P, o Options) error {", "}", ADD_MIDDLEWARE_HELPER_NAME, stackSymbol, () -> {
writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE);
String closeBlock = String.format("}, \"%s\", middleware.Before)",
ProtocolUtils.OPERATION_SERIALIZER_MIDDLEWARE_ID);
writer.openBlock("return stack.Serialize.Insert(&$T{", closeBlock,
middleware.getMiddlewareSymbol(),
() -> {
writer.write("Resolver: o.EndpointResolver,");
writer.write("Options: o.EndpointOptions,");
});
});
writer.write("");
// Generate Middleware Remover Helper
writer.openBlock("func Remove$LMiddleware(stack $P) error {", "}", middleware.getMiddlewareSymbol(),
writer.openBlock("func remove$LMiddleware(stack $P) error {", "}", middleware.getMiddlewareSymbol(),
stackSymbol, () -> {
writer.write("return stack.Serialize.Remove((&$T{}).ID())", middleware.getMiddlewareSymbol());
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ protected void generateOperationDocumentSerializer(
OperationShape operation
) {
Model model = context.getModel();
HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class);
HttpBindingIndex bindingIndex = HttpBindingIndex.of(model);
Set<MemberShape> documentBindings = bindingIndex.getRequestBindings(operation, HttpBinding.Location.DOCUMENT)
.stream()
.map(HttpBinding::getMember)
Expand Down Expand Up @@ -184,7 +184,7 @@ protected void writeMiddlewareDocumentDeserializerDelegator(
boolean isShapeWithPayloadBinding = isShapeWithResponseBindings(model, operation, HttpBinding.Location.PAYLOAD);
if (isShapeWithPayloadBinding) {
// since payload trait can only be applied to a single member in a output shape
MemberShape memberShape = model.getKnowledge(HttpBindingIndex.class)
MemberShape memberShape = HttpBindingIndex.of(model)
.getResponseBindings(operation, HttpBinding.Location.PAYLOAD).stream()
.findFirst()
.orElseThrow(() -> new CodegenException("Expected payload binding member"))
Expand Down Expand Up @@ -258,7 +258,7 @@ protected void generateOperationDocumentDeserializer(
OperationShape operation
) {
Model model = context.getModel();
HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class);
HttpBindingIndex bindingIndex = HttpBindingIndex.of(model);
Set<MemberShape> documentBindings = bindingIndex.getResponseBindings(operation, HttpBinding.Location.DOCUMENT)
.stream()
.map(HttpBinding::getMember)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ protected TimestampFormatTrait.Format getDocumentTimestampFormat() {
@Override
protected void generateOperationDocumentSerializer(GenerationContext context, OperationShape operation) {
Model model = context.getModel();
HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class);
HttpBindingIndex bindingIndex = HttpBindingIndex.of(model);

Set<MemberShape> documentBindings = bindingIndex.getRequestBindings(operation, HttpBinding.Location.DOCUMENT)
.stream()
Expand Down Expand Up @@ -213,7 +213,7 @@ protected void writeMiddlewareDocumentDeserializerDelegator(

if (isShapeWithResponseBindings(model, operation, HttpBinding.Location.PAYLOAD)) {
// since payload trait can only be applied to a single member in a output shape
MemberShape memberShape = model.getKnowledge(HttpBindingIndex.class)
MemberShape memberShape = HttpBindingIndex.of(model)
.getResponseBindings(operation, HttpBinding.Location.PAYLOAD).stream()
.findFirst()
.orElseThrow(() -> new CodegenException("Expected payload binding member"))
Expand All @@ -239,7 +239,7 @@ protected void generateOperationDocumentDeserializer(
GenerationContext context, OperationShape operation
) {
Model model = context.getModel();
HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class);
HttpBindingIndex bindingIndex = HttpBindingIndex.of(model);
Set<MemberShape> documentBindings = bindingIndex.getResponseBindings(operation, HttpBinding.Location.DOCUMENT)
.stream()
.map(HttpBinding::getMember)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class S3MetadataRetriever implements GoIntegration {
*/
@Override
public byte getOrder() {
return 127;
return 126;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ software.amazon.smithy.aws.go.codegen.AwsSignatureVersion4
software.amazon.smithy.aws.go.codegen.AwsIdempotencyTokenProvider
software.amazon.smithy.aws.go.codegen.AwsClientUserAgent
software.amazon.smithy.aws.go.codegen.AwsSdkServiceId
software.amazon.smithy.aws.go.codegen.AwsRetryMiddlewareHelper
software.amazon.smithy.aws.go.codegen.AWSRequestIDRetriever
software.amazon.smithy.aws.go.codegen.AWSResponseErrorWrapper
software.amazon.smithy.aws.go.codegen.customization.DynamoDBValidateResponseChecksum
Expand Down
7 changes: 1 addition & 6 deletions credentials/endpointcreds/internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@ func (o Options) Copy() Options {
return to
}

// GetRetryer returns the configured retryer
func (o Options) GetRetryer() retry.Retryer {
return o.Retryer
}

// Client is an client for retrieving AWS credentials from an endpoint
type Client struct {
options Options
Expand Down Expand Up @@ -96,7 +91,7 @@ func (c *Client) GetCredentials(ctx context.Context, params *GetCredentialsInput
stack.Serialize.Add(&serializeOpGetCredential{}, smithymiddleware.After)
stack.Build.Add(&buildEndpoint{Endpoint: options.Endpoint}, smithymiddleware.After)
stack.Deserialize.Add(&deserializeOpGetCredential{}, smithymiddleware.After)
retry.AddRetryMiddlewares(stack, options)
retry.AddRetryMiddlewares(stack, retry.AddRetryMiddlewaresOptions{Retryer: options.Retryer})
middleware.AddUserAgentKey(ServiceID)
smithyhttp.AddErrorCloseResponseBodyMiddleware(stack)
smithyhttp.AddCloseResponseBodyMiddleware(stack)
Expand Down
7 changes: 0 additions & 7 deletions ec2imds/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,6 @@ type Options struct {
disableAPIToken bool
}

// GetRetryer returns the retryer.
//
// TODO remove this in favor of structured options.
func (o Options) GetRetryer() retry.Retryer {
return o.Retryer
}

// HTTPClient provides the interface for a client making HTTP requests with the
// API.
type HTTPClient interface {
Expand Down
2 changes: 1 addition & 1 deletion ec2imds/request_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func addRequestMiddleware(stack *middleware.Stack,
}

// Retry support
retry.AddRetryMiddlewares(stack, options)
retry.AddRetryMiddlewares(stack, retry.AddRetryMiddlewaresOptions{Retryer: options.Retryer})

return nil
}
Expand Down
27 changes: 7 additions & 20 deletions internal/protocoltest/awsrestjson/api_client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading