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
2 changes: 1 addition & 1 deletion docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Release preparation

- Replace `psy/psysh` `dev-main` in the root and `src/tinker` manifests with the first stable release containing PsySH #951–#954. The latest stable release, v0.12.24, predates those changes.
- Replace `psy/psysh` `dev-main` in the root and `src/tinker` manifests with the first stable release containing PsySH #951–#954 and #972. The latest stable release, v0.12.24, predates those changes.

## Authentication

Expand Down
2 changes: 1 addition & 1 deletion src/broadcasting/src/Mercure/ChannelEncrypter.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function encrypt(string $plaintext, string $channel): string

$this->serializer ??= new CompactSerializer;

$jwe = $this->jweBuilder->create()
$jwe = $this->jweBuilder
->withPayload($plaintext)
->withSharedProtectedHeader(['alg' => 'dir', 'enc' => 'A256GCM'])
->addRecipient(new JWK(['kty' => 'oct', 'k' => Base64UrlSafe::encodeUnpadded($this->channelKey($channel))]))
Expand Down
8 changes: 3 additions & 5 deletions src/console/src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Process\PhpExecutableFinder;
use Throwable;

Expand Down Expand Up @@ -80,10 +79,9 @@ public function __construct(
) {
parent::__construct('Hypervel Framework', $version);

if ($dispatcher instanceof EventDispatcher) {
$this->setDispatcher($dispatcher);
$this->setSignalsToDispatchEvent();
}
// Commands trap signals through Swoole. Symfony's default signal events would install
// PCNTL handlers on every run, which Swoole rejects inside coroutines.
$this->setSignalsToDispatchEvent();

$this->setAutoExit(false);
$this->setCatchExceptions(false);
Expand Down
5 changes: 5 additions & 0 deletions src/contracts/src/Engine/Http/V2/ResponseInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public function getStreamId(): int;
*/
public function getStatusCode(): int;

/**
* Get the HTTP/2 error code when the peer resets the stream.
*/
public function getResetCode(): ?int;

/**
* Get the response headers.
*/
Expand Down
1 change: 0 additions & 1 deletion src/docs/grpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -947,6 +947,5 @@ Hypervel's gRPC client and server are tested against an independent grpc-go impl
- Hypervel servers support unary and server-streaming methods. Server-side client streaming and bidirectional streaming are not available because Swoole gives the request handler the complete body instead of exposing each incoming HTTP/2 data frame. Hypervel clients may use all four call types against compatible servers.
- Swoole cannot reset an individual client stream. Calling `cancel` abandons the stream locally, reports `CANCELLED`, and retires the connection instead of sending `RST_STREAM`. Deadlines are still enforced.
- Swoole may reduce independently repeated metadata fields to one value and does not expose the inbound `:scheme` pseudo-header. Hypervel preserves repeated values whenever the transport exposes them, but inbound duplicate-field and metadata-size validation can only cover the values Swoole provides.
- When a server resets a stream, only the affected client call fails. Swoole's HTTP/2 client does not expose the reset error code.
- Swoole merges initial response metadata immediately followed by final metadata without a response message into one uncommitted response. Since this cannot be distinguished from a Trailers-Only response, an explicitly retry-enabled call may retry it.
- The built-in health service returns `Unimplemented` from `Watch` because it does not publish health changes across workers.
4 changes: 3 additions & 1 deletion src/docs/porting-from-laravel.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ Laravel's `DeferrableProvider` interface is not useful in Hypervel's long-runnin

Coroutine safety is the most important part of a Laravel-to-Hypervel port. In Hypervel, multiple requests or jobs may run concurrently inside the same worker process. Any mutable state on a singleton, static property, manager, or service provider can be observed by another coroutine if it is not isolated correctly.

Process-wide PCNTL calls such as `pcntl_signal()`, `pcntl_sigprocmask()`, and `pcntl_alarm()` conflict with Swoole's coroutine runtime. Use [command signal traps](/docs/{{version}}/artisan#signal-handling) in Artisan commands and set timeouts on the operations a job waits for.

<a name="request-specific-state"></a>
### Request-Specific State

Expand Down Expand Up @@ -957,7 +959,7 @@ When dispatching batched jobs to a queue such as Redis or SQS inside a transacti

Custom queue drivers whose job classes implement `Hypervel\Contracts\Queue\Job` directly must also implement `Hypervel\Contracts\Queue\JobLifecycleCallbacks` to run jobs that use `CountCrashesAsExceptions`; extending `Hypervel\Queue\Jobs\Job` provides it. See [counting worker crashes](/docs/{{version}}/queues#counting-worker-crashes) for the callback requirements.

Timeouts unwind yielding job code with `Swoole\Coroutine\CanceledException`, starting its `catch` and `finally` blocks. Use `finally` for cleanup and rethrow cancellation from broad `catch (Exception)` or `catch (Throwable)` handlers. The worker gives canceled code a bounded wait; if the job is still unwinding when that wait ends, it terminates without waiting for cleanup or running the job's failure handling. `Worker::$killOnTimeout = false` instead waits for the job to unwind while other jobs continue. Failure callbacks receive `TimeoutExceededException`. See [worker timeouts](/docs/{{version}}/queues#worker-timeouts) for recovery behavior and limits.
Timeouts unwind yielding job code with `Swoole\Coroutine\CanceledException`, starting its `catch` and `finally` blocks. Use `finally` for cleanup and rethrow cancellation from broad `catch (Exception)` or `catch (Throwable)` handlers. The worker gives canceled code a bounded wait; if the job is still unwinding when that wait ends, it terminates without waiting for cleanup or running the job's failure handling. `Worker::$killOnTimeout = false` instead waits for the job to unwind while other jobs continue. Failure callbacks receive `TimeoutExceededException`. Laravel can interrupt a PHP loop with a process alarm. In Hypervel, a job that never yields blocks timeout checks for the entire worker. See [worker timeouts](/docs/{{version}}/queues#worker-timeouts).

If you extend Horizon's `RedisQueue`, do not rely on `push()` calling your `pushRaw()` override. Override the protected `preparePayloadForPush()` method to prepare normal pushes, or `handlePayloadPushed()` to run code after Redis accepts the job. Direct calls to `pushRaw()` remain supported.

Expand Down
10 changes: 5 additions & 5 deletions src/docs/queues.md
Original file line number Diff line number Diff line change
Expand Up @@ -2072,7 +2072,7 @@ php artisan queue:work --timeout=30

If the job exceeds its maximum attempts by continually timing out, it will be marked as failed.

Hypervel checks for timed out jobs using a coroutine timer. With PCNTL enabled, the worker can also recover when PHP code blocks that timer. See [worker timeouts](#worker-timeouts) for cancellation and recovery behavior. You may configure how often the worker checks running jobs using the `--monitor-interval` option:
Hypervel checks for timed out jobs using a coroutine timer. See [worker timeouts](#worker-timeouts) for cancellation and recovery behavior. You may configure how often the worker checks running jobs using the `--monitor-interval` option:

```shell
php artisan queue:work --monitor-interval=1
Expand All @@ -2098,7 +2098,7 @@ class ProcessPodcast implements ShouldQueue
Sometimes, IO blocking processes such as sockets or outgoing HTTP connections may not respect your specified timeout. Therefore, when using these features, you should always attempt to specify a timeout using their APIs as well. For example, when using [Guzzle](https://docs.guzzlephp.org), you should always specify a connection and request timeout value.

> [!WARNING]
> A job's "timeout" value should always be less than its ["retry after"](#job-expiration) value, allowing time for detection and cleanup. Otherwise, the job may be re-attempted before it has actually finished executing or timed out. The `--timeout` option has no effect when the `queue:work` command is invoked with the `--once` option. The [PCNTL](https://www.php.net/manual/en/book.pcntl.php) PHP extension enables graceful process signals and timeout recovery when PHP code blocks the event loop.
> A job's "timeout" value should always be less than its ["retry after"](#job-expiration) value, allowing time for detection and cleanup. Otherwise, the job may be re-attempted before it has actually finished executing or timed out. The `--timeout` option has no effect when the `queue:work` command is invoked with the `--once` option.

<a name="failing-on-timeout"></a>
#### Failing on Timeout
Expand Down Expand Up @@ -3186,7 +3186,7 @@ By default, a timeout stops the worker process, including its other running jobs

Use `finally` for cleanup and rethrow cancellation if caught. `CanceledException` extends `Exception`, so a broad `catch (Exception)` also catches it. If job code catches cancellation and completes, releases, or fails the attempt during cleanup, the worker preserves that outcome. If the coroutine remains active after the wait, the worker terminates without running failure handling concurrently with it. A remaining reservation becomes available again normally, but `FailOnTimeout`, ordinary exception counting, and failure callbacks cannot run on that path.

When PHP code blocks the event loop, the PCNTL alarm suspends the blocking coroutine so the timeout monitor can run failure handling before terminating the worker. Recovery, including the job's `failed` method, has `max(1, monitorInterval) + 1` seconds to finish (two seconds by default). A second alarm terminates the process when that deadline expires, even if recovery blocks again. Native calls that block signal handling cannot be interrupted this way. Other jobs interrupted by process termination recover through their queue reservations.
A job that blocks the event loop also blocks timeout checks and every other job in that worker. While blocked, the worker cannot act on stop signals, `--max-time`, `--max-jobs`, or `queue:restart`. If a job never yields or finishes, the worker needs an external restart. Deployments that need automatic recovery should use a health check that detects a lack of progress.

To cancel only the timed-out job and keep the worker running, set the following property during application boot:

Expand All @@ -3196,7 +3196,7 @@ use Hypervel\Queue\Worker;
Worker::$killOnTimeout = false;
```

In this mode, the job also receives `Swoole\Coroutine\CanceledException`. Once its code unwinds, the worker handles the timeout using the job's normal retry, backoff, and failure settings, including `FailOnTimeout`, and reports a `Hypervel\Queue\TimeoutExceededException`. Other jobs continue running. Once job execution finishes, the worker's failure handling and completion listeners finish without further timeout cancellation. A job that swallows cancellation and continues running keeps its concurrency slot. This mode does not use the PCNTL recovery alarm: cancellation requires the job to yield, so CPU-bound code cannot be interrupted by the coroutine timer.
In this mode, the job also receives `Swoole\Coroutine\CanceledException`. Once its code unwinds, the worker handles the timeout using the job's normal retry, backoff, and failure settings, including `FailOnTimeout`, and reports a `Hypervel\Queue\TimeoutExceededException`. Other jobs continue running. Once job execution finishes, the worker's failure handling and completion listeners finish without further timeout cancellation. A job that swallows cancellation and continues running keeps its concurrency slot.

> [!WARNING]
> Keep `--timeout` comfortably shorter than `retry_after`, with room for the monitor interval, cancellation, and failure cleanup. A timeout is not a guarantee that cleanup or process termination finishes before the reservation expires. Jobs may be delivered again after a worker stops, so make jobs safe to retry and set timeouts on external calls as well.
Expand Down Expand Up @@ -4242,7 +4242,7 @@ When an interrupting signal is delivered to running jobs, Hypervel dispatches a

Queue workers also dispatch a `WorkerStopping` event before they stop. You may register a listener using `Queue::stopping` in the `boot` method of a service provider. Its `connectionName` and `queue` properties identify the worker, while `terminatesImmediately` is `true` when the process will be terminated as soon as the listeners return. In that case, listeners should not start cleanup that must finish after the listener returns.

When a job times out, the worker normally ends its own process with `SIGKILL`, so a process supervisor sees the signal rather than an exit status. If you need to control how the worker terminates, you may register a callback using `Hypervel\Queue\Worker::killUsing` in a service provider's `boot` method. The callback receives the worker's exit status after the `WorkerStopping` event is dispatched. If the callback returns, the worker is terminated as usual. Exceptions from stopping listeners or the callback are reported and do not prevent termination. During [blocked-loop recovery](#worker-timeouts), emergency termination can occur before stopping listeners or the callback finish.
When a job times out, the worker normally ends its own process with `SIGKILL`, so a process supervisor sees the signal. When the worker is the main process in a container (PID 1), it exits with the worker's exit status instead. If you need to control how the worker terminates, you may register a callback using `Hypervel\Queue\Worker::killUsing` in a service provider's `boot` method. The callback receives the worker's exit status after the `WorkerStopping` event is dispatched. If the callback returns, the worker is terminated as usual. Exceptions from stopping listeners or the callback are reported and do not prevent termination.

<a name="credits"></a>
## Credits
Expand Down
2 changes: 2 additions & 0 deletions src/docs/redis.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,8 @@ Redis::listenForFailures(function (CommandFailed $event): void {

Listening for a failure does not suppress the command's exception. You may also use `Redis::listen` to register a callback that receives a `Hypervel\Redis\Events\CommandExecuted` event after each successful command.

If you cancel a coroutine without asking Swoole to throw an exception, a Redis command waiting for a reply may throw its original `RedisException`. In that case, failure listeners receive the exception as well.

<a name="holding-a-pooled-connection"></a>
#### Holding a Pooled Connection

Expand Down
1 change: 1 addition & 0 deletions src/engine/src/Http/V2/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ private function transformResponse(SwResponse $response): ResponseInterface
$response->headers ?? [],
$response->data,
$response->pipeline,
$response->statusCode === SWOOLE_HTTP_CLIENT_ESTATUS_SERVER_RESET ? $response->errCode : null,
);
}

Expand Down
9 changes: 9 additions & 0 deletions src/engine/src/Http/V2/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public function __construct(
protected array $headers,
protected ?string $body,
protected bool $pipeline,
protected ?int $resetCode = null,
) {
}

Expand All @@ -36,6 +37,14 @@ public function getStatusCode(): int
return $this->statusCode;
}

/**
* Get the HTTP/2 error code when the peer resets the stream.
*/
public function getResetCode(): ?int
{
return $this->resetCode;
}

/**
* Get the response headers.
*/
Expand Down
1 change: 1 addition & 0 deletions src/foundation/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"require": {
"php": "^8.4",
"ext-filter": "*",
"ext-pcntl": "*",
"ext-posix": "*",
"composer-runtime-api": "^2.2",
"brick/math": "^1.0",
Expand Down
1 change: 0 additions & 1 deletion src/foundation/src/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,6 @@ public function getArtisan(): ApplicationContract

if ($this->symfonyDispatcher instanceof EventDispatcher) {
$artisan->setDispatcher($this->symfonyDispatcher);
$artisan->setSignalsToDispatchEvent();
}

$this->setArtisan($artisan);
Expand Down
57 changes: 41 additions & 16 deletions src/foundation/src/Testing/Concerns/RunTestsInCoroutine.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Hypervel\Foundation\Testing\Concerns;

use Closure;
use Hypervel\Context\CoroutineContext;
use Hypervel\Coordinator\Constants;
use Hypervel\Coordinator\CoordinatorManager;
Expand Down Expand Up @@ -69,11 +70,13 @@ protected function invokeTestMethod(string $methodName, array $testArguments): m
}
};

run(function () use (&$testResult, &$exception, &$timeoutException, &$rootCompleted, $capture, $methodName, $testArguments): void {
$this->runWithTestTimeLimit($timeoutException, function (?float $deadline) use (&$testResult, &$exception, &$timeoutException, &$rootCompleted, $capture, $methodName, $testArguments): void {
$shouldBootFramework = false;

try {
$this->enforceCoroutineTestTimeLimit($timeoutException, $rootCompleted);
if ($deadline !== null) {
$this->enforceCoroutineTestTimeLimit($deadline, $timeoutException, $rootCompleted);
}
$this->clearNonCoroutineTransactionContext();

if ($this->copyNonCoroutineContext) {
Expand Down Expand Up @@ -127,24 +130,50 @@ protected function invokeTestMethod(string $methodName, array $testArguments): m
}

/**
* Enforce PHPUnit's deadline while the test or its children are suspended.
* Run the test while preserving PHPUnit's native deadline for non-yielding code.
*
* @param Closure(?float): void $test
*/
protected function enforceCoroutineTestTimeLimit(?TimeoutException &$timeoutException, bool &$rootCompleted): void
private function runWithTestTimeLimit(?TimeoutException &$timeoutException, Closure $test): void
{
if (! function_exists('pcntl_alarm')) {
$handler = pcntl_signal_get_handler(SIGALRM);
$remaining = is_callable($handler) ? pcntl_alarm(0) : 0;
if ($remaining === 0) {
run(static fn () => $test(null));
return;
}

// Keep the native alarm armed so non-yielding tests are still interrupted.
$remaining = pcntl_alarm(0);
pcntl_alarm($remaining);
$deadline = hrtime(true) / 1e9 + $remaining;
// Swoole owns signal registration while the runtime is active. A late native
// alarm must not interrupt cleanup after the coroutine watchdog has fired.
pcntl_signal(SIGALRM, static function (int $signal, ?array $info) use ($handler, &$timeoutException): void {
if ($timeoutException === null) {
// @phpstan-ignore arguments.count (PCNTL passes the signal number and siginfo to the installed handler)
$handler($signal, $info);
}
});

if ($remaining === 0) {
return;
try {
pcntl_alarm($remaining);
run(static fn () => $test($deadline));
} finally {
try {
if ($timeoutException !== null) {
pcntl_alarm(0);
pcntl_signal_dispatch();
}
} finally {
pcntl_signal(SIGALRM, $handler);
}
}
}

/**
* Enforce PHPUnit's deadline while the test or its children are suspended.
*/
protected function enforceCoroutineTestTimeLimit(float $deadline, ?TimeoutException &$timeoutException, bool &$rootCompleted): void
{
$root = Coroutine::getCid();
$deadline = hrtime(true) / 1e9 + $remaining;
// Buffer the exit signal so cleanup cannot block after the deadline has expired.
$completed = new Channel(1);
// Register first so the signal follows all other root cleanup defers.
Expand Down Expand Up @@ -184,11 +213,7 @@ protected function enforceCoroutineTestTimeLimit(?TimeoutException &$timeoutExce
}
}

// Cancel the native alarm while protected so it cannot fire during cleanup.
pcntl_alarm(0);
pcntl_signal_dispatch();

throw new TimeoutException('The coroutine test exceeded its time limit.');
throw $timeoutException = new TimeoutException('The coroutine test exceeded its time limit.');
} catch (TimeoutException $exception) {
$timeoutException = $exception;

Expand Down
Loading
Loading