Skip to content

Commit

Permalink
Rename combinators, introduce CompositeLengthException (#383)
Browse files Browse the repository at this point in the history
  • Loading branch information
kelunik authored Jan 16, 2022
1 parent cadf1c0 commit 2a07609
Show file tree
Hide file tree
Showing 8 changed files with 202 additions and 76 deletions.
4 changes: 2 additions & 2 deletions src/CompositeException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class CompositeException extends \Exception

/**
* @param non-empty-array<array-key, \Throwable> $reasons Array of exceptions.
* @param string|null $message Exception message, defaults to message generated from passed exceptions.
* @param string|null $message Exception message, defaults to message generated from passed exceptions.
*
* @psalm-assert non-empty-array<array-key, \Throwable> $reasons
*/
Expand All @@ -36,7 +36,7 @@ public function getReasons(): array
private function generateMessage(array $reasons): string
{
$message = \sprintf(
'Multiple errors encountered (%d); use "%s::getReasons()" to retrieve the array of exceptions thrown:',
'Multiple exceptions encountered (%d); use "%s::getReasons()" to retrieve the array of exceptions thrown:',
\count($reasons),
self::class
);
Expand Down
11 changes: 11 additions & 0 deletions src/CompositeLengthException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Amp;

final class CompositeLengthException extends \Exception
{
public function __construct(string $message)
{
parent::__construct($message);
}
}
156 changes: 135 additions & 21 deletions src/Future/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Amp\Cancellation;
use Amp\CompositeException;
use Amp\CompositeLengthException;
use Amp\Future;

/**
Expand All @@ -14,57 +15,106 @@
* @template T
*
* @param iterable<Future<T>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return T
*
* @throws \Error If $futures is empty.
* @throws CompositeLengthException If {@code $futures} is empty.
*/
function race(iterable $futures, ?Cancellation $cancellation = null): mixed
function awaitFirst(iterable $futures, ?Cancellation $cancellation = null): mixed
{
foreach (Future::iterate($futures, $cancellation) as $first) {
return $first->await();
}

throw new \Error('No future provided');
throw new CompositeLengthException('Argument #1 ($futures) is empty');
}

/**
* Unwraps the first successfully completed future.
* Unwraps the first completed future.
*
* If you want the first future completed without an error, use {@see any()} instead.
*
* @template T
*
* If you want the first future completed, successful or not, use {@see race()} instead.
* @param iterable<Future<T>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return T
*
* @throws CompositeLengthException If $futures is empty.
*
* @deprecated Use {@see awaitFirst()} instead.
*/
function race(iterable $futures, ?Cancellation $cancellation = null): mixed
{
return awaitFirst($futures, $cancellation);
}

/**
* Awaits the first successfully completed future, ignoring errors.
*
* If you want the first future completed, successful or not, use {@see awaitFirst()} instead.
*
* @template Tk of array-key
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return Tv
*
* @throws CompositeException If all futures errored.
* @throws CompositeLengthException If {@code $futures} is empty.
*/
function any(iterable $futures, ?Cancellation $cancellation = null): mixed
function awaitAny(iterable $futures, ?Cancellation $cancellation = null): mixed
{
$result = some($futures, 1, $cancellation);
$result = awaitAnyN(1, $futures, $cancellation);
return $result[\array_key_first($result)];
}

/**
* Awaits the first successfully completed future, ignoring errors.
*
* If you want the first future completed, successful or not, use {@see awaitFirst()} instead.
*
* @template Tk of array-key
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return non-empty-array<Tk, Tv>
* @return Tv
*
* @throws CompositeException If all futures errored.
* @throws CompositeLengthException If {@code $futures} is empty.
*
* @deprecated Use {@see awaitFirst()} instead.
*/
function some(iterable $futures, int $count, ?Cancellation $cancellation = null): array
function any(iterable $futures, ?Cancellation $cancellation = null): mixed
{
return awaitAny($futures, $cancellation);
}

/**
* Awaits the first N successfully completed futures, ignoring errors.
*
* @template Tk of array-key
* @template Tv
*
* @param positive-int $count
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return non-empty-array<Tk, Tv>
*
* @throws CompositeException If too many futures errored.
* @throws CompositeLengthException If {@code $futures} is empty.
*/
function awaitAnyN(int $count, iterable $futures, ?Cancellation $cancellation = null): array
{
if ($count <= 0) {
throw new \ValueError('The count must be greater than 0, got ' . $count);
throw new \ValueError('Argument #1 ($count) must be greater than 0, got ' . $count);
}

$values = [];
Expand All @@ -81,8 +131,8 @@ function some(iterable $futures, int $count, ?Cancellation $cancellation = null)
}
}

if (empty($errors)) {
throw new \Error('Iterable did provide enough futures to satisfy the required count of ' . $count);
if (\count($values) + \count($errors) < $count) {
throw new CompositeLengthException('Argument #2 ($futures) contains too few futures to satisfy the required count of ' . $count);
}

/**
Expand All @@ -96,11 +146,35 @@ function some(iterable $futures, int $count, ?Cancellation $cancellation = null)
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
* @param positive-int $count
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return non-empty-array<Tk, Tv>
*
* @throws CompositeException If all futures errored.
* @throws CompositeLengthException If {@code $futures} is empty.
*
* @deprecated Use {@see awaitAnyN()} instead.
*/
function some(iterable $futures, int $count, ?Cancellation $cancellation = null): array
{
return awaitAnyN($count, $futures, $cancellation);
}

/**
* Awaits all futures to complete or error.
*
* This awaits all futures without aborting on first error (unlike {@see await()}).
*
* @template Tk of array-key
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return array{array<Tk, \Throwable>, array<Tk, Tv>}
*/
function settle(iterable $futures, ?Cancellation $cancellation = null): array
function awaitAll(iterable $futures, ?Cancellation $cancellation = null): array
{
$values = [];
$errors = [];
Expand All @@ -117,18 +191,39 @@ function settle(iterable $futures, ?Cancellation $cancellation = null): array
}

/**
* Awaits all futures to complete or aborts if any errors. The returned array keys will be in the order the futures
* resolved, not in the order given by the iterable. Sort the array after resolution if necessary.
* @template Tk of array-key
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return array{array<Tk, \Throwable>, array<Tk, Tv>}
*
* @deprecated Use {@see awaitAll()} instead.
*/
function settle(iterable $futures, ?Cancellation $cancellation = null): array
{
return awaitAll($futures, $cancellation);
}

/**
* Awaits all futures to complete or aborts if any errors.
*
* The returned array keys will be in the order the futures resolved, not in the order given by the iterable.
* Sort the array after completion if necessary.
*
* This is equivalent to awaiting all futures in a loop, except that it aborts as soon as one of the futures errors
* instead of relying on the order in the iterable and awaiting the futures sequentially.
*
* @template Tk of array-key
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return array<Tk, Tv> Unwrapped values with the order preserved.
*/
function all(iterable $futures, Cancellation $cancellation = null): array
function await(iterable $futures, ?Cancellation $cancellation = null): array
{
$values = [];

Expand All @@ -140,3 +235,22 @@ function all(iterable $futures, Cancellation $cancellation = null): array
/** @var array<Tk, Tv> */
return $values;
}

/**
* Awaits all futures to complete or aborts if any errors. The returned array keys will be in the order the futures
* resolved, not in the order given by the iterable. Sort the array after resolution if necessary.
*
* @template Tk of array-key
* @template Tv
*
* @param iterable<Tk, Future<Tv>> $futures
* @param Cancellation|null $cancellation Optional cancellation.
*
* @return array<Tk, Tv> Unwrapped values with the order preserved.
*
* @deprecated Use {@see await()} instead.
*/
function all(iterable $futures, ?Cancellation $cancellation = null): array
{
return await($futures, $cancellation);
}
16 changes: 8 additions & 8 deletions test/Future/SettleTest.php → test/Future/AwaitAllTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,38 @@
use PHPUnit\Framework\TestCase;
use Revolt\EventLoop;

class SettleTest extends TestCase
class AwaitAllTest extends TestCase
{
public function testSingleComplete(): void
{
self::assertSame([[], [42]], settle([Future::complete(42)]));
self::assertSame([[], [42]], awaitAll([Future::complete(42)]));
}

public function testTwoComplete(): void
{
self::assertSame([[], [1, 2]], settle([Future::complete(1), Future::complete(2)]));
self::assertSame([[], [1, 2]], awaitAll([Future::complete(1), Future::complete(2)]));
}

public function testTwoFirstThrowing(): void
{
$exception = new \Exception('foo');
self::assertSame(
[['one' => $exception], ['two' => 2]],
settle(['one' => Future::error($exception), 'two' => Future::complete(2)])
awaitAll(['one' => Future::error($exception), 'two' => Future::complete(2)])
);
}

public function testTwoBothThrowing(): void
{
$one = new \Exception('foo');
$two = new \RuntimeException('bar');
self::assertSame([[$one, $two], []], Future\settle([Future::error($one), Future::error($two)]));
self::assertSame([[$one, $two], []], Future\awaitAll([Future::error($one), Future::error($two)]));
}

public function testTwoGeneratorThrows(): void
{
$exception = new \Exception('foo');
self::assertSame([[0 => $exception], [1 => 2]], settle((static function () use ($exception) {
self::assertSame([[0 => $exception], [1 => 2]], awaitAll((static function () use ($exception) {
yield Future::error($exception);
yield Future::complete(2);
})()));
Expand All @@ -55,7 +55,7 @@ public function testCancellation(): void
return $deferred;
}, \range(1, 3));

settle(\array_map(
awaitAll(\array_map(
fn (DeferredFuture $deferred) => $deferred->getFuture(),
$deferreds
), new TimeoutCancellation(0.05));
Expand All @@ -69,7 +69,7 @@ public function testCompleteBeforeCancellation(): void
return $deferred;
}, \range(1, 3));

self::assertSame([[], \range(1, 3)], settle(\array_map(
self::assertSame([[], \range(1, 3)], awaitAll(\array_map(
fn (DeferredFuture $deferred) => $deferred->getFuture(),
$deferreds
), new TimeoutCancellation(0.5)));
Expand Down
Loading

0 comments on commit 2a07609

Please sign in to comment.