1
0
mirror of https://github.com/danog/amp.git synced 2024-12-13 18:07:30 +01:00
amp/lib/NativeLoop.php

671 lines
19 KiB
PHP
Raw Normal View History

2016-05-19 18:12:35 +02:00
<?php
namespace Amp\Loop;
2016-05-26 06:09:53 +02:00
use Amp\Loop\Internal\Watcher;
2016-05-19 18:12:35 +02:00
use Interop\Async\LoopDriver;
use Interop\Async\UnsupportedFeatureException;
class NativeLoop implements LoopDriver {
const MILLISEC_PER_SEC = 1e3;
const MICROSEC_PER_SEC = 1e6;
/**
* @var \Amp\Loop\Internal\Watcher[]
*/
private $watchers = [];
/**
* @var string[]
*/
private $deferQueue = [];
/**
* @var resource[]
*/
private $readStreams = [];
/**
* @var string[]
*/
private $readWatchers = [];
/**
* @var resource[]
*/
private $writeStreams = [];
/**
* @var string[]
*/
private $writeWatchers = [];
/**
* @var int[]
*/
private $timerExpires = [];
/**
* @var \SplPriorityQueue
*/
private $timerQueue;
/**
* @var string[][]
*/
private $signalWatchers = [];
/**
* @var \Amp\Loop\Internal\Watcher[]
*/
private $unreferenced = [];
/**
* @var callable
*/
private $errorHandler;
/**
* @var bool
*/
private $running = false;
/**
* @var bool
*/
private $signalHandling;
public function __construct() {
$this->timerQueue = new \SplPriorityQueue();
2016-05-26 06:09:53 +02:00
$this->signalHandling = \extension_loaded("pcntl");
2016-05-19 18:12:35 +02:00
}
/**
* {@inheritdoc}
*
2016-05-26 06:24:06 +02:00
* @throws \Amp\Loop\AlreadyRunningException
2016-05-19 18:12:35 +02:00
*/
public function run() {
if ($this->running) {
2016-05-26 06:24:06 +02:00
throw new AlreadyRunningException("Cannot run loop recursively; loop already running");
2016-05-19 18:12:35 +02:00
}
$this->running = true;
try {
while ($this->running) {
if ($this->isEmpty()) {
return;
}
$this->tick();
}
} finally {
$this->stop();
}
}
/**
* {@inheritdoc}
*/
public function stop() {
$this->running = false;
}
/**
* @return bool True if no referenced watchers remain in the loop.
*/
private function isEmpty() {
if (empty($this->watchers)) {
return true;
}
if (empty($this->unreferenced)) {
return false;
}
return \count($this->watchers) === \count($this->unreferenced);
2016-05-19 18:12:35 +02:00
}
/**
* Executes a single tick of the event loop.
*/
private function tick() {
try {
2016-05-23 07:37:56 +02:00
if (!empty($this->deferQueue)) {
$this->invokeDeferred();
}
2016-05-19 18:12:35 +02:00
$this->selectStreams($this->readStreams, $this->writeStreams, $this->getTimeout());
2016-05-23 07:37:56 +02:00
if (!empty($this->timerExpires)) {
$this->invokeTimers();
}
2016-05-19 18:12:35 +02:00
if ($this->signalHandling) {
\pcntl_signal_dispatch();
2016-05-19 18:12:35 +02:00
}
} catch (\Throwable $exception) {
if (null === $this->errorHandler) {
throw $exception;
}
$errorHandler = $this->errorHandler;
$errorHandler($exception);
2016-05-23 07:37:56 +02:00
} catch (\Exception $exception) { // @todo Remove when PHP 5.x support is no longer needed.
2016-05-19 18:12:35 +02:00
if (null === $this->errorHandler) {
throw $exception;
}
$errorHandler = $this->errorHandler;
$errorHandler($exception);
}
}
/**
* @param resource[] $read
* @param resource[] $write
* @param int $timeout
*/
private function selectStreams(array $read, array $write, $timeout) {
$timeout /= self::MILLISEC_PER_SEC;
if (!empty($read) || !empty($write)) { // Use stream_select() if there are any streams in the loop.
if ($timeout >= 0) {
2016-05-19 18:12:35 +02:00
$seconds = (int) $timeout;
$microseconds = (int) (($timeout - $seconds) * self::MICROSEC_PER_SEC);
} else {
$seconds = null;
$microseconds = null;
}
$except = null;
// Error reporting suppressed since stream_select() emits an E_WARNING if it is interrupted by a signal.
$count = @\stream_select($read, $write, $except, $seconds, $microseconds);
2016-05-19 18:12:35 +02:00
if ($count) {
foreach ($read as $stream) {
$key = (int) $stream;
if (isset($this->readStreams[$key], $this->readWatchers[$key])) {
$watcher = $this->watchers[$this->readWatchers[$key]];
$callback = $watcher->callback;
$callback($watcher->id, $stream, $watcher->data);
}
}
foreach ($write as $stream) {
$key = (int) $stream;
if (isset($this->writeStreams[$key], $this->writeWatchers[$key])) {
$watcher = $this->watchers[$this->writeWatchers[$key]];
$callback = $watcher->callback;
$callback($watcher->id, $stream, $watcher->data);
}
}
}
return;
}
if ($timeout > 0) { // Otherwise sleep with usleep() if $timeout > 0.
\usleep($timeout * self::MICROSEC_PER_SEC);
2016-05-19 18:12:35 +02:00
}
}
/**
* @return int Milliseconds until next timer expires or -1 if there are no pending times.
*/
private function getTimeout() {
while (!$this->timerQueue->isEmpty()) {
list($id, $timeout) = $this->timerQueue->top();
if (!isset($this->timerExpires[$id]) || $timeout !== $this->timerExpires[$id]) {
$this->timerQueue->extract(); // Timer was removed from queue.
continue;
}
$timeout -= (int) (\microtime(true) * self::MILLISEC_PER_SEC);
2016-05-19 18:12:35 +02:00
if ($timeout < 0) {
2016-05-19 18:12:35 +02:00
return 0;
}
return $timeout;
}
return -1;
}
/**
* Invokes all pending defer watchers.
*/
private function invokeDeferred() {
2016-05-24 16:36:16 +02:00
$queue = $this->deferQueue;
$this->deferQueue = [];
$count = 0;
2016-05-19 18:12:35 +02:00
try {
2016-05-24 16:36:16 +02:00
foreach ($queue as $id) {
++$count;
2016-05-19 18:12:35 +02:00
if (!isset($this->watchers[$id])) {
continue;
}
$watcher = $this->watchers[$id];
unset($this->watchers[$id], $this->unreferenced[$id]);
$callback = $watcher->callback;
$callback($watcher->id, $watcher->data);
}
2016-05-24 16:36:16 +02:00
} catch (\Throwable $exception) {
if ($count !== \count($queue)) {
$this->deferQueue = \array_merge(\array_slice($queue, $count), $this->deferQueue);
}
throw $exception;
} catch (\Exception $exception) {
if ($count !== \count($queue)) {
$this->deferQueue = \array_merge(\array_slice($queue, $count), $this->deferQueue);
2016-05-19 18:12:35 +02:00
}
2016-05-24 16:36:16 +02:00
throw $exception;
2016-05-19 18:12:35 +02:00
}
}
/**
* Invokes all pending delay and repeat watchers.
*/
private function invokeTimers() {
$time = (int) (\microtime(true) * self::MILLISEC_PER_SEC);
2016-05-19 18:12:35 +02:00
while (!$this->timerQueue->isEmpty()) {
list($id, $timeout) = $this->timerQueue->top();
if (!isset($this->timerExpires[$id]) || $timeout !== $this->timerExpires[$id]) {
$this->timerQueue->extract(); // Timer was removed from queue.
continue;
}
if ($this->timerExpires[$id] > $time) { // Timer at top of queue has not expired.
return;
}
// Remove and execute timer. Replace timer if persistent.
$this->timerQueue->extract();
2016-05-26 06:09:53 +02:00
$watcher = $this->watchers[$id];
2016-05-19 18:12:35 +02:00
2016-05-26 06:09:53 +02:00
if ($watcher->type === Watcher::REPEAT) {
$timeout = $time + $watcher->value;
2016-05-19 18:12:35 +02:00
$this->timerQueue->insert([$id, $timeout], -$timeout);
$this->timerExpires[$id] = $timeout;
} else {
unset($this->watchers[$id], $this->timerExpires[$id], $this->unreferenced[$id]);
}
// Execute the timer.
2016-05-26 06:09:53 +02:00
$callback = $watcher->callback;
$callback($watcher->id, $watcher->data);
2016-05-19 18:12:35 +02:00
}
}
/**
* {@inheritdoc}
*/
public function defer(callable $callback, $data = null) {
2016-05-26 06:09:53 +02:00
$watcher = new Watcher;
$watcher->type = Watcher::DEFER;
$watcher->id = \spl_object_hash($watcher);
$watcher->callback = $callback;
$watcher->data = $data;
2016-05-19 18:12:35 +02:00
$this->watchers[$watcher->id] = $watcher;
$this->deferQueue[] = $watcher->id;
return $watcher->id;
}
/**
* {@inheritdoc}
*/
public function delay($delay, callable $callback, $data = null) {
2016-05-26 06:09:53 +02:00
$delay = (int) $delay;
if ($delay <= 0) {
throw new \InvalidArgumentException("Delay must be greater than or equal to zero");
}
$watcher = new Watcher;
$watcher->type = Watcher::DELAY;
$watcher->id = \spl_object_hash($watcher);
$watcher->callback = $callback;
$watcher->value = $delay;
$watcher->data = $data;
$this->watchers[$watcher->id] = $watcher;
$expiration = (int) (\microtime(true) * self::MILLISEC_PER_SEC) + $watcher->value;
$this->timerExpires[$watcher->id] = $expiration;
$this->timerQueue->insert([$watcher->id, $expiration], -$expiration);
return $watcher->id;
2016-05-19 18:12:35 +02:00
}
/**
* {@inheritdoc}
*/
public function repeat($interval, callable $callback, $data = null) {
2016-05-26 06:09:53 +02:00
$interval = (int) $interval;
if ($interval <= 0) {
throw new \InvalidArgumentException("Interval must be greater than or equal to zero");
}
$watcher = new Watcher;
$watcher->type = Watcher::REPEAT;
$watcher->id = \spl_object_hash($watcher);
$watcher->callback = $callback;
$watcher->value = $interval;
$watcher->data = $data;
2016-05-19 18:12:35 +02:00
$this->watchers[$watcher->id] = $watcher;
2016-05-26 06:09:53 +02:00
$expiration = (int) (\microtime(true) * self::MILLISEC_PER_SEC) + $watcher->value;
2016-05-19 18:12:35 +02:00
$this->timerExpires[$watcher->id] = $expiration;
$this->timerQueue->insert([$watcher->id, $expiration], -$expiration);
return $watcher->id;
}
/**
* {@inheritdoc}
*/
public function onReadable($stream, callable $callback, $data = null) {
2016-05-26 06:09:53 +02:00
$watcher = new Watcher;
$watcher->type = Watcher::READABLE;
$watcher->id = \spl_object_hash($watcher);
$watcher->callback = $callback;
$watcher->value = $stream;
$watcher->data = $data;
2016-05-19 18:12:35 +02:00
$this->watchers[$watcher->id] = $watcher;
2016-05-26 06:09:53 +02:00
$key = (int) $watcher->value;
$this->readWatchers[$key] = $watcher->id;
$this->readStreams[$key] = $watcher->value;
2016-05-19 18:12:35 +02:00
return $watcher->id;
}
/**
* {@inheritdoc}
*/
public function onWritable($stream, callable $callback, $data = null) {
2016-05-26 06:09:53 +02:00
$watcher = new Watcher;
$watcher->type = Watcher::WRITABLE;
$watcher->id = \spl_object_hash($watcher);
$watcher->callback = $callback;
$watcher->value = $stream;
$watcher->data = $data;
2016-05-19 18:12:35 +02:00
$this->watchers[$watcher->id] = $watcher;
2016-05-26 06:09:53 +02:00
$key = (int) $watcher->value;
$this->writeWatchers[$key] = $watcher->id;
$this->writeStreams[$key] = $watcher->value;
2016-05-19 18:12:35 +02:00
return $watcher->id;
}
/**
* {@inheritdoc}
*
* @throws \Interop\Async\UnsupportedFeatureException If the pcntl extension is not available.
2016-05-26 06:24:06 +02:00
* @throws \Amp\Loop\SignalHandlerException If creating the backend signal handler fails.
2016-05-19 18:12:35 +02:00
*/
public function onSignal($signo, callable $callback, $data = null) {
if (!$this->signalHandling) {
2016-05-26 06:09:53 +02:00
throw new UnsupportedFeatureException("Signal handling requires the pcntl extension");
2016-05-19 18:12:35 +02:00
}
2016-05-26 06:09:53 +02:00
$watcher = new Watcher;
$watcher->type = Watcher::WRITABLE;
$watcher->id = \spl_object_hash($watcher);
$watcher->callback = $callback;
$watcher->value = $signo;
$watcher->data = $data;
2016-05-19 18:12:35 +02:00
$this->enableSignal($watcher);
$this->watchers[$watcher->id] = $watcher;
return $watcher->id;
}
/**
2016-05-26 06:09:53 +02:00
* @param \Amp\Loop\Internal\Watcher $watcher
2016-05-19 18:12:35 +02:00
*
2016-05-26 06:24:06 +02:00
* @throws \Amp\Loop\SignalHandlerException If creating the backend signal handler fails.
2016-05-19 18:12:35 +02:00
*/
2016-05-26 06:09:53 +02:00
private function enableSignal(Watcher $watcher) {
if (!isset($this->signalWatchers[$watcher->value])) {
if (!@\pcntl_signal($watcher->value, function ($signo) {
2016-05-19 18:12:35 +02:00
foreach ($this->signalWatchers[$signo] as $id) {
if (!isset($this->watchers[$id])) {
continue;
}
$watcher = $this->watchers[$id];
$callback = $watcher->callback;
2016-05-26 06:09:53 +02:00
$callback($watcher->id, $watcher->value, $watcher->data);
2016-05-19 18:12:35 +02:00
}
})) {
2016-05-26 06:24:06 +02:00
throw new SignalHandlerException("Failed to register signal handler");
2016-05-19 18:12:35 +02:00
}
2016-05-26 06:09:53 +02:00
$this->signalWatchers[$watcher->value] = [];
2016-05-19 18:12:35 +02:00
}
2016-05-26 06:09:53 +02:00
$this->signalWatchers[$watcher->value][$watcher->id] = $watcher->id;
2016-05-19 18:12:35 +02:00
}
/**
2016-05-26 06:09:53 +02:00
* @param \Amp\Loop\Internal\Watcher $watcher
2016-05-19 18:12:35 +02:00
*/
2016-05-26 06:09:53 +02:00
private function disableSignal(Watcher $watcher) {
if (isset($this->signalWatchers[$watcher->value])) {
unset($this->signalWatchers[$watcher->value][$watcher->id]);
2016-05-19 18:12:35 +02:00
2016-05-26 06:09:53 +02:00
if (empty($this->signalWatchers[$watcher->value])) {
unset($this->signalWatchers[$watcher->value]);
@\pcntl_signal($watcher->value, \SIG_DFL);
2016-05-19 18:12:35 +02:00
}
}
}
/**
* {@inheritdoc}
*/
public function setErrorHandler(callable $callback = null) {
$this->errorHandler = $callback;
}
/**
* {@inheritdoc}
*/
public function enable($watcherIdentifier) {
if (!isset($this->watchers[$watcherIdentifier])) {
return;
}
$watcher = $this->watchers[$watcherIdentifier];
2016-05-26 06:09:53 +02:00
switch ($watcher->type) {
case Watcher::READABLE:
$key = (int) $watcher->value;
$this->readWatchers[$key] = $watcher->id;
$this->readStreams[$key] = $watcher->value;
break;
case Watcher::WRITABLE:
$key = (int) $watcher->value;
$this->writeWatchers[$key] = $watcher->id;
$this->writeStreams[$key] = $watcher->value;
break;
case Watcher::DELAY:
case Watcher::REPEAT:
$expiration = (int) (\microtime(true) * self::MILLISEC_PER_SEC) + $watcher->value;
$this->timerExpires[$watcher->id] = $expiration;
$this->timerQueue->insert([$watcher->id, $expiration], -$expiration);
break;
case Watcher::SIGNAL:
$this->enableSignal($watcher);
break;
2016-05-19 18:12:35 +02:00
}
}
/**
* {@inheritdoc}
*/
public function disable($watcherIdentifier) {
if (!isset($this->watchers[$watcherIdentifier])) {
return;
}
$watcher = $this->watchers[$watcherIdentifier];
2016-05-26 06:09:53 +02:00
switch ($watcher->type) {
case Watcher::READABLE:
$key = (int) $watcher->value;
unset($this->readWatchers[$key], $this->readStreams[$key]);
break;
case Watcher::WRITABLE:
$key = (int) $watcher->value;
unset($this->writeWatchers[$key], $this->writeStreams[$key]);
break;
case Watcher::DELAY:
2016-05-19 18:12:35 +02:00
unset($this->watchers[$watcher->id]);
2016-05-26 06:09:53 +02:00
// No break
case Watcher::REPEAT:
unset($this->timerExpires[$watcher->id]);
break;
case Watcher::DEFER:
unset($this->watchers[$watcher->id]);
break;
case Watcher::SIGNAL:
$this->disableSignal($watcher);
break;
2016-05-19 18:12:35 +02:00
}
}
/**
* {@inheritdoc}
*/
public function cancel($watcherIdentifier) {
$this->disable($watcherIdentifier);
unset($this->watchers[$watcherIdentifier], $this->unreferenced[$watcherIdentifier]);
}
/**
* {@inheritdoc}
*/
public function reference($watcherIdentifier) {
unset($this->unreferenced[$watcherIdentifier]);
}
/**
* {@inheritdoc}
*/
public function unreference($watcherIdentifier) {
if (!isset($this->watchers[$watcherIdentifier])) {
return;
}
$this->unreferenced[$watcherIdentifier] = $watcherIdentifier;
}
/**
* {@inheritdoc}
*/
public function info() {
$watchers = [
2016-05-26 06:09:53 +02:00
"referenced" => \count($this->watchers) - \count($this->unreferenced),
"unreferenced" => \count($this->unreferenced),
];
2016-05-19 18:12:35 +02:00
$defer = $delay = $repeat = $onReadable = $onWritable = $onSignal = [
2016-05-26 06:09:53 +02:00
"enabled" => 0,
"disabled" => 0,
2016-05-19 18:12:35 +02:00
];
foreach ($this->watchers as $watcher) {
2016-05-26 06:09:53 +02:00
switch ($watcher->type) {
case Watcher::READABLE:
if (isset($this->readWatchers[(int) $watcher->value])) {
++$onReadable["enabled"];
} else {
++$onReadable["disabled"];
}
break;
case Watcher::WRITABLE:
if (isset($this->writeWatchers[(int) $watcher->value])) {
++$onWritable["enabled"];
} else {
++$onWritable["disabled"];
}
break;
case Watcher::DEFER:
++$defer["enabled"];
break;
case Watcher::DELAY:
++$delay["enabled"];
break;
case Watcher::REPEAT:
if (isset($this->timerExpires[$watcher->id])) {
++$repeat["enabled"];
} else {
++$repeat["disabled"];
}
break;
2016-05-19 18:12:35 +02:00
}
}
return [
2016-05-26 06:09:53 +02:00
"defer" => $defer,
"delay" => $delay,
"repeat" => $repeat,
"on_readable" => $onReadable,
"on_writable" => $onWritable,
"on_signal" => $onSignal,
"watchers" => $watchers,
"running" => $this->running,
2016-05-19 18:12:35 +02:00
];
}
/**
* {@inheritdoc}
*/
public function getHandle() {
2016-05-19 18:12:35 +02:00
return null;
}
2016-05-26 06:09:53 +02:00
/**
* Returns the same array of data as info().
*
* @return array
*/
public function __debugInfo() {
return $this->info();
}
2016-05-19 18:12:35 +02:00
}