TaskGroup+CancellableTask.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  17. extension TaskGroup {
  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 -> ChildTaskResult
  26. ) -> CancellableTaskHandle {
  27. let signal = AsyncStream.makeStream(of: Void.self)
  28. self.addTask {
  29. return await withTaskGroup(
  30. of: _ResultOrCancelled.self,
  31. returning: ChildTaskResult.self
  32. ) { group in
  33. group.addTask {
  34. let childTaskResult = await operation()
  35. return .result(childTaskResult)
  36. }
  37. group.addTask {
  38. for await _ in signal.stream {}
  39. return .cancelled
  40. }
  41. let first = await group.next()!
  42. group.cancelAll()
  43. let second = await group.next()!
  44. switch (first, second) {
  45. case (.result(let result), .cancelled), (.cancelled, .result(let result)):
  46. return result
  47. default:
  48. fatalError("Internal inconsistency")
  49. }
  50. }
  51. }
  52. return CancellableTaskHandle(continuation: signal.continuation)
  53. }
  54. @usableFromInline
  55. enum _ResultOrCancelled {
  56. case result(ChildTaskResult)
  57. case cancelled
  58. }
  59. }
  60. @usableFromInline
  61. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  62. struct CancellableTaskHandle: Sendable {
  63. @usableFromInline
  64. private(set) var continuation: AsyncStream<Void>.Continuation
  65. @inlinable
  66. init(continuation: AsyncStream<Void>.Continuation) {
  67. self.continuation = continuation
  68. }
  69. @inlinable
  70. func cancel() {
  71. self.continuation.finish()
  72. }
  73. }