Initial Commit

This commit is contained in:
David Stone
2024-11-30 18:24:12 -07:00
commit e8f7955c1c
5432 changed files with 1397750 additions and 0 deletions

View File

@ -0,0 +1,159 @@
<?php
namespace WP_Ultimo\Dependencies\Amp\Internal;
use WP_Ultimo\Dependencies\Amp\Coroutine;
use WP_Ultimo\Dependencies\Amp\Failure;
use WP_Ultimo\Dependencies\Amp\Loop;
use WP_Ultimo\Dependencies\Amp\Promise;
use WP_Ultimo\Dependencies\React\Promise\PromiseInterface as ReactPromise;
/**
* Trait used by Promise implementations. Do not use this trait in your code, instead compose your class from one of
* the available classes implementing \Amp\Promise.
*
* @internal
*/
trait Placeholder
{
/** @var bool */
private $resolved = \false;
/** @var mixed */
private $result;
/** @var ResolutionQueue|null|callable(\Throwable|null, mixed): (Promise|\React\Promise\PromiseInterface|\Generator<mixed,
* Promise|\React\Promise\PromiseInterface|array<array-key, Promise|\React\Promise\PromiseInterface>, mixed,
* mixed>|null)|callable(\Throwable|null, mixed): void */
private $onResolved;
/** @var null|array */
private $resolutionTrace;
/**
* @inheritdoc
*/
public function onResolve(callable $onResolved)
{
if ($this->resolved) {
if ($this->result instanceof Promise) {
$this->result->onResolve($onResolved);
return;
}
try {
/** @var mixed $result */
$result = $onResolved(null, $this->result);
if ($result === null) {
return;
}
if ($result instanceof \Generator) {
$result = new Coroutine($result);
}
if ($result instanceof Promise || $result instanceof ReactPromise) {
Promise\rethrow($result);
}
} catch (\Throwable $exception) {
Loop::defer(static function () use($exception) {
throw $exception;
});
}
return;
}
if (null === $this->onResolved) {
$this->onResolved = $onResolved;
return;
}
if (!$this->onResolved instanceof ResolutionQueue) {
/** @psalm-suppress InternalClass */
$this->onResolved = new ResolutionQueue($this->onResolved);
}
/** @psalm-suppress InternalMethod */
$this->onResolved->push($onResolved);
}
public function __destruct()
{
try {
$this->result = null;
} catch (\Throwable $e) {
Loop::defer(static function () use($e) {
throw $e;
});
}
}
/**
* @param mixed $value
*
* @return void
*
* @throws \Error Thrown if the promise has already been resolved.
*/
private function resolve($value = null)
{
if ($this->resolved) {
$message = "Promise has already been resolved";
if (isset($this->resolutionTrace)) {
$trace = formatStacktrace($this->resolutionTrace);
$message .= ". Previous resolution trace:\n\n{$trace}\n\n";
} else {
// @codeCoverageIgnoreStart
$message .= ", define environment variable AMP_DEBUG or const AMP_DEBUG = true and enable assertions " . "for a stacktrace of the previous resolution.";
// @codeCoverageIgnoreEnd
}
throw new \Error($message);
}
\assert((function () {
$env = \getenv("AMP_DEBUG") ?: "0";
if ($env !== "0" && $env !== "false" || \defined("AMP_DEBUG") && \AMP_DEBUG) {
$trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
\array_shift($trace);
// remove current closure
$this->resolutionTrace = $trace;
}
return \true;
})());
if ($value instanceof ReactPromise) {
$value = Promise\adapt($value);
}
$this->resolved = \true;
$this->result = $value;
if ($this->onResolved === null) {
return;
}
$onResolved = $this->onResolved;
$this->onResolved = null;
if ($this->result instanceof Promise) {
$this->result->onResolve($onResolved);
return;
}
try {
/** @var mixed $result */
$result = $onResolved(null, $this->result);
$onResolved = null;
// allow garbage collection of $onResolved, to catch any exceptions from destructors
if ($result === null) {
return;
}
if ($result instanceof \Generator) {
$result = new Coroutine($result);
}
if ($result instanceof Promise || $result instanceof ReactPromise) {
Promise\rethrow($result);
}
} catch (\Throwable $exception) {
Loop::defer(static function () use($exception) {
throw $exception;
});
}
}
/**
* @param \Throwable $reason Failure reason.
*
* @return void
*/
private function fail(\Throwable $reason)
{
$this->resolve(new Failure($reason));
}
/**
* @return bool True if the placeholder has been resolved.
*/
private function isResolved() : bool
{
return $this->resolved;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace WP_Ultimo\Dependencies\Amp\Internal;
use WP_Ultimo\Dependencies\Amp\Iterator;
use WP_Ultimo\Dependencies\Amp\Promise;
/**
* Wraps an Iterator instance that has public methods to emit, complete, and fail into an object that only allows
* access to the public API methods.
*
* @template-covariant TValue
* @template-implements Iterator<TValue>
*/
final class PrivateIterator implements Iterator
{
/** @var Iterator<TValue> */
private $iterator;
/**
* @param Iterator $iterator
*
* @psalm-param Iterator<TValue> $iterator
*/
public function __construct(Iterator $iterator)
{
$this->iterator = $iterator;
}
/**
* @return Promise<bool>
*/
public function advance() : Promise
{
return $this->iterator->advance();
}
/**
* @psalm-return TValue
*/
public function getCurrent()
{
return $this->iterator->getCurrent();
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace WP_Ultimo\Dependencies\Amp\Internal;
use WP_Ultimo\Dependencies\Amp\Promise;
/**
* Wraps a Promise instance that has public methods to resolve and fail the promise into an object that only allows
* access to the public API methods.
*/
final class PrivatePromise implements Promise
{
/** @var Promise */
private $promise;
public function __construct(Promise $promise)
{
$this->promise = $promise;
}
public function onResolve(callable $onResolved)
{
$this->promise->onResolve($onResolved);
}
}

View File

@ -0,0 +1,173 @@
<?php
namespace WP_Ultimo\Dependencies\Amp\Internal;
use WP_Ultimo\Dependencies\Amp\Deferred;
use WP_Ultimo\Dependencies\Amp\Failure;
use WP_Ultimo\Dependencies\Amp\Promise;
use WP_Ultimo\Dependencies\Amp\Success;
use WP_Ultimo\Dependencies\React\Promise\PromiseInterface as ReactPromise;
/**
* Trait used by Iterator implementations. Do not use this trait in your code, instead compose your class from one of
* the available classes implementing \Amp\Iterator.
* Note that it is the responsibility of the user of this trait to ensure that listeners have a chance to listen first
* before emitting values.
*
* @internal
* @template-covariant TValue
*/
trait Producer
{
/** @var Promise|null */
private $complete;
/** @var mixed[] */
private $values = [];
/** @var Deferred[] */
private $backPressure = [];
/** @var int */
private $consumePosition = -1;
/** @var int */
private $emitPosition = -1;
/** @var Deferred|null */
private $waiting;
/** @var null|array */
private $resolutionTrace;
/**
* {@inheritdoc}
*
* @return Promise<bool>
*/
public function advance() : Promise
{
if ($this->waiting !== null) {
throw new \Error("The prior promise returned must resolve before invoking this method again");
}
unset($this->values[$this->consumePosition]);
$position = ++$this->consumePosition;
if (\array_key_exists($position, $this->values)) {
\assert(isset($this->backPressure[$position]));
$deferred = $this->backPressure[$position];
unset($this->backPressure[$position]);
$deferred->resolve();
return new Success(\true);
}
if ($this->complete) {
return $this->complete;
}
$this->waiting = new Deferred();
return $this->waiting->promise();
}
/**
* {@inheritdoc}
*
* @return TValue
*/
public function getCurrent()
{
if (empty($this->values) && $this->complete) {
throw new \Error("The iterator has completed");
}
if (!\array_key_exists($this->consumePosition, $this->values)) {
throw new \Error("Promise returned from advance() must resolve before calling this method");
}
return $this->values[$this->consumePosition];
}
/**
* Emits a value from the iterator. The returned promise is resolved once the emitted value has been consumed.
*
* @param mixed $value
*
* @return Promise
* @psalm-return Promise<null>
*
* @throws \Error If the iterator has completed.
*/
private function emit($value) : Promise
{
if ($this->complete) {
throw new \Error("Iterators cannot emit values after calling complete");
}
if ($value instanceof ReactPromise) {
$value = Promise\adapt($value);
}
if ($value instanceof Promise) {
$deferred = new Deferred();
$value->onResolve(function ($e, $v) use($deferred) {
if ($this->complete) {
$deferred->fail(new \Error("The iterator was completed before the promise result could be emitted"));
return;
}
if ($e) {
$this->fail($e);
$deferred->fail($e);
return;
}
$deferred->resolve($this->emit($v));
});
return $deferred->promise();
}
$position = ++$this->emitPosition;
$this->values[$position] = $value;
if ($this->waiting !== null) {
$waiting = $this->waiting;
$this->waiting = null;
$waiting->resolve(\true);
return new Success();
// Consumer was already waiting for a new value, so back-pressure is unnecessary.
}
$this->backPressure[$position] = $pressure = new Deferred();
return $pressure->promise();
}
/**
* Completes the iterator.
*
* @return void
*
* @throws \Error If the iterator has already been completed.
*/
private function complete()
{
if ($this->complete) {
$message = "Iterator has already been completed";
if (isset($this->resolutionTrace)) {
$trace = formatStacktrace($this->resolutionTrace);
$message .= ". Previous completion trace:\n\n{$trace}\n\n";
} else {
// @codeCoverageIgnoreStart
$message .= ", define environment variable AMP_DEBUG or const AMP_DEBUG = true and enable assertions " . "for a stacktrace of the previous resolution.";
// @codeCoverageIgnoreEnd
}
throw new \Error($message);
}
\assert((function () {
$env = \getenv("AMP_DEBUG") ?: "0";
if ($env !== "0" && $env !== "false" || \defined("AMP_DEBUG") && \AMP_DEBUG) {
$trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
\array_shift($trace);
// remove current closure
$this->resolutionTrace = $trace;
}
return \true;
})());
$this->complete = new Success(\false);
if ($this->waiting !== null) {
$waiting = $this->waiting;
$this->waiting = null;
$waiting->resolve($this->complete);
}
}
/**
* @param \Throwable $exception
*
* @return void
*/
private function fail(\Throwable $exception)
{
$this->complete = new Failure($exception);
if ($this->waiting !== null) {
$waiting = $this->waiting;
$this->waiting = null;
$waiting->resolve($this->complete);
}
}
}

View File

@ -0,0 +1,82 @@
<?php
namespace WP_Ultimo\Dependencies\Amp\Internal;
use WP_Ultimo\Dependencies\Amp\Coroutine;
use WP_Ultimo\Dependencies\Amp\Loop;
use WP_Ultimo\Dependencies\Amp\Promise;
use WP_Ultimo\Dependencies\React\Promise\PromiseInterface as ReactPromise;
/**
* Stores a set of functions to be invoked when a promise is resolved.
*
* @internal
* @psalm-internal Amp\Internal
*/
class ResolutionQueue
{
/** @var array<array-key, callable(\Throwable|null, mixed): (Promise|\React\Promise\PromiseInterface|\Generator<mixed,
* Promise|\React\Promise\PromiseInterface|array<array-key, Promise|\React\Promise\PromiseInterface>, mixed,
* mixed>|null) | callable(\Throwable|null, mixed): void> */
private $queue = [];
/**
* @param callable|null $callback Initial callback to add to queue.
*
* @psalm-param null|callable(\Throwable|null, mixed): (Promise|\React\Promise\PromiseInterface|\Generator<mixed,
* Promise|\React\Promise\PromiseInterface|array<array-key, Promise|\React\Promise\PromiseInterface>, mixed,
* mixed>|null) | callable(\Throwable|null, mixed): void $callback
*/
public function __construct(callable $callback = null)
{
if ($callback !== null) {
$this->push($callback);
}
}
/**
* Unrolls instances of self to avoid blowing up the call stack on resolution.
*
* @param callable $callback
*
* @psalm-param callable(\Throwable|null, mixed): (Promise|\React\Promise\PromiseInterface|\Generator<mixed,
* Promise|\React\Promise\PromiseInterface|array<array-key, Promise|\React\Promise\PromiseInterface>, mixed,
* mixed>|null) | callable(\Throwable|null, mixed): void $callback
*
* @return void
*/
public function push(callable $callback)
{
if ($callback instanceof self) {
$this->queue = \array_merge($this->queue, $callback->queue);
return;
}
$this->queue[] = $callback;
}
/**
* Calls each callback in the queue, passing the provided values to the function.
*
* @param \Throwable|null $exception
* @param mixed $value
*
* @return void
*/
public function __invoke($exception, $value)
{
foreach ($this->queue as $callback) {
try {
$result = $callback($exception, $value);
if ($result === null) {
continue;
}
if ($result instanceof \Generator) {
$result = new Coroutine($result);
}
if ($result instanceof Promise || $result instanceof ReactPromise) {
Promise\rethrow($result);
}
} catch (\Throwable $exception) {
Loop::defer(static function () use($exception) {
throw $exception;
});
}
}
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace WP_Ultimo\Dependencies\Amp\Internal;
/**
* Formats a stacktrace obtained via `debug_backtrace()`.
*
* @param array<array{file?: string, line: int, type?: string, class: string, function: string}> $trace Output of
* `debug_backtrace()`.
*
* @return string Formatted stacktrace.
*
* @codeCoverageIgnore
* @internal
*/
function formatStacktrace(array $trace) : string
{
return \implode("\n", \array_map(static function ($e, $i) {
$line = "#{$i} ";
if (isset($e["file"])) {
$line .= "{$e['file']}:{$e['line']} ";
}
if (isset($e["type"])) {
$line .= $e["class"] . $e["type"];
}
return $line . $e["function"] . "()";
}, $trace, \array_keys($trace)));
}
/**
* Creates a `TypeError` with a standardized error message.
*
* @param string[] $expected Expected types.
* @param mixed $given Given value.
*
* @return \TypeError
*
* @internal
*/
function createTypeError(array $expected, $given) : \TypeError
{
$givenType = \is_object($given) ? \sprintf("instance of %s", \get_class($given)) : \gettype($given);
if (\count($expected) === 1) {
$expectedType = "Expected the following type: " . \array_pop($expected);
} else {
$expectedType = "Expected one of the following types: " . \implode(", ", $expected);
}
return new \TypeError("{$expectedType}; {$givenType} given");
}
/**
* Returns the current time relative to an arbitrary point in time.
*
* @return int Time in milliseconds.
*/
function getCurrentTime() : int
{
/** @var int|null $startTime */
static $startTime;
/** @var int|null $nextWarning */
static $nextWarning;
if (\PHP_INT_SIZE === 4) {
// @codeCoverageIgnoreStart
if ($startTime === null) {
$startTime = \PHP_VERSION_ID >= 70300 ? \hrtime(\false)[0] : \time();
$nextWarning = \PHP_INT_MAX - 86400 * 7;
}
if (\PHP_VERSION_ID >= 70300) {
list($seconds, $nanoseconds) = \hrtime(\false);
$seconds -= $startTime;
if ($seconds >= $nextWarning) {
$timeToOverflow = (\PHP_INT_MAX - $seconds * 1000) / 1000;
\trigger_error("getCurrentTime() will overflow in {$timeToOverflow} seconds, please restart the process before that. " . "You're using a 32 bit version of PHP, so time will overflow about every 24 days. Regular restarts are required.", \E_USER_WARNING);
/** @psalm-suppress PossiblyNullOperand */
$nextWarning += 600;
// every 10 minutes
}
return (int) ($seconds * 1000 + $nanoseconds / 1000000);
}
$seconds = \microtime(\true) - $startTime;
if ($seconds >= $nextWarning) {
$timeToOverflow = (\PHP_INT_MAX - $seconds * 1000) / 1000;
\trigger_error("getCurrentTime() will overflow in {$timeToOverflow} seconds, please restart the process before that. " . "You're using a 32 bit version of PHP, so time will overflow about every 24 days. Regular restarts are required.", \E_USER_WARNING);
/** @psalm-suppress PossiblyNullOperand */
$nextWarning += 600;
// every 10 minutes
}
return (int) ($seconds * 1000);
// @codeCoverageIgnoreEnd
}
if (\PHP_VERSION_ID >= 70300) {
list($seconds, $nanoseconds) = \hrtime(\false);
return (int) ($seconds * 1000 + $nanoseconds / 1000000);
}
return (int) (\microtime(\true) * 1000);
}