Skip to content
124 changes: 107 additions & 17 deletions src/StreamSelectLoop.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
class StreamSelectLoop implements LoopInterface
{
const MICROSECONDS_PER_SECOND = 1000000;
const NANOSECONDS_PER_SECOND = 1000000000;
const NANOSECONDS_PER_MICROSECOND = 1000;

private $futureTickQueue;
private $timers;
Expand Down Expand Up @@ -152,20 +154,9 @@ public function run()
// Future-tick queue has pending callbacks ...
if (!$this->running || !$this->futureTickQueue->isEmpty()) {
$timeout = 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;
} else {
/*
* round() needed to correct float error:
* https://github.com/reactphp/event-loop/issues/48
*/
$timeout = round($timeout * self::MICROSECONDS_PER_SECOND);
}

$timeout = max($scheduledAt - $this->timers->getTime(), 0);
// The only possible event is stream activity, so wait forever ...
} elseif ($this->readStreams || $this->writeStreams) {
$timeout = null;
Expand All @@ -189,6 +180,8 @@ public function stop()

/**
* Wait/check for stream activity, or until the next timer is due.
*
* @param float $timeout
*/
private function waitForStreamActivity($timeout)
{
Expand Down Expand Up @@ -219,28 +212,125 @@ private function waitForStreamActivity($timeout)
}
}

/**
* Returns integer amount of seconds in $time or null.
*
* @param float|null $time – time in seconds
*
* @return int|null
*/
private static function getSeconds($time)
{
if ($time === null) {
return null;
}

/*
* Workaround for PHP int overflow:
* (float)PHP_INT_MAX == PHP_INT_MAX => true
* (int)(float)PHP_INT_MAX == PHP_INT_MAX => false
* (int)(float)PHP_INT_MAX == PHP_INT_MIN => true
*/
if ($time == PHP_INT_MAX) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strict comparision (===)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jsor, $time is float, so strict comparison will always return false.

(float) PHP_INT_MAX === PHP_INT_MAX; //is false
(float) PHP_INT_MAX == PHP_INT_MAX; //is true

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 (maybe add a comment that loose comparision is intentional)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jsor I added more description about this tricky if in 3c8a5d6 😄

return PHP_INT_MAX;
}

return intval(floor($time));
}

/**
* Returns integer amount of microseconds in $time or null.
*
* @param float|null $time – time in seconds
*
* @return int|null
*/
private static function getMicroseconds($time)
{
if ($time === null) {
return null;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably return 0. stream_select accepts null only for the $seconds parameter.

}
$fractional = fmod($time, 1);
$microseconds = round($fractional * self::MICROSECONDS_PER_SECOND);

return intval($microseconds);
}

/**
* Returns integer amount of nanoseconds in $time or null.
* The precision is 1 microsecond.
*
* @param float|null $time – time in seconds
*
* @return int|null
*/
private static function getNanoseconds($time)
{
if ($time === null) {
return null;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably return 0, see above.

}

return intval(self::getMicroseconds($time) * self::NANOSECONDS_PER_MICROSECOND);
}

/**
* Emulate a stream_select() implementation that does not break when passed
* empty stream arrays.
*
* @param array &$read An array of read streams to select upon.
* @param array &$write An array of write streams to select upon.
* @param integer|null $timeout Activity timeout in microseconds, or null to wait forever.
* @param float|null $timeout Activity timeout in seconds, or null to wait forever.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a rather subtle BC break as consumers could possibly rely on this protected API. Not saying this is an issue with your proposed change, it's more that we screwed up could have done better with defining our external API.

*
* @return integer|false The total number of streams that are ready for read/write.
* Can return false if stream_select() is interrupted by a signal.
*/
protected function streamSelect(array &$read, array &$write, $timeout)
{
$seconds = self::getSeconds($timeout);
$microseconds = self::getMicroseconds($timeout);
$nanoseconds = self::getNanoseconds($timeout);

if ($read || $write) {
$except = null;
$except = [];

// suppress warnings that occur, when stream_select is interrupted by a signal
return @stream_select($read, $write, $except, $timeout === null ? null : 0, $timeout);
return $this->doSelectStream($read, $write, $except, $seconds, $microseconds);
}

$timeout && usleep($timeout);
$this->sleep($seconds, $nanoseconds);

return 0;
}

/**
* Proxy for built-in stream_select method.
*
* @param array $read
* @param array $write
* @param array $except
* @param int|null $seconds
* @param int|null $microseconds
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should only accept int, see also above.

*
* @return int
*/
protected function doSelectStream(array &$read, array &$write, array &$except, $seconds, $microseconds = null)
{
// suppress warnings that occur, when stream_select is interrupted by a signal
return @stream_select($read, $write, $except, $seconds, $microseconds);
}

/**
* Sleeps for $seconds and $nanoseconds.
*
* @param int|null $seconds
* @param int|null $nanoseconds
*/
protected function sleep($seconds, $nanoseconds = 0)
{
if ($seconds === null || $nanoseconds === null) {
return;
}
if ($seconds > 0 || $nanoseconds > 0) {
time_nanosleep($seconds, $nanoseconds);
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to see explicit handling of $secondsor $nanosecondsbeing null here.

}
}
29 changes: 24 additions & 5 deletions tests/StreamSelectLoopTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,15 @@ protected function forkSendSignal($signal)
public function testSmallTimerInterval()
{
/** @var StreamSelectLoop|\PHPUnit_Framework_MockObject_MockObject $loop */
$loop = $this->getMock('React\EventLoop\StreamSelectLoop', ['streamSelect']);
$loop = $this->getMock('React\EventLoop\StreamSelectLoop', ['sleep']);
$loop
->expects($this->at(0))
->method('streamSelect')
->with([], [], 1);
->method('sleep')
->with(0, intval(Timer::MIN_INTERVAL * StreamSelectLoop::NANOSECONDS_PER_SECOND));
$loop
->expects($this->at(1))
->method('streamSelect')
->with([], [], 0);
->method('sleep')
->with(0, 0);

$callsCount = 0;
$loop->addPeriodicTimer(Timer::MIN_INTERVAL, function() use (&$loop, &$callsCount) {
Expand All @@ -176,4 +176,23 @@ public function testSmallTimerInterval()

$loop->run();
}

/**
* https://github.com/reactphp/event-loop/issues/19
*
* Tests that timer with PHP_INT_MAX seconds interval will work.
*/
public function testIntOverflowTimerInterval()
{
/** @var StreamSelectLoop|\PHPUnit_Framework_MockObject_MockObject $loop */
$loop = $this->getMock('React\EventLoop\StreamSelectLoop', ['sleep']);
$loop->expects($this->once())
->method('sleep')
->with(PHP_INT_MAX, 0)
->willReturnCallback(function() use (&$loop) {
$loop->stop();
});
$loop->addTimer(PHP_INT_MAX, function(){});
$loop->run();
}
}