InProcessServerTransport.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2023, 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. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  17. /// An in-process implementation of a ``ServerTransport``.
  18. public struct InProcessServerTransport: ServerTransport {
  19. public typealias Inbound = RPCAsyncSequence<RPCRequestPart>
  20. public typealias Outbound = RPCWriter<RPCResponsePart>.Closable
  21. private let newStreams: AsyncStream<RPCStream<Inbound, Outbound>>
  22. private let newStreamsContinuation: AsyncStream<RPCStream<Inbound, Outbound>>.Continuation
  23. /// Creates a new instance of ``InProcessServerTransport``.
  24. public init() {
  25. (self.newStreams, self.newStreamsContinuation) = AsyncStream.makeStream()
  26. }
  27. /// Publish a new ``RPCStream``, which will be returned by the transport's ``RPCAsyncSequence``,
  28. /// returned when calling ``listen()``.
  29. ///
  30. /// - Parameter stream: The new ``RPCStream`` to publish.
  31. /// - Throws: ``RPCError`` with code ``RPCError/Code-swift.struct/failedPrecondition``
  32. /// if the server transport stopped listening to new streams (i.e., if ``stopListening()`` has been called).
  33. internal func acceptStream(_ stream: RPCStream<Inbound, Outbound>) throws {
  34. let yieldResult = self.newStreamsContinuation.yield(stream)
  35. if case .terminated = yieldResult {
  36. throw RPCError(
  37. code: .failedPrecondition,
  38. message: "The server transport is closed."
  39. )
  40. }
  41. }
  42. /// Return a new ``RPCAsyncSequence`` that will contain all published ``RPCStream``s published
  43. /// to this transport using the ``acceptStream(_:)`` method.
  44. ///
  45. /// - Returns: An ``RPCAsyncSequence`` of all published ``RPCStream``s.
  46. public func listen() -> RPCAsyncSequence<RPCStream<Inbound, Outbound>> {
  47. RPCAsyncSequence(wrapping: self.newStreams)
  48. }
  49. /// Stop listening to any new ``RPCStream`` publications.
  50. ///
  51. /// All further calls to ``acceptStream(_:)`` will not produce any new elements on the
  52. /// ``RPCAsyncSequence`` returned by ``listen()``.
  53. public func stopListening() {
  54. self.newStreamsContinuation.finish()
  55. }
  56. }