-
Notifications
You must be signed in to change notification settings - Fork 54
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
Add Gzip request compression feature #467
Changes from 13 commits
791088d
f65e28c
f07d7c1
be821ce
833fea1
e23df69
cab0c67
fc068fa
293356e
1296474
5b5d3bf
7840dc4
6031dad
2054530
eb29c1c
6b279ca
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"id": "80ed2832-7bcd-4301-a264-f318efaf8216", | ||
"type": "feature", | ||
"description": "Support modeled request compression.", | ||
"modules": [ | ||
"." | ||
] | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
/* | ||
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
wty-Bryant marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* 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.requestcompression; | ||
|
||
import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import software.amazon.smithy.codegen.core.SymbolProvider; | ||
import software.amazon.smithy.go.codegen.GoCodegenPlugin; | ||
import software.amazon.smithy.go.codegen.GoDelegator; | ||
import software.amazon.smithy.go.codegen.GoSettings; | ||
import software.amazon.smithy.go.codegen.GoUniverseTypes; | ||
import software.amazon.smithy.go.codegen.GoWriter; | ||
import software.amazon.smithy.go.codegen.SmithyGoTypes; | ||
import software.amazon.smithy.go.codegen.SymbolUtils; | ||
import software.amazon.smithy.go.codegen.integration.ConfigField; | ||
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 software.amazon.smithy.model.shapes.ShapeId; | ||
import software.amazon.smithy.model.traits.RequestCompressionTrait; | ||
import software.amazon.smithy.utils.ListUtils; | ||
import software.amazon.smithy.utils.MapUtils; | ||
|
||
|
||
public final class RequestCompression implements GoIntegration { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit overall: private fields should go below public fields, and private methods should go towards the bottom of the class below all the public methods. |
||
private static final String DISABLE_REQUEST_COMPRESSION = "DisableRequestCompression"; | ||
|
||
private static final String REQUEST_MIN_COMPRESSION_SIZE_BYTES = "RequestMinCompressSizeBytes"; | ||
|
||
private final List<RuntimeClientPlugin> runtimeClientPlugins = new ArrayList<>(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keeping state in an integration is generally not best practice. |
||
|
||
private static String getAddRequestCompressionMiddlewareFuncName(String operationName) { | ||
return String.format("addOperation%sRequestCompressionMiddleware", operationName); | ||
} | ||
|
||
// Write operation plugin for request compression middleware | ||
@Override | ||
public void processFinalizedModel(GoSettings settings, Model model) { | ||
ServiceShape service = settings.getService(model); | ||
TopDownIndex.of(model) | ||
.getContainedOperations(service).forEach(operation -> { | ||
if (!operation.hasTrait(RequestCompressionTrait.class)) { | ||
return; | ||
} | ||
SymbolProvider symbolProvider = GoCodegenPlugin.createSymbolProvider(model, settings); | ||
String funcName = getAddRequestCompressionMiddlewareFuncName( | ||
symbolProvider.toSymbol(operation).getName() | ||
); | ||
runtimeClientPlugins.add(RuntimeClientPlugin.builder().operationPredicate((m, s, o) -> { | ||
if (!o.hasTrait(RequestCompressionTrait.class)) { | ||
return false; | ||
} | ||
return o.equals(operation); | ||
syall marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}).registerMiddleware(MiddlewareRegistrar.builder() | ||
.resolvedFunction(SymbolUtils.buildPackageSymbol(funcName)) | ||
.useClientOptions().build()) | ||
.build()); | ||
}); | ||
} | ||
|
||
@Override | ||
public void writeAdditionalFiles( | ||
GoSettings settings, | ||
Model model, | ||
SymbolProvider symbolProvider, | ||
GoDelegator goDelegator | ||
) { | ||
ServiceShape service = settings.getService(model); | ||
for (ShapeId operationID : service.getAllOperations()) { | ||
OperationShape operation = model.expectShape(operationID, OperationShape.class); | ||
if (!operation.hasTrait(RequestCompressionTrait.class)) { | ||
continue; | ||
} | ||
goDelegator.useShapeWriter(operation, writeMiddlewareHelper(symbolProvider, operation)); | ||
} | ||
} | ||
|
||
|
||
public static boolean isRequestCompressionService(Model model, ServiceShape service) { | ||
return TopDownIndex.of(model) | ||
.getContainedOperations(service).stream() | ||
.anyMatch(it -> it.hasTrait(RequestCompressionTrait.class)); | ||
} | ||
|
||
private GoWriter.Writable writeMiddlewareHelper(SymbolProvider symbolProvider, OperationShape operation) { | ||
String operationName = symbolProvider.toSymbol(operation).getName(); | ||
RequestCompressionTrait trait = operation.expectTrait(RequestCompressionTrait.class); | ||
|
||
return goTemplate(""" | ||
func $add:L(stack $stack:P, options Options) error { | ||
return $addInternal:T(stack, options.DisableRequestCompression, options.RequestMinCompressSizeBytes, | ||
$algorithms:W) | ||
} | ||
""", | ||
MapUtils.of( | ||
"add", getAddRequestCompressionMiddlewareFuncName(operationName), | ||
"stack", SmithyGoTypes.Middleware.Stack, | ||
"addInternal", SmithyGoTypes.Private.RequestCompression.AddRequestCompression, | ||
"algorithms", generateAlgorithmList(trait.getEncodings()) | ||
)); | ||
} | ||
|
||
@Override | ||
public List<RuntimeClientPlugin> getClientPlugins() { | ||
runtimeClientPlugins.add( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FYI he's doing this because of having to add per-operation middlewares elsewhere in There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we have confirmed that in resolved comments, thx for clarification |
||
RuntimeClientPlugin.builder() | ||
.servicePredicate(RequestCompression::isRequestCompressionService) | ||
.configFields(ListUtils.of( | ||
ConfigField.builder() | ||
.name(DISABLE_REQUEST_COMPRESSION) | ||
.type(GoUniverseTypes.Bool) | ||
.documentation( | ||
"Whether to disable automatic request compression for supported operations.") | ||
.build(), | ||
ConfigField.builder() | ||
.name(REQUEST_MIN_COMPRESSION_SIZE_BYTES) | ||
.type(GoUniverseTypes.Int64) | ||
.documentation("The minimum request body size, in bytes, at which compression " | ||
+ "should occur. The default value is 10 KiB. Values must fall within " | ||
+ "[0, 1MiB].") | ||
.build() | ||
)) | ||
.build() | ||
); | ||
|
||
return runtimeClientPlugins; | ||
} | ||
|
||
private GoWriter.Writable generateAlgorithmList(List<String> algorithms) { | ||
return goTemplate(""" | ||
[]string{ | ||
$W | ||
} | ||
""", | ||
GoWriter.ChainWritable.of( | ||
algorithms.stream() | ||
.map(it -> goTemplate("$S,", it)) | ||
.toList() | ||
).compose(false)); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package requestcompression | ||
|
||
import ( | ||
"bytes" | ||
"compress/gzip" | ||
"fmt" | ||
"io" | ||
) | ||
|
||
func gzipCompress(input io.Reader) ([]byte, error) { | ||
var b bytes.Buffer | ||
w, err := gzip.NewWriterLevel(&b, gzip.DefaultCompression) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to create gzip writer, %v", err) | ||
} | ||
|
||
inBytes, err := io.ReadAll(input) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed read payload to compress, %v", err) | ||
} | ||
|
||
if _, err = w.Write(inBytes); err != nil { | ||
return nil, fmt.Errorf("failed to write payload to be compressed, %v", err) | ||
} | ||
if err = w.Close(); err != nil { | ||
return nil, fmt.Errorf("failed to flush payload being compressed, %v", err) | ||
} | ||
|
||
return b.Bytes(), nil | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
// Package requestcompression implements runtime support for smithy-modeled | ||
// request compression. | ||
// | ||
// This package is designated as private and is intended for use only by the | ||
// smithy client runtime. The exported API therein is not considered stable and | ||
// is subject to breaking changes without notice. | ||
package requestcompression | ||
wty-Bryant marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
"github.com/aws/smithy-go/middleware" | ||
"github.com/aws/smithy-go/transport/http" | ||
"io" | ||
) | ||
|
||
const maxRequestMinCompressSizeBytes = 10485760 | ||
|
||
// Enumeration values for supported compress Algorithms. | ||
const ( | ||
GZIP = "gzip" | ||
) | ||
|
||
type compressFunc func(io.Reader) ([]byte, error) | ||
|
||
var allowedAlgorithms = map[string]compressFunc{ | ||
GZIP: gzipCompress, | ||
} | ||
|
||
// AddRequestCompression add requestCompression middleware to op stack | ||
func AddRequestCompression(stack *middleware.Stack, disabled bool, minBytes int64, algorithms []string) error { | ||
return stack.Serialize.Add(&requestCompression{ | ||
disableRequestCompression: disabled, | ||
requestMinCompressSizeBytes: minBytes, | ||
compressAlgorithms: algorithms, | ||
}, middleware.After) | ||
} | ||
|
||
type requestCompression struct { | ||
disableRequestCompression bool | ||
wty-Bryant marked this conversation as resolved.
Show resolved
Hide resolved
|
||
requestMinCompressSizeBytes int64 | ||
compressAlgorithms []string | ||
} | ||
|
||
// ID returns the ID of the middleware | ||
func (m requestCompression) ID() string { | ||
return "RequestCompression" | ||
} | ||
|
||
// HandleSerialize gzip compress the request's stream/body if enabled by config fields | ||
func (m requestCompression) HandleSerialize( | ||
ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, | ||
) ( | ||
out middleware.SerializeOutput, metadata middleware.Metadata, err error, | ||
) { | ||
if m.disableRequestCompression { | ||
return next.HandleSerialize(ctx, in) | ||
} | ||
// still need to check requestMinCompressSizeBytes in case it is out of range after service client config | ||
if m.requestMinCompressSizeBytes < 0 || m.requestMinCompressSizeBytes > maxRequestMinCompressSizeBytes { | ||
return out, metadata, fmt.Errorf("invalid range for min request compression size bytes %d, must be within 0 and 10485760 inclusively", m.requestMinCompressSizeBytes) | ||
} | ||
|
||
req, ok := in.Request.(*http.Request) | ||
if !ok { | ||
return out, metadata, fmt.Errorf("unknown request type %T", req) | ||
} | ||
|
||
for _, algorithm := range m.compressAlgorithms { | ||
compressFunc := allowedAlgorithms[algorithm] | ||
if compressFunc != nil { | ||
if stream := req.GetStream(); stream != nil { | ||
wty-Bryant marked this conversation as resolved.
Show resolved
Hide resolved
|
||
size, found, err := req.StreamLength() | ||
if err != nil { | ||
return out, metadata, fmt.Errorf("error while finding request stream length, %v", err) | ||
} else if !found || size < m.requestMinCompressSizeBytes { | ||
return next.HandleSerialize(ctx, in) | ||
} | ||
|
||
compressedBytes, err := compressFunc(stream) | ||
if err != nil { | ||
return out, metadata, fmt.Errorf("failed to compress request stream, %v", err) | ||
} | ||
|
||
var newReq *http.Request | ||
if newReq, err = req.SetStream(bytes.NewReader(compressedBytes)); err != nil { | ||
return out, metadata, fmt.Errorf("failed to set request stream, %v", err) | ||
} | ||
*req = *newReq | ||
|
||
if val := req.Header.Get("Content-Encoding"); val != "" { | ||
req.Header.Set("Content-Encoding", fmt.Sprintf("%s, %s", val, algorithm)) | ||
} else { | ||
req.Header.Set("Content-Encoding", algorithm) | ||
} | ||
} | ||
break | ||
} | ||
} | ||
|
||
return next.HandleSerialize(ctx, in) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix formatting for this line.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
smithy go doesn't allow single line exceeding 120 chars, that's why there's a separate line
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.