-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.go.tmpl
More file actions
463 lines (409 loc) · 13.9 KB
/
runtime.go.tmpl
File metadata and controls
463 lines (409 loc) · 13.9 KB
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
{{define "runtime"}}
{{- $webrpcErrors := .WebrpcErrors -}}
{{- $schemaErrors := .SchemaErrors -}}
{{- $opts := .Opts -}}
public let WEBRPC_HEADER = "Webrpc"
public let WEBRPC_HEADER_VALUE = "{{.WebrpcHeader}}"
public struct WebRPCGeneratedVersions: Sendable, Equatable {
public let webrpcGenVersion: String
public let codeGenName: String
public let codeGenVersion: String
public let schemaName: String
public let schemaVersion: String
public init(
webrpcGenVersion: String = "",
codeGenName: String = "",
codeGenVersion: String = "",
schemaName: String = "",
schemaVersion: String = ""
) {
self.webrpcGenVersion = webrpcGenVersion
self.codeGenName = codeGenName
self.codeGenVersion = codeGenVersion
self.schemaName = schemaName
self.schemaVersion = schemaVersion
}
public static let empty = WebRPCGeneratedVersions()
}
public func versionFromHeader(_ headers: [String: String]) -> WebRPCGeneratedVersions {
guard let headerValue = webRPCHeaderValue(in: headers) else {
return .empty
}
return parseWebRPCGeneratedVersions(headerValue)
}
public func versionFromHeader(_ response: WebRPCHTTPResponse) -> WebRPCGeneratedVersions {
versionFromHeader(response.headers)
}
private func webRPCHeaderValue(in headers: [String: String]) -> String? {
for (name, value) in headers {
if name.caseInsensitiveCompare(WEBRPC_HEADER) == .orderedSame {
return value
}
}
return nil
}
private func parseWebRPCGeneratedVersions(_ header: String) -> WebRPCGeneratedVersions {
let versions = header.split(separator: ";", omittingEmptySubsequences: false)
guard versions.count >= 3 else {
return .empty
}
let webrpcParts = versions[0].split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false)
let codeGenParts = versions[1].split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false)
let schemaParts = versions[2].split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false)
return WebRPCGeneratedVersions(
webrpcGenVersion: webrpcParts.count > 1 ? String(webrpcParts[1]) : "",
codeGenName: codeGenParts.count > 0 ? String(codeGenParts[0]) : "",
codeGenVersion: codeGenParts.count > 1 ? String(codeGenParts[1]) : "",
schemaName: schemaParts.count > 0 ? String(schemaParts[0]) : "",
schemaVersion: schemaParts.count > 1 ? String(schemaParts[1]) : ""
)
}
private func makeWebRPCHeaders(
_ headers: [String: String],
includeWebRPCHeader: Bool
) -> [String: String] {
var requestHeaders = headers
{{- if eq (get $opts "webrpcHeader") true }}
if includeWebRPCHeader {
requestHeaders[WEBRPC_HEADER] = WEBRPC_HEADER_VALUE
}
{{- else }}
_ = includeWebRPCHeader
{{- end }}
return requestHeaders
}
public enum WebRPCJSON {
public static func makeEncoder() -> JSONEncoder {
JSONEncoder()
}
public static func makeDecoder() -> JSONDecoder {
JSONDecoder()
}
}
public struct WebRPCNull: Codable, Sendable {
public init() {}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
guard container.decodeNil() else {
throw DecodingError.typeMismatch(
WebRPCNull.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Expected null",
),
)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
public enum WebRPCJSONValue: Codable, Sendable {
case object([String: WebRPCJSONValue])
case array([WebRPCJSONValue])
case string(String)
case integer(Int64)
case unsignedInteger(UInt64)
case number(Double)
case bool(Bool)
case null
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .null
} else if let value = try? container.decode(Bool.self) {
self = .bool(value)
} else if let value = try? container.decode(Int64.self) {
self = .integer(value)
} else if let value = try? container.decode(UInt64.self) {
self = .unsignedInteger(value)
} else if let value = try? container.decode(Double.self) {
self = .number(value)
} else if let value = try? container.decode(String.self) {
self = .string(value)
} else if let value = try? container.decode([WebRPCJSONValue].self) {
self = .array(value)
} else if let value = try? container.decode([String: WebRPCJSONValue].self) {
self = .object(value)
} else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Unsupported JSON value",
)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .object(let value):
try container.encode(value)
case .array(let value):
try container.encode(value)
case .string(let value):
try container.encode(value)
case .integer(let value):
try container.encode(value)
case .unsignedInteger(let value):
try container.encode(value)
case .number(let value):
try container.encode(value)
case .bool(let value):
try container.encode(value)
case .null:
try container.encodeNil()
}
}
}
public protocol WebRPCEnumKey: Hashable, Sendable {
init(wireValue: String)
var wireValue: String { get }
}
public struct WebRPCEnumMap<Key, Value>: Codable, Sendable
where Key: WebRPCEnumKey, Value: Codable & Sendable {
public var values: [Key: Value]
public init(_ values: [Key: Value] = [:]) {
self.values = values
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let rawValues = try container.decode([String: Value].self)
var values: [Key: Value] = [:]
values.reserveCapacity(rawValues.count)
for (key, value) in rawValues {
values[Key(wireValue: key)] = value
}
self.values = values
}
public func encode(to encoder: Encoder) throws {
let rawValues = Dictionary(uniqueKeysWithValues: values.map { ($0.key.wireValue, $0.value) })
var container = encoder.singleValueContainer()
try container.encode(rawValues)
}
}
public struct WebRPCHTTPResponse: Sendable {
public let statusCode: Int
public let body: Data
public let headers: [String: String]
public init(
statusCode: Int,
body: Data,
headers: [String: String] = [:]
) {
self.statusCode = statusCode
self.body = body
self.headers = headers
}
}
public protocol WebRPCTransport: Sendable {
func post(
baseURL: String,
path: String,
body: Data,
headers: [String: String]
) async throws -> WebRPCHTTPResponse
}
public struct WebRPCTransportError: Error, Sendable {
public let message: String
public let underlyingDescription: String?
public init(message: String, underlyingDescription: String? = nil) {
self.message = message
self.underlyingDescription = underlyingDescription
}
}
public struct URLSessionWebRPCTransport: WebRPCTransport, @unchecked Sendable {
public let session: URLSession
public init(session: URLSession = .shared) {
self.session = session
}
public func post(
baseURL: String,
path: String,
body: Data,
headers: [String: String]
) async throws -> WebRPCHTTPResponse {
guard let url = URL(string: joinWebRPCURL(baseURL: baseURL, path: path)) else {
throw WebRPCTransportError(message: "Invalid WebRPC URL")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
for (name, value) in headers {
request.setValue(value, forHTTPHeaderField: name)
}
do {
let (data, response) = try await session.data(for: request)
let httpResponse = response as? HTTPURLResponse
let responseHeaders = (httpResponse?.allHeaderFields ?? [:]).reduce(into: [String: String]()) { result, item in
guard let key = item.key as? String else {
return
}
result[key] = String(describing: item.value)
}
return WebRPCHTTPResponse(
statusCode: httpResponse?.statusCode ?? 0,
body: data,
headers: responseHeaders,
)
} catch is CancellationError {
throw CancellationError()
} catch {
throw WebRPCTransportError(
message: "WebRPC HTTP request failed",
underlyingDescription: String(describing: error),
)
}
}
}
private func joinWebRPCURL(baseURL: String, path: String) -> String {
baseURL.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/" + path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
}
public func executeWebRPC<Response>(
baseURL: String,
urlPath: String,
body: Data,
transport: any WebRPCTransport,
headers: [String: String] = [:],
decodeSuccess: (Data, JSONDecoder) throws -> Response
) async throws -> Response {
let response: WebRPCHTTPResponse
do {
response = try await transport.post(
baseURL: baseURL,
path: urlPath,
body: body,
headers: headers,
)
} catch is CancellationError {
throw CancellationError()
} catch let error as WebRPCTransportError {
throw error
} catch {
throw WebRPCTransportError(
message: "WebRPC request failed",
underlyingDescription: String(describing: error),
)
}
guard (200...299).contains(response.statusCode) else {
throw decodeWebRPCError(statusCode: response.statusCode, data: response.body)
}
do {
return try decodeSuccess(response.body, WebRPCJSON.makeDecoder())
} catch let error as WebRPCError {
throw error
} catch {
throw webRPCBadResponseError(
statusCode: response.statusCode,
data: response.body,
cause: String(describing: error)
)
}
}
public enum WebRPCErrorKind: Sendable {
{{- range $_, $error := $webrpcErrors}}
case {{template "swiftLowerCamel" dict "Name" $error.Name}}
{{- end}}
{{- range $_, $error := $schemaErrors}}
case {{template "swiftLowerCamel" dict "Name" $error.Name}}
{{- end}}
case unknown
public var code: Int {
switch self {
{{- range $_, $error := $webrpcErrors}}
case .{{template "swiftLowerCamel" dict "Name" $error.Name}}:
return {{$error.Code}}
{{- end}}
{{- range $_, $error := $schemaErrors}}
case .{{template "swiftLowerCamel" dict "Name" $error.Name}}:
return {{$error.Code}}
{{- end}}
case .unknown:
return -999
}
}
public static func fromCode(_ code: Int) -> WebRPCErrorKind {
switch code {
{{- range $_, $error := $webrpcErrors}}
case {{$error.Code}}:
return .{{template "swiftLowerCamel" dict "Name" $error.Name}}
{{- end}}
{{- range $_, $error := $schemaErrors}}
case {{$error.Code}}:
return .{{template "swiftLowerCamel" dict "Name" $error.Name}}
{{- end}}
default:
return .unknown
}
}
}
public struct WebRPCError: Error, Sendable {
public let error: String
public let code: Int
public let message: String
public let cause: String
public let status: Int
public let kind: WebRPCErrorKind
public init(
error: String,
code: Int,
message: String,
cause: String,
status: Int,
kind: WebRPCErrorKind
) {
self.error = error
self.code = code
self.message = message
self.cause = cause
self.status = status
self.kind = kind
}
}
private struct WebRPCErrorPayload: Decodable, Sendable {
let error: String?
let code: Int?
let msg: String?
let cause: String?
let status: Int?
}
public func decodeWebRPCError(
statusCode: Int,
data: Data,
decoder: JSONDecoder = WebRPCJSON.makeDecoder()
) -> WebRPCError {
do {
let payload = try decoder.decode(WebRPCErrorPayload.self, from: data)
let code = payload.code ?? WebRPCErrorKind.unknown.code
return WebRPCError(
error: payload.error ?? "WebrpcEndpoint",
code: code,
message: payload.msg ?? "endpoint error",
cause: payload.cause ?? "",
status: payload.status ?? statusCode,
kind: WebRPCErrorKind.fromCode(code),
)
} catch {
return webRPCBadResponseError(
statusCode: statusCode,
data: data,
cause: "Unable to decode error response"
)
}
}
private func webRPCBadResponseError(
statusCode: Int,
data: Data,
cause: String
) -> WebRPCError {
let bodyText = String(data: data, encoding: .utf8) ?? "<non-utf8 body>"
return WebRPCError(
error: "WebrpcBadResponse",
code: WebRPCErrorKind.webrpcBadResponse.code,
message: "bad response",
cause: "\(cause): \(bodyText)",
status: statusCode,
kind: .webrpcBadResponse
)
}
{{end}}