forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServerRPCExecutor.swift
333 lines (307 loc) · 10.6 KB
/
ServerRPCExecutor.swift
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
/*
* Copyright 2023, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@usableFromInline
struct ServerRPCExecutor {
/// Executes an RPC using the provided handler.
///
/// - Parameters:
/// - context: The context for the RPC.
/// - stream: The accepted stream to execute the RPC on.
/// - deserializer: A deserializer for messages received from the client.
/// - serializer: A serializer for messages to send to the client.
/// - interceptors: Server interceptors to apply to this RPC.
/// - handler: A handler which turns the request into a response.
@inlinable
static func execute<Input, Output>(
context: ServerContext,
stream: RPCStream<
RPCAsyncSequence<RPCRequestPart, any Error>,
RPCWriter<RPCResponsePart>.Closable
>,
deserializer: some MessageDeserializer<Input>,
serializer: some MessageSerializer<Output>,
interceptors: [any ServerInterceptor],
handler: @Sendable @escaping (
_ request: StreamingServerRequest<Input>,
_ context: ServerContext
) async throws -> StreamingServerResponse<Output>
) async {
// Wait for the first request part from the transport.
let firstPart = await Self._waitForFirstRequestPart(inbound: stream.inbound)
switch firstPart {
case .process(let metadata, let inbound):
await Self._execute(
context: context,
metadata: metadata,
inbound: inbound,
outbound: stream.outbound,
deserializer: deserializer,
serializer: serializer,
interceptors: interceptors,
handler: handler
)
case .reject(let error):
// Stream can't be handled; write an error status and close.
let status = Status(code: Status.Code(error.code), message: error.message)
try? await stream.outbound.write(.status(status, error.metadata))
await stream.outbound.finish()
}
}
@inlinable
static func _execute<Input, Output>(
context: ServerContext,
metadata: Metadata,
inbound: UnsafeTransfer<RPCAsyncSequence<RPCRequestPart, any Error>.AsyncIterator>,
outbound: RPCWriter<RPCResponsePart>.Closable,
deserializer: some MessageDeserializer<Input>,
serializer: some MessageSerializer<Output>,
interceptors: [any ServerInterceptor],
handler: @escaping @Sendable (
_ request: StreamingServerRequest<Input>,
_ context: ServerContext
) async throws -> StreamingServerResponse<Output>
) async {
if let timeout = metadata.timeout {
await Self._processRPCWithTimeout(
timeout: timeout,
context: context,
metadata: metadata,
inbound: inbound,
outbound: outbound,
deserializer: deserializer,
serializer: serializer,
interceptors: interceptors,
handler: handler
)
} else {
await Self._processRPC(
context: context,
metadata: metadata,
inbound: inbound,
outbound: outbound,
deserializer: deserializer,
serializer: serializer,
interceptors: interceptors,
handler: handler
)
}
}
@inlinable
static func _processRPCWithTimeout<Input, Output>(
timeout: Duration,
context: ServerContext,
metadata: Metadata,
inbound: UnsafeTransfer<RPCAsyncSequence<RPCRequestPart, any Error>.AsyncIterator>,
outbound: RPCWriter<RPCResponsePart>.Closable,
deserializer: some MessageDeserializer<Input>,
serializer: some MessageSerializer<Output>,
interceptors: [any ServerInterceptor],
handler: @escaping @Sendable (
_ request: StreamingServerRequest<Input>,
_ context: ServerContext
) async throws -> StreamingServerResponse<Output>
) async {
await withTaskGroup(of: Void.self) { group in
group.addTask {
do {
try await Task.sleep(for: timeout, clock: .continuous)
context.cancellation.cancel()
} catch {
() // Only cancel the RPC if the timeout completes.
}
}
await Self._processRPC(
context: context,
metadata: metadata,
inbound: inbound,
outbound: outbound,
deserializer: deserializer,
serializer: serializer,
interceptors: interceptors,
handler: handler
)
// Cancel the timeout
group.cancelAll()
}
}
@inlinable
static func _processRPC<Input, Output>(
context: ServerContext,
metadata: Metadata,
inbound: UnsafeTransfer<RPCAsyncSequence<RPCRequestPart, any Error>.AsyncIterator>,
outbound: RPCWriter<RPCResponsePart>.Closable,
deserializer: some MessageDeserializer<Input>,
serializer: some MessageSerializer<Output>,
interceptors: [any ServerInterceptor],
handler: @escaping @Sendable (
_ request: StreamingServerRequest<Input>,
_ context: ServerContext
) async throws -> StreamingServerResponse<Output>
) async {
let messages = UncheckedAsyncIteratorSequence(inbound.wrappedValue).map { part in
switch part {
case .message(let bytes):
return try deserializer.deserialize(bytes)
case .metadata:
throw RPCError(
code: .internalError,
message: """
Server received an extra set of metadata. Only one set of metadata may be received \
at the start of the RPC. This is likely to be caused by a misbehaving client.
"""
)
}
}
let response = await Result {
// Run the request through the interceptors, finally passing it to the handler.
return try await Self._intercept(
request: StreamingServerRequest(
metadata: metadata,
messages: RPCAsyncSequence(wrapping: messages)
),
context: context,
interceptors: interceptors
) { request, context in
try await handler(request, context)
}
}.castError(to: RPCError.self) { error in
RPCError(code: .unknown, message: "Service method threw an unknown error.", cause: error)
}.flatMap { response in
response.accepted
}
let status: Status
let metadata: Metadata
switch response {
case .success(let contents):
let result = await Result {
// Write the metadata and run the producer.
try await outbound.write(.metadata(contents.metadata))
return try await contents.producer(
.serializingToRPCResponsePart(into: outbound, with: serializer)
)
}.castError(to: RPCError.self) { error in
RPCError(code: .unknown, message: "", cause: error)
}
switch result {
case .success(let trailingMetadata):
status = .ok
metadata = trailingMetadata
case .failure(let error):
status = Status(code: Status.Code(error.code), message: error.message)
metadata = error.metadata
}
case .failure(let error):
status = Status(code: Status.Code(error.code), message: error.message)
metadata = error.metadata
}
try? await outbound.write(.status(status, metadata))
await outbound.finish()
}
@inlinable
static func _waitForFirstRequestPart(
inbound: RPCAsyncSequence<RPCRequestPart, any Error>
) async -> OnFirstRequestPart {
var iterator = inbound.makeAsyncIterator()
let part = await Result { try await iterator.next() }
let onFirstRequestPart: OnFirstRequestPart
switch part {
case .success(.metadata(let metadata)):
// The only valid first part.
onFirstRequestPart = .process(metadata, UnsafeTransfer(iterator))
case .success(.none):
// Empty stream; reject.
let error = RPCError(code: .internalError, message: "Empty inbound server stream.")
onFirstRequestPart = .reject(error)
case .success(.message):
let error = RPCError(
code: .internalError,
message: """
Invalid inbound server stream; received message bytes at start of stream. This is \
likely to be a transport specific bug.
"""
)
onFirstRequestPart = .reject(error)
case .failure(let error):
let error = RPCError(
code: .unknown,
message: "Inbound server stream threw error when reading metadata.",
cause: error
)
onFirstRequestPart = .reject(error)
}
return onFirstRequestPart
}
@usableFromInline
enum OnFirstRequestPart {
case process(
Metadata,
UnsafeTransfer<RPCAsyncSequence<RPCRequestPart, any Error>.AsyncIterator>
)
case reject(RPCError)
}
@usableFromInline
enum ServerExecutorTask: Sendable {
case timedOut(Result<Void, any Error>)
case executed
}
}
extension ServerRPCExecutor {
@inlinable
static func _intercept<Input, Output>(
request: StreamingServerRequest<Input>,
context: ServerContext,
interceptors: [any ServerInterceptor],
finally: @escaping @Sendable (
_ request: StreamingServerRequest<Input>,
_ context: ServerContext
) async throws -> StreamingServerResponse<Output>
) async throws -> StreamingServerResponse<Output> {
return try await self._intercept(
request: request,
context: context,
iterator: interceptors.makeIterator(),
finally: finally
)
}
@inlinable
static func _intercept<Input, Output>(
request: StreamingServerRequest<Input>,
context: ServerContext,
iterator: Array<any ServerInterceptor>.Iterator,
finally: @escaping @Sendable (
_ request: StreamingServerRequest<Input>,
_ context: ServerContext
) async throws -> StreamingServerResponse<Output>
) async throws -> StreamingServerResponse<Output> {
var iterator = iterator
switch iterator.next() {
case .some(let interceptor):
let iter = iterator
do {
return try await interceptor.intercept(request: request, context: context) {
try await self._intercept(request: $0, context: $1, iterator: iter, finally: finally)
}
} catch let error as RPCError {
return StreamingServerResponse(error: error)
} catch let other {
let error = RPCError(code: .unknown, message: "", cause: other)
return StreamingServerResponse(error: error)
}
case .none:
return try await finally(request, context)
}
}
}