-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go.tmpl
259 lines (230 loc) · 9.58 KB
/
client.go.tmpl
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
{{define "client"}}
{{- $typeMap := .TypeMap -}}
{{- $types := .Types -}}
{{- if .Services -}}
// region Client
{{- range $_, $service := .Services}}
interface {{$service.Name}} {
{{- range $i, $method := $service.Methods}}
@Throws(WebRpcError::class)
suspend fun {{firstLetterToLower $method.Name}}({{template "methodInputs" dict "Method" $method "TypeMap" $typeMap}}){{if gt (len $method.Outputs) 0 }}: {{template "methodOutputsAsObject" dict "Service" $service "Method" $method "TypeMap" $typeMap}}{{end}}
{{- end}}
{{range $_, $method := $service.Methods }}
{{- if gt (len $method.Inputs) 0 }}
data class {{$method.Name}}Request(
{{- range $_, $field := $method.Inputs}}
{{- $isExportable := true -}}
{{- range $meta := $field.Meta -}}
{{- if exists $meta "json" -}}
{{- if eq (printf "%v" (get $meta "json")) "-" -}}
{{- $isExportable = false}}
{{- end -}}
{{- end -}}
{{- end }}
{{- if $isExportable }}
@Json(name = "{{template "codingKey" dict "Field" .}}") val {{template "fieldName" dict "Field" .}}: {{template "type" dict "Type" $field.Type "TypeMap" $typeMap}}{{if .Optional}}?{{end}},
{{- end -}}
{{- end}}
)
{{ end -}}
{{- if gt (len $method.Outputs) 0 }}
data class {{$method.Name}}Response(
{{- range $_, $field := $method.Outputs}}
{{- $isExportable := true -}}
{{- range $meta := $field.Meta -}}
{{- if exists $meta "json" -}}
{{- if eq (printf "%v" (get $meta "json")) "-" -}}
{{- $isExportable = false}}
{{- end -}}
{{- end -}}
{{- end }}
{{- if $isExportable }}
@Json(name = "{{template "codingKey" dict "Field" .}}") val {{template "fieldName" dict "Field" .}}: {{template "type" dict "Type" $field.Type "TypeMap" $typeMap}}{{if .Optional}}?{{end}},
{{- end -}}
{{- end}}
)
{{end -}}
{{end -}}
}
{{ end }}
open class WebRpcKtorClient {
@Suppress("RethrowCaughtException")
@Throws(WebRpcError::class)
protected suspend inline fun <reified I, reified O> request(
client: HttpClient,
baseUrl: String,
method: String,
body: I?,
serialize: (I) -> String,
deserialize: (String) -> O,
deserializeError: (String) -> WebRpcError,
extraHttpBuilder: HttpRequestBuilder.() -> Unit = {},
): O {
return try {
val response = client.post(baseUrl) {
url {
appendPathSegments(method)
}
contentType(ContentType.Application.Json)
setBody(body?.let { serialize(body) } ?: "{}")
extraHttpBuilder()
}
val responseBody = response.bodyAsText(fallbackCharset = Charsets.UTF_8)
if (response.status.isSuccess()) {
if (O::class.java != Unit::class.java) {
deserialize(responseBody)
} else Unit as O
} else {
throw deserializeError(responseBody)
}
} catch (e: CancellationException) {
// CancellationException must be propagated to ensure correct cancellation of coroutines
throw e
} catch (e: WebRpcError) {
// Propagate original WebRpcError out of the function
throw e
} catch (e: Throwable) {
throw createUnknownError(exception = e)
}
}
protected fun createUnknownError(exception: Throwable? = null) = WebRpcError(
error = "Unknown error",
code = ErrorKind.UNKNOWN.code,
message = exception?.message ?: "",
causeString = exception?.cause?.toString() ?: "",
status = ErrorKind.UNKNOWN.code,
errorKind = ErrorKind.UNKNOWN,
cause = exception,
)
}
private object Serializer {
@JvmStatic
val moshiBuilder: Moshi.Builder = SerializerHelper.addEnumUnknownDefaultCase(Moshi.Builder())
}
private object SerializerHelper {
fun addEnumUnknownDefaultCase(moshiBuilder: Moshi.Builder): Moshi.Builder {
return moshiBuilder
{{- if $types -}}
{{range $_i, $type := $types -}}
{{if isEnumType $type }}
.add(
{{$type.Name}}::class.java,
EnumJsonAdapter.create({{$type.Name}}::class.java).withUnknownFallback({{$type.Name}}.UNKNOWN_DEFAULT).nullSafe(),
)
{{- end -}}
{{- end -}}
{{- end -}}
.add(UnsignedNumberJsonAdapter.Factory)
.add(IsoDateAdapter())
.addLast(KotlinJsonAdapterFactory())
}
}
private class UnsignedNumberJsonAdapter<UnsignedT : Any> private constructor(
private val toUnsignedT: ULong.() -> UnsignedT,
) : JsonAdapter<UnsignedT>() {
override fun toJson(writer: JsonWriter, value: UnsignedT?) {
when (value) {
null -> writer.nullValue()
else -> writer.valueSink().use { it.writeUtf8(value.toString()) }
}
}
override fun fromJson(reader: JsonReader): UnsignedT? = when (val next = reader.peek()) {
Token.NUMBER -> {
try {
reader.nextString().toULong().toUnsignedT()
} catch (numberFormatException: NumberFormatException) {
throw JsonDataException(
"${numberFormatException.message} for unsigned number at ${reader.path}"
)
}
}
Token.NULL -> reader.nextNull()
else -> throw JsonDataException(
"Expected an unsigned number but was ${reader.readJsonValue()}, " +
"a $next, at path ${reader.path}",
IllegalArgumentException(next.name)
)
}
object Factory : JsonAdapter.Factory {
private val unsignedTypesMapperMap: Map<Class<*>, ULong.() -> Any> = mapOf(
ULong::class.java to { this },
UInt::class.java to {
if (this > UInt.MAX_VALUE) throw NumberFormatException("Invalid number format: '$this'") else toUInt()
},
UShort::class.java to {
if (this > UShort.MAX_VALUE) throw NumberFormatException("Invalid number format: '$this'") else toUShort()
},
UByte::class.java to {
if (this > UByte.MAX_VALUE) throw NumberFormatException("Invalid number format: '$this'") else toUByte()
}
)
private val Type.isUnsignedType: Boolean
get() = unsignedTypesMapperMap.keys.contains(rawType)
private val Type.mapper: ULong.() -> Any
get() = unsignedTypesMapperMap[rawType]!!
override fun create(
type: Type,
annotations: Set<Annotation>,
moshi: Moshi,
): JsonAdapter<*>? = if (type.isUnsignedType) UnsignedNumberJsonAdapter(type.mapper) else null
}
}
class IsoDateAdapter {
@ToJson
fun toJson(value: OffsetDateTime): String {
return value.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
}
@FromJson
fun fromJson(value: String): OffsetDateTime {
return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
}
}
{{- range $service := .Services}}
open class {{.Name}}Client(
baseUrl: String,
httpClientBuilder: () -> HttpClient,
private val httpRequestBuilder: HttpRequestBuilder.() -> Unit = {},
moshiBuilder: Moshi.Builder = Serializer.moshiBuilder,
): WebRpcKtorClient(), {{$service.Name}} {
private val baseUrl = baseUrl.normalizeUrl() + "rpc/{{$service.Name}}"
private val ktorClient by lazy { httpClientBuilder() }
private val moshi by lazy { moshiBuilder.build() }
@Throws(WebRpcError::class)
private suspend inline fun <reified O> request(method: String, body: Any? = null): O {
return request(
client = ktorClient,
baseUrl = baseUrl,
method = method,
body = body,
serialize = this::toJson,
deserialize = { json -> fromJson(json, O::class.java) },
deserializeError = { json -> fromJson(json, WebRpcError::class.java) },
extraHttpBuilder = httpRequestBuilder,
)
}
private fun toJson(obj: Any): String {
return moshi.adapter(obj.javaClass).toJson(obj)
}
private fun <T> fromJson(json: String, type: Type): T {
return moshi.adapter<T>(type).fromJson(json) ?: throw createUnknownError(
ParseException("Cannot parse JSON body.", cause = IllegalStateException(json))
)
}
private fun String.normalizeUrl() = this.takeIf { it.endsWith("/") } ?: "$this/"
{{- range $i, $method := $service.Methods}}
@Throws(WebRpcError::class)
override suspend fun {{firstLetterToLower $method.Name}}({{template "methodInputs" dict "Method" $method "TypeMap" $typeMap}}){{if gt (len $method.Outputs) 0 }}: {{template "methodOutputsAsObject" dict "Service" $service "Method" $method "TypeMap" $typeMap}}{{end}} {
{{if gt (len $method.Outputs) 0 }}return {{end}}request<{{template "methodOutputs" dict "Service" $service "Method" $method "TypeMap" $typeMap}}>(
method = "{{$method.Name}}",
{{- if gt (len $method.Inputs) 0 }}
body = {{$service.Name}}.{{$method.Name}}Request(
{{ range $i, $input := $method.Inputs }}{{camelCase $input.Name}} = {{camelCase $input.Name}},{{ end }}
){{ end }}
){{ if eq (len $method.Outputs) 1 }}.{{ (index $method.Outputs 0).Name }}{{end}}
}
{{- end}}
}
{{end -}}
{{end -}}
// endregion
{{end}}