generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 24
Add http and restjson1 client protocols #448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 |
27 changes: 27 additions & 0 deletions
27
packages/smithy-aws-core/src/smithy_aws_core/aio/protocols.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| from typing import Final | ||
|
|
||
| from smithy_aws_core.traits import RestJson1Trait | ||
| from smithy_http.aio.protocols import HttpBindingClientProtocol | ||
| from smithy_core.codecs import Codec | ||
| from smithy_core.shapes import ShapeID | ||
| from smithy_json import JSONCodec | ||
|
|
||
|
|
||
| class RestJsonClientProtocol(HttpBindingClientProtocol): | ||
| """An implementation of the aws.protocols#restJson1 protocol.""" | ||
|
|
||
| _id: ShapeID = RestJson1Trait.id | ||
| _codec: JSONCodec = JSONCodec() | ||
| _contentType: Final = "application/json" | ||
|
|
||
| @property | ||
| def id(self) -> ShapeID: | ||
| return self._id | ||
|
|
||
| @property | ||
| def payload_codec(self) -> Codec: | ||
| return self._codec | ||
|
|
||
| @property | ||
| def content_type(self) -> str: | ||
| return self._contentType |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| # This ruff check warns against using the assert statement, which can be stripped out | ||
| # when running Python with certain (common) optimization settings. Assert is used here | ||
| # for trait values. Since these are always generated, we can be fairly confident that | ||
| # they're correct regardless, so it's okay if the checks are stripped out. | ||
| # ruff: noqa: S101 | ||
|
|
||
| from dataclasses import dataclass, field | ||
| from typing import Mapping, Sequence | ||
|
|
||
| from smithy_core.shapes import ShapeID | ||
| from smithy_core.traits import Trait, DocumentValue, DynamicTrait | ||
|
|
||
|
|
||
| @dataclass(init=False, frozen=True) | ||
| class RestJson1Trait(Trait, id=ShapeID("aws.protocols#restJson1")): | ||
| http: Sequence[str] = field( | ||
| repr=False, hash=False, compare=False, default_factory=tuple | ||
| ) | ||
| event_stream_http: Sequence[str] = field( | ||
| repr=False, hash=False, compare=False, default_factory=tuple | ||
| ) | ||
|
|
||
| def __init__(self, value: DocumentValue | DynamicTrait = None): | ||
| super().__init__(value) | ||
| assert isinstance(self.document_value, Mapping) | ||
|
|
||
| http_versions = self.document_value["http"] | ||
| assert isinstance(http_versions, Sequence) | ||
| for val in http_versions: | ||
| assert isinstance(val, str) | ||
| object.__setattr__(self, "http", tuple(http_versions)) | ||
| event_stream_http_versions = self.document_value.get("eventStreamHttp") | ||
| if not event_stream_http_versions: | ||
| object.__setattr__(self, "event_stream_http", self.http) | ||
| else: | ||
| assert isinstance(event_stream_http_versions, Sequence) | ||
| for val in event_stream_http_versions: | ||
| assert isinstance(val, str) | ||
| object.__setattr__( | ||
| self, "event_stream_http", tuple(event_stream_http_versions) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| import os | ||
| from inspect import iscoroutinefunction | ||
| from io import BytesIO | ||
|
|
||
| from smithy_core.aio.interfaces import ClientProtocol | ||
| from smithy_core.codecs import Codec | ||
| from smithy_core.deserializers import DeserializeableShape | ||
| from smithy_core.documents import TypeRegistry | ||
| from smithy_core.exceptions import ExpectationNotMetException | ||
| from smithy_core.interfaces import Endpoint, TypedProperties, URI | ||
| from smithy_core.schemas import APIOperation | ||
| from smithy_core.serializers import SerializeableShape | ||
| from smithy_core.traits import HTTPTrait, EndpointTrait | ||
| from smithy_http.aio.interfaces import HTTPRequest, HTTPResponse | ||
| from smithy_http.deserializers import HTTPResponseDeserializer | ||
| from smithy_http.serializers import HTTPRequestSerializer | ||
|
|
||
|
|
||
| class HttpClientProtocol(ClientProtocol[HTTPRequest, HTTPResponse]): | ||
| """An HTTP-based protocol.""" | ||
|
|
||
| def set_service_endpoint( | ||
| self, | ||
| *, | ||
| request: HTTPRequest, | ||
| endpoint: Endpoint, | ||
| ) -> HTTPRequest: | ||
| uri = endpoint.uri | ||
| uri_builder = request.destination | ||
|
|
||
| if uri.scheme: | ||
| uri_builder.scheme = uri.scheme | ||
| if uri.host: | ||
| uri_builder.host = uri.host | ||
| if uri.port and uri.port > -1: | ||
| uri_builder.port = uri.port | ||
| if uri.path: | ||
| uri_builder.path = os.path.join(uri.path, uri_builder.path or "") | ||
| # TODO: merge headers from the endpoint properties bag | ||
| return request | ||
|
|
||
|
|
||
| class HttpBindingClientProtocol(HttpClientProtocol): | ||
| """An HTTP-based protocol that uses HTTP binding traits.""" | ||
|
|
||
| @property | ||
| def payload_codec(self) -> Codec: | ||
| """The codec used for the serde of input and output payloads.""" | ||
| ... | ||
|
|
||
| @property | ||
| def content_type(self) -> str: | ||
| """The media type of the http payload.""" | ||
| ... | ||
|
|
||
| def serialize_request[ | ||
| OperationInput: "SerializeableShape", | ||
| OperationOutput: "DeserializeableShape", | ||
| ]( | ||
| self, | ||
| *, | ||
| operation: APIOperation[OperationInput, OperationOutput], | ||
| input: OperationInput, | ||
| endpoint: URI, | ||
| context: TypedProperties, | ||
| ) -> HTTPRequest: | ||
| # TODO(optimization): request binding cache like done in SJ | ||
| serializer = HTTPRequestSerializer( | ||
| payload_codec=self.payload_codec, | ||
| http_trait=operation.schema.expect_trait(HTTPTrait), | ||
| endpoint_trait=operation.schema.get_trait(EndpointTrait), | ||
| ) | ||
|
|
||
| input.serialize(serializer=serializer) | ||
| request = serializer.result | ||
|
|
||
| if request is None: | ||
| raise ExpectationNotMetException( | ||
| "Expected request to be serialized, but was None" | ||
| ) | ||
|
|
||
| return request | ||
|
|
||
| async def deserialize_response[ | ||
| OperationInput: "SerializeableShape", | ||
| OperationOutput: "DeserializeableShape", | ||
| ]( | ||
| self, | ||
| *, | ||
| operation: APIOperation[OperationInput, OperationOutput], | ||
| request: HTTPRequest, | ||
| response: HTTPResponse, | ||
| error_registry: TypeRegistry, | ||
| context: TypedProperties, | ||
| ) -> OperationOutput: | ||
| if not (200 <= response.status <= 299): | ||
| # TODO: implement error serde from type registry | ||
| raise NotImplementedError | ||
|
|
||
| body = response.body | ||
|
|
||
| # if body is not streaming and is async, we have to buffer it | ||
| if not operation.output_stream_member: | ||
| if ( | ||
| read := getattr(body, "read", None) | ||
| ) is not None and iscoroutinefunction(read): | ||
| body = BytesIO(await read()) | ||
|
|
||
| # TODO(optimization): response binding cache like done in SJ | ||
| deserializer = HTTPResponseDeserializer( | ||
| payload_codec=self.payload_codec, | ||
| http_trait=operation.schema.expect_trait(HTTPTrait), | ||
| response=response, | ||
| body=body, # type: ignore | ||
| ) | ||
|
|
||
| return operation.output.deserialize(deserializer) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It'll be under
headersin the properties bag. Not necessary right now though.