2
0

InProcessClientTransport.swift 13 KB

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