From 89bb51ebf8c6cbb012766e05944cefe618722671 Mon Sep 17 00:00:00 2001 From: Cees-Jan Kiewiet Date: Fri, 25 Sep 2026 14:22:58 +0200 Subject: [PATCH] [3.x] Add Io\Poll Event Loop --- .github/workflows/ci.yml | 2 + README.md | 20 ++- src/IoPollLoop.php | 258 ++++++++++++++++++++++++++++++++++ src/Loop.php | 4 + src/Watcher/StreamWatcher.php | 15 ++ tests/IoPollLoopTest.php | 17 +++ 6 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 src/IoPollLoop.php create mode 100644 src/Watcher/StreamWatcher.php create mode 100644 tests/IoPollLoopTest.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b909775c..bc9a59be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,7 @@ jobs: name: PHPUnit (PHP ${{ matrix.php }}) runs-on: ubuntu-26.04 strategy: + fail-fast: false matrix: php: - 8.6 @@ -82,6 +83,7 @@ jobs: runs-on: windows-2022 continue-on-error: true strategy: + fail-fast: false matrix: php: - 8.6 diff --git a/README.md b/README.md index 8394784f..112d8e2e 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ single [`run()`](#run) call that is controlled by the user. * [get()](#get) * [Loop implementations](#loop-implementations) * [StreamSelectLoop](#streamselectloop) + * [IoPollLoop](#iopollloop) * [ExtEventLoop](#exteventloop) * [ExtEvLoop](#extevloop) * [ExtUvLoop](#extuvloop) @@ -328,7 +329,8 @@ event loop implementation first or they will throw a `BadMethodCallException` on A `stream_select()` based event loop. This uses the [`stream_select()`](https://www.php.net/manual/en/function.stream-select.php) -function and is the only implementation that works out of the box with PHP. +function and is the only implementation that works out of the box on PHP +versions before 8.6. This event loop works out of the box on any PHP version. This means that no installation is required and this library works on all @@ -365,6 +367,22 @@ This means that if you schedule a timer to trigger in 30s on PHP < 7.3 and then adjust your system time forward by 20s, the timer may trigger in 10s. See also [`addTimer()`](#addtimer) for more details. +#### IoPollLoop + +A `Io\Poll\Context` based event loop. + +This uses PHP's built-in [polling API](https://www.php.net/manual/en/book.io.php), +introduced in PHP 8.6. The [`Io\Poll\Context`](https://www.php.net/manual/en/class.io-poll-context.php) +automatically selects an available platform-specific polling backend. + +This event loop works out of the box on PHP 8.6 and higher and does not require +an additional event loop extension. Unlike the [`StreamSelectLoop`](#streamselectloop), +it does not use `stream_select()` and is not subject to its file descriptor limit. + +Like the [`StreamSelectLoop`](#streamselectloop), this event loop supports timers +and signal handling. Both loops use the same classes for these features under the +hood, see [`StreamSelectLoop`](#streamselectloop) for the details. + #### ExtEventLoop An `ext-event` based event loop. diff --git a/src/IoPollLoop.php b/src/IoPollLoop.php new file mode 100644 index 00000000..992ed5c6 --- /dev/null +++ b/src/IoPollLoop.php @@ -0,0 +1,258 @@ + */ + private array $watchers = []; + + public function __construct() + { + $this->context = new Context(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new Timers(); + $this->pcntl = \function_exists('pcntl_signal') && \function_exists('pcntl_signal_dispatch') && \function_exists('pcntl_async_signals'); + $this->signals = new SignalsHandler(); + + if ($this->pcntl) { + \pcntl_async_signals(true); + } + } + + public function addReadStream($stream, $listener) + { + $this->manageStream($stream, Event::Read, $listener); + } + + public function addWriteStream($stream, $listener) + { + $this->manageStream($stream, Event::Write, $listener); + } + + public function removeReadStream($stream) + { + $this->manageStream($stream, Event::Read); + } + + public function removeWriteStream($stream) + { + $this->manageStream($stream, Event::Write); + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->timers->add($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->timers->add($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + $this->timers->cancel($timer); + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + if ($this->pcntl === false) { + throw new \BadMethodCallException('Event loop feature "signals" isn\'t supported by the "IoPollLoop"'); + } + + $first = $this->signals->count($signal) === 0; + $this->signals->add($signal, $listener); + + if ($first) { + \pcntl_signal($signal, [$this->signals, 'call']); + } + } + + public function removeSignal($signal, $listener) + { + if (!$this->signals->count($signal)) { + return; + } + + $this->signals->remove($signal, $listener); + + if ($this->signals->count($signal) === 0) { + \pcntl_signal($signal, \SIG_DFL); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $this->timers->tick(); + + // Future-tick queue has pending callbacks ... + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $duration = Duration::fromSeconds(0); + + // There is a pending timer, only block until it is due ... + } elseif ($scheduledAt = $this->timers->getFirst()) { + $timeout = $scheduledAt - $this->timers->getTime(); + if ($timeout < 0) { + $timeout = 0; + } + + $seconds = (int)$timeout; + $nanoseconds = (int)(($timeout - $seconds) * 1000000000); + + $duration = Duration::fromSeconds($seconds, $nanoseconds); + + // The only possible event is stream or signal activity, so wait forever ... + } elseif ($this->watchers !== [] || !$this->signals->isEmpty()) { + $duration = null; + + // There's nothing left to do ... + } else { + break; + } + + try { + foreach ($this->context->wait($duration) as $watcher) { + $stream = $watcher->getHandle()->getStream(); + $streamWatcher = $watcher->getData(); + + // Both of these are automatically monitored + $errorOrHangUp = $watcher->hasTriggered(Event::Error) || $watcher->hasTriggered(Event::HangUp); + $readReady = $watcher->hasTriggered(Event::Read) || $errorOrHangUp; + $writeReady = $watcher->hasTriggered(Event::Write) || $errorOrHangUp; + + if ($streamWatcher->readListener !== null && $readReady) { + \call_user_func($streamWatcher->readListener, $stream); + } + + if ($streamWatcher->writeListener !== null && $writeReady) { + \call_user_func($streamWatcher->writeListener, $stream); + } + } + } catch (FailedPollWaitException $failedPollWaitException) { + if ($failedPollWaitException->getCode() === FailedPollWaitException::ERROR_INTERRUPTED) { + if ($this->pcntl) { + \pcntl_signal_dispatch(); + } + } else { + throw $failedPollWaitException; + } + } + } + } + + public function stop() + { + $this->running = false; + } + + private function manageStream($stream, Event $event, ?callable $listener = null) + { + $key = (int) $stream; + $watcher = $this->watchers[$key] ?? null; + if ($watcher !== null && !$watcher->isActive()) { + unset($this->watchers[$key]); + $watcher = null; + } + + /** @var StreamWatcher|null $streamWatcher */ + $streamWatcher = $watcher !== null ? $watcher->getData() : null; + + if ($streamWatcher === null) { + if ($listener === null) { + return; + } + + $streamWatcher = new StreamWatcher($key); + } + + $this->updateStreamWatcherListener($streamWatcher, $event, $listener); + $events = []; + if ($streamWatcher->readListener !== null) { + $events[] = Event::Read; + $events[] = Event::ReadHangUp; + } + if ($streamWatcher->writeListener !== null) { + $events[] = Event::Write; + } + + if ($events === []) { + if ($watcher !== null) { + $watcher->remove(); + } + + unset($this->watchers[$key]); + + return; + } + + if ($watcher !== null) { + $watcher->modifyEvents($events); + + return; + } + + $this->watchers[$key] = $this->context->add(new \StreamPollHandle($stream), $events, $streamWatcher); + } + + private function updateStreamWatcherListener(StreamWatcher $streamWatcher, Event $event, ?callable $listener = null): void + { + if ($event === Event::Read && ($listener === null || $streamWatcher->readListener === null)) { + $streamWatcher->readListener = $listener; + } elseif ($event === Event::Write && ($listener === null || $streamWatcher->writeListener === null)) { + $streamWatcher->writeListener = $listener; + } + } +} diff --git a/src/Loop.php b/src/Loop.php index 732c5d5e..97aa6ccc 100644 --- a/src/Loop.php +++ b/src/Loop.php @@ -250,6 +250,10 @@ private static function create() return new ExtEventLoop(); } + if (\PHP_VERSION_ID >= 80600 && \class_exists('Io\Poll\Context', false)) { + return new IoPollLoop(); + } + return new StreamSelectLoop(); // @codeCoverageIgnoreEnd } diff --git a/src/Watcher/StreamWatcher.php b/src/Watcher/StreamWatcher.php new file mode 100644 index 00000000..3e5cbcf8 --- /dev/null +++ b/src/Watcher/StreamWatcher.php @@ -0,0 +1,15 @@ +markTestSkipped('IOPollLoop tests skipped because IO Poll is not available.'); + } + + return new IoPollLoop(); + } +}