InProcessClientTransport.swift 13 KB

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