Select.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. declare(strict_types=1);
  15. namespace Workerman\Events;
  16. use SplPriorityQueue;
  17. use Throwable;
  18. use function count;
  19. use function max;
  20. use function microtime;
  21. use function pcntl_signal;
  22. use function pcntl_signal_dispatch;
  23. use const DIRECTORY_SEPARATOR;
  24. /**
  25. * select eventloop
  26. */
  27. final class Select implements EventInterface
  28. {
  29. /**
  30. * Running.
  31. *
  32. * @var bool
  33. */
  34. private bool $running = true;
  35. /**
  36. * All listeners for read/write event.
  37. *
  38. * @var array<int, callable>
  39. */
  40. private array $readEvents = [];
  41. /**
  42. * All listeners for read/write event.
  43. *
  44. * @var array<int, callable>
  45. */
  46. private array $writeEvents = [];
  47. /**
  48. * @var array<int, callable>
  49. */
  50. private array $exceptEvents = [];
  51. /**
  52. * Event listeners of signal.
  53. *
  54. * @var array<int, callable>
  55. */
  56. private array $signalEvents = [];
  57. /**
  58. * Fds waiting for read event.
  59. *
  60. * @var array<int, resource>
  61. */
  62. private array $readFds = [];
  63. /**
  64. * Fds waiting for write event.
  65. *
  66. * @var array<int, resource>
  67. */
  68. private array $writeFds = [];
  69. /**
  70. * Fds waiting for except event.
  71. *
  72. * @var array<int, resource>
  73. */
  74. private array $exceptFds = [];
  75. /**
  76. * Timer scheduler.
  77. * {['data':timer_id, 'priority':run_timestamp], ..}
  78. *
  79. * @var SplPriorityQueue
  80. */
  81. private SplPriorityQueue $scheduler;
  82. /**
  83. * All timer event listeners.
  84. * [[func, args, flag, timer_interval], ..]
  85. *
  86. * @var array
  87. */
  88. private array $eventTimer = [];
  89. /**
  90. * Timer id.
  91. *
  92. * @var int
  93. */
  94. private int $timerId = 1;
  95. /**
  96. * Select timeout.
  97. *
  98. * @var int
  99. */
  100. private int $selectTimeout = 100000000;
  101. /**
  102. * @var ?callable
  103. */
  104. private $errorHandler = null;
  105. /**
  106. * Construct.
  107. */
  108. public function __construct()
  109. {
  110. $this->scheduler = new SplPriorityQueue();
  111. $this->scheduler->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function delay(float $delay, callable $func, array $args = []): int
  117. {
  118. $timerId = $this->timerId++;
  119. $runTime = microtime(true) + $delay;
  120. $this->scheduler->insert($timerId, -$runTime);
  121. $this->eventTimer[$timerId] = [$func, $args];
  122. $selectTimeout = ($runTime - microtime(true)) * 1000000;
  123. $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
  124. if ($this->selectTimeout > $selectTimeout) {
  125. $this->selectTimeout = $selectTimeout;
  126. }
  127. return $timerId;
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function repeat(float $interval, callable $func, array $args = []): int
  133. {
  134. $timerId = $this->timerId++;
  135. $runTime = microtime(true) + $interval;
  136. $this->scheduler->insert($timerId, -$runTime);
  137. $this->eventTimer[$timerId] = [$func, $args, $interval];
  138. $selectTimeout = ($runTime - microtime(true)) * 1000000;
  139. $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
  140. if ($this->selectTimeout > $selectTimeout) {
  141. $this->selectTimeout = $selectTimeout;
  142. }
  143. return $timerId;
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function offDelay(int $timerId): bool
  149. {
  150. if (isset($this->eventTimer[$timerId])) {
  151. unset($this->eventTimer[$timerId]);
  152. return true;
  153. }
  154. return false;
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function offRepeat(int $timerId): bool
  160. {
  161. return $this->offDelay($timerId);
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. public function onReadable($stream, callable $func): void
  167. {
  168. $count = count($this->readFds);
  169. if ($count >= 1024) {
  170. trigger_error("System call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.", E_USER_WARNING);
  171. } else if (DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
  172. trigger_error("System call select exceeded the maximum number of connections 256.", E_USER_WARNING);
  173. }
  174. $fdKey = (int)$stream;
  175. $this->readEvents[$fdKey] = $func;
  176. $this->readFds[$fdKey] = $stream;
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function offReadable($stream): bool
  182. {
  183. $fdKey = (int)$stream;
  184. if (isset($this->readEvents[$fdKey])) {
  185. unset($this->readEvents[$fdKey], $this->readFds[$fdKey]);
  186. return true;
  187. }
  188. return false;
  189. }
  190. /**
  191. * {@inheritdoc}
  192. */
  193. public function onWritable($stream, callable $func): void
  194. {
  195. $count = count($this->writeFds);
  196. if ($count >= 1024) {
  197. trigger_error("System call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.", E_USER_WARNING);
  198. } else if (DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
  199. trigger_error("System call select exceeded the maximum number of connections 256.", E_USER_WARNING);
  200. }
  201. $fdKey = (int)$stream;
  202. $this->writeEvents[$fdKey] = $func;
  203. $this->writeFds[$fdKey] = $stream;
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. public function offWritable($stream): bool
  209. {
  210. $fdKey = (int)$stream;
  211. if (isset($this->writeEvents[$fdKey])) {
  212. unset($this->writeEvents[$fdKey], $this->writeFds[$fdKey]);
  213. return true;
  214. }
  215. return false;
  216. }
  217. /**
  218. * On except.
  219. *
  220. * @param resource $stream
  221. * @param callable $func
  222. */
  223. public function onExcept($stream, callable $func): void
  224. {
  225. $fdKey = (int)$stream;
  226. $this->exceptEvents[$fdKey] = $func;
  227. $this->exceptFds[$fdKey] = $stream;
  228. }
  229. /**
  230. * Off except.
  231. *
  232. * @param resource $stream
  233. * @return bool
  234. */
  235. public function offExcept($stream): bool
  236. {
  237. $fdKey = (int)$stream;
  238. if (isset($this->exceptEvents[$fdKey])) {
  239. unset($this->exceptEvents[$fdKey], $this->exceptFds[$fdKey]);
  240. return true;
  241. }
  242. return false;
  243. }
  244. /**
  245. * {@inheritdoc}
  246. */
  247. public function onSignal(int $signal, callable $func): void
  248. {
  249. if (!function_exists('pcntl_signal')) {
  250. return;
  251. }
  252. $this->signalEvents[$signal] = $func;
  253. pcntl_signal($signal, fn () => $this->safeCall($this->signalEvents[$signal], [$signal]));
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function offSignal(int $signal): bool
  259. {
  260. if (!function_exists('pcntl_signal')) {
  261. return false;
  262. }
  263. pcntl_signal($signal, SIG_IGN);
  264. if (isset($this->signalEvents[$signal])) {
  265. unset($this->signalEvents[$signal]);
  266. return true;
  267. }
  268. return false;
  269. }
  270. /**
  271. * Tick for timer.
  272. *
  273. * @return void
  274. */
  275. protected function tick(): void
  276. {
  277. $tasksToInsert = [];
  278. while (!$this->scheduler->isEmpty()) {
  279. $schedulerData = $this->scheduler->top();
  280. $timerId = $schedulerData['data'];
  281. $nextRunTime = -$schedulerData['priority'];
  282. $timeNow = microtime(true);
  283. $this->selectTimeout = (int)(($nextRunTime - $timeNow) * 1000000);
  284. if ($this->selectTimeout <= 0) {
  285. $this->scheduler->extract();
  286. if (!isset($this->eventTimer[$timerId])) {
  287. continue;
  288. }
  289. // [func, args, timer_interval]
  290. $taskData = $this->eventTimer[$timerId];
  291. if (isset($taskData[2])) {
  292. $nextRunTime = $timeNow + $taskData[2];
  293. $tasksToInsert[] = [$timerId, -$nextRunTime];
  294. } else {
  295. unset($this->eventTimer[$timerId]);
  296. }
  297. $this->safeCall($taskData[0], $taskData[1]);
  298. } else {
  299. break;
  300. }
  301. }
  302. foreach ($tasksToInsert as $item) {
  303. $this->scheduler->insert($item[0], $item[1]);
  304. }
  305. if (!$this->scheduler->isEmpty()) {
  306. $schedulerData = $this->scheduler->top();
  307. $nextRunTime = -$schedulerData['priority'];
  308. $timeNow = microtime(true);
  309. $this->selectTimeout = max((int)(($nextRunTime - $timeNow) * 1000000), 0);
  310. return;
  311. }
  312. $this->selectTimeout = 100000000;
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. public function deleteAllTimer(): void
  318. {
  319. $this->scheduler = new SplPriorityQueue();
  320. $this->scheduler->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
  321. $this->eventTimer = [];
  322. }
  323. /**
  324. * {@inheritdoc}
  325. */
  326. public function run(): void
  327. {
  328. while ($this->running) {
  329. $read = $this->readFds;
  330. $write = $this->writeFds;
  331. $except = $this->exceptFds;
  332. if (!empty($read) || !empty($write) || !empty($except)) {
  333. // Waiting read/write/signal/timeout events.
  334. try {
  335. @stream_select($read, $write, $except, 0, $this->selectTimeout);
  336. } catch (Throwable) {
  337. // do nothing
  338. }
  339. } else {
  340. $this->selectTimeout >= 1 && usleep($this->selectTimeout);
  341. }
  342. if (!$this->scheduler->isEmpty()) {
  343. $this->tick();
  344. }
  345. foreach ($read as $fd) {
  346. $fdKey = (int)$fd;
  347. if (isset($this->readEvents[$fdKey])) {
  348. $this->readEvents[$fdKey]($fd);
  349. }
  350. }
  351. foreach ($write as $fd) {
  352. $fdKey = (int)$fd;
  353. if (isset($this->writeEvents[$fdKey])) {
  354. $this->writeEvents[$fdKey]($fd);
  355. }
  356. }
  357. foreach ($except as $fd) {
  358. $fdKey = (int)$fd;
  359. if (isset($this->exceptEvents[$fdKey])) {
  360. $this->exceptEvents[$fdKey]($fd);
  361. }
  362. }
  363. if (!empty($this->signalEvents)) {
  364. // Calls signal handlers for pending signals
  365. pcntl_signal_dispatch();
  366. }
  367. }
  368. }
  369. /**
  370. * {@inheritdoc}
  371. */
  372. public function stop(): void
  373. {
  374. $this->running = false;
  375. $this->deleteAllTimer();
  376. foreach ($this->signalEvents as $signal => $item) {
  377. $this->offsignal($signal);
  378. }
  379. $this->readFds = [];
  380. $this->writeFds = [];
  381. $this->exceptFds = [];
  382. $this->readEvents = [];
  383. $this->writeEvents = [];
  384. $this->exceptEvents = [];
  385. $this->signalEvents = [];
  386. }
  387. /**
  388. * {@inheritdoc}
  389. */
  390. public function getTimerCount(): int
  391. {
  392. return count($this->eventTimer);
  393. }
  394. /**
  395. * {@inheritdoc}
  396. */
  397. public function setErrorHandler(callable $errorHandler): void
  398. {
  399. $this->errorHandler = $errorHandler;
  400. }
  401. /**
  402. * @param callable $func
  403. * @param array $args
  404. * @return void
  405. */
  406. private function safeCall(callable $func, array $args = []): void
  407. {
  408. try {
  409. $func(...$args);
  410. } catch (Throwable $e) {
  411. if ($this->errorHandler === null) {
  412. echo $e;
  413. } else {
  414. ($this->errorHandler)($e);
  415. }
  416. }
  417. }
  418. }