InProcessTransport+Server.swift 4.9 KB

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