Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ parameters:
- RuntimeException

ignoreErrors:
# JsonEachRow<T> explicitly implements Format<Output\JsonEachRow<T>>; 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\\Output\\JsonEachRow<array<string, mixed>>>, SimPod\\ClickHouseClient\\Format\\JsonEachRow<array<string, mixed>> 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~'

Expand Down
9 changes: 9 additions & 0 deletions src/Client/ClickHouseAsyncClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
/**
Expand All @@ -24,6 +29,7 @@ public function select(
string $query,
Format $outputFormat,
SettingsProvider $settings = new EmptySettingsProvider(),
Cancellation|null $cancellation = null,
): Future;

/**
Expand All @@ -39,6 +45,7 @@ public function selectWithParams(
array $params,
Format $outputFormat,
SettingsProvider $settings = new EmptySettingsProvider(),
Cancellation|null $cancellation = null,
): Future;

/**
Expand All @@ -50,6 +57,7 @@ public function selectStream(
string $query,
Format $outputFormat,
SettingsProvider $settings = new EmptySettingsProvider(),
Cancellation|null $cancellation = null,
): Future;

/**
Expand All @@ -63,5 +71,6 @@ public function selectStreamWithParams(
array $params,
Format $outputFormat,
SettingsProvider $settings = new EmptySettingsProvider(),
Cancellation|null $cancellation = null,
): Future;
}
175 changes: 175 additions & 0 deletions src/Client/Http/CancellationStream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
<?php

declare(strict_types=1);

namespace SimPod\ClickHouseClient\Client\Http;

use Amp\ByteStream\ReadableStream;
use Amp\ByteStream\ReadableStreamIteratorAggregate;
use Amp\ByteStream\StreamException;
use Amp\Cancellation;
use Amp\CancelledException;
use Amp\CompositeCancellation;
use Amp\DeferredFuture;
use Closure;
use IteratorAggregate;
use Throwable;
use WeakReference;

/**
* @internal
*
* @implements IteratorAggregate<int, string>
*/
final class CancellationStream implements ReadableStream, IteratorAggregate
{
use ReadableStreamIteratorAggregate;

private string|null $subscription = null;

private CancelledException|null $exception = null;

private ReadableStream|null $source;

/** @var DeferredFuture<null> */
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();

Check warning on line 74 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ : 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();
$cancellation?->throwIfRequested();

Check warning on line 75 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ 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) {
$chunk = $source->read($readCancellation);
$this->throwIfCancelled();

Check warning on line 77 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ $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();
} 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) {

Check warning on line 82 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "LogicalOr": @@ @@ // Closing a pending source read can produce a stream error or EOF instead of cancellation. $this->throwIfCancelled(); - if (! $exception instanceof CancelledException || $cancellation?->isRequested() !== true) { + if (! $exception instanceof CancelledException && $cancellation?->isRequested() !== true) { $this->close(); }

Check warning on line 82 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "NullSafeMethodCall": @@ @@ // Closing a pending source read can produce a stream error or EOF instead of cancellation. $this->throwIfCancelled(); - if (! $exception instanceof CancelledException || $cancellation?->isRequested() !== true) { + if (! $exception instanceof CancelledException || $cancellation->isRequested() !== true) { $this->close(); }
$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 {

Check warning on line 116 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "UnwrapFinally": @@ @@ $this->cancellation->unsubscribe($this->subscription); $this->subscription = null; } - - try { - $source->close(); - } finally { - $this->onClose->complete(); - } + $source->close(); + $this->onClose->complete(); } public function isClosed(): bool
$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 {

Check warning on line 148 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ $this->cancellation->unsubscribe($subscription); } else { $this->subscription = $subscription; - $this->source->onClose(static function () use ($reference): void { - $reference->get()?->close(); - }); + } }
$reference->get()?->close();

Check warning on line 149 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ } 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;

Check warning on line 157 in src/Client/Http/CancellationStream.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "ReturnRemoval": @@ @@ private function cancel(CancelledException $exception): void { if ($this->source === null) { - return; + } $this->exception = $exception;
}

$this->exception = $exception;
$this->close();
}

/** @throws CancelledException */
private function throwIfCancelled(): void
{
try {
$this->cancellation->throwIfRequested();
} catch (CancelledException $exception) {
$this->cancel($exception);

throw $exception;
}
}
}
Loading
Loading