Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow referencing a TimeoutCancellation #421

Open
wants to merge 3 commits into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 7 additions & 4 deletions src/TimeoutCancellation.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ final class TimeoutCancellation implements Cancellation
private readonly Cancellation $cancellation;

/**
* @param float $timeout Seconds until cancellation is requested.
* @param string $message Message for TimeoutException. Default is "Operation timed out".
* @param float $timeout Seconds until cancellation is requested.
* @param string $message Message for TimeoutException. Default is "Operation timed out".
* @param bool $unreference Whether to unreference the timer.
*/
public function __construct(float $timeout, string $message = "Operation timed out")
public function __construct(float $timeout, string $message = "Operation timed out", bool $unreference = true)
danog marked this conversation as resolved.
Show resolved Hide resolved
{
$this->cancellation = $source = new Internal\Cancellable;

Expand All @@ -37,7 +38,9 @@ public function __construct(float $timeout, string $message = "Operation timed o
$source->cancel(new TimeoutException($message));
});

EventLoop::unreference($this->watcher);
if ($unreference) {
EventLoop::unreference($this->watcher);
}
}

/**
Expand Down
17 changes: 17 additions & 0 deletions test/Cancellation/TimeoutCancellationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Amp\Cancellation;

use Amp\CancelledException;
use Amp\DeferredFuture;
use Amp\TestCase;
use Amp\TimeoutCancellation;
use Amp\TimeoutException;
Expand Down Expand Up @@ -42,4 +43,20 @@ public function testWatcherCancellation(): void
unset($cancellation);
self::assertSame($identifiers, EventLoop::getIdentifiers());
}

public function testWatcherUnreference(): void
{
$this->expectExceptionMessageMatches("/Event loop terminated without resuming the current suspension/");
$deferred = new DeferredFuture;
$cancellation = new TimeoutCancellation(0.001);
$deferred->getFuture()->await($cancellation);
}

public function testWatcherNoUnreference(): void
{
$this->expectException(CancelledException::class);
$cancellation = new TimeoutCancellation(0.001, unreference: false);
$deferred = new DeferredFuture;
$deferred->getFuture()->await($cancellation);
}
}