diff --git a/Sources/NIOCore/AsyncAwaitSupport.swift b/Sources/NIOCore/AsyncAwaitSupport.swift index 7b1afd77d..dcc1d2f35 100644 --- a/Sources/NIOCore/AsyncAwaitSupport.swift +++ b/Sources/NIOCore/AsyncAwaitSupport.swift @@ -83,6 +83,9 @@ extension EventLoopFuture { /// /// This function can be used to bridge an `EventLoopFuture` into the `async` world. Ie. if you're in an `async` /// function and want to get the result of this future. + /// + /// - seealso: ``getAbandoningOnCancel()`` which returns a `CancellationError` on cancellation (by abandoning this + /// future) instead of ignoring cancellation altogether. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @preconcurrency @inlinable @@ -98,6 +101,33 @@ extension EventLoopFuture { } }.wrappedValue } + + /// Get the value/error from an `EventLoopFuture` in an `async` context, abandoning the future on cancellation. + /// + /// - warning: This method still violates Structured Concurrency: Cancelling the surrounding task does _not_ + /// cancel the operation that this future represents, it merely _abandons_ the future. In other words, the + /// operation is likely still ongoing (holding on to its resources) and its result will be dropped. Unlike + /// ``get()`` however, this method _will_ return promptly on cancellation, throwing `CancellationError`. + /// + /// This function can be used to bridge an `EventLoopFuture` into the `async` world. Ie. if you're in an `async` + /// function and want to get the result of this future. + /// + /// If cancellation and the completion of this future race, either the future's result or a `CancellationError` + /// may be returned. + /// + /// - seealso: ``get()`` which ignores cancellation entirely and therefore only returns once this future completes. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @inlinable + public func getAbandoningOnCancel() async throws -> Value where Value: Sendable { + let promise = self.eventLoop.makePromise(of: Value.self) + self.cascade(to: promise) + return try await withTaskCancellationHandler { + try await promise.futureResult.get() + } onCancel: { + // If the future completes first, this is a no-op (first completion wins). + promise.fail(CancellationError()) + } + } } #if canImport(Dispatch) diff --git a/Sources/NIOCore/Docs.docc/swift-concurrency.md b/Sources/NIOCore/Docs.docc/swift-concurrency.md index dd3b08369..120d74d9b 100644 --- a/Sources/NIOCore/Docs.docc/swift-concurrency.md +++ b/Sources/NIOCore/Docs.docc/swift-concurrency.md @@ -16,7 +16,10 @@ methods are ``EventLoopFuture/get()`` and ``EventLoopPromise/completeWithTask(_:)``. > Warning: The future ``EventLoopFuture/get()`` method does not support task -> cancellation. +> cancellation. If you need to return on cancellation, use +> ``EventLoopFuture/getAbandoningOnCancel()``: it throws `CancellationError` +> when the `Task` is cancelled but it merely _abandons_ the future, i.e. the +> operation backing the future is likely still ongoing. Here is a small example of how these work: diff --git a/Tests/NIOPosixTests/EventLoopFutureGetAbandoningOnCancelTests.swift b/Tests/NIOPosixTests/EventLoopFutureGetAbandoningOnCancelTests.swift new file mode 100644 index 000000000..3207aba95 --- /dev/null +++ b/Tests/NIOPosixTests/EventLoopFutureGetAbandoningOnCancelTests.swift @@ -0,0 +1,125 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIOCore +import NIOPosix +import Testing + +private struct DummyError: Error {} + +@Suite("EventLoopFuture.getAbandoningOnCancel()") +struct EventLoopFutureGetAbandoningOnCancelTests { + private let loop = MultiThreadedEventLoopGroup.singleton.next() + + @Test + func returnsValueOfAlreadySucceededFuture() async throws { + let value = try await self.loop.makeSucceededFuture(42).getAbandoningOnCancel() + #expect(value == 42) + } + + @Test + func returnsValueOfFutureThatSucceedsLater() async throws { + let promise = self.loop.makePromise(of: Int.self) + + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + let value = try await promise.futureResult.getAbandoningOnCancel() + #expect(value == 42) + } + promise.succeed(42) + try await group.waitForAll() + } + } + + @Test + func throwsErrorOfFailedFuture() async throws { + let future: EventLoopFuture = self.loop.makeFailedFuture(DummyError()) + await #expect(throws: DummyError.self) { + try await future.getAbandoningOnCancel() + } + } + + @Test + func throwsCancellationErrorAndAbandonsTheFutureOnCancellation() async throws { + let promise = self.loop.makePromise(of: Int.self) + let awaitingPromise = self.loop.makePromise(of: Void.self) + + await withTaskGroup(of: Void.self) { group in + group.addTask { + awaitingPromise.succeed(()) + await #expect(throws: CancellationError.self) { + try await promise.futureResult.getAbandoningOnCancel() + } + } + + // Give the child task a chance to actually suspend on the future before we cancel it. Both orderings + // (cancellation before and after the suspension) must throw `CancellationError` though. + try? await awaitingPromise.futureResult.get() + try? await self.loop.submit {}.get() + + group.cancelAll() + } + + // Cancellation only abandoned the future, it didn't complete it: The underlying operation is still ongoing and + // completing it later works just as before. + promise.succeed(42) + let value = try await promise.futureResult.get() + #expect(value == 42) + } + + @Test + func throwsCancellationErrorIfTheTaskIsAlreadyCancelled() async throws { + let promise = self.loop.makePromise(of: Int.self) + + await withTaskGroup(of: Void.self) { group in + group.addTask { + while !Task.isCancelled { + await Task.yield() + } + await #expect(throws: CancellationError.self) { + try await promise.futureResult.getAbandoningOnCancel() + } + } + group.cancelAll() + } + + // The future itself is untouched, so we still need to complete it (or we'd leak an unfulfilled promise). + promise.succeed(42) + let value = try await promise.futureResult.get() + #expect(value == 42) + } + + @Test + func survivesCancellationRacingTheFuturesCompletion() async throws { + for _ in 0..<100 { + let promise = self.loop.makePromise(of: Int.self) + + await withTaskGroup(of: Void.self) { group in + group.addTask { + do { + let value = try await promise.futureResult.getAbandoningOnCancel() + #expect(value == 42) + } catch is CancellationError { + // Also acceptable: cancellation won the race. + } catch { + Issue.record("unexpected error: \(error)") + } + } + + promise.succeed(42) + group.cancelAll() + } + } + } +}