GRPCClient.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. import Atomics
  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:handler:)``
  23. /// - ``clientStreaming(request:descriptor:serializer:deserializer:handler:)``
  24. /// - ``serverStreaming(request:descriptor:serializer:deserializer:handler:)``
  25. /// - ``bidirectionalStreaming(request:descriptor:serializer:deserializer:handler:)``
  26. ///
  27. /// However, in most cases you should prefer wrapping the ``GRPCClient`` with a generated stub.
  28. ///
  29. /// You can set ``ServiceConfiguration``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 = ServiceConfiguration(
  42. /// methodConfiguration: [
  43. /// MethodConfiguration(
  44. /// names: [
  45. /// MethodConfiguration.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 = ServiceConfiguration(
  55. /// methodConfiguration: [
  56. /// MethodConfiguration(
  57. /// names: [
  58. /// MethodConfiguration.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.close()
  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 ``close()``.
  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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  111. public struct 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 configuration used by the client.
  122. public let configuration: Configuration
  123. /// A cache of method config overrides.
  124. private let methodConfigurationOverrides: _MethodConfigurations
  125. /// A cache of method config defaults.
  126. private let methodConfigurationDefaults: _MethodConfigurations
  127. /// The current state of the client.
  128. private let state: ManagedAtomic<State>
  129. /// The state of the client.
  130. private enum State: UInt8, AtomicValue {
  131. /// The client hasn't been started yet. Can transition to `running` or `stopped`.
  132. case notStarted
  133. /// The client is running and can send RPCs. Can transition to `stopping`.
  134. case running
  135. /// The client is stopping and no new RPCs will be sent. Existing RPCs may run to
  136. /// completion. May transition to `stopped`.
  137. case stopping
  138. /// The client has stopped, no RPCs are in flight and no more will be accepted. This state
  139. /// is terminal.
  140. case stopped
  141. }
  142. /// Creates a new client with the given transport, interceptors and configuration.
  143. ///
  144. /// - Parameters:
  145. /// - transport: The transport used to establish a communication channel with a server.
  146. /// - interceptors: A collection of interceptors providing cross-cutting functionality to each
  147. /// accepted RPC. The order in which interceptors are added reflects the order in which they
  148. /// are called. The first interceptor added will be the first interceptor to intercept each
  149. /// request. The last interceptor added will be the final interceptor to intercept each
  150. /// request before calling the appropriate handler.
  151. /// - configuration: Configuration for the client.
  152. public init(
  153. transport: some ClientTransport,
  154. interceptors: [any ClientInterceptor] = [],
  155. configuration: Configuration = Configuration()
  156. ) {
  157. self.transport = transport
  158. self.interceptors = interceptors
  159. self.configuration = configuration
  160. self.methodConfigurationOverrides = _MethodConfigurations(
  161. serviceConfiguration: self.configuration.service.overrides
  162. )
  163. self.methodConfigurationDefaults = _MethodConfigurations(
  164. serviceConfiguration: self.configuration.service.defaults
  165. )
  166. self.state = ManagedAtomic(.notStarted)
  167. }
  168. /// Start the client.
  169. ///
  170. /// This returns once ``close()`` has been called and all in-flight RPCs have finished executing.
  171. /// If you need to abruptly stop all work you should cancel the task executing this method.
  172. ///
  173. /// The client, and by extension this function, can only be run once. If the client is already
  174. /// running or has already been closed then a ``ClientError`` is thrown.
  175. public func run() async throws {
  176. let (wasNotStarted, original) = self.state.compareExchange(
  177. expected: .notStarted,
  178. desired: .running,
  179. ordering: .sequentiallyConsistent
  180. )
  181. guard wasNotStarted else {
  182. switch original {
  183. case .notStarted:
  184. // The value wasn't exchanged so the original value can't be 'notStarted'.
  185. fatalError()
  186. case .running:
  187. throw RuntimeError(
  188. code: .clientIsAlreadyRunning,
  189. message: "The client is already running and can only be started once."
  190. )
  191. case .stopping, .stopped:
  192. throw RuntimeError(
  193. code: .clientIsStopped,
  194. message: "The client has stopped and can only be started once."
  195. )
  196. }
  197. }
  198. // When we exit this function we must have stopped.
  199. defer {
  200. self.state.store(.stopped, ordering: .sequentiallyConsistent)
  201. }
  202. do {
  203. try await self.transport.connect(lazily: false)
  204. } catch {
  205. throw RuntimeError(
  206. code: .transportError,
  207. message: "The transport threw an error while connected.",
  208. cause: error
  209. )
  210. }
  211. }
  212. /// Close the client.
  213. ///
  214. /// The transport will be closed: this means that it will be given enough time to wait for
  215. /// in-flight RPCs to finish executing, but no new RPCs will be accepted. You can cancel the task
  216. /// executing ``run()`` if you want to abruptly stop in-flight RPCs.
  217. public func close() {
  218. while true {
  219. let (wasRunning, actualState) = self.state.compareExchange(
  220. expected: .running,
  221. desired: .stopping,
  222. ordering: .sequentiallyConsistent
  223. )
  224. // Transition from running to stopping: close the transport.
  225. if wasRunning {
  226. self.transport.close()
  227. return
  228. }
  229. // The expected state wasn't 'running'. There are two options:
  230. // 1. The client isn't running yet.
  231. // 2. The client is already stopping or stopped.
  232. switch actualState {
  233. case .notStarted:
  234. // Not started: try going straight to stopped.
  235. let (wasNotStarted, _) = self.state.compareExchange(
  236. expected: .notStarted,
  237. desired: .stopped,
  238. ordering: .sequentiallyConsistent
  239. )
  240. // If the exchange happened then just return: the client wasn't started so there's no
  241. // transport to start.
  242. //
  243. // If the exchange didn't happen then continue looping: the client must've been started by
  244. // another thread.
  245. if wasNotStarted {
  246. return
  247. } else {
  248. continue
  249. }
  250. case .running:
  251. // Unreachable: the value was exchanged and this was the expected value.
  252. fatalError()
  253. case .stopping, .stopped:
  254. // No exchange happened but the client is already stopping.
  255. return
  256. }
  257. }
  258. }
  259. /// Executes a unary RPC.
  260. ///
  261. /// - Parameters:
  262. /// - request: The unary request.
  263. /// - descriptor: The method descriptor for which to execute this request.
  264. /// - serializer: A request serializer.
  265. /// - deserializer: A response deserializer.
  266. /// - handler: A unary response handler.
  267. ///
  268. /// - Returns: The return value from the `handler`.
  269. public func unary<Request, Response, ReturnValue>(
  270. request: ClientRequest.Single<Request>,
  271. descriptor: MethodDescriptor,
  272. serializer: some MessageSerializer<Request>,
  273. deserializer: some MessageDeserializer<Response>,
  274. handler: @Sendable @escaping (ClientResponse.Single<Response>) async throws -> ReturnValue
  275. ) async throws -> ReturnValue {
  276. try await self.bidirectionalStreaming(
  277. request: ClientRequest.Stream(single: request),
  278. descriptor: descriptor,
  279. serializer: serializer,
  280. deserializer: deserializer
  281. ) { stream in
  282. let singleResponse = await ClientResponse.Single(stream: stream)
  283. return try await handler(singleResponse)
  284. }
  285. }
  286. /// Start a client-streaming RPC.
  287. ///
  288. /// - Parameters:
  289. /// - request: The request stream.
  290. /// - descriptor: The method descriptor for which to execute this request.
  291. /// - serializer: A request serializer.
  292. /// - deserializer: A response deserializer.
  293. /// - handler: A unary response handler.
  294. ///
  295. /// - Returns: The return value from the `handler`.
  296. public func clientStreaming<Request, Response, ReturnValue>(
  297. request: ClientRequest.Stream<Request>,
  298. descriptor: MethodDescriptor,
  299. serializer: some MessageSerializer<Request>,
  300. deserializer: some MessageDeserializer<Response>,
  301. handler: @Sendable @escaping (ClientResponse.Single<Response>) async throws -> ReturnValue
  302. ) async throws -> ReturnValue {
  303. try await self.bidirectionalStreaming(
  304. request: request,
  305. descriptor: descriptor,
  306. serializer: serializer,
  307. deserializer: deserializer
  308. ) { stream in
  309. let singleResponse = await ClientResponse.Single(stream: stream)
  310. return try await handler(singleResponse)
  311. }
  312. }
  313. /// Start a server-streaming RPC.
  314. ///
  315. /// - Parameters:
  316. /// - request: The unary request.
  317. /// - descriptor: The method descriptor for which to execute this request.
  318. /// - serializer: A request serializer.
  319. /// - deserializer: A response deserializer.
  320. /// - handler: A response stream handler.
  321. ///
  322. /// - Returns: The return value from the `handler`.
  323. public func serverStreaming<Request, Response, ReturnValue>(
  324. request: ClientRequest.Single<Request>,
  325. descriptor: MethodDescriptor,
  326. serializer: some MessageSerializer<Request>,
  327. deserializer: some MessageDeserializer<Response>,
  328. handler: @Sendable @escaping (ClientResponse.Stream<Response>) async throws -> ReturnValue
  329. ) async throws -> ReturnValue {
  330. try await self.bidirectionalStreaming(
  331. request: ClientRequest.Stream(single: request),
  332. descriptor: descriptor,
  333. serializer: serializer,
  334. deserializer: deserializer,
  335. handler: handler
  336. )
  337. }
  338. /// Start a bidirectional streaming RPC.
  339. ///
  340. /// - Note: ``run()`` must have been called and still executing, and ``close()`` mustn't
  341. /// have been called.
  342. ///
  343. /// - Parameters:
  344. /// - request: The streaming request.
  345. /// - descriptor: The method descriptor for which to execute this request.
  346. /// - serializer: A request serializer.
  347. /// - deserializer: A response deserializer.
  348. /// - handler: A response stream handler.
  349. ///
  350. /// - Returns: The return value from the `handler`.
  351. public func bidirectionalStreaming<Request, Response, ReturnValue>(
  352. request: ClientRequest.Stream<Request>,
  353. descriptor: MethodDescriptor,
  354. serializer: some MessageSerializer<Request>,
  355. deserializer: some MessageDeserializer<Response>,
  356. handler: @Sendable @escaping (ClientResponse.Stream<Response>) async throws -> ReturnValue
  357. ) async throws -> ReturnValue {
  358. switch self.state.load(ordering: .sequentiallyConsistent) {
  359. case .notStarted, .running:
  360. // Allow .notStarted as making a request can race with 'run()'. Transports should tolerate
  361. // queuing the request if not yet started.
  362. ()
  363. case .stopping, .stopped:
  364. throw RuntimeError(
  365. code: .clientIsStopped,
  366. message: "Client has been stopped. Can't make any more RPCs."
  367. )
  368. }
  369. return try await ClientRPCExecutor.execute(
  370. request: request,
  371. method: descriptor,
  372. configuration: self.resolveMethodConfiguration(for: descriptor),
  373. serializer: serializer,
  374. deserializer: deserializer,
  375. transport: self.transport,
  376. interceptors: self.interceptors,
  377. handler: handler
  378. )
  379. }
  380. private func resolveMethodConfiguration(for descriptor: MethodDescriptor) -> MethodConfiguration {
  381. if let configuration = self.methodConfigurationOverrides[descriptor] {
  382. return configuration
  383. }
  384. if let configuration = self.transport.configuration(forMethod: descriptor) {
  385. return configuration
  386. }
  387. if let configuration = self.methodConfigurationDefaults[descriptor] {
  388. return configuration
  389. }
  390. // No configuration found, return the "vanilla" configuration.
  391. return MethodConfiguration(names: [], timeout: nil, executionPolicy: nil)
  392. }
  393. }
  394. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  395. extension GRPCClient {
  396. public struct Configuration: Sendable {
  397. /// Configuration for how the client interacts with services.
  398. ///
  399. /// The configuration includes information about how the client should load balance requests,
  400. /// how retries should be throttled and how methods should be executed. Some services and
  401. /// transports provide this information to the client when the server name is resolved. However,
  402. /// you can override this configuration and set default values should no override be set and the
  403. /// transport doesn't provide a value.
  404. ///
  405. /// See also ``ServiceConfiguration``.
  406. public var service: Service
  407. /// Creates a new default configuration.
  408. public init() {
  409. self.service = Service()
  410. }
  411. }
  412. }
  413. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  414. extension GRPCClient.Configuration {
  415. /// Configuration for how the client interacts with services.
  416. ///
  417. /// In most cases the client should defer to the configuration provided by the transport as this
  418. /// can be provided to the transport as part of name resolution when establishing a connection.
  419. ///
  420. /// The client first checks ``overrides`` for a configuration, followed by the transport, followed
  421. /// by ``defaults``.
  422. public struct Service: Sendable, Hashable {
  423. /// Configuration to use in precedence to that provided by the transport.
  424. public var overrides: ServiceConfiguration
  425. /// Configuration to use only if there are no overrides and the transport doesn't specify
  426. /// any configuration.
  427. public var defaults: ServiceConfiguration
  428. public init() {
  429. self.overrides = ServiceConfiguration()
  430. self.defaults = ServiceConfiguration()
  431. }
  432. }
  433. }