diff --git a/README.md b/README.md index 18a633c..b7dccdd 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,43 @@ $client = new PsrClickHouseAsyncClient( $output = $client->select('SELECT 1 AS data', new JsonEachRow())->await(); ``` +### Cancellation + +All four async select methods accept a trailing optional `Amp\Cancellation` argument. +Omitting it keeps the operation uncancelled: + +```php +use Amp\DeferredCancellation; +use SimPod\ClickHouseClient\Format\TabSeparated; + +$cancellation = new DeferredCancellation(); +$future = $client->selectStream( + 'SELECT number FROM system.numbers', + new TabSeparated(), + cancellation: $cancellation->getCancellation(), +); + +$payload = $future->await(); + +try { + $chunk = $payload->read(); + $cancellation->cancel(); + $payload->read(); // Throws Amp\CancelledException, without needing another read token. +} finally { + $payload->close(); +} +``` + +The operation token applies to the HTTP request, buffered response bodies, and later reads or buffering of a +returned payload. A token passed directly to `read()` or `buffer()` is combined with the operation token. +Cancellation is reported through the future or payload as `Amp\CancelledException`. +Pipeline 1.2.1 or later is required to avoid a pending-read cancellation defect in earlier versions. +Close a streamed payload when it is no longer needed. Client I/O cancellation does not guarantee that ClickHouse +has stopped executing the query. + +Existing calls do not need to change. Implementations of `ClickHouseAsyncClient` and subclasses overriding its +methods must add the trailing `Cancellation|null $cancellation = null` parameter and forward it when delegating. + ## Parameters "binding" ```php diff --git a/composer.json b/composer.json index d84f562..6268ae0 100644 --- a/composer.json +++ b/composer.json @@ -30,8 +30,10 @@ "require": { "php": "^8.4", "amphp/amp": "^3.1", + "amphp/byte-stream": "^2.0", "amphp/http-client": "^5.3", "amphp/http-client-psr7": "^1.1", + "amphp/pipeline": "^1.2.1", "guzzlehttp/psr7": "^2.6 || ^3.0", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 44c9e90..4903e79 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -12,6 +12,12 @@ parameters: - RuntimeException ignoreErrors: + # JsonEachRow explicitly implements Format>; PHPStan 2.3.6 rejects nested mixed. + - message: '~^Parameter #3 \$outputFormat of method SimPod\\ClickHouseClient\\Client\\ClickHouseClient::selectWithParams\(\) expects SimPod\\ClickHouseClient\\Format\\Format>>, SimPod\\ClickHouseClient\\Format\\JsonEachRow> given\.$~' + identifier: argument.type + path: src/Snippet/Parts.php + count: 1 + # There's no other way to test-pass without assertions while counting it towards coverage https://github.com/sebastianbergmann/phpunit/issues/3016 - '~Call to static method PHPUnit\\Framework\\Assert::assertTrue\(\) with true will always evaluate to true~' diff --git a/src/Client/ClickHouseAsyncClient.php b/src/Client/ClickHouseAsyncClient.php index 2a38351..dddd539 100644 --- a/src/Client/ClickHouseAsyncClient.php +++ b/src/Client/ClickHouseAsyncClient.php @@ -5,12 +5,17 @@ namespace SimPod\ClickHouseClient\Client; use Amp\ByteStream\Payload; +use Amp\Cancellation; use Amp\Future; use SimPod\ClickHouseClient\Format\Format; use SimPod\ClickHouseClient\Output\Output; use SimPod\ClickHouseClient\Settings\EmptySettingsProvider; use SimPod\ClickHouseClient\Settings\SettingsProvider; +/** + * Cancellation applies to the HTTP request and response consumption, including later reads of a returned payload. + * Cancelled operations fail with Amp\CancelledException through their future or returned payload. + */ interface ClickHouseAsyncClient { /** @@ -24,6 +29,7 @@ public function select( string $query, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future; /** @@ -39,6 +45,7 @@ public function selectWithParams( array $params, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future; /** @@ -50,6 +57,7 @@ public function selectStream( string $query, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future; /** @@ -63,5 +71,6 @@ public function selectStreamWithParams( array $params, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future; } diff --git a/src/Client/Http/CancellationStream.php b/src/Client/Http/CancellationStream.php new file mode 100644 index 0000000..969b625 --- /dev/null +++ b/src/Client/Http/CancellationStream.php @@ -0,0 +1,175 @@ + + */ +final class CancellationStream implements ReadableStream, IteratorAggregate +{ + use ReadableStreamIteratorAggregate; + + private string|null $subscription = null; + + private CancelledException|null $exception = null; + + private ReadableStream|null $source; + + /** @var DeferredFuture */ + private readonly DeferredFuture $onClose; + + public function __construct( + ReadableStream $source, + private readonly Cancellation $cancellation, + ) { + $this->source = $source; + $this->onClose = new DeferredFuture(); + + $this->subscribe(); + } + + public function __destruct() + { + $this->close(); + } + + /** + * @throws CancelledException + * @throws StreamException + */ + public function read(Cancellation|null $cancellation = null): string|null + { + if ($this->exception !== null) { + throw $this->exception; + } + + $source = $this->source; + + if ($source === null) { + return null; + } + + $readCancellation = $cancellation === null + ? $this->cancellation + : new CompositeCancellation($this->cancellation, $cancellation); + + try { + // Buffered sources need not inspect cancellation, and older composites update asynchronously. + $this->throwIfCancelled(); + $cancellation?->throwIfRequested(); + $chunk = $source->read($readCancellation); + $this->throwIfCancelled(); + } catch (Throwable $exception) { + // Closing a pending source read can produce a stream error or EOF instead of cancellation. + $this->throwIfCancelled(); + + if (! $exception instanceof CancelledException || $cancellation?->isRequested() !== true) { + $this->close(); + } + + throw $exception; + } + + if ($chunk === null) { + $this->close(); + } + + return $chunk; + } + + public function isReadable(): bool + { + return $this->source?->isReadable() ?? false; + } + + public function close(): void + { + $source = $this->source; + + if ($source === null) { + return; + } + + $this->source = null; + + if ($this->subscription !== null) { + $this->cancellation->unsubscribe($this->subscription); + $this->subscription = null; + } + + try { + $source->close(); + } finally { + $this->onClose->complete(); + } + } + + public function isClosed(): bool + { + return ! $this->isReadable(); + } + + public function onClose(Closure $onClose): void + { + $this->onClose->getFuture()->finally($onClose); + } + + private function subscribe(): void + { + $reference = WeakReference::create($this); + + $subscription = $this->cancellation->subscribe( + static function (CancelledException $exception) use ($reference): void { + $reference->get()?->cancel($exception); + }, + ); + + // A Cancellation implementation may invoke its callback before subscribe() returns. + if ($this->source === null) { + $this->cancellation->unsubscribe($subscription); + } else { + $this->subscription = $subscription; + $this->source->onClose(static function () use ($reference): void { + $reference->get()?->close(); + }); + } + } + + private function cancel(CancelledException $exception): void + { + if ($this->source === null) { + return; + } + + $this->exception = $exception; + $this->close(); + } + + /** @throws CancelledException */ + private function throwIfCancelled(): void + { + try { + $this->cancellation->throwIfRequested(); + } catch (CancelledException $exception) { + $this->cancel($exception); + + throw $exception; + } + } +} diff --git a/src/Client/PsrClickHouseAsyncClient.php b/src/Client/PsrClickHouseAsyncClient.php index 4660ca2..121ce93 100644 --- a/src/Client/PsrClickHouseAsyncClient.php +++ b/src/Client/PsrClickHouseAsyncClient.php @@ -5,6 +5,7 @@ namespace SimPod\ClickHouseClient\Client; use Amp\ByteStream\Payload; +use Amp\Cancellation; use Amp\Future; use Amp\Http\Client\HttpClient; use Amp\Http\Client\Psr7\PsrAdapter; @@ -12,6 +13,7 @@ use Error; use Exception; use Psr\Http\Message\RequestInterface; +use SimPod\ClickHouseClient\Client\Http\CancellationStream; use SimPod\ClickHouseClient\Client\Http\RequestFactory; use SimPod\ClickHouseClient\Client\Http\RequestOptions; use SimPod\ClickHouseClient\Client\Http\RequestSettings; @@ -23,6 +25,7 @@ use SimPod\ClickHouseClient\Settings\SettingsProvider; use SimPod\ClickHouseClient\Sql\SqlFactory; use SimPod\ClickHouseClient\Sql\ValueFormatter; +use Throwable; use function Amp\async; use function uniqid; @@ -53,8 +56,9 @@ public function select( string $query, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future { - return $this->selectWithParams($query, [], $outputFormat, $settings); + return $this->selectWithParams($query, [], $outputFormat, $settings, $cancellation); } /** @@ -68,6 +72,7 @@ public function selectWithParams( array $params, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future { $formatClause = $outputFormat::toSql(); @@ -81,6 +86,7 @@ public function selectWithParams( params: $params, settings: $settings, processResponse: static fn (string $body) => $outputFormat::output($body), + cancellation: $cancellation, ); } @@ -96,8 +102,9 @@ public function selectStream( string $query, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future { - return $this->selectStreamWithParams($query, [], $outputFormat, $settings); + return $this->selectStreamWithParams($query, [], $outputFormat, $settings, $cancellation); } /** @@ -114,6 +121,7 @@ public function selectStreamWithParams( array $params, Format $outputFormat, SettingsProvider $settings = new EmptySettingsProvider(), + Cancellation|null $cancellation = null, ): Future { $formatClause = $outputFormat::toSql(); @@ -126,6 +134,7 @@ public function selectStreamWithParams( CLICKHOUSE, params: $params, settings: $settings, + cancellation: $cancellation, ); } @@ -145,6 +154,7 @@ private function executeRequest( array $params, SettingsProvider $settings, callable $processResponse, + Cancellation|null $cancellation, ): Future { $request = $this->requestFactory->prepareSqlRequest( $sql, @@ -158,13 +168,22 @@ private function executeRequest( ); /** @var Future $future */ - $future = async(function () use ($processResponse, $request, $sql): mixed { + $future = async(function () use ($processResponse, $request, $sql, $cancellation): mixed { $id = uniqid('', true); $this->sqlLogger?->startQuery($id, $sql); try { - $response = $this->client->request($this->toAmpRequest($request)); - $body = $response->getBody()->buffer(); + $cancellation?->throwIfRequested(); + $response = $this->client->request($this->toAmpRequest($request), $cancellation); + $payload = $response->getBody(); + + try { + $cancellation?->throwIfRequested(); + $body = $payload->buffer($cancellation); + $cancellation?->throwIfRequested(); + } finally { + $payload->close(); + } if ( $response->getStatus() !== 200 @@ -193,8 +212,12 @@ private function executeRequest( * @throws Error * @throws Exception */ - private function executeStreamRequest(string $sql, array $params, SettingsProvider $settings): Future - { + private function executeStreamRequest( + string $sql, + array $params, + SettingsProvider $settings, + Cancellation|null $cancellation, + ): Future { $request = $this->requestFactory->prepareSqlRequest( $sql, new RequestSettings( @@ -207,21 +230,33 @@ private function executeStreamRequest(string $sql, array $params, SettingsProvid ); /** @var Future $future */ - $future = async(function () use ($request, $sql): Payload { + $future = async(function () use ($request, $sql, $cancellation): Payload { $id = uniqid('', true); $this->sqlLogger?->startQuery($id, $sql); try { - $response = $this->client->request($this->toAmpRequest($request)); + $cancellation?->throwIfRequested(); + $response = $this->client->request($this->toAmpRequest($request), $cancellation); + $body = $response->getBody(); - if ($response->getStatus() !== 200) { - throw ServerError::fromResponseContent( - $response->getBody()->buffer(), - $response->getStatus(), - ); - } + try { + $cancellation?->throwIfRequested(); + + if ($response->getStatus() !== 200) { + $content = $body->buffer($cancellation); + $cancellation?->throwIfRequested(); - return $response->getBody(); + throw ServerError::fromResponseContent($content, $response->getStatus()); + } + + return $cancellation === null + ? $body + : new Payload(new CancellationStream($body, $cancellation)); + } catch (Throwable $exception) { + $body->close(); + + throw $exception; + } } finally { $this->sqlLogger?->stopQuery($id); } diff --git a/tests/Client/Http/CancellationStreamTest.php b/tests/Client/Http/CancellationStreamTest.php new file mode 100644 index 0000000..ab3047d --- /dev/null +++ b/tests/Client/Http/CancellationStreamTest.php @@ -0,0 +1,184 @@ +getCancellation(), + )); + + // Do not yield: cancellation must also be checked before queued callbacks have run. + $cancellation->cancel(); + + $this->expectException(CancelledException::class); + + try { + if ($method === 'read') { + $payload->read(); + } else { + $payload->buffer(); + } + } finally { + self::assertTrue($payload->isClosed()); + } + } + + /** @phpstan-return Generator */ + public static function provideBufferedPayloadHonoursOperationCancellation(): Generator + { + yield 'read buffered data' => ['read']; + yield 'buffer buffered data' => ['buffer']; + } + + #[DataProvider('provideReadCancellation')] + public function testReadCancellation(bool $cancelOperation): void + { + /** @var Queue $queue */ + $queue = new Queue(); + $source = new ReadableIterableStream($queue->iterate()); + $operation = new DeferredCancellation(); + $read = new DeferredCancellation(); + $payload = new Payload(new CancellationStream($source, $operation->getCancellation())); + /** @var DeferredFuture $started */ + $started = new DeferredFuture(); + $future = async(static function () use ($started, $payload, $read): string|null { + $started->complete(); + + return $payload->read($read->getCancellation()); + }); + + $started->getFuture()->await(); + ($cancelOperation ? $operation : $read)->cancel(); + + try { + $future->await(); + self::fail('The pending read was not cancelled.'); + } catch (CancelledException) { + self::assertSame($cancelOperation, $source->isClosed()); + } + + if (! $cancelOperation) { + // A read-only token does not replace or cancel the operation token, or close a reusable source. + self::assertFalse($operation->isCancelled()); + $consumed = $queue->pushAsync("next\n"); + self::assertSame("next\n", $payload->read()); + $consumed->await(); + } + + $payload->close(); + } + + /** @phpstan-return Generator */ + public static function provideReadCancellation(): Generator + { + yield 'operation token remains active with an explicit read token' => [true]; + yield 'explicit read token can cancel only its read' => [false]; + } + + public function testCancellationClosesAnIdleSource(): void + { + $source = new ReadableIterableStream(["1\n"]); + $cancellation = new TrackedCancellation(); + $payload = new Payload(new CancellationStream($source, $cancellation)); + $cancellation->cancel(); + + // Run queued cancellation callbacks without reading the payload. + async(static fn () => null)->await(); + + self::assertTrue($source->isClosed()); + self::assertSame(0, $cancellation->countSubscriptions()); + + $this->expectException(CancelledException::class); + $payload->read(); + } + + public function testAbandonedStreamReleasesItsSourceAndSubscription(): void + { + $source = new ReadableIterableStream(["1\n"]); + $cancellation = new TrackedCancellation(); + $stream = new CancellationStream($source, $cancellation); + + unset($stream); + + self::assertTrue($source->isClosed()); + self::assertSame(0, $cancellation->countSubscriptions()); + } + + /** @param 'close'|'eof'|'failure' $ending */ + #[DataProvider('provideStreamLifecycle')] + public function testStreamLifecycle(string $ending): void + { + $source = new ReadableIterableStream((static function () use ($ending): Generator { + yield "1\n"; + + if ($ending === 'failure') { + throw new StreamException('Response body failed.'); + } + })()); + + $cancellation = new TrackedCancellation(); + $stream = new CancellationStream($source, $cancellation); + /** @var DeferredFuture $closed */ + $closed = new DeferredFuture(); + $stream->onClose($closed->complete(...)); + + self::assertTrue($stream->isReadable()); + self::assertSame("1\n", $stream->read()); + self::assertGreaterThan(0, $cancellation->countSubscriptions()); + + if ($ending === 'close') { + $stream->close(); + $stream->close(); + } elseif ($ending === 'eof') { + self::assertNull($stream->read()); + } else { + try { + $stream->read(); + self::fail('The response body failure was not propagated.'); + } catch (StreamException $exception) { + self::assertSame('Response body failed.', $exception->getMessage()); + } + } + + $closed->getFuture()->await(); + self::assertTrue($stream->isClosed()); + self::assertTrue($source->isClosed()); + self::assertSame(0, $cancellation->countSubscriptions()); + $cancellation->cancel(); + self::assertNull($stream->read()); + } + + /** @phpstan-return Generator */ + public static function provideStreamLifecycle(): Generator + { + yield 'explicit close is idempotent' => ['close']; + yield 'EOF without an onClose notification' => ['eof']; + yield 'terminal body failure' => ['failure']; + } +} diff --git a/tests/Client/Http/Fixture/TrackedCancellation.php b/tests/Client/Http/Fixture/TrackedCancellation.php new file mode 100644 index 0000000..a41c7ed --- /dev/null +++ b/tests/Client/Http/Fixture/TrackedCancellation.php @@ -0,0 +1,63 @@ + */ + private array $subscriptions = []; + + private readonly DeferredCancellation $deferred; + + private readonly Cancellation $cancellation; + + public function __construct() + { + $this->deferred = new DeferredCancellation(); + $this->cancellation = $this->deferred->getCancellation(); + } + + public function subscribe(Closure $callback): string + { + $id = $this->cancellation->subscribe($callback); + $this->subscriptions[$id] = true; + + return $id; + } + + public function unsubscribe(string $id): void + { + $this->cancellation->unsubscribe($id); + unset($this->subscriptions[$id]); + } + + public function isRequested(): bool + { + return $this->cancellation->isRequested(); + } + + /** @throws CancelledException */ + public function throwIfRequested(): void + { + $this->cancellation->throwIfRequested(); + } + + public function cancel(): void + { + $this->deferred->cancel(); + } + + public function countSubscriptions(): int + { + return count($this->subscriptions); + } +} diff --git a/tests/Client/PsrClickHouseAsyncClientCancellationTest.php b/tests/Client/PsrClickHouseAsyncClientCancellationTest.php new file mode 100644 index 0000000..aa72fec --- /dev/null +++ b/tests/Client/PsrClickHouseAsyncClientCancellationTest.php @@ -0,0 +1,243 @@ + $started */ + $started = new DeferredFuture(); + /** @var DeferredFuture $pending */ + $pending = new DeferredFuture(); + $delegate = new class ($started, $pending) implements DelegateHttpClient { + /** + * @param DeferredFuture $started + * @param DeferredFuture $pending + */ + public function __construct(private DeferredFuture $started, private DeferredFuture $pending) + { + } + + public function request(Request $request, Cancellation $cancellation): Response + { + $this->started->complete(); + + return $this->pending->getFuture()->await($cancellation); + } + }; + + $client = self::createClient($delegate); + $cancellation = new DeferredCancellation(); + $token = $cancellation->getCancellation(); + $format = new TabSeparated(); + + $future = match ($method) { + 'select' => $client->select('SELECT 1', $format, cancellation: $token), + 'selectWithParams' => $client->selectWithParams('SELECT 1', [], $format, cancellation: $token), + 'selectStream' => $client->selectStream('SELECT 1', $format, cancellation: $token), + 'selectStreamWithParams' => $client->selectStreamWithParams('SELECT 1', [], $format, cancellation: $token), + }; + + $started->getFuture()->await(); + $cancellation->cancel(); + + $this->expectException(CancelledException::class); + $future->await(); + } + + /** @phpstan-return Generator */ + public static function provideRequestCancellation(): Generator + { + yield 'buffered' => ['select']; + yield 'buffered with parameters' => ['selectWithParams']; + yield 'streamed' => ['selectStream']; + yield 'streamed with parameters' => ['selectStreamWithParams']; + } + + public function testAlreadyCancelledRequestIsNotSent(): void + { + $delegate = new class implements DelegateHttpClient { + public int $requests = 0; + + /** @throws InvalidHeaderException */ + public function request(Request $request, Cancellation $cancellation): Response + { + ++$this->requests; + + return new Response('1.1', 200, null, [], "1\n", $request); + } + }; + + $cancellation = new DeferredCancellation(); + $cancellation->cancel(); + + $this->expectException(CancelledException::class); + + try { + self::createClient($delegate)->select( + 'SELECT 1', + new TabSeparated(), + cancellation: $cancellation->getCancellation(), + )->await(); + } finally { + self::assertSame(0, $delegate->requests); + } + } + + #[DataProvider('provideBodyCancellation')] + public function testBodyCancellation(bool $streamedError): void + { + /** @var Queue $queue */ + $queue = new Queue(); + $consumed = $queue->pushAsync("1\n"); + $source = new ReadableIterableStream($queue->iterate()); + $logger = $this->createMock(SqlLogger::class); + $logger->expects(self::once())->method('startQuery'); + $logger->expects(self::once())->method('stopQuery'); + + $client = self::createClient( + self::respondWith($source, $streamedError ? 500 : 200), + $logger, + ); + + $cancellation = new DeferredCancellation(); + $token = $cancellation->getCancellation(); + $future = $streamedError + ? $client->selectStream('SELECT 1', new TabSeparated(), cancellation: $token) + : $client->select('SELECT 1', new TabSeparated(), cancellation: $token); + + // One chunk has been consumed; the operation is now waiting for the unfinished body, not headers. + $consumed->await(); + self::assertFalse($future->isComplete()); + $cancellation->cancel(); + + $this->expectException(CancelledException::class); + + try { + $future->await(); + } finally { + self::assertTrue($source->isClosed()); + } + } + + /** @phpstan-return Generator */ + public static function provideBodyCancellation(): Generator + { + yield 'buffered success response' => [false]; + yield 'streamed error response' => [true]; + } + + public function testReturnedPayloadRemainsCancellable(): void + { + /** @var Queue $queue */ + $queue = new Queue(); + $source = new ReadableIterableStream($queue->iterate()); + $cancellation = new DeferredCancellation(); + $payload = self::createClient(self::respondWith($source))->selectStream( + 'SELECT 1', + new TabSeparated(), + cancellation: $cancellation->getCancellation(), + )->await(); + + /** @var DeferredFuture $started */ + $started = new DeferredFuture(); + $read = async(static function () use ($started, $payload): string|null { + $started->complete(); + + return $payload->read(); + }); + + $started->getFuture()->await(); + $cancellation->cancel(); + + $this->expectException(CancelledException::class); + + try { + $read->await(); + } finally { + self::assertTrue($source->isClosed()); + } + } + + private static function respondWith(ReadableStream|string $body, int $status = 200): DelegateHttpClient + { + return new class ($body, $status) implements DelegateHttpClient { + // Keep the payload alive so its destructor cannot satisfy explicit body-cleanup assertions. + private Response $response; + + public function __construct(private ReadableStream|string $body, private int $status) + { + } + + /** @throws InvalidHeaderException */ + public function request(Request $request, Cancellation $cancellation): Response + { + $this->response = new Response('1.1', $this->status, null, [], $this->body, $request); + + return $this->response; + } + }; + } + + private static function createClient( + DelegateHttpClient $delegate, + SqlLogger|null $logger = null, + ): PsrClickHouseAsyncClient { + $psr17Factory = new Psr17Factory(); + + try { + $requestFactory = new RequestFactory( + new ParamValueConverterRegistry(), + $psr17Factory, + $psr17Factory, + $psr17Factory, + 'https://clickhouse.example', + ); + } catch (InvalidArgumentException) { + absurd(); + } + + return new PsrClickHouseAsyncClient( + new HttpClient($delegate, []), + $requestFactory, + new PsrAdapter($psr17Factory, $psr17Factory), + sqlLogger: $logger, + ); + } +}