Unverified Commit 78022d69 authored by Harry Barber's avatar Harry Barber Committed by GitHub
Browse files

Remove Protocol enum (#1829)

* Remove Protocol enum

* Update Python implementation
parent 238cf8b4
Loading
Loading
Loading
Loading
+12 −0
Original line number Diff line number Diff line
@@ -137,3 +137,15 @@ message = "Fix regression where `connect_timeout` and `read_timeout` fields are
references = ["smithy-rs#1822"]
meta = { "breaking" = false, "tada" = false, "bug" = true }
author = "kevinpark1217"

[[smithy-rs]]
message = "Remove `Protocol` enum, removing an obstruction to extending smithy to third-party protocols."
references = ["smithy-rs#1829"]
meta = { "breaking" = true, "tada" = false, "bug" = false, "target" = "server" }
author = "hlbarber"

[[smithy-rs]]
message = "Convert the `protocol` argument on `PyMiddlewares::new` constructor to a type parameter."
references = ["smithy-rs#1829"]
meta = { "breaking" = true, "tada" = false, "bug" = false, "target" = "server" }
author = "hlbarber"
+28 −14
Original line number Diff line number Diff line
@@ -23,6 +23,7 @@ import software.amazon.smithy.rust.codegen.core.util.outputShape
import software.amazon.smithy.rust.codegen.core.util.toSnakeCase
import software.amazon.smithy.rust.codegen.server.python.smithy.PythonServerCargoDependency
import software.amazon.smithy.rust.codegen.server.smithy.ServerCargoDependency
import software.amazon.smithy.rust.codegen.server.smithy.generators.protocol.ServerProtocol

/**
 * Generates a Python compatible application and server that can be configured from Python.
@@ -62,13 +63,13 @@ import software.amazon.smithy.rust.codegen.server.smithy.ServerCargoDependency
 */
class PythonApplicationGenerator(
    codegenContext: CodegenContext,
    private val protocol: ServerProtocol,
    private val operations: List<OperationShape>,
) {
    private val symbolProvider = codegenContext.symbolProvider
    private val libName = "lib${codegenContext.settings.moduleName.toSnakeCase()}"
    private val runtimeConfig = codegenContext.runtimeConfig
    private val model = codegenContext.model
    private val protocol = codegenContext.protocol
    private val codegenScope =
        arrayOf(
            "SmithyPython" to PythonServerCargoDependency.SmithyHttpServerPython(runtimeConfig).asType(),
@@ -88,6 +89,7 @@ class PythonApplicationGenerator(
    fun render(writer: RustWriter) {
        renderPyApplicationRustDocs(writer)
        renderAppStruct(writer)
        renderAppDefault(writer)
        renderAppClone(writer)
        renderPyAppTrait(writer)
        renderAppImpl(writer)
@@ -98,7 +100,7 @@ class PythonApplicationGenerator(
        writer.rustTemplate(
            """
            ##[#{pyo3}::pyclass]
            ##[derive(Debug, Default)]
            ##[derive(Debug)]
            pub struct App {
                handlers: #{HashMap}<String, #{SmithyPython}::PyHandler>,
                middlewares: #{SmithyPython}::PyMiddlewares,
@@ -128,6 +130,25 @@ class PythonApplicationGenerator(
        )
    }

    private fun renderAppDefault(writer: RustWriter) {
        writer.rustTemplate(
            """
            impl Default for App {
                fn default() -> Self {
                    Self {
                        handlers: Default::default(),
                        middlewares: #{SmithyPython}::PyMiddlewares::new::<#{Protocol}>(vec![]),
                        context: None,
                        workers: #{parking_lot}::Mutex::new(vec![]),
                    }
                }
            }
            """,
            "Protocol" to protocol.markerStruct(),
            *codegenScope,
        )
    }

    private fun renderAppImpl(writer: RustWriter) {
        writer.rustBlockTemplate(
            """
@@ -165,13 +186,9 @@ class PythonApplicationGenerator(
                rustTemplate(
                    """
                    let middleware_locals = pyo3_asyncio::TaskLocals::new(event_loop);
                    use #{SmithyPython}::PyApp;
                    let service = #{tower}::ServiceBuilder::new().layer(
                        #{SmithyPython}::PyMiddlewareLayer::new(
                            self.middlewares.clone(),
                            self.protocol(),
                            middleware_locals
                        )?,
                    let service = #{tower}::ServiceBuilder::new()
                        .layer(
                            #{SmithyPython}::PyMiddlewareLayer::<#{Protocol}>::new(self.middlewares.clone(), middleware_locals),
                        );
                    let router: #{SmithyServer}::routing::Router = router
                        .build()
@@ -179,6 +196,7 @@ class PythonApplicationGenerator(
                        .into();
                    Ok(router.layer(service))
                    """,
                    "Protocol" to protocol.markerStruct(),
                    *codegenScope,
                )
            }
@@ -186,7 +204,6 @@ class PythonApplicationGenerator(
    }

    private fun renderPyAppTrait(writer: RustWriter) {
        val protocol = protocol.toString().replace("#", "##")
        writer.rustTemplate(
            """
            impl #{SmithyPython}::PyApp for App {
@@ -202,9 +219,6 @@ class PythonApplicationGenerator(
                fn middlewares(&mut self) -> &mut #{SmithyPython}::PyMiddlewares {
                    &mut self.middlewares
                }
                fn protocol(&self) -> &'static str {
                    "$protocol"
                }
            }
            """,
            *codegenScope,
+3 −1
Original line number Diff line number Diff line
@@ -16,6 +16,7 @@ import software.amazon.smithy.rust.codegen.core.util.toSnakeCase
import software.amazon.smithy.rust.codegen.server.python.smithy.PythonServerCargoDependency
import software.amazon.smithy.rust.codegen.server.smithy.ServerCargoDependency
import software.amazon.smithy.rust.codegen.server.smithy.generators.ServerOperationHandlerGenerator
import software.amazon.smithy.rust.codegen.server.smithy.generators.protocol.ServerProtocol

/**
 * The Rust code responsible to run the Python business logic on the Python interpreter
@@ -33,8 +34,9 @@ import software.amazon.smithy.rust.codegen.server.smithy.generators.ServerOperat
 */
class PythonServerOperationHandlerGenerator(
    codegenContext: CodegenContext,
    protocol: ServerProtocol,
    private val operations: List<OperationShape>,
) : ServerOperationHandlerGenerator(codegenContext, operations) {
) : ServerOperationHandlerGenerator(codegenContext, protocol, operations) {
    private val symbolProvider = codegenContext.symbolProvider
    private val runtimeConfig = codegenContext.runtimeConfig
    private val codegenScope =
+2 −2
Original line number Diff line number Diff line
@@ -34,12 +34,12 @@ class PythonServerServiceGenerator(
    }

    override fun renderOperationHandler(writer: RustWriter, operations: List<OperationShape>) {
        PythonServerOperationHandlerGenerator(context, operations).render(writer)
        PythonServerOperationHandlerGenerator(context, protocol, operations).render(writer)
    }

    override fun renderExtras(operations: List<OperationShape>) {
        rustCrate.withModule(RustModule.public("python_server_application", "Python server and application implementation.")) { writer ->
            PythonApplicationGenerator(context, operations)
            PythonApplicationGenerator(context, protocol, operations)
                .render(writer)
        }
    }
+7 −9
Original line number Diff line number Diff line
@@ -19,9 +19,9 @@ import software.amazon.smithy.rust.codegen.core.smithy.transformers.operationErr
import software.amazon.smithy.rust.codegen.core.util.hasStreamingMember
import software.amazon.smithy.rust.codegen.core.util.inputShape
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.ServerRuntimeType
import software.amazon.smithy.rust.codegen.server.smithy.generators.protocol.ServerProtocol
import software.amazon.smithy.rust.codegen.server.smithy.protocols.ServerHttpBoundProtocolGenerator

/**
@@ -29,12 +29,11 @@ import software.amazon.smithy.rust.codegen.server.smithy.protocols.ServerHttpBou
 */
open class ServerOperationHandlerGenerator(
    codegenContext: CodegenContext,
    val protocol: ServerProtocol,
    private val operations: List<OperationShape>,
) {
    private val serverCrate = "aws_smithy_http_server"
    private val service = codegenContext.serviceShape
    private val model = codegenContext.model
    private val protocol = codegenContext.protocol
    private val symbolProvider = codegenContext.symbolProvider
    private val runtimeConfig = codegenContext.runtimeConfig
    private val codegenScope = arrayOf(
@@ -83,11 +82,8 @@ open class ServerOperationHandlerGenerator(
                        Ok(v) => v,
                        Err(extension_not_found_rejection) => {
                            let extension = $serverCrate::extension::RuntimeErrorExtension::new(extension_not_found_rejection.to_string());
                            let runtime_error = $serverCrate::runtime_error::RuntimeError {
                                protocol: #{SmithyHttpServer}::protocols::Protocol::${protocol.name.toPascalCase()},
                                kind: extension_not_found_rejection.into(),
                            };
                            let mut response = runtime_error.into_response();
                            let runtime_error = $serverCrate::runtime_error::RuntimeError::from(extension_not_found_rejection);
                            let mut response = #{SmithyHttpServer}::response::IntoResponse::<#{Protocol}>::into_response(runtime_error);
                            response.extensions_mut().insert(extension);
                            return response.map($serverCrate::body::boxed);
                        }
@@ -109,7 +105,8 @@ open class ServerOperationHandlerGenerator(
                        let input_wrapper = match $inputWrapperName::from_request(&mut req).await {
                            Ok(v) => v,
                            Err(runtime_error) => {
                                return runtime_error.into_response().map($serverCrate::body::boxed);
                                let response = #{SmithyHttpServer}::response::IntoResponse::<#{Protocol}>::into_response(runtime_error);
                                return response.map($serverCrate::body::boxed);
                            }
                        };
                        $callImpl
@@ -120,6 +117,7 @@ open class ServerOperationHandlerGenerator(
                        response.map(#{SmithyHttpServer}::body::boxed)
                    }
                    """,
                    "Protocol" to protocol.markerStruct(),
                    *codegenScope,
                )
            }
Loading