diff --git a/composer.json b/composer.json index 69f0928b20..42373aeb4e 100644 --- a/composer.json +++ b/composer.json @@ -59,7 +59,7 @@ "google/protobuf": "^5.35", "guzzlehttp/psr7": "^3.1", "guzzlehttp/uri-template": "^1.0 || ^2.0", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "laravel/agent-detector": "^2.0.5", "laravel/serializable-closure": "^2.0.11", diff --git a/docs/todo.md b/docs/todo.md index 9705b7fe11..1508d2002d 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -21,6 +21,8 @@ ## Framework-wide +- Remove native Windows runtime support across all Hypervel packages, including standalone packages that do not depend on Swoole. Remove code paths and test expectations used only when running on native Windows, and direct Windows developers to WSL 2 in the platform docs. Preserve public Laravel-compatible helpers and signatures. Keep handling Windows-originated input wherever it is valid on a supported host. + - Audit the entire codebase for behavior missing from its contracts, designing them as complete greenfield framework interfaces rather than copying Laravel's omissions. Add methods every conforming implementation must provide, based on real consumers and implementation semantics; keep internal helpers and implementation- or driver-specific capabilities off general contracts. Update implementations, tests and public-contract documentation together. - In a separate PR, make factory-created dates immutable by contract, removing the application-wide mutable opt-out from `Date` / `DateFactory`, `now()` and `today()`. Audit custom classes, factories, callbacks and consumers; preserve useful timezone, locale and test-clock customization and immutable subclasses. Keep explicit mutable conversion at third-party boundaries. Update runtime enforcement, return types, tests and docs together, then tighten `hypervel/phpstan` typing and discarded-date diagnostics wherever immutability is guaranteed; retain accurate handling of external mutable dates. Review the Laravel API departures before implementation. @@ -92,6 +94,8 @@ Remove older ways of doing things once a modern equivalent fully replaces them, ## Testing +- Remove Pest integration from Artisan’s test runners and generators, Testbench, and the user documentation. Update the affected tests to cover PHPUnit behavior. + - Finish switching the regular and nightly database jobs to Unix sockets, matching [laravel/framework#62323](https://github.com/laravel/framework/pull/62323). Swoole 6.3.0 RC2 fixes cold `caching_sha2_password` authentication over Unix sockets, and the MySQL 9.7 job and `UnixSocketAuthenticationTest` already run on a socket. Convert the remaining MySQL 8.4, MySQL Innovation and PostgreSQL 18 jobs. Keep the dedicated schema TLS check on TCP, and keep TCP coverage of MySQL Innovation's native dump path. - Investigate a method attribute such as `#[ResetAfterTest]` to replace the manual static-reset list in `AfterEachTestSubscriber`. Discover methods once per test process and reuse the list after each test, covering classes loaded later without eagerly loading optional packages. Preserve required cleanup ordering, avoid duplicate inherited calls, and keep special lifecycle cleanup explicit. Reuse existing test-state registration where appropriate; avoid per-test scanning or a complex discovery system. diff --git a/src/ai/composer.json b/src/ai/composer.json index 32912722d5..16b6c31b1b 100644 --- a/src/ai/composer.json +++ b/src/ai/composer.json @@ -44,7 +44,7 @@ "hypervel/events": "^0.4", "hypervel/filesystem": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/http": "^0.4", "hypervel/json-schema": "^0.4", diff --git a/src/api-client/composer.json b/src/api-client/composer.json index 6e03550bad..3631dabca1 100644 --- a/src/api-client/composer.json +++ b/src/api-client/composer.json @@ -31,7 +31,7 @@ "hypervel/conditionable": "^0.4", "hypervel/container": "^0.4", "hypervel/contracts": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/http": "^0.4", "hypervel/pipeline": "^0.4", diff --git a/src/broadcasting/composer.json b/src/broadcasting/composer.json index 5d9822529b..47045f6769 100644 --- a/src/broadcasting/composer.json +++ b/src/broadcasting/composer.json @@ -34,7 +34,7 @@ "hypervel/contracts": "^0.4", "hypervel/database": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/http": "^0.4", "hypervel/object-pool": "^0.4", diff --git a/src/bus/src/Batch.php b/src/bus/src/Batch.php index 9aa10ad6bf..15955afcce 100644 --- a/src/bus/src/Batch.php +++ b/src/bus/src/Batch.php @@ -11,10 +11,12 @@ use Hypervel\Container\Container; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Queue\Factory as QueueFactory; +use Hypervel\Contracts\Queue\Job; use Hypervel\Contracts\Support\Arrayable; use Hypervel\Coroutine\Coroutine; use Hypervel\Database\ConnectionResolverInterface; use Hypervel\Queue\CallQueuedClosure; +use Hypervel\Queue\InteractsWithQueue; use Hypervel\Support\Arr; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Collection; @@ -22,9 +24,17 @@ use JsonSerializable; use LogicException; use Throwable; +use WeakMap; class Batch implements Arrayable, JsonSerializable { + /** + * The batch job IDs of commands being processed that cannot reach their queued job. + * + * @var null|WeakMap + */ + protected static ?WeakMap $commandJobIds = null; + /** * Create a new batch instance. */ @@ -159,6 +169,51 @@ public function progress(): int return $this->totalJobs > 0 ? (int) round(($this->processedJobs() / $this->totalJobs) * 100) : 0; } + /** + * Get the ID the batch records for the given queued job. + * + * Horizon gives each retry a new UUID, so a retried batch job carries its original ID in the payload. + * + * @internal + */ + public static function jobIdFor(Job $job): ?string + { + return $job->payload()['batchJobId'] ?? $job->uuid(); + } + + /** + * Get the ID the batch records for the given command while it is processed. + * + * @internal + */ + public static function jobIdForCommand(object $command): ?string + { + if (isset(static::$commandJobIds[$command])) { + return static::$commandJobIds[$command]; + } + + // Only InteractsWithQueue makes $job the queued job; another job property belongs to the application. + return isset(class_uses_recursive($command)[InteractsWithQueue::class]) && $command->job instanceof Job + ? static::jobIdFor($command->job) + : null; + } + + /** + * Remember the batch job ID of a command that cannot reach its queued job. + * + * Commands without InteractsWithQueue have no queued job, and the IDs are held weakly so they never travel + * with the command or outlive it. + * + * @internal + */ + public static function rememberJobIdForCommand(object $command, Job $job): void + { + if (($jobId = static::jobIdFor($job)) !== null) { + static::$commandJobIds ??= new WeakMap; + static::$commandJobIds[$command] = $jobId; + } + } + /** * Record that a job within the batch finished successfully, executing any callbacks if necessary. */ @@ -204,6 +259,8 @@ public function recordSuccessfulJob(string $jobId): void $this->invokeCallbacks('then'); } + $this->markAsFinishedIfOnlyFailuresRemain($counts); + if ($counts->allJobsHaveRanExactlyOnce() && $this->hasFinallyCallbacks()) { $this->invokeCallbacks('finally'); } @@ -314,6 +371,8 @@ public function recordFailedJob(string $jobId, ?Throwable $e): void $this->invokeCallbacks('catch', $e); } + $this->markAsFinishedIfOnlyFailuresRemain($counts); + if ($counts->allJobsHaveRanExactlyOnce() && $this->hasFinallyCallbacks()) { $this->invokeCallbacks('finally'); } @@ -327,6 +386,21 @@ public function incrementFailedJobs(string $jobId): ?UpdatedBatchJobCounts return $this->repository->incrementFailedJobs($this->id, $jobId); } + /** + * Mark a batch that allows failures as finished once every remaining job has failed. + */ + protected function markAsFinishedIfOnlyFailuresRemain(UpdatedBatchJobCounts $counts): void + { + // Repositories that report completedFirstPass already finished the batch in their locked update. + if ($counts->completedFirstPass !== null) { + return; + } + + if ($this->allowsFailures() && $counts->pendingJobs > 0 && $counts->allJobsHaveRanExactlyOnce()) { + $this->repository->markAsFinished($this->id); + } + } + /** * Determine if this is the first job processed in the batch. */ diff --git a/src/bus/src/Batchable.php b/src/bus/src/Batchable.php index 395e948fc3..08675e7fc7 100644 --- a/src/bus/src/Batchable.php +++ b/src/bus/src/Batchable.php @@ -46,7 +46,13 @@ public function batching(): bool { $batch = $this->batch(); - return $batch && ! $batch->finished() && ! $batch->cancelled(); + if (! $batch || $batch->cancelled()) { + return false; + } + + // Unlike Laravel, a failed job retried after its batch finished still belongs to the batch, so it does its work. + return ! $batch->finished() + || in_array(Batch::jobIdForCommand($this), $batch->failedJobIds, true); } /** diff --git a/src/bus/src/DatabaseBatchRepository.php b/src/bus/src/DatabaseBatchRepository.php index 4518630460..3259997889 100644 --- a/src/bus/src/DatabaseBatchRepository.php +++ b/src/bus/src/DatabaseBatchRepository.php @@ -106,17 +106,29 @@ public function incrementTotalJobs(string $batchId, int $amount): void */ public function decrementPendingJobs(string $batchId, string $jobId): ?UpdatedBatchJobCounts { - $values = $this->updateAtomicValues($batchId, function ($batch) use ($jobId) { + $completedFirstPass = false; + + $values = $this->updateAtomicValues($batchId, function ($batch) use ($jobId, &$completedFirstPass) { + $failedJobIds = (array) json_decode($batch->failed_job_ids, true); + $remainingFailedJobIds = array_values(array_diff($failedJobIds, [$jobId])); + $pendingJobs = $batch->pending_jobs - 1; + + $completedFirstPass = $this->completesFirstPass( + $batch->pending_jobs - count($failedJobIds), + $pendingJobs - count($remainingFailedJobIds), + ); + return [ - 'pending_jobs' => $batch->pending_jobs - 1, + 'pending_jobs' => $pendingJobs, 'failed_jobs' => $batch->failed_jobs, - 'failed_job_ids' => json_encode(array_values(array_diff((array) json_decode($batch->failed_job_ids, true), [$jobId]))), - ]; + 'failed_job_ids' => json_encode($remainingFailedJobIds), + ] + $this->finishWhenOnlyFailuresRemain($batch, $pendingJobs, $completedFirstPass); }); return $values === null ? null : new UpdatedBatchJobCounts( $values['pending_jobs'], - $values['failed_jobs'] + $values['failed_jobs'], + $completedFirstPass, ); } @@ -125,20 +137,62 @@ public function decrementPendingJobs(string $batchId, string $jobId): ?UpdatedBa */ public function incrementFailedJobs(string $batchId, string $jobId): ?UpdatedBatchJobCounts { - $values = $this->updateAtomicValues($batchId, function ($batch) use ($jobId) { + $completedFirstPass = false; + + $values = $this->updateAtomicValues($batchId, function ($batch) use ($jobId, &$completedFirstPass) { + $failedJobIds = (array) json_decode($batch->failed_job_ids, true); + $updatedFailedJobIds = array_values(array_unique(array_merge($failedJobIds, [$jobId]))); + + $completedFirstPass = $this->completesFirstPass( + $batch->pending_jobs - count($failedJobIds), + $batch->pending_jobs - count($updatedFailedJobIds), + ); + return [ 'pending_jobs' => $batch->pending_jobs, 'failed_jobs' => $batch->failed_jobs + 1, - 'failed_job_ids' => json_encode(array_values(array_unique(array_merge((array) json_decode($batch->failed_job_ids, true), [$jobId])))), - ]; + 'failed_job_ids' => json_encode($updatedFailedJobIds), + ] + $this->finishWhenOnlyFailuresRemain($batch, $batch->pending_jobs, $completedFirstPass); }); return $values === null ? null : new UpdatedBatchJobCounts( $values['pending_jobs'], - $values['failed_jobs'] + $values['failed_jobs'], + $completedFirstPass, ); } + /** + * Determine if an update ran the batch's last job that had not yet run. + * + * Failed jobs stay pending until they succeed, so the jobs that have not yet run are the pending + * jobs minus the distinct failed jobs. A job that fails again on retry is only counted once. + */ + protected function completesFirstPass(int $notYetRunBefore, int $notYetRunAfter): bool + { + return $notYetRunBefore > 0 && $notYetRunAfter <= 0; + } + + /** + * Get the finish time to store when only failed jobs remain in a batch that allows failures. + * + * Unlike Laravel, the batch is finished in the same locked update instead of after the job's callbacks, so a job + * added to the batch at the same moment reopens it instead of being stranded in a finished batch. An existing + * finish time, such as a cancellation's, is kept. + * + * @return array{finished_at?: int} + */ + protected function finishWhenOnlyFailuresRemain(object $batch, int $pendingJobs, bool $completedFirstPass): array + { + if (! $completedFirstPass || $pendingJobs <= 0 || $batch->finished_at !== null) { + return []; + } + + return ($this->unserialize($batch->options)['allowFailures'] ?? false) === true + ? ['finished_at' => time()] + : []; + } + /** * Update an atomic value within the batch. */ diff --git a/src/bus/src/UpdatedBatchJobCounts.php b/src/bus/src/UpdatedBatchJobCounts.php index 23fe60c39f..4042e45911 100644 --- a/src/bus/src/UpdatedBatchJobCounts.php +++ b/src/bus/src/UpdatedBatchJobCounts.php @@ -8,10 +8,13 @@ class UpdatedBatchJobCounts { /** * Create a new batch job counts object. + * + * @param null|bool $completedFirstPass Whether the update ran the batch's last job that had not yet run, or null when the repository does not report it. A repository that reports it also marks a batch that allows failures as finished in that same update. */ public function __construct( public int $pendingJobs = 0, public int $failedJobs = 0, + public ?bool $completedFirstPass = null, ) { } @@ -20,6 +23,6 @@ public function __construct( */ public function allJobsHaveRanExactlyOnce(): bool { - return ($this->pendingJobs - $this->failedJobs) === 0; + return $this->completedFirstPass ?? ($this->pendingJobs - $this->failedJobs) === 0; } } diff --git a/src/cache/src/Repository.php b/src/cache/src/Repository.php index 3de9ec527d..3d75a1bf94 100644 --- a/src/cache/src/Repository.php +++ b/src/cache/src/Repository.php @@ -1165,7 +1165,8 @@ protected function handleManyResult(array $keys, string $key, mixed $value): mix // genuine miss (null) and cached-null (sentinel) both resolve to the // per-key default, matching get()'s convention. if (is_null($value) || $value === NullSentinel::VALUE) { - return (isset($keys[$key]) && ! array_is_list($keys)) ? value($keys[$key]) : null; + // PHP stores canonical integer strings as integer keys, which are requested keys rather than defaults. + return isset($keys[$key]) && (string) (int) $key !== $key ? value($keys[$key]) : null; } return $value; diff --git a/src/console/composer.json b/src/console/composer.json index eea3389629..bbfb023e65 100644 --- a/src/console/composer.json +++ b/src/console/composer.json @@ -41,7 +41,7 @@ "hypervel/coroutine": "^0.4", "hypervel/engine": "^0.4", "hypervel/filesystem": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/log": "^0.4", "hypervel/macroable": "^0.4", "hypervel/prompts": "^0.4", diff --git a/src/console/src/GeneratorCommand.php b/src/console/src/GeneratorCommand.php index c45fdf9c25..ea55a895cb 100644 --- a/src/console/src/GeneratorCommand.php +++ b/src/console/src/GeneratorCommand.php @@ -16,6 +16,9 @@ use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Finder\Finder; +use Symfony\Component\Process\Process; + +use function Hypervel\Support\php_binary; abstract class GeneratorCommand extends Command implements PromptsForMissingInput { @@ -183,10 +186,9 @@ public function handle(): bool|int // First we need to ensure that the given name is not a reserved word within the PHP // language and that the class name will actually be valid. If it is not valid we // can error now and prevent from polluting the filesystem using invalid files. + // Unlike Laravel, this fails so the command exits with an error and generates no companion files. if ($this->isReservedName($this->getNameInput())) { - $this->components->error('The name "' . $this->getNameInput() . '" is reserved by PHP.'); - - return false; + $this->fail('The name "' . $this->getNameInput() . '" is reserved by PHP.'); } $name = $this->qualifyClass($this->getNameInput()); @@ -207,9 +209,13 @@ public function handle(): bool|int // Next, we will generate the path to the location where this class' file should get // written. Then, we will build the class and make the proper replacements on the // stub files so that it gets the correctly formatted namespace and class name. + $contents = $this->sortImports($this->buildClass($name)); + + $this->ensureGeneratedCodeCompiles($path, $contents); + $this->makeDirectory($path); - $this->replaceFile($path, $this->sortImports($this->buildClass($name))); + $this->replaceFile($path, $contents); $info = $this->type; @@ -485,6 +491,26 @@ protected function isReservedName(string $name): bool return array_any($this->reservedNames, fn ($reservedName) => strtolower($reservedName) === $name); } + /** + * Ensure the generated PHP compiles before it is written. + * + * Unlike Laravel, the command fails before writing the file, even with --force, instead of creating one that PHP + * refuses to load, such as a class named like a class it imports. + */ + protected function ensureGeneratedCodeCompiles(string $path, string $contents): void + { + // Blade views are compiled by Blade before PHP reads them. + if (! str_ends_with($path, '.php') || str_ends_with($path, '.blade.php')) { + return; + } + + $process = new Process([php_binary(), '-d', 'display_errors=stderr', '-d', 'log_errors=0', '-l'], input: $contents); + + if ($process->run() !== 0) { + $this->fail(sprintf('The generated file [%s] is not valid PHP. %s', $path, trim($process->getErrorOutput()))); + } + } + /** * Get the first view directory path from the application configuration. */ diff --git a/src/database/src/Connection.php b/src/database/src/Connection.php index b5eb73ff61..db2b509564 100755 --- a/src/database/src/Connection.php +++ b/src/database/src/Connection.php @@ -1426,6 +1426,25 @@ public function forgetRecordModificationState(): void $this->recordsModified = false; } + /** + * Execute the given callback without affecting the connection's read / write stickiness. + * + * @template TReturn + * + * @param Closure($this): TReturn $callback + * @return TReturn + */ + public function withoutAffectingStickiness(Closure $callback): mixed + { + $recordsModified = $this->recordsModified; + + try { + return $callback($this); + } finally { + $this->recordsModified = $recordsModified; + } + } + /** * Indicate that the connection should use the write connection for reads. * diff --git a/src/database/src/Eloquent/Builder.php b/src/database/src/Eloquent/Builder.php index 75d6c5b9e7..88425ac4af 100644 --- a/src/database/src/Eloquent/Builder.php +++ b/src/database/src/Eloquent/Builder.php @@ -27,6 +27,7 @@ use Hypervel\Pagination\Paginator; use Hypervel\Support\Arr; use Hypervel\Support\Collection as BaseCollection; +use Hypervel\Support\Enumerable; use Hypervel\Support\LazyCollection; use Hypervel\Support\Str; use Hypervel\Support\Traits\ForwardsCalls; @@ -288,6 +289,8 @@ public function whereKey(mixed $id, string $boolean = 'and', bool $not = false): } if (is_array($id) || $id instanceof Arrayable) { + $id = $this->normalizeFindIds($id); + if (in_array($this->model->getKeyType(), ['int', 'integer'], true)) { $this->query->whereIntegerInRaw($this->model->getQualifiedKeyName(), $id, $boolean, $not); } else { @@ -596,7 +599,12 @@ public function findSole(mixed $id, array|string $columns = ['*']): Model */ public function findMany(Arrayable|array $ids, array|string $columns = ['*']): Collection { - $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; + // Keep a collection's models so whereKey() queries their keys rather than their attributes. + $ids = match (true) { + $ids instanceof Enumerable => $ids->all(), + $ids instanceof Arrayable => $ids->toArray(), + default => $ids, + }; if (empty($ids)) { return $this->model->newCollection(); @@ -616,15 +624,16 @@ public function findOrFail(mixed $id, array|string $columns = ['*']): Model|Coll { if ($id instanceof Model) { $id = $id->getKey(); + } elseif ($id instanceof LazyCollection) { + // find() and the comparison below both read the IDs, which a lazy source may only produce once. + $id = $id->eager(); } $result = $this->find($id, $columns); - $id = $id instanceof Arrayable ? $id->toArray() : $id; + $id = $this->normalizeFindIds($id); if (is_array($id)) { - $id = array_map(enum_value(...), $id); - if (count($result) !== count(array_unique($id))) { throw (new ModelNotFoundException)->setModel( get_class($this->model), @@ -684,15 +693,16 @@ public function findOr(mixed $id, Closure|array|string $columns = ['*'], ?Closur if ($id instanceof Model) { $id = $id->getKey(); + } elseif ($id instanceof LazyCollection) { + // find() and the comparison below both read the IDs, which a lazy source may only produce once. + $id = $id->eager(); } $result = $this->find($id, $columns); - $id = $id instanceof Arrayable ? $id->toArray() : $id; + $id = $this->normalizeFindIds($id); if (is_array($id)) { - $id = array_map(enum_value(...), $id); - if (count($result) === count(array_unique($id))) { return $result; } @@ -703,6 +713,29 @@ public function findOr(mixed $id, Closure|array|string $columns = ['*'], ?Closur return $callback(); } + /** + * Normalize the given identifiers into a comparable list of keys. + * + * Enumerable keeps the models of any collection, including a lazy one, instead of converting them to attribute arrays. + */ + protected function normalizeFindIds(mixed $id): mixed + { + $id = match (true) { + $id instanceof Enumerable => $id->all(), + $id instanceof Arrayable => $id->toArray(), + default => $id, + }; + + if (! is_array($id)) { + return $id; + } + + return array_map( + fn (mixed $id): mixed => $id instanceof Model ? $id->getKey() : enum_value($id), + $id + ); + } + /** * Get the first record matching the attributes or instantiate it. * diff --git a/src/database/src/Eloquent/Relations/BelongsTo.php b/src/database/src/Eloquent/Relations/BelongsTo.php index 63fd619f9c..20f3e095bd 100644 --- a/src/database/src/Eloquent/Relations/BelongsTo.php +++ b/src/database/src/Eloquent/Relations/BelongsTo.php @@ -252,15 +252,6 @@ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder ); } - /** - * Determine if the related model has an auto-incrementing ID. - */ - protected function relationHasIncrementingId(): bool - { - return $this->related->getIncrementing() - && in_array($this->related->getKeyType(), ['int', 'integer']); - } - /** * Make a new related instance for the given model. * diff --git a/src/database/src/Eloquent/Relations/BelongsToMany.php b/src/database/src/Eloquent/Relations/BelongsToMany.php index def94db61c..1e9283d59c 100644 --- a/src/database/src/Eloquent/Relations/BelongsToMany.php +++ b/src/database/src/Eloquent/Relations/BelongsToMany.php @@ -25,7 +25,6 @@ use Hypervel\Pagination\LengthAwarePaginator; use Hypervel\Support\Arr; use Hypervel\Support\Collection as BaseCollection; -use Hypervel\Support\Enumerable; use Hypervel\Support\LazyCollection; use Hypervel\Support\StrCache; use InvalidArgumentException; @@ -915,25 +914,6 @@ public function findOr(mixed $id, Closure|array|string $columns = ['*'], ?Closur return $callback(); } - /** - * Normalize primary keys for related-model lookups. - */ - protected function parseFindIds(mixed $ids): mixed - { - if ($ids instanceof Model) { - return $ids->getKey(); - } - - if ($ids instanceof Arrayable) { - // Preserve model objects instead of converting their attributes into candidate IDs. - $ids = $ids instanceof Enumerable ? $ids->all() : $ids->toArray(); - } - - return is_array($ids) - ? array_map(fn (mixed $id): mixed => $id instanceof Model ? $id->getKey() : $id, $ids) - : $ids; - } - /** * Add a basic where clause to the query, and return the first result. * diff --git a/src/database/src/Eloquent/Relations/HasOneOrManyThrough.php b/src/database/src/Eloquent/Relations/HasOneOrManyThrough.php index dce607e309..66fe915056 100644 --- a/src/database/src/Eloquent/Relations/HasOneOrManyThrough.php +++ b/src/database/src/Eloquent/Relations/HasOneOrManyThrough.php @@ -452,7 +452,7 @@ public function findSole(mixed $id, array $columns = ['*']): Model */ public function findMany(Arrayable|array $ids, array $columns = ['*']): EloquentCollection { - $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; + $ids = $this->parseFindIds($ids); if (empty($ids)) { return $this->getRelated()->newCollection(); @@ -475,11 +475,14 @@ public function findOrFail(mixed $id, array $columns = ['*']): EloquentCollectio { if ($id instanceof Model) { $id = $id->getKey(); + } elseif ($id instanceof LazyCollection) { + // find() and the comparison below both read the IDs, which a lazy source may only produce once. + $id = $id->eager(); } $result = $this->find($id, $columns); - $id = $id instanceof Arrayable ? $id->toArray() : $id; + $id = $this->parseFindIds($id); if (is_array($id)) { $id = array_map(enum_value(...), $id); @@ -519,11 +522,14 @@ public function findOr(mixed $id, Closure|array|string $columns = ['*'], ?Closur if ($id instanceof Model) { $id = $id->getKey(); + } elseif ($id instanceof LazyCollection) { + // find() and the comparison below both read the IDs, which a lazy source may only produce once. + $id = $id->eager(); } $result = $this->find($id, $columns); - $id = $id instanceof Arrayable ? $id->toArray() : $id; + $id = $this->parseFindIds($id); if (is_array($id)) { $id = array_map(enum_value(...), $id); diff --git a/src/database/src/Eloquent/Relations/Relation.php b/src/database/src/Eloquent/Relations/Relation.php index 06f61bc7f4..5042017822 100644 --- a/src/database/src/Eloquent/Relations/Relation.php +++ b/src/database/src/Eloquent/Relations/Relation.php @@ -7,6 +7,7 @@ use Closure; use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Database\Eloquent\Builder as BuilderContract; +use Hypervel\Contracts\Support\Arrayable; use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Collection as EloquentCollection; use Hypervel\Database\Eloquent\Model; @@ -17,6 +18,7 @@ use Hypervel\Database\Query\Expression; use Hypervel\Support\Attributes\BootOnly; use Hypervel\Support\Collection as BaseCollection; +use Hypervel\Support\Enumerable; use Hypervel\Support\Traits\ForwardsCalls; use Hypervel\Support\Traits\Macroable; @@ -386,6 +388,25 @@ protected function getKeys(array $models, ?string $key = null): array })->values()->unique(null, true)->sort()->all(); } + /** + * Normalize primary keys for related-model lookups. + */ + protected function parseFindIds(mixed $ids): mixed + { + if ($ids instanceof Model) { + return $ids->getKey(); + } + + if ($ids instanceof Arrayable) { + // Preserve model objects instead of converting their attributes into candidate IDs. + $ids = $ids instanceof Enumerable ? $ids->all() : $ids->toArray(); + } + + return is_array($ids) + ? array_map(fn (mixed $id): mixed => $id instanceof Model ? $id->getKey() : $id, $ids) + : $ids; + } + /** * Get the query builder that will contain the relationship constraints. * diff --git a/src/database/src/Query/Builder.php b/src/database/src/Query/Builder.php index e6327c2d45..2c6a926ea6 100644 --- a/src/database/src/Query/Builder.php +++ b/src/database/src/Query/Builder.php @@ -572,7 +572,8 @@ public function distinct(): static public function from(Closure|self|EloquentBuilder|Relation|ExpressionContract|string $table, ?string $as = null): static { if ($this->isQueryable($table)) { - return $this->fromSub($table, $as); + // Laravel uses an empty alias here, which PostgreSQL rejects; every supported database accepts a name. + return $this->fromSub($table, $as ?? 'hypervel_table'); } if ($table instanceof ExpressionContract && $as !== null && $as !== '') { diff --git a/src/docs/blade.md b/src/docs/blade.md index a0032d07b5..ad6f622ce2 100644 --- a/src/docs/blade.md +++ b/src/docs/blade.md @@ -989,44 +989,6 @@ You may execute this method from your component template by invoking the variabl ``` - -#### Accessing Attributes and Slots Within Component Classes - -Blade components also allow you to access the component name, attributes, and slot inside the class's render method. However, in order to access this data, you should return a closure from your component's `render` method: - -```php -use Closure; - -/** - * Get the view / contents that represent the component. - */ -public function render(): Closure -{ - return function () { - return '
Components content
'; - }; -} -``` - -The closure returned by your component's `render` method may also receive a `$data` array as its only argument. This array will contain several elements that provide information about the component: - -```php -return function (array $data) { - // $data['componentName']; - // $data['attributes']; - // $data['slot']; - - return '
Components content
'; -}; -``` - -> [!WARNING] -> The elements in the `$data` array should never be directly embedded into the Blade string returned by your `render` method, as doing so could allow remote code execution via malicious attribute content. - -The `componentName` is equal to the name used in the HTML tag after the `x-` prefix. So ``'s `componentName` will be `alert`. The `attributes` element will contain all of the attributes that were present on the HTML tag. The `slot` element is a `Hypervel\View\ComponentSlot` instance with the contents of the component's slot. - -The closure should return a string. If the returned string corresponds to an existing view, that view will be rendered; otherwise, the returned string will be evaluated as an inline Blade view. - #### Additional Dependencies @@ -1395,22 +1357,27 @@ To interact with slot attributes, you may access the `attributes` property of th ### Inline Component Views -For very small components, it may feel cumbersome to manage both the component class and the component's view template. For this reason, you may return the component's markup directly from the `render` method: +For very small components, it may feel cumbersome to manage both the component class and the component's view template. For this reason, you may return the component's markup directly from the `render` method by wrapping it in a `Hypervel\View\RawTemplate` instance: ```php +use Hypervel\View\RawTemplate; + /** * Get the view / contents that represent the component. */ -public function render(): string +public function render(): RawTemplate { - return <<<'blade' + return new RawTemplate(<<<'blade'
{{ $slot }}
- blade; + blade); } ``` +> [!WARNING] +> A `RawTemplate` is compiled and executed as Blade, so injected content could allow remote code execution. Never build the template from untrusted data. Instead, pass the data to the component and display it using Blade's escaped `{{ }}` syntax. + #### Generating Inline View Components @@ -1420,6 +1387,41 @@ To create a component that renders an inline view, you may use the `inline` opti php artisan make:component Alert --inline ``` + +#### Accessing Attributes and Slots in Inline Views + +If you need the component name, attributes, or slot inside the class's `render` method, you may return a closure instead. The closure receives a `$data` array as its only argument: + +```php +use Closure; +use Hypervel\View\RawTemplate; + +/** + * Get the view / contents that represent the component. + */ +public function render(): Closure +{ + return function (array $data) { + // $data['componentName']; + // $data['attributes']; + // $data['slot']; + + if ($data['slot']->isEmpty()) { + return new RawTemplate('
No content provided.
'); + } + + return new RawTemplate('
{{ $slot }}
'); + }; +} +``` + +The `componentName` is equal to the name used in the HTML tag after the `x-` prefix. So ``'s `componentName` will be `alert`. The `attributes` element will contain all of the attributes that were present on the HTML tag. The `slot` element is a `Hypervel\View\ComponentSlot` instance with the contents of the component's slot. + +The closure should return either the name of a view or a `RawTemplate` instance. + +> [!WARNING] +> The elements in the `$data` array should be treated as untrusted, since they contain the attributes and slot content passed to the component. Never embed them into the template returned by your closure, as doing so could allow remote code execution. + ### Dynamic Components @@ -1941,8 +1943,10 @@ return Blade::render( ); ``` +For templates you render repeatedly, leave `deleteCachedView` off. Enabling it makes repeated renders slower because Blade recompiles the template and writes a new file each time, even when only the data changes. + > [!WARNING] -> Keep inline Blade templates stable and pass changing values as view data or slots. Hypervel caches and stores each distinct template string separately for reuse, so continually generating unique Blade source grows worker memory and stored view artifacts. +> The template string passed to the `render` method is compiled and executed as Blade, so injected content could allow remote code execution. Never build the template from untrusted data. Instead, pass the data using the method's second argument and display it using Blade's escaped `{{ }}` syntax. Keeping the template stable also matters for performance: by default, Hypervel caches and stores each distinct template string separately for reuse, so continually generating unique Blade source grows worker memory and stored view artifacts. ## Rendering Blade Fragments diff --git a/src/docs/database.md b/src/docs/database.md index fb2e7a5750..e62b6bf6d2 100644 --- a/src/docs/database.md +++ b/src/docs/database.md @@ -251,6 +251,16 @@ The `sticky` option is an *optional* value that can be used to allow the immedia A long-running queue worker gives each job its own coroutine, so one job's writes do not send later jobs' reads to the write connection. +If you need to perform write operations without triggering stickiness for subsequent reads (for example, updating job progress or recording audit timestamps), you may execute the operations within the `withoutAffectingStickiness` method. Afterward, reads keep the routing they had before the callback, so a connection that was already sticky stays sticky: + +```php +use Hypervel\Support\Facades\DB; + +DB::withoutAffectingStickiness(function () use ($jobId) { + DB::table('jobs')->where('id', $jobId)->update(['started_at' => now()]); +}); +``` + #### Preventing Stale Database Reads @@ -454,7 +464,7 @@ $client->getHandlerList()->prependInit( Active queries, transactions, open cursors and `Schema::withoutForeignKeyConstraints` callbacks retain their sessions automatically. This includes transactions started directly through PDO or SQL, on either the read or write connection. In particular, an HTTP call inside `DB::transaction()` keeps the transaction's connection. Completed `chunk` or `lazy` query batches may release between batches. -When a connection's writes may reach different servers, because its write side lists several hosts or records, a connection that has modified records keeps its session until the execution ends. Sticky and write-routed reads then reach the server that took its writes. Calling `forgetRecordModificationState()` on the connection gives this up, along with sticky routing for those writes. +When a connection's writes may reach different servers, because its write side lists several hosts or records, a connection that has modified records keeps its session until the execution ends. Sticky and write-routed reads then reach the server that took its writes. Calling `forgetRecordModificationState()` on the connection gives this up, along with sticky routing for those writes. Writes made within `withoutAffectingStickiness` likewise do not keep the session after the callback returns. If your code requires the same physical session across an external call, wrap the entire operation in `DB::withPinnedSession()`. For a named connection, call `withPinnedSession()` on that connection. For example, a PostgreSQL session-level advisory lock must be released on the session that acquired it: diff --git a/src/docs/events.md b/src/docs/events.md index 72305426e0..9fded2448f 100644 --- a/src/docs/events.md +++ b/src/docs/events.md @@ -850,7 +850,9 @@ public function retryUntil(): DateTimeInterface } ``` -If both `retryUntil` and `tries` are defined, Hypervel gives precedence to the `retryUntil` method. +For a fixed window from when the listener is dispatched to the queue, you may use the [RetryFor attribute](/docs/{{version}}/queues#time-based-attempts) instead, such as `#[RetryFor(minutes: 5)]`. + +If both a retry window and `tries` are defined, Hypervel gives precedence to the retry window. #### Specifying Queued Listener Backoff diff --git a/src/docs/queues.md b/src/docs/queues.md index fb651e3928..a3cfa82981 100644 --- a/src/docs/queues.md +++ b/src/docs/queues.md @@ -1921,10 +1921,27 @@ public function retryUntil(): DateTimeInterface } ``` -If both `retryUntil` and `tries` are defined, Hypervel gives precedence to the `retryUntil` method. +When the window is a fixed length of time from when the job is dispatched, you may use the `RetryFor` attribute instead. Its first argument is in seconds, and `minutes` and `hours` may be passed by name. A `retryUntil` method or property takes precedence over the attribute: + +```php + [!NOTE] -> You may also define a `Tries` attribute or `retryUntil` method on your [queued event listeners](/docs/{{version}}/events#queued-event-listeners) and [queued notifications](/docs/{{version}}/notifications#queueing-notifications). +> You may also define a `Tries` or `RetryFor` attribute or a `retryUntil` method on your [queued event listeners](/docs/{{version}}/events#queued-event-listeners), [queued notifications](/docs/{{version}}/notifications#queueing-notifications) and queued mailables. #### Max Exceptions @@ -2319,6 +2336,12 @@ $this->release(10); $this->release(now()->plus(seconds: 10)); ``` +If the job defines a [backoff](#dealing-with-failed-jobs), the `releaseUsingBackoff` method releases it with the delay for the current attempt, just as the worker would after an exception. Once the attempts outnumber the configured delays, the last delay is used. A job without a backoff is released for immediate processing: + +```php +$this->releaseUsingBackoff(); +``` + After releasing a job, return from its handler. If a worker-processed job throws after release, the worker reports the exception but does not fail or release that attempt again. Exceptions thrown after release do not count toward `maxExceptions`. The next delivery checks the job's attempt limit as usual. @@ -2668,7 +2691,7 @@ Route::get('/batch/{batchId}', function (string $batchId) { ### Batch Events -Hypervel dispatches events as a batch moves through its lifecycle. You may listen for `BatchDispatched` after a batch is dispatched, `BatchStarted` when its first job is processed, `BatchFinished` when it is marked as finished, and `BatchCanceled` when it is canceled. Each event exposes the batch through its `$batch` property; `BatchCanceled` also exposes the exception that caused cancellation, when available. +Hypervel dispatches events as a batch moves through its lifecycle. You may listen for `BatchDispatched` after a batch is dispatched, `BatchStarted` when its first job is processed, `BatchFinished` when all of its jobs have completed successfully, and `BatchCanceled` when it is canceled. Each event exposes the batch through its `$batch` property; `BatchCanceled` also exposes the exception that caused cancellation, when available. ### Cancelling Batches @@ -2735,6 +2758,8 @@ $batch = Bus::batch([ })->dispatch(); ``` +A batch that allows failures is marked as finished once each of its jobs has run, even if some of them failed. Its failed jobs may still be retried, and the batch's `then` callbacks will run once every job has completed successfully. + #### Retrying Failed Batch Jobs @@ -2763,7 +2788,7 @@ use Hypervel\Support\Facades\Schedule; Schedule::command('queue:prune-batches --hours=48')->daily(); ``` -Sometimes, your `job_batches` table may accumulate batch records for batches that never completed successfully, such as batches where a job failed and that job was never retried successfully. You may instruct the `queue:prune-batches` command to prune these unfinished batch records using the `unfinished` option: +Sometimes, your `job_batches` table may accumulate batch records for batches that never finished, such as batches whose jobs were cleared from the queue before they could run. Batches that [allow failures](#allowing-failures) finish once every job has run, so they are pruned along with other finished batches. You may instruct the `queue:prune-batches` command to prune these unfinished batch records using the `unfinished` option: ```php use Hypervel\Support\Facades\Schedule; diff --git a/src/docs/validation.md b/src/docs/validation.md index 602b3656dc..35b0280eaa 100644 --- a/src/docs/validation.md +++ b/src/docs/validation.md @@ -2523,6 +2523,17 @@ The field under validation must be lowercase. The field under validation must be an array that is a list. An array is considered a list if its keys consist of consecutive numbers from 0 to `count($array) - 1`. +List rules may also be constructed using the fluent `Rule::list()` rule builder, which provides the `min`, `max`, `between`, and `exactly` methods to limit the number of items in the list: + +```php +use Hypervel\Validation\Rule; + +'tags' => [ + 'required', + Rule::list()->between(1, 5), +], +``` + #### mac_address diff --git a/src/events/src/CallQueuedListener.php b/src/events/src/CallQueuedListener.php index 6f5256034b..245a2b5ccb 100644 --- a/src/events/src/CallQueuedListener.php +++ b/src/events/src/CallQueuedListener.php @@ -58,6 +58,13 @@ class CallQueuedListener implements ShouldQueue */ public DateTimeInterface|int|null $retryUntil = null; + /** + * The retry window in seconds when the deadline comes from the listener's RetryFor attribute. + * + * Unlike Laravel, the window is kept so queue:retry can refresh the deadline. + */ + public ?int $retryFor = null; + /** * The number of seconds the job can run before timing out. */ diff --git a/src/events/src/Dispatcher.php b/src/events/src/Dispatcher.php index 2209fd83fb..187386cd88 100755 --- a/src/events/src/Dispatcher.php +++ b/src/events/src/Dispatcher.php @@ -37,12 +37,14 @@ use Hypervel\Queue\Attributes\FailOnTimeout; use Hypervel\Queue\Attributes\MaxExceptions; use Hypervel\Queue\Attributes\Queue as QueueAttribute; +use Hypervel\Queue\Attributes\RetryFor; use Hypervel\Queue\Attributes\Timeout; use Hypervel\Queue\Attributes\Tries; use Hypervel\Queue\Attributes\UniqueFor; use Hypervel\Support\Arr; use Hypervel\Support\Attributes\BootOnly; use Hypervel\Support\Attributes\BootOrTestsOnly; +use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Collection; use Hypervel\Support\Queue\Concerns\ResolvesQueueRoutes; use Hypervel\Support\Str; @@ -1068,7 +1070,11 @@ protected function propagateListenerOptions(mixed $listener, CallQueuedListener $job->backoff = method_exists($listener, 'backoff') ? $listener->backoff(...$data) : $this->getAttributeValue($listener, Backoff::class, 'backoff'); $job->maxExceptions = $this->getAttributeValue($listener, MaxExceptions::class, 'maxExceptions'); - $job->retryUntil = method_exists($listener, 'retryUntil') ? $listener->retryUntil(...$data) : null; + $job->retryUntil = match (true) { + method_exists($listener, 'retryUntil') => $listener->retryUntil(...$data), + ! is_null($job->retryFor = $this->getAttributeValue($listener, RetryFor::class)) => CarbonImmutable::now()->addSeconds($job->retryFor), + default => null, + }; $job->shouldBeEncrypted = $listener instanceof ShouldBeEncrypted; $job->timeout = $this->getAttributeValue($listener, Timeout::class, 'timeout'); $job->failOnTimeout = $this->getAttributeValue($listener, FailOnTimeout::class, 'failOnTimeout') ?? false; diff --git a/src/foundation/composer.json b/src/foundation/composer.json index f39cf4221f..75204bdc06 100644 --- a/src/foundation/composer.json +++ b/src/foundation/composer.json @@ -51,7 +51,7 @@ "hypervel/engine": "^0.4", "hypervel/events": "^0.4", "hypervel/filesystem": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/http": "^0.4", "hypervel/http-server": "^0.4", "hypervel/log": "^0.4", diff --git a/src/foundation/src/Configuration/ApplicationBuilder.php b/src/foundation/src/Configuration/ApplicationBuilder.php index 78c0626c02..096fc5def6 100644 --- a/src/foundation/src/Configuration/ApplicationBuilder.php +++ b/src/foundation/src/Configuration/ApplicationBuilder.php @@ -320,24 +320,6 @@ public function withCommands(array $commands = []): static return $this; } - /** - * Register additional Artisan route paths. - * - * The route paths register on the shared console kernel for the worker - * lifetime. - * - * @return $this - */ - #[BootOnly] - protected function withCommandRouting(array $paths): static - { - $this->app->afterResolving(ConsoleKernel::class, function ($kernel) use ($paths) { - $this->app->booted(fn () => $kernel->addCommandRoutePaths($paths)); - }); - - return $this; - } - /** * Register the scheduled tasks for the application. * diff --git a/src/foundation/src/Console/ComponentMakeCommand.php b/src/foundation/src/Console/ComponentMakeCommand.php index d7dde9b1f7..7d65a27e60 100644 --- a/src/foundation/src/Console/ComponentMakeCommand.php +++ b/src/foundation/src/Console/ComponentMakeCommand.php @@ -95,7 +95,7 @@ protected function buildClass(string $name): string if ($this->option('inline')) { return str_replace( ['DummyView', '{{ view }}'], - "<<<'blade'\n
\n \n
\nblade", + "<<<'blade'\n
\n {{-- " . Inspiring::quotes()->random() . " --}}\n
\n blade", parent::buildClass($name) ); } @@ -135,7 +135,9 @@ protected function getView(): string */ protected function getStub(): string { - return $this->resolveStubPath('/stubs/view-component.stub'); + return $this->option('inline') + ? $this->resolveStubPath('/stubs/view-component.inline.stub') + : $this->resolveStubPath('/stubs/view-component.stub'); } /** diff --git a/src/foundation/src/Console/ModelMakeCommand.php b/src/foundation/src/Console/ModelMakeCommand.php index 631e593b7b..6da7ba219e 100644 --- a/src/foundation/src/Console/ModelMakeCommand.php +++ b/src/foundation/src/Console/ModelMakeCommand.php @@ -56,10 +56,6 @@ class ModelMakeCommand extends GeneratorCommand public function handle(): bool|int { if (parent::handle() === false && ! $this->option('force')) { - if (! $this->alreadyExists($this->getNameInput())) { - return false; - } - if (! confirm('Do you want to generate additional components for the model?')) { return false; } diff --git a/src/foundation/src/Console/StubPublishCommand.php b/src/foundation/src/Console/StubPublishCommand.php index 84fb5dce17..8a8c164b3c 100644 --- a/src/foundation/src/Console/StubPublishCommand.php +++ b/src/foundation/src/Console/StubPublishCommand.php @@ -65,6 +65,7 @@ public function handle(): void __DIR__ . '/stubs/test.stub' => 'test.stub', __DIR__ . '/stubs/test.unit.stub' => 'test.unit.stub', __DIR__ . '/stubs/trait.stub' => 'trait.stub', + __DIR__ . '/stubs/view-component.inline.stub' => 'view-component.inline.stub', __DIR__ . '/stubs/view-component.stub' => 'view-component.stub', __DIR__ . '/../../../database/src/Console/Factories/stubs/factory.stub' => 'factory.stub', __DIR__ . '/../../../database/src/Console/Seeds/stubs/seeder.stub' => 'seeder.stub', diff --git a/src/foundation/src/Console/stubs/view-component.inline.stub b/src/foundation/src/Console/stubs/view-component.inline.stub new file mode 100644 index 0000000000..34a8751520 --- /dev/null +++ b/src/foundation/src/Console/stubs/view-component.inline.stub @@ -0,0 +1,27 @@ + $data - * @return array - */ - protected function filterViewData(array $data): array - { - return array_filter($data, function ($value, $key) { - if ($key === 'app') { - return ! $value instanceof Application; - } - - return $key !== '__env'; - }, ARRAY_FILTER_USE_BOTH); - } - /** * Detect the line number in the original blade file. */ diff --git a/src/horizon/src/Jobs/RetryFailedJob.php b/src/horizon/src/Jobs/RetryFailedJob.php index 92e456d2b5..52ee1d66ef 100644 --- a/src/horizon/src/Jobs/RetryFailedJob.php +++ b/src/horizon/src/Jobs/RetryFailedJob.php @@ -45,13 +45,20 @@ protected function preparePayload(string $id, string $payload): string { $payload = json_decode($payload, true); - return json_encode(array_merge($payload, [ + $retry = [ 'id' => $id, 'uuid' => $id, 'attempts' => 0, 'retry_of' => $this->id, 'retryUntil' => $this->prepareNewTimeout($payload), - ])); + ]; + + // Horizon tracks each retry by its new UUID, but a batch tracks the job by its original ID. + if (isset($payload['data']['batchId'])) { + $retry['batchJobId'] = $payload['batchJobId'] ?? $payload['uuid']; + } + + return json_encode(array_merge($payload, $retry)); } /** diff --git a/src/http/composer.json b/src/http/composer.json index 8499b97390..03ca8f2a12 100644 --- a/src/http/composer.json +++ b/src/http/composer.json @@ -39,7 +39,7 @@ "hypervel/coroutine": "^0.4", "hypervel/database": "^0.4", "hypervel/engine": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/macroable": "^0.4", "hypervel/object-pool": "^0.4", diff --git a/src/http/src/Client/CurlStreamingBody.php b/src/http/src/Client/CurlStreamingBody.php index d4be73f54f..2fbfa86888 100644 --- a/src/http/src/Client/CurlStreamingBody.php +++ b/src/http/src/Client/CurlStreamingBody.php @@ -262,10 +262,6 @@ protected function advance(): void { $result = curl_multi_exec($this->connection->handle, $running); - if (Coroutine::isCanceled()) { - throw new CanceledException('The streaming request was canceled.'); - } - if ($result !== CURLM_OK) { throw new RuntimeException('Unable to read the streaming response: ' . curl_multi_strerror($result)); } @@ -333,7 +329,7 @@ protected function advance(): void try { $this->completedResponse = CurlFactory::finish($retry, $easy, $this->factory)->wait(); } catch (TransferException $exception) { - // Completion callbacks run after the native cancellation check above. + // Guzzle still wraps a cancellation thrown while rewinding or replaying the request body. // @phpstan-ignore hypervel.cancellation.exactType (restores the direct cancellation Guzzle wrapped; a deeper carrier still propagates) if ($exception->getPrevious() instanceof CanceledException) { throw $exception->getPrevious(); @@ -369,17 +365,15 @@ protected function wait(?float &$idleDeadline, bool $headers = false): void throw new RuntimeException('The streaming response read timed out.'); } + // The hooked select runs no PHP code, so after clearing, a cancellation error can only come from this wait. + swoole_clear_error(); $selected = curl_multi_select($this->connection->handle, min(1.0, $remaining)); - if (Coroutine::isCanceled()) { + if (Coroutine::isCanceled() && swoole_last_error() === SWOOLE_ERROR_CO_CANCELED) { throw new CanceledException('The streaming request was canceled.'); } - if ($selected === -1) { - // libcurl can briefly have no descriptors while scheduling its next action. - // @phpstan-ignore hypervel.rawSleep (libcurl needs real time to schedule its next action) - usleep(1000); - } elseif ($selected > 0 && $this->readTimeout > 0) { + if ($selected > 0 && $this->readTimeout > 0) { $idleDeadline = hrtime(true) / 1e9 + $this->readTimeout; } } diff --git a/src/http/src/Client/CurlStreamingHandler.php b/src/http/src/Client/CurlStreamingHandler.php index b9f3ad25a8..6a9d270f51 100644 --- a/src/http/src/Client/CurlStreamingHandler.php +++ b/src/http/src/Client/CurlStreamingHandler.php @@ -18,11 +18,13 @@ use GuzzleHttp\Psr7\HttpFactory; use GuzzleHttp\TransportSharing; use Hypervel\Coroutine\Coroutine; +use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Support\Sleep; use InvalidArgumentException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use RuntimeException; +use Swoole\Coroutine\CanceledException; use Swoole\Runtime; use Throwable; @@ -97,7 +99,13 @@ public function __invoke(RequestInterface $request, array $options): PromiseInte HostValidator::assertRequestHost($request); if (isset($options['delay'])) { + // An earlier, handled cancellation must not make this delay look canceled. + swoole_clear_error(); Sleep::usleep((int) ($options['delay'] * 1000)); + + if (EngineCoroutine::isCanceled() && swoole_last_error() === SWOOLE_ERROR_CO_CANCELED) { + throw new CanceledException('The streaming request was canceled.'); + } } $timeout = $this->timeout($options['timeout'] ?? 0, 'timeout'); diff --git a/src/mail/src/SendQueuedMailable.php b/src/mail/src/SendQueuedMailable.php index 50e9a36b13..adbcf5ee63 100644 --- a/src/mail/src/SendQueuedMailable.php +++ b/src/mail/src/SendQueuedMailable.php @@ -19,9 +19,11 @@ use Hypervel\Queue\Attributes\MaxExceptions; use Hypervel\Queue\Attributes\Queue as QueueAttribute; use Hypervel\Queue\Attributes\ReadsQueueAttributes; +use Hypervel\Queue\Attributes\RetryFor; use Hypervel\Queue\Attributes\Timeout; use Hypervel\Queue\Attributes\Tries; use Hypervel\Queue\InteractsWithQueue; +use Hypervel\Support\CarbonImmutable; use Throwable; class SendQueuedMailable @@ -128,7 +130,9 @@ public function backoff(): mixed public function retryUntil(): ?DateTimeInterface { if (! method_exists($this->mailable, 'retryUntil') && ! isset($this->mailable->retryUntil)) { - return null; + $retryFor = $this->getAttributeValue($this->mailable, RetryFor::class); + + return is_null($retryFor) ? null : CarbonImmutable::now()->addSeconds($retryFor); } return $this->mailable->retryUntil ?? $this->mailable->retryUntil(); diff --git a/src/notifications/composer.json b/src/notifications/composer.json index cb8d67a9ed..e6087dea7d 100644 --- a/src/notifications/composer.json +++ b/src/notifications/composer.json @@ -36,7 +36,7 @@ "hypervel/context": "^0.4", "hypervel/contracts": "^0.4", "hypervel/database": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/http": "^0.4", "hypervel/macroable": "^0.4", "hypervel/mail": "^0.4", diff --git a/src/notifications/src/SendQueuedNotifications.php b/src/notifications/src/SendQueuedNotifications.php index 816082bc20..b82bd76bf9 100644 --- a/src/notifications/src/SendQueuedNotifications.php +++ b/src/notifications/src/SendQueuedNotifications.php @@ -18,10 +18,12 @@ use Hypervel\Queue\Attributes\FailOnTimeout; use Hypervel\Queue\Attributes\MaxExceptions; use Hypervel\Queue\Attributes\ReadsQueueAttributes; +use Hypervel\Queue\Attributes\RetryFor; use Hypervel\Queue\Attributes\Timeout; use Hypervel\Queue\Attributes\Tries; use Hypervel\Queue\InteractsWithQueue; use Hypervel\Queue\SerializesModels; +use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Collection; use Throwable; @@ -177,7 +179,9 @@ public function backoff(): mixed public function retryUntil(): ?DateTimeInterface { if (! method_exists($this->notification, 'retryUntil') && ! isset($this->notification->retryUntil)) { - return null; + $retryFor = $this->getAttributeValue($this->notification, RetryFor::class); + + return is_null($retryFor) ? null : CarbonImmutable::now()->addSeconds($retryFor); } return $this->notification->retryUntil ?? $this->notification->retryUntil(); diff --git a/src/opentelemetry/composer.json b/src/opentelemetry/composer.json index c16e953f0b..c288b6dcf9 100644 --- a/src/opentelemetry/composer.json +++ b/src/opentelemetry/composer.json @@ -51,7 +51,7 @@ "hypervel/engine": "^0.4", "hypervel/events": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/http": "^0.4", "hypervel/http-server": "^0.4", diff --git a/src/queue/src/Attributes/RetryFor.php b/src/queue/src/Attributes/RetryFor.php new file mode 100644 index 0000000000..dba77b50cc --- /dev/null +++ b/src/queue/src/Attributes/RetryFor.php @@ -0,0 +1,28 @@ +retryFor = $seconds + ($minutes * 60) + ($hours * 3600); + } +} diff --git a/src/queue/src/CallQueuedHandler.php b/src/queue/src/CallQueuedHandler.php index 6b420a003d..31c0da9a84 100644 --- a/src/queue/src/CallQueuedHandler.php +++ b/src/queue/src/CallQueuedHandler.php @@ -6,6 +6,7 @@ use __PHP_Incomplete_Class; use Exception; +use Hypervel\Bus\Batch; use Hypervel\Bus\Batchable; use Hypervel\Bus\BatchRepository; use Hypervel\Bus\DebounceLock; @@ -173,8 +174,12 @@ protected function resolveHandler(Job $job, mixed $command): mixed */ protected function setJobInstanceIfNecessary(Job $job, mixed $instance): mixed { - if (isset(class_uses_recursive($instance)[InteractsWithQueue::class])) { + $uses = class_uses_recursive($instance); + + if (isset($uses[InteractsWithQueue::class])) { $instance->setJob($job); + } elseif (isset($uses[Batchable::class]) && ($instance->batchId ?? '') !== '') { + Batch::rememberJobIdForCommand($instance, $job); } return $instance; @@ -195,14 +200,13 @@ protected function ensureNextJobInChainIsDispatched(mixed $command): void */ protected function ensureSuccessfulBatchJobIsRecorded(mixed $command): void { - $uses = class_uses_recursive($command); - - if (! isset($uses[Batchable::class], $uses[InteractsWithQueue::class])) { + // Unlike Laravel, a batched command without InteractsWithQueue is counted too, so its batch can finish. + if (! isset(class_uses_recursive($command)[Batchable::class])) { return; } - if ($batch = $command->batch()) { - $batch->recordSuccessfulJob($command->job->uuid()); + if (($batch = $command->batch()) && ($jobId = Batch::jobIdForCommand($command)) !== null) { + $batch->recordSuccessfulJob($jobId); } } @@ -461,15 +465,16 @@ protected function ensureSuccessfulBatchJobIsRecordedForMissingModel(Job $job, s } $batchId = $job->payload()['data']['batchId'] ?? null; + $jobId = Batch::jobIdFor($job); if ((! is_string($batchId) || $batchId === '') - || ! is_string($job->uuid()) || $job->uuid() === '' + || ! is_string($jobId) || $jobId === '' ) { return; } if ($batch = $this->container->make(BatchRepository::class)->find($batchId)) { - $batch->recordSuccessfulJob($job->uuid()); + $batch->recordSuccessfulJob($jobId); } } @@ -480,6 +485,8 @@ protected function ensureSuccessfulBatchJobIsRecordedForMissingModel(Job $job, s */ public function failed(array $data, ?Throwable $e, string $uuid, ?Job $job = null): void { + $batchJobId = $job === null ? $uuid : (Batch::jobIdFor($job) ?? $uuid); + try { $command = $this->getCommand($data); } catch (ModelNotFoundException $exception) { @@ -489,7 +496,7 @@ public function failed(array $data, ?Throwable $e, string $uuid, ?Job $job = nul beforeProcessing: $job !== null && CoroutineContext::get(self::MISSING_MODEL_FAILURE_CONTEXT_KEY) === $job, ); - $this->ensureFailedBatchJobIsRecordedForMissingModel($uuid, $data, $e); + $this->ensureFailedBatchJobIsRecordedForMissingModel($batchJobId, $data, $e); throw $exception; } @@ -508,7 +515,7 @@ public function failed(array $data, ?Throwable $e, string $uuid, ?Job $job = nul return; } - $this->ensureFailedBatchJobIsRecorded($uuid, $command, $e); + $this->ensureFailedBatchJobIsRecorded($batchJobId, $command, $e); $this->ensureChainCatchCallbacksAreInvoked($uuid, $command, $e); if (method_exists($command, 'failed')) { diff --git a/src/queue/src/Console/ListenCommand.php b/src/queue/src/Console/ListenCommand.php index ca295cb2d1..82335052e4 100644 --- a/src/queue/src/Console/ListenCommand.php +++ b/src/queue/src/Console/ListenCommand.php @@ -96,7 +96,7 @@ protected function gatherOptions(): ListenerOptions return new ListenerOptions( name: $this->option('name'), environment: $this->option('env'), - backoff: (int) $backoff, + backoff: (string) $backoff, memory: (string) $this->option('memory'), timeout: (int) $this->option('timeout'), sleep: (float) $this->option('sleep'), diff --git a/src/queue/src/Console/RetryCommand.php b/src/queue/src/Console/RetryCommand.php index 6093888c4f..f5f484cbff 100644 --- a/src/queue/src/Console/RetryCommand.php +++ b/src/queue/src/Console/RetryCommand.php @@ -12,13 +12,18 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Queue\Queue; use Hypervel\Database\Eloquent\ModelNotFoundException; +use Hypervel\Events\CallQueuedListener; +use Hypervel\Queue\Attributes\ReadsQueueAttributes; +use Hypervel\Queue\Attributes\RetryFor; use Hypervel\Queue\Events\JobRetryRequested; use Hypervel\Queue\Failed\FailedJobProviderInterface; use Hypervel\Queue\Jobs\JobName; use Hypervel\Queue\QueuePoolProxy; use Hypervel\Queue\SqsQueue; use Hypervel\Support\Enumerable; +use Hypervel\Support\InteractsWithTime; use Hypervel\Support\LazyCollection; +use ReflectionClass; use RuntimeException; use stdClass; use Symfony\Component\Console\Attribute\AsCommand; @@ -26,6 +31,9 @@ #[AsCommand(name: 'queue:retry')] class RetryCommand extends Command { + use InteractsWithTime; + use ReadsQueueAttributes; + /** * The console command signature. */ @@ -204,14 +212,31 @@ protected function refreshRetryUntil(string $payload): string return json_encode($payload, JSON_THROW_ON_ERROR); } - if (is_object($instance) && ! $instance instanceof __PHP_Incomplete_Class && method_exists($instance, 'retryUntil')) { - $retryUntil = $instance->retryUntil(); + if (! is_object($instance) || $instance instanceof __PHP_Incomplete_Class) { + return json_encode($payload, JSON_THROW_ON_ERROR); + } - $payload['retryUntil'] = $retryUntil instanceof DateTimeInterface - ? $retryUntil->getTimestamp() - : $retryUntil; + if (method_exists($instance, 'retryUntil')) { + $retryUntil = $instance->retryUntil(); + } elseif ($instance instanceof CallQueuedListener && method_exists($instance->class, 'retryUntil')) { + // Unlike Laravel, a queued listener's deadline is recalculated too, from its method as dispatch does. + $retryUntil = (new ReflectionClass($instance->class)) + ->newInstanceWithoutConstructor() + ->retryUntil(...array_values($instance->data)); + } elseif ($instance instanceof CallQueuedListener && ! is_null($instance->retryFor)) { + // Dispatch keeps the listener's RetryFor window on the job so it can be refreshed here. + $retryUntil = $this->availableAt($instance->retryFor); + } elseif (! isset($instance->retryUntil) && ! is_null($retryFor = $this->getAttributeValue($instance, RetryFor::class))) { + // Unlike Laravel, a retryUntil property keeps its absolute deadline, as it does at dispatch. + $retryUntil = $this->availableAt($retryFor); + } else { + return json_encode($payload, JSON_THROW_ON_ERROR); } + $payload['retryUntil'] = $retryUntil instanceof DateTimeInterface + ? $retryUntil->getTimestamp() + : $retryUntil; + return json_encode($payload, JSON_THROW_ON_ERROR); } diff --git a/src/queue/src/Console/WorkCommand.php b/src/queue/src/Console/WorkCommand.php index 2e07a45100..e0462bf4cc 100644 --- a/src/queue/src/Console/WorkCommand.php +++ b/src/queue/src/Console/WorkCommand.php @@ -152,9 +152,12 @@ protected function gatherWorkerOptions(): WorkerOptions ? max(1, $this->config->integer('queue.concurrency')) : max(1, (int) $this->option('concurrency')); + $backoff = (string) $this->option('backoff'); + return new WorkerOptions( name: (string) $this->option('name'), - backoff: (int) max($this->option('backoff'), $this->option('delay')), + // A comma-separated schedule has no single delay to compare with the deprecated --delay option. + backoff: str_contains($backoff, ',') ? $backoff : (string) max($backoff, $this->option('delay')), memory: (string) $this->option('memory'), timeout: (int) $this->option('timeout'), sleep: (float) $this->option('sleep'), diff --git a/src/queue/src/InteractsWithQueue.php b/src/queue/src/InteractsWithQueue.php index fc9bdf45c3..e941de7dff 100644 --- a/src/queue/src/InteractsWithQueue.php +++ b/src/queue/src/InteractsWithQueue.php @@ -66,6 +66,28 @@ public function release(DateInterval|DateTimeInterface|int $delay = 0): void } } + /** + * Release the job back into the queue using its backoff for the current attempt. + */ + public function releaseUsingBackoff(): void + { + if (! $this->job) { + return; + } + + $backoff = method_exists($this->job, 'backoff') ? $this->job->backoff() : null; + + if (is_null($backoff)) { + $this->release(); + + return; + } + + $backoff = is_array($backoff) ? $backoff : explode(',', (string) $backoff); + + $this->release((int) ($backoff[$this->attempts() - 1] ?? end($backoff))); + } + /** * Indicate that queue interactions like fail, delete, and release should be faked. * diff --git a/src/queue/src/Listener.php b/src/queue/src/Listener.php index b8c92ed756..86e17b956d 100644 --- a/src/queue/src/Listener.php +++ b/src/queue/src/Listener.php @@ -125,7 +125,7 @@ protected function createCommand(?string $connection, string $queue, ListenerOpt '--once', "--name={$options->name}", "--queue={$queue}", - "--backoff={$options->backoff}", + '--backoff=' . (is_array($options->backoff) ? implode(',', $options->backoff) : $options->backoff), "--memory={$options->memory}", "--sleep={$options->sleep}", "--tries={$options->maxTries}", diff --git a/src/queue/src/ListenerOptions.php b/src/queue/src/ListenerOptions.php index ee0da3dca4..fbae9e0358 100644 --- a/src/queue/src/ListenerOptions.php +++ b/src/queue/src/ListenerOptions.php @@ -14,12 +14,12 @@ class ListenerOptions extends WorkerOptions /** * Create a new listener options instance. * - * @param int|int[] $backoff + * @param int|int[]|string $backoff the seconds to wait before retrying a failed job, or a schedule as a list or comma-separated string */ public function __construct( string $name = 'default', ?string $environment = null, - array|int $backoff = 0, + array|int|string $backoff = 0, float|string $memory = 128, int $timeout = 60, float $sleep = 3, diff --git a/src/queue/src/Queue.php b/src/queue/src/Queue.php index 8af92a2518..a7c94d49cf 100644 --- a/src/queue/src/Queue.php +++ b/src/queue/src/Queue.php @@ -26,6 +26,7 @@ use Hypervel\Queue\Attributes\FailOnTimeout; use Hypervel\Queue\Attributes\MaxExceptions; use Hypervel\Queue\Attributes\ReadsQueueAttributes; +use Hypervel\Queue\Attributes\RetryFor; use Hypervel\Queue\Attributes\Timeout; use Hypervel\Queue\Attributes\Tries; use Hypervel\Queue\Concerns\StagesOutboxJobs; @@ -353,7 +354,9 @@ public function getJobBackoff(mixed $job): mixed public function getJobExpiration(mixed $job): mixed { if (! method_exists($job, 'retryUntil') && ! isset($job->retryUntil)) { - return null; + $retryFor = $this->getAttributeValue($job, RetryFor::class); + + return is_null($retryFor) ? null : $this->availableAt($retryFor); } $expiration = $job->retryUntil ?? $job->retryUntil(); diff --git a/src/queue/src/Worker.php b/src/queue/src/Worker.php index 877c52a35c..4c7752be23 100644 --- a/src/queue/src/Worker.php +++ b/src/queue/src/Worker.php @@ -1664,7 +1664,7 @@ protected function calculateBackoff(JobContract $job, WorkerOptions $options): i ? $job->backoff() : $options->backoff; - $backoff = explode(',', (string) $backoff); + $backoff = is_array($backoff) ? $backoff : explode(',', (string) $backoff); return (int) ($backoff[$job->attempts() - 1] ?? last($backoff)); } diff --git a/src/queue/src/WorkerOptions.php b/src/queue/src/WorkerOptions.php index 3a9d437acd..3c07d3f908 100644 --- a/src/queue/src/WorkerOptions.php +++ b/src/queue/src/WorkerOptions.php @@ -6,11 +6,18 @@ class WorkerOptions { + /** + * The number of seconds to wait before retrying a job that encountered an uncaught exception, or a schedule of them. + * + * @var int|int[] + */ + public array|int $backoff; + /** * Create a new worker options instance. * * @param string $name the name of the worker - * @param int|int[] $backoff + * @param int|int[]|string $backoff the seconds to wait before retrying a failed job, or a schedule as a list or comma-separated string * @param float|string $memory the maximum RAM in megabytes or a percentage of PHP's memory limit * @param int $timeout the maximum number of seconds a child worker may run * @param float $sleep the number of seconds to wait in between polling the queue @@ -27,7 +34,7 @@ class WorkerOptions */ public function __construct( public string $name = 'default', - public array|int $backoff = 0, + array|int|string $backoff = 0, public float|string $memory = 128, public int $timeout = 60, public float $sleep = 3, @@ -42,5 +49,9 @@ public function __construct( public int $monitorInterval = 1, public array $coroutineContext = [], ) { + // Console options arrive as strings, where a comma-separated schedule such as Horizon's becomes a list of delays. + $this->backoff = is_string($backoff) + ? (str_contains($backoff, ',') ? array_map(intval(...), explode(',', $backoff)) : (int) $backoff) + : $backoff; } } diff --git a/src/redis/src/PhpRedisClusterConnection.php b/src/redis/src/PhpRedisClusterConnection.php index da9a066c1b..c7eb807e03 100644 --- a/src/redis/src/PhpRedisClusterConnection.php +++ b/src/redis/src/PhpRedisClusterConnection.php @@ -371,6 +371,7 @@ protected function createRedisCluster(): RedisCluster ); } + swoole_clear_error(); $redis = new RedisCluster(...$parameters); } catch (Throwable $exception) { if ($cancellation = RedisCancellation::cancellationFrom( diff --git a/src/redis/src/PhpRedisConnection.php b/src/redis/src/PhpRedisConnection.php index 23fd219c98..5044bad4aa 100644 --- a/src/redis/src/PhpRedisConnection.php +++ b/src/redis/src/PhpRedisConnection.php @@ -39,6 +39,8 @@ public function __construct(Container $container, ConnectionPool $pool, array $c public function reconnect(): bool { try { + swoole_clear_error(); + $database = ! $this->invalid && $this->connection instanceof Redis && $this->connection->isConnected() diff --git a/src/redis/src/RedisCancellation.php b/src/redis/src/RedisCancellation.php index c45b5eef2b..fe3ebab8b2 100644 --- a/src/redis/src/RedisCancellation.php +++ b/src/redis/src/RedisCancellation.php @@ -20,6 +20,9 @@ class RedisCancellation { /** * Resolve an exact or native phpredis cancellation. + * + * Call swoole_clear_error() immediately before the native operation, so an earlier + * cancellation the coroutine already handled cannot be mistaken for this one. */ public static function cancellationFrom(Throwable $exception, string $message): ?CanceledException { @@ -28,8 +31,10 @@ public static function cancellationFrom(Throwable $exception, string $message): return $exception; } + // phpredis keeps a thrown cancellation as the cause; a non-throwing one leaves only the socket error. if (($exception instanceof RedisException || $exception instanceof RedisClusterException) - && EngineCoroutine::isCanceled() + && (Coroutine::causedByCancellation($exception) + || (EngineCoroutine::isCanceled() && swoole_last_error() === SOCKET_ECANCELED)) ) { return new CanceledException($message, previous: $exception); } diff --git a/src/redis/src/RedisConnection.php b/src/redis/src/RedisConnection.php index 4bf9f7ea30..d62f50a8ea 100644 --- a/src/redis/src/RedisConnection.php +++ b/src/redis/src/RedisConnection.php @@ -361,20 +361,29 @@ public function __construct(Container $container, ConnectionPool $pool, array $c */ public function __call(string $name, array $arguments): mixed { + $command = false; + try { if (static::hasMacro($name)) { return $this->macroCall($name, $arguments); } $name = strtolower($name); + $command = true; + swoole_clear_error(); $result = $this->executeCommand($name, $arguments); } catch (RedisException|RedisClusterException|ErrorException $exception) { + // Classify before invalidation reads the client's state; a macro's failure keeps its own meaning. + $cancellation = $command + ? RedisCancellation::cancellationFrom($exception, "Executing Redis command [{$name}] was canceled.") + : null; + // REMOVED: Laravel's command retry loop can replay writes Redis already committed. - if ($this->shouldInvalidateAfter($exception)) { + if ($cancellation !== null || $this->shouldInvalidateAfter($exception)) { $this->markInvalid(); } - throw $exception; + throw $cancellation ?? $exception; } if ($name === 'watch' && $result !== false) { @@ -662,6 +671,7 @@ protected function parseBackoffAlgorithm(mixed $algorithm): int public function close(): bool { try { + swoole_clear_error(); $this->connection?->close(); } catch (Throwable $exception) { if ($cancellation = RedisCancellation::cancellationFrom( @@ -723,11 +733,8 @@ public function release(): void try { $queueing = $this->isQueueingMode(); } catch (Throwable $exception) { - if ($cancellation = RedisCancellation::cancellationFrom( - $exception, - 'Inspecting Redis connection state during release was canceled.', - )) { - $this->releaseAfterCancellation($cancellation); + if (Coroutine::causedByCancellation($exception)) { + $this->releaseAfterCancellation($exception); } $this->markInvalid(); @@ -789,10 +796,9 @@ public function release(): void } } } catch (Throwable $exception) { - if ($cancellation = RedisCancellation::cancellationFrom( - $exception, - 'Preparing the Redis connection for release was canceled.', - )) { + // Only SELECT waits here, and command dispatch already classified its cancellation. + if (Coroutine::causedByCancellation($exception)) { + $cancellation = $exception; $this->markInvalid(); } else { $this->markInvalid(); @@ -867,7 +873,12 @@ private function releaseAfterCancellation(Throwable $cancellation): never */ public function discardTransaction(): bool|Redis { - $result = $this->connection->discard(); + try { + swoole_clear_error(); + $result = $this->connection->discard(); + } catch (RedisException|RedisClusterException $exception) { + throw RedisCancellation::cancellationFrom($exception, 'Discarding the Redis transaction was canceled.') ?? $exception; + } if ($result !== false) { $this->watching = false; @@ -986,6 +997,8 @@ public static function hasHashTag(string $key): bool protected function pingForHeartbeat(): bool { try { + swoole_clear_error(); + if ($this->connection instanceof Redis) { return $this->connection->ping() !== false; } @@ -1979,6 +1992,8 @@ public function evalWithShaCache(string $script, array $keys = [], array $args = $combinedArgs = [...$keys, ...$args]; try { + swoole_clear_error(); + // Clear any stale error from previous commands to ensure getLastError() // reflects this call, not a previous one $this->connection->clearLastError(); @@ -2010,11 +2025,14 @@ public function evalWithShaCache(string $script, array $keys = [], array $args = return $this->normalizeNullReplies($result); } catch (RedisException|RedisClusterException|ErrorException $exception) { - if ($this->shouldInvalidateAfter($exception)) { + // Classify before invalidation reads the client's state. + $cancellation = RedisCancellation::cancellationFrom($exception, 'Executing the Redis script was canceled.'); + + if ($cancellation !== null || $this->shouldInvalidateAfter($exception)) { $this->markInvalid(); } - throw $exception; + throw $cancellation ?? $exception; } } diff --git a/src/redis/src/RedisProxy.php b/src/redis/src/RedisProxy.php index c71ff7939e..a8ee4a5e94 100644 --- a/src/redis/src/RedisProxy.php +++ b/src/redis/src/RedisProxy.php @@ -224,7 +224,11 @@ private function executeMultiExec(string $command, ?callable $callback = null): $cleanupFailure = null; try { - $result = tap($instance, $callback)->exec(); + // The callback drives the native client, so classify its escaping failures and EXEC's separately. + swoole_clear_error(); + $callback($instance); + swoole_clear_error(); + $result = $instance->exec(); if ($command === 'multi' && $hasExistingConnection) { $connection = CoroutineContext::get($this->getContextKey()); @@ -294,10 +298,8 @@ public function __call(string $name, array $arguments): mixed ? $connection->discardTransaction() : $connection->{$name}(...$arguments); } catch (Throwable $throwable) { - $commandException = RedisCancellation::cancellationFrom( - $throwable, - "Executing Redis command [{$name}] was canceled.", - ) ?? $throwable; + $commandException = $throwable; + if (! Coroutine::causedByCancellation($commandException)) { try { $dispatcher = $connection->getEventDispatcher(); @@ -585,6 +587,8 @@ public function withConnection(callable $callback, bool $transform = true): mixe try { $connection->getConnection(); + // The callback can drive the native client directly, such as a pipeline it executes. + swoole_clear_error(); $result = $callback($connection); } catch (Throwable $exception) { $operationFailure = RedisCancellation::cancellationFrom( @@ -633,6 +637,7 @@ public function withPinnedConnection(callable $callback): mixed try { $connection->getConnection(); + swoole_clear_error(); $result = $callback(); } catch (Throwable $exception) { $operationFailure = RedisCancellation::cancellationFrom( @@ -736,10 +741,8 @@ public function subscriber(): Subscriber $connection->getConnection(); $masters = $connection->masters(); } catch (Throwable $exception) { - $discoveryException = RedisCancellation::cancellationFrom( - $exception, - 'Discovering Redis Cluster masters was canceled.', - ) ?? $exception; + // Master discovery reads the client's cached topology; only reconnecting waits, and it classifies itself. + $discoveryException = $exception; } if ($contextConnection === null) { diff --git a/src/redis/src/RedisSentinelFactory.php b/src/redis/src/RedisSentinelFactory.php index 5479e20abe..33f290c448 100644 --- a/src/redis/src/RedisSentinelFactory.php +++ b/src/redis/src/RedisSentinelFactory.php @@ -57,6 +57,8 @@ public function resolveMaster(array $config): array } try { + swoole_clear_error(); + $options = [ 'host' => $hasScheme ? "{$resolved['scheme']}://{$resolved['host']}" diff --git a/src/saloon/composer.json b/src/saloon/composer.json index 80ed04ca02..0049e69635 100644 --- a/src/saloon/composer.json +++ b/src/saloon/composer.json @@ -50,7 +50,7 @@ "hypervel/events": "^0.4", "hypervel/filesystem": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/http": "^0.4", "hypervel/macroable": "^0.4", "hypervel/prompts": "^0.4", diff --git a/src/scout/composer.json b/src/scout/composer.json index 61a42c1a5c..466db8a4df 100644 --- a/src/scout/composer.json +++ b/src/scout/composer.json @@ -48,7 +48,7 @@ "hypervel/coroutine": "^0.4", "hypervel/database": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/http": "^0.4", "hypervel/macroable": "^0.4", "hypervel/pagination": "^0.4", diff --git a/src/sentry/composer.json b/src/sentry/composer.json index 9bed882d7d..cb29e8429e 100644 --- a/src/sentry/composer.json +++ b/src/sentry/composer.json @@ -48,7 +48,7 @@ "hypervel/di": "^0.4", "hypervel/filesystem": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/http": "^0.4", "hypervel/http-server": "^0.4", diff --git a/src/slack-notification-channel/composer.json b/src/slack-notification-channel/composer.json index 8fa0d11809..03ecaeac10 100644 --- a/src/slack-notification-channel/composer.json +++ b/src/slack-notification-channel/composer.json @@ -30,7 +30,7 @@ "hypervel/collections": "^0.4", "hypervel/conditionable": "^0.4", "hypervel/contracts": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/http": "^0.4", "hypervel/notifications": "^0.4", "hypervel/support": "^0.4", diff --git a/src/socialite/composer.json b/src/socialite/composer.json index 45a3a9c380..1088be2ac7 100644 --- a/src/socialite/composer.json +++ b/src/socialite/composer.json @@ -37,7 +37,7 @@ "hypervel/context": "^0.4", "hypervel/contracts": "^0.4", "hypervel/coroutine": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/http": "^0.4", "hypervel/support": "^0.4", "psr/http-message": "^2.0" diff --git a/src/support/src/Aws/SerializedCredentialProvider.php b/src/support/src/Aws/SerializedCredentialProvider.php index 9c76782005..c7ec971319 100644 --- a/src/support/src/Aws/SerializedCredentialProvider.php +++ b/src/support/src/Aws/SerializedCredentialProvider.php @@ -68,6 +68,9 @@ public function __invoke(mixed ...$arguments): PromiseInterface static::$owners[$this->lockKey] = $coroutine; } + // An earlier, handled cancellation must not make this provider's failure look canceled. + swoole_clear_error(); + try { return Create::promiseFor(($this->provider)(...$arguments)->wait()); } catch (Throwable $exception) { @@ -75,8 +78,10 @@ public function __invoke(mixed ...$arguments): PromiseInterface throw $exception; } - // SDK providers can wrap an interrupted fetch in CredentialsException. - if (EngineCoroutine::isCanceled()) { + // SDK providers can rethrow an interrupted fetch without its cause. + if (EngineCoroutine::isCanceled() + && in_array(swoole_last_error(), [SWOOLE_ERROR_CO_CANCELED, SOCKET_ECANCELED], true) + ) { throw new CanceledException('Resolving AWS credentials was canceled.', previous: $exception); } diff --git a/src/support/src/Facades/DB.php b/src/support/src/Facades/DB.php index 9251901c65..0d2900d6c9 100644 --- a/src/support/src/Facades/DB.php +++ b/src/support/src/Facades/DB.php @@ -128,6 +128,7 @@ * @method static void useDefaultSchemaGrammar() * @method static \Hypervel\Database\Connection useWriteConnectionWhenReading(bool $value = true) * @method static mixed usingWritePdo(\Closure $callback) + * @method static mixed withoutAffectingStickiness(\Closure $callback) * @method static mixed withoutPretending(\Closure $callback) * @method static mixed withoutTablePrefix(\Closure $callback) * @method static mixed withPinnedSession(\Closure $callback) diff --git a/src/support/src/Sleep.php b/src/support/src/Sleep.php index 8979e113ca..59fb47c9e1 100644 --- a/src/support/src/Sleep.php +++ b/src/support/src/Sleep.php @@ -8,6 +8,7 @@ use Closure; use DateInterval; use DateTimeInterface; +use Hypervel\Engine\Coroutine; use Hypervel\Support\Attributes\TestsOnly; use Hypervel\Support\Facades\Date; use Hypervel\Support\Traits\Macroable; @@ -313,14 +314,19 @@ protected function goodnight(): void $microseconds = (int) $this->duration->totalMicroseconds - $seconds * Carbon::MICROSECONDS_PER_SECOND; while ($while()) { - if ($seconds > 0) { - // @phpstan-ignore hypervel.rawSleep (the Sleep implementation itself) - sleep($seconds); + // @phpstan-ignore hypervel.rawSleep (the Sleep implementation itself) + if ($seconds > 0 && sleep($seconds) !== 0 && Coroutine::isCanceled()) { + // Sleeping again would hide the coroutine's cancellation from its caller. + return; } if ($microseconds > 0) { // @phpstan-ignore hypervel.rawSleep (the Sleep implementation itself) usleep($microseconds); + + if (Coroutine::isCanceled()) { + return; + } } } } diff --git a/src/telescope/composer.json b/src/telescope/composer.json index 220b42cc8c..b71e7569e5 100644 --- a/src/telescope/composer.json +++ b/src/telescope/composer.json @@ -42,7 +42,7 @@ "hypervel/events": "^0.4", "hypervel/filesystem": "^0.4", "hypervel/foundation": "^0.4", - "hypervel/guzzle": "^8.3", + "hypervel/guzzle": "^8.5.0.2", "hypervel/guzzle-promises": "^3.1", "hypervel/http": "^0.4", "hypervel/http-server": "^0.4", diff --git a/src/validation/src/Rule.php b/src/validation/src/Rule.php index 8ac0983504..dc955c859a 100644 --- a/src/validation/src/Rule.php +++ b/src/validation/src/Rule.php @@ -37,6 +37,7 @@ use Hypervel\Validation\Rules\InArray; use Hypervel\Validation\Rules\InArrayKeys; use Hypervel\Validation\Rules\IpAddress; +use Hypervel\Validation\Rules\ListRule; use Hypervel\Validation\Rules\MissingIf; use Hypervel\Validation\Rules\MissingUnless; use Hypervel\Validation\Rules\MissingWith; @@ -253,9 +254,9 @@ public static function json(): string /** * Get a list validation rule. */ - public static function list(): string + public static function list(): ListRule { - return 'list'; + return new ListRule; } /** diff --git a/src/validation/src/Rules/ListRule.php b/src/validation/src/Rules/ListRule.php new file mode 100644 index 0000000000..66981a27a3 --- /dev/null +++ b/src/validation/src/Rules/ListRule.php @@ -0,0 +1,90 @@ +addRule('between:' . $min . ',' . $max); + } + + /** + * The field under validation must have exactly the given number of items. + * + * @return $this + */ + public function exactly(int $value): static + { + return $this->addRule('size:' . $value); + } + + /** + * The field under validation must not have more than the given number of items. + * + * @param non-negative-int $value + * @return $this + */ + public function max(int $value): static + { + return $this->addRule('max:' . $value); + } + + /** + * The field under validation must have at least the given number of items. + * + * @return $this + */ + public function min(int $value): static + { + return $this->addRule('min:' . $value); + } + + /** + * Convert the rule to a validation string. + */ + public function __toString(): string + { + return implode('|', $this->toArray()); + } + + /** + * Convert the rule to an array of validation rules. + * + * @return list + */ + public function toArray(): array + { + return array_values(array_unique(['list', ...$this->constraints])); + } + + /** + * Add custom rules to the validation rules array. + * + * @return $this + */ + protected function addRule(array|string $rules): static + { + $this->constraints = array_merge($this->constraints, Arr::wrap($rules)); + + return $this; + } +} diff --git a/src/validation/src/ValidationRuleParser.php b/src/validation/src/ValidationRuleParser.php index bc18b5b43e..27bd8fb26e 100644 --- a/src/validation/src/ValidationRuleParser.php +++ b/src/validation/src/ValidationRuleParser.php @@ -17,6 +17,7 @@ use Hypervel\Validation\Rules\ArrayRule; use Hypervel\Validation\Rules\Date; use Hypervel\Validation\Rules\Exists; +use Hypervel\Validation\Rules\ListRule; use Hypervel\Validation\Rules\Numeric; use Hypervel\Validation\Rules\StringRule; use Hypervel\Validation\Rules\Unique; @@ -89,7 +90,7 @@ protected function explodeExplicitRule(mixed $rule, string $attribute): array } if (is_object($rule)) { - if ($rule instanceof ArrayRule || $rule instanceof Date || $rule instanceof Numeric || $rule instanceof StringRule) { + if ($rule instanceof ArrayRule || $rule instanceof Date || $rule instanceof ListRule || $rule instanceof Numeric || $rule instanceof StringRule) { // Composite rules already separate constraints; literal parameters may contain pipes. return $rule->toArray(); } @@ -100,7 +101,7 @@ protected function explodeExplicitRule(mixed $rule, string $attribute): array $rules = []; foreach ($rule as $value) { - if ($value instanceof ArrayRule || $value instanceof Date || $value instanceof Numeric || $value instanceof StringRule) { + if ($value instanceof ArrayRule || $value instanceof Date || $value instanceof ListRule || $value instanceof Numeric || $value instanceof StringRule) { $rules = array_merge($rules, $value->toArray()); } else { $rules[] = $this->prepareRule($value, $attribute); diff --git a/src/validation/src/Validator.php b/src/validation/src/Validator.php index 45dfa78e0e..30a297bf4a 100644 --- a/src/validation/src/Validator.php +++ b/src/validation/src/Validator.php @@ -1207,6 +1207,7 @@ protected function getExplicitKeys(string $attribute): array */ protected function getPrimaryAttribute(string $attribute): string { + // One reverse map answers in a single lookup; Laravel's per-pattern sets still scan every wildcard. return $this->getImplicitAttributeMap()[$attribute] ?? $attribute; } diff --git a/src/view/src/Compilers/BladeCompiler.php b/src/view/src/Compilers/BladeCompiler.php index c15f275f61..fd303df577 100644 --- a/src/view/src/Compilers/BladeCompiler.php +++ b/src/view/src/Compilers/BladeCompiler.php @@ -9,7 +9,8 @@ use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Support\Htmlable; use Hypervel\Contracts\View\Factory as ViewFactory; -use Hypervel\Contracts\View\View; +use Hypervel\Contracts\View\View as ViewContract; +use Hypervel\Filesystem\Filesystem; use Hypervel\Support\Arr; use Hypervel\Support\Attributes\BootOnly; use Hypervel\Support\Collection; @@ -17,6 +18,9 @@ use Hypervel\Support\Stringable; use Hypervel\Support\Traits\ReflectsClosures; use Hypervel\View\Component; +use Hypervel\View\Engines\CompilerEngine; +use Hypervel\View\Factory; +use Hypervel\View\View; use InvalidArgumentException; use ParseError; @@ -323,6 +327,34 @@ public function compileString(string $value): string */ public static function render(string $string, array $data = [], bool $deleteCachedView = false): string { + $container = Container::getInstance(); + $factory = $container->make(ViewFactory::class); + + // Each deletable render owns its source file, so deleting it cannot break another render of the same + // template. Factory implementations without temporary views keep the named render below. + if ($deleteCachedView && $factory instanceof Factory) { + $hash = hash('xxh128', $string); + $directory = $container->make('config')->string('view.compiled'); + $path = $directory . '/' . $hash . '-' . bin2hex(random_bytes(8)) . '.blade.php'; + $files = $container->make(Filesystem::class); + $view = null; + + $files->ensureDirectoryExists($directory); + + try { + $files->put($path, $string); + $view = $factory->makeFromTemporaryFile('__components::' . $hash, $path, $data); + + return $view->render(); + } finally { + @unlink($path); + + if ($view instanceof View && ($engine = $view->getEngine()) instanceof CompilerEngine) { + @unlink($engine->getCompiler()->getCompiledPath($path)); + } + } + } + $component = new class($string) extends Component { /** * Create a new inline Blade component instance. @@ -352,9 +384,7 @@ public function resolveView(): string } }; - $view = Container::getInstance() - ->make(ViewFactory::class) - ->make($component->resolveView(), $data); + $view = $factory->make($component->resolveView(), $data); return tap($view->render(), function () use ($component, $string, $view, $deleteCachedView) { if ($deleteCachedView) { @@ -375,7 +405,7 @@ public static function renderComponent(Component $component): string $view = value($component->resolveView(), $data); - if ($view instanceof View) { + if ($view instanceof ViewContract) { return $view->with($data)->render(); } if ($view instanceof Htmlable) { diff --git a/src/view/src/Compilers/ComponentTagCompiler.php b/src/view/src/Compilers/ComponentTagCompiler.php index 81111facce..2a36a56eeb 100644 --- a/src/view/src/Compilers/ComponentTagCompiler.php +++ b/src/view/src/Compilers/ComponentTagCompiler.php @@ -252,11 +252,21 @@ protected function componentString(string $component, array $attributes): string $parameters = $data->all(); } + $escapeAttributes = $class !== DynamicComponent::class; + + $bound = $this->getBoundAttributes(); + + $boundAttributes = $escapeAttributes ? '' : 'withBoundAttributes([' . $attributes->keys() + ->filter(fn ($key) => isset($bound[$key])) + ->map(fn ($key) => "'{$key}'") + ->implode(',') . ']); ?> +'; + return "##BEGIN-COMPONENT-CLASS##@component('{$class}', '{$component}', [" . $this->attributesToString($parameters, escapeBound: false) . ']) except(\\' . $class . '::ignoredParameterNames()); ?> -withAttributes([' . $this->attributesToString($attributes->all(), $escapeAttributes = $class !== DynamicComponent::class) . ']); ?>'; +' . $boundAttributes . 'withAttributes([' . $this->attributesToString($attributes->all(), $escapeAttributes) . ']); ?>'; } /** diff --git a/src/view/src/Component.php b/src/view/src/Component.php index fc00a4d3e1..061642814c 100644 --- a/src/view/src/Component.php +++ b/src/view/src/Component.php @@ -78,10 +78,17 @@ abstract class Component */ protected static array $ignoredParameterNames = []; + /** + * The cache of blade view names for raw templates, keyed by template. + * + * @var array + */ + protected static array $rawTemplateViewCache = []; + /** * Get the view / view contents that represent the component. */ - abstract public function render(): ViewContract|Htmlable|Closure|string; + abstract public function render(): ViewContract|Htmlable|RawTemplate|Closure|string; /** * Resolve the component instance with the given data. @@ -143,6 +150,10 @@ public function resolveView(): ViewContract|Htmlable|Closure|string return $view; } + if ($view instanceof RawTemplate) { + return $this->createBladeViewFromRawTemplate($view); + } + return $this->extractBladeViewFromString($view); }; @@ -170,6 +181,17 @@ protected function extractBladeViewFromString(string $contents): string return static::$bladeViewCache[$key] = $this->createBladeViewFromString($this->factory(), $contents); } + /** + * Create a Blade view from the given raw template. + */ + protected function createBladeViewFromRawTemplate(RawTemplate $template): string + { + return static::$rawTemplateViewCache[static::bladeViewCacheKey($template->template)] ??= $this->createBladeViewFromString( + $this->factory(), + $template->template + ); + } + /** * Get the cache key for the given Blade view contents. */ @@ -406,6 +428,7 @@ public static function ignoredParameterNames(): array public static function flushCache(): void { static::$bladeViewCache = []; + static::$rawTemplateViewCache = []; static::$constructorParametersCache = []; static::$methodCache = []; static::$propertyCache = []; diff --git a/src/view/src/DynamicComponent.php b/src/view/src/DynamicComponent.php index feeb2438ee..0c396baad0 100644 --- a/src/view/src/DynamicComponent.php +++ b/src/view/src/DynamicComponent.php @@ -9,6 +9,7 @@ use Hypervel\Container\Container; use Hypervel\Support\Collection; use Hypervel\Support\Str; +use Hypervel\View\Compilers\BladeCompiler; use Hypervel\View\Compilers\ComponentTagCompiler; use function Hypervel\Support\enum_value; @@ -30,6 +31,16 @@ class DynamicComponent extends Component */ protected static array $componentClasses = []; + /** + * The names of the attributes that were bound on the component tag. + */ + protected array $boundAttributes = []; + + /** + * The methods that should be ignored. + */ + protected array $except = ['withBoundAttributes']; + /** * Create a new component instance. */ @@ -77,6 +88,38 @@ class_exists($class) ? '{{ $attributes }}' : '', }; } + /** + * Set the names of the attributes that were bound on the component tag. + * + * @return $this + */ + public function withBoundAttributes(array $attributes): static + { + $this->boundAttributes = $attributes; + + return $this; + } + + /** + * Set the extra attributes that the component should make available. + * + * @return $this + */ + public function withAttributes(array $attributes): static + { + if ($this->boundAttributes && class_exists($class = $this->classForComponent())) { + [$data] = $this->compiler()->partitionDataAndAttributes($class, $attributes); + + foreach ($this->boundAttributes as $key) { + if (array_key_exists($key, $attributes) && ! $data->has($key)) { + $attributes[$key] = BladeCompiler::sanitizeComponentAttribute($attributes[$key]); + } + } + } + + return parent::withAttributes($attributes); + } + /** * Compile the @props directive for the component. */ diff --git a/src/view/src/Factory.php b/src/view/src/Factory.php index 14292adcb4..827839c9c2 100755 --- a/src/view/src/Factory.php +++ b/src/view/src/Factory.php @@ -130,6 +130,25 @@ public function file(string $path, Arrayable|array $data = [], array $mergeData }); } + /** + * Create a view for a source file that will be deleted after rendering. + * + * The view name must already be normalized. The path is unique to one render, + * so it is not kept in the engine cache. + * + * @internal + */ + public function makeFromTemporaryFile(string $view, string $path, Arrayable|array $data = []): ViewContract + { + try { + return tap($this->viewInstance($view, $path, $this->parseData($data)), function ($view) { + $this->callCreator($view); + }); + } finally { + unset($this->pathEngineCache[$path]); + } + } + /** * Get the evaluated view contents for the given view. */ diff --git a/src/view/src/RawTemplate.php b/src/view/src/RawTemplate.php new file mode 100644 index 0000000000..e9a6ee3e01 --- /dev/null +++ b/src/view/src/RawTemplate.php @@ -0,0 +1,21 @@ +add([$job, $secondJob]); $this->assertEquals(2, $batch->pendingJobs); - $batch->recordFailedJob('test-id', new RuntimeException('Something went wrong.')); - $batch->recordFailedJob('test-id', new RuntimeException('Something else went wrong.')); + // Distinct IDs: Laravel records 'test-id' twice, which is one job failing twice, not every job running. + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + $batch->recordFailedJob('second-id', new RuntimeException('Something else went wrong.')); $this->assertInstanceOf(Batch::class, $_SERVER['__finally.batch']); $this->assertFalse(isset($_SERVER['__then.batch'])); @@ -492,22 +501,214 @@ public function testFailedJobsCanBeRecordedWhileAllowingFailures(): void $batch = $batch->add([$job, $secondJob]); $this->assertEquals(2, $batch->pendingJobs); - $batch->recordFailedJob('test-id', new RuntimeException('Something went wrong.')); - $batch->recordFailedJob('test-id', new RuntimeException('Something else went wrong.')); + // Distinct IDs: Laravel records 'test-id' twice, which is one job failing twice, not every job running. + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + $batch->recordFailedJob('second-id', new RuntimeException('Something else went wrong.')); - // While allowing failures this batch never actually completes... $this->assertFalse(isset($_SERVER['__then.batch'])); $batch = $batch->fresh(); $this->assertEquals(2, $batch->pendingJobs); $this->assertEquals(2, $batch->failedJobs); - $this->assertFalse($batch->finished()); + $this->assertTrue($batch->finished()); + $this->assertTrue($_SERVER['__finally.batch']->finished()); $this->assertFalse($batch->cancelled()); $this->assertEquals(1, $_SERVER['__catch.count']); $this->assertEquals(2, $_SERVER['__progress.count']); $this->assertSame('Something went wrong.', $_SERVER['__catch.exception']->getMessage()); } + public function testBatchAllowingFailuresIsFinishedWhenTheLastJobSucceedsAfterAFailure(): void + { + $queue = Double::for(Factory::class)->strict(); + + $batch = $this->createTestBatch($queue, $allowFailures = true); + + $connection = Double::for(QueueContract::class)->strict(); + $queue->expects('connection')->with('test-connection')->returns($connection); + + $connection->expects('bulk'); + + $batch = $batch->add([new class { + use Batchable; + }, new class { + use Batchable; + }]); + + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + + $this->assertFalse($batch->fresh()->finished()); + + $batch->recordSuccessfulJob('second-id'); + + $batch = $batch->fresh(); + $this->assertTrue($batch->finished()); + $this->assertEquals(1, $batch->pendingJobs); + $this->assertSame(['first-id'], $batch->failedJobIds); + $this->assertEquals(0, $_SERVER['__then.count']); + $this->assertEquals(1, $_SERVER['__finally.count']); + $this->assertTrue($_SERVER['__finally.batch']->finished()); + + $batch->recordSuccessfulJob('first-id'); + + $this->assertSame([], $batch->fresh()->failedJobIds); + $this->assertEquals(1, $_SERVER['__then.count']); + } + + public function testRetriedJobsDoNotCompleteTheBatchUntilEveryJobHasRun(): void + { + $queue = Double::for(Factory::class)->strict(); + + $batch = $this->createTestBatch($queue, $allowFailures = true); + + $connection = Double::for(QueueContract::class)->strict(); + $queue->expects('connection')->with('test-connection')->returns($connection); + + $connection->expects('bulk'); + + $batch = $batch->add([new class { + use Batchable; + }, new class { + use Batchable; + }]); + + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + $batch->recordFailedJob('first-id', new RuntimeException('The retry failed too.')); + $batch->recordSuccessfulJob('first-id'); + + $this->assertFalse($batch->fresh()->finished()); + $this->assertEquals(0, $_SERVER['__finally.count']); + + $batch->recordSuccessfulJob('second-id'); + + $this->assertTrue($batch->fresh()->finished()); + $this->assertEquals(1, $_SERVER['__then.count']); + $this->assertEquals(1, $_SERVER['__finally.count']); + } + + /** + * @param class-string $job + */ + #[TestWith([RetriedBatchJob::class])] + #[TestWith([RetriedBatchableOnlyJob::class])] + public function testRetriedJobDoesItsWorkAfterItsBatchFinishedWithFailures(string $job): void + { + $queue = Double::for(Factory::class)->strict(); + + $batch = $this->createTestBatch($queue, $allowFailures = true); + + $connection = Double::for(QueueContract::class)->strict(); + $queue->expects('connection')->with('test-connection')->returns($connection); + + $connection->expects('bulk'); + + $batch = $batch->add([new $job, new $job]); + + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + $batch->recordSuccessfulJob('second-id'); + + $this->assertTrue($batch->fresh()->finished()); + + $handler = new CallQueuedHandler(new Dispatcher($this->app), $this->app); + $command = serialize((new $job)->withBatchId($batch->id)); + + // Horizon gives each retry a new UUID and carries the original batch job ID. + $handler->failed(['command' => $command], new RuntimeException('The retry failed.'), 'first-retry-uuid', new FakeJob([ + 'uuid' => 'first-retry-uuid', + 'batchJobId' => 'first-id', + ])); + + $this->assertSame(['first-id'], $batch->fresh()->failedJobIds); + $this->assertEquals(1, $_SERVER['__finally.count']); + + $handler->call(new FakeJob(['uuid' => 'second-retry-uuid', 'batchJobId' => 'first-id']), ['command' => $command]); + + $this->assertTrue($job::$handled); + $this->assertSame([], $batch->fresh()->failedJobIds); + $this->assertEquals(1, $_SERVER['__then.count']); + } + + public function testWorkAddedWhileOnlyFailuresRemainReopensTheBatch(): void + { + $queue = Double::for(Factory::class)->strict(); + $connection = Double::for(QueueContract::class)->strict(); + $queue->expects('connection')->times(2)->returns($connection); + $connection->expects('bulk')->times(2); + + $repository = new DatabaseBatchRepository(new BatchFactory($queue), $this->app->make('db'), 'job_batches'); + + // The failure callback stands in for a retried job adding work just as the batch finishes. + $batch = $repository->store((new PendingBatch($this->app, Collection::make()))->allowFailures( + fn (Batch $batch) => $batch->add([new TestBatchJob]), + )); + + $batch = $batch->add([new TestBatchJob]); + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + + $batch = $batch->fresh(); + $this->assertFalse($batch->finished()); + $this->assertSame(2, $batch->pendingJobs); + } + + public function testFinishingWithFailuresKeepsAnEarlierCancellationTime(): void + { + $queue = Double::for(Factory::class)->strict(); + + $batch = $this->createTestBatch($queue, $allowFailures = true); + + $connection = Double::for(QueueContract::class)->strict(); + $queue->expects('connection')->with('test-connection')->returns($connection); + + $connection->expects('bulk'); + + $batch = $batch->add([new TestBatchJob]); + + $this->app->make('db')->table('job_batches')->where('id', $batch->id)->update([ + 'cancelled_at' => 100, + 'finished_at' => 100, + ]); + + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + + $this->assertSame(100, $batch->fresh()->finishedAt->getTimestamp()); + } + + public function testBatchesNotAllowingFailuresAreOnlyFinishedByCancellation(): void + { + $queue = Double::for(Factory::class)->strict(); + + $batch = $this->createTestBatch($queue); + + $connection = Double::for(QueueContract::class)->strict(); + $queue->expects('connection')->with('test-connection')->returns($connection); + + $connection->expects('bulk'); + + $batch = $batch->add([new TestBatchJob]); + + $finishedWhenStarted = null; + $this->app->make(EventDispatcher::class)->listen(BatchStarted::class, function (BatchStarted $event) use (&$finishedWhenStarted): void { + $finishedWhenStarted = $event->batch->fresh()->finished(); + }); + + $batch->recordFailedJob('first-id', new RuntimeException('Something went wrong.')); + + $this->assertFalse($finishedWhenStarted); + $this->assertTrue($batch->fresh()->cancelled()); + } + + public function testRepositoriesWithoutFirstPassReportingFinishBatchesAfterTheCallbacks(): void + { + $repository = Double::for(BatchRepository::class)->strict(); + $batch = new Batch(Double::for(Factory::class)->strict(), $repository, 'batch', 'batch', 1, 1, 0, [], [ + 'allowFailures' => true, + ], CarbonImmutable::now()); + $repository->expects('incrementFailedJobs')->with('batch', 'job')->returns(new UpdatedBatchJobCounts(1, 1)); + $repository->expects('markAsFinished')->with('batch'); + + $batch->recordFailedJob('job', new RuntimeException('Something went wrong.')); + } + public function testPendingBatchFiltersOutFalsyJobs(): void { $job = new class { @@ -1021,6 +1222,48 @@ public function handle(): void } } +class RetriedBatchJob implements ShouldQueue +{ + use Batchable; + use InteractsWithQueue; + use Queueable; + + public static bool $handled = false; + + /** + * Do the job's work while its batch still includes it. + */ + public function handle(): void + { + if ($this->batching()) { + static::$handled = true; + } + } +} + +class RetriedBatchableOnlyJob implements ShouldQueue +{ + use Batchable; + use Queueable; + + public static bool $handled = false; + + public ?Job $job = null; + + /** + * Do the job's work while its batch still includes it. + */ + public function handle(): void + { + // The application's own job property does not identify this job to its batch. + $this->job = new FakeJob(['uuid' => 'referenced-job']); + + if ($this->batching()) { + static::$handled = true; + } + } +} + class ChainHeadJob implements ShouldQueue { use Batchable; diff --git a/tests/Cache/CacheRepositoryTest.php b/tests/Cache/CacheRepositoryTest.php index d281eefab3..9e62dbbd74 100644 --- a/tests/Cache/CacheRepositoryTest.php +++ b/tests/Cache/CacheRepositoryTest.php @@ -165,6 +165,19 @@ public function testGetReturnsMultipleValuesFromCacheWhenGivenAnArrayOfOneTwoThr $this->assertEquals([1 => null, 2 => null, 3 => null], $repo->get([1, 2, 3])); } + public function testGetDoesNotUseRequestedKeysAsDefaultsForNumericKeys(): void + { + $repo = $this->getRepository(); + $repo->getStore()->expects('many')->with(['foo', '02', 'bar', '0'])->returns(['foo' => null, '02' => null, 'bar' => null, '0' => null]); + $repo->getStore()->expects('many')->with(['2', 'bar'])->returns(['2' => null, 'bar' => null]); + + $this->assertSame( + ['foo' => 'default', '02' => 'zero-two', 'bar' => null, 0 => null], + $repo->get(['foo' => 'default', '02' => 'zero-two', 'bar', '0']) + ); + $this->assertSame([2 => null, 'bar' => null], $repo->get([1 => '2', 2 => 'bar'])); + } + public function testDefaultValueIsReturned(): void { $repo = $this->getRepository(); diff --git a/tests/Cache/Redis/AllTaggedCacheTest.php b/tests/Cache/Redis/AllTaggedCacheTest.php index c0939a2985..e0ed5b34fa 100644 --- a/tests/Cache/Redis/AllTaggedCacheTest.php +++ b/tests/Cache/Redis/AllTaggedCacheTest.php @@ -227,11 +227,15 @@ public function testManyUsesSingleMgetWithCachedTagPrefix(): void ->with([ "prefix:{$prefix}name", "prefix:{$prefix}age", + "prefix:{$prefix}facets", + "prefix:{$prefix}123", "prefix:{$prefix}missing", ]) ->returns([ serialize('Sally'), '30', + serialize(['facet']), + null, null, ]); @@ -241,16 +245,23 @@ public function testManyUsesSingleMgetWithCachedTagPrefix(): void $result = (new AllTaggedCache($store, $tags))->many([ 'name' => 'unused', 'age', - 'missing' => 'fallback', + 'facets', + '123', + 'missing' => fn () => 'fallback', ]); $this->assertSame([ 'name' => 'Sally', 'age' => '30', + 'facets' => ['facet'], + 123 => null, 'missing' => 'fallback', ], $result); } + // REMOVED: Laravel's Predis-cluster per-key read and PhpRedis read-retry tests for tagged many(); + // Hypervel is phpredis-only and never replays a Redis command after a failure. + public function testManyFiresTaggedManyEvents(): void { $connection = $this->mockConnection(); @@ -916,6 +927,20 @@ public function testRememberWithMultipleTags(): void $this->assertSame('activity_data', $result); } + public function testFlexibleReadsFreshTaggedValueAndTimestampInOneMget(): void + { + $connection = $this->mockConnection(); + $prefix = hash('xxh128', '_all:tag:store:entries') . ':'; + + $connection->client()->expects('mget') + ->with(["prefix:{$prefix}key", "prefix:{$prefix}" . Repository::FLEXIBLE_CREATED_KEY_PREFIX . 'key']) + ->returns([serialize('cached'), serialize(now()->getTimestamp())]); + + $store = $this->createStore($connection); + + $this->assertSame('cached', $store->tags(['store'])->flexible('key', [60, 120], fn () => $this->fail('The cached value is fresh.'))); + } + public function testFlexibleNullableReturnsNullOnFreshSentinelHit(): void { $connection = $this->mockConnection(); diff --git a/tests/Console/Fixtures/class.stub b/tests/Console/Fixtures/class.stub index b31ca86e44..681befaea3 100644 --- a/tests/Console/Fixtures/class.stub +++ b/tests/Console/Fixtures/class.stub @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace %NAMESPACE%; +namespace {{ namespace }}; -class %CLASS% +class {{ class }} { } diff --git a/tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php b/tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php index 3fc64506ca..269ce5820f 100644 --- a/tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php +++ b/tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Database\DatabaseEloquentHasManyThroughIntegrationTest; +use Generator; use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\ConnectionInterface; use Hypervel\Database\Eloquent\Casts\Attribute; @@ -180,6 +181,29 @@ public function testFindManyMethod(): void $this->assertCount(2, $country->posts()->findMany([1, 2])); $this->assertCount(2, $country->posts()->findMany(new Collection([1, 2]))); + + // Post 2's user_id is post 1's ID, so querying its attributes would also find post 1. + $posts = Post::whereKey(2)->get(); + + $this->assertSame([2], $country->posts()->findMany($posts)->modelKeys()); + $this->assertSame([2], $country->posts()->findOrFail($posts)->modelKeys()); + $this->assertSame([2], $country->posts()->findOr($posts, fn (): string => 'missing')->modelKeys()); + + // Like a stream, each source produces its IDs only once. + $ids = function (): LazyCollection { + $read = false; + + return new LazyCollection(function () use (&$read): Generator { + if (! $read) { + $read = true; + + yield from [1, 2]; + } + }); + }; + + $this->assertSame([1, 2], $country->posts()->findOrFail($ids())->modelKeys()); + $this->assertSame([1, 2], $country->posts()->findOr($ids(), fn (): string => 'missing')->modelKeys()); } public function testFirstOrFailThrowsAnException(): void diff --git a/tests/Database/DatabaseEloquentIntegrationTest.php b/tests/Database/DatabaseEloquentIntegrationTest.php index da055957bb..02e7b20a60 100644 --- a/tests/Database/DatabaseEloquentIntegrationTest.php +++ b/tests/Database/DatabaseEloquentIntegrationTest.php @@ -7,6 +7,7 @@ use ArrayObject; use DateTimeInterface; use Exception; +use Generator; use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\ConnectionInterface; use Hypervel\Database\Eloquent\Attributes\Refreshes; @@ -36,6 +37,7 @@ use Hypervel\Pagination\LengthAwarePaginator; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Collection as BaseCollection; +use Hypervel\Support\LazyCollection; use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Database\Fixtures\Enums\Bar; @@ -759,6 +761,51 @@ public function testFindOrWithManyIdentifiersReturnsACollection(bool $useCollect $this->assertCount(0, $found); } + public function testFindOrFailWithACollectionOfModelsReturnsTheModels(): void + { + User::create(['id' => 1, 'email' => 'first@example.com']); + User::create(['id' => 2, 'email' => 'second@example.com']); + + $found = User::findOrFail(User::all()); + + $this->assertInstanceOf(Collection::class, $found); + $this->assertSame([1, 2], $found->modelKeys()); + } + + public function testFindWithModelsQueriesOnlyTheirKeys(): void + { + $first = Post::create(['id' => 1, 'user_id' => 3, 'name' => 'First']); + $second = Post::create(['id' => 2, 'user_id' => 3, 'name' => 'Second']); + Post::create(['id' => 3, 'user_id' => 1, 'name' => 'Third']); + + // Each model's user_id is another post's ID, so querying their attributes would also find post 3. + $this->assertSame([1, 2], Post::find(Post::whereKey([1, 2])->get())->modelKeys()); + $this->assertSame([1, 2], Post::find([$first, $second])->modelKeys()); + $this->assertSame([3], Post::whereKeyNot(Post::whereKey([1, 2])->cursor())->pluck('id')->all()); + } + + public function testFindOrFailAndFindOrReadLazyIdsOnce(): void + { + User::create(['id' => 1, 'email' => 'first@example.com']); + User::create(['id' => 2, 'email' => 'second@example.com']); + + // Like a stream, each source produces its IDs only once. + $ids = function (): LazyCollection { + $read = false; + + return new LazyCollection(function () use (&$read): Generator { + if (! $read) { + $read = true; + + yield from [1, 2]; + } + }); + }; + + $this->assertSame([1, 2], User::findOrFail($ids())->modelKeys()); + $this->assertSame([1, 2], User::findOr($ids(), fn (): string => 'missing')->modelKeys()); + } + public function testDestroyAcceptsVariousIdentifierShapes(): void { foreach ([1, 2, 3, 4, 5, 6, 7, 8] as $id) { diff --git a/tests/Database/DatabasePdoConnectionTest.php b/tests/Database/DatabasePdoConnectionTest.php index 15eabc2d07..3d41d9e32b 100755 --- a/tests/Database/DatabasePdoConnectionTest.php +++ b/tests/Database/DatabasePdoConnectionTest.php @@ -987,6 +987,15 @@ public function testUsingWritePdoPreservesAnAlreadyEnabledWriteConnectionPrefere $this->assertSame($writePdo, $connection->getReadPdo()); } + public function testWithoutAffectingStickiness(): void + { + $connection = new MySqlConnection(new PDOStub); + + $connection->withoutAffectingStickiness(fn (MySqlConnection $connection) => $connection->recordsHaveBeenModified()); + + $this->assertFalse($connection->hasModifiedRecords()); + } + public function testExplicitPhysicalCommitFailureLeavesTheTransactionCallerOwned(): void { $failure = new RuntimeException('commit failure'); diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index 0c60b0e868..55d9df2827 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -9,6 +9,7 @@ use DateInterval; use DatePeriod; use DateTime; +use ErrorException; use Hypervel\Contracts\Database\Query\ConditionExpression; use Hypervel\Contracts\Database\Query\Expression as ExpressionContract; use Hypervel\Database\Connection; @@ -8872,6 +8873,31 @@ public function testFrom(): void $this->assertSame('select * from (select * from "users") as "u"', $builder->toSql()); } + public function testFromSubWithoutAlias(): void + { + $errorReporting = error_reporting(E_ALL); + + set_error_handler(function (int $level, string $message, string $file = '', int $line = 0): never { + throw new ErrorException($message, 0, $level, $file, $line); + }); + + try { + $builder = $this->getBuilder(); + $builder->selectRaw('1')->from(function ($query) { + $query->selectRaw('1 as a'); + }); + $this->assertSame('select 1 from (select 1 as a) as "hypervel_table"', $builder->toSql()); + + $builder = $this->getMySqlBuilder(); + $builder->selectRaw('1')->from($this->getMySqlBuilder()->selectRaw('1 as a')); + $this->assertSame('select 1 from (select 1 as a) as `hypervel_table`', $builder->toSql()); + } finally { + restore_error_handler(); + + error_reporting($errorReporting); + } + } + public function testFromSub(): void { $builder = $this->getBuilder(); diff --git a/tests/Foundation/FoundationExceptionsHandlerTest.php b/tests/Foundation/FoundationExceptionsHandlerTest.php index d234c3aaa4..e42cce9fec 100644 --- a/tests/Foundation/FoundationExceptionsHandlerTest.php +++ b/tests/Foundation/FoundationExceptionsHandlerTest.php @@ -286,25 +286,31 @@ public function testHandlerCallsContextMethodIfPresent(): void public function testHandlerMergesInlineContextIntoLogContext(): void { - $logger = Double::for(LoggerInterface::class)->strict(); - $this->container->instance(LoggerInterface::class, $logger); - $logger->expects('error')->with('Exception message', Argument::satisfies(fn (array $context): bool => ($context['from'] ?? null) === 'user@example.com' && ($context['subject'] ?? null) === 'Hello')); + $logger = $this->getRealLogger(); $this->handler->report(new RuntimeException('Exception message'), [ 'from' => 'user@example.com', 'subject' => 'Hello', ]); + + $this->assertCount(1, $logger->logs); + $this->assertSame('error', $logger->logs[0]['level']); + $this->assertSame('Exception message', $logger->logs[0]['message']); + $this->assertSame('user@example.com', $logger->logs[0]['context']['from']); + $this->assertSame('Hello', $logger->logs[0]['context']['subject']); } public function testHandlerInlineContextOverridesExceptionContext(): void { - $logger = Double::for(LoggerInterface::class)->strict(); - $this->container->instance(LoggerInterface::class, $logger); - $logger->expects('error')->with('Exception message', Argument::satisfies(fn (array $context): bool => ($context['foo'] ?? null) === 'overridden')); + $logger = $this->getRealLogger(); $this->handler->report(new ContextProvidingException('Exception message'), [ 'foo' => 'overridden', ]); + + $this->assertCount(1, $logger->logs); + $this->assertSame('error', $logger->logs[0]['level']); + $this->assertSame('overridden', $logger->logs[0]['context']['foo']); } public function testReportableCallbackReceivesInlineContext(): void @@ -404,13 +410,7 @@ public function testHandlerReportsExceptionWithCustomLogLevel(): void public function testHandlerReportsExceptionWithInlineLogLevel(): void { - $logger = Double::for(LoggerInterface::class)->strict(); - $this->container->instance(LoggerInterface::class, $logger); - - $logger->expects('warning')->with( - 'Warning message', - Argument::satisfies(fn (array $context): bool => ($context['from'] ?? null) === 'user@example.com'), - ); + $logger = $this->getRealLogger(); $this->handler->level(InvalidArgumentException::class, LogLevel::CRITICAL); @@ -419,6 +419,11 @@ public function testHandlerReportsExceptionWithInlineLogLevel(): void ['from' => 'user@example.com'], LogLevel::WARNING, ); + + $this->assertCount(1, $logger->logs); + $this->assertSame(LogLevel::WARNING, $logger->logs[0]['level']); + $this->assertSame('Warning message', $logger->logs[0]['message']); + $this->assertSame('user@example.com', $logger->logs[0]['context']['from']); } public function testHandlerIgnoresNotReportableExceptions(): void diff --git a/tests/Http/Client/CurlStreamingHandlerTest.php b/tests/Http/Client/CurlStreamingHandlerTest.php index 751603dfd4..cbc87aef14 100644 --- a/tests/Http/Client/CurlStreamingHandlerTest.php +++ b/tests/Http/Client/CurlStreamingHandlerTest.php @@ -376,6 +376,41 @@ public static function trailerBodySizes(): array return [[5], [65536]]; } + public function testAHandledCancellationDoesNotCancelALaterRequest(): void + { + $server = LoopbackHttpServer::start([['body' => 'hello']]); + $coroutine = Coroutine::id(); + Coroutine::create(static function () use ($coroutine): void { + usleep(10000); + Coroutine::cancelById($coroutine); + }); + + $this->assertFalse((new Channel(1))->pop(1)); + $this->assertTrue(Coroutine::isCanceled()); + + $response = (new Factory)->withOptions(['stream' => true])->get('http://127.0.0.1:' . $server->port); + + $this->assertSame('hello', $response->body()); + } + + public function testCancelingTheDelayCancelsTheRequest(): void + { + $coroutine = Coroutine::id(); + Coroutine::create(static function () use ($coroutine): void { + usleep(50000); + Coroutine::cancelById($coroutine); + }); + + try { + // The canceled delay ends the request before it connects. + (new Factory)->withOptions(['stream' => true, 'delay' => 1500])->get('http://127.0.0.1:1'); + + $this->fail('Expected the delay cancellation.'); + } catch (CanceledException $exception) { + $this->assertSame('The streaming request was canceled.', $exception->getMessage()); + } + } + public function testAbandonedResponseBodyIsReleasedWithoutCyclicGarbageCollection(): void { $factory = new class(new CurlFactory(0)) implements CurlFactoryInterface { diff --git a/tests/Integration/Console/GeneratorCommandTest.php b/tests/Integration/Console/GeneratorCommandTest.php index 9cca6d7942..f4ec004ce0 100644 --- a/tests/Integration/Console/GeneratorCommandTest.php +++ b/tests/Integration/Console/GeneratorCommandTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Integration\Console; use Generator; +use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\Concerns\InteractsWithPublishedFiles; use Hypervel\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -17,6 +18,14 @@ class GeneratorCommandTest extends TestCase 'app/Console/Commands/FooCommand.php', 'resources/views/foo/php.blade.php', 'tests/Feature/fixtures.php/SomeTest.php', + 'app/Mail/Envelope.php', + 'stubs/mail.stub', + 'app/View/Components/View.php', + 'resources/views/components/view.blade.php', + 'database/factories/ClassFactory.php', + 'database/seeders/ClassSeeder.php', + 'app/Http/Controllers/ClassController.php', + 'app/Policies/ClassPolicy.php', ]; public function testItChopsPhpExtension(): void @@ -41,13 +50,14 @@ public function testItChopsPhpExtensionFromMakeViewCommands(): void public function testItOnlyChopsPhpExtensionFromFilename(): void { - $this->artisan('make:test', ['name' => 'fixtures.php/SomeTest']) + // Unlike Laravel, this generates a Pest test, since a class test would declare the invalid namespace Tests\Feature\fixtures.php. + $this->artisan('make:test', ['name' => 'fixtures.php/SomeTest', '--pest' => true]) ->assertExitCode(0); $this->assertFilenameExists('tests/Feature/fixtures.php/SomeTest.php'); $this->assertFileContains([ - 'class SomeTest extends TestCase', + "test('example'", ], 'tests/Feature/fixtures.php/SomeTest.php'); } @@ -59,7 +69,7 @@ public function testItCannotGenerateClassUsingReservedName(string $given): void $this->artisan('make:command', ['name' => $given]) ->expectsOutputToContain('The name "' . $given . '" is reserved by PHP.') - ->assertExitCode(0); + ->assertExitCode(1); $this->assertFilenameDoesNotExists($path); } @@ -76,4 +86,64 @@ public static function reservedNamesDataProvider(): Generator yield ['__class__']; yield ['__CLASS__']; } + + public function testItDoesNotGenerateCompanionFilesForReservedName(): void + { + $this->artisan('make:model', ['name' => 'Class', '--all' => true, '--force' => true]) + ->expectsOutputToContain('The name "Class" is reserved by PHP.') + ->assertExitCode(1); + + $this->assertFilenameDoesNotExists('database/factories/ClassFactory.php'); + $this->assertFilenameDoesNotExists('database/seeders/ClassSeeder.php'); + $this->assertFilenameDoesNotExists('app/Http/Controllers/ClassController.php'); + $this->assertFilenameDoesNotExists('app/Policies/ClassPolicy.php'); + $this->assertMigrationFileNotExists('create_classes_table.php'); + } + + public function testItCanGenerateClassNamedLikeAnAliasedImport(): void + { + $files = new Filesystem; + $files->ensureDirectoryExists($this->app->basePath('stubs')); + $files->put($this->app->basePath('stubs/mail.stub'), <<<'PHP' + artisan('make:mail', ['name' => 'Envelope']) + ->assertExitCode(0); + + $this->assertFileContains([ + 'use Hypervel\Mail\Mailables\Envelope as MailEnvelope;', + 'class Envelope extends Mailable', + ], 'app/Mail/Envelope.php'); + } + + public function testForceDoesNotReplaceFilesForClassNamedLikeAnImportedClass(): void + { + $files = new Filesystem; + $files->ensureDirectoryExists($this->app->basePath('app/View/Components')); + $files->ensureDirectoryExists($this->app->resourcePath('views/components')); + $files->put($this->app->basePath('app/View/Components/View.php'), 'existing class'); + $files->put($this->app->resourcePath('views/components/view.blade.php'), 'existing view'); + + $this->artisan('make:component', ['name' => 'View', '--force' => true]) + ->expectsOutputToContain('The generated file [app/View/Components/View.php] is not valid PHP.') + ->expectsOutputToContain('App\View\Components\View') + ->assertExitCode(1); + + $this->assertStringEqualsFile($this->app->basePath('app/View/Components/View.php'), 'existing class'); + $this->assertStringEqualsFile($this->app->resourcePath('views/components/view.blade.php'), 'existing view'); + } } diff --git a/tests/Integration/Database/EloquentCursorPaginateTest.php b/tests/Integration/Database/EloquentCursorPaginateTest.php index 00442122d3..8820ebae23 100644 --- a/tests/Integration/Database/EloquentCursorPaginateTest.php +++ b/tests/Integration/Database/EloquentCursorPaginateTest.php @@ -775,6 +775,39 @@ public function testPaginationWithMultipleAliasesAndMultipleOrders(): void $this->assertEquals(2, current($result->items())->rank); } + public function testPaginationWithUnionAndAliasedExpressions(): void + { + TestUser::fillAndInsert([['name' => 'alpha'], ['name' => 'bravo']]); + TestPost::fillAndInsert([['title' => 'bravo'], ['title' => 'charlie']]); + + $union = fn (): QueryBuilder => TestPost::select('test_posts.id')->selectRaw('UPPER(test_posts.title) as label')->toBase() + ->unionAll(TestUser::select('test_users.id')->selectRaw('UPPER(test_users.name) as label')->toBase()); + + // Hypervel rejects computed union paging columns rather than guessing a raw selection's width. + try { + $union()->orderBy('label')->orderBy('id')->cursorPaginate(2, ['*'], 'cursor', new Cursor(['label' => 'BRAVO', 'id' => 1])); + $this->fail('The computed union paging column must be rejected.'); + } catch (InvalidArgumentException $exception) { + $this->assertStringContainsString('fromSub()', $exception->getMessage()); + } + + $query = fn (string $direction): QueryBuilder => DB::query()->fromSub($union(), 'entries') + ->orderBy('label', $direction) + ->orderBy('id', $direction); + + $first = $query('asc')->cursorPaginate(2); + $second = $query('asc')->cursorPaginate(2, ['*'], 'cursor', $first->nextCursor()); + + $this->assertSame(['BRAVO', 'CHARLIE'], collect($second->items())->pluck('label')->all()); + $this->assertEquals([2, 2], collect($second->items())->pluck('id')->all()); + + $first = $query('desc')->cursorPaginate(2); + $second = $query('desc')->cursorPaginate(2, ['*'], 'cursor', $first->nextCursor()); + + $this->assertSame(['BRAVO', 'ALPHA'], collect($second->items())->pluck('label')->all()); + $this->assertEquals([1, 1], collect($second->items())->pluck('id')->all()); + } + public function testPaginationWithAliasedOrderBy(): void { TestUser::fillAndInsert([[], [], [], [], [], []]); diff --git a/tests/Integration/Database/QueryBuilderTest.php b/tests/Integration/Database/QueryBuilderTest.php index 5bd4e4d57f..d73e157f4c 100644 --- a/tests/Integration/Database/QueryBuilderTest.php +++ b/tests/Integration/Database/QueryBuilderTest.php @@ -375,6 +375,13 @@ public function testFromWithSubQuery(): void $query->selectRaw("'Fake Post' as title"); }, 'posts')->first()->title ); + + $this->assertSame( + 'Fake Post', + DB::table(function ($query) { + $query->selectRaw("'Fake Post' as title"); + })->first()->title + ); } public function testWhereValueSubQuery(): void diff --git a/tests/Integration/Generators/ComponentMakeCommandTest.php b/tests/Integration/Generators/ComponentMakeCommandTest.php index d70f2c9608..e78e05183c 100644 --- a/tests/Integration/Generators/ComponentMakeCommandTest.php +++ b/tests/Integration/Generators/ComponentMakeCommandTest.php @@ -50,8 +50,15 @@ public function testItCanGenerateInlineComponentFile(): void $this->assertFileContains([ 'namespace App\View\Components;', 'use Hypervel\View\Component;', + 'use Hypervel\View\RawTemplate;', 'class Foo extends Component', - "return <<<'blade'", + 'public function render(): RawTemplate', + "return new RawTemplate(<<<'blade'", + '{{--', + ], 'app/View/Components/Foo.php'); + + $this->assertFileNotContains([ + '