Waiter.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Coroutine;
  12. use Closure;
  13. use Hyperf\Coroutine\Exception\ExceptionThrower;
  14. use Hyperf\Coroutine\Exception\WaitTimeoutException;
  15. use Hyperf\Engine\Channel;
  16. use Throwable;
  17. class Waiter
  18. {
  19. protected float $pushTimeout = 10.0;
  20. protected float $popTimeout = 10.0;
  21. public function __construct(float $timeout = 10.0)
  22. {
  23. $this->popTimeout = $timeout;
  24. }
  25. /**
  26. * @param null|float $timeout seconds
  27. */
  28. public function wait(Closure $closure, ?float $timeout = null)
  29. {
  30. if ($timeout === null) {
  31. $timeout = $this->popTimeout;
  32. }
  33. $channel = new Channel(1);
  34. Coroutine::create(function () use ($channel, $closure) {
  35. try {
  36. $result = $closure();
  37. } catch (Throwable $exception) {
  38. $result = new ExceptionThrower($exception);
  39. } finally {
  40. $channel->push($result ?? null, $this->pushTimeout);
  41. }
  42. });
  43. $result = $channel->pop($timeout);
  44. if ($result === false && $channel->isTimeout()) {
  45. throw new WaitTimeoutException(sprintf('Channel wait failed, reason: Timed out for %s s', $timeout));
  46. }
  47. if ($result instanceof ExceptionThrower) {
  48. throw $result->getThrowable();
  49. }
  50. return $result;
  51. }
  52. }