Skip to content
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions libp2p/utils/future.nim
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

{.push raises: [].}

import sequtils
import chronos

type AllFuturesFailedError* = object of CatchableError
Expand All @@ -31,3 +32,11 @@ proc anyCompleted*[T](futs: seq[Future[T]]): Future[Future[T]] {.async.} =

let index = requests.find(raceFut)
requests.del(index)

proc raceCancel*(
futs: seq[Future | InternalRaisesFuture]
): Future[void] {.async: (raises: [ValueError, CancelledError]).} =
try:
discard await race(futs)
finally:
Copy link
Contributor

Choose a reason for hiding this comment

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

there is no need for finally .. in particular, if race is cancelled, it should not cancel futs to maintain the race contract in general - ValueError means there are no futures, so nothing to cancel either

await noCancel allFutures(futs.filterIt(not it.finished).mapIt(it.cancelAndWait))
57 changes: 57 additions & 0 deletions tests/utils/testfuture.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{.used.}

# Nim-Libp2p
# Copyright (c) 2023 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.

import ../helpers
import ../../libp2p/utils/future

suite "Utils Future":
asyncTest "All Pending Tasks are canceled when returned future is canceled":
proc longRunningTaskA() {.async.} =
await sleepAsync(10.seconds)

proc longRunningTaskB() {.async.} =
await sleepAsync(10.seconds)

let
futureA = longRunningTaskA()
futureB = longRunningTaskB()

# Both futures should be canceled when raceCancel is called
await raceCancel(@[futureA, futureB]).cancelAndWait()
check futureA.cancelled
check futureB.cancelled

# Test where one task finishes immediately, leading to the cancellation of the pending task
asyncTest "Cancel Pending Tasks When One Completes":
proc quickTask() {.async.} =
return

proc slowTask() {.async.} =
await sleepAsync(10.seconds)

let
futureQuick = quickTask()
futureSlow = slowTask()

# The quick task finishes, so the slow task should be canceled
await raceCancel(@[futureQuick, futureSlow])
check futureQuick.finished
check futureSlow.cancelled

asyncTest "raceCancel with AsyncEvent":
let asyncEvent = newAsyncEvent()
let fut1 = asyncEvent.wait()
let fut2 = newAsyncEvent().wait()
asyncEvent.fire()
await raceCancel(@[fut1, fut2])

check fut1.finished
check fut2.cancelled