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 1 commit
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
27 changes: 27 additions & 0 deletions
27
packages/smithy-aws-core/src/smithy_aws_core/protocols/restjson.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 Literal | ||
|
|
||
| from smithy_aws_core.traits import RestJson1Trait | ||
| from smithy_core.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: Literal["application/json"] = "application/json" | ||
|
|
||
| @property | ||
| def id(self) -> ShapeID: | ||
| return self._id | ||
|
|
||
| @property | ||
| def 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,41 @@ | ||
| # 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: set[str] = field(repr=False, hash=False, compare=False, default_factory=set) | ||
| eventStreamHttp: set[str] = field( | ||
| repr=False, hash=False, compare=False, default_factory=set | ||
| ) | ||
haydenbaker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def __init__(self, value: DocumentValue | DynamicTrait = None): | ||
| super().__init__(value) | ||
| assert isinstance(self.document_value, Mapping) | ||
|
|
||
| assert isinstance(self.document_value["http"], Sequence) | ||
| for val in self.document_value["http"]: | ||
| assert isinstance(val, str) | ||
| self.http.add(val) | ||
|
|
||
| if vals := self.document_value.get("eventStreamHttp") is None: | ||
| object.__setattr__(self, "eventStreamHttp", self.http) | ||
| else: | ||
| # check that eventStreamHttp is a subset of http | ||
| assert isinstance(vals, Sequence) | ||
| for val in self.document_value["eventStreamHttp"]: | ||
| assert val in self.http | ||
| assert isinstance(val, str) | ||
| self.eventStreamHttp.add(val) | ||
|
||
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,113 @@ | ||
| 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.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 codec(self) -> Codec: | ||
haydenbaker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """The codec used for the serde of input and output shapes.""" | ||
| ... | ||
|
|
||
| @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: request binding cache like done in SJ | ||
| serializer = HTTPRequestSerializer( | ||
| payload_codec=self.codec, | ||
| http_trait=operation.schema.expect_trait(HTTPTrait), # TODO | ||
haydenbaker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| endpoint_trait=operation.schema.get_trait(EndpointTrait), | ||
| ) | ||
|
|
||
| input.serialize(serializer=serializer) | ||
| request = serializer.result | ||
|
|
||
| if request is None: | ||
| raise ValueError("Request is None") # TODO | ||
haydenbaker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| request.fields["content-type"].add(self.content_type) | ||
haydenbaker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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: extract to utility | ||
| # TODO: implement error serde from type registry | ||
| raise NotImplementedError | ||
|
|
||
| body = response.body | ||
| # TODO: extract to utility, seems common | ||
| if (read := getattr(body, "read", None)) is not None and iscoroutinefunction( | ||
| read | ||
| ): | ||
| body = BytesIO(await read()) | ||
haydenbaker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # TODO: response binding cache like done in SJ | ||
| deserializer = HTTPResponseDeserializer( | ||
| payload_codec=self.codec, | ||
| http_trait=operation.schema.expect_trait(HTTPTrait), | ||
| response=response, | ||
| body=body, # type: ignore | ||
| ) | ||
|
|
||
| return operation.output.deserialize(deserializer) | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.