GRPCClient.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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:onResponse:)``
  23. /// - ``clientStreaming(request:descriptor:serializer:deserializer:options:onResponse:)``
  24. /// - ``serverStreaming(request:descriptor:serializer:deserializer:options:onResponse:)``
  25. /// - ``bidirectionalStreaming(request:descriptor:serializer:deserializer:options:onResponse:)``
  26. ///
  27. /// However, in most cases you should prefer wrapping the ``GRPCClient`` with a generated stub.
  28. ///
  29. /// ## Creating a client
  30. ///
  31. /// You can create and run a client using ``withGRPCClient(transport:interceptors:isolation:handleClient:)``
  32. /// or ``withGRPCClient(transport:interceptorPipeline:isolation:handleClient:)`` which create, configure and
  33. /// run the client providing scoped access to it via the `handleClient` closure. The client will
  34. /// begin gracefully shutting down when the closure returns.
  35. ///
  36. /// ```swift
  37. /// let transport: any ClientTransport = ...
  38. /// try await withGRPCClient(transport: transport) { client in
  39. /// // ...
  40. /// }
  41. /// ```
  42. ///
  43. /// ## Creating a client manually
  44. ///
  45. /// If the `with`-style methods for creating clients isn't suitable for your application then you
  46. /// can create and run a client manually. This requires you to call the ``run()`` method in a task
  47. /// which instructs the client to start connecting to the server.
  48. ///
  49. /// The ``run()`` method won't return until the client has finished handling all requests. You can
  50. /// signal to the client that it should stop creating new request streams by calling ``beginGracefulShutdown()``.
  51. /// This gives the client enough time to drain any requests already in flight. To stop the client
  52. /// more abruptly you can cancel the task running your client. If your application requires
  53. /// additional resources that need their lifecycles managed you should consider using [Swift Service
  54. /// Lifecycle](https://github.com/swift-server/swift-service-lifecycle).
  55. public final class GRPCClient: Sendable {
  56. /// The transport which provides a bidirectional communication channel with the server.
  57. private let transport: any ClientTransport
  58. /// The current state of the client.
  59. private let stateMachine: Mutex<StateMachine>
  60. /// The state of the client.
  61. private enum State: Sendable {
  62. /// The client hasn't been started yet. Can transition to `running` or `stopped`.
  63. case notStarted
  64. /// The client is running and can send RPCs. Can transition to `stopping`.
  65. case running
  66. /// The client is stopping and no new RPCs will be sent. Existing RPCs may run to
  67. /// completion. May transition to `stopped`.
  68. case stopping
  69. /// The client has stopped, no RPCs are in flight and no more will be accepted. This state
  70. /// is terminal.
  71. case stopped
  72. mutating func run() throws {
  73. switch self {
  74. case .notStarted:
  75. self = .running
  76. case .running:
  77. throw RuntimeError(
  78. code: .clientIsAlreadyRunning,
  79. message: "The client is already running and can only be started once."
  80. )
  81. case .stopping, .stopped:
  82. throw RuntimeError(
  83. code: .clientIsStopped,
  84. message: "The client has stopped and can only be started once."
  85. )
  86. }
  87. }
  88. mutating func stopped() {
  89. self = .stopped
  90. }
  91. mutating func beginGracefulShutdown() -> Bool {
  92. switch self {
  93. case .notStarted:
  94. self = .stopped
  95. return false
  96. case .running:
  97. self = .stopping
  98. return true
  99. case .stopping, .stopped:
  100. return false
  101. }
  102. }
  103. func checkExecutable() throws {
  104. switch self {
  105. case .notStarted, .running:
  106. // Allow .notStarted as making a request can race with 'run()'. Transports should tolerate
  107. // queuing the request if not yet started.
  108. ()
  109. case .stopping, .stopped:
  110. throw RuntimeError(
  111. code: .clientIsStopped,
  112. message: "Client has been stopped. Can't make any more RPCs."
  113. )
  114. }
  115. }
  116. }
  117. private struct StateMachine {
  118. var state: State
  119. private let interceptorPipeline: [ClientInterceptorPipelineOperation]
  120. /// A collection of interceptors providing cross-cutting functionality to each accepted RPC, keyed by the method to which they apply.
  121. ///
  122. /// The list of interceptors for each method is computed from `interceptorsPipeline` when calling a method for the first time.
  123. /// This caching is done to avoid having to compute the applicable interceptors for each request made.
  124. ///
  125. /// The order in which interceptors are added reflects the order in which they are called. The
  126. /// first interceptor added will be the first interceptor to intercept each request. The last
  127. /// interceptor added will be the final interceptor to intercept each request before calling
  128. /// the appropriate handler.
  129. var interceptorsPerMethod: [MethodDescriptor: [any ClientInterceptor]]
  130. init(interceptorPipeline: [ClientInterceptorPipelineOperation]) {
  131. self.state = .notStarted
  132. self.interceptorPipeline = interceptorPipeline
  133. self.interceptorsPerMethod = [:]
  134. }
  135. mutating func checkExecutableAndGetApplicableInterceptors(
  136. for method: MethodDescriptor
  137. ) throws -> [any ClientInterceptor] {
  138. try self.state.checkExecutable()
  139. guard let applicableInterceptors = self.interceptorsPerMethod[method] else {
  140. let applicableInterceptors = self.interceptorPipeline
  141. .filter { $0.applies(to: method) }
  142. .map { $0.interceptor }
  143. self.interceptorsPerMethod[method] = applicableInterceptors
  144. return applicableInterceptors
  145. }
  146. return applicableInterceptors
  147. }
  148. }
  149. /// Creates a new client with the given transport, interceptors and configuration.
  150. ///
  151. /// - Parameters:
  152. /// - transport: The transport used to establish a communication channel with a server.
  153. /// - interceptors: A collection of ``ClientInterceptor``s providing cross-cutting functionality to each
  154. /// accepted RPC. The order in which interceptors are added reflects the order in which they
  155. /// are called. The first interceptor added will be the first interceptor to intercept each
  156. /// request. The last interceptor added will be the final interceptor to intercept each
  157. /// request before calling the appropriate handler.
  158. convenience public init(
  159. transport: some ClientTransport,
  160. interceptors: [any ClientInterceptor] = []
  161. ) {
  162. self.init(
  163. transport: transport,
  164. interceptorPipeline: interceptors.map { .apply($0, to: .all) }
  165. )
  166. }
  167. /// Creates a new client with the given transport, interceptors and configuration.
  168. ///
  169. /// - Parameters:
  170. /// - transport: The transport used to establish a communication channel with a server.
  171. /// - interceptorPipeline: A collection of ``ClientInterceptorPipelineOperation`` providing cross-cutting
  172. /// functionality to each accepted RPC. Only applicable interceptors from the pipeline will be applied to each RPC.
  173. /// The order in which interceptors are added reflects the order in which they are called.
  174. /// The first interceptor added will be the first interceptor to intercept each request.
  175. /// The last interceptor added will be the final interceptor to intercept each request before calling the appropriate handler.
  176. public init(
  177. transport: some ClientTransport,
  178. interceptorPipeline: [ClientInterceptorPipelineOperation]
  179. ) {
  180. self.transport = transport
  181. self.stateMachine = Mutex(StateMachine(interceptorPipeline: interceptorPipeline))
  182. }
  183. /// Start the client.
  184. ///
  185. /// This returns once ``beginGracefulShutdown()`` has been called and all in-flight RPCs have finished executing.
  186. /// If you need to abruptly stop all work you should cancel the task executing this method.
  187. ///
  188. /// The client, and by extension this function, can only be run once. If the client is already
  189. /// running or has already been closed then a ``RuntimeError`` is thrown.
  190. public func run() async throws {
  191. try self.stateMachine.withLock { try $0.state.run() }
  192. // When this function exits the client must have stopped.
  193. defer {
  194. self.stateMachine.withLock { $0.state.stopped() }
  195. }
  196. do {
  197. try await self.transport.connect()
  198. } catch {
  199. throw RuntimeError(
  200. code: .transportError,
  201. message: "The transport threw an error while connected.",
  202. cause: error
  203. )
  204. }
  205. }
  206. /// Close the client.
  207. ///
  208. /// The transport will be closed: this means that it will be given enough time to wait for
  209. /// in-flight RPCs to finish executing, but no new RPCs will be accepted. You can cancel the task
  210. /// executing ``run()`` if you want to abruptly stop in-flight RPCs.
  211. public func beginGracefulShutdown() {
  212. let wasRunning = self.stateMachine.withLock { $0.state.beginGracefulShutdown() }
  213. if wasRunning {
  214. self.transport.beginGracefulShutdown()
  215. }
  216. }
  217. /// Executes a unary RPC.
  218. ///
  219. /// - Parameters:
  220. /// - request: The unary request.
  221. /// - descriptor: The method descriptor for which to execute this request.
  222. /// - serializer: A request serializer.
  223. /// - deserializer: A response deserializer.
  224. /// - options: Call specific options.
  225. /// - handleResponse: A unary response handler.
  226. ///
  227. /// - Returns: The return value from the `handleResponse`.
  228. public func unary<Request, Response, ReturnValue: Sendable>(
  229. request: ClientRequest<Request>,
  230. descriptor: MethodDescriptor,
  231. serializer: some MessageSerializer<Request>,
  232. deserializer: some MessageDeserializer<Response>,
  233. options: CallOptions,
  234. onResponse handleResponse: @Sendable @escaping (
  235. _ response: ClientResponse<Response>
  236. ) async throws -> ReturnValue
  237. ) async throws -> ReturnValue {
  238. try await self.bidirectionalStreaming(
  239. request: StreamingClientRequest(single: request),
  240. descriptor: descriptor,
  241. serializer: serializer,
  242. deserializer: deserializer,
  243. options: options
  244. ) { stream in
  245. let singleResponse = await ClientResponse(stream: stream)
  246. return try await handleResponse(singleResponse)
  247. }
  248. }
  249. /// Start a client-streaming RPC.
  250. ///
  251. /// - Parameters:
  252. /// - request: The request stream.
  253. /// - descriptor: The method descriptor for which to execute this request.
  254. /// - serializer: A request serializer.
  255. /// - deserializer: A response deserializer.
  256. /// - options: Call specific options.
  257. /// - handleResponse: A unary response handler.
  258. ///
  259. /// - Returns: The return value from the `handleResponse`.
  260. public func clientStreaming<Request, Response, ReturnValue: Sendable>(
  261. request: StreamingClientRequest<Request>,
  262. descriptor: MethodDescriptor,
  263. serializer: some MessageSerializer<Request>,
  264. deserializer: some MessageDeserializer<Response>,
  265. options: CallOptions,
  266. onResponse handleResponse: @Sendable @escaping (
  267. _ response: ClientResponse<Response>
  268. ) async throws -> ReturnValue
  269. ) async throws -> ReturnValue {
  270. try await self.bidirectionalStreaming(
  271. request: request,
  272. descriptor: descriptor,
  273. serializer: serializer,
  274. deserializer: deserializer,
  275. options: options
  276. ) { stream in
  277. let singleResponse = await ClientResponse(stream: stream)
  278. return try await handleResponse(singleResponse)
  279. }
  280. }
  281. /// Start a server-streaming RPC.
  282. ///
  283. /// - Parameters:
  284. /// - request: The unary request.
  285. /// - descriptor: The method descriptor for which to execute this request.
  286. /// - serializer: A request serializer.
  287. /// - deserializer: A response deserializer.
  288. /// - options: Call specific options.
  289. /// - handleResponse: A response stream handler.
  290. ///
  291. /// - Returns: The return value from the `handleResponse`.
  292. public func serverStreaming<Request, Response, ReturnValue: Sendable>(
  293. request: ClientRequest<Request>,
  294. descriptor: MethodDescriptor,
  295. serializer: some MessageSerializer<Request>,
  296. deserializer: some MessageDeserializer<Response>,
  297. options: CallOptions,
  298. onResponse handleResponse: @Sendable @escaping (
  299. _ response: StreamingClientResponse<Response>
  300. ) async throws -> ReturnValue
  301. ) async throws -> ReturnValue {
  302. try await self.bidirectionalStreaming(
  303. request: StreamingClientRequest(single: request),
  304. descriptor: descriptor,
  305. serializer: serializer,
  306. deserializer: deserializer,
  307. options: options,
  308. onResponse: handleResponse
  309. )
  310. }
  311. /// Start a bidirectional streaming RPC.
  312. ///
  313. /// - Note: ``run()`` must have been called and still executing, and ``beginGracefulShutdown()`` mustn't
  314. /// have been called.
  315. ///
  316. /// - Parameters:
  317. /// - request: The streaming request.
  318. /// - descriptor: The method descriptor for which to execute this request.
  319. /// - serializer: A request serializer.
  320. /// - deserializer: A response deserializer.
  321. /// - options: Call specific options.
  322. /// - handleResponse: A response stream handler.
  323. ///
  324. /// - Returns: The return value from the `handleResponse`.
  325. public func bidirectionalStreaming<Request, Response, ReturnValue: Sendable>(
  326. request: StreamingClientRequest<Request>,
  327. descriptor: MethodDescriptor,
  328. serializer: some MessageSerializer<Request>,
  329. deserializer: some MessageDeserializer<Response>,
  330. options: CallOptions,
  331. onResponse handleResponse: @Sendable @escaping (
  332. _ response: StreamingClientResponse<Response>
  333. ) async throws -> ReturnValue
  334. ) async throws -> ReturnValue {
  335. let applicableInterceptors = try self.stateMachine.withLock {
  336. try $0.checkExecutableAndGetApplicableInterceptors(for: descriptor)
  337. }
  338. let methodConfig = self.transport.config(forMethod: descriptor)
  339. var options = options
  340. options.formUnion(with: methodConfig)
  341. return try await ClientRPCExecutor.execute(
  342. request: request,
  343. method: descriptor,
  344. options: options,
  345. serializer: serializer,
  346. deserializer: deserializer,
  347. transport: self.transport,
  348. interceptors: applicableInterceptors,
  349. handler: handleResponse
  350. )
  351. }
  352. }
  353. /// Creates and runs a new client with the given transport and interceptors.
  354. ///
  355. /// - Parameters:
  356. /// - transport: The transport used to establish a communication channel with a server.
  357. /// - interceptors: A collection of ``ClientInterceptor``s providing cross-cutting functionality to each
  358. /// accepted RPC. The order in which interceptors are added reflects the order in which they
  359. /// are called. The first interceptor added will be the first interceptor to intercept each
  360. /// request. The last interceptor added will be the final interceptor to intercept each
  361. /// request before calling the appropriate handler.
  362. /// - isolation: A reference to the actor to which the enclosing code is isolated, or nil if the
  363. /// code is nonisolated.
  364. /// - handleClient: A closure which is called with the client. When the closure returns, the
  365. /// client is shutdown gracefully.
  366. public func withGRPCClient<Result: Sendable>(
  367. transport: some ClientTransport,
  368. interceptors: [any ClientInterceptor] = [],
  369. isolation: isolated (any Actor)? = #isolation,
  370. handleClient: (GRPCClient) async throws -> Result
  371. ) async throws -> Result {
  372. try await withGRPCClient(
  373. transport: transport,
  374. interceptorPipeline: interceptors.map { .apply($0, to: .all) },
  375. isolation: isolation,
  376. handleClient: handleClient
  377. )
  378. }
  379. /// Creates and runs a new client with the given transport and interceptors.
  380. ///
  381. /// - Parameters:
  382. /// - transport: The transport used to establish a communication channel with a server.
  383. /// - interceptorPipeline: A collection of ``ClientInterceptorPipelineOperation`` providing cross-cutting
  384. /// functionality to each accepted RPC. Only applicable interceptors from the pipeline will be applied to each RPC.
  385. /// The order in which interceptors are added reflects the order in which they are called.
  386. /// The first interceptor added will be the first interceptor to intercept each request.
  387. /// The last interceptor added will be the final interceptor to intercept each request before calling the appropriate handler.
  388. /// - isolation: A reference to the actor to which the enclosing code is isolated, or nil if the
  389. /// code is nonisolated.
  390. /// - handleClient: A closure which is called with the client. When the closure returns, the
  391. /// client is shutdown gracefully.
  392. /// - Returns: The result of the `handleClient` closure.
  393. public func withGRPCClient<Result: Sendable>(
  394. transport: some ClientTransport,
  395. interceptorPipeline: [ClientInterceptorPipelineOperation],
  396. isolation: isolated (any Actor)? = #isolation,
  397. handleClient: (GRPCClient) async throws -> Result
  398. ) async throws -> Result {
  399. try await withThrowingDiscardingTaskGroup { group in
  400. let client = GRPCClient(transport: transport, interceptorPipeline: interceptorPipeline)
  401. group.addTask {
  402. try await client.run()
  403. }
  404. let result = try await handleClient(client)
  405. client.beginGracefulShutdown()
  406. return result
  407. }
  408. }