forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGRPCServer.swift
312 lines (289 loc) · 12.1 KB
/
GRPCServer.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
/*
* 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.
*/
private import Synchronization
/// A gRPC server.
///
/// The server accepts connections from clients and listens on each connection for new streams
/// which are initiated by the client. Each stream maps to a single RPC. The server routes accepted
/// streams to a service to handle the RPC or rejects them with an appropriate error if no service
/// can handle the RPC.
///
/// A ``GRPCServer`` listens with a specific transport implementation (for example, HTTP/2 or in-process),
/// and routes requests from the transport to the service instance. You can also use "interceptors",
/// to implement cross-cutting logic which apply to all accepted RPCs. Example uses of interceptors
/// include request filtering, authentication, and logging. Once requests have been intercepted
/// they are passed to a handler which in turn returns a response to send back to the client.
///
/// ## Configuring and starting a server
///
/// The following example demonstrates how to create and run a server.
///
/// ```swift
/// // Create an transport
/// let transport: any ServerTransport = ...
///
/// // Create the 'Greeter' and 'Echo' services.
/// let greeter = GreeterService()
/// let echo = EchoService()
///
/// // Create an interceptor.
/// let statsRecorder = StatsRecordingServerInterceptors()
///
/// // Run the server.
/// try await withGRPCServer(
/// transport: transport,
/// services: [greeter, echo],
/// interceptors: [statsRecorder]
/// ) { server in
/// // ...
/// // The server begins shutting down when this closure returns
/// // ...
/// }
/// ```
///
/// ## Creating a client manually
///
/// If the `with`-style methods for creating a server isn't suitable for your application then you
/// can create and run it manually. This requires you to call the ``serve()`` method in a task
/// which instructs the server to start its transport and listen for new RPCs. A ``RuntimeError`` is
/// thrown if the transport can't be started or encounters some other runtime error.
///
/// ```swift
/// // Start running the server.
/// try await server.serve()
/// ```
///
/// The ``serve()`` method won't return until the server has finished handling all requests. You can
/// signal to the server that it should stop accepting new requests by calling ``beginGracefulShutdown()``.
/// This allows the server to drain existing requests gracefully. To stop the server more abruptly
/// you can cancel the task running your server. If your application requires additional resources
/// that need their lifecycles managed you should consider using [Swift Service
/// Lifecycle](https://github.com/swift-server/swift-service-lifecycle).
public final class GRPCServer: Sendable {
typealias Stream = RPCStream<ServerTransport.Inbound, ServerTransport.Outbound>
/// The ``ServerTransport`` implementation that the server uses to listen for new requests.
public let transport: any ServerTransport
/// The services registered which the server is serving.
private let router: RPCRouter
/// The state of the server.
private let state: Mutex<State>
private enum State: Sendable {
/// The server hasn't been started yet. Can transition to `running` or `stopped`.
case notStarted
/// The server is running and accepting RPCs. Can transition to `stopping`.
case running
/// The server is stopping and no new RPCs will be accepted. Existing RPCs may run to
/// completion. May transition to `stopped`.
case stopping
/// The server has stopped, no RPCs are in flight and no more will be accepted. This state
/// is terminal.
case stopped
mutating func startServing() throws {
switch self {
case .notStarted:
self = .running
case .running:
throw RuntimeError(
code: .serverIsAlreadyRunning,
message: "The server is already running and can only be started once."
)
case .stopping, .stopped:
throw RuntimeError(
code: .serverIsStopped,
message: "The server has stopped and can only be started once."
)
}
}
mutating func beginGracefulShutdown() -> Bool {
switch self {
case .notStarted:
self = .stopped
return false
case .running:
self = .stopping
return true
case .stopping, .stopped:
// Already stopping/stopped, ignore.
return false
}
}
mutating func stopped() {
self = .stopped
}
}
/// Creates a new server with no resources.
///
/// - Parameters:
/// - transport: The transport the server should listen on.
/// - services: Services offered by the server.
/// - interceptors: A collection of interceptors providing cross-cutting functionality to each
/// accepted RPC. The order in which interceptors are added reflects the order in which they
/// are called. The first interceptor added will be the first interceptor to intercept each
/// request. The last interceptor added will be the final interceptor to intercept each
/// request before calling the appropriate handler.
public convenience init(
transport: any ServerTransport,
services: [any RegistrableRPCService],
interceptors: [any ServerInterceptor] = []
) {
self.init(
transport: transport,
services: services,
interceptorPipeline: interceptors.map { .apply($0, to: .all) }
)
}
/// Creates a new server with no resources.
///
/// - Parameters:
/// - transport: The transport the server should listen on.
/// - services: Services offered by the server.
/// - interceptorPipeline: A collection of interceptors providing cross-cutting functionality to each
/// accepted RPC. The order in which interceptors are added reflects the order in which they
/// are called. The first interceptor added will be the first interceptor to intercept each
/// request. The last interceptor added will be the final interceptor to intercept each
/// request before calling the appropriate handler.
public convenience init(
transport: any ServerTransport,
services: [any RegistrableRPCService],
interceptorPipeline: [ServerInterceptorPipelineOperation]
) {
var router = RPCRouter()
for service in services {
service.registerMethods(with: &router)
}
router.registerInterceptors(pipeline: interceptorPipeline)
self.init(transport: transport, router: router)
}
/// Creates a new server with no resources.
///
/// - Parameters:
/// - transport: The transport the server should listen on.
/// - router: A ``RPCRouter`` used by the server to route accepted streams to method handlers.
public init(transport: any ServerTransport, router: RPCRouter) {
self.state = Mutex(.notStarted)
self.transport = transport
self.router = router
}
/// Starts the server and runs until the registered transport has closed.
///
/// No RPCs are processed until the configured transport is listening. If the transport fails to start
/// listening, or if it encounters a runtime error, then ``RuntimeError`` is thrown.
///
/// This function returns when the configured transport has stopped listening and all requests have been
/// handled. You can signal to the transport that it should stop listening by calling
/// ``beginGracefulShutdown()``. The server will continue to process existing requests.
///
/// To stop the server more abruptly you can cancel the task that this function is running in.
///
/// - Note: You can only call this function once, repeated calls will result in a
/// ``RuntimeError`` being thrown.
public func serve() async throws {
try self.state.withLock { try $0.startServing() }
// When we exit this function the server must have stopped.
defer {
self.state.withLock { $0.stopped() }
}
do {
try await transport.listen { stream, context in
await self.router.handle(stream: stream, context: context)
}
} catch {
throw RuntimeError(
code: .transportError,
message: "Server transport threw an error.",
cause: error
)
}
}
/// Signal to the server that it should stop listening for new requests.
///
/// By calling this function you indicate to clients that they mustn't start new requests
/// against this server. Once the server has processed all requests the ``serve()`` method returns.
///
/// Calling this on a server which is already stopping or has stopped has no effect.
public func beginGracefulShutdown() {
let wasRunning = self.state.withLock { $0.beginGracefulShutdown() }
if wasRunning {
self.transport.beginGracefulShutdown()
}
}
}
/// Creates and runs a gRPC server.
///
/// - Parameters:
/// - transport: The transport the server should listen on.
/// - services: Services offered by the server.
/// - interceptors: A collection of interceptors providing cross-cutting functionality to each
/// accepted RPC. The order in which interceptors are added reflects the order in which they
/// are called. The first interceptor added will be the first interceptor to intercept each
/// request. The last interceptor added will be the final interceptor to intercept each
/// request before calling the appropriate handler.
/// - isolation: A reference to the actor to which the enclosing code is isolated, or nil if the
/// code is nonisolated.
/// - handleServer: A closure which is called with the server. When the closure returns, the
/// server is shutdown gracefully.
/// - Returns: The result of the `handleServer` closure.
public func withGRPCServer<Result: Sendable>(
transport: any ServerTransport,
services: [any RegistrableRPCService],
interceptors: [any ServerInterceptor] = [],
isolation: isolated (any Actor)? = #isolation,
handleServer: (GRPCServer) async throws -> Result
) async throws -> Result {
try await withGRPCServer(
transport: transport,
services: services,
interceptorPipeline: interceptors.map { .apply($0, to: .all) },
isolation: isolation,
handleServer: handleServer
)
}
/// Creates and runs a gRPC server.
///
/// - Parameters:
/// - transport: The transport the server should listen on.
/// - services: Services offered by the server.
/// - interceptorPipeline: A collection of interceptors providing cross-cutting functionality to each
/// accepted RPC. The order in which interceptors are added reflects the order in which they
/// are called. The first interceptor added will be the first interceptor to intercept each
/// request. The last interceptor added will be the final interceptor to intercept each
/// request before calling the appropriate handler.
/// - isolation: A reference to the actor to which the enclosing code is isolated, or nil if the
/// code is nonisolated.
/// - handleServer: A closure which is called with the server. When the closure returns, the
/// server is shutdown gracefully.
/// - Returns: The result of the `handleServer` closure.
public func withGRPCServer<Result: Sendable>(
transport: any ServerTransport,
services: [any RegistrableRPCService],
interceptorPipeline: [ServerInterceptorPipelineOperation],
isolation: isolated (any Actor)? = #isolation,
handleServer: (GRPCServer) async throws -> Result
) async throws -> Result {
return try await withThrowingDiscardingTaskGroup { group in
let server = GRPCServer(
transport: transport,
services: services,
interceptorPipeline: interceptorPipeline
)
group.addTask {
try await server.serve()
}
let result = try await handleServer(server)
server.beginGracefulShutdown()
return result
}
}