diff --git a/AGENTS.md b/AGENTS.md index 19a4db2d7a..196c708013 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -759,7 +759,7 @@ See the existing entries for database, Redis, Meilisearch, and Typesense as exam Components is analyzed with its own `hypervel/phpstan` extension. [Static Analysis](src/docs/static-analysis.md#fixing-and-ignoring-diagnostics) is the source of truth for each diagnostic's intended fix and legitimate exceptions; the rules below add Components-specific requirements. -**Keep `hypervel/phpstan` evolving** — Codify framework contracts and useful conventions to help agents avoid mistakes. When implementation or review reveals a pattern worth checking, verify realistic usage, reliable detection and proportionate complexity; reach peer consensus, then seek owner approval for the new rule. Investigate false positives on realistic code; fix analyzer defects rather than rewriting correct code to work around them. Keep inference limits explicit; do not add brittle machinery merely to handle unusual cases. +**Keep `hypervel/phpstan` evolving** — Codify framework contracts and useful conventions. Prefer a simple framework fix when it prevents the mistake. Add rules for mistakes likely to recur in packages or apps, even when existing cases are already fixed. Check each proposed rule against real mistakes and realistic correct usage. Reject rules that flag correct code or need a growing list of exceptions to avoid doing so. Keep inference limits explicit. Reach peer consensus, then seek owner approval for a new rule. If an existing rule flags correct code, fix the analyzer and leave the correct code alone. The `tests/` directory is excluded from phpstan. Do not run phpstan on tests. diff --git a/src/coroutine/src/Coroutine.php b/src/coroutine/src/Coroutine.php index d545d2eef4..936eb5637d 100644 --- a/src/coroutine/src/Coroutine.php +++ b/src/coroutine/src/Coroutine.php @@ -203,10 +203,57 @@ private static function runChild(callable $callable, array $context): void * that the timeout elapsed. It is not a general failure signal. * * @param list $coroutineIds + * @throws CanceledException if the caller is canceled during the wait */ public static function join(array $coroutineIds, float $timeout = -1): bool { - return Co::join($coroutineIds, $timeout); + $joined = Co::join($coroutineIds, $timeout); + + // Swoole rejects repeated live IDs before waiting. Retry only that case to avoid copying normal lists. + if (! $joined && swoole_last_error() === SWOOLE_ERROR_WRONG_OPERATION && count($coroutineIds) > 1) { + $distinctIds = array_keys(array_flip($coroutineIds)); + if (count($distinctIds) < count($coroutineIds)) { + $joined = Co::join($distinctIds, $timeout); + } + } + + // A join with no live targets doesn't yield, so isCanceled() can still describe an earlier wait. + if (! $joined && swoole_last_error() === SWOOLE_ERROR_CO_CANCELED) { + throw new CanceledException('Waiting for child coroutines was canceled.'); + } + + return $joined; + } + + /** + * Wait for the given coroutines to finish before propagating caller cancellation. + * + * A timeout of zero or less waits without limit, like join(). + * + * @param list $coroutineIds + * @return bool whether none of the supplied coroutines remain active + * @throws CanceledException if the caller was canceled during the wait + */ + public static function joinUninterruptibly(array $coroutineIds, float $timeout = -1): bool + { + $deadline = $timeout > 0 ? hrtime(true) / 1e9 + $timeout : null; + $cancellation = null; + $joined = false; + + do { + try { + $joined = static::join($coroutineIds, $timeout); + break; + } catch (CanceledException $exception) { + $cancellation ??= $exception; + } + } while ($deadline === null || ($timeout = $deadline - hrtime(true) / 1e9) > 0); + + if ($cancellation !== null) { + throw $cancellation; + } + + return $joined || ! array_any($coroutineIds, Co::exists(...)); } /** diff --git a/src/coroutine/src/Parallel.php b/src/coroutine/src/Parallel.php index 12407d6deb..b21840babb 100644 --- a/src/coroutine/src/Parallel.php +++ b/src/coroutine/src/Parallel.php @@ -169,11 +169,7 @@ public function wait(bool $throw = true): array // WaitGroup completion precedes the last child's physical teardown. if ($coroutineIds !== []) { - $joined = Coroutine::join($coroutineIds); - - if (! $joined && EngineCoroutine::isCanceled()) { - throw new CanceledException('Waiting for parallel child coroutines was canceled.'); - } + Coroutine::join($coroutineIds); } } catch (Throwable $throwable) { // Context copying can wrap the cancellation after earlier children started. diff --git a/src/coroutine/src/Waiter.php b/src/coroutine/src/Waiter.php index fcdc297c46..a2e5031fd0 100644 --- a/src/coroutine/src/Waiter.php +++ b/src/coroutine/src/Waiter.php @@ -109,18 +109,12 @@ public function wait( // Throw into the operation so an interrupted wait cannot be ignored accidentally, // then give the child a bounded interval to unwind and run deferred cleanup. $this->cancelChild($childCoroutineId, $childCancellationRequested); - $joined = Coroutine::join([$childCoroutineId], $this->pushTimeout); + Coroutine::join([$childCoroutineId], $this->pushTimeout); } catch (CanceledException $exception) { $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); throw $exception; } - if (! $joined && EngineCoroutine::isCanceled()) { - $exception = new CanceledException('Waiting for a child coroutine was canceled.'); - $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); - throw $exception; - } - // A false join may mean either timeout or a missing coroutine, so only // existence proves that the child survived the cleanup allowance. if ($waitForChildTermination && Coroutine::exists($childCoroutineId)) { @@ -142,18 +136,12 @@ public function wait( } try { - $joined = Coroutine::join([$childCoroutineId]); + Coroutine::join([$childCoroutineId]); } catch (CanceledException $exception) { $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); throw $exception; } - if (! $joined && EngineCoroutine::isCanceled()) { - $exception = new CanceledException('Waiting for a child coroutine was canceled.'); - $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); - throw $exception; - } - if ($result instanceof ExceptionThrower) { $exception = $result->getThrowable(); @@ -196,20 +184,12 @@ protected function cancelChild(?int $childCoroutineId, bool &$cancellationReques */ protected function awaitChildTermination(int $childCoroutineId): ?CanceledException { - $cancellation = null; - - // Each cancellation interrupts the join, so join again until the child is gone. - while (Coroutine::exists($childCoroutineId)) { - try { - if (! Coroutine::join([$childCoroutineId]) && EngineCoroutine::isCanceled()) { - $cancellation ??= new CanceledException('Waiting for a child coroutine was canceled.'); - } - } catch (CanceledException $exception) { - // @phpstan-ignore hypervel.cancellation.precedence (both values are this coroutine's direct cancellation) - $cancellation ??= $exception; - } + try { + Coroutine::joinUninterruptibly([$childCoroutineId]); + } catch (CanceledException $exception) { + return $exception; } - return $cancellation; + return null; } } diff --git a/src/docs/coroutines.md b/src/docs/coroutines.md index cc2ebea49d..637aab6cef 100644 --- a/src/docs/coroutines.md +++ b/src/docs/coroutines.md @@ -974,19 +974,9 @@ $coroutineIds = Coroutine::list(); The `join` method waits for the supplied child coroutine IDs to finish. You may include IDs for coroutines that have already finished. -A `false` result may mean that none of the supplied coroutines remained active or that the timeout elapsed. It does not always indicate a failure. +A `false` result may mean that all supplied coroutines had already finished or that the timeout elapsed. If the caller is canceled during the wait, `join` throws a `CanceledException`. -Low-level infrastructure that must distinguish a canceled native wait from its other `false` outcomes may inspect the engine cancellation state immediately: - -```php -use Hypervel\Engine\Coroutine as EngineCoroutine; - -if (! Coroutine::join($coroutineIds) && EngineCoroutine::isCanceled()) { - // The join was canceled... -} -``` - -This state is not durable. Read it only at the failed native operation boundary. +Use `joinUninterruptibly` when cleanup must wait for children to exit even if the caller is canceled. It waits until the children exit or the original timeout expires, then throws the caller's first cancellation. Without cancellation, it returns `true` if none of the supplied coroutines are still running. As with `join`, a timeout of zero or less waits without a deadline. The `afterCreated` method registers a callback that runs during child startup for `Coroutine::create`, `fork`, `createOwned`, and `forkOwned`, as well as helpers such as `go` and `co`: diff --git a/src/grpc/src/Client/Connection.php b/src/grpc/src/Client/Connection.php index 57c67d2e28..4a054b507d 100644 --- a/src/grpc/src/Client/Connection.php +++ b/src/grpc/src/Client/Connection.php @@ -764,11 +764,7 @@ private function terminateWhileLocked(ConnectionException $failure): ConnectionE // Native close must wait for physical receiver and engine-client cleanup. // A bounded join could still leave the socket owned when its timeout elapsed. - if (! Coroutine::join([$receiverCoroutineId]) && Coroutine::isCanceled()) { - $cancellation = new CanceledException( - 'Waiting for the gRPC response receiver to stop was canceled.', - ); - } + FrameworkCoroutine::joinUninterruptibly([$receiverCoroutineId]); } catch (CanceledException $exception) { $cancellation = $exception; } diff --git a/src/phpstan/src/Collectors/SwallowedCancellationCollector.php b/src/phpstan/src/Collectors/SwallowedCancellationCollector.php index 0abce8a574..3185b6048a 100644 --- a/src/phpstan/src/Collectors/SwallowedCancellationCollector.php +++ b/src/phpstan/src/Collectors/SwallowedCancellationCollector.php @@ -352,7 +352,7 @@ class SwallowedCancellationCollector implements Collector WaitConcurrent::class => [self::WAIT, ['create' => true, 'fork' => true, 'wait' => true]], Concurrency::class => [self::WAIT, ['run' => true]], SwooleCoroutine::class => [self::WAIT, ['join' => true, 'sleep' => true]], - Coroutine::class => [self::WAIT, ['join' => true, 'sleep' => true]], + Coroutine::class => [self::WAIT, ['join' => true, 'joinuninterruptibly' => true, 'sleep' => true]], EngineCoroutine::class => [self::WAIT, ['join' => true]], Sleep::class => [self::WAIT, ['then' => true]], ]; diff --git a/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php b/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php index b8b9b57e33..29b32dc550 100644 --- a/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php +++ b/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php @@ -77,7 +77,7 @@ class CoroutineRuleHelper 'Hypervel\Coroutine\WaitGroup' => ['add', 'done', 'wait'], 'Hypervel\Coroutine\Waiter' => ['wait'], 'Swoole\Coroutine' => ['join'], - 'Hypervel\Coroutine\Coroutine' => ['join'], + 'Hypervel\Coroutine\Coroutine' => ['join', 'joinuninterruptibly'], 'Hypervel\Engine\Coroutine' => ['join'], ]; diff --git a/src/prompts/src/Progress.php b/src/prompts/src/Progress.php index 2a2bb95412..f3d0bc3634 100644 --- a/src/prompts/src/Progress.php +++ b/src/prompts/src/Progress.php @@ -98,13 +98,11 @@ public function map(Closure $callback): array try { $this->renderTerminalFrame(); - } catch (Throwable) { - // The callback failure remains primary while settlement continues. + } catch (Throwable $renderFailure) { + $e = Coroutine::preferCancellation($e, $renderFailure); } - $this->settleOperation($e); - - throw $e; + throw $this->settleOperation($e); } $this->finish(); @@ -159,9 +157,7 @@ public function start(): void $this->state = 'active'; } catch (Throwable $exception) { - $this->settleOperation($exception); - - throw $exception; + throw $this->settleOperation($exception); } } @@ -204,6 +200,8 @@ public function finish(): void /** * Restore signal and terminal state for one progress operation. + * + * @return ($failure is Throwable ? Throwable : null|Throwable) */ private function settleOperation(?Throwable $failure = null): ?Throwable { diff --git a/src/prompts/src/Prompt.php b/src/prompts/src/Prompt.php index 0c1c0387c5..0d2467762c 100644 --- a/src/prompts/src/Prompt.php +++ b/src/prompts/src/Prompt.php @@ -226,9 +226,7 @@ public function prompt(): mixed try { $this->restoreTerminalState(); } catch (Throwable $exception) { - if ($operationFailure === null) { - throw $exception; - } + throw Coroutine::preferCancellation($operationFailure, $exception); } } } diff --git a/src/prompts/src/Spinner.php b/src/prompts/src/Spinner.php index d5505f2422..a19413aed0 100644 --- a/src/prompts/src/Spinner.php +++ b/src/prompts/src/Spinner.php @@ -77,24 +77,24 @@ public function spin(Closure $callback): mixed throw $exception; } finally { + $failure = $operationFailure; $animationFailure = null; try { $animationFailure = $animation?->stop(); } catch (Throwable $exception) { - $animationFailure = $exception; + $failure = Coroutine::preferCancellation($failure, $exception); } $cleanupFailure = $this->settleOperation(); - if ($operationFailure === null) { - if ($animationFailure !== null) { - throw $animationFailure; - } + if ($cleanupFailure !== null && Coroutine::causedByCancellation($cleanupFailure)) { + $failure = Coroutine::preferCancellation($failure, $cleanupFailure); + } - if ($cleanupFailure !== null) { - throw $cleanupFailure; - } + $failure ??= $animationFailure ?? $cleanupFailure; + if ($failure !== null && $failure !== $operationFailure) { + throw $failure; } } } @@ -124,8 +124,8 @@ protected function renderStatically(Closure $callback): mixed } finally { $cleanupFailure = $this->settleOperation(); - if ($operationFailure === null && $cleanupFailure !== null) { - throw $cleanupFailure; + if ($cleanupFailure !== null) { + throw Coroutine::preferCancellation($operationFailure, $cleanupFailure); } } } diff --git a/src/prompts/src/Support/PromptAnimation.php b/src/prompts/src/Support/PromptAnimation.php index b441bb90eb..6424ad1122 100644 --- a/src/prompts/src/Support/PromptAnimation.php +++ b/src/prompts/src/Support/PromptAnimation.php @@ -69,7 +69,7 @@ public function stop(): ?Throwable $this->coroutineId = null; $this->stop->push(true); - Coroutine::join([$coroutineId]); + Coroutine::joinUninterruptibly([$coroutineId]); return $this->renderFailure; } diff --git a/src/prompts/src/Task.php b/src/prompts/src/Task.php index e11e915f8e..bd713cf868 100644 --- a/src/prompts/src/Task.php +++ b/src/prompts/src/Task.php @@ -725,12 +725,12 @@ protected function renderStatically(Closure $callback): mixed $cleanupFailure = $this->settleOperation(success: $success); - if ($operationFailure !== null) { - throw $operationFailure; + if ($cleanupFailure !== null) { + throw Coroutine::preferCancellation($operationFailure, $cleanupFailure); } - if ($cleanupFailure !== null) { - throw $cleanupFailure; + if ($operationFailure !== null) { + throw $operationFailure; } return $result; @@ -750,7 +750,7 @@ protected function renderInCoroutine(Closure $callback): mixed { $animation = null; $result = null; - $operationFailure = null; + $failure = null; $success = false; try { @@ -771,7 +771,7 @@ protected function renderInCoroutine(Closure $callback): mixed $result = $callback($logger); $success = true; } catch (Throwable $exception) { - $operationFailure = $exception; + $failure = $exception; } $animationFailure = null; @@ -779,21 +779,18 @@ protected function renderInCoroutine(Closure $callback): mixed try { $animationFailure = $animation?->stop(); } catch (Throwable $exception) { - $animationFailure = $exception; + $failure = Coroutine::preferCancellation($failure, $exception); } $cleanupFailure = $this->settleOperation(renderFinalFrame: true, success: $success); - if ($operationFailure !== null) { - throw $operationFailure; - } - - if ($animationFailure !== null) { - throw $animationFailure; + if ($cleanupFailure !== null && Coroutine::causedByCancellation($cleanupFailure)) { + $failure = Coroutine::preferCancellation($failure, $cleanupFailure); } - if ($cleanupFailure !== null) { - throw $cleanupFailure; + $failure ??= $animationFailure ?? $cleanupFailure; + if ($failure !== null) { + throw $failure; } return $result; diff --git a/tests/Coroutine/CoroutineTest.php b/tests/Coroutine/CoroutineTest.php index d9768c7a95..4e38f27629 100644 --- a/tests/Coroutine/CoroutineTest.php +++ b/tests/Coroutine/CoroutineTest.php @@ -27,9 +27,12 @@ use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; +use Swoole\Event; use Throwable; use function Hypervel\Coroutine\go; +use function Hypervel\Coroutine\parallel; +use function Hypervel\Coroutine\wait; class CoroutineTest extends TestCase { @@ -124,11 +127,111 @@ public function testJoinWaitsForCreatedCoroutines(): void $completed = true; }); - $this->assertTrue(Coroutine::join([$coroutineId], 1)); + $this->assertTrue(Coroutine::join([$coroutineId, $coroutineId], 1)); $this->assertTrue($completed); $this->assertFalse(Coroutine::exists($coroutineId)); } + #[TestWith([false])] + #[TestWith([true])] + public function testJoinThrowsWhenTheWaitIsCanceled(bool $throw): void + { + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + $parent = Coroutine::id(); + Event::defer(static fn () => EngineCoroutine::cancelById($parent, $throw)); + + $this->expectException(CanceledException::class); + try { + Coroutine::join([$child], 1); + } finally { + $release->close(); + } + } + + public function testUninterruptibleJoinReportsWhetherAnyChildRemainsActive(): void + { + $finished = Coroutine::create(static fn () => null); + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + + try { + $this->assertFalse(Coroutine::joinUninterruptibly([$finished, $child], 0.001)); + } finally { + $release->close(); + } + + $this->assertTrue(Coroutine::joinUninterruptibly([$finished, $child])); + } + + #[TestWith([false])] + #[TestWith([true])] + public function testUninterruptibleJoinPropagatesCancellationAfterChildExit(bool $throw): void + { + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + $failure = null; + $waiter = Coroutine::create(static function () use ($child, &$failure): void { + try { + Coroutine::joinUninterruptibly([$child, $child], 0); + } catch (CanceledException $exception) { + $failure = $exception; + } + }); + + try { + EngineCoroutine::cancelById($waiter, $throw); + $this->assertTrue(Coroutine::exists($waiter)); + } finally { + $release->close(); + Coroutine::join([$waiter]); + } + + $this->assertInstanceOf(CanceledException::class, $failure); + } + + public function testRepeatedInterruptionsDoNotRestartTheJoinTimeout(): void + { + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + $failure = null; + $waiter = Coroutine::create(static function () use ($child, &$failure): void { + try { + Coroutine::joinUninterruptibly([$child], 0.03); + } catch (CanceledException $exception) { + $failure = $exception; + } + }); + + try { + $limit = hrtime(true) + 500_000_000; + while (Coroutine::exists($waiter) && hrtime(true) < $limit) { + EngineCoroutine::cancelById($waiter); + Coroutine::sleep(0.002); + } + + $this->assertInstanceOf(CanceledException::class, $failure); + $this->assertTrue(Coroutine::exists($child)); + } finally { + $release->close(); + Coroutine::join([$waiter]); + } + } + + public function testJoiningFinishedChildrenAfterAnEarlierWaitWasCanceled(): void + { + $parent = Coroutine::id(); + Event::defer(static fn () => EngineCoroutine::cancelById($parent)); + $channel = new Channel(1); + $channel->pop(1); + $this->assertTrue($channel->isCanceled()); + + $finished = Coroutine::create(static fn () => null); + $this->assertTrue(Coroutine::joinUninterruptibly([$finished])); + $this->assertSame('done', wait(static fn () => 'done')); + $this->assertSame(['done'], parallel([static fn () => 'done'])); + } + public function testCoroutineParentId(): void { $pid = Coroutine::id(); diff --git a/tests/Grpc/ConnectionTest.php b/tests/Grpc/ConnectionTest.php index 4261a25bcf..9653ad8d94 100644 --- a/tests/Grpc/ConnectionTest.php +++ b/tests/Grpc/ConnectionTest.php @@ -877,7 +877,9 @@ static function () use (&$now): int { $this->assertSame(1, $retired); } - public function testCloseJoinsTheReceiverBeforeClosingItsNativeClient(): void + #[TestWith([false])] + #[TestWith([true])] + public function testCloseJoinsTheReceiverBeforeClosingItsNativeClient(bool $interrupt): void { $client = new ConnectionCloseWaitTestClient; $connection = $this->connection(new ConnectionTestClientFactory($client)); @@ -889,7 +891,21 @@ public function testCloseJoinsTheReceiverBeforeClosingItsNativeClient(): void $this->assertIsInt($receiverCoroutineId); $this->assertTrue($client->waiting); - $connection->close(); + if ($interrupt) { + $cancellation = null; + $closer = Coroutine::create(static function () use ($connection, &$cancellation): void { + try { + $connection->close(); + } catch (CanceledException $exception) { + $cancellation = $exception; + } + })->getId(); + Coroutine::cancelById($closer, throwException: true); + Coroutine::join([$closer]); + $this->assertInstanceOf(CanceledException::class, $cancellation); + } else { + $connection->close(); + } $this->assertFalse($client->waiting); $this->assertTrue($client->receiverCleanupCompleted); diff --git a/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php b/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php index 3b1ed1cbf2..c95982b6c2 100644 --- a/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php +++ b/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php @@ -29,12 +29,12 @@ public function testRule(): void [sprintf(self::MESSAGE, 74), 72], [sprintf(self::MESSAGE, 85), 83], [sprintf(self::MESSAGE, 169), 167], - [sprintf(self::MESSAGE, 220), 218], - [sprintf(self::MESSAGE, 235), 233], - [sprintf(self::MESSAGE, 248), 246], - [sprintf(self::MESSAGE, 339), 337], - [sprintf(self::MESSAGE, 352), 350], - [sprintf(self::MESSAGE, 377), 375], + [sprintf(self::MESSAGE, 221), 219], + [sprintf(self::MESSAGE, 236), 234], + [sprintf(self::MESSAGE, 249), 247], + [sprintf(self::MESSAGE, 340), 338], + [sprintf(self::MESSAGE, 353), 351], + [sprintf(self::MESSAGE, 378), 376], ]); } diff --git a/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php b/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php index a083088bd6..2f83b36bf4 100644 --- a/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php +++ b/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php @@ -104,11 +104,12 @@ public function testRule(): void public function testConcurrencyWaitsAndPropertyReceivers(): void { $this->analyse([__DIR__ . '/data/swallowed-cancellation-waits.php'], [ - self::swallowed('a wait', 23), - self::swallowed('a wait', 30), - self::swallowed('a wait', 36), - self::swallowed('a database query', 44), - self::swallowed('a database query', 51), + self::swallowed('a wait', 24), + self::swallowed('a wait', 31), + self::swallowed('a wait', 37), + self::swallowed('a database query', 45), + self::swallowed('a database query', 52), + self::swallowed('a wait', 58), ]); } diff --git a/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php b/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php index 60995b7bf8..aec7a85976 100644 --- a/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php +++ b/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php @@ -185,6 +185,7 @@ public function waitsNatively(Channel $channel, WaitGroup $waitGroup, array $cor try { $waitGroup->wait(1.0); Coroutine::join($coroutineIds, 1.0); + Coroutine::joinUninterruptibly($coroutineIds); $results = new Channel(1); $later = $this->work(...); diff --git a/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php b/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php index 5e8dedcdd0..0490cbc207 100644 --- a/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php +++ b/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php @@ -7,6 +7,7 @@ use Hypervel\Contracts\Engine\ChannelInterface; use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Coroutine\Concurrent; +use Hypervel\Coroutine\Coroutine; use Hypervel\Coroutine\WaitConcurrent; use Hypervel\Database\Connection; use Hypervel\Support\Facades\DB; @@ -16,7 +17,7 @@ class WaitingImportJob implements ShouldQueue { private ?Connection $connection = null; - public function handle(WaitConcurrent $imports, Concurrent $limiter, ChannelInterface $results, ?Connection $connection): void + public function handle(WaitConcurrent $imports, Concurrent $limiter, ChannelInterface $results, ?Connection $connection, int $childId): void { try { $imports->wait(1.0); @@ -51,5 +52,11 @@ public function handle(WaitConcurrent $imports, Concurrent $limiter, ChannelInte } catch (Throwable) { return; } + + try { + Coroutine::joinUninterruptibly([$childId]); + } catch (Throwable) { + return; + } } } diff --git a/tests/Passport/Feature/DeviceAuthorizationGrantTest.php b/tests/Passport/Feature/DeviceAuthorizationGrantTest.php index 9dc1be9d64..3f40e8dc83 100644 --- a/tests/Passport/Feature/DeviceAuthorizationGrantTest.php +++ b/tests/Passport/Feature/DeviceAuthorizationGrantTest.php @@ -54,7 +54,7 @@ public function testIssueDeviceCode(): void $this->assertArrayHasKey('device_code', $json); $this->assertArrayHasKey('user_code', $json); $this->assertSame(5, $json['interval']); - $this->assertSame(600, $json['expires_in']); + $this->assertEqualsWithDelta(600, $json['expires_in'], 2); $this->assertSame('http://localhost/oauth/device', $json['verification_uri']); $this->assertSame('http://localhost/oauth/device?user_code=' . $json['user_code'], $json['verification_uri_complete']); } diff --git a/tests/Prompts/ProgressTest.php b/tests/Prompts/ProgressTest.php index e98fc4f2cc..50a8c93c7e 100644 --- a/tests/Prompts/ProgressTest.php +++ b/tests/Prompts/ProgressTest.php @@ -12,8 +12,10 @@ use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; use RuntimeException; +use Swoole\Coroutine\CanceledException; use WeakReference; use function Hypervel\Prompts\progress; @@ -158,7 +160,9 @@ public function testRepeatedStartRestoresTheApplicationSignalState(): void } #[RunInSeparateProcess] - public function testStartFailureRestoresExactSignalAndTerminalState(): void + #[TestWith([false])] + #[TestWith([true])] + public function testStartFailureRestoresExactSignalAndTerminalState(bool $canceled): void { Prompt::fake(); $originalHandler = pcntl_signal_get_handler(SIGINT); @@ -166,6 +170,11 @@ public function testStartFailureRestoresExactSignalAndTerminalState(): void $previousHandler = static function (): void { }; $failure = new RuntimeException('unable to render progress'); + $expected = $failure; + if ($canceled) { + $expected = new CanceledException; + Prompt::terminal()->shouldReceive('restoreTty')->once()->andThrow($expected); + } $output = new class($failure) extends BufferedConsoleOutput { /** @var list */ public array $directWrites = []; @@ -197,8 +206,8 @@ protected function doWrite(string $message, bool $newline): void $progress->start(); $this->fail('Expected the initial progress render to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($failure, $exception); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($expected, $exception); } $this->assertSame(["\e[?25l", "\e[?25h"], $output->directWrites); @@ -260,12 +269,14 @@ public function testCallbackFailureRendersOneUndecoratedErrorFrameAndSettles(): ); } - public function testCallbackFailureRemainsPrimaryWhenRenderingAndTerminalCleanupFail(): void + #[TestWith([false])] + #[TestWith([true])] + public function testCallbackFailureRemainsPrimaryUnlessCleanupIsCanceled(bool $canceled): void { Prompt::fake(); $callbackFailure = new RuntimeException('progress callback failed'); $renderFailure = new RuntimeException('unable to render progress error'); - $cleanupFailure = new RuntimeException('unable to restore terminal'); + $cleanupFailure = $canceled ? new CanceledException : new RuntimeException('unable to restore terminal'); $output = new class($renderFailure) extends BufferedConsoleOutput { public bool $failFrames = false; @@ -306,8 +317,8 @@ protected function doWrite(string $message, bool $newline): void }); $this->fail('Expected the progress callback to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($callbackFailure, $exception); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($canceled ? $cleanupFailure : $callbackFailure, $exception); } $this->assertSame("\e[?25l", $output->directWrites[0]); diff --git a/tests/Prompts/PromptLifecycleTest.php b/tests/Prompts/PromptLifecycleTest.php index c09dbc42fa..166df74c51 100644 --- a/tests/Prompts/PromptLifecycleTest.php +++ b/tests/Prompts/PromptLifecycleTest.php @@ -16,6 +16,7 @@ use ReflectionMethod; use ReflectionProperty; use RuntimeException; +use Swoole\Coroutine\CanceledException; use function Hypervel\Prompts\text; @@ -203,6 +204,15 @@ protected function doWrite(string $message, bool $newline): void $this->assertFalse(TextPrompt::shouldFallback()); } + public function testTerminalCleanupCancellationPropagatesAfterSubmissionFails(): void + { + Prompt::fake([Key::ENTER]); + Prompt::terminal()->shouldReceive('restoreTty')->once()->andThrow(new CanceledException); + $this->expectException(CanceledException::class); + + (new TextPrompt('Name', transform: static fn () => throw new RuntimeException('Submission failed.')))->prompt(); + } + public function testCursorOwnershipIsReleasedWhenOperationCleanupCannotRestoreIt(): void { Prompt::fake(); diff --git a/tests/Prompts/SpinnerTest.php b/tests/Prompts/SpinnerTest.php index 5e1e79f0c0..6e3548f090 100644 --- a/tests/Prompts/SpinnerTest.php +++ b/tests/Prompts/SpinnerTest.php @@ -6,11 +6,16 @@ use Hypervel\Coroutine\Coroutine; use Hypervel\Engine\Channel; +use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Prompts\Output\BufferedConsoleOutput; use Hypervel\Prompts\Prompt; use Hypervel\Prompts\Spinner; use Hypervel\Tests\TestCase; +use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; +use Swoole\Coroutine\CanceledException; +use Swoole\Event; +use Throwable; use function Hypervel\Prompts\spin; @@ -61,15 +66,18 @@ public function testRestoresThePreviousSignalHandler(): void } } - public function testCallbackFailureRemainsPrimaryWhenTerminalRestorationFails(): void + #[TestWith([false])] + #[TestWith([true])] + public function testCallbackFailureRemainsPrimaryUnlessTerminalRestorationIsCanceled(bool $canceled): void { Prompt::fake(); $callbackFailure = new RuntimeException('callback failed'); + $cleanupFailure = $canceled ? new CanceledException : new RuntimeException('terminal restoration failed'); Prompt::terminal() ->shouldReceive('restoreTty') // @phpstan-ignore-line ->once() - ->andThrow(new RuntimeException('terminal restoration failed')); + ->andThrow($cleanupFailure); try { (new Spinner('Running...'))->spin(function () use ($callbackFailure): never { @@ -77,8 +85,8 @@ public function testCallbackFailureRemainsPrimaryWhenTerminalRestorationFails(): }); $this->fail('Expected the spinner callback to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($callbackFailure, $exception); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($canceled ? $cleanupFailure : $callbackFailure, $exception); } } @@ -146,6 +154,38 @@ public function testWaitsForAnInFlightAnimationBeforeSettling(): void $this->assertSame($renderCalls, $spinner->renderCalls); } + public function testCancellationDuringStopWaitsForTheLastFrame(): void + { + Prompt::fake(); + $spinner = new SpinnerAnimationFixture('Running'); + $spinner->interval = 1; + $cancellation = null; + $callbackFinished = new Channel(1); + $owner = Coroutine::fork(static function () use ($spinner, $callbackFinished, &$cancellation): void { + try { + $spinner->spin(static function () use ($spinner, $callbackFinished): void { + $spinner->renderStarted->pop(1); + Event::defer(static fn () => $callbackFinished->push(true)); + throw new RuntimeException('Callback failed before the spinner stopped.'); + }); + } catch (Throwable $exception) { + $cancellation = $exception; + } + }); + + try { + $this->assertTrue($callbackFinished->pop(1)); + EngineCoroutine::cancelById($owner); + $this->assertTrue(Coroutine::exists($owner)); + } finally { + $spinner->renderRelease->push(true); + Coroutine::join([$owner]); + } + + $this->assertInstanceOf(CanceledException::class, $cancellation); + $this->assertFalse($spinner->rendering); + } + public function testSurfacesAnimationRenderFailureAfterSuccessfulCallback(): void { Prompt::fake(); diff --git a/tests/Prompts/TaskTest.php b/tests/Prompts/TaskTest.php index 79bdb5993c..49e3f294f5 100644 --- a/tests/Prompts/TaskTest.php +++ b/tests/Prompts/TaskTest.php @@ -16,9 +16,11 @@ use Hypervel\Prompts\Themes\Default\TaskRenderer; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use PHPUnit\Framework\Attributes\TestWith; use ReflectionMethod; use ReflectionProperty; use RuntimeException; +use Swoole\Coroutine\CanceledException; use function Hypervel\Prompts\task; @@ -91,6 +93,22 @@ public function testDoesNotPrintStaticCompletionLineAfterFailure(): void Prompt::assertStrippedOutputDoesntContain('✔ My Task'); } + #[TestWith([false])] + #[TestWith([true])] + public function testCancellationWhileRenderingTheFinalSummaryPropagatesAfterCallbackFailure(bool $decorated): void + { + Prompt::fake(); + Prompt::setOutput(new BufferedConsoleOutput(decorated: $decorated)); + $this->expectException(CanceledException::class); + + (new Task('Deploy', keepSummary: true))->run(static function (Logger $logger): never { + $logger->success('Uploaded'); + Prompt::terminal()->shouldReceive('cols')->once()->andThrow(new CanceledException); + + throw new RuntimeException('Deploy failed.'); + }); + } + public function testPrintsCompletionLineAfterSuccessfulCoroutineTaskWithSummary(): void { Prompt::fake();