PassthroughMessageSource.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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.6)
  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 10.15, iOS 13, tvOS 13, watchOS 6, *)
  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. @discardableResult
  76. internal func finish(throwing error: Failure? = nil) -> YieldResult {
  77. let continuationResult: _ContinuationResult = error.map { .failure($0) } ?? .success(nil)
  78. return self._yield(continuationResult, isTerminator: true)
  79. }
  80. @usableFromInline
  81. internal enum _YieldResult {
  82. /// The sequence has already been terminated; drop the element.
  83. case alreadyTerminated
  84. /// The element was added to the queue to be consumed later.
  85. case queued(Int)
  86. /// Demand for an element already existed: complete the continuation with the result being
  87. /// yielded.
  88. case resume(CheckedContinuation<Element?, Error>)
  89. }
  90. @inlinable
  91. internal func _yield(
  92. _ continuationResult: _ContinuationResult, isTerminator: Bool
  93. ) -> YieldResult {
  94. let result: _YieldResult = self._lock.withLock {
  95. if self._isTerminated {
  96. return .alreadyTerminated
  97. } else if let continuation = self._continuation {
  98. self._continuation = nil
  99. return .resume(continuation)
  100. } else {
  101. self._isTerminated = isTerminator
  102. self._continuationResults.append(continuationResult)
  103. return .queued(self._continuationResults.count)
  104. }
  105. }
  106. let yieldResult: YieldResult
  107. switch result {
  108. case let .queued(size):
  109. yieldResult = .accepted(queueDepth: size)
  110. case let .resume(continuation):
  111. // If we resume a continuation then the queue must be empty
  112. yieldResult = .accepted(queueDepth: 0)
  113. continuation.resume(with: continuationResult)
  114. case .alreadyTerminated:
  115. yieldResult = .dropped
  116. }
  117. return yieldResult
  118. }
  119. // MARK: - Next
  120. @inlinable
  121. internal func consumeNextElement() async throws -> Element? {
  122. return try await withCheckedThrowingContinuation {
  123. self._consumeNextElement(continuation: $0)
  124. }
  125. }
  126. @inlinable
  127. internal func _consumeNextElement(continuation: CheckedContinuation<Element?, Error>) {
  128. let continuationResult: _ContinuationResult? = self._lock.withLock {
  129. if let nextResult = self._continuationResults.popFirst() {
  130. return nextResult
  131. } else {
  132. // Nothing buffered and not terminated yet: save the continuation for later.
  133. assert(self._continuation == nil)
  134. self._continuation = continuation
  135. return nil
  136. }
  137. }
  138. if let continuationResult = continuationResult {
  139. continuation.resume(with: continuationResult)
  140. }
  141. }
  142. }
  143. #endif // compiler(>=5.6)