Add whenAllComplete EventLoopFuture method (#773)

* Add `whenAllComplete` method to group a homogenous array of future results into a single ELF
This commit is contained in:
Nathan Harris authored and Cory Benfield committed 2019-01-25 10:03:11 +00:00
1 parent 3563b9d795
commit 30f1a544d0
3 files changed
+133

No files matched your search

+58
View File
@@ -106,6 +106,9 @@ private struct CallbackList: ExpressibleByArrayLiteral {
}
/// Internal error for operations that return results that were not replaced
private struct OperationPlaceholderError: Error { }
/// A promise to provide a result later.
///
/// This is the provider API for `EventLoopFuture<Value>`. If you want to return an
@@ -983,6 +986,61 @@ extension EventLoopFuture {
}
}
extension EventLoopFuture {
/// Returns a new `EventLoopFuture` that succeeds when all of the provided `EventLoopFuture`s complete.
/// The new `EventLoopFuture` will contain an array of results, maintaining ordering for each of the `EventLoopFuture`s.
///
/// The returned `EventLoopFuture` always succeeds, regardless of any failures from the waiting futures.
///
/// If it is desired to flatten them into a single `EventLoopFuture` that fails on the first `EventLoopFuture` failure,
/// use one of the `reduce` methods instead.
/// - Parameter futures: An array of homogenous `EventLoopFuture`s to gather results from.
/// - Returns: A new `EventLoopFuture` with all the results of the provided futures.
public static func whenAllComplete(_ futures: [EventLoopFuture<Value>],
eventLoop: EventLoop) -> EventLoopFuture<[Result<Value, Error>]> {
let promise = eventLoop.makePromise(of: [Result<Value, Error>].self)
if eventLoop.inEventLoop {
_whenAllComplete0(promise, futures, eventLoop: eventLoop)
} else {
eventLoop.execute {
_whenAllComplete0(promise, futures, eventLoop: eventLoop)
}
}
return promise.futureResult
}
private static func _whenAllComplete0<InputValue>(_ promise: EventLoopPromise<[Result<InputValue, Error>]>,
_ futures: [EventLoopFuture<InputValue>],
eventLoop: EventLoop) {
eventLoop.assertInEventLoop()
var remainingCount = futures.count
var results: [Result<InputValue, Error>] = .init(repeating: .failure(OperationPlaceholderError()), count: futures.count)
// loop through the futures to chain callbacks to execute on the initiating event loop and grab their index
// in the "futures" to store their result in the same location
for (index, future) in futures.enumerated() {
future.hopTo(eventLoop: eventLoop)
.whenComplete { result in
results[index] = result
remainingCount -= 1
guard remainingCount == 0 else { return }
// verify that all operations have been completed
assert(!results.contains(where: {
guard case let .failure(error) = $0 else { return false }
return error is OperationPlaceholderError
}))
promise.succeed(results)
}
}
}
}
public extension EventLoopFuture {
/// Returns an `EventLoopFuture` that fires when this future completes, but executes its callbacks on the
/// target event loop instead of the original one.
@@ -64,6 +64,9 @@ extension EventLoopFutureTest {
("testLoopHoppingHelperNoHopping", testLoopHoppingHelperNoHopping),
("testFlatMapResultHappyPath", testFlatMapResultHappyPath),
("testFlatMapResultFailurePath", testFlatMapResultFailurePath),
("testWhenAllCompleteResultsWithFailuresStillSucceed", testWhenAllCompleteResultsWithFailuresStillSucceed),
("testWhenAllCompleteResults", testWhenAllCompleteResults),
("testWhenAllCompleteResolvesAfterFutures", testWhenAllCompleteResolvesAfterFutures),
]
}
}
+72
View File
@@ -859,4 +859,76 @@ class EventLoopFutureTest : XCTestCase {
XCTAssert(type(of: error) == DummyError.self)
}
}
func testWhenAllCompleteResultsWithFailuresStillSucceed() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let future = EventLoopFuture.whenAllComplete([
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(true)
], eventLoop: group.next())
XCTAssertNoThrow(try future.wait())
}
func testWhenAllCompleteResults() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let results = try EventLoopFuture.whenAllComplete([
group.next().makeSucceededFuture(3),
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(10),
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(5)
], eventLoop: group.next()).wait()
XCTAssertEqual(try results[0].get(), 3)
XCTAssertThrowsError(try results[1].get())
XCTAssertEqual(try results[2].get(), 10)
XCTAssertThrowsError(try results[3].get())
XCTAssertEqual(try results[4].get(), 5)
}
func testWhenAllCompleteResolvesAfterFutures() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let promises = (0..<5).map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture = EventLoopFuture.whenAllComplete(futures, eventLoop: group.next())
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
// Should be false, as none of the promises have completed yet
XCTAssertFalse(succeeded)
// complete the first four promises
for (index, promise) in promises.dropLast().enumerated() {
promise.succeed(index)
}
// Should still be false, as one promise hasn't completed yet
XCTAssertFalse(succeeded)
// Complete the last promise
completedPromises = true
promises.last!.succeed(4)
let results = try assertNoThrowWithValue(mainFuture.wait().map { try $0.get() })
XCTAssertEqual(results, [0, 1, 2, 3, 4])
}
}