From 67d22967cbb381816cff7ca5893f2b53c91def47 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:56:01 +0000 Subject: [PATCH 01/19] =?UTF-8?q?Use=20Monolog=E2=80=99s=20rotated-file=20?= =?UTF-8?q?finder=20for=20log=20retention?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Daily and monthly logs could accumulate expired files when a literal backslash in the log path was interpreted as a glob escape. Use the finder supplied by Monolog to identify rotated files while keeping Hypervel’s coroutine-safe stream and deletion handling. Require Monolog 3.13 across the matching package manifests. Its finder handles literal characters in log paths. Exercise retention with an expired file in a bracketed directory containing a backslash. --- composer.json | 2 +- src/contracts/composer.json | 2 +- src/doctor/composer.json | 2 +- src/foundation/composer.json | 2 +- src/log/composer.json | 2 +- src/log/src/Handlers/RotatingFileHandler.php | 13 +++++++++++-- src/opentelemetry/composer.json | 2 +- src/sentry/composer.json | 2 +- tests/Log/StreamHandlerTest.php | 12 +++++++----- 9 files changed, 25 insertions(+), 14 deletions(-) diff --git a/composer.json b/composer.json index a2cf224d6e..2156be92bc 100644 --- a/composer.json +++ b/composer.json @@ -71,7 +71,7 @@ "league/flysystem-read-only": "^3.25.1", "league/oauth2-server": "^9.4", "league/uri": "^7.6", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "nesbot/carbon": "^3.13.1", "nikic/php-parser": "^5.7", "nunomaduro/termwind": "^2.0", diff --git a/src/contracts/composer.json b/src/contracts/composer.json index 82a132fc4a..bd956ee98b 100644 --- a/src/contracts/composer.json +++ b/src/contracts/composer.json @@ -26,7 +26,7 @@ "require": { "php": "^8.4", "hypervel/attributes": "^0.4", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "nesbot/carbon": "^3.13.1", "psr/container": "^2.0.1", "psr/http-message": "^2.0", diff --git a/src/doctor/composer.json b/src/doctor/composer.json index 0526bc7039..5b1d58c51c 100644 --- a/src/doctor/composer.json +++ b/src/doctor/composer.json @@ -45,7 +45,7 @@ "hypervel/session": "^0.4", "hypervel/support": "^0.4", "laravel/agent-detector": "^2.0.5", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "symfony/console": "^8.1.10", "symfony/finder": "^8.1" }, diff --git a/src/foundation/composer.json b/src/foundation/composer.json index 96ccc371ff..f895668710 100644 --- a/src/foundation/composer.json +++ b/src/foundation/composer.json @@ -71,7 +71,7 @@ "laravel/serializable-closure": "^2.0.11", "league/flysystem": "^3.25.1", "league/uri": "^7.6", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "nesbot/carbon": "^3.13.1", "psr/clock": "^1.0", "psr/log": "^3.0", diff --git a/src/log/composer.json b/src/log/composer.json index 4b2be861d5..8c612063b8 100644 --- a/src/log/composer.json +++ b/src/log/composer.json @@ -36,7 +36,7 @@ "hypervel/macroable": "^0.4", "hypervel/queue": "^0.4", "hypervel/support": "^0.4", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "psr/log": "^3.0" }, "autoload": { diff --git a/src/log/src/Handlers/RotatingFileHandler.php b/src/log/src/Handlers/RotatingFileHandler.php index ba54d51ca1..2ef6e48d83 100644 --- a/src/log/src/Handlers/RotatingFileHandler.php +++ b/src/log/src/Handlers/RotatingFileHandler.php @@ -14,6 +14,9 @@ class RotatingFileHandler extends MonologRotatingFileHandler { use PerformsSafeStreamOperations; + /** + * Close the stream and rotate its files when needed. + */ #[Override] public function close(): void { @@ -24,6 +27,9 @@ public function close(): void } } + /** + * Write the record and rotate the log on schedule. + */ #[Override] protected function write(LogRecord $record): void { @@ -43,6 +49,9 @@ protected function write(LogRecord $record): void } } + /** + * Remove expired logs without replacing the error handler shared by other coroutines. + */ #[Override] protected function rotate(): void { @@ -55,12 +64,12 @@ protected function rotate(): void } try { - $logFiles = glob($this->getGlobPattern()); + $logFiles = $this->findRotatedFiles(); } catch (Throwable) { return; } - if ($logFiles === false || $this->maxFiles >= count($logFiles)) { + if ($this->maxFiles >= count($logFiles)) { return; } diff --git a/src/opentelemetry/composer.json b/src/opentelemetry/composer.json index 9503040bae..bed94d6222 100644 --- a/src/opentelemetry/composer.json +++ b/src/opentelemetry/composer.json @@ -65,7 +65,7 @@ "hypervel/support": "^0.4", "hypervel/view": "^0.4", "hypervel/websocket-server": "^0.4", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "open-telemetry/api": "^1.10", "open-telemetry/context": "^1.5", "open-telemetry/exporter-otlp": "^1.4", diff --git a/src/sentry/composer.json b/src/sentry/composer.json index f43bdfe322..7e6b491ddb 100644 --- a/src/sentry/composer.json +++ b/src/sentry/composer.json @@ -61,7 +61,7 @@ "hypervel/routing": "^0.4", "hypervel/support": "^0.4", "hypervel/view": "^0.4", - "monolog/monolog": "^3.10", + "monolog/monolog": "^3.13", "nyholm/psr7": "^1.0", "psr/http-message": "^2.0", "psr/log": "^3.0", diff --git a/tests/Log/StreamHandlerTest.php b/tests/Log/StreamHandlerTest.php index e1b571be6a..40fc3744b2 100644 --- a/tests/Log/StreamHandlerTest.php +++ b/tests/Log/StreamHandlerTest.php @@ -275,9 +275,12 @@ public function testDirectoryCreationFailureThrowsDeterministically(): void } } - public function testRotatingHandlerWritesThroughTheSafeStreamBoundary(): void + public function testRotatingHandlerWritesAndPrunesLogsInTheConfiguredDirectory(): void { - $handler = new RotatingFileHandler($this->directory . '/app.log', 1); + $directory = $this->directory . '/logs [app]\daily'; + mkdir($directory); + touch($directory . '/app-2000-01-01.log'); + $handler = new RotatingFileHandler($directory . '/app.log', 1); try { (new Logger('test', [$handler]))->info('rotating message'); @@ -285,10 +288,9 @@ public function testRotatingHandlerWritesThroughTheSafeStreamBoundary(): void $handler->close(); } - $files = glob($this->directory . '/app-*.log'); - $this->assertIsArray($files); + $files = (new Filesystem)->files($directory); $this->assertCount(1, $files); - $this->assertStringContainsString('rotating message', (string) file_get_contents($files[0])); + $this->assertStringContainsString('rotating message', $files[0]->getContents()); } private function captureOpenFailureMessage(string $message): string From 1431bf7d51c852cedd4c4417b318936f53a4ad12 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:56:01 +0000 Subject: [PATCH 02/19] Keep literal directories separate from filesystem glob patterns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Treat framework-owned paths literally when discovering migrations, listeners, skills and configuration or cleaning up generated files. A checkout named project [a] could previously match project a and read migrations from the neighboring application. Preserve caller-supplied wildcard patterns and single-file paths. Share glob quoting in the filesystem package and apply it where each caller knows the literal directory. Keep missing default migration paths visible to PHPStan’s dependency tracking without reading files from a lookalike directory. Cover the command, Doctor, analyzer and event discovery paths with real filesystem regressions. --- bin/sync-skeleton-config/sync.php | 8 ++-- src/ai/src/Tools/LoadSkill.php | 4 +- src/console/src/MigrationGeneratorCommand.php | 3 +- .../src/Console/Migrations/BaseCommand.php | 32 ++++++++++++--- .../src/Migrations/MigrationCreator.php | 6 ++- src/database/src/Migrations/Migrator.php | 10 ++++- src/di/src/Aop/ProxyManager.php | 4 +- .../src/Diagnostics/MigrationsAreUpToDate.php | 11 +++-- src/filesystem/src/functions.php | 24 +++++++++++ src/foundation/src/Console/AboutCommand.php | 6 ++- .../src/Console/ViewClearCommand.php | 4 +- .../Providers/EventServiceProvider.php | 10 +++-- src/permission/composer.json | 1 + .../src/Commands/UpgradeForTeamsCommand.php | 4 +- src/phpstan/src/Properties/MigrationCache.php | 3 +- .../src/Properties/MigrationHelper.php | 4 ++ .../Properties/SquashedMigrationHelper.php | 2 +- src/phpstan/src/Support/ConfigParser.php | 3 +- src/phpstan/src/Support/DirectoryResolver.php | 15 ++++--- src/testbench/src/Bootstrapper.php | 4 +- .../InteractsWithSqliteDatabaseFile.php | 8 ++-- .../Concerns/InteractsWithPublishedFiles.php | 8 ++-- .../Bootstrap/SyncTestbenchCachedRoutes.php | 4 +- .../Console/DropSqliteDbCommand.php | 3 +- .../Console/PurgeSkeletonCommand.php | 21 +++++----- src/testing/src/Console/TestCommandBase.php | 5 ++- tests/Benchmarks/Sentry/setup-app.sh | 21 ++++++---- .../PackageManifestConsistencyTest.php | 4 +- .../Validation/ValidationRuleFactoryTest.php | 4 +- .../DatabaseMigratorIntegrationTest.php | 22 ++++++++++ .../Diagnostics/MigrationsAreUpToDateTest.php | 16 ++++++++ tests/Filesystem/GlobQuoteHelperTest.php | 41 +++++++++++++++++++ tests/Foundation/Console/AboutCommandTest.php | 4 +- .../Providers/EventServiceProviderTest.php | 28 +++++++++++++ .../Migration/StatusCommandTest.php | 32 +++++++++++++++ tests/PHPStan/Unit/MigrationHelperTest.php | 25 +++++++++++ .../Unit/Support/DirectoryResolverTest.php | 11 +++++ tests/Testing/PackageMetadataTest.php | 4 +- 38 files changed, 350 insertions(+), 69 deletions(-) create mode 100644 tests/Filesystem/GlobQuoteHelperTest.php diff --git a/bin/sync-skeleton-config/sync.php b/bin/sync-skeleton-config/sync.php index 8e298870db..5fba7f3e2b 100644 --- a/bin/sync-skeleton-config/sync.php +++ b/bin/sync-skeleton-config/sync.php @@ -23,6 +23,8 @@ use RuntimeException; use Throwable; +use function Hypervel\Filesystem\glob_quote; + require dirname(__DIR__, 2) . '/vendor/autoload.php'; class SkeletonConfigSync @@ -43,7 +45,7 @@ public function run(string $root, bool $check): int $sources = []; - foreach (glob($root . '/src/foundation/config/*.php') as $path) { + foreach (glob(glob_quote($root) . '/src/foundation/config/*.php') as $path) { $sources[basename($path)] = file_get_contents($path); } @@ -88,7 +90,7 @@ public function run(string $root, bool $check): int $this->validateKeys($options, ['files', 'preserve'], $skeleton); $files = $options['files'] ?? []; $preserved = $options['preserve'] ?? []; - $existing = array_map('basename', glob($root . "/skeletons/{$skeleton}/config/*.php")); + $existing = array_map('basename', glob(glob_quote($root . '/skeletons/' . $skeleton) . '/config/*.php')); foreach ($preserved as $name) { if (array_key_exists($name, $sources)) { @@ -142,7 +144,7 @@ public function run(string $root, bool $check): int // This directory contains only generated overrides. Removed rules must not // leave obsolete stubs that config:publish would continue to prefer. - foreach (glob($root . '/src/foundation/config-stubs/*.php') as $path) { + foreach (glob(glob_quote($root) . '/src/foundation/config-stubs/*.php') as $path) { $relative = 'src/foundation/config-stubs/' . basename($path); if (! array_key_exists($relative, $expected)) { diff --git a/src/ai/src/Tools/LoadSkill.php b/src/ai/src/Tools/LoadSkill.php index 29be0571c8..1981ccf00e 100644 --- a/src/ai/src/Tools/LoadSkill.php +++ b/src/ai/src/Tools/LoadSkill.php @@ -20,6 +20,8 @@ use Stringable; use Symfony\Component\Finder\SplFileInfo; +use function Hypervel\Filesystem\glob_quote; + class LoadSkill implements Tool, Transient { /** @@ -224,7 +226,7 @@ protected function discover(string $directory): Collection return new Collection(static::$discoveredSkills[$directory]); } - $skills = collect(glob($directory . '/*/SKILL.md') ?: []) + $skills = collect(glob(glob_quote($directory) . '/*/SKILL.md') ?: []) ->map(fn (string $file): ?Skill => Skill::fromDirectory(dirname($file))) ->filter(); diff --git a/src/console/src/MigrationGeneratorCommand.php b/src/console/src/MigrationGeneratorCommand.php index 3eaae9a3e3..acbf6351d8 100644 --- a/src/console/src/MigrationGeneratorCommand.php +++ b/src/console/src/MigrationGeneratorCommand.php @@ -7,6 +7,7 @@ use Hypervel\Filesystem\Filesystem; use RuntimeException; +use function Hypervel\Filesystem\glob_quote; use function Hypervel\Filesystem\join_paths; abstract class MigrationGeneratorCommand extends Command @@ -92,7 +93,7 @@ protected function createBaseMigration(string $table, ?string $stubPath = null): protected function migrationExists(string $table): bool { return $this->matchingMigrationFiles( - join_paths($this->hypervel->databasePath('migrations'), '*_*_*_*_create_' . $table . '_table.php') + join_paths(glob_quote($this->hypervel->databasePath('migrations')), '*_*_*_*_create_' . glob_quote($table) . '_table.php') ) !== []; } diff --git a/src/database/src/Console/Migrations/BaseCommand.php b/src/database/src/Console/Migrations/BaseCommand.php index bcf7125b75..174c85b26f 100644 --- a/src/database/src/Console/Migrations/BaseCommand.php +++ b/src/database/src/Console/Migrations/BaseCommand.php @@ -15,6 +15,8 @@ use RuntimeException; use Throwable; +use function Hypervel\Filesystem\glob_quote_prefix; + abstract class BaseCommand extends Command { /** @@ -33,19 +35,39 @@ protected function getMigrationPaths(): array // use the path relative to the root of the installation folder so our database // migrations may be run for any customized path from within the application. if ($this->input->hasOption('path') && $this->option('path')) { - return (new Collection($this->option('path')))->map(function ($path) { - return ! $this->usingRealPath() - ? $this->hypervel->basePath() . '/' . $path - : $path; + return (new Collection($this->option('path')))->flatMap(function ($path) { + if ($this->usingRealPath()) { + return [$path]; + } + + $base = $this->hypervel->basePath(); + + return $this->resolveMigrationPath($base . '/' . $path, $base); })->all(); } return array_merge( $this->migrator->paths(), - [$this->getMigrationPath()] + $this->resolveMigrationPath($this->getMigrationPath(), $this->hypervel->databasePath(), $this->hypervel->basePath()) ); } + /** + * Expand a directory pattern when its application root needs quoting. + * + * @return string[] + */ + private function resolveMigrationPath(string $path, string ...$roots): array + { + $pattern = glob_quote_prefix($path, ...$roots); + + if ($pattern === $path || str_ends_with($path, '.php') || is_dir($path)) { + return [$path]; + } + + return glob($pattern, GLOB_ONLYDIR) ?: []; + } + /** * Determine if the given path(s) are pre-resolved "real" paths. */ diff --git a/src/database/src/Migrations/MigrationCreator.php b/src/database/src/Migrations/MigrationCreator.php index e2e1449fda..89235895e8 100644 --- a/src/database/src/Migrations/MigrationCreator.php +++ b/src/database/src/Migrations/MigrationCreator.php @@ -14,6 +14,8 @@ use InvalidArgumentException; use RuntimeException; +use function Hypervel\Filesystem\glob_quote; + class MigrationCreator { protected const string CURRENT_MIGRATION_PATH_CONTEXT_KEY_PREFIX = '__database.migration_creator.current_path.'; @@ -75,7 +77,7 @@ public function create(string $name, string $path, ?string $table = null, bool $ protected function ensureMigrationDoesntAlreadyExist(string $name, ?string $migrationPath = null): void { if (! empty($migrationPath)) { - $migrationFiles = $this->matchingFiles($migrationPath . '/*.php'); + $migrationFiles = $this->matchingFiles(glob_quote($migrationPath) . '/*.php'); foreach ($migrationFiles as $migrationFile) { $this->files->requireOnce($migrationFile); @@ -199,7 +201,7 @@ protected function getDatePrefix(): string $date = Date::now(); - while ($this->matchingFiles($path . '/' . $date->format('Y_m_d_His') . '_*.php')) { + while ($this->matchingFiles(glob_quote($path) . '/' . $date->format('Y_m_d_His') . '_*.php')) { $date = $date->addSecond(); } diff --git a/src/database/src/Migrations/Migrator.php b/src/database/src/Migrations/Migrator.php index 8f5b81d967..6114e5e32a 100755 --- a/src/database/src/Migrations/Migrator.php +++ b/src/database/src/Migrations/Migrator.php @@ -38,6 +38,8 @@ use Throwable; use WeakReference; +use function Hypervel\Filesystem\glob_quote; + class Migrator { protected const string STATE_CONTEXT_KEY_PREFIX = '__database.migrator.'; @@ -633,7 +635,13 @@ protected function getMigrationClass(string $migrationName): string public function getMigrationFiles(array|string $paths): array { return (new Collection($paths)) - ->flatMap(fn ($path) => str_ends_with($path, '.php') ? [$path] : $this->files->glob($path . '/*_*.php')) + ->flatMap(function (string $path) { + if (str_ends_with($path, '.php')) { + return [$path]; + } + + return $this->files->glob((is_dir($path) ? glob_quote($path) : $path) . '/*_*.php'); + }) ->filter() ->values() ->keyBy(fn ($file) => $this->getMigrationName($file)) diff --git a/src/di/src/Aop/ProxyManager.php b/src/di/src/Aop/ProxyManager.php index 68ee4160e6..063d3d79d4 100644 --- a/src/di/src/Aop/ProxyManager.php +++ b/src/di/src/Aop/ProxyManager.php @@ -11,6 +11,8 @@ use InvalidArgumentException; use Throwable; +use function Hypervel\Filesystem\glob_quote; + class ProxyManager { private const string FINGERPRINT_HEADER = '// Hypervel AOP fingerprint: '; @@ -255,7 +257,7 @@ private function aopSourceFingerprint(): string { $sources = []; - foreach (glob(__DIR__ . '/*.php') as $path) { + foreach (glob(glob_quote(__DIR__) . '/*.php') as $path) { $sources[basename($path)] = $this->filesystem->get($path); } diff --git a/src/doctor/src/Diagnostics/MigrationsAreUpToDate.php b/src/doctor/src/Diagnostics/MigrationsAreUpToDate.php index c82f8b567e..00ca26b6f6 100644 --- a/src/doctor/src/Diagnostics/MigrationsAreUpToDate.php +++ b/src/doctor/src/Diagnostics/MigrationsAreUpToDate.php @@ -58,10 +58,13 @@ public function check(): DiagnosticResult $migrator = app('migrator'); try { - $files = $migrator->getMigrationFiles(array_values(array_unique([ - ...$migrator->paths(), - database_path('migrations'), - ]))); + $paths = $migrator->paths(); + + if (is_dir($directory = database_path('migrations'))) { + $paths[] = $directory; + } + + $files = $migrator->getMigrationFiles(array_values(array_unique($paths))); if ($files === []) { return $this->pass('no-files'); diff --git a/src/filesystem/src/functions.php b/src/filesystem/src/functions.php index a1921105fe..28caf42d83 100644 --- a/src/filesystem/src/functions.php +++ b/src/filesystem/src/functions.php @@ -22,3 +22,27 @@ function join_paths($basePath, ...$paths): string return $basePath . implode('', $paths); } + +/** + * Quote a literal path or filename for use in a glob pattern. + */ +function glob_quote(string $path): string +{ + return addcslashes($path, '\*?[{'); +} + +/** + * Quote the first matching directory prefix, leaving the caller's pattern intact. + */ +function glob_quote_prefix(string $pattern, string ...$directories): string +{ + foreach ($directories as $directory) { + $directory = rtrim($directory, '/'); + + if ($pattern === $directory || str_starts_with($pattern, $directory . '/')) { + return glob_quote($directory) . substr($pattern, strlen($directory)); + } + } + + return $pattern; +} diff --git a/src/foundation/src/Console/AboutCommand.php b/src/foundation/src/Console/AboutCommand.php index c58b4e4ab8..d41df6e4b2 100644 --- a/src/foundation/src/Console/AboutCommand.php +++ b/src/foundation/src/Console/AboutCommand.php @@ -13,6 +13,8 @@ use Hypervel\Support\Stringable; use Symfony\Component\Console\Attribute\AsCommand; +use function Hypervel\Filesystem\glob_quote; + #[AsCommand(name: 'about')] class AboutCommand extends Command { @@ -254,9 +256,9 @@ protected function determineStoragePathLinkStatus(callable $formatStorageLinkedS /** * Determine whether the given directory has PHP files. */ - protected function hasPhpFiles(string $path, string $extension = 'php'): bool + protected function hasPhpFiles(string $path): bool { - $files = @glob($path . "/*.{$extension}"); + $files = @glob(glob_quote($path) . '/*.php'); return $files !== false && $files !== []; } diff --git a/src/foundation/src/Console/ViewClearCommand.php b/src/foundation/src/Console/ViewClearCommand.php index 9c1afc2428..9994031b51 100644 --- a/src/foundation/src/Console/ViewClearCommand.php +++ b/src/foundation/src/Console/ViewClearCommand.php @@ -13,6 +13,8 @@ use Symfony\Component\Console\Attribute\AsCommand; use Throwable; +use function Hypervel\Filesystem\glob_quote; + #[AsCommand(name: 'view:clear')] class ViewClearCommand extends Command { @@ -48,7 +50,7 @@ public function handle(): void throw new RuntimeException('View path not found.'); } - $views = $this->files->glob("{$path}/*"); + $views = $this->files->glob(glob_quote($path) . '/*'); if ($views === false) { throw new RuntimeException("Unable to enumerate compiled views in [{$path}]."); diff --git a/src/foundation/src/Support/Providers/EventServiceProvider.php b/src/foundation/src/Support/Providers/EventServiceProvider.php index 2d7402590d..b66089607a 100644 --- a/src/foundation/src/Support/Providers/EventServiceProvider.php +++ b/src/foundation/src/Support/Providers/EventServiceProvider.php @@ -13,6 +13,8 @@ use Hypervel\Support\LazyCollection; use Hypervel\Support\ServiceProvider; +use function Hypervel\Filesystem\glob_quote_prefix; + class EventServiceProvider extends ServiceProvider { /** @@ -132,10 +134,10 @@ public function discoverEvents(): array { return (new LazyCollection($this->discoverEventsWithin())) ->flatMap(function ($directory) { - return glob($directory, GLOB_ONLYDIR); - }) - ->reject(function ($directory) { - return ! is_dir($directory); + return is_dir($directory) ? [$directory] : glob( + glob_quote_prefix($directory, $this->app->path(), $this->app->basePath()), + GLOB_ONLYDIR + ); }) ->pipe(fn ($directories) => DiscoverEvents::within( $directories->all(), diff --git a/src/permission/composer.json b/src/permission/composer.json index 4dc250786d..5ae6921ff6 100644 --- a/src/permission/composer.json +++ b/src/permission/composer.json @@ -45,6 +45,7 @@ "hypervel/contracts": "^0.4", "hypervel/database": "^0.4", "hypervel/events": "^0.4", + "hypervel/filesystem": "^0.4", "hypervel/foundation": "^0.4", "hypervel/http": "^0.4", "hypervel/queue": "^0.4", diff --git a/src/permission/src/Commands/UpgradeForTeamsCommand.php b/src/permission/src/Commands/UpgradeForTeamsCommand.php index 9b60a732ee..b472e29463 100644 --- a/src/permission/src/Commands/UpgradeForTeamsCommand.php +++ b/src/permission/src/Commands/UpgradeForTeamsCommand.php @@ -9,6 +9,8 @@ use Symfony\Component\Console\Attribute\AsCommand; use Throwable; +use function Hypervel\Filesystem\glob_quote_prefix; + #[AsCommand(name: 'permission:setup-teams')] class UpgradeForTeamsCommand extends Command { @@ -106,7 +108,7 @@ protected function getExistingMigrationsWarning(array $existingMigrations): stri */ protected function alreadyExistingMigrations(): array { - $matchingFiles = glob($this->getMigrationPath('*')); + $matchingFiles = glob(glob_quote_prefix($this->getMigrationPath('*'), database_path('migrations'))); if ($matchingFiles === false) { return []; diff --git a/src/phpstan/src/Properties/MigrationCache.php b/src/phpstan/src/Properties/MigrationCache.php index 147aacffeb..dd7ff98fe1 100644 --- a/src/phpstan/src/Properties/MigrationCache.php +++ b/src/phpstan/src/Properties/MigrationCache.php @@ -24,6 +24,7 @@ use function glob; use function hash; use function hash_file; +use function Hypervel\Filesystem\glob_quote; use function implode; use function is_array; use function is_file; @@ -199,7 +200,7 @@ private static function hashSource(string $path): false|string private function cleanupOldCacheFiles(string $currentFingerprint): void { $currentCacheFile = sprintf('%s%s.cache', self::CACHE_PREFIX, $currentFingerprint); - $files = glob(sprintf('%s/%s*.cache', $this->cacheDirectory, self::CACHE_PREFIX)) ?: []; + $files = glob(sprintf('%s/%s*.cache', glob_quote($this->cacheDirectory), self::CACHE_PREFIX)) ?: []; foreach (array_filter($files, static fn (string $file): bool => ! str_ends_with($file, $currentCacheFile)) as $file) { @unlink($file); diff --git a/src/phpstan/src/Properties/MigrationHelper.php b/src/phpstan/src/Properties/MigrationHelper.php index 90162862a3..2efb22863d 100644 --- a/src/phpstan/src/Properties/MigrationHelper.php +++ b/src/phpstan/src/Properties/MigrationHelper.php @@ -206,6 +206,10 @@ public function getMigrationFiles(): array $paths = $this->getMigrationPaths(); if ($this->databaseMigrationPath === [] && $paths !== []) { + if (! is_dir($directory = database_path('migrations'))) { + unset($paths[$directory]); + } + // Unlike upstream, default discovery is migrate's: a later path's migration replaces an // earlier one of the same name, so a published copy replaces its package's original. return $this->migrationFiles = array_map( diff --git a/src/phpstan/src/Properties/SquashedMigrationHelper.php b/src/phpstan/src/Properties/SquashedMigrationHelper.php index 215969dbb7..adb3a72c4f 100644 --- a/src/phpstan/src/Properties/SquashedMigrationHelper.php +++ b/src/phpstan/src/Properties/SquashedMigrationHelper.php @@ -182,7 +182,7 @@ public function getSchemaDirectories(): array } if (empty($this->schemaPaths)) { - $this->schemaPaths = [database_path('schema')]; + return [database_path('schema')]; } return DirectoryResolver::resolve($this->schemaPaths, $this->fileHelper); diff --git a/src/phpstan/src/Support/ConfigParser.php b/src/phpstan/src/Support/ConfigParser.php index 7fe6f34797..7ca3a97b54 100644 --- a/src/phpstan/src/Support/ConfigParser.php +++ b/src/phpstan/src/Support/ConfigParser.php @@ -57,6 +57,7 @@ use function count; use function explode; use function glob; +use function Hypervel\Filesystem\glob_quote; use function implode; use function in_array; use function is_int; @@ -1236,7 +1237,7 @@ private function loadConfigFiles(): void $this->configFiles = $configFiles; if ($this->configSourceResolver->shouldMergeFrameworkConfiguration()) { - foreach (glob(LoadConfiguration::frameworkConfigPath() . '/*.php') ?: [] as $file) { + foreach (glob(glob_quote(LoadConfiguration::frameworkConfigPath()) . '/*.php') ?: [] as $file) { $this->frameworkConfigFiles[basename($file, '.php')] = $this->fileHelper->normalizePath($file); } } diff --git a/src/phpstan/src/Support/DirectoryResolver.php b/src/phpstan/src/Support/DirectoryResolver.php index 617bb42487..d91dccda4b 100644 --- a/src/phpstan/src/Support/DirectoryResolver.php +++ b/src/phpstan/src/Support/DirectoryResolver.php @@ -8,6 +8,7 @@ use function array_values; use function glob; +use function Hypervel\Filesystem\glob_quote_prefix; use function is_dir; use function strpbrk; @@ -27,7 +28,8 @@ class DirectoryResolver * * An existing directory is taken literally, so glob characters in its path are not expanded. * A path without glob characters is kept even if it does not exist, so that creating it can be - * noticed. A glob that matches no directory resolves to nothing. + * noticed. A glob that matches no directory resolves to nothing. Relative patterns treat their + * working directory as literal. * * @param string[] $paths * @@ -38,11 +40,14 @@ public static function resolve(array $paths, FileHelper $fileHelper): array $directories = []; foreach ($paths as $path) { - $path = $fileHelper->absolutizePath($path); + $absolutePath = $fileHelper->absolutizePath($path); - $matches = is_dir($path) || strpbrk($path, '*?[') === false - ? [$path] - : (glob($path, GLOB_ONLYDIR) ?: []); + if (is_dir($absolutePath) || strpbrk($path, '*?[') === false) { + $matches = [$absolutePath]; + } else { + $pattern = $absolutePath === $path ? $path : glob_quote_prefix($absolutePath, $fileHelper->absolutizePath('')); + $matches = glob($pattern, GLOB_ONLYDIR) ?: []; + } foreach ($matches as $directory) { $directory = $fileHelper->normalizePath($directory); diff --git a/src/testbench/src/Bootstrapper.php b/src/testbench/src/Bootstrapper.php index 470a25ea75..10a5e92c5e 100644 --- a/src/testbench/src/Bootstrapper.php +++ b/src/testbench/src/Bootstrapper.php @@ -17,6 +17,8 @@ use SplFileInfo; use Throwable; +use function Hypervel\Filesystem\glob_quote; + class Bootstrapper { protected const string RUNTIME_PROCESS_MARKER = '.testbench-process'; @@ -425,7 +427,7 @@ protected static function purgeStaleRuntimeCopies(string $tempDirectory, int $pi // A dir is stale when its owning PID is dead, reused by this process // without being the active copy, or an identity-matched orphaned // serve master whose parent exited. - foreach (glob($tempDirectory . '/hypervel-components-testbench-*') ?: [] as $staleDirectory) { + foreach (glob(glob_quote($tempDirectory) . '/hypervel-components-testbench-*') ?: [] as $staleDirectory) { if (! $filesystem->isDirectory($staleDirectory)) { continue; } diff --git a/src/testbench/src/Concerns/Database/InteractsWithSqliteDatabaseFile.php b/src/testbench/src/Concerns/Database/InteractsWithSqliteDatabaseFile.php index 727c850b92..8c88088b7c 100644 --- a/src/testbench/src/Concerns/Database/InteractsWithSqliteDatabaseFile.php +++ b/src/testbench/src/Concerns/Database/InteractsWithSqliteDatabaseFile.php @@ -15,6 +15,8 @@ use RuntimeException; use Throwable; +use function Hypervel\Filesystem\glob_quote; + trait InteractsWithSqliteDatabaseFile { use InteractsWithPublishedFiles; @@ -288,9 +290,9 @@ public static function cleanupBackupSqliteDatabaseFilesOnFailed(): void $filesystem->delete( (new Collection([ - ...$filesystem->glob(database_path('database.sqlite*.backup-*')), - ...$filesystem->glob(database_path('database.sqlite-*')), - ...$filesystem->glob(database_path('database.sqlite_test_*')), + ...$filesystem->glob(glob_quote(database_path()) . '/database.sqlite*.backup-*'), + ...$filesystem->glob(glob_quote(database_path()) . '/database.sqlite-*'), + ...$filesystem->glob(glob_quote(database_path()) . '/database.sqlite_test_*'), ]))->filter(static fn ($file) => $filesystem->exists($file)) ->all() ); diff --git a/src/testbench/src/Concerns/InteractsWithPublishedFiles.php b/src/testbench/src/Concerns/InteractsWithPublishedFiles.php index 2b3f999e40..ad62e96ff8 100644 --- a/src/testbench/src/Concerns/InteractsWithPublishedFiles.php +++ b/src/testbench/src/Concerns/InteractsWithPublishedFiles.php @@ -10,6 +10,7 @@ use Symfony\Component\Finder\SplFileInfo; use Throwable; +use function Hypervel\Filesystem\glob_quote; use function Hypervel\Filesystem\join_paths; /** @@ -255,8 +256,9 @@ protected function cleanUpPublishedFiles(): void { $filesystem = $this->app->make(Filesystem::class); $files = (new Collection($this->files ?? [])) - ->transform(fn ($file) => $this->app->basePath($file)) - ->map(fn ($file) => str_contains($file, '*') ? [...$filesystem->glob($file)] : $file) + ->map(fn ($file) => str_contains($file, '*') + ? [...$filesystem->glob(join_paths(glob_quote($this->app->basePath()), $file))] + : $this->app->basePath($file)) ->flatten() ->filter(fn ($file) => $filesystem->exists($file)) ->reject(static fn ($file) => str_ends_with($file, '.gitkeep') || str_ends_with($file, '.gitignore')) @@ -286,7 +288,7 @@ protected function findFirstPublishedMigrationFile(string $filename, ?string $di ? $this->app->basePath($directory) : $this->app->databasePath('migrations'); - return $this->app->make('files')->glob(join_paths($migrationPath, "*{$filename}"))[0] ?? null; + return $this->app->make('files')->glob(join_paths(glob_quote($migrationPath), '*' . glob_quote($filename)))[0] ?? null; } /** diff --git a/src/testbench/src/Foundation/Bootstrap/SyncTestbenchCachedRoutes.php b/src/testbench/src/Foundation/Bootstrap/SyncTestbenchCachedRoutes.php index d907c09ad0..6ab9c83795 100644 --- a/src/testbench/src/Foundation/Bootstrap/SyncTestbenchCachedRoutes.php +++ b/src/testbench/src/Foundation/Bootstrap/SyncTestbenchCachedRoutes.php @@ -8,7 +8,7 @@ use Hypervel\Routing\Router; use Hypervel\Support\Collection; -use function Hypervel\Filesystem\join_paths; +use function Hypervel\Filesystem\glob_quote; class SyncTestbenchCachedRoutes { @@ -19,7 +19,7 @@ public function bootstrap(Application $app): void { /** @var Router $router */ $router = $app->make('router'); - $routeFiles = glob($app->basePath(join_paths('routes', 'testbench-*.php'))) ?: []; + $routeFiles = glob(glob_quote($app->basePath('routes')) . '/testbench-*.php') ?: []; (new Collection($routeFiles)) ->each(static function ($routeFile) use ($app, $router) { diff --git a/src/testbench/src/Foundation/Console/DropSqliteDbCommand.php b/src/testbench/src/Foundation/Console/DropSqliteDbCommand.php index 3506527eca..e1ef54ecca 100644 --- a/src/testbench/src/Foundation/Console/DropSqliteDbCommand.php +++ b/src/testbench/src/Foundation/Console/DropSqliteDbCommand.php @@ -10,6 +10,7 @@ use Hypervel\Testbench\Foundation\Console\Actions\DeleteFiles; use Symfony\Component\Console\Attribute\AsCommand; +use function Hypervel\Filesystem\glob_quote; use function Hypervel\Filesystem\join_paths; #[AsCommand(name: 'package:drop-sqlite-db', description: 'Drop sqlite database file')] @@ -39,7 +40,7 @@ public function handle(Filesystem $filesystem): int pretending: $pretending, ))->handle( match ($this->option('all')) { - true => [...$filesystem->glob(join_paths($databasePath, '*.sqlite'))], + true => [...$filesystem->glob(glob_quote($databasePath) . '/*.sqlite')], default => [join_paths($databasePath, $this->databaseName())], } ); diff --git a/src/testbench/src/Foundation/Console/PurgeSkeletonCommand.php b/src/testbench/src/Foundation/Console/PurgeSkeletonCommand.php index 5c5cd934cc..b471e2dfba 100644 --- a/src/testbench/src/Foundation/Console/PurgeSkeletonCommand.php +++ b/src/testbench/src/Foundation/Console/PurgeSkeletonCommand.php @@ -15,6 +15,7 @@ use Symfony\Component\Console\Attribute\AsCommand; use Throwable; +use function Hypervel\Filesystem\glob_quote; use function Hypervel\Filesystem\join_paths; #[AsCommand(name: 'package:purge-skeleton', description: 'Purge skeleton folder to original state')] @@ -83,10 +84,10 @@ public function handle(Filesystem $filesystem, ConfigContract $config): int ))->handle( (new LazyCollection(function () use ($filesystem) { yield $this->hypervel->databasePath('database.sqlite'); - yield $filesystem->glob($this->hypervel->basePath(join_paths('routes', 'testbench-*.php'))); - yield $filesystem->glob($this->hypervel->storagePath(join_paths('app', 'public', '*'))); - yield $filesystem->glob($this->hypervel->storagePath(join_paths('app', '*'))); - yield $filesystem->glob($this->hypervel->storagePath(join_paths('framework', 'sessions', '*'))); + yield $filesystem->glob(glob_quote($this->hypervel->basePath('routes')) . '/testbench-*.php'); + yield $filesystem->glob(glob_quote($this->hypervel->storagePath('app/public')) . '/*'); + yield $filesystem->glob(glob_quote($this->hypervel->storagePath('app')) . '/*'); + yield $filesystem->glob(glob_quote($this->hypervel->storagePath('framework/sessions')) . '/*'); }))->flatten() )); @@ -96,10 +97,10 @@ public function handle(Filesystem $filesystem, ConfigContract $config): int pretending: $pretending, ))->handle( (new LazyCollection($files)) - ->map(fn (string $file) => $this->hypervel->basePath($file)) - ->map(static fn (string $file) => str_contains($file, '*') ? [...$filesystem->glob($file)] : $file) + ->map(fn (string $file) => str_contains($file, '*') + ? [...$filesystem->glob(join_paths(glob_quote($this->hypervel->basePath()), $file))] + : $this->hypervel->basePath($file)) ->flatten() - ->reject(static fn (string $file) => str_contains($file, '*')) )); $run(fn () => (new Actions\DeleteDirectories( @@ -108,10 +109,10 @@ public function handle(Filesystem $filesystem, ConfigContract $config): int pretending: $pretending, ))->handle( (new Collection($directories)) - ->map(fn (string $directory) => $this->hypervel->basePath($directory)) - ->map(static fn (string $directory) => str_contains($directory, '*') ? [...$filesystem->glob($directory)] : $directory) + ->map(fn (string $directory) => str_contains($directory, '*') + ? [...$filesystem->glob(join_paths(glob_quote($this->hypervel->basePath()), $directory))] + : $this->hypervel->basePath($directory)) ->flatten() - ->reject(static fn (string $directory) => str_contains($directory, '*')) )); if (! $pretending) { diff --git a/src/testing/src/Console/TestCommandBase.php b/src/testing/src/Console/TestCommandBase.php index 3fbc7f5960..b9a6c33296 100644 --- a/src/testing/src/Console/TestCommandBase.php +++ b/src/testing/src/Console/TestCommandBase.php @@ -26,6 +26,7 @@ use Symfony\Component\Process\Process; use Throwable; +use function Hypervel\Filesystem\glob_quote; use function Hypervel\Filesystem\join_paths; abstract class TestCommandBase extends Command @@ -598,7 +599,7 @@ protected function reportProfile(): void $tests = []; - foreach (glob($directory . DIRECTORY_SEPARATOR . 'profile-*.json') ?: [] as $path) { + foreach (glob(glob_quote($directory) . DIRECTORY_SEPARATOR . 'profile-*.json') ?: [] as $path) { /** @var array $workerTests */ $workerTests = json_decode((string) file_get_contents($path), associative: true, flags: JSON_THROW_ON_ERROR); $tests = array_merge($tests, $workerTests); @@ -633,7 +634,7 @@ protected function cleanupProfileDirectory(): void return; } - foreach (glob($profileDirectory . DIRECTORY_SEPARATOR . '*') ?: [] as $path) { + foreach (glob(glob_quote($profileDirectory) . DIRECTORY_SEPARATOR . '*') ?: [] as $path) { if (is_file($path)) { unlink($path); } diff --git a/tests/Benchmarks/Sentry/setup-app.sh b/tests/Benchmarks/Sentry/setup-app.sh index 1c2389fdf0..6ba638252a 100755 --- a/tests/Benchmarks/Sentry/setup-app.sh +++ b/tests/Benchmarks/Sentry/setup-app.sh @@ -23,17 +23,22 @@ mkdir -p "$app" git -C "$skeleton" archive HEAD | tar -x -C "$app" cp -R "$harness/Fixtures/app/." "$app/" -versions=$(php -r ' +cd "$app" +php -r ' + require $argv[3] . "/../../../src/filesystem/src/functions.php"; + $sourcePattern = Hypervel\Filesystem\glob_quote($argv[1]) . "/src/*"; $versions = []; - foreach (glob($argv[1] . "/src/*/composer.json") as $file) { + foreach (glob($sourcePattern . "/composer.json") as $file) { $versions[json_decode(file_get_contents($file), true)["name"]] = "0.4.x-dev"; } - echo json_encode($versions, JSON_UNESCAPED_SLASHES); -' "$components") - -cd "$app" -composer config repositories.framework "{\"type\":\"path\",\"url\":\"$framework\",\"options\":{\"symlink\":true}}" -composer config repositories.components "{\"type\":\"path\",\"url\":\"$components/src/*\",\"options\":{\"symlink\":true,\"versions\":$versions}}" + $manifest = json_decode(file_get_contents("composer.json"), true, flags: JSON_THROW_ON_ERROR); + $manifest["repositories"] = [ + "components" => ["type" => "path", "url" => $sourcePattern, "options" => ["symlink" => true, "versions" => $versions]], + "framework" => ["type" => "path", "url" => Hypervel\Filesystem\glob_quote($argv[2]), "options" => ["symlink" => true]], + ...($manifest["repositories"] ?? []), + ]; + file_put_contents("composer.json", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n"); +' "$components" "$framework" "$harness" composer require hypervel/sentry:0.4.x-dev --no-update -n php -r ' diff --git a/tests/Composer/PackageManifestConsistencyTest.php b/tests/Composer/PackageManifestConsistencyTest.php index 18104dda44..4ca5151bc6 100644 --- a/tests/Composer/PackageManifestConsistencyTest.php +++ b/tests/Composer/PackageManifestConsistencyTest.php @@ -10,6 +10,8 @@ use Hypervel\Tests\TestCase; use JsonException; +use function Hypervel\Filesystem\glob_quote; + /** * Enforce root-checkable Composer structures without constraining package-specific metadata. */ @@ -159,7 +161,7 @@ private function decodeManifest(string $path): array */ private function splitManifests(): array { - $manifests = glob(__DIR__ . '/../../src/*/composer.json'); + $manifests = glob(glob_quote(dirname(__DIR__, 2)) . '/src/*/composer.json'); $this->assertNotFalse($manifests); diff --git a/tests/Data/Support/Validation/ValidationRuleFactoryTest.php b/tests/Data/Support/Validation/ValidationRuleFactoryTest.php index 01e65d3b33..77e3ce5439 100644 --- a/tests/Data/Support/Validation/ValidationRuleFactoryTest.php +++ b/tests/Data/Support/Validation/ValidationRuleFactoryTest.php @@ -14,13 +14,15 @@ use Hypervel\Validation\Rule; use ReflectionClass; +use function Hypervel\Filesystem\glob_quote; + class ValidationRuleFactoryTest extends TestCase { public function testMapsEveryValidationAttributeByItsKeyword(): void { $expected = []; - foreach (glob(dirname(__DIR__, 4) . '/src/data/src/Attributes/Validation/*.php') as $file) { + foreach (glob(glob_quote(dirname(__DIR__, 4)) . '/src/data/src/Attributes/Validation/*.php') as $file) { $class = 'Hypervel\Data\Attributes\Validation\\' . basename($file, '.php'); $reflection = new ReflectionClass($class); diff --git a/tests/Database/DatabaseMigratorIntegrationTest.php b/tests/Database/DatabaseMigratorIntegrationTest.php index 1174d8dece..ecd778f22e 100644 --- a/tests/Database/DatabaseMigratorIntegrationTest.php +++ b/tests/Database/DatabaseMigratorIntegrationTest.php @@ -12,6 +12,7 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; +use Hypervel\Testing\ParallelTesting; use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; @@ -257,6 +258,27 @@ public function testMigrationsCanBeProperlySortedAcrossMultiplePaths(): void $this->assertEquals($expected, $migrationsFilesFullPaths); } + public function testMigrationDiscoveryDistinguishesLiteralDirectoriesFromPatterns(): void + { + $root = ParallelTesting::tempDir('migration-glob'); + $filesystem = new Filesystem; + $literal = $root . '/project [a]'; + $other = $root . '/project a'; + $filename = '2026_01_01_000000_example.php'; + + try { + foreach ([$literal, $other] as $directory) { + $filesystem->ensureDirectoryExists($directory); + touch($directory . '/' . $filename); + } + + $this->assertSame([$literal . '/' . $filename], array_values($this->migrator->getMigrationFiles($literal))); + $this->assertSame([$other . '/' . $filename], array_values($this->migrator->getMigrationFiles($root . '/project ?'))); + } finally { + $filesystem->deleteDirectory($root); + } + } + public function testConnectionPriorToMigrationIsNotChangedAfterMigration(): void { $this->migrator->setConnection('default'); diff --git a/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php b/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php index 3316b00891..6def82f8eb 100644 --- a/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php +++ b/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php @@ -66,6 +66,22 @@ public function testReportsPendingMigrations(): void } } + public function testDoesNotReportMigrationsFromALookalikeDatabaseDirectory(): void + { + $root = ParallelTesting::tempDir('DoctorMigrationPaths'); + File::deleteDirectory($root); + + try { + File::ensureDirectoryExists($root . '/database a/migrations'); + touch($root . '/database a/migrations/2024_01_01_000000_other_project.php'); + $this->app->useDatabasePath($root . '/database [a]'); + + $this->assertSame('The application does not have migration files.', (new MigrationsAreUpToDate)->check()->summary); + } finally { + File::deleteDirectory($root); + } + } + public function testOffersToCreateTheMigrationRepositoryLocally(): void { $this->app->instance('migrator', new class { diff --git a/tests/Filesystem/GlobQuoteHelperTest.php b/tests/Filesystem/GlobQuoteHelperTest.php new file mode 100644 index 0000000000..bca897f1f1 --- /dev/null +++ b/tests/Filesystem/GlobQuoteHelperTest.php @@ -0,0 +1,41 @@ +assertSame('/app \[a]/*', glob_quote_prefix('/app [a]/*', '/app [a]/')); + $this->assertSame('/app [a]-old/*', glob_quote_prefix('/app [a]-old/*', '/app [a]')); + } + + public function testQuotedNamesMatchLiterallyWithinAPattern(): void + { + $directory = ParallelTesting::tempDir('glob-quote'); + $files = new Filesystem; + $files->ensureDirectoryExists($directory); + + try { + foreach (['[a]', 'a', 'x*?', 'xyz', 'name\\', 'name', '{x,y}', 'x', 'y'] as $name) { + touch($directory . '/' . $name . '.txt'); + } + + foreach (['[a]', 'x*?', 'name\\', '{x,y}'] as $name) { + $path = $directory . '/' . $name; + $this->assertSame([$path . '.txt'], glob(glob_quote($path) . '.*', defined('GLOB_BRACE') ? GLOB_BRACE : 0)); + } + } finally { + $files->deleteDirectory($directory); + } + } +} diff --git a/tests/Foundation/Console/AboutCommandTest.php b/tests/Foundation/Console/AboutCommandTest.php index eb4954f57e..33701dcaa2 100644 --- a/tests/Foundation/Console/AboutCommandTest.php +++ b/tests/Foundation/Console/AboutCommandTest.php @@ -56,8 +56,8 @@ public function testItReportsNoPhpFilesWhenGlobCannotEnumerateThePath(): void class TestableAboutCommand extends AboutCommand { - public function hasPhpFiles(string $path, string $extension = 'php'): bool + public function hasPhpFiles(string $path): bool { - return parent::hasPhpFiles($path, $extension); + return parent::hasPhpFiles($path); } } diff --git a/tests/Foundation/Support/Providers/EventServiceProviderTest.php b/tests/Foundation/Support/Providers/EventServiceProviderTest.php index 6ffc92b5d8..d079ab86b2 100644 --- a/tests/Foundation/Support/Providers/EventServiceProviderTest.php +++ b/tests/Foundation/Support/Providers/EventServiceProviderTest.php @@ -6,9 +6,12 @@ use Hypervel\Auth\Events\Registered; use Hypervel\Auth\Listeners\SendEmailVerificationNotification; +use Hypervel\Filesystem\Filesystem; +use Hypervel\Foundation\Events\DiscoverEvents; use Hypervel\Foundation\Support\Providers\EventServiceProvider; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; +use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventOne; use Hypervel\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\AbstractListener; use Hypervel\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\Listener; @@ -136,6 +139,31 @@ public function testSetEventDiscoveryPaths(): void $this->assertSame(['/custom/path'], $paths); } + public function testDiscoversListenersFromAWildcardUnderALiteralBasePath(): void + { + $base = $this->app->basePath(); + $project = ParallelTesting::tempDir('EventDiscovery [a]'); + $files = new Filesystem; + $files->deleteDirectory($project); + + try { + mkdir($project . '/bootstrap', recursive: true); + mkdir($project . '/app/Domain/Billing/Listeners', recursive: true); + touch($project . '/app/Domain/Billing/Listeners/Listener.php'); + + $this->app->setBasePath($project); + DiscoverEvents::guessClassNamesUsing(fn () => Listener::class); + EventServiceProvider::setEventDiscoveryPaths([$project . '/bootstrap/../app/Domain/*/Listeners']); + + $events = (new EventServiceProvider($this->app))->discoverEvents(); + + $this->assertContains(Listener::class . '@handle', $events[EventOne::class] ?? []); + } finally { + $this->app->setBasePath($base); + $files->deleteDirectory($project); + } + } + public function testAddEventDiscoveryPaths(): void { EventServiceProvider::setEventDiscoveryPaths(['/first/path']); diff --git a/tests/Integration/Migration/StatusCommandTest.php b/tests/Integration/Migration/StatusCommandTest.php index 2ee83f6a53..b7b1e5804e 100644 --- a/tests/Integration/Migration/StatusCommandTest.php +++ b/tests/Integration/Migration/StatusCommandTest.php @@ -4,9 +4,11 @@ namespace Hypervel\Tests\Integration\Migration; +use Hypervel\Filesystem\Filesystem; use Hypervel\Support\Facades\Schema; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; +use Hypervel\Testing\ParallelTesting; #[WithConfig('database.default', 'sqlite')] #[WithConfig('database.connections.sqlite.database', ':memory:')] @@ -30,6 +32,36 @@ public function testMigrationsThatShouldNotRunAreReportedAsSkipped(): void ->assertSuccessful(); } + public function testMigrationDiscoveryKeepsTheApplicationRootLiteral(): void + { + $base = $this->app->basePath(); + $database = $this->app->databasePath(); + $root = ParallelTesting::tempDir('MigrationStatusPaths'); + $project = $root . '/project [a]'; + $migration = '2024_01_01_000000_create_airlines_table.php'; + $files = new Filesystem; + $files->deleteDirectory($root); + + try { + mkdir($project . '/modules/flight', recursive: true); + mkdir($root . '/project a/database/migrations', recursive: true); + copy(__DIR__ . '/Fixtures/status/' . $migration, $project . '/modules/flight/' . $migration); + copy(__DIR__ . '/Fixtures/status/' . $migration, $root . '/project a/database/migrations/' . $migration); + + $this->app->setBasePath($project)->useDatabasePath($project . '/database'); + $this->artisan('migrate:status')->expectsOutputToContain('No migrations found')->assertSuccessful(); + + foreach (['modules/*', 'modules/flight/' . $migration] as $path) { + $this->artisan('migrate:status', ['--path' => [$path]]) + ->expectsOutputToContain('2024_01_01_000000_create_airlines_table') + ->assertSuccessful(); + } + } finally { + $this->app->setBasePath($base)->useDatabasePath($database); + $files->deleteDirectory($root); + } + } + public function testSkippedMigrationsAreNotConsideredPending(): void { $this->app->make('migrator')->run([__DIR__ . '/../../Database/Fixtures/Migrator']); diff --git a/tests/PHPStan/Unit/MigrationHelperTest.php b/tests/PHPStan/Unit/MigrationHelperTest.php index 066d39a7da..b3a583b765 100644 --- a/tests/PHPStan/Unit/MigrationHelperTest.php +++ b/tests/PHPStan/Unit/MigrationHelperTest.php @@ -5,9 +5,11 @@ namespace Hypervel\Tests\PHPStan\Unit; use Hypervel\Database\Schema\Blueprint; +use Hypervel\Filesystem\Filesystem; use Hypervel\PHPStan\Properties\ConnectionConfigResolver; use Hypervel\PHPStan\Properties\SchemaConnection; use Hypervel\PHPStan\Schema\BlueprintMacroExtension; +use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\PHPStan\Fixtures\Bootstrap\Billing\BillingBlueprintMacros; use Hypervel\Tests\PHPStan\Fixtures\Bootstrap\Billing\BillingSchema; use Hypervel\Tests\PHPStan\Fixtures\CreatesMigrationHelpers; @@ -90,6 +92,29 @@ public function itKeepsAMigrationDirectoryThatDoesNotExist(): void self::assertSame([], $migrationHelper->getMigrationFiles()); } + #[Test] + public function itDoesNotReadALookalikeDirectoryWhenTheDefaultIsMissing(): void + { + $root = ParallelTesting::tempDir('AnalyzerMigrationPaths'); + $files = new Filesystem; + $files->deleteDirectory($root); + $database = database_path(); + + try { + $files->ensureDirectoryExists($root . '/database a/migrations'); + $unrelated = $root . '/database a/migrations/2024_01_01_000000_other_project.php'; + touch($unrelated); + app()->useDatabasePath($root . '/database [a]'); + + $helper = $this->createMigrationHelper(); + $this->assertArrayHasKey(database_path('migrations'), $helper->getMigrationPaths()); + $this->assertNotContains($unrelated, array_map(strval(...), $helper->getMigrationFiles())); + } finally { + app()->useDatabasePath($database); + $files->deleteDirectory($root); + } + } + #[Test] public function itHasNoMigrationDirectoriesWhenTheMigrationScanIsDisabled(): void { diff --git a/tests/PHPStan/Unit/Support/DirectoryResolverTest.php b/tests/PHPStan/Unit/Support/DirectoryResolverTest.php index 860f17f529..db5110bfd2 100644 --- a/tests/PHPStan/Unit/Support/DirectoryResolverTest.php +++ b/tests/PHPStan/Unit/Support/DirectoryResolverTest.php @@ -51,6 +51,17 @@ public function itKeepsAPathWithoutGlobCharactersEvenIfItDoesNotExist(): void ); } + #[Test] + public function itExpandsOnlyTheConfiguredPartOfARelativePattern(): void + { + $workingDirectory = $this->root . '/[literal]'; + mkdir($workingDirectory . '/migrations'); + $this->assertSame( + [$workingDirectory . '/migrations', $workingDirectory . '/missing'], + DirectoryResolver::resolve(['mig*', 'missing'], new FileHelper($workingDirectory)), + ); + } + #[Test] public function itExpandsAGlobToTheDirectoriesItMatches(): void { diff --git a/tests/Testing/PackageMetadataTest.php b/tests/Testing/PackageMetadataTest.php index e1706b13ab..eb7748eb28 100644 --- a/tests/Testing/PackageMetadataTest.php +++ b/tests/Testing/PackageMetadataTest.php @@ -8,6 +8,8 @@ use Hypervel\Tests\TestCase; use JsonException; +use function Hypervel\Filesystem\glob_quote; + class PackageMetadataTest extends TestCase { /** @@ -95,7 +97,7 @@ public function testGuaranteedCoreExtensionsAreNotDeclared(): void { $paths = array_merge( [__DIR__ . '/../../composer.json'], - glob(__DIR__ . '/../../src/*/composer.json') ?: [], + glob(glob_quote(dirname(__DIR__, 2)) . '/src/*/composer.json') ?: [], ); foreach ($paths as $path) { From 2b87afd47847b120663b1bea1e4d2aa103f94645 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:59:26 +0000 Subject: [PATCH 03/19] Bound numeric string length before validation arithmetic Limit trimmed numeric inputs to 4,096 characters at the guard shared by compiled and delegated arithmetic rules. This bounds the length of a submitted mantissa before arbitrary-precision arithmetic can occupy a worker. The existing exponent policy still governs expansion, including larger exponents explicitly authorized by an application. Keep syntax-only numeric validation and developer-supplied rule literals unchanged. Document the limit and exercise both sides of the boundary for size checks, ordered comparisons and multiple_of. Comparisons also check the referenced field. The Validation suite passes all 2,190 tests with 8,350 assertions. --- src/docs/validation.md | 2 ++ .../src/Concerns/ReplacesAttributes.php | 2 +- .../src/Concerns/ValidatesAttributes.php | 8 +++++- .../ValidationCompiledExecutionTest.php | 26 +++++++++++++++++-- 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/docs/validation.md b/src/docs/validation.md index af7353640a..1fc92bb25e 100644 --- a/src/docs/validation.md +++ b/src/docs/validation.md @@ -2671,6 +2671,8 @@ You may use the `strict` parameter to only consider the field valid if its value 'amount' => ['numeric:strict'] ``` +When evaluating numeric values, the `size`, `min`, `max`, `between`, `gt`, `gte`, `lt`, `lte`, and `multiple_of` rules reject submitted numeric strings longer than 4,096 characters. The limit applies after trimming surrounding whitespace and includes any sign, decimal point, and exponent as written. + For convenience, numeric rules may also be constructed using the fluent `numeric` rule builder: ```php diff --git a/src/validation/src/Concerns/ReplacesAttributes.php b/src/validation/src/Concerns/ReplacesAttributes.php index 734f0ad380..d70f1e0deb 100644 --- a/src/validation/src/Concerns/ReplacesAttributes.php +++ b/src/validation/src/Concerns/ReplacesAttributes.php @@ -470,7 +470,7 @@ protected function replaceGt(string $message, string $attribute, string $rule, a try { $size = $this->getSize($attribute, $value); } catch (MathException) { - // Rejected exponents fail validation; rendering their message must not throw. + // A numeric limit can reject the comparison value while its message is being rendered. $size = $this->trim($value); } diff --git a/src/validation/src/Concerns/ValidatesAttributes.php b/src/validation/src/Concerns/ValidatesAttributes.php index df03306389..2497143a03 100644 --- a/src/validation/src/Concerns/ValidatesAttributes.php +++ b/src/validation/src/Concerns/ValidatesAttributes.php @@ -48,6 +48,8 @@ trait ValidatesAttributes { + private const int MAX_NUMERIC_LENGTH = 4096; + /** * Validate that an attribute was "accepted". * @@ -3212,7 +3214,7 @@ private function prepareNumericValue(mixed $value): mixed } /** - * Ensure the exponent is within the allowed range. + * Ensure the numeric input's written length and exponent are within the allowed range. */ protected function ensureExponentWithinAllowedRange(string $attribute, mixed $value): mixed { @@ -3220,6 +3222,10 @@ protected function ensureExponentWithinAllowedRange(string $attribute, mixed $va return $value; } + if (is_string($value) && strlen($value) > self::MAX_NUMERIC_LENGTH) { + throw new MathException('Numeric input exceeds the maximum length for arithmetic validation.'); + } + if (is_float($value)) { if (! is_finite($value)) { return Number::toString($value); diff --git a/tests/Validation/ValidationCompiledExecutionTest.php b/tests/Validation/ValidationCompiledExecutionTest.php index ba30495a4e..554ebf8ba0 100644 --- a/tests/Validation/ValidationCompiledExecutionTest.php +++ b/tests/Validation/ValidationCompiledExecutionTest.php @@ -480,10 +480,32 @@ public function testNumericInputBeyondTheDefaultExponentRangeFailsValidation(): } } + public function testNumericArithmeticLimitsTheWrittenLengthOfEitherInput(): void + { + $withinLimit = '+' . str_repeat('0', 4094) . '1'; + $oversized = '+' . str_repeat('0', 4095) . '1'; + + foreach ([Validator::class, DelegatedValidationValidator::class] as $validatorClass) { + $passes = fn (array $data, array $rules): bool => $this->makeValidator($data, ['value' => $rules], validatorClass: $validatorClass)->passes(); + + $this->assertTrue($passes(['value' => $oversized], ['numeric'])); + + foreach (['size:1', 'min:1', 'max:1', 'between:1,1', 'multiple_of:1', 'gt:lower', 'gte:lower', 'lt:upper', 'lte:upper'] as $rule) { + $this->assertTrue($passes(['value' => " {$withinLimit} ", 'lower' => 0, 'upper' => 2], ['numeric', $rule]), $rule); + $this->assertFalse($passes(['value' => " {$oversized} ", 'lower' => 0, 'upper' => 2], ['numeric', $rule]), $rule); + } + + foreach (['gt' => 2, 'gte' => 1, 'lt' => 0, 'lte' => 1] as $rule => $value) { + $this->assertTrue($passes(['value' => $value, 'other' => " {$withinLimit} "], ['numeric', $rule . ':other']), $rule); + $this->assertFalse($passes(['value' => $value, 'other' => " {$oversized} "], ['numeric', $rule . ':other']), $rule); + } + } + } + public function testMultipleOfHonorsExponentOverridesWithoutRestrictingRuleLiterals(): void { foreach ([Validator::class, DelegatedValidationValidator::class] as $validatorClass) { - $validator = $this->makeValidator(['value' => '1e1001'], ['value' => 'multiple_of:1'], validatorClass: $validatorClass); + $validator = $this->makeValidator(['value' => '1e5000'], ['value' => 'multiple_of:1'], validatorClass: $validatorClass); $arguments = []; $validator->ensureExponentWithinAllowedRangeUsing(function (...$values) use (&$arguments): bool { $arguments[] = $values; @@ -492,7 +514,7 @@ public function testMultipleOfHonorsExponentOverridesWithoutRestrictingRuleLiter }); $this->assertTrue($validator->passes()); - $this->assertSame([[1001, 'value', '1e1001']], $arguments); + $this->assertSame([[5000, 'value', '1e5000']], $arguments); $this->assertTrue($this->makeValidator(['value' => 0], ['value' => 'multiple_of:1e1001'], validatorClass: $validatorClass)->passes()); } } From cea5da5aff885adf1b7c4cdd28e7c9c029984334 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:59:26 +0000 Subject: [PATCH 04/19] Document MariaDB 10.11.6 as the minimum supported version Hypervel uses native MariaDB UUID columns and generates UUIDv7 keys. MariaDB 10.11.4 can return those keys in the wrong chronological order. Version 10.11.5 fixed on-disk ordering but can still miss a matching row when evaluating a UUID range predicate. Verified native ordering and comparisons against 10.11.4, 10.11.5 and 10.11.6. The last release passed both checks. Update the canonical support list to reflect the patch that fixed MDEV-31926. --- src/docs/database.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/database.md b/src/docs/database.md index fa3fe4fa5c..408c1bbe9d 100644 --- a/src/docs/database.md +++ b/src/docs/database.md @@ -39,7 +39,7 @@ Almost every modern web application interacts with a database. Hypervel makes in
-- MariaDB 10.11+ ([Version Policy](https://mariadb.org/about/#maintenance-policy)) +- MariaDB 10.11.6+ ([Version Policy](https://mariadb.org/about/#maintenance-policy)) - MySQL 5.7+ ([Version Policy](https://en.wikipedia.org/wiki/MySQL#Release_history)) - PostgreSQL 10.0+ ([Version Policy](https://www.postgresql.org/support/versioning/)) - SQLite 3.32.0+ From 6ee26b0aa140264a2f1f16bb43244ac4a1f43c76 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:59:26 +0000 Subject: [PATCH 05/19] Close the numeric validation and conversation query investigations The shared written-length guard resolves the validation item while preserving the application's exponent policy. Remove the stale dependency prerequisite and the completed conversation query task. Tested the stock AI migration on MySQL 9.7.4, PostgreSQL 19.0, MariaDB 10.11.19 and SQLite 3.45.1 with clustered and interleaved histories. Checked the store's generated SQL and native bindings. On a 300,000-message fixture, MySQL read 291,100 primary-key entries for 100 messages when the oldest conversation held 3% of rows. PostgreSQL filtered 270,000 at a 10% share. The existing composite index was available on both engines. A scalar ID bound helped some clustered histories and slowed smaller conversations and cursor pages. Forcing the MySQL composite index cut resumed-history latency from 282.66 to 1.43 ms but increased recent dense-history latency from 0.68 to 1.33 ms. On PostgreSQL a UUID-cast scalar parameter improved the resumed case by hiding selectivity from the planner and assumed a native UUID column. A descending index did not resolve the scans. Keep the current SQL and indexes as the general default and close the measured investigation with that limitation. --- docs/todo.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/docs/todo.md b/docs/todo.md index 07db0872bb..67bd55c694 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -21,10 +21,6 @@ - Add native return types to the `test*` methods that lack them: about 5,600 methods in 490 files. `AGENTS.md` requires `: void` on test methods; a test that returns a value for `#[Depends]` takes its actual return type instead. Make the change as one approved sweep and add an automated check for missing test method return types. - Integrate the resolution of [PHPUnit #7039](https://github.com/sebastianbergmann/phpunit/issues/7039) into `RunTestsInCoroutine` once PHPUnit 13.5 is released ([scheduled for December 4, 2026](https://github.com/sebastianbergmann/phpunit/blob/main/ChangeLog-13.5.md)); it adds `TestCase::suspendOutputBuffering()` and `resumeOutputBuffering()` ([PR #7040](https://github.com/sebastianbergmann/phpunit/pull/7040)). Follow the merged upstream design, including calling `parent::invokeTestMethod()` if capture is handled there. Add regression coverage for output expectations, flushed output and buffer cleanup; update the testing guidance and reassess output-related coroutine opt-outs. Lift the `~13.4.3` PHPUnit constraints in the root, Testbench and dogfood manifests, the testing package's suggestion and the `hypervel/hypervel` skeleton once Testbench's PHPUnit integration is verified on 13.5. Do not add a private-buffer adapter, maintained fork or ongoing Composer/vendor patches. Prefer supported subclass or method overrides; use AOP only as an absolute last resort. Never document a confirmed defect as an accepted limitation. -## AI and MCP - -- Revisit conversation-history query plans when production evidence or newer database versions warrant it; this does not block the AI port. Reproduce with the stock migration, one oldest conversation containing 10,000 messages, then 999 other participants/conversations with 20 newer messages each. After updating statistics, inspect actual execution of `DatabaseConversationStore::latestConversationId()`, `getLatestConversationMessages(..., 100)` and the first/subsequent cursor pages. MySQL 9.5 and PostgreSQL chose reverse primary-key scans, examining 20,080 rows for 100 messages despite `(conversation_id, id)` being available; smaller targets at roughly 1% of the table used conversation indexes and did not scan other conversations. MariaDB 10.11 read history efficiently but filtered cursor IDs after seeking only the conversation, scanning preceding pages within it; SQLite 3.45 used both index bounds. The query shape matches Laravel's. Selecting IDs first, including through a bounded subquery joined back to messages, did not fix the MySQL/PostgreSQL plans. Include the similar latest-row queries in `pendingApprovalsFor()` and `pausedRowFor()` when investigating; their execution plans have not been measured. Test an index-derived scalar upper bound on message IDs with both oldest-only and interleaved conversations. A stored pointer needs maintenance across all supported writes; a stale low pointer would hide messages. Keep current queries and indexes unless a measured improvement preserves other workloads, configured/partitioned schemas and pagination behavior without unnecessary round trips or database-specific machinery. - ## HTTP Client - When a Swoole HTTP transport is available, compare it with cURL under concurrent Inertia SSR requests to a local server through the `inertia-ssr` connection. @@ -42,10 +38,6 @@ - Port `spatie/typescript-transformer` as a general first-party Hypervel package, then add an optional Hypervel Data adapter that recognizes data classes and their existing mapping, Optional, lazy, and collection metadata. Keep TypeScript generation outside `hypervel/data`: the transformer must also support ordinary PHP classes and enums without making runtime data construction depend on filesystem discovery or code generation. -## Validation - -- Adopt Brick Math 0.20's bounded parsing API for untrusted numeric validation inputs once the supported dependency graph permits it. Ramsey UUID currently limits Brick Math to 0.18, which has neither bounded parsing nor 0.20's parser-backtracking fix, so an intermediate upgrade would not address this issue. Preserve the configurable exponent-range behavior and cover delegated and compiled rules, oversized mantissas and exponents, malformed input, and `multiple_of`; do not add a local parsing workaround or disguise an incompatible Brick version with a Composer alias. - ## Sentry - Once a released Excimer includes `ExcimerProfiler::setSampleFilter()` ([Excimer change 1354126](https://gerrit.wikimedia.org/r/c/mediawiki/php/excimer/+/1354126)), compare native filtering with the transaction collector under concurrent load. Preserve request context ownership, idle intervals and SDK drop reporting. From 731001cd2914d498b34ce74673d0053cf8f44035 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:53:21 +0000 Subject: [PATCH 06/19] Exercise the broadcast facade against a live Reverb server Send an event through the configured Reverb broadcaster and assert the full frame received by each of three WebSocket subscribers. This covers the public broadcasting API, its HTTP publishing request, and delivery to the channel in one test. Use the existing Reverb CI fixture and update its comments to reflect worker startup and the single-worker queue fake. Verified with the live server suite and a focused ParaTest run. --- tests/Integration/Reverb/Fixtures/server.php | 10 +--- tests/Integration/Reverb/ServerTest.php | 52 +++++++++++++------- 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/tests/Integration/Reverb/Fixtures/server.php b/tests/Integration/Reverb/Fixtures/server.php index 20f87caa64..a16bcba84d 100644 --- a/tests/Integration/Reverb/Fixtures/server.php +++ b/tests/Integration/Reverb/Fixtures/server.php @@ -63,10 +63,7 @@ $workerNum = (int) (Env::get('REVERB_TEST_WORKER_NUM') ?: 1); $label = $scaling ? 'Reverb Redis test server' : ($workerNum > 1 ? "Reverb multi-worker test server ({$workerNum} workers)" : 'Reverb test server'); -// Set Reverb app env vars BEFORE boot so the config file picks them up. -// These survive the worker-start config reload because the reload re-reads -// environment values while rebuilding configuration from disk. -// Only set defaults — don't override values already set by the caller. +// Supply defaults before the application loads its Reverb configuration. $defaults = [ 'REVERB_APP_KEY' => 'reverb-key', 'REVERB_APP_SECRET' => 'reverb-secret', @@ -108,8 +105,7 @@ $disabledRateLimiting = array_replace($baseApplication['rate_limiting'], ['enabled' => false]); $disabledWebhooks = array_replace($baseApplication['webhooks'], ['url' => null]); -// Webhook inspection only works with worker_num=1 (no fork). -// Queue::fake() creates an in-memory fake that doesn't survive forking. +// Webhook delivery and inspection need a single worker so they share the same in-memory queue fake. if ($workerNum === 1) { $config->set('reverb.apps.apps.0.webhooks', array_replace($baseApplication['webhooks'], [ 'url' => 'https://example.com/webhook', @@ -122,8 +118,6 @@ } // Add additional test apps (env vars only support one app). -// Boot-time configuration mutations are tracked automatically and survive -// the worker-start configuration rebuild. $config->set('reverb.apps.apps.1', array_replace($baseApplication, [ 'key' => 'reverb-key-2', 'secret' => 'reverb-secret-2', diff --git a/tests/Integration/Reverb/ServerTest.php b/tests/Integration/Reverb/ServerTest.php index 684206abd1..a3c5b9a705 100644 --- a/tests/Integration/Reverb/ServerTest.php +++ b/tests/Integration/Reverb/ServerTest.php @@ -4,6 +4,8 @@ namespace Hypervel\Tests\Integration\Reverb; +use Hypervel\Support\Facades\Broadcast; +use Hypervel\Testbench\Foundation\Application as TestbenchApplication; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Coroutine\Http\Client; @@ -363,28 +365,44 @@ public function testLimitsTheLengthOfChannelNames(): void // ── Broadcasting ─────────────────────────────────────────────────── - public function testCanReceiveABroadcastFromTheServer(): void + public function testCanReceiveAMessageBroadcastFromTheServer(): void { - ['client' => $clientOne, 'socketId' => $socketIdOne] = $this->connect(); - $this->subscribe($clientOne, $socketIdOne, 'test-channel'); - - ['client' => $clientTwo, 'socketId' => $socketIdTwo] = $this->connect(); - $this->subscribe($clientTwo, $socketIdTwo, 'test-channel'); - - $this->triggerEvent('test-channel', 'App\Events\TestEvent', ['foo' => 'bar']); + $app = TestbenchApplication::create(); + $clients = []; - $msgOne = $this->recv($clientOne); - $msgTwo = $this->recv($clientTwo); + try { + config(['broadcasting.connections.reverb' => [ + 'driver' => 'reverb', + 'app_id' => $this->appId, + 'key' => $this->appKey, + 'secret' => $this->appSecret, + 'options' => ['host' => $this->getServerHost(), 'port' => $this->getServerPort(), 'scheme' => 'http'], + ]]); - $this->assertNotNull($msgOne); - $this->assertNotNull($msgTwo); + for ($i = 0; $i < 3; ++$i) { + ['client' => $client, 'socketId' => $socketId] = $this->connect(); + $clients[] = $client; + $this->subscribe($client, $socketId, 'test-channel'); + } - $dataOne = json_decode($msgOne, associative: true); - $this->assertSame('App\Events\TestEvent', $dataOne['event']); - $this->assertSame('test-channel', $dataOne['channel']); + Broadcast::on('test-channel')->via('reverb')->as('OrderShipped')->with(['order_id' => 42])->sendNow(); - $this->disconnect($clientOne); - $this->disconnect($clientTwo); + foreach ($clients as $client) { + $frame = $this->recv($client); + $this->assertNotNull($frame); + $this->assertSame([ + 'event' => 'OrderShipped', + 'data' => '{"order_id":42}', + 'channel' => 'test-channel', + ], $this->decodeEventMessage($frame)); + } + } finally { + foreach ($clients as $client) { + $this->disconnect($client); + } + $app->terminate(); + $app->flush(); + } } public function testCanHandleAnEventOnPresenceChannel(): void From 3c68c93df53c8c48e472946ada4bfbfcc7eecc43 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:53:22 +0000 Subject: [PATCH 07/19] Test concurrent SMTP delivery against Mailpit in framework CI Send two messages through the named SMTP mailer and verify the recipient, subject and body delivered to Mailpit. Give each test its own recipient domain so parallel workers can read and clean up their own mail. MAILPIT_HOST opts into the test locally and the existing framework CI job supplies the service. Live delivery exposed pooled SMTP transports sending QUIT after the test coroutine had exited. Purge resolved object pools inside a coroutine before flushing the test application, including when an earlier teardown step failed. Document Mailpit and Mercure in the testing guide and point agent instructions to that shared trait list. Verified delivery, cleanup isolation, unconfigured skips, connection failures and socket closure against a live Mailpit instance. --- .env.example | 6 ++ .github/workflows/tests.yml | 6 ++ AGENTS.md | 14 +--- src/docs/testing.md | 4 ++ .../Testing/Concerns/InteractsWithMailpit.php | 71 +++++++++++++++++++ .../InteractsWithTestCaseLifecycle.php | 9 +++ .../InteractsWithTestCaseLifecycleTest.php | 9 +++ .../Mail/Mailpit/SmtpDeliveryTest.php | 45 ++++++++++++ 8 files changed, 152 insertions(+), 12 deletions(-) create mode 100644 src/foundation/src/Testing/Concerns/InteractsWithMailpit.php create mode 100644 tests/Integration/Mail/Mailpit/SmtpDeliveryTest.php diff --git a/.env.example b/.env.example index 696792035b..d83d353ff8 100644 --- a/.env.example +++ b/.env.example @@ -57,6 +57,12 @@ # integration tests serially against database 0 on a local Cluster. # REDIS_CLUSTER_HOSTS_AND_PORTS=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002 +# Mailpit Integration Tests +# Uncomment MAILPIT_HOST to run SMTP delivery tests against Mailpit. +# MAILPIT_HOST=127.0.0.1 +# MAILPIT_SMTP_PORT=1025 +# MAILPIT_HTTP_PORT=8025 + # Mercure Integration Tests # Uncomment MERCURE_URL to opt into real-hub broadcasting tests. # Configure the hub with matching keys, issuer, cookie name, subscriptions, diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1e3f11618c..f3414de538 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -56,6 +56,10 @@ jobs: container: image: ghcr.io/hypervel/components-ci:php${{ matrix.php }}-swoole-nightly + services: + mailpit: + image: axllent/mailpit:v1.34.0 + steps: - name: Checkout code uses: actions/checkout@v7.0.1 @@ -69,6 +73,8 @@ jobs: run: COMPOSER_MEMORY_LIMIT=-1 composer install --prefer-dist -n -o - name: Run framework test suite + env: + MAILPIT_HOST: mailpit run: vendor/bin/paratest -c phpunit.xml.dist - name: Run Permission suite with the database cache store diff --git a/AGENTS.md b/AGENTS.md index 3f04645312..3f63f8712b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -734,17 +734,7 @@ For service suites outside the directory conventions above, register new test di #### External service test traits -Integration tests that use an external service must use that service's test trait. - -| Trait | Service | Key Env Vars | -|-------|---------|-------------| -| `InteractsWithRedis` | Redis / Redis Cluster / Valkey | `REDIS_HOST`, `REDIS_PORT`, `REDIS_CLUSTER_HOSTS_AND_PORTS` | -| `InteractsWithMeilisearch` | Meilisearch | `MEILISEARCH_HOST`, `MEILISEARCH_PORT`, `MEILISEARCH_KEY` | -| `InteractsWithTypesense` | Typesense | `TYPESENSE_HOST`, `TYPESENSE_PORT`, `TYPESENSE_API_KEY`, `TYPESENSE_PROTOCOL` | -| `InteractsWithAlgolia` | Algolia | `ALGOLIA_APP_ID`, `ALGOLIA_SECRET` | -| `InteractsWithServer` | Engine test servers (HTTP, TCP, WebSocket, HTTP/2) | `TEST_SERVER_HOST` | - -This applies whether the test calls the service directly or reaches it through the package code under test. +Integration tests that use an external service, directly or through the code under test, must use the trait listed for it under [External Service Tests](src/docs/testing.md#external-service-tests). These traits are required for external-service tests to work under ParaTest. Parallel workers share external services unless the trait isolates them. Tests that bypass the trait will leak state across workers and fail depending on timing. @@ -752,7 +742,7 @@ The traits handle service-specific setup and cleanup. For example, `InteractsWit If a service is not configured, the trait skips the test before connecting. If the service is configured but unreachable or misconfigured, the test fails. -When adding integration tests for a new service type that has no trait yet, create one following this same pattern (per-worker isolation, skip-when-unconfigured, fail-when-unreachable). +If the service has no trait yet, create one following this pattern and add it to [External Service Tests](src/docs/testing.md#external-service-tests). #### phpunit.xml.dist diff --git a/src/docs/testing.md b/src/docs/testing.md index 63647bd135..dd0b49ad96 100644 --- a/src/docs/testing.md +++ b/src/docs/testing.md @@ -382,6 +382,8 @@ Integration tests that use an external service must use that service's test trai | `InteractsWithMeilisearch` | Meilisearch | `MEILISEARCH_HOST`, `MEILISEARCH_PORT`, `MEILISEARCH_KEY` | | `InteractsWithTypesense` | Typesense | `TYPESENSE_HOST`, `TYPESENSE_PORT`, `TYPESENSE_API_KEY`, `TYPESENSE_PROTOCOL` | | `InteractsWithAlgolia` | Algolia | `ALGOLIA_APP_ID`, `ALGOLIA_SECRET` | +| `InteractsWithMailpit` | Mailpit | `MAILPIT_HOST`, `MAILPIT_SMTP_PORT`, `MAILPIT_HTTP_PORT` | +| `InteractsWithMercure` | Mercure | `MERCURE_URL`, `MERCURE_JWT_SECRET` | | `InteractsWithServer` | Engine test servers | `TEST_SERVER_HOST` | The Meilisearch, Typesense, and Algolia traits require their corresponding client package: `meilisearch/meilisearch-php`, `typesense/typesense-php`, or `algolia/algoliasearch-client-php`. @@ -394,6 +396,8 @@ The traits handle service-specific setup and cleanup. If a service is not config The search traits create a worker-specific prefix from `TEST_TOKEN`. Prefix test indexes and collections with `$this->meilisearchTestPrefix`, `$this->typesenseTestPrefix`, or `$this->algoliaTestPrefix`. Cleanup only removes resources that start with the matching prefix. +`InteractsWithMailpit` points the `smtp` mailer at Mailpit and makes it the default. Send mail to addresses at `$this->mailpitDomain` and read the delivered messages with `$this->mailpitMessages()`. Cleanup deletes only messages sent to that domain. + #### Parallel Testing and Redis diff --git a/src/foundation/src/Testing/Concerns/InteractsWithMailpit.php b/src/foundation/src/Testing/Concerns/InteractsWithMailpit.php new file mode 100644 index 0000000000..ff55ddaf32 --- /dev/null +++ b/src/foundation/src/Testing/Concerns/InteractsWithMailpit.php @@ -0,0 +1,71 @@ +markTestSkipped('Set MAILPIT_HOST to run Mailpit integration tests.'); + } + + // @phpstan-ignore hypervel.noEnvCallsOutsideOfConfig (integration tests read service settings from the test process environment) + $smtpPort = (int) Env::get('MAILPIT_SMTP_PORT', 1025); + // @phpstan-ignore hypervel.noEnvCallsOutsideOfConfig (integration tests read service settings from the test process environment) + $httpPort = (int) Env::get('MAILPIT_HTTP_PORT', 8025); + + $this->app->make('config')->set([ + 'mail.default' => 'smtp', + 'mail.mailers.smtp' => ['transport' => 'smtp', 'host' => $host, 'port' => $smtpPort, 'timeout' => 5], + ]); + + $this->mailpitDomain = bin2hex(random_bytes(8)) . '.hypervel.test'; + $this->mailpitClient = new Client(['base_uri' => "http://{$host}:{$httpPort}/api/v1/", 'timeout' => 5]); + } + + /** + * Retrieve the messages sent to this test's recipient domain. + * + * @return list> + */ + protected function mailpitMessages(): array + { + // Mailpit returns only the first 50 matches by default. + $response = $this->mailpitClient->get('search', [ + 'query' => ['query' => 'to:' . $this->mailpitDomain, 'limit' => PHP_INT_MAX], + ]); + $search = json_decode((string) $response->getBody(), true, flags: JSON_THROW_ON_ERROR); + $messages = []; + + foreach ($search['messages'] as $summary) { + $response = $this->mailpitClient->get('message/' . $summary['ID']); + $messages[] = json_decode((string) $response->getBody(), true, flags: JSON_THROW_ON_ERROR); + } + + return $messages; + } + + /** + * Delete the messages sent to this test's recipient domain. + */ + protected function tearDownInteractsWithMailpit(): void + { + $this->mailpitClient->delete('search', ['query' => ['query' => 'to:' . $this->mailpitDomain]]); + } +} diff --git a/src/foundation/src/Testing/Concerns/InteractsWithTestCaseLifecycle.php b/src/foundation/src/Testing/Concerns/InteractsWithTestCaseLifecycle.php index 2a77cd43c4..5c1f8eca50 100644 --- a/src/foundation/src/Testing/Concerns/InteractsWithTestCaseLifecycle.php +++ b/src/foundation/src/Testing/Concerns/InteractsWithTestCaseLifecycle.php @@ -20,6 +20,7 @@ use Hypervel\Foundation\Testing\WithFaker; use Hypervel\Foundation\Testing\WithoutEvents; use Hypervel\Foundation\Testing\WithoutMiddleware; +use Hypervel\ObjectPool\PoolManager as ObjectPoolManager; use Hypervel\Support\Facades\Facade; use Hypervel\Support\Facades\ParallelTesting; use ReflectionClass; @@ -141,6 +142,14 @@ protected function tearDownTheTestEnvironment(): void $exception = Coroutine::preferCancellation($exception, $throwable); } + try { + if ($app->resolved(ObjectPoolManager::class)) { + $this->runInCoroutine(fn () => $app->make(ObjectPoolManager::class)->purgeAll()); + } + } catch (Throwable $throwable) { + $exception = Coroutine::preferCancellation($exception, $throwable); + } + try { $app->flush(); } catch (Throwable $throwable) { diff --git a/tests/Foundation/Testing/InteractsWithTestCaseLifecycleTest.php b/tests/Foundation/Testing/InteractsWithTestCaseLifecycleTest.php index fde6dd903d..98a972ded7 100644 --- a/tests/Foundation/Testing/InteractsWithTestCaseLifecycleTest.php +++ b/tests/Foundation/Testing/InteractsWithTestCaseLifecycleTest.php @@ -14,6 +14,7 @@ use Hypervel\Foundation\Testing\DatabaseConnectionResolver; use Hypervel\Foundation\Testing\LazilyRefreshDatabase; use Hypervel\Foundation\Testing\TestCase as FoundationTestCase; +use Hypervel\ObjectPool\PoolManager as ObjectPoolManager; use Hypervel\Support\Facades\DB; use Hypervel\Support\Facades\Facade; use Hypervel\Support\Facades\ParallelTesting; @@ -80,9 +81,16 @@ function () use (&$steps, $poolException): never { } ); + $objectPools = Double::for(ObjectPoolManager::class)->strict(); + $objectPools->expects('purgeAll')->resolves(function () use (&$steps): void { + $steps[] = 'object pools'; + }); + $app = Double::for(ApplicationContract::class, override: true)->strict(); $app->expects('resolved')->with(PoolManager::class)->returns(true); $app->expects('make')->with(PoolManager::class)->returns($poolManager); + $app->expects('resolved')->with(ObjectPoolManager::class)->returns(true); + $app->expects('make')->with(ObjectPoolManager::class)->returns($objectPools); $app->expects('flush')->resolves( function () use (&$steps, $applicationException): never { $steps[] = 'application'; @@ -136,6 +144,7 @@ function () use (&$steps, $callbackException): never { 'parallel', 'database', 'pool', + 'object pools', 'application', 'flushState', ], $steps); diff --git a/tests/Integration/Mail/Mailpit/SmtpDeliveryTest.php b/tests/Integration/Mail/Mailpit/SmtpDeliveryTest.php new file mode 100644 index 0000000000..40b9d650eb --- /dev/null +++ b/tests/Integration/Mail/Mailpit/SmtpDeliveryTest.php @@ -0,0 +1,45 @@ +mailpitDomain => ['Order shipped', 'Your order is on its way.'], + 'bob@' . $this->mailpitDomain => ['Invoice ready', 'Your invoice is available.'], + ]; + $sends = []; + + foreach ($expected as $address => [$subject, $body]) { + $sends[] = static fn () => Mail::raw($body, static fn (Message $message) => $message->to($address)->subject($subject)); + } + + parallel($sends); + + $messages = $this->mailpitMessages(); + $this->assertCount(2, $messages); + + $received = []; + foreach ($messages as $message) { + $this->assertCount(1, $message['To']); + $received[$message['To'][0]['Address']] = [$message['Subject'], $message['Text']]; + } + + foreach ($expected as $address => [$subject, $body]) { + $this->assertSame([$subject, $body . "\r\n"], $received[$address] ?? null); + } + } +} From e6fbb0520560d2745d9de7b18ccd5a2cef8c98b1 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:53:22 +0000 Subject: [PATCH 08/19] Prepare fresh parallel databases for matching Testbench requirements A test with a matching RequiresDatabase attribute could be the first database user on its worker. Without a migration or transaction trait, the configured worker database did not exist, and the first query or server version check failed. Earlier tests or a retained database could hide the failure. Let Testbench prepare its default worker database after the driver matches and before reading its version. Share preparation across requirements and the database trait phase and resolve the connection again after creation purges it. Preserve standalone attribute callbacks and skip mismatched drivers without contacting them. Remove manual provisioning from the Scout integration test. Cover fresh SQLite files, version checks with and without migrations, driver mismatches, and named connections. Verified on fresh PostgreSQL and MySQL workers and in sequential package-mode and parallel Testbench suites. --- .../src/Attributes/RequiresDatabase.php | 9 +++- .../src/Concerns/HandlesDatabases.php | 26 +++++++++-- src/testbench/src/Features/TestingFeature.php | 2 +- src/testbench/src/TestCase.php | 8 ---- .../Attributes/RequiresDatabaseTest.php | 23 ++++++++++ .../Postgres/DatabaseVectorImportTest.php | 1 - .../ParallelDatabaseRequirementsTest.php | 46 +++++++++++++++---- 7 files changed, 90 insertions(+), 25 deletions(-) diff --git a/src/testbench/src/Attributes/RequiresDatabase.php b/src/testbench/src/Attributes/RequiresDatabase.php index 107f281f36..fcb323d38d 100644 --- a/src/testbench/src/Attributes/RequiresDatabase.php +++ b/src/testbench/src/Attributes/RequiresDatabase.php @@ -53,8 +53,9 @@ public function __construct( * Handle the attribute. * * @param Closure(string, array):void $action + * @param null|Closure():void $prepareDefaultDatabase called when the default connection's driver matches, before checking its version */ - public function handle(ApplicationContract $app, Closure $action): mixed + public function handle(ApplicationContract $app, Closure $action, ?Closure $prepareDefaultDatabase = null): mixed { $connection = DB::connection($this->connection); @@ -82,6 +83,12 @@ public function handle(ApplicationContract $app, Closure $action): mixed return null; } + // Creating the worker database purges the connection, so resolve it again before checking its version. + if ($prepareDefaultDatabase !== null && $connection->getName() === $app->make('config')->nullableString('database.default')) { + $prepareDefaultDatabase(); + $connection = DB::connection($this->connection); + } + if ( is_string($this->driver) && $this->versionRequirement !== null diff --git a/src/testbench/src/Concerns/HandlesDatabases.php b/src/testbench/src/Concerns/HandlesDatabases.php index 89a08f38c0..a9ce654914 100644 --- a/src/testbench/src/Concerns/HandlesDatabases.php +++ b/src/testbench/src/Concerns/HandlesDatabases.php @@ -8,6 +8,10 @@ use Hypervel\Config\Repository; use Hypervel\Database\Events\DatabaseRefreshed; use Hypervel\Database\SQLiteDatabase; +use Hypervel\Foundation\Testing\DatabaseMigrations; +use Hypervel\Foundation\Testing\DatabaseTransactions; +use Hypervel\Foundation\Testing\DatabaseTruncation; +use Hypervel\Foundation\Testing\RefreshDatabase; use Hypervel\Testbench\Attributes\DefineDatabase; use Hypervel\Testbench\Attributes\RequiresDatabase; use Hypervel\Testbench\Attributes\WithMigration; @@ -31,10 +35,24 @@ protected function setUpDatabaseRequirements(Closure $callback): void { $app = hypervel_or_fail($this->app); - TestingFeature::run( - testCase: $this, - attribute: fn () => $this->parseTestMethodAttributes($app, RequiresDatabase::class), - ); + $prepareDatabase = TestingFeature::once($this->ensureParallelDatabaseExists(...)); + // Dispatch directly so matching requirements can prepare the worker database before checking its version. + foreach ($this->resolvePhpUnitAttributes()->get(RequiresDatabase::class, []) as $requirement) { + $requirement->handle( + $app, + fn ($method, $parameters) => $this->{$method}(...$parameters), + $prepareDatabase, + ); + } + + // Migration hooks may query before the database traits run. + $uses = static::cachedUsesForTestCase(); + if (isset($uses[RefreshDatabase::class]) + || isset($uses[DatabaseMigrations::class]) + || isset($uses[DatabaseTruncation::class]) + || isset($uses[DatabaseTransactions::class])) { + $prepareDatabase(); + } $app->make('events')->listen(DatabaseRefreshed::class, function () { $this->defineDatabaseMigrationsAfterDatabaseRefreshed(); diff --git a/src/testbench/src/Features/TestingFeature.php b/src/testbench/src/Features/TestingFeature.php index ed8cf0bf5f..e0130958c5 100644 --- a/src/testbench/src/Features/TestingFeature.php +++ b/src/testbench/src/Features/TestingFeature.php @@ -49,7 +49,7 @@ public static function run( * @param null|(Closure():mixed) $callback * @return Closure():mixed */ - private static function once(?Closure $callback): Closure + public static function once(?Closure $callback): Closure { $called = false; $response = null; diff --git a/src/testbench/src/TestCase.php b/src/testbench/src/TestCase.php index f978bef802..7440179522 100644 --- a/src/testbench/src/TestCase.php +++ b/src/testbench/src/TestCase.php @@ -154,14 +154,6 @@ protected function setUpDatabaseTraits(array $uses): void $this->prepareDatabaseTruncationForMethod($uses); $this->forgetStaleMigrationState($uses); - // Version requirements and migration hooks may query before the database traits run. - if (isset($uses[RefreshDatabase::class]) - || isset($uses[DatabaseMigrations::class]) - || isset($uses[DatabaseTruncation::class]) - || isset($uses[DatabaseTransactions::class])) { - $this->ensureParallelDatabaseExists(); - } - $this->setUpDatabaseRequirements(function () use ($uses): void { if (isset($uses[RefreshDatabase::class])) { $this->refreshDatabase(); diff --git a/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php b/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php index 9945909daf..71c2feb2fb 100644 --- a/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php +++ b/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php @@ -7,6 +7,7 @@ use Hypervel\Testbench\Attributes\RequiresDatabase; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use PHPUnit\Framework\Attributes\TestWith; class RequiresDatabaseTest extends TestCase { @@ -49,6 +50,28 @@ public function testDoesNotSkipWhenDriverMatches(): void $this->assertFalse($skipped); } + #[TestWith(['sqlite', 'sqlite', 1])] + #[TestWith(['pgsql', 'sqlite', 0])] + #[TestWith(['sqlite', 'reporting', 0])] + public function testOnlyAMatchingDefaultConnectionIsPrepared(string $driver, string $connection, int $expectedCalls): void + { + config([ + 'database.default' => 'sqlite', + 'database.connections.reporting' => ['driver' => 'sqlite', 'database' => ':memory:'], + ]); + + $calls = 0; + (new RequiresDatabase($driver, connection: $connection))->handle( + $this->app, + static function (): void {}, + static function () use (&$calls): void { + ++$calls; + }, + ); + + $this->assertSame($expectedCalls, $calls); + } + public function testAcceptsArrayOfDrivers(): void { $attribute = new RequiresDatabase(['sqlite', 'mysql'], connection: null); diff --git a/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php b/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php index cd68d9d279..0e99c4a06f 100644 --- a/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php +++ b/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php @@ -53,7 +53,6 @@ protected function defineEnvironment(Application $app): void #[DataProvider('poolCapacities')] public function testImportUsesTheQueryConnectionCapacity(int $capacity, bool $wrapResolver = false): void { - $this->ensureParallelDatabaseExists(); config(['database.connections.vector_import.pool.max_connections' => $capacity]); $schema = Schema::connection('vector_import'); if (! DB::connection('vector_import')->table('pg_available_extensions')->where('name', 'vector')->exists()) { diff --git a/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php b/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php index 2eff74cc96..6f862dfa2e 100644 --- a/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php +++ b/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php @@ -11,10 +11,18 @@ use Hypervel\Testbench\TestCase as TestbenchTestCase; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; +use PHPUnit\Framework\Attributes\TestWith; +use PHPUnit\Framework\SkippedTest; class ParallelDatabaseRequirementsTest extends TestCase { - public function testDatabaseExistsBeforeVersionRequirementsRun(): void + /** + * @param class-string $fixtureClass + */ + #[TestWith([ParallelSqliteRequirementsFixture::class])] + #[TestWith([ParallelSqliteMigrationsFixture::class])] + #[TestWith([ParallelPostgresMigrationsFixture::class, 'Requires pgsql to be configured for "sqlite" database connection'])] + public function testWorkerDatabaseIsCreatedOnlyForMatchingRequirements(string $fixtureClass, ?string $expectedSkip = null): void { $directory = ParallelTesting::tempDir('ParallelDatabaseRequirementsTest'); $files = new Filesystem; @@ -46,19 +54,23 @@ public function testDatabaseExistsBeforeVersionRequirementsRun(): void } try { - $fixture = new ParallelDatabaseRequirementsFixture('start'); - ParallelDatabaseRequirementsFixture::setUpBeforeClass(); + $fixture = new $fixtureClass('start'); + $fixtureClass::setUpBeforeClass(); try { + $skip = null; try { $fixture->start(); - - $this->assertFileExists($database . '_test_' . $environment['TEST_TOKEN']); + } catch (SkippedTest $exception) { + $skip = $exception->getMessage(); } finally { $fixture->finish(); } + + $this->assertSame($expectedSkip, $skip); + $this->assertSame($expectedSkip === null, is_file($database . '_test_' . $environment['TEST_TOKEN'])); } finally { - ParallelDatabaseRequirementsFixture::tearDownAfterClass(); + $fixtureClass::tearDownAfterClass(); } } finally { if ($previousWithoutDatabasesExists) { @@ -88,11 +100,8 @@ public function testDatabaseExistsBeforeVersionRequirementsRun(): void } } -#[RequiresDatabase('sqlite', '>=3.0.0')] -class ParallelDatabaseRequirementsFixture extends TestbenchTestCase +abstract class ParallelDatabaseRequirementsFixture extends TestbenchTestCase { - use DatabaseMigrations; - /** * Start the database test lifecycle. */ @@ -109,3 +118,20 @@ public function finish(): void $this->tearDown(); } } + +#[RequiresDatabase('sqlite', '>=3.0.0')] +class ParallelSqliteRequirementsFixture extends ParallelDatabaseRequirementsFixture +{ +} + +#[RequiresDatabase('sqlite', '>=3.0.0')] +class ParallelSqliteMigrationsFixture extends ParallelDatabaseRequirementsFixture +{ + use DatabaseMigrations; +} + +#[RequiresDatabase('pgsql')] +class ParallelPostgresMigrationsFixture extends ParallelDatabaseRequirementsFixture +{ + use DatabaseMigrations; +} From d39666a78f1374999fb4f2d4e0a9e4c137c938b8 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:16:03 +0000 Subject: [PATCH 09/19] Share one Excimer sampler across Sentry transaction profiles A worker used to start a native profiler for each sampled transaction. When requests overlapped, each timer woke its own thread and captured the running stack, even when another transaction owned that sample. Start a single stock Excimer profiler with the first recording and release it with the last, including when a transaction is abandoned. Route each native sample to the matching Sentry context and to any transaction following its originating coroutine. Record idle boundaries only for recordings that just stopped matching. Each transaction keeps its own time origin, shared frames, event counts and SDK duration limit. Cover overlapping requests, nested transactions, child coroutines and release and restart after collection. Remove the follow-up that depended on an upstream sample filter. The default collector needs no new extension API or application configuration. In 11 interleaved local benchmark rounds at the SDK's 10.1 ms period, 16 overlapping profiled requests added one timer thread instead of 16. Median process CPU overhead against profiling disabled fell from 7.8% to 1.8% for the same work, with comparable sample counts and stack depths. This measures transaction profiling on a single Swoole worker. --- docs/todo.md | 1 - .../src/Profiling/CoroutineProfiler.php | 79 ------------ src/sentry/src/Profiling/ProfileSamples.php | 37 +++--- .../src/Profiling/TransactionProfiler.php | 72 +++++++++++ .../src/Profiling/TransactionSampler.php | 117 ++++++++++++++++++ src/sentry/src/SentryServiceProvider.php | 6 +- tests/Benchmarks/Sentry/README.md | 2 +- tests/Sentry/Profiling/ProfileSamplesTest.php | 51 +++----- .../ProfilingCoroutineIsolationTest.php | 71 ++++++++++- 9 files changed, 298 insertions(+), 138 deletions(-) delete mode 100644 src/sentry/src/Profiling/CoroutineProfiler.php create mode 100644 src/sentry/src/Profiling/TransactionProfiler.php create mode 100644 src/sentry/src/Profiling/TransactionSampler.php diff --git a/docs/todo.md b/docs/todo.md index 67bd55c694..3f9948a137 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -40,7 +40,6 @@ ## Sentry -- Once a released Excimer includes `ExcimerProfiler::setSampleFilter()` ([Excimer change 1354126](https://gerrit.wikimedia.org/r/c/mediawiki/php/excimer/+/1354126)), compare native filtering with the transaction collector under concurrent load. Preserve request context ownership, idle intervals and SDK drop reporting. - Once a Sentry PHP SDK release includes [sentry-php #2420](https://github.com/getsentry/sentry-php/pull/2420), require that release and register `Coroutine::causedByCancellation(...)` with `SentrySdk::setCancellationDetector()` in `SentryServiceProvider`. Verify that cancellation during a Sentry callback reaches the calling coroutine. ## Notifications diff --git a/src/sentry/src/Profiling/CoroutineProfiler.php b/src/sentry/src/Profiling/CoroutineProfiler.php deleted file mode 100644 index a6fcff2238..0000000000 --- a/src/sentry/src/Profiling/CoroutineProfiler.php +++ /dev/null @@ -1,79 +0,0 @@ -profile = new Profile($options); - $this->profile->setStartTimeStamp(microtime(true)); - $this->profiler = new ExcimerProfiler; - $this->profiler->setEventType(EXCIMER_REAL); - $this->profiler->setPeriod(self::SAMPLE_PERIOD); - $this->profiler->setMaxDepth(self::MAX_STACK_DEPTH); - - $samples = new ProfileSamples; - $this->samples = $samples; - $context = $storage->get(); - $coroutineId = Coroutine::id(); - - // The flush runs in the sampled coroutine. Capturing this profiler would keep the native timer alive. - $this->profiler->setFlushCallback(static function (ExcimerLog $log) use ($samples, $context, $storage, $coroutineId): void { - $samples->record($log, $context === null ? Coroutine::id() === $coroutineId : $storage->get() === $context); - }, 1); - } - - /** - * Start collecting stack samples. - */ - public function start(): void - { - $this->profiler->start(); - } - - /** - * Stop collecting samples and attach them to the SDK profile. - */ - public function stop(): void - { - $this->profiler?->stop(); - $this->profiler = null; - $this->profile->setExcimerLog($this->samples->finish()); - } - - /** - * Get the transaction profile. - */ - public function getProfile(): Profile - { - return $this->profile; - } -} diff --git a/src/sentry/src/Profiling/ProfileSamples.php b/src/sentry/src/Profiling/ProfileSamples.php index c50352ca8d..5d3faa4162 100644 --- a/src/sentry/src/Profiling/ProfileSamples.php +++ b/src/sentry/src/Profiling/ProfileSamples.php @@ -4,8 +4,6 @@ namespace Hypervel\Sentry\Profiling; -use ExcimerLog; - /** * @internal */ @@ -20,32 +18,35 @@ class ProfileSamples private ?float $idleSince = null; - private bool $tooLong = false; + public private(set) bool $tooLong = false; /** - * Record the running stack or the beginning of a gap in this transaction's work. + * Capture the monotonic origin used for this transaction's sample timestamps. */ - public function record(ExcimerLog $log, bool $belongsToTransaction): void + public function __construct(private readonly float $startedAt) { - if ($this->tooLong) { - return; - } - - if (! $belongsToTransaction) { - if ($this->samples !== []) { - $this->idleSince ??= $log[0]->getTimestamp(); - } + } - return; + /** + * Remember the first tick spent outside the transaction between two samples. + */ + public function markIdle(float $now): void + { + if ($this->samples !== []) { + $this->idleSince ??= $now - $this->startedAt; } + } - $entry = $log[0]; + /** + * Record a stack captured while this transaction was running. + */ + public function record(float $now, array $trace, int $eventCount): void + { if ($this->idleSince !== null) { $this->samples[] = ['trace' => [], 'timestamp' => $this->idleSince]; $this->idleSince = null; } - $trace = $entry->getTrace(); // Flushing one native sample at a time loses Excimer's frame sharing across samples. foreach ($trace as $index => $frame) { $trace[$index] = $this->frames[serialize($frame)] ??= $frame; @@ -54,8 +55,8 @@ public function record(ExcimerLog $log, bool $belongsToTransaction): void $previous = array_key_last($this->samples); $this->samples[] = [ 'trace' => $trace, - 'timestamp' => $entry->getTimestamp(), - 'event_count' => $entry->getEventCount(), + 'timestamp' => $now - $this->startedAt, + 'event_count' => $eventCount, ]; // The SDK can backdate a coalesced sample, but no earlier than its predecessor. diff --git a/src/sentry/src/Profiling/TransactionProfiler.php b/src/sentry/src/Profiling/TransactionProfiler.php new file mode 100644 index 0000000000..62b793b292 --- /dev/null +++ b/src/sentry/src/Profiling/TransactionProfiler.php @@ -0,0 +1,72 @@ +profile = new Profile($options); + $this->profile->setStartTimeStamp(microtime(true)); + $this->samples = new ProfileSamples(hrtime(true) / 1e9); + } + + /** + * Release an unfinished transaction's recording. + */ + public function __destruct() + { + if ($this->samples !== null) { + $this->sampler->stop($this->owner, $this->samples); + } + } + + /** + * Start collecting stack samples. + */ + public function start(): void + { + if ($this->samples !== null) { + $this->sampler->start($this->owner, $this->samples); + } + } + + /** + * Stop collecting samples and attach them to the SDK profile. + */ + public function stop(): void + { + if ($this->samples !== null) { + $this->sampler->stop($this->owner, $this->samples); + $this->profile->setExcimerLog($this->samples->finish()); + $this->samples = null; + } + } + + /** + * Get the transaction profile. + */ + public function getProfile(): Profile + { + return $this->profile; + } +} diff --git a/src/sentry/src/Profiling/TransactionSampler.php b/src/sentry/src/Profiling/TransactionSampler.php new file mode 100644 index 0000000000..ba524d6097 --- /dev/null +++ b/src/sentry/src/Profiling/TransactionSampler.php @@ -0,0 +1,117 @@ +> */ + private array $recordings = []; + + /** @var array */ + private array $previous = []; + + /** + * Create a sampler shared by the worker's transaction profiles. + */ + public function __construct(private readonly CoroutineRuntimeContextStorage $storage) + { + } + + /** + * Create a profile for the current Sentry context or its originating coroutine. + */ + public function createProfiler(Options $options): TransactionProfiler + { + return new TransactionProfiler($options, $this, $this->contextKey() ?? Coroutine::id()); + } + + /** + * Start the native profiler when the first transaction begins recording. + */ + public function start(int|string $owner, ProfileSamples $samples): void + { + $this->recordings[$owner][spl_object_id($samples)] = $samples; + + if ($this->profiler === null) { + $this->profiler = new ExcimerProfiler; + $this->profiler->setEventType(EXCIMER_REAL); + $this->profiler->setPeriod(self::SAMPLE_PERIOD); + $this->profiler->setMaxDepth(self::MAX_STACK_DEPTH); + $this->profiler->setFlushCallback($this->sample(...), 1); + $this->profiler->start(); + } + } + + /** + * Release the native timer when its final transaction stops recording. + */ + public function stop(int|string $owner, ProfileSamples $samples): void + { + $id = spl_object_id($samples); + unset($this->recordings[$owner][$id], $this->previous[$id]); + + if (empty($this->recordings[$owner])) { + unset($this->recordings[$owner]); + } + + if ($this->recordings === []) { + $this->profiler?->stop(); + $this->profiler = null; + } + } + + /** + * Attribute the native stack to the transactions running on this tick. + */ + private function sample(ExcimerLog $log): void + { + $now = hrtime(true) / 1e9; + // A transaction started without a context still follows its coroutine if a context starts later. + $current = $this->recordings[Coroutine::id()] ?? []; + $context = $this->contextKey(); + if ($context !== null) { + $current += $this->recordings[$context] ?? []; + } + + foreach (array_diff_key($this->previous, $current) as $samples) { + $samples->markIdle($now); + } + $this->previous = $current; + + $trace = null; + foreach ($current as $samples) { + if (! $samples->tooLong) { + $entry = $log[0]; + $samples->record($now, $trace ??= $entry->getTrace(), $entry->getEventCount()); + } + } + } + + /** + * Keep Sentry context IDs distinct from numeric coroutine IDs. + */ + private function contextKey(): ?string + { + $context = $this->storage->get(); + + return $context === null ? null : 'context:' . $context->getId(); + } +} diff --git a/src/sentry/src/SentryServiceProvider.php b/src/sentry/src/SentryServiceProvider.php index 2e03080a98..46db8eaf89 100644 --- a/src/sentry/src/SentryServiceProvider.php +++ b/src/sentry/src/SentryServiceProvider.php @@ -34,7 +34,7 @@ use Hypervel\Sentry\Http\SetRequestIpMiddleware; use Hypervel\Sentry\Integration\ExceptionContextIntegration; use Hypervel\Sentry\Integration\HypervelContextIntegration; -use Hypervel\Sentry\Profiling\CoroutineProfiler; +use Hypervel\Sentry\Profiling\TransactionSampler; use Hypervel\Sentry\State\CoroutineRuntimeContextStorage; use Hypervel\Sentry\State\RuntimeContextBoundary; use Hypervel\Sentry\Tracing\BacktraceHelper; @@ -251,8 +251,8 @@ protected function configureAndRegisterClient(): void $sentryOptions = $clientBuilder->getOptions(); if (extension_loaded('excimer') && $sentryOptions->getProfilerFactory() === null) { - $storage = $this->app->make(CoroutineRuntimeContextStorage::class); - $sentryOptions->setProfilerFactory(static fn (Options $options): CoroutineProfiler => new CoroutineProfiler($options, $storage)); + $sampler = $this->app->make(TransactionSampler::class); + $sentryOptions->setProfilerFactory($sampler->createProfiler(...)); } // Make the pooled transport the default transport option for async sending via Swoole coroutines, diff --git a/tests/Benchmarks/Sentry/README.md b/tests/Benchmarks/Sentry/README.md index 115bd6e0af..61c2b3855c 100644 --- a/tests/Benchmarks/Sentry/README.md +++ b/tests/Benchmarks/Sentry/README.md @@ -67,7 +67,7 @@ CPU affinity is optional. On a machine with those CPUs available, add `--server- | C4 | Sample rate one, shipped instrumentation defaults | | C5 | Sample rate one, optional breadcrumb and tracing instrumentation disabled | -C5 is not zero instrumentation: request transactions, runtime boundaries and trace propagation still have work to do. The structural inventory explains which registrations remain. Request/transaction profiling stays at its shipped disabled default; this harness does not enable Excimer profiling or resolve its coroutine-attribution limitation. +C5 is not zero instrumentation: request transactions, runtime boundaries and trace propagation still have work to do. The structural inventory explains which registrations remain. Transaction profiling stays disabled in this benchmark. Each configuration uses a fresh single-worker server. `/plain` returns a string. `/work` runs three SQLite queries, array-cache reads and writes, one log event, two child coroutines and a small Blade view. Logging uses the `null` channel, checked in the cached config, to exercise breadcrumbs without file I/O. The statistics endpoint bypasses the HTTP kernel so measuring resources does not create Sentry events. diff --git a/tests/Sentry/Profiling/ProfileSamplesTest.php b/tests/Sentry/Profiling/ProfileSamplesTest.php index d989a3ff18..d18d4df214 100644 --- a/tests/Sentry/Profiling/ProfileSamplesTest.php +++ b/tests/Sentry/Profiling/ProfileSamplesTest.php @@ -4,13 +4,10 @@ namespace Hypervel\Tests\Sentry\Profiling; -use ExcimerLog; -use ExcimerLogEntry; use Hypervel\Sentry\Profiling\ProfileSamples; use Hypervel\Tests\TestCase; use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; -use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\Attributes\TestWith; use Psr\Log\LoggerInterface; use Sentry\Context\OsContext; @@ -19,24 +16,24 @@ use Sentry\Options; use Sentry\Profiling\Profile; -#[RequiresPhpExtension('excimer')] class ProfileSamplesTest extends TestCase { use VerifiesDoubles; public function testAnIdleIntervalOnlySeparatesTwoRealSamples(): void { - $samples = new ProfileSamples; - $samples->record($this->logAt(0.01), false); - $samples->record($this->logAt(0.02), true); - $samples->record($this->logAt(0.03), false); - $samples->record($this->logAt(0.04), false); + $samples = new ProfileSamples(1.0); + $trace = [['file' => __FILE__, 'line' => __LINE__]]; + $samples->markIdle(1.125); + $samples->record(1.25, $trace, 1); + $samples->markIdle(1.375); + $samples->markIdle(1.5); - $samples->record($this->logAt(0.05, 3), true); - $samples->record($this->logAt(0.06), false); + $samples->record(1.625, $trace, 3); + $samples->markIdle(1.75); $recording = $samples->finish(); - $this->assertSame([0.02, 0.03, 0.05], array_column($recording, 'timestamp')); + $this->assertSame([0.25, 0.375, 0.625], array_column($recording, 'timestamp')); $this->assertSame([], $recording[1]['trace']); $this->assertSame(3, $recording[2]['event_count']); } @@ -49,11 +46,16 @@ public function testLongProfilesRetainOnlyTheAdjacencyNeededByTheSdk( int $eventCount, float $expectedDuration, ): void { - $samples = new ProfileSamples; - $samples->record($this->logAt(29.9), true); - $samples->record($this->logAt(30.1), $ownsPredecessor); - $samples->record($this->logAt($lastTimestamp, $eventCount), true); - $samples->record(Double::for(ExcimerLog::class)->strict(), true); + $samples = new ProfileSamples(0.0); + $trace = [['file' => __FILE__, 'line' => __LINE__]]; + $samples->record(29.9, $trace, 1); + if ($ownsPredecessor) { + $samples->record(30.1, $trace, 1); + } else { + $samples->markIdle(30.1); + } + $samples->record($lastTimestamp, $trace, $eventCount); + $this->assertTrue($samples->tooLong); $recording = $samples->finish(); $this->assertSame([30.1, $lastTimestamp], array_column($recording, 'timestamp')); @@ -71,19 +73,4 @@ public function testLongProfilesRetainOnlyTheAdjacencyNeededByTheSdk( $this->assertNull($profile->getFormattedData($event)); } - - /** - * Supply a native log entry at a known offset from the start of the profile. - */ - private function logAt(float $timestamp, int $eventCount = 1): ExcimerLog - { - $entry = Double::for(ExcimerLogEntry::class)->strict(); - $entry->allows('getTrace')->returns([['file' => __FILE__, 'line' => __LINE__]]); - $entry->allows('getTimestamp')->returns($timestamp); - $entry->allows('getEventCount')->returns($eventCount); - $log = Double::for(ExcimerLog::class)->strict(); - $log->allows('offsetGet')->with(0)->returns($entry); - - return $log; - } } diff --git a/tests/Sentry/ProfilingCoroutineIsolationTest.php b/tests/Sentry/ProfilingCoroutineIsolationTest.php index 9f4f6fd381..b2c8b5135f 100644 --- a/tests/Sentry/ProfilingCoroutineIsolationTest.php +++ b/tests/Sentry/ProfilingCoroutineIsolationTest.php @@ -7,9 +7,11 @@ use Closure; use Hypervel\Coroutine\Coroutine; use Hypervel\Engine\Channel; +use Hypervel\Sentry\Profiling\TransactionSampler; use Hypervel\Sentry\State\RuntimeContextBoundary; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\Attributes\TestWith; +use ReflectionProperty; use Sentry\Profiling\Profile; use Sentry\Tracing\TransactionContext; use WeakReference; @@ -24,7 +26,9 @@ class ProfilingCoroutineIsolationTest extends TestCase 'sentry.profiles_sample_rate' => 1.0, ]; - public function testTransactionProfileExcludesWorkFromAnotherRequest(): void + #[TestWith([false])] + #[TestWith([true])] + public function testTransactionProfileExcludesWorkFromAnotherRequest(bool $profileRequestB): void { $requestAStarted = new Channel(1); $requestBFinished = new Channel(1); @@ -45,18 +49,30 @@ function () use ($requestAStarted, $requestBFinished): void { $transaction->finish(); } }, - function () use ($requestAStarted, $requestBFinished): void { + function () use ($requestAStarted, $requestBFinished, $profileRequestB): void { try { $this->assertTrue($requestAStarted->pop(2.0)); $this->app->make(RuntimeContextBoundary::class)->start(); + $transaction = $profileRequestB + ? $this->getSentryHubFromContainer()->startTransaction(new TransactionContext('request-b')) + : null; $this->requestBWork(); + $transaction?->finish(); } finally { $requestBFinished->push(true); } }, ]); - $this->assertSentryTransactionCount(1); + $this->assertSentryTransactionCount($profileRequestB ? 2 : 1); + if ($profileRequestB) { + $other = $this->getCapturedSentryEvents()[0][0]; + $otherProfile = $other->getSdkMetadata('profile')->getFormattedData($other); + $functions = array_column($otherProfile['profile']['frames'], 'function'); + $this->assertContains(self::class . '::requestBWork', $functions); + $this->assertNotContains(self::class . '::requestAWork', $functions); + } + $event = $this->getLastSentryEvent(); $this->assertNotNull($event); $this->assertSame('request-a', $event->getTransaction()); @@ -106,14 +122,61 @@ public function testOnlyChildrenSharingTheRequestAreProfiled(bool $hasContext): $this->assertNotContains(self::class . '::requestBWork', $functions); } + #[TestWith([false])] + #[TestWith([true])] + public function testOverlappingTransactionsKeepTheirOwnStacks(bool $startWithContext): void + { + $hub = $this->getSentryHubFromContainer(); + if ($startWithContext) { + $this->app->make(RuntimeContextBoundary::class)->start(); + } + $outer = $hub->startTransaction(new TransactionContext('outer')); + $this->app->make(RuntimeContextBoundary::class)->start(); + $inner = $hub->startTransaction(new TransactionContext('inner')); + + $this->requestAWork(); + Coroutine::create(fn () => $this->attachedChildWork()); + $inner->finish(); + $this->requestBWork(); + $outer->finish(); + + [$innerEvent, $outerEvent] = array_column($this->getCapturedSentryEvents(), 0); + $innerPayload = $innerEvent->getSdkMetadata('profile')->getFormattedData($innerEvent); + $outerPayload = $outerEvent->getSdkMetadata('profile')->getFormattedData($outerEvent); + $innerFunctions = array_column($innerPayload['profile']['frames'], 'function'); + $outerFunctions = array_column($outerPayload['profile']['frames'], 'function'); + $this->assertContains(self::class . '::requestAWork', $outerFunctions); + $this->assertContains(self::class . '::requestAWork', $innerFunctions); + $this->assertContains(self::class . '::attachedChildWork', $innerFunctions); + $this->assertSame($startWithContext, in_array(self::class . '::attachedChildWork', $outerFunctions, true)); + $this->assertContains(self::class . '::requestBWork', $outerFunctions); + $this->assertNotContains(self::class . '::requestBWork', $innerFunctions); + } + public function testAnUnfinishedTransactionReleasesItsProfilerWhenCollected(): void { - $transaction = $this->getSentryHubFromContainer()->startTransaction(new TransactionContext('unfinished')); + $hub = $this->getSentryHubFromContainer(); + $sampler = $this->app->make(TransactionSampler::class); + $native = new ReflectionProperty($sampler, 'profiler'); + $transaction = $hub->startTransaction(new TransactionContext('unfinished')); $profiler = WeakReference::create($transaction->getProfiler()); + $timer = WeakReference::create($native->getValue($sampler)); + $other = $hub->startTransaction(new TransactionContext('other')); + $this->assertSame($timer->get(), $native->getValue($sampler)); + $other->finish(); + $this->assertNotNull($timer->get()); + unset($transaction); gc_collect_cycles(); $this->assertNull($profiler->get()); + $this->assertNull($timer->get()); + + $next = $hub->startTransaction(new TransactionContext('next')); + $this->requestAWork(); + $next->finish(); + $event = $this->getLastSentryEvent(); + $this->assertNotNull($event->getSdkMetadata('profile')->getFormattedData($event)); } /** From 780e05c21bf8ff5e31835a0df51e7756ff19ed1a Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:27:08 +0000 Subject: [PATCH 10/19] Clarify which column can identify rows for a write Document the unique, non-null requirement on identifiedBy() where callers select the column. Explain its use in joined MySQL and MariaDB mass pruning as well as limited and joined SQLite writes. --- src/database/src/Query/Builder.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/database/src/Query/Builder.php b/src/database/src/Query/Builder.php index f78225e705..00fd2b2a41 100644 --- a/src/database/src/Query/Builder.php +++ b/src/database/src/Query/Builder.php @@ -5490,7 +5490,8 @@ public function getGrammar(): Grammar } /** - * Identify rows for limited or joined updates and deletes on SQLite tables without a rowid. + * Set the unique, non-null column that identifies rows for limited or joined SQLite writes. + * Joined mass pruning on MySQL and MariaDB also uses this column in place of the model's primary key. * * @return $this */ From a94f74bd5f7ffa097c32e6bed3222b901cae74e1 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:06:18 +0000 Subject: [PATCH 11/19] Allow the Saloon OAuth account model only when account caching is enabled Installing Saloon previously allowed the configured account model to be deserialized from the cache even with account caching disabled. Read the same setting for model registration, account lookup and invalidation. Resolve the model during cache policy finalization so applications can still select their model during boot. Cover the disabled default with a serialized cache round trip. Clarify when Auth and Sanctum contribute their models and why even a restricted cache requires trusted writers. --- src/docs/cache.md | 4 ++-- src/saloon/src/OAuthAccounts.php | 20 ++++++++++---------- src/saloon/src/SaloonServiceProvider.php | 2 +- tests/Saloon/SaloonServiceProviderTest.php | 10 ++++++++++ 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/docs/cache.md b/src/docs/cache.md index 89c3731aeb..7e36e75644 100644 --- a/src/docs/cache.md +++ b/src/docs/cache.md @@ -87,7 +87,7 @@ Use `array` for request-local test and scratch data. Use `worker-array` only whe ### Serializable Cached Objects -Hypervel applies one global class policy to PHP-serialized cache values. By default, `serializable_classes` is `false`, so PHP may instantiate only classes contributed by framework, package, and application providers. Auth and Sanctum contribute their configured root models and Hypervel contributes the standard Eloquent collection and pivot classes they use. +Hypervel applies one global class policy to PHP-serialized cache values. By default, `serializable_classes` is `false`, so PHP may instantiate only classes contributed by framework, package, and application providers. When their caching is enabled, Auth and Sanctum contribute their configured root models and the standard Eloquent collection and pivot classes they use. Set this option to an array to add application-owned classes, or to `null` / `true` to allow every class: @@ -97,7 +97,7 @@ Set this option to an array to add application-owned classes, or to `null` / `tr ], ``` -You should generally list only the application-owned classes your cached values require. Allowing every class permits any class named in a cached value to be instantiated when the value is read. +You should generally list only the application-owned classes your cached values require. Allowing every class permits any class named in a cached value to be instantiated when the value is read. Even with an allowlist, only trusted code should be able to write to your cache. Packages and applications may contribute classes lazily from a service provider's `boot` method. Contributions are combined with the configured array in registration order, and duplicates are removed: diff --git a/src/saloon/src/OAuthAccounts.php b/src/saloon/src/OAuthAccounts.php index f1b1575e97..59179b9e89 100644 --- a/src/saloon/src/OAuthAccounts.php +++ b/src/saloon/src/OAuthAccounts.php @@ -109,6 +109,14 @@ public static function accountModel(): string return static::$accountModel; } + /** + * Determine whether shared credential caching is enabled. + */ + public static function cacheEnabled(ConfigRepository $config): bool + { + return $config->boolean('saloon.oauth_accounts.cache.enabled', false); + } + /** * Configure the account partition resolver. * @@ -234,7 +242,7 @@ public function find(OAuthAccountIdentity $identity): OAuthAccount $this->ensurePartition($identity); $read = fn (): OAuthAccount => $identity->query()->useWritePdo()->firstOrFail()->unsetRelations(); - $account = $this->cacheEnabled() + $account = static::cacheEnabled($this->config) ? $this->cacheCoordinator->fill( $this->cache(), $identity->newModel(...), @@ -254,7 +262,7 @@ public function find(OAuthAccountIdentity $identity): OAuthAccount */ public function invalidate(OAuthAccountIdentity $identity): void { - if (! $this->cacheEnabled()) { + if (! static::cacheEnabled($this->config)) { return; } @@ -536,14 +544,6 @@ protected function failureResponse(Throwable $exception): ?ResponseInterface }; } - /** - * Determine whether shared credential caching is enabled. - */ - protected function cacheEnabled(): bool - { - return $this->config->boolean('saloon.oauth_accounts.cache.enabled', false); - } - /** * Resolve and validate the credential cache only when it is used. */ diff --git a/src/saloon/src/SaloonServiceProvider.php b/src/saloon/src/SaloonServiceProvider.php index 9525cda3a8..e5b24933b7 100644 --- a/src/saloon/src/SaloonServiceProvider.php +++ b/src/saloon/src/SaloonServiceProvider.php @@ -67,7 +67,7 @@ public function boot(HttpFactory $httpFactory, ConfigRepository $config, CacheMa DateTimeImmutable::class, BaseCarbonImmutable::class, CarbonImmutable::class, - OAuthAccounts::accountModel(), + ...(OAuthAccounts::cacheEnabled($config) ? [OAuthAccounts::accountModel()] : []), ]); $connection = $config->string('saloon.connection.name'); diff --git a/tests/Saloon/SaloonServiceProviderTest.php b/tests/Saloon/SaloonServiceProviderTest.php index 0cb425e06b..ee758fbf37 100644 --- a/tests/Saloon/SaloonServiceProviderTest.php +++ b/tests/Saloon/SaloonServiceProviderTest.php @@ -4,10 +4,12 @@ namespace Hypervel\Tests\Saloon; +use __PHP_Incomplete_Class; use GuzzleHttp\TransportSharing; use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Http\Client\Factory; use Hypervel\Saloon\Facades\Saloon; +use Hypervel\Saloon\OAuthAccount; use Hypervel\Saloon\OAuthAccounts; use Hypervel\Saloon\SaloonManager; use Hypervel\Saloon\SaloonServiceProvider; @@ -43,6 +45,14 @@ public function testProviderMergesConfigurationAndRegistersTheNamedConnection(): $this->assertSame(OAuthAccounts::DEFAULT_CACHE_PREFIX, config('saloon.oauth_accounts.cache.prefix')); } + public function testAccountModelIsExcludedFromCacheDeserializationByDefault(): void + { + $cache = $this->app->make('cache')->build(['driver' => 'array', 'serialize' => true]); + $cache->put('account', new OAuthAccount); + + $this->assertInstanceOf(__PHP_Incomplete_Class::class, $cache->get('account')); + } + public function testOmittedFixtureSettingsUsePackageDefaults(): void { $fixturePath = base_path('tests/Fixtures/Saloon'); From c9e4017543f7dce237ef99d15fc4def1d8cf7eca Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:16:59 +0000 Subject: [PATCH 12/19] Use built-in validation rule defaults when a callback returns null Restore the Laravel convention used by applications that configure a stronger password rule only in production. A null result selects the eight-character password minimum or a fresh built-in Email or File rule. Continue cloning configured rule instances for worker isolation. Document the existing requirement that a non-null callback result belong to the same rule family, and cover the null fallback for all three rules. --- src/docs/validation.md | 2 +- src/validation/README.md | 1 + src/validation/src/Rules/Email.php | 14 ++++++++------ src/validation/src/Rules/File.php | 14 ++++++++------ src/validation/src/Rules/Password.php | 14 ++++++++------ .../ValidationDefaultRuleIsolationTest.php | 15 ++++++++++++++- 6 files changed, 40 insertions(+), 20 deletions(-) diff --git a/src/docs/validation.md b/src/docs/validation.md index 1fc92bb25e..6e769cf8b2 100644 --- a/src/docs/validation.md +++ b/src/docs/validation.md @@ -3492,7 +3492,7 @@ You may convert a `Password` rule object to a string suitable for the HTML `pass #### Defining Default Password Rules -You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the `Password::defaults` method, which accepts a closure. The closure given to the `defaults` method should return the default configuration of the Password rule. Typically, the `defaults` rule should be called within the `boot` method of one of your application's service providers: +You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the `Password::defaults` method, which accepts a closure. The closure may return a configured Password rule or `null` to use the built-in eight-character minimum. Typically, the `defaults` rule should be called within the `boot` method of one of your application's service providers: ```php use Hypervel\Validation\Rules\Password; diff --git a/src/validation/README.md b/src/validation/README.md index d867670174..ccdba85100 100644 --- a/src/validation/README.md +++ b/src/validation/README.md @@ -7,6 +7,7 @@ Documentation: https://hypervel.org/docs/validation ## Differences From Laravel +- Hypervel throws if a default callback for `Email`, `File`, or `Password` returns anything other than an instance of that rule or `null`. Laravel accepts any `Rule` instance for `File` and `Password`. Its `Email` rule uses the built-in default for other results. - String rule parameters use standard CSV quoting with literal backslashes. See [rule parameters](https://hypervel.org/docs/validation#rule-parameters). - The `encoding` rule rejects numbers, booleans, and non-nullable `null`; it does not coerce scalar values to strings. - Date comparison rules allow a referenced field to be missing or `null` unless it is also required. Unparseable date strings and invalid referenced values fail validation instead of being compared with `null`. diff --git a/src/validation/src/Rules/Email.php b/src/validation/src/Rules/Email.php index 4902fd8ac3..921cabd2fa 100644 --- a/src/validation/src/Rules/Email.php +++ b/src/validation/src/Rules/Email.php @@ -97,16 +97,18 @@ public static function defaults(mixed $callback = null): ?static */ public static function default(): static { - if (static::$defaultCallback === null) { - return new static; + $email = static::$defaultCallback; + + if (is_callable($email)) { + $email = $email(); } - $email = is_callable(static::$defaultCallback) - ? call_user_func(static::$defaultCallback) - : static::$defaultCallback; + if ($email === null) { + return new static; + } if (! $email instanceof static) { - throw new InvalidArgumentException('The default callback must return an instance of ' . static::class . '.'); + throw new InvalidArgumentException('The default callback must return an instance of ' . static::class . ' or null.'); } return clone $email; diff --git a/src/validation/src/Rules/File.php b/src/validation/src/Rules/File.php index b95deac88e..4001ef88ac 100644 --- a/src/validation/src/Rules/File.php +++ b/src/validation/src/Rules/File.php @@ -112,16 +112,18 @@ public static function defaults(mixed $callback = null): ?static */ public static function default(): static { - if (static::$defaultCallback === null) { - return new static; + $file = static::$defaultCallback; + + if (is_callable($file)) { + $file = $file(); } - $file = is_callable(static::$defaultCallback) - ? call_user_func(static::$defaultCallback) - : static::$defaultCallback; + if ($file === null) { + return new static; + } if (! $file instanceof static) { - throw new InvalidArgumentException('The default callback must return an instance of ' . static::class . '.'); + throw new InvalidArgumentException('The default callback must return an instance of ' . static::class . ' or null.'); } return clone $file; diff --git a/src/validation/src/Rules/Password.php b/src/validation/src/Rules/Password.php index 132c5931d3..56a4d4b5bf 100644 --- a/src/validation/src/Rules/Password.php +++ b/src/validation/src/Rules/Password.php @@ -148,16 +148,18 @@ public static function defaults(mixed $callback = null): ?static */ public static function default(): static { - if (static::$defaultCallback === null) { - return static::min(8); + $password = static::$defaultCallback; + + if (is_callable($password)) { + $password = $password(); } - $password = is_callable(static::$defaultCallback) - ? call_user_func(static::$defaultCallback) - : static::$defaultCallback; + if ($password === null) { + return static::min(8); + } if (! $password instanceof static) { - throw new InvalidArgumentException('The default callback must return an instance of ' . static::class . '.'); + throw new InvalidArgumentException('The default callback must return an instance of ' . static::class . ' or null.'); } return clone $password; diff --git a/tests/Validation/ValidationDefaultRuleIsolationTest.php b/tests/Validation/ValidationDefaultRuleIsolationTest.php index 585942f5b0..fec7260b08 100644 --- a/tests/Validation/ValidationDefaultRuleIsolationTest.php +++ b/tests/Validation/ValidationDefaultRuleIsolationTest.php @@ -10,8 +10,10 @@ use Hypervel\Engine\Channel; use Hypervel\Tests\TestCase; use Hypervel\Validation\Rules\Email; +use Hypervel\Validation\Rules\File; use Hypervel\Validation\Rules\Password; use InvalidArgumentException; +use PHPUnit\Framework\Attributes\TestWith; use function Hypervel\Coroutine\parallel; @@ -86,12 +88,23 @@ function () use ($ready, $continue): array { $this->assertSame(['string', 'min:12'], $default); } + #[TestWith([Email::class])] + #[TestWith([File::class])] + #[TestWith([Password::class])] + public function testNullCallbackResultUsesTheBuiltInDefault(string $rule): void + { + $default = $rule::default(); + $rule::defaults(static fn () => null); + + $this->assertEquals($default, $rule::default()); + } + public function testInvalidCallableResultIsRejected(): void { Password::defaults(static fn (): Email => new Email); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessageIs('The default callback must return an instance of ' . Password::class . '.'); + $this->expectExceptionMessageIs('The default callback must return an instance of ' . Password::class . ' or null.'); Password::default(); } From 4eb2d78439bc85f533cd3835fbd6957be525390c Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:31:35 +0000 Subject: [PATCH 13/19] Prepare copied worker database connections before checking their version A named connection copied from the default inherits the parallel worker database name. Its version check could open the database before Testbench had created it, making the result depend on which test ran first. After matching the driver, check whether the resolved connection targets the default worker database. Provision that database once and resolve the connection again before asking for its version. Cover both a copied SQLite connection on a fresh worker and an independent reporting connection. --- .../InteractsWithParallelDatabase.php | 35 ++++++++++++++--- .../src/Attributes/RequiresDatabase.php | 9 +++-- .../src/Concerns/HandlesDatabases.php | 7 +++- .../Attributes/RequiresDatabaseTest.php | 17 +++++---- .../ParallelDatabaseRequirementsTest.php | 38 ++++++++++++++++--- 5 files changed, 82 insertions(+), 24 deletions(-) diff --git a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php index 40ef792c32..d422979129 100644 --- a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php +++ b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php @@ -6,6 +6,7 @@ use Hypervel\Contracts\Config\Repository as ConfigContract; use Hypervel\Database\ConfigurationUrlParser; +use Hypervel\Database\ConnectionInterface; use Hypervel\Database\QueryException; use Hypervel\Database\SQLiteDatabase; use Hypervel\Support\Env; @@ -21,8 +22,8 @@ * connection's database name to {database}_test_{token} before * defineEnvironment() runs, so custom connections derived from the * default connection inherit the correct database name. - * 2. Database creation (before Testbench database requirements and in database - * traits): ensures the per-worker database exists, creating it on demand. + * 2. Database creation: Testbench and the database testing traits create + * the worker database when a test needs it. * * In-memory SQLite databases are skipped — each worker process gets its * own memory space naturally. @@ -86,13 +87,35 @@ protected function configureParallelDatabaseName($app): void } } + /** + * Determine whether a test connection targets the default worker database. + */ + protected function usesParallelDatabase(ConnectionInterface $connection): bool + { + /** @var ConfigContract $config */ + $config = $this->app->make('config'); + $default = $config->nullableString('database.default', null); + + if ($default === null) { + return false; + } + + if ($connection->getName() === $default) { + return true; + } + + $configuration = $config->nullableArray("database.connections.{$default}", null); + + return ($configuration['driver'] ?? null) === $connection->getDriverName() + && ($configuration['database'] ?? null) === $connection->getDatabaseName(); + } + /** * Ensure the per-worker database exists, creating it if needed. * - * Called before Testbench database requirements and from database testing - * traits (RefreshDatabase, DatabaseMigrations, DatabaseTruncation, - * DatabaseTransactions) after the app is booted and connections are available. - * The config has already been rewritten by configureParallelDatabaseName(). + * Testbench calls this after a requirement matches the driver of a connection + * that uses the worker database, before it checks the server version. Database + * testing traits also call it after the app boots. * * No-op when not running in parallel or when using in-memory SQLite. */ diff --git a/src/testbench/src/Attributes/RequiresDatabase.php b/src/testbench/src/Attributes/RequiresDatabase.php index fcb323d38d..dcb80e0cf8 100644 --- a/src/testbench/src/Attributes/RequiresDatabase.php +++ b/src/testbench/src/Attributes/RequiresDatabase.php @@ -7,6 +7,7 @@ use Attribute; use Closure; use Hypervel\Contracts\Foundation\Application as ApplicationContract; +use Hypervel\Database\ConnectionInterface; use Hypervel\Support\Arr; use Hypervel\Support\Collection; use Hypervel\Support\Facades\DB; @@ -53,9 +54,9 @@ public function __construct( * Handle the attribute. * * @param Closure(string, array):void $action - * @param null|Closure():void $prepareDefaultDatabase called when the default connection's driver matches, before checking its version + * @param null|Closure(ConnectionInterface):void $prepareDatabase called when the driver matches, before checking its version */ - public function handle(ApplicationContract $app, Closure $action, ?Closure $prepareDefaultDatabase = null): mixed + public function handle(ApplicationContract $app, Closure $action, ?Closure $prepareDatabase = null): mixed { $connection = DB::connection($this->connection); @@ -84,8 +85,8 @@ public function handle(ApplicationContract $app, Closure $action, ?Closure $prep } // Creating the worker database purges the connection, so resolve it again before checking its version. - if ($prepareDefaultDatabase !== null && $connection->getName() === $app->make('config')->nullableString('database.default')) { - $prepareDefaultDatabase(); + if ($prepareDatabase !== null) { + $prepareDatabase($connection); $connection = DB::connection($this->connection); } diff --git a/src/testbench/src/Concerns/HandlesDatabases.php b/src/testbench/src/Concerns/HandlesDatabases.php index a9ce654914..3da5cd375a 100644 --- a/src/testbench/src/Concerns/HandlesDatabases.php +++ b/src/testbench/src/Concerns/HandlesDatabases.php @@ -6,6 +6,7 @@ use Closure; use Hypervel\Config\Repository; +use Hypervel\Database\ConnectionInterface; use Hypervel\Database\Events\DatabaseRefreshed; use Hypervel\Database\SQLiteDatabase; use Hypervel\Foundation\Testing\DatabaseMigrations; @@ -41,7 +42,11 @@ protected function setUpDatabaseRequirements(Closure $callback): void $requirement->handle( $app, fn ($method, $parameters) => $this->{$method}(...$parameters), - $prepareDatabase, + function (ConnectionInterface $connection) use ($prepareDatabase): void { + if ($this->usesParallelDatabase($connection)) { + $prepareDatabase(); + } + }, ); } diff --git a/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php b/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php index 71c2feb2fb..3f4ca3b255 100644 --- a/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php +++ b/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Foundation\Testing\Attributes; +use Hypervel\Database\ConnectionInterface; use Hypervel\Testbench\Attributes\RequiresDatabase; use Hypervel\Testbench\TestCase; use InvalidArgumentException; @@ -50,26 +51,26 @@ public function testDoesNotSkipWhenDriverMatches(): void $this->assertFalse($skipped); } - #[TestWith(['sqlite', 'sqlite', 1])] - #[TestWith(['pgsql', 'sqlite', 0])] - #[TestWith(['sqlite', 'reporting', 0])] - public function testOnlyAMatchingDefaultConnectionIsPrepared(string $driver, string $connection, int $expectedCalls): void + #[TestWith(['sqlite', 'sqlite', 'sqlite'])] + #[TestWith(['pgsql', 'sqlite', null])] + #[TestWith(['sqlite', 'reporting', 'reporting'])] + public function testPreparationReceivesTheMatchingConnection(string $driver, string $connection, ?string $expected): void { config([ 'database.default' => 'sqlite', 'database.connections.reporting' => ['driver' => 'sqlite', 'database' => ':memory:'], ]); - $calls = 0; + $prepared = null; (new RequiresDatabase($driver, connection: $connection))->handle( $this->app, static function (): void {}, - static function () use (&$calls): void { - ++$calls; + static function (ConnectionInterface $connection) use (&$prepared): void { + $prepared = $connection->getName(); }, ); - $this->assertSame($expectedCalls, $calls); + $this->assertSame($expected, $prepared); } public function testAcceptsArrayOfDrivers(): void diff --git a/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php b/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php index 6f862dfa2e..de1694ddc1 100644 --- a/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php +++ b/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Testbench\Databases; +use Hypervel\Contracts\Foundation\Application; use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Testing\DatabaseMigrations; use Hypervel\Support\Env; @@ -19,10 +20,12 @@ class ParallelDatabaseRequirementsTest extends TestCase /** * @param class-string $fixtureClass */ - #[TestWith([ParallelSqliteRequirementsFixture::class])] - #[TestWith([ParallelSqliteMigrationsFixture::class])] - #[TestWith([ParallelPostgresMigrationsFixture::class, 'Requires pgsql to be configured for "sqlite" database connection'])] - public function testWorkerDatabaseIsCreatedOnlyForMatchingRequirements(string $fixtureClass, ?string $expectedSkip = null): void + #[TestWith([ParallelSqliteRequirementsFixture::class, true])] + #[TestWith([ParallelSqliteMigrationsFixture::class, true])] + #[TestWith([ParallelSqliteReportingFixture::class, true])] + #[TestWith([IndependentSqliteReportingFixture::class, false])] + #[TestWith([ParallelPostgresMigrationsFixture::class, false, 'Requires pgsql to be configured for "sqlite" database connection'])] + public function testWorkerDatabaseIsCreatedOnlyForMatchingRequirements(string $fixtureClass, bool $expectsWorkerDatabase, ?string $expectedSkip = null): void { $directory = ParallelTesting::tempDir('ParallelDatabaseRequirementsTest'); $files = new Filesystem; @@ -68,7 +71,7 @@ public function testWorkerDatabaseIsCreatedOnlyForMatchingRequirements(string $f } $this->assertSame($expectedSkip, $skip); - $this->assertSame($expectedSkip === null, is_file($database . '_test_' . $environment['TEST_TOKEN'])); + $this->assertSame($expectsWorkerDatabase, is_file($database . '_test_' . $environment['TEST_TOKEN'])); } finally { $fixtureClass::tearDownAfterClass(); } @@ -135,3 +138,28 @@ class ParallelPostgresMigrationsFixture extends ParallelDatabaseRequirementsFixt { use DatabaseMigrations; } + +#[RequiresDatabase('sqlite', '>=3.0.0', connection: 'reporting')] +class ParallelSqliteReportingFixture extends ParallelDatabaseRequirementsFixture +{ + /** + * Point the reporting connection at the same worker database. + */ + protected function defineEnvironment(Application $app): void + { + $config = $app->make('config'); + $config->set('database.connections.reporting', $config->array('database.connections.sqlite')); + } +} + +#[RequiresDatabase('sqlite', '>=3.0.0', connection: 'reporting')] +class IndependentSqliteReportingFixture extends ParallelDatabaseRequirementsFixture +{ + /** + * Give the reporting connection its own in-memory database. + */ + protected function defineEnvironment(Application $app): void + { + $app->make('config')->set('database.connections.reporting', ['driver' => 'sqlite', 'database' => ':memory:']); + } +} From f798087a4dd7c0fd6545ae13c0d0ea2021f42116 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:31:35 +0000 Subject: [PATCH 14/19] Propagate cancellation during log writes and rotation Catching every throwable around stream operations could turn a canceled log write into an open failure or retry, or silently stop retention. Limit recovery to PHP warnings converted to ErrorException. If stream cleanup raises a warning while cancellation unwinds, propagate the original exception and its cause. Keep ordinary warning handling and partial-write behavior intact. Exercise cancellation during a blocked stream open with a warning raised by the wrapper during cleanup. --- .../Concerns/PerformsSafeStreamOperations.php | 47 +++++++----- src/log/src/Handlers/RotatingFileHandler.php | 17 +++-- tests/Log/StreamHandlerTest.php | 74 ++++++++++++++----- 3 files changed, 94 insertions(+), 44 deletions(-) diff --git a/src/log/src/Handlers/Concerns/PerformsSafeStreamOperations.php b/src/log/src/Handlers/Concerns/PerformsSafeStreamOperations.php index b38a066188..109e8c094c 100644 --- a/src/log/src/Handlers/Concerns/PerformsSafeStreamOperations.php +++ b/src/log/src/Handlers/Concerns/PerformsSafeStreamOperations.php @@ -4,10 +4,11 @@ namespace Hypervel\Log\Handlers\Concerns; +use ErrorException; +use Hypervel\Coroutine\Coroutine; use LogicException; use Monolog\LogRecord; use Monolog\Utils; -use Throwable; use UnexpectedValueException; trait PerformsSafeStreamOperations @@ -33,8 +34,8 @@ protected function closeStreamSafely(): void if ($this->url !== null && is_resource($stream)) { try { fclose($stream); - } catch (Throwable) { - // Closing is best-effort and must not abort reset or rotation. + } catch (ErrorException $warning) { + $this->handleStreamWarning($warning); } } } @@ -67,8 +68,8 @@ protected function writeStreamSafely(LogRecord $record): void $this->createStreamDirectory($url); try { $stream = fopen($url, $this->fileOpenMode); - } catch (Throwable) { - $stream = false; + } catch (ErrorException $warning) { + $stream = $this->handleStreamWarning($warning); } if (! is_resource($stream)) { @@ -86,8 +87,8 @@ protected function writeStreamSafely(LogRecord $record): void if ($this->filePermission !== null) { try { chmod($url, $this->filePermission); - } catch (Throwable) { - // File permissions are best-effort, matching Monolog. + } catch (ErrorException $warning) { + $this->handleStreamWarning($warning); } } @@ -102,8 +103,8 @@ protected function writeStreamSafely(LogRecord $record): void if ($this->useLocking) { try { $locked = flock($stream, LOCK_EX); - } catch (Throwable) { - // Locking is best-effort, matching Monolog. + } catch (ErrorException $warning) { + $locked = $this->handleStreamWarning($warning); } } @@ -116,8 +117,8 @@ protected function writeStreamSafely(LogRecord $record): void $stream, $offset === 0 ? $contents : substr($contents, $offset), ); - } catch (Throwable) { - $written = false; + } catch (ErrorException $warning) { + $written = $this->handleStreamWarning($warning); } if ($written === false || $written === 0) { @@ -130,8 +131,8 @@ protected function writeStreamSafely(LogRecord $record): void if ($locked) { try { flock($stream, LOCK_UN); - } catch (Throwable) { - // Unlocking is best-effort, matching Monolog. + } catch (ErrorException $warning) { + $this->handleStreamWarning($warning); } } } @@ -169,8 +170,8 @@ private function createStreamDirectory(string $url): void if ($directory !== null && ! is_dir($directory)) { try { $created = mkdir($directory, 0777, true); - } catch (Throwable) { - $created = false; + } catch (ErrorException $warning) { + $created = $this->handleStreamWarning($warning); } if (! $created && ! is_dir($directory)) { @@ -204,8 +205,8 @@ private function getStreamInode(): ?int try { $inode = fileinode($this->url); - } catch (Throwable) { - return null; + } catch (ErrorException $warning) { + $inode = $this->handleStreamWarning($warning); } return $inode === false ? null : $inode; @@ -216,4 +217,16 @@ private function hasStreamInodeChanged(): bool return $this->safeInodeUrl !== null && $this->safeInodeUrl !== $this->getStreamInode(); } + + /** + * Treat a stream warning as a failed operation unless it arose while unwinding cancellation. + */ + private function handleStreamWarning(ErrorException $warning): false + { + if (Coroutine::causedByCancellation($warning)) { + throw $warning; + } + + return false; + } } diff --git a/src/log/src/Handlers/RotatingFileHandler.php b/src/log/src/Handlers/RotatingFileHandler.php index 2ef6e48d83..480cfc1f85 100644 --- a/src/log/src/Handlers/RotatingFileHandler.php +++ b/src/log/src/Handlers/RotatingFileHandler.php @@ -4,11 +4,11 @@ namespace Hypervel\Log\Handlers; +use ErrorException; use Hypervel\Log\Handlers\Concerns\PerformsSafeStreamOperations; use Monolog\Handler\RotatingFileHandler as MonologRotatingFileHandler; use Monolog\LogRecord; use Override; -use Throwable; class RotatingFileHandler extends MonologRotatingFileHandler { @@ -65,7 +65,8 @@ protected function rotate(): void try { $logFiles = $this->findRotatedFiles(); - } catch (Throwable) { + } catch (ErrorException $warning) { + $this->handleStreamWarning($warning); return; } @@ -84,8 +85,8 @@ protected function rotate(): void try { $deleted = unlink($file); - } catch (Throwable) { - $deleted = false; + } catch (ErrorException $warning) { + $deleted = $this->handleStreamWarning($warning); } if (! $deleted) { @@ -97,8 +98,8 @@ protected function rotate(): void while ($directory !== $basePath) { try { $entries = scandir($directory); - } catch (Throwable) { - break; + } catch (ErrorException $warning) { + $entries = $this->handleStreamWarning($warning); } if ($entries === false || count(array_diff($entries, ['.', '..'])) > 0) { @@ -107,8 +108,8 @@ protected function rotate(): void try { $removed = rmdir($directory); - } catch (Throwable) { - $removed = false; + } catch (ErrorException $warning) { + $removed = $this->handleStreamWarning($warning); } if (! $removed) { diff --git a/tests/Log/StreamHandlerTest.php b/tests/Log/StreamHandlerTest.php index 40fc3744b2..4fa6272499 100644 --- a/tests/Log/StreamHandlerTest.php +++ b/tests/Log/StreamHandlerTest.php @@ -4,8 +4,11 @@ namespace Hypervel\Tests\Log; +use Closure; use ErrorException; +use Hypervel\Coroutine\Coroutine; use Hypervel\Engine\Channel; +use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Filesystem\Filesystem; use Hypervel\Log\Handlers\RotatingFileHandler; use Hypervel\Log\Handlers\StreamHandler; @@ -13,6 +16,8 @@ use Hypervel\Tests\TestCase; use Monolog\Formatter\LineFormatter; use Monolog\Logger; +use Swoole\Coroutine\CanceledException; +use Throwable; use UnexpectedValueException; use function Hypervel\Coroutine\parallel; @@ -52,9 +57,14 @@ protected function tearDown(): void public function testYieldingOpenDoesNotCaptureASiblingCoroutineWarning(): void { - LogStreamWrapper::$entered = new Channel(1); - LogStreamWrapper::$release = new Channel(1); - LogStreamWrapper::$failOpenAfterYield = true; + $entered = new Channel(1); + $release = new Channel(1); + LogStreamWrapper::$opening = static function () use ($entered, $release): bool { + $entered->push(true); + $release->pop(); + + return false; + }; $warnings = []; $exceptionMessage = null; @@ -75,10 +85,10 @@ function () use (&$exceptionMessage): void { $exceptionMessage = $exception->getMessage(); } }, - function (): void { - LogStreamWrapper::$entered->pop(); + function () use ($entered, $release): void { + $entered->pop(); trigger_error('warning from sibling coroutine', E_USER_WARNING); - LogStreamWrapper::$release->push(true); + $release->push(true); }, ]); } finally { @@ -90,6 +100,40 @@ function (): void { $this->assertStringNotContainsString('warning from sibling coroutine', $exceptionMessage); } + public function testStreamOpenPropagatesCleanupWarningsDuringCancellation(): void + { + $blocked = new Channel(1); + $result = new Channel(1); + LogStreamWrapper::$opening = static function () use ($blocked): bool { + try { + return $blocked->pop(); + } finally { + trigger_error('Stream cleanup failed', E_USER_WARNING); + } + }; + set_error_handler(static function (int $level, string $message): never { + throw new ErrorException($message, 0, $level); + }); + + try { + $writer = Coroutine::create(static function () use ($result): void { + try { + (new Logger('test', [new StreamHandler(self::STREAM_SCHEME . '://cancelled')]))->info('message'); + } catch (Throwable $exception) { + $result->push($exception); + } + }); + + $this->assertTrue(EngineCoroutine::cancelById($writer, throwException: true)); + $exception = $result->pop(1); + $this->assertInstanceOf(ErrorException::class, $exception); + $this->assertSame('Stream cleanup failed', $exception->getMessage()); + $this->assertInstanceOf(CanceledException::class, $exception->getPrevious()); + } finally { + restore_error_handler(); + } + } + public function testOpenFailureIsNormalizedWithReturningAndThrowingErrorHandlers(): void { LogStreamWrapper::$failOpen = true; @@ -309,11 +353,8 @@ private function captureOpenFailureMessage(string $message): string class LogStreamWrapper { - public static ?Channel $entered = null; - - public static ?Channel $release = null; - - public static bool $failOpenAfterYield = false; + /** @var null|Closure():bool */ + public static ?Closure $opening = null; public static bool $failOpen = false; @@ -342,9 +383,7 @@ class LogStreamWrapper public static function reset(): void { - self::$entered = null; - self::$release = null; - self::$failOpenAfterYield = false; + self::$opening = null; self::$failOpen = false; self::$failFirstWrite = false; self::$maximumWriteLength = null; @@ -365,11 +404,8 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ return false; } - if (self::$failOpenAfterYield) { - self::$entered?->push(true); - self::$release?->pop(); - - return false; + if (self::$opening !== null) { + return (self::$opening)(); } return true; From 3f60bebacd6ce145e407f39885d8555f2536a133 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:31:35 +0000 Subject: [PATCH 15/19] Keep the selected checkout paths in the Sentry benchmark A skeleton could override the supplied components or framework checkout by declaring a repository with the same name. Put the selected path repositories first and combine them with the skeleton repositories using array union so unrelated entries are preserved. --- tests/Benchmarks/Sentry/setup-app.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/Benchmarks/Sentry/setup-app.sh b/tests/Benchmarks/Sentry/setup-app.sh index 6ba638252a..c13ef7e841 100755 --- a/tests/Benchmarks/Sentry/setup-app.sh +++ b/tests/Benchmarks/Sentry/setup-app.sh @@ -35,8 +35,7 @@ php -r ' $manifest["repositories"] = [ "components" => ["type" => "path", "url" => $sourcePattern, "options" => ["symlink" => true, "versions" => $versions]], "framework" => ["type" => "path", "url" => Hypervel\Filesystem\glob_quote($argv[2]), "options" => ["symlink" => true]], - ...($manifest["repositories"] ?? []), - ]; + ] + ($manifest["repositories"] ?? []); file_put_contents("composer.json", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n"); ' "$components" "$framework" "$harness" composer require hypervel/sentry:0.4.x-dev --no-update -n From ed746d5797eafb29567c8cfc3d90ae439af5a4ff Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:44:44 +0000 Subject: [PATCH 16/19] Require MariaDB patch releases with correct mixed UUID lookups MariaDB can omit matching rows when an IN query mixes native UUIDv4 and UUIDv7 values (MDEV-35468). Document the first fixed patches on the 10.11 and 11.4 series so applications can rely on these lookups when porting existing data. --- src/docs/database.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/database.md b/src/docs/database.md index 408c1bbe9d..e5f05cac14 100644 --- a/src/docs/database.md +++ b/src/docs/database.md @@ -39,7 +39,7 @@ Almost every modern web application interacts with a database. Hypervel makes in
-- MariaDB 10.11.6+ ([Version Policy](https://mariadb.org/about/#maintenance-policy)) +- MariaDB 10.11.11+ on 10.11, 11.4.5+ on 11.4, or a newer maintained series ([Version Policy](https://mariadb.org/about/#maintenance-policy)) - MySQL 5.7+ ([Version Policy](https://en.wikipedia.org/wiki/MySQL#Release_history)) - PostgreSQL 10.0+ ([Version Policy](https://www.postgresql.org/support/versioning/)) - SQLite 3.32.0+ From 2fd020a3b9e20711aa38273401b255b95df817a8 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:48:29 +0000 Subject: [PATCH 17/19] Match the server before preparing a named parallel test database A database requirement on a reporting connection could create or contact the default worker database when both servers used the same database name. Match the configured server address as well as the driver and database before provisioning the default connection. Compare against the effective read or write endpoint without opening a connection. Cover copied MySQL settings, a separate port, and a copied connection whose write host overrides the base host. --- .../InteractsWithParallelDatabase.php | 49 ++++++++++++++++++- .../InteractsWithParallelDatabaseTest.php | 26 ++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php index d422979129..9a1b99fee0 100644 --- a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php +++ b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php @@ -6,7 +6,9 @@ use Hypervel\Contracts\Config\Repository as ConfigContract; use Hypervel\Database\ConfigurationUrlParser; +use Hypervel\Database\Connection; use Hypervel\Database\ConnectionInterface; +use Hypervel\Database\ConnectionName; use Hypervel\Database\QueryException; use Hypervel\Database\SQLiteDatabase; use Hypervel\Support\Env; @@ -106,8 +108,51 @@ protected function usesParallelDatabase(ConnectionInterface $connection): bool $configuration = $config->nullableArray("database.connections.{$default}", null); - return ($configuration['driver'] ?? null) === $connection->getDriverName() - && ($configuration['database'] ?? null) === $connection->getDatabaseName(); + if (($configuration['driver'] ?? null) !== $connection->getDriverName() + || ($configuration['database'] ?? null) !== $connection->getDatabaseName()) { + return false; + } + + if ($connection->getDriverName() === 'sqlite') { + return true; + } + + $role = $connection->getConfig(Connection::READ_WRITE_TYPE_CONFIG_KEY) ?? ConnectionName::WRITE; + $endpoints = $configuration[$role] ?? []; + $address = $this->parallelDatabaseAddress($connection->getConfig()); + + foreach (isset($endpoints[0]) ? $endpoints : [$endpoints] as $endpoint) { + if ($this->parallelDatabaseAddress(array_replace($configuration, $endpoint)) === $address) { + return true; + } + } + + return false; + } + + /** + * Get the configured server address without opening a database connection. + * + * @param array $configuration + */ + private function parallelDatabaseAddress(array $configuration): array + { + if (in_array($configuration['driver'], ['mysql', 'mariadb'], true) && ! empty($configuration['unix_socket'])) { + return ['socket' => $configuration['unix_socket']]; + } + + $port = $configuration['port'] ?? null; + $database = $configuration['database']; + if ($configuration['driver'] === 'pgsql') { + $port = $configuration['connect_via_port'] ?? $port; + $database = $configuration['connect_via_database'] ?? $database; + } + + return [ + 'host' => (array) ($configuration['host'] ?? []), + 'port' => (string) $port, + 'database' => $database, + ]; } /** diff --git a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php index d4346c4acf..6ab1354a54 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php @@ -24,6 +24,32 @@ class InteractsWithParallelDatabaseTest extends TestCase use InteractsWithParallelDatabase; use VerifiesDoubles; + #[DataProvider('namedConnectionServers')] + public function testNamedConnectionUsesTheWorkerDatabaseOnTheSameServer( + array $endpoints, + array $overrides, + bool $expected + ): void { + $config = $this->app->make('config'); + $default = ['driver' => 'mysql', 'database' => 'app_test_1', 'host' => '127.0.0.1', 'port' => 3306] + $endpoints; + $config->set('database.default', 'primary'); + $config->set('database.connections.primary', $default); + $config->set('database.connections.reporting', array_replace($default, $overrides)); + + $this->assertSame($expected, $this->usesParallelDatabase(DB::connection('reporting'))); + } + + public static function namedConnectionServers(): iterable + { + yield 'copied connection' => [[], [], true]; + yield 'separate server on another port' => [[], ['port' => 3307], false]; + yield 'copied connection with a separate write host' => [ + ['read' => ['host' => 'reader'], 'write' => ['host' => 'writer']], + [], + true, + ]; + } + public function testParallelTestDatabaseAppendsTokenToName(): void { $result = $this->parallelTestDatabase('testing', '3'); From 2f2c31da52b18088c1a75b72f6e3edb94a184996 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:21:51 +0000 Subject: [PATCH 18/19] Recognize equivalent server settings during parallel database setup Compare host candidates independently of their configured order because the connection factory shuffles them. Treat an omitted MySQL or MariaDB port as 3306, the TCP default used by PDO MySQL. Leave an omitted PostgreSQL port to libpq, which can obtain its value from the environment. This lets a named test connection prepare its shared worker database before checking the server version. The regression cases exercise both equivalent configurations and preserve the separate-server check. --- .../Concerns/InteractsWithParallelDatabase.php | 12 +++++++++--- .../Concerns/InteractsWithParallelDatabaseTest.php | 10 ++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php index 9a1b99fee0..a65515eed1 100644 --- a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php +++ b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php @@ -137,11 +137,17 @@ protected function usesParallelDatabase(ConnectionInterface $connection): bool */ private function parallelDatabaseAddress(array $configuration): array { - if (in_array($configuration['driver'], ['mysql', 'mariadb'], true) && ! empty($configuration['unix_socket'])) { + $mysql = in_array($configuration['driver'], ['mysql', 'mariadb'], true); + if ($mysql && ! empty($configuration['unix_socket'])) { return ['socket' => $configuration['unix_socket']]; } - $port = $configuration['port'] ?? null; + // The connection factory shuffles hosts. PDO MySQL defaults to port 3306, + // while libpq can take its port from the environment. + $hosts = (array) ($configuration['host'] ?? []); + sort($hosts, SORT_STRING); + + $port = $configuration['port'] ?? ($mysql ? 3306 : null); $database = $configuration['database']; if ($configuration['driver'] === 'pgsql') { $port = $configuration['connect_via_port'] ?? $port; @@ -149,7 +155,7 @@ private function parallelDatabaseAddress(array $configuration): array } return [ - 'host' => (array) ($configuration['host'] ?? []), + 'host' => $hosts, 'port' => (string) $port, 'database' => $database, ]; diff --git a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php index 6ab1354a54..a3c1d95144 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php @@ -26,12 +26,12 @@ class InteractsWithParallelDatabaseTest extends TestCase #[DataProvider('namedConnectionServers')] public function testNamedConnectionUsesTheWorkerDatabaseOnTheSameServer( - array $endpoints, + array $primary, array $overrides, bool $expected ): void { $config = $this->app->make('config'); - $default = ['driver' => 'mysql', 'database' => 'app_test_1', 'host' => '127.0.0.1', 'port' => 3306] + $endpoints; + $default = $primary + ['driver' => 'mysql', 'database' => 'app_test_1', 'host' => '127.0.0.1']; $config->set('database.default', 'primary'); $config->set('database.connections.primary', $default); $config->set('database.connections.reporting', array_replace($default, $overrides)); @@ -43,6 +43,12 @@ public static function namedConnectionServers(): iterable { yield 'copied connection' => [[], [], true]; yield 'separate server on another port' => [[], ['port' => 3307], false]; + yield 'explicit default port' => [[], ['port' => 3306], true]; + yield 'same hosts in a different order' => [ + ['host' => ['primary', 'replica']], + ['host' => ['replica', 'primary']], + true, + ]; yield 'copied connection with a separate write host' => [ ['read' => ['host' => 'reader'], 'write' => ['host' => 'writer']], [], From a20e88761a600a3406617455fbc0f18d0286e0b0 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:39:34 +0000 Subject: [PATCH 19/19] Preserve cancellation when pruning nested log directories Monolog's recursive iterator skips unreadable directories by suppressing exceptions during traversal. With a stream wrapper that yields, this can discard a cancellation and let the interrupted operation continue. Use Monolog's filename pattern and scan one path segment at a time. Visit only matching directories, leave symlinked directories alone, and skip unreadable subtrees while letting cancellation propagate. Cover cancellation during a nested directory open, retention across empty date directories, and logging when a directory cannot be read. --- src/log/src/Handlers/RotatingFileHandler.php | 59 ++++++++++++ tests/Log/StreamHandlerTest.php | 98 +++++++++++++++++++- 2 files changed, 156 insertions(+), 1 deletion(-) diff --git a/src/log/src/Handlers/RotatingFileHandler.php b/src/log/src/Handlers/RotatingFileHandler.php index 480cfc1f85..91a21f8b57 100644 --- a/src/log/src/Handlers/RotatingFileHandler.php +++ b/src/log/src/Handlers/RotatingFileHandler.php @@ -5,10 +5,13 @@ namespace Hypervel\Log\Handlers; use ErrorException; +use FilesystemIterator; +use Hypervel\Coroutine\Coroutine; use Hypervel\Log\Handlers\Concerns\PerformsSafeStreamOperations; use Monolog\Handler\RotatingFileHandler as MonologRotatingFileHandler; use Monolog\LogRecord; use Override; +use UnexpectedValueException; class RotatingFileHandler extends MonologRotatingFileHandler { @@ -120,4 +123,60 @@ protected function rotate(): void } } } + + /** + * Find rotated files without swallowing cancellation from a stream wrapper. + * + * Monolog's nested iterator uses CATCH_GET_CHILD, which suppresses cancellation along with directory errors. + */ + #[Override] + protected function findRotatedFiles(): array + { + $pattern = $this->getGlobPattern(); + // Monolog quotes literal [, * and ? as bracket expressions in the directory prefix. + preg_match('{^(?:[^*?\[]|\[[*?\[]\])*}', $pattern, $literalPrefix); + $slashPosition = strrpos($literalPrefix[0], '/'); + $directory = $slashPosition === false ? './' : strtr(substr($pattern, 0, $slashPosition + 1), ['[[]' => '[', '[*]' => '*', '[?]' => '?']); + $relativePattern = $slashPosition === false ? $pattern : substr($pattern, $slashPosition + 1); + + $files = []; + $this->collectRotatedFiles($directory, $relativePattern, $files); + + return $files; + } + + /** + * Descend through directories matching each segment of the rotation pattern. + * + * @param list $files + */ + private function collectRotatedFiles(string $directory, string $pattern, array &$files): void + { + [$segment, $remaining] = array_pad(explode('/', $pattern, 2), 2, null); + + try { + $entries = new FilesystemIterator($directory, FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_SELF); + + foreach ($entries as $entry) { + $name = $entry->getFilename(); + if (! fnmatch($segment, $name, FNM_NOESCAPE)) { + continue; + } + + $path = $directory . $name; + if ($remaining === null) { + if (is_file($path)) { + $files[] = $path; + } + } elseif (! is_link($path) && is_dir($path)) { + $this->collectRotatedFiles($path . '/', $remaining, $files); + } + } + } catch (ErrorException|UnexpectedValueException $exception) { + // Skip unreadable directories, but propagate cancellation from stream wrappers. + if (Coroutine::causedByCancellation($exception)) { + throw $exception; + } + } + } } diff --git a/tests/Log/StreamHandlerTest.php b/tests/Log/StreamHandlerTest.php index 4fa6272499..e67e40b9ce 100644 --- a/tests/Log/StreamHandlerTest.php +++ b/tests/Log/StreamHandlerTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Log; use Closure; +use DateTimeImmutable; use ErrorException; use Hypervel\Coroutine\Coroutine; use Hypervel\Engine\Channel; @@ -15,7 +16,9 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use Monolog\Formatter\LineFormatter; +use Monolog\Level; use Monolog\Logger; +use Monolog\LogRecord; use Swoole\Coroutine\CanceledException; use Throwable; use UnexpectedValueException; @@ -337,6 +340,66 @@ public function testRotatingHandlerWritesAndPrunesLogsInTheConfiguredDirectory() $this->assertStringContainsString('rotating message', $files[0]->getContents()); } + public function testNestedLogRotationPrunesEmptyDirectoriesAndSkipsSymlinkedDirectories(): void + { + $logs = $this->directory . '/logs'; + mkdir($logs . '/2000/01', 0777, true); + touch($logs . '/2000/01/01-app.log'); + mkdir($this->directory . '/elsewhere/01', 0777, true); + $outsideLog = $this->directory . '/elsewhere/01/01-app.log'; + touch($outsideLog); + symlink($this->directory . '/elsewhere', $logs . '/1999'); + + $handler = new RotatingFileHandler($logs . '/app.log', 1, dateFormat: 'Y/m/d', filenameFormat: '{date}-{filename}'); + (new Logger('test', [$handler]))->info('rotating message'); + + $this->assertDirectoryDoesNotExist($logs . '/2000'); + $this->assertFileExists($outsideLog); + } + + public function testUnreadableNestedLogDirectoryDoesNotInterruptLogging(): void + { + mkdir($this->directory . '/2000'); + $root = self::STREAM_SCHEME . '://logs'; + $directory = $this->directory; + LogStreamWrapper::$openDirectory = static fn (string $path) => rtrim($path, '/') === $root ? opendir($directory) : false; + + $handler = new RotatingFileHandler($root . '/app.log', 1, dateFormat: 'Y/m/d', filenameFormat: '{date}-{filename}'); + $handler->handle(new LogRecord(new DateTimeImmutable('+1 year'), 'test', Level::Info, 'rotating message')); + + $this->assertStringContainsString('rotating message', LogStreamWrapper::$written); + } + + public function testNestedLogRotationPropagatesCancellationDuringDirectoryDiscovery(): void + { + mkdir($this->directory . '/2000'); + $entered = new Channel(1); + $blocked = new Channel(1); + $result = new Channel(1); + $root = self::STREAM_SCHEME . '://logs'; + LogStreamWrapper::$openDirectory = function (string $path) use ($root, $entered, $blocked) { + if (rtrim($path, '/') === $root . '/2000') { + $entered->push(true); + $blocked->pop(); + } + + return opendir($this->directory . substr(rtrim($path, '/'), strlen($root))); + }; + $handler = new RotatingFileHandler($root . '/app.log', 1, dateFormat: 'Y/m/d', filenameFormat: '{date}-{filename}'); + $writer = Coroutine::create(static function () use ($handler, $result): void { + try { + $handler->handle(new LogRecord(new DateTimeImmutable('+1 year'), 'test', Level::Info, 'rotate')); + $result->push(null); + } catch (Throwable $exception) { + $result->push($exception); + } + }); + + $this->assertTrue($entered->pop(1)); + $this->assertTrue(EngineCoroutine::cancelById($writer, throwException: true)); + $this->assertInstanceOf(CanceledException::class, $result->pop(1)); + } + private function captureOpenFailureMessage(string $message): string { try { @@ -356,6 +419,9 @@ class LogStreamWrapper /** @var null|Closure():bool */ public static ?Closure $opening = null; + /** @var null|Closure(string):(false|resource) */ + public static ?Closure $openDirectory = null; + public static bool $failOpen = false; public static bool $failFirstWrite = false; @@ -381,9 +447,13 @@ class LogStreamWrapper public mixed $context; + /** @var false|resource */ + private mixed $directory; + public static function reset(): void { self::$opening = null; + self::$openDirectory = null; self::$failOpen = false; self::$failFirstWrite = false; self::$maximumWriteLength = null; @@ -396,6 +466,32 @@ public static function reset(): void self::$lockOperations = []; } + public function dir_opendir(string $path, int $options): bool + { + $this->directory = (self::$openDirectory)($path); + + return is_resource($this->directory); + } + + public function dir_readdir(): string|false + { + return readdir($this->directory); + } + + public function dir_rewinddir(): bool + { + rewinddir($this->directory); + + return true; + } + + public function dir_closedir(): bool + { + closedir($this->directory); + + return true; + } + public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool { ++self::$openCount; @@ -485,7 +581,7 @@ private function stat(): array return [ 'dev' => 0, 'ino' => self::$inode, - 'mode' => 0100666, + 'mode' => self::$openDirectory === null ? 0100666 : 0040755, 'nlink' => 1, 'uid' => 0, 'gid' => 0,