Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions packages/smithy-aws-core/src/smithy_aws_core/protocols/restjson.py
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
41 changes: 41 additions & 0 deletions packages/smithy-aws-core/src/smithy_aws_core/traits.py
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
)

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)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have validators to validate this kind of constraint model-side, but this would be good time to discuss whether we do any kind of validation in our trait definitions here. Thoughts?

113 changes: 113 additions & 0 deletions packages/smithy-core/src/smithy_core/protocols.py
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:
"""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
endpoint_trait=operation.schema.get_trait(EndpointTrait),
)

input.serialize(serializer=serializer)
request = serializer.result

if request is None:
raise ValueError("Request is None") # TODO

request.fields["content-type"].add(self.content_type)
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())

# 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)
Loading