GRPCClient.swift 14 KB

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