Skip to content
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

Improve flexibility of handlers #2858

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@ class ServerOperationGenerator(

impl #{SmithyHttpServer}::operation::OperationShape for $operationName {
const ID: #{SmithyHttpServer}::shape_id::ShapeId = #{SmithyHttpServer}::shape_id::ShapeId::new(${operationIdAbsolute.dq()}, ${operationId.namespace.dq()}, ${operationId.name.dq()});

type Input = crate::input::${operationName}Input;
type Output = crate::output::${operationName}Output;
type Error = #{Error:W};
}

impl #{SmithyHttpServer}::instrumentation::sensitivity::Sensitivity for $operationName {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class ServerServiceGenerator(
private val codegenScope =
arrayOf(
"Bytes" to RuntimeType.Bytes,
"FuturesUtil" to ServerCargoDependency.FuturesUtil.toType(),
"Http" to RuntimeType.Http,
"SmithyHttp" to RuntimeType.smithyHttp(runtimeConfig),
"HttpBody" to RuntimeType.HttpBody,
Expand Down Expand Up @@ -129,19 +130,20 @@ class ServerServiceGenerator(
/// /* Set other handlers */
/// .build()
/// .unwrap();
/// ## let app: $serviceName<#{SmithyHttpServer}::routing::Route<#{SmithyHttp}::body::SdkBody>> = app;
/// ## fn check<S: #{Tower}::Service<#{Http}::Request<#{SmithyHttp}::body::SdkBody>>>(_: S) {}
/// ## check(app);
/// ```
///
pub fn $fieldName<HandlerType, HandlerExtractors, UpgradeExtractors>(self, handler: HandlerType) -> Self
pub fn $fieldName<Input, HandlerType>(self, handler: HandlerType) -> Self
where
HandlerType: #{SmithyHttpServer}::operation::Handler<crate::operation_shape::$structName, HandlerExtractors>,
HandlerType: #{SmithyHttpServer}::operation::Handler<Input>,

ModelPl: #{SmithyHttpServer}::plugin::Plugin<
$serviceName,
crate::operation_shape::$structName,
#{SmithyHttpServer}::operation::IntoService<crate::operation_shape::$structName, HandlerType>
#{SmithyHttpServer}::operation::FixInput<Input, #{SmithyHttpServer}::operation::IntoService<HandlerType>>
>,
#{SmithyHttpServer}::operation::UpgradePlugin::<UpgradeExtractors>: #{SmithyHttpServer}::plugin::Plugin<
#{SmithyHttpServer}::operation::UpgradePlugin: #{SmithyHttpServer}::plugin::Plugin<
$serviceName,
crate::operation_shape::$structName,
ModelPl::Output
Expand All @@ -150,7 +152,7 @@ class ServerServiceGenerator(
$serviceName,
crate::operation_shape::$structName,
<
#{SmithyHttpServer}::operation::UpgradePlugin::<UpgradeExtractors>
#{SmithyHttpServer}::operation::UpgradePlugin
as #{SmithyHttpServer}::plugin::Plugin<
$serviceName,
crate::operation_shape::$structName,
Expand All @@ -163,13 +165,8 @@ class ServerServiceGenerator(
<HttpPl::Output as #{Tower}::Service<#{Http}::Request<Body>>>::Future: Send + 'static,

{
use #{SmithyHttpServer}::operation::OperationShapeExt;
use #{SmithyHttpServer}::plugin::Plugin;
let svc = crate::operation_shape::$structName::from_handler(handler);
let svc = self.model_plugin.apply(svc);
let svc = #{SmithyHttpServer}::operation::UpgradePlugin::<UpgradeExtractors>::new().apply(svc);
let svc = self.http_plugin.apply(svc);
self.${fieldName}_custom(svc)
let svc = #{SmithyHttpServer}::operation::IntoService::new(handler);
self.${fieldName}_service(svc)
}

/// Sets the [`$structName`](crate::operation_shape::$structName) operation.
Expand All @@ -192,19 +189,18 @@ class ServerServiceGenerator(
/// /* Set other handlers */
/// .build()
/// .unwrap();
/// ## let app: $serviceName<#{SmithyHttpServer}::routing::Route<#{SmithyHttp}::body::SdkBody>> = app;
/// ## fn check<S: #{Tower}::Service<#{Http}::Request<#{SmithyHttp}::body::SdkBody>>>(_: S) {}
/// ## check(app);
/// ```
///
pub fn ${fieldName}_service<S, ServiceExtractors, UpgradeExtractors>(self, service: S) -> Self
pub fn ${fieldName}_service<Input, S>(self, service: S) -> Self
where
S: #{SmithyHttpServer}::operation::OperationService<crate::operation_shape::$structName, ServiceExtractors>,

ModelPl: #{SmithyHttpServer}::plugin::Plugin<
$serviceName,
crate::operation_shape::$structName,
#{SmithyHttpServer}::operation::Normalize<crate::operation_shape::$structName, S>
#{SmithyHttpServer}::operation::FixInput<Input, S>
>,
#{SmithyHttpServer}::operation::UpgradePlugin::<UpgradeExtractors>: #{SmithyHttpServer}::plugin::Plugin<
#{SmithyHttpServer}::operation::UpgradePlugin: #{SmithyHttpServer}::plugin::Plugin<
$serviceName,
crate::operation_shape::$structName,
ModelPl::Output
Expand All @@ -213,7 +209,7 @@ class ServerServiceGenerator(
$serviceName,
crate::operation_shape::$structName,
<
#{SmithyHttpServer}::operation::UpgradePlugin::<UpgradeExtractors>
#{SmithyHttpServer}::operation::UpgradePlugin
as #{SmithyHttpServer}::plugin::Plugin<
$serviceName,
crate::operation_shape::$structName,
Expand All @@ -226,11 +222,10 @@ class ServerServiceGenerator(
<HttpPl::Output as #{Tower}::Service<#{Http}::Request<Body>>>::Future: Send + 'static,

{
use #{SmithyHttpServer}::operation::OperationShapeExt;
use #{SmithyHttpServer}::plugin::Plugin;
let svc = crate::operation_shape::$structName::from_service(service);
let svc = #{SmithyHttpServer}::operation::FixInput::new(service);
let svc = self.model_plugin.apply(svc);
let svc = #{SmithyHttpServer}::operation::UpgradePlugin::<UpgradeExtractors>::new().apply(svc);
let svc = #{SmithyHttpServer}::operation::UpgradePlugin::new().apply(svc);
let svc = self.http_plugin.apply(svc);
self.${fieldName}_custom(svc)
}
Expand Down Expand Up @@ -295,7 +290,13 @@ class ServerServiceGenerator(
///
/// Check out [`$builderName::build_unchecked`] if you'd prefer the service to return status code 500 when an
/// unspecified route requested.
pub fn build(self) -> Result<$serviceName<#{SmithyHttpServer}::routing::Route<$builderBodyGenericTypeName>>, MissingOperationsError>
pub fn build(self) -> Result<$serviceName<
#{SmithyHttpServer}::routing::RoutingService<
#{Router} <
#{SmithyHttpServer}::routing::Route<$builderBodyGenericTypeName>
>
>
>, MissingOperationsError>
{
let router = {
use #{SmithyHttpServer}::operation::OperationShape;
Expand All @@ -313,7 +314,7 @@ class ServerServiceGenerator(
#{Router}::from_iter([#{RoutesArrayElements:W}])
};
Ok($serviceName {
router: #{SmithyHttpServer}::routing::RoutingService::new(router),
inner: #{SmithyHttpServer}::routing::RoutingService::new(router),
})
}
""",
Expand Down Expand Up @@ -359,7 +360,7 @@ class ServerServiceGenerator(
(
$requestSpecsModuleName::$specBuilderFunctionName(),
self.$fieldName.unwrap_or_else(|| {
let svc = #{SmithyHttpServer}::operation::MissingFailure::<#{Protocol}>::default();
let svc = #{SmithyHttpServer}::operation::MissingFailure::<$serviceName, #{Protocol}>::default();
#{SmithyHttpServer}::routing::Route::new(svc)
})
),
Expand All @@ -376,13 +377,19 @@ class ServerServiceGenerator(
///
/// Check out [`$builderName::build`] if you'd prefer the builder to fail if one or more operations do
/// not have a registered handler.
pub fn build_unchecked(self) -> $serviceName<#{SmithyHttpServer}::routing::Route<$builderBodyGenericTypeName>>
pub fn build_unchecked(self) -> $serviceName<
#{SmithyHttpServer}::routing::RoutingService<
#{Router} <
#{SmithyHttpServer}::routing::Route<$builderBodyGenericTypeName>
>
>
>
where
$builderBodyGenericTypeName: Send + 'static
{
let router = #{Router}::from_iter([#{Pairs:W}]);
$serviceName {
router: #{SmithyHttpServer}::routing::RoutingService::new(router),
inner: #{SmithyHttpServer}::routing::RoutingService::new(router),
}
}
""",
Expand Down Expand Up @@ -463,8 +470,8 @@ class ServerServiceGenerator(
///
/// See the [root](crate) documentation for more information.
##[derive(Clone)]
pub struct $serviceName<S = #{SmithyHttpServer}::routing::Route> {
router: #{SmithyHttpServer}::routing::RoutingService<#{Router}<S>, #{Protocol}>,
pub struct $serviceName<S = ()> {
inner: S,
}

impl $serviceName<()> {
Expand Down Expand Up @@ -498,7 +505,6 @@ class ServerServiceGenerator(
#{SmithyHttpServer}::routing::IntoMakeService::new(self)
}


/// Converts [`$serviceName`] into a [`MakeService`](tower::make::MakeService) with [`ConnectInfo`](#{SmithyHttpServer}::request::connect_info::ConnectInfo).
pub fn into_make_service_with_connect_info<C>(self) -> #{SmithyHttpServer}::routing::IntoMakeServiceWithConnectInfo<Self, C> {
#{SmithyHttpServer}::routing::IntoMakeServiceWithConnectInfo::new(self)
Expand All @@ -510,7 +516,7 @@ class ServerServiceGenerator(
L: #{Tower}::Layer<S>
{
$serviceName {
router: self.router.map(|s| s.layer(layer))
inner: layer.layer(self.inner)
}
}

Expand All @@ -530,22 +536,26 @@ class ServerServiceGenerator(
}
}

impl<B, RespB, S> #{Tower}::Service<#{Http}::Request<B>> for $serviceName<S>
impl<B, S> #{Tower}::Service<#{Http}::Request<B>> for $serviceName<S>
where
S: #{Tower}::Service<#{Http}::Request<B>, Response = #{Http}::Response<RespB>> + Clone,
RespB: #{HttpBody}::Body<Data = #{Bytes}> + Send + 'static,
RespB::Error: Into<Box<dyn std::error::Error + Send + Sync>>
S: #{Tower}::Service<
#{Http}::Request<B>,
Response = #{Http}::Response<#{SmithyHttpServer}::body::BoxBody>
> + Clone,
S::Error: #{SmithyHttpServer}::response::IntoResponseUniform<<$serviceName as #{SmithyHttpServer}::service::ServiceShape>::Protocol>
{
type Response = #{Http}::Response<#{SmithyHttpServer}::body::BoxBody>;
type Response = S::Response;
type Error = S::Error;
type Future = #{SmithyHttpServer}::routing::RoutingFuture<S, B>;
type Future = #{FuturesUtil}::future::Map<S::Future, fn(Result<Self::Response, Self::Error>) -> Result<Self::Response, Self::Error>>;

fn poll_ready(&mut self, cx: &mut std::task::Context) -> std::task::Poll<Result<(), Self::Error>> {
self.router.poll_ready(cx)
self.inner.poll_ready(cx)
}

fn call(&mut self, request: #{Http}::Request<B>) -> Self::Future {
self.router.call(request)
use #{FuturesUtil}::FutureExt;
use #{SmithyHttpServer}::response::IntoResponseUniform;
self.inner.call(request).map(|result| match result { Ok(ok) => Ok(ok), Err(err) => Ok(err.into_response()) })
}
}
""",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import software.amazon.smithy.rust.codegen.core.util.hasTrait
import software.amazon.smithy.rust.codegen.core.util.inputShape
import software.amazon.smithy.rust.codegen.core.util.isStreaming
import software.amazon.smithy.rust.codegen.core.util.outputShape
import software.amazon.smithy.rust.codegen.core.util.toPascalCase
import software.amazon.smithy.rust.codegen.server.smithy.ServerCargoDependency
import software.amazon.smithy.rust.codegen.server.smithy.ServerCodegenContext
import software.amazon.smithy.rust.codegen.server.smithy.canReachConstrainedShape
Expand Down Expand Up @@ -157,6 +158,7 @@ class ServerHttpBoundProtocolTraitImplGenerator(
private val runtimeConfig = codegenContext.runtimeConfig
private val httpBindingResolver = protocol.httpBindingResolver
private val protocolFunctions = ProtocolFunctions(codegenContext)
private val serviceName = codegenContext.serviceShape.id.name.toPascalCase()

private val codegenScope = arrayOf(
"AsyncTrait" to ServerCargoDependency.AsyncTrait.toType(),
Expand Down Expand Up @@ -277,7 +279,7 @@ class ServerHttpBoundProtocolTraitImplGenerator(
}
}

impl<B> #{SmithyHttpServer}::request::FromRequest<#{Marker}, B> for #{I}
impl<B> #{SmithyHttpServer}::request::FromRequest<crate::$serviceName, crate::operation_shape::$operationName, B> for #{I}
where
B: #{SmithyHttpServer}::body::HttpBody + Send,
B: 'static,
Expand Down Expand Up @@ -309,7 +311,6 @@ class ServerHttpBoundProtocolTraitImplGenerator(
""",
*codegenScope,
"I" to inputSymbol,
"Marker" to protocol.markerStruct(),
"parse_request" to serverParseRequest(operationShape),
"verifyAcceptHeader" to verifyAcceptHeader,
"verifyAcceptHeaderStaticContentTypeInit" to verifyAcceptHeaderStaticContentTypeInit,
Expand All @@ -323,28 +324,27 @@ class ServerHttpBoundProtocolTraitImplGenerator(
// to let them know.
rustTemplate(
"""
impl #{SmithyHttpServer}::response::IntoResponse<#{Marker}> for #{O} {
impl #{SmithyHttpServer}::response::IntoResponse<crate::$serviceName, crate::operation_shape::$operationName> for #{O} {
fn into_response(self) -> #{SmithyHttpServer}::response::Response {
match #{serialize_response}(self) {
Ok(response) => response,
Err(e) => {
#{Tracing}::error!(error = %e, "failed to serialize response");
#{SmithyHttpServer}::response::IntoResponse::<#{Marker}>::into_response(#{RuntimeError}::from(e))
#{SmithyHttpServer}::response::IntoResponse::<crate::$serviceName, crate::operation_shape::$operationName>::into_response(#{RuntimeError}::from(e))
}
}
}
}
""",
*codegenScope,
"O" to outputSymbol,
"Marker" to protocol.markerStruct(),
"serialize_response" to serverSerializeResponse(operationShape),
)

if (operationShape.operationErrors(model).isNotEmpty()) {
rustTemplate(
"""
impl #{SmithyHttpServer}::response::IntoResponse<#{Marker}> for #{E} {
impl #{SmithyHttpServer}::response::IntoResponse<crate::$serviceName, crate::operation_shape::$operationName> for #{E} {
fn into_response(self) -> #{SmithyHttpServer}::response::Response {
match #{serialize_error}(&self) {
Ok(mut response) => {
Expand All @@ -353,15 +353,14 @@ class ServerHttpBoundProtocolTraitImplGenerator(
},
Err(e) => {
#{Tracing}::error!(error = %e, "failed to serialize response");
#{SmithyHttpServer}::response::IntoResponse::<#{Marker}>::into_response(#{RuntimeError}::from(e))
#{SmithyHttpServer}::response::IntoResponse::<crate::$serviceName, crate::operation_shape::$operationName>::into_response(#{RuntimeError}::from(e))
}
}
}
}
""".trimIndent(),
*codegenScope,
"E" to errorSymbol,
"Marker" to protocol.markerStruct(),
"serialize_error" to serverSerializeError(operationShape),
)
}
Expand Down
10 changes: 5 additions & 5 deletions rust-runtime/aws-smithy-http-server-python/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use aws_smithy_http_server::{
protocol::{
aws_json_10::AwsJson1_0, aws_json_11::AwsJson1_1, rest_json_1::RestJson1, rest_xml::RestXml,
},
response::IntoResponse,
response::IntoResponseUniform,
};
use aws_smithy_types::date_time::{ConversionError, DateTimeParseError};
use pyo3::{create_exception, exceptions::PyException as BasePyException, prelude::*, PyErr};
Expand Down Expand Up @@ -79,7 +79,7 @@ impl From<PyErr> for PyMiddlewareException {
}
}

impl IntoResponse<RestJson1> for PyMiddlewareException {
impl IntoResponseUniform<RestJson1> for PyMiddlewareException {
fn into_response(self) -> http::Response<BoxBody> {
http::Response::builder()
.status(self.status_code)
Expand All @@ -90,7 +90,7 @@ impl IntoResponse<RestJson1> for PyMiddlewareException {
}
}

impl IntoResponse<RestXml> for PyMiddlewareException {
impl IntoResponseUniform<RestXml> for PyMiddlewareException {
fn into_response(self) -> http::Response<BoxBody> {
http::Response::builder()
.status(self.status_code)
Expand All @@ -100,7 +100,7 @@ impl IntoResponse<RestXml> for PyMiddlewareException {
}
}

impl IntoResponse<AwsJson1_0> for PyMiddlewareException {
impl IntoResponseUniform<AwsJson1_0> for PyMiddlewareException {
fn into_response(self) -> http::Response<BoxBody> {
http::Response::builder()
.status(self.status_code)
Expand All @@ -111,7 +111,7 @@ impl IntoResponse<AwsJson1_0> for PyMiddlewareException {
}
}

impl IntoResponse<AwsJson1_1> for PyMiddlewareException {
impl IntoResponseUniform<AwsJson1_1> for PyMiddlewareException {
fn into_response(self) -> http::Response<BoxBody> {
http::Response::builder()
.status(self.status_code)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::{

use aws_smithy_http_server::{
body::{Body, BoxBody},
response::IntoResponse,
response::IntoResponseUniform,
};
use futures::{future::BoxFuture, TryFutureExt};
use http::{Request, Response};
Expand Down Expand Up @@ -47,7 +47,7 @@ impl<P> PyMiddlewareLayer<P> {

impl<S, P> Layer<S> for PyMiddlewareLayer<P>
where
PyMiddlewareException: IntoResponse<P>,
PyMiddlewareException: IntoResponseUniform<P>,
{
type Service = PyMiddlewareService<S>;

Expand Down
Loading