PassthroughMessageSource.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. /*
  2. * Copyright 2021, 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. #if compiler(>=5.5)
  17. import NIOConcurrencyHelpers
  18. import NIOCore
  19. /// The source of messages for a ``PassthroughMessageSequence``.`
  20. ///
  21. /// Values may be provided to the source with calls to ``yield(_:)`` which returns whether the value
  22. /// was accepted (and how many values are yet to be consumed) -- or dropped.
  23. ///
  24. /// The backing storage has an unbounded capacity and callers should use the number of unconsumed
  25. /// values returned from ``yield(_:)`` as an indication of when to stop providing values.
  26. ///
  27. /// The source must be finished exactly once by calling ``finish()`` or ``finish(throwing:)`` to
  28. /// indicate that the sequence should end with an error.
  29. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  30. @usableFromInline
  31. internal final class PassthroughMessageSource<Element, Failure: Error> {
  32. @usableFromInline
  33. internal typealias _ContinuationResult = Result<Element?, Error>
  34. /// All state in this class must be accessed via the lock.
  35. ///
  36. /// - Important: We use a `class` with a lock rather than an `actor` as we must guarantee that
  37. /// calls to ``yield(_:)`` are not reordered.
  38. @usableFromInline
  39. internal let _lock: Lock
  40. /// A queue of elements which may be consumed as soon as there is demand.
  41. @usableFromInline
  42. internal var _continuationResults: CircularBuffer<_ContinuationResult>
  43. /// A continuation which will be resumed in the future. The continuation must be `nil`
  44. /// if ``continuationResults`` is not empty.
  45. @usableFromInline
  46. internal var _continuation: Optional<CheckedContinuation<Element?, Error>>
  47. /// True if a terminal continuation result (`.success(nil)` or `.failure()`) has been seen.
  48. /// No more values may be enqueued to `continuationResults` if this is `true`.
  49. @usableFromInline
  50. internal var _isTerminated: Bool
  51. @usableFromInline
  52. internal init(initialBufferCapacity: Int = 16) {
  53. self._lock = Lock()
  54. self._continuationResults = CircularBuffer(initialCapacity: initialBufferCapacity)
  55. self._continuation = nil
  56. self._isTerminated = false
  57. }
  58. // MARK: - Append / Yield
  59. @usableFromInline
  60. internal enum YieldResult: Hashable {
  61. /// The value was accepted. The `queueDepth` indicates how many elements are waiting to be
  62. /// consumed.
  63. ///
  64. /// If `queueDepth` is zero then the value was consumed immediately.
  65. case accepted(queueDepth: Int)
  66. /// The value was dropped because the source has already been finished.
  67. case dropped
  68. }
  69. @inlinable
  70. internal func yield(_ element: Element) -> YieldResult {
  71. let continuationResult: _ContinuationResult = .success(element)
  72. return self._yield(continuationResult, isTerminator: false)
  73. }
  74. @inlinable
  75. internal func finish(throwing error: Failure? = nil) -> YieldResult {
  76. let continuationResult: _ContinuationResult = error.map { .failure($0) } ?? .success(nil)
  77. return self._yield(continuationResult, isTerminator: true)
  78. }
  79. @usableFromInline
  80. internal enum _YieldResult {
  81. /// The sequence has already been terminated; drop the element.
  82. case alreadyTerminated
  83. /// The element was added to the queue to be consumed later.
  84. case queued(Int)
  85. /// Demand for an element already existed: complete the continuation with the result being
  86. /// yielded.
  87. case resume(CheckedContinuation<Element?, Error>)
  88. }
  89. @inlinable
  90. internal func _yield(
  91. _ continuationResult: _ContinuationResult, isTerminator: Bool
  92. ) -> YieldResult {
  93. let result: _YieldResult = self._lock.withLock {
  94. if self._isTerminated {
  95. return .alreadyTerminated
  96. } else if let continuation = self._continuation {
  97. self._continuation = nil
  98. return .resume(continuation)
  99. } else {
  100. self._isTerminated = isTerminator
  101. self._continuationResults.append(continuationResult)
  102. return .queued(self._continuationResults.count)
  103. }
  104. }
  105. let yieldResult: YieldResult
  106. switch result {
  107. case let .queued(size):
  108. yieldResult = .accepted(queueDepth: size)
  109. case let .resume(continuation):
  110. // If we resume a continuation then the queue must be empty
  111. yieldResult = .accepted(queueDepth: 0)
  112. continuation.resume(with: continuationResult)
  113. case .alreadyTerminated:
  114. yieldResult = .dropped
  115. }
  116. return yieldResult
  117. }
  118. // MARK: - Next
  119. @inlinable
  120. internal func consumeNextElement() async throws -> Element? {
  121. return try await withCheckedThrowingContinuation {
  122. self._consumeNextElement(continuation: $0)
  123. }
  124. }
  125. @inlinable
  126. internal func _consumeNextElement(continuation: CheckedContinuation<Element?, Error>) {
  127. let continuationResult: _ContinuationResult? = self._lock.withLock {
  128. if let nextResult = self._continuationResults.popFirst() {
  129. return nextResult
  130. } else {
  131. // Nothing buffered and not terminated yet: save the continuation for later.
  132. assert(self._continuation == nil)
  133. self._continuation = continuation
  134. return nil
  135. }
  136. }
  137. if let continuationResult = continuationResult {
  138. continuation.resume(with: continuationResult)
  139. }
  140. }
  141. }
  142. #endif // compiler(>=5.5)