ExtUvLoop.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. namespace React\EventLoop;
  3. use React\EventLoop\Tick\FutureTickQueue;
  4. use React\EventLoop\Timer\Timer;
  5. use SplObjectStorage;
  6. /**
  7. * An `ext-uv` based event loop.
  8. *
  9. * This loop uses the [`uv` PECL extension](https://pecl.php.net/package/uv),
  10. * that provides an interface to `libuv` library.
  11. * `libuv` itself supports a number of system-specific backends (epoll, kqueue).
  12. *
  13. * This loop is known to work with PHP 7+.
  14. *
  15. * @see https://github.com/bwoebi/php-uv
  16. */
  17. final class ExtUvLoop implements LoopInterface
  18. {
  19. private $uv;
  20. private $futureTickQueue;
  21. private $timers;
  22. private $streamEvents = array();
  23. private $readStreams = array();
  24. private $writeStreams = array();
  25. private $running;
  26. private $signals;
  27. private $signalEvents = array();
  28. private $streamListener;
  29. public function __construct()
  30. {
  31. if (!\function_exists('uv_loop_new')) {
  32. throw new \BadMethodCallException('Cannot create LibUvLoop, ext-uv extension missing');
  33. }
  34. $this->uv = \uv_loop_new();
  35. $this->futureTickQueue = new FutureTickQueue();
  36. $this->timers = new SplObjectStorage();
  37. $this->streamListener = $this->createStreamListener();
  38. $this->signals = new SignalsHandler();
  39. }
  40. /**
  41. * Returns the underlying ext-uv event loop. (Internal ReactPHP use only.)
  42. *
  43. * @internal
  44. *
  45. * @return resource
  46. */
  47. public function getUvLoop()
  48. {
  49. return $this->uv;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function addReadStream($stream, $listener)
  55. {
  56. if (isset($this->readStreams[(int) $stream])) {
  57. return;
  58. }
  59. $this->readStreams[(int) $stream] = $listener;
  60. $this->addStream($stream);
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function addWriteStream($stream, $listener)
  66. {
  67. if (isset($this->writeStreams[(int) $stream])) {
  68. return;
  69. }
  70. $this->writeStreams[(int) $stream] = $listener;
  71. $this->addStream($stream);
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function removeReadStream($stream)
  77. {
  78. if (!isset($this->streamEvents[(int) $stream])) {
  79. return;
  80. }
  81. unset($this->readStreams[(int) $stream]);
  82. $this->removeStream($stream);
  83. }
  84. /**
  85. * {@inheritdoc}
  86. */
  87. public function removeWriteStream($stream)
  88. {
  89. if (!isset($this->streamEvents[(int) $stream])) {
  90. return;
  91. }
  92. unset($this->writeStreams[(int) $stream]);
  93. $this->removeStream($stream);
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function addTimer($interval, $callback)
  99. {
  100. $timer = new Timer($interval, $callback, false);
  101. $that = $this;
  102. $timers = $this->timers;
  103. $callback = function () use ($timer, $timers, $that) {
  104. \call_user_func($timer->getCallback(), $timer);
  105. if ($timers->contains($timer)) {
  106. $that->cancelTimer($timer);
  107. }
  108. };
  109. $event = \uv_timer_init($this->uv);
  110. $this->timers->attach($timer, $event);
  111. \uv_timer_start(
  112. $event,
  113. $this->convertFloatSecondsToMilliseconds($interval),
  114. 0,
  115. $callback
  116. );
  117. return $timer;
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function addPeriodicTimer($interval, $callback)
  123. {
  124. $timer = new Timer($interval, $callback, true);
  125. $callback = function () use ($timer) {
  126. \call_user_func($timer->getCallback(), $timer);
  127. };
  128. $interval = $this->convertFloatSecondsToMilliseconds($interval);
  129. $event = \uv_timer_init($this->uv);
  130. $this->timers->attach($timer, $event);
  131. \uv_timer_start(
  132. $event,
  133. $interval,
  134. (int) $interval === 0 ? 1 : $interval,
  135. $callback
  136. );
  137. return $timer;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function cancelTimer(TimerInterface $timer)
  143. {
  144. if (isset($this->timers[$timer])) {
  145. @\uv_timer_stop($this->timers[$timer]);
  146. $this->timers->detach($timer);
  147. }
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function futureTick($listener)
  153. {
  154. $this->futureTickQueue->add($listener);
  155. }
  156. public function addSignal($signal, $listener)
  157. {
  158. $this->signals->add($signal, $listener);
  159. if (!isset($this->signalEvents[$signal])) {
  160. $signals = $this->signals;
  161. $this->signalEvents[$signal] = \uv_signal_init($this->uv);
  162. \uv_signal_start($this->signalEvents[$signal], function () use ($signals, $signal) {
  163. $signals->call($signal);
  164. }, $signal);
  165. }
  166. }
  167. public function removeSignal($signal, $listener)
  168. {
  169. $this->signals->remove($signal, $listener);
  170. if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) {
  171. \uv_signal_stop($this->signalEvents[$signal]);
  172. unset($this->signalEvents[$signal]);
  173. }
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. public function run()
  179. {
  180. $this->running = true;
  181. while ($this->running) {
  182. $this->futureTickQueue->tick();
  183. $hasPendingCallbacks = !$this->futureTickQueue->isEmpty();
  184. $wasJustStopped = !$this->running;
  185. $nothingLeftToDo = !$this->readStreams
  186. && !$this->writeStreams
  187. && !$this->timers->count()
  188. && $this->signals->isEmpty();
  189. // Use UV::RUN_ONCE when there are only I/O events active in the loop and block until one of those triggers,
  190. // otherwise use UV::RUN_NOWAIT.
  191. // @link http://docs.libuv.org/en/v1.x/loop.html#c.uv_run
  192. $flags = \UV::RUN_ONCE;
  193. if ($wasJustStopped || $hasPendingCallbacks) {
  194. $flags = \UV::RUN_NOWAIT;
  195. } elseif ($nothingLeftToDo) {
  196. break;
  197. }
  198. \uv_run($this->uv, $flags);
  199. }
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function stop()
  205. {
  206. $this->running = false;
  207. }
  208. private function addStream($stream)
  209. {
  210. if (!isset($this->streamEvents[(int) $stream])) {
  211. $this->streamEvents[(int)$stream] = \uv_poll_init_socket($this->uv, $stream);
  212. }
  213. if ($this->streamEvents[(int) $stream] !== false) {
  214. $this->pollStream($stream);
  215. }
  216. }
  217. private function removeStream($stream)
  218. {
  219. if (!isset($this->streamEvents[(int) $stream])) {
  220. return;
  221. }
  222. if (!isset($this->readStreams[(int) $stream])
  223. && !isset($this->writeStreams[(int) $stream])) {
  224. \uv_poll_stop($this->streamEvents[(int) $stream]);
  225. \uv_close($this->streamEvents[(int) $stream]);
  226. unset($this->streamEvents[(int) $stream]);
  227. return;
  228. }
  229. $this->pollStream($stream);
  230. }
  231. private function pollStream($stream)
  232. {
  233. if (!isset($this->streamEvents[(int) $stream])) {
  234. return;
  235. }
  236. $flags = 0;
  237. if (isset($this->readStreams[(int) $stream])) {
  238. $flags |= \UV::READABLE;
  239. }
  240. if (isset($this->writeStreams[(int) $stream])) {
  241. $flags |= \UV::WRITABLE;
  242. }
  243. \uv_poll_start($this->streamEvents[(int) $stream], $flags, $this->streamListener);
  244. }
  245. /**
  246. * Create a stream listener
  247. *
  248. * @return callable Returns a callback
  249. */
  250. private function createStreamListener()
  251. {
  252. $callback = function ($event, $status, $events, $stream) {
  253. // libuv automatically stops polling on error, re-enable polling to match other loop implementations
  254. if ($status !== 0) {
  255. $this->pollStream($stream);
  256. // libuv may report no events on error, but this should still invoke stream listeners to report closed connections
  257. // re-enable both readable and writable, correct listeners will be checked below anyway
  258. if ($events === 0) {
  259. $events = \UV::READABLE | \UV::WRITABLE;
  260. }
  261. }
  262. if (isset($this->readStreams[(int) $stream]) && ($events & \UV::READABLE)) {
  263. \call_user_func($this->readStreams[(int) $stream], $stream);
  264. }
  265. if (isset($this->writeStreams[(int) $stream]) && ($events & \UV::WRITABLE)) {
  266. \call_user_func($this->writeStreams[(int) $stream], $stream);
  267. }
  268. };
  269. return $callback;
  270. }
  271. /**
  272. * @param float $interval
  273. * @return int
  274. */
  275. private function convertFloatSecondsToMilliseconds($interval)
  276. {
  277. if ($interval < 0) {
  278. return 0;
  279. }
  280. $maxValue = (int) (\PHP_INT_MAX / 1000);
  281. $intInterval = (int) $interval;
  282. if (($intInterval <= 0 && $interval > 1) || $intInterval >= $maxValue) {
  283. throw new \InvalidArgumentException(
  284. "Interval overflow, value must be lower than '{$maxValue}', but '{$interval}' passed."
  285. );
  286. }
  287. return (int) \floor($interval * 1000);
  288. }
  289. }