From a622e7d7d47137a16cce56dba9464f9a3d11c024 Mon Sep 17 00:00:00 2001 From: Chad Sikorra Date: Fri, 13 Nov 2026 10:59:52 -0500 Subject: [PATCH] Add a per-call read timeout. --- .github/workflows/build.yml | 3 + composer.json | 6 +- phpunit.xml.dist | 3 + .../Socket/Exception/ReadTimeoutException.php | 23 ++ src/FreeDSx/Socket/Socket.php | 162 ++++++++---- src/FreeDSx/Socket/Timeout/ReadDeadline.php | 130 ++++++++++ tests/integration/PartialTlsRecordClient.php | 126 +++++++++ tests/integration/TlsReadTimeoutTest.php | 177 +++++++++++++ tests/unit/SocketTest.php | 244 ++++++++++++++++++ tests/unit/Timeout/ReadDeadlineTest.php | 234 +++++++++++++++++ 10 files changed, 1062 insertions(+), 46 deletions(-) create mode 100644 src/FreeDSx/Socket/Exception/ReadTimeoutException.php create mode 100644 src/FreeDSx/Socket/Timeout/ReadDeadline.php create mode 100644 tests/integration/PartialTlsRecordClient.php create mode 100644 tests/integration/TlsReadTimeoutTest.php create mode 100644 tests/unit/Timeout/ReadDeadlineTest.php diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 51a5db8..922b418 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -35,3 +35,6 @@ jobs: - name: Run Tests run: composer run-script test-unit + + - name: Run Integration Tests + run: composer run-script test-integration diff --git a/composer.json b/composer.json index 46dc8b1..332234c 100644 --- a/composer.json +++ b/composer.json @@ -35,7 +35,8 @@ }, "autoload-dev": { "psr-4": { - "Tests\\Unit\\FreeDSx\\Socket\\": "tests/unit" + "Tests\\Unit\\FreeDSx\\Socket\\": "tests/unit", + "Tests\\Integration\\FreeDSx\\Socket\\": "tests/integration" } }, "config": { @@ -47,6 +48,9 @@ "test-unit": [ "@php -d xdebug.mode=off vendor/bin/phpunit --testsuite unit" ], + "test-integration": [ + "@php -d xdebug.mode=off vendor/bin/phpunit --testsuite integration" + ], "test-coverage": [ "@php -d xdebug.mode=coverage vendor/bin/phpunit --testsuite unit --coverage-clover=coverage.xml" ], diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 63ba7d6..9333cf2 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -26,5 +26,8 @@ ./tests/unit + + ./tests/integration + diff --git a/src/FreeDSx/Socket/Exception/ReadTimeoutException.php b/src/FreeDSx/Socket/Exception/ReadTimeoutException.php new file mode 100644 index 0000000..e09cacf --- /dev/null +++ b/src/FreeDSx/Socket/Exception/ReadTimeoutException.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace FreeDSx\Socket\Exception; + +/** + * Thrown when a blocking read does not complete within the timeout given for that read. + * + * @author Chad Sikorra + */ +final class ReadTimeoutException extends ConnectionException +{ +} diff --git a/src/FreeDSx/Socket/Socket.php b/src/FreeDSx/Socket/Socket.php index ed204a4..0980de2 100644 --- a/src/FreeDSx/Socket/Socket.php +++ b/src/FreeDSx/Socket/Socket.php @@ -15,6 +15,8 @@ use FreeDSx\Socket\Exception\ConnectionException; use FreeDSx\Socket\Exception\IdleTimeoutException; +use FreeDSx\Socket\Exception\ReadTimeoutException; +use FreeDSx\Socket\Timeout\ReadDeadline; use FreeDSx\Socket\Timeout\WriteTimeoutEnforcerInterface; use FreeDSx\Socket\Tls\Certificate; use OpenSSLCertificate; @@ -27,7 +29,7 @@ use function is_array; use function is_resource; use function is_string; -use function microtime; +use function max; use function sprintf; use function stream_context_create; use function stream_context_get_options; @@ -49,6 +51,8 @@ class Socket { private const MICROSECONDS_PER_SECOND = 1_000_000; + private const MINIMUM_STREAM_TIMEOUT = 0.001; + protected bool $isEncrypted = false; protected ?SocketAddress $peerAddress = null; @@ -87,24 +91,87 @@ public function __construct( } /** + * @param float|null $timeout The most seconds a blocking read may take when shorter than the read timeout. * @throws IdleTimeoutException when a blocking read makes no progress within the configured read timeout. + * @throws ReadTimeoutException when a blocking read does not complete within the timeout given for it. */ - public function read(bool $block = true): string|false - { + public function read( + bool $block = true, + ?float $timeout = null, + ): string|false { $stream = $this->getStream(); + if (!$block) { + $data = $this->readWithoutBlocking($stream); + + return $data === '' + ? false + : $data; + } // Bytes decrypted into the TLS buffer are off the wire already. - $buffered = $block && $this->isEncrypted + $buffered = $this->isEncrypted ? $this->readWithoutBlocking($stream) : ''; - if ($buffered !== '') { - return $buffered; + + return $buffered !== '' + ? $buffered + : $this->readBlocking( + $stream, + ReadDeadline::start( + $this->options->getTimeoutRead(), + $timeout, + ), + ); + } + + /** + * A timeout given for the read also bounds the stream, which a partial TLS record would otherwise hold. + * + * @param resource $stream + * @throws IdleTimeoutException|ReadTimeoutException + */ + private function readBlocking( + $stream, + ReadDeadline $deadline, + ): string|false { + $this->awaitReadable( + $stream, + $deadline, + ); + $streamTimeout = $deadline->streamTimeout(); + if ($streamTimeout === null) { + return $this->fetch( + $stream, + $deadline, + ); } - if ($block) { - $this->awaitReadable($stream); + + $this->setReadTimeout( + $stream, + $streamTimeout, + ); + try { + return $this->fetch( + $stream, + $deadline, + ); + } finally { + $this->setStreamOpts(); } - stream_set_blocking($stream, $block); + } + /** + * @param resource $stream + * @throws IdleTimeoutException|ReadTimeoutException + */ + private function fetch( + $stream, + ReadDeadline $deadline, + ): string|false { + stream_set_blocking( + $stream, + true, + ); $data = fread( $stream, $this->options->getBufferSize(), @@ -112,18 +179,8 @@ public function read(bool $block = true): string|false // A blocking read yields no bytes on either a peer disconnect (feof, empty string) or a read timeout // (false). Only the timeout case sets the timed_out meta flag, which distinguishes the two. - if ($block && ($data === '' || $data === false) && $this->hasReadTimedOut($stream)) { - throw new IdleTimeoutException(sprintf( - 'The connection was idle for longer than the read timeout of %d seconds.', - $this->options->getTimeoutRead(), - )); - } - - if (!$block) { - stream_set_blocking( - $stream, - true, - ); + if (($data === '' || $data === false) && $this->hasReadTimedOut($stream, $deadline)) { + throw $deadline->exceeded(); } return $data === '' @@ -154,35 +211,21 @@ private function readWithoutBlocking($stream): string } /** - * Wait for the socket to become readable. This enforces the read timeout that the blocking read would. + * Wait for the socket to become readable. This enforces the deadline that the blocking read would. * * Waiting here returns on EINTR and lets the caller run its signal handlers. * * @param resource $stream - * @throws IdleTimeoutException + * @throws IdleTimeoutException|ReadTimeoutException */ - private function awaitReadable($stream): void - { - $timeout = $this->options->getTimeoutRead(); - $deadline = $timeout > 0 - ? microtime(true) + $timeout - : null; - + private function awaitReadable( + $stream, + ReadDeadline $deadline, + ): void { while (true) { - $remaining = $deadline === null - ? null - : $deadline - microtime(true); - - if ($remaining !== null && $remaining <= 0) { - throw new IdleTimeoutException(sprintf( - 'The connection was idle for longer than the read timeout of %d seconds.', - $timeout, - )); - } - $ready = self::selectReadable( $stream, - $remaining, + $deadline->remaining(), ); if ($ready > 0) { @@ -191,18 +234,47 @@ private function awaitReadable($stream): void if (!is_resource($stream)) { return; } + if ($deadline->hasPassed()) { + throw $deadline->exceeded(); + } } } /** * @param resource $stream */ - private function hasReadTimedOut($stream): bool - { - return $this->options->getTimeoutRead() > 0 + private function hasReadTimedOut( + $stream, + ReadDeadline $deadline, + ): bool { + return $deadline->isBounded() && stream_get_meta_data($stream)['timed_out'] === true; } + /** + * Never below a millisecond, since a stream timeout of zero waits without limit on TLS. + * + * @param resource $stream + */ + private function setReadTimeout( + $stream, + float $seconds, + ): void { + $seconds = max( + self::MINIMUM_STREAM_TIMEOUT, + $seconds, + ); + + stream_set_timeout( + $stream, + (int) $seconds, + (int) (fmod( + $seconds, + 1.0, + ) * self::MICROSECONDS_PER_SECOND), + ); + } + public function write(string $data): static { $timeout = $this->options->getTimeoutWrite(); diff --git a/src/FreeDSx/Socket/Timeout/ReadDeadline.php b/src/FreeDSx/Socket/Timeout/ReadDeadline.php new file mode 100644 index 0000000..c411ec6 --- /dev/null +++ b/src/FreeDSx/Socket/Timeout/ReadDeadline.php @@ -0,0 +1,130 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace FreeDSx\Socket\Timeout; + +use FreeDSx\Socket\Exception\IdleTimeoutException; +use FreeDSx\Socket\Exception\ReadTimeoutException; + +use function is_finite; +use function max; +use function microtime; +use function sprintf; + +/** + * When a blocking read must finish, set by the shorter of the read timeout and a timeout given for that read. + * + * @internal + * + * @author Chad Sikorra + */ +readonly class ReadDeadline +{ + private function __construct( + private ?float $expiresAt, + private int $readTimeout, + private ?float $timeout, + private bool $isSetByTimeout, + ) { + } + + /** + * @param int $readTimeout The read timeout in seconds, or zero or less for none. + * @param float|null $timeout The seconds given for the read, ignored when it is not finite. + */ + public static function start( + int $readTimeout, + ?float $timeout, + ): self { + $timeout = $timeout !== null && is_finite($timeout) + ? max( + 0.0, + $timeout, + ) + : null; + $isSetByTimeout = self::isSetByTimeout( + $timeout, + $readTimeout, + ); + $seconds = match (true) { + $isSetByTimeout => $timeout, + $readTimeout > 0 => (float) $readTimeout, + default => null, + }; + + return new self( + $seconds === null + ? null + : microtime(true) + $seconds, + $readTimeout, + $timeout, + $isSetByTimeout, + ); + } + + public function isBounded(): bool + { + return $this->expiresAt !== null; + } + + /** + * The seconds left, never below zero, or null when the read has no deadline. + */ + public function remaining(): ?float + { + return $this->expiresAt === null + ? null + : max( + 0.0, + $this->expiresAt - microtime(true), + ); + } + + public function hasPassed(): bool + { + return $this->expiresAt !== null && microtime(true) >= $this->expiresAt; + } + + /** + * The seconds the stream itself may block for, or null to keep its read timeout when no timeout was given. + */ + public function streamTimeout(): ?float + { + return $this->timeout === null + ? null + : $this->remaining(); + } + + public function exceeded(): IdleTimeoutException|ReadTimeoutException + { + if ($this->isSetByTimeout) { + return new ReadTimeoutException(sprintf( + 'The read did not complete within its timeout of %g seconds.', + $this->timeout, + )); + } + + return new IdleTimeoutException(sprintf( + 'The connection was idle for longer than the read timeout of %d seconds.', + $this->readTimeout, + )); + } + + private static function isSetByTimeout( + ?float $timeout, + int $readTimeout, + ): bool { + return $timeout !== null + && ($readTimeout <= 0 || $timeout < $readTimeout); + } +} diff --git a/tests/integration/PartialTlsRecordClient.php b/tests/integration/PartialTlsRecordClient.php new file mode 100644 index 0000000..1088a77 --- /dev/null +++ b/tests/integration/PartialTlsRecordClient.php @@ -0,0 +1,126 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Tests\Integration\FreeDSx\Socket; + +use RuntimeException; + +/** + * A TLS client in its own process that sends only the start of a record. + */ +final class PartialTlsRecordClient +{ + private const AUTOLOADER = __DIR__ . '/../../vendor/autoload.php'; + + /** + * A record header that announces more bytes than ever follow it. + */ + private const PARTIAL_RECORD = "\x17\x03\x03\x04\x00partial"; + + /** + * @param resource $process + * @param resource $input + */ + private function __construct( + private $process, + private $input, + ) { + } + + /** + * Connects to the port and sends the partial record once the delay in seconds has passed. + */ + public static function start( + int $port, + float $delay, + ): self { + $pipes = []; + $process = proc_open( + [ + PHP_BINARY, + '-r', + sprintf( + 'require %s; %s::run(%d, %F);', + var_export( + self::AUTOLOADER, + true, + ), + self::class, + $port, + $delay, + ), + ], + [0 => ['pipe', 'r']], + $pipes, + ); + if (!is_resource($process) || !isset($pipes[0])) { + throw new RuntimeException('Unable to start the client.'); + } + + return new self( + $process, + $pipes[0], + ); + } + + /** + * Closing the input ends the client, which holds its connection open until then. + */ + public function stop(): void + { + fclose($this->input); + proc_close($this->process); + } + + /** + * Runs in the client's own process. + */ + public static function run( + int $port, + float $delay, + ): void { + $client = stream_socket_client( + 'tcp://127.0.0.1:' . $port, + $errorNumber, + $errorMessage, + 5.0, + STREAM_CLIENT_CONNECT, + stream_context_create([ + 'ssl' => [ + 'verify_peer' => false, + 'verify_peer_name' => false, + ], + ]), + ); + if ($client === false) { + throw new RuntimeException('Unable to connect: ' . $errorMessage); + } + + // Taken before TLS starts, since a stream with TLS on cannot be imported. + $raw = socket_import_stream($client); + stream_set_timeout( + $client, + 5, + ); + if ($raw === false || stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) !== true) { + throw new RuntimeException('Unable to start TLS.'); + } + + usleep((int) ($delay * 1_000_000)); + socket_write( + $raw, + self::PARTIAL_RECORD, + ); + fgets(STDIN); + } +} diff --git a/tests/integration/TlsReadTimeoutTest.php b/tests/integration/TlsReadTimeoutTest.php new file mode 100644 index 0000000..e0ef112 --- /dev/null +++ b/tests/integration/TlsReadTimeoutTest.php @@ -0,0 +1,177 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Tests\Integration\FreeDSx\Socket; + +use FreeDSx\Socket\Exception\ReadTimeoutException; +use FreeDSx\Socket\SocketServer; +use FreeDSx\Socket\SocketServerOptions; +use PHPUnit\Framework\TestCase; +use RuntimeException; +use Tests\Unit\FreeDSx\Socket\GeneratesCertificates; +use Tests\Unit\FreeDSx\Socket\RunsInCoroutine; +use Throwable; + +final class TlsReadTimeoutTest extends TestCase +{ + use GeneratesCertificates; + use RunsInCoroutine; + + private int $port = 0; + + private string $certFile = ''; + + private string $keyFile = ''; + + protected function setUp(): void + { + if (!extension_loaded('openssl') || !extension_loaded('sockets')) { + self::markTestSkipped('The openssl and sockets extensions are required.'); + } + $this->port = self::freePort(); + [$certificate, $key] = $this->generateCertificate(); + $this->certFile = $this->tempFile(); + $this->keyFile = $this->tempFile(); + openssl_x509_export_to_file( + $certificate, + $this->certFile, + ); + openssl_pkey_export_to_file( + $key, + $this->keyFile, + ); + } + + protected function tearDown(): void + { + foreach ([$this->certFile, $this->keyFile] as $file) { + if ($file !== '') { + @unlink($file); + } + } + } + + public function test_a_partial_tls_record_does_not_hold_a_read_past_its_own_timeout(): void + { + [$caught, $elapsed] = $this->readWhileTheClientSendsAPartialRecord(); + + self::assertInstanceOf( + ReadTimeoutException::class, + $caught, + ); + self::assertLessThan( + 3.0, + $elapsed, + ); + } + + public function test_a_partial_tls_record_does_not_hold_a_read_in_a_coroutine_past_its_own_timeout(): void + { + if (!extension_loaded('swoole')) { + self::markTestSkipped('The swoole extension is required.'); + } + $result = [null, 0.0]; + + $this->runInCoroutine(function () use (&$result): void { + $result = $this->readWhileTheClientSendsAPartialRecord(); + }); + [$caught, $elapsed] = $result; + + self::assertInstanceOf( + ReadTimeoutException::class, + $caught, + ); + self::assertLessThan( + 3.0, + $elapsed, + ); + } + + /** + * @return array{0: ?Throwable, 1: float} + */ + private function readWhileTheClientSendsAPartialRecord(): array + { + $server = null; + $client = null; + $start = microtime(true); + + try { + // A short idle timeout keeps a read the stream timeout fails to bound from hanging the test. + $server = SocketServer::bindTcp( + '127.0.0.1', + $this->port, + (new SocketServerOptions()) + ->setUseSsl(true) + ->setSslCert($this->certFile) + ->setSslCertKey($this->keyFile) + ->setIdleTimeout(5), + ); + $client = PartialTlsRecordClient::start( + $this->port, + 0.3, + ); + $connection = $server->accept(5.0) ?? throw new RuntimeException('The client did not connect.'); + + $start = microtime(true); + $connection->read( + true, + 1.0, + ); + + return [null, microtime(true) - $start]; + } catch (Throwable $e) { + return [$e, microtime(true) - $start]; + } finally { + $client?->stop(); + $server?->close(); + } + } + + private function tempFile(): string + { + $file = tempnam( + sys_get_temp_dir(), + 'freedsx_socket_', + ); + if ($file === false) { + self::fail('Unable to create a temporary file.'); + } + + return $file; + } + + private static function freePort(): int + { + $probe = stream_socket_server('tcp://127.0.0.1:0'); + if ($probe === false) { + self::fail('Unable to find a free port.'); + } + $name = stream_socket_get_name( + $probe, + false, + ); + fclose($probe); + if ($name === false) { + self::fail('Unable to read the free port.'); + } + + return (int) substr( + $name, + (int) strrpos( + $name, + ':', + ) + 1, + ); + } +} diff --git a/tests/unit/SocketTest.php b/tests/unit/SocketTest.php index dbfb318..a03397c 100644 --- a/tests/unit/SocketTest.php +++ b/tests/unit/SocketTest.php @@ -14,18 +14,22 @@ namespace Tests\Unit\FreeDSx\Socket; use FreeDSx\Socket\Exception\IdleTimeoutException; +use FreeDSx\Socket\Exception\ReadTimeoutException; use FreeDSx\Socket\Exception\WriteTimeoutException; use FreeDSx\Socket\Socket; use FreeDSx\Socket\SocketOptions; use FreeDSx\Socket\Tls\Certificate; use FreeDSx\Socket\Transport; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use Throwable; final class SocketTest extends TestCase { use RequiresNonWindows; use RequiresUnixTransport; use GeneratesCertificates; + use RunsInCoroutine; /** * @var resource|null @@ -344,6 +348,239 @@ public function test_it_should_leave_the_socket_in_blocking_mode_after_a_non_blo self::assertTrue(stream_get_meta_data($local)['blocked']); } + public function test_a_blocking_read_throws_a_read_timeout_when_its_own_timeout_passes_first(): void + { + [$local] = $this->createSocketPair(); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(5), + ); + + $this->expectException(ReadTimeoutException::class); + + $subject->read( + true, + 0.2, + ); + } + + public function test_a_blocking_read_throws_an_idle_timeout_when_the_read_timeout_passes_first(): void + { + [$local] = $this->createSocketPair(); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(1), + ); + + $this->expectException(IdleTimeoutException::class); + + $subject->read( + true, + 5.0, + ); + } + + public function test_a_blocking_read_returns_data_that_arrives_within_its_own_timeout(): void + { + [$local, $remote] = $this->createSocketPair(); + fwrite( + $remote, + 'data', + ); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(5), + ); + + self::assertSame( + 'data', + $subject->read( + true, + 1.0, + ), + ); + } + + /** + * @return array + */ + public static function noTimeLeftProvider(): array + { + return [ + 'zero' => [0.0], + 'negative' => [-1.0], + ]; + } + + #[DataProvider('noTimeLeftProvider')] + public function test_a_blocking_read_with_no_time_left_returns_data_already_received(float $timeout): void + { + $this->requireNonWindows('A loopback socket pair on Windows may not have the bytes ready at once.'); + [$local, $remote] = $this->createSocketPair(); + fwrite( + $remote, + 'data', + ); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(5), + ); + + self::assertSame( + 'data', + $subject->read( + true, + $timeout, + ), + ); + } + + #[DataProvider('noTimeLeftProvider')] + public function test_a_blocking_read_with_no_time_left_throws_a_read_timeout_when_nothing_was_received( + float $timeout, + ): void { + [$local] = $this->createSocketPair(); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(5), + ); + + $this->expectException(ReadTimeoutException::class); + + $subject->read( + true, + $timeout, + ); + } + + public function test_a_blocking_read_with_its_own_timeout_returns_false_when_the_peer_has_closed(): void + { + [$local, $remote] = $this->createSocketPair(); + fclose($remote); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(5), + ); + + self::assertFalse($subject->read( + true, + 1.0, + )); + } + + public function test_a_blocking_read_with_its_own_timeout_puts_back_the_read_timeout_of_the_stream(): void + { + [$local, $remote] = $this->createSocketPair(); + fwrite( + $remote, + 'data', + ); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(1), + ); + $subject->read( + true, + 0.5, + ); + + $start = microtime(true); + fread( + $local, + 1, + ); + + self::assertGreaterThanOrEqual( + 0.9, + microtime(true) - $start, + ); + } + + public function test_a_non_blocking_read_ignores_a_timeout_given_for_it(): void + { + [$local] = $this->createSocketPair(); + $subject = new Socket($local); + + self::assertFalse($subject->read( + false, + 0.0, + )); + } + + public function test_a_blocking_read_in_a_coroutine_throws_a_read_timeout_when_its_own_timeout_passes_first(): void + { + $this->requireSwoole(); + $caught = null; + + $this->runInCoroutine(function () use (&$caught): void { + [$local, $remote] = $this->createSocketPair(); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(5), + ); + + try { + $subject->read( + true, + 0.2, + ); + } catch (Throwable $e) { + $caught = $e; + } finally { + fclose($local); + fclose($remote); + } + }); + + self::assertInstanceOf( + ReadTimeoutException::class, + $caught, + ); + } + + public function test_a_blocking_read_in_a_coroutine_with_its_own_timeout_puts_back_the_read_timeout_of_the_stream( + ): void { + $this->requireSwoole(); + $caught = null; + $elapsed = 0.0; + + $this->runInCoroutine(function () use (&$caught, &$elapsed): void { + [$local, $remote] = $this->createSocketPair(); + fwrite( + $remote, + 'data', + ); + $subject = new Socket( + $local, + (new SocketOptions())->setTimeoutRead(1), + ); + + try { + $subject->read( + true, + 0.5, + ); + $start = microtime(true); + fread( + $local, + 1, + ); + $elapsed = microtime(true) - $start; + } catch (Throwable $e) { + $caught = $e; + } finally { + fclose($local); + fclose($remote); + } + }); + + self::assertNull($caught); + self::assertGreaterThanOrEqual( + 0.9, + $elapsed, + ); + } + public function test_it_should_return_null_for_the_peer_certificate_when_not_connected(): void { self::assertNull((new Socket())->getPeerCertificate()); @@ -451,4 +688,11 @@ private function createUnixServer(): string return $this->unixPath; } + + private function requireSwoole(): void + { + if (!extension_loaded('swoole')) { + self::markTestSkipped('The swoole extension is required.'); + } + } } diff --git a/tests/unit/Timeout/ReadDeadlineTest.php b/tests/unit/Timeout/ReadDeadlineTest.php new file mode 100644 index 0000000..13d2b8a --- /dev/null +++ b/tests/unit/Timeout/ReadDeadlineTest.php @@ -0,0 +1,234 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Tests\Unit\FreeDSx\Socket\Timeout; + +use FreeDSx\Socket\Exception\IdleTimeoutException; +use FreeDSx\Socket\Exception\ReadTimeoutException; +use FreeDSx\Socket\Timeout\ReadDeadline; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; + +final class ReadDeadlineTest extends TestCase +{ + /** + * @return array + */ + public static function setByTimeoutProvider(): array + { + return [ + 'shorter than the read timeout' => [ + 10, + 0.5, + ], + 'without a read timeout' => [ + 0, + 5.0, + ], + ]; + } + + /** + * @return array + */ + public static function setByReadTimeoutProvider(): array + { + return [ + 'a longer timeout given' => [ + 1, + 5.0, + ], + 'an equal timeout given' => [ + 5, + 5.0, + ], + 'no timeout given' => [ + 10, + null, + ], + 'a timeout given that is not finite' => [ + 10, + INF, + ], + ]; + } + + /** + * @return array + */ + public static function unboundedProvider(): array + { + return [ + 'no timeouts' => [ + 0, + null, + ], + 'a negative read timeout' => [ + -1, + null, + ], + 'an infinite timeout given' => [ + 0, + INF, + ], + 'a timeout given that is not a number' => [ + 0, + NAN, + ], + ]; + } + + /** + * @return array + */ + public static function noTimeLeftProvider(): array + { + return [ + 'zero' => [0.0], + 'negative' => [-1.0], + ]; + } + + #[DataProvider('setByTimeoutProvider')] + public function test_a_deadline_set_by_the_timeout_given_is_exceeded_with_a_read_timeout( + int $readTimeout, + float $timeout, + ): void { + self::assertInstanceOf( + ReadTimeoutException::class, + ReadDeadline::start( + $readTimeout, + $timeout, + )->exceeded(), + ); + } + + #[DataProvider('setByReadTimeoutProvider')] + public function test_a_deadline_set_by_the_read_timeout_is_exceeded_with_an_idle_timeout( + int $readTimeout, + ?float $timeout, + ): void { + self::assertInstanceOf( + IdleTimeoutException::class, + ReadDeadline::start( + $readTimeout, + $timeout, + )->exceeded(), + ); + } + + public function test_a_read_timeout_names_the_timeout_given(): void + { + self::assertSame( + 'The read did not complete within its timeout of 0.5 seconds.', + ReadDeadline::start( + 10, + 0.5, + )->exceeded()->getMessage(), + ); + } + + public function test_a_deadline_without_a_timeout_given_leaves_the_stream_timeout_as_it_is(): void + { + self::assertNull(ReadDeadline::start( + 10, + null, + )->streamTimeout()); + } + + public function test_a_timeout_given_bounds_the_stream_by_the_time_left(): void + { + $streamTimeout = ReadDeadline::start( + 10, + 0.5, + )->streamTimeout(); + + self::assertNotNull($streamTimeout); + self::assertGreaterThan( + 0.0, + $streamTimeout, + ); + self::assertLessThanOrEqual( + 0.5, + $streamTimeout, + ); + } + + public function test_a_timeout_given_bounds_the_stream_by_the_read_timeout_when_that_is_shorter(): void + { + $streamTimeout = ReadDeadline::start( + 1, + 5.0, + )->streamTimeout(); + + self::assertNotNull($streamTimeout); + self::assertGreaterThan( + 0.5, + $streamTimeout, + ); + self::assertLessThanOrEqual( + 1.0, + $streamTimeout, + ); + } + + #[DataProvider('unboundedProvider')] + public function test_a_read_without_a_finite_timeout_has_no_deadline( + int $readTimeout, + ?float $timeout, + ): void { + $subject = ReadDeadline::start( + $readTimeout, + $timeout, + ); + + self::assertFalse($subject->isBounded()); + self::assertNull($subject->remaining()); + self::assertFalse($subject->hasPassed()); + self::assertNull($subject->streamTimeout()); + } + + public function test_a_deadline_has_time_left_before_it_passes(): void + { + $subject = ReadDeadline::start( + 10, + null, + ); + + self::assertTrue($subject->isBounded()); + self::assertFalse($subject->hasPassed()); + self::assertGreaterThan( + 9.0, + $subject->remaining(), + ); + } + + #[DataProvider('noTimeLeftProvider')] + public function test_a_timeout_given_of_zero_or_less_has_already_passed(float $timeout): void + { + $subject = ReadDeadline::start( + 10, + $timeout, + ); + + self::assertTrue($subject->hasPassed()); + self::assertSame( + 0.0, + $subject->remaining(), + ); + self::assertInstanceOf( + ReadTimeoutException::class, + $subject->exceeded(), + ); + } +}