InProcessTransport+Server.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 `ServerTransport`.
  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 server, you call ``listen(streamHandler:)`` and iterate over the returned `AsyncSequence` to get all
  26. /// RPC requests made from clients (as `RPCStream`s).
  27. /// To stop listening to new requests, call ``beginGracefulShutdown()``.
  28. ///
  29. /// - SeeAlso: `ClientTransport`
  30. public final class Server: ServerTransport, Sendable {
  31. public typealias Bytes = [UInt8]
  32. public typealias Inbound = RPCAsyncSequence<RPCRequestPart<Bytes>, any Error>
  33. public typealias Outbound = RPCWriter<RPCResponsePart<Bytes>>.Closable
  34. private let newStreams: AsyncStream<RPCStream<Inbound, Outbound>>
  35. private let newStreamsContinuation: AsyncStream<RPCStream<Inbound, Outbound>>.Continuation
  36. package let peer: String
  37. private struct State: Sendable {
  38. private var _nextID: UInt64
  39. private var handles: [UInt64: ServerContext.RPCCancellationHandle]
  40. private var isShutdown: Bool
  41. private mutating func nextID() -> UInt64 {
  42. let id = self._nextID
  43. self._nextID &+= 1
  44. return id
  45. }
  46. init() {
  47. self._nextID = 0
  48. self.handles = [:]
  49. self.isShutdown = false
  50. }
  51. mutating func addHandle(_ handle: ServerContext.RPCCancellationHandle) -> (UInt64, Bool) {
  52. let handleID = self.nextID()
  53. self.handles[handleID] = handle
  54. return (handleID, self.isShutdown)
  55. }
  56. mutating func removeHandle(withID id: UInt64) {
  57. self.handles.removeValue(forKey: id)
  58. }
  59. mutating func beginShutdown() -> [ServerContext.RPCCancellationHandle] {
  60. self.isShutdown = true
  61. let values = Array(self.handles.values)
  62. self.handles.removeAll()
  63. return values
  64. }
  65. }
  66. private let handles: Mutex<State>
  67. /// Creates a new instance of ``Server``.
  68. ///
  69. /// - Parameters:
  70. /// - peer: The system's PID for the running client and server.
  71. package init(peer: String) {
  72. (self.newStreams, self.newStreamsContinuation) = AsyncStream.makeStream()
  73. self.handles = Mutex(State())
  74. self.peer = peer
  75. }
  76. /// Publish a new ``RPCStream``, which will be returned by the transport's ``events``
  77. /// successful case.
  78. ///
  79. /// - Parameter stream: The new ``RPCStream`` to publish.
  80. /// - Throws: ``RPCError`` with code ``RPCError/Code-swift.struct/failedPrecondition``
  81. /// if the server transport stopped listening to new streams (i.e., if ``beginGracefulShutdown()`` has been called).
  82. internal func acceptStream(_ stream: RPCStream<Inbound, Outbound>) throws {
  83. let yieldResult = self.newStreamsContinuation.yield(stream)
  84. if case .terminated = yieldResult {
  85. throw RPCError(
  86. code: .failedPrecondition,
  87. message: "The server transport is closed."
  88. )
  89. }
  90. }
  91. public func listen(
  92. streamHandler: @escaping @Sendable (
  93. _ stream: RPCStream<Inbound, Outbound>,
  94. _ context: ServerContext
  95. ) async -> Void
  96. ) async throws {
  97. await withDiscardingTaskGroup { group in
  98. for await stream in self.newStreams {
  99. group.addTask {
  100. await withServerContextRPCCancellationHandle { handle in
  101. let (id, isShutdown) = self.handles.withLock({ $0.addHandle(handle) })
  102. defer {
  103. self.handles.withLock { $0.removeHandle(withID: id) }
  104. }
  105. // This happens if `beginGracefulShutdown` is called after the stream is added to
  106. // new streams but before it's dequeued.
  107. if isShutdown {
  108. handle.cancel()
  109. }
  110. let context = ServerContext(
  111. descriptor: stream.descriptor,
  112. remotePeer: self.peer,
  113. localPeer: self.peer,
  114. cancellation: handle
  115. )
  116. await streamHandler(stream, context)
  117. }
  118. }
  119. }
  120. }
  121. }
  122. /// Stop listening to any new `RPCStream` publications.
  123. ///
  124. /// - SeeAlso: `ServerTransport`
  125. public func beginGracefulShutdown() {
  126. self.newStreamsContinuation.finish()
  127. for handle in self.handles.withLock({ $0.beginShutdown() }) {
  128. handle.cancel()
  129. }
  130. }
  131. }
  132. }