DiscardingTaskGroup+CancellableHandle.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2024, 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 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  17. extension DiscardingTaskGroup {
  18. /// Adds a child task to the group which is individually cancellable.
  19. ///
  20. /// - Parameter operation: The task to add to the group.
  21. /// - Returns: A handle which can be used to cancel the task without cancelling the rest of
  22. /// the group.
  23. @inlinable
  24. mutating func addCancellableTask(
  25. _ operation: @Sendable @escaping () async -> Void
  26. ) -> CancellableTaskHandle {
  27. let signal = AsyncStream.makeStream(of: Void.self)
  28. self.addTask {
  29. return await withTaskGroup(of: FinishedOrCancelled.self) { group in
  30. group.addTask {
  31. await operation()
  32. return .finished
  33. }
  34. group.addTask {
  35. for await _ in signal.stream {}
  36. return .cancelled
  37. }
  38. let first = await group.next()!
  39. group.cancelAll()
  40. let second = await group.next()!
  41. switch (first, second) {
  42. case (.finished, .cancelled), (.cancelled, .finished):
  43. return
  44. default:
  45. fatalError("Internal inconsistency")
  46. }
  47. }
  48. }
  49. return CancellableTaskHandle(continuation: signal.continuation)
  50. }
  51. @usableFromInline
  52. enum FinishedOrCancelled: Sendable {
  53. case finished
  54. case cancelled
  55. }
  56. }
  57. @usableFromInline
  58. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  59. struct CancellableTaskHandle: Sendable {
  60. @usableFromInline
  61. private(set) var continuation: AsyncStream<Void>.Continuation
  62. @inlinable
  63. init(continuation: AsyncStream<Void>.Continuation) {
  64. self.continuation = continuation
  65. }
  66. @inlinable
  67. func cancel() {
  68. self.continuation.finish()
  69. }
  70. }