Skip to content
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
name: Build lowest version
runs-on: ubuntu-24.04
container:
image: ghcr.io/hypervel/components-ci:php8.4-swoole6.3.0-rc1
image: ghcr.io/hypervel/components-ci:php8.4-swoole-nightly

steps:
- name: Set up Node
Expand All @@ -41,7 +41,7 @@ jobs:
name: Build
runs-on: ubuntu-24.04
container:
image: ghcr.io/hypervel/components-ci:php${{ matrix.php }}-swoole6.3.0-rc1
image: ghcr.io/hypervel/components-ci:php${{ matrix.php }}-swoole-nightly
strategy:
fail-fast: false
max-parallel: 10
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/static.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
name: PHPStan
runs-on: ubuntu-24.04
container:
image: ghcr.io/hypervel/components-ci:php8.4-swoole6.3.0-rc1
image: ghcr.io/hypervel/components-ci:php8.4-swoole-nightly

steps:
- name: Checkout code
Expand All @@ -35,7 +35,7 @@ jobs:
name: PHP-CS-Fixer
runs-on: ubuntu-24.04
container:
image: ghcr.io/hypervel/components-ci:php8.4-swoole6.3.0-rc1
image: ghcr.io/hypervel/components-ci:php8.4-swoole-nightly

steps:
- name: Checkout code
Expand All @@ -54,7 +54,7 @@ jobs:
name: Composer Normalize
runs-on: ubuntu-24.04
container:
image: ghcr.io/hypervel/components-ci:php8.4-swoole6.3.0-rc1
image: ghcr.io/hypervel/components-ci:php8.4-swoole-nightly

steps:
- name: Checkout code
Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ sections of the README and `UPGRADING.md` describe the fork; the rest of
runtime requirements are defined in `composer.json`. Preserve upstream's
source style and formatting, including attribute placement and parameter
commas; avoid unrelated syntax modernization.
- Match this fork's `require.ext-swoole` constraint to the one in the root
`composer.json` of the `hypervel/components` version this branch supports.
- Regenerate `phpstan-baseline.neon` with
`make static-phpstan-update-baseline` whenever an upstream merge conflicts in
it. Investigate new errors before accepting baseline changes.
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ Guzzle client, including clients that SDKs create. This fork adds:
send requests through it, tick, run or close it, or wait on or cancel its
transfers: those calls throw a `LogicException` without changing the handler.
See [Coroutine Ownership](docs/handlers.md#coroutine-ownership).
- **Coroutine cancellation.** Canceling a coroutine interrupts the request it is
waiting on and reports Swoole's `CanceledException` instead of a transfer
error. See [Coroutine Cancellation](docs/handlers.md#coroutine-cancellation).
- **Transfer tracking.** When the promise task queue implements
`ScopedTaskQueueInterface` from
[`hypervel/guzzle-promises`](https://github.com/hypervel/guzzle-promises), the
Expand Down Expand Up @@ -74,7 +77,7 @@ composer require hypervel/guzzle

## Version Guidance

This fork requires PHP 8.4 or newer and the Swoole extension.
This fork requires PHP 8.4 or newer and Swoole 6.3.0 RC2 or a later 6.x release.
[composer.json](composer.json) lists the exact requirements. Each fork version
is the upstream release it is based on plus a fork release number. For example,
`8.2.0.1` is the first fork release based on upstream `8.2.0`.
Expand Down
14 changes: 11 additions & 3 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ fork.

#### PHP Version and Dependencies

This fork requires PHP 8.4 or newer and the Swoole extension. It requires
`hypervel/guzzle-promises`, Hypervel's fork of `guzzlehttp/promises`, in place
of `guzzlehttp/promises`; also read its
This fork requires PHP 8.4 or newer and Swoole 6.3.0 RC2 or a later 6.x release.
It requires `hypervel/guzzle-promises`, Hypervel's fork of
`guzzlehttp/promises`, in place of `guzzlehttp/promises`; also read its
[upgrade guide](https://github.com/hypervel/guzzle-promises/blob/3.1/UPGRADING.md).

#### Multi Handler Ownership
Expand All @@ -33,6 +33,14 @@ its coroutine ends, unless the task queue implements
`GuzzleHttp\Promise\ScopedTaskQueueInterface`, which cancels them. See
[Coroutine Handlers](docs/handlers.md#coroutine-handlers).

#### Coroutine Cancellation

A request interrupted by canceling its coroutine reports
`Swoole\Coroutine\CanceledException` instead of a Guzzle transfer exception,
such as cURL error 42. It is not a `GuzzleException`, so handle it separately
where a canceled request needs handling. See
[Coroutine Cancellation](docs/handlers.md#coroutine-cancellation).

#### Task Queues

Promise callbacks settle promises in the coroutine that drains the task queue,
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"require": {
"php": "^8.4",
"ext-json": "*",
"ext-swoole": "*",
"ext-swoole": "^6.3.0RC2",
"guzzlehttp/psr7": "^3.4",
"hypervel/guzzle-promises": "^3.1",
"psr/http-client": "^1.0",
Expand Down
12 changes: 12 additions & 0 deletions docs/contributing/exception-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ no-response interface, so among PSR-18's request-bound interfaces only
`RequestExceptionInterface` remains once Guzzle holds a response. This is a
deliberate classification, not a claim that the request message was malformed.

## Coroutine cancellation

When canceling the current Swoole coroutine interrupts a wait the handler owns,
or throws into a callback or into a read or write of a stock PSR-7 stream, the
handler reports the `Swoole\Coroutine\CanceledException` itself, never a Guzzle
exception wrapping it. A cancellation is not a transfer failure, and wrapping it
would let retry logic resend a request its caller abandoned. Keep catch blocks
that wrap other failures from catching it. Unwrap only a stock stream's failure,
and only to its immediate cancellation cause: an application exception that
carries a cancellation, or a failure from any other stream, keeps its own
meaning.

## `GuzzleHttp\Exception\InvalidArgumentException`

`final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException`
Expand Down
34 changes: 34 additions & 0 deletions docs/handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,40 @@ one coroutine at a time. Capped clients keep one multi handler so the limits
apply across all their requests. Requests with `stream` enabled use
`StreamHandler`, which rejects them when connection caps are configured.

### Coroutine Cancellation

Canceling a Swoole coroutine interrupts the request it is waiting on. The
built-in handlers then report the `Swoole\Coroutine\CanceledException` instead
of a transfer error, whether or not `Swoole\Coroutine::cancel()` was asked to
throw. This includes a cancellation thrown into a callback such as `on_headers`,
`progress` or `on_trailers`, into a read of the request body or into a write to
the `sink`. An application exception that carries a cancellation keeps its own
meaning, as does a failure from a custom stream implementation. A cancellation
while a stream seeks or rewinds can still be reported as a request or response
exception. An interrupted request delay throws the cancellation.

- `CurlHandler` releases the transfer and reports the cancellation to
`on_stats`. If `curl_exec()` itself throws the cancellation, it leaves the
handler call, so promise-based middleware in the handler stack, such as
retries, never handles it. Global middleware runs outside the handler stack
and receives it as a rejection. Any other cancellation rejects the promise.
Reading a request body smaller than 1 MB happens before the transfer starts,
so a cancellation there is thrown. When the coroutine is canceled without an
exception, a transfer created by a custom `handle_factory` keeps its cURL
error, because the factory's callbacks can abort a transfer with the error
Swoole reports for that cancellation.
- `CurlMultiHandler` throws it from `tick()` and `execute()` and leaves the
pending transfers running. Waiting on a promise instead rejects the promise
with it and removes the promise's transfer; other transfers stay pending. A
transfer whose callback, body read or sink write is canceled rejects with the
cancellation after reporting it to `on_stats`. Like `CurlHandler`, it throws
when reading a request body smaller than 1 MB is interrupted.
- `StreamHandler` reports it to `on_stats` and rejects with it. Reading a
streamed body throws it.

The cancellation does not implement `Psr\Http\Client\ClientExceptionInterface`,
so it also escapes PSR-18 `sendRequest()` unwrapped.

## Transport Sharing

By default, Guzzle does not ask handlers to share low-level transport state.
Expand Down
2 changes: 1 addition & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ parameters:
-
message: '#^Parameter \#1 \$multi_handle of function curl_multi_select expects CurlMultiHandle, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 3
count: 2
path: src/Handler/CurlMultiHandler.php

-
Expand Down
60 changes: 60 additions & 0 deletions src/Handler/CancelableTransportStream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace GuzzleHttp\Handler;

use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\Exception\TimeoutException;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
use Swoole\Coroutine\CanceledException;

/**
* Decorates the stock stream of a blocking response transport so a read that
* canceling the coroutine interrupted throws the cancellation instead of a
* read failure.
*
* @internal
*/
final class CancelableTransportStream implements StreamInterface
{
use NonSerializableTrait;
use StreamDecoratorTrait;

private StreamInterface $stream;

private StreamCancellation $cancellation;

public function __construct(StreamInterface $stream, StreamCancellation $cancellation)
{
$this->stream = $stream;
$this->cancellation = $cancellation;
}

public function __clone()
{
// Detaching a clone must not detach this body's transport.
$this->stream = clone $this->stream;
}

public function read(int $length): string
{
$this->cancellation->begin();

try {
return $this->stream->read($length);
} catch (\RuntimeException $e) {
$cancellation = CoroutineCancellation::fromStreamFailure($e, true);
if ($cancellation !== null) {
throw $cancellation;
}

if ($e->getPrevious() === null && !$e instanceof TimeoutException && $this->cancellation->interrupted()) {
throw new CanceledException('Reading the response body was canceled.', 0, $e);
}

throw $e;
}
}
}
12 changes: 12 additions & 0 deletions src/Handler/Clock.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace GuzzleHttp\Handler;

use Swoole\Coroutine\CanceledException;

/**
* @internal
*/
Expand All @@ -21,11 +23,21 @@ public static function now(): float
return \hrtime(true) / 1e9;
}

/**
* @throws CanceledException when canceling the current coroutine
* interrupts the sleep
*/
public static function sleep(int $microseconds): void
{
while ($microseconds > 0) {
$slice = \min($microseconds, 0xFFFFFFFF);
\swoole_clear_error();
\usleep($slice);

if (CoroutineCancellation::interrupted(\SWOOLE_ERROR_CO_CANCELED)) {
throw new CanceledException('The coroutine was canceled while sleeping.');
}

$microseconds -= $slice;
}
}
Expand Down
66 changes: 66 additions & 0 deletions src/Handler/CoroutineCancellation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace GuzzleHttp\Handler;

use GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
use Swoole\Coroutine\CanceledException;

/**
* Recognizes and reports Swoole coroutine cancellations of transfers.
*
* @internal
*/
final class CoroutineCancellation
{
private function __construct()
{
}

/**
* Returns whether canceling the current coroutine interrupted the native
* wait made since swoole_clear_error() was last called. The answer is only
* exact when no PHP code ran between the wait and this call.
*
* @param int $error Native error the interrupted wait records, such as
* SWOOLE_ERROR_CO_CANCELED
*/
public static function interrupted(int $error): bool
{
return \Swoole\Coroutine::getCid() > 0
&& \Swoole\Coroutine::isCanceled()
&& \swoole_last_error() === $error;
}

/**
* Returns whether a stream is the stock PSR-7 stream, which reports a
* cancellation thrown during its I/O as the cause of its own failure.
*/
public static function isStockStream(StreamInterface $stream): bool
{
$class = \get_class($stream);

return $class === Psr7\Stream::class || $class === Psr7\LazyOpenStream::class;
}

/**
* Returns the cancellation a stream operation failed with: the failure
* itself, or, for a stock stream, the cancellation it reports as the cause.
* Another stream's failure keeps its own meaning, because the application
* may have wrapped a cancellation that belongs to something else.
*/
public static function fromStreamFailure(\Throwable $failure, bool $stockStream): ?CanceledException
{
if ($failure instanceof CanceledException) {
return $failure;
}

$previous = $failure->getPrevious();

return $stockStream && $failure instanceof \RuntimeException && $previous instanceof CanceledException
? $previous
: null;
}
}
Loading