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/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/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/docs/todo.md b/docs/todo.md index 07db0872bb..3f9948a137 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,13 +38,8 @@ - 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. - 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/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/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/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/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 */ 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/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/docs/database.md b/src/docs/database.md index fa3fe4fa5c..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+ ([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+ 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/docs/validation.md b/src/docs/validation.md index af7353640a..6e769cf8b2 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 @@ -3490,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/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/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/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/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/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/InteractsWithParallelDatabase.php b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php index 40ef792c32..a65515eed1 100644 --- a/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php +++ b/src/foundation/src/Testing/Concerns/InteractsWithParallelDatabase.php @@ -6,6 +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; @@ -21,8 +24,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 +89,84 @@ 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); + + 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 + { + $mysql = in_array($configuration['driver'], ['mysql', 'mariadb'], true); + if ($mysql && ! empty($configuration['unix_socket'])) { + return ['socket' => $configuration['unix_socket']]; + } + + // 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; + $database = $configuration['connect_via_database'] ?? $database; + } + + return [ + 'host' => $hosts, + 'port' => (string) $port, + 'database' => $database, + ]; + } + /** * 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/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/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/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 ba54d51ca1..91a21f8b57 100644 --- a/src/log/src/Handlers/RotatingFileHandler.php +++ b/src/log/src/Handlers/RotatingFileHandler.php @@ -4,16 +4,22 @@ 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 Throwable; +use UnexpectedValueException; class RotatingFileHandler extends MonologRotatingFileHandler { use PerformsSafeStreamOperations; + /** + * Close the stream and rotate its files when needed. + */ #[Override] public function close(): void { @@ -24,6 +30,9 @@ public function close(): void } } + /** + * Write the record and rotate the log on schedule. + */ #[Override] protected function write(LogRecord $record): void { @@ -43,6 +52,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 +67,13 @@ protected function rotate(): void } try { - $logFiles = glob($this->getGlobPattern()); - } catch (Throwable) { + $logFiles = $this->findRotatedFiles(); + } catch (ErrorException $warning) { + $this->handleStreamWarning($warning); return; } - if ($logFiles === false || $this->maxFiles >= count($logFiles)) { + if ($this->maxFiles >= count($logFiles)) { return; } @@ -75,8 +88,8 @@ protected function rotate(): void try { $deleted = unlink($file); - } catch (Throwable) { - $deleted = false; + } catch (ErrorException $warning) { + $deleted = $this->handleStreamWarning($warning); } if (! $deleted) { @@ -88,8 +101,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) { @@ -98,8 +111,8 @@ protected function rotate(): void try { $removed = rmdir($directory); - } catch (Throwable) { - $removed = false; + } catch (ErrorException $warning) { + $removed = $this->handleStreamWarning($warning); } if (! $removed) { @@ -110,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/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/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/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/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/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/src/testbench/src/Attributes/RequiresDatabase.php b/src/testbench/src/Attributes/RequiresDatabase.php index 107f281f36..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,8 +54,9 @@ public function __construct( * Handle the attribute. * * @param Closure(string, array):void $action + * @param null|Closure(ConnectionInterface):void $prepareDatabase called when the driver matches, before checking its version */ - public function handle(ApplicationContract $app, Closure $action): mixed + public function handle(ApplicationContract $app, Closure $action, ?Closure $prepareDatabase = null): mixed { $connection = DB::connection($this->connection); @@ -82,6 +84,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 ($prepareDatabase !== null) { + $prepareDatabase($connection); + $connection = DB::connection($this->connection); + } + if ( is_string($this->driver) && $this->versionRequirement !== null 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/HandlesDatabases.php b/src/testbench/src/Concerns/HandlesDatabases.php index 89a08f38c0..3da5cd375a 100644 --- a/src/testbench/src/Concerns/HandlesDatabases.php +++ b/src/testbench/src/Concerns/HandlesDatabases.php @@ -6,8 +6,13 @@ use Closure; use Hypervel\Config\Repository; +use Hypervel\Database\ConnectionInterface; 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 +36,28 @@ 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), + function (ConnectionInterface $connection) use ($prepareDatabase): void { + if ($this->usesParallelDatabase($connection)) { + $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/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/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/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/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/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/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/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/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/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/Benchmarks/Sentry/setup-app.sh b/tests/Benchmarks/Sentry/setup-app.sh index 1c2389fdf0..c13ef7e841 100755 --- a/tests/Benchmarks/Sentry/setup-app.sh +++ b/tests/Benchmarks/Sentry/setup-app.sh @@ -23,17 +23,21 @@ 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/Foundation/Testing/Attributes/RequiresDatabaseTest.php b/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php index 9945909daf..3f4ca3b255 100644 --- a/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php +++ b/tests/Foundation/Testing/Attributes/RequiresDatabaseTest.php @@ -4,9 +4,11 @@ namespace Hypervel\Tests\Foundation\Testing\Attributes; +use Hypervel\Database\ConnectionInterface; use Hypervel\Testbench\Attributes\RequiresDatabase; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use PHPUnit\Framework\Attributes\TestWith; class RequiresDatabaseTest extends TestCase { @@ -49,6 +51,28 @@ public function testDoesNotSkipWhenDriverMatches(): void $this->assertFalse($skipped); } + #[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:'], + ]); + + $prepared = null; + (new RequiresDatabase($driver, connection: $connection))->handle( + $this->app, + static function (): void {}, + static function (ConnectionInterface $connection) use (&$prepared): void { + $prepared = $connection->getName(); + }, + ); + + $this->assertSame($expected, $prepared); + } + public function testAcceptsArrayOfDrivers(): void { $attribute = new RequiresDatabase(['sqlite', 'mysql'], connection: null); diff --git a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php index d4346c4acf..a3c1d95144 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php @@ -24,6 +24,38 @@ class InteractsWithParallelDatabaseTest extends TestCase use InteractsWithParallelDatabase; use VerifiesDoubles; + #[DataProvider('namedConnectionServers')] + public function testNamedConnectionUsesTheWorkerDatabaseOnTheSameServer( + array $primary, + array $overrides, + bool $expected + ): void { + $config = $this->app->make('config'); + $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)); + + $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 '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']], + [], + true, + ]; + } + public function testParallelTestDatabaseAppendsTokenToName(): void { $result = $this->parallelTestDatabase('testing', '3'); 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); + } + } +} 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/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 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/Log/StreamHandlerTest.php b/tests/Log/StreamHandlerTest.php index e1b571be6a..e67e40b9ce 100644 --- a/tests/Log/StreamHandlerTest.php +++ b/tests/Log/StreamHandlerTest.php @@ -4,15 +4,23 @@ namespace Hypervel\Tests\Log; +use Closure; +use DateTimeImmutable; 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; 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; use function Hypervel\Coroutine\parallel; @@ -52,9 +60,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 +88,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 +103,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; @@ -275,9 +322,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 +335,69 @@ 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()); + } + + 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 @@ -307,11 +416,11 @@ private function captureOpenFailureMessage(string $message): string class LogStreamWrapper { - public static ?Channel $entered = null; + /** @var null|Closure():bool */ + public static ?Closure $opening = null; - public static ?Channel $release = null; - - public static bool $failOpenAfterYield = false; + /** @var null|Closure(string):(false|resource) */ + public static ?Closure $openDirectory = null; public static bool $failOpen = false; @@ -338,11 +447,13 @@ class LogStreamWrapper public mixed $context; + /** @var false|resource */ + private mixed $directory; + public static function reset(): void { - self::$entered = null; - self::$release = null; - self::$failOpenAfterYield = false; + self::$opening = null; + self::$openDirectory = null; self::$failOpen = false; self::$failFirstWrite = false; self::$maximumWriteLength = null; @@ -355,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; @@ -363,11 +500,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; @@ -447,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, 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/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'); 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)); } /** diff --git a/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php b/tests/Testbench/Databases/ParallelDatabaseRequirementsTest.php index 2eff74cc96..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; @@ -11,10 +12,20 @@ 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, 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; @@ -46,19 +57,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($expectsWorkerDatabase, is_file($database . '_test_' . $environment['TEST_TOKEN'])); } finally { - ParallelDatabaseRequirementsFixture::tearDownAfterClass(); + $fixtureClass::tearDownAfterClass(); } } finally { if ($previousWithoutDatabasesExists) { @@ -88,11 +103,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 +121,45 @@ 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; +} + +#[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:']); + } +} 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) { 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()); } } 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(); }