PassthroughMessageSource.swift 5.9 KB

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