2
0

InProcessTransport+Client.swift 14 KB

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