Waiter.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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\Utils;
  12. use Closure;
  13. use Hyperf\Engine\Channel;
  14. use Hyperf\Utils\Exception\ExceptionThrower;
  15. use Hyperf\Utils\Exception\WaitTimeoutException;
  16. use Throwable;
  17. class Waiter
  18. {
  19. /**
  20. * @var float
  21. */
  22. protected $pushTimeout = 10.0;
  23. /**
  24. * @var float
  25. */
  26. protected $popTimeout = 10.0;
  27. public function __construct(float $timeout = 10.0)
  28. {
  29. $this->popTimeout = $timeout;
  30. }
  31. /**
  32. * @param null|float $timeout seconds
  33. */
  34. public function wait(Closure $closure, ?float $timeout = null)
  35. {
  36. if ($timeout === null) {
  37. $timeout = $this->popTimeout;
  38. }
  39. $channel = new Channel(1);
  40. Coroutine::create(function () use ($channel, $closure) {
  41. try {
  42. $result = $closure();
  43. } catch (Throwable $exception) {
  44. $result = new ExceptionThrower($exception);
  45. } finally {
  46. $channel->push($result ?? null, $this->pushTimeout);
  47. }
  48. });
  49. $result = $channel->pop($timeout);
  50. if ($result === false && $channel->isTimeout()) {
  51. throw new WaitTimeoutException(sprintf('Channel wait failed, reason: Timed out for %s s', $timeout));
  52. }
  53. if ($result instanceof ExceptionThrower) {
  54. throw $result->getThrowable();
  55. }
  56. return $result;
  57. }
  58. }