InProcessTransport+Client.swift 14 KB

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