InProcessTransport+Client.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * Copyright 2024, 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. public import GRPCCore
  17. private import Synchronization
  18. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  19. extension InProcessTransport {
  20. /// An in-process implementation of a ``ClientTransport``.
  21. ///
  22. /// This is useful when you're interested in testing your application without any actual networking layers
  23. /// involved, as the client and server will communicate directly with each other via in-process streams.
  24. ///
  25. /// To use this client, you'll have to provide a ``ServerTransport`` upon creation, as well
  26. /// as a ``ServiceConfig``.
  27. ///
  28. /// Once you have a client, you must keep a long-running task executing ``connect()``, which
  29. /// will return only once all streams have been finished and ``beginGracefulShutdown()`` has been called on this client; or
  30. /// when the containing task is cancelled.
  31. ///
  32. /// To execute requests using this client, use ``withStream(descriptor:options:_:)``. If this function is
  33. /// called before ``connect()`` is called, then any streams will remain pending and the call will
  34. /// block until ``connect()`` is called or the task is cancelled.
  35. ///
  36. /// - SeeAlso: ``ClientTransport``
  37. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  38. public final class Client: ClientTransport {
  39. private enum State: Sendable {
  40. struct UnconnectedState {
  41. var serverTransport: InProcessTransport.Server
  42. var pendingStreams: [AsyncStream<Void>.Continuation]
  43. init(serverTransport: InProcessTransport.Server) {
  44. self.serverTransport = serverTransport
  45. self.pendingStreams = []
  46. }
  47. }
  48. struct ConnectedState {
  49. var serverTransport: InProcessTransport.Server
  50. var nextStreamID: Int
  51. var openStreams:
  52. [Int: (
  53. RPCStream<Inbound, Outbound>,
  54. RPCStream<
  55. RPCAsyncSequence<RPCRequestPart, any Error>, RPCWriter<RPCResponsePart>.Closable
  56. >
  57. )]
  58. var signalEndContinuation: AsyncStream<Void>.Continuation
  59. init(
  60. fromUnconnected state: UnconnectedState,
  61. signalEndContinuation: AsyncStream<Void>.Continuation
  62. ) {
  63. self.serverTransport = state.serverTransport
  64. self.nextStreamID = 0
  65. self.openStreams = [:]
  66. self.signalEndContinuation = signalEndContinuation
  67. }
  68. }
  69. struct ClosedState {
  70. var openStreams:
  71. [Int: (
  72. RPCStream<Inbound, Outbound>,
  73. RPCStream<
  74. RPCAsyncSequence<RPCRequestPart, any Error>, RPCWriter<RPCResponsePart>.Closable
  75. >
  76. )]
  77. var signalEndContinuation: AsyncStream<Void>.Continuation?
  78. init() {
  79. self.openStreams = [:]
  80. self.signalEndContinuation = nil
  81. }
  82. init(fromConnected state: ConnectedState) {
  83. self.openStreams = state.openStreams
  84. self.signalEndContinuation = state.signalEndContinuation
  85. }
  86. }
  87. case unconnected(UnconnectedState)
  88. case connected(ConnectedState)
  89. case closed(ClosedState)
  90. }
  91. public typealias Inbound = RPCAsyncSequence<RPCResponsePart, any Error>
  92. public typealias Outbound = RPCWriter<RPCRequestPart>.Closable
  93. public let retryThrottle: RetryThrottle?
  94. private let methodConfig: MethodConfigs
  95. private let state: Mutex<State>
  96. /// Creates a new in-process client transport.
  97. ///
  98. /// - Parameters:
  99. /// - server: The in-process server transport to connect to.
  100. /// - serviceConfig: Service configuration.
  101. public init(
  102. server: InProcessTransport.Server,
  103. serviceConfig: ServiceConfig = ServiceConfig()
  104. ) {
  105. self.retryThrottle = serviceConfig.retryThrottling.map { RetryThrottle(policy: $0) }
  106. self.methodConfig = MethodConfigs(serviceConfig: serviceConfig)
  107. self.state = Mutex(.unconnected(.init(serverTransport: server)))
  108. }
  109. /// Establish and maintain a connection to the remote destination.
  110. ///
  111. /// Maintains a long-lived connection, or set of connections, to a remote destination.
  112. /// Connections may be added or removed over time as required by the implementation and the
  113. /// demand for streams by the client.
  114. ///
  115. /// Implementations of this function will typically create a long-lived task group which
  116. /// maintains connections. The function exits when all open streams have been closed and new connections
  117. /// are no longer required by the caller who signals this by calling ``beginGracefulShutdown()``, or by cancelling the
  118. /// task this function runs in.
  119. public func connect() async throws {
  120. let (stream, continuation) = AsyncStream<Void>.makeStream()
  121. try self.state.withLock { state in
  122. switch state {
  123. case .unconnected(let unconnectedState):
  124. state = .connected(
  125. .init(
  126. fromUnconnected: unconnectedState,
  127. signalEndContinuation: continuation
  128. )
  129. )
  130. for pendingStream in unconnectedState.pendingStreams {
  131. pendingStream.finish()
  132. }
  133. case .connected:
  134. throw RPCError(
  135. code: .failedPrecondition,
  136. message: "Already connected to server."
  137. )
  138. case .closed:
  139. throw RPCError(
  140. code: .failedPrecondition,
  141. message: "Can't connect to server, transport is closed."
  142. )
  143. }
  144. }
  145. for await _ in stream {
  146. // This for-await loop will exit (and thus `connect()` will return)
  147. // only when the task is cancelled, or when the stream's continuation is
  148. // finished - whichever happens first.
  149. // The continuation will be finished when `close()` is called and there
  150. // are no more open streams.
  151. }
  152. // If at this point there are any open streams, it's because Cancellation
  153. // occurred and all open streams must now be closed.
  154. let openStreams = self.state.withLock { state in
  155. switch state {
  156. case .unconnected:
  157. // We have transitioned to connected, and we can't transition back.
  158. fatalError("Invalid state")
  159. case .connected(let connectedState):
  160. state = .closed(.init())
  161. return connectedState.openStreams.values
  162. case .closed(let closedState):
  163. return closedState.openStreams.values
  164. }
  165. }
  166. for (clientStream, serverStream) in openStreams {
  167. await clientStream.outbound.finish(throwing: CancellationError())
  168. await serverStream.outbound.finish(throwing: CancellationError())
  169. }
  170. }
  171. /// Signal to the transport that no new streams may be created.
  172. ///
  173. /// Existing streams may run to completion naturally but calling ``withStream(descriptor:options:_:)``
  174. /// will result in an ``RPCError`` with code ``RPCError/Code/failedPrecondition`` being thrown.
  175. ///
  176. /// If you want to forcefully cancel all active streams then cancel the task running ``connect()``.
  177. public func beginGracefulShutdown() {
  178. let maybeContinuation: AsyncStream<Void>.Continuation? = self.state.withLock { state in
  179. switch state {
  180. case .unconnected:
  181. state = .closed(.init())
  182. return nil
  183. case .connected(let connectedState):
  184. if connectedState.openStreams.count == 0 {
  185. state = .closed(.init())
  186. return connectedState.signalEndContinuation
  187. } else {
  188. state = .closed(.init(fromConnected: connectedState))
  189. return nil
  190. }
  191. case .closed:
  192. return nil
  193. }
  194. }
  195. maybeContinuation?.finish()
  196. }
  197. /// Opens a stream using the transport, and uses it as input into a user-provided closure.
  198. ///
  199. /// - Important: The opened stream is closed after the closure is finished.
  200. ///
  201. /// This transport implementation throws ``RPCError/Code/failedPrecondition`` if the transport
  202. /// is closing or has been closed.
  203. ///
  204. /// This implementation will queue any streams (and thus block this call) if this function is called before
  205. /// ``connect()``, until a connection is established - at which point all streams will be
  206. /// created.
  207. ///
  208. /// - Parameters:
  209. /// - descriptor: A description of the method to open a stream for.
  210. /// - options: Options specific to the stream.
  211. /// - closure: A closure that takes the opened stream as parameter.
  212. /// - Returns: Whatever value was returned from `closure`.
  213. public func withStream<T>(
  214. descriptor: MethodDescriptor,
  215. options: CallOptions,
  216. _ closure: (RPCStream<Inbound, Outbound>) async throws -> T
  217. ) async throws -> T {
  218. let request = GRPCAsyncThrowingStream.makeStream(of: RPCRequestPart.self)
  219. let response = GRPCAsyncThrowingStream.makeStream(of: RPCResponsePart.self)
  220. let clientStream = RPCStream(
  221. descriptor: descriptor,
  222. inbound: RPCAsyncSequence(wrapping: response.stream),
  223. outbound: RPCWriter.Closable(wrapping: request.continuation)
  224. )
  225. let serverStream = RPCStream(
  226. descriptor: descriptor,
  227. inbound: RPCAsyncSequence(wrapping: request.stream),
  228. outbound: RPCWriter.Closable(wrapping: response.continuation)
  229. )
  230. let waitForConnectionStream: AsyncStream<Void>? = self.state.withLock { state in
  231. if case .unconnected(var unconnectedState) = state {
  232. let (stream, continuation) = AsyncStream<Void>.makeStream()
  233. unconnectedState.pendingStreams.append(continuation)
  234. state = .unconnected(unconnectedState)
  235. return stream
  236. }
  237. return nil
  238. }
  239. if let waitForConnectionStream {
  240. for await _ in waitForConnectionStream {
  241. // This loop will exit either when the task is cancelled or when the
  242. // client connects and this stream can be opened.
  243. }
  244. try Task.checkCancellation()
  245. }
  246. let acceptStream: Result<Int, RPCError> = self.state.withLock { state in
  247. switch state {
  248. case .unconnected:
  249. // The state cannot be unconnected because if it was, then the above
  250. // for-await loop on `pendingStream` would have not returned.
  251. // The only other option is for the task to have been cancelled,
  252. // and that's why we check for cancellation right after the loop.
  253. fatalError("Invalid state.")
  254. case .connected(var connectedState):
  255. let streamID = connectedState.nextStreamID
  256. do {
  257. try connectedState.serverTransport.acceptStream(serverStream)
  258. connectedState.openStreams[streamID] = (clientStream, serverStream)
  259. connectedState.nextStreamID += 1
  260. state = .connected(connectedState)
  261. return .success(streamID)
  262. } catch let acceptStreamError as RPCError {
  263. return .failure(acceptStreamError)
  264. } catch {
  265. return .failure(RPCError(code: .unknown, message: "Unknown error: \(error)."))
  266. }
  267. case .closed:
  268. let error = RPCError(
  269. code: .failedPrecondition,
  270. message: "The client transport is closed."
  271. )
  272. return .failure(error)
  273. }
  274. }
  275. switch acceptStream {
  276. case .success(let streamID):
  277. let streamHandlingResult: Result<T, any Error>
  278. do {
  279. let result = try await closure(clientStream)
  280. streamHandlingResult = .success(result)
  281. } catch {
  282. streamHandlingResult = .failure(error)
  283. }
  284. await clientStream.outbound.finish()
  285. self.removeStream(id: streamID)
  286. return try streamHandlingResult.get()
  287. case .failure(let error):
  288. await serverStream.outbound.finish(throwing: error)
  289. await clientStream.outbound.finish(throwing: error)
  290. throw error
  291. }
  292. }
  293. private func removeStream(id streamID: Int) {
  294. let maybeEndContinuation = self.state.withLock { state in
  295. switch state {
  296. case .unconnected:
  297. // The state cannot be unconnected at this point, because if we made
  298. // it this far, it's because the transport was connected.
  299. // Once connected, it's impossible to transition back to unconnected,
  300. // so this is an invalid state.
  301. fatalError("Invalid state")
  302. case .connected(var connectedState):
  303. connectedState.openStreams.removeValue(forKey: streamID)
  304. state = .connected(connectedState)
  305. case .closed(var closedState):
  306. closedState.openStreams.removeValue(forKey: streamID)
  307. state = .closed(closedState)
  308. if closedState.openStreams.isEmpty {
  309. // This was the last open stream: signal the closure of the client.
  310. return closedState.signalEndContinuation
  311. }
  312. }
  313. return nil
  314. }
  315. maybeEndContinuation?.finish()
  316. }
  317. /// Returns the execution configuration for a given method.
  318. ///
  319. /// - Parameter descriptor: The method to lookup configuration for.
  320. /// - Returns: Execution configuration for the method, if it exists.
  321. public func config(
  322. forMethod descriptor: MethodDescriptor
  323. ) -> MethodConfig? {
  324. self.methodConfig[descriptor]
  325. }
  326. }
  327. }