-
Notifications
You must be signed in to change notification settings - Fork 180
/
CombinedErrorGenerator.kt
269 lines (249 loc) · 11.3 KB
/
CombinedErrorGenerator.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rust.codegen.smithy.generators.error
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.codegen.core.SymbolProvider
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.shapes.StructureShape
import software.amazon.smithy.model.shapes.UnionShape
import software.amazon.smithy.model.traits.RetryableTrait
import software.amazon.smithy.rust.codegen.rustlang.Attribute
import software.amazon.smithy.rust.codegen.rustlang.RustMetadata
import software.amazon.smithy.rust.codegen.rustlang.RustWriter
import software.amazon.smithy.rust.codegen.rustlang.Visibility
import software.amazon.smithy.rust.codegen.rustlang.Writable
import software.amazon.smithy.rust.codegen.rustlang.documentShape
import software.amazon.smithy.rust.codegen.rustlang.rust
import software.amazon.smithy.rust.codegen.rustlang.rustBlock
import software.amazon.smithy.rust.codegen.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.rustlang.writable
import software.amazon.smithy.rust.codegen.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.smithy.RustSymbolProvider
import software.amazon.smithy.rust.codegen.smithy.customize.Section
import software.amazon.smithy.rust.codegen.smithy.transformers.eventStreamErrors
import software.amazon.smithy.rust.codegen.smithy.transformers.operationErrors
import software.amazon.smithy.rust.codegen.util.hasTrait
import software.amazon.smithy.rust.codegen.util.isEventStream
import software.amazon.smithy.rust.codegen.util.toSnakeCase
/**
* For a given Operation ([this]), return the symbol referring to the unified error. This can be used
* if you, e.g. want to return a unified error from a function:
*
* ```kotlin
* rustWriter.rustBlock("fn get_error() -> #T", operation.errorSymbol(symbolProvider)) {
* write("todo!() // function body")
* }
* ```
*/
fun OperationShape.errorSymbol(symbolProvider: SymbolProvider): RuntimeType {
val symbol = symbolProvider.toSymbol(this)
return RuntimeType("${symbol.name}Error", null, "crate::error")
}
fun UnionShape.eventStreamErrorSymbol(symbolProvider: SymbolProvider): RuntimeType {
val symbol = symbolProvider.toSymbol(this)
return RuntimeType("${symbol.name}Error", null, "crate::error")
}
/**
* Generates a unified error enum for [operation]. [ErrorGenerator] handles generating the individual variants,
* but we must still combine those variants into an enum covering all possible errors for a given operation.
*/
class CombinedErrorGenerator(
private val model: Model,
private val symbolProvider: RustSymbolProvider,
private val operation: OperationShape
) {
private val runtimeConfig = symbolProvider.config().runtimeConfig
private val genericError = RuntimeType.GenericError(symbolProvider.config().runtimeConfig)
fun render(writer: RustWriter) {
val symbol = operation.errorSymbol(symbolProvider)
val operationSymbol = symbolProvider.toSymbol(operation)
renderErrors(writer, operation.operationErrors(model).map { it.asStructureShape().get() }.toMutableList(), symbol, operationSymbol)
if (operation.isEventStream(model)) {
operation.eventStreamErrors(model)
.forEach { (unionShape, unionErrors) ->
renderErrors(
writer,
unionErrors,
unionShape.eventStreamErrorSymbol(symbolProvider),
symbolProvider.toSymbol(unionShape)
)
}
}
}
private fun renderErrors(
writer: RustWriter,
errors: List<StructureShape>,
errorSymbol: RuntimeType,
operationSymbol: Symbol
) {
val meta = RustMetadata(
derives = Attribute.Derives(setOf(RuntimeType.Debug)),
additionalAttributes = listOf(Attribute.NonExhaustive),
visibility = Visibility.PUBLIC
)
writer.rust("/// Error type for the `${operationSymbol.name}` operation.")
meta.render(writer)
writer.rustBlock("struct ${errorSymbol.name}") {
rust(
"""
/// Kind of error that occurred.
pub kind: ${errorSymbol.name}Kind,
/// Additional metadata about the error, including error code, message, and request ID.
pub (crate) meta: #T
""",
RuntimeType.GenericError(runtimeConfig)
)
}
writer.rust("/// Types of errors that can occur for the `${operationSymbol.name}` operation.")
meta.render(writer)
writer.rustBlock("enum ${errorSymbol.name}Kind") {
errors.forEach { errorVariant ->
documentShape(errorVariant, model)
val errorVariantSymbol = symbolProvider.toSymbol(errorVariant)
write("${errorVariantSymbol.name}(#T),", errorVariantSymbol)
}
rust(
"""
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn #T + Send + Sync + 'static>),
""",
RuntimeType.StdError
)
}
writer.rustBlock("impl #T for ${errorSymbol.name}", RuntimeType.Display) {
rustBlock("fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result") {
delegateToVariants(errors, errorSymbol) {
writable { rust("_inner.fmt(f)") }
}
}
}
val errorKindT = RuntimeType.errorKind(symbolProvider.config().runtimeConfig)
writer.rustBlock(
"impl #T for ${errorSymbol.name}",
RuntimeType.provideErrorKind(symbolProvider.config().runtimeConfig)
) {
rustBlock("fn code(&self) -> Option<&str>") {
rust("${errorSymbol.name}::code(self)")
}
rustBlock("fn retryable_error_kind(&self) -> Option<#T>", errorKindT) {
val retryableVariants = errors.filter { it.hasTrait<RetryableTrait>() }
if (retryableVariants.isEmpty()) {
rust("None")
} else {
rustBlock("match &self.kind") {
retryableVariants.forEach {
val errorVariantSymbol = symbolProvider.toSymbol(it)
rust("${errorSymbol.name}Kind::${errorVariantSymbol.name}(inner) => Some(inner.retryable_error_kind()),")
}
rust("_ => None")
}
}
}
}
writer.rustBlock("impl ${errorSymbol.name}") {
writer.rustTemplate(
"""
/// Creates a new `${errorSymbol.name}`.
pub fn new(kind: ${errorSymbol.name}Kind, meta: #{generic_error}) -> Self {
Self { kind, meta }
}
/// Creates the `${errorSymbol.name}::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn #{std_error} + Send + Sync + 'static>>) -> Self {
Self {
kind: ${errorSymbol.name}Kind::Unhandled(err.into()),
meta: Default::default()
}
}
/// Creates the `${errorSymbol.name}::Unhandled` variant from a `#{generic_error}`.
pub fn generic(err: #{generic_error}) -> Self {
Self {
meta: err.clone(),
kind: ${errorSymbol.name}Kind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &#{generic_error} {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
""",
"generic_error" to genericError, "std_error" to RuntimeType.StdError
)
errors.forEach { error ->
val errorVariantSymbol = symbolProvider.toSymbol(error)
val fnName = errorVariantSymbol.name.toSnakeCase()
writer.rust("/// Returns `true` if the error kind is `${errorSymbol.name}Kind::${errorVariantSymbol.name}`.")
writer.rustBlock("pub fn is_$fnName(&self) -> bool") {
rust("matches!(&self.kind, ${errorSymbol.name}Kind::${errorVariantSymbol.name}(_))")
}
}
}
writer.rustBlock("impl #T for ${errorSymbol.name}", RuntimeType.StdError) {
rustBlock("fn source(&self) -> Option<&(dyn #T + 'static)>", RuntimeType.StdError) {
delegateToVariants(errors, errorSymbol) {
writable {
when (it) {
is VariantMatch.Unhandled -> rust("Some(_inner.as_ref())")
is VariantMatch.Modeled -> rust("Some(_inner)")
}
}
}
}
}
}
sealed class VariantMatch(name: String) : Section(name) {
object Unhandled : VariantMatch("Unhandled")
data class Modeled(val symbol: Symbol, val shape: Shape) : VariantMatch("Modeled")
}
/**
* Generates code to delegate behavior to the variants, for example:
*
* ```rust
* match &self.kind {
* GreetingWithErrorsError::InvalidGreeting(_inner) => inner.fmt(f),
* GreetingWithErrorsError::ComplexError(_inner) => inner.fmt(f),
* GreetingWithErrorsError::FooError(_inner) => inner.fmt(f),
* GreetingWithErrorsError::Unhandled(_inner) => _inner.fmt(f),
* }
* ```
*
* [handler] is passed an instance of [VariantMatch]—a [writable] should be returned containing the content to be
* written for this variant.
*
* The field will always be bound as `_inner`.
*/
private fun RustWriter.delegateToVariants(
errors: List<StructureShape>,
symbol: RuntimeType,
handler: (VariantMatch) -> Writable
) {
rustBlock("match &self.kind") {
errors.forEach {
val errorSymbol = symbolProvider.toSymbol(it)
rust("""${symbol.name}Kind::${errorSymbol.name}(_inner) => """)
handler(VariantMatch.Modeled(errorSymbol, it))(this)
write(",")
}
val unhandledHandler = handler(VariantMatch.Unhandled)
rustBlock("${symbol.name}Kind::Unhandled(_inner) =>") {
unhandledHandler(this)
}
}
}
}