GRPCClient.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  110. public final class GRPCClient: Sendable {
  111. /// The transport which provides a bidirectional communication channel with the server.
  112. private let transport: any ClientTransport
  113. /// A collection of interceptors providing cross-cutting functionality to each accepted RPC.
  114. ///
  115. /// The order in which interceptors are added reflects the order in which they are called. The
  116. /// first interceptor added will be the first interceptor to intercept each request. The last
  117. /// interceptor added will be the final interceptor to intercept each request before calling
  118. /// the appropriate handler.
  119. private let interceptors: [any ClientInterceptor]
  120. /// The current state of the client.
  121. private let state: Mutex<State>
  122. /// The state of the client.
  123. private enum State: Sendable {
  124. /// The client hasn't been started yet. Can transition to `running` or `stopped`.
  125. case notStarted
  126. /// The client is running and can send RPCs. Can transition to `stopping`.
  127. case running
  128. /// The client is stopping and no new RPCs will be sent. Existing RPCs may run to
  129. /// completion. May transition to `stopped`.
  130. case stopping
  131. /// The client has stopped, no RPCs are in flight and no more will be accepted. This state
  132. /// is terminal.
  133. case stopped
  134. mutating func run() throws {
  135. switch self {
  136. case .notStarted:
  137. self = .running
  138. case .running:
  139. throw RuntimeError(
  140. code: .clientIsAlreadyRunning,
  141. message: "The client is already running and can only be started once."
  142. )
  143. case .stopping, .stopped:
  144. throw RuntimeError(
  145. code: .clientIsStopped,
  146. message: "The client has stopped and can only be started once."
  147. )
  148. }
  149. }
  150. mutating func stopped() {
  151. self = .stopped
  152. }
  153. mutating func beginGracefulShutdown() -> Bool {
  154. switch self {
  155. case .notStarted:
  156. self = .stopped
  157. return false
  158. case .running:
  159. self = .stopping
  160. return true
  161. case .stopping, .stopped:
  162. return false
  163. }
  164. }
  165. func checkExecutable() throws {
  166. switch self {
  167. case .notStarted, .running:
  168. // Allow .notStarted as making a request can race with 'run()'. Transports should tolerate
  169. // queuing the request if not yet started.
  170. ()
  171. case .stopping, .stopped:
  172. throw RuntimeError(
  173. code: .clientIsStopped,
  174. message: "Client has been stopped. Can't make any more RPCs."
  175. )
  176. }
  177. }
  178. }
  179. /// Creates a new client with the given transport, interceptors and configuration.
  180. ///
  181. /// - Parameters:
  182. /// - transport: The transport used to establish a communication channel with a server.
  183. /// - interceptors: A collection of interceptors providing cross-cutting functionality to each
  184. /// accepted RPC. The order in which interceptors are added reflects the order in which they
  185. /// are called. The first interceptor added will be the first interceptor to intercept each
  186. /// request. The last interceptor added will be the final interceptor to intercept each
  187. /// request before calling the appropriate handler.
  188. public init(
  189. transport: some ClientTransport,
  190. interceptors: [any ClientInterceptor] = []
  191. ) {
  192. self.transport = transport
  193. self.interceptors = interceptors
  194. self.state = Mutex(.notStarted)
  195. }
  196. /// Start the client.
  197. ///
  198. /// This returns once ``beginGracefulShutdown()`` has been called and all in-flight RPCs have finished executing.
  199. /// If you need to abruptly stop all work you should cancel the task executing this method.
  200. ///
  201. /// The client, and by extension this function, can only be run once. If the client is already
  202. /// running or has already been closed then a ``RuntimeError`` is thrown.
  203. public func run() async throws {
  204. try self.state.withLock { try $0.run() }
  205. // When this function exits the client must have stopped.
  206. defer {
  207. self.state.withLock { $0.stopped() }
  208. }
  209. do {
  210. try await self.transport.connect()
  211. } catch {
  212. throw RuntimeError(
  213. code: .transportError,
  214. message: "The transport threw an error while connected.",
  215. cause: error
  216. )
  217. }
  218. }
  219. /// Close the client.
  220. ///
  221. /// The transport will be closed: this means that it will be given enough time to wait for
  222. /// in-flight RPCs to finish executing, but no new RPCs will be accepted. You can cancel the task
  223. /// executing ``run()`` if you want to abruptly stop in-flight RPCs.
  224. public func beginGracefulShutdown() {
  225. let wasRunning = self.state.withLock { $0.beginGracefulShutdown() }
  226. if wasRunning {
  227. self.transport.beginGracefulShutdown()
  228. }
  229. }
  230. /// Executes a unary RPC.
  231. ///
  232. /// - Parameters:
  233. /// - request: The unary request.
  234. /// - descriptor: The method descriptor for which to execute this request.
  235. /// - serializer: A request serializer.
  236. /// - deserializer: A response deserializer.
  237. /// - options: Call specific options.
  238. /// - handler: A unary response handler.
  239. ///
  240. /// - Returns: The return value from the `handler`.
  241. public func unary<Request, Response, ReturnValue: Sendable>(
  242. request: ClientRequest<Request>,
  243. descriptor: MethodDescriptor,
  244. serializer: some MessageSerializer<Request>,
  245. deserializer: some MessageDeserializer<Response>,
  246. options: CallOptions,
  247. handler: @Sendable @escaping (ClientResponse<Response>) async throws -> ReturnValue
  248. ) async throws -> ReturnValue {
  249. try await self.bidirectionalStreaming(
  250. request: StreamingClientRequest(single: request),
  251. descriptor: descriptor,
  252. serializer: serializer,
  253. deserializer: deserializer,
  254. options: options
  255. ) { stream in
  256. let singleResponse = await ClientResponse(stream: stream)
  257. return try await handler(singleResponse)
  258. }
  259. }
  260. /// Start a client-streaming RPC.
  261. ///
  262. /// - Parameters:
  263. /// - request: The request stream.
  264. /// - descriptor: The method descriptor for which to execute this request.
  265. /// - serializer: A request serializer.
  266. /// - deserializer: A response deserializer.
  267. /// - options: Call specific options.
  268. /// - handler: A unary response handler.
  269. ///
  270. /// - Returns: The return value from the `handler`.
  271. public func clientStreaming<Request, Response, ReturnValue: Sendable>(
  272. request: StreamingClientRequest<Request>,
  273. descriptor: MethodDescriptor,
  274. serializer: some MessageSerializer<Request>,
  275. deserializer: some MessageDeserializer<Response>,
  276. options: CallOptions,
  277. handler: @Sendable @escaping (ClientResponse<Response>) async throws -> ReturnValue
  278. ) async throws -> ReturnValue {
  279. try await self.bidirectionalStreaming(
  280. request: request,
  281. descriptor: descriptor,
  282. serializer: serializer,
  283. deserializer: deserializer,
  284. options: options
  285. ) { stream in
  286. let singleResponse = await ClientResponse(stream: stream)
  287. return try await handler(singleResponse)
  288. }
  289. }
  290. /// Start a server-streaming RPC.
  291. ///
  292. /// - Parameters:
  293. /// - request: The unary request.
  294. /// - descriptor: The method descriptor for which to execute this request.
  295. /// - serializer: A request serializer.
  296. /// - deserializer: A response deserializer.
  297. /// - options: Call specific options.
  298. /// - handler: A response stream handler.
  299. ///
  300. /// - Returns: The return value from the `handler`.
  301. public func serverStreaming<Request, Response, ReturnValue: Sendable>(
  302. request: ClientRequest<Request>,
  303. descriptor: MethodDescriptor,
  304. serializer: some MessageSerializer<Request>,
  305. deserializer: some MessageDeserializer<Response>,
  306. options: CallOptions,
  307. handler: @Sendable @escaping (StreamingClientResponse<Response>) async throws -> ReturnValue
  308. ) async throws -> ReturnValue {
  309. try await self.bidirectionalStreaming(
  310. request: StreamingClientRequest(single: request),
  311. descriptor: descriptor,
  312. serializer: serializer,
  313. deserializer: deserializer,
  314. options: options,
  315. handler: handler
  316. )
  317. }
  318. /// Start a bidirectional streaming RPC.
  319. ///
  320. /// - Note: ``run()`` must have been called and still executing, and ``beginGracefulShutdown()`` mustn't
  321. /// have been called.
  322. ///
  323. /// - Parameters:
  324. /// - request: The streaming request.
  325. /// - descriptor: The method descriptor for which to execute this request.
  326. /// - serializer: A request serializer.
  327. /// - deserializer: A response deserializer.
  328. /// - options: Call specific options.
  329. /// - handler: A response stream handler.
  330. ///
  331. /// - Returns: The return value from the `handler`.
  332. public func bidirectionalStreaming<Request, Response, ReturnValue: Sendable>(
  333. request: StreamingClientRequest<Request>,
  334. descriptor: MethodDescriptor,
  335. serializer: some MessageSerializer<Request>,
  336. deserializer: some MessageDeserializer<Response>,
  337. options: CallOptions,
  338. handler: @Sendable @escaping (StreamingClientResponse<Response>) async throws -> ReturnValue
  339. ) async throws -> ReturnValue {
  340. try self.state.withLock { try $0.checkExecutable() }
  341. let methodConfig = self.transport.config(forMethod: descriptor)
  342. var options = options
  343. options.formUnion(with: methodConfig)
  344. return try await ClientRPCExecutor.execute(
  345. request: request,
  346. method: descriptor,
  347. options: options,
  348. serializer: serializer,
  349. deserializer: deserializer,
  350. transport: self.transport,
  351. interceptors: self.interceptors,
  352. handler: handler
  353. )
  354. }
  355. }