InProcessTransport+Client.swift 14 KB

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