Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ jobs:
name: PHPUnit (PHP ${{ matrix.php }})
runs-on: ubuntu-26.04
strategy:
fail-fast: false
matrix:
php:
- 8.6
Expand Down Expand Up @@ -50,6 +51,7 @@ jobs:
runs-on: ${{ matrix.php >= 8.0 && 'ubuntu-26.04' || 'ubuntu-24.04' }} # legacy extensions do not build on 26.04
continue-on-error: true
strategy:
fail-fast: false
matrix:
php:
- 8.6
Expand Down
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ single [`run()`](#run) call that is controlled by the user.
* [~~create()~~](#create)
* [Loop implementations](#loop-implementations)
* [StreamSelectLoop](#streamselectloop)
* [IoPollLoop](#iopollloop)
* [ExtEventLoop](#exteventloop)
* [ExtEvLoop](#extevloop)
* [ExtUvLoop](#extuvloop)
Expand Down Expand Up @@ -352,7 +353,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 PHP 5.3 through PHP 8+ and HHVM.
This means that no installation is required and this library works on all
Expand Down Expand Up @@ -390,6 +392,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.
Expand Down
4 changes: 4 additions & 0 deletions src/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ private static function construct()
return new ExtLibeventLoop();
}

if (\PHP_VERSION_ID >= 80600 && \class_exists('Io\Poll\Context', false)) {
return new IoPollLoop();
}

return new StreamSelectLoop();
// @codeCoverageIgnoreEnd
}
Expand Down
258 changes: 258 additions & 0 deletions src/IoPollLoop.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
<?php

namespace React\EventLoop;

use Io\Poll\Context;
use Io\Poll\Event;
use Io\Poll\FailedPollWaitException;
use Io\Poll\Watcher;
use React\EventLoop\Tick\FutureTickQueue;
use React\EventLoop\Timer\Timer;
use React\EventLoop\Timer\Timers;
use React\EventLoop\Watcher\StreamWatcher;
use Time\Duration;

/**
* 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.
*
* @link https://www.php.net/manual/en/book.io.php
* @link https://www.php.net/manual/en/class.io-poll-context.php
*/
final class IoPollLoop implements LoopInterface
{
private bool $running = false;
private Context $context;
private FutureTickQueue $futureTickQueue;
private Timers $timers;
private bool $pcntl;
private SignalsHandler $signals;
/** @var array<Watcher> */
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;
}
}
}
15 changes: 15 additions & 0 deletions src/Watcher/StreamWatcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace React\EventLoop\Watcher;

final class StreamWatcher
{
public function __construct(
public int $key,
/** @var ?callable */
public $readListener = null,
/** @var ?callable */
public $writeListener = null,
) {
}
}
17 changes: 17 additions & 0 deletions tests/IoPollLoopTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace React\Tests\EventLoop;

use React\EventLoop\IoPollLoop;

class IoPollLoopTest extends \React\Tests\EventLoop\AbstractLoopTest
{
public function createLoop()
{
if (\PHP_VERSION_ID < 80600 && !\class_exists('Io\Poll\Context', false)) {
$this->markTestSkipped('IOPollLoop tests skipped because IO Poll is not available.');
}

return new IoPollLoop();
}
}
Loading