diff --git a/Sources/NIO/EventLoopFuture.swift b/Sources/NIO/EventLoopFuture.swift index 2ecba4b6b..a47b5778c 100644 --- a/Sources/NIO/EventLoopFuture.swift +++ b/Sources/NIO/EventLoopFuture.swift @@ -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`. 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], + eventLoop: EventLoop) -> EventLoopFuture<[Result]> { + let promise = eventLoop.makePromise(of: [Result].self) + + if eventLoop.inEventLoop { + _whenAllComplete0(promise, futures, eventLoop: eventLoop) + } else { + eventLoop.execute { + _whenAllComplete0(promise, futures, eventLoop: eventLoop) + } + } + + return promise.futureResult + } + + private static func _whenAllComplete0(_ promise: EventLoopPromise<[Result]>, + _ futures: [EventLoopFuture], + eventLoop: EventLoop) { + eventLoop.assertInEventLoop() + + var remainingCount = futures.count + var results: [Result] = .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. diff --git a/Tests/NIOTests/EventLoopFutureTest+XCTest.swift b/Tests/NIOTests/EventLoopFutureTest+XCTest.swift index bc94881c8..1f163120f 100644 --- a/Tests/NIOTests/EventLoopFutureTest+XCTest.swift +++ b/Tests/NIOTests/EventLoopFutureTest+XCTest.swift @@ -64,6 +64,9 @@ extension EventLoopFutureTest { ("testLoopHoppingHelperNoHopping", testLoopHoppingHelperNoHopping), ("testFlatMapResultHappyPath", testFlatMapResultHappyPath), ("testFlatMapResultFailurePath", testFlatMapResultFailurePath), + ("testWhenAllCompleteResultsWithFailuresStillSucceed", testWhenAllCompleteResultsWithFailuresStillSucceed), + ("testWhenAllCompleteResults", testWhenAllCompleteResults), + ("testWhenAllCompleteResolvesAfterFutures", testWhenAllCompleteResolvesAfterFutures), ] } } diff --git a/Tests/NIOTests/EventLoopFutureTest.swift b/Tests/NIOTests/EventLoopFutureTest.swift index 6e7135245..5dfbf6149 100644 --- a/Tests/NIOTests/EventLoopFutureTest.swift +++ b/Tests/NIOTests/EventLoopFutureTest.swift @@ -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]) + } }