Skip to content

Add AsyncThrowingStream.init(unfolding:onCancel:) to handle cancellation. #78723

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 69 additions & 3 deletions stdlib/public/Concurrency/AsyncThrowingStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,66 @@ public struct AsyncThrowingStream<Element, Failure: Error> {
public init(
unfolding produce: @escaping @Sendable () async throws -> Element?
) where Failure == Error {
let storage: _AsyncStreamCriticalStorage<Optional<() async throws -> Element?>>
= .create(produce)
self.init(produce: produce, onCancel: nil)
}

/// Constructs an asynchronous throwing stream from a given element-producing
/// closure and an optional cancellation handler.
///
/// - Parameters:
/// - produce: A closure that asynchronously produces elements for the
/// stream.
/// - onCancel: A closure to execute when canceling the stream's task.
///
/// Use this convenience initializer when you have an asynchronous function
/// that can produce elements for the stream, and don't want to invoke
/// a continuation manually. This initializer "unfolds" your closure into
/// a full-blown asynchronous stream. The created stream handles adherence to
/// the `AsyncSequence` protocol automatically. To terminate the stream with
/// an error, throw the error from your closure.
///
/// `onCancel` may be executed concurrently with `produce` and will be
/// executed ahead of it if the task had already been cancelled an execution
/// of `produce`.
Copy link
Author

@adlich adlich Jan 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: Behavior mentioned in description (concurrency of cancellation call itself.)

///
/// The following example shows an `AsyncThrowingStream` created with this
/// initializer that produces random numbers on a one-second interval. If the
/// random number is divisible by 5 with no remainder, the stream throws a
/// `MyRandomNumberError`.
///
/// let stream = AsyncThrowingStream<Int, Error>(unfolding: {
/// await Task.sleep(1 * 1_000_000_000)
/// let random = Int.random(in: 1...10)
/// if random % 5 == 0 {
/// throw MyRandomNumberError()
/// }
/// return random
/// }, onCancel: { @Sendable () in print("Canceled.") })
///
/// // Call point:
/// do {
/// for try await random in stream {
/// print(random)
/// }
/// } catch {
/// print(error)
/// }
///
@available(SwiftStdlib 6.1, *)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read [1] and noticed [2] (6.1 and 6.2 defined) but am still unsure which is appropriate.

[1] https://github.com/swiftlang/swift/blob/main/docs/LibraryEvolution.rst
[2] https://github.com/swiftlang/swift/blob/main/utils/availability-macros.def

public init(
unfolding produce: @escaping @Sendable () async throws -> Element?,
onCancel: (@Sendable () -> Void)?
) where Failure == Error {
self.init(produce: produce, onCancel: onCancel)
}

private init(
produce: @escaping @Sendable () async throws -> Element?,
onCancel: (@Sendable () -> Void)?
) where Failure == Error {
let storage: _AsyncStreamCriticalStorage<
Optional<() async throws -> Element?>
> = .create(produce)
Copy link
Author

@adlich adlich Jan 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My best interpretation of line-breaking guidelines in [1]. Some other possibly "questionable" ones in tests as well. Happy to change as preferred.

[1] https://github.com/swiftlang/swift/blob/main/docs/StandardLibraryProgrammersManual.md#line-breaking

context = _Context {
return try await withTaskCancellationHandler {
guard let result = try await storage.value?() else {
Expand All @@ -384,6 +442,7 @@ public struct AsyncThrowingStream<Element, Failure: Error> {
return result
} onCancel: {
storage.value = nil
onCancel?()
}
}
}
Expand Down Expand Up @@ -586,7 +645,14 @@ public struct AsyncThrowingStream<Element, Failure: Error> {
) where Failure == Error {
fatalError("Unavailable in task-to-thread concurrency model")
}
}
@available(SwiftStdlib 6.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public init(
unfolding produce: @escaping () async throws -> Element?,
onCancel: (@Sendable () -> Void)?
) where Failure == Error {
fatalError("Unavailable in task-to-thread concurrency model")
}}

@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
Expand Down
Loading