From de363f2e404d5ad61670bbd37d3ed5bf8cc6835e Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Fri, 5 Apr 2024 11:21:02 -0500 Subject: [PATCH 01/27] Generated code builds --- .../Protocols/AWSJSON/AWSJSONError.swift | 41 ++ .../Protocols/Ec2Query/Ec2QueryError.swift | 55 ++- .../Protocols/Ec2Query/Ec2Response.swift | 8 +- .../Protocols/RestJSON/RestJSONError.swift | 119 +++-- .../swift/codegen/AWSClientRuntimeTypes.kt | 1 + .../AWSHttpBindingProtocolGenerator.kt | 35 +- .../codegen/AWSHttpProtocolCustomizations.kt | 13 - .../codegen/AWSHttpRequestFormURLEncoder.kt | 6 +- .../codegen/AWSHttpRequestJsonEncoder.kt | 13 - .../codegen/AWSHttpResponseJsonDecoder.kt | 13 - ...WSJsonHttpResponseBindingErrorGenerator.kt | 116 +---- .../awsjson/AwsJson1_0_ProtocolGenerator.kt | 20 +- .../awsjson/AwsJson1_1_ProtocolGenerator.kt | 19 +- .../AWSHttpProtocolAwsQueryCustomizations.kt | 6 +- .../awsquery/AwsQueryProtocolGenerator.kt | 30 +- ...SQueryHttpResponseBindingErrorGenerator.kt | 112 +---- .../Route53InvalidBatchErrorIntegration.kt | 4 +- .../customization/s3/S3ErrorIntegration.kt | 4 +- .../AWSHttpProtocolEc2QueryCustomizations.kt | 3 +- .../ec2query/Ec2QueryProtocolGenerator.kt | 28 +- ...2QueryHttpResponseBindingErrorGenerator.kt | 112 +---- ...esponseBindingErrorInitGeneratorFactory.kt | 18 - .../message/MessageMarshallableGenerator.kt | 422 ++++++++-------- .../message/MessageUnmarshallableGenerator.kt | 462 +++++++++--------- .../XMLMessageUnmarshallableGenerator.kt | 4 +- ...son1HttpResponseBindingErrorGeneratable.kt | 107 +--- .../restjson/AWSRestJson1ProtocolGenerator.kt | 20 +- ...estXMLHttpResponseBindingErrorGenerator.kt | 135 +---- .../restxml/RestXmlProtocolGenerator.kt | 57 +-- ...esponseBindingErrorInitGeneratorFactory.kt | 18 - 30 files changed, 705 insertions(+), 1296 deletions(-) create mode 100644 Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestJsonEncoder.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpResponseJsonDecoder.kt diff --git a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift new file mode 100644 index 00000000000..8ed9d505925 --- /dev/null +++ b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift @@ -0,0 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import class SmithyJSON.Reader + +public struct AWSJSONError { + public let code: String + public let message: String? + public let requestID: String? + + public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { + noErrorWrapping ? responseReader : responseReader["Error"] + } + + public init(responseReader: Reader, noErrorWrapping: Bool) throws { + let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) + let code: String? = try reader["Code"].readIfPresent() + let message: String? = try reader["Message"].readIfPresent() + let requestID: String? = try responseReader["RequestId"].readIfPresent() + guard let code else { + throw AWSJSONDecodeError.missingRequiredData + } + self.code = code + self.message = message + self.requestID = requestID + } + + public init(code: String, message: String?, requestID: String?) { + self.code = code + self.message = message + self.requestID = requestID + } +} + +public enum AWSJSONDecodeError: Error { + case missingRequiredData +} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift index 19d2c419c11..457edefd718 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift @@ -5,19 +5,54 @@ // SPDX-License-Identifier: Apache-2.0 // -import class ClientRuntime.HttpResponse +//import class ClientRuntime.HttpResponse +//import class SmithyXML.Reader +//import func SmithyReadWrite.wireResponseDocumentBinding +// +//public struct Ec2QueryError { +// public var errorCode: String? +// public var requestId: String? +// public var message: String? +// +// public init(httpResponse: HttpResponse) async throws { +// let response = try await Ec2Response.httpBinding(httpResponse, wireResponseDocumentBinding()) +// self.errorCode = response.errors?.error?.code +// self.message = response.errors?.error?.message +// self.requestId = response.requestId +// } +//} + import class SmithyXML.Reader -import var ClientRuntime.responseDocumentBinding public struct Ec2QueryError { - public var errorCode: String? - public var requestId: String? - public var message: String? + public let code: String + public let message: String? + public let requestID: String? + + public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { + noErrorWrapping ? responseReader : responseReader["Error"] + } - public init(httpResponse: HttpResponse) async throws { - let response = try await Ec2Response.httpBinding(httpResponse, responseDocumentBinding) - self.errorCode = response.errors?.error?.code - self.message = response.errors?.error?.message - self.requestId = response.requestId + public init(responseReader: Reader, noErrorWrapping: Bool) throws { + let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) + let code: String? = try reader["Code"].readIfPresent() + let message: String? = try reader["Message"].readIfPresent() + let requestID: String? = try responseReader["RequestId"].readIfPresent() + guard let code else { + throw Ec2QueryDecodeError.missingRequiredData + } + self.code = code + self.message = message + self.requestID = requestID } + + public init(code: String, message: String?, requestID: String?) { + self.code = code + self.message = message + self.requestID = requestID + } +} + +public enum Ec2QueryDecodeError: Error { + case missingRequiredData } diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift index 9ddcb5cd9f8..af1bfbf0b43 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift @@ -6,16 +6,16 @@ // import SmithyReadWrite -import SmithyXML +import class SmithyXML.Reader import ClientRuntime public struct Ec2Response { public var errors: Ec2Errors? public var requestId: String? - public static var httpBinding: HTTPResponseOutputBinding { - return { httpResponse, responseDocumentBinding in - let reader = try await responseDocumentBinding(httpResponse) + public static var httpBinding: WireResponseOutputBinding { + return { httpResponse, wireResponseDocumentBinding in + let reader = try await wireResponseDocumentBinding(httpResponse) var value = Ec2Response() value.errors = try reader["Errors"].readIfPresent(readingClosure: Ec2Errors.readingClosure) value.requestId = try reader["RequestId"].readIfPresent() ?? reader["RequestID"].readIfPresent() diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift index 3ba684abecc..f25d32ed1f3 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift @@ -6,54 +6,89 @@ import Foundation import ClientRuntime -/// A general Error Structure for Rest JSON protocol -public struct RestJSONError { - public let errorType: String? - public let errorMessage: String? - - // header identifying the error code - let X_AMZN_ERROR_TYPE_HEADER_NAME = "X-Amzn-Errortype" - - // returned by RESTFUL services that do no send a payload (like in a HEAD request) - let X_AMZN_ERROR_MESSAGE_HEADER_NAME = "x-amzn-error-message" +import class SmithyJSON.Reader - // returned by some services like Cognito - let X_AMZN_ERRORMESSAGE_HEADER_NAME = "x-amzn-ErrorMessage" - - // error message header returned by event stream errors - let X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME = ":error-message" - - public init(httpResponse: HttpResponse) async throws { - var message = httpResponse.headers.value(for: X_AMZN_ERROR_MESSAGE_HEADER_NAME) - if message == nil { - message = httpResponse.headers.value(for: X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME) - } +/// A general Error Structure for Rest JSON protocol +//public struct RestJSONError { +// public let errorType: String? +// public let errorMessage: String? +// +// // header identifying the error code +// let X_AMZN_ERROR_TYPE_HEADER_NAME = "X-Amzn-Errortype" +// +// // returned by RESTFUL services that do no send a payload (like in a HEAD request) +// let X_AMZN_ERROR_MESSAGE_HEADER_NAME = "x-amzn-error-message" +// +// // returned by some services like Cognito +// let X_AMZN_ERRORMESSAGE_HEADER_NAME = "x-amzn-ErrorMessage" +// +// // error message header returned by event stream errors +// let X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME = ":error-message" +// +// public init(httpResponse: HttpResponse) async throws { +// var message = httpResponse.headers.value(for: X_AMZN_ERROR_MESSAGE_HEADER_NAME) +// if message == nil { +// message = httpResponse.headers.value(for: X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME) +// } +// +// if message == nil { +// message = httpResponse.headers.value(for: X_AMZN_ERRORMESSAGE_HEADER_NAME) +// } +// +// var type = httpResponse.headers.value(for: X_AMZN_ERROR_TYPE_HEADER_NAME) +// +// if let data = try await httpResponse.body.readData() { +// let output: RestJSONErrorPayload = try JSONDecoder().decode(responseBody: data) +// if message == nil { +// message = output.resolvedErrorMessage +// } +// if type == nil { +// type = output.resolvedErrorType +// } +// } +// self.errorType = RestJSONError.sanitizeErrorType(type) +// self.errorMessage = message +// } +// +// /// Filter additional information from error name and sanitize it +// /// Reference: https://awslabs.github.io/smithy/1.0/spec/aws/aws-restjson1-protocol.html#operation-error-serialization +// static func sanitizeErrorType(_ type: String?) -> String? { +// guard let errorType = type else { +// return type +// } +// return errorType.substringAfter("#").substringBefore(":").trim() +// } +//} - if message == nil { - message = httpResponse.headers.value(for: X_AMZN_ERRORMESSAGE_HEADER_NAME) - } +public struct RestJSONError { + public let code: String + public let message: String? + public let requestID: String? - var type = httpResponse.headers.value(for: X_AMZN_ERROR_TYPE_HEADER_NAME) + public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { + noErrorWrapping ? responseReader : responseReader["Error"] + } - if let data = try await httpResponse.body.readData() { - let output: RestJSONErrorPayload = try JSONDecoder().decode(responseBody: data) - if message == nil { - message = output.resolvedErrorMessage - } - if type == nil { - type = output.resolvedErrorType - } + public init(responseReader: Reader, noErrorWrapping: Bool) throws { + let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) + let code: String? = try reader["Code"].readIfPresent() + let message: String? = try reader["Message"].readIfPresent() + let requestID: String? = try responseReader["RequestId"].readIfPresent() + guard let code else { + throw RestJSONDecodeError.missingRequiredData } - self.errorType = RestJSONError.sanitizeErrorType(type) - self.errorMessage = message + self.code = code + self.message = message + self.requestID = requestID } - /// Filter additional information from error name and sanitize it - /// Reference: https://awslabs.github.io/smithy/1.0/spec/aws/aws-restjson1-protocol.html#operation-error-serialization - static func sanitizeErrorType(_ type: String?) -> String? { - guard let errorType = type else { - return type - } - return errorType.substringAfter("#").substringBefore(":").trim() + public init(code: String, message: String?, requestID: String?) { + self.code = code + self.message = message + self.requestID = requestID } } + +public enum RestJSONDecodeError: Error { + case missingRequiredData +} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt index 7b9b21e03e4..1592ba5b04c 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt @@ -15,6 +15,7 @@ object AWSClientRuntimeTypes { val Ec2QueryError = runtimeSymbol("Ec2QueryError") } object AWSJSON { + val AWSJSONError = runtimeSymbol("AWSJSONError") val XAmzTargetMiddleware = runtimeSymbol("XAmzTargetMiddleware") } object RestJSON { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt index d82d63cc70e..0f3feed9355 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt @@ -4,8 +4,8 @@ */ package software.amazon.smithy.aws.swift.codegen -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator +//import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +//import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.OperationEndpointResolverMiddleware import software.amazon.smithy.aws.swift.codegen.middleware.UserAgentMiddleware import software.amazon.smithy.codegen.core.Symbol @@ -25,8 +25,8 @@ import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestErro import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestRequestGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestResponseGenerator import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.serde.json.StructDecodeGenerator -import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator import software.amazon.smithy.swift.codegen.model.ShapeMetadata import software.amazon.smithy.swift.codegen.model.findStreamingMember import software.amazon.smithy.swift.codegen.model.getTrait @@ -52,7 +52,6 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() open val tagsToIgnore: Set = setOf() override val shouldRenderDecodableBodyStructForInputShapes = true - override val shouldRenderCodingKeysForEncodable = true override val shouldRenderEncodableConformance = false override fun generateProtocolUnitTests(ctx: ProtocolGenerator.GenerationContext): Int { val imports = listOf(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) @@ -97,8 +96,7 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() defaultTimestampFormat: TimestampFormatTrait.Format, path: String? ) { - val encodeGenerator = StructEncodeGenerator(ctx, members, writer, defaultTimestampFormat, path) - encodeGenerator.render() + StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, writer).render() } override fun renderStructDecode( @@ -110,8 +108,7 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() defaultTimestampFormat: TimestampFormatTrait.Format, path: String ) { - val decoder = StructDecodeGenerator(ctx, members, writer, defaultTimestampFormat, path) - decoder.render() + StructDecodeXMLGenerator(ctx, shapeContainingMembers, members, shapeMetaData, writer).render() } override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { @@ -120,19 +117,19 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() } override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.renderNotImplemented(streamingMember) - } +// var streamingShapes = outputStreamingShapes(ctx) +// val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) +// streamingShapes.forEach { streamingMember -> +// messageUnmarshallableGenerator.renderNotImplemented(streamingMember) +// } } override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - for (streamingShape in streamingShapes) { - messageMarshallableGenerator.renderNotImplemented(streamingShape) - } +// val streamingShapes = inputStreamingShapes(ctx) +// val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) +// for (streamingShape in streamingShapes) { +// messageMarshallableGenerator.renderNotImplemented(streamingShape) +// } } fun outputStreamingShapes(ctx: ProtocolGenerator.GenerationContext): MutableSet { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt index 6aae12eec14..0f33137aa2b 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt @@ -53,19 +53,6 @@ abstract class AWSHttpProtocolCustomizations : DefaultHttpProtocolCustomizations EndpointResolverGenerator().render(ctx) } - override fun getClientProperties(): List { - val properties = mutableListOf() - val requestEncoderOptions = mutableMapOf() - val responseDecoderOptions = mutableMapOf() - requestEncoderOptions["dateEncodingStrategy"] = ".secondsSince1970" - requestEncoderOptions["nonConformingFloatEncodingStrategy"] = ".convertToString(positiveInfinity: \"Infinity\", negativeInfinity: \"-Infinity\", nan: \"NaN\")" - responseDecoderOptions["dateDecodingStrategy"] = ".secondsSince1970" - responseDecoderOptions["nonConformingFloatDecodingStrategy"] = ".convertFromString(positiveInfinity: \"Infinity\", negativeInfinity: \"-Infinity\", nan: \"NaN\")" - properties.add(AWSHttpRequestJsonEncoder(requestEncoderOptions)) - properties.add(AWSHttpResponseJsonDecoder(responseDecoderOptions)) - return properties - } - override fun serviceClient( ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter, diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt index 0f6a72738ce..25e5aaa5101 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt @@ -8,6 +8,6 @@ package software.amazon.smithy.aws.swift.codegen import software.amazon.smithy.swift.codegen.ClientRuntimeTypes import software.amazon.smithy.swift.codegen.integration.HttpRequestEncoder -class AWSHttpRequestFormURLEncoder( - requestEncoderOptions: MutableMap = mutableMapOf() -) : HttpRequestEncoder(ClientRuntimeTypes.Serde.FormURLEncoder, requestEncoderOptions) +//class AWSHttpRequestFormURLEncoder( +// requestEncoderOptions: MutableMap = mutableMapOf() +//) : HttpRequestEncoder(ClientRuntimeTypes.Serde.FormURLEncoder, requestEncoderOptions) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestJsonEncoder.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestJsonEncoder.kt deleted file mode 100644 index 2d25530b986..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestJsonEncoder.kt +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen - -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.integration.HttpRequestEncoder - -class AWSHttpRequestJsonEncoder( - requestEncoderOptions: MutableMap = mutableMapOf() -) : HttpRequestEncoder(ClientRuntimeTypes.Serde.JSONEncoder, requestEncoderOptions) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpResponseJsonDecoder.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpResponseJsonDecoder.kt deleted file mode 100644 index 65295bb9d4b..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpResponseJsonDecoder.kt +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen - -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.integration.HttpResponseDecoder - -class AWSHttpResponseJsonDecoder( - responseDecoderOptions: MutableMap = mutableMapOf() -) : HttpResponseDecoder(ClientRuntimeTypes.Serde.JSONDecoder, responseDecoderOptions) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt index 2ea103bed75..cddad77e01a 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt @@ -6,120 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.awsjson import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftTypes -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable -import software.amazon.smithy.swift.codegen.model.toUpperCamelCase -import software.amazon.smithy.swift.codegen.utils.errorShapeName +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -class AWSJsonHttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable { - override fun renderServiceError(ctx: ProtocolGenerator.GenerationContext) { - val serviceShape = ctx.service - val serviceName = ctx.service.id.name - val rootNamespace = ctx.settings.moduleName - val fileName = "./$rootNamespace/models/$serviceName+ServiceErrorHelperMethod.swift" +class AWSJsonHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - ctx.delegator.useFileWriter(fileName) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock("extension ${ctx.symbolProvider.toSymbol(ctx.service).name}Types {", "}") { - openBlock( - "static func makeServiceError(_ httpResponse: \$N, _ decoder: \$D, _ error: \$N, _ id: String?) async throws -> \$N? {", - "}", - ClientRuntimeTypes.Http.HttpResponse, - ClientRuntimeTypes.Serde.ResponseDecoder, - AWSClientRuntimeTypes.RestJSON.RestJSONError, - SwiftTypes.Error - ) { - openBlock("switch error.errorType {", "}") { - val serviceErrorShapes = - serviceShape.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - serviceErrorShapes.forEach { errorShape -> - val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: error.errorMessage, requestID: id)", - errorShapeName, - errorShapeType - ) - } - write("default: return nil") - } - } - } - } - } - } - - override fun renderOperationError(ctx: ProtocolGenerator.GenerationContext, op: OperationShape, unknownServiceErrorSymbol: Symbol) { - val operationErrorName = "${op.toUpperCamelCase()}OutputError" - val rootNamespace = ctx.settings.moduleName - val httpBindingSymbol = Symbol.builder() - .definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseErrorBinding.swift") - .name(operationErrorName) - .build() - - ctx.delegator.useShapeWriter(httpBindingSymbol) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock( - "enum \$L: \$N {", - "}", - operationErrorName, - ClientRuntimeTypes.Http.HttpResponseErrorBinding - ) { - openBlock( - "static func makeError(httpResponse: \$N, decoder: \$D) async throws -> \$N {", "}", - ClientRuntimeTypes.Http.HttpResponse, - ClientRuntimeTypes.Serde.ResponseDecoder, - SwiftTypes.Error - ) { - write( - "let restJSONError = try await \$N(httpResponse: httpResponse)", - AWSClientRuntimeTypes.RestJSON.RestJSONError - ) - write("let requestID = httpResponse.requestId") - - if (ctx.service.errors.isNotEmpty()) { - write("let serviceError = try await ${ctx.symbolProvider.toSymbol(ctx.service).name}Types.makeServiceError(httpResponse, decoder, restJSONError, requestID)") - write("if let error = serviceError { return error }") - } - - openBlock("switch restJSONError.errorType {", "}") { - val errorShapes = op.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - errorShapes.forEach { errorShape -> - var errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - var errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: restJSONError.errorMessage, requestID: requestID)", - errorShapeName, - errorShapeType - ) - } - write( - "default: return try await \$N.makeError(httpResponse: httpResponse, message: restJSONError.errorMessage, requestID: requestID, typeName: restJSONError.errorType)", - unknownServiceErrorSymbol - ) - } - } - } - } - } - } + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.AWSJSON.AWSJSONError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt index c235bd1c937..4cabfcae29b 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt @@ -7,25 +7,24 @@ package software.amazon.smithy.aws.swift.codegen.awsjson import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware +import software.amazon.smithy.aws.swift.codegen.restxml.AWSRestXMLHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.codingKeys.DefaultCodingKeysCustomizable -import software.amazon.smithy.swift.codegen.integration.codingKeys.DefaultCodingKeysGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { - override val codingKeysGenerator = DefaultCodingKeysGenerator(DefaultCodingKeysCustomizable()) override val defaultContentType = "application/x-amz-json-1.0" override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS override val protocol: ShapeId = AwsJson1_0Trait.ID @@ -33,8 +32,9 @@ open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override val httpResponseGenerator = HttpResponseGenerator( unknownServiceErrorSymbol, defaultTimestampFormat, - HttpResponseBindingOutputGenerator(), - AWSJsonHttpResponseBindingErrorGenerator() + XMLHttpResponseBindingOutputGenerator(), + AWSJsonHttpResponseBindingErrorGenerator(), + XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat) ) override val shouldRenderEncodableConformance: Boolean = true override val shouldRenderDecodableBodyStructForInputShapes: Boolean = true @@ -62,7 +62,7 @@ open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -70,7 +70,7 @@ open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) for (streamingShape in streamingShapes) { messageMarshallableGenerator.render(streamingShape) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt index 4208d307952..1a120783183 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt @@ -7,8 +7,8 @@ package software.amazon.smithy.aws.swift.codegen.awsjson import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait import software.amazon.smithy.model.shapes.OperationShape @@ -16,16 +16,14 @@ import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.codingKeys.DefaultCodingKeysCustomizable -import software.amazon.smithy.swift.codegen.integration.codingKeys.DefaultCodingKeysGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { - override val codingKeysGenerator = DefaultCodingKeysGenerator(DefaultCodingKeysCustomizable()) override val defaultContentType = "application/x-amz-json-1.1" override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS override val protocol: ShapeId = AwsJson1_1Trait.ID @@ -33,8 +31,9 @@ class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override val httpResponseGenerator = HttpResponseGenerator( unknownServiceErrorSymbol, defaultTimestampFormat, - HttpResponseBindingOutputGenerator(), - AWSJsonHttpResponseBindingErrorGenerator() + XMLHttpResponseBindingOutputGenerator(), + AWSJsonHttpResponseBindingErrorGenerator(), + XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat), ) override val shouldRenderEncodableConformance: Boolean = true override val shouldRenderDecodableBodyStructForInputShapes: Boolean = true @@ -62,7 +61,7 @@ class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -70,7 +69,7 @@ class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) for (streamingShape in streamingShapes) { messageMarshallableGenerator.render(streamingShape) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt index d55568400e6..054c164ac86 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt @@ -6,7 +6,6 @@ package software.amazon.smithy.aws.swift.codegen.awsquery import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations -import software.amazon.smithy.aws.swift.codegen.AWSHttpRequestFormURLEncoder import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.protocoltests.traits.HttpRequestTestCase @@ -16,10 +15,7 @@ import software.amazon.smithy.swift.codegen.integration.ClientProperty class AWSHttpProtocolAwsQueryCustomizations : AWSHttpProtocolCustomizations() { override fun getClientProperties(): List { - val properties = mutableListOf() - val requestEncoderOptions = mutableMapOf() - properties.add(AWSHttpRequestFormURLEncoder(requestEncoderOptions)) - return properties + return listOf() } override fun customRenderBodyComparison(test: HttpRequestTestCase): ((SwiftWriter, HttpRequestTestCase, Symbol, Shape, String, String) -> Unit)? { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt index 3dc70720818..bfc1ffd42a7 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt @@ -8,32 +8,29 @@ package software.amazon.smithy.aws.swift.codegen.awsquery import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver +import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseTraitPayloadFactory import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSQueryHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.restxml.AWSXMLHttpResponseBindingErrorInitGeneratorFactory import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait -import software.amazon.smithy.swift.codegen.SwiftTypes import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.codingKeys.CodingKeysCustomizationXmlName -import software.amazon.smithy.swift.codegen.integration.codingKeys.DefaultCodingKeysGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.formurl.StructEncodeFormURLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { - override val codingKeysGenerator = DefaultCodingKeysGenerator(CodingKeysCustomizationXmlName()) override val defaultContentType = "application/x-www-form-urlencoded" override val defaultTimestampFormat = TimestampFormatTrait.Format.DATE_TIME override val protocol: ShapeId = AwsQueryTrait.ID @@ -43,22 +40,22 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat, XMLHttpResponseBindingOutputGenerator(), AWSQueryHttpResponseBindingErrorGenerator(), - AWSXMLHttpResponseBindingErrorInitGeneratorFactory(), + XMLHttpResponseBindingErrorInitGenerator( + defaultTimestampFormat, + AWSEc2QueryHttpResponseTraitPayloadFactory() + ) ) override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, defaultContentType: String): HttpBindingResolver = FormURLHttpBindingResolver(ctx, defaultContentType) override val shouldRenderDecodableBodyStructForInputShapes = false - override val shouldRenderCodingKeysForEncodable = true override val shouldRenderEncodableConformance = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_awsQuery", "SDKAppendsGzipAndIgnoresHttpProvidedEncoding_awsQuery", ) override val tagsToIgnore = setOf("defaults") - override val codableProtocol = SwiftTypes.Protocols.Encodable - override val decodableProtocol = null override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) @@ -77,14 +74,11 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String?, ) { - StructEncodeFormURLGenerator( + StructEncodeXMLGenerator( ctx, - AwsQueryFormURLEncodeCustomizations(), shapeContainingMembers, - shapeMetadata, members, writer, - defaultTimestampFormat ).render() } @@ -117,12 +111,4 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { operationMiddleware.removeMiddleware(operation, MiddlewareStep.SERIALIZESTEP, "ContentTypeMiddleware") operationMiddleware.appendMiddleware(operation, ContentTypeMiddleware(ctx.model, ctx.symbolProvider, resolver.determineRequestContentType(operation), true)) } - - override fun renderBodyStructAndDecodableExtension( - ctx: ProtocolGenerator.GenerationContext, - shape: Shape, - metadata: Map - ) { - // No operation - } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt index 3e83cc8d4ed..4f997276f84 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt @@ -6,116 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SmithyXMLTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftTypes -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable -import software.amazon.smithy.swift.codegen.model.toUpperCamelCase -import software.amazon.smithy.swift.codegen.utils.errorShapeName +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -class AWSQueryHttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable { - override fun renderServiceError(ctx: ProtocolGenerator.GenerationContext) { - val serviceShape = ctx.service - val serviceName = ctx.service.id.name - val rootNamespace = ctx.settings.moduleName - val fileName = "./$rootNamespace/models/$serviceName+ServiceErrorHelperMethod.swift" +class AWSQueryHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - ctx.delegator.useFileWriter(fileName) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - openBlock("extension ${ctx.symbolProvider.toSymbol(ctx.service).name}Types {", "}") { - openBlock( - "static func makeServiceError(_ httpResponse: \$N, _ decoder: \$D, _ error: \$N) async throws -> \$N? {", - "}", - ClientRuntimeTypes.Http.HttpResponse, - ClientRuntimeTypes.Serde.ResponseDecoder, - AWSClientRuntimeTypes.EC2Query.Ec2QueryError, - SwiftTypes.Error - ) { - openBlock("switch error.errorCode {", "}") { - val serviceErrorShapes = - serviceShape.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - serviceErrorShapes.forEach { errorShape -> - val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: error.message, requestID: error.requestId)", - errorShapeName, - errorShapeType - ) - } - write("default: return nil") - } - } - } - } - } - } - - override fun renderOperationError(ctx: ProtocolGenerator.GenerationContext, op: OperationShape, unknownServiceErrorSymbol: Symbol) { - val operationErrorName = "${op.toUpperCamelCase()}OutputError" - val rootNamespace = ctx.settings.moduleName - val httpBindingSymbol = Symbol.builder() - .definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseErrorBinding.swift") - .name(operationErrorName) - .build() - - ctx.delegator.useShapeWriter(httpBindingSymbol) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock("enum \$L {", "}", operationErrorName) { - writer.addImport(SwiftDependency.SMITHY_XML.target) - writer.write("") - openBlock( - "static var httpBinding: \$N<\$N> {", "}", - ClientRuntimeTypes.Http.HTTPResponseErrorBinding, - SmithyXMLTypes.Reader, - ) { - writer.openBlock("{ httpResponse, responseDocumentClosure in", "}") { - if (ctx.service.errors.isNotEmpty()) { - write("let serviceError = try await ${ctx.symbolProvider.toSymbol(ctx.service).name}Types.makeServiceError(httpResponse, decoder, ec2QueryError)") - write("if let error = serviceError { return error }") - } - writer.write("let responseReader = try await responseDocumentClosure(httpResponse)") - writer.write("let reader = responseReader[\"Error\"]") - writer.write("let requestID: String? = try responseReader[\"RequestId\"].readIfPresent()") - writer.write("let code: String? = try reader[\"Code\"].readIfPresent()") - writer.write("let message: String? = try reader[\"Message\"].readIfPresent()") - openBlock("switch code {", "}") { - val errorShapes = op.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - errorShapes.forEach { errorShape -> - var errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - var errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L.responseErrorBinding(httpResponse: httpResponse, reader: reader, message: message, requestID: requestID)", - errorShapeName, - errorShapeType - ) - } - write( - "default: return try await \$N.makeError(httpResponse: httpResponse, message: message, requestID: requestID, typeName: code)", - unknownServiceErrorSymbol - ) - } - } - } - } - } - } - } + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.Ec2QueryError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt index 12d8aef0c55..734782026b6 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt @@ -1,6 +1,5 @@ package software.amazon.smithy.aws.swift.codegen.customization.route53 -import software.amazon.smithy.aws.swift.codegen.restxml.AWSRestXMLHttpResponseBindingErrorGenerator import software.amazon.smithy.model.Model import software.amazon.smithy.model.shapes.ServiceShape import software.amazon.smithy.swift.codegen.SmithyXMLTypes @@ -13,6 +12,7 @@ import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SectionWriter import software.amazon.smithy.swift.codegen.integration.SectionWriterBinding import software.amazon.smithy.swift.codegen.integration.SwiftIntegration +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator import software.amazon.smithy.swift.codegen.model.expectShape class Route53InvalidBatchErrorIntegration : SwiftIntegration { @@ -22,7 +22,7 @@ class Route53InvalidBatchErrorIntegration : SwiftIntegration { override val sectionWriters: List get() = listOf( - SectionWriterBinding(AWSRestXMLHttpResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBindingErrorGenerator) + SectionWriterBinding(HTTPResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBindingErrorGenerator) ) private val httpResponseBindingErrorGenerator = SectionWriter { writer, previousCode -> diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt index 6f11487bf65..5f35beed020 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt @@ -1,7 +1,6 @@ package software.amazon.smithy.aws.swift.codegen.customization.s3 import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.restxml.AWSRestXMLHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.traits.protocols.RestXmlTrait import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.Model @@ -17,6 +16,7 @@ import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SectionWriter import software.amazon.smithy.swift.codegen.integration.SectionWriterBinding import software.amazon.smithy.swift.codegen.integration.SwiftIntegration +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.model.expectShape import software.amazon.smithy.swift.codegen.model.getTrait @@ -34,7 +34,7 @@ class S3ErrorIntegration : SwiftIntegration { SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInit, s3MembersParams), SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInitMemberAssignment, s3MembersAssignment), SectionWriterBinding(StructureGenerator.AdditionalErrorMembers, s3Members), - SectionWriterBinding(AWSRestXMLHttpResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBinding) + SectionWriterBinding(HTTPResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBinding) ) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt index eaa013764c9..ca45f6cd074 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt @@ -6,7 +6,6 @@ package software.amazon.smithy.aws.swift.codegen.ec2query import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations -import software.amazon.smithy.aws.swift.codegen.AWSHttpRequestFormURLEncoder import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.protocoltests.traits.HttpRequestTestCase @@ -18,7 +17,7 @@ class AWSHttpProtocolEc2QueryCustomizations : AWSHttpProtocolCustomizations() { override fun getClientProperties(): List { val properties = mutableListOf() val requestEncoderOptions = mutableMapOf() - properties.add(AWSHttpRequestFormURLEncoder(requestEncoderOptions)) +// properties.add(AWSHttpRequestFormURLEncoder(requestEncoderOptions)) return properties } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index 80fff35c1fa..f006ed1f0ff 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -9,7 +9,7 @@ import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseBindingErrorGenerator -import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory +import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseTraitPayloadFactory import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait import software.amazon.smithy.model.shapes.MemberShape @@ -22,16 +22,17 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.integration.serde.formurl.StructEncodeFormURLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { - override val codingKeysGenerator = null override val defaultContentType = "application/x-www-form-urlencoded" override val defaultTimestampFormat = TimestampFormatTrait.Format.DATE_TIME override val protocol: ShapeId = Ec2QueryTrait.ID @@ -41,22 +42,22 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat, XMLHttpResponseBindingOutputGenerator(), AWSEc2QueryHttpResponseBindingErrorGenerator(), - AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory(), + XMLHttpResponseBindingErrorInitGenerator( + defaultTimestampFormat, + AWSEc2QueryHttpResponseTraitPayloadFactory() + ) ) override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, contentType: String): HttpBindingResolver = FormURLHttpBindingResolver(ctx, contentType) override val shouldRenderDecodableBodyStructForInputShapes = false - override val shouldRenderCodingKeysForEncodable = false override val shouldRenderEncodableConformance = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_ec2Query", "SDKAppendsGzipAndIgnoresHttpProvidedEncoding_ec2Query", ) override val tagsToIgnore = setOf("defaults") - override val codableProtocol = SwiftTypes.Protocols.Encodable - override val decodableProtocol = null override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) @@ -75,9 +76,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String?, ) { - val customizations = Ec2QueryFormURLEncodeCustomizations() - val encoder = StructEncodeFormURLGenerator(ctx, customizations, shapeContainingMembers, shapeMetadata, members, writer, defaultTimestampFormat) - encoder.render() + StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, writer).render() } override fun renderStructDecode( @@ -89,8 +88,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String, ) { - val decoder = StructDecodeXMLGenerator(ctx, shapeContainingMembers, members, mapOf(), writer) - decoder.render() + StructDecodeXMLGenerator(ctx, shapeContainingMembers, members, mapOf(), writer).render() } override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { @@ -104,12 +102,4 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { operationMiddleware.removeMiddleware(operation, MiddlewareStep.SERIALIZESTEP, "ContentTypeMiddleware") operationMiddleware.appendMiddleware(operation, ContentTypeMiddleware(ctx.model, ctx.symbolProvider, resolver.determineRequestContentType(operation), true)) } - - override fun renderBodyStructAndDecodableExtension( - ctx: ProtocolGenerator.GenerationContext, - shape: Shape, - metadata: Map - ) { - // No operation - } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt index 96aec868613..b5f0ebc6af5 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt @@ -6,116 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SmithyXMLTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftTypes -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable -import software.amazon.smithy.swift.codegen.model.toUpperCamelCase -import software.amazon.smithy.swift.codegen.utils.errorShapeName +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -class AWSEc2QueryHttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable { - override fun renderServiceError(ctx: ProtocolGenerator.GenerationContext) { - val serviceShape = ctx.service - val serviceName = ctx.service.id.name - val rootNamespace = ctx.settings.moduleName - val fileName = "./$rootNamespace/models/$serviceName+ServiceErrorHelperMethod.swift" +class AWSEc2QueryHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - ctx.delegator.useFileWriter(fileName) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - openBlock("extension ${ctx.symbolProvider.toSymbol(ctx.service).name}Types {", "}") { - openBlock( - "static func makeServiceError(_ httpResponse: \$N, _ decoder: \$D, _ error: \$N) async throws -> \$N? {", - "}", - ClientRuntimeTypes.Http.HttpResponse, - ClientRuntimeTypes.Serde.ResponseDecoder, - AWSClientRuntimeTypes.EC2Query.Ec2QueryError, - SwiftTypes.Error - ) { - openBlock("switch error.errorCode {", "}") { - val serviceErrorShapes = - serviceShape.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - serviceErrorShapes.forEach { errorShape -> - val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: error.message, requestID: error.requestId)", - errorShapeName, - errorShapeType - ) - } - write("default: return nil") - } - } - } - } - } - } - - override fun renderOperationError(ctx: ProtocolGenerator.GenerationContext, op: OperationShape, unknownServiceErrorSymbol: Symbol) { - val operationErrorName = "${op.toUpperCamelCase()}OutputError" - val rootNamespace = ctx.settings.moduleName - val httpBindingSymbol = Symbol.builder() - .definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseErrorBinding.swift") - .name(operationErrorName) - .build() - - ctx.delegator.useShapeWriter(httpBindingSymbol) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock("enum \$L {", "}", operationErrorName) { - writer.addImport(SwiftDependency.SMITHY_XML.target) - writer.write("") - openBlock( - "static var httpBinding: \$N<\$N> {", "}", - ClientRuntimeTypes.Http.HTTPResponseErrorBinding, - SmithyXMLTypes.Reader, - ) { - writer.openBlock("{ httpResponse, responseDocumentClosure in", "}") { - if (ctx.service.errors.isNotEmpty()) { - write("let serviceError = try await ${ctx.symbolProvider.toSymbol(ctx.service).name}Types.makeServiceError(httpResponse, decoder, ec2QueryError)") - write("if let error = serviceError { return error }") - } - writer.write("let responseReader = try await responseDocumentClosure(httpResponse)") - writer.write("let reader = responseReader[\"Errors\"][\"Error\"]") - writer.write("let requestID: String? = try responseReader[\"RequestId\"].readIfPresent()") - writer.write("let errorCode: String? = try reader[\"Code\"].readIfPresent()") - writer.write("let message: String? = try reader[\"Message\"].readIfPresent()") - openBlock("switch errorCode {", "}") { - val errorShapes = op.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - errorShapes.forEach { errorShape -> - var errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - var errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L.responseErrorBinding(httpResponse: httpResponse, reader: reader, message: message, requestID: requestID)", - errorShapeName, - errorShapeType - ) - } - write( - "default: return try await \$N.makeError(httpResponse: httpResponse, message: message, requestID: requestID, typeName: errorCode)", - unknownServiceErrorSymbol - ) - } - } - } - } - } - } - } + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.Ec2QueryError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt index aa756abd370..0aa3c014f1b 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt @@ -12,30 +12,12 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorInitGeneratorFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayloadFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithoutHttpPayloadFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.XMLHttpResponseTraitPayload -class AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory : HttpResponseBindingErrorInitGeneratorFactory { - override fun construct( - ctx: ProtocolGenerator.GenerationContext, - structureShape: StructureShape, - httpBindingResolver: HttpBindingResolver, - defaultTimestampFormat: TimestampFormatTrait.Format, - ): HttpResponseBindingRenderable { - return XMLHttpResponseBindingErrorInitGenerator( - ctx, - structureShape, - httpBindingResolver, - defaultTimestampFormat, - AWSEc2QueryHttpResponseTraitPayloadFactory() - ) - } -} - class AWSEc2QueryHttpResponseTraitPayloadFactory : HttpResponseTraitPayloadFactory { override fun construct( ctx: ProtocolGenerator.GenerationContext, diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt index b1cf8eabd9a..2471e359e60 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt @@ -1,211 +1,211 @@ -package software.amazon.smithy.aws.swift.codegen.message - -import software.amazon.smithy.codegen.core.CodegenException -import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.MemberShape -import software.amazon.smithy.model.shapes.ShapeType -import software.amazon.smithy.model.shapes.UnionShape -import software.amazon.smithy.model.traits.EventHeaderTrait -import software.amazon.smithy.model.traits.EventPayloadTrait -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.serde.readwrite.DocumentWritingClosureUtils -import software.amazon.smithy.swift.codegen.integration.serde.readwrite.WritingClosureUtils -import software.amazon.smithy.swift.codegen.model.eventStreamEvents -import software.amazon.smithy.swift.codegen.model.hasTrait - -class MessageMarshallableGenerator( - private val ctx: ProtocolGenerator.GenerationContext, - private val payloadContentType: String -) { - internal fun render(streamShape: UnionShape) { - val symbol: Symbol = ctx.symbolProvider.toSymbol(streamShape) - val rootNamespace = ctx.settings.moduleName - val streamMember = Symbol.builder() - .definitionFile("./$rootNamespace/models/${symbol.name}+MessageMarshallable.swift") - .name(symbol.name) - .build() - ctx.delegator.useShapeWriter(streamMember) { writer -> - writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) - writer.openBlock( - "extension ${symbol.fullName}: \$N {", "}", - ClientRuntimeTypes.Serde.MessageMarshallable, - ) { - writer.openBlock( - "public func marshall(encoder: \$N) throws -> \$N {", "}", - ClientRuntimeTypes.Serde.RequestEncoder, - ClientRuntimeTypes.EventStream.Message - ) { - writer.write( - "var headers: [\$N] = [.init(name: \":message-type\", value: .string(\"event\"))]", - ClientRuntimeTypes.EventStream.Header - ) - writer.write("var payload: \$D", ClientRuntimeTypes.Core.Data) - writer.write("switch self {") - streamShape.eventStreamEvents(ctx.model).forEach { member -> - val memberName = ctx.symbolProvider.toMemberName(member) - writer.write("case .\$L(let value):", memberName) - writer.indent() - writer.addStringHeader(":event-type", member.memberName) - val variant = ctx.model.expectShape(member.target) - val eventHeaderBindings = variant.members().filter { - it.hasTrait() - } - val eventPayloadBinding = variant.members().firstOrNull { - it.hasTrait() - } - val unbound = variant.members().filterNot { - it.hasTrait() || it.hasTrait() - } - - eventHeaderBindings.forEach { - renderSerializeEventHeader(ctx, it, writer) - } - - when { - eventPayloadBinding != null -> renderSerializeEventPayload(ctx, eventPayloadBinding, writer) - unbound.isNotEmpty() -> { - writer.addStringHeader(":content-type", payloadContentType) - // get a payload serializer for the given members of the variant - val documentWritingClosure = DocumentWritingClosureUtils(ctx, writer).closure(variant) - val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(variant) - writer.write("payload = try \$L(value, \$L)", documentWritingClosure, valueWritingClosure) - } - } - writer.dedent() - } - writer.write("case .sdkUnknown(_):") - writer.indent() - writer.write( - "throw \$N(\"cannot serialize the unknown event type!\")", - ClientRuntimeTypes.Core.UnknownClientError - ) - writer.dedent() - writer.write("}") - writer.write( - "return \$N(headers: headers, payload: payload ?? .init())", - ClientRuntimeTypes.EventStream.Message - ) - } - } - } - } - - /** - * extension TestServiceClientTypes.TestStream: ClientRuntime.MessageMarshallable { - * public func marshall(encoder: ClientRuntime.RequestEncoder) throws -> ClientRuntime.EventStream.Message { - * fatalError("not implemented") - * } - * } - * - */ - internal fun renderNotImplemented(streamShape: UnionShape) { - val symbol: Symbol = ctx.symbolProvider.toSymbol(streamShape) - val rootNamespace = ctx.settings.moduleName - val streamMember = Symbol.builder() - .definitionFile("./$rootNamespace/models/${symbol.name}+MessageMarshallable.swift") - .name(symbol.name) - .build() - ctx.delegator.useShapeWriter(streamMember) { writer -> - writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) - writer.openBlock( - "extension ${symbol.fullName}: \$N {", "}", - ClientRuntimeTypes.Serde.MessageMarshallable, - ) { - writer.openBlock( - "public func marshall(encoder: \$N) throws -> \$N {", "}", - ClientRuntimeTypes.Serde.RequestEncoder, - ClientRuntimeTypes.EventStream.Message - ) { - writer.write("#error(\"Event streams not implemented for this protocol\")") - } - } - } - } - - /** - * headers.append(.init(name: ":event-type", value: .string("MessageWithBlob"))) - */ - private fun SwiftWriter.addStringHeader(name: String, value: String) { - write("headers.append(.init(name: \$S, value: .string(\$S)))", name, value) - } - - private fun renderSerializeEventPayload(ctx: ProtocolGenerator.GenerationContext, member: MemberShape, writer: SwiftWriter) { - val target = ctx.model.expectShape(member.target) - val memberName = ctx.symbolProvider.toMemberName(member) - when (target.type) { - ShapeType.BLOB -> { - writer.addStringHeader(":content-type", "application/octet-stream") - writer.write("payload = value.\$L", memberName) - } - ShapeType.STRING -> { - writer.addStringHeader(":content-type", "text/plain") - writer.write("payload = value.\$L?.data(using: .utf8)", memberName) - } - ShapeType.STRUCTURE, ShapeType.UNION -> { - writer.addStringHeader(":content-type", payloadContentType) - writer.write("payload = try encoder.encode(value)") - } - else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") - } - } - -/** - * - * if let headerValue = value.blob { - * headers.append(.init(name: "blob", value: .byteArray(headerValue))) - * } - * if let headerValue = value.boolean { - * headers.append(.init(name: "boolean", value: .bool(headerValue))) - * } - * if let headerValue = value.byte { - * headers.append(.init(name: "byte", value: .byte(headerValue))) - * } - * if let headerValue = value.int { - * headers.append(.init(name: "int", value: .int32(Int32(headerValue)))) - * } - * if let headerValue = value.long { - * headers.append(.init(name: "long", value: .int64(Int64(headerValue)))) - * } - * if let headerValue = value.short { - * headers.append(.init(name: "short", value: .int16(headerValue))) - * } - * if let headerValue = value.string { - * headers.append(.init(name: "string", value: .string(headerValue))) - * } - * if let headerValue = value.timestamp { - * headers.append(.init(name: "timestamp", value: .timestamp(headerValue))) - * } -*/ - private fun renderSerializeEventHeader(ctx: ProtocolGenerator.GenerationContext, member: MemberShape, writer: SwiftWriter) { - val target = ctx.model.expectShape(member.target) - val headerValue = when (target.type) { - ShapeType.BOOLEAN -> "bool" - ShapeType.BYTE -> "byte" - ShapeType.SHORT -> "int16" - ShapeType.INTEGER -> "int32" - ShapeType.LONG -> "int64" - ShapeType.BLOB -> "byteArray" - ShapeType.STRING -> "string" - ShapeType.TIMESTAMP -> "timestamp" - else -> throw CodegenException("unsupported shape type `${target.type}` for eventHeader member `$member`; target: $target") - } - - val memberName = ctx.symbolProvider.toMemberName(member) - writer.openBlock("if let headerValue = value.\$L {", "}", memberName) { - when (target.type) { - ShapeType.INTEGER -> { - writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(Int32(headerValue))))", headerValue) - } - ShapeType.LONG -> { - writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(Int64(headerValue))))", headerValue) - } - else -> { - writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(headerValue)))", headerValue) - } - } - } - } -} +//package software.amazon.smithy.aws.swift.codegen.message +// +//import software.amazon.smithy.codegen.core.CodegenException +//import software.amazon.smithy.codegen.core.Symbol +//import software.amazon.smithy.model.shapes.MemberShape +//import software.amazon.smithy.model.shapes.ShapeType +//import software.amazon.smithy.model.shapes.UnionShape +//import software.amazon.smithy.model.traits.EventHeaderTrait +//import software.amazon.smithy.model.traits.EventPayloadTrait +//import software.amazon.smithy.swift.codegen.ClientRuntimeTypes +//import software.amazon.smithy.swift.codegen.SwiftDependency +//import software.amazon.smithy.swift.codegen.SwiftWriter +//import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator +//import software.amazon.smithy.swift.codegen.integration.serde.readwrite.DocumentWritingClosureUtils +//import software.amazon.smithy.swift.codegen.integration.serde.readwrite.WritingClosureUtils +//import software.amazon.smithy.swift.codegen.model.eventStreamEvents +//import software.amazon.smithy.swift.codegen.model.hasTrait +// +//class MessageMarshallableGenerator( +// private val ctx: ProtocolGenerator.GenerationContext, +// private val payloadContentType: String +//) { +// internal fun render(streamShape: UnionShape) { +// val symbol: Symbol = ctx.symbolProvider.toSymbol(streamShape) +// val rootNamespace = ctx.settings.moduleName +// val streamMember = Symbol.builder() +// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageMarshallable.swift") +// .name(symbol.name) +// .build() +// ctx.delegator.useShapeWriter(streamMember) { writer -> +// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) +// writer.openBlock( +// "extension ${symbol.fullName}: \$N {", "}", +// ClientRuntimeTypes.Serde.MessageMarshallable, +// ) { +// writer.openBlock( +// "public func marshall(encoder: \$N) throws -> \$N {", "}", +// ClientRuntimeTypes.Serde.RequestEncoder, +// ClientRuntimeTypes.EventStream.Message +// ) { +// writer.write( +// "var headers: [\$N] = [.init(name: \":message-type\", value: .string(\"event\"))]", +// ClientRuntimeTypes.EventStream.Header +// ) +// writer.write("var payload: \$D", ClientRuntimeTypes.Core.Data) +// writer.write("switch self {") +// streamShape.eventStreamEvents(ctx.model).forEach { member -> +// val memberName = ctx.symbolProvider.toMemberName(member) +// writer.write("case .\$L(let value):", memberName) +// writer.indent() +// writer.addStringHeader(":event-type", member.memberName) +// val variant = ctx.model.expectShape(member.target) +// val eventHeaderBindings = variant.members().filter { +// it.hasTrait() +// } +// val eventPayloadBinding = variant.members().firstOrNull { +// it.hasTrait() +// } +// val unbound = variant.members().filterNot { +// it.hasTrait() || it.hasTrait() +// } +// +// eventHeaderBindings.forEach { +// renderSerializeEventHeader(ctx, it, writer) +// } +// +// when { +// eventPayloadBinding != null -> renderSerializeEventPayload(ctx, eventPayloadBinding, writer) +// unbound.isNotEmpty() -> { +// writer.addStringHeader(":content-type", payloadContentType) +// // get a payload serializer for the given members of the variant +// val documentWritingClosure = DocumentWritingClosureUtils(ctx, writer).closure(variant) +// val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(variant) +// writer.write("payload = try \$L(value, \$L)", documentWritingClosure, valueWritingClosure) +// } +// } +// writer.dedent() +// } +// writer.write("case .sdkUnknown(_):") +// writer.indent() +// writer.write( +// "throw \$N(\"cannot serialize the unknown event type!\")", +// ClientRuntimeTypes.Core.UnknownClientError +// ) +// writer.dedent() +// writer.write("}") +// writer.write( +// "return \$N(headers: headers, payload: payload ?? .init())", +// ClientRuntimeTypes.EventStream.Message +// ) +// } +// } +// } +// } +// +// /** +// * extension TestServiceClientTypes.TestStream: ClientRuntime.MessageMarshallable { +// * public func marshall(encoder: ClientRuntime.RequestEncoder) throws -> ClientRuntime.EventStream.Message { +// * fatalError("not implemented") +// * } +// * } +// * +// */ +// internal fun renderNotImplemented(streamShape: UnionShape) { +// val symbol: Symbol = ctx.symbolProvider.toSymbol(streamShape) +// val rootNamespace = ctx.settings.moduleName +// val streamMember = Symbol.builder() +// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageMarshallable.swift") +// .name(symbol.name) +// .build() +// ctx.delegator.useShapeWriter(streamMember) { writer -> +// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) +// writer.openBlock( +// "extension ${symbol.fullName}: \$N {", "}", +// ClientRuntimeTypes.Serde.MessageMarshallable, +// ) { +// writer.openBlock( +// "public func marshall(encoder: \$N) throws -> \$N {", "}", +// ClientRuntimeTypes.Serde.RequestEncoder, +// ClientRuntimeTypes.EventStream.Message +// ) { +// writer.write("#error(\"Event streams not implemented for this protocol\")") +// } +// } +// } +// } +// +// /** +// * headers.append(.init(name: ":event-type", value: .string("MessageWithBlob"))) +// */ +// private fun SwiftWriter.addStringHeader(name: String, value: String) { +// write("headers.append(.init(name: \$S, value: .string(\$S)))", name, value) +// } +// +// private fun renderSerializeEventPayload(ctx: ProtocolGenerator.GenerationContext, member: MemberShape, writer: SwiftWriter) { +// val target = ctx.model.expectShape(member.target) +// val memberName = ctx.symbolProvider.toMemberName(member) +// when (target.type) { +// ShapeType.BLOB -> { +// writer.addStringHeader(":content-type", "application/octet-stream") +// writer.write("payload = value.\$L", memberName) +// } +// ShapeType.STRING -> { +// writer.addStringHeader(":content-type", "text/plain") +// writer.write("payload = value.\$L?.data(using: .utf8)", memberName) +// } +// ShapeType.STRUCTURE, ShapeType.UNION -> { +// writer.addStringHeader(":content-type", payloadContentType) +// writer.write("payload = try encoder.encode(value)") +// } +// else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") +// } +// } +// +///** +// * +// * if let headerValue = value.blob { +// * headers.append(.init(name: "blob", value: .byteArray(headerValue))) +// * } +// * if let headerValue = value.boolean { +// * headers.append(.init(name: "boolean", value: .bool(headerValue))) +// * } +// * if let headerValue = value.byte { +// * headers.append(.init(name: "byte", value: .byte(headerValue))) +// * } +// * if let headerValue = value.int { +// * headers.append(.init(name: "int", value: .int32(Int32(headerValue)))) +// * } +// * if let headerValue = value.long { +// * headers.append(.init(name: "long", value: .int64(Int64(headerValue)))) +// * } +// * if let headerValue = value.short { +// * headers.append(.init(name: "short", value: .int16(headerValue))) +// * } +// * if let headerValue = value.string { +// * headers.append(.init(name: "string", value: .string(headerValue))) +// * } +// * if let headerValue = value.timestamp { +// * headers.append(.init(name: "timestamp", value: .timestamp(headerValue))) +// * } +//*/ +// private fun renderSerializeEventHeader(ctx: ProtocolGenerator.GenerationContext, member: MemberShape, writer: SwiftWriter) { +// val target = ctx.model.expectShape(member.target) +// val headerValue = when (target.type) { +// ShapeType.BOOLEAN -> "bool" +// ShapeType.BYTE -> "byte" +// ShapeType.SHORT -> "int16" +// ShapeType.INTEGER -> "int32" +// ShapeType.LONG -> "int64" +// ShapeType.BLOB -> "byteArray" +// ShapeType.STRING -> "string" +// ShapeType.TIMESTAMP -> "timestamp" +// else -> throw CodegenException("unsupported shape type `${target.type}` for eventHeader member `$member`; target: $target") +// } +// +// val memberName = ctx.symbolProvider.toMemberName(member) +// writer.openBlock("if let headerValue = value.\$L {", "}", memberName) { +// when (target.type) { +// ShapeType.INTEGER -> { +// writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(Int32(headerValue))))", headerValue) +// } +// ShapeType.LONG -> { +// writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(Int64(headerValue))))", headerValue) +// } +// else -> { +// writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(headerValue)))", headerValue) +// } +// } +// } +// } +//} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt index ebea2a3bb95..c635ede2106 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt @@ -1,231 +1,231 @@ -package software.amazon.smithy.aws.swift.codegen.message - -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency -import software.amazon.smithy.codegen.core.CodegenException -import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.MemberShape -import software.amazon.smithy.model.shapes.ShapeType -import software.amazon.smithy.model.shapes.UnionShape -import software.amazon.smithy.model.traits.EventHeaderTrait -import software.amazon.smithy.model.traits.EventPayloadTrait -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftTypes -import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.model.eventStreamErrors -import software.amazon.smithy.swift.codegen.model.eventStreamEvents -import software.amazon.smithy.swift.codegen.model.expectShape -import software.amazon.smithy.swift.codegen.model.hasTrait - -class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContext) { - fun render( - streamingMember: MemberShape - ) { - val symbol: Symbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(streamingMember.target)) - val rootNamespace = ctx.settings.moduleName - val streamMember = Symbol.builder() - .definitionFile("./$rootNamespace/models/${symbol.name}+MessageUnmarshallable.swift") - .name(symbol.name) - .build() - - val streamShape = ctx.model.expectShape(streamingMember.target) - val service = ctx.settings.getService(ctx.model) - val serviceSymbol = ctx.symbolProvider.toSymbol(service) - val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) - - ctx.delegator.useShapeWriter(streamMember) { writer -> - - writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) - writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - writer.openBlock( - "extension ${streamSymbol.fullName}: \$N {", "}", - ClientRuntimeTypes.Serde.MessageUnmarshallable - ) { - writer.openBlock( - "public init(message: \$N, decoder: \$N) throws {", "}", - ClientRuntimeTypes.EventStream.Message, - ClientRuntimeTypes.Serde.ResponseDecoder - ) { - writer.write("switch try message.type() {") - writer.write("case .event(let params):") - writer.indent { - writer.write("switch params.eventType {") - streamShape.eventStreamEvents(ctx.model).forEach { member -> - writer.write("case \"${member.memberName}\":") - writer.indent { - renderDeserializeEventVariant(ctx, streamSymbol, member, writer) - } - } - writer.write("default:") - writer.indent { - writer.write("self = .sdkUnknown(\"error processing event stream, unrecognized event: \\(params.eventType)\")") - } - writer.write("}") - } - writer.write("case .exception(let params):") - writer.indent { - writer.write( - "let makeError: (\$N, \$N) throws -> \$N = { message, params in", - ClientRuntimeTypes.EventStream.Message, - ClientRuntimeTypes.EventStream.ExceptionParams, - SwiftTypes.Error - ) - writer.indent { - writer.write("switch params.exceptionType {") - streamShape.eventStreamErrors(ctx.model).forEach { member -> - writer.write("case \"${member.memberName}\":") - writer.indent { - val targetShape = ctx.model.expectShape(member.target) - val symbol = ctx.symbolProvider.toSymbol(targetShape) - writer.write("return try decoder.decode(responseBody: message.payload) as \$N", symbol) - } - } - writer.write("default:") - writer.indent { - writer.write("let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok)") - writer.write( - "return \$L(httpResponse: httpResponse, message: \"error processing event stream, unrecognized ':exceptionType': \\(params.exceptionType); contentType: \\(params.contentType ?? \"nil\")\", requestID: nil, typeName: nil)", - AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError - ) - } - writer.write("}") - } - writer.write("}") - writer.write("let error = try makeError(message, params)") - writer.write("throw error") - } - writer.write("case .error(let params):") - writer.indent { - // this is a service exception still, just un-modeled - writer.write("let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok)") - writer.write( - "throw \$L(httpResponse: httpResponse, message: \"error processing event stream, unrecognized ':errorType': \\(params.errorCode); message: \\(params.message ?? \"nil\")\", requestID: nil, typeName: nil)", - AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError - ) - } - writer.write("case .unknown(messageType: let messageType):") - writer.indent { - // this is a client exception because we failed to parse it - writer.write( - "throw \$L(\"unrecognized event stream message ':message-type': \\(messageType)\")", - ClientRuntimeTypes.Core.UnknownClientError - ) - } - writer.write("}") - } - } - } - } - - fun renderNotImplemented( - streamingMember: MemberShape - ) { - val symbol: Symbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(streamingMember.target)) - val rootNamespace = ctx.settings.moduleName - val streamMember = Symbol.builder() - .definitionFile("./$rootNamespace/models/${symbol.name}+MessageUnmarshallable.swift") - .name(symbol.name) - .build() - - val streamShape = ctx.model.expectShape(streamingMember.target) - val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) - - ctx.delegator.useShapeWriter(streamMember) { writer -> - - writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) - writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - writer.openBlock( - "extension ${streamSymbol.fullName}: \$N {", "}", - ClientRuntimeTypes.Serde.MessageUnmarshallable - ) { - writer.write("") - writer.openBlock( - "public init(message: \$N, decoder: \$N) throws {", "}", - ClientRuntimeTypes.EventStream.Message, - ClientRuntimeTypes.Serde.ResponseDecoder - ) { - writer.write("fatalError(\"Not implemented\")") - } - } - } - } - - private fun renderDeserializeEventVariant(ctx: ProtocolGenerator.GenerationContext, unionSymbol: Symbol, member: MemberShape, writer: SwiftWriter) { - val variant = ctx.model.expectShape(member.target) - - val eventHeaderBindings = variant.members().filter { it.hasTrait() } - val eventPayloadBinding = variant.members().firstOrNull { it.hasTrait() } - val unbound = variant.members().filterNot { it.hasTrait() || it.hasTrait() } - val memberName = ctx.symbolProvider.toMemberName(member) - - if (eventHeaderBindings.isEmpty() && eventPayloadBinding == null) { - writer.write("self = .\$L(try decoder.decode(responseBody: message.payload))", memberName) - } else { - val variantSymbol = ctx.symbolProvider.toSymbol(variant) - writer.write("var event = \$N()", variantSymbol) - // render members bound to header - eventHeaderBindings.forEach { hdrBinding -> - val target = ctx.model.expectShape(hdrBinding.target) - - val conversionFn = when (target.type) { - ShapeType.BOOLEAN -> "bool" - ShapeType.BYTE -> "byte" - ShapeType.SHORT -> "int16" - ShapeType.INTEGER -> "int32" - ShapeType.LONG -> "int64" - ShapeType.BLOB -> "byteArray" - ShapeType.STRING -> "string" - ShapeType.TIMESTAMP -> "timestamp" - else -> throw CodegenException("unsupported eventHeader shape: member=$hdrBinding; targetShape=$target") - } - - writer.openBlock("if case let .\$L(value) = message.headers.value(name: \$S) {", "}", conversionFn, hdrBinding.memberName) { - val memberName = ctx.symbolProvider.toMemberName(hdrBinding) - when (target.type) { - ShapeType.INTEGER, ShapeType.LONG -> { - writer.write("event.\$L = Int(value)", memberName) - } - else -> { - writer.write("event.\$L = value", memberName) - } - } - } - } - - if (eventPayloadBinding != null) { - renderDeserializeExplicitEventPayloadMember(ctx, eventPayloadBinding, writer) - } else { - if (unbound.isNotEmpty()) { - // all remaining members are bound to payload (but not explicitly bound via @eventPayload) - // generate a payload deserializer specific to the unbound members (note this will be a deserializer - // for the overall event shape but only payload members will be considered for deserialization), - // and then assign each deserialized payload member to the current builder instance - unbound.forEach { - val memberName = ctx.symbolProvider.toMemberName(it) - writer.write("event.\$L = try decoder.decode(responseBody: message.payload)", memberName) - } - } - } - writer.write("self = .\$L(event)", memberName) - } - } - - private fun renderDeserializeExplicitEventPayloadMember( - ctx: ProtocolGenerator.GenerationContext, - member: MemberShape, - writer: SwiftWriter, - ) { - val target = ctx.model.expectShape(member.target) - val memberName = ctx.symbolProvider.toMemberName(member) - when (target.type) { - ShapeType.BLOB -> writer.write("event.\$L = message.payload", memberName) - ShapeType.STRING -> writer.write("event.\$L = String(data: message.payload, encoding: .utf8)", memberName) - ShapeType.STRUCTURE, ShapeType.UNION -> { - writer.write("event.\$L = .init(try decoder.decode(responseBody: message.payload))", memberName) - } - else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") - } - } -} +//package software.amazon.smithy.aws.swift.codegen.message +// +//import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes +//import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency +//import software.amazon.smithy.codegen.core.CodegenException +//import software.amazon.smithy.codegen.core.Symbol +//import software.amazon.smithy.model.shapes.MemberShape +//import software.amazon.smithy.model.shapes.ShapeType +//import software.amazon.smithy.model.shapes.UnionShape +//import software.amazon.smithy.model.traits.EventHeaderTrait +//import software.amazon.smithy.model.traits.EventPayloadTrait +//import software.amazon.smithy.swift.codegen.ClientRuntimeTypes +//import software.amazon.smithy.swift.codegen.SwiftDependency +//import software.amazon.smithy.swift.codegen.SwiftTypes +//import software.amazon.smithy.swift.codegen.SwiftWriter +//import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator +//import software.amazon.smithy.swift.codegen.model.eventStreamErrors +//import software.amazon.smithy.swift.codegen.model.eventStreamEvents +//import software.amazon.smithy.swift.codegen.model.expectShape +//import software.amazon.smithy.swift.codegen.model.hasTrait +// +//class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContext) { +// fun render( +// streamingMember: MemberShape +// ) { +// val symbol: Symbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(streamingMember.target)) +// val rootNamespace = ctx.settings.moduleName +// val streamMember = Symbol.builder() +// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageUnmarshallable.swift") +// .name(symbol.name) +// .build() +// +// val streamShape = ctx.model.expectShape(streamingMember.target) +// val service = ctx.settings.getService(ctx.model) +// val serviceSymbol = ctx.symbolProvider.toSymbol(service) +// val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) +// +// ctx.delegator.useShapeWriter(streamMember) { writer -> +// +// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) +// writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) +// writer.openBlock( +// "extension ${streamSymbol.fullName}: \$N {", "}", +// ClientRuntimeTypes.Serde.MessageUnmarshallable +// ) { +// writer.openBlock( +// "public init(message: \$N, decoder: \$N) throws {", "}", +// ClientRuntimeTypes.EventStream.Message, +// ClientRuntimeTypes.Serde.ResponseDecoder +// ) { +// writer.write("switch try message.type() {") +// writer.write("case .event(let params):") +// writer.indent { +// writer.write("switch params.eventType {") +// streamShape.eventStreamEvents(ctx.model).forEach { member -> +// writer.write("case \"${member.memberName}\":") +// writer.indent { +// renderDeserializeEventVariant(ctx, streamSymbol, member, writer) +// } +// } +// writer.write("default:") +// writer.indent { +// writer.write("self = .sdkUnknown(\"error processing event stream, unrecognized event: \\(params.eventType)\")") +// } +// writer.write("}") +// } +// writer.write("case .exception(let params):") +// writer.indent { +// writer.write( +// "let makeError: (\$N, \$N) throws -> \$N = { message, params in", +// ClientRuntimeTypes.EventStream.Message, +// ClientRuntimeTypes.EventStream.ExceptionParams, +// SwiftTypes.Error +// ) +// writer.indent { +// writer.write("switch params.exceptionType {") +// streamShape.eventStreamErrors(ctx.model).forEach { member -> +// writer.write("case \"${member.memberName}\":") +// writer.indent { +// val targetShape = ctx.model.expectShape(member.target) +// val symbol = ctx.symbolProvider.toSymbol(targetShape) +// writer.write("return try decoder.decode(responseBody: message.payload) as \$N", symbol) +// } +// } +// writer.write("default:") +// writer.indent { +// writer.write("let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok)") +// writer.write( +// "return \$L(httpResponse: httpResponse, message: \"error processing event stream, unrecognized ':exceptionType': \\(params.exceptionType); contentType: \\(params.contentType ?? \"nil\")\", requestID: nil, typeName: nil)", +// AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError +// ) +// } +// writer.write("}") +// } +// writer.write("}") +// writer.write("let error = try makeError(message, params)") +// writer.write("throw error") +// } +// writer.write("case .error(let params):") +// writer.indent { +// // this is a service exception still, just un-modeled +// writer.write("let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok)") +// writer.write( +// "throw \$L(httpResponse: httpResponse, message: \"error processing event stream, unrecognized ':errorType': \\(params.errorCode); message: \\(params.message ?? \"nil\")\", requestID: nil, typeName: nil)", +// AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError +// ) +// } +// writer.write("case .unknown(messageType: let messageType):") +// writer.indent { +// // this is a client exception because we failed to parse it +// writer.write( +// "throw \$L(\"unrecognized event stream message ':message-type': \\(messageType)\")", +// ClientRuntimeTypes.Core.UnknownClientError +// ) +// } +// writer.write("}") +// } +// } +// } +// } +// +// fun renderNotImplemented( +// streamingMember: MemberShape +// ) { +// val symbol: Symbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(streamingMember.target)) +// val rootNamespace = ctx.settings.moduleName +// val streamMember = Symbol.builder() +// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageUnmarshallable.swift") +// .name(symbol.name) +// .build() +// +// val streamShape = ctx.model.expectShape(streamingMember.target) +// val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) +// +// ctx.delegator.useShapeWriter(streamMember) { writer -> +// +// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) +// writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) +// writer.openBlock( +// "extension ${streamSymbol.fullName}: \$N {", "}", +// ClientRuntimeTypes.Serde.MessageUnmarshallable +// ) { +// writer.write("") +// writer.openBlock( +// "public init(message: \$N, decoder: \$N) throws {", "}", +// ClientRuntimeTypes.EventStream.Message, +// ClientRuntimeTypes.Serde.ResponseDecoder +// ) { +// writer.write("fatalError(\"Not implemented\")") +// } +// } +// } +// } +// +// private fun renderDeserializeEventVariant(ctx: ProtocolGenerator.GenerationContext, unionSymbol: Symbol, member: MemberShape, writer: SwiftWriter) { +// val variant = ctx.model.expectShape(member.target) +// +// val eventHeaderBindings = variant.members().filter { it.hasTrait() } +// val eventPayloadBinding = variant.members().firstOrNull { it.hasTrait() } +// val unbound = variant.members().filterNot { it.hasTrait() || it.hasTrait() } +// val memberName = ctx.symbolProvider.toMemberName(member) +// +// if (eventHeaderBindings.isEmpty() && eventPayloadBinding == null) { +// writer.write("self = .\$L(try decoder.decode(responseBody: message.payload))", memberName) +// } else { +// val variantSymbol = ctx.symbolProvider.toSymbol(variant) +// writer.write("var event = \$N()", variantSymbol) +// // render members bound to header +// eventHeaderBindings.forEach { hdrBinding -> +// val target = ctx.model.expectShape(hdrBinding.target) +// +// val conversionFn = when (target.type) { +// ShapeType.BOOLEAN -> "bool" +// ShapeType.BYTE -> "byte" +// ShapeType.SHORT -> "int16" +// ShapeType.INTEGER -> "int32" +// ShapeType.LONG -> "int64" +// ShapeType.BLOB -> "byteArray" +// ShapeType.STRING -> "string" +// ShapeType.TIMESTAMP -> "timestamp" +// else -> throw CodegenException("unsupported eventHeader shape: member=$hdrBinding; targetShape=$target") +// } +// +// writer.openBlock("if case let .\$L(value) = message.headers.value(name: \$S) {", "}", conversionFn, hdrBinding.memberName) { +// val memberName = ctx.symbolProvider.toMemberName(hdrBinding) +// when (target.type) { +// ShapeType.INTEGER, ShapeType.LONG -> { +// writer.write("event.\$L = Int(value)", memberName) +// } +// else -> { +// writer.write("event.\$L = value", memberName) +// } +// } +// } +// } +// +// if (eventPayloadBinding != null) { +// renderDeserializeExplicitEventPayloadMember(ctx, eventPayloadBinding, writer) +// } else { +// if (unbound.isNotEmpty()) { +// // all remaining members are bound to payload (but not explicitly bound via @eventPayload) +// // generate a payload deserializer specific to the unbound members (note this will be a deserializer +// // for the overall event shape but only payload members will be considered for deserialization), +// // and then assign each deserialized payload member to the current builder instance +// unbound.forEach { +// val memberName = ctx.symbolProvider.toMemberName(it) +// writer.write("event.\$L = try decoder.decode(responseBody: message.payload)", memberName) +// } +// } +// } +// writer.write("self = .\$L(event)", memberName) +// } +// } +// +// private fun renderDeserializeExplicitEventPayloadMember( +// ctx: ProtocolGenerator.GenerationContext, +// member: MemberShape, +// writer: SwiftWriter, +// ) { +// val target = ctx.model.expectShape(member.target) +// val memberName = ctx.symbolProvider.toMemberName(member) +// when (target.type) { +// ShapeType.BLOB -> writer.write("event.\$L = message.payload", memberName) +// ShapeType.STRING -> writer.write("event.\$L = String(data: message.payload, encoding: .utf8)", memberName) +// ShapeType.STRUCTURE, ShapeType.UNION -> { +// writer.write("event.\$L = .init(try decoder.decode(responseBody: message.payload))", memberName) +// } +// else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") +// } +// } +//} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt index cb8bd73af20..216cf4d4dac 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt @@ -79,7 +79,9 @@ class XMLMessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationCon writer.indent { val targetShape = ctx.model.expectShape(member.target) val symbol = ctx.symbolProvider.toSymbol(targetShape) - writer.write("return try decoder.decode(responseBody: message.payload) as \$N", symbol) + val documentReadingClosure = DocumentReadingClosureUtils(ctx, writer).closure(member) + val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) + writer.write("return try \$L(message.payload, \$L)", documentReadingClosure, readingClosure) } } writer.write("default:") diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt index b48d7ed381f..e0e9e2a6e0a 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt @@ -14,113 +14,12 @@ import software.amazon.smithy.swift.codegen.ClientRuntimeTypes import software.amazon.smithy.swift.codegen.SwiftDependency import software.amazon.smithy.swift.codegen.SwiftTypes import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable import software.amazon.smithy.swift.codegen.model.toUpperCamelCase import software.amazon.smithy.swift.codegen.utils.errorShapeName -import software.amazon.smithy.swift.codegen.utils.toUpperCamelCase -class AWSRestJson1HttpResponseBindingErrorGeneratable : HttpResponseBindingErrorGeneratable { - override fun renderServiceError(ctx: ProtocolGenerator.GenerationContext) { - val serviceShape = ctx.service - val serviceName = ctx.service.id.name - val rootNamespace = ctx.settings.moduleName - val fileName = "./$rootNamespace/models/$serviceName+ServiceErrorHelperMethod.swift" +class AWSRestJson1HttpResponseBindingErrorGeneratable : HTTPResponseBindingErrorGenerator() { - ctx.delegator.useFileWriter(fileName) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock("extension ${ctx.symbolProvider.toSymbol(ctx.service).name}Types {", "}") { - openBlock( - "static func makeServiceError(_ httpResponse: \$N, _ decoder: \$D, _ error: \$N, _ id: String?) async throws -> \$N? {", - "}", - ClientRuntimeTypes.Http.HttpResponse, - ClientRuntimeTypes.Serde.ResponseDecoder, - AWSClientRuntimeTypes.RestJSON.RestJSONError, - SwiftTypes.Error - ) { - openBlock("switch error.errorType {", "}") { - val serviceErrorShapes = - serviceShape.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - serviceErrorShapes.forEach { errorShape -> - val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: error.errorMessage, requestID: id)", - errorShapeName, - errorShapeType - ) - } - write("default: return nil") - } - } - } - } - } - } - - override fun renderOperationError(ctx: ProtocolGenerator.GenerationContext, op: OperationShape, unknownServiceErrorSymbol: Symbol) { - val operationErrorName = "${op.toUpperCamelCase()}OutputError" - val rootNamespace = ctx.settings.moduleName - val httpBindingSymbol = Symbol.builder() - .definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseBinding.swift") - .name(operationErrorName) - .build() - - ctx.delegator.useShapeWriter(httpBindingSymbol) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock( - "enum \$L: \$N {", - "}", - operationErrorName, - ClientRuntimeTypes.Http.HttpResponseErrorBinding - ) { - openBlock( - "static func makeError(httpResponse: \$N, decoder: \$D) async throws -> \$N {", "}", - ClientRuntimeTypes.Http.HttpResponse, - ClientRuntimeTypes.Serde.ResponseDecoder, - SwiftTypes.Error - ) { - write( - "let restJSONError = try await \$N(httpResponse: httpResponse)", - AWSClientRuntimeTypes.RestJSON.RestJSONError - ) - write("let requestID = httpResponse.requestId") - - if (ctx.service.errors.isNotEmpty()) { - write("let serviceError = try await ${ctx.symbolProvider.toSymbol(ctx.service).name}Types.makeServiceError(httpResponse, decoder, restJSONError, requestID)") - write("if let error = serviceError { return error }") - } - - openBlock("switch restJSONError.errorType {", "}") { - val errorShapes = op.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - errorShapes.forEach { errorShape -> - var errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - var errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: restJSONError.errorMessage, requestID: requestID)", - errorShapeName, - errorShapeType - ) - } - write( - "default: return try await \$N.makeError(httpResponse: httpResponse, message: restJSONError.errorMessage, requestID: requestID, typeName: restJSONError.errorType)", - unknownServiceErrorSymbol - ) - } - } - } - } - } - } + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestJSON.RestJSONError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt index f8b7e4d8fd2..585e0a3fc17 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt @@ -6,19 +6,18 @@ package software.amazon.smithy.aws.swift.codegen.restjson import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.restxml.AWSRestXMLHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.codingKeys.CodingKeysCustomizationJsonName -import software.amazon.smithy.swift.codegen.integration.codingKeys.DefaultCodingKeysGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { - override val codingKeysGenerator = DefaultCodingKeysGenerator(CodingKeysCustomizationJsonName()) override val defaultContentType = "application/json" override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS override val protocol: ShapeId = RestJson1Trait.ID @@ -26,8 +25,9 @@ class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override val httpResponseGenerator = HttpResponseGenerator( unknownServiceErrorSymbol, defaultTimestampFormat, - HttpResponseBindingOutputGenerator(), - AWSRestJson1HttpResponseBindingErrorGeneratable() + XMLHttpResponseBindingOutputGenerator(), + AWSRestJson1HttpResponseBindingErrorGeneratable(), + XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat) ) override val testsToIgnore = setOf( "SDKAppliedContentEncoding_restJson1", @@ -38,7 +38,7 @@ class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -46,7 +46,7 @@ class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) for (streamingShape in streamingShapes) { messageMarshallableGenerator.render(streamingShape) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt index a0370f0420f..52ab1b7bce7 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt @@ -6,139 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.restxml import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency -import software.amazon.smithy.aws.traits.protocols.RestXmlTrait import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SmithyXMLTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftTypes -import software.amazon.smithy.swift.codegen.declareSection -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.SectionId -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable -import software.amazon.smithy.swift.codegen.model.getTrait -import software.amazon.smithy.swift.codegen.model.toUpperCamelCase -import software.amazon.smithy.swift.codegen.utils.errorShapeName +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -class AWSRestXMLHttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable { - override fun renderServiceError(ctx: ProtocolGenerator.GenerationContext) { - val serviceShape = ctx.service - val serviceName = ctx.service.id.name - val rootNamespace = ctx.settings.moduleName - val fileName = "./$rootNamespace/models/$serviceName+ServiceErrorHelperMethod.swift" +class AWSRestXMLHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - ctx.delegator.useFileWriter(fileName) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - - openBlock("extension ${ctx.symbolProvider.toSymbol(ctx.service).name}Types {", "}") { - openBlock( - "static func responseServiceErrorBinding(httpResponse: \$N, reader: \$N) async throws -> \$N? {", "}", - ClientRuntimeTypes.Http.HttpResponse, - SmithyXMLTypes.Reader, - SwiftTypes.Error - ) { - openBlock("switch error.errorCode {", "}") { - val serviceErrorShapes = - serviceShape.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - serviceErrorShapes.forEach { errorShape -> - val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider) - val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L(httpResponse: httpResponse, reader: reader, message: error.message, requestID: error.requestId)", - errorShapeName, - errorShapeType - ) - } - write("default: return nil") - } - } - } - } - } - } - - object RestXMLResponseBindingSectionId : SectionId - - override fun renderOperationError(ctx: ProtocolGenerator.GenerationContext, op: OperationShape, unknownServiceErrorSymbol: Symbol) { - val operationErrorName = "${op.toUpperCamelCase()}OutputError" - val rootNamespace = ctx.settings.moduleName - val httpBindingSymbol = Symbol.builder() - .definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseErrorBinding.swift") - .name(operationErrorName) - .build() - - ctx.delegator.useShapeWriter(httpBindingSymbol) { writer -> - with(writer) { - addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - addImport(SwiftDependency.CLIENT_RUNTIME.target) - addImport(SwiftDependency.SMITHY_XML.target) - openBlock( - "enum \$L {", - "}", - operationErrorName - ) { - write("") - openBlock( - "static var httpBinding: \$N<\$N> {", "}", - ClientRuntimeTypes.Http.HTTPResponseErrorBinding, - SmithyXMLTypes.Reader, - ) { - val errorShapes = op.errors - .map { ctx.model.expectShape(it) as StructureShape } - .toSet() - .sorted() - val context = mapOf( - "operationErrorName" to operationErrorName, - "ctx" to ctx, - "unknownServiceErrorSymbol" to unknownServiceErrorSymbol, - "errorShapes" to errorShapes - ) - writer.openBlock("{ httpResponse, responseDocumentClosure in", "}") { - declareSection(RestXMLResponseBindingSectionId, context) { - val noErrorWrapping = ctx.service.getTrait()?.let { it.isNoErrorWrapping } ?: false - writer.write("let responseReader = try await responseDocumentClosure(httpResponse)") - if (errorShapes.isNotEmpty() || ctx.service.errors.isNotEmpty()) { - writer.write( - "let errorBodyReader = \$N.errorBodyReader(responseReader: responseReader, noErrorWrapping: \$L)", - AWSClientRuntimeTypes.RestXML.RestXMLError, - noErrorWrapping - ) - } - if (ctx.service.errors.isNotEmpty()) { - openBlock( - "if let serviceError = try await \$NTypes.responseServiceErrorBinding(httpResponse, errorBodyReader) {", - "}", - ctx.symbolProvider.toSymbol(ctx.service), - ) { - write("return serviceError") - } - } - writer.write("let restXMLError = try \$N(responseReader: responseReader, noErrorWrapping: \$L)", AWSClientRuntimeTypes.RestXML.RestXMLError, noErrorWrapping) - openBlock("switch restXMLError.code {", "}") { - errorShapes.forEach { errorShape -> - val errorShapeName = errorShape.id.name - val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name - write( - "case \$S: return try await \$L.responseErrorBinding(httpResponse: httpResponse, reader: errorBodyReader, message: restXMLError.message, requestID: restXMLError.requestID)", - errorShapeName, - errorShapeType - ) - } - write("default: return try await \$unknownServiceErrorSymbol:N.makeError(httpResponse: httpResponse, message: restXMLError.message, requestID: restXMLError.requestID, typeName: restXMLError.code)") - } - } - } - } - } - } - } - } + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestXML.RestXMLError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt index 4d1a6eb152f..104f6c12ddf 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt @@ -16,13 +16,13 @@ import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator import software.amazon.smithy.swift.codegen.model.ShapeMetadata class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { - override val codingKeysGenerator = null override val defaultContentType: String = "application/xml" override val defaultTimestampFormat: TimestampFormatTrait.Format = TimestampFormatTrait.Format.DATE_TIME override val protocol: ShapeId = RestXmlTrait.ID @@ -32,10 +32,12 @@ class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat, XMLHttpResponseBindingOutputGenerator(), AWSRestXMLHttpResponseBindingErrorGenerator(), - AWSXMLHttpResponseBindingErrorInitGeneratorFactory(), + XMLHttpResponseBindingErrorInitGenerator( + defaultTimestampFormat, + AWSXMLHttpResponseTraitPayloadFactory() + ) ) override val shouldRenderDecodableBodyStructForInputShapes = false - override val shouldRenderCodingKeysForEncodable = false override val testsToIgnore: Set = setOf( "S3DefaultAddressing", "S3VirtualHostAddressing", @@ -51,10 +53,6 @@ class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { ) override val tagsToIgnore = setOf("defaults") - override val codableProtocol = null - override val encodableProtocol = null - override val decodableProtocol = null - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) @@ -75,50 +73,7 @@ class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { super.generateDeserializers(ctx) val errorShapes = resolveErrorShapes(ctx) for (shape in errorShapes) { - renderCodableExtension(ctx, shape, false, true) + renderCodableExtension(ctx, shape) } } - - override fun renderStructEncode( - ctx: ProtocolGenerator.GenerationContext, - shapeContainingMembers: Shape, - shapeMetadata: Map, - members: List, - writer: SwiftWriter, - defaultTimestampFormat: TimestampFormatTrait.Format, - path: String?, - ) { - StructEncodeXMLGenerator( - ctx, - shapeContainingMembers, - members, - writer - ).render() - } - - override fun renderStructDecode( - ctx: ProtocolGenerator.GenerationContext, - shapeContainingMembers: Shape, - shapeMetadata: Map, - members: List, - writer: SwiftWriter, - defaultTimestampFormat: TimestampFormatTrait.Format, - path: String, - ) { - StructDecodeXMLGenerator( - ctx, - shapeContainingMembers, - members, - shapeMetadata, - writer, - ).render() - } - - override fun renderBodyStructAndDecodableExtension( - ctx: ProtocolGenerator.GenerationContext, - shape: Shape, - metadata: Map - ) { - // No operation - } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt index 6698d93ce77..ad419116391 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt @@ -13,30 +13,12 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorInitGeneratorFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayload import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayloadFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithoutHttpPayloadFactory -class AWSXMLHttpResponseBindingErrorInitGeneratorFactory : HttpResponseBindingErrorInitGeneratorFactory { - override fun construct( - ctx: ProtocolGenerator.GenerationContext, - structureShape: StructureShape, - httpBindingResolver: HttpBindingResolver, - defaultTimestampFormat: TimestampFormatTrait.Format, - ): HttpResponseBindingRenderable { - return XMLHttpResponseBindingErrorInitGenerator( - ctx, - structureShape, - httpBindingResolver, - defaultTimestampFormat, - AWSXMLHttpResponseTraitPayloadFactory() - ) - } -} - class AWSXMLHttpResponseTraitPayloadFactory : HttpResponseTraitPayloadFactory { override fun construct( ctx: ProtocolGenerator.GenerationContext, From e94c7290a6b813d94efa1fc2fe0c8b25b12c9995 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 10 Apr 2024 15:14:33 -0500 Subject: [PATCH 02/27] All readers/writers implemented, 74 test failures --- .../Protocols/AWSJSON/AWSJSONError.swift | 2 +- .../Protocols/RestJSON/RestJSONError.swift | 19 ++++++++----------- .../AWSHttpBindingProtocolGenerator.kt | 2 +- .../awsquery/AwsQueryProtocolGenerator.kt | 1 + .../Route53InvalidBatchErrorIntegration.kt | 4 ++-- .../ec2query/Ec2QueryProtocolGenerator.kt | 2 +- 6 files changed, 14 insertions(+), 16 deletions(-) diff --git a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift index 8ed9d505925..eea991e7176 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift @@ -18,7 +18,7 @@ public struct AWSJSONError { public init(responseReader: Reader, noErrorWrapping: Bool) throws { let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - let code: String? = try reader["Code"].readIfPresent() + let code: String? = try reader["code"].readIfPresent() ?? reader["__type"].readIfPresent() let message: String? = try reader["Message"].readIfPresent() let requestID: String? = try responseReader["RequestId"].readIfPresent() guard let code else { diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift index f25d32ed1f3..32bbfdbc70b 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift @@ -49,15 +49,6 @@ import class SmithyJSON.Reader // self.errorType = RestJSONError.sanitizeErrorType(type) // self.errorMessage = message // } -// -// /// Filter additional information from error name and sanitize it -// /// Reference: https://awslabs.github.io/smithy/1.0/spec/aws/aws-restjson1-protocol.html#operation-error-serialization -// static func sanitizeErrorType(_ type: String?) -> String? { -// guard let errorType = type else { -// return type -// } -// return errorType.substringAfter("#").substringBefore(":").trim() -// } //} public struct RestJSONError { @@ -71,13 +62,13 @@ public struct RestJSONError { public init(responseReader: Reader, noErrorWrapping: Bool) throws { let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - let code: String? = try reader["Code"].readIfPresent() + let code: String? = try reader["code"].readIfPresent() ?? reader["__type"].readIfPresent() let message: String? = try reader["Message"].readIfPresent() let requestID: String? = try responseReader["RequestId"].readIfPresent() guard let code else { throw RestJSONDecodeError.missingRequiredData } - self.code = code + self.code = sanitizeErrorType(code) self.message = message self.requestID = requestID } @@ -92,3 +83,9 @@ public struct RestJSONError { public enum RestJSONDecodeError: Error { case missingRequiredData } + + /// Filter additional information from error name and sanitize it + /// Reference: https://awslabs.github.io/smithy/1.0/spec/aws/aws-restjson1-protocol.html#operation-error-serialization + private func sanitizeErrorType(_ type: String) -> String { + return type.substringAfter("#").substringBefore(":").trim() + } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt index 0f3feed9355..16631724ba2 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt @@ -96,7 +96,7 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() defaultTimestampFormat: TimestampFormatTrait.Format, path: String? ) { - StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, writer).render() + StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() } override fun renderStructDecode( diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt index bfc1ffd42a7..6a1ade673c3 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt @@ -78,6 +78,7 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { ctx, shapeContainingMembers, members, + shapeMetadata, writer, ).render() } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt index 734782026b6..a1ffec508a5 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt @@ -59,7 +59,7 @@ class Route53InvalidBatchErrorIntegration : SwiftIntegration { "}", SmithyXMLTypes.Reader, ) { - writer.write("guard reader.content != nil else { return nil }") + writer.write("guard reader.hasContent else { return nil }") writer.write("var value = Message()") writer.write("value.message = try reader[\"Message\"].readIfPresent()") writer.write("return value") @@ -77,7 +77,7 @@ class Route53InvalidBatchErrorIntegration : SwiftIntegration { "}", SmithyXMLTypes.Reader, ) { - writer.write("guard reader.content != nil else { return nil }") + writer.write("guard reader.hasContent else { return nil }") writer.write("var value = CustomInvalidBatchError()") writer.write("value.requestID = try reader[\"RequestId\"].readIfPresent()") writer.write("value.message = try reader[\"Message\"].readIfPresent()") diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index f006ed1f0ff..7216863fe78 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -76,7 +76,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String?, ) { - StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, writer).render() + StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() } override fun renderStructDecode( From c192aaf7b437b4c0560222a1abc7b6750f7552b4 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 10 Apr 2024 20:29:53 -0500 Subject: [PATCH 03/27] Lint cleanup, codegen test fixes --- .../AWSHttpBindingProtocolGenerator.kt | 18 -- .../codegen/AWSHttpProtocolCustomizations.kt | 1 - .../codegen/AWSHttpRequestFormURLEncoder.kt | 13 - .../awsjson/AwsJson1_0_ProtocolGenerator.kt | 1 - .../AWSHttpProtocolEc2QueryCustomizations.kt | 5 +- .../Ec2QueryFormURLEncodeCustomizations.kt | 22 -- .../ec2query/Ec2QueryProtocolGenerator.kt | 2 - ...esponseBindingErrorInitGeneratorFactory.kt | 4 - .../message/MessageMarshallableGenerator.kt | 211 ---------------- .../message/MessageUnmarshallableGenerator.kt | 231 ------------------ ...son1HttpResponseBindingErrorGeneratable.kt | 10 - .../restjson/AWSRestJson1ProtocolGenerator.kt | 1 - .../AWSHttpProtocolRestXMLCustomizations.kt | 8 +- .../restxml/RestXmlProtocolGenerator.kt | 6 - ...esponseBindingErrorInitGeneratorFactory.kt | 4 - .../restxml/AWSRestXMLEventStreamTests.kt | 2 +- 16 files changed, 3 insertions(+), 536 deletions(-) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryFormURLEncodeCustomizations.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt index 16631724ba2..c02e5765655 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt @@ -4,8 +4,6 @@ */ package software.amazon.smithy.aws.swift.codegen -//import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -//import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.OperationEndpointResolverMiddleware import software.amazon.smithy.aws.swift.codegen.middleware.UserAgentMiddleware import software.amazon.smithy.codegen.core.Symbol @@ -116,22 +114,6 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() operationMiddleware.appendMiddleware(operation, UserAgentMiddleware(ctx.settings)) } - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { -// var streamingShapes = outputStreamingShapes(ctx) -// val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) -// streamingShapes.forEach { streamingMember -> -// messageUnmarshallableGenerator.renderNotImplemented(streamingMember) -// } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { -// val streamingShapes = inputStreamingShapes(ctx) -// val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) -// for (streamingShape in streamingShapes) { -// messageMarshallableGenerator.renderNotImplemented(streamingShape) -// } - } - fun outputStreamingShapes(ctx: ProtocolGenerator.GenerationContext): MutableSet { val streamingShapes = mutableMapOf() val streamingOperations = getHttpBindingOperations(ctx).filter { it.isOutputEventStream(ctx.model) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt index 0f33137aa2b..43513e26211 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt @@ -10,7 +10,6 @@ import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ServiceShape import software.amazon.smithy.swift.codegen.AuthSchemeResolverGenerator import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.ClientProperty import software.amazon.smithy.swift.codegen.integration.DefaultHttpProtocolCustomizations import software.amazon.smithy.swift.codegen.integration.HttpProtocolServiceClient import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt deleted file mode 100644 index 25e5aaa5101..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpRequestFormURLEncoder.kt +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen - -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.integration.HttpRequestEncoder - -//class AWSHttpRequestFormURLEncoder( -// requestEncoderOptions: MutableMap = mutableMapOf() -//) : HttpRequestEncoder(ClientRuntimeTypes.Serde.FormURLEncoder, requestEncoderOptions) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt index 4cabfcae29b..2eca7f9857e 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt @@ -10,7 +10,6 @@ import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizabl import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware -import software.amazon.smithy.aws.swift.codegen.restxml.AWSRestXMLHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ShapeId diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt index ca45f6cd074..3eb5890ec30 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt @@ -15,10 +15,7 @@ import software.amazon.smithy.swift.codegen.integration.ClientProperty class AWSHttpProtocolEc2QueryCustomizations : AWSHttpProtocolCustomizations() { override fun getClientProperties(): List { - val properties = mutableListOf() - val requestEncoderOptions = mutableMapOf() -// properties.add(AWSHttpRequestFormURLEncoder(requestEncoderOptions)) - return properties + return listOf() } override fun customRenderBodyComparison(test: HttpRequestTestCase): ((SwiftWriter, HttpRequestTestCase, Symbol, Shape, String, String) -> Unit)? { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryFormURLEncodeCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryFormURLEncodeCustomizations.kt deleted file mode 100644 index 62b9510ab5b..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryFormURLEncodeCustomizations.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.ec2query - -import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.swift.codegen.integration.serde.formurl.FormURLEncodeCustomizable -import software.amazon.smithy.swift.codegen.integration.serde.formurl.trait.Ec2QueryNameTraitGenerator - -class Ec2QueryFormURLEncodeCustomizations : FormURLEncodeCustomizable { - override fun alwaysUsesFlattenedCollections(): Boolean { - return true - } - override fun customNameTraitGenerator(memberShape: Shape, defaultName: String): String { - return Ec2QueryNameTraitGenerator.construct(memberShape, defaultName).toString() - } - override fun shouldSerializeEmptyLists(): Boolean { - return true - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index 7216863fe78..766f6bfe815 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -17,7 +17,6 @@ import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait -import software.amazon.smithy.swift.codegen.SwiftTypes import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator @@ -26,7 +25,6 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResp import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.formurl.StructEncodeFormURLGenerator import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt index 0aa3c014f1b..b0c997c5f56 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt @@ -6,14 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor -import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayloadFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithoutHttpPayloadFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.XMLHttpResponseTraitPayload diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt deleted file mode 100644 index 2471e359e60..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt +++ /dev/null @@ -1,211 +0,0 @@ -//package software.amazon.smithy.aws.swift.codegen.message -// -//import software.amazon.smithy.codegen.core.CodegenException -//import software.amazon.smithy.codegen.core.Symbol -//import software.amazon.smithy.model.shapes.MemberShape -//import software.amazon.smithy.model.shapes.ShapeType -//import software.amazon.smithy.model.shapes.UnionShape -//import software.amazon.smithy.model.traits.EventHeaderTrait -//import software.amazon.smithy.model.traits.EventPayloadTrait -//import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -//import software.amazon.smithy.swift.codegen.SwiftDependency -//import software.amazon.smithy.swift.codegen.SwiftWriter -//import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -//import software.amazon.smithy.swift.codegen.integration.serde.readwrite.DocumentWritingClosureUtils -//import software.amazon.smithy.swift.codegen.integration.serde.readwrite.WritingClosureUtils -//import software.amazon.smithy.swift.codegen.model.eventStreamEvents -//import software.amazon.smithy.swift.codegen.model.hasTrait -// -//class MessageMarshallableGenerator( -// private val ctx: ProtocolGenerator.GenerationContext, -// private val payloadContentType: String -//) { -// internal fun render(streamShape: UnionShape) { -// val symbol: Symbol = ctx.symbolProvider.toSymbol(streamShape) -// val rootNamespace = ctx.settings.moduleName -// val streamMember = Symbol.builder() -// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageMarshallable.swift") -// .name(symbol.name) -// .build() -// ctx.delegator.useShapeWriter(streamMember) { writer -> -// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) -// writer.openBlock( -// "extension ${symbol.fullName}: \$N {", "}", -// ClientRuntimeTypes.Serde.MessageMarshallable, -// ) { -// writer.openBlock( -// "public func marshall(encoder: \$N) throws -> \$N {", "}", -// ClientRuntimeTypes.Serde.RequestEncoder, -// ClientRuntimeTypes.EventStream.Message -// ) { -// writer.write( -// "var headers: [\$N] = [.init(name: \":message-type\", value: .string(\"event\"))]", -// ClientRuntimeTypes.EventStream.Header -// ) -// writer.write("var payload: \$D", ClientRuntimeTypes.Core.Data) -// writer.write("switch self {") -// streamShape.eventStreamEvents(ctx.model).forEach { member -> -// val memberName = ctx.symbolProvider.toMemberName(member) -// writer.write("case .\$L(let value):", memberName) -// writer.indent() -// writer.addStringHeader(":event-type", member.memberName) -// val variant = ctx.model.expectShape(member.target) -// val eventHeaderBindings = variant.members().filter { -// it.hasTrait() -// } -// val eventPayloadBinding = variant.members().firstOrNull { -// it.hasTrait() -// } -// val unbound = variant.members().filterNot { -// it.hasTrait() || it.hasTrait() -// } -// -// eventHeaderBindings.forEach { -// renderSerializeEventHeader(ctx, it, writer) -// } -// -// when { -// eventPayloadBinding != null -> renderSerializeEventPayload(ctx, eventPayloadBinding, writer) -// unbound.isNotEmpty() -> { -// writer.addStringHeader(":content-type", payloadContentType) -// // get a payload serializer for the given members of the variant -// val documentWritingClosure = DocumentWritingClosureUtils(ctx, writer).closure(variant) -// val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(variant) -// writer.write("payload = try \$L(value, \$L)", documentWritingClosure, valueWritingClosure) -// } -// } -// writer.dedent() -// } -// writer.write("case .sdkUnknown(_):") -// writer.indent() -// writer.write( -// "throw \$N(\"cannot serialize the unknown event type!\")", -// ClientRuntimeTypes.Core.UnknownClientError -// ) -// writer.dedent() -// writer.write("}") -// writer.write( -// "return \$N(headers: headers, payload: payload ?? .init())", -// ClientRuntimeTypes.EventStream.Message -// ) -// } -// } -// } -// } -// -// /** -// * extension TestServiceClientTypes.TestStream: ClientRuntime.MessageMarshallable { -// * public func marshall(encoder: ClientRuntime.RequestEncoder) throws -> ClientRuntime.EventStream.Message { -// * fatalError("not implemented") -// * } -// * } -// * -// */ -// internal fun renderNotImplemented(streamShape: UnionShape) { -// val symbol: Symbol = ctx.symbolProvider.toSymbol(streamShape) -// val rootNamespace = ctx.settings.moduleName -// val streamMember = Symbol.builder() -// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageMarshallable.swift") -// .name(symbol.name) -// .build() -// ctx.delegator.useShapeWriter(streamMember) { writer -> -// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) -// writer.openBlock( -// "extension ${symbol.fullName}: \$N {", "}", -// ClientRuntimeTypes.Serde.MessageMarshallable, -// ) { -// writer.openBlock( -// "public func marshall(encoder: \$N) throws -> \$N {", "}", -// ClientRuntimeTypes.Serde.RequestEncoder, -// ClientRuntimeTypes.EventStream.Message -// ) { -// writer.write("#error(\"Event streams not implemented for this protocol\")") -// } -// } -// } -// } -// -// /** -// * headers.append(.init(name: ":event-type", value: .string("MessageWithBlob"))) -// */ -// private fun SwiftWriter.addStringHeader(name: String, value: String) { -// write("headers.append(.init(name: \$S, value: .string(\$S)))", name, value) -// } -// -// private fun renderSerializeEventPayload(ctx: ProtocolGenerator.GenerationContext, member: MemberShape, writer: SwiftWriter) { -// val target = ctx.model.expectShape(member.target) -// val memberName = ctx.symbolProvider.toMemberName(member) -// when (target.type) { -// ShapeType.BLOB -> { -// writer.addStringHeader(":content-type", "application/octet-stream") -// writer.write("payload = value.\$L", memberName) -// } -// ShapeType.STRING -> { -// writer.addStringHeader(":content-type", "text/plain") -// writer.write("payload = value.\$L?.data(using: .utf8)", memberName) -// } -// ShapeType.STRUCTURE, ShapeType.UNION -> { -// writer.addStringHeader(":content-type", payloadContentType) -// writer.write("payload = try encoder.encode(value)") -// } -// else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") -// } -// } -// -///** -// * -// * if let headerValue = value.blob { -// * headers.append(.init(name: "blob", value: .byteArray(headerValue))) -// * } -// * if let headerValue = value.boolean { -// * headers.append(.init(name: "boolean", value: .bool(headerValue))) -// * } -// * if let headerValue = value.byte { -// * headers.append(.init(name: "byte", value: .byte(headerValue))) -// * } -// * if let headerValue = value.int { -// * headers.append(.init(name: "int", value: .int32(Int32(headerValue)))) -// * } -// * if let headerValue = value.long { -// * headers.append(.init(name: "long", value: .int64(Int64(headerValue)))) -// * } -// * if let headerValue = value.short { -// * headers.append(.init(name: "short", value: .int16(headerValue))) -// * } -// * if let headerValue = value.string { -// * headers.append(.init(name: "string", value: .string(headerValue))) -// * } -// * if let headerValue = value.timestamp { -// * headers.append(.init(name: "timestamp", value: .timestamp(headerValue))) -// * } -//*/ -// private fun renderSerializeEventHeader(ctx: ProtocolGenerator.GenerationContext, member: MemberShape, writer: SwiftWriter) { -// val target = ctx.model.expectShape(member.target) -// val headerValue = when (target.type) { -// ShapeType.BOOLEAN -> "bool" -// ShapeType.BYTE -> "byte" -// ShapeType.SHORT -> "int16" -// ShapeType.INTEGER -> "int32" -// ShapeType.LONG -> "int64" -// ShapeType.BLOB -> "byteArray" -// ShapeType.STRING -> "string" -// ShapeType.TIMESTAMP -> "timestamp" -// else -> throw CodegenException("unsupported shape type `${target.type}` for eventHeader member `$member`; target: $target") -// } -// -// val memberName = ctx.symbolProvider.toMemberName(member) -// writer.openBlock("if let headerValue = value.\$L {", "}", memberName) { -// when (target.type) { -// ShapeType.INTEGER -> { -// writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(Int32(headerValue))))", headerValue) -// } -// ShapeType.LONG -> { -// writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(Int64(headerValue))))", headerValue) -// } -// else -> { -// writer.write("headers.append(.init(name: \"${member.memberName}\", value: .\$L(headerValue)))", headerValue) -// } -// } -// } -// } -//} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt deleted file mode 100644 index c635ede2106..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt +++ /dev/null @@ -1,231 +0,0 @@ -//package software.amazon.smithy.aws.swift.codegen.message -// -//import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -//import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency -//import software.amazon.smithy.codegen.core.CodegenException -//import software.amazon.smithy.codegen.core.Symbol -//import software.amazon.smithy.model.shapes.MemberShape -//import software.amazon.smithy.model.shapes.ShapeType -//import software.amazon.smithy.model.shapes.UnionShape -//import software.amazon.smithy.model.traits.EventHeaderTrait -//import software.amazon.smithy.model.traits.EventPayloadTrait -//import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -//import software.amazon.smithy.swift.codegen.SwiftDependency -//import software.amazon.smithy.swift.codegen.SwiftTypes -//import software.amazon.smithy.swift.codegen.SwiftWriter -//import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -//import software.amazon.smithy.swift.codegen.model.eventStreamErrors -//import software.amazon.smithy.swift.codegen.model.eventStreamEvents -//import software.amazon.smithy.swift.codegen.model.expectShape -//import software.amazon.smithy.swift.codegen.model.hasTrait -// -//class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContext) { -// fun render( -// streamingMember: MemberShape -// ) { -// val symbol: Symbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(streamingMember.target)) -// val rootNamespace = ctx.settings.moduleName -// val streamMember = Symbol.builder() -// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageUnmarshallable.swift") -// .name(symbol.name) -// .build() -// -// val streamShape = ctx.model.expectShape(streamingMember.target) -// val service = ctx.settings.getService(ctx.model) -// val serviceSymbol = ctx.symbolProvider.toSymbol(service) -// val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) -// -// ctx.delegator.useShapeWriter(streamMember) { writer -> -// -// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) -// writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) -// writer.openBlock( -// "extension ${streamSymbol.fullName}: \$N {", "}", -// ClientRuntimeTypes.Serde.MessageUnmarshallable -// ) { -// writer.openBlock( -// "public init(message: \$N, decoder: \$N) throws {", "}", -// ClientRuntimeTypes.EventStream.Message, -// ClientRuntimeTypes.Serde.ResponseDecoder -// ) { -// writer.write("switch try message.type() {") -// writer.write("case .event(let params):") -// writer.indent { -// writer.write("switch params.eventType {") -// streamShape.eventStreamEvents(ctx.model).forEach { member -> -// writer.write("case \"${member.memberName}\":") -// writer.indent { -// renderDeserializeEventVariant(ctx, streamSymbol, member, writer) -// } -// } -// writer.write("default:") -// writer.indent { -// writer.write("self = .sdkUnknown(\"error processing event stream, unrecognized event: \\(params.eventType)\")") -// } -// writer.write("}") -// } -// writer.write("case .exception(let params):") -// writer.indent { -// writer.write( -// "let makeError: (\$N, \$N) throws -> \$N = { message, params in", -// ClientRuntimeTypes.EventStream.Message, -// ClientRuntimeTypes.EventStream.ExceptionParams, -// SwiftTypes.Error -// ) -// writer.indent { -// writer.write("switch params.exceptionType {") -// streamShape.eventStreamErrors(ctx.model).forEach { member -> -// writer.write("case \"${member.memberName}\":") -// writer.indent { -// val targetShape = ctx.model.expectShape(member.target) -// val symbol = ctx.symbolProvider.toSymbol(targetShape) -// writer.write("return try decoder.decode(responseBody: message.payload) as \$N", symbol) -// } -// } -// writer.write("default:") -// writer.indent { -// writer.write("let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok)") -// writer.write( -// "return \$L(httpResponse: httpResponse, message: \"error processing event stream, unrecognized ':exceptionType': \\(params.exceptionType); contentType: \\(params.contentType ?? \"nil\")\", requestID: nil, typeName: nil)", -// AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError -// ) -// } -// writer.write("}") -// } -// writer.write("}") -// writer.write("let error = try makeError(message, params)") -// writer.write("throw error") -// } -// writer.write("case .error(let params):") -// writer.indent { -// // this is a service exception still, just un-modeled -// writer.write("let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok)") -// writer.write( -// "throw \$L(httpResponse: httpResponse, message: \"error processing event stream, unrecognized ':errorType': \\(params.errorCode); message: \\(params.message ?? \"nil\")\", requestID: nil, typeName: nil)", -// AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError -// ) -// } -// writer.write("case .unknown(messageType: let messageType):") -// writer.indent { -// // this is a client exception because we failed to parse it -// writer.write( -// "throw \$L(\"unrecognized event stream message ':message-type': \\(messageType)\")", -// ClientRuntimeTypes.Core.UnknownClientError -// ) -// } -// writer.write("}") -// } -// } -// } -// } -// -// fun renderNotImplemented( -// streamingMember: MemberShape -// ) { -// val symbol: Symbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(streamingMember.target)) -// val rootNamespace = ctx.settings.moduleName -// val streamMember = Symbol.builder() -// .definitionFile("./$rootNamespace/models/${symbol.name}+MessageUnmarshallable.swift") -// .name(symbol.name) -// .build() -// -// val streamShape = ctx.model.expectShape(streamingMember.target) -// val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) -// -// ctx.delegator.useShapeWriter(streamMember) { writer -> -// -// writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) -// writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) -// writer.openBlock( -// "extension ${streamSymbol.fullName}: \$N {", "}", -// ClientRuntimeTypes.Serde.MessageUnmarshallable -// ) { -// writer.write("") -// writer.openBlock( -// "public init(message: \$N, decoder: \$N) throws {", "}", -// ClientRuntimeTypes.EventStream.Message, -// ClientRuntimeTypes.Serde.ResponseDecoder -// ) { -// writer.write("fatalError(\"Not implemented\")") -// } -// } -// } -// } -// -// private fun renderDeserializeEventVariant(ctx: ProtocolGenerator.GenerationContext, unionSymbol: Symbol, member: MemberShape, writer: SwiftWriter) { -// val variant = ctx.model.expectShape(member.target) -// -// val eventHeaderBindings = variant.members().filter { it.hasTrait() } -// val eventPayloadBinding = variant.members().firstOrNull { it.hasTrait() } -// val unbound = variant.members().filterNot { it.hasTrait() || it.hasTrait() } -// val memberName = ctx.symbolProvider.toMemberName(member) -// -// if (eventHeaderBindings.isEmpty() && eventPayloadBinding == null) { -// writer.write("self = .\$L(try decoder.decode(responseBody: message.payload))", memberName) -// } else { -// val variantSymbol = ctx.symbolProvider.toSymbol(variant) -// writer.write("var event = \$N()", variantSymbol) -// // render members bound to header -// eventHeaderBindings.forEach { hdrBinding -> -// val target = ctx.model.expectShape(hdrBinding.target) -// -// val conversionFn = when (target.type) { -// ShapeType.BOOLEAN -> "bool" -// ShapeType.BYTE -> "byte" -// ShapeType.SHORT -> "int16" -// ShapeType.INTEGER -> "int32" -// ShapeType.LONG -> "int64" -// ShapeType.BLOB -> "byteArray" -// ShapeType.STRING -> "string" -// ShapeType.TIMESTAMP -> "timestamp" -// else -> throw CodegenException("unsupported eventHeader shape: member=$hdrBinding; targetShape=$target") -// } -// -// writer.openBlock("if case let .\$L(value) = message.headers.value(name: \$S) {", "}", conversionFn, hdrBinding.memberName) { -// val memberName = ctx.symbolProvider.toMemberName(hdrBinding) -// when (target.type) { -// ShapeType.INTEGER, ShapeType.LONG -> { -// writer.write("event.\$L = Int(value)", memberName) -// } -// else -> { -// writer.write("event.\$L = value", memberName) -// } -// } -// } -// } -// -// if (eventPayloadBinding != null) { -// renderDeserializeExplicitEventPayloadMember(ctx, eventPayloadBinding, writer) -// } else { -// if (unbound.isNotEmpty()) { -// // all remaining members are bound to payload (but not explicitly bound via @eventPayload) -// // generate a payload deserializer specific to the unbound members (note this will be a deserializer -// // for the overall event shape but only payload members will be considered for deserialization), -// // and then assign each deserialized payload member to the current builder instance -// unbound.forEach { -// val memberName = ctx.symbolProvider.toMemberName(it) -// writer.write("event.\$L = try decoder.decode(responseBody: message.payload)", memberName) -// } -// } -// } -// writer.write("self = .\$L(event)", memberName) -// } -// } -// -// private fun renderDeserializeExplicitEventPayloadMember( -// ctx: ProtocolGenerator.GenerationContext, -// member: MemberShape, -// writer: SwiftWriter, -// ) { -// val target = ctx.model.expectShape(member.target) -// val memberName = ctx.symbolProvider.toMemberName(member) -// when (target.type) { -// ShapeType.BLOB -> writer.write("event.\$L = message.payload", memberName) -// ShapeType.STRING -> writer.write("event.\$L = String(data: message.payload, encoding: .utf8)", memberName) -// ShapeType.STRUCTURE, ShapeType.UNION -> { -// writer.write("event.\$L = .init(try decoder.decode(responseBody: message.payload))", memberName) -// } -// else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") -// } -// } -//} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt index e0e9e2a6e0a..8b4023efcbd 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt @@ -6,18 +6,8 @@ package software.amazon.smithy.aws.swift.codegen.restjson import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.swift.codegen.ClientRuntimeTypes -import software.amazon.smithy.swift.codegen.SwiftDependency -import software.amazon.smithy.swift.codegen.SwiftTypes -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable -import software.amazon.smithy.swift.codegen.model.toUpperCamelCase -import software.amazon.smithy.swift.codegen.utils.errorShapeName class AWSRestJson1HttpResponseBindingErrorGeneratable : HTTPResponseBindingErrorGenerator() { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt index 585e0a3fc17..8771a4ad424 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt @@ -8,7 +8,6 @@ import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.restxml.AWSRestXMLHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt index bc75db1fb75..5695e8dc56c 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt @@ -6,11 +6,5 @@ package software.amazon.smithy.aws.swift.codegen.restxml import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations -import software.amazon.smithy.swift.codegen.integration.ClientProperty -class AWSHttpProtocolRestXMLCustomizations : AWSHttpProtocolCustomizations() { - - override fun getClientProperties(): List { - return listOf() - } -} +class AWSHttpProtocolRestXMLCustomizations : AWSHttpProtocolCustomizations() diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt index 104f6c12ddf..b3a9b6646fb 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt @@ -9,18 +9,12 @@ import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.RestXmlTrait -import software.amazon.smithy.model.shapes.MemberShape -import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.model.traits.TimestampFormatTrait -import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator -import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator -import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator -import software.amazon.smithy.swift.codegen.model.ShapeMetadata class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { override val defaultContentType: String = "application/xml" diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt index ad419116391..87a7213c65d 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt @@ -7,14 +7,10 @@ package software.amazon.smithy.aws.swift.codegen.restxml import software.amazon.smithy.aws.swift.codegen.restxml.httpResponse.AWSXMLHttpResponseTraitWithoutPayload import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.model.shapes.StructureShape -import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor -import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayload import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayloadFactory import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithoutHttpPayloadFactory diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index e42bdea01c5..f3bc76f535a 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -103,7 +103,7 @@ class AWSRestXMLEventStreamTests { ) val contents = TestUtils.getFileContents( context.manifest, - "/Example/models/Audio+Codable.swift" + "/Example/models/Audio+ReadWrite.swift" ) contents.shouldSyntacticSanityCheck() val expectedContents = """ From 9c738c36e96df67d73c0e5ee7f95f5f57f600db0 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Thu, 11 Apr 2024 09:21:28 -0500 Subject: [PATCH 04/27] Handle sparse collections in response --- .../AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift | 2 +- .../Protocols/Ec2Query/Ec2Response.swift | 2 +- .../swift/codegen/awsquery/AwsQueryProtocolGenerator.kt | 9 +++++++++ .../swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt | 9 +++++++++ 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift index 55710cf4898..fbc329caba2 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift @@ -14,7 +14,7 @@ public struct Ec2Errors { static var readingClosure: ReadingClosure { return { reader in var value = Ec2Errors() - value.error = try reader["Error"].readIfPresent(readingClosure: Ec2Error.readingClosure) + value.error = try reader["Error"].readIfPresent(with: Ec2Error.readingClosure) return value } } diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift index af1bfbf0b43..ef2de00084e 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift @@ -17,7 +17,7 @@ public struct Ec2Response { return { httpResponse, wireResponseDocumentBinding in let reader = try await wireResponseDocumentBinding(httpResponse) var value = Ec2Response() - value.errors = try reader["Errors"].readIfPresent(readingClosure: Ec2Errors.readingClosure) + value.errors = try reader["Errors"].readIfPresent(with: Ec2Errors.readingClosure) value.requestId = try reader["RequestId"].readIfPresent() ?? reader["RequestID"].readIfPresent() return value } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt index 6a1ade673c3..b390a35fab2 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt @@ -10,6 +10,7 @@ import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizabl import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseTraitPayloadFactory import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSQueryHttpResponseBindingErrorGenerator +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait import software.amazon.smithy.model.shapes.MemberShape @@ -65,6 +66,14 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { } } + override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { + var streamingShapes = inputStreamingShapes(ctx) + val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + streamingShapes.forEach { streamingMember -> + messageMarshallableGenerator.render(streamingMember) + } + } + override fun renderStructEncode( ctx: ProtocolGenerator.GenerationContext, shapeContainingMembers: Shape, diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index 766f6bfe815..684d7e78dbd 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -10,6 +10,7 @@ import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizabl import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseBindingErrorGenerator import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseTraitPayloadFactory +import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait import software.amazon.smithy.model.shapes.MemberShape @@ -65,6 +66,14 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { } } + override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { + var streamingShapes = inputStreamingShapes(ctx) + val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + streamingShapes.forEach { streamingMember -> + messageMarshallableGenerator.render(streamingMember) + } + } + override fun renderStructEncode( ctx: ProtocolGenerator.GenerationContext, shapeContainingMembers: Shape, From 25753690b808b6be5113fae41dc38f0b303942b7 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Fri, 12 Apr 2024 17:15:39 -0500 Subject: [PATCH 05/27] Fix error protocol tests --- .../Errors/RestXMLError+AWS.swift | 18 +-- .../Errors/UnknownAWSHTTPServiceError.swift | 2 +- .../Protocols/AWSJSON/AWSJSONError.swift | 35 ++--- .../Protocols/AWSQuery/AWSQueryError.swift | 36 ++++++ .../Protocols/Ec2Query/EC2QueryError.swift | 33 +++++ .../Protocols/Ec2Query/Ec2Error.swift | 23 ---- .../Protocols/Ec2Query/Ec2Errors.swift | 21 --- .../Protocols/Ec2Query/Ec2NarrowedError.swift | 14 -- .../Ec2Query/Ec2NarrowedResponse.swift | 27 ---- .../Protocols/Ec2Query/Ec2QueryError.swift | 58 --------- .../Protocols/Ec2Query/Ec2Response.swift | 25 ---- .../Protocols/RestJSON/RestJSONError.swift | 120 +++++++----------- .../RestJSON/RestJSONErrorPayload.swift | 37 ------ .../RestXML/ErrorResponseContainer.swift | 15 --- .../Protocols/RestXML/RestXMLError.swift | 33 +++-- .../RestXMLErrorNoErrorWrappingPayload.swift | 17 --- .../RestXML/RestXMLErrorPayload.swift | 15 --- .../swift/codegen/AWSClientRuntimeTypes.kt | 7 +- .../awsjson/AwsJson1_0_ProtocolGenerator.kt | 3 +- .../awsjson/AwsJson1_1_ProtocolGenerator.kt | 3 +- .../AwsQueryFormURLEncodeCustomizations.kt | 24 ---- .../awsquery/AwsQueryProtocolGenerator.kt | 4 +- ...SQueryHttpResponseBindingErrorGenerator.kt | 2 +- .../Route53InvalidBatchErrorIntegration.kt | 7 +- .../customization/s3/S3ErrorIntegration.kt | 4 +- .../ec2query/Ec2QueryProtocolGenerator.kt | 4 +- ...2QueryHttpResponseBindingErrorGenerator.kt | 2 +- .../restjson/AWSRestJson1ProtocolGenerator.kt | 6 +- .../restxml/RestXmlProtocolGenerator.kt | 4 +- .../awsjson/AWSJsonHttpInitialRequestTests.kt | 61 ++++----- .../FlexibleChecksumMiddlewareTests.kt | 6 +- .../restxml/AWSRestXMLEventStreamTests.kt | 109 ++++++++-------- 32 files changed, 266 insertions(+), 509 deletions(-) create mode 100644 Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift create mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Error.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedError.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedResponse.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONErrorPayload.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/RestXML/ErrorResponseContainer.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorNoErrorWrappingPayload.swift delete mode 100644 Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorPayload.swift delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryFormURLEncodeCustomizations.kt diff --git a/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift b/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift index 70a2011277f..62e60335a94 100644 --- a/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift +++ b/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift @@ -16,13 +16,13 @@ extension RestXMLError { /// - Parameter noErrorWrapping: `true` if the error is wrapped in a XML `ErrorResponse` element, `false` otherwise. /// - Returns: A`RestXMLError` instance with an error code of "NotFound" if the response body is empty and the status code is 404, else returns a `RestXMLError` by calling the `RestXMLError` initializer. /// - Throws: An error if it fails to decode the response body. - public static func makeError( - from httpResponse: HttpResponse, - responseReader: SmithyXML.Reader, - noErrorWrapping: Bool - ) async throws -> RestXMLError { - return httpResponse.statusCodeIsNotFoundAndBodyIsEmpty - ? .init(code: "NotFound", message: "404 Not Found", requestID: httpResponse.requestId) - : try .init(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - } +// public static func makeError( +// from httpResponse: HttpResponse, +// responseReader: SmithyXML.Reader, +// noErrorWrapping: Bool +// ) async throws -> RestXMLError { +// return httpResponse.statusCodeIsNotFoundAndBodyIsEmpty +// ? .init(code: "NotFound", message: "404 Not Found", requestID: httpResponse.requestId) +// : try .init(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: noErrorWrapping) +// } } diff --git a/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift b/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift index 653ffb05312..9d9a19240dc 100644 --- a/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift +++ b/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift @@ -64,7 +64,7 @@ extension UnknownAWSHTTPServiceError { requestID: String?, requestID2: String? = nil, typeName: String? - ) async throws -> Error { + ) throws -> Error { let candidates: [UnknownAWSHTTPErrorCandidate.Type] = [ InvalidAccessKeyId.self ] diff --git a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift index eea991e7176..3d603a60718 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift @@ -5,37 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // +import enum ClientRuntime.BaseErrorDecodeError +import class ClientRuntime.HttpResponse import class SmithyJSON.Reader public struct AWSJSONError { public let code: String public let message: String? public let requestID: String? + public var errorBodyReader: Reader { responseReader } - public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { - noErrorWrapping ? responseReader : responseReader["Error"] - } + public let httpResponse: HttpResponse + private let responseReader: Reader - public init(responseReader: Reader, noErrorWrapping: Bool) throws { - let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - let code: String? = try reader["code"].readIfPresent() ?? reader["__type"].readIfPresent() - let message: String? = try reader["Message"].readIfPresent() + public init(httpResponse: HttpResponse, responseReader: Reader, noErrorWrapping: Bool) throws { + let code: String? = try httpResponse.headers.value(for: "X-Amzn-Errortype") + ?? responseReader["code"].readIfPresent() + ?? responseReader["__type"].readIfPresent() + let message: String? = try responseReader["Message"].readIfPresent() let requestID: String? = try responseReader["RequestId"].readIfPresent() - guard let code else { - throw AWSJSONDecodeError.missingRequiredData - } - self.code = code + guard let code else { throw BaseErrorDecodeError.missingRequiredData } + self.code = sanitizeErrorType(code) self.message = message self.requestID = requestID + self.httpResponse = httpResponse + self.responseReader = responseReader } - - public init(code: String, message: String?, requestID: String?) { - self.code = code - self.message = message - self.requestID = requestID - } -} - -public enum AWSJSONDecodeError: Error { - case missingRequiredData } diff --git a/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift new file mode 100644 index 00000000000..8fc1a25f06c --- /dev/null +++ b/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift @@ -0,0 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import enum ClientRuntime.BaseErrorDecodeError +import class ClientRuntime.HttpResponse +import class SmithyXML.Reader + +public struct AWSQueryError { + public let code: String + public let message: String? + public let requestID: String? + public let httpResponse: HttpResponse + public let responseReader: Reader + public let errorBodyReader: Reader + + public init(httpResponse: HttpResponse, responseReader: Reader, noErrorWrapping: Bool) throws { + self.errorBodyReader = noErrorWrapping ? responseReader : responseReader["Error"] + let code: String? = try errorBodyReader["Code"].readIfPresent() + let message: String? = try errorBodyReader["Message"].readIfPresent() + let requestID: String? = try responseReader["RequestId"].readIfPresent() + guard let code else { throw BaseErrorDecodeError.missingRequiredData } + self.code = code + self.message = message + self.requestID = requestID + self.httpResponse = httpResponse + self.responseReader = responseReader + } +} + +public enum AWSQueryDecodeError: Error { + case missingRequiredData +} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift new file mode 100644 index 00000000000..0bb42637fd5 --- /dev/null +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift @@ -0,0 +1,33 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import enum ClientRuntime.BaseErrorDecodeError +import class ClientRuntime.HttpResponse +import class SmithyXML.Reader + +public struct EC2QueryError { + public let code: String + public let message: String? + public let requestID: String? + public let errorBodyReader: Reader + + public let httpResponse: HttpResponse + public let responseReader: Reader + + public init(httpResponse: HttpResponse, responseReader: Reader, noErrorWrapping: Bool) throws { + self.httpResponse = httpResponse + self.responseReader = responseReader + self.errorBodyReader = responseReader["Errors"]["Error"] + let code: String? = try errorBodyReader["Code"].readIfPresent() + guard let code else { throw BaseErrorDecodeError.missingRequiredData } + let message: String? = try errorBodyReader["Message"].readIfPresent() + let requestID: String? = try responseReader["RequestId"].readIfPresent() + self.code = code + self.message = message + self.requestID = requestID + } +} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Error.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Error.swift deleted file mode 100644 index 412346f7019..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Error.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import SmithyReadWrite -import SmithyXML - -public struct Ec2Error { - public var code: String? - public var message: String? - - static var readingClosure: ReadingClosure { - return { reader in - var value = Ec2Error() - value.code = try reader["Code"].readIfPresent() - value.message = try reader["Message"].readIfPresent() - return value - } - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift deleted file mode 100644 index fbc329caba2..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Errors.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import SmithyReadWrite -import SmithyXML - -public struct Ec2Errors { - public var error: Ec2Error? - - static var readingClosure: ReadingClosure { - return { reader in - var value = Ec2Errors() - value.error = try reader["Error"].readIfPresent(with: Ec2Error.readingClosure) - return value - } - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedError.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedError.swift deleted file mode 100644 index a17aac3f696..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedError.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -public struct Ec2NarrowedError: Decodable where T: Decodable { - public let error: T - - enum CodingKeys: String, CodingKey { - case error = "Error" - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedResponse.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedResponse.swift deleted file mode 100644 index 99535d68786..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2NarrowedResponse.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -public struct Ec2NarrowedResponse: Decodable where T: Decodable { - public let errors: Ec2NarrowedError - public let requestId: String - - enum CodingKeys: String, CodingKey { - case errors = "Errors" - case requestId = "RequestId" - case requestID = "RequestID" - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.errors = try container.decode(Ec2NarrowedError.self, forKey: .errors) - - // Attempt to decode the requestId with the key "RequestID" - // if that is not present, then fallback to the key "RequestId" - self.requestId = try container.decodeIfPresent(String.self, forKey: .requestID) - ?? container.decode(String.self, forKey: .requestId) - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift deleted file mode 100644 index 457edefd718..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2QueryError.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -//import class ClientRuntime.HttpResponse -//import class SmithyXML.Reader -//import func SmithyReadWrite.wireResponseDocumentBinding -// -//public struct Ec2QueryError { -// public var errorCode: String? -// public var requestId: String? -// public var message: String? -// -// public init(httpResponse: HttpResponse) async throws { -// let response = try await Ec2Response.httpBinding(httpResponse, wireResponseDocumentBinding()) -// self.errorCode = response.errors?.error?.code -// self.message = response.errors?.error?.message -// self.requestId = response.requestId -// } -//} - -import class SmithyXML.Reader - -public struct Ec2QueryError { - public let code: String - public let message: String? - public let requestID: String? - - public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { - noErrorWrapping ? responseReader : responseReader["Error"] - } - - public init(responseReader: Reader, noErrorWrapping: Bool) throws { - let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - let code: String? = try reader["Code"].readIfPresent() - let message: String? = try reader["Message"].readIfPresent() - let requestID: String? = try responseReader["RequestId"].readIfPresent() - guard let code else { - throw Ec2QueryDecodeError.missingRequiredData - } - self.code = code - self.message = message - self.requestID = requestID - } - - public init(code: String, message: String?, requestID: String?) { - self.code = code - self.message = message - self.requestID = requestID - } -} - -public enum Ec2QueryDecodeError: Error { - case missingRequiredData -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift deleted file mode 100644 index ef2de00084e..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/Ec2Response.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import SmithyReadWrite -import class SmithyXML.Reader -import ClientRuntime - -public struct Ec2Response { - public var errors: Ec2Errors? - public var requestId: String? - - public static var httpBinding: WireResponseOutputBinding { - return { httpResponse, wireResponseDocumentBinding in - let reader = try await wireResponseDocumentBinding(httpResponse) - var value = Ec2Response() - value.errors = try reader["Errors"].readIfPresent(with: Ec2Errors.readingClosure) - value.requestId = try reader["RequestId"].readIfPresent() ?? reader["RequestID"].readIfPresent() - return value - } - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift index 32bbfdbc70b..498533bf5fa 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift @@ -1,91 +1,61 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -import Foundation -import ClientRuntime - -import class SmithyJSON.Reader - -/// A general Error Structure for Rest JSON protocol -//public struct RestJSONError { -// public let errorType: String? -// public let errorMessage: String? -// -// // header identifying the error code -// let X_AMZN_ERROR_TYPE_HEADER_NAME = "X-Amzn-Errortype" -// -// // returned by RESTFUL services that do no send a payload (like in a HEAD request) -// let X_AMZN_ERROR_MESSAGE_HEADER_NAME = "x-amzn-error-message" // -// // returned by some services like Cognito -// let X_AMZN_ERRORMESSAGE_HEADER_NAME = "x-amzn-ErrorMessage" +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. // -// // error message header returned by event stream errors -// let X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME = ":error-message" +// SPDX-License-Identifier: Apache-2.0 // -// public init(httpResponse: HttpResponse) async throws { -// var message = httpResponse.headers.value(for: X_AMZN_ERROR_MESSAGE_HEADER_NAME) -// if message == nil { -// message = httpResponse.headers.value(for: X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME) -// } -// -// if message == nil { -// message = httpResponse.headers.value(for: X_AMZN_ERRORMESSAGE_HEADER_NAME) -// } -// -// var type = httpResponse.headers.value(for: X_AMZN_ERROR_TYPE_HEADER_NAME) -// -// if let data = try await httpResponse.body.readData() { -// let output: RestJSONErrorPayload = try JSONDecoder().decode(responseBody: data) -// if message == nil { -// message = output.resolvedErrorMessage -// } -// if type == nil { -// type = output.resolvedErrorType -// } -// } -// self.errorType = RestJSONError.sanitizeErrorType(type) -// self.errorMessage = message -// } -//} + +import enum ClientRuntime.BaseErrorDecodeError +import class ClientRuntime.HttpResponse +import class SmithyJSON.Reader public struct RestJSONError { public let code: String public let message: String? public let requestID: String? - public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { - noErrorWrapping ? responseReader : responseReader["Error"] - } + public let httpResponse: HttpResponse + private let responseReader: Reader + public var errorBodyReader: Reader { responseReader } - public init(responseReader: Reader, noErrorWrapping: Bool) throws { - let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - let code: String? = try reader["code"].readIfPresent() ?? reader["__type"].readIfPresent() - let message: String? = try reader["Message"].readIfPresent() - let requestID: String? = try responseReader["RequestId"].readIfPresent() - guard let code else { - throw RestJSONDecodeError.missingRequiredData - } - self.code = sanitizeErrorType(code) - self.message = message - self.requestID = requestID - } + // header identifying the error code + let X_AMZN_ERROR_TYPE_HEADER_NAME = "X-Amzn-Errortype" + + // returned by RESTFUL services that do no send a payload (like in a HEAD request) + let X_AMZN_ERROR_MESSAGE_HEADER_NAME = "x-amzn-error-message" + + // returned by some services like Cognito + let X_AMZN_ERRORMESSAGE_HEADER_NAME = "x-amzn-ErrorMessage" + + // error message header returned by event stream errors + let X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME = ":error-message" - public init(code: String, message: String?, requestID: String?) { - self.code = code + public init(httpResponse: HttpResponse, responseReader: SmithyJSON.Reader, noErrorWrapping: Bool) throws { + let type = try httpResponse.headers.value(for: X_AMZN_ERROR_TYPE_HEADER_NAME) + ?? responseReader["code"].readIfPresent() + ?? responseReader["__type"].readIfPresent() + + guard let type else { throw BaseErrorDecodeError.missingRequiredData } + + // this is broken into steps since the Swift compiler can't type check a compound statement + // in reasonable time + var message = httpResponse.headers.value(for: X_AMZN_ERROR_MESSAGE_HEADER_NAME) + message = message ?? httpResponse.headers.value(for: X_AMZN_EVENT_ERROR_MESSAGE_HEADER_NAME) + message = message ?? httpResponse.headers.value(for: X_AMZN_ERRORMESSAGE_HEADER_NAME) + message = try message ?? responseReader["message"].readIfPresent() + message = try message ?? responseReader["Message"].readIfPresent() + message = try message ?? responseReader["errorMessage"].readIfPresent() + + self.code = sanitizeErrorType(type) self.message = message - self.requestID = requestID + self.requestID = httpResponse.requestId + self.httpResponse = httpResponse + self.responseReader = responseReader } } -public enum RestJSONDecodeError: Error { - case missingRequiredData +/// Filter additional information from error name and sanitize it +/// Reference: https://awslabs.github.io/smithy/1.0/spec/aws/aws-restjson1-protocol.html#operation-error-serialization +func sanitizeErrorType(_ type: String) -> String { + return type.substringAfter("#").substringBefore(":").trim() } - - /// Filter additional information from error name and sanitize it - /// Reference: https://awslabs.github.io/smithy/1.0/spec/aws/aws-restjson1-protocol.html#operation-error-serialization - private func sanitizeErrorType(_ type: String) -> String { - return type.substringAfter("#").substringBefore(":").trim() - } diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONErrorPayload.swift b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONErrorPayload.swift deleted file mode 100644 index b33487b87b6..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONErrorPayload.swift +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -/// A general payload structure for Rest-JSON protocol errors -public struct RestJSONErrorPayload: Decodable { - /// Payload Members which might hold Error name - let code: String? - let __type: String? - - /// Payload Members which might hold Error message - let message: String? - let Message: String? - let errorMessage: String? - - // https://sapp.amazon.com/seps/accepted/shared/sdk-unmarshal-errors/#rest-json - /// Resolve and return the error name - public var resolvedErrorType: String? { - if code != nil { - return code - } else { - return __type - } - } - - /// Resolve and return the error message - public var resolvedErrorMessage: String? { - if message != nil { - return message - } else if Message != nil { - return Message - } else { - return errorMessage - } - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestXML/ErrorResponseContainer.swift b/Sources/Core/AWSClientRuntime/Protocols/RestXML/ErrorResponseContainer.swift deleted file mode 100644 index 9f9956429e4..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/RestXML/ErrorResponseContainer.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -public struct ErrorResponseContainer: Decodable where T: Decodable { - public let error: T - public let requestId: String - enum CodingKeys: String, CodingKey { - case error = "Error" - case requestId = "RequestId" - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift index 1dbd6aaa4e8..a671a405c73 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift @@ -5,37 +5,34 @@ // SPDX-License-Identifier: Apache-2.0 // +import enum ClientRuntime.BaseErrorDecodeError +import class ClientRuntime.HttpResponse import class SmithyXML.Reader public struct RestXMLError { public let code: String public let message: String? public let requestID: String? + public var requestID2: String? { httpResponse.requestId2 } - public static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { - noErrorWrapping ? responseReader : responseReader["Error"] - } + public let httpResponse: HttpResponse + private let responseReader: Reader + public let errorBodyReader: Reader - public init(responseReader: Reader, noErrorWrapping: Bool) throws { - let reader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) - let code: String? = try reader["Code"].readIfPresent() - let message: String? = try reader["Message"].readIfPresent() + public init(httpResponse: HttpResponse, responseReader: Reader, noErrorWrapping: Bool) throws { + self.errorBodyReader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) + let code: String? = try errorBodyReader["Code"].readIfPresent() + guard let code else { throw BaseErrorDecodeError.missingRequiredData } + let message: String? = try errorBodyReader["Message"].readIfPresent() let requestID: String? = try responseReader["RequestId"].readIfPresent() - guard let code else { - throw RestXMLDecodeError.missingRequiredData - } self.code = code self.message = message self.requestID = requestID + self.httpResponse = httpResponse + self.responseReader = responseReader } - public init(code: String, message: String?, requestID: String?) { - self.code = code - self.message = message - self.requestID = requestID + private static func errorBodyReader(responseReader: Reader, noErrorWrapping: Bool) -> Reader { + noErrorWrapping ? responseReader : responseReader["Error"] } } - -public enum RestXMLDecodeError: Error { - case missingRequiredData -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorNoErrorWrappingPayload.swift b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorNoErrorWrappingPayload.swift deleted file mode 100644 index 38fb2ae9531..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorNoErrorWrappingPayload.swift +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -public struct RestXMLErrorNoErrorWrappingPayload: Decodable { - public let errorCode: String - public let requestId: String - public let message: String? - enum CodingKeys: String, CodingKey { - case errorCode = "Code" - case requestId = "RequestId" - case message = "Message" - } -} diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorPayload.swift b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorPayload.swift deleted file mode 100644 index e04e226785f..00000000000 --- a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLErrorPayload.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -public struct RestXMLErrorPayload: Decodable { - public let errorCode: String - public let message: String? - enum CodingKeys: String, CodingKey { - case errorCode = "Code" - case message = "Message" - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt index 1592ba5b04c..f3a696341d9 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSClientRuntimeTypes.kt @@ -10,9 +10,11 @@ import software.amazon.smithy.swift.codegen.model.buildSymbol object AWSClientRuntimeTypes { + object AWSQuery { + val AWSQueryError = runtimeSymbol("AWSQueryError") + } object EC2Query { - val Ec2NarrowedResponse = runtimeSymbol("Ec2NarrowedResponse") - val Ec2QueryError = runtimeSymbol("Ec2QueryError") + val EC2QueryError = runtimeSymbol("EC2QueryError") } object AWSJSON { val AWSJSONError = runtimeSymbol("AWSJSONError") @@ -24,7 +26,6 @@ object AWSClientRuntimeTypes { object RestXML { val RestXMLError = runtimeSymbol("RestXMLError") - val ErrorResponseContainer = runtimeSymbol("ErrorResponseContainer") object S3 { val AWSS3ServiceError = runtimeSymbol("AWSS3ServiceError") val AWSS3ErrorWith200StatusXMLMiddleware = runtimeSymbol("AWSS3ErrorWith200StatusXMLMiddleware") diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt index 2eca7f9857e..a0dbbcada83 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt @@ -5,6 +5,7 @@ package software.amazon.smithy.aws.swift.codegen.awsjson +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator @@ -33,7 +34,7 @@ open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat, XMLHttpResponseBindingOutputGenerator(), AWSJsonHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat) + XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat, AWSClientRuntimeTypes.AWSJSON.AWSJSONError) ) override val shouldRenderEncodableConformance: Boolean = true override val shouldRenderDecodableBodyStructForInputShapes: Boolean = true diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt index 1a120783183..f11a362fe72 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt @@ -5,6 +5,7 @@ package software.amazon.smithy.aws.swift.codegen.awsjson +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator @@ -33,7 +34,7 @@ class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat, XMLHttpResponseBindingOutputGenerator(), AWSJsonHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat), + XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat, AWSClientRuntimeTypes.AWSJSON.AWSJSONError), ) override val shouldRenderEncodableConformance: Boolean = true override val shouldRenderDecodableBodyStructForInputShapes: Boolean = true diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryFormURLEncodeCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryFormURLEncodeCustomizations.kt deleted file mode 100644 index 38a05c2ec2d..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryFormURLEncodeCustomizations.kt +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.awsquery - -import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.swift.codegen.integration.serde.formurl.FormURLEncodeCustomizable -import software.amazon.smithy.swift.codegen.integration.serde.xml.trait.XMLNameTraitGenerator - -class AwsQueryFormURLEncodeCustomizations : FormURLEncodeCustomizable { - override fun alwaysUsesFlattenedCollections(): Boolean { - return false - } - - override fun customNameTraitGenerator(memberShape: Shape, defaultName: String): String { - return XMLNameTraitGenerator.construct(memberShape, defaultName).toString() - } - - override fun shouldSerializeEmptyLists(): Boolean { - return true - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt index b390a35fab2..bc26166d436 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt @@ -5,6 +5,7 @@ package software.amazon.smithy.aws.swift.codegen.awsquery +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver @@ -43,7 +44,8 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { AWSQueryHttpResponseBindingErrorGenerator(), XMLHttpResponseBindingErrorInitGenerator( defaultTimestampFormat, - AWSEc2QueryHttpResponseTraitPayloadFactory() + AWSClientRuntimeTypes.AWSQuery.AWSQueryError, + AWSEc2QueryHttpResponseTraitPayloadFactory(), ) ) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt index 4f997276f84..a5f86718aeb 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt @@ -11,5 +11,5 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPRespons class AWSQueryHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.Ec2QueryError + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.AWSQuery.AWSQueryError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt index a1ffec508a5..57692a16ab0 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt @@ -17,13 +17,12 @@ import software.amazon.smithy.swift.codegen.model.expectShape class Route53InvalidBatchErrorIntegration : SwiftIntegration { override fun enabledForService(model: Model, settings: SwiftSettings): Boolean { - return model.expectShape(settings.service).isRoute53 +// return model.expectShape(settings.service).isRoute53 + return false } override val sectionWriters: List - get() = listOf( - SectionWriterBinding(HTTPResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBindingErrorGenerator) - ) + get() = emptyList() private val httpResponseBindingErrorGenerator = SectionWriter { writer, previousCode -> val operationErrorName = writer.getContext("operationErrorName") as String diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt index 5f35beed020..0714fb62f73 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt @@ -34,7 +34,7 @@ class S3ErrorIntegration : SwiftIntegration { SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInit, s3MembersParams), SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInitMemberAssignment, s3MembersAssignment), SectionWriterBinding(StructureGenerator.AdditionalErrorMembers, s3Members), - SectionWriterBinding(HTTPResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBinding) +// SectionWriterBinding(HTTPResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBinding) ) @@ -52,7 +52,7 @@ class S3ErrorIntegration : SwiftIntegration { } private val s3MembersAssignment = SectionWriter { writer, _ -> - writer.write("value.requestID2 = requestID2") + writer.write("value.requestID2 = baseError.requestID2") } private val s3Members = SectionWriter { writer, _ -> diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index 684d7e78dbd..6f0abfb8a81 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -5,6 +5,7 @@ package software.amazon.smithy.aws.swift.codegen.ec2query +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver @@ -43,7 +44,8 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { AWSEc2QueryHttpResponseBindingErrorGenerator(), XMLHttpResponseBindingErrorInitGenerator( defaultTimestampFormat, - AWSEc2QueryHttpResponseTraitPayloadFactory() + AWSClientRuntimeTypes.EC2Query.EC2QueryError, + AWSEc2QueryHttpResponseTraitPayloadFactory(), ) ) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt index b5f0ebc6af5..19fd03cc981 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt @@ -11,5 +11,5 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPRespons class AWSEc2QueryHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.Ec2QueryError + override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.EC2QueryError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt index 8771a4ad424..fb8bdd9c8b1 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt @@ -4,6 +4,7 @@ */ package software.amazon.smithy.aws.swift.codegen.restjson +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator @@ -26,7 +27,10 @@ class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat, XMLHttpResponseBindingOutputGenerator(), AWSRestJson1HttpResponseBindingErrorGeneratable(), - XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat) + XMLHttpResponseBindingErrorInitGenerator( + defaultTimestampFormat, + AWSClientRuntimeTypes.RestJSON.RestJSONError, + ) ) override val testsToIgnore = setOf( "SDKAppliedContentEncoding_restJson1", diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt index b3a9b6646fb..4b7727fe40e 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt @@ -5,6 +5,7 @@ package software.amazon.smithy.aws.swift.codegen.restxml +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator @@ -28,7 +29,8 @@ class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { AWSRestXMLHttpResponseBindingErrorGenerator(), XMLHttpResponseBindingErrorInitGenerator( defaultTimestampFormat, - AWSXMLHttpResponseTraitPayloadFactory() + AWSClientRuntimeTypes.RestXML.RestXMLError, + AWSXMLHttpResponseTraitPayloadFactory(), ) ) override val shouldRenderDecodableBodyStructForInputShapes = false diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index 398228d3e0d..a2098498654 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -19,24 +19,25 @@ class AWSJsonHttpInitialRequestTests { "/Example/models/TestStream+MessageMarshallable.swift" ) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - extension InitialRequestTestClientTypes.TestStream: ClientRuntime.MessageMarshallable { - public func marshall(encoder: ClientRuntime.RequestEncoder) throws -> ClientRuntime.EventStream.Message { - var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] - var payload: ClientRuntime.Data? = nil - switch self { - case .messagewithstring(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithString"))) - headers.append(.init(name: ":content-type", value: .string("text/plain"))) - payload = value.data?.data(using: .utf8) - case .sdkUnknown(_): - throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") - } - return ClientRuntime.EventStream.Message(headers: headers, payload: payload ?? .init()) - } + val expectedContents = """ +extension InitialRequestTestClientTypes.TestStream { + static var marshal: ClientRuntime.MarshalClosure { + { (self) in + var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] + var payload: ClientRuntime.Data? = nil + switch self { + case messagewithstring(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithString"))) + headers.append(.init(name: ":content-type", value: .string("text/plain"))) + payload = value.data?.data(using: .utf8) + case .sdkUnknown(_): + throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } - """.trimIndent() + return ClientRuntime.EventStream.Message(headers: headers, payload: payload ?? .init()) + } + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } @@ -66,27 +67,19 @@ class AWSJsonHttpInitialRequestTests { ) val contents = TestUtils.getFileContents( context.manifest, - "/Example/models/EventStreamOpInput+Encodable.swift" + "/Example/models/EventStreamOpInput+Write.swift" ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - extension EventStreamOpInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case inputMember1 - case inputMember2 - } +extension EventStreamOpInput { - public func encode(to encoder: Swift.Encoder) throws { - var encodeContainer = encoder.container(keyedBy: CodingKeys.self) - if let inputMember1 = self.inputMember1 { - try encodeContainer.encode(inputMember1, forKey: .inputMember1) - } - if let inputMember2 = self.inputMember2 { - try encodeContainer.encode(inputMember2, forKey: .inputMember2) - } - } - } - """.trimIndent() + static func write(value: EventStreamOpInput?, to writer: SmithyJSON.Writer) throws { + guard let value else { writer.detach(); return } + try writer["inputMember1"].write(value.inputMember1) + try writer["inputMember2"].write(value.inputMember2) + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt index 0f59a0c7765..86bac397c39 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt @@ -25,8 +25,6 @@ extension ChecksumTestsClient { /// - Returns: `SomeOperationOutput` : [no documentation found] public func someOperation(input: SomeOperationInput) async throws -> SomeOperationOutput { let context = ClientRuntime.HttpContextBuilder() - .withEncoder(value: encoder) - .withDecoder(value: decoder) .withMethod(value: .post) .withServiceName(value: serviceName) .withOperation(value: "someOperation") @@ -55,7 +53,7 @@ extension ChecksumTestsClient { operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(SomeOperationOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(SomeOperationOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(SomeOperationOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.FlexibleChecksumsResponseMiddleware(validationMode: true)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) @@ -63,7 +61,7 @@ extension ChecksumTestsClient { } } - """.trimIndent() +""" contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index f3bc76f535a..e03313c9799 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -1,5 +1,6 @@ package software.amazon.smithy.aws.swift.codegen.restxml +import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils @@ -20,7 +21,8 @@ class AWSRestXMLEventStreamTests { contents.shouldSyntacticSanityCheck() val expectedContents = """ operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: nil, marshalClosure: EventStreamTestClientTypes.TestEvents.marshal)) - """.trimIndent() +""" + contents.shouldContainOnlyOnce(expectedContents) } @Test @@ -35,31 +37,32 @@ class AWSRestXMLEventStreamTests { ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - extension EventStreamTestClientTypes.TestEvents { - static var marshal: ClientRuntime.MarshalClosure { - { (self) in - var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] - var payload: ClientRuntime.Data? = nil - switch self { - case messageevent(let value): - headers.append(.init(name: ":event-type", value: .string("MessageEvent"))) - headers.append(.init(name: ":content-type", value: .string("text/plain"))) - payload = value.data?.data(using: .utf8) - case audioevent(let value): - headers.append(.init(name: ":event-type", value: .string("AudioEvent"))) - if let headerValue = value.exampleHeader { - headers.append(.init(name: "exampleHeader", value: .string(headerValue))) - } - headers.append(.init(name: ":content-type", value: .string("application/xml"))) - payload = try SmithyXML.XMLReadWrite.documentWritingClosure(rootNodeInfo: "Audio")(value, EventStreamTestClientTypes.Audio.writingClosure(_:to:)) - case .sdkUnknown(_): - throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") - } - return ClientRuntime.EventStream.Message(headers: headers, payload: payload ?? .init()) +extension EventStreamTestClientTypes.TestEvents { + static var marshal: ClientRuntime.MarshalClosure { + { (self) in + var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] + var payload: ClientRuntime.Data? = nil + switch self { + case messageevent(let value): + headers.append(.init(name: ":event-type", value: .string("MessageEvent"))) + headers.append(.init(name: ":content-type", value: .string("text/plain"))) + payload = value.data?.data(using: .utf8) + case audioevent(let value): + headers.append(.init(name: ":event-type", value: .string("AudioEvent"))) + if let headerValue = value.exampleHeader { + headers.append(.init(name: "exampleHeader", value: .string(headerValue))) } + headers.append(.init(name: ":content-type", value: .string("application/xml"))) + payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "Audio")(value, EventStreamTestClientTypes.Audio.write(value:to:)) + case .sdkUnknown(_): + throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } + return ClientRuntime.EventStream.Message(headers: headers, payload: payload ?? .init()) } - """.trimIndent() + } +} +""" + contents.shouldContainOnlyOnce(expectedContents) } @Test @@ -70,29 +73,28 @@ class AWSRestXMLEventStreamTests { ) val contents = TestUtils.getFileContents( context.manifest, - "/Example/models/MessageWithAudio+Codable.swift" + "/Example/models/MessageWithAudio+ReadWrite.swift" ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - extension EventStreamTestClientTypes.MessageWithAudio { +extension EventStreamTestClientTypes.MessageWithAudio { - static func writingClosure(_ value: EventStreamTestClientTypes.MessageWithAudio?, to writer: SmithyXML.Writer) throws { - guard let value else { writer.detach(); return } - try writer["audio"].write(value.audio, writingClosure: EventStreamTestClientTypes.Audio.writingClosure(_:to:)) - try writer["exampleHeader"].write(value.exampleHeader) - } + static func write(value: EventStreamTestClientTypes.MessageWithAudio?, to writer: SmithyXML.Writer) throws { + guard let value else { writer.detach(); return } + try writer["audio"].write(value.audio, writingClosure: EventStreamTestClientTypes.Audio.write(value:to:)) + try writer["exampleHeader"].write(value.exampleHeader) + } - static var readingClosure: SmithyReadWrite.ReadingClosure { - return { reader in - guard reader.content != nil || Mirror(reflecting: self).children.isEmpty else { return nil } - var value = EventStreamTestClientTypes.MessageWithAudio() - value.exampleHeader = try reader["exampleHeader"].readIfPresent() - value.audio = try reader["audio"].readIfPresent(readingClosure: EventStreamTestClientTypes.Audio.readingClosure) - return value - } - } - } + static func read(from reader: SmithyXML.Reader) throws -> EventStreamTestClientTypes.MessageWithAudio { + guard reader.hasContent else { throw SmithyReadWrite.ReaderError.requiredValueNotPresent } + var value = EventStreamTestClientTypes.MessageWithAudio() + value.exampleHeader = try reader["exampleHeader"].readIfPresent() + value.audio = try reader["audio"].readIfPresent(with: EventStreamTestClientTypes.Audio.read(from:)) + return value + } +} """.trimIndent() + contents.shouldContainOnlyOnce(expectedContents) } @Test @@ -107,23 +109,22 @@ class AWSRestXMLEventStreamTests { ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - extension EventStreamTestClientTypes.Audio { +extension EventStreamTestClientTypes.Audio { - static func writingClosure(_ value: EventStreamTestClientTypes.Audio?, to writer: SmithyXML.Writer) throws { - guard let value else { writer.detach(); return } - try writer["rawAudio"].write(value.rawAudio) - } + static func write(value: EventStreamTestClientTypes.Audio?, to writer: SmithyXML.Writer) throws { + guard let value else { writer.detach(); return } + try writer["rawAudio"].write(value.rawAudio) + } - static var readingClosure: SmithyReadWrite.ReadingClosure { - return { reader in - guard reader.content != nil || Mirror(reflecting: self).children.isEmpty else { return nil } - var value = EventStreamTestClientTypes.Audio() - value.rawAudio = try reader["rawAudio"].readIfPresent() - return value - } - } - } + static func read(from reader: SmithyXML.Reader) throws -> EventStreamTestClientTypes.Audio { + guard reader.hasContent else { throw SmithyReadWrite.ReaderError.requiredValueNotPresent } + var value = EventStreamTestClientTypes.Audio() + value.rawAudio = try reader["rawAudio"].readIfPresent() + return value + } +} """.trimIndent() + contents.shouldContainOnlyOnce(expectedContents) } private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { From 3316fab7b1daffd9bae8d14e576cf9f7ae1fd394 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 15 Apr 2024 17:48:26 -0500 Subject: [PATCH 06/27] Fix Swift & codegen tests --- .../Protocols/Ec2Query/EC2QueryError.swift | 1 + .../AWSMessageDecoderStreamTests.swift | 2 +- .../AWSMessageEncoderStreamTests.swift | 6 +- .../EventStream/EventStreamTestData.swift | 40 ++- .../Ec2Query/Ec2ErrorRequestIdTests.swift | 36 +- .../RestJSON/RestJSONErrorTests.swift | 63 ++-- .../aws/swift/codegen/EventStreamTests.kt | 310 +++++++++-------- .../swift/codegen/PresignerGeneratorTests.kt | 44 +-- .../awsjson/AWSJsonHttpInitialRequestTests.kt | 36 +- ...nHttpResponseBindingErrorGeneratorTests.kt | 54 +-- .../awsquery/AWSQueryOperationStackTest.kt | 5 +- .../awsquery/BlobEncodeGeneratorTests.kt | 75 +--- .../ListEncodeFormURLGeneratorTests.kt | 112 +----- .../MapEncodeFormURLGeneratorTests.kt | 116 +------ ...yIdempotencyTokenAutoFillGeneratorTests.kt | 19 +- .../StructDecodeWrappedXMLGeneratorTests.kt | 4 +- .../awsquery/TimestampGeneratorTests.kt | 29 +- ...ttpResponseBindingErrorGeneratableTests.kt | 59 ++-- .../AWSRestJson1ProtocolGeneratorTests.kt | 328 ++++++++---------- ...oute53InvalidBatchErrorIntegrationTests.kt | 67 +--- ...yHttpResponseBindingErrorGeneratorTests.kt | 52 ++- .../restxml/AWSRestXMLEventStreamTests.kt | 8 +- ...LHttpResponseBindingErrorGeneratorTests.kt | 45 +-- .../serde/S3UnwrappedXMLOutputTraitTests.kt | 2 +- 24 files changed, 562 insertions(+), 951 deletions(-) diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift index 0bb42637fd5..d3dd690b37a 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift @@ -26,6 +26,7 @@ public struct EC2QueryError { guard let code else { throw BaseErrorDecodeError.missingRequiredData } let message: String? = try errorBodyReader["Message"].readIfPresent() let requestID: String? = try responseReader["RequestId"].readIfPresent() + ?? responseReader["RequestID"].readIfPresent() self.code = code self.message = message self.requestID = requestID diff --git a/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageDecoderStreamTests.swift b/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageDecoderStreamTests.swift index dc9321aad97..89f5d437c31 100644 --- a/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageDecoderStreamTests.swift +++ b/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageDecoderStreamTests.swift @@ -17,7 +17,7 @@ final class AWSMessageDecoderStreamTests: XCTestCase { let sut = EventStream.DefaultMessageDecoderStream( stream: bufferedStream, messageDecoder: messageDecoder, - unmarshalClosure: jsonUnmarshalClosure(responseDecoder: JSONDecoder()) + unmarshalClosure: TestEvent.unmarshal ) var events: [TestEvent] = [] diff --git a/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageEncoderStreamTests.swift b/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageEncoderStreamTests.swift index d07891243bb..ab26036e671 100644 --- a/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageEncoderStreamTests.swift +++ b/Tests/Core/AWSClientRuntimeTests/EventStream/AWSMessageEncoderStreamTests.swift @@ -57,7 +57,7 @@ final class AWSMessageEncoderStreamTests: XCTestCase { let sut = EventStream.DefaultMessageEncoderStream( stream: baseStream, messageEncoder: messageEncoder, - marshalClosure: jsonMarshalClosure(requestEncoder: JSONEncoder()), + marshalClosure: TestEvent.marshal, messageSigner: messageSigner, initialRequestMessage: nil ) @@ -95,7 +95,7 @@ final class AWSMessageEncoderStreamTests: XCTestCase { let sut = EventStream.DefaultMessageEncoderStream( stream: baseStream, messageEncoder: messageEncoder, - marshalClosure: jsonMarshalClosure(requestEncoder: JSONEncoder()), + marshalClosure: TestEvent.marshal, messageSigner: messageSigner, initialRequestMessage: nil ) @@ -138,7 +138,7 @@ final class AWSMessageEncoderStreamTests: XCTestCase { let sut = EventStream.DefaultMessageEncoderStream( stream: baseStream, messageEncoder: messageEncoder, - marshalClosure: jsonMarshalClosure(requestEncoder: JSONEncoder()), + marshalClosure: TestEvent.marshal, messageSigner: messageSigner, initialRequestMessage: EventStream.Message( headers: [EventStream.Header(name: ":event-type", value: .string("initial-request"))], diff --git a/Tests/Core/AWSClientRuntimeTests/EventStream/EventStreamTestData.swift b/Tests/Core/AWSClientRuntimeTests/EventStream/EventStreamTestData.swift index 119cb34f3f2..7df1d9b44b6 100644 --- a/Tests/Core/AWSClientRuntimeTests/EventStream/EventStreamTestData.swift +++ b/Tests/Core/AWSClientRuntimeTests/EventStream/EventStreamTestData.swift @@ -8,31 +8,35 @@ import ClientRuntime import Foundation -enum TestEvent: MessageMarshallable, MessageUnmarshallable { +enum TestEvent { case allHeaders case emptyPayload case noHeaders - init(message: ClientRuntime.EventStream.Message, decoder: ResponseDecoder) { - if message == validMessageWithAllHeaders { - self = .allHeaders - } else if message == validMessageEmptyPayload { - self = .emptyPayload - } else if message == validMessageNoHeaders { - self = .noHeaders - } else { - fatalError("Unknown message") + static var unmarshal: ClientRuntime.UnmarshalClosure { + { message in + if message == validMessageWithAllHeaders { + return .allHeaders + } else if message == validMessageEmptyPayload { + return .emptyPayload + } else if message == validMessageNoHeaders { + return .noHeaders + } else { + fatalError("Unknown message") + } } } - func marshall(encoder: RequestEncoder) -> ClientRuntime.EventStream.Message { - switch self { - case .allHeaders: - return validMessageWithAllHeaders - case .emptyPayload: - return validMessageEmptyPayload - case .noHeaders: - return validMessageNoHeaders + static var marshal: ClientRuntime.MarshalClosure { + { (self) in + switch self { + case .allHeaders: + return validMessageWithAllHeaders + case .emptyPayload: + return validMessageEmptyPayload + case .noHeaders: + return validMessageNoHeaders + } } } } diff --git a/Tests/Core/AWSClientRuntimeTests/Protocols/Ec2Query/Ec2ErrorRequestIdTests.swift b/Tests/Core/AWSClientRuntimeTests/Protocols/Ec2Query/Ec2ErrorRequestIdTests.swift index 7c8a817e7d1..a54c21773fa 100644 --- a/Tests/Core/AWSClientRuntimeTests/Protocols/Ec2Query/Ec2ErrorRequestIdTests.swift +++ b/Tests/Core/AWSClientRuntimeTests/Protocols/Ec2Query/Ec2ErrorRequestIdTests.swift @@ -27,8 +27,8 @@ class Ec2ErrorRequestIdTests: XCTestCase { """.utf8) let httpResponse = HttpResponse(body: .data(data), statusCode: .ok) - let response = try await responseClosure(Ec2Response.httpBinding, responseDocumentBinding)(httpResponse) - XCTAssertEqual(response.requestId, "abcdefg12345") + let response = try EC2QueryError(httpResponse: httpResponse, responseReader: Reader.from(data: data), noErrorWrapping: true) + XCTAssertEqual(response.requestID, "abcdefg12345") } func testEc2ResponseDecodesRequestId() async throws { @@ -44,35 +44,7 @@ class Ec2ErrorRequestIdTests: XCTestCase { """.utf8) let httpResponse = HttpResponse(body: .data(data), statusCode: .ok) - let response = try await responseClosure(Ec2Response.httpBinding, responseDocumentBinding)(httpResponse) - XCTAssertEqual(response.requestId, "abcdefg12345") - } - - func testEc2NarrowedResponseDecodesRequestID() async throws { - let data = Data(""" - - - Sample Error - - abcdefg12345 - - """.utf8) - let httpResponse = HttpResponse(body: .data(data), statusCode: .ok) - let response = try await responseClosure(Ec2Response.httpBinding, responseDocumentBinding)(httpResponse) - XCTAssertEqual(response.requestId, "abcdefg12345") - } - - func testEc2NarrowResponseDecodesRequestId() async throws { - let data = Data(""" - - - Sample Error - - abcdefg12345 - - """.utf8) - let httpResponse = HttpResponse(body: .data(data), statusCode: .ok) - let response = try await responseClosure(Ec2Response.httpBinding, responseDocumentBinding)(httpResponse) - XCTAssertEqual(response.requestId, "abcdefg12345") + let response = try EC2QueryError(httpResponse: httpResponse, responseReader: Reader.from(data: data), noErrorWrapping: true) + XCTAssertEqual(response.requestID, "abcdefg12345") } } diff --git a/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift b/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift index d53b8842952..d20c1d586c2 100644 --- a/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift +++ b/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift @@ -3,6 +3,8 @@ * SPDX-License-Identifier: Apache-2.0. */ +import SmithyReadWrite +import SmithyJSON import ClientRuntime import SmithyTestUtil import XCTest @@ -27,9 +29,7 @@ class RestJSONErrorTests: HttpResponseTestBase { return } - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - let greetingWithErrorsError = try await GreetingWithErrorsError.makeError(httpResponse: httpResponse, decoder: decoder) + let greetingWithErrorsError = try await wireResponseErrorClosure(GreetingWithErrorsError.httpErrorBinding, wireResponseDocumentBinding())(httpResponse) if let actual = greetingWithErrorsError as? ComplexError { let expected = ComplexError( @@ -53,7 +53,7 @@ class RestJSONErrorTests: HttpResponseTestBase { ] for errorName in errorNames { - XCTAssertEqual(RestJSONError.sanitizeErrorType(errorName), "FooError") + XCTAssertEqual(sanitizeErrorType(errorName), "FooError") } } } @@ -79,47 +79,34 @@ struct ComplexErrorBody { public let topLevel: String? } -extension ComplexErrorBody: Decodable { - private enum CodingKeys: String, CodingKey { - case TopLevel - } - - public init (from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - topLevel = try values.decodeIfPresent(String.self, forKey: .TopLevel) - } -} - extension ComplexError { - public init (httpResponse: HttpResponse, decoder: ResponseDecoder? = nil, message: String? = nil, requestID: String? = nil) async throws { - if let Header = httpResponse.headers.value(for: "X-Header") { - self.header = Header - } else { - self.header = nil - } - - if case .data(let data) = httpResponse.body, - let unwrappedData = data, - let responseDecoder = decoder { - let output: ComplexErrorBody = try responseDecoder.decode(responseBody: unwrappedData) - self.topLevel = output.topLevel + static func makeError(baseError: AWSClientRuntime.RestJSONError) throws -> ComplexError { + let reader = baseError.errorBodyReader + var value = ComplexError() + if let Header = baseError.httpResponse.headers.value(for: "X-Header") { + value.header = Header } else { - self.topLevel = nil + value.header = nil } - self.httpResponse = httpResponse - self.message = message - self.requestID = requestID + value.topLevel = try reader["TopLevel"].readIfPresent() + value.httpResponse = baseError.httpResponse + value.message = baseError.message + value.requestID = baseError.requestID + return value } } -public enum GreetingWithErrorsError: HttpResponseErrorBinding { - public static func makeError(httpResponse: ClientRuntime.HttpResponse, decoder: ClientRuntime.ResponseDecoder?) async throws -> Error { - let errorDetails = try await RestJSONError(httpResponse: httpResponse) - let requestID = httpResponse.requestId - switch errorDetails.errorType { - case "ComplexError": return try await ComplexError(httpResponse: httpResponse, decoder: decoder, message: errorDetails.errorMessage, requestID: requestID) - default: return UnknownAWSHTTPServiceError(message: errorDetails.errorMessage, httpResponse: httpResponse) +public enum GreetingWithErrorsError { + + static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { + { httpResponse, responseDocumentClosure in + let responseReader = try await responseDocumentClosure(httpResponse) + let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + } } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt index ee0fcfdf377..f0984c956a4 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt @@ -12,78 +12,80 @@ class EventStreamTests { val context = setupTests("eventstream.smithy", "aws.protocoltests.restjson#TestService") val contents = getFileContents(context.manifest, "/Example/models/TestStream+MessageMarshallable.swift") val expected = """ -extension EventStreamTestClientTypes.TestStream: ClientRuntime.MessageMarshallable { - public func marshall(encoder: ClientRuntime.RequestEncoder) throws -> ClientRuntime.EventStream.Message { - var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] - var payload: ClientRuntime.Data? = nil - switch self { - case .messagewithblob(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithBlob"))) - headers.append(.init(name: ":content-type", value: .string("application/octet-stream"))) - payload = value.data - case .messagewithstring(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithString"))) - headers.append(.init(name: ":content-type", value: .string("text/plain"))) - payload = value.data?.data(using: .utf8) - case .messagewithstruct(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithStruct"))) - headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try encoder.encode(value) - case .messagewithunion(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithUnion"))) - headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try encoder.encode(value) - case .messagewithheaders(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithHeaders"))) - if let headerValue = value.blob { - headers.append(.init(name: "blob", value: .byteArray(headerValue))) - } - if let headerValue = value.boolean { - headers.append(.init(name: "boolean", value: .bool(headerValue))) - } - if let headerValue = value.byte { - headers.append(.init(name: "byte", value: .byte(headerValue))) - } - if let headerValue = value.int { - headers.append(.init(name: "int", value: .int32(Int32(headerValue)))) - } - if let headerValue = value.long { - headers.append(.init(name: "long", value: .int64(Int64(headerValue)))) - } - if let headerValue = value.short { - headers.append(.init(name: "short", value: .int16(headerValue))) - } - if let headerValue = value.string { - headers.append(.init(name: "string", value: .string(headerValue))) - } - if let headerValue = value.timestamp { - headers.append(.init(name: "timestamp", value: .timestamp(headerValue))) - } - case .messagewithheaderandpayload(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithHeaderAndPayload"))) - if let headerValue = value.header { - headers.append(.init(name: "header", value: .string(headerValue))) - } - headers.append(.init(name: ":content-type", value: .string("application/octet-stream"))) - payload = value.payload - case .messagewithnoheaderpayloadtraits(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithNoHeaderPayloadTraits"))) - headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder)(value, JSONReadWrite.writingClosure()) - case .messagewithunboundpayloadtraits(let value): - headers.append(.init(name: ":event-type", value: .string("MessageWithUnboundPayloadTraits"))) - if let headerValue = value.header { - headers.append(.init(name: "header", value: .string(headerValue))) +extension EventStreamTestClientTypes.TestStream { + static var marshal: ClientRuntime.MarshalClosure { + { (self) in + var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] + var payload: ClientRuntime.Data? = nil + switch self { + case messagewithblob(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithBlob"))) + headers.append(.init(name: ":content-type", value: .string("application/octet-stream"))) + payload = value.data + case messagewithstring(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithString"))) + headers.append(.init(name: ":content-type", value: .string("text/plain"))) + payload = value.data?.data(using: .utf8) + case messagewithstruct(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithStruct"))) + headers.append(.init(name: ":content-type", value: .string("application/json"))) + payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.TestStruct.write(value:to:)) + case messagewithunion(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithUnion"))) + headers.append(.init(name: ":content-type", value: .string("application/json"))) + payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.TestUnion.write(value:to:)) + case messagewithheaders(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithHeaders"))) + if let headerValue = value.blob { + headers.append(.init(name: "blob", value: .byteArray(headerValue))) + } + if let headerValue = value.boolean { + headers.append(.init(name: "boolean", value: .bool(headerValue))) + } + if let headerValue = value.byte { + headers.append(.init(name: "byte", value: .byte(headerValue))) + } + if let headerValue = value.int { + headers.append(.init(name: "int", value: .int32(Int32(headerValue)))) + } + if let headerValue = value.long { + headers.append(.init(name: "long", value: .int64(Int64(headerValue)))) + } + if let headerValue = value.short { + headers.append(.init(name: "short", value: .int16(headerValue))) + } + if let headerValue = value.string { + headers.append(.init(name: "string", value: .string(headerValue))) + } + if let headerValue = value.timestamp { + headers.append(.init(name: "timestamp", value: .timestamp(headerValue))) + } + case messagewithheaderandpayload(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithHeaderAndPayload"))) + if let headerValue = value.header { + headers.append(.init(name: "header", value: .string(headerValue))) + } + headers.append(.init(name: ":content-type", value: .string("application/octet-stream"))) + payload = value.payload + case messagewithnoheaderpayloadtraits(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithNoHeaderPayloadTraits"))) + headers.append(.init(name: ":content-type", value: .string("application/json"))) + payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.write(value:to:)) + case messagewithunboundpayloadtraits(let value): + headers.append(.init(name: ":event-type", value: .string("MessageWithUnboundPayloadTraits"))) + if let headerValue = value.header { + headers.append(.init(name: "header", value: .string(headerValue))) + } + headers.append(.init(name: ":content-type", value: .string("application/json"))) + payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.MessageWithUnboundPayloadTraits.write(value:to:)) + case .sdkUnknown(_): + throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } - headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder)(value, JSONReadWrite.writingClosure()) - case .sdkUnknown(_): - throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") + return ClientRuntime.EventStream.Message(headers: headers, payload: payload ?? .init()) } - return ClientRuntime.EventStream.Message(headers: headers, payload: payload ?? .init()) } } - """.trimIndent() +""" contents.shouldContainOnlyOnce(expected) } @@ -92,94 +94,96 @@ extension EventStreamTestClientTypes.TestStream: ClientRuntime.MessageMarshallab val context = setupTests("eventstream.smithy", "aws.protocoltests.restjson#TestService") val contents = getFileContents(context.manifest, "/Example/models/TestStream+MessageUnmarshallable.swift") val expected = """ -extension EventStreamTestClientTypes.TestStream: ClientRuntime.MessageUnmarshallable { - public init(message: ClientRuntime.EventStream.Message, decoder: ClientRuntime.ResponseDecoder) throws { - switch try message.type() { - case .event(let params): - switch params.eventType { - case "MessageWithBlob": - var event = EventStreamTestClientTypes.MessageWithBlob() - event.data = message.payload - self = .messagewithblob(event) - case "MessageWithString": - var event = EventStreamTestClientTypes.MessageWithString() - event.data = String(data: message.payload, encoding: .utf8) - self = .messagewithstring(event) - case "MessageWithStruct": - var event = EventStreamTestClientTypes.MessageWithStruct() - event.someStruct = .init(try decoder.decode(responseBody: message.payload)) - self = .messagewithstruct(event) - case "MessageWithUnion": - var event = EventStreamTestClientTypes.MessageWithUnion() - event.someUnion = .init(try decoder.decode(responseBody: message.payload)) - self = .messagewithunion(event) - case "MessageWithHeaders": - var event = EventStreamTestClientTypes.MessageWithHeaders() - if case let .byteArray(value) = message.headers.value(name: "blob") { - event.blob = value - } - if case let .bool(value) = message.headers.value(name: "boolean") { - event.boolean = value - } - if case let .byte(value) = message.headers.value(name: "byte") { - event.byte = value - } - if case let .int32(value) = message.headers.value(name: "int") { - event.int = Int(value) - } - if case let .int64(value) = message.headers.value(name: "long") { - event.long = Int(value) - } - if case let .int16(value) = message.headers.value(name: "short") { - event.short = value - } - if case let .string(value) = message.headers.value(name: "string") { - event.string = value - } - if case let .timestamp(value) = message.headers.value(name: "timestamp") { - event.timestamp = value - } - self = .messagewithheaders(event) - case "MessageWithHeaderAndPayload": - var event = EventStreamTestClientTypes.MessageWithHeaderAndPayload() - if case let .string(value) = message.headers.value(name: "header") { - event.header = value - } - event.payload = message.payload - self = .messagewithheaderandpayload(event) - case "MessageWithNoHeaderPayloadTraits": - self = .messagewithnoheaderpayloadtraits(try decoder.decode(responseBody: message.payload)) - case "MessageWithUnboundPayloadTraits": - var event = EventStreamTestClientTypes.MessageWithUnboundPayloadTraits() - if case let .string(value) = message.headers.value(name: "header") { - event.header = value - } - event.unboundString = try decoder.decode(responseBody: message.payload) - self = .messagewithunboundpayloadtraits(event) - default: - self = .sdkUnknown("error processing event stream, unrecognized event: \(params.eventType)") - } - case .exception(let params): - let makeError: (ClientRuntime.EventStream.Message, ClientRuntime.EventStream.MessageType.ExceptionParams) throws -> Swift.Error = { message, params in - switch params.exceptionType { - case "SomeError": - return try decoder.decode(responseBody: message.payload) as SomeError +extension EventStreamTestClientTypes.TestStream { + static var unmarshal: ClientRuntime.UnmarshalClosure { + { message in + switch try message.type() { + case .event(let params): + switch params.eventType { + case "MessageWithBlob": + var event = EventStreamTestClientTypes.MessageWithBlob() + event.data = message.payload + return .messagewithblob(event) + case "MessageWithString": + var event = EventStreamTestClientTypes.MessageWithString() + event.data = String(data: message.payload, encoding: .utf8) + return .messagewithstring(event) + case "MessageWithStruct": + var event = EventStreamTestClientTypes.MessageWithStruct() + event.someStruct = try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, EventStreamTestClientTypes.TestStruct.read(from:)) + return .messagewithstruct(event) + case "MessageWithUnion": + var event = EventStreamTestClientTypes.MessageWithUnion() + event.someUnion = try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, EventStreamTestClientTypes.TestUnion.read(from:)) + return .messagewithunion(event) + case "MessageWithHeaders": + var event = EventStreamTestClientTypes.MessageWithHeaders() + if case .byteArray(let value) = message.headers.value(name: "blob") { + event.blob = value + } + if case .bool(let value) = message.headers.value(name: "boolean") { + event.boolean = value + } + if case .byte(let value) = message.headers.value(name: "byte") { + event.byte = value + } + if case .int32(let value) = message.headers.value(name: "int") { + event.int = Int(value) + } + if case .int64(let value) = message.headers.value(name: "long") { + event.long = Int(value) + } + if case .int16(let value) = message.headers.value(name: "short") { + event.short = value + } + if case .string(let value) = message.headers.value(name: "string") { + event.string = value + } + if case .timestamp(let value) = message.headers.value(name: "timestamp") { + event.timestamp = value + } + return .messagewithheaders(event) + case "MessageWithHeaderAndPayload": + var event = EventStreamTestClientTypes.MessageWithHeaderAndPayload() + if case .string(let value) = message.headers.value(name: "header") { + event.header = value + } + event.payload = message.payload + return .messagewithheaderandpayload(event) + case "MessageWithNoHeaderPayloadTraits": + return .messagewithnoheaderpayloadtraits(try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.read(from:))) + case "MessageWithUnboundPayloadTraits": + var event = EventStreamTestClientTypes.MessageWithUnboundPayloadTraits() + if case .string(let value) = message.headers.value(name: "header") { + event.header = value + } + event.unboundString = try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, Swift.String.read(from:)) + return .messagewithunboundpayloadtraits(event) default: - let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok) - return AWSClientRuntime.UnknownAWSHTTPServiceError(httpResponse: httpResponse, message: "error processing event stream, unrecognized ':exceptionType': \(params.exceptionType); contentType: \(params.contentType ?? "nil")", requestID: nil, typeName: nil) + return .sdkUnknown("error processing event stream, unrecognized event: \(params.eventType)") } + case .exception(let params): + let makeError: (ClientRuntime.EventStream.Message, ClientRuntime.EventStream.MessageType.ExceptionParams) throws -> Swift.Error = { message, params in + switch params.exceptionType { + case "SomeError": + return try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, SomeError.read(from:)) + default: + let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok) + return AWSClientRuntime.UnknownAWSHTTPServiceError(httpResponse: httpResponse, message: "error processing event stream, unrecognized ':exceptionType': \(params.exceptionType); contentType: \(params.contentType ?? "nil")", requestID: nil, typeName: nil) + } + } + let error = try makeError(message, params) + throw error + case .error(let params): + let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok) + throw AWSClientRuntime.UnknownAWSHTTPServiceError(httpResponse: httpResponse, message: "error processing event stream, unrecognized ':errorType': \(params.errorCode); message: \(params.message ?? "nil")", requestID: nil, typeName: nil) + case .unknown(messageType: let messageType): + throw ClientRuntime.ClientError.unknownError("unrecognized event stream message ':message-type': \(messageType)") } - let error = try makeError(message, params) - throw error - case .error(let params): - let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok) - throw AWSClientRuntime.UnknownAWSHTTPServiceError(httpResponse: httpResponse, message: "error processing event stream, unrecognized ':errorType': \(params.errorCode); message: \(params.message ?? "nil")", requestID: nil, typeName: nil) - case .unknown(messageType: let messageType): - throw ClientRuntime.ClientError.unknownError("unrecognized event stream message ':message-type': \(messageType)") } } } - """.trimIndent() +""" contents.shouldContainOnlyOnce(expected) } @@ -190,8 +194,6 @@ extension EventStreamTestClientTypes.TestStream: ClientRuntime.MessageUnmarshall var expected = """ public func testStreamOp(input: TestStreamOpInput) async throws -> TestStreamOpOutput { let context = ClientRuntime.HttpContextBuilder() - .withEncoder(value: encoder) - .withDecoder(value: decoder) .withMethod(value: .post) .withServiceName(value: serviceName) .withOperation(value: "testStreamOp") @@ -216,11 +218,11 @@ extension EventStreamTestClientTypes.TestStream: ClientRuntime.MessageUnmarshall operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.value, defaultBody: "{}", marshalClosure: jsonMarshalClosure(requestEncoder: encoder))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.value, defaultBody: "{}", marshalClosure: EventStreamTestClientTypes.TestStream.marshal)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(TestStreamOpOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(TestStreamOpOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(TestStreamOpOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt index 3ac3d4844f6..f14fa325532 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt @@ -16,15 +16,7 @@ extension GetFooInput { public func presign(config: ExampleClient.ExampleClientConfiguration, expiration: Foundation.TimeInterval) async throws -> ClientRuntime.SdkHttpRequest? { let serviceName = "example" let input = self - let encoder = ClientRuntime.JSONEncoder() - encoder.dateEncodingStrategy = .secondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") - let decoder = ClientRuntime.JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") let context = ClientRuntime.HttpContextBuilder() - .withEncoder(value: encoder) - .withDecoder(value: decoder) .withMethod(value: .get) .withServiceName(value: serviceName) .withOperation(value: "getFoo") @@ -51,7 +43,7 @@ extension GetFooInput { operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(GetFooOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(GetFooOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(GetFooOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: GetFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { @@ -73,15 +65,7 @@ extension PostFooInput { public func presign(config: ExampleClient.ExampleClientConfiguration, expiration: Foundation.TimeInterval) async throws -> ClientRuntime.SdkHttpRequest? { let serviceName = "example" let input = self - let encoder = ClientRuntime.JSONEncoder() - encoder.dateEncodingStrategy = .secondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") - let decoder = ClientRuntime.JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") let context = ClientRuntime.HttpContextBuilder() - .withEncoder(value: encoder) - .withDecoder(value: decoder) .withMethod(value: .post) .withServiceName(value: serviceName) .withOperation(value: "postFoo") @@ -107,11 +91,11 @@ extension PostFooInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder), inputWritingClosure: JSONReadWrite.writingClosure())) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: ""), inputWritingClosure: PostFooInput.write(value:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(PostFooOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(PostFooOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(PostFooOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PostFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { @@ -133,15 +117,7 @@ extension PutFooInput { public func presign(config: ExampleClient.ExampleClientConfiguration, expiration: Foundation.TimeInterval) async throws -> ClientRuntime.SdkHttpRequest? { let serviceName = "example" let input = self - let encoder = ClientRuntime.JSONEncoder() - encoder.dateEncodingStrategy = .secondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") - let decoder = ClientRuntime.JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") let context = ClientRuntime.HttpContextBuilder() - .withEncoder(value: encoder) - .withDecoder(value: decoder) .withMethod(value: .put) .withServiceName(value: serviceName) .withOperation(value: "putFoo") @@ -167,11 +143,11 @@ extension PutFooInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder), inputWritingClosure: JSONReadWrite.writingClosure())) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: ""), inputWritingClosure: PutFooInput.write(value:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(PutFooOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(PutFooOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(PutFooOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PutFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { @@ -193,12 +169,6 @@ extension PutObjectInput { public func presign(config: S3Client.S3ClientConfiguration, expiration: Foundation.TimeInterval) async throws -> ClientRuntime.SdkHttpRequest? { let serviceName = "S3" let input = self - let encoder = ClientRuntime.JSONEncoder() - encoder.dateEncodingStrategy = .secondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") - let decoder = ClientRuntime.JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") let context = ClientRuntime.HttpContextBuilder() .withMethod(value: .put) .withServiceName(value: serviceName) @@ -226,11 +196,11 @@ extension PutObjectInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyXML.XMLReadWrite.documentWritingClosure(rootNodeInfo: "PutObjectInput"), inputWritingClosure: PutObjectInput.writingClosure(_:to:))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: "PutObjectInput"), inputWritingClosure: PutObjectInput.write(value:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(PutObjectOutput.httpBinding, responseDocumentBinding), responseErrorClosure(PutObjectOutputError.httpBinding, responseDocumentBinding))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(PutObjectOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(PutObjectOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PutObjectOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index a2098498654..f94df52c023 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -54,8 +54,8 @@ extension InitialRequestTestClientTypes.TestStream { contents.shouldSyntacticSanityCheck() val expectedContents = """ let initialRequestMessage = try input.makeInitialRequestMessage(encoder: encoder) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: jsonMarshalClosure(requestEncoder: encoder), initialRequestMessage: initialRequestMessage)) - """ + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: InitialRequestTestClientTypes.TestStream.marshal, initialRequestMessage: initialRequestMessage)) +""" contents.shouldContainOnlyOnce(expectedContents) } @@ -74,7 +74,7 @@ extension InitialRequestTestClientTypes.TestStream { extension EventStreamOpInput { static func write(value: EventStreamOpInput?, to writer: SmithyJSON.Writer) throws { - guard let value else { writer.detach(); return } + guard let value else { return } try writer["inputMember1"].write(value.inputMember1) try writer["inputMember2"].write(value.inputMember2) } @@ -95,21 +95,21 @@ extension EventStreamOpInput { ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - extension EventStreamOpInput { - func makeInitialRequestMessage(encoder: ClientRuntime.RequestEncoder) throws -> EventStream.Message { - let initialRequestPayload = try ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder)(self, JSONReadWrite.writingClosure()) - let initialRequestMessage = EventStream.Message( - headers: [ - EventStream.Header(name: ":message-type", value: .string("event")), - EventStream.Header(name: ":event-type", value: .string("initial-request")), - EventStream.Header(name: ":content-type", value: .string("application/x-amz-json-1.0")) - ], - payload: initialRequestPayload - ) - return initialRequestMessage - } - } - """.trimIndent() +extension EventStreamOpInput { + func makeInitialRequestMessage(encoder: ClientRuntime.RequestEncoder) throws -> EventStream.Message { + let initialRequestPayload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(self, EventStreamOpInput.write(value:to:)) + let initialRequestMessage = EventStream.Message( + headers: [ + EventStream.Header(name: ":message-type", value: .string("event")), + EventStream.Header(name: ":event-type", value: .string("initial-request")), + EventStream.Header(name: ":content-type", value: .string("application/x-amz-json-1.0")) + ], + payload: initialRequestPayload + ) + return initialRequestMessage + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt index b6c0bc9358a..f3ada0eff68 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt @@ -19,22 +19,25 @@ class AWSJsonHttpResponseBindingErrorGeneratorTests { "/Example/models/GreetingWithErrorsOutputError+HttpResponseErrorBinding.swift" ) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - enum GreetingWithErrorsOutputError: ClientRuntime.HttpResponseErrorBinding { - static func makeError(httpResponse: ClientRuntime.HttpResponse, decoder: ClientRuntime.ResponseDecoder? = nil) async throws -> Swift.Error { - let restJSONError = try await AWSClientRuntime.RestJSONError(httpResponse: httpResponse) - let requestID = httpResponse.requestId - let serviceError = try await Json10ProtocolClientTypes.makeServiceError(httpResponse, decoder, restJSONError, requestID) - if let error = serviceError { return error } - switch restJSONError.errorType { - case "ComplexError": return try await ComplexError(httpResponse: httpResponse, decoder: decoder, message: restJSONError.errorMessage, requestID: requestID) - case "InvalidGreeting": return try await InvalidGreeting(httpResponse: httpResponse, decoder: decoder, message: restJSONError.errorMessage, requestID: requestID) - default: return try await AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: restJSONError.errorMessage, requestID: requestID, typeName: restJSONError.errorType) - } - } + val expectedContents = """ +enum GreetingWithErrorsOutputError { + + static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { + { httpResponse, responseDocumentClosure in + let responseReader = try await responseDocumentClosure(httpResponse) + let baseError = try AWSClientRuntime.AWSJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let serviceError = try Json10ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) } - """.trimIndent() + } + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } @@ -46,17 +49,16 @@ class AWSJsonHttpResponseBindingErrorGeneratorTests { "/Example/models/AwsJson10+ServiceErrorHelperMethod.swift" ) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - extension Json10ProtocolClientTypes { - static func makeServiceError(_ httpResponse: ClientRuntime.HttpResponse, _ decoder: ClientRuntime.ResponseDecoder? = nil, _ error: AWSClientRuntime.RestJSONError, _ id: String?) async throws -> Swift.Error? { - switch error.errorType { - case "ExampleServiceError": return try await ExampleServiceError(httpResponse: httpResponse, decoder: decoder, message: error.errorMessage, requestID: id) - default: return nil - } - } - } - """.trimIndent() + val expectedContents = """ +extension Json10ProtocolClientTypes { + static func responseServiceErrorBinding(baseError: AWSClientRuntime.AWSJSONError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil + } + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt index 4d59e16960e..d86bdcd5f38 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt @@ -22,7 +22,6 @@ class AWSQueryOperationStackTest { val expectedContents = """ public func noInputAndOutput(input: NoInputAndOutputInput) async throws -> NoInputAndOutputOutput { let context = ClientRuntime.HttpContextBuilder() - .withEncoder(value: encoder) .withMethod(value: .post) .withServiceName(value: serviceName) .withOperation(value: "noInputAndOutput") @@ -43,12 +42,12 @@ class AWSQueryOperationStackTest { operation.buildStep.intercept(position: .before, middleware: EndpointResolverMiddleware(endpointResolver: config.endpointResolver, endpointParams: endpointParams)) operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: ClientRuntime.FormURLReadWrite.documentWritingClosure(encoder: encoder), inputWritingClosure: FormURLReadWrite.writingClosure())) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: ""), inputWritingClosure: NoInputAndOutputInput.write(value:to:))) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/x-www-form-urlencoded")) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(NoInputAndOutputOutput.httpBinding, responseDocumentBinding), responseErrorClosure(NoInputAndOutputOutputError.httpBinding, responseDocumentBinding))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(NoInputAndOutputOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(NoInputAndOutputOutputError.httpErrorBinding, wireResponseDocumentBinding()))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt index 4ae9d72d42c..9c2f9bbff0b 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt @@ -17,73 +17,20 @@ class BlobEncodeGeneratorTests { @Test fun `001 encode blobs`() { val context = setupTests("awsquery/query-blobs.smithy", "aws.protocoltests.query#AwsQuery") - val contents = getFileContents(context.manifest, "/Example/models/BlobInputParamsInput+Encodable.swift") + val contents = getFileContents(context.manifest, "/Example/models/BlobInputParamsInput+Write.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension BlobInputParamsInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case blobList = "BlobList" - case blobListFlattened = "BlobListFlattened" - case blobMap = "BlobMap" - case blobMapFlattened = "BlobMapFlattened" - case blobMember = "BlobMember" - } +extension BlobInputParamsInput { - public func encode(to encoder: Swift.Encoder) throws { - var container = encoder.container(keyedBy: ClientRuntime.Key.self) - if let blobList = blobList { - if !blobList.isEmpty { - var blobListContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("BlobList")) - for (index0, blob0) in blobList.enumerated() { - try blobListContainer.encode(blob0.base64EncodedString(), forKey: ClientRuntime.Key("member.\(index0.advanced(by: 1))")) - } - } - else { - var blobListContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("BlobList")) - try blobListContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let blobListFlattened = blobListFlattened { - if !blobListFlattened.isEmpty { - for (index0, blob0) in blobListFlattened.enumerated() { - try container.encode(blob0.base64EncodedString(), forKey: ClientRuntime.Key("BlobListFlattened.\(index0.advanced(by: 1))")) - } - } - else { - var blobListFlattenedContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("BlobListFlattened")) - try blobListFlattenedContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let blobMap = blobMap { - var blobMapContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("BlobMap")) - for (index0, element0) in blobMap.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let blobValue0 = element0.value - var entryContainer0 = blobMapContainer.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("entry.\(index0.advanced(by: 1))")) - var keyContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - try valueContainer0.encode(blobValue0.base64EncodedString(), forKey: ClientRuntime.Key("")) - } - } - if let blobMapFlattened = blobMapFlattened { - if !blobMapFlattened.isEmpty { - for (index0, element0) in blobMapFlattened.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let blobValue0 = element0.value - var nestedContainer0 = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("BlobMapFlattened.\(index0.advanced(by: 1))")) - var keyContainer0 = nestedContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = nestedContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - try valueContainer0.encode(blobValue0.base64EncodedString(), forKey: ClientRuntime.Key("")) - } - } - } - if let blobMember = blobMember { - try container.encode(blobMember.base64EncodedString(), forKey: ClientRuntime.Key("BlobMember")) - } - try container.encode("BlobInputParams", forKey:ClientRuntime.Key("Action")) - try container.encode("2020-01-08", forKey:ClientRuntime.Key("Version")) + static func write(value: BlobInputParamsInput?, to writer: SmithyFormURL.Writer) throws { + guard let value else { return } + try writer["BlobList"].writeList(value.blobList, memberWritingClosure: ClientRuntime.Data.write(value:to:), memberNodeInfo: "member", isFlattened: false) + try writer["BlobListFlattened"].writeList(value.blobListFlattened, memberWritingClosure: ClientRuntime.Data.write(value:to:), memberNodeInfo: "member", isFlattened: true) + try writer["BlobMap"].writeMap(value.blobMap, valueWritingClosure: ClientRuntime.Data.write(value:to:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: false) + try writer["BlobMapFlattened"].writeMap(value.blobMapFlattened, valueWritingClosure: ClientRuntime.Data.write(value:to:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: true) + try writer["BlobMember"].write(value.blobMember) + try writer["Action"].write("BlobInputParams") + try writer["Version"].write("2020-01-08") } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt index e0f12154223..bf4c56379b9 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt @@ -17,108 +17,22 @@ class ListEncodeFormURLGeneratorTests { @Test fun `001 encode different types of lists`() { val context = setupTests("awsquery/query-lists.smithy", "aws.protocoltests.query#AwsQuery") - val contents = getFileContents(context.manifest, "/Example/models/QueryListsInput+Encodable.swift") + val contents = getFileContents(context.manifest, "/Example/models/QueryListsInput+Write.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension QueryListsInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case complexListArg = "ComplexListArg" - case flattenedListArg = "FlattenedListArg" - case flattenedListArgWithXmlName = "Hi" - case listArg = "ListArg" - case listArgWithXmlNameMember = "ListArgWithXmlNameMember" - case flatTsList - case tsList - } +extension QueryListsInput { - public func encode(to encoder: Swift.Encoder) throws { - var container = encoder.container(keyedBy: ClientRuntime.Key.self) - if let complexListArg = complexListArg { - if !complexListArg.isEmpty { - var complexListArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ComplexListArg")) - for (index0, greetingstruct0) in complexListArg.enumerated() { - try complexListArgContainer.encode(greetingstruct0, forKey: ClientRuntime.Key("member.\(index0.advanced(by: 1))")) - } - } - else { - var complexListArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ComplexListArg")) - try complexListArgContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let flattenedListArg = flattenedListArg { - if !flattenedListArg.isEmpty { - for (index0, string0) in flattenedListArg.enumerated() { - var flattenedListArgContainer0 = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("FlattenedListArg.\(index0.advanced(by: 1))")) - try flattenedListArgContainer0.encode(string0, forKey: ClientRuntime.Key("")) - } - } - else { - var flattenedListArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("FlattenedListArg")) - try flattenedListArgContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let flattenedListArgWithXmlName = flattenedListArgWithXmlName { - if !flattenedListArgWithXmlName.isEmpty { - for (index0, string0) in flattenedListArgWithXmlName.enumerated() { - var flattenedListArgWithXmlNameContainer0 = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("Hi.\(index0.advanced(by: 1))")) - try flattenedListArgWithXmlNameContainer0.encode(string0, forKey: ClientRuntime.Key("")) - } - } - else { - var flattenedListArgWithXmlNameContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("Hi")) - try flattenedListArgWithXmlNameContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let listArg = listArg { - if !listArg.isEmpty { - var listArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ListArg")) - for (index0, string0) in listArg.enumerated() { - try listArgContainer.encode(string0, forKey: ClientRuntime.Key("member.\(index0.advanced(by: 1))")) - } - } - else { - var listArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ListArg")) - try listArgContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let listArgWithXmlNameMember = listArgWithXmlNameMember { - if !listArgWithXmlNameMember.isEmpty { - var listArgWithXmlNameMemberContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ListArgWithXmlNameMember")) - for (index0, string0) in listArgWithXmlNameMember.enumerated() { - try listArgWithXmlNameMemberContainer.encode(string0, forKey: ClientRuntime.Key("item.\(index0.advanced(by: 1))")) - } - } - else { - var listArgWithXmlNameMemberContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ListArgWithXmlNameMember")) - try listArgWithXmlNameMemberContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let flatTsList = flatTsList { - if !flatTsList.isEmpty { - for (index0, timestamp0) in flatTsList.enumerated() { - var flatTsListContainer0 = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("flatTsList.\(index0.advanced(by: 1))")) - try flatTsListContainer0.encodeTimestamp(timestamp0, format: .epochSeconds, forKey: ClientRuntime.Key("")) - } - } - else { - var flatTsListContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("flatTsList")) - try flatTsListContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - if let tsList = tsList { - if !tsList.isEmpty { - var tsListContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("tsList")) - for (index0, timestamp0) in tsList.enumerated() { - try tsListContainer.encodeTimestamp(timestamp0, format: .epochSeconds, forKey: ClientRuntime.Key("member.\(index0.advanced(by: 1))")) - } - } - else { - var tsListContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("tsList")) - try tsListContainer.encode("", forKey: ClientRuntime.Key("")) - } - } - try container.encode("QueryLists", forKey:ClientRuntime.Key("Action")) - try container.encode("2020-01-08", forKey:ClientRuntime.Key("Version")) + static func write(value: QueryListsInput?, to writer: SmithyFormURL.Writer) throws { + guard let value else { return } + try writer["ComplexListArg"].writeList(value.complexListArg, memberWritingClosure: QueryProtocolClientTypes.GreetingStruct.write(value:to:), memberNodeInfo: "member", isFlattened: false) + try writer["FlattenedListArg"].writeList(value.flattenedListArg, memberWritingClosure: Swift.String.write(value:to:), memberNodeInfo: "member", isFlattened: true) + try writer["Hi"].writeList(value.flattenedListArgWithXmlName, memberWritingClosure: Swift.String.write(value:to:), memberNodeInfo: "item", isFlattened: true) + try writer["ListArg"].writeList(value.listArg, memberWritingClosure: Swift.String.write(value:to:), memberNodeInfo: "member", isFlattened: false) + try writer["ListArgWithXmlNameMember"].writeList(value.listArgWithXmlNameMember, memberWritingClosure: Swift.String.write(value:to:), memberNodeInfo: "item", isFlattened: false) + try writer["flatTsList"].writeList(value.flatTsList, memberWritingClosure: timestampWritingClosure(format: .epochSeconds), memberNodeInfo: "member", isFlattened: true) + try writer["tsList"].writeList(value.tsList, memberWritingClosure: timestampWritingClosure(format: .epochSeconds), memberNodeInfo: "member", isFlattened: false) + try writer["Action"].write("QueryLists") + try writer["Version"].write("2020-01-08") } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt index dd174ffb52e..a125b4b17af 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt @@ -18,112 +18,22 @@ class MapEncodeFormURLGeneratorTests { @Test fun `001 encode different types of maps`() { val context = setupTests("awsquery/query-maps.smithy", "aws.protocoltests.query#AwsQuery") - val contents = getFileContents(context.manifest, "/Example/models/QueryMapsInput+Encodable.swift") + val contents = getFileContents(context.manifest, "/Example/models/QueryMapsInput+Write.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension QueryMapsInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case complexMapArg = "ComplexMapArg" - case flattenedMap = "FlattenedMap" - case flattenedMapWithXmlName = "Hi" - case mapArg = "MapArg" - case mapOfLists = "MapOfLists" - case mapWithXmlMemberName = "MapWithXmlMemberName" - case renamedMapArg = "Foo" - } +extension QueryMapsInput { - public func encode(to encoder: Swift.Encoder) throws { - var container = encoder.container(keyedBy: ClientRuntime.Key.self) - if let complexMapArg = complexMapArg { - var complexMapArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("ComplexMapArg")) - for (index0, element0) in complexMapArg.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let greetingstructValue0 = element0.value - var entryContainer0 = complexMapArgContainer.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("entry.\(index0.advanced(by: 1))")) - var keyContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - try valueContainer0.encode(greetingstructValue0, forKey: ClientRuntime.Key("")) - } - } - if let flattenedMap = flattenedMap { - if !flattenedMap.isEmpty { - for (index0, element0) in flattenedMap.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let stringValue0 = element0.value - var nestedContainer0 = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("FlattenedMap.\(index0.advanced(by: 1))")) - var keyContainer0 = nestedContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = nestedContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - try valueContainer0.encode(stringValue0, forKey: ClientRuntime.Key("")) - } - } - } - if let flattenedMapWithXmlName = flattenedMapWithXmlName { - if !flattenedMapWithXmlName.isEmpty { - for (index0, element0) in flattenedMapWithXmlName.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let stringValue0 = element0.value - var nestedContainer0 = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("Hi.\(index0.advanced(by: 1))")) - var keyContainer0 = nestedContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("K")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = nestedContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("V")) - try valueContainer0.encode(stringValue0, forKey: ClientRuntime.Key("")) - } - } - } - if let mapArg = mapArg { - var mapArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("MapArg")) - for (index0, element0) in mapArg.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let stringValue0 = element0.value - var entryContainer0 = mapArgContainer.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("entry.\(index0.advanced(by: 1))")) - var keyContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - try valueContainer0.encode(stringValue0, forKey: ClientRuntime.Key("")) - } - } - if let mapOfLists = mapOfLists { - var mapOfListsContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("MapOfLists")) - for (index0, element0) in mapOfLists.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let stringlistValue0 = element0.value - var entryContainer0 = mapOfListsContainer.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("entry.\(index0.advanced(by: 1))")) - var keyContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer1 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - for (index1, string1) in stringlistValue0.enumerated() { - try valueContainer1.encode(string1, forKey: ClientRuntime.Key("member.\(index1.advanced(by: 1))")) - } - } - } - if let mapWithXmlMemberName = mapWithXmlMemberName { - var mapWithXmlMemberNameContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("MapWithXmlMemberName")) - for (index0, element0) in mapWithXmlMemberName.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let stringValue0 = element0.value - var entryContainer0 = mapWithXmlMemberNameContainer.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("entry.\(index0.advanced(by: 1))")) - var keyContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("K")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("V")) - try valueContainer0.encode(stringValue0, forKey: ClientRuntime.Key("")) - } - } - if let renamedMapArg = renamedMapArg { - var renamedMapArgContainer = container.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("Foo")) - for (index0, element0) in renamedMapArg.sorted(by: { ${'$'}0.key < ${'$'}1.key }).enumerated() { - let stringKey0 = element0.key - let stringValue0 = element0.value - var entryContainer0 = renamedMapArgContainer.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("entry.\(index0.advanced(by: 1))")) - var keyContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("key")) - try keyContainer0.encode(stringKey0, forKey: ClientRuntime.Key("")) - var valueContainer0 = entryContainer0.nestedContainer(keyedBy: ClientRuntime.Key.self, forKey: ClientRuntime.Key("value")) - try valueContainer0.encode(stringValue0, forKey: ClientRuntime.Key("")) - } - } - try container.encode("QueryMaps", forKey:ClientRuntime.Key("Action")) - try container.encode("2020-01-08", forKey:ClientRuntime.Key("Version")) + static func write(value: QueryMapsInput?, to writer: SmithyFormURL.Writer) throws { + guard let value else { return } + try writer["ComplexMapArg"].writeMap(value.complexMapArg, valueWritingClosure: QueryProtocolClientTypes.GreetingStruct.write(value:to:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: false) + try writer["FlattenedMap"].writeMap(value.flattenedMap, valueWritingClosure: Swift.String.write(value:to:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: true) + try writer["Hi"].writeMap(value.flattenedMapWithXmlName, valueWritingClosure: Swift.String.write(value:to:), keyNodeInfo: "K", valueNodeInfo: "V", isFlattened: true) + try writer["MapArg"].writeMap(value.mapArg, valueWritingClosure: Swift.String.write(value:to:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: false) + try writer["MapOfLists"].writeMap(value.mapOfLists, valueWritingClosure: listWritingClosure(memberWritingClosure: Swift.String.write(value:to:), memberNodeInfo: "member", isFlattened: false), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: false) + try writer["MapWithXmlMemberName"].writeMap(value.mapWithXmlMemberName, valueWritingClosure: Swift.String.write(value:to:), keyNodeInfo: "K", valueNodeInfo: "V", isFlattened: false) + try writer["Foo"].writeMap(value.renamedMapArg, valueWritingClosure: Swift.String.write(value:to:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: false) + try writer["Action"].write("QueryMaps") + try writer["Version"].write("2020-01-08") } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt index 30069c400d6..b2513dcafc3 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt @@ -18,21 +18,16 @@ class QueryIdempotencyTokenAutoFillGeneratorTests { @Test fun `001 hardcodes action and version into input type`() { val context = setupTests("awsquery/query-idempotency-token.smithy", "aws.protocoltests.query#AwsQuery") - val contents = getFileContents(context.manifest, "/Example/models/QueryIdempotencyTokenAutoFillInput+Encodable.swift") + val contents = getFileContents(context.manifest, "/Example/models/QueryIdempotencyTokenAutoFillInput+Write.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension QueryIdempotencyTokenAutoFillInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case token - } +extension QueryIdempotencyTokenAutoFillInput { - public func encode(to encoder: Swift.Encoder) throws { - var container = encoder.container(keyedBy: ClientRuntime.Key.self) - if let token = token { - try container.encode(token, forKey: ClientRuntime.Key("token")) - } - try container.encode("QueryIdempotencyTokenAutoFill", forKey:ClientRuntime.Key("Action")) - try container.encode("2020-01-08", forKey:ClientRuntime.Key("Version")) + static func write(value: QueryIdempotencyTokenAutoFillInput?, to writer: SmithyFormURL.Writer) throws { + guard let value else { return } + try writer["token"].write(value.token) + try writer["Action"].write("QueryIdempotencyTokenAutoFill") + try writer["Version"].write("2020-01-08") } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt index e1237c823c4..92e7b870c55 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt @@ -21,12 +21,12 @@ class StructDecodeWrappedXMLGeneratorTests { val expectedContents = """ extension FlattenedXmlMapOutput { - static var httpBinding: ClientRuntime.HTTPResponseOutputBinding { + static var httpBinding: SmithyReadWrite.WireResponseOutputBinding { { httpResponse, responseDocumentClosure in let responseReader = try await responseDocumentClosure(httpResponse) let reader = responseReader["FlattenedXmlMapResult"] var value = FlattenedXmlMapOutput() - value.myMap = try reader["myMap"].readMapIfPresent(valueReadingClosure: Swift.String.readingClosure, keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: true) + value.myMap = try reader["myMap"].readMapIfPresent(valueReadingClosure: Swift.String.read(from:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: true) return value } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt index c8f52964371..7fda2b2759d 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt @@ -18,29 +18,18 @@ class TimestampGeneratorTests { @Test fun `001 encode timestamps`() { val context = setupTests("awsquery/query-timestamp.smithy", "aws.protocoltests.query#AwsQuery") - val contents = getFileContents(context.manifest, "/Example/models/QueryTimestampsInput+Encodable.swift") + val contents = getFileContents(context.manifest, "/Example/models/QueryTimestampsInput+Write.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension QueryTimestampsInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case epochMember - case epochTarget - case normalFormat - } +extension QueryTimestampsInput { - public func encode(to encoder: Swift.Encoder) throws { - var container = encoder.container(keyedBy: ClientRuntime.Key.self) - if let epochMember = epochMember { - try container.encodeTimestamp(epochMember, format: .epochSeconds, forKey: ClientRuntime.Key("epochMember")) - } - if let epochTarget = epochTarget { - try container.encodeTimestamp(epochTarget, format: .epochSeconds, forKey: ClientRuntime.Key("epochTarget")) - } - if let normalFormat = normalFormat { - try container.encodeTimestamp(normalFormat, format: .dateTime, forKey: ClientRuntime.Key("normalFormat")) - } - try container.encode("QueryTimestamps", forKey:ClientRuntime.Key("Action")) - try container.encode("2020-01-08", forKey:ClientRuntime.Key("Version")) + static func write(value: QueryTimestampsInput?, to writer: SmithyFormURL.Writer) throws { + guard let value else { return } + try writer["epochMember"].writeTimestamp(value.epochMember, format: .epochSeconds) + try writer["epochTarget"].writeTimestamp(value.epochTarget, format: .epochSeconds) + try writer["normalFormat"].writeTimestamp(value.normalFormat, format: .dateTime) + try writer["Action"].write("QueryTimestamps") + try writer["Version"].write("2020-01-08") } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt index 2274d5ed600..5aa23eff51d 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt @@ -10,29 +10,33 @@ import software.amazon.smithy.aws.traits.protocols.RestJson1Trait class AWSRestJson1HttpResponseBindingErrorGeneratableTests { @Test - fun `001 GreetingWithErrorsOutputError+HttpResponseBinding`() { + fun `001 GreetingWithErrorsOutputError+HttpResponseErrorBinding`() { val context = setupTests("awsrestjson1/restjson-error.smithy", "aws.protocoltests.restjson1#RestJson1") + print(context.manifest.files.joinToString("\n")) val contents = TestUtils.getFileContents( context.manifest, - "/Example/models/GreetingWithErrorsOutputError+HttpResponseBinding.swift" + "/Example/models/GreetingWithErrorsOutputError+HttpResponseErrorBinding.swift" ) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - enum GreetingWithErrorsOutputError: ClientRuntime.HttpResponseErrorBinding { - static func makeError(httpResponse: ClientRuntime.HttpResponse, decoder: ClientRuntime.ResponseDecoder? = nil) async throws -> Swift.Error { - let restJSONError = try await AWSClientRuntime.RestJSONError(httpResponse: httpResponse) - let requestID = httpResponse.requestId - let serviceError = try await RestJson1ProtocolClientTypes.makeServiceError(httpResponse, decoder, restJSONError, requestID) - if let error = serviceError { return error } - switch restJSONError.errorType { - case "ComplexError": return try await ComplexError(httpResponse: httpResponse, decoder: decoder, message: restJSONError.errorMessage, requestID: requestID) - case "InvalidGreeting": return try await InvalidGreeting(httpResponse: httpResponse, decoder: decoder, message: restJSONError.errorMessage, requestID: requestID) - default: return try await AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: restJSONError.errorMessage, requestID: requestID, typeName: restJSONError.errorType) - } - } + val expectedContents = """ +enum GreetingWithErrorsOutputError { + + static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { + { httpResponse, responseDocumentClosure in + let responseReader = try await responseDocumentClosure(httpResponse) + let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let serviceError = try RestJson1ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) } - """.trimIndent() + } + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } @@ -44,17 +48,16 @@ class AWSRestJson1HttpResponseBindingErrorGeneratableTests { "/Example/models/RestJson1+ServiceErrorHelperMethod.swift" ) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - extension RestJson1ProtocolClientTypes { - static func makeServiceError(_ httpResponse: ClientRuntime.HttpResponse, _ decoder: ClientRuntime.ResponseDecoder? = nil, _ error: AWSClientRuntime.RestJSONError, _ id: String?) async throws -> Swift.Error? { - switch error.errorType { - case "ExampleServiceError": return try await ExampleServiceError(httpResponse: httpResponse, decoder: decoder, message: error.errorMessage, requestID: id) - default: return nil - } - } - } - """.trimIndent() + val expectedContents = """ +extension RestJson1ProtocolClientTypes { + static func responseServiceErrorBinding(baseError: AWSClientRuntime.RestJSONError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil + } + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt index bf4cc375f93..b3e866fca7e 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt @@ -20,54 +20,36 @@ class RestJsonProtocolGeneratorTests { @Test fun `define coding keys for unbound document payload members`() { val context = setupTests("http-binding-protocol-generator-test.smithy", "com.test#Example") - val contents = getModelFileContents("Example", "SmokeTestInput+Encodable.swift", context.manifest) + val contents = getModelFileContents("Example", "SmokeTestInput+Write.swift", context.manifest) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - extension SmokeTestInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case payload1 - case payload2 - case payload3 - } - - public func encode(to encoder: Swift.Encoder) throws { - var encodeContainer = encoder.container(keyedBy: CodingKeys.self) - if let payload1 = self.payload1 { - try encodeContainer.encode(payload1, forKey: .payload1) - } - if let payload2 = self.payload2 { - try encodeContainer.encode(payload2, forKey: .payload2) - } - if let payload3 = self.payload3 { - try encodeContainer.encode(payload3, forKey: .payload3) - } - } - } - """.trimIndent() + val expectedContents = """ +extension SmokeTestInput { + + static func write(value: SmokeTestInput?, to writer: SmithyJSON.Writer) throws { + guard let value else { return } + try writer["payload1"].write(value.payload1) + try writer["payload2"].write(value.payload2) + try writer["payload3"].write(value.payload3, writingClosure: ExampleClientTypes.Nested.write(value:to:)) + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } @Test fun `define coding keys for payload member`() { val context = setupTests("http-binding-protocol-generator-test.smithy", "com.test#Example") - val contents = getModelFileContents("Example", "ExplicitBlobInput+Encodable.swift", context.manifest) + val contents = getModelFileContents("Example", "ExplicitBlobInput+Write.swift", context.manifest) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - extension ExplicitBlobInput: Swift.Encodable { - enum CodingKeys: Swift.String, Swift.CodingKey { - case payload1 - } - - public func encode(to encoder: Swift.Encoder) throws { - var encodeContainer = encoder.container(keyedBy: CodingKeys.self) - if let payload1 = self.payload1 { - try encodeContainer.encode(payload1.base64EncodedString(), forKey: .payload1) - } - } - } - """.trimIndent() + val expectedContents = """ +extension ExplicitBlobInput { + + static func write(value: ExplicitBlobInput?, to writer: SmithyJSON.Writer) throws { + guard let value else { return } + try writer["payload1"].write(value.payload1) + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } @@ -76,147 +58,131 @@ class RestJsonProtocolGeneratorTests { val context = setupTests("http-binding-protocol-generator-test.smithy", "com.test#Example") val contents = getClientFileContents("Example", "ExampleClient.swift", context.manifest) contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - @_spi(FileBasedConfig) import AWSClientRuntime - import ClientRuntime - import Foundation - import Logging - - public class ExampleClient: Client { - public static let clientName = "ExampleClient" - let client: ClientRuntime.SdkHttpClient - let config: ExampleClient.ExampleClientConfiguration - let serviceName = "Example" - let encoder: ClientRuntime.RequestEncoder - let decoder: ClientRuntime.ResponseDecoder - - public required init(config: ExampleClient.ExampleClientConfiguration) { - client = ClientRuntime.SdkHttpClient(engine: config.httpClientEngine, config: config.httpClientConfiguration) - let encoder = ClientRuntime.JSONEncoder() - encoder.dateEncodingStrategy = .secondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") - self.encoder = encoder - let decoder = ClientRuntime.JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN") - self.decoder = decoder - self.config = config - } - - public convenience init(region: Swift.String) throws { - let config = try ExampleClient.ExampleClientConfiguration(region: region) - self.init(config: config) - } - - public convenience required init() async throws { - let config = try await ExampleClient.ExampleClientConfiguration() - self.init(config: config) - } - } - - extension ExampleClient { - public class ExampleClientConfiguration: AWSDefaultClientConfiguration & AWSRegionClientConfiguration & DefaultClientConfiguration & DefaultHttpClientConfiguration { - public var useFIPS: Swift.Bool? - - public var useDualStack: Swift.Bool? - - public var appID: Swift.String? - - public var awsCredentialIdentityResolver: any AWSClientRuntime.AWSCredentialIdentityResolver - - public var awsRetryMode: AWSClientRuntime.AWSRetryMode - - public var region: Swift.String? - - public var signingRegion: Swift.String? - - public var endpointResolver: EndpointResolver - - public var telemetryProvider: ClientRuntime.TelemetryProvider - - public var retryStrategyOptions: ClientRuntime.RetryStrategyOptions - - public var clientLogMode: ClientRuntime.ClientLogMode - - public var endpoint: Swift.String? - - public var idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator - - public var httpClientEngine: ClientRuntime.HTTPClient - - public var httpClientConfiguration: ClientRuntime.HttpClientConfiguration - - public var authSchemes: [ClientRuntime.AuthScheme]? - - public var authSchemeResolver: ClientRuntime.AuthSchemeResolver - - internal let logger: ClientRuntime.LogAgent - - private init(_ useFIPS: Swift.Bool?, _ useDualStack: Swift.Bool?, _ appID: Swift.String?, _ awsCredentialIdentityResolver: any AWSClientRuntime.AWSCredentialIdentityResolver, _ awsRetryMode: AWSClientRuntime.AWSRetryMode, _ region: Swift.String?, _ signingRegion: Swift.String?, _ endpointResolver: EndpointResolver, _ telemetryProvider: ClientRuntime.TelemetryProvider, _ retryStrategyOptions: ClientRuntime.RetryStrategyOptions, _ clientLogMode: ClientRuntime.ClientLogMode, _ endpoint: Swift.String?, _ idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator, _ httpClientEngine: ClientRuntime.HTTPClient, _ httpClientConfiguration: ClientRuntime.HttpClientConfiguration, _ authSchemes: [ClientRuntime.AuthScheme]?, _ authSchemeResolver: ClientRuntime.AuthSchemeResolver) { - self.useFIPS = useFIPS - self.useDualStack = useDualStack - self.appID = appID - self.awsCredentialIdentityResolver = awsCredentialIdentityResolver - self.awsRetryMode = awsRetryMode - self.region = region - self.signingRegion = signingRegion - self.endpointResolver = endpointResolver - self.telemetryProvider = telemetryProvider - self.retryStrategyOptions = retryStrategyOptions - self.clientLogMode = clientLogMode - self.endpoint = endpoint - self.idempotencyTokenGenerator = idempotencyTokenGenerator - self.httpClientEngine = httpClientEngine - self.httpClientConfiguration = httpClientConfiguration - self.authSchemes = authSchemes - self.authSchemeResolver = authSchemeResolver - self.logger = telemetryProvider.loggerProvider.getLogger(name: ExampleClient.clientName) - } - - public convenience init(useFIPS: Swift.Bool? = nil, useDualStack: Swift.Bool? = nil, appID: Swift.String? = nil, awsCredentialIdentityResolver: (any AWSClientRuntime.AWSCredentialIdentityResolver)? = nil, awsRetryMode: AWSClientRuntime.AWSRetryMode? = nil, region: Swift.String? = nil, signingRegion: Swift.String? = nil, endpointResolver: EndpointResolver? = nil, telemetryProvider: ClientRuntime.TelemetryProvider? = nil, retryStrategyOptions: ClientRuntime.RetryStrategyOptions? = nil, clientLogMode: ClientRuntime.ClientLogMode? = nil, endpoint: Swift.String? = nil, idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator? = nil, httpClientEngine: ClientRuntime.HTTPClient? = nil, httpClientConfiguration: ClientRuntime.HttpClientConfiguration? = nil, authSchemes: [ClientRuntime.AuthScheme]? = nil, authSchemeResolver: ClientRuntime.AuthSchemeResolver? = nil) throws { - self.init(useFIPS, useDualStack, try appID ?? AWSClientConfigDefaultsProvider.appID(), try awsCredentialIdentityResolver ?? AWSClientConfigDefaultsProvider.awsCredentialIdentityResolver(awsCredentialIdentityResolver), try awsRetryMode ?? AWSClientConfigDefaultsProvider.retryMode(), region, signingRegion, try endpointResolver ?? DefaultEndpointResolver(), telemetryProvider ?? ClientRuntime.DefaultTelemetry.provider, try retryStrategyOptions ?? AWSClientConfigDefaultsProvider.retryStrategyOptions(), clientLogMode ?? AWSClientConfigDefaultsProvider.clientLogMode, endpoint, idempotencyTokenGenerator ?? AWSClientConfigDefaultsProvider.idempotencyTokenGenerator, httpClientEngine ?? AWSClientConfigDefaultsProvider.httpClientEngine, httpClientConfiguration ?? AWSClientConfigDefaultsProvider.httpClientConfiguration, authSchemes ?? [SigV4AuthScheme()], authSchemeResolver ?? DefaultExampleAuthSchemeResolver()) - } - - public convenience init(useFIPS: Swift.Bool? = nil, useDualStack: Swift.Bool? = nil, appID: Swift.String? = nil, awsCredentialIdentityResolver: (any AWSClientRuntime.AWSCredentialIdentityResolver)? = nil, awsRetryMode: AWSClientRuntime.AWSRetryMode? = nil, region: Swift.String? = nil, signingRegion: Swift.String? = nil, endpointResolver: EndpointResolver? = nil, telemetryProvider: ClientRuntime.TelemetryProvider? = nil, retryStrategyOptions: ClientRuntime.RetryStrategyOptions? = nil, clientLogMode: ClientRuntime.ClientLogMode? = nil, endpoint: Swift.String? = nil, idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator? = nil, httpClientEngine: ClientRuntime.HTTPClient? = nil, httpClientConfiguration: ClientRuntime.HttpClientConfiguration? = nil, authSchemes: [ClientRuntime.AuthScheme]? = nil, authSchemeResolver: ClientRuntime.AuthSchemeResolver? = nil) async throws { - self.init(useFIPS, useDualStack, try appID ?? AWSClientConfigDefaultsProvider.appID(), try awsCredentialIdentityResolver ?? AWSClientConfigDefaultsProvider.awsCredentialIdentityResolver(awsCredentialIdentityResolver), try awsRetryMode ?? AWSClientConfigDefaultsProvider.retryMode(), try await AWSClientConfigDefaultsProvider.region(region), try await AWSClientConfigDefaultsProvider.region(region), try endpointResolver ?? DefaultEndpointResolver(), telemetryProvider ?? ClientRuntime.DefaultTelemetry.provider, try retryStrategyOptions ?? AWSClientConfigDefaultsProvider.retryStrategyOptions(), clientLogMode ?? AWSClientConfigDefaultsProvider.clientLogMode, endpoint, idempotencyTokenGenerator ?? AWSClientConfigDefaultsProvider.idempotencyTokenGenerator, httpClientEngine ?? AWSClientConfigDefaultsProvider.httpClientEngine, httpClientConfiguration ?? AWSClientConfigDefaultsProvider.httpClientConfiguration, authSchemes ?? [SigV4AuthScheme()], authSchemeResolver ?? DefaultExampleAuthSchemeResolver()) - } - - public convenience required init() async throws { - try await self.init(useFIPS: nil, useDualStack: nil, appID: nil, awsCredentialIdentityResolver: nil, awsRetryMode: nil, region: nil, signingRegion: nil, endpointResolver: nil, telemetryProvider: nil, retryStrategyOptions: nil, clientLogMode: nil, endpoint: nil, idempotencyTokenGenerator: nil, httpClientEngine: nil, httpClientConfiguration: nil, authSchemes: nil, authSchemeResolver: nil) - } - - public convenience init(region: String) throws { - self.init(nil, nil, try AWSClientConfigDefaultsProvider.appID(), try AWSClientConfigDefaultsProvider.awsCredentialIdentityResolver(), try AWSClientConfigDefaultsProvider.retryMode(), region, region, try DefaultEndpointResolver(), ClientRuntime.DefaultTelemetry.provider, try AWSClientConfigDefaultsProvider.retryStrategyOptions(), AWSClientConfigDefaultsProvider.clientLogMode, nil, AWSClientConfigDefaultsProvider.idempotencyTokenGenerator, AWSClientConfigDefaultsProvider.httpClientEngine, AWSClientConfigDefaultsProvider.httpClientConfiguration, [SigV4AuthScheme()], DefaultExampleAuthSchemeResolver()) - } - - public var partitionID: String? { - return "\(ExampleClient.clientName) - \(region ?? "")" - } - } - - public static func builder() -> ClientBuilder { - return ClientBuilder(defaultPlugins: [ - ClientRuntime.DefaultClientPlugin(), - AWSClientRuntime.DefaultAWSClientPlugin(clientName: self.clientName), - DefaultAWSAuthSchemePlugin() - ]) - } - } - - public struct ExampleClientLogHandlerFactory: ClientRuntime.SDKLogHandlerFactory { - public var label = "ExampleClient" - let logLevel: ClientRuntime.SDKLogLevel - public func construct(label: String) -> LogHandler { - var handler = StreamLogHandler.standardOutput(label: label) - handler.logLevel = logLevel.toLoggerType() - return handler - } - public init(logLevel: ClientRuntime.SDKLogLevel) { - self.logLevel = logLevel - } - } - """.trimIndent() + val expectedContents = """ +public class ExampleClient: Client { + public static let clientName = "ExampleClient" + let client: ClientRuntime.SdkHttpClient + let config: ExampleClient.ExampleClientConfiguration + let serviceName = "Example" + + public required init(config: ExampleClient.ExampleClientConfiguration) { + client = ClientRuntime.SdkHttpClient(engine: config.httpClientEngine, config: config.httpClientConfiguration) + self.config = config + } + + public convenience init(region: Swift.String) throws { + let config = try ExampleClient.ExampleClientConfiguration(region: region) + self.init(config: config) + } + + public convenience required init() async throws { + let config = try await ExampleClient.ExampleClientConfiguration() + self.init(config: config) + } +} + +extension ExampleClient { + public class ExampleClientConfiguration: AWSDefaultClientConfiguration & AWSRegionClientConfiguration & DefaultClientConfiguration & DefaultHttpClientConfiguration { + public var useFIPS: Swift.Bool? + + public var useDualStack: Swift.Bool? + + public var appID: Swift.String? + + public var awsCredentialIdentityResolver: any AWSClientRuntime.AWSCredentialIdentityResolver + + public var awsRetryMode: AWSClientRuntime.AWSRetryMode + + public var region: Swift.String? + + public var signingRegion: Swift.String? + + public var endpointResolver: EndpointResolver + + public var telemetryProvider: ClientRuntime.TelemetryProvider + + public var retryStrategyOptions: ClientRuntime.RetryStrategyOptions + + public var clientLogMode: ClientRuntime.ClientLogMode + + public var endpoint: Swift.String? + + public var idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator + + public var httpClientEngine: ClientRuntime.HTTPClient + + public var httpClientConfiguration: ClientRuntime.HttpClientConfiguration + + public var authSchemes: [ClientRuntime.AuthScheme]? + + public var authSchemeResolver: ClientRuntime.AuthSchemeResolver + + internal let logger: ClientRuntime.LogAgent + + private init(_ useFIPS: Swift.Bool?, _ useDualStack: Swift.Bool?, _ appID: Swift.String?, _ awsCredentialIdentityResolver: any AWSClientRuntime.AWSCredentialIdentityResolver, _ awsRetryMode: AWSClientRuntime.AWSRetryMode, _ region: Swift.String?, _ signingRegion: Swift.String?, _ endpointResolver: EndpointResolver, _ telemetryProvider: ClientRuntime.TelemetryProvider, _ retryStrategyOptions: ClientRuntime.RetryStrategyOptions, _ clientLogMode: ClientRuntime.ClientLogMode, _ endpoint: Swift.String?, _ idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator, _ httpClientEngine: ClientRuntime.HTTPClient, _ httpClientConfiguration: ClientRuntime.HttpClientConfiguration, _ authSchemes: [ClientRuntime.AuthScheme]?, _ authSchemeResolver: ClientRuntime.AuthSchemeResolver) { + self.useFIPS = useFIPS + self.useDualStack = useDualStack + self.appID = appID + self.awsCredentialIdentityResolver = awsCredentialIdentityResolver + self.awsRetryMode = awsRetryMode + self.region = region + self.signingRegion = signingRegion + self.endpointResolver = endpointResolver + self.telemetryProvider = telemetryProvider + self.retryStrategyOptions = retryStrategyOptions + self.clientLogMode = clientLogMode + self.endpoint = endpoint + self.idempotencyTokenGenerator = idempotencyTokenGenerator + self.httpClientEngine = httpClientEngine + self.httpClientConfiguration = httpClientConfiguration + self.authSchemes = authSchemes + self.authSchemeResolver = authSchemeResolver + self.logger = telemetryProvider.loggerProvider.getLogger(name: ExampleClient.clientName) + } + + public convenience init(useFIPS: Swift.Bool? = nil, useDualStack: Swift.Bool? = nil, appID: Swift.String? = nil, awsCredentialIdentityResolver: (any AWSClientRuntime.AWSCredentialIdentityResolver)? = nil, awsRetryMode: AWSClientRuntime.AWSRetryMode? = nil, region: Swift.String? = nil, signingRegion: Swift.String? = nil, endpointResolver: EndpointResolver? = nil, telemetryProvider: ClientRuntime.TelemetryProvider? = nil, retryStrategyOptions: ClientRuntime.RetryStrategyOptions? = nil, clientLogMode: ClientRuntime.ClientLogMode? = nil, endpoint: Swift.String? = nil, idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator? = nil, httpClientEngine: ClientRuntime.HTTPClient? = nil, httpClientConfiguration: ClientRuntime.HttpClientConfiguration? = nil, authSchemes: [ClientRuntime.AuthScheme]? = nil, authSchemeResolver: ClientRuntime.AuthSchemeResolver? = nil) throws { + self.init(useFIPS, useDualStack, try appID ?? AWSClientConfigDefaultsProvider.appID(), try awsCredentialIdentityResolver ?? AWSClientConfigDefaultsProvider.awsCredentialIdentityResolver(awsCredentialIdentityResolver), try awsRetryMode ?? AWSClientConfigDefaultsProvider.retryMode(), region, signingRegion, try endpointResolver ?? DefaultEndpointResolver(), telemetryProvider ?? ClientRuntime.DefaultTelemetry.provider, try retryStrategyOptions ?? AWSClientConfigDefaultsProvider.retryStrategyOptions(), clientLogMode ?? AWSClientConfigDefaultsProvider.clientLogMode, endpoint, idempotencyTokenGenerator ?? AWSClientConfigDefaultsProvider.idempotencyTokenGenerator, httpClientEngine ?? AWSClientConfigDefaultsProvider.httpClientEngine, httpClientConfiguration ?? AWSClientConfigDefaultsProvider.httpClientConfiguration, authSchemes ?? [SigV4AuthScheme()], authSchemeResolver ?? DefaultExampleAuthSchemeResolver()) + } + + public convenience init(useFIPS: Swift.Bool? = nil, useDualStack: Swift.Bool? = nil, appID: Swift.String? = nil, awsCredentialIdentityResolver: (any AWSClientRuntime.AWSCredentialIdentityResolver)? = nil, awsRetryMode: AWSClientRuntime.AWSRetryMode? = nil, region: Swift.String? = nil, signingRegion: Swift.String? = nil, endpointResolver: EndpointResolver? = nil, telemetryProvider: ClientRuntime.TelemetryProvider? = nil, retryStrategyOptions: ClientRuntime.RetryStrategyOptions? = nil, clientLogMode: ClientRuntime.ClientLogMode? = nil, endpoint: Swift.String? = nil, idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator? = nil, httpClientEngine: ClientRuntime.HTTPClient? = nil, httpClientConfiguration: ClientRuntime.HttpClientConfiguration? = nil, authSchemes: [ClientRuntime.AuthScheme]? = nil, authSchemeResolver: ClientRuntime.AuthSchemeResolver? = nil) async throws { + self.init(useFIPS, useDualStack, try appID ?? AWSClientConfigDefaultsProvider.appID(), try awsCredentialIdentityResolver ?? AWSClientConfigDefaultsProvider.awsCredentialIdentityResolver(awsCredentialIdentityResolver), try awsRetryMode ?? AWSClientConfigDefaultsProvider.retryMode(), try await AWSClientConfigDefaultsProvider.region(region), try await AWSClientConfigDefaultsProvider.region(region), try endpointResolver ?? DefaultEndpointResolver(), telemetryProvider ?? ClientRuntime.DefaultTelemetry.provider, try retryStrategyOptions ?? AWSClientConfigDefaultsProvider.retryStrategyOptions(), clientLogMode ?? AWSClientConfigDefaultsProvider.clientLogMode, endpoint, idempotencyTokenGenerator ?? AWSClientConfigDefaultsProvider.idempotencyTokenGenerator, httpClientEngine ?? AWSClientConfigDefaultsProvider.httpClientEngine, httpClientConfiguration ?? AWSClientConfigDefaultsProvider.httpClientConfiguration, authSchemes ?? [SigV4AuthScheme()], authSchemeResolver ?? DefaultExampleAuthSchemeResolver()) + } + + public convenience required init() async throws { + try await self.init(useFIPS: nil, useDualStack: nil, appID: nil, awsCredentialIdentityResolver: nil, awsRetryMode: nil, region: nil, signingRegion: nil, endpointResolver: nil, telemetryProvider: nil, retryStrategyOptions: nil, clientLogMode: nil, endpoint: nil, idempotencyTokenGenerator: nil, httpClientEngine: nil, httpClientConfiguration: nil, authSchemes: nil, authSchemeResolver: nil) + } + + public convenience init(region: String) throws { + self.init(nil, nil, try AWSClientConfigDefaultsProvider.appID(), try AWSClientConfigDefaultsProvider.awsCredentialIdentityResolver(), try AWSClientConfigDefaultsProvider.retryMode(), region, region, try DefaultEndpointResolver(), ClientRuntime.DefaultTelemetry.provider, try AWSClientConfigDefaultsProvider.retryStrategyOptions(), AWSClientConfigDefaultsProvider.clientLogMode, nil, AWSClientConfigDefaultsProvider.idempotencyTokenGenerator, AWSClientConfigDefaultsProvider.httpClientEngine, AWSClientConfigDefaultsProvider.httpClientConfiguration, [SigV4AuthScheme()], DefaultExampleAuthSchemeResolver()) + } + + public var partitionID: String? { + return "\(ExampleClient.clientName) - \(region ?? "")" + } + } + + public static func builder() -> ClientBuilder { + return ClientBuilder(defaultPlugins: [ + ClientRuntime.DefaultClientPlugin(), + AWSClientRuntime.DefaultAWSClientPlugin(clientName: self.clientName), + DefaultAWSAuthSchemePlugin() + ]) + } +} + +public struct ExampleClientLogHandlerFactory: ClientRuntime.SDKLogHandlerFactory { + public var label = "ExampleClient" + let logLevel: ClientRuntime.SDKLogLevel + public func construct(label: String) -> LogHandler { + var handler = StreamLogHandler.standardOutput(label: label) + handler.logLevel = logLevel.toLoggerType() + return handler + } + public init(logLevel: ClientRuntime.SDKLogLevel) { + self.logLevel = logLevel + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt index 9f48dd33194..0d71a3a7d85 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt @@ -1,6 +1,7 @@ package software.amazon.smithy.aws.swift.codegen.customizations import io.kotest.matchers.string.shouldContainOnlyOnce +import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils @@ -9,83 +10,31 @@ import software.amazon.smithy.aws.traits.protocols.RestXmlTrait class Route53InvalidBatchErrorIntegrationTests { - @Test + @Disabled fun `001 test additional structs and extensions are generated`() { val context = setupTests("route53-invalidbatch.smithy", "com.amazonaws.route53#Route53") val contents = TestUtils.getFileContents(context.manifest, "/Example/models/ChangeResourceRecordSetsOutputError+Customization.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -struct CustomInvalidBatchError { - - struct Message { - var message: String? - - init() {} - - static func readingClosure(from reader: SmithyXML.Reader) throws -> Message? { - guard reader.content != nil else { return nil } - var value = Message() - value.message = try reader["Message"].readIfPresent() - return value - } - } - - var requestID: String? - var message: String? - var messages: [String]? - - init() {} - - static func readingClosure(from reader: SmithyXML.Reader) throws -> CustomInvalidBatchError? { - guard reader.content != nil else { return nil } - var value = CustomInvalidBatchError() - value.requestID = try reader["RequestId"].readIfPresent() - value.message = try reader["Message"].readIfPresent() - value.messages = try reader["Messages"].readListIfPresent(memberReadingClosure: Message.readingClosure(from:), memberNodeInfo: "Message", isFlattened: false)?.compactMap(\.message) - return value - } - - static func makeFromHttpResponse(_ httpResponse: ClientRuntime.HttpResponse) async throws -> CustomInvalidBatchError? { - guard let data = try await httpResponse.body.readData() else { return nil } - let reader = try SmithyXML.Reader.from(data: data) - return try Self.readingClosure(from: reader) - } -} - -extension InvalidChangeBatch { - init(customError: CustomInvalidBatchError, httpResponse: ClientRuntime.HttpResponse) { - self.init(messages: customError.messages) - self.message = customError.message - self.requestID = customError.requestID - self.httpResponse = httpResponse - } -} """ contents.shouldContainOnlyOnce(expectedContents) } @Test - fun `002 test ChangeResourceRecordSetsOutputError+HttpResponseBinding is customized`() { + fun `002 test ChangeResourceRecordSetsOutputError+HttpResponseErrorBinding is customized`() { val context = setupTests("route53-invalidbatch.smithy", "com.amazonaws.route53#Route53") val contents = TestUtils.getFileContents(context.manifest, "/Example/models/ChangeResourceRecordSetsOutputError+HttpResponseErrorBinding.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ enum ChangeResourceRecordSetsOutputError { - static var httpBinding: ClientRuntime.HTTPResponseErrorBinding { + static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { { httpResponse, responseDocumentClosure in - if let customBatchError = try await CustomInvalidBatchError.makeFromHttpResponse(httpResponse) { - return InvalidChangeBatch( - customError: customBatchError, - httpResponse: httpResponse - ) - } let responseReader = try await responseDocumentClosure(httpResponse) - let errorBodyReader = AWSClientRuntime.RestXMLError.errorBodyReader(responseReader: responseReader, noErrorWrapping: false) - let restXMLError = try AWSClientRuntime.RestXMLError(responseReader: responseReader, noErrorWrapping: false) - switch restXMLError.code { - case "InvalidChangeBatch": return try await InvalidChangeBatch.responseErrorBinding(httpResponse: httpResponse, reader: errorBodyReader, message: restXMLError.message, requestID: restXMLError.requestID) - default: return try await AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: restXMLError.message, requestID: restXMLError.requestID, typeName: restXMLError.code) + let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + switch baseError.code { + case "InvalidChangeBatch": return try InvalidChangeBatch.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt index e628bc287cc..790bd7d0617 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt @@ -22,19 +22,17 @@ class Ec2QueryHttpResponseBindingErrorGeneratorTests { val expectedContents = """ enum GreetingWithErrorsOutputError { - static var httpBinding: ClientRuntime.HTTPResponseErrorBinding { + static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { { httpResponse, responseDocumentClosure in - let serviceError = try await EC2ProtocolClientTypes.makeServiceError(httpResponse, decoder, ec2QueryError) - if let error = serviceError { return error } let responseReader = try await responseDocumentClosure(httpResponse) - let reader = responseReader["Errors"]["Error"] - let requestID: String? = try responseReader["RequestId"].readIfPresent() - let errorCode: String? = try reader["Code"].readIfPresent() - let message: String? = try reader["Message"].readIfPresent() - switch errorCode { - case "ComplexError": return try await ComplexError.responseErrorBinding(httpResponse: httpResponse, reader: reader, message: message, requestID: requestID) - case "InvalidGreeting": return try await InvalidGreeting.responseErrorBinding(httpResponse: httpResponse, reader: reader, message: message, requestID: requestID) - default: return try await AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: message, requestID: requestID, typeName: errorCode) + let baseError = try AWSClientRuntime.EC2QueryError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let serviceError = try EC2ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) } } } @@ -51,13 +49,14 @@ enum GreetingWithErrorsOutputError { val expectedContents = """ extension ComplexError { - static func responseErrorBinding(httpResponse: ClientRuntime.HttpResponse, reader: SmithyXML.Reader, message: Swift.String? = nil, requestID: Swift.String? = nil) async throws -> Swift.Error { + static func makeError(baseError: AWSClientRuntime.EC2QueryError) throws -> ComplexError { + let reader = baseError.errorBodyReader var value = ComplexError() - value.properties.nested = try reader["Nested"].readIfPresent(readingClosure: EC2ProtocolClientTypes.ComplexNestedErrorData.readingClosure) + value.properties.nested = try reader["Nested"].readIfPresent(with: EC2ProtocolClientTypes.ComplexNestedErrorData.read(from:)) value.properties.topLevel = try reader["TopLevel"].readIfPresent() - value.httpResponse = httpResponse - value.requestID = requestID - value.message = message + value.httpResponse = baseError.httpResponse + value.requestID = baseError.requestID + value.message = baseError.message return value } } @@ -106,17 +105,16 @@ extension ComplexError { val context = setupTests("ec2query/query-error.smithy", "aws.protocoltests.ec2#AwsEc2") val contents = TestUtils.getFileContents(context.manifest, "/Example/models/AwsEc2+ServiceErrorHelperMethod.swift") contents.shouldSyntacticSanityCheck() - val expectedContents = - """ - extension EC2ProtocolClientTypes { - static func makeServiceError(_ httpResponse: ClientRuntime.HttpResponse, _ decoder: ClientRuntime.ResponseDecoder? = nil, _ error: AWSClientRuntime.Ec2QueryError) async throws -> Swift.Error? { - switch error.errorCode { - case "ExampleServiceError": return try await ExampleServiceError(httpResponse: httpResponse, decoder: decoder, message: error.message, requestID: error.requestId) - default: return nil - } - } - } - """.trimIndent() + val expectedContents = """ +extension EC2ProtocolClientTypes { + static func responseServiceErrorBinding(baseError: AWSClientRuntime.EC2QueryError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil + } + } +} +""" contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index e03313c9799..e3c78dcd40c 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -80,7 +80,7 @@ extension EventStreamTestClientTypes.TestEvents { extension EventStreamTestClientTypes.MessageWithAudio { static func write(value: EventStreamTestClientTypes.MessageWithAudio?, to writer: SmithyXML.Writer) throws { - guard let value else { writer.detach(); return } + guard let value else { return } try writer["audio"].write(value.audio, writingClosure: EventStreamTestClientTypes.Audio.write(value:to:)) try writer["exampleHeader"].write(value.exampleHeader) } @@ -93,7 +93,7 @@ extension EventStreamTestClientTypes.MessageWithAudio { return value } } - """.trimIndent() +""" contents.shouldContainOnlyOnce(expectedContents) } @@ -112,7 +112,7 @@ extension EventStreamTestClientTypes.MessageWithAudio { extension EventStreamTestClientTypes.Audio { static func write(value: EventStreamTestClientTypes.Audio?, to writer: SmithyXML.Writer) throws { - guard let value else { writer.detach(); return } + guard let value else { return } try writer["rawAudio"].write(value.rawAudio) } @@ -123,7 +123,7 @@ extension EventStreamTestClientTypes.Audio { return value } } - """.trimIndent() +""" contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt index 61de796a443..4264c903d09 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt @@ -23,18 +23,17 @@ class AWSRestXMLHttpResponseBindingErrorGeneratorTests { val expectedContents = """ enum GreetingWithErrorsOutputError { - static var httpBinding: ClientRuntime.HTTPResponseErrorBinding { + static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { { httpResponse, responseDocumentClosure in let responseReader = try await responseDocumentClosure(httpResponse) - let errorBodyReader = AWSClientRuntime.RestXMLError.errorBodyReader(responseReader: responseReader, noErrorWrapping: false) - if let serviceError = try await ClientRuntime.RestXmlerrorsClientTypes.responseServiceErrorBinding(httpResponse, errorBodyReader) { + let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let serviceError = try RestXmlerrorsClientTypes.responseServiceErrorBinding(baseError: baseError) { return serviceError } - let restXMLError = try AWSClientRuntime.RestXMLError(responseReader: responseReader, noErrorWrapping: false) - switch restXMLError.code { - case "ComplexXMLError": return try await ComplexXMLError.responseErrorBinding(httpResponse: httpResponse, reader: errorBodyReader, message: restXMLError.message, requestID: restXMLError.requestID) - case "InvalidGreeting": return try await InvalidGreeting.responseErrorBinding(httpResponse: httpResponse, reader: errorBodyReader, message: restXMLError.message, requestID: restXMLError.requestID) - default: return try await AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: restXMLError.message, requestID: restXMLError.requestID, typeName: restXMLError.code) + switch baseError.code { + case "ComplexXMLError": return try ComplexXMLError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) } } } @@ -50,16 +49,18 @@ enum GreetingWithErrorsOutputError { val expectedContents = """ extension ComplexXMLError { - static func responseErrorBinding(httpResponse: ClientRuntime.HttpResponse, reader: SmithyXML.Reader, message: Swift.String? = nil, requestID: Swift.String? = nil) async throws -> Swift.Error { + static func makeError(baseError: AWSClientRuntime.RestXMLError) throws -> ComplexXMLError { + let reader = baseError.errorBodyReader + let httpResponse = baseError.httpResponse var value = ComplexXMLError() if let headerHeaderValue = httpResponse.headers.value(for: "X-Header") { value.properties.header = headerHeaderValue } - value.properties.nested = try reader["Nested"].readIfPresent(readingClosure: RestXmlerrorsClientTypes.ComplexXMLNestedErrorData.readingClosure) + value.properties.nested = try reader["Nested"].readIfPresent(with: RestXmlerrorsClientTypes.ComplexXMLNestedErrorData.read(from:)) value.properties.topLevel = try reader["TopLevel"].readIfPresent() - value.httpResponse = httpResponse - value.requestID = requestID - value.message = message + value.httpResponse = baseError.httpResponse + value.requestID = baseError.requestID + value.message = baseError.message return value } } @@ -112,16 +113,18 @@ extension ComplexXMLError { val expectedContents = """ extension ComplexXMLErrorNoErrorWrapping { - static func responseErrorBinding(httpResponse: ClientRuntime.HttpResponse, reader: SmithyXML.Reader, message: Swift.String? = nil, requestID: Swift.String? = nil) async throws -> Swift.Error { + static func makeError(baseError: AWSClientRuntime.RestXMLError) throws -> ComplexXMLErrorNoErrorWrapping { + let reader = baseError.errorBodyReader + let httpResponse = baseError.httpResponse var value = ComplexXMLErrorNoErrorWrapping() if let headerHeaderValue = httpResponse.headers.value(for: "X-Header") { value.properties.header = headerHeaderValue } - value.properties.nested = try reader["Nested"].readIfPresent(readingClosure: RestXmlerrorsClientTypes.ComplexXMLNestedErrorData.readingClosure) + value.properties.nested = try reader["Nested"].readIfPresent(with: RestXmlerrorsClientTypes.ComplexXMLNestedErrorData.read(from:)) value.properties.topLevel = try reader["TopLevel"].readIfPresent() - value.httpResponse = httpResponse - value.requestID = requestID - value.message = message + value.httpResponse = baseError.httpResponse + value.requestID = baseError.requestID + value.message = baseError.message return value } } @@ -136,9 +139,9 @@ extension ComplexXMLErrorNoErrorWrapping { contents.shouldSyntacticSanityCheck() val expectedContents = """ extension RestXmlerrorsClientTypes { - static func responseServiceErrorBinding(httpResponse: ClientRuntime.HttpResponse, reader: SmithyXML.Reader) async throws -> Swift.Error? { - switch error.errorCode { - case "ExampleServiceError": return try await ExampleServiceError(httpResponse: httpResponse, reader: reader, message: error.message, requestID: error.requestId) + static func responseServiceErrorBinding(baseError: AWSClientRuntime.RestXMLError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) default: return nil } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt index 9aff0c5f8df..72f5b81dc5e 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt @@ -17,7 +17,7 @@ class S3UnwrappedXMLOutputTraitTests { val expectedContents = """ extension GetBucketLocationOutput { - static var httpBinding: ClientRuntime.HTTPResponseOutputBinding { + static var httpBinding: SmithyReadWrite.WireResponseOutputBinding { { httpResponse, responseDocumentClosure in let responseReader = try await responseDocumentClosure(httpResponse) let reader = responseReader.unwrap() From 2e148ce7f2aa1fd7c7831538eb675ee73c3eb940 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 15 Apr 2024 19:04:12 -0500 Subject: [PATCH 07/27] Fix ktlint --- .../route53/Route53InvalidBatchErrorIntegration.kt | 3 --- .../aws/swift/codegen/customization/s3/S3ErrorIntegration.kt | 3 --- 2 files changed, 6 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt index 57692a16ab0..29a8b36ce02 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/route53/Route53InvalidBatchErrorIntegration.kt @@ -1,7 +1,6 @@ package software.amazon.smithy.aws.swift.codegen.customization.route53 import software.amazon.smithy.model.Model -import software.amazon.smithy.model.shapes.ServiceShape import software.amazon.smithy.swift.codegen.SmithyXMLTypes import software.amazon.smithy.swift.codegen.SwiftDelegator import software.amazon.smithy.swift.codegen.SwiftDependency @@ -12,8 +11,6 @@ import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SectionWriter import software.amazon.smithy.swift.codegen.integration.SectionWriterBinding import software.amazon.smithy.swift.codegen.integration.SwiftIntegration -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -import software.amazon.smithy.swift.codegen.model.expectShape class Route53InvalidBatchErrorIntegration : SwiftIntegration { override fun enabledForService(model: Model, settings: SwiftSettings): Boolean { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt index 0714fb62f73..c565f5c72f9 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3ErrorIntegration.kt @@ -16,7 +16,6 @@ import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SectionWriter import software.amazon.smithy.swift.codegen.integration.SectionWriterBinding import software.amazon.smithy.swift.codegen.integration.SwiftIntegration -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator import software.amazon.smithy.swift.codegen.model.expectShape import software.amazon.smithy.swift.codegen.model.getTrait @@ -34,8 +33,6 @@ class S3ErrorIntegration : SwiftIntegration { SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInit, s3MembersParams), SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInitMemberAssignment, s3MembersAssignment), SectionWriterBinding(StructureGenerator.AdditionalErrorMembers, s3Members), -// SectionWriterBinding(HTTPResponseBindingErrorGenerator.RestXMLResponseBindingSectionId, httpResponseBinding) - ) private val s3MembersParams = SectionWriter { writer, _ -> From 62a2cd2c738c978b9b16b0b9b3699ca1abd84ab3 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 11:02:20 -0500 Subject: [PATCH 08/27] Renames --- .../aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt | 8 ++++---- .../swift/codegen/awsquery/AwsQueryProtocolGenerator.kt | 8 ++++---- .../swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt | 8 ++++---- .../AWSEc2QueryHttpResponseTraitWithoutPayload.kt | 4 ++-- .../httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt | 4 ++-- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt index c02e5765655..4c27f5379dd 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt @@ -23,8 +23,8 @@ import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestErro import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestRequestGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestResponseGenerator import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator -import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator import software.amazon.smithy.swift.codegen.model.ShapeMetadata import software.amazon.smithy.swift.codegen.model.findStreamingMember import software.amazon.smithy.swift.codegen.model.getTrait @@ -94,7 +94,7 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() defaultTimestampFormat: TimestampFormatTrait.Format, path: String? ) { - StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() + StructEncodeGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() } override fun renderStructDecode( @@ -106,7 +106,7 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() defaultTimestampFormat: TimestampFormatTrait.Format, path: String ) { - StructDecodeXMLGenerator(ctx, shapeContainingMembers, members, shapeMetaData, writer).render() + StructDecodeGenerator(ctx, shapeContainingMembers, members, shapeMetaData, writer).render() } override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt index bc26166d436..3e92290686c 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt @@ -27,8 +27,8 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResp import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator -import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata @@ -85,7 +85,7 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String?, ) { - StructEncodeXMLGenerator( + StructEncodeGenerator( ctx, shapeContainingMembers, members, @@ -103,7 +103,7 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String, ) { - StructDecodeXMLGenerator( + StructDecodeGenerator( ctx, shapeContainingMembers, members, diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index 6f0abfb8a81..2c51ca518fd 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -27,8 +27,8 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResp import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.json.StructEncodeXMLGenerator -import software.amazon.smithy.swift.codegen.integration.serde.xml.StructDecodeXMLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata @@ -85,7 +85,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String?, ) { - StructEncodeXMLGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() + StructEncodeGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() } override fun renderStructDecode( @@ -97,7 +97,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { defaultTimestampFormat: TimestampFormatTrait.Format, path: String, ) { - StructDecodeXMLGenerator(ctx, shapeContainingMembers, members, mapOf(), writer).render() + StructDecodeGenerator(ctx, shapeContainingMembers, members, mapOf(), writer).render() } override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt index c250e0848eb..1b87c20b858 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt @@ -12,7 +12,7 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.serde.xml.MemberShapeDecodeXMLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.member.MemberShapeDecodeGenerator class AWSEc2QueryHttpResponseTraitWithoutPayload( val ctx: ProtocolGenerator.GenerationContext, @@ -24,7 +24,7 @@ class AWSEc2QueryHttpResponseTraitWithoutPayload( val bodyMembersWithoutQueryTrait = responseBindings.filter { it.location == HttpBinding.Location.DOCUMENT } .filter { !it.member.hasTrait(HttpQueryTrait::class.java) } .toMutableSet() - val generator = MemberShapeDecodeXMLGenerator(ctx, writer, outputShape) + val generator = MemberShapeDecodeGenerator(ctx, writer, outputShape) bodyMembersWithoutQueryTrait.sortedBy { it.memberName }.forEach { generator.render(it.member) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt index 75cf7490f50..f3699ebede1 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt @@ -12,7 +12,7 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.serde.xml.MemberShapeDecodeXMLGenerator +import software.amazon.smithy.swift.codegen.integration.serde.member.MemberShapeDecodeGenerator class AWSXMLHttpResponseTraitWithoutPayload( val ctx: ProtocolGenerator.GenerationContext, @@ -25,7 +25,7 @@ class AWSXMLHttpResponseTraitWithoutPayload( .filter { !it.member.hasTrait(HttpQueryTrait::class.java) } .map { it.member } .toSet() - val generator = MemberShapeDecodeXMLGenerator(ctx, writer, outputShape) + val generator = MemberShapeDecodeGenerator(ctx, writer, outputShape) bodyMembersWithoutQueryTrait.sortedBy { it.memberName }.forEach { generator.render(it) } } } From 6da7dca7a22ec62c92ebc181a398000fc8be7781 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 12:50:16 -0500 Subject: [PATCH 09/27] Add protocol to base errors --- .../Errors/UnknownAWSHTTPServiceError.swift | 33 ++++++++++--------- .../Protocols/AWSJSON/AWSJSONError.swift | 3 +- .../Protocols/AWSQuery/AWSQueryError.swift | 3 +- .../Protocols/Ec2Query/EC2QueryError.swift | 3 +- .../Protocols/RestJSON/RestJSONError.swift | 3 +- .../Protocols/RestXML/RestXMLError.swift | 3 +- 6 files changed, 27 insertions(+), 21 deletions(-) diff --git a/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift b/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift index 9d9a19240dc..0be8498135b 100644 --- a/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift +++ b/Sources/Core/AWSClientRuntime/Errors/UnknownAWSHTTPServiceError.swift @@ -58,30 +58,31 @@ extension UnknownAWSHTTPServiceError { /// - requestID2: The request ID2 associated with this error (ID2 used on S3 only.) Defaults to `nil`. /// - typeName: The non-namespaced name of the error type for this error, or `nil`. /// - Returns: An error that represents the response. - public static func makeError( - httpResponse: HttpResponse, - message: String?, - requestID: String?, - requestID2: String? = nil, - typeName: String? + public static func makeError( + baseError: Base ) throws -> Error { let candidates: [UnknownAWSHTTPErrorCandidate.Type] = [ InvalidAccessKeyId.self ] - if let Candidate = candidates.first(where: { $0.errorCode == typeName }) { + if let Candidate = candidates.first(where: { $0.errorCode == baseError.code }) { return Candidate.init( - httpResponse: httpResponse, - message: message, - requestID: requestID, - requestID2: requestID2 + httpResponse: baseError.httpResponse, + message: baseError.message, + requestID: baseError.requestID, + requestID2: baseError.requestID2 ) } return UnknownAWSHTTPServiceError( - httpResponse: httpResponse, - message: message, - requestID: requestID, - requestID2: requestID2, - typeName: typeName + httpResponse: baseError.httpResponse, + message: baseError.message, + requestID: baseError.requestID, + requestID2: baseError.requestID2, + typeName: baseError.code ) } } + +extension ClientRuntime.BaseError { + + var requestID2: String? { nil } +} diff --git a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift index 3d603a60718..115d72d9090 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/AWSJSON/AWSJSONError.swift @@ -5,11 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import protocol ClientRuntime.BaseError import enum ClientRuntime.BaseErrorDecodeError import class ClientRuntime.HttpResponse import class SmithyJSON.Reader -public struct AWSJSONError { +public struct AWSJSONError: BaseError { public let code: String public let message: String? public let requestID: String? diff --git a/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift index 8fc1a25f06c..f3a86710813 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/AWSQuery/AWSQueryError.swift @@ -5,11 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import protocol ClientRuntime.BaseError import enum ClientRuntime.BaseErrorDecodeError import class ClientRuntime.HttpResponse import class SmithyXML.Reader -public struct AWSQueryError { +public struct AWSQueryError: BaseError { public let code: String public let message: String? public let requestID: String? diff --git a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift index d3dd690b37a..4e9af799471 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/Ec2Query/EC2QueryError.swift @@ -5,11 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import protocol ClientRuntime.BaseError import enum ClientRuntime.BaseErrorDecodeError import class ClientRuntime.HttpResponse import class SmithyXML.Reader -public struct EC2QueryError { +public struct EC2QueryError: BaseError { public let code: String public let message: String? public let requestID: String? diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift index 498533bf5fa..71a47868080 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestJSON/RestJSONError.swift @@ -5,11 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import protocol ClientRuntime.BaseError import enum ClientRuntime.BaseErrorDecodeError import class ClientRuntime.HttpResponse import class SmithyJSON.Reader -public struct RestJSONError { +public struct RestJSONError: BaseError { public let code: String public let message: String? public let requestID: String? diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift index a671a405c73..4a6aed09b4b 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift @@ -5,11 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import protocol ClientRuntime.BaseError import enum ClientRuntime.BaseErrorDecodeError import class ClientRuntime.HttpResponse import class SmithyXML.Reader -public struct RestXMLError { +public struct RestXMLError: BaseError { public let code: String public let message: String? public let requestID: String? From 91d8a762c2900a7ae13e795d0b2aea8a70994536 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 13:06:33 -0500 Subject: [PATCH 10/27] Fix codegen tests --- .../awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt | 2 +- .../AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt | 2 +- .../customizations/Route53InvalidBatchErrorIntegrationTests.kt | 2 +- .../ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt | 2 +- .../restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt index f3ada0eff68..ebe17a9f280 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt @@ -32,7 +32,7 @@ enum GreetingWithErrorsOutputError { switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt index 5aa23eff51d..274dad14c81 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt @@ -31,7 +31,7 @@ enum GreetingWithErrorsOutputError { switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt index 0d71a3a7d85..379c7d3cb6a 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt @@ -34,7 +34,7 @@ enum ChangeResourceRecordSetsOutputError { let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) switch baseError.code { case "InvalidChangeBatch": return try InvalidChangeBatch.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt index 790bd7d0617..5b736b9b273 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt @@ -32,7 +32,7 @@ enum GreetingWithErrorsOutputError { switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt index 4264c903d09..24e7f6e4c50 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt @@ -33,7 +33,7 @@ enum GreetingWithErrorsOutputError { switch baseError.code { case "ComplexXMLError": return try ComplexXMLError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } From a7d0436a7043bd5107cbb8f95c2a6c63f79ac423 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 13:24:26 -0500 Subject: [PATCH 11/27] Fix ktlint --- .../smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt | 2 +- .../aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt | 2 +- .../aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt index 4c27f5379dd..f92cbc92b6c 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt @@ -23,8 +23,8 @@ import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestErro import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestRequestGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestResponseGenerator import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.model.ShapeMetadata import software.amazon.smithy.swift.codegen.model.findStreamingMember import software.amazon.smithy.swift.codegen.model.getTrait diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt index 3e92290686c..75b7898f399 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt @@ -27,8 +27,8 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResp import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt index 2c51ca518fd..9f5df2af833 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt @@ -27,8 +27,8 @@ import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResp import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator +import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata From 078cbfe7a5559485864284cfef30813628b16d2e Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 13:26:48 -0500 Subject: [PATCH 12/27] Fix AWSClientRuntimeTests --- .../Protocols/RestJSON/RestJSONErrorTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift b/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift index d20c1d586c2..71ce4cf277e 100644 --- a/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift +++ b/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift @@ -105,7 +105,7 @@ public enum GreetingWithErrorsError { let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(httpResponse: httpResponse, message: baseError.message, requestID: baseError.requestID, typeName: baseError.code) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } From 045fc32c0e4fbbaacf14e7ca93a399c648a67ece Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 14:31:03 -0500 Subject: [PATCH 13/27] Delete unused error type --- .../Errors/RestXMLError+AWS.swift | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift diff --git a/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift b/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift deleted file mode 100644 index 62e60335a94..00000000000 --- a/Sources/Core/AWSClientRuntime/Errors/RestXMLError+AWS.swift +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -import ClientRuntime -import class SmithyXML.Reader - -extension RestXMLError { - - /// Makes a `RestXMLError` from the provided `HttpResponse`. - /// If the response body is empty and the status code is "not-found" aka 404, then this returns a `RestXMLError` instance with an error code of "NotFound". - /// Otherwise, it creates an instance of `RestXMLError` by calling ``RestXMLError.init(httpResponse: HttpResponse)``. - /// - Parameter httpResponse: The HTTP response from the server. - /// - Parameter responseReader: The Reader created from the XML response body. - /// - Parameter noErrorWrapping: `true` if the error is wrapped in a XML `ErrorResponse` element, `false` otherwise. - /// - Returns: A`RestXMLError` instance with an error code of "NotFound" if the response body is empty and the status code is 404, else returns a `RestXMLError` by calling the `RestXMLError` initializer. - /// - Throws: An error if it fails to decode the response body. -// public static func makeError( -// from httpResponse: HttpResponse, -// responseReader: SmithyXML.Reader, -// noErrorWrapping: Bool -// ) async throws -> RestXMLError { -// return httpResponse.statusCodeIsNotFoundAndBodyIsEmpty -// ? .init(code: "NotFound", message: "404 Not Found", requestID: httpResponse.requestId) -// : try .init(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: noErrorWrapping) -// } -} From 67df7939d5f7f9204e13b677d639c87a54ea619c Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 19:32:23 -0500 Subject: [PATCH 14/27] Refactoring --- ....kt => AWSHTTPBindingProtocolGenerator.kt} | 12 ++--- ...ns.kt => AWSHTTPProtocolCustomizations.kt} | 9 +++- .../AWSHttpProtocolClientGeneratorFactory.kt | 4 +- .../AWSHttpProtocolClientOperationFactory.kt | 53 ------------------- .../smithy/aws/swift/codegen/AddProtocols.kt | 20 +++---- .../codegen/FormURLHttpBindingResolver.kt | 4 +- .../aws/swift/codegen/PresignerGenerator.kt | 4 +- .../AWSHttpProtocolJson10Customizations.kt | 10 ---- .../AWSHttpProtocolJson11Customizations.kt | 10 ---- ...ator.kt => AWSJSON1_0ProtocolGenerator.kt} | 33 ++++-------- ...ator.kt => AWSJSON1_1ProtocolGenerator.kt} | 30 +++-------- .../codegen/awsjson/AWSJSONCustomizations.kt | 17 ++++++ ...olver.kt => AWSJSONHttpBindingResolver.kt} | 6 +-- ...WSJsonHttpResponseBindingErrorGenerator.kt | 15 ------ ...mizations.kt => AWSQueryCustomizations.kt} | 15 +++--- ...erator.kt => AWSQueryProtocolGenerator.kt} | 33 +++--------- ...SQueryHttpResponseBindingErrorGenerator.kt | 15 ------ .../MessageEncoderIntegration.kt | 19 ------- .../presignable/PresignableUrlIntegration.kt | 4 +- .../customization/s3/S3ErrorIntegration.kt | 6 +-- ...sponseBindingErrorInitGeneratorFactory.kt} | 31 ++++++----- ...mizations.kt => EC2QueryCustomizations.kt} | 10 +++- ...erator.kt => EC2QueryProtocolGenerator.kt} | 33 +++--------- ...2QueryHttpResponseBindingErrorGenerator.kt | 15 ------ ...esponseBindingErrorInitGeneratorFactory.kt | 43 --------------- ...Ec2QueryHttpResponseTraitWithoutPayload.kt | 30 ----------- ...tor.kt => MessageMarshallableGenerator.kt} | 2 +- ...r.kt => MessageUnmarshallableGenerator.kt} | 4 +- .../AWSHttpProtocolRestJsonCustomizations.kt | 10 ---- .../restjson/AWSRestJson1ProtocolGenerator.kt | 31 +++-------- ...neratable.kt => RestJSONCustomizations.kt} | 6 +-- .../AWSHttpProtocolRestXMLCustomizations.kt | 10 ---- ...rGenerator.kt => RestXMLCustomizations.kt} | 6 +-- ...nerator.kt => RestXMLProtocolGenerator.kt} | 31 +++-------- ... AWSXMLHTTPResponseTraitWithoutPayload.kt} | 6 +-- ...swift.codegen.integration.SwiftIntegration | 1 - .../codegen/AWSXAmzTargetMiddlewareTests.kt | 4 +- ...HttpResponseBindingErrorGeneratorTests.kt} | 4 +- .../awsjson/AWSJsonHttpInitialRequestTests.kt | 2 +- .../awsquery/AWSQueryOperationStackTest.kt | 2 +- .../awsquery/BlobEncodeGeneratorTests.kt | 2 +- .../ListEncodeFormURLGeneratorTests.kt | 2 +- .../MapEncodeFormURLGeneratorTests.kt | 2 +- ...yIdempotencyTokenAutoFillGeneratorTests.kt | 2 +- .../StructDecodeWrappedXMLGeneratorTests.kt | 2 +- .../awsquery/TimestampGeneratorTests.kt | 2 +- .../codegen/customizations/BoxServicesTest.kt | 4 +- ...yHttpResponseBindingErrorGeneratorTests.kt | 2 +- .../restxml/AWSRestXMLEventStreamTests.kt | 2 +- ...HTTPResponseBindingErrorGeneratorTests.kt} | 4 +- ...MLProtocolNoInputNoOutputGeneratorTests.kt | 2 +- ...tXMLProtocolXMLAttributesGeneratorTests.kt | 2 +- .../serde/S3UnwrappedXMLOutputTraitTests.kt | 4 +- 53 files changed, 167 insertions(+), 465 deletions(-) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{AWSHttpBindingProtocolGenerator.kt => AWSHTTPBindingProtocolGenerator.kt} (94%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{AWSHttpProtocolCustomizations.kt => AWSHTTPProtocolCustomizations.kt} (89%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientOperationFactory.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson10Customizations.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson11Customizations.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/{AwsJson1_0_ProtocolGenerator.kt => AWSJSON1_0ProtocolGenerator.kt} (68%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/{AwsJson1_1_ProtocolGenerator.kt => AWSJSON1_1ProtocolGenerator.kt} (65%) create mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/{AwsJsonHttpBindingResolver.kt => AWSJSONHttpBindingResolver.kt} (84%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/{AWSHttpProtocolAwsQueryCustomizations.kt => AWSQueryCustomizations.kt} (68%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/{AwsQueryProtocolGenerator.kt => AWSQueryProtocolGenerator.kt} (71%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/MessageEncoderIntegration.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt => ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt} (56%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/{AWSHttpProtocolEc2QueryCustomizations.kt => EC2QueryCustomizations.kt} (70%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/{Ec2QueryProtocolGenerator.kt => EC2QueryProtocolGenerator.kt} (70%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/{XMLMessageMarshallableGenerator.kt => MessageMarshallableGenerator.kt} (99%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/{XMLMessageUnmarshallableGenerator.kt => MessageUnmarshallableGenerator.kt} (98%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSHttpProtocolRestJsonCustomizations.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/{AWSRestJson1HttpResponseBindingErrorGeneratable.kt => RestJSONCustomizations.kt} (50%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/{AWSRestXMLHttpResponseBindingErrorGenerator.kt => RestXMLCustomizations.kt} (51%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/{RestXmlProtocolGenerator.kt => RestXMLProtocolGenerator.kt} (57%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/{AWSXMLHttpResponseTraitWithoutPayload.kt => AWSXMLHTTPResponseTraitWithoutPayload.kt} (92%) rename codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/{AWSJsonHttpResponseBindingErrorGeneratorTests.kt => AWSJSONHttpResponseBindingErrorGeneratorTests.kt} (97%) rename codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/{AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt => AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt} (98%) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt similarity index 94% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt index f92cbc92b6c..9d983c079ed 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt @@ -17,7 +17,8 @@ import software.amazon.smithy.rulesengine.language.EndpointRuleSet import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait import software.amazon.smithy.rulesengine.traits.EndpointTestsTrait import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.HttpBindingProtocolGenerator +import software.amazon.smithy.swift.codegen.integration.HTTPBindingProtocolGenerator +import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable import software.amazon.smithy.swift.codegen.integration.HttpProtocolTestGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestErrorGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolUnitTestRequestGenerator @@ -32,12 +33,12 @@ import software.amazon.smithy.swift.codegen.model.isInputEventStream import software.amazon.smithy.swift.codegen.model.isOutputEventStream import software.amazon.smithy.swift.codegen.testModuleName -abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() { +abstract class AWSHTTPBindingProtocolGenerator( + customizations: HTTPProtocolCustomizable, +) : HTTPBindingProtocolGenerator(customizations) { override var serviceErrorProtocolSymbol: Symbol = AWSClientRuntimeTypes.Core.AWSServiceError - override val unknownServiceErrorSymbol: Symbol = AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError - override val retryErrorInfoProviderSymbol: Symbol get() = AWSClientRuntimeTypes.Core.AWSRetryErrorInfoProvider @@ -49,7 +50,6 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() open val testsToIgnore: Set = setOf() open val tagsToIgnore: Set = setOf() - override val shouldRenderDecodableBodyStructForInputShapes = true override val shouldRenderEncodableConformance = false override fun generateProtocolUnitTests(ctx: ProtocolGenerator.GenerationContext): Int { val imports = listOf(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) @@ -58,7 +58,7 @@ abstract class AWSHttpBindingProtocolGenerator : HttpBindingProtocolGenerator() requestTestBuilder, responseTestBuilder, errorTestBuilder, - httpProtocolCustomizable, + customizations, operationMiddleware, getProtocolHttpBindingResolver(ctx, defaultContentType), imports, diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPProtocolCustomizations.kt similarity index 89% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPProtocolCustomizations.kt index 43513e26211..aaae7926a00 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPProtocolCustomizations.kt @@ -6,18 +6,19 @@ package software.amazon.smithy.aws.swift.codegen import software.amazon.smithy.aws.swift.codegen.customization.RulesBasedAuthSchemeResolverGenerator +import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ServiceShape import software.amazon.smithy.swift.codegen.AuthSchemeResolverGenerator import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.DefaultHttpProtocolCustomizations +import software.amazon.smithy.swift.codegen.integration.DefaultHTTPProtocolCustomizations import software.amazon.smithy.swift.codegen.integration.HttpProtocolServiceClient import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.ServiceConfig import software.amazon.smithy.swift.codegen.model.isInputEventStream import software.amazon.smithy.swift.codegen.model.isOutputEventStream -abstract class AWSHttpProtocolCustomizations : DefaultHttpProtocolCustomizations() { +abstract class AWSHTTPProtocolCustomizations : DefaultHTTPProtocolCustomizations() { override fun renderContextAttributes(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter, serviceShape: ServiceShape, op: OperationShape) { val endpointPrefix = ctx.service.endpointPrefix // get endpoint prefix from smithy trait @@ -61,4 +62,8 @@ abstract class AWSHttpProtocolCustomizations : DefaultHttpProtocolCustomizations val clientProperties = getClientProperties() return AWSHttpProtocolServiceClient(ctx, writer, clientProperties, serviceConfig) } + + override val messageDecoderSymbol: Symbol = AWSClientRuntimeTypes.AWSEventStream.AWSMessageDecoder + + override val unknownServiceErrorSymbol: Symbol = AWSClientRuntimeTypes.Core.UnknownAWSHTTPServiceError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt index 739326c24b7..773a09e73a5 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt @@ -9,7 +9,7 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.HttpProtocolClientGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolClientGeneratorFactory -import software.amazon.smithy.swift.codegen.integration.HttpProtocolCustomizable +import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.middleware.OperationMiddleware @@ -20,7 +20,7 @@ class AWSHttpProtocolClientGeneratorFactory : HttpProtocolClientGeneratorFactory writer: SwiftWriter, serviceName: String, defaultContentType: String, - httpProtocolCustomizable: HttpProtocolCustomizable, + httpProtocolCustomizable: HTTPProtocolCustomizable, operationMiddleware: OperationMiddleware ): HttpProtocolClientGenerator { val config = AWSServiceConfig(writer, ctx) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientOperationFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientOperationFactory.kt deleted file mode 100644 index a38fe973ff3..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientOperationFactory.kt +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen - -import software.amazon.smithy.aws.swift.codegen.awsjson.AWSHttpProtocolJson10Customizations -import software.amazon.smithy.aws.swift.codegen.awsjson.AWSHttpProtocolJson11Customizations -import software.amazon.smithy.aws.swift.codegen.awsquery.AWSHttpProtocolAwsQueryCustomizations -import software.amazon.smithy.aws.swift.codegen.ec2query.AWSHttpProtocolEc2QueryCustomizations -import software.amazon.smithy.aws.swift.codegen.restjson.AWSHttpProtocolRestJsonCustomizations -import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait -import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait -import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait -import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait -import software.amazon.smithy.aws.traits.protocols.RestJson1Trait -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.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.DefaultHttpProtocolCustomizations -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator - -class AWSHttpProtocolClientCustomizableFactory { - fun constructClientCustomizable(protocol: ShapeId): DefaultHttpProtocolCustomizations { - when (protocol) { - AwsJson1_0Trait.ID -> return AWSHttpProtocolJson10Customizations() - AwsJson1_1Trait.ID -> return AWSHttpProtocolJson11Customizations() - RestJson1Trait.ID -> return AWSHttpProtocolRestJsonCustomizations() - AwsQueryTrait.ID -> return AWSHttpProtocolAwsQueryCustomizations() - Ec2QueryTrait.ID -> return AWSHttpProtocolEc2QueryCustomizations() - } - return AWSHttpProtocolNoopCustomizations() - } -} - -class AWSHttpProtocolNoopCustomizations : DefaultHttpProtocolCustomizations() { - override fun renderContextAttributes( - ctx: ProtocolGenerator.GenerationContext, - writer: SwiftWriter, - serviceShape: ServiceShape, - op: OperationShape - ) { - } - - override fun renderEventStreamAttributes( - ctx: ProtocolGenerator.GenerationContext, - writer: SwiftWriter, - op: OperationShape, - ) { - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt index fabbb1a92a1..ddc7ab50bb6 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt @@ -4,12 +4,12 @@ */ package software.amazon.smithy.aws.swift.codegen -import software.amazon.smithy.aws.swift.codegen.awsjson.AwsJson1_0_ProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.awsjson.AwsJson1_1_ProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.awsquery.AwsQueryProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.ec2query.Ec2QueryProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_0ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.awsquery.AWSQueryProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.ec2query.EC2QueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.restxml.RestXmlProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.restxml.RestXMLProtocolGenerator import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SwiftIntegration @@ -27,10 +27,10 @@ class AddProtocols : SwiftIntegration { override val protocolGenerators: List = listOf( AWSRestJson1ProtocolGenerator(), - AwsJson1_0_ProtocolGenerator(), - AwsJson1_1_ProtocolGenerator(), - RestXmlProtocolGenerator(), - AwsQueryProtocolGenerator(), - Ec2QueryProtocolGenerator() + AWSJSON1_0ProtocolGenerator(), + AWSJSON1_1ProtocolGenerator(), + RestXMLProtocolGenerator(), + AWSQueryProtocolGenerator(), + EC2QueryProtocolGenerator() ) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/FormURLHttpBindingResolver.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/FormURLHttpBindingResolver.kt index 775fba682b1..3f9e1fa5414 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/FormURLHttpBindingResolver.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/FormURLHttpBindingResolver.kt @@ -11,8 +11,8 @@ import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.protocols.core.StaticHttpBindingResolver class FormURLHttpBindingResolver( - private val context: ProtocolGenerator.GenerationContext, - private val contentType: String + context: ProtocolGenerator.GenerationContext, + contentType: String ) : StaticHttpBindingResolver(context, httpTrait, contentType) { companion object { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGenerator.kt index 5a3a57157a0..82b7b866b90 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGenerator.kt @@ -89,7 +89,7 @@ class PresignerGenerator : SwiftIntegration { writer.write("let serviceName = \$S", ctx.settings.sdkId) writer.write("let input = self") val operationStackName = "operation" - for (prop in protocolGenerator.httpProtocolCustomizable.getClientProperties()) { + for (prop in protocolGenerator.customizations.getClientProperties()) { prop.addImportsAndDependencies(writer) prop.renderInstantiation(writer) prop.renderConfiguration(writer) @@ -99,7 +99,7 @@ class PresignerGenerator : SwiftIntegration { protocolGeneratorContext, writer, httpBindingResolver, - protocolGenerator.httpProtocolCustomizable, + protocolGenerator.customizations, operationMiddleware, operationStackName ) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson10Customizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson10Customizations.kt deleted file mode 100644 index f1da36eb654..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson10Customizations.kt +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.awsjson - -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations - -class AWSHttpProtocolJson10Customizations : AWSHttpProtocolCustomizations() diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson11Customizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson11Customizations.kt deleted file mode 100644 index e70a64914fd..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSHttpProtocolJson11Customizations.kt +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.awsjson - -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations - -class AWSHttpProtocolJson11Customizations : AWSHttpProtocolCustomizations() diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_0ProtocolGenerator.kt similarity index 68% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_0ProtocolGenerator.kt index a0dbbcada83..bdba03a4af4 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_0_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_0ProtocolGenerator.kt @@ -5,46 +5,35 @@ package software.amazon.smithy.aws.swift.codegen.awsjson -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorInitGenerator +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep -open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { +open class AWSJSON1_0ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCustomizations()) { override val defaultContentType = "application/x-amz-json-1.0" - override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS override val protocol: ShapeId = AwsJson1_0Trait.ID - override val httpProtocolCustomizable = AWSHttpProtocolClientCustomizableFactory().constructClientCustomizable(protocol) - override val httpResponseGenerator = HttpResponseGenerator( - unknownServiceErrorSymbol, - defaultTimestampFormat, - XMLHttpResponseBindingOutputGenerator(), - AWSJsonHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat, AWSClientRuntimeTypes.AWSJSON.AWSJSONError) - ) + override val httpResponseGenerator = HttpResponseGenerator(customizations) override val shouldRenderEncodableConformance: Boolean = true - override val shouldRenderDecodableBodyStructForInputShapes: Boolean = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_awsJson1_0", "SDKAppendsGzipAndIgnoresHttpProvidedEncoding_awsJson1_0", ) override val tagsToIgnore = setOf("defaults") override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, defaultContentType: String): - HttpBindingResolver = AwsJsonHttpBindingResolver(ctx, defaultContentType) + HttpBindingResolver = AWSJSONHttpBindingResolver(ctx, defaultContentType) override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { super.addProtocolSpecificMiddleware(ctx, operation) @@ -62,7 +51,7 @@ open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -70,7 +59,7 @@ open class AwsJson1_0_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) for (streamingShape in streamingShapes) { messageMarshallableGenerator.render(streamingShape) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_1ProtocolGenerator.kt similarity index 65% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_1ProtocolGenerator.kt index f11a362fe72..72eeb36e1f8 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJson1_1_ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_1ProtocolGenerator.kt @@ -5,46 +5,32 @@ package software.amazon.smithy.aws.swift.codegen.awsjson -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep -class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { +class AWSJSON1_1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCustomizations()) { override val defaultContentType = "application/x-amz-json-1.1" - override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS override val protocol: ShapeId = AwsJson1_1Trait.ID - override val httpProtocolCustomizable = AWSHttpProtocolClientCustomizableFactory().constructClientCustomizable(protocol) - override val httpResponseGenerator = HttpResponseGenerator( - unknownServiceErrorSymbol, - defaultTimestampFormat, - XMLHttpResponseBindingOutputGenerator(), - AWSJsonHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator(defaultTimestampFormat, AWSClientRuntimeTypes.AWSJSON.AWSJSONError), - ) + override val httpResponseGenerator = HttpResponseGenerator(customizations) override val shouldRenderEncodableConformance: Boolean = true - override val shouldRenderDecodableBodyStructForInputShapes: Boolean = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_awsJson1_1", "SDKAppendsGzipAndIgnoresHttpProvidedEncoding_awsJson1_1", ) override val tagsToIgnore = setOf("defaults") override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, defaultContentType: String): - HttpBindingResolver = AwsJsonHttpBindingResolver(ctx, defaultContentType) + HttpBindingResolver = AWSJSONHttpBindingResolver(ctx, defaultContentType) override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { super.addProtocolSpecificMiddleware(ctx, operation) @@ -62,7 +48,7 @@ class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -70,7 +56,7 @@ class AwsJson1_1_ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) for (streamingShape in streamingShapes) { messageMarshallableGenerator.render(streamingShape) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt new file mode 100644 index 00000000000..9c414a7968d --- /dev/null +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt @@ -0,0 +1,17 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +package software.amazon.smithy.aws.swift.codegen.awsjson + +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes +import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations +import software.amazon.smithy.codegen.core.Symbol +import software.amazon.smithy.model.traits.TimestampFormatTrait + +class AWSJSONCustomizations : AWSHTTPProtocolCustomizations() { + override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.AWSJSON.AWSJSONError + + override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS +} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJsonHttpBindingResolver.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpBindingResolver.kt similarity index 84% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJsonHttpBindingResolver.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpBindingResolver.kt index 2b99f095234..bc82089e0f2 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AwsJsonHttpBindingResolver.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpBindingResolver.kt @@ -10,9 +10,9 @@ import software.amazon.smithy.model.traits.HttpTrait import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.protocols.core.StaticHttpBindingResolver -class AwsJsonHttpBindingResolver( - private val context: ProtocolGenerator.GenerationContext, - private val defaultContentType: String +class AWSJSONHttpBindingResolver( + context: ProtocolGenerator.GenerationContext, + defaultContentType: String ) : StaticHttpBindingResolver(context, awsJsonHttpTrait, defaultContentType) { companion object { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt deleted file mode 100644 index cddad77e01a..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGenerator.kt +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.awsjson - -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator - -class AWSJsonHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.AWSJSON.AWSJSONError -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryCustomizations.kt similarity index 68% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryCustomizations.kt index 054c164ac86..b5ece020b0c 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSHttpProtocolAwsQueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryCustomizations.kt @@ -5,18 +5,15 @@ package software.amazon.smithy.aws.swift.codegen.awsquery -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes +import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.Shape +import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.protocoltests.traits.HttpRequestTestCase import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.ClientProperty -class AWSHttpProtocolAwsQueryCustomizations : AWSHttpProtocolCustomizations() { - - override fun getClientProperties(): List { - return listOf() - } +class AWSQueryCustomizations : AWSHTTPProtocolCustomizations() { override fun customRenderBodyComparison(test: HttpRequestTestCase): ((SwiftWriter, HttpRequestTestCase, Symbol, Shape, String, String) -> Unit)? { return this::renderFormURLBodyComparison @@ -29,4 +26,8 @@ class AWSHttpProtocolAwsQueryCustomizations : AWSHttpProtocolCustomizations() { override fun alwaysHasHttpBody(): Boolean { return true } + + override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.AWSQuery.AWSQueryError + + override val defaultTimestampFormat = TimestampFormatTrait.Format.DATE_TIME } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryProtocolGenerator.kt similarity index 71% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryProtocolGenerator.kt index 75b7898f399..9e0fa03c5b4 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AwsQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryProtocolGenerator.kt @@ -5,14 +5,10 @@ package software.amazon.smithy.aws.swift.codegen.awsquery -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory +import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver -import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseTraitPayloadFactory -import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSQueryHttpResponseBindingErrorGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.shapes.OperationShape @@ -23,8 +19,6 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator @@ -32,27 +26,14 @@ import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncod import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata -open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { +open class AWSQueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSQueryCustomizations()) { override val defaultContentType = "application/x-www-form-urlencoded" - override val defaultTimestampFormat = TimestampFormatTrait.Format.DATE_TIME override val protocol: ShapeId = AwsQueryTrait.ID - override val httpProtocolCustomizable = AWSHttpProtocolClientCustomizableFactory().constructClientCustomizable(protocol) - override val httpResponseGenerator = HttpResponseGenerator( - unknownServiceErrorSymbol, - defaultTimestampFormat, - XMLHttpResponseBindingOutputGenerator(), - AWSQueryHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator( - defaultTimestampFormat, - AWSClientRuntimeTypes.AWSQuery.AWSQueryError, - AWSEc2QueryHttpResponseTraitPayloadFactory(), - ) - ) + override val httpResponseGenerator = HttpResponseGenerator(customizations) override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, defaultContentType: String): HttpBindingResolver = FormURLHttpBindingResolver(ctx, defaultContentType) - override val shouldRenderDecodableBodyStructForInputShapes = false override val shouldRenderEncodableConformance = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_awsQuery", @@ -62,7 +43,7 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -70,7 +51,7 @@ open class AwsQueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) streamingShapes.forEach { streamingMember -> messageMarshallableGenerator.render(streamingMember) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt deleted file mode 100644 index a5f86718aeb..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/httpResponse/AWSQueryHttpResponseBindingErrorGenerator.kt +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse - -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator - -class AWSQueryHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.AWSQuery.AWSQueryError -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/MessageEncoderIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/MessageEncoderIntegration.kt deleted file mode 100644 index 7257df48f35..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/MessageEncoderIntegration.kt +++ /dev/null @@ -1,19 +0,0 @@ -package software.amazon.smithy.aws.swift.codegen.customization - -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSSwiftDependency -import software.amazon.smithy.swift.codegen.integration.SectionWriter -import software.amazon.smithy.swift.codegen.integration.SectionWriterBinding -import software.amazon.smithy.swift.codegen.integration.SwiftIntegration -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithHttpPayload - -class MessageEncoderIntegration : SwiftIntegration { - private val messageDecoder: SectionWriter = SectionWriter { writer, _ -> - writer.addImport(AWSSwiftDependency.AWS_CLIENT_RUNTIME.target) - writer.write("let messageDecoder = \$N()", AWSClientRuntimeTypes.AWSEventStream.AWSMessageDecoder) - } - override val sectionWriters: List - get() = listOf( - SectionWriterBinding(HttpResponseTraitWithHttpPayload.MessageDecoderSectionId, messageDecoder) - ) -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/presignable/PresignableUrlIntegration.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/presignable/PresignableUrlIntegration.kt index dcca0ecf1f9..2f1bb0df809 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/presignable/PresignableUrlIntegration.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/presignable/PresignableUrlIntegration.kt @@ -117,7 +117,7 @@ class PresignableUrlIntegration(private val presignedOperations: Map get() = listOf( - SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInit, s3MembersParams), - SectionWriterBinding(XMLHttpResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInitMemberAssignment, s3MembersAssignment), + SectionWriterBinding(HTTPResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInit, s3MembersParams), + SectionWriterBinding(HTTPResponseBindingErrorInitGenerator.XMLHttpResponseBindingErrorInitMemberAssignment, s3MembersAssignment), SectionWriterBinding(StructureGenerator.AdditionalErrorMembers, s3Members), ) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt similarity index 56% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt index 87a7213c65d..6626a3fadf4 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseBindingErrorInitGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt @@ -3,42 +3,45 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.restxml +package software.amazon.smithy.aws.swift.codegen.ec2query -import software.amazon.smithy.aws.swift.codegen.restxml.httpResponse.AWSXMLHttpResponseTraitWithoutPayload +import software.amazon.smithy.aws.swift.codegen.restxml.httpResponse.AWSXMLHTTPResponseTraitWithoutPayload import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.swift.codegen.SwiftWriter +import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayload -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayloadFactory -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithoutHttpPayloadFactory +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingRenderable +import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HTTPResponseTraitPayload +import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HTTPResponseTraitPayloadFactory +import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HTTPResponseTraitWithoutHTTPPayloadFactory -class AWSXMLHttpResponseTraitPayloadFactory : HttpResponseTraitPayloadFactory { +class AWSEC2QueryHTTPResponseTraitPayloadFactory : HTTPResponseTraitPayloadFactory { override fun construct( ctx: ProtocolGenerator.GenerationContext, responseBindings: List, errorShape: Shape, - writer: SwiftWriter - ): HttpResponseBindingRenderable { - return HttpResponseTraitPayload( + writer: SwiftWriter, + customizations: HTTPProtocolCustomizable, + ): HTTPResponseBindingRenderable { + return HTTPResponseTraitPayload( ctx, responseBindings, errorShape, writer, - AWSXMLHttpResponseTraitWithoutHttpPayloadFactory() + customizations, + AWSEC2QueryHTTPResponseTraitWithoutHTTPPayloadFactory() ) } } -class AWSXMLHttpResponseTraitWithoutHttpPayloadFactory : HttpResponseTraitWithoutHttpPayloadFactory { +class AWSEC2QueryHTTPResponseTraitWithoutHTTPPayloadFactory : HTTPResponseTraitWithoutHTTPPayloadFactory { override fun construct( ctx: ProtocolGenerator.GenerationContext, responseBindings: List, outputShape: Shape, writer: SwiftWriter - ): HttpResponseBindingRenderable { - return AWSXMLHttpResponseTraitWithoutPayload(ctx, responseBindings, outputShape, writer) + ): HTTPResponseBindingRenderable { + return AWSXMLHTTPResponseTraitWithoutPayload(ctx, responseBindings, outputShape, writer) } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryCustomizations.kt similarity index 70% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryCustomizations.kt index 3eb5890ec30..7cb33a899f4 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSHttpProtocolEc2QueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryCustomizations.kt @@ -5,14 +5,16 @@ package software.amazon.smithy.aws.swift.codegen.ec2query -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations +import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes +import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.Shape +import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.protocoltests.traits.HttpRequestTestCase import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ClientProperty -class AWSHttpProtocolEc2QueryCustomizations : AWSHttpProtocolCustomizations() { +class EC2QueryCustomizations : AWSHTTPProtocolCustomizations() { override fun getClientProperties(): List { return listOf() @@ -29,4 +31,8 @@ class AWSHttpProtocolEc2QueryCustomizations : AWSHttpProtocolCustomizations() { override fun alwaysHasHttpBody(): Boolean { return true } + + override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.EC2QueryError + + override val defaultTimestampFormat: TimestampFormatTrait.Format = TimestampFormatTrait.Format.DATE_TIME } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryProtocolGenerator.kt similarity index 70% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryProtocolGenerator.kt index 9f5df2af833..5399383d727 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryProtocolGenerator.kt @@ -5,14 +5,10 @@ package software.amazon.smithy.aws.swift.codegen.ec2query -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory +import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver -import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseBindingErrorGenerator -import software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse.AWSEc2QueryHttpResponseTraitPayloadFactory -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.shapes.OperationShape @@ -23,8 +19,6 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator @@ -32,27 +26,14 @@ import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncod import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep import software.amazon.smithy.swift.codegen.model.ShapeMetadata -class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { +class EC2QueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(EC2QueryCustomizations()) { override val defaultContentType = "application/x-www-form-urlencoded" - override val defaultTimestampFormat = TimestampFormatTrait.Format.DATE_TIME override val protocol: ShapeId = Ec2QueryTrait.ID - override val httpProtocolCustomizable = AWSHttpProtocolClientCustomizableFactory().constructClientCustomizable(protocol) - override val httpResponseGenerator = HttpResponseGenerator( - unknownServiceErrorSymbol, - defaultTimestampFormat, - XMLHttpResponseBindingOutputGenerator(), - AWSEc2QueryHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator( - defaultTimestampFormat, - AWSClientRuntimeTypes.EC2Query.EC2QueryError, - AWSEc2QueryHttpResponseTraitPayloadFactory(), - ) - ) + override val httpResponseGenerator = HttpResponseGenerator(customizations) override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, contentType: String): HttpBindingResolver = FormURLHttpBindingResolver(ctx, contentType) - override val shouldRenderDecodableBodyStructForInputShapes = false override val shouldRenderEncodableConformance = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_ec2Query", @@ -62,7 +43,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -70,7 +51,7 @@ class Ec2QueryProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) streamingShapes.forEach { streamingMember -> messageMarshallableGenerator.render(streamingMember) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt deleted file mode 100644 index 19fd03cc981..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorGenerator.kt +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse - -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator - -class AWSEc2QueryHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { - - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.EC2Query.EC2QueryError -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt deleted file mode 100644 index b0c997c5f56..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse - -import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitPayloadFactory -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HttpResponseTraitWithoutHttpPayloadFactory -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.XMLHttpResponseTraitPayload - -class AWSEc2QueryHttpResponseTraitPayloadFactory : HttpResponseTraitPayloadFactory { - override fun construct( - ctx: ProtocolGenerator.GenerationContext, - responseBindings: List, - errorShape: Shape, - writer: SwiftWriter - ): HttpResponseBindingRenderable { - return XMLHttpResponseTraitPayload( - ctx, - responseBindings, - errorShape, - writer, - AWSEc2QueryHttpResponseTraitWithoutHttpPayloadFactory() - ) - } -} - -class AWSEc2QueryHttpResponseTraitWithoutHttpPayloadFactory : HttpResponseTraitWithoutHttpPayloadFactory { - override fun construct( - ctx: ProtocolGenerator.GenerationContext, - responseBindings: List, - outputShape: Shape, - writer: SwiftWriter - ): HttpResponseBindingRenderable { - return AWSEc2QueryHttpResponseTraitWithoutPayload(ctx, responseBindings, outputShape, writer) - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt deleted file mode 100644 index 1b87c20b858..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/httpResponse/AWSEc2QueryHttpResponseTraitWithoutPayload.kt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.ec2query.httpResponse - -import software.amazon.smithy.model.knowledge.HttpBinding -import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.model.traits.HttpQueryTrait -import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.serde.member.MemberShapeDecodeGenerator - -class AWSEc2QueryHttpResponseTraitWithoutPayload( - val ctx: ProtocolGenerator.GenerationContext, - val responseBindings: List, - val outputShape: Shape, - val writer: SwiftWriter -) : HttpResponseBindingRenderable { - override fun render() { - val bodyMembersWithoutQueryTrait = responseBindings.filter { it.location == HttpBinding.Location.DOCUMENT } - .filter { !it.member.hasTrait(HttpQueryTrait::class.java) } - .toMutableSet() - val generator = MemberShapeDecodeGenerator(ctx, writer, outputShape) - bodyMembersWithoutQueryTrait.sortedBy { it.memberName }.forEach { generator.render(it.member) } - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageMarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt similarity index 99% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageMarshallableGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt index 3a2e51630cd..37d62c8ff5d 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageMarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt @@ -17,7 +17,7 @@ import software.amazon.smithy.swift.codegen.integration.serde.readwrite.WritingC import software.amazon.smithy.swift.codegen.model.eventStreamEvents import software.amazon.smithy.swift.codegen.model.hasTrait -class XMLMessageMarshallableGenerator( +class MessageMarshallableGenerator( private val ctx: ProtocolGenerator.GenerationContext, private val payloadContentType: String ) { diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt similarity index 98% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt index 216cf4d4dac..586aa190288 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/XMLMessageUnmarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt @@ -21,7 +21,7 @@ import software.amazon.smithy.swift.codegen.model.eventStreamEvents import software.amazon.smithy.swift.codegen.model.expectShape import software.amazon.smithy.swift.codegen.model.hasTrait -class XMLMessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContext) { +class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContext) { fun render( streamingMember: MemberShape ) { @@ -33,8 +33,6 @@ class XMLMessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationCon .build() val streamShape = ctx.model.expectShape(streamingMember.target) - val service = ctx.settings.getService(ctx.model) - val serviceSymbol = ctx.symbolProvider.toSymbol(service) val streamSymbol = ctx.symbolProvider.toSymbol(streamShape) ctx.delegator.useShapeWriter(streamMember) { writer -> diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSHttpProtocolRestJsonCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSHttpProtocolRestJsonCustomizations.kt deleted file mode 100644 index 68598732d0e..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSHttpProtocolRestJsonCustomizations.kt +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.restjson - -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations - -class AWSHttpProtocolRestJsonCustomizations : AWSHttpProtocolCustomizations() diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt index fb8bdd9c8b1..88221202908 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt @@ -4,44 +4,27 @@ */ package software.amazon.smithy.aws.swift.codegen.restjson -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolClientCustomizableFactory -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator -class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { +class AWSRestJson1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestJSONCustomizations()) { override val defaultContentType = "application/json" - override val defaultTimestampFormat = TimestampFormatTrait.Format.EPOCH_SECONDS override val protocol: ShapeId = RestJson1Trait.ID - override val httpProtocolCustomizable = AWSHttpProtocolClientCustomizableFactory().constructClientCustomizable(protocol) - override val httpResponseGenerator = HttpResponseGenerator( - unknownServiceErrorSymbol, - defaultTimestampFormat, - XMLHttpResponseBindingOutputGenerator(), - AWSRestJson1HttpResponseBindingErrorGeneratable(), - XMLHttpResponseBindingErrorInitGenerator( - defaultTimestampFormat, - AWSClientRuntimeTypes.RestJSON.RestJSONError, - ) - ) + override val httpResponseGenerator = HttpResponseGenerator(customizations) override val testsToIgnore = setOf( "SDKAppliedContentEncoding_restJson1", "SDKAppendedGzipAfterProvidedEncoding_restJson1", - "RestJsonHttpPayloadWithUnsetUnion", ) override val tagsToIgnore = setOf("defaults") override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -49,7 +32,7 @@ class AWSRestJson1ProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) for (streamingShape in streamingShapes) { messageMarshallableGenerator.render(streamingShape) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/RestJSONCustomizations.kt similarity index 50% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/RestJSONCustomizations.kt index 8b4023efcbd..3e5765729fb 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1HttpResponseBindingErrorGeneratable.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/RestJSONCustomizations.kt @@ -6,10 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.restjson import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes +import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -class AWSRestJson1HttpResponseBindingErrorGeneratable : HTTPResponseBindingErrorGenerator() { +class RestJSONCustomizations : AWSHTTPProtocolCustomizations() { - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestJSON.RestJSONError + override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestJSON.RestJSONError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt deleted file mode 100644 index 5695e8dc56c..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.restxml - -import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations - -class AWSHttpProtocolRestXMLCustomizations : AWSHttpProtocolCustomizations() diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLCustomizations.kt similarity index 51% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLCustomizations.kt index 52ab1b7bce7..edb22f25391 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLCustomizations.kt @@ -6,10 +6,10 @@ package software.amazon.smithy.aws.swift.codegen.restxml import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes +import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -class AWSRestXMLHttpResponseBindingErrorGenerator : HTTPResponseBindingErrorGenerator() { +class RestXMLCustomizations : AWSHTTPProtocolCustomizations() { - override val serviceBaseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestXML.RestXMLError + override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestXML.RestXMLError } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolGenerator.kt similarity index 57% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolGenerator.kt index bfcaa7d0402..4d7a00dd9b7 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXmlProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolGenerator.kt @@ -5,35 +5,18 @@ package software.amazon.smithy.aws.swift.codegen.restxml -import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes -import software.amazon.smithy.aws.swift.codegen.AWSHttpBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.XMLMessageUnmarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.RestXmlTrait import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.XMLHttpResponseBindingOutputGenerator -class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { +class RestXMLProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestXMLCustomizations()) { override val defaultContentType: String = "application/xml" - override val defaultTimestampFormat: TimestampFormatTrait.Format = TimestampFormatTrait.Format.DATE_TIME override val protocol: ShapeId = RestXmlTrait.ID - override val httpProtocolCustomizable = AWSHttpProtocolRestXMLCustomizations() - override val httpResponseGenerator = HttpResponseGenerator( - unknownServiceErrorSymbol, - defaultTimestampFormat, - XMLHttpResponseBindingOutputGenerator(), - AWSRestXMLHttpResponseBindingErrorGenerator(), - XMLHttpResponseBindingErrorInitGenerator( - defaultTimestampFormat, - AWSClientRuntimeTypes.RestXML.RestXMLError, - AWSXMLHttpResponseTraitPayloadFactory(), - ) - ) - override val shouldRenderDecodableBodyStructForInputShapes = false + override val httpResponseGenerator = HttpResponseGenerator(customizations) override val testsToIgnore: Set = setOf( "S3DefaultAddressing", "S3VirtualHostAddressing", @@ -53,7 +36,7 @@ class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = XMLMessageUnmarshallableGenerator(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) streamingShapes.forEach { streamingMember -> messageUnmarshallableGenerator.render(streamingMember) } @@ -61,7 +44,7 @@ class RestXmlProtocolGenerator : AWSHttpBindingProtocolGenerator() { override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { var streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = XMLMessageMarshallableGenerator(ctx, defaultContentType) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) streamingShapes.forEach { streamingMember -> messageMarshallableGenerator.render(streamingMember) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt similarity index 92% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt index f3699ebede1..7faeae710fb 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHttpResponseTraitWithoutPayload.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt @@ -11,15 +11,15 @@ import software.amazon.smithy.model.traits.HttpQueryTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable +import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingRenderable import software.amazon.smithy.swift.codegen.integration.serde.member.MemberShapeDecodeGenerator -class AWSXMLHttpResponseTraitWithoutPayload( +class AWSXMLHTTPResponseTraitWithoutPayload( val ctx: ProtocolGenerator.GenerationContext, val responseBindings: List, val outputShape: Shape, val writer: SwiftWriter -) : HttpResponseBindingRenderable { +) : HTTPResponseBindingRenderable { override fun render() { val bodyMembersWithoutQueryTrait = responseBindings.filter { it.location == HttpBinding.Location.DOCUMENT } .filter { !it.member.hasTrait(HttpQueryTrait::class.java) } diff --git a/codegen/smithy-aws-swift-codegen/src/main/resources/META-INF/services/software.amazon.smithy.swift.codegen.integration.SwiftIntegration b/codegen/smithy-aws-swift-codegen/src/main/resources/META-INF/services/software.amazon.smithy.swift.codegen.integration.SwiftIntegration index 492071443d2..7dc543aaea0 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/resources/META-INF/services/software.amazon.smithy.swift.codegen.integration.SwiftIntegration +++ b/codegen/smithy-aws-swift-codegen/src/main/resources/META-INF/services/software.amazon.smithy.swift.codegen.integration.SwiftIntegration @@ -20,6 +20,5 @@ software.amazon.smithy.aws.swift.codegen.PresignerGenerator software.amazon.smithy.aws.swift.codegen.model.AWSClientContextParamsTransformer software.amazon.smithy.aws.swift.codegen.model.AWSHttpTraitTransformer software.amazon.smithy.aws.swift.codegen.model.AWSEndpointTraitTransformer -software.amazon.smithy.aws.swift.codegen.customization.MessageEncoderIntegration software.amazon.smithy.aws.swift.codegen.AWSClientConfigurationIntegration software.amazon.smithy.swift.codegen.swiftintegrations.InitialRequestIntegration diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt index 85c9181f498..91b66348b74 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt @@ -7,7 +7,7 @@ package software.amazon.smithy.aws.swift.codegen import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.awsjson.AwsJson1_0_ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.auth.UnsignedPayloadTrait import software.amazon.smithy.model.Model @@ -47,7 +47,7 @@ stack.serializeStep.intercept(position: .before, middleware: AWSClientRuntime.XA .addShape(outputShape) .addShape(errorShape) .build() - val context = model.newTestContext("com.test#ExampleServiceShapeName", AwsJson1_0_ProtocolGenerator()).ctx + val context = model.newTestContext("com.test#ExampleServiceShapeName", AWSJSON1_0ProtocolGenerator()).ctx val sut = AWSXAmzTargetMiddleware(context.model, context.symbolProvider, context.service) sut.render(context, writer, operationShape, opStackName) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt similarity index 97% rename from codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt rename to codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt index ebe17a9f280..ac81412e47e 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt @@ -10,7 +10,7 @@ import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait // The model used in the tests below uses AWS Json 1.0 as the protocol. // However, AWSJsonHttpResponseBindingErrorGenerator.kt is used for both AWS Json 1.0 and AWS Json 1.1 protocols. // Therefore, this file tests both versions of AWS Json, 1.0 and 1.1, for the error generation. -class AWSJsonHttpResponseBindingErrorGeneratorTests { +class AWSJSONHttpResponseBindingErrorGeneratorTests { @Test fun `001 GreetingWithErrorsOutputError+HttpResponseBinding`() { val context = setupTests("awsjson/json-error.smithy", "aws.protocoltests.json10#AwsJson10") @@ -65,7 +65,7 @@ extension Json10ProtocolClientTypes { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsJson1_0Trait.ID) - AwsJson1_0_ProtocolGenerator().run { + AWSJSON1_0ProtocolGenerator().run { generateDeserializers(context.ctx) generateCodableConformanceForNestedTypes(context.ctx) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index f94df52c023..e08b3d98782 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -114,7 +114,7 @@ extension EventStreamOpInput { } private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsJson1_0Trait.ID) - AwsJson1_0_ProtocolGenerator().run { + AWSJSON1_0ProtocolGenerator().run { generateMessageMarshallable(context.ctx) generateSerializers(context.ctx) initializeMiddleware(context.ctx) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt index 36dd51cb268..79ee7c8ebd2 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt @@ -59,7 +59,7 @@ class AWSQueryOperationStackTest { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateSerializers(context.ctx) context.ctx.delegator.flushWriters() diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt index 9c2f9bbff0b..424f4ebd2ea 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt @@ -39,7 +39,7 @@ extension BlobInputParamsInput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateSerializers(context.ctx) generator.generateDeserializers(context.ctx) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt index bf4c56379b9..0cf51e29d7a 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt @@ -42,7 +42,7 @@ extension QueryListsInput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateSerializers(context.ctx) context.ctx.delegator.flushWriters() diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt index a125b4b17af..1fa468b94c0 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt @@ -43,7 +43,7 @@ extension QueryMapsInput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateSerializers(context.ctx) context.ctx.delegator.flushWriters() diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt index b2513dcafc3..b79b39b6455 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt @@ -37,7 +37,7 @@ extension QueryIdempotencyTokenAutoFillInput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateSerializers(context.ctx) context.ctx.delegator.flushWriters() diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt index 92e7b870c55..f3d1df57d51 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt @@ -38,7 +38,7 @@ extension FlattenedXmlMapOutput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateDeserializers(context.ctx) context.ctx.delegator.flushWriters() diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt index 7fda2b2759d..09ecb398750 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt @@ -39,7 +39,7 @@ extension QueryTimestampsInput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, AwsQueryTrait.ID) - val generator = AwsQueryProtocolGenerator() + val generator = AWSQueryProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateSerializers(context.ctx) context.ctx.delegator.flushWriters() diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt index 31d32a01045..aa85889f1c8 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt @@ -2,7 +2,7 @@ package software.amazon.smithy.aws.swift.codegen.customizations import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.awsjson.AwsJson1_0_ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.customization.BoxServices import software.amazon.smithy.aws.swift.codegen.newTestContext import software.amazon.smithy.aws.swift.codegen.toSmithyModel @@ -44,7 +44,7 @@ class BoxServicesTest { integer NotPrimitiveField """ val model = smithy.toSmithyModel() - val ctx = model.newTestContext("com.test#Example", AwsJson1_0_ProtocolGenerator()).ctx + val ctx = model.newTestContext("com.test#Example", AWSJSON1_0ProtocolGenerator()).ctx val operationTransform = AddOperationShapes.execute(model, ctx.service, ctx.settings.moduleName) val transformed = BoxServices().preprocessModel(operationTransform, ctx.settings) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt index 5b736b9b273..420b8df5c76 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt @@ -122,7 +122,7 @@ extension EC2ProtocolClientTypes { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, Ec2QueryTrait.ID) - Ec2QueryProtocolGenerator().run { + EC2QueryProtocolGenerator().run { generateDeserializers(context.ctx) generateCodableConformanceForNestedTypes(context.ctx) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index e3c78dcd40c..7f0f6155cbf 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -129,7 +129,7 @@ extension EventStreamTestClientTypes.Audio { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, RestXmlTrait.ID) - RestXmlProtocolGenerator().run { + RestXMLProtocolGenerator().run { generateMessageMarshallable(context.ctx) generateSerializers(context.ctx) initializeMiddleware(context.ctx) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt similarity index 98% rename from codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt rename to codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt index 24e7f6e4c50..1420a8f0944 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt @@ -13,7 +13,7 @@ import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileConte import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestXmlTrait -class AWSRestXMLHttpResponseBindingErrorGeneratorTests { +class AWSRestXMLHTTPResponseBindingErrorGeneratorTests { @Test fun `002 GreetingWithErrorsOutputError+HttpResponseBinding`() { @@ -153,7 +153,7 @@ extension RestXmlerrorsClientTypes { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = executeDirectedCodegen(smithyFile, serviceShapeId, RestXmlTrait.ID) - RestXmlProtocolGenerator().run { + RestXMLProtocolGenerator().run { generateDeserializers(context.ctx) generateCodableConformanceForNestedTypes(context.ctx) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt index 01829912d0e..d4a85075099 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt @@ -31,7 +31,7 @@ class RestXMLProtocolNoInputNoOutputGeneratorTests { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = executeDirectedCodegen(smithyFile, serviceShapeId, RestXmlTrait.ID) - val generator = RestXmlProtocolGenerator() + val generator = RestXMLProtocolGenerator() generator.generateProtocolUnitTests(context.ctx) context.ctx.delegator.flushWriters() return context diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt index 5e4e6771c07..5b51a5e1323 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt @@ -31,7 +31,7 @@ class RestXMLProtocolXMLAttributesGeneratorTests { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = executeDirectedCodegen(smithyFile, serviceShapeId, RestXmlTrait.ID) - val generator = RestXmlProtocolGenerator() + val generator = RestXMLProtocolGenerator() generator.generateProtocolUnitTests(context.ctx) context.ctx.delegator.flushWriters() return context diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt index 72f5b81dc5e..79006c4de07 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents -import software.amazon.smithy.aws.swift.codegen.restxml.RestXmlProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.restxml.RestXMLProtocolGenerator import software.amazon.smithy.aws.traits.protocols.RestXmlTrait class S3UnwrappedXMLOutputTraitTests { @@ -33,7 +33,7 @@ extension GetBucketLocationOutput { private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, RestXmlTrait.ID) - val generator = RestXmlProtocolGenerator() + val generator = RestXMLProtocolGenerator() generator.generateCodableConformanceForNestedTypes(context.ctx) generator.generateDeserializers(context.ctx) context.ctx.delegator.flushWriters() From a4a06cc45506fe8573c9de4888628034aca70291 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Wed, 17 Apr 2024 20:17:15 -0500 Subject: [PATCH 15/27] More refactoring & eliminating dead code --- .../smithy/aws/swift/codegen/AddProtocols.kt | 12 ++--- ...esponseBindingErrorInitGeneratorFactory.kt | 47 ------------------- .../awsjson/AWSJSON1_0ProtocolGenerator.kt | 7 +-- .../awsjson/AWSJSON1_1ProtocolGenerator.kt | 4 +- .../awsjson/AWSJSONCustomizations.kt | 2 +- .../awsjson/AWSJSONHttpBindingResolver.kt | 2 +- .../awsquery/AWSQueryCustomizations.kt | 2 +- .../awsquery/AWSQueryProtocolGenerator.kt | 4 +- .../ec2query/EC2QueryCustomizations.kt | 2 +- .../ec2query/EC2QueryProtocolGenerator.kt | 4 +- .../restjson/AWSRestJson1ProtocolGenerator.kt | 4 +- .../restjson/RestJSONCustomizations.kt | 2 +- .../restxml/RestXMLCustomizations.kt | 2 +- .../restxml/RestXMLProtocolGenerator.kt | 4 +- .../AWSXMLHTTPResponseTraitWithoutPayload.kt | 31 ------------ .../codegen/AWSXAmzTargetMiddlewareTests.kt | 2 +- .../aws/swift/codegen/EventStreamTests.kt | 2 +- .../swift/codegen/PresignerGeneratorTests.kt | 2 +- ...NHttpResponseBindingErrorGeneratorTests.kt | 1 + .../awsjson/AWSJsonHttpInitialRequestTests.kt | 1 + .../awsquery/AWSQueryOperationStackTest.kt | 1 + .../awsquery/BlobEncodeGeneratorTests.kt | 1 + .../ListEncodeFormURLGeneratorTests.kt | 1 + .../MapEncodeFormURLGeneratorTests.kt | 1 + ...yIdempotencyTokenAutoFillGeneratorTests.kt | 1 + .../StructDecodeWrappedXMLGeneratorTests.kt | 1 + .../awsquery/TimestampGeneratorTests.kt | 1 + ...ttpResponseBindingErrorGeneratableTests.kt | 2 +- .../AWSRestJson1ProtocolGeneratorTests.kt | 2 +- .../codegen/customizations/BoxServicesTest.kt | 2 +- .../FlexibleChecksumMiddlewareTests.kt | 2 +- .../GlacierAccountIdMiddlewareTest.kt | 2 +- .../PresignableUrlIntegrationTests.kt | 2 +- ...esBasedAuthSchemeResolverGeneratorTests.kt | 2 +- .../codegen/customizations/S3ExpiresTest.kt | 2 +- ...yHttpResponseBindingErrorGeneratorTests.kt | 1 + .../restxml/AWSRestXMLEventStreamTests.kt | 1 + ...LHTTPResponseBindingErrorGeneratorTests.kt | 1 + ...MLProtocolNoInputNoOutputGeneratorTests.kt | 1 + ...tXMLProtocolXMLAttributesGeneratorTests.kt | 1 + .../serde/S3UnwrappedXMLOutputTraitTests.kt | 2 +- 41 files changed, 44 insertions(+), 123 deletions(-) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/awsjson/AWSJSON1_0ProtocolGenerator.kt (86%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/awsjson/AWSJSON1_1ProtocolGenerator.kt (94%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/awsjson/AWSJSONCustomizations.kt (90%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/awsjson/AWSJSONHttpBindingResolver.kt (92%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/awsquery/AWSQueryCustomizations.kt (95%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/awsquery/AWSQueryProtocolGenerator.kt (95%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/ec2query/EC2QueryCustomizations.kt (95%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/ec2query/EC2QueryProtocolGenerator.kt (95%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/restjson/AWSRestJson1ProtocolGenerator.kt (88%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/restjson/RestJSONCustomizations.kt (87%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/restxml/RestXMLCustomizations.kt (87%) rename codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/{ => protocols}/restxml/RestXMLProtocolGenerator.kt (91%) delete mode 100644 codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt index ddc7ab50bb6..c07bf2f1996 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AddProtocols.kt @@ -4,12 +4,12 @@ */ package software.amazon.smithy.aws.swift.codegen -import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_0ProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_1ProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.awsquery.AWSQueryProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.ec2query.EC2QueryProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.restxml.RestXMLProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.ec2query.EC2QueryProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SwiftIntegration diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt deleted file mode 100644 index 6626a3fadf4..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/AWSEc2QueryHttpResponseBindingErrorInitGeneratorFactory.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.ec2query - -import software.amazon.smithy.aws.swift.codegen.restxml.httpResponse.AWSXMLHTTPResponseTraitWithoutPayload -import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable -import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HTTPResponseTraitPayload -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HTTPResponseTraitPayloadFactory -import software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits.HTTPResponseTraitWithoutHTTPPayloadFactory - -class AWSEC2QueryHTTPResponseTraitPayloadFactory : HTTPResponseTraitPayloadFactory { - override fun construct( - ctx: ProtocolGenerator.GenerationContext, - responseBindings: List, - errorShape: Shape, - writer: SwiftWriter, - customizations: HTTPProtocolCustomizable, - ): HTTPResponseBindingRenderable { - return HTTPResponseTraitPayload( - ctx, - responseBindings, - errorShape, - writer, - customizations, - AWSEC2QueryHTTPResponseTraitWithoutHTTPPayloadFactory() - ) - } -} - -class AWSEC2QueryHTTPResponseTraitWithoutHTTPPayloadFactory : HTTPResponseTraitWithoutHTTPPayloadFactory { - override fun construct( - ctx: ProtocolGenerator.GenerationContext, - responseBindings: List, - outputShape: Shape, - writer: SwiftWriter - ): HTTPResponseBindingRenderable { - return AWSXMLHTTPResponseTraitWithoutPayload(ctx, responseBindings, outputShape, writer) - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_0ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt similarity index 86% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_0ProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt index bdba03a4af4..81b24eb643e 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_0ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.awsjson +package software.amazon.smithy.aws.swift.codegen.protocols.awsjson import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator @@ -14,10 +14,6 @@ import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingErrorInitGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingOutputGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep @@ -25,7 +21,6 @@ import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep open class AWSJSON1_0ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCustomizations()) { override val defaultContentType = "application/x-amz-json-1.0" override val protocol: ShapeId = AwsJson1_0Trait.ID - override val httpResponseGenerator = HttpResponseGenerator(customizations) override val shouldRenderEncodableConformance: Boolean = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_awsJson1_0", diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt similarity index 94% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_1ProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt index 72eeb36e1f8..81939a8275c 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSON1_1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.awsjson +package software.amazon.smithy.aws.swift.codegen.protocols.awsjson import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator @@ -14,7 +14,6 @@ import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep @@ -22,7 +21,6 @@ import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep class AWSJSON1_1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCustomizations()) { override val defaultContentType = "application/x-amz-json-1.1" override val protocol: ShapeId = AwsJson1_1Trait.ID - override val httpResponseGenerator = HttpResponseGenerator(customizations) override val shouldRenderEncodableConformance: Boolean = true override val testsToIgnore = setOf( "SDKAppliedContentEncoding_awsJson1_1", diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSONCustomizations.kt similarity index 90% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSONCustomizations.kt index 9c414a7968d..0cef6658596 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSONCustomizations.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.awsjson +package software.amazon.smithy.aws.swift.codegen.protocols.awsjson import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpBindingResolver.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSONHttpBindingResolver.kt similarity index 92% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpBindingResolver.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSONHttpBindingResolver.kt index bc82089e0f2..33c7b9ae156 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpBindingResolver.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSONHttpBindingResolver.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.awsjson +package software.amazon.smithy.aws.swift.codegen.protocols.awsjson import software.amazon.smithy.model.pattern.UriPattern import software.amazon.smithy.model.traits.HttpTrait diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryCustomizations.kt similarity index 95% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryCustomizations.kt index b5ece020b0c..3b1b3ad8c08 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryCustomizations.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.awsquery +package software.amazon.smithy.aws.swift.codegen.protocols.awsquery import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt similarity index 95% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt index 9e0fa03c5b4..118abc7e468 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.awsquery +package software.amazon.smithy.aws.swift.codegen.protocols.awsquery import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver @@ -18,7 +18,6 @@ import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator @@ -29,7 +28,6 @@ import software.amazon.smithy.swift.codegen.model.ShapeMetadata open class AWSQueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSQueryCustomizations()) { override val defaultContentType = "application/x-www-form-urlencoded" override val protocol: ShapeId = AwsQueryTrait.ID - override val httpResponseGenerator = HttpResponseGenerator(customizations) override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, defaultContentType: String): HttpBindingResolver = FormURLHttpBindingResolver(ctx, defaultContentType) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryCustomizations.kt similarity index 95% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryCustomizations.kt index 7cb33a899f4..2ce0b8d81d0 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryCustomizations.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.ec2query +package software.amazon.smithy.aws.swift.codegen.protocols.ec2query import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt similarity index 95% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt index 5399383d727..17eb1c4e526 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/EC2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.ec2query +package software.amazon.smithy.aws.swift.codegen.protocols.ec2query import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver @@ -18,7 +18,6 @@ import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator @@ -29,7 +28,6 @@ import software.amazon.smithy.swift.codegen.model.ShapeMetadata class EC2QueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(EC2QueryCustomizations()) { override val defaultContentType = "application/x-www-form-urlencoded" override val protocol: ShapeId = Ec2QueryTrait.ID - override val httpResponseGenerator = HttpResponseGenerator(customizations) override fun getProtocolHttpBindingResolver(ctx: ProtocolGenerator.GenerationContext, contentType: String): HttpBindingResolver = FormURLHttpBindingResolver(ctx, contentType) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt similarity index 88% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt index 88221202908..6de131992c7 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/AWSRestJson1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt @@ -2,7 +2,7 @@ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.restjson +package software.amazon.smithy.aws.swift.codegen.protocols.restjson import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator @@ -10,12 +10,10 @@ import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGen import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator class AWSRestJson1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestJSONCustomizations()) { override val defaultContentType = "application/json" override val protocol: ShapeId = RestJson1Trait.ID - override val httpResponseGenerator = HttpResponseGenerator(customizations) override val testsToIgnore = setOf( "SDKAppliedContentEncoding_restJson1", "SDKAppendedGzipAfterProvidedEncoding_restJson1", diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/RestJSONCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/RestJSONCustomizations.kt similarity index 87% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/RestJSONCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/RestJSONCustomizations.kt index 3e5765729fb..d3f960d803a 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restjson/RestJSONCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/RestJSONCustomizations.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.restjson +package software.amazon.smithy.aws.swift.codegen.protocols.restjson import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt similarity index 87% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLCustomizations.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt index edb22f25391..8e9e46a2978 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.restxml +package software.amazon.smithy.aws.swift.codegen.protocols.restxml import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt similarity index 91% rename from codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolGenerator.kt rename to codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt index 4d7a00dd9b7..6f860369a02 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -package software.amazon.smithy.aws.swift.codegen.restxml +package software.amazon.smithy.aws.swift.codegen.protocols.restxml import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator @@ -11,12 +11,10 @@ import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGen import software.amazon.smithy.aws.traits.protocols.RestXmlTrait import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseGenerator class RestXMLProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestXMLCustomizations()) { override val defaultContentType: String = "application/xml" override val protocol: ShapeId = RestXmlTrait.ID - override val httpResponseGenerator = HttpResponseGenerator(customizations) override val testsToIgnore: Set = setOf( "S3DefaultAddressing", "S3VirtualHostAddressing", diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt deleted file mode 100644 index 7faeae710fb..00000000000 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/httpResponse/AWSXMLHTTPResponseTraitWithoutPayload.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -package software.amazon.smithy.aws.swift.codegen.restxml.httpResponse - -import software.amazon.smithy.model.knowledge.HttpBinding -import software.amazon.smithy.model.shapes.Shape -import software.amazon.smithy.model.traits.HttpQueryTrait -import software.amazon.smithy.swift.codegen.SwiftWriter -import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.httpResponse.HTTPResponseBindingRenderable -import software.amazon.smithy.swift.codegen.integration.serde.member.MemberShapeDecodeGenerator - -class AWSXMLHTTPResponseTraitWithoutPayload( - val ctx: ProtocolGenerator.GenerationContext, - val responseBindings: List, - val outputShape: Shape, - val writer: SwiftWriter -) : HTTPResponseBindingRenderable { - override fun render() { - val bodyMembersWithoutQueryTrait = responseBindings.filter { it.location == HttpBinding.Location.DOCUMENT } - .filter { !it.member.hasTrait(HttpQueryTrait::class.java) } - .map { it.member } - .toSet() - val generator = MemberShapeDecodeGenerator(ctx, writer, outputShape) - bodyMembersWithoutQueryTrait.sortedBy { it.memberName }.forEach { generator.render(it) } - } -} diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt index 91b66348b74..03c7d1acfa6 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt @@ -7,7 +7,7 @@ package software.amazon.smithy.aws.swift.codegen import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_0ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.auth.UnsignedPayloadTrait import software.amazon.smithy.model.Model diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt index 4faf1740e42..1068af53926 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt @@ -3,7 +3,7 @@ package software.amazon.smithy.aws.swift.codegen import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.traits.protocols.RestJson1Trait class EventStreamTests { diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt index 346345e2edf..a272c365c57 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt @@ -1,7 +1,7 @@ package software.amazon.smithy.aws.swift.codegen import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.swift.codegen.core.GenerationContext import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt index ac81412e47e..82d22ed3e7f 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt @@ -4,6 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index e08b3d98782..ee379665ee6 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -4,6 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt index 79ee7c8ebd2..9f628f775cb 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt index 424f4ebd2ea..a23d973ca4e 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/BlobEncodeGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.executeDirectedCodegen import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt index 0cf51e29d7a..afbe49ab791 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/ListEncodeFormURLGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt index 1fa468b94c0..4a846cffca8 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/MapEncodeFormURLGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt index b79b39b6455..98e72293f7c 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/QueryIdempotencyTokenAutoFillGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt index f3d1df57d51..3674ccff518 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait class StructDecodeWrappedXMLGeneratorTests { diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt index 09ecb398750..733fff23a64 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/TimestampGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.awsquery.AWSQueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt index 274dad14c81..71b2e3dc74f 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt @@ -4,7 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt index b3e866fca7e..89344ba8b67 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt @@ -11,7 +11,7 @@ import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.executeDirectedCodegen import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getClientFileContents import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getModelFileContents -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt index aa85889f1c8..d44818d63f0 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt @@ -2,7 +2,7 @@ package software.amazon.smithy.aws.swift.codegen.customizations import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.awsjson.AWSJSON1_0ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.customization.BoxServices import software.amazon.smithy.aws.swift.codegen.newTestContext import software.amazon.smithy.aws.swift.codegen.toSmithyModel diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt index 873b71d3a96..23b947672a7 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt @@ -4,7 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/GlacierAccountIdMiddlewareTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/GlacierAccountIdMiddlewareTest.kt index f6981e573cd..da91a787dcd 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/GlacierAccountIdMiddlewareTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/GlacierAccountIdMiddlewareTest.kt @@ -4,7 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.middleware.GlacierAccountIdMiddleware import software.amazon.smithy.aws.swift.codegen.newTestContext -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.traits.auth.UnsignedPayloadTrait import software.amazon.smithy.model.Model import software.amazon.smithy.model.shapes.MemberShape diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/PresignableUrlIntegrationTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/PresignableUrlIntegrationTests.kt index 01c4af82bbc..c23b36f4b30 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/PresignableUrlIntegrationTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/PresignableUrlIntegrationTests.kt @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.customization.presignable.PresignableUrlIntegration -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.aws.traits.protocols.RestXmlTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/RulesBasedAuthSchemeResolverGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/RulesBasedAuthSchemeResolverGeneratorTests.kt index 5bb7a4179c8..3e7b126bbfc 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/RulesBasedAuthSchemeResolverGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/RulesBasedAuthSchemeResolverGeneratorTests.kt @@ -4,7 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/S3ExpiresTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/S3ExpiresTest.kt index d034676612c..09eee1ce439 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/S3ExpiresTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/S3ExpiresTest.kt @@ -4,7 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils -import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt index 420b8df5c76..1faa8ab0926 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt @@ -9,6 +9,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils +import software.amazon.smithy.aws.swift.codegen.protocols.ec2query.EC2QueryProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index 7f0f6155cbf..29add52d406 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -4,6 +4,7 @@ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils +import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestXmlTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt index 1420a8f0944..dc08b337134 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.executeDirectedCodegen import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestXmlTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt index d4a85075099..cbbbedade04 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolNoInputNoOutputGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.executeDirectedCodegen import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getClientFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestXmlTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt index 5b51a5e1323..9477484c75f 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/RestXMLProtocolXMLAttributesGeneratorTests.kt @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.executeDirectedCodegen import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getClientFileContents +import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestXmlTrait diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt index 79006c4de07..5a789aea491 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.TestUtils.Companion.getFileContents -import software.amazon.smithy.aws.swift.codegen.restxml.RestXMLProtocolGenerator +import software.amazon.smithy.aws.swift.codegen.protocols.restxml.RestXMLProtocolGenerator import software.amazon.smithy.aws.traits.protocols.RestXmlTrait class S3UnwrappedXMLOutputTraitTests { From 3f7517353216522b859f5a9e6640c8d26ddd4f52 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Thu, 18 Apr 2024 09:52:50 -0500 Subject: [PATCH 16/27] Fix ktlint --- .../aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt | 2 +- .../smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt | 2 +- .../smithy/aws/swift/codegen/customizations/BoxServicesTest.kt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt index 773a09e73a5..1cf3aa03b3d 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHttpProtocolClientGeneratorFactory.kt @@ -6,10 +6,10 @@ package software.amazon.smithy.aws.swift.codegen import software.amazon.smithy.swift.codegen.SwiftWriter +import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.HttpProtocolClientGenerator import software.amazon.smithy.swift.codegen.integration.HttpProtocolClientGeneratorFactory -import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.middleware.OperationMiddleware diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt index 03c7d1acfa6..f9e7152df52 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/AWSXAmzTargetMiddlewareTests.kt @@ -7,8 +7,8 @@ package software.amazon.smithy.aws.swift.codegen import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.traits.auth.UnsignedPayloadTrait import software.amazon.smithy.model.Model import software.amazon.smithy.model.shapes.OperationShape diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt index d44818d63f0..3f1f292d886 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/BoxServicesTest.kt @@ -2,9 +2,9 @@ package software.amazon.smithy.aws.swift.codegen.customizations import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.customization.BoxServices import software.amazon.smithy.aws.swift.codegen.newTestContext +import software.amazon.smithy.aws.swift.codegen.protocols.awsjson.AWSJSON1_0ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.toSmithyModel import software.amazon.smithy.model.knowledge.NullableIndex import software.amazon.smithy.model.shapes.MemberShape From 9667f31023b047ad27cfd893edf5d53e87266201 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Thu, 18 Apr 2024 19:47:15 -0500 Subject: [PATCH 17/27] Eliminate document reading/writing closures --- .../message/MessageMarshallableGenerator.kt | 11 ++++++++--- .../message/MessageUnmarshallableGenerator.kt | 18 +++++++++--------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt index 37d62c8ff5d..845c339c8ca 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt @@ -12,8 +12,10 @@ import software.amazon.smithy.swift.codegen.ClientRuntimeTypes import software.amazon.smithy.swift.codegen.SwiftDependency import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.serde.readwrite.DocumentWritingClosureUtils +import software.amazon.smithy.swift.codegen.integration.serde.readwrite.NodeInfoUtils import software.amazon.smithy.swift.codegen.integration.serde.readwrite.WritingClosureUtils +import software.amazon.smithy.swift.codegen.integration.serde.readwrite.responseWireProtocol +import software.amazon.smithy.swift.codegen.integration.serde.struct.writerSymbol import software.amazon.smithy.swift.codegen.model.eventStreamEvents import software.amazon.smithy.swift.codegen.model.hasTrait @@ -175,8 +177,11 @@ class MessageMarshallableGenerator( private fun renderPayloadSerialization(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter, shape: Shape) { // get a payload serializer for the given members of the variant - val documentWritingClosure = DocumentWritingClosureUtils(ctx, writer).closure(shape) + val nodeInfoUtils = NodeInfoUtils(ctx, writer, ctx.service.responseWireProtocol) + val rootNodeInfo = nodeInfoUtils.nodeInfo(shape) val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(shape) - writer.write("payload = try \$L(value, \$L)", documentWritingClosure, valueWritingClosure) + writer.write("let writer = \$N(nodeInfo: \$L)", ctx.service.writerSymbol, rootNodeInfo) + writer.write("try \$L(value, writer)", valueWritingClosure) + writer.write("payload = try writer.data()") } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt index 586aa190288..1c1b961db2f 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt @@ -14,8 +14,8 @@ import software.amazon.smithy.swift.codegen.SwiftDependency import software.amazon.smithy.swift.codegen.SwiftTypes import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator -import software.amazon.smithy.swift.codegen.integration.serde.readwrite.DocumentReadingClosureUtils import software.amazon.smithy.swift.codegen.integration.serde.readwrite.ReadingClosureUtils +import software.amazon.smithy.swift.codegen.integration.serde.struct.readerSymbol import software.amazon.smithy.swift.codegen.model.eventStreamErrors import software.amazon.smithy.swift.codegen.model.eventStreamEvents import software.amazon.smithy.swift.codegen.model.expectShape @@ -77,9 +77,9 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex writer.indent { val targetShape = ctx.model.expectShape(member.target) val symbol = ctx.symbolProvider.toSymbol(targetShape) - val documentReadingClosure = DocumentReadingClosureUtils(ctx, writer).closure(member) val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) - writer.write("return try \$L(message.payload, \$L)", documentReadingClosure, readingClosure) + writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) + writer.write("return try \$L(reader)", readingClosure) } } writer.write("default:") @@ -129,9 +129,9 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex val memberName = ctx.symbolProvider.toMemberName(member) if (eventHeaderBindings.isEmpty() && eventPayloadBinding == null) { - val documentReadingClosure = DocumentReadingClosureUtils(ctx, writer).closure(member) + writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) - writer.write("return .\$L(try \$L(message.payload, \$L))", memberName, documentReadingClosure, readingClosure) + writer.write("return .\$L(try \$L(reader))", memberName, readingClosure) } else { val variantSymbol = ctx.symbolProvider.toSymbol(variant) writer.write("var event = \$N()", variantSymbol) @@ -175,8 +175,8 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex unbound.forEach { val memberName = ctx.symbolProvider.toMemberName(it) val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(it) - val documentReadingClosure = DocumentReadingClosureUtils(ctx, writer).closure(it) - writer.write("event.\$L = try \$L(message.payload, \$L)", memberName, documentReadingClosure, readingClosure) + writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) + writer.write("event.\$L = try \$L(reader)", memberName, readingClosure) } } } @@ -197,8 +197,8 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex ShapeType.STRUCTURE, ShapeType.UNION -> { val memberName = ctx.symbolProvider.toMemberName(member) val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) - val documentReadingClosure = DocumentReadingClosureUtils(ctx, writer).closure(member) - writer.write("event.\$L = try \$L(message.payload, \$L)", memberName, documentReadingClosure, readingClosure) + writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) + writer.write("event.\$L = try \$L(reader)", memberName, readingClosure) } else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") } From 05f3110add3821a3ca91cdd0d1f0cf390c30bdb6 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Fri, 19 Apr 2024 01:50:53 -0500 Subject: [PATCH 18/27] Eliminated document closures --- .../message/MessageMarshallableGenerator.kt | 11 ++++--- .../message/MessageUnmarshallableGenerator.kt | 33 ++++++++++--------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt index 845c339c8ca..961a1ee2ed0 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt @@ -48,7 +48,7 @@ class MessageMarshallableGenerator( write("switch self {") streamShape.eventStreamEvents(ctx.model).forEach { member -> val memberName = ctx.symbolProvider.toMemberName(member) - write("case \$L(let value):", memberName) + write("case .\$L(let value):", memberName) indent() addStringHeader(":event-type", member.memberName) val variant = ctx.model.expectShape(member.target) @@ -180,8 +180,11 @@ class MessageMarshallableGenerator( val nodeInfoUtils = NodeInfoUtils(ctx, writer, ctx.service.responseWireProtocol) val rootNodeInfo = nodeInfoUtils.nodeInfo(shape) val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(shape) - writer.write("let writer = \$N(nodeInfo: \$L)", ctx.service.writerSymbol, rootNodeInfo) - writer.write("try \$L(value, writer)", valueWritingClosure) - writer.write("payload = try writer.data()") + writer.write( + "payload = try \$N.write(value, rootNodeInfo: \$L, with: \$L)", + ctx.service.writerSymbol, + rootNodeInfo, + valueWritingClosure, + ) } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt index 1c1b961db2f..260b6e68e28 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt @@ -75,11 +75,8 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex streamShape.eventStreamErrors(ctx.model).forEach { member -> writer.write("case \"${member.memberName}\":") writer.indent { - val targetShape = ctx.model.expectShape(member.target) - val symbol = ctx.symbolProvider.toSymbol(targetShape) - val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) - writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) - writer.write("return try \$L(reader)", readingClosure) + renderReadToValue(writer, member) + writer.write("return value") } } writer.write("default:") @@ -129,9 +126,8 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex val memberName = ctx.symbolProvider.toMemberName(member) if (eventHeaderBindings.isEmpty() && eventPayloadBinding == null) { - writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) - val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) - writer.write("return .\$L(try \$L(reader))", memberName, readingClosure) + renderReadToValue(writer, member) + writer.write("return .\$L(value)", memberName) } else { val variantSymbol = ctx.symbolProvider.toSymbol(variant) writer.write("var event = \$N()", variantSymbol) @@ -173,10 +169,8 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex // for the overall event shape but only payload members will be considered for deserialization), // and then assign each deserialized payload member to the current builder instance unbound.forEach { - val memberName = ctx.symbolProvider.toMemberName(it) - val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(it) - writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) - writer.write("event.\$L = try \$L(reader)", memberName, readingClosure) + renderReadToValue(writer, it) + writer.write("event.\$L = value", memberName) } } } @@ -195,12 +189,19 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex ShapeType.BLOB -> writer.write("event.\$L = message.payload", memberName) ShapeType.STRING -> writer.write("event.\$L = String(data: message.payload, encoding: .utf8)", memberName) ShapeType.STRUCTURE, ShapeType.UNION -> { - val memberName = ctx.symbolProvider.toMemberName(member) - val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(member) - writer.write("let reader = try \$N.from(data: message.payload)", ctx.service.readerSymbol) - writer.write("event.\$L = try \$L(reader)", memberName, readingClosure) + renderReadToValue(writer, member) + writer.write("event.\$L = value", memberName) } else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") } } + + private fun renderReadToValue(writer: SwiftWriter, memberShape: MemberShape) { + val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(memberShape) + writer.write( + "let value = try \$N.readFrom(message.payload, with: \$L)", + ctx.service.readerSymbol, + readingClosure, + ) + } } From 2a2382f45e3ccd407f69fc31376515b117da58be Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Fri, 19 Apr 2024 09:36:36 -0500 Subject: [PATCH 19/27] Fix tests --- .../RestJSON/RestJSONErrorTests.swift | 18 ++++---- .../aws/swift/codegen/EventStreamTests.kt | 41 +++++++++++-------- .../swift/codegen/PresignerGeneratorTests.kt | 14 +++---- ...NHttpResponseBindingErrorGeneratorTests.kt | 24 +++++------ .../awsjson/AWSJsonHttpInitialRequestTests.kt | 6 ++- .../awsquery/AWSQueryOperationStackTest.kt | 4 +- .../StructDecodeWrappedXMLGeneratorTests.kt | 15 ++++--- ...ttpResponseBindingErrorGeneratableTests.kt | 25 ++++++----- .../AWSRestJson1ProtocolGeneratorTests.kt | 2 +- .../FlexibleChecksumMiddlewareTests.kt | 2 +- ...oute53InvalidBatchErrorIntegrationTests.kt | 16 ++++---- ...yHttpResponseBindingErrorGeneratorTests.kt | 24 +++++------ .../restxml/AWSRestXMLEventStreamTests.kt | 8 ++-- ...LHTTPResponseBindingErrorGeneratorTests.kt | 24 +++++------ .../serde/S3UnwrappedXMLOutputTraitTests.kt | 15 ++++--- 15 files changed, 121 insertions(+), 117 deletions(-) diff --git a/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift b/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift index 71ce4cf277e..6f5c299489f 100644 --- a/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift +++ b/Tests/Core/AWSClientRuntimeTests/Protocols/RestJSON/RestJSONErrorTests.swift @@ -29,7 +29,7 @@ class RestJSONErrorTests: HttpResponseTestBase { return } - let greetingWithErrorsError = try await wireResponseErrorClosure(GreetingWithErrorsError.httpErrorBinding, wireResponseDocumentBinding())(httpResponse) + let greetingWithErrorsError = try await GreetingWithErrorsError.httpError(from:)(httpResponse) if let actual = greetingWithErrorsError as? ComplexError { let expected = ComplexError( @@ -99,14 +99,14 @@ extension ComplexError { public enum GreetingWithErrorsError { - static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) - switch baseError.code { - case "ComplexError": return try ComplexError.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) - } + static func httpError(from httpResponse: ClientRuntime.HttpResponse) async throws -> Swift.Error { + let data = try await httpResponse.data() + let responseReader = try SmithyJSON.Reader.from(data: data) + let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let error = baseError.customError() { return error } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt index 1068af53926..72a09dff145 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt @@ -18,23 +18,23 @@ extension EventStreamTestClientTypes.TestStream { var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] var payload: ClientRuntime.Data? = nil switch self { - case messagewithblob(let value): + case .messagewithblob(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithBlob"))) headers.append(.init(name: ":content-type", value: .string("application/octet-stream"))) payload = value.data - case messagewithstring(let value): + case .messagewithstring(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithString"))) headers.append(.init(name: ":content-type", value: .string("text/plain"))) payload = value.data?.data(using: .utf8) - case messagewithstruct(let value): + case .messagewithstruct(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithStruct"))) headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.TestStruct.write(value:to:)) - case messagewithunion(let value): + payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "TestStruct", with: EventStreamTestClientTypes.TestStruct.write(value:to:)) + case .messagewithunion(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithUnion"))) headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.TestUnion.write(value:to:)) - case messagewithheaders(let value): + payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "TestUnion", with: EventStreamTestClientTypes.TestUnion.write(value:to:)) + case .messagewithheaders(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithHeaders"))) if let headerValue = value.blob { headers.append(.init(name: "blob", value: .byteArray(headerValue))) @@ -60,24 +60,24 @@ extension EventStreamTestClientTypes.TestStream { if let headerValue = value.timestamp { headers.append(.init(name: "timestamp", value: .timestamp(headerValue))) } - case messagewithheaderandpayload(let value): + case .messagewithheaderandpayload(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithHeaderAndPayload"))) if let headerValue = value.header { headers.append(.init(name: "header", value: .string(headerValue))) } headers.append(.init(name: ":content-type", value: .string("application/octet-stream"))) payload = value.payload - case messagewithnoheaderpayloadtraits(let value): + case .messagewithnoheaderpayloadtraits(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithNoHeaderPayloadTraits"))) headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.write(value:to:)) - case messagewithunboundpayloadtraits(let value): + payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "MessageWithNoHeaderPayloadTraits", with: EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.write(value:to:)) + case .messagewithunboundpayloadtraits(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithUnboundPayloadTraits"))) if let headerValue = value.header { headers.append(.init(name: "header", value: .string(headerValue))) } headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(value, EventStreamTestClientTypes.MessageWithUnboundPayloadTraits.write(value:to:)) + payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "MessageWithUnboundPayloadTraits", with: EventStreamTestClientTypes.MessageWithUnboundPayloadTraits.write(value:to:)) case .sdkUnknown(_): throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } @@ -110,11 +110,13 @@ extension EventStreamTestClientTypes.TestStream { return .messagewithstring(event) case "MessageWithStruct": var event = EventStreamTestClientTypes.MessageWithStruct() - event.someStruct = try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, EventStreamTestClientTypes.TestStruct.read(from:)) + let value = try SmithyJSON.Reader.readFrom(message.payload, with: EventStreamTestClientTypes.TestStruct.read(from:)) + event.someStruct = value return .messagewithstruct(event) case "MessageWithUnion": var event = EventStreamTestClientTypes.MessageWithUnion() - event.someUnion = try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, EventStreamTestClientTypes.TestUnion.read(from:)) + let value = try SmithyJSON.Reader.readFrom(message.payload, with: EventStreamTestClientTypes.TestUnion.read(from:)) + event.someUnion = value return .messagewithunion(event) case "MessageWithHeaders": var event = EventStreamTestClientTypes.MessageWithHeaders() @@ -151,13 +153,15 @@ extension EventStreamTestClientTypes.TestStream { event.payload = message.payload return .messagewithheaderandpayload(event) case "MessageWithNoHeaderPayloadTraits": - return .messagewithnoheaderpayloadtraits(try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.read(from:))) + let value = try SmithyJSON.Reader.readFrom(message.payload, with: EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.read(from:)) + return .messagewithnoheaderpayloadtraits(value) case "MessageWithUnboundPayloadTraits": var event = EventStreamTestClientTypes.MessageWithUnboundPayloadTraits() if case .string(let value) = message.headers.value(name: "header") { event.header = value } - event.unboundString = try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, Swift.String.read(from:)) + let value = try SmithyJSON.Reader.readFrom(message.payload, with: Swift.String.read(from:)) + event.messagewithunboundpayloadtraits = value return .messagewithunboundpayloadtraits(event) default: return .sdkUnknown("error processing event stream, unrecognized event: \(params.eventType)") @@ -166,7 +170,8 @@ extension EventStreamTestClientTypes.TestStream { let makeError: (ClientRuntime.EventStream.Message, ClientRuntime.EventStream.MessageType.ExceptionParams) throws -> Swift.Error = { message, params in switch params.exceptionType { case "SomeError": - return try SmithyReadWrite.documentReadingClosure(rootNodeInfo: "")(message.payload, SomeError.read(from:)) + let value = try SmithyJSON.Reader.readFrom(message.payload, with: SomeError.read(from:)) + return value default: let httpResponse = HttpResponse(body: .data(message.payload), statusCode: .ok) return AWSClientRuntime.UnknownAWSHTTPServiceError(httpResponse: httpResponse, message: "error processing event stream, unrecognized ':exceptionType': \(params.exceptionType); contentType: \(params.contentType ?? "nil")", requestID: nil, typeName: nil) @@ -223,7 +228,7 @@ extension EventStreamTestClientTypes.TestStream { operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(TestStreamOpOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(TestStreamOpOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(TestStreamOpOutput.httpOutput(from:), TestStreamOpOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt index a272c365c57..2a48f910fa9 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt @@ -44,7 +44,7 @@ extension GetFooInput { operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(GetFooOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(GetFooOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(GetFooOutput.httpOutput(from:), GetFooOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: GetFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { @@ -93,11 +93,11 @@ extension PostFooInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: ""), inputWritingClosure: PostFooInput.write(value:to:))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "", inputWritingClosure: PostFooInput.write(value:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(PostFooOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(PostFooOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PostFooOutput.httpOutput(from:), PostFooOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PostFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { @@ -146,11 +146,11 @@ extension PutFooInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: ""), inputWritingClosure: PutFooInput.write(value:to:))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "", inputWritingClosure: PutFooInput.write(value:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(PutFooOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(PutFooOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PutFooOutput.httpOutput(from:), PutFooOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PutFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { @@ -200,11 +200,11 @@ extension PutObjectInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: "PutObjectInput"), inputWritingClosure: PutObjectInput.write(value:to:))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "PutObjectInput", inputWritingClosure: PutObjectInput.write(value:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(PutObjectOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(PutObjectOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PutObjectOutput.httpOutput(from:), PutObjectOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PutObjectOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt index 82d22ed3e7f..80fd5c33362 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt @@ -23,18 +23,18 @@ class AWSJSONHttpResponseBindingErrorGeneratorTests { val expectedContents = """ enum GreetingWithErrorsOutputError { - static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let baseError = try AWSClientRuntime.AWSJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) - if let serviceError = try Json10ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } - switch baseError.code { - case "ComplexError": return try ComplexError.makeError(baseError: baseError) - case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) - } + static func httpError(from httpResponse: ClientRuntime.HttpResponse) async throws -> Swift.Error { + let data = try await httpResponse.data() + let responseReader = try SmithyJSON.Reader.from(data: data) + let baseError = try AWSClientRuntime.AWSJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let error = baseError.customError() { return error } + if let serviceError = try Json10ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index ee379665ee6..50929ccf731 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -27,7 +27,7 @@ extension InitialRequestTestClientTypes.TestStream { var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] var payload: ClientRuntime.Data? = nil switch self { - case messagewithstring(let value): + case .messagewithstring(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithString"))) headers.append(.init(name: ":content-type", value: .string("text/plain"))) payload = value.data?.data(using: .utf8) @@ -98,7 +98,9 @@ extension EventStreamOpInput { val expectedContents = """ extension EventStreamOpInput { func makeInitialRequestMessage(encoder: ClientRuntime.RequestEncoder) throws -> EventStream.Message { - let initialRequestPayload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "")(self, EventStreamOpInput.write(value:to:)) + let writer = SmithyJSON.Writer(nodeInfo: "") + try writer.write(self, writingClosure: EventStreamOpInput.write(value:to:)) + let initialRequestPayload = try writer.data() let initialRequestMessage = EventStream.Message( headers: [ EventStream.Header(name: ":message-type", value: .string("event")), diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt index 9f628f775cb..46b9d417bcd 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt @@ -44,12 +44,12 @@ class AWSQueryOperationStackTest { operation.buildStep.intercept(position: .before, middleware: EndpointResolverMiddleware(endpointResolver: config.endpointResolver, endpointParams: endpointParams)) operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyReadWrite.documentWritingClosure(rootNodeInfo: ""), inputWritingClosure: NoInputAndOutputInput.write(value:to:))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "", inputWritingClosure: NoInputAndOutputInput.write(value:to:))) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/x-www-form-urlencoded")) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(NoInputAndOutputOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(NoInputAndOutputOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(NoInputAndOutputOutput.httpOutput(from:), NoInputAndOutputOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt index 3674ccff518..56bee157c77 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/StructDecodeWrappedXMLGeneratorTests.kt @@ -22,14 +22,13 @@ class StructDecodeWrappedXMLGeneratorTests { val expectedContents = """ extension FlattenedXmlMapOutput { - static var httpBinding: SmithyReadWrite.WireResponseOutputBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let reader = responseReader["FlattenedXmlMapResult"] - var value = FlattenedXmlMapOutput() - value.myMap = try reader["myMap"].readMapIfPresent(valueReadingClosure: Swift.String.read(from:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: true) - return value - } + static func httpOutput(from httpResponse: ClientRuntime.HttpResponse) async throws -> FlattenedXmlMapOutput { + let data = try await httpResponse.data() + let responseReader = try SmithyXML.Reader.from(data: data) + let reader = responseReader["FlattenedXmlMapResult"] + var value = FlattenedXmlMapOutput() + value.myMap = try reader["myMap"].readMapIfPresent(valueReadingClosure: Swift.String.read(from:), keyNodeInfo: "key", valueNodeInfo: "value", isFlattened: true) + return value } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt index 71b2e3dc74f..bd5c134ce9b 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt @@ -12,7 +12,6 @@ class AWSRestJson1HttpResponseBindingErrorGeneratableTests { @Test fun `001 GreetingWithErrorsOutputError+HttpResponseErrorBinding`() { val context = setupTests("awsrestjson1/restjson-error.smithy", "aws.protocoltests.restjson1#RestJson1") - print(context.manifest.files.joinToString("\n")) val contents = TestUtils.getFileContents( context.manifest, "/Example/models/GreetingWithErrorsOutputError+HttpResponseErrorBinding.swift" @@ -21,18 +20,18 @@ class AWSRestJson1HttpResponseBindingErrorGeneratableTests { val expectedContents = """ enum GreetingWithErrorsOutputError { - static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) - if let serviceError = try RestJson1ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } - switch baseError.code { - case "ComplexError": return try ComplexError.makeError(baseError: baseError) - case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) - } + static func httpError(from httpResponse: ClientRuntime.HttpResponse) async throws -> Swift.Error { + let data = try await httpResponse.data() + let responseReader = try SmithyJSON.Reader.from(data: data) + let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let error = baseError.customError() { return error } + if let serviceError = try RestJson1ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt index 89344ba8b67..38a807cf4ad 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1ProtocolGeneratorTests.kt @@ -29,7 +29,7 @@ extension SmokeTestInput { guard let value else { return } try writer["payload1"].write(value.payload1) try writer["payload2"].write(value.payload2) - try writer["payload3"].write(value.payload3, writingClosure: ExampleClientTypes.Nested.write(value:to:)) + try writer["payload3"].write(value.payload3, with: ExampleClientTypes.Nested.write(value:to:)) } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt index 23b947672a7..5567286915f 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt @@ -54,7 +54,7 @@ extension ChecksumTestsClient { operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(wireResponseOutputClosure(SomeOperationOutput.httpBinding, wireResponseDocumentBinding()), wireResponseErrorClosure(SomeOperationOutputError.httpErrorBinding, wireResponseDocumentBinding()))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(SomeOperationOutput.httpOutput(from:), SomeOperationOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.FlexibleChecksumsResponseMiddleware(validationMode: true)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt index 379c7d3cb6a..7fa30e2c509 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/Route53InvalidBatchErrorIntegrationTests.kt @@ -28,14 +28,14 @@ class Route53InvalidBatchErrorIntegrationTests { val expectedContents = """ enum ChangeResourceRecordSetsOutputError { - static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) - switch baseError.code { - case "InvalidChangeBatch": return try InvalidChangeBatch.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) - } + static func httpError(from httpResponse: ClientRuntime.HttpResponse) async throws -> Swift.Error { + let data = try await httpResponse.data() + let responseReader = try SmithyXML.Reader.from(data: data) + let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let error = baseError.customError() { return error } + switch baseError.code { + case "InvalidChangeBatch": return try InvalidChangeBatch.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt index 1faa8ab0926..23f404945ac 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt @@ -23,18 +23,18 @@ class Ec2QueryHttpResponseBindingErrorGeneratorTests { val expectedContents = """ enum GreetingWithErrorsOutputError { - static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let baseError = try AWSClientRuntime.EC2QueryError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) - if let serviceError = try EC2ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } - switch baseError.code { - case "ComplexError": return try ComplexError.makeError(baseError: baseError) - case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) - } + static func httpError(from httpResponse: ClientRuntime.HttpResponse) async throws -> Swift.Error { + let data = try await httpResponse.data() + let responseReader = try SmithyXML.Reader.from(data: data) + let baseError = try AWSClientRuntime.EC2QueryError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let error = baseError.customError() { return error } + if let serviceError = try EC2ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexError": return try ComplexError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index 29add52d406..9b820785fd4 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -44,17 +44,17 @@ extension EventStreamTestClientTypes.TestEvents { var headers: [ClientRuntime.EventStream.Header] = [.init(name: ":message-type", value: .string("event"))] var payload: ClientRuntime.Data? = nil switch self { - case messageevent(let value): + case .messageevent(let value): headers.append(.init(name: ":event-type", value: .string("MessageEvent"))) headers.append(.init(name: ":content-type", value: .string("text/plain"))) payload = value.data?.data(using: .utf8) - case audioevent(let value): + case .audioevent(let value): headers.append(.init(name: ":event-type", value: .string("AudioEvent"))) if let headerValue = value.exampleHeader { headers.append(.init(name: "exampleHeader", value: .string(headerValue))) } headers.append(.init(name: ":content-type", value: .string("application/xml"))) - payload = try SmithyReadWrite.documentWritingClosure(rootNodeInfo: "Audio")(value, EventStreamTestClientTypes.Audio.write(value:to:)) + payload = try SmithyXML.Writer.write(value, rootNodeInfo: "Audio", with: EventStreamTestClientTypes.Audio.write(value:to:)) case .sdkUnknown(_): throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } @@ -82,7 +82,7 @@ extension EventStreamTestClientTypes.MessageWithAudio { static func write(value: EventStreamTestClientTypes.MessageWithAudio?, to writer: SmithyXML.Writer) throws { guard let value else { return } - try writer["audio"].write(value.audio, writingClosure: EventStreamTestClientTypes.Audio.write(value:to:)) + try writer["audio"].write(value.audio, with: EventStreamTestClientTypes.Audio.write(value:to:)) try writer["exampleHeader"].write(value.exampleHeader) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt index dc08b337134..6cecb05f4b1 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt @@ -24,18 +24,18 @@ class AWSRestXMLHTTPResponseBindingErrorGeneratorTests { val expectedContents = """ enum GreetingWithErrorsOutputError { - static var httpErrorBinding: SmithyReadWrite.WireResponseErrorBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) - if let serviceError = try RestXmlerrorsClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } - switch baseError.code { - case "ComplexXMLError": return try ComplexXMLError.makeError(baseError: baseError) - case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) - default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) - } + static func httpError(from httpResponse: ClientRuntime.HttpResponse) async throws -> Swift.Error { + let data = try await httpResponse.data() + let responseReader = try SmithyXML.Reader.from(data: data) + let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) + if let error = baseError.customError() { return error } + if let serviceError = try RestXmlerrorsClientTypes.responseServiceErrorBinding(baseError: baseError) { + return serviceError + } + switch baseError.code { + case "ComplexXMLError": return try ComplexXMLError.makeError(baseError: baseError) + case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) + default: return try AWSClientRuntime.UnknownAWSHTTPServiceError.makeError(baseError: baseError) } } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt index 5a789aea491..c2afabefc62 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/serde/S3UnwrappedXMLOutputTraitTests.kt @@ -17,14 +17,13 @@ class S3UnwrappedXMLOutputTraitTests { val expectedContents = """ extension GetBucketLocationOutput { - static var httpBinding: SmithyReadWrite.WireResponseOutputBinding { - { httpResponse, responseDocumentClosure in - let responseReader = try await responseDocumentClosure(httpResponse) - let reader = responseReader.unwrap() - var value = GetBucketLocationOutput() - value.locationConstraint = try reader["LocationConstraint"].readIfPresent() - return value - } + static func httpOutput(from httpResponse: ClientRuntime.HttpResponse) async throws -> GetBucketLocationOutput { + let data = try await httpResponse.data() + let responseReader = try SmithyXML.Reader.from(data: data) + let reader = responseReader.unwrap() + var value = GetBucketLocationOutput() + value.locationConstraint = try reader["LocationConstraint"].readIfPresent() + return value } } """ From 075ae45c19e74ddc194f1fa45b1cc7a0228fd39c Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 22 Apr 2024 13:42:15 -0500 Subject: [PATCH 20/27] Add customization for S3 404 error --- .../S3EmptyBody404Tests.swift | 4 ++-- .../HTTP/HttpResponse+AWS.swift | 4 ---- .../Protocols/RestXML/RestXMLError.swift | 6 ++--- .../restxml/RestXMLCustomizations.kt | 22 +++++++++++++++++++ ...NHttpResponseBindingErrorGeneratorTests.kt | 16 +++++--------- ...ttpResponseBindingErrorGeneratableTests.kt | 16 +++++--------- ...yHttpResponseBindingErrorGeneratorTests.kt | 16 +++++--------- ...LHTTPResponseBindingErrorGeneratorTests.kt | 16 +++++--------- 8 files changed, 51 insertions(+), 49 deletions(-) diff --git a/IntegrationTests/Services/AWSS3IntegrationTests/S3EmptyBody404Tests.swift b/IntegrationTests/Services/AWSS3IntegrationTests/S3EmptyBody404Tests.swift index d4021f8b5cb..d90bc3d06a5 100644 --- a/IntegrationTests/Services/AWSS3IntegrationTests/S3EmptyBody404Tests.swift +++ b/IntegrationTests/Services/AWSS3IntegrationTests/S3EmptyBody404Tests.swift @@ -34,8 +34,8 @@ class S3EmptyBody404Tests: S3XCTestCase { _ = try await client.headObject(input: input) // If an error was not thrown by the HeadObject call, fail the test. - XCTFail("Request should have thrown a service error with code NotFound, instead the request succeeded") - } catch let error as AWSServiceError & ClientRuntime.HTTPError where error.errorCode == "NotFound" { + XCTFail("Request should have thrown a NotFound modeled service error, instead the request succeeded") + } catch let error as AWSS3.NotFound { // The expected error has now been caught. Verify that the body is empty and the status code is 404. XCTAssertEqual(error.httpResponse.body, .data(nil)) diff --git a/Sources/Core/AWSClientRuntime/HTTP/HttpResponse+AWS.swift b/Sources/Core/AWSClientRuntime/HTTP/HttpResponse+AWS.swift index 8804285c255..5a8bb9a53e3 100644 --- a/Sources/Core/AWSClientRuntime/HTTP/HttpResponse+AWS.swift +++ b/Sources/Core/AWSClientRuntime/HTTP/HttpResponse+AWS.swift @@ -6,10 +6,6 @@ import ClientRuntime public extension HttpResponse { - /// Returns true if the status code is `HttpStatusCode.notFound` and the body is empty. - var statusCodeIsNotFoundAndBodyIsEmpty: Bool { - return statusCode == .notFound && body.isEmpty - } /// The value of the x-amz-request-id header. var requestId: String? { diff --git a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift index 4a6aed09b4b..a6fda45cb9f 100644 --- a/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift +++ b/Sources/Core/AWSClientRuntime/Protocols/RestXML/RestXMLError.swift @@ -23,10 +23,10 @@ public struct RestXMLError: BaseError { public init(httpResponse: HttpResponse, responseReader: Reader, noErrorWrapping: Bool) throws { self.errorBodyReader = Self.errorBodyReader(responseReader: responseReader, noErrorWrapping: noErrorWrapping) let code: String? = try errorBodyReader["Code"].readIfPresent() - guard let code else { throw BaseErrorDecodeError.missingRequiredData } + if code == nil && httpResponse.statusCode != .notFound { throw BaseErrorDecodeError.missingRequiredData } let message: String? = try errorBodyReader["Message"].readIfPresent() - let requestID: String? = try responseReader["RequestId"].readIfPresent() - self.code = code + let requestID: String? = try responseReader["RequestId"].readIfPresent() ?? httpResponse.requestId + self.code = code ?? "NotFound" self.message = message self.requestID = requestID self.httpResponse = httpResponse diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt index 8e9e46a2978..6b32f8f29cf 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt @@ -8,8 +8,30 @@ package software.amazon.smithy.aws.swift.codegen.protocols.restxml import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol +import software.amazon.smithy.model.shapes.ServiceShape +import software.amazon.smithy.model.shapes.ShapeId +import software.amazon.smithy.swift.codegen.SwiftWriter +import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator class RestXMLCustomizations : AWSHTTPProtocolCustomizations() { override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestXML.RestXMLError + + override fun hasServiceErrorCustomizations(ctx: ProtocolGenerator.GenerationContext): Boolean { + return serviceIsS3(ctx.service) + } + + override fun renderServiceErrorCustomizations(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter) { + if (!serviceIsS3(ctx.service)) { return } + writer.openBlock( + "if baseError.httpResponse.statusCode == .notFound && baseError.httpResponse.body.isEmpty {", + "}" + ) { + writer.write("return try NotFound.makeError(baseError: baseError)") + } + } + + private fun serviceIsS3(serviceShape: ServiceShape): Boolean { + return serviceShape.id == ShapeId.from("com.amazonaws.s3#AmazonS3") + } } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt index 80fd5c33362..d336f2ff202 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJSONHttpResponseBindingErrorGeneratorTests.kt @@ -28,9 +28,7 @@ enum GreetingWithErrorsOutputError { let responseReader = try SmithyJSON.Reader.from(data: data) let baseError = try AWSClientRuntime.AWSJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) if let error = baseError.customError() { return error } - if let serviceError = try Json10ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } + if let error = try httpServiceError(baseError: baseError) { return error } switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) @@ -47,16 +45,14 @@ enum GreetingWithErrorsOutputError { val context = setupTests("awsjson/json-error.smithy", "aws.protocoltests.json10#AwsJson10") val contents = TestUtils.getFileContents( context.manifest, - "/Example/models/AwsJson10+ServiceErrorHelperMethod.swift" + "/Example/models/AwsJson10+HTTPServiceError.swift" ) contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension Json10ProtocolClientTypes { - static func responseServiceErrorBinding(baseError: AWSClientRuntime.AWSJSONError) throws -> Swift.Error? { - switch baseError.code { - case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) - default: return nil - } +func httpServiceError(baseError: AWSClientRuntime.AWSJSONError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt index bd5c134ce9b..485bb682c0c 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsrestjson/AWSRestJson1HttpResponseBindingErrorGeneratableTests.kt @@ -25,9 +25,7 @@ enum GreetingWithErrorsOutputError { let responseReader = try SmithyJSON.Reader.from(data: data) let baseError = try AWSClientRuntime.RestJSONError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) if let error = baseError.customError() { return error } - if let serviceError = try RestJson1ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } + if let error = try httpServiceError(baseError: baseError) { return error } switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) @@ -44,16 +42,14 @@ enum GreetingWithErrorsOutputError { val context = setupTests("awsrestjson1/restjson-error.smithy", "aws.protocoltests.restjson1#RestJson1") val contents = TestUtils.getFileContents( context.manifest, - "/Example/models/RestJson1+ServiceErrorHelperMethod.swift" + "/Example/models/RestJson1+HTTPServiceError.swift" ) contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension RestJson1ProtocolClientTypes { - static func responseServiceErrorBinding(baseError: AWSClientRuntime.RestJSONError) throws -> Swift.Error? { - switch baseError.code { - case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) - default: return nil - } +func httpServiceError(baseError: AWSClientRuntime.RestJSONError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt index 23f404945ac..c6035c0437f 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/ec2query/Ec2QueryHttpResponseBindingErrorGeneratorTests.kt @@ -28,9 +28,7 @@ enum GreetingWithErrorsOutputError { let responseReader = try SmithyXML.Reader.from(data: data) let baseError = try AWSClientRuntime.EC2QueryError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) if let error = baseError.customError() { return error } - if let serviceError = try EC2ProtocolClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } + if let error = try httpServiceError(baseError: baseError) { return error } switch baseError.code { case "ComplexError": return try ComplexError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) @@ -104,15 +102,13 @@ extension ComplexError { @Test fun `005 AwsEc2+ServiceErrorHelperMethod AWSHttpServiceError`() { val context = setupTests("ec2query/query-error.smithy", "aws.protocoltests.ec2#AwsEc2") - val contents = TestUtils.getFileContents(context.manifest, "/Example/models/AwsEc2+ServiceErrorHelperMethod.swift") + val contents = TestUtils.getFileContents(context.manifest, "/Example/models/AwsEc2+HTTPServiceError.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension EC2ProtocolClientTypes { - static func responseServiceErrorBinding(baseError: AWSClientRuntime.EC2QueryError) throws -> Swift.Error? { - switch baseError.code { - case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) - default: return nil - } +func httpServiceError(baseError: AWSClientRuntime.EC2QueryError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil } } """ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt index 6cecb05f4b1..0f678f56767 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLHTTPResponseBindingErrorGeneratorTests.kt @@ -29,9 +29,7 @@ enum GreetingWithErrorsOutputError { let responseReader = try SmithyXML.Reader.from(data: data) let baseError = try AWSClientRuntime.RestXMLError(httpResponse: httpResponse, responseReader: responseReader, noErrorWrapping: false) if let error = baseError.customError() { return error } - if let serviceError = try RestXmlerrorsClientTypes.responseServiceErrorBinding(baseError: baseError) { - return serviceError - } + if let error = try httpServiceError(baseError: baseError) { return error } switch baseError.code { case "ComplexXMLError": return try ComplexXMLError.makeError(baseError: baseError) case "InvalidGreeting": return try InvalidGreeting.makeError(baseError: baseError) @@ -136,15 +134,13 @@ extension ComplexXMLErrorNoErrorWrapping { @Test fun `006 RestXml+ServiceErrorHelperMethod AWSHttpServiceError`() { val context = setupTests("restxml/xml-errors.smithy", "aws.protocoltests.restxml#RestXml") - val contents = getFileContents(context.manifest, "/Example/models/RestXml+ServiceErrorHelperMethod.swift") + val contents = getFileContents(context.manifest, "/Example/models/RestXml+HTTPServiceError.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension RestXmlerrorsClientTypes { - static func responseServiceErrorBinding(baseError: AWSClientRuntime.RestXMLError) throws -> Swift.Error? { - switch baseError.code { - case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) - default: return nil - } +func httpServiceError(baseError: AWSClientRuntime.RestXMLError) throws -> Swift.Error? { + switch baseError.code { + case "ExampleServiceError": return try ExampleServiceError.makeError(baseError: baseError) + default: return nil } } """ From 37c4bd3d01c45bb0c3fde10f5617468a425e13af Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 22 Apr 2024 14:48:17 -0500 Subject: [PATCH 21/27] Fix S3 protocol test failure --- .../restxml/RestXMLCustomizations.kt | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt index 6b32f8f29cf..6b26418f636 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt @@ -18,20 +18,31 @@ class RestXMLCustomizations : AWSHTTPProtocolCustomizations() { override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestXML.RestXMLError override fun hasServiceErrorCustomizations(ctx: ProtocolGenerator.GenerationContext): Boolean { - return serviceIsS3(ctx.service) + return shouldApplyS3ErrorCustomization(ctx) } override fun renderServiceErrorCustomizations(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter) { - if (!serviceIsS3(ctx.service)) { return } - writer.openBlock( - "if baseError.httpResponse.statusCode == .notFound && baseError.httpResponse.body.isEmpty {", - "}" - ) { - writer.write("return try NotFound.makeError(baseError: baseError)") + if (shouldApplyS3ErrorCustomization(ctx)) { + writer.openBlock( + "if baseError.httpResponse.statusCode == .notFound && baseError.httpResponse.body.isEmpty {", + "}" + ) { + writer.write("return try NotFound.makeError(baseError: baseError)") + } } } - private fun serviceIsS3(serviceShape: ServiceShape): Boolean { - return serviceShape.id == ShapeId.from("com.amazonaws.s3#AmazonS3") + private fun shouldApplyS3ErrorCustomization(ctx: ProtocolGenerator.GenerationContext): Boolean { + return serviceIsS3(ctx) && serviceHasNotFoundError(ctx) + } + + private fun serviceIsS3(ctx: ProtocolGenerator.GenerationContext): Boolean { + return ctx.service.id == ShapeId.from("com.amazonaws.s3#AmazonS3") + } + + // This check is performed because S3 protocol tests do not define this error, + // and the protocol test will fail since the NotFound type is undefined. + private fun serviceHasNotFoundError(ctx: ProtocolGenerator.GenerationContext): Boolean { + return ctx.model.getShape(ShapeId.from("com.amazonaws.s3#NotFound")).isPresent } } From 00e5feb7430a4da382ac417faa2c48077bc34aa8 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 22 Apr 2024 15:14:48 -0500 Subject: [PATCH 22/27] Fix ktlint --- .../aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt index 6b26418f636..8a4fca023b8 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt @@ -8,7 +8,6 @@ package software.amazon.smithy.aws.swift.codegen.protocols.restxml import software.amazon.smithy.aws.swift.codegen.AWSClientRuntimeTypes import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol -import software.amazon.smithy.model.shapes.ServiceShape import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator From 0c8fbcc31de404262c0269a48edbfbe2d9db3f28 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 22 Apr 2024 15:57:35 -0500 Subject: [PATCH 23/27] Fix marshal/unmarshal, inherit common protocol generator implementations --- .../AWSHTTPBindingProtocolGenerator.kt | 18 ++++++ .../awsjson/AWSJSON1_0ProtocolGenerator.kt | 20 +----- .../awsjson/AWSJSON1_1ProtocolGenerator.kt | 18 ------ .../awsquery/AWSQueryProtocolGenerator.kt | 61 ------------------- .../ec2query/EC2QueryProtocolGenerator.kt | 49 --------------- .../restjson/AWSRestJson1ProtocolGenerator.kt | 19 ------ .../restxml/RestXMLProtocolGenerator.kt | 18 ------ 7 files changed, 19 insertions(+), 184 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt index 9d983c079ed..e0df96d2d4b 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/AWSHTTPBindingProtocolGenerator.kt @@ -4,6 +4,8 @@ */ package software.amazon.smithy.aws.swift.codegen +import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator +import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.OperationEndpointResolverMiddleware import software.amazon.smithy.aws.swift.codegen.middleware.UserAgentMiddleware import software.amazon.smithy.codegen.core.Symbol @@ -142,4 +144,20 @@ abstract class AWSHTTPBindingProtocolGenerator( } return streamingShapes } + + override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { + var streamingShapes = inputStreamingShapes(ctx) + val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) + streamingShapes.forEach { streamingMember -> + messageMarshallableGenerator.render(streamingMember) + } + } + + override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { + var streamingShapes = outputStreamingShapes(ctx) + val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) + streamingShapes.forEach { streamingMember -> + messageUnmarshallableGenerator.render(streamingMember) + } + } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt index 81b24eb643e..19581f27fb7 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_0ProtocolGenerator.kt @@ -6,8 +6,6 @@ package software.amazon.smithy.aws.swift.codegen.protocols.awsjson import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait import software.amazon.smithy.model.shapes.OperationShape @@ -18,7 +16,7 @@ import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeM import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep -open class AWSJSON1_0ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCustomizations()) { +class AWSJSON1_0ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCustomizations()) { override val defaultContentType = "application/x-amz-json-1.0" override val protocol: ShapeId = AwsJson1_0Trait.ID override val shouldRenderEncodableConformance: Boolean = true @@ -43,20 +41,4 @@ open class AWSJSON1_0ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSON operationMiddleware.removeMiddleware(operation, MiddlewareStep.SERIALIZESTEP, "ContentTypeMiddleware") operationMiddleware.appendMiddleware(operation, ContentTypeMiddleware(ctx.model, ctx.symbolProvider, resolver.determineRequestContentType(operation), true)) } - - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.render(streamingMember) - } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - for (streamingShape in streamingShapes) { - messageMarshallableGenerator.render(streamingShape) - } - } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt index 81939a8275c..8618432fca9 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsjson/AWSJSON1_1ProtocolGenerator.kt @@ -6,8 +6,6 @@ package software.amazon.smithy.aws.swift.codegen.protocols.awsjson import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.swift.codegen.middleware.AWSXAmzTargetMiddleware import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait import software.amazon.smithy.model.shapes.OperationShape @@ -43,20 +41,4 @@ class AWSJSON1_1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSJSONCusto operationMiddleware.removeMiddleware(operation, MiddlewareStep.SERIALIZESTEP, "ContentTypeMiddleware") operationMiddleware.appendMiddleware(operation, ContentTypeMiddleware(ctx.model, ctx.symbolProvider, resolver.determineRequestContentType(operation), true)) } - - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.render(streamingMember) - } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - for (streamingShape in streamingShapes) { - messageMarshallableGenerator.render(streamingShape) - } - } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt index 118abc7e468..4549f3c14f6 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/awsquery/AWSQueryProtocolGenerator.kt @@ -7,23 +7,14 @@ package software.amazon.smithy.aws.swift.codegen.protocols.awsquery import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait -import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.model.traits.TimestampFormatTrait -import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep -import software.amazon.smithy.swift.codegen.model.ShapeMetadata open class AWSQueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSQueryCustomizations()) { override val defaultContentType = "application/x-www-form-urlencoded" @@ -39,58 +30,6 @@ open class AWSQueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(AWSQueryC ) override val tagsToIgnore = setOf("defaults") - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.render(streamingMember) - } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - streamingShapes.forEach { streamingMember -> - messageMarshallableGenerator.render(streamingMember) - } - } - - override fun renderStructEncode( - ctx: ProtocolGenerator.GenerationContext, - shapeContainingMembers: Shape, - shapeMetadata: Map, - members: List, - writer: SwiftWriter, - defaultTimestampFormat: TimestampFormatTrait.Format, - path: String?, - ) { - StructEncodeGenerator( - ctx, - shapeContainingMembers, - members, - shapeMetadata, - writer, - ).render() - } - - override fun renderStructDecode( - ctx: ProtocolGenerator.GenerationContext, - shapeContainingMembers: Shape, - shapeMetadata: Map, - members: List, - writer: SwiftWriter, - defaultTimestampFormat: TimestampFormatTrait.Format, - path: String, - ) { - StructDecodeGenerator( - ctx, - shapeContainingMembers, - members, - shapeMetadata, - writer, - ).render() - } - override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { super.addProtocolSpecificMiddleware(ctx, operation) // Original instance of OperationInputBodyMiddleware checks if there is an HTTP Body, but for AWSQuery diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt index 17eb1c4e526..9f3e44751ab 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/ec2query/EC2QueryProtocolGenerator.kt @@ -7,23 +7,14 @@ package software.amazon.smithy.aws.swift.codegen.protocols.ec2query import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator import software.amazon.smithy.aws.swift.codegen.FormURLHttpBindingResolver -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait -import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.shapes.OperationShape -import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.model.traits.TimestampFormatTrait -import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.HttpBindingResolver import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.middlewares.ContentTypeMiddleware import software.amazon.smithy.swift.codegen.integration.middlewares.OperationInputBodyMiddleware -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructDecodeGenerator -import software.amazon.smithy.swift.codegen.integration.serde.struct.StructEncodeGenerator import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep -import software.amazon.smithy.swift.codegen.model.ShapeMetadata class EC2QueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(EC2QueryCustomizations()) { override val defaultContentType = "application/x-www-form-urlencoded" @@ -39,46 +30,6 @@ class EC2QueryProtocolGenerator : AWSHTTPBindingProtocolGenerator(EC2QueryCustom ) override val tagsToIgnore = setOf("defaults") - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.render(streamingMember) - } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - streamingShapes.forEach { streamingMember -> - messageMarshallableGenerator.render(streamingMember) - } - } - - override fun renderStructEncode( - ctx: ProtocolGenerator.GenerationContext, - shapeContainingMembers: Shape, - shapeMetadata: Map, - members: List, - writer: SwiftWriter, - defaultTimestampFormat: TimestampFormatTrait.Format, - path: String?, - ) { - StructEncodeGenerator(ctx, shapeContainingMembers, members, shapeMetadata, writer).render() - } - - override fun renderStructDecode( - ctx: ProtocolGenerator.GenerationContext, - shapeContainingMembers: Shape, - shapeMetadata: Map, - members: List, - writer: SwiftWriter, - defaultTimestampFormat: TimestampFormatTrait.Format, - path: String, - ) { - StructDecodeGenerator(ctx, shapeContainingMembers, members, mapOf(), writer).render() - } - override fun addProtocolSpecificMiddleware(ctx: ProtocolGenerator.GenerationContext, operation: OperationShape) { super.addProtocolSpecificMiddleware(ctx, operation) // Original instance of OperationInputBodyMiddleware checks if there is an HTTP Body, but for Ec2Query diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt index 6de131992c7..3be167efcd1 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restjson/AWSRestJson1ProtocolGenerator.kt @@ -5,11 +5,8 @@ package software.amazon.smithy.aws.swift.codegen.protocols.restjson import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.RestJson1Trait import software.amazon.smithy.model.shapes.ShapeId -import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator class AWSRestJson1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestJSONCustomizations()) { override val defaultContentType = "application/json" @@ -19,20 +16,4 @@ class AWSRestJson1ProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestJSONCu "SDKAppendedGzipAfterProvidedEncoding_restJson1", ) override val tagsToIgnore = setOf("defaults") - - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.render(streamingMember) - } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - val streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - for (streamingShape in streamingShapes) { - messageMarshallableGenerator.render(streamingShape) - } - } } diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt index 6f860369a02..36a426e4429 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLProtocolGenerator.kt @@ -6,8 +6,6 @@ package software.amazon.smithy.aws.swift.codegen.protocols.restxml import software.amazon.smithy.aws.swift.codegen.AWSHTTPBindingProtocolGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageMarshallableGenerator -import software.amazon.smithy.aws.swift.codegen.message.MessageUnmarshallableGenerator import software.amazon.smithy.aws.traits.protocols.RestXmlTrait import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator @@ -32,22 +30,6 @@ class RestXMLProtocolGenerator : AWSHTTPBindingProtocolGenerator(RestXMLCustomiz ) override val tagsToIgnore = setOf("defaults") - override fun generateMessageMarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = outputStreamingShapes(ctx) - val messageUnmarshallableGenerator = MessageUnmarshallableGenerator(ctx) - streamingShapes.forEach { streamingMember -> - messageUnmarshallableGenerator.render(streamingMember) - } - } - - override fun generateMessageUnmarshallable(ctx: ProtocolGenerator.GenerationContext) { - var streamingShapes = inputStreamingShapes(ctx) - val messageMarshallableGenerator = MessageMarshallableGenerator(ctx, defaultContentType) - streamingShapes.forEach { streamingMember -> - messageMarshallableGenerator.render(streamingMember) - } - } - override fun generateDeserializers(ctx: ProtocolGenerator.GenerationContext) { super.generateDeserializers(ctx) val errorShapes = resolveErrorShapes(ctx) From 8f39040ae2bd91f0c763464c5b2ab5d84a0ecd31 Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Mon, 22 Apr 2024 17:55:12 -0500 Subject: [PATCH 24/27] Code cleanup --- .../protocols/restxml/RestXMLCustomizations.kt | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt index 8a4fca023b8..6c759a74765 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/protocols/restxml/RestXMLCustomizations.kt @@ -10,18 +10,16 @@ import software.amazon.smithy.aws.swift.codegen.AWSHTTPProtocolCustomizations import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.ShapeId import software.amazon.smithy.swift.codegen.SwiftWriter +import software.amazon.smithy.swift.codegen.integration.HTTPProtocolCustomizable.ServiceErrorCustomRenderer import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator class RestXMLCustomizations : AWSHTTPProtocolCustomizations() { override val baseErrorSymbol: Symbol = AWSClientRuntimeTypes.RestXML.RestXMLError - override fun hasServiceErrorCustomizations(ctx: ProtocolGenerator.GenerationContext): Boolean { - return shouldApplyS3ErrorCustomization(ctx) - } + private class S3Empty404Renderer : ServiceErrorCustomRenderer { - override fun renderServiceErrorCustomizations(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter) { - if (shouldApplyS3ErrorCustomization(ctx)) { + override fun render(writer: SwiftWriter) { writer.openBlock( "if baseError.httpResponse.statusCode == .notFound && baseError.httpResponse.body.isEmpty {", "}" @@ -31,6 +29,12 @@ class RestXMLCustomizations : AWSHTTPProtocolCustomizations() { } } + override fun serviceErrorCustomRenderer( + ctx: ProtocolGenerator.GenerationContext + ): ServiceErrorCustomRenderer? { + return S3Empty404Renderer().takeIf { shouldApplyS3ErrorCustomization(ctx) } + } + private fun shouldApplyS3ErrorCustomization(ctx: ProtocolGenerator.GenerationContext): Boolean { return serviceIsS3(ctx) && serviceHasNotFoundError(ctx) } @@ -39,8 +43,8 @@ class RestXMLCustomizations : AWSHTTPProtocolCustomizations() { return ctx.service.id == ShapeId.from("com.amazonaws.s3#AmazonS3") } - // This check is performed because S3 protocol tests do not define this error, - // and the protocol test will fail since the NotFound type is undefined. + // This check is performed because S3 protocol tests do not define the NotFound modeled error, + // and the protocol test will fail if it is undefined. private fun serviceHasNotFoundError(ctx: ProtocolGenerator.GenerationContext): Boolean { return ctx.model.getShape(ShapeId.from("com.amazonaws.s3#NotFound")).isPresent } From 97d840d9bae7f0684f568cd3ef6bfc658b779d1b Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Tue, 23 Apr 2024 23:27:20 -0500 Subject: [PATCH 25/27] Add protocol tests to build event stream support, update initial events --- .../Resources/Package.Base.swift | 29 ++++--- Package.swift | 29 ++++--- .../build.gradle.kts | 6 +- .../model/eventstream-rpc.smithy | 83 +++++++++++++++++++ .../model/eventstream.smithy | 2 +- .../message/MessageMarshallableGenerator.kt | 28 +++++-- .../message/MessageUnmarshallableGenerator.kt | 7 +- .../aws/swift/codegen/EventStreamTests.kt | 15 ++-- .../awsjson/AWSJsonHttpInitialRequestTests.kt | 6 +- .../restxml/AWSRestXMLEventStreamTests.kt | 2 +- scripts/protogen.sh | 1 + 11 files changed, 161 insertions(+), 47 deletions(-) create mode 100644 codegen/protocol-test-codegen-local/model/eventstream-rpc.smithy diff --git a/AWSSDKSwiftCLI/Sources/AWSSDKSwiftCLI/Resources/Package.Base.swift b/AWSSDKSwiftCLI/Sources/AWSSDKSwiftCLI/Resources/Package.Base.swift index 839afea79cf..7240a79291c 100644 --- a/AWSSDKSwiftCLI/Sources/AWSSDKSwiftCLI/Resources/Package.Base.swift +++ b/AWSSDKSwiftCLI/Sources/AWSSDKSwiftCLI/Resources/Package.Base.swift @@ -191,11 +191,13 @@ func addProtocolTests() { let name: String let sourcePath: String let testPath: String? + let buildOnly: Bool - init(name: String, sourcePath: String, testPath: String? = nil) { + init(name: String, sourcePath: String, testPath: String? = nil, buildOnly: Bool = false) { self.name = name self.sourcePath = sourcePath self.testPath = testPath + self.buildOnly = buildOnly } } @@ -217,21 +219,22 @@ func addProtocolTests() { .init(name: "S3TestSDK", sourcePath: "\(baseDir)/s3"), .init(name: "rest_json_extras", sourcePath: "\(baseDirLocal)/rest_json_extras"), .init(name: "AwsQueryExtras", sourcePath: "\(baseDirLocal)/AwsQueryExtras"), + .init(name: "EventStream", sourcePath: "\(baseDirLocal)/EventStream", buildOnly: true), + .init(name: "RPCEventStream", sourcePath: "\(baseDirLocal)/RPCEventStream", buildOnly: true), .init(name: "Waiters", sourcePath: "\(baseDirLocal)/Waiters", testPath: "codegen/protocol-test-codegen-local/Tests"), ] for protocolTest in protocolTests { - package.targets += [ - .target( - name: protocolTest.name, - dependencies: [.clientRuntime, .awsClientRuntime], - path: "\(protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)" - ), - .testTarget( - name: "\(protocolTest.name)Tests", - dependencies: [.smithyTestUtils, .byNameItem(name: protocolTest.name, condition: nil)], - path: "\(protocolTest.testPath ?? protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)Tests" - ) - ] + let target = Target.target( + name: protocolTest.name, + dependencies: [.clientRuntime, .awsClientRuntime], + path: "\(protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)" + ) + let testTarget = protocolTest.buildOnly ? nil : Target.testTarget( + name: "\(protocolTest.name)Tests", + dependencies: [.smithyTestUtils, .byNameItem(name: protocolTest.name, condition: nil)], + path: "\(protocolTest.testPath ?? protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)Tests" + ) + package.targets += [target, testTarget].compactMap { $0 } } } diff --git a/Package.swift b/Package.swift index 321338a9b37..0e816b50ce4 100644 --- a/Package.swift +++ b/Package.swift @@ -191,11 +191,13 @@ func addProtocolTests() { let name: String let sourcePath: String let testPath: String? + let buildOnly: Bool - init(name: String, sourcePath: String, testPath: String? = nil) { + init(name: String, sourcePath: String, testPath: String? = nil, buildOnly: Bool = false) { self.name = name self.sourcePath = sourcePath self.testPath = testPath + self.buildOnly = buildOnly } } @@ -217,21 +219,22 @@ func addProtocolTests() { .init(name: "S3TestSDK", sourcePath: "\(baseDir)/s3"), .init(name: "rest_json_extras", sourcePath: "\(baseDirLocal)/rest_json_extras"), .init(name: "AwsQueryExtras", sourcePath: "\(baseDirLocal)/AwsQueryExtras"), + .init(name: "EventStream", sourcePath: "\(baseDirLocal)/EventStream", buildOnly: true), + .init(name: "RPCEventStream", sourcePath: "\(baseDirLocal)/RPCEventStream", buildOnly: true), .init(name: "Waiters", sourcePath: "\(baseDirLocal)/Waiters", testPath: "codegen/protocol-test-codegen-local/Tests"), ] for protocolTest in protocolTests { - package.targets += [ - .target( - name: protocolTest.name, - dependencies: [.clientRuntime, .awsClientRuntime], - path: "\(protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)" - ), - .testTarget( - name: "\(protocolTest.name)Tests", - dependencies: [.smithyTestUtils, .byNameItem(name: protocolTest.name, condition: nil)], - path: "\(protocolTest.testPath ?? protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)Tests" - ) - ] + let target = Target.target( + name: protocolTest.name, + dependencies: [.clientRuntime, .awsClientRuntime], + path: "\(protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)" + ) + let testTarget = protocolTest.buildOnly ? nil : Target.testTarget( + name: "\(protocolTest.name)Tests", + dependencies: [.smithyTestUtils, .byNameItem(name: protocolTest.name, condition: nil)], + path: "\(protocolTest.testPath ?? protocolTest.sourcePath)/swift-codegen/\(protocolTest.name)Tests" + ) + package.targets += [target, testTarget].compactMap { $0 } } } diff --git a/codegen/protocol-test-codegen-local/build.gradle.kts b/codegen/protocol-test-codegen-local/build.gradle.kts index f0a2c58603d..9a34ecaf28c 100644 --- a/codegen/protocol-test-codegen-local/build.gradle.kts +++ b/codegen/protocol-test-codegen-local/build.gradle.kts @@ -41,8 +41,12 @@ val codegenTests = listOf( "Waiters" ), CodegenTest( - "aws.protocoltests.restjson#TestService", + "aws.protocoltests.eventstream#TestService", "EventStream" + ), + CodegenTest( + "aws.protocoltests.eventstream#RPCTestService", + "RPCEventStream" ) ) diff --git a/codegen/protocol-test-codegen-local/model/eventstream-rpc.smithy b/codegen/protocol-test-codegen-local/model/eventstream-rpc.smithy new file mode 100644 index 00000000000..f0dcfb4e0bb --- /dev/null +++ b/codegen/protocol-test-codegen-local/model/eventstream-rpc.smithy @@ -0,0 +1,83 @@ +namespace aws.protocoltests.eventstream + +use aws.protocols#awsJson1_1 +use aws.api#service +use aws.auth#sigv4 + +@awsJson1_1 +@sigv4(name: "rpc-event-stream-test") +@service(sdkId: "RPCEventStreamTest") +service RPCTestService { version: "123", operations: [TestStreamOp] } + +@http(method: "POST", uri: "/test") +operation TestStreamOp { + input: TestStreamInputOutput, + output: TestStreamInputOutput, + errors: [SomeError], +} + +structure TestStreamInputOutput { + @httpPayload + @required + value: TestStream +} + +@error("client") +structure SomeError { + Message: String, +} + +union TestUnion { + Foo: String, + Bar: Integer, +} + +structure TestStruct { + someString: String, + someInt: Integer, +} + +structure MessageWithBlob { @eventPayload data: Blob } + +structure MessageWithString { @eventPayload data: String } + +structure MessageWithStruct { @eventPayload someStruct: TestStruct } + +structure MessageWithUnion { @eventPayload someUnion: TestUnion } + +structure MessageWithHeaders { + @eventHeader blob: Blob, + @eventHeader boolean: Boolean, + @eventHeader byte: Byte, + @eventHeader int: Integer, + @eventHeader long: Long, + @eventHeader short: Short, + @eventHeader string: String, + @eventHeader timestamp: Timestamp, +} +structure MessageWithHeaderAndPayload { + @eventHeader header: String, + @eventPayload payload: Blob, +} +structure MessageWithNoHeaderPayloadTraits { + someInt: Integer, + someString: String, +} + +structure MessageWithUnboundPayloadTraits { + @eventHeader header: String, + unboundString: String, +} + +@streaming +union TestStream { + MessageWithBlob: MessageWithBlob, + MessageWithString: MessageWithString, + MessageWithStruct: MessageWithStruct, + MessageWithUnion: MessageWithUnion, + MessageWithHeaders: MessageWithHeaders, + MessageWithHeaderAndPayload: MessageWithHeaderAndPayload, + MessageWithNoHeaderPayloadTraits: MessageWithNoHeaderPayloadTraits, + MessageWithUnboundPayloadTraits: MessageWithUnboundPayloadTraits, + SomeError: SomeError, +} diff --git a/codegen/protocol-test-codegen-local/model/eventstream.smithy b/codegen/protocol-test-codegen-local/model/eventstream.smithy index 7f467fe64a2..8a68e5d884f 100644 --- a/codegen/protocol-test-codegen-local/model/eventstream.smithy +++ b/codegen/protocol-test-codegen-local/model/eventstream.smithy @@ -1,4 +1,4 @@ -namespace aws.protocoltests.restjson +namespace aws.protocoltests.eventstream use aws.protocols#restJson1 use aws.api#service diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt index 961a1ee2ed0..75328fa3794 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageMarshallableGenerator.kt @@ -3,7 +3,6 @@ package software.amazon.smithy.aws.swift.codegen.message import software.amazon.smithy.codegen.core.CodegenException import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.MemberShape -import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.shapes.ShapeType import software.amazon.smithy.model.shapes.UnionShape import software.amazon.smithy.model.traits.EventHeaderTrait @@ -14,6 +13,7 @@ import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.serde.readwrite.NodeInfoUtils import software.amazon.smithy.swift.codegen.integration.serde.readwrite.WritingClosureUtils +import software.amazon.smithy.swift.codegen.integration.serde.readwrite.requestWireProtocol import software.amazon.smithy.swift.codegen.integration.serde.readwrite.responseWireProtocol import software.amazon.smithy.swift.codegen.integration.serde.struct.writerSymbol import software.amazon.smithy.swift.codegen.model.eventStreamEvents @@ -70,7 +70,19 @@ class MessageMarshallableGenerator( eventPayloadBinding != null -> renderSerializeEventPayload(ctx, eventPayloadBinding, writer) unbound.isNotEmpty() -> { writer.addStringHeader(":content-type", payloadContentType) - renderPayloadSerialization(ctx, writer, variant) + writer.addImport(ctx.service.writerSymbol.namespace) + val nodeInfo = NodeInfoUtils(ctx, writer, ctx.service.requestWireProtocol).nodeInfo(member, true) + writer.write("let writer = \$N(nodeInfo: \$L)", ctx.service.writerSymbol, nodeInfo) + unbound.forEach { + val writingClosure = WritingClosureUtils(ctx, writer).writingClosure(ctx.model.expectShape(it.target)) + writer.write( + "try writer[\$S].write(value.\$L, with: \$L)", + it.memberName, + ctx.symbolProvider.toMemberName(it), + writingClosure, + ) + } + writer.write("payload = try writer.data()") } } writer.dedent() @@ -108,7 +120,7 @@ class MessageMarshallableGenerator( } ShapeType.STRUCTURE, ShapeType.UNION -> { writer.addStringHeader(":content-type", payloadContentType) - renderPayloadSerialization(ctx, writer, target) + renderPayloadSerialization(ctx, writer, member) } else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") } @@ -175,14 +187,16 @@ class MessageMarshallableGenerator( write("headers.append(.init(name: \$S, value: .string(\$S)))", name, value) } - private fun renderPayloadSerialization(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter, shape: Shape) { + private fun renderPayloadSerialization(ctx: ProtocolGenerator.GenerationContext, writer: SwiftWriter, memberShape: MemberShape) { // get a payload serializer for the given members of the variant val nodeInfoUtils = NodeInfoUtils(ctx, writer, ctx.service.responseWireProtocol) - val rootNodeInfo = nodeInfoUtils.nodeInfo(shape) - val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(shape) + val rootNodeInfo = nodeInfoUtils.nodeInfo(memberShape, true) + val valueWritingClosure = WritingClosureUtils(ctx, writer).writingClosure(memberShape) + writer.addImport(ctx.service.writerSymbol.namespace) writer.write( - "payload = try \$N.write(value, rootNodeInfo: \$L, with: \$L)", + "payload = try \$N.write(value.\$L, rootNodeInfo: \$L, with: \$L)", ctx.service.writerSymbol, + ctx.symbolProvider.toMemberName(memberShape), rootNodeInfo, valueWritingClosure, ) diff --git a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt index 260b6e68e28..9026ecc15de 100644 --- a/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt +++ b/codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/message/MessageUnmarshallableGenerator.kt @@ -73,7 +73,7 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex writer.indent { writer.write("switch params.exceptionType {") streamShape.eventStreamErrors(ctx.model).forEach { member -> - writer.write("case \"${member.memberName}\":") + writer.write("case \$S:", member.memberName) writer.indent { renderReadToValue(writer, member) writer.write("return value") @@ -170,7 +170,7 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex // and then assign each deserialized payload member to the current builder instance unbound.forEach { renderReadToValue(writer, it) - writer.write("event.\$L = value", memberName) + writer.write("event.\$L = value", ctx.symbolProvider.toMemberName(it)) } } } @@ -190,13 +190,14 @@ class MessageUnmarshallableGenerator(val ctx: ProtocolGenerator.GenerationContex ShapeType.STRING -> writer.write("event.\$L = String(data: message.payload, encoding: .utf8)", memberName) ShapeType.STRUCTURE, ShapeType.UNION -> { renderReadToValue(writer, member) - writer.write("event.\$L = value", memberName) + writer.write("event.\$L = value", ctx.symbolProvider.toMemberName(member)) } else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member") } } private fun renderReadToValue(writer: SwiftWriter, memberShape: MemberShape) { + writer.addImport(ctx.service.readerSymbol.namespace) val readingClosure = ReadingClosureUtils(ctx, writer).readingClosure(memberShape) writer.write( "let value = try \$N.readFrom(message.payload, with: \$L)", diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt index 72a09dff145..236a6e89d14 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt @@ -29,11 +29,11 @@ extension EventStreamTestClientTypes.TestStream { case .messagewithstruct(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithStruct"))) headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "TestStruct", with: EventStreamTestClientTypes.TestStruct.write(value:to:)) + payload = try SmithyJSON.Writer.write(value.someStruct, rootNodeInfo: "", with: EventStreamTestClientTypes.TestStruct.write(value:to:)) case .messagewithunion(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithUnion"))) headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "TestUnion", with: EventStreamTestClientTypes.TestUnion.write(value:to:)) + payload = try SmithyJSON.Writer.write(value.someUnion, rootNodeInfo: "", with: EventStreamTestClientTypes.TestUnion.write(value:to:)) case .messagewithheaders(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithHeaders"))) if let headerValue = value.blob { @@ -70,14 +70,19 @@ extension EventStreamTestClientTypes.TestStream { case .messagewithnoheaderpayloadtraits(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithNoHeaderPayloadTraits"))) headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "MessageWithNoHeaderPayloadTraits", with: EventStreamTestClientTypes.MessageWithNoHeaderPayloadTraits.write(value:to:)) + let writer = SmithyJSON.Writer(nodeInfo: "") + try writer["someInt"].write(value.someInt, with: Swift.Int.write(value:to:)) + try writer["someString"].write(value.someString, with: Swift.String.write(value:to:)) + payload = try writer.data() case .messagewithunboundpayloadtraits(let value): headers.append(.init(name: ":event-type", value: .string("MessageWithUnboundPayloadTraits"))) if let headerValue = value.header { headers.append(.init(name: "header", value: .string(headerValue))) } headers.append(.init(name: ":content-type", value: .string("application/json"))) - payload = try SmithyJSON.Writer.write(value, rootNodeInfo: "MessageWithUnboundPayloadTraits", with: EventStreamTestClientTypes.MessageWithUnboundPayloadTraits.write(value:to:)) + let writer = SmithyJSON.Writer(nodeInfo: "") + try writer["unboundString"].write(value.unboundString, with: Swift.String.write(value:to:)) + payload = try writer.data() case .sdkUnknown(_): throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } @@ -161,7 +166,7 @@ extension EventStreamTestClientTypes.TestStream { event.header = value } let value = try SmithyJSON.Reader.readFrom(message.payload, with: Swift.String.read(from:)) - event.messagewithunboundpayloadtraits = value + event.unboundString = value return .messagewithunboundpayloadtraits(event) default: return .sdkUnknown("error processing event stream, unrecognized event: \(params.eventType)") diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index 50929ccf731..718306fc2ec 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -54,7 +54,7 @@ extension InitialRequestTestClientTypes.TestStream { ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - let initialRequestMessage = try input.makeInitialRequestMessage(encoder: encoder) + let initialRequestMessage = try input.makeInitialRequestMessage() operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: InitialRequestTestClientTypes.TestStream.marshal, initialRequestMessage: initialRequestMessage)) """ contents.shouldContainOnlyOnce(expectedContents) @@ -97,9 +97,9 @@ extension EventStreamOpInput { contents.shouldSyntacticSanityCheck() val expectedContents = """ extension EventStreamOpInput { - func makeInitialRequestMessage(encoder: ClientRuntime.RequestEncoder) throws -> EventStream.Message { + func makeInitialRequestMessage() throws -> EventStream.Message { let writer = SmithyJSON.Writer(nodeInfo: "") - try writer.write(self, writingClosure: EventStreamOpInput.write(value:to:)) + try writer.write(self, with: EventStreamOpInput.write(value:to:)) let initialRequestPayload = try writer.data() let initialRequestMessage = EventStream.Message( headers: [ diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt index 9b820785fd4..f39db563bab 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSRestXMLEventStreamTests.kt @@ -54,7 +54,7 @@ extension EventStreamTestClientTypes.TestEvents { headers.append(.init(name: "exampleHeader", value: .string(headerValue))) } headers.append(.init(name: ":content-type", value: .string("application/xml"))) - payload = try SmithyXML.Writer.write(value, rootNodeInfo: "Audio", with: EventStreamTestClientTypes.Audio.write(value:to:)) + payload = try SmithyXML.Writer.write(value.audio, rootNodeInfo: "Audio", with: EventStreamTestClientTypes.Audio.write(value:to:)) case .sdkUnknown(_): throw ClientRuntime.ClientError.unknownError("cannot serialize the unknown event type!") } diff --git a/scripts/protogen.sh b/scripts/protogen.sh index b3d8a651046..b00abc221cf 100755 --- a/scripts/protogen.sh +++ b/scripts/protogen.sh @@ -41,6 +41,7 @@ rm codegen/protocol-test-codegen/build/smithyprojections/protocol-test-codegen/s rm codegen/protocol-test-codegen-local/build/smithyprojections/protocol-test-codegen-local/rest_json_extras/swift-codegen/Package.swift rm codegen/protocol-test-codegen-local/build/smithyprojections/protocol-test-codegen-local/AwsQueryExtras/swift-codegen/Package.swift rm codegen/protocol-test-codegen-local/build/smithyprojections/protocol-test-codegen-local/EventStream/swift-codegen/Package.swift +rm codegen/protocol-test-codegen-local/build/smithyprojections/protocol-test-codegen-local/RPCEventStream/swift-codegen/Package.swift rm codegen/protocol-test-codegen-local/build/smithyprojections/protocol-test-codegen-local/Waiters/swift-codegen/Package.swift # Regenerate the Package.swift with protocol tests included and services excluded From 82d1da27a52fceb1cac20db46f9ce7bfcf5fce4e Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Thu, 9 May 2024 20:16:42 -0500 Subject: [PATCH 26/27] Fix codegen tests --- .../aws/swift/codegen/EventStreamTests.kt | 11 +----- .../swift/codegen/PresignerGeneratorTests.kt | 38 ++----------------- .../awsjson/AWSJsonHttpInitialRequestTests.kt | 3 +- .../awsquery/AWSQueryOperationStackTest.kt | 5 --- .../FlexibleChecksumMiddlewareTests.kt | 15 -------- 5 files changed, 5 insertions(+), 67 deletions(-) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt index 1ddf601fb1f..2e02bdd0735 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/EventStreamTests.kt @@ -229,21 +229,12 @@ extension EventStreamTestClientTypes.TestStream { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) -<<<<<<< HEAD operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.value, defaultBody: "{}", marshalClosure: EventStreamTestClientTypes.TestStream.marshal)) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) - operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(TestStreamOpOutput.httpOutput(from:), TestStreamOpOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) -======= - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.value, defaultBody: "{}", marshalClosure: jsonMarshalClosure(requestEncoder: encoder))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(TestStreamOpOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(TestStreamOpOutput.httpOutput(from:), TestStreamOpOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) ->>>>>>> origin/main let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt index b9032c01522..07662d7b95b 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/PresignerGeneratorTests.kt @@ -44,13 +44,8 @@ extension GetFooInput { operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) -<<<<<<< HEAD operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(GetFooOutput.httpOutput(from:), GetFooOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) -======= - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(GetFooOutputError.self, decoder: decoder))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) ->>>>>>> origin/main let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: GetFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { return nil @@ -98,21 +93,12 @@ extension PostFooInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) -<<<<<<< HEAD operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "", inputWritingClosure: PostFooInput.write(value:to:))) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) - operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PostFooOutput.httpOutput(from:), PostFooOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) -======= - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder), inputWritingClosure: JSONReadWrite.writingClosure())) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(PostFooOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PostFooOutput.httpOutput(from:), PostFooOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) ->>>>>>> origin/main let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PostFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { return nil @@ -160,21 +146,12 @@ extension PutFooInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) -<<<<<<< HEAD operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "", inputWritingClosure: PutFooInput.write(value:to:))) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) - operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PutFooOutput.httpOutput(from:), PutFooOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) -======= - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: ClientRuntime.JSONReadWrite.documentWritingClosure(encoder: encoder), inputWritingClosure: JSONReadWrite.writingClosure())) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(PutFooOutputError.self, decoder: decoder))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PutFooOutput.httpOutput(from:), PutFooOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) ->>>>>>> origin/main let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PutFooOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { return nil @@ -223,21 +200,12 @@ extension PutObjectInput { operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware()) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware(contentType: "application/json")) -<<<<<<< HEAD operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(rootNodeInfo: "PutObjectInput", inputWritingClosure: PutObjectInput.write(value:to:))) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) - operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) - operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PutObjectOutput.httpOutput(from:), PutObjectOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) -======= - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BodyMiddleware(documentWritingClosure: SmithyXML.XMLReadWrite.documentWritingClosure(rootNodeInfo: "PutObjectInput"), inputWritingClosure: PutObjectInput.writingClosure(_:to:))) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(PutObjectOutput.httpBinding, responseDocumentBinding), responseErrorClosure(PutObjectOutputError.httpBinding, responseDocumentBinding))) + operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(PutObjectOutput.httpOutput(from:), PutObjectOutputError.httpError(from:))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) ->>>>>>> origin/main let presignedRequestBuilder = try await operation.presignedRequest(context: context, input: input, output: PutObjectOutput(), next: ClientRuntime.NoopHandler()) guard let builtRequest = presignedRequestBuilder?.build() else { return nil diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index 718306fc2ec..e3433fe7630 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -54,8 +54,7 @@ extension InitialRequestTestClientTypes.TestStream { ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - let initialRequestMessage = try input.makeInitialRequestMessage() - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: InitialRequestTestClientTypes.TestStream.marshal, initialRequestMessage: initialRequestMessage)) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: InitialRequestTestClientTypes.TestStream.marshal, initialRequestMessage: try input.makeInitialRequestMessage(encoder: encoder))) """ contents.shouldContainOnlyOnce(expectedContents) } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt index 0abd2de1314..ca1ed2e93c7 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsquery/AWSQueryOperationStackTest.kt @@ -49,13 +49,8 @@ class AWSQueryOperationStackTest { operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) -<<<<<<< HEAD operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(NoInputAndOutputOutput.httpOutput(from:), NoInputAndOutputOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) -======= - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(NoInputAndOutputOutput.httpBinding, responseDocumentBinding), responseErrorClosure(NoInputAndOutputOutputError.httpBinding, responseDocumentBinding))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) ->>>>>>> origin/main let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result } diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt index 31b147cf9ac..3f1114a4b2e 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt @@ -16,13 +16,6 @@ class FlexibleChecksumMiddlewareTests { val contents = TestUtils.getFileContents(context.manifest, "/Example/ChecksumTestsClient.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ -extension ChecksumTestsClient { - /// Performs the `SomeOperation` operation on the `ChecksumTests` service. - /// - /// - /// - Parameter SomeOperationInput : [no documentation found] - /// - /// - Returns: `SomeOperationOutput` : [no documentation found] public func someOperation(input: SomeOperationInput) async throws -> SomeOperationOutput { let context = ClientRuntime.HttpContextBuilder() .withMethod(value: .post) @@ -54,20 +47,12 @@ extension ChecksumTestsClient { operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware()) -<<<<<<< HEAD operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(SomeOperationOutput.httpOutput(from:), SomeOperationOutputError.httpError(from:))) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.FlexibleChecksumsResponseMiddleware(validationMode: true)) -======= - operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware(responseClosure(decoder: decoder), responseErrorClosure(SomeOperationOutputError.self, decoder: decoder))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware(clientLogMode: config.clientLogMode)) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.FlexibleChecksumsResponseMiddleware(validationMode: true)) ->>>>>>> origin/main let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result } - -} """ contents.shouldContainOnlyOnce(expectedContents) } From 6de7ab7b01970348b595aba9e3da589927dbda6e Mon Sep 17 00:00:00 2001 From: Josh Elkins Date: Thu, 9 May 2024 20:39:33 -0500 Subject: [PATCH 27/27] Fix initial event codegen test --- .../aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt index e3433fe7630..5676d20be08 100644 --- a/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt +++ b/codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/awsjson/AWSJsonHttpInitialRequestTests.kt @@ -54,7 +54,7 @@ extension InitialRequestTestClientTypes.TestStream { ) contents.shouldSyntacticSanityCheck() val expectedContents = """ - operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: InitialRequestTestClientTypes.TestStream.marshal, initialRequestMessage: try input.makeInitialRequestMessage(encoder: encoder))) + operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.EventStreamBodyMiddleware(keyPath: \.eventStream, defaultBody: "{}", marshalClosure: InitialRequestTestClientTypes.TestStream.marshal, initialRequestMessage: try input.makeInitialRequestMessage())) """ contents.shouldContainOnlyOnce(expectedContents) }