InProcessTransport+Server.swift 5.1 KB

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