From 4d4022e91bc29e370a93ef3c4eaace0ec090b7f6 Mon Sep 17 00:00:00 2001 From: Philippe Hausler Date: Thu, 17 Mar 2022 18:40:14 -0700 Subject: [PATCH] Add a whole bunch more to the guides (#64) * Rebase guides WIP to avoid source changes * Add prose for debounce and throttle * Add an alterantive for debounce * Starts to prose for reductions * Add effect listings for all types * Add some examples for reductions * Update Guides/Channel.md Co-authored-by: Chris Adamson * Update Guides/Channel.md Co-authored-by: Chris Adamson * Update Guides/Channel.md Co-authored-by: Chris Adamson * Update Guides/Channel.md Co-authored-by: Chris Adamson * Update Guides/Collections.md Co-authored-by: Chris Adamson * Update Guides/Throttle.md Co-authored-by: Chris Adamson * Update Guides/Throttle.md Co-authored-by: Chris Adamson * Update Guides/Throttle.md Co-authored-by: Chris Adamson * Update Sources/AsyncAlgorithms/AsyncInclusiveReductionsSequence.swift Co-authored-by: Chris Adamson * Adjust events to elements for channels * Add a bit more detail to the README and a start to the guide for Task.select * Chunked updates * Add a getting started section to the README * Add some more prose for Channel * Update Guides/RemoveDuplicates.md Co-authored-by: Chris Adamson * Apply suggestions from code review Co-authored-by: Chris Adamson * Add some brief prose for Compacted * reductions could be named scan * spelling and correctness fixes * Apply @kperryua's suggestion for changing the intro of Compacted * Add some brief prose for Timer * Apply suggestions from code review for README Co-authored-by: Tony Parker * Add some brief prose for RemoveDuplicates * Fleshing out of `Joined` Co-authored-by: Chris Adamson Co-authored-by: Kevin Perry Co-authored-by: Tony Parker --- Guides/Channel.md | 82 +++++ Guides/Chunked.md | 314 ++++++++++++++++++ Guides/Collections.md | 104 ++++++ Guides/Compacted.md | 57 ++++ Guides/Debounce.md | 75 +++++ Guides/Effects.md | 58 ++++ Guides/Joined.md | 127 +++++++ Guides/Lazy.md | 4 - Guides/Reductions.md | 131 ++++++++ Guides/RemoveDuplicates.md | 93 ++++++ Guides/Select.md | 54 +++ Guides/Throttle.md | 88 +++++ Guides/Timer.md | 51 +++ Guides/Zip.md | 2 +- README.md | 65 +++- .../AsyncInclusiveReductionsSequence.swift | 3 +- 16 files changed, 1292 insertions(+), 16 deletions(-) create mode 100644 Guides/Channel.md create mode 100644 Guides/Chunked.md create mode 100644 Guides/Collections.md create mode 100644 Guides/Compacted.md create mode 100644 Guides/Debounce.md create mode 100644 Guides/Effects.md create mode 100644 Guides/Joined.md create mode 100644 Guides/Reductions.md create mode 100644 Guides/RemoveDuplicates.md create mode 100644 Guides/Select.md create mode 100644 Guides/Throttle.md create mode 100644 Guides/Timer.md diff --git a/Guides/Channel.md b/Guides/Channel.md new file mode 100644 index 0000000..c907cc0 --- /dev/null +++ b/Guides/Channel.md @@ -0,0 +1,82 @@ +# Channel + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChannel.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncThrowingChannel.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChannel.swift) +] + +## Introduction + +`AsyncStream` introduced a mechanism to send buffered elements from a context that doesn't use Swift concurrency into one that does. That design only addressed a portion of the potential use cases; the missing portion was the back pressure excerpted across two concurrency domains. + +## Proposed Solution + +To achieve a system that supports back pressure and allows for the communication of more than one value from one task to another we are introducing a new type, the _channel_. The channel will be a reference-type asynchronous sequence with an asynchronous sending capability that awaits the consumption of iteration. Each value sent by the channel, or finish transmitted, will await the consumption of that value or event by iteration. That awaiting behavior will allow for the affordance of back pressure applied from the consumption site to be transmitted to the production site. This means that the rate of production cannot exceed the rate of consumption, and that the rate of consumption cannot exceed the rate of production. + +## Detailed Design + +Similar to the `AsyncStream` and `AsyncThrowingStream` types, the type for sending elements via back pressure will come in two versions. These two versions will account for the throwing nature or non-throwing nature of the elements being produced. + +Each type will have functions to send elements and to send terminal events. + +```swift +public final class AsyncChannel: AsyncSequence, Sendable { + public struct Iterator: AsyncIteratorProtocol, Sendable { + public mutating func next() async -> Element? + } + + public init(element elementType: Element.Type = Element.self) + + public func send(_ element: Element) async + public func finish() async + + public func makeAsyncIterator() -> Iterator +} + +public final class AsyncThrowingChannel: AsyncSequence, Sendable { + public struct Iterator: AsyncIteratorProtocol, Sendable { + public mutating func next() async throws -> Element? + } + + public init(element elementType: Element.Type = Element.self, failure failureType: Failure.Type = Failure.self) + + public func send(_ element: Element) async + public func fail(_ error: Error) async where Failure == Error + public func finish() async + + public func makeAsyncIterator() -> Iterator +} +``` + +Channels are intended to be used as communication types between tasks. Particularly when one task produces values and another task consumes said values. The back pressure applied by `send(_:)`, `fail(_:)` and `finish()` via the suspension/resume ensure that the production of values does not exceed the consumption of values from iteration. Each of these methods suspend after enqueuing the event and are resumed when the next call to `next()` on the `Iterator` is made. + +```swift +let channel = AsyncChannel() +Task { + while let resultOfLongCalculation = doLongCalculations() { + await channel.send(resultOfLongCalculation) + } + await channel.finish() +} + +for await calculationResult in channel { + print(calculationResult) +} +``` + +The example above uses a task to perform intense calculations; each of which are sent to the other task via the `send(_:)` method. That call to `send(_:)` returns when the next iteration of the channel is invoked. + +## Alternatives Considered + +The use of the name "subject" was considered, due to its heritage as a name for a sync-to-async adapter type. + +It was considered to make `AsyncChannel` and `AsyncThrowingChannel` actors, however due to the cancellation internals it would imply that these types would need to create new tasks to handle cancel events. The advantages of an actor in this particular case did not outweigh the impact of adjusting the implementations to be actors. + +## Credits/Inspiration + +`AsyncChannel` and `AsyncThrowingChannel` was heavily inspired from `Subject` but with the key difference that it uses Swift concurrency to apply back pressure. + +https://developer.apple.com/documentation/combine/subject/ diff --git a/Guides/Chunked.md b/Guides/Chunked.md new file mode 100644 index 0000000..2ddacc5 --- /dev/null +++ b/Guides/Chunked.md @@ -0,0 +1,314 @@ +# Chunked + +* Author(s): [Kevin Perry](https://github.com/kperryua) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunksOfCountAndSignalSequence.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunksOfCountSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChunk.swift) +] + +## Introduction + +Grouping of values from an asynchronous sequence is often useful for tasks that involve writing those values efficiently or useful to handle specific structured data inputs. + +## Proposed Solution + +Chunking operations can be broken down into a few distinct categories: grouping according to a binary predicate used to determine whether consecutive elements belong to the same group, projecting an element's property to determine the element's chunk membership, by discrete count, by another signal asynchronous sequence which indicates when the chunk should be delimited, or by a combination of count and signal. + +### Grouping + +Group chunks are determined by passing two consecutive elements to a closure which tests whether they are in the same group. When the `AsyncChunkedByGroupSequence` iterator receives the first element from the base sequence, it will immediately be added to a group. When it receives the second item, it tests whether the previous item and the current item belong to the same group. If they are not in the same group, then the iterator emits the first item's group and a new group is created containing the second item. Items declared to be in the same group accumulate until a new group is declared, or the iterator finds the end of the base sequence. When the base sequence terminates, the final group is emitted. If the base sequence throws an error, `AsyncChunkedByGroupSequence` will rethrow that error immediately and discard any current group. + +```swift +extension AsyncSequence { + public func chunked( + into: Collected.Type, + by belongInSameGroup: @escaping @Sendable (Element, Element) -> Bool + ) -> AsyncChunkedByGroupSequence + where Collected.Element == Element + + public func chunked( + by belongInSameGroup: @escaping @Sendable (Element, Element) -> Bool + ) -> AsyncChunkedByGroupSequence +} +``` + +Consider an example where an asynchronous sequence emits the following values: `10, 20, 30, 10, 40, 40, 10, 20`. Given the chunked operation to be defined as follows: + +```swift +let chunks = numbers.chunked { $0 <= $1 } +for await numberChunk in chunks { + print(numberChunk) +} +``` + +That snippet will produce the following values: + +```swift +[10, 20, 30] +[10, 40, 40] +[10, 20] +``` + +While `Array` is the default type for chunks, thanks to the overload that takes a `RangeReplaceableCollection` type, the same sample can be chunked into instances of `ContiguousArray`, or any other `RangeReplaceableCollection` instead. + +```swift +let chunks = numbers.chunked(into: ContiguousArray.self) { $0 <= $1 } +for await numberChunk in chunks { + print(numberChunk) +} +``` + +That variant is the funnel method for the main implementation, which passes `[Element].self` in as the parameter. + +### Projection + +In some scenarios, chunks are determined not by comparing different elements, but by the element itself. This may be the case when the element has some sort of discriminator that can determine the chunk it belongs to. When two consecutive elements have different projections, the current chunk is emitted and a new chunk is created for the new element. + +When the `AsyncChunkedOnProjectionSequence`'s iterator receives `nil` from the base sequence, it emits the final chunk. When the base sequence throws an error, the iterator discards the current chunk and rethrows that error. + +Similarly to the `chunked(by:)` method this algorithm has an optional specification for the `RangeReplaceableCollection` which is used as the type of each chunk. + +```swift +extension AsyncSequence { + public func chunked( + into: Collected.Type, + on projection: @escaping @Sendable (Element) -> Subject + ) -> AsyncChunkedOnProjectionSequence + + public func chunked( + on projection: @escaping @Sendable (Element) -> Subject + ) -> AsyncChunkedOnProjectionSequence +} +``` + +The following example shows how a sequence of names can be chunked together by their first characters. + +```swift +let names = URL(fileURLWithPath: "/tmp/names.txt").lines +let groupedNames = names.chunked(on: \.first!) +for try await (firstLetter, names) in groupedNames { + print(firstLetter) + for name in names { + print(" ", name) + } +} +``` + +A special property of this kind of projection chunking is that when an asynchronous sequence's elements are known to be ordered, the output of the chunking asynchronous sequence is suitable for initializing dictionaries using the `AsyncSequence` initializer for `Dictionary`. This is because the projection can be easily designed to match the sorting characteristics and thereby guarantee that the output matches the pattern of an array of pairs of unique "keys" with the chunks as the "values". + +In the example above, if the names are known to be ordered then you can take advantage of the uniqueness of each "first character" projection to initialize a `Dictionary` like so: + +```swift +let names = URL(fileURLWithPath: "/tmp/names.txt").lines +let nameDirectory = try await Dictionary(uniqueKeysWithValues: names.chunked(on: \.first!)) +``` + +### Count or Signal + +Sometimes chunks are determined not by the elements themselves, but by external factors. This final category enables limiting chunks to a specific size and/or delimiting them by another asynchronous sequence which is referred to as a "signal". This particular chunking family is useful for scenarios where the elements are more efficiently processed as chunks than individual elements, regardless of their values. + +This family is broken down into two sub-families of methods: ones that employ a signal plus an optional count (which return an `AsyncChunksOfCountOrSignalSequence`), and the ones that only deal with counts (which return an `AsyncChunksOfCountSequence`). Both sub-families have `Collected` as their element type, or `Array` if unspecified. These sub-families have rethrowing behaviors; if the base `AsyncSequence` can throw then the chunks sequence can also throw. Likewise if the base `AsyncSequence` cannot throw then the chunks sequence also cannot throw. + +##### Count only + +```swift +extension AsyncSequence { + public func chunks( + ofCount count: Int, + into: Collected.Type + ) -> AsyncChunksOfCountSequence + where Collected.Element == Element + + public func chunks( + ofCount count: Int + ) -> AsyncChunksOfCountSequence +} +``` + +If a chunk size limit is specified via an `ofCount` parameter, the sequence will produce chunks of type `Collected` with at most the specified number of elements. When a chunk reaches the given size, the asynchronous sequence will emit it immediately. + +For example, an asynchronous sequence of `UInt8` bytes can be chunked into at most 1024-byte `Data` instances like so: + +```swift +let packets = bytes.chunks(ofCount: 1024, into: Data.self) +for try await packet in packets { + write(packet) +} +``` + +##### Signal only + +```swift +extension AsyncSequence { + public func chunked( + by signal: Signal, + into: Collected.Type + ) -> AsyncChunksOfCountOrSignalSequence + where Collected.Element == Element + + public func chunked( + by signal: Signal + ) -> AsyncChunksOfCountOrSignalSequence + + public func chunked( + by timer: AsyncTimerSequence, + into: Collected.Type + ) -> AsyncChunksOfCountOrSignalSequence> + where Collected.Element == Element + + public func chunked( + by timer: AsyncTimerSequence + ) -> AsyncChunksOfCountOrSignalSequence> +} +``` + +If a signal asynchronous sequence is specified, the chunking asynchronous sequence emits chunks whenever the signal emits. The signals element values are ignored. If the chunking asynchronous sequence hasn't accumulated any elements since its previous emission, then no value is emitted in response to the signal. + +Since time is a frequent method of signaling desired delineations of chunks, there is a pre-specialized set of overloads that take `AsyncTimerSequence`. These allow shorthand initialization by using `AsyncTimerSequence`'s static member initializers. + +As an example, an asynchronous sequence of log messages can be chunked into arrays of logs in four second segments like so: + +```swift +let fourSecondsOfLogs = logs.chunked(by: .repeating(every: .seconds(4))) +for await chunk in fourSecondsOfLogs { + send(chunk) +} +``` + +##### Count or Signal + +```swift +extension AsyncSequence { + public func chunks( + ofCount count: Int, + or signal: Signal, + into: Collected.Type + ) -> AsyncChunksOfCountOrSignalSequence + where Collected.Element == Element + + public func chunks( + ofCount count: Int, + or signal: Signal + ) -> AsyncChunksOfCountOrSignalSequence + + public func chunked( + by timer: AsyncTimerSequence, + into: Collected.Type + ) -> AsyncChunksOfCountOrSignalSequence> + where Collected.Element == Element + + public func chunked( + by timer: AsyncTimerSequence + ) -> AsyncChunksOfCountOrSignalSequence> +} +``` + +If both count and signal are specified, the chunking asynchronous sequence emits chunks whenever *either* the chunk reaches the specified size *or* the signal asynchronous sequence emits. When a signal causes a chunk to be emitted, the accumulated element count is reset back to zero. When an `AsyncTimerSequence` is used as a signal, the timer is started from the moment `next()` is called for the first time on `AsyncChunksOfCountOrSignalSequence`'s iterator, and it emits on a regular cadence from that moment. Note that the scheduling of the timer's emission is unaffected by any chunks emitted based on count. + +Like the example above, this code emits up to 1024-byte `Data` instances, but a chunk will also be emitted every second. + +```swift +let packets = bytes.chunks(ofCount: 1024 or: .repeating(every: .seconds(1)), into: Data.self) +for try await packet in packets { + write(packet) +} +``` + +In any configuration of any of the chunking families, when the base asynchronous sequence terminates, one of two things will happen: 1) a partial chunk will be emitted, or 2) no chunk will be emitted (i.e. the iterator received no elements since the emission of the previous chunk). No elements from the base asynchronous sequence are ever discarded, except in the case of a thrown error. + +## Detailed Design + +### Grouping + +```swift +public struct AsyncChunkedByGroupSequence: AsyncSequence + where Collected.Element == Base.Element { + public typealias Element = Collected + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Collected? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncChunkedByGroupSequence: Sendable + where Base: Sendable, Base.Element: Sendable { } + +extension AsyncChunkedByGroupSequence.Iterator: Sendable + where Base.AsyncIterator: Sendable, Base.Element: Sendable { } +``` + +### Projection + +```swift +public struct AsyncChunkedOnProjectionSequence: AsyncSequence where Collected.Element == Base.Element { + public typealias Element = (Subject, Collected) + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> (Subject, Collected)? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncChunkedOnProjectionSequence: Sendable + where Base: Sendable, Base.Element: Sendable { } +extension AsyncChunkedOnProjectionSequence.Iterator: Sendable + where Base.AsyncIterator: Sendable, Base.Element: Sendable, Subject: Sendable { } +``` + +### Count + +```swift +public struct AsyncChunksOfCountSequence: AsyncSequence + where Collected.Element == Base.Element { + public typealias Element = Collected + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Collected? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncChunksOfCountSequence : Sendable where Base : Sendable, Base.Element : Sendable { } +extension AsyncChunksOfCountSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable { } + +``` + +### Count or Signal + +```swift +public struct AsyncChunksOfCountOrSignalSequence: AsyncSequence, Sendable + where + Collected.Element == Base.Element, + Base: Sendable, Signal: Sendable, + Base.AsyncIterator: Sendable, Signal.AsyncIterator: Sendable, + Base.Element: Sendable, Signal.Element: Sendable { + public typealias Element = Collected + + public struct Iterator: AsyncIteratorProtocol, Sendable { + public mutating func next() async rethrows -> Collected? + } + + public func makeAsyncIterator() -> Iterator +} +``` + +## Alternatives Considered + +It was considered to make the chunked element to be an `AsyncSequence` instead of allowing collection into a `RangeReplaceableCollection` however it was determined that the throwing behavior of that would be complex to understand. If that hurdle could be overcome then that might be a future direction/consideration that would be worth exploring. + +Variants of `chunked(by:)` (grouping) and `chunked(on:)` (projection) methods could be added that take delimiting `Signal` and `AsyncTimerSequence` inputs similar to `chunked(byCount:or:)`. However, it was decided that such functionality was likely to be underutilized and not worth the complication to the already broad surface area of `chunked` methods. + +The naming of this family was considered to be `collect` which is used in APIs like `Combine`. This family of functions has distinct similarity to those APIs. + +## Credits/Inspiration + +This transformation function is a heavily inspired analog of the synchronous version [defined in the Swift Algorithms package](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md) diff --git a/Guides/Collections.md b/Guides/Collections.md new file mode 100644 index 0000000..366918d --- /dev/null +++ b/Guides/Collections.md @@ -0,0 +1,104 @@ +# Collection Initializers + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Dictionary.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/RangeReplaceableCollection.swift), +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/SetAlgebra.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestDictionary.swift), +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestRangeReplacableCollection.swift), +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestSetAlgebra.swift), +] + + +## Introduction + +`Array`, `Dictionary` and `Set` are some of the most commonly-used data structures for storing collections of elements. Having a way to transition from an `AsyncSequence` to a collection is not only a useful shorthand but a powerful way of expressing direct intent for how to consume an `AsyncSequence`. + +This type of functionality can be useful for examples and testing, and also for interfacing with existing APIs that expect a fully-formed collection before processing it. + +## Proposed Solution + +Three categories of initializers will be added to provide initializers for those three primary types: `Array`, `Dictionary` and `Set`. However these initializers can be written in a generic fashion such that they can apply to all similar collections. + +`RangeReplaceableCollection` will gain a new that constructs a collection given an `AsyncSequence`. This will allow for creating arrays from asynchronous sequences but also allow for creating types like `Data` or `ContiguousArray`. Because of the nature of asynchronous sequences, this initializer must be asynchronous and declare that it rethrows errors from the base asynchronous sequence. + +```swift +extension RangeReplaceableCollection { + public init( + _ source: Source + ) async rethrows + where Source.Element == Element +} +``` + +`Dictionary` will gain a family of new asynchronous, rethrowing initializers to parallel the existing `Sequence`-based initializers. The initializers will be asynchronous to facilitate uniquing keys and other tasks that may be asynchronous, in addition to the asynchronous initialization of the dictionaries. + +```swift +extension Dictionary { + public init( + uniqueKeysWithValues keysAndValues: S + ) async rethrows + where S.Element == (Key, Value) + + public init( + _ keysAndValues: S, + uniquingKeysWith combine: (Value, Value) async throws -> Value + ) async rethrows + where S.Element == (Key, Value) + + public init( + grouping values: S, + by keyForValue: (S.Element) async throws -> Key + ) async rethrows + where Value == [S.Element] +} +``` + +`SetAlgebra` will gain a new asynchronous, rethrowing initializer that constructs a `SetAlgebra` type given an `AsyncSequence`. This will allow for creating sets from asynchronous sequences and allow for creating types like `OptionSet` types or `IndexSet`. + +```swift +extension SetAlgebra { + public init( + _ source: Source + ) async rethrows + where Source.Element == Element +} +``` + +## Detailed Design + +Each of the initializers is intended for uses where the `AsyncSequence` being used for initialization is known to be finite. Common uses include: + +* Reading from files via the `AsyncBytes` style sequences or `lines` accessors. +* Gathering elements produced by a `TaskGroup`. +* Accessing a prefix of an indefinite `AsyncSequence`. + +Each of the initializers will use the `for`-`await`-`in`/`for`-`try`-`await`-`in` syntax to iterate the sequence directly in the initializer. In addition each initializer relies on the `AsyncSequence` being passed in to properly respect cancellation. In the cases where cancellation is a potential, developers should be ready to either check immediately or be ready for initialization based on a partial sequence, depending on the behavior of the `AsyncSequence` being used. + +### RangeReplaceableCollection + +```swift +let contents = try await Data(URL(fileURLWithPath: "/tmp/example.bin").resourceBytes) +``` + +### Dictionary + +```swift +let table = await Dictionary(uniqueKeysWithValues: zip(keys, values)) +``` + +### SetAlgebra + +```swift +let allItems = await Set(items.prefix(10)) +``` + +## Alternatives Considered + +The spelling of these initializers could be expressed as a trailing conversion. However, that can lead to hard-to-read chains of operations. Functionally these all belong to the `reduce` family of functions, but due to source readability concerns they are more ergonomic for understanding what the code does by using the initializer patterns. + +## Credits/Inspiration + +The direct inspiration for each initialization is from their standard library counterparts. diff --git a/Guides/Compacted.md b/Guides/Compacted.md new file mode 100644 index 0000000..64802de --- /dev/null +++ b/Guides/Compacted.md @@ -0,0 +1,57 @@ +# Compacted + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncCompactedSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestCompacted.swift) +] + +## Introduction + +Just as it is common for `Sequence` types that contain optional values to need to `.compactMap { $0 }`, `AsyncSequence` types have the same use cases. This common task means that the type must employ a closure to test the optional value. This can be done more efficeintly for both execution performance as well as API efficiency of typing. + +## Proposed Solution + +Similar to the Swift Algorithms package we propose that a new method be added to `AsyncSequence` to fit this need. + +```swift +extension AsyncSequence { + public func compacted() -> AsyncCompactedSequence + where Element == Unwrapped? +} +``` + +This is equivalent to writing `.compactMap { $0 }` from a behavioral standpoint but is easier to reason about and is more efficient since it does not need to execute or store a closure. + +## Detailed Design + +The `AsyncCompactedSequence` type from an effects standpoint works just like `AsyncCompactMapSequence`. When the base asynchronous sequence throws, the iteration of `AsyncCompactedSequence` can throw. Likewise if the base does not throw then the iteration of `AsyncCompactedSequence` does not throw. This type is conditionally `Sendable` when the base, base element, and base iterator are `Sendable. + +```swift +public struct AsyncCompactedSequence: AsyncSequence + where Base.Element == Element? { + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Element? + } + + public func makeAsyncIterator() -> Iterator { + Iterator(base.makeAsyncIterator()) + } +} + +extension AsyncCompactedSequence: Sendable + where + Base: Sendable, Base.Element: Sendable, + Base.AsyncIterator: Sendable { } + +extension AsyncCompactedSequence.Iterator: Sendable + where + Base: Sendable, Base.Element: Sendable, + Base.AsyncIterator: Sendable { } +``` + +## Credits/Inspiration + +This transformation function is a direct analog to the synchronous version [defined in the Swift Algorithms package](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md) diff --git a/Guides/Debounce.md b/Guides/Debounce.md new file mode 100644 index 0000000..b193c31 --- /dev/null +++ b/Guides/Debounce.md @@ -0,0 +1,75 @@ +# Debounce + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncDebounceSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestDebounce.swift) +] + +## Introduction + +When events can potentially happen faster than the desired consumption rate, there are multiple ways to handle the situation. One approach is to only emit values after a given period of time of inactivity, or "quiescence", has elapsed. This algorithm is commonly referred to as debouncing. + +## Proposed Solution + +The debounce algorithm produces elements after a particular duration has passed between events. It transacts within a given tolerance applied to a clock. If values are produced by the base `AsyncSequence` during this quiet period, the debounce does not resume its next iterator until the period has elapsed with no values are produced or unless a terminal event is encountered. + +The interface for this algorithm is available on all `AsyncSequence` types where the base type, iterator, and element are `Sendable`, since this algorithm will inherently create tasks to manage their timing of events. A shorthand implementation will be offered where the clock is the `ContinuousClock`, which allows for easy construction with `Duration` values. + +```swift +extension AsyncSequence { + public func debounce( + for interval: C.Instant.Duration, + tolerance: C.Instant.Duration? = nil, + clock: C + ) -> AsyncDebounceSequence + + public func debounce( + for interval: Duration, + tolerance: Duration? = nil + ) -> AsyncDebounceSequence +} +``` + +This all boils down to a terse description of how to transform the asynchronous sequence over time. + +```swift +fastEvents.debounce(for: .seconds(1)) +``` + +In this case it transforms a potentially fast asynchronous sequence of events into one that waits for a window of 1 second with no events to elapse before emitting a value. + +## Detailed Design + +The type that implements the algorithm for debounce emits the same element type as the base that it applies to. It also throws when the base type throws (and likewise does not throw when the base type does not throw). + +```swift +public struct AsyncDebounceSequence: Sendable + where Base.AsyncIterator: Sendable, Base.Element: Sendable, Base: Sendable { +} + +extension AsyncDebounceSequence: AsyncSequence { + public typealias Element = Base.Element + + public struct Iterator: AsyncIteratorProtocol, Sendable { + public mutating func next() async rethrows -> Base.Element? + } + + public func makeAsyncIterator() -> Iterator +} +``` + +Since the stored types comprising `AsyncDebounceSequence` must be `Sendable`; `AsyncDebounceSequence` is unconditionally always `Sendable`. + +## Alternatives Considered + +An alternative form of `debounce` could exist similar to the reductions of `throttle`, where a closure would be invoked for each value being set as the latest, and reducing a new value to produce for the debounce. + +## Credits/Inspiration + +The naming for debounce comes as a term of art; originally this term was inspired by electronic circuitry. When a physical switch closes a circuit it can easily have a "bouncing" behavior (also called chatter) that is caused by electrical contact resistance and the physical bounce of springs associated with switches. That phenomenon is often addressed with additional circuits to de-bounce (removing the bouncing) by ensuring a certain quiescence occurs. + +http://reactivex.io/documentation/operators/debounce.html + +https://developer.apple.com/documentation/combine/publishers/debounce/ diff --git a/Guides/Effects.md b/Guides/Effects.md new file mode 100644 index 0000000..09c1b28 --- /dev/null +++ b/Guides/Effects.md @@ -0,0 +1,58 @@ +| Type | Throws | Sendablity | +|-----------------------------------------------------|--------------|-------------| +| `AsyncBufferedByteIterator` | throws | Sendable | +| `AsyncBufferSequence` | rethrows | Conditional | +| `AsyncBufferSequence.Iterator` | rethrows | Conditional | +| `AsyncChain2Sequence` | rethrows | Conditional | +| `AsyncChain2Sequence.Iterator` | rethrows | Conditional | +| `AsyncChain3Sequence` | rethrows | Conditional | +| `AsyncChain3Sequence.Iterator` | rethrows | Conditional | +| `AsyncChannel` | non-throwing | Sendable | +| `AsyncChannel.Iterator` | non-throwing | Sendable | +| `AsyncChunkedByGroupSequence` | rethrows | Conditional | +| `AsyncChunkedByGroupSequence.Iterator` | rethrows | Conditional | +| `AsyncChunkedOnProjectionSequence` | rethrows | Conditional | +| `AsyncChunkedOnProjectionSequence.Iterator` | rethrows | Conditional | +| `AsyncChunksOfCountOrSignalSequence` | rethrows | Sendable | +| `AsyncChunksOfCountOrSignalSequence.Iterator` | rethrows | Sendable | +| `AsyncChunksOfCountSequence` | rethrows | Conditional | +| `AsyncChunksOfCountSequence.Iterator` | rethrows | Conditional | +| `AsyncCombineLatest2Sequence` | rethrows | Sendable | +| `AsyncCombineLatest2Sequence.Iterator` | rethrows | Sendable | +| `AsyncCombineLatest3Sequence` | rethrows | Sendable | +| `AsyncCombineLatest3Sequence.Iterator` | rethrows | Sendable | +| `AsyncCompactedSequence` | rethrows | Conditional | +| `AsyncCompactedSequence.Iterator` | rethrows | Conditional | +| `AsyncDebounceSequence` | rethrows | Sendable | +| `AsyncDebounceSequence.Iterator` | rethrows | Sendable | +| `AsyncExclusiveReductionsSequence` | rethrows | Conditional | +| `AsyncExclusiveReductionsSequence.Iterator` | rethrows | Conditional | +| `AsyncInclusiveReductionsSequence` | rethrows | Conditional | +| `AsyncInclusiveReductionsSequence.Iterator` | rethrows | Conditional | +| `AsyncInterspersedSequence` | rethrows | Conditional | +| `AsyncInterspersedSequence.Iterator` | rethrows | Conditional | +| `AsyncJoinedSequence` | rethrows | Conditional | +| `AsyncJoinedSequence.Iterator` | rethrows | Conditional | +| `AsyncLazySequence` | non-throwing | Conditional | +| `AsyncLazySequence.Iterator` | non-throwing | Conditional | +| `AsyncLimitBuffer` | non-throwing | Sendable | +| `AsyncMerge2Sequence` | rethrows | Sendable | +| `AsyncMerge2Sequence.Iterator` | rethrows | Sendable | +| `AsyncMerge3Sequence` | rethrows | Sendable | +| `AsyncMerge3Sequence.Iterator` | rethrows | Sendable | +| `AsyncRemoveDuplicatesSequence` | rethrows | Conditional | +| `AsyncRemoveDuplicatesSequence.Iterator` | rethrows | Conditional | +| `AsyncThrottleSequence` | rethrows | Conditional | +| `AsyncThrottleSequence.Iterator` | rethrows | Conditional | +| `AsyncThrowingChannel` | throws | Sendable | +| `AsyncThrowingChannel.Iterator` | throws | Sendable | +| `AsyncThrowingExclusiveReductionsSequence` | throws | Conditional | +| `AsyncThrowingExclusiveReductionsSequence.Iterator` | throws | Conditional | +| `AsyncThrowingInclusiveReductionsSequence` | throws | Conditional | +| `AsyncThrowingInclusiveReductionsSequence.Iterator` | throws | Conditional | +| `AsyncTimerSequence` | non-throwing | Sendable | +| `AsyncTimerSequence.Iterator` | non-throwing | Sendable | +| `AsyncZip2Sequence` | rethrows | Sendable | +| `AsyncZip2Sequence.Iterator` | rethrows | Sendable | +| `AsyncZip3Sequence` | rethrows | Sendable | +| `AsyncZip3Sequence.Iterator` | rethrows | Sendable | diff --git a/Guides/Joined.md b/Guides/Joined.md new file mode 100644 index 0000000..91c5ec2 --- /dev/null +++ b/Guides/Joined.md @@ -0,0 +1,127 @@ +# Joined + +* Author(s): [Kevin Perry](https://github.com/kperryua) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncJoinedSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestJoin.swift) +] + +## Introduction + +Concatenates an asynchronous sequence of asynchronous sequences that share an `Element` type together sequentially where the elements from the resulting asynchronous sequence are comprised in order from the elements of the first asynchronous sequence and then the second (and so on) or until an error occurs. Similar to `chain()`, except the number of asynchronous sequences to concatenate is not known up front. + +Optionally allows inserting the elements of a separator asynchronous sequence in between each of the other sequences. + +```swift +let sequenceOfURLs: AsyncSequence = ... +let sequenceOfLines = sequenceOfURLs.map { $0.lines } +let joinedWithSeparator = sequenceOfLines.joined(separator: ["===================="].async) + +for try await lineOrSeparator in joinedWithSeparator { + print(lineOrSeparator) +} +``` + +This example shows how an `AsyncSequence` of `URL`s can be turned into an `AsyncSequence` of the lines of each of those files in sequence, with a separator line in between each file. + +## Proposed Solution + +```swift +extension AsyncSequence where Element: AsyncSequence { + public func joined() -> AsyncJoinedSequence { + return AsyncJoinedSequence(self) + } +} +``` + +```swift +extension AsyncSequence where Element: AsyncSequence { + public func joined(separator: Separator) -> AsyncJoinedBySeparatorSequence { + return AsyncJoinedBySeparatorSequence(self, separator: separator) + } +} +``` + +## Detailed Design + +```swift +public struct AsyncJoinedSequence: AsyncSequence where Base.Element: AsyncSequence { + public typealias Element = Base.Element.Element + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Base.Element.Element? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncJoinedSequence: Sendable + where + Base: Sendable, + Base.Element: Sendable, + Base.Element.Element: Sendable, + Base.AsyncIterator: Sendable, + Base.Element.AsyncIterator: Sendable { } + +extension AsyncJoinedSequence.Iterator: Sendable + where + Base: Sendable, + Base.Element: Sendable, + Base.Element.Element: Sendable, + Base.AsyncIterator: Sendable, + Base.Element.AsyncIterator: Sendable { } +``` + +```swift +public struct AsyncJoinedBySeparatorSequence: AsyncSequence + where Base.Element: AsyncSequence, Separator.Element == Base.Element.Element { + public typealias Element = Base.Element.Element + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Base.Element.Element? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncJoinedBySeparatorSequence: Sendable + where + Base: Sendable, + Base.Element: Sendable, + Base.Element.Element: Sendable, + Base.AsyncIterator: Sendable, + Separator: Sendable, + Separator.AsyncIterator: Sendable, + Base.Element.AsyncIterator: Sendable { } + +extension AsyncJoinedBySeparatorSequence.Iterator: Sendable + where + Base: Sendable, + Base.Element: Sendable, + Base.Element.Element: Sendable, + Base.AsyncIterator: Sendable, + Separator: Sendable, + Separator.AsyncIterator: Sendable, + Base.Element.AsyncIterator: Sendable { } +``` + +The resulting `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments conform. + +When any of the asynchronous sequences being joined together come to their end of iteration, the `Joined` sequence iteration proceeds to the separator asynchronous sequence, if any. When the separator asynchronous sequence terminates, or if no sepaerator was specified, it proceeds on to the next asynchronous sequence. When the last asynchronous sequence reaches the end of iteration the `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` then ends its iteration. At any point in time if one of the comprising asynchronous sequences ever throws an error during iteration the `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` iteration will throw that error and end iteration. + +## Future Directions + +The Swift Algorithms package has [additional synchronous variants of `joined()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Joined.md). It is conceivable to bring asynchronous variants of those over to `AsyncSequence`. + +The variant that takes a single element as a separator is straightforward, but can be trivially replicated with `[element].async`. However, it may be beneficial for performance to reimplement this directly. + +There is another variant that takes a closure that allows one to customize the separator based on the return value of a closure. That closure is passed each of the two consecutive asynchronous sequences (not the two neighboring elements in consecutive sequences). This variant arguably has the greatest utility when the sequence type conforms to `Collection`, allowing either the `count` or any arbitrary element to be obtained directly. With `AsyncSequence`, it is less likely that this function with provide a similar level of utility, so it has been omitted. + +## Alternatives Considered + +Because `joined()` is essentially identical to `flatMap { $0 }`, it was considered that this should be called `flatten()` instead. However, it is preferable to follow the lead of the Swift standard library's `joined()` method. + +## Credits/Inspiration + +The Swift standard library has functions on synchronous sequences ([`joined()`](https://developer.apple.com/documentation/swift/sequence/1641166-joined), [`joined(separator:)`](https://developer.apple.com/documentation/swift/sequence/2431985-joined)) that perform similar (but synchronous) tasks. diff --git a/Guides/Lazy.md b/Guides/Lazy.md index 2d0ef33..3254ab0 100644 --- a/Guides/Lazy.md +++ b/Guides/Lazy.md @@ -32,10 +32,6 @@ extension AsyncLazySequence: Sendable where Base: Sendable { } extension AsyncLazySequence.Iterator: Sendable where Base.Iterator: Sendable { } ``` -The resulting `AsyncLazySequence` is an `AsyncSequence`, with conditional conformance to `Sendable`, `Codable`, `Equatable`, -and `Hashable` when the base type conforms to these protocols. - - ### Naming This property's and type's name match the naming approaches in the Swift standard library. The property is named with a diff --git a/Guides/Reductions.md b/Guides/Reductions.md new file mode 100644 index 0000000..d86484f --- /dev/null +++ b/Guides/Reductions.md @@ -0,0 +1,131 @@ +# Reductions + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncExclusiveReductionsSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestReductions.swift) +] + +## Introduction + +The family of algorithms for reduce are useful for converting a sequence or asynchronous sequence into a single value, but that can elide important intermediate information. The _reductions_ algorithm is often called "scan", but this name does not convey its heritage to the family of reducing. + +There are two strategies that are usable for creating continuous reductions: exclusive reductions and inclusive reductions: + + * Exclusive reductions take a value and incorporate values into that initial value. A common example is reductions by appending to an array. + * Inclusive reductions transact only on the values provided. A common example is adding numbers. + +## Proposed Solution + +Exclusive reductions come in two variants: transforming by application, or transformation via mutation. This replicates the same interface as `reduce(_:_:)` and `reduce(into:_:)`. Unlike the `reduce` algorithms, the `reductions` algorithm also comes in two flavors: throwing or non throwing transformations. + +```swift +extension AsyncSequence { + public func reductions( + _ initial: Result, + _ transform: @Sendable @escaping (Result, Element) async -> Result + ) -> AsyncExclusiveReductionsSequence + + public func reductions( + into initial: Result, + _ transform: @Sendable @escaping (inout Result, Element) async -> Void + ) -> AsyncExclusiveReductionsSequence +} + +extension AsyncSequence { + public func reductions( + _ initial: Result, + _ transform: @Sendable @escaping (Result, Element) async throws -> Result + ) -> AsyncThrowingExclusiveReductionsSequence + + public func reductions( + into initial: Result, + _ transform: @Sendable @escaping (inout Result, Element) async throws -> Void + ) -> AsyncThrowingExclusiveReductionsSequence +} +``` + +These APIs can be used to reduce an initial value progressively or reduce into an initial value via mutation. In practice, a common use case for reductions is to mutate a collection by appending values. + +```swift +characters.reductions(into: "") { $0.append($1) } +``` + +If the characters being produced asynchronously are `"a", "b", "c"`, then the iteration of the reductions is `"a", "ab", "abc"`. + +Inclusive reductions do not have an initial value and therefore do not need an additional variations beyond the throwing and non throwing flavors. + +```swift +extension AsyncSequence { + public func reductions( + _ transform: @Sendable @escaping (Element, Element) async -> Element + ) -> AsyncInclusiveReductionsSequence + + public func reductions( + _ transform: @Sendable @escaping (Element, Element) async throws -> Element + ) -> AsyncThrowingInclusiveReductionsSequence +} +``` + +This is often used for scenarios like a running tally or other similar cases. + +```swift +numbers.reductions { $0 + $1 } +``` + +In the above example, if the numbers are a sequence of `1, 2, 3, 4`, the produced values would be `1, 3, 6, 10`. + +## Detailed Design + +The exclusive reduction variants come in two distinct cases: non-throwing and throwing. These both have corresponding types to encompass that throwing behavior. + +For non-throwing exclusive reductions, the element type of the sequence is the result of the reduction transform. `AsyncExclusiveReductionsSequence` will throw if the base asynchronous sequence throws, and will not throw if the base does not throws. + +```swift +public struct AsyncExclusiveReductionsSequence { +} + +extension AsyncExclusiveReductionsSequence: AsyncSequence { + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Element? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncExclusiveReductionsSequence: Sendable + where Base: Sendable, Element: Sendable { } + +extension AsyncExclusiveReductionsSequence.Iterator: Sendable + where Base.AsyncIterator: Sendable, Element: Sendable { } +``` + +The sendability behavior of `AsyncExclusiveReductionsSequence` is such that when the base, base iterator, and element are `Sendable` then `AsyncExclusiveReductionsSequence` is `Sendable`. + +```swift +public struct AsyncThrowingExclusiveReductionsSequence { +} + +extension AsyncThrowingExclusiveReductionsSequence: AsyncSequence { + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async throws -> Element? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncThrowingExclusiveReductionsSequence: Sendable + where Base: Sendable, Element: Sendable { } + +extension AsyncThrowingExclusiveReductionsSequence.Iterator: Sendable + where Base.AsyncIterator: Sendable, Element: Sendable { } +``` + +## Alternatives Considered + +One alternate name for `reductions` was to name it `scan`; however the naming from the Swift Algorithms package offers considerably more inference to the heritage of what family of functions this algorithm belongs to. + +## Credits/Inspiration + +This transformation function is a direct analog to the synchronous version [defined in the Swift Algorithms package](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md) diff --git a/Guides/RemoveDuplicates.md b/Guides/RemoveDuplicates.md new file mode 100644 index 0000000..4f0bb7d --- /dev/null +++ b/Guides/RemoveDuplicates.md @@ -0,0 +1,93 @@ +# RemoveDuplicates + +* Author(s): [Kevin Perry](https://github.com/kperryua) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncRemoveDuplicatesSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestRemoveDuplicates.swift) +] + +## Introduction + +When processing values over time it is definitely possible that the same value may occur in a row. When the distinctness of the presence value is not needed it is useful to consider the values over time that are differing from the last. Particularly this can be expressed as removing duplicate values either in the case as they are directly `Equatable` or by a predicate. + +## Proposed Solution + +The `removeDuplicates()` and `removeDuplicates(by:)` APIs serve this purpose of removing duplicate values that occur. These algorithms test against the previous value and if the latest iteration of the base `AsyncSequence` is the same as the last it invokes `next()` again. The resulting `AsyncRemoveDuplicatesSequence` will ensure that no duplicate values occur next to each other. This should not be confused with only emitting unique new values; where each value is tested against a collected set of values. + +```swift +extension AsyncSequence where Element: Equatable { + public func removeDuplicates() -> AsyncRemoveDuplicatesSequence +} + +extension AsyncSequence { + public func removeDuplicates( + by predicate: @escaping @Sendable (Element, Element) async -> Bool + ) -> AsyncRemoveDuplicatesSequence + + public func removeDuplicates( + by predicate: @escaping @Sendable (Element, Element) async throws -> Bool + ) -> AsyncThrowingRemoveDuplicatesSequence +} +``` + +The `removeDuplicates` family comes in three variants. One variant is conditional upon the `Element` type being `Equatable`. This variation is a shorthand for writing `.removeDuplicates { $0 == $1 }`. The next variation is the closure version that allows for custom predicates to be applied. This algorithm allows for the cases where the elements themselves may not be equatable but portions of the element may be compared. Lastly is the variation that allows for comparison when the comparison method may throw. + +## Detailed Design + +In the cases where the `Element` type is `Equatable` or the non-trowing predicate variant these utilize the type `AsyncRemoveDuplicatesSequence`. The throwing predicate variant uses `AsyncThrowingRemoveDuplicatesSequence`. Both of these types are conditionally `Sendable` when the base, base element, and base iterator are `Sendable` + +The `AsyncRemoveDuplicatesSequence` will rethrow if the base asynchronous sequence throws and will not throw if the base asynchronous sequence does not throw. + +```swift +public struct AsyncRemoveDuplicatesSequence: AsyncSequence { + public typealias Element = Base.Element + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Element? + } + + public func makeAsyncIterator() -> Iterator { + Iterator(iterator: base.makeAsyncIterator(), predicate: predicate) + } +} + +extension AsyncRemoveDuplicatesSequence: Sendable + where Base: Sendable, Base.Element: Sendable, Base.AsyncIterator: Sendable { } + +extension AsyncRemoveDuplicatesSequence.Iterator: Sendable + where Base: Sendable, Base.Element: Sendable, Base.AsyncIterator: Sendable { } + +``` + +The `AsyncThrowingRemoveDuplicatesSequence` will rethrow if the base asynchronous sequence throws and still may throw if the base asynchronous sequence does not throw due to the predicate having the potential of throwing. + +```swift + +public struct AsyncThrowingRemoveDuplicatesSequence: AsyncSequence { + public typealias Element = Base.Element + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async throws -> Element? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncThrowingRemoveDuplicatesSequence: Sendable + where Base: Sendable, Base.Element: Sendable, Base.AsyncIterator: Sendable { } + +extension AsyncThrowingRemoveDuplicatesSequence.Iterator: Sendable + where Base: Sendable, Base.Element: Sendable, Base.AsyncIterator: Sendable { } + +``` + +## Alternatives Considered + +An alternative algorithm for uniqueness was considered but was discounted since it does not directly belong to this particular family of methods. + +The name of this method could be considered to belong to the `filter` family and could refer directly to the repetitions. There is distinct merit to considering the name to be `filterRepetitions` or `removeRepetitions`. Likewise the terminology of `drop` also has merit. + +## Credits/Inspiration + +The Combine framework has a [function for publishers](https://developer.apple.com/documentation/combine/publisher/removeduplicates()/) that performs a similar task. diff --git a/Guides/Select.md b/Guides/Select.md new file mode 100644 index 0000000..0598201 --- /dev/null +++ b/Guides/Select.md @@ -0,0 +1,54 @@ +# Task.select + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/TaskSelect.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestTaskSelect.swift) +] + +## Introduction + +A fundamental part of many algorithms is being able to select the first resolved task from a given list of active tasks. This enables algorithms like `debounce` or `merge`. + +## Proposed Solution + +Selecting the first task to complete from a list of active tasks is a similar algorithm to `select(2)`. This has similar behavior to `TaskGroup` except that instead of child tasks this function transacts upon already running tasks and does not cancel them upon completion of the selection and does not need to await for the completion of all of the tasks in the list to select. + +```swift +extension Task { + public static func select( + _ tasks: Tasks + ) async -> Task + + public static func select( + _ tasks: Task... + ) async -> Task +} +``` + +## Detailed Design + +Given any number of `Task` objects that share the same `Success` and `Failure` types; `Task.select` will suspend and await each tasks result and resume when the first task has produced a result. While the calling task of `Task.select` is suspended if that task is cancelled the tasks being selected receive the cancel. This is similar to the family of `TaskGroup` with a few behavioral and structural differences. + +The `withTaskGroup` API will create efficient child tasks. +The `Task.select` API takes pre-existing tasks. + +The `withTaskGroup` API will await all child tasks to be finished before returning. +The `Task.select` API will await for the first task to be finished before returning. + +The `withTaskGroup` API will cancel all outstanding child tasks upon awaiting its return. +The `Task.select` API will let the non selected tasks keep on running. + +The `withTaskGroup` can support having 0 child tasks. +The `Task.select` API requires at least 1 task to select over, anything less is a programmer error. + +This means that `withTaskGroup` is highly suited to run work in parallel, whereas `Task.select` is intended to find the first task that provides a value. There is inherent additional cost to the non-child tasks so `Task.select` should not be used as a replacement for anywhere that is more suitable as a group, but offers more potential for advanced algorithms. + +## Alternatives Considered + +## Future Directions + + + +## Credits/Inspiration diff --git a/Guides/Throttle.md b/Guides/Throttle.md new file mode 100644 index 0000000..cd3e0f4 --- /dev/null +++ b/Guides/Throttle.md @@ -0,0 +1,88 @@ +# Throttle + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncThrottleSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestThrottle.swift) +] + +## Introduction + +When events can potentially happen faster than the desired consumption rate, there are multiple ways to handle the situation. One approach is to emit values after a given period has elapsed. These emitted values can be reduced from the values encountered during the waiting period. This algorithm is commonly referred to as throttling. + +## Proposed Solution + +The throttle algorithm produces elements such that at least a specific interval has elapsed between them. It transacts by measuring against a specific clock. If values are produced by the base `AsyncSequence` the throttle does not resume its next iterator until the period has elapsed or unless a terminal event is encountered. + +The interface for this algorithm is available on all `AsyncSequence` types. Unlike other algorithms like `debounce`, the throttle algorithm does not need to create additional tasks or require any sort of tolerance because the interval is just measured. A shorthand implementation will be offered in conjunction where the clock is the `ContinuousClock`, which allows for easy construction with `Duration` values. An additional shorthand is offered to reduce the values such that it provides a "latest" or "earliest" value, representing the leading or trailing edge of a throttled region of production of events. + +```swift +extension AsyncSequence { + public func throttle( + for interval: C.Instant.Duration, + clock: C, + reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced + ) -> AsyncThrottleSequence + + public func throttle( + for interval: Duration, + reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced + ) -> AsyncThrottleSequence + + public func throttle( + for interval: C.Instant.Duration, + clock: C, + latest: Bool = true + ) -> AsyncThrottleSequence + + public func throttle( + for interval: Duration, + latest: Bool = true + ) -> AsyncThrottleSequence +} +``` + +This all boils down to a terse description of how to transform the asynchronous sequence over time. + +```swift +fastEvents.throttle(for: .seconds(1)) +``` + +In this case, the throttle transforms a potentially fast asynchronous sequence of events into one that waits for a window of 1 second to elapse before emitting a value. + +## Detailed Design + +The type that implements the algorithm for throttle emits the same element type as the base that it applies to. It also throws when the base type throws (and likewise does not throw when the base type does not throw). + +```swift +public struct AsyncThrottleSequence { +} + +extension AsyncThrottleSequence: AsyncSequence { + public typealias Element = Reduced + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async rethrows -> Reduced? + } + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncThrottleSequence: Sendable + where Base: Sendable, Element: Sendable { } +extension AsyncThrottleSequence.Iterator: Sendable + where Base.AsyncIterator: Sendable { } +``` + +The `AsyncThrottleSequence` and its `Iterator` are conditionally `Sendable` if the base types comprising it are `Sendable`. + +## Alternatives Considered + +It was considered to only provide the "latest" style APIs, however the reduction version grants more flexibility and can act as a funnel to the implementations of `latest`. + +## Credits/Inspiration + +http://reactivex.io/documentation/operators/sample.html + +https://developer.apple.com/documentation/combine/publishers/throttle/ diff --git a/Guides/Timer.md b/Guides/Timer.md new file mode 100644 index 0000000..931636d --- /dev/null +++ b/Guides/Timer.md @@ -0,0 +1,51 @@ +# Timer + +* Author(s): [Philippe Hausler](https://github.com/phausler) + +[ +[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncTimerSequence.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestTimer.swift) +] + +## Introduction + +Producing elements at regular intervals can be useful for composing with other algorithms. These can range from invoking code at specific times to using those regular intervals as a delimter of events. There are other cases this exists in APIs however those do not currently interact with Swift concurrency. These existing APIs are ones like `Timer` or `DispatchTimer` but are bound to internal clocks that are not extensible. + +## Proposed Solution + +We propose to add a new type; `AsyncTimerSequence` which utilizes the new `Clock`, `Instant` and `Duration` types. This allows the interaction of the timer to custom implementations of types adopting `Clock`. + +This asynchronous sequence will produce elements of the clock's `Instant` type after the interval has elapsed. That instant will be the `now` at the time that the sleep has resumed. For each invocation to `next()` the `AsyncTimerSequence.Iterator` will calculate the next deadline to resume and pass that and the tolerance to the clock. If at any point in time the task executing that iteration is cancelled the iteration will return `nil` from the call to `next()`. + +```swift +public struct AsyncTimerSequence: AsyncSequence { + public typealias Element = C.Instant + + public struct Iterator: AsyncIteratorProtocol { + public mutating func next() async -> C.Instant? + } + + public init( + interval: C.Instant.Duration, + tolerance: C.Instant.Duration? = nil, + clock: C + ) + + public func makeAsyncIterator() -> Iterator +} + +extension AsyncTimerSequence where C == SuspendingClock { + public static func repeating(every interval: Duration, tolerance: Duration? = nil) -> AsyncTimerSequence +} + +extension AsyncTimerSequence: Sendable { } +extension AsyncTimerSequence.Iterator: Sendable { } +``` + +Since all the types comprising `AsyncTimerSequence` and it's `Iterator` are `Sendable` these types are also `Sendable. + +## Credits/Inspiration + +https://developer.apple.com/documentation/foundation/timer + +https://developer.apple.com/documentation/foundation/timer/timerpublisher diff --git a/Guides/Zip.md b/Guides/Zip.md index de9440f..faedd09 100644 --- a/Guides/Zip.md +++ b/Guides/Zip.md @@ -78,7 +78,7 @@ It is common in some libraries to have a `ZipMap` or some other combination of ` ### Comparison with other libraries -**Swift** The swift standard library has an [API definition of zip](https://developer.apple.com/documentation/swift/1541125-zip) as a top level function for comining two sequences. +**Swift** The swift standard library has an [API definition of zip](https://developer.apple.com/documentation/swift/1541125-zip) as a top level function for combining two sequences. **ReactiveX** ReactiveX has an [API definition of Zip](https://reactivex.io/documentation/operators/zip.html) as a top level function for combinining Observables. diff --git a/README.md b/README.md index 8cb8f51..afe6004 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,20 @@ **Swift Async Algorithms** is an open-source package of asynchronous sequence and advanced algorithms that involve concurrency, along with their related types. +This package has three main goals: + +- First-class integration with `async/await` +- Provide a home for time-based algorithms +- Be cross-platform and open source + +## Motivation + + AsyncAlgorithms is a package for algorithms that work with *values over time*. That includes those primarily about *time*, like `debounce` and `throttle`, but also algorithms about *order* like `combineLatest` and `merge`. Operations that work with multiple inputs (like `zip` does on `Sequence`) can be surprisingly complex to implement, with subtle behaviors and many edge cases to consider. A shared package can get these details correct, with extensive testing and documentation, for the benefit of all Swift apps. + + The foundation for AsyncAlgorithms was included in Swift 5.5 from [AsyncSequence](https://github.com/apple/swift-evolution/blob/main/proposals/0298-asyncsequence.md). Swift 5.5 also brings the ability to use a natural `for/in` loop with `await` to process the values in an `AsyncSequence` and `Sequence`-equivalent API like `map` and `filter`. Structured concurrency allows us to write code where intermediate state is simply a local variable, `try` can be used directly on functions that `throw`, and generally treat the logic for asynchronous code similar to that of synchronous code. + +This package is the home for these APIs. Development and API design take place on [GitHub](https://github.com/apple/swift-async-algorithms) and the [Swift Forums](https://forums.swift.org/c/related-projects/). + ## Contents #### Combining asynchronous sequences @@ -10,35 +24,46 @@ - [`combineLatest(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/CombineLatest.md): Combines two or more asynchronous sequences into an asynchronous sequence producing a tuple of elements from those base asynchronous sequences that updates when any of the base sequences produce a value. - [`merge(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Merge.md): Merges two or more asynchronous sequence into a single asynchronous sequence producing the elements of all of the underlying asynchronous sequences. - [`zip(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Zip.md): Creates an asynchronous sequence of pairs built out of underlying asynchronous sequences. +- [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Joined.md): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element. #### Creating asynchronous sequences - [`async`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Lazy.md): Create an asynchronous sequence composed from a synchronous sequence. +- [`AsyncChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics. +- [`AsyncThrowingChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics that can emit failures. #### Performance optimized asynchronous iterators - [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions. #### Other useful asynchronous sequences -- [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element. -- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Remove nil values from an asynchronous sequence. -- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Remove sequentially adjacent duplicate values. +- [`chunks(...)` and `chunked(...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Chunked.md): Collect values into chunks. +- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Compacted.md): Remove nil values from an asynchronous sequence. +- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/RemoveDuplicates.md): Remove sequentially adjacent duplicate values. - [`interspersed(with:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of an asynchronous sequence. +#### Asynchronous Sequences that transact in time + +- [`debounce(for:tolerance:clock:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Debounce.md): Emit values after a quiessence period has been reached. +- [`throttle(for:clock:reducing:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Throttle.md): Ensure a minimum interval has elapsed between events. +- [`AsyncTimerSequence`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Timer.md): Emit the value of now at a given interval repeatedly. + #### Obtaining all values from an asynchronous sequence -- [`RangeReplaceableCollection.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Creates a new instance of a collection containing the elements of an asynchronous sequence. -- [`Dictionary.init(uniqueKeysWithValues:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Creates a new dictionary from the key-value pairs in the given asynchronous sequence. -- [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys. -- [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): /// Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key. -- [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Creates a new set from an asynchronous sequence of items. +- [`RangeReplaceableCollection.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new instance of a collection containing the elements of an asynchronous sequence. +- [`Dictionary.init(uniqueKeysWithValues:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence. +- [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys. +- [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): /// Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key. +- [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new set from an asynchronous sequence of items. #### Task management -- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Determine the first task to complete of a sequence of tasks. +- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Select.md): Determine the first task to complete of a sequence of tasks. -#### +#### Effects + +Each algorithm has specific behavioral effects. For throwing effects these can either be if the sequence throws, does not throw, or rethrows errors. Sendability effects in some asynchronous sequences are conditional whereas others require the composed parts to all be sendable to satisfy a requirement of `Sendable`. The effects are [listed here](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Effects.md). ## Adding Swift Algorithms as a Dependency @@ -59,6 +84,26 @@ Include `"AsyncAlgorithms"` as a dependency for your executable target: Finally, add `import AsyncAlgorithms` to your source code. +## Getting Started + +⚠️ Please note that this package currently requires a recent [Swift Trunk Development toolchain](https://www.swift.org/download/#trunk-development-main). More information on how to use custom toolchains with Xcode can be viewed [here](https://developer.apple.com/library/archive/documentation/ToolsLanguages/Conceptual/Xcode_Overview/AlternativeToolchains.html). + +### Building/Testing Using Xcode on macOS + + 1. Download the most recent development Xcode toolchain. + 2. Install the package + 4. Select the development toolchain in Xcode + 4. Open the `swift-async-algorithms` package directory in Xcode + 5. Build or Test in Xcode as normal + +⚠️ Note: `swift test` does not currently work properly with custom toolchains for this package. + +### Building/Testing on Linux + + 1. Download the most recent development toolchain for your Linux distribution + 2. Decompress the archive to a path in which the `swift` executable is in the binary search path environment variable (`$PATH`) + 3. In the `swift-async-algorithms` directory run `swift build` or `swift test` accordingly + ## Source Stability The Swift Async Algorithms package has a goal of being source stable as soon as possible; version numbers will follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version. diff --git a/Sources/AsyncAlgorithms/AsyncInclusiveReductionsSequence.swift b/Sources/AsyncAlgorithms/AsyncInclusiveReductionsSequence.swift index 7df0fc2..7514502 100644 --- a/Sources/AsyncAlgorithms/AsyncInclusiveReductionsSequence.swift +++ b/Sources/AsyncAlgorithms/AsyncInclusiveReductionsSequence.swift @@ -3,7 +3,8 @@ extension AsyncSequence { /// elements of the asynchronous sequence using the given closure. /// /// This can be seen as applying the reduce function to each element and - /// providing the initial value followed by these results as an asynchronous sequence. + /// producing an asynchronous sequence consisting of the initial value followed + /// by these results. /// /// ``` /// let runningTotal = [1, 2, 3, 4].async.reductions(+)