RPCWriterProtocol.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. /// A sink for values which are produced over time.
  17. public protocol RPCWriterProtocol<Element>: Sendable {
  18. /// The type of value written.
  19. associatedtype Element: Sendable
  20. /// Writes a single element.
  21. ///
  22. /// This function suspends until the element has been accepted. Implementers can use this
  23. /// to exert backpressure on callers.
  24. ///
  25. /// - Parameter element: The element to write.
  26. func write(_ element: Element) async throws
  27. /// Writes a sequence of elements.
  28. ///
  29. /// This function suspends until the elements have been accepted. Implementers can use this
  30. /// to exert backpressure on callers.
  31. ///
  32. /// - Parameter elements: The elements to write.
  33. func write(contentsOf elements: some Sequence<Element>) async throws
  34. }
  35. extension RPCWriterProtocol {
  36. /// Writes an `AsyncSequence` of values into the sink.
  37. ///
  38. /// - Parameter elements: The elements to write.
  39. public func write<Elements: AsyncSequence>(
  40. contentsOf elements: Elements
  41. ) async throws where Elements.Element == Element {
  42. for try await element in elements {
  43. try await self.write(element)
  44. }
  45. }
  46. }
  47. public protocol ClosableRPCWriterProtocol<Element>: RPCWriterProtocol {
  48. /// Indicate to the writer that no more writes are to be accepted.
  49. ///
  50. /// All writes after ``finish()`` has been called should result in an error
  51. /// being thrown.
  52. func finish() async
  53. /// Indicate to the writer that no more writes are to be accepted because an error occurred.
  54. ///
  55. /// All writes after ``finish(throwing:)`` has been called should result in an error
  56. /// being thrown.
  57. func finish(throwing error: any Error) async
  58. }