2
0

GRPCClient.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. * Copyright 2023, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. private import Synchronization
  17. /// A gRPC client.
  18. ///
  19. /// A ``GRPCClient`` communicates to a server via a ``ClientTransport``.
  20. ///
  21. /// You can start RPCs to the server by calling the corresponding method:
  22. /// - ``unary(request:descriptor:serializer:deserializer:options:handler:)``
  23. /// - ``clientStreaming(request:descriptor:serializer:deserializer:options:handler:)``
  24. /// - ``serverStreaming(request:descriptor:serializer:deserializer:options:handler:)``
  25. /// - ``bidirectionalStreaming(request:descriptor:serializer:deserializer:options:handler:)``
  26. ///
  27. /// However, in most cases you should prefer wrapping the ``GRPCClient`` with a generated stub.
  28. ///
  29. /// You can set ``ServiceConfig``s on this client to override whatever configurations have been
  30. /// set on the given transport. You can also use ``ClientInterceptor``s to implement cross-cutting
  31. /// logic which apply to all RPCs. Example uses of interceptors include authentication and logging.
  32. ///
  33. /// ## Creating and configuring a client
  34. ///
  35. /// The following example demonstrates how to create and configure a client.
  36. ///
  37. /// ```swift
  38. /// // Create a configuration object for the client and override the timeout for the 'Get' method on
  39. /// // the 'echo.Echo' service. This configuration takes precedence over any set by the transport.
  40. /// var configuration = GRPCClient.Configuration()
  41. /// configuration.service.override = ServiceConfig(
  42. /// methodConfig: [
  43. /// MethodConfig(
  44. /// names: [
  45. /// MethodConfig.Name(service: "echo.Echo", method: "Get")
  46. /// ],
  47. /// timeout: .seconds(5)
  48. /// )
  49. /// ]
  50. /// )
  51. ///
  52. /// // Configure a fallback timeout for all RPCs (indicated by an empty service and method name) if
  53. /// // no configuration is provided in the overrides or by the transport.
  54. /// configuration.service.defaults = ServiceConfig(
  55. /// methodConfig: [
  56. /// MethodConfig(
  57. /// names: [
  58. /// MethodConfig.Name(service: "", method: "")
  59. /// ],
  60. /// timeout: .seconds(10)
  61. /// )
  62. /// ]
  63. /// )
  64. ///
  65. /// // Finally create a transport and instantiate the client, adding an interceptor.
  66. /// let inProcessTransport = InProcessTransport()
  67. ///
  68. /// let client = GRPCClient(
  69. /// transport: inProcessTransport.client,
  70. /// interceptors: [StatsRecordingClientInterceptor()],
  71. /// configuration: configuration
  72. /// )
  73. /// ```
  74. ///
  75. /// ## Starting and stopping the client
  76. ///
  77. /// Once you have configured the client, call ``run()`` to start it. Calling ``run()`` instructs the
  78. /// transport to start connecting to the server.
  79. ///
  80. /// ```swift
  81. /// // Start running the client. 'run()' must be running while RPCs are execute so it's executed in
  82. /// // a task group.
  83. /// try await withThrowingTaskGroup(of: Void.self) { group in
  84. /// group.addTask {
  85. /// try await client.run()
  86. /// }
  87. ///
  88. /// // Execute a request against the "echo.Echo" service.
  89. /// try await client.unary(
  90. /// request: ClientRequest<[UInt8]>(message: [72, 101, 108, 108, 111, 33]),
  91. /// descriptor: MethodDescriptor(service: "echo.Echo", method: "Get"),
  92. /// serializer: IdentitySerializer(),
  93. /// deserializer: IdentityDeserializer(),
  94. /// ) { response in
  95. /// print(response.message)
  96. /// }
  97. ///
  98. /// // The RPC has completed, close the client.
  99. /// client.beginGracefulShutdown()
  100. /// }
  101. /// ```
  102. ///
  103. /// The ``run()`` method won't return until the client has finished handling all requests. You can
  104. /// signal to the client that it should stop creating new request streams by calling ``beginGracefulShutdown()``.
  105. /// This gives the client enough time to drain any requests already in flight. To stop the client
  106. /// more abruptly you can cancel the task running your client. If your application requires
  107. /// additional resources that need their lifecycles managed you should consider using [Swift Service
  108. /// Lifecycle](https://github.com/swift-server/swift-service-lifecycle).
  109. public final class GRPCClient: Sendable {
  110. /// The transport which provides a bidirectional communication channel with the server.
  111. private let transport: any ClientTransport
  112. /// A collection of interceptors providing cross-cutting functionality to each accepted RPC.
  113. ///
  114. /// The order in which interceptors are added reflects the order in which they are called. The
  115. /// first interceptor added will be the first interceptor to intercept each request. The last
  116. /// interceptor added will be the final interceptor to intercept each request before calling
  117. /// the appropriate handler.
  118. private let interceptors: [any ClientInterceptor]
  119. /// The current state of the client.
  120. private let state: Mutex<State>
  121. /// The state of the client.
  122. private enum State: Sendable {
  123. /// The client hasn't been started yet. Can transition to `running` or `stopped`.
  124. case notStarted
  125. /// The client is running and can send RPCs. Can transition to `stopping`.
  126. case running
  127. /// The client is stopping and no new RPCs will be sent. Existing RPCs may run to
  128. /// completion. May transition to `stopped`.
  129. case stopping
  130. /// The client has stopped, no RPCs are in flight and no more will be accepted. This state
  131. /// is terminal.
  132. case stopped
  133. mutating func run() throws {
  134. switch self {
  135. case .notStarted:
  136. self = .running
  137. case .running:
  138. throw RuntimeError(
  139. code: .clientIsAlreadyRunning,
  140. message: "The client is already running and can only be started once."
  141. )
  142. case .stopping, .stopped:
  143. throw RuntimeError(
  144. code: .clientIsStopped,
  145. message: "The client has stopped and can only be started once."
  146. )
  147. }
  148. }
  149. mutating func stopped() {
  150. self = .stopped
  151. }
  152. mutating func beginGracefulShutdown() -> Bool {
  153. switch self {
  154. case .notStarted:
  155. self = .stopped
  156. return false
  157. case .running:
  158. self = .stopping
  159. return true
  160. case .stopping, .stopped:
  161. return false
  162. }
  163. }
  164. func checkExecutable() throws {
  165. switch self {
  166. case .notStarted, .running:
  167. // Allow .notStarted as making a request can race with 'run()'. Transports should tolerate
  168. // queuing the request if not yet started.
  169. ()
  170. case .stopping, .stopped:
  171. throw RuntimeError(
  172. code: .clientIsStopped,
  173. message: "Client has been stopped. Can't make any more RPCs."
  174. )
  175. }
  176. }
  177. }
  178. /// Creates a new client with the given transport, interceptors and configuration.
  179. ///
  180. /// - Parameters:
  181. /// - transport: The transport used to establish a communication channel with a server.
  182. /// - interceptors: A collection of interceptors providing cross-cutting functionality to each
  183. /// accepted RPC. The order in which interceptors are added reflects the order in which they
  184. /// are called. The first interceptor added will be the first interceptor to intercept each
  185. /// request. The last interceptor added will be the final interceptor to intercept each
  186. /// request before calling the appropriate handler.
  187. public init(
  188. transport: some ClientTransport,
  189. interceptors: [any ClientInterceptor] = []
  190. ) {
  191. self.transport = transport
  192. self.interceptors = interceptors
  193. self.state = Mutex(.notStarted)
  194. }
  195. /// Start the client.
  196. ///
  197. /// This returns once ``beginGracefulShutdown()`` has been called and all in-flight RPCs have finished executing.
  198. /// If you need to abruptly stop all work you should cancel the task executing this method.
  199. ///
  200. /// The client, and by extension this function, can only be run once. If the client is already
  201. /// running or has already been closed then a ``RuntimeError`` is thrown.
  202. public func run() async throws {
  203. try self.state.withLock { try $0.run() }
  204. // When this function exits the client must have stopped.
  205. defer {
  206. self.state.withLock { $0.stopped() }
  207. }
  208. do {
  209. try await self.transport.connect()
  210. } catch {
  211. throw RuntimeError(
  212. code: .transportError,
  213. message: "The transport threw an error while connected.",
  214. cause: error
  215. )
  216. }
  217. }
  218. /// Close the client.
  219. ///
  220. /// The transport will be closed: this means that it will be given enough time to wait for
  221. /// in-flight RPCs to finish executing, but no new RPCs will be accepted. You can cancel the task
  222. /// executing ``run()`` if you want to abruptly stop in-flight RPCs.
  223. public func beginGracefulShutdown() {
  224. let wasRunning = self.state.withLock { $0.beginGracefulShutdown() }
  225. if wasRunning {
  226. self.transport.beginGracefulShutdown()
  227. }
  228. }
  229. /// Executes a unary RPC.
  230. ///
  231. /// - Parameters:
  232. /// - request: The unary request.
  233. /// - descriptor: The method descriptor for which to execute this request.
  234. /// - serializer: A request serializer.
  235. /// - deserializer: A response deserializer.
  236. /// - options: Call specific options.
  237. /// - handler: A unary response handler.
  238. ///
  239. /// - Returns: The return value from the `handler`.
  240. public func unary<Request, Response, ReturnValue: Sendable>(
  241. request: ClientRequest<Request>,
  242. descriptor: MethodDescriptor,
  243. serializer: some MessageSerializer<Request>,
  244. deserializer: some MessageDeserializer<Response>,
  245. options: CallOptions,
  246. handler: @Sendable @escaping (ClientResponse<Response>) async throws -> ReturnValue
  247. ) async throws -> ReturnValue {
  248. try await self.bidirectionalStreaming(
  249. request: StreamingClientRequest(single: request),
  250. descriptor: descriptor,
  251. serializer: serializer,
  252. deserializer: deserializer,
  253. options: options
  254. ) { stream in
  255. let singleResponse = await ClientResponse(stream: stream)
  256. return try await handler(singleResponse)
  257. }
  258. }
  259. /// Start a client-streaming RPC.
  260. ///
  261. /// - Parameters:
  262. /// - request: The request stream.
  263. /// - descriptor: The method descriptor for which to execute this request.
  264. /// - serializer: A request serializer.
  265. /// - deserializer: A response deserializer.
  266. /// - options: Call specific options.
  267. /// - handler: A unary response handler.
  268. ///
  269. /// - Returns: The return value from the `handler`.
  270. public func clientStreaming<Request, Response, ReturnValue: Sendable>(
  271. request: StreamingClientRequest<Request>,
  272. descriptor: MethodDescriptor,
  273. serializer: some MessageSerializer<Request>,
  274. deserializer: some MessageDeserializer<Response>,
  275. options: CallOptions,
  276. handler: @Sendable @escaping (ClientResponse<Response>) async throws -> ReturnValue
  277. ) async throws -> ReturnValue {
  278. try await self.bidirectionalStreaming(
  279. request: request,
  280. descriptor: descriptor,
  281. serializer: serializer,
  282. deserializer: deserializer,
  283. options: options
  284. ) { stream in
  285. let singleResponse = await ClientResponse(stream: stream)
  286. return try await handler(singleResponse)
  287. }
  288. }
  289. /// Start a server-streaming RPC.
  290. ///
  291. /// - Parameters:
  292. /// - request: The unary request.
  293. /// - descriptor: The method descriptor for which to execute this request.
  294. /// - serializer: A request serializer.
  295. /// - deserializer: A response deserializer.
  296. /// - options: Call specific options.
  297. /// - handler: A response stream handler.
  298. ///
  299. /// - Returns: The return value from the `handler`.
  300. public func serverStreaming<Request, Response, ReturnValue: Sendable>(
  301. request: ClientRequest<Request>,
  302. descriptor: MethodDescriptor,
  303. serializer: some MessageSerializer<Request>,
  304. deserializer: some MessageDeserializer<Response>,
  305. options: CallOptions,
  306. handler: @Sendable @escaping (StreamingClientResponse<Response>) async throws -> ReturnValue
  307. ) async throws -> ReturnValue {
  308. try await self.bidirectionalStreaming(
  309. request: StreamingClientRequest(single: request),
  310. descriptor: descriptor,
  311. serializer: serializer,
  312. deserializer: deserializer,
  313. options: options,
  314. handler: handler
  315. )
  316. }
  317. /// Start a bidirectional streaming RPC.
  318. ///
  319. /// - Note: ``run()`` must have been called and still executing, and ``beginGracefulShutdown()`` mustn't
  320. /// have been called.
  321. ///
  322. /// - Parameters:
  323. /// - request: The streaming request.
  324. /// - descriptor: The method descriptor for which to execute this request.
  325. /// - serializer: A request serializer.
  326. /// - deserializer: A response deserializer.
  327. /// - options: Call specific options.
  328. /// - handler: A response stream handler.
  329. ///
  330. /// - Returns: The return value from the `handler`.
  331. public func bidirectionalStreaming<Request, Response, ReturnValue: Sendable>(
  332. request: StreamingClientRequest<Request>,
  333. descriptor: MethodDescriptor,
  334. serializer: some MessageSerializer<Request>,
  335. deserializer: some MessageDeserializer<Response>,
  336. options: CallOptions,
  337. handler: @Sendable @escaping (StreamingClientResponse<Response>) async throws -> ReturnValue
  338. ) async throws -> ReturnValue {
  339. try self.state.withLock { try $0.checkExecutable() }
  340. let methodConfig = self.transport.config(forMethod: descriptor)
  341. var options = options
  342. options.formUnion(with: methodConfig)
  343. return try await ClientRPCExecutor.execute(
  344. request: request,
  345. method: descriptor,
  346. options: options,
  347. serializer: serializer,
  348. deserializer: deserializer,
  349. transport: self.transport,
  350. interceptors: self.interceptors,
  351. handler: handler
  352. )
  353. }
  354. }