InProcessClientTransport.swift 13 KB

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