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

[DO NOT MERGE] Feat flex checksum #2808

Open
wants to merge 41 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
e89e0c9
add config and change default behavior of checksum middleware
Sep 25, 2024
ee0fb5b
merge main into branch
Sep 25, 2024
0efe635
regenerate client
Sep 25, 2024
bc3f437
regenerate clients
Sep 26, 2024
58bf509
merge protocol test code from main
Sep 26, 2024
ab72530
merge from main
Sep 26, 2024
b0a53a4
add more test cases
Sep 26, 2024
f7b5a2d
add changelog
Sep 26, 2024
b93f439
modify s3 internal test
Sep 26, 2024
72c3ba6
separate checksum config check and workflow
Sep 29, 2024
f70fb1d
Merge branch 'main' into feat-flex-checksum
Sep 29, 2024
7bc5326
restore s3 test
Sep 29, 2024
28e8ac4
remove unused md5 header
Sep 30, 2024
23a7d0e
separate checksum config and workflow
Oct 1, 2024
e12cb30
Merge branch 'main' into feat-flex-checksum
Oct 1, 2024
df759d3
change default checksum to const
Oct 1, 2024
93aee16
add checksum unset enum and modify comment of cfg
Oct 2, 2024
b147f0f
change comment
Oct 7, 2024
db21450
Merge branch 'main' into feat-flex-checksum
Oct 7, 2024
3eb7ed7
Update aws/checksum.go
lucix-aws Oct 8, 2024
6be56d3
change checksum value check logic
Oct 21, 2024
05ed9a0
remove old check
Oct 21, 2024
3b801c2
correct unseekable stream logic without tls and its test cases
Nov 20, 2024
606d1ad
resolve merge conflict
Nov 20, 2024
59e520b
revert extra codegen
Nov 20, 2024
cda7bcc
change tmv1 upload test cases after introducing flex checksum
Nov 22, 2024
e912c0a
Merge branch 'main' into feat-flex-checksum
Nov 22, 2024
f84cffb
add error test case for crc64
Nov 26, 2024
2df24d6
change test name
Nov 26, 2024
1cc4bfc
Merge branch 'main' into feat-flex-checksum
Nov 26, 2024
16f3efe
default tmv1 checksum and add flex checksum metrics tracking
Dec 7, 2024
2288595
Merge branch 'main' into feat-flex-checksum
Dec 7, 2024
24c37b1
regenerate client and add metrics mw test
Dec 9, 2024
7dde0a9
add comment to exported type
Dec 9, 2024
c6f34d2
update s3 snapshot
Dec 9, 2024
29f1c9c
update tmv1 integ test
Dec 10, 2024
3f79e71
Merge branch 'main' into feat-flex-checksum
Dec 10, 2024
9ff1219
exclude default checksum from presign op
Dec 11, 2024
4dd0258
Merge branch 'main' into feat-flex-checksum
Dec 11, 2024
25d943c
reorder feature id and simplify metric tracking test
Dec 18, 2024
bf57f67
Merge branch 'main' into feat-flex-checksum
Dec 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions aws/middleware/user_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,28 @@ type UserAgentFeature string

// Enumerates UserAgentFeature.
const (
UserAgentFeatureResourceModel UserAgentFeature = "A" // n/a (we don't generate separate resource types)
UserAgentFeatureWaiter = "B"
UserAgentFeaturePaginator = "C"
UserAgentFeatureRetryModeLegacy = "D" // n/a (equivalent to standard)
UserAgentFeatureRetryModeStandard = "E"
UserAgentFeatureRetryModeAdaptive = "F"
UserAgentFeatureS3Transfer = "G"
UserAgentFeatureS3CryptoV1N = "H" // n/a (crypto client is external)
UserAgentFeatureS3CryptoV2 = "I" // n/a
UserAgentFeatureS3ExpressBucket = "J"
UserAgentFeatureS3AccessGrants = "K" // not yet implemented
UserAgentFeatureGZIPRequestCompression = "L"
UserAgentFeatureProtocolRPCV2CBOR = "M"
UserAgentFeatureResourceModel UserAgentFeature = "A" // n/a (we don't generate separate resource types)
UserAgentFeatureWaiter = "B"
UserAgentFeaturePaginator = "C"
UserAgentFeatureRetryModeLegacy = "D" // n/a (equivalent to standard)
UserAgentFeatureRetryModeStandard = "E"
UserAgentFeatureRetryModeAdaptive = "F"
UserAgentFeatureS3Transfer = "G"
UserAgentFeatureS3CryptoV1N = "H" // n/a (crypto client is external)
UserAgentFeatureS3CryptoV2 = "I" // n/a
UserAgentFeatureS3ExpressBucket = "J"
UserAgentFeatureS3AccessGrants = "K" // not yet implemented
wty-Bryant marked this conversation as resolved.
Show resolved Hide resolved
UserAgentFeatureGZIPRequestCompression = "L"
UserAgentFeatureProtocolRPCV2CBOR = "M"
UserAgentFeatureRequestChecksumWhenSupported = "Z"
UserAgentFeatureRequestChecksumWhenRequired = "a"
UserAgentFeatureResponseChecksumWhenSupported = "b"
UserAgentFeatureResponseChecksumWhenRequired = "c"
UserAgentFeatureRequestChecksumCRC32 = "U"
UserAgentFeatureRequestChecksumCRC32C = "V"
UserAgentFeatureRequestChecksumCRC64 = "W"
UserAgentFeatureRequestChecksumSHA1 = "X"
UserAgentFeatureRequestChecksumSHA256 = "Y"
wty-Bryant marked this conversation as resolved.
Show resolved Hide resolved
)

// RequestUserAgent is a build middleware that set the User-Agent for the request.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.TreeSet;
import software.amazon.smithy.aws.go.codegen.customization.AwsCustomGoDependency;
import software.amazon.smithy.aws.go.codegen.customization.PresignURLAutoFill;
import software.amazon.smithy.aws.traits.HttpChecksumTrait;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait;
import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait;
Expand Down Expand Up @@ -67,7 +68,7 @@ public class AwsHttpPresignURLClientGenerator implements GoIntegration {
private static final String CONVERT_TO_PRESIGN_MIDDLEWARE_NAME = "convertToPresignMiddleware";
private static final String CONVERT_TO_PRESIGN_TYPE_NAME = "presignConverter";
private static final String NOP_HTTP_CLIENT_OPTION_FUNC_NAME = "withNopHTTPClientAPIOption";

private static final String NO_DEFAULT_CHECKSUM_OPTION_FUNC_NAME = "withNoDefaultChecksumAPIOption";
private static final String PRESIGN_CLIENT = "PresignClient";
private static final Symbol presignClientSymbol = buildSymbol(PRESIGN_CLIENT, true);

Expand Down Expand Up @@ -218,7 +219,11 @@ public void writeAdditionalFiles(
writeConvertToPresignMiddleware(writer, model, symbolProvider, serviceShape);
});

boolean supportsComputeInputChecksumsWorkflow = false;
for (OperationShape operationShape : TopDownIndex.of(model).getContainedOperations(serviceShape)) {
if (hasInputChecksumTrait(operationShape)) {
supportsComputeInputChecksumsWorkflow = true;
}
if (!validOperations.contains(operationShape.getId())) {
continue;
}
Expand All @@ -231,6 +236,10 @@ public void writeAdditionalFiles(
writeS3AddAsUnsignedPayloadHelper(writer, model, symbolProvider, serviceShape, operationShape);
});
}

if (supportsComputeInputChecksumsWorkflow) {
writePresignRequestChecksumConfigHelpers(settings, goDelegator);
}
}

private void writePresignOperationFunction(
Expand Down Expand Up @@ -263,6 +272,10 @@ private void writePresignOperationFunction(

writer.write("clientOptFns := append(options.ClientOptions, $L)", NOP_HTTP_CLIENT_OPTION_FUNC_NAME);
writer.write("");
if (hasInputChecksumTrait(operationShape)) {
writer.write("clientOptFns = append(options.ClientOptions, $L)", NO_DEFAULT_CHECKSUM_OPTION_FUNC_NAME);
writer.write("");
}

writer.openBlock("result, _, err := c.client.invokeOperation(ctx, $S, params, clientOptFns,", ")",
operationSymbol.getName(), () -> {
Expand Down Expand Up @@ -572,6 +585,29 @@ private void writePresignClientHelpers(
writer.write("");
}

private void writePresignRequestChecksumConfigHelpers(
GoSettings settings,
GoDelegator goDelegator
) {
goDelegator.useFileWriter("api_client.go", settings.getModuleName(), goTemplate("""
func $fn:L(options *Options) {
options.RequestChecksumCalculation = $requestChecksumCalculationWhenRequired:T
}""",
Map.of(
"fn", NO_DEFAULT_CHECKSUM_OPTION_FUNC_NAME,
"requestChecksumCalculationWhenRequired",
AwsGoDependency.AWS_CORE.valueSymbol("RequestChecksumCalculationWhenRequired")
)));
}

private static boolean hasInputChecksumTrait(OperationShape operation) {
if (!operation.hasTrait(HttpChecksumTrait.class)) {
return false;
}
HttpChecksumTrait trait = operation.expectTrait(HttpChecksumTrait.class);
return trait.isRequestChecksumRequired() || trait.getRequestAlgorithmMember().isPresent();
}

/**
* Writes the presigner interface used by the presign url client
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package software.amazon.smithy.aws.go.codegen.customization;

import software.amazon.smithy.aws.go.codegen.AwsGoDependency;
import software.amazon.smithy.aws.traits.HttpChecksumTrait;
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.SmithyGoDependency;
import software.amazon.smithy.go.codegen.integration.GoIntegration;
import software.amazon.smithy.go.codegen.integration.MiddlewareRegistrar;
import software.amazon.smithy.go.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;

import java.util.List;
import java.util.Map;

import static software.amazon.smithy.go.codegen.GoWriter.goTemplate;
import static software.amazon.smithy.go.codegen.SymbolUtils.buildPackageSymbol;

public class ChecksumMetricsTracking implements GoIntegration {
private static final MiddlewareRegistrar RequestMIDDLEWARE = MiddlewareRegistrar.builder()
.resolvedFunction(buildPackageSymbol("addRequestChecksumMetricsTracking"))
.useClientOptions()
.build();
private static final MiddlewareRegistrar ResponseMIDDLEWARE = MiddlewareRegistrar.builder()
.resolvedFunction(buildPackageSymbol("addResponseChecksumMetricsTracking"))
.useClientOptions()
.build();

@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return List.of(
RuntimeClientPlugin.builder()
.operationPredicate((m, s, o) -> {
if (!hasInputChecksumTrait(m, s, o)) {
return false;
}
return true;
})
.registerMiddleware(RequestMIDDLEWARE)
.build(),
RuntimeClientPlugin.builder()
.operationPredicate((m, s, o) -> {
if (!hasOutputChecksumTrait(m, s, o)) {
return false;
}
return true;
})
.registerMiddleware(ResponseMIDDLEWARE)
.build()
);
}

private static boolean hasChecksumTrait(Model model, ServiceShape service, OperationShape operation) {
return operation.hasTrait(HttpChecksumTrait.class);
}

private static boolean hasInputChecksumTrait(Model model, ServiceShape service, OperationShape operation) {
if (!hasChecksumTrait(model, service, operation)) {
return false;
}
HttpChecksumTrait trait = operation.expectTrait(HttpChecksumTrait.class);
return trait.isRequestChecksumRequired() || trait.getRequestAlgorithmMember().isPresent();
}

private static boolean hasOutputChecksumTrait(Model model, ServiceShape service, OperationShape operation) {
if (!hasChecksumTrait(model, service, operation)) {
return false;
}
HttpChecksumTrait trait = operation.expectTrait(HttpChecksumTrait.class);
return trait.getRequestValidationModeMember().isPresent() && !trait.getResponseAlgorithms().isEmpty();
}

@Override
public void writeAdditionalFiles(GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator goDelegator) {
ServiceShape service = settings.getService(model);
boolean supportsComputeInputChecksumsWorkflow = false;
boolean supportsChecksumValidationWorkflow = false;

for (OperationShape operation : TopDownIndex.of(model).getContainedOperations(service)) {
if (!hasChecksumTrait(model, service, operation)) {
continue;
}

if (hasInputChecksumTrait(model, service, operation)) {
supportsComputeInputChecksumsWorkflow = true;
}

if (hasOutputChecksumTrait(model, service, operation)) {
supportsChecksumValidationWorkflow = true;
}
}

if (supportsComputeInputChecksumsWorkflow) {
goDelegator.useFileWriter("api_client.go", settings.getModuleName(), goTemplate("""
func addRequestChecksumMetricsTracking(stack $stack:P, options Options) error {
ua, err := getOrAddRequestUserAgent(stack)
if err != nil {
return err
}

return stack.Build.Insert(&$requestMetricsTracking:P{
RequestChecksumCalculation: options.RequestChecksumCalculation,
UserAgent: ua,
}, "UserAgent", $before:T)
}""",
Map.of(
"stack", SmithyGoDependency.SMITHY_MIDDLEWARE.struct("Stack"),
"requestMetricsTracking", AwsGoDependency.SERVICE_INTERNAL_CHECKSUM.valueSymbol("RequestChecksumMetricsTracking"),
"before", SmithyGoDependency.SMITHY_MIDDLEWARE
.valueSymbol("Before")
)));
}

if (supportsChecksumValidationWorkflow) {
goDelegator.useFileWriter("api_client.go", settings.getModuleName(), goTemplate("""
func addResponseChecksumMetricsTracking(stack $stack:P, options Options) error {
ua, err := getOrAddRequestUserAgent(stack)
if err != nil {
return err
}

return stack.Build.Insert(&$responseMetricsTracking:P{
ResponseChecksumValidation: options.ResponseChecksumValidation,
UserAgent: ua,
}, "UserAgent", $before:T)
}""",
Map.of(
"stack", SmithyGoDependency.SMITHY_MIDDLEWARE.struct("Stack"),
"responseMetricsTracking", AwsGoDependency.SERVICE_INTERNAL_CHECKSUM.valueSymbol("ResponseChecksumMetricsTracking"),
"before", SmithyGoDependency.SMITHY_MIDDLEWARE
.valueSymbol("Before")
)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,4 @@ software.amazon.smithy.aws.go.codegen.customization.s3.ExpressUserAgent
software.amazon.smithy.aws.go.codegen.customization.BackfillRequiredTrait
software.amazon.smithy.aws.go.codegen.customization.DeprecateService
software.amazon.smithy.aws.go.codegen.customization.BasicUserAgentFeatures

software.amazon.smithy.aws.go.codegen.customization.ChecksumMetricsTracking
39 changes: 30 additions & 9 deletions feature/s3/manager/integ_upload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"testing"

"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
Expand Down Expand Up @@ -223,6 +222,28 @@ func TestInteg_UploadPresetChecksum(t *testing.T) {
},
},
"auto multipart part": {
"no checksum": {
wty-Bryant marked this conversation as resolved.
Show resolved Hide resolved
payload: bytes.NewReader(multiPartBytes),
expectParts: []s3types.CompletedPart{
{
ChecksumCRC32: aws.String(singlePartCRC32),
ETag: aws.String(singlePartETag),
PartNumber: aws.Int32(1),
},
{
ChecksumCRC32: aws.String(singlePartCRC32),
ETag: aws.String(singlePartETag),
PartNumber: aws.Int32(2),
},
{
ChecksumCRC32: aws.String(multiPartTailCRC32),
ETag: aws.String(multiPartTailETag),
PartNumber: aws.Int32(3),
},
},
expectChecksumCRC32: multiPartCRC32,
expectETag: multiPartETag,
},
"CRC32": {
algorithm: s3types.ChecksumAlgorithmCrc32,
payload: bytes.NewReader(multiPartBytes),
Expand Down Expand Up @@ -468,21 +489,21 @@ func toStringPtr(v string) *string {
return &v
}

type invalidateHash struct{}
type failedMultipartUpload struct{}

func (b *invalidateHash) ID() string {
return "s3manager:InvalidateHash"
func (m *failedMultipartUpload) ID() string {
return "s3manager:FailedMultipartUpload"
}

func (b *invalidateHash) RegisterMiddleware(stack *middleware.Stack) error {
return stack.Serialize.Add(b, middleware.After)
func (m *failedMultipartUpload) RegisterMiddleware(stack *middleware.Stack) error {
return stack.Serialize.Add(m, middleware.After)
}

func (b *invalidateHash) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
func (m *failedMultipartUpload) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if input, ok := in.Parameters.(*s3.UploadPartInput); ok && aws.ToInt32(input.PartNumber) == 2 {
ctx = v4.SetPayloadHash(ctx, "000")
return out, metadata, fmt.Errorf("multipart upload error")
}

return next.HandleSerialize(ctx, in)
Expand All @@ -493,7 +514,7 @@ func TestInteg_UploadFailCleanup(t *testing.T) {
mgr := manager.NewUploader(client, func(u *manager.Uploader) {
u.LeavePartsOnError = false
u.ClientOptions = append(u.ClientOptions, func(options *s3.Options) {
options.APIOptions = append(options.APIOptions, (&invalidateHash{}).RegisterMiddleware)
options.APIOptions = append(options.APIOptions, (&failedMultipartUpload{}).RegisterMiddleware)
})
})
_, err := mgr.Upload(context.Background(), &s3.PutObjectInput{
Expand Down
21 changes: 21 additions & 0 deletions feature/s3/manager/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,8 @@ func (a completedParts) Less(i, j int) bool {
// upload will perform a multipart upload using the firstBuf buffer containing
// the first chunk of data.
func (u *multiuploader) upload(firstBuf io.ReadSeeker, cleanup func()) (*UploadOutput, error) {
u.initChecksumAlgorithm()

var params s3.CreateMultipartUploadInput
awsutil.Copy(&params, u.in)

Expand Down Expand Up @@ -752,6 +754,25 @@ func (u *multiuploader) send(c chunk) error {
return nil
}

func (u *multiuploader) initChecksumAlgorithm() {
if u.in.ChecksumAlgorithm != "" {
return
}

switch {
case u.in.ChecksumCRC32 != nil:
u.in.ChecksumAlgorithm = types.ChecksumAlgorithmCrc32
case u.in.ChecksumCRC32C != nil:
u.in.ChecksumAlgorithm = types.ChecksumAlgorithmCrc32c
case u.in.ChecksumSHA1 != nil:
u.in.ChecksumAlgorithm = types.ChecksumAlgorithmSha1
case u.in.ChecksumSHA256 != nil:
u.in.ChecksumAlgorithm = types.ChecksumAlgorithmSha256
default:
u.in.ChecksumAlgorithm = types.ChecksumAlgorithmCrc32
}
}

// geterr is a thread-safe getter for the error object
func (u *multiuploader) geterr() error {
u.m.Lock()
Expand Down
Loading
Loading