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

Document the new service builder #2021

Merged
merged 26 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e6e7a2f
Document the new service builder
82marbag Nov 22, 2022
3dfc04b
Generate docs for current service
82marbag Nov 22, 2022
79dc931
Address comments
82marbag Nov 23, 2022
ddbedf1
Rename variable
82marbag Nov 23, 2022
630a914
Merge branch 'main' into new-service-builder-docs
82marbag Nov 23, 2022
f7a2393
Change handler names
82marbag Nov 23, 2022
7a13a5f
Update docs
82marbag Nov 24, 2022
28cfe35
Update docs
82marbag Nov 24, 2022
c6e321d
Update docs
Nov 24, 2022
bb75fde
Update docs
82marbag Nov 24, 2022
58292cc
Merge branch 'main' into new-service-builder-docs
82marbag Nov 24, 2022
2260908
Update dependencies
82marbag Nov 24, 2022
566d12a
Update docs
82marbag Nov 25, 2022
0a943c6
Update docs
82marbag Nov 25, 2022
f687d5d
Address comments
82marbag Nov 29, 2022
78cc474
Address comments
82marbag Nov 30, 2022
28f182f
Fix CI
82marbag Nov 30, 2022
9e3bf62
Fix CI
82marbag Nov 30, 2022
bc9e5bd
Fix CI
82marbag Nov 30, 2022
8faff7d
Fix CI
82marbag Nov 30, 2022
9ec3ad3
Address comments
82marbag Nov 30, 2022
f2f83df
Update codegen-server/src/main/kotlin/software/amazon/smithy/rust/cod…
82marbag Nov 30, 2022
90fca46
Update codegen-server/src/main/kotlin/software/amazon/smithy/rust/cod…
82marbag Nov 30, 2022
43b45dd
Update codegen-server/src/main/kotlin/software/amazon/smithy/rust/cod…
82marbag Nov 30, 2022
be9335b
Update codegen-server/src/main/kotlin/software/amazon/smithy/rust/cod…
82marbag Nov 30, 2022
9d63316
Merge branch 'main' into new-service-builder-docs
LukeMathWalker Dec 1, 2022
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 @@ -18,39 +18,38 @@ import software.amazon.smithy.rust.codegen.core.smithy.Outputs
import software.amazon.smithy.rust.codegen.core.smithy.generators.error.errorSymbol
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.toSnakeCase

/**
Generates a stub for use within documentation.
*/
class DocHandlerGenerator(private val operation: OperationShape, private val commentToken: String = "//", private val codegenContext: CodegenContext) {
class DocHandlerGenerator(private val operation: OperationShape, private val commentToken: String = "//", private val handlerName: String, codegenContext: CodegenContext) {
private val model = codegenContext.model
private val symbolProvider = codegenContext.symbolProvider
private val crateName = codegenContext.settings.moduleName.toSnakeCase()
private val crateName = codegenContext.moduleUseName()

/**
* Returns the function signature for an operation handler implementation. Used in the documentation.
*/
private fun OperationShape.docSignature(): Writable {
val inputSymbol = symbolProvider.toSymbol(inputShape(model))
val outputSymbol = symbolProvider.toSymbol(outputShape(model))
val errorSymbol = errorSymbol(model, symbolProvider, CodegenTarget.SERVER)
fun docSignature(): Writable {
val inputSymbol = symbolProvider.toSymbol(operation.inputShape(model))
val outputSymbol = symbolProvider.toSymbol(operation.outputShape(model))
val errorSymbol = operation.errorSymbol(model, symbolProvider, CodegenTarget.SERVER)

val outputT = if (errors.isEmpty()) {
val outputT = if (operation.errors.isEmpty()) {
outputSymbol.name
} else {
"Result<${outputSymbol.name}, ${errorSymbol.name}>"
}

return writable {
if (!errors.isEmpty()) {
if (operation.errors.isNotEmpty()) {
rust("$commentToken ## use $crateName::${Errors.namespace}::${errorSymbol.name};")
}
rust(
"""
$commentToken ## use $crateName::${Inputs.namespace}::${inputSymbol.name};
$commentToken ## use $crateName::${Outputs.namespace}::${outputSymbol.name};
$commentToken async fn handler(input: ${inputSymbol.name}) -> $outputT {
$commentToken async fn $handlerName(input: ${inputSymbol.name}) -> $outputT {
$commentToken todo!()
$commentToken }
""".trimIndent(),
Expand All @@ -59,6 +58,6 @@ class DocHandlerGenerator(private val operation: OperationShape, private val com
}

fun render(writer: RustWriter) {
operation.docSignature()(writer)
docSignature()(writer)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class ServerOperationShapeGenerator(
"SmithyHttpServer" to
ServerCargoDependency.SmithyHttpServer(codegenContext.runtimeConfig).toType(),
"Tower" to ServerCargoDependency.Tower.toType(),
"Handler" to DocHandlerGenerator(operations[0], "//!", codegenContext)::render,
"Handler" to DocHandlerGenerator(operations[0], "//!", "handler", codegenContext)::render,
)
for (operation in operations) {
ServerOperationGenerator(codegenContext, operation).render(writer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import software.amazon.smithy.rust.codegen.core.rustlang.rust
import software.amazon.smithy.rust.codegen.core.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.core.rustlang.writable
import software.amazon.smithy.rust.codegen.core.smithy.CodegenContext
import software.amazon.smithy.rust.codegen.core.smithy.Errors
import software.amazon.smithy.rust.codegen.core.smithy.Inputs
import software.amazon.smithy.rust.codegen.core.smithy.Outputs
import software.amazon.smithy.rust.codegen.core.util.toPascalCase
import software.amazon.smithy.rust.codegen.core.util.toSnakeCase
import software.amazon.smithy.rust.codegen.server.smithy.ServerCargoDependency
Expand Down Expand Up @@ -156,7 +159,7 @@ class ServerServiceGeneratorV2(
}
""",
"Protocol" to protocol.markerStruct(),
"Handler" to DocHandlerGenerator(operationShape, "///", codegenContext)::render,
"Handler" to DocHandlerGenerator(operationShape, "///", "handler", codegenContext)::render,
*codegenScope,
)

Expand Down Expand Up @@ -469,8 +472,104 @@ class ServerServiceGeneratorV2(
}

fun render(writer: RustWriter) {
val crateName = codegenContext.moduleUseName()
val handlers: Writable = operations
.map { operation ->
DocHandlerGenerator(operation, "///", builderFieldNames[operation]!!, codegenContext).docSignature()
}
.reduce { acc, wt ->
writable {
rustTemplate("#{acc:W} \n#{wt:W}", "acc" to acc, "wt" to wt)
}
}

writer.rustTemplate(
"""
/// A fast and customizable Rust implementation of the $serviceName Smithy service.
///
/// This crate provides all types required to setup the [`$serviceName`] Service.
/// The [`$crateName::${Inputs.namespace}`], [`$crateName::${Outputs.namespace}`], and [`$crateName::${Errors.namespace}`] modules provide the types used in each operation.
82marbag marked this conversation as resolved.
Show resolved Hide resolved
///
/// The primary export is [`$serviceName`]: it is the
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
/// [`$builderName`] is used to set your business logic to implement your [operations],
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
/// customize your [operations]'s behaviors by applying middleware,
/// and build your service.
///
/// [`$builderName`] contains the [operations] modeled in your Smithy service.
/// You must set an implementation for all operations with the correct signature,
/// or your service will fail to be constructed at runtime and panic.
/// For each of the [operations] modeled in
/// your Smithy service, you need to provide an implementation in the
/// form of an async function that takes in the
/// operation's input as their first parameter, and returns the
/// operation's output. If your operation is fallible (i.e. it
/// contains the `errors` member in your Smithy model), the function
/// implementing the operation has to be fallible (i.e. return a [`Result`]).
/// The possible forms for your async functions are:
/// ```rust
/// async fn handler_fallible(input: Input, extensions: #{SmithyHttpServer}Extension<T>) -> Result<Output, Error>;
/// async fn handler_infallible(input: Input, extensions: #{SmithyHttpServer}Extension<T>) -> Output;
/// ```
/// Both can take up to 8 extensions, or none:
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
/// ```rust
/// async fn handler_with_no_extensions(input: Input) -> ...;
/// async fn handler_with_one_extension(input: Input, ext: #{SmithyHttpServer}Extension<T>) -> ...;
/// async fn handler_with_two_extensions(input: Input, ext0: #{SmithyHttpServer}Extension<T>, ext1: #{SmithyHttpServer}Extension<T>) -> ...;
/// ...
/// ```
/// For a full list of the possible extensions, see: [`#{SmithyHttpServer}::request`]. Any `T: Send + Sync + 'static` is also allowed.
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
///
/// To construct [`$serviceName`], you can use:
/// * [`$serviceName::builder_without_plugins()`] which returns a [`$builderName`] without any service-wide middleware applied.
/// * [`$serviceName::builder_with_plugins(plugins)`] which returns a [`$builderName`] that applies `plugins` to all your operations.
///
/// To know more about plugins, see: [`#{SmithyHttpServer}::plugin`].
82marbag marked this conversation as resolved.
Show resolved Hide resolved
///
/// When you have set all your operations, you can convert [`$serviceName`] into a tower [Service] calling:
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
/// * [`$serviceName::into_make_service`] that converts $serviceName into a type that implements [`tower::make::MakeService`], a _service factory_.
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
/// * [`$serviceName::into_make_service_with_connect_info`] that converts $serviceName into [`tower::make::MakeService`]
/// with [`ConnectInfo`](#{SmithyHttpServer}::request::connect_info::ConnectInfo).
/// You can write your implementations to be passed in the connection information, populated by the [Hyper server], as an [`#{SmithyHttpServer}Extension`].
///
/// You can feed this [Service] to a [Hyper server], and the
/// server will instantiate and [`serve`] your service.
///
/// Here's a full example to get you started:
hlbarber marked this conversation as resolved.
Show resolved Hide resolved
///
/// ```rust
/// use std::net::SocketAddr;
/// use $crateName::$serviceName;
///
/// ##[tokio::main]
/// pub async fn main() {
/// let app = $serviceName::builder_without_plugins()
${builderFieldNames.values.joinToString("\n") { "/// .$it($it)" }}
/// .build()
/// .expect("failed to build an instance of $serviceName");
///
/// let bind: SocketAddr = "127.0.0.1:6969".parse()
/// .expect("unable to parse the server bind address and port");
///
/// let server = hyper::Server::bind(&bind).serve(app.into_make_service());
/// ## let server = async { Ok::<_, ()>(()) };
///
/// // Run your service!
/// if let Err(err) = server.await {
/// eprintln!("server error: {}", err);
/// }
/// }
///
#{Handlers:W}
///
/// ```
///
/// [`serve`]: https://docs.rs/hyper/0.14.16/hyper/server/struct.Builder.html##method.serve
/// [`tower::make::MakeService`]: https://docs.rs/tower/latest/tower/make/trait.MakeService.html
/// [HTTP binding traits]: https://smithy.io/2.0/spec/http-bindings.html
/// [operations]: https://smithy.io/2.0/spec/service-types.html##operation
/// [Hyper server]: https://docs.rs/hyper/latest/hyper/server/index.html
82marbag marked this conversation as resolved.
Show resolved Hide resolved
/// [Service]: https://docs.rs/tower-service/latest/tower_service/trait.Service.html

#{Builder:W}

#{MissingOperationsError:W}
Expand All @@ -483,6 +582,9 @@ class ServerServiceGeneratorV2(
"MissingOperationsError" to missingOperationsError(),
"RequestSpecs" to requestSpecsModule(),
"Struct" to serviceStruct(),
"Handlers" to handlers,
"ExampleHandler" to operations.take(1).map { operation -> DocHandlerGenerator(operation, "///", builderFieldNames[operation]!!, codegenContext).docSignature() },
*codegenScope,
)
}
}