diff --git a/src/console/src/Commands/ScheduleRunCommand.php b/src/console/src/Commands/ScheduleRunCommand.php index 382df1c5e2..c9e15228e1 100644 --- a/src/console/src/Commands/ScheduleRunCommand.php +++ b/src/console/src/Commands/ScheduleRunCommand.php @@ -123,9 +123,9 @@ class ScheduleRunCommand extends Command protected ?Concurrent $concurrent = null; /** - * The minute currently represented by the evaluated event cache. + * The minute since the Unix epoch currently represented by the evaluated event cache. */ - protected ?string $evaluatedEventsMinute = null; + protected ?int $evaluatedEventsMinute = null; /** * The non-repeatable events already evaluated for the current minute. @@ -293,17 +293,33 @@ protected function repeatEvents(Collection $events): void protected function runEvents(Collection $events, CarbonInterface $startedAt): void { $paused = $this->isPaused(); + $minute = intdiv($startedAt->getTimestamp(), 60); + + // A clock set back into the previous minute doesn't run its events again, while a longer + // correction evaluates the earlier minutes again, as a fresh scheduler would. Every poll + // records its minute, so minutes without due events don't hide a longer correction. + $isPreviousMinute = $this->evaluatedEventsMinute !== null && $minute === $this->evaluatedEventsMinute - 1; + + if (! $isPreviousMinute && $minute !== $this->evaluatedEventsMinute) { + $this->evaluatedEventsMinute = $minute; + $this->evaluatedEvents = []; + } foreach ($events as $event) { if ($this->shouldQuit) { break; } - if ($event->isRepeatable() && $event->lastChecked && ! $event->shouldRepeatNow()) { + // Laravel starts a fresh scheduler each minute, so a repeatable event's first check in a later + // minute runs regardless of the last check. Otherwise a late check would delay later minutes too. + if ($event->isRepeatable() + && $event->lastChecked + && intdiv($event->lastChecked->getTimestamp(), 60) >= $minute + && ! $event->shouldRepeatNow()) { continue; } - if ($this->hasAlreadyEvaluatedNonRepeatableEvent($event, $startedAt)) { + if ($this->hasAlreadyEvaluatedNonRepeatableEvent($event, $isPreviousMinute)) { continue; } @@ -419,17 +435,14 @@ protected function runScheduledEvent(Event $event, CarbonInterface $startedAt): /** * Determine if the non-repeatable event was already evaluated this minute. */ - protected function hasAlreadyEvaluatedNonRepeatableEvent(Event $event, CarbonInterface $startedAt): bool + protected function hasAlreadyEvaluatedNonRepeatableEvent(Event $event, bool $isPreviousMinute): bool { if ($event->isRepeatable()) { return false; } - $minute = $startedAt->format('YmdHi'); - - if ($this->evaluatedEventsMinute !== $minute) { - $this->evaluatedEventsMinute = $minute; - $this->evaluatedEvents = []; + if ($isPreviousMinute) { + return true; } $eventId = spl_object_id($event); diff --git a/src/console/src/Scheduling/Event.php b/src/console/src/Scheduling/Event.php index 254f7259d6..9d956f6743 100644 --- a/src/console/src/Scheduling/Event.php +++ b/src/console/src/Scheduling/Event.php @@ -399,8 +399,9 @@ protected function expressionPasses(DateTimeInterface $time): bool $date = $date->setTimezone($this->timezone); } - return (new CronExpression($this->expression)) - ->isDue($date->toDateTimeString()); + // Laravel passes a formatted string, which is read in the application's timezone and + // matches the wrong times around that timezone's daylight saving changes + return (new CronExpression($this->expression))->isDue($date); } /** diff --git a/src/docs/permission.md b/src/docs/permission.md index cea7b443da..c4a23c739a 100644 --- a/src/docs/permission.md +++ b/src/docs/permission.md @@ -60,6 +60,7 @@ - [Deleting Models](#deleting-models) - [UUID and ULID Keys](#uuid-and-ulid-keys) - [Caching](#caching) + - [Global Scopes and Multitenancy](#global-scopes-and-multitenancy) - [Testing and Seeding](#testing-and-seeding) - [Seeding](#seeding) - [Testing](#testing) @@ -1051,7 +1052,7 @@ The `@hasrole` directive is an alias of `@role`. Role directives accept a role n ## Route Macros -Routes also receive permission macros: +Routes and route groups also receive `role`, `permission`, and `roleOrPermission` macros, which accept a string, an array, or an [enum](#using-enums): ```php Route::get('/admin', [AdminController::class, 'index'])->role('admin'); @@ -1060,8 +1061,52 @@ Route::get('/posts/edit', [PostController::class, 'edit'])->permission('edit art Route::get('/content', [ContentController::class, 'index']) ->roleOrPermission(['editor', 'edit articles']); + +Route::permission('publish articles')->group(function () { + // ... +}); + +Route::prefix('admin')->middleware('auth')->role('manager')->group(function () { + // ... +}); ``` +The `canAny` and `canAll` macros check a list of permissions, requiring any one of them or all of them. They work on individual routes and groups, accepting strings, enums, or arrays containing either: + +```php +Route::get('/articles', [ArticleController::class, 'index']) + ->canAny(['publish articles', 'edit articles']); + +Route::get('/articles', [ArticleController::class, 'index']) + ->canAll(['publish articles', 'edit articles']); + +Route::middleware('auth:admin')->canAll(['publish articles', 'edit articles'])->group(function () { + // Requires both permissions for the authenticated admin. +}); +``` + +These macros use the package's permission middleware; the route's own `can` method is unchanged. `canAny` is an alias for `permission`. `canAll` adds a permission middleware check for each array entry, so use separate entries to require separate permissions: a string separated by `|` still requires only one of its permissions. An empty `canAll([])` adds no checks, so apply authentication middleware separately when needed. + +On route groups, call `middleware` before `role`, `permission`, `roleOrPermission`, `canAny`, or `canAll`. Calling `middleware` again on a group replaces the group's middleware, so calling it after one of these macros removes the role or permission check: + +```php +Route::middleware('auth')->role('manager')->permission('publish articles')->group(function () { + // Requires authentication, the manager role, and the publish articles permission. +}); +``` + +To add more middleware without replacing the group's authorization checks, use a nested group: + +```php +Route::middleware('auth')->role('manager')->group(function () { + Route::middleware('throttle:60,1')->group(function () { + // Requires authentication, the manager role, and the rate limit. + }); +}); +``` + +Individual routes, such as `Route::get(...)->role('manager')->middleware('auth')`, add the middleware rather than replacing it. + ## Custom Permission Checks @@ -1824,6 +1869,22 @@ app(PermissionRegistrar::class)->forgetCachedPermissions(); If you reset the cache inside a database transaction, the reset is applied after the transaction commits and discarded if it rolls back. The method returns `true` once such a reset has been registered. When row partitioning is enabled, the reset applies only to the current partition. + +### Global Scopes and Multitenancy + +The package fills the cached catalog and each model's cached assignments by querying your configured role and permission models, so Eloquent global scopes on either model apply to these queries. + +The cache is shared between requests and jobs, so a scope that depends on the current request can affect later permission checks. For example, if a request for tenant A fills the cache while a global scope limits roles to tenant A, tenant B's roles will be missing from the catalog. A later request for tenant B can then deny permissions its roles should grant. Request-specific scopes on the permission model cause the same problem. + +Teams don't prevent this. Every team shares the catalog, and selecting a team with `setPermissionsTeamId()` doesn't change which global scopes apply when the cache is filled. + +Choose an approach that matches what the scope is for: + +- If the scope only filters an administration screen, apply it to that screen's queries instead of registering it globally on the role or permission model. Check whether a package you use registers such a scope on these models. +- If authorization must be limited to the current tenant, use [row partitioning](#row-partitioning), which separates each tenant's rows and cache entries. + +After correcting the scope, reset the permission cache as shown above. Resetting the cache on every request does not solve this problem, since the next fill still uses whichever scopes are active at that time. + ## Testing and Seeding diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 87067cbadd..2efd13c99b 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -1029,6 +1029,8 @@ When porting an application, start from a fresh Hypervel application skeleton an Do not replace the Hypervel skeleton's `composer.json`, `bootstrap/app.php`, `config` directory, `.env.example`, or `phpunit.xml` with their Laravel counterparts. Move application providers into `bootstrap/providers.php`, move routes into Hypervel's `routes` files, and configure middleware through the Hypervel `bootstrap/app.php` file. Transfer environment values into the corresponding Hypervel configuration keys instead of copying the Laravel environment file unchanged. +Use Hypervel's migrations for framework tables such as jobs, job batches, sessions, and cache. Bring over migrations for your application's own tables and reapply any customizations to framework tables on top of Hypervel's schema. If you're keeping an existing database, preserve its migration history and keep the skeleton's migrations only for framework tables the database doesn't have yet, since the others would try to create tables that already exist. Then write new migrations for the changes needed to bring its existing framework tables in line with Hypervel's schema. Once those migrations have run, [dump the database schema](/docs/{{version}}/migrations#squashing-migrations) with its migration records. Fresh databases then start from the dump, since no remaining migration creates the framework tables the database already had. + Hypervel runs its Swoole HTTP server using `php artisan serve` and does not use `public/index.php` as its HTTP entry point. Review the [deployment documentation](/docs/{{version}}/deployment) before adapting web server or process-monitor configuration. Build production releases with `composer install --no-dev --classmap-authoritative` instead of `--optimize-autoloader`; Doctor fails production checks without an authoritative class map. See [Autoloader Optimization](/docs/{{version}}/deployment#autoloader-optimization). diff --git a/src/docs/saloon.md b/src/docs/saloon.md index 470db843e8..dffd7f4133 100644 --- a/src/docs/saloon.md +++ b/src/docs/saloon.md @@ -641,7 +641,7 @@ class AnthropicConnector extends Connector } ``` -In URL mode, the version replaces a `{version}` placeholder in the base URL, endpoint, or URL override, such as `https://generativelanguage.googleapis.com/{version}`. The version may only contain letters, numbers, dashes, underscores, and single dots, so it can only fill that subdomain label or path segment. You may override `getApiVersion` to calculate the version. When both a connector and a request send a version, the request's version is used. +In URL mode, the version replaces a `{version}` placeholder in the base URL, endpoint, or URL override, such as `https://generativelanguage.googleapis.com/{version}`. The version may only contain letters, numbers, dashes, underscores, and single dots, so it can only fill that subdomain label or path segment. You may override `getApiVersion` to calculate the version. When a connector and a request both send a version in the same place, the request's version is used. To choose the version substituted into the URL differently, a connector with an API version may override the protected `resolveUrlApiVersion` method, which receives the pending request. ### Authentication diff --git a/src/docs/sentry.md b/src/docs/sentry.md index 0bd1abcff3..8fd972f073 100644 --- a/src/docs/sentry.md +++ b/src/docs/sentry.md @@ -196,7 +196,7 @@ To enable performance monitoring, configure a trace sample rate between `0.0` an SENTRY_TRACES_SAMPLE_RATE=0.1 ``` -The default configuration traces requests, database queries, HTTP client requests, cache operations, queued jobs, notifications, and views. The conventional `/up` health route path is ignored by default. +The default configuration traces requests, database queries, HTTP client requests, cache operations, queued jobs, notifications, and views. The conventional `/up` health route path and the Horizon and Telescope routes are ignored by default. Cache spans and breadcrumbs follow cache repository events. Configured stores honor their `events` option, but the `failover` store defaults this option to `false`; enable it explicitly when failover operations should produce telemetry. `Cache::memo()` does not emit a second event for its memoization layer, while operations that reach the wrapped repository follow that store's setting. @@ -368,6 +368,17 @@ Schedule::command('reports:generate') When no monitor slug is given, one is derived from the task's command or description. The macro also accepts the `checkInMargin`, `maxRuntime`, `failureIssueThreshold`, and `recoveryThreshold` monitor settings. Pass `updateMonitorConfig: false` when the monitor is configured in Sentry instead. +To monitor every scheduled task without calling `sentryMonitor` on each one, set the `SENTRY_CRONS_MONITOR_SCHEDULED_TASKS` environment variable to `true`. Tasks that call `sentryMonitor` keep their own settings. You may leave tasks out by listing their monitor slugs, commands, or names in the `crons.exclude_scheduled_tasks` configuration option, using `*` as a wildcard. Unless you give a scheduled job a name, it's named after its class, or by its `displayName` method when you schedule a job instance that has one: + +```php +'crons' => [ + 'monitor_scheduled_tasks' => (bool) env('SENTRY_CRONS_MONITOR_SCHEDULED_TASKS', false), + 'exclude_scheduled_tasks' => ['horizon:snapshot', 'scheduled_reports-*'], +], +``` + +Tasks are only monitored automatically when Sentry can expect every run, so closures without a `name`, tasks that share a slug, sub-minute tasks, tasks with a timezone offset instead of a timezone name, tasks limited by `between`, `unlessBetween`, `when`, or `skip`, and schedules Sentry would read differently, such as some times of day that a daylight saving change skips, are left out. Only a task's time and weekday are compared with daylight saving changes, so a task at such a time can be left out even if its dates never have a change. Call `sentryMonitor` on such a task to monitor it yourself. + Sentry expects a check-in for every run of the task's schedule. Tasks limited by `between`, `unlessBetween`, `when`, or `skip` do not check in when they are skipped, so their skipped runs are reported as missed. Prefer expressing the schedule with the `cron` method. Failed runs check in as errors, including failures before completion callbacks run. When coroutine cancellation interrupts a run without a known failure, any unfinished check-in is left open because Sentry has no canceled status. Sentry later reports it as timed out. An earlier task failure, or a cleanup failure before the task's outcome is known, still produces an error check-in. diff --git a/src/permission/src/PermissionServiceProvider.php b/src/permission/src/PermissionServiceProvider.php index 424e34b7e3..91c815af41 100644 --- a/src/permission/src/PermissionServiceProvider.php +++ b/src/permission/src/PermissionServiceProvider.php @@ -21,6 +21,8 @@ use Hypervel\Permission\Middleware\RoleMiddleware; use Hypervel\Permission\Middleware\RoleOrPermissionMiddleware; use Hypervel\Routing\Route; +use Hypervel\Routing\Router; +use Hypervel\Routing\RouteRegistrar; use Hypervel\Support\Arr; use Hypervel\Support\Collection; use Hypervel\Support\ServiceProvider; @@ -156,6 +158,92 @@ protected function registerMacroHelpers(): void /** @var Route $this */ return $this->middleware('role_or_permission:' . implode('|', $rolesOrPermissions)); }); + + RouteRegistrar::macro('role', function (mixed $roles = []): RouteRegistrar { + $roles = Arr::wrap($roles); + $roles = array_map(enum_value(...), $roles); + + /** @var RouteRegistrar $this */ + return $this->middleware([...($this->attributes['middleware'] ?? []), 'role:' . implode('|', $roles)]); + }); + + RouteRegistrar::macro('permission', function (mixed $permissions = []): RouteRegistrar { + $permissions = Arr::wrap($permissions); + $permissions = array_map(enum_value(...), $permissions); + + /** @var RouteRegistrar $this */ + return $this->middleware([...($this->attributes['middleware'] ?? []), 'permission:' . implode('|', $permissions)]); + }); + + RouteRegistrar::macro('roleOrPermission', function (mixed $rolesOrPermissions = []): RouteRegistrar { + $rolesOrPermissions = Arr::wrap($rolesOrPermissions); + $rolesOrPermissions = array_map(enum_value(...), $rolesOrPermissions); + + /** @var RouteRegistrar $this */ + return $this->middleware([...($this->attributes['middleware'] ?? []), 'role_or_permission:' . implode('|', $rolesOrPermissions)]); + }); + + Router::macro('role', function (mixed $roles = []): RouteRegistrar { + $roles = Arr::wrap($roles); + $roles = array_map(enum_value(...), $roles); + + /** @var Router $this */ + return $this->middleware('role:' . implode('|', $roles)); + }); + + Router::macro('permission', function (mixed $permissions = []): RouteRegistrar { + $permissions = Arr::wrap($permissions); + $permissions = array_map(enum_value(...), $permissions); + + /** @var Router $this */ + return $this->middleware('permission:' . implode('|', $permissions)); + }); + + Router::macro('roleOrPermission', function (mixed $rolesOrPermissions = []): RouteRegistrar { + $rolesOrPermissions = Arr::wrap($rolesOrPermissions); + $rolesOrPermissions = array_map(enum_value(...), $rolesOrPermissions); + + /** @var Router $this */ + return $this->middleware('role_or_permission:' . implode('|', $rolesOrPermissions)); + }); + + Route::macro('canAny', function (mixed $permissions = []): Route { + /** @var Route $this */ + return $this->permission($permissions); + }); + + Route::macro('canAll', function (mixed $permissions = []): Route { + foreach (Arr::wrap($permissions) as $permission) { + /** @var Route $this */ + $this->permission($permission); + } + + return $this; + }); + + RouteRegistrar::macro('canAny', function (mixed $permissions = []): RouteRegistrar { + /** @var RouteRegistrar $this */ + return $this->permission($permissions); + }); + + RouteRegistrar::macro('canAll', function (mixed $permissions = []): RouteRegistrar { + foreach (Arr::wrap($permissions) as $permission) { + /** @var RouteRegistrar $this */ + $this->permission($permission); + } + + return $this; + }); + + Router::macro('canAny', function (mixed $permissions = []): RouteRegistrar { + /** @var Router $this */ + return $this->permission($permissions); + }); + + Router::macro('canAll', function (mixed $permissions = []): RouteRegistrar { + /** @var Router $this */ + return (new RouteRegistrar($this))->canAll($permissions); + }); } /** diff --git a/src/permission/src/Relations/DisabledTeamsMorphToMany.php b/src/permission/src/Relations/DisabledTeamsMorphToMany.php new file mode 100644 index 0000000000..9f31955189 --- /dev/null +++ b/src/permission/src/Relations/DisabledTeamsMorphToMany.php @@ -0,0 +1,89 @@ + + */ +class DisabledTeamsMorphToMany extends MorphToMany +{ + /** + * Reject attaching models, since teams are disabled. + * + * @throws TeamsNotEnabled + */ + public function attach(mixed $ids, array $attributes = [], bool $touch = true): void + { + throw TeamsNotEnabled::create(); + } + + /** + * Reject querying the pivot table, since teams are disabled. + * + * Syncing, toggling, detaching and updating pivot records all start here, so this + * rejects them even when they would find nothing to change. + * + * @throws TeamsNotEnabled + */ + public function newPivotQuery(): QueryBuilder + { + throw TeamsNotEnabled::create(); + } + + /** + * Get all of the IDs for the related models, of which there are none. + * + * @return Collection + */ + public function allRelatedIds(): Collection + { + return new Collection; + } + + /** + * Reject saving a related model, since teams are disabled. + * + * @throws TeamsNotEnabled + */ + public function save(Model $model, array $pivotAttributes = [], bool $touch = true): Model + { + throw TeamsNotEnabled::create(); + } + + /** + * Reject creating a related model, since teams are disabled. + * + * @throws TeamsNotEnabled + */ + public function create(array $attributes = [], array $joining = [], bool $touch = true): Model + { + throw TeamsNotEnabled::create(); + } + + /** + * Reject force creating a related model, since teams are disabled. + * + * @throws TeamsNotEnabled + */ + public function forceCreate(array $attributes = [], array $joining = [], bool $touch = true): Model + { + throw TeamsNotEnabled::create(); + } +} diff --git a/src/permission/src/Traits/HasRoles.php b/src/permission/src/Traits/HasRoles.php index 45e76f787c..0dbc7e7e40 100644 --- a/src/permission/src/Traits/HasRoles.php +++ b/src/permission/src/Traits/HasRoles.php @@ -15,6 +15,7 @@ use Hypervel\Permission\Events\RoleDetachedEvent; use Hypervel\Permission\Guard; use Hypervel\Permission\PermissionRegistrar; +use Hypervel\Permission\Relations\DisabledTeamsMorphToMany; use Hypervel\Permission\Support\Config; use Hypervel\Permission\Support\PermissionPartition; use Hypervel\Permission\Support\PermissionRelationContext; @@ -263,16 +264,25 @@ public function scopeWithoutRole(Builder $query, array|Collection|int|Role|strin * * When the teams feature is disabled this returns an empty BelongsToMany so * tooling that introspects model relations (e.g. ide-helper:models) does not - * break. Querying it is a no-op and produces no rows. + * break. Querying it is a no-op and produces no rows, and attaching, detaching, + * syncing, saving or creating through it throws. */ public function teams(): BelongsToMany { if (! Config::teamsEnabled()) { - $relation = $this->permissionMorphToMany( - Config::permissionModel(), - Config::modelHasRolesTable(), + // Unlike upstream's permissions()->whereRaw('1 = 0'), writes through this relation can't change the + // model's direct permissions, and loading it doesn't mark them as loaded. + $permission = $this->newRelatedInstance(Config::permissionModel()); + + $relation = new DisabledTeamsMorphToMany( + $permission->newQuery(), + $this, + Config::MORPH_NAME, + Config::modelHasPermissionsTable(), Config::morphKey(), - Config::teamForeignKey(), + $this->permissionRegistrar()->pivotPermission, + $this->getKeyName(), + $permission->getKeyName(), 'teams', ); diff --git a/src/saloon/src/Traits/Plugins/HasApiVersion.php b/src/saloon/src/Traits/Plugins/HasApiVersion.php index 4b5d8f6dbb..0c7b2a371c 100644 --- a/src/saloon/src/Traits/Plugins/HasApiVersion.php +++ b/src/saloon/src/Traits/Plugins/HasApiVersion.php @@ -5,7 +5,9 @@ namespace Hypervel\Saloon\Traits\Plugins; use Hypervel\Saloon\Enums\VersionMode; +use Hypervel\Saloon\Http\Connector; use Hypervel\Saloon\Http\PendingRequest; +use Hypervel\Saloon\Http\Request; use InvalidArgumentException; trait HasApiVersion @@ -36,11 +38,26 @@ public function getApiVersion(): ?string return $this->apiVersion; } + /** + * Get where the API version is applied to the request. + */ + public function getVersionMode(): VersionMode + { + return $this->versionMode; + } + /** * Boot HasApiVersion plugin. */ public function bootHasApiVersion(PendingRequest $pendingRequest): void { + // The connector boots first, and its resolveUrlApiVersion() has already chosen the URL version for the request + if ($this->versionMode === VersionMode::Url + && $pendingRequest->connector() !== $this + && $this->getUrlApiVersionOf($pendingRequest->connector()) !== null) { + return; + } + $version = $this->getApiVersion(); if ($version === null || $version === '') { @@ -51,10 +68,43 @@ public function bootHasApiVersion(PendingRequest $pendingRequest): void match ($this->versionMode) { VersionMode::Header => $pendingRequest->replaceHeaders([$this->versionKey => $version]), VersionMode::QueryParam => $pendingRequest->withQueryParameters([$this->versionKey => $version]), - VersionMode::Url => $pendingRequest->withUrlParameters(['version' => $this->ensureVersionIsSafeForUrl($version)]), + VersionMode::Url => $pendingRequest->withUrlParameters([ + 'version' => $this->ensureVersionIsSafeForUrl($this->resolveUrlApiVersion($pendingRequest)), + ]), }; } + /** + * Resolve which version to substitute into `{version}` for URL mode. + */ + protected function resolveUrlApiVersion(PendingRequest $pendingRequest): string + { + $requestVersion = $pendingRequest->connector() === $this + ? $this->getUrlApiVersionOf($pendingRequest->request()) + : null; + + // @phpstan-ignore return.type (bootHasApiVersion() only resolves a URL version after finding one) + return $requestVersion ?? $this->getApiVersion(); + } + + /** + * Get the version a connector or request substitutes into its URL, if it uses this plugin in URL mode. + */ + private function getUrlApiVersionOf(Connector|Request $resource): ?string + { + // A lookalike getApiVersion() without this plugin doesn't version the URL + if (! in_array(HasApiVersion::class, class_uses_recursive($resource), true) + // @phpstan-ignore method.notFound (the plugin provides it) + || $resource->getVersionMode() !== VersionMode::Url) { + return null; + } + + // @phpstan-ignore method.notFound (the plugin provides it) + $version = $resource->getApiVersion(); + + return is_string($version) && $version !== '' ? $version : null; + } + /** * Ensure the version can only ever form a single subdomain label or path segment. * diff --git a/src/sentry/composer.json b/src/sentry/composer.json index cb29e8429e..a724c4dc47 100644 --- a/src/sentry/composer.json +++ b/src/sentry/composer.json @@ -31,6 +31,7 @@ "require": { "php": "^8.4", "ext-filter": "*", + "dragonmantank/cron-expression": "^3.4", "guzzlehttp/psr7": "^3.1", "hypervel/attributes": "^0.4", "hypervel/auth": "^0.4", diff --git a/src/sentry/config/sentry.php b/src/sentry/config/sentry.php index d562efca74..7795abc562 100644 --- a/src/sentry/config/sentry.php +++ b/src/sentry/config/sentry.php @@ -87,6 +87,9 @@ 'ignore_transactions' => [ // Ignore Hypervel's default health URL '/up', + + // Ignore the Hypervel Horizon and Hypervel Telescope routes + '/^\/(horizon|telescope)(\/|$)/', ], // Breadcrumb specific configuration @@ -123,6 +126,15 @@ 'notifications' => (bool) env('SENTRY_BREADCRUMBS_NOTIFICATIONS_ENABLED', true), ], + // Crons monitoring specific configuration + 'crons' => [ + // Monitor every scheduled task as if `->sentryMonitor()` was called on it + 'monitor_scheduled_tasks' => (bool) env('SENTRY_CRONS_MONITOR_SCHEDULED_TASKS', false), + + // Monitor slugs, commands with their arguments, job classes or task descriptions of tasks that are not monitored automatically, `*` is a wildcard + 'exclude_scheduled_tasks' => [], + ], + // Performance monitoring specific configuration 'tracing' => [ // Trace queue jobs as their own transactions (this enables tracing for queue jobs) diff --git a/src/sentry/src/Features/Classification/ClassificationMessageFormatter.php b/src/sentry/src/Features/Classification/ClassificationMessageFormatter.php index 662c363259..9b2c6ba4a6 100644 --- a/src/sentry/src/Features/Classification/ClassificationMessageFormatter.php +++ b/src/sentry/src/Features/Classification/ClassificationMessageFormatter.php @@ -131,6 +131,8 @@ private static function withConfidence(array $formatted, ?float $confidence): ar /** * Encode a complete evaluation message without truncating JSON. + * + * @param array $message */ private static function encode(array $message): ?string { diff --git a/src/sentry/src/Features/ConsoleSchedulingIntegration.php b/src/sentry/src/Features/ConsoleSchedulingIntegration.php index 085a1ee9b7..66c332d156 100644 --- a/src/sentry/src/Features/ConsoleSchedulingIntegration.php +++ b/src/sentry/src/Features/ConsoleSchedulingIntegration.php @@ -4,16 +4,22 @@ namespace Hypervel\Sentry\Features; +use Cron\CronExpression; +use DateTimeImmutable; use DateTimeZone; use Hypervel\Console\Application as ConsoleApplication; +use Hypervel\Console\Events\CommandStarting; use Hypervel\Console\Events\ScheduledTaskCanceled; use Hypervel\Console\Events\ScheduledTaskFailed; use Hypervel\Console\Events\ScheduledTaskFinished; use Hypervel\Console\Events\ScheduledTaskStarting; use Hypervel\Console\Scheduling\Event as SchedulingEvent; +use Hypervel\Console\Scheduling\Schedule; use Hypervel\Context\CoroutineContext; +use Hypervel\Coroutine\Coroutine; use Hypervel\Sentry\Features\Concerns\TracksPushedScopesAndSpans; use Hypervel\Sentry\Features\Concerns\WorksWithSpans; +use Hypervel\Support\Facades\Date; use Hypervel\Support\Str; use RuntimeException; use Sentry\CheckIn; @@ -25,6 +31,8 @@ use Sentry\Tracing\SpanStatus; use Sentry\Tracing\TransactionContext; use Sentry\Tracing\TransactionSource; +use Throwable; +use WeakMap; class ConsoleSchedulingIntegration extends Feature { @@ -38,11 +46,23 @@ class ConsoleSchedulingIntegration extends Feature private bool $shouldHandleCheckIn = false; + /** + * The scheduled tasks that `sentryMonitor()` was called on, with their explicit slug or `false`. + * + * Weak keys let schedules built by other `resolveConsoleSchedule()` calls be freed. + * + * @var WeakMap + */ + private WeakMap $monitoredTasks; + /** * Register the `sentryMonitor` scheduling macro. */ public function register(): void { + $this->monitoredTasks = new WeakMap; + $monitoredTasks = $this->monitoredTasks; + $startCheckIn = function ( ?string $slug, SchedulingEvent $scheduled, @@ -76,7 +96,7 @@ public function register(): void ?int $failureIssueThreshold = null, ?int $recoveryThreshold = null, ?string $schedule = null - ) use ($startCheckIn, $finishCheckIn): SchedulingEvent { + ) use ($startCheckIn, $finishCheckIn, $monitoredTasks): SchedulingEvent { /** @var SchedulingEvent $this */ if ($monitorSlug === null && empty($this->command) && empty($this->description)) { throw new RuntimeException( @@ -84,6 +104,9 @@ public function register(): void ); } + // A WeakMap treats a null value as missing, so an implicit slug is stored as false. + $monitoredTasks[$this] = $monitorSlug ?? false; + return $this ->before(function () use ( $startCheckIn, @@ -139,6 +162,10 @@ public function onBoot(): void $dispatcher->listen(ScheduledTaskFailed::class, [$this, 'handleScheduledTaskFailed']); $dispatcher->listen(ScheduledTaskCanceled::class, [$this, 'handleScheduledTaskCanceled']); + if ($this->getUserConfig()['crons']['monitor_scheduled_tasks'] === true) { + $dispatcher->listen(CommandStarting::class, [$this, 'handleCommandStarting']); + } + if (! $this->canRecordSpans()) { return; } @@ -147,6 +174,29 @@ public function onBoot(): void $dispatcher->listen(ScheduledTaskFinished::class, [$this, 'handleScheduledTaskFinished']); } + /** + * Call `sentryMonitor()` on every scheduled task before the scheduler runs them. + */ + public function handleCommandStarting(CommandStarting $event): void + { + // Unlike upstream, there is no `schedule:finish`: background tasks finish in the scheduler process. + if (! in_array($event->command, ['schedule:run', 'schedule:test'], true)) { + return; + } + + try { + $this->monitorScheduledTasks($this->container->make(Schedule::class)); + } catch (Throwable $exception) { + // Resolving the schedule runs the application's schedule definitions, which a cancellation can interrupt. + if (Coroutine::causedByCancellation($exception)) { + throw $exception; + } + + SentrySdk::getCurrentHub()->getClient()?->getOptions()->getLoggerOrNullLogger() + ->warning('Failed to set up cron monitoring for scheduled tasks.', ['exception' => $exception]); + } + } + /** * Set up the feature in the environment in an inactive state (when no DSN was set). */ @@ -229,6 +279,187 @@ private function finishedStatus(SchedulingEvent $task): SpanStatus : SpanStatus::internalError(); } + /** + * Monitor every scheduled task that is not monitored, excluded or ambiguous. + */ + private function monitorScheduledTasks(Schedule $schedule): void + { + $excluded = $this->getUserConfig()['crons']['exclude_scheduled_tasks']; + $monitoredSlugs = []; + $tasksBySlug = []; + $taskSlugs = []; + + foreach ($schedule->events() as $task) { + if (isset($this->monitoredTasks[$task])) { + $explicitSlug = $this->monitoredTasks[$task]; + $monitoredSlugs[$explicitSlug === false ? $this->makeSlugForScheduled($task) : $explicitSlug] = true; + + continue; + } + + // Closures without a name have nothing to make a stable slug from + if (empty($task->command) && empty($task->description)) { + continue; + } + + $slug = $this->makeSlugForScheduled($task); + // Sentry cuts slugs at 50 characters + $taskSlug = strlen($slug) > 50 ? substr($slug, 0, 41) . '_' . hash('crc32b', $slug) : $slug; + + if (! $this->isExcluded($task, $slug, $taskSlug, $excluded)) { + $tasksBySlug[$slug][] = $task; + $taskSlugs[$slug] = $taskSlug; + } + } + + foreach ($tasksBySlug as $slug => $tasks) { + $taskSlug = $taskSlugs[$slug]; + + // Task order isn't stable, so a shared slug can't be given to any one of the tasks + if (count($tasks) > 1 || isset($monitoredSlugs[$slug]) || isset($monitoredSlugs[$taskSlug])) { + SentrySdk::getCurrentHub()->getClient()?->getOptions()->getLoggerOrNullLogger()->warning(sprintf( + 'Not monitoring scheduled tasks with the slug "%s" because more than one task uses it. Give each task a unique slug with `->sentryMonitor(\'your-monitor-slug\')`.', + $slug + )); + + continue; + } + + $crontab = $this->getMonitorCrontab($tasks[0]); + + if ($crontab === null) { + SentrySdk::getCurrentHub()->getClient()?->getOptions()->getLoggerOrNullLogger()->debug(sprintf( + 'Not monitoring the scheduled task "%s" because Sentry can\'t match its schedule.', + $slug + )); + + continue; + } + + $tasks[0]->sentryMonitor($taskSlug, null, null, true, null, null, $crontab); + } + } + + /** + * Determine if the scheduled task matches an excluded slug, command or description. + * + * @param array $excluded + */ + private function isExcluded(SchedulingEvent $task, string $slug, string $taskSlug, array $excluded): bool + { + // Unlike upstream, the shortened slug that Sentry shows is matched too + foreach ([$slug, $taskSlug, $this->getCommandNameForScheduled($task), $task->description] as $name) { + if ($name !== null && $name !== '' && Str::is($excluded, $name)) { + return true; + } + } + + return false; + } + + /** + * Get the crontab Sentry should expect, or null when Sentry would expect runs that the task skips or reads it differently. + */ + private function getMonitorCrontab(SchedulingEvent $task): ?string + { + $hasConditions = (function (): bool { + /** @var SchedulingEvent $this */ + // `withoutOverlapping()` adds a reject, but an overlap means the previous run is late anyway + return count($this->filters) > 0 || count($this->rejects) > ($this->withoutOverlapping ? 1 : 0); + })->call($task); + + // Without a timezone the check-in is read as UTC, and Sentry needs a timezone name, not an offset + $timezone = $task->timezone instanceof DateTimeZone ? $task->timezone : new DateTimeZone($task->timezone ?? 'UTC'); + $isTimezoneSupported = $timezone->getLocation() !== false && ($task->timezone !== null || date_default_timezone_get() === 'UTC'); + + // Sub-minute tasks (`everyTenSeconds()`) can't be expressed as a crontab + if ($hasConditions || $task->repeatSeconds !== null || ! $isTimezoneSupported) { + return null; + } + + // cron-expression reads "?" as "*" + $fields = preg_split('/\s+/', trim(str_replace('?', '*', $task->getExpression()))); + + if ($fields === false || count($fields) !== 5) { + return null; + } + + // With both day fields restricted, cron-expression runs on either day, while Sentry's parser depends on a leading "*" + if ($fields[2] !== '*' && $fields[4] !== '*') { + return null; + } + + // Unlike upstream, a day of month equal to this month's last day stays monitored: Hypervel's + // `lastDayOfMonth()` writes "L" rather than the day number, so the crontab doesn't change each month. + + foreach ($fields as $position => $field) { + foreach (explode(',', $field) as $item) { + // Only items cron-expression and Sentry read the same way; a step from a number such as "5/15" isn't one + $isSupported = preg_match('/^(?:(?:\*|\d+-\d+)(?:\/\d+)?|\d+|[a-z]{3}(?:-[a-z]{3})?)$/i', $item) + || ($position === 2 && $item === 'L') + || ($position === 4 && preg_match('/^(?:\d(?:L|#[1-5])|[a-z]{3}#[1-5])$/i', $item)); + + if (! $isSupported) { + return null; + } + + if (preg_match('/^(?:\*|(\d+)-(\d+))(?:\/(\d+))?$/', $item, $range) === 1) { + [, $start, $end, $step] = $range + ['', '', '', '']; + + // The parsers also differ on a range of one value, a step as large as the field's last + // value, and a stepped weekday range ending at 7: Sentry reads "0-7/2" with Sundays + if (($start !== '' && (int) $start === (int) $end) + || ($step !== '' && ((int) $step >= [59, 23, 31, 12, 7][$position] || ($position === 4 && (int) $end === 7)))) { + return null; + } + } + } + } + + // Like Debian cron, Sentry expects a task with a set minute and hour that a clock change skips to run + // when the change ends, which the scheduler doesn't always do. Clock changes fall on the same weekday + // each year but not the same date, so only the time and weekday are compared, unless the weekday + // depends on the date, as "5L" and "1#2" do. + if (! str_starts_with($fields[0], '*') && ! str_starts_with($fields[1], '*')) { + $weekday = preg_match('/[L#]/i', $fields[4]) === 1 ? '*' : $fields[4]; + + if ($this->runsLateAfterClockChange(new CronExpression("{$fields[0]} {$fields[1]} * * {$weekday}"), $timezone)) { + return null; + } + } + + return implode(' ', $fields); + } + + /** + * Determine if the schedule falls in local times that a clock change skips, but isn't due when the change ends. + */ + private function runsLateAfterClockChange(CronExpression $cron, DateTimeZone $timezone): bool + { + $now = Date::now()->getTimestamp(); + // Two years always include each yearly change, which can be up to 371 days apart + $transitions = $timezone->getTransitions($now, $now + 2 * 366 * 86400); + + for ($index = 1, $count = count($transitions); $index < $count; ++$index) { + $previousOffset = $transitions[$index - 1]['offset']; + $change = $transitions[$index]; + + if ($change['offset'] <= $previousOffset) { + continue; + } + + // The skipped local times run from the old offset up to the new one, compared here as UTC times + $firstMatch = $cron->getNextRunDate(new DateTimeImmutable('@' . ($change['ts'] + $previousOffset)), allowCurrentDate: true); + + if ($firstMatch->getTimestamp() < $change['ts'] + $change['offset'] + && ! $cron->isDue((new DateTimeImmutable('@' . $change['ts']))->setTimezone($timezone))) { + return true; + } + } + + return false; + } + /** * Send the in-progress check-in for the scheduled event. */ @@ -401,8 +632,9 @@ private function makeSlugForScheduled(SchedulingEvent $scheduled): string ':', '-', trim( - // The command string always starts with the PHP binary, so we remove it since it's not relevant to the slug - Str::after($scheduled->command, ConsoleApplication::phpBinary()) + // Commands built with `formatCommandString()` start with the PHP binary, which isn't relevant to the slug. + // Upstream's Str::after() would also remove the start of a command that passes the binary as an argument. + Str::chopStart($scheduled->command, ConsoleApplication::phpBinary()) ) ) ); @@ -420,9 +652,10 @@ private function getCommandNameForScheduled(SchedulingEvent $scheduled): ?string return null; } - // The command string always starts with the PHP binary and artisan binary, so we remove it since it's not relevant to the name + // Commands built with `formatCommandString()` start with the PHP and Artisan binaries, which aren't part of the name. + // Upstream's Str::after() would also remove the start of a command that passes them as arguments. return trim( - Str::after($scheduled->command, ConsoleApplication::phpBinary() . ' ' . ConsoleApplication::artisanBinary()) + Str::chopStart($scheduled->command, ConsoleApplication::phpBinary() . ' ' . ConsoleApplication::artisanBinary()) ); } } diff --git a/src/sentry/src/Integration/ModelViolations/DiscardedAttributeViolationReporter.php b/src/sentry/src/Integration/ModelViolations/DiscardedAttributeViolationReporter.php index 45d501bb1a..67c6bb860d 100644 --- a/src/sentry/src/Integration/ModelViolations/DiscardedAttributeViolationReporter.php +++ b/src/sentry/src/Integration/ModelViolations/DiscardedAttributeViolationReporter.php @@ -12,6 +12,8 @@ class DiscardedAttributeViolationReporter extends ModelViolationReporter { /** * Get the context data for the violation. + * + * @return array */ protected function getViolationContext(Model $model, string $property): array { diff --git a/src/sentry/src/Integration/ModelViolations/LazyLoadingModelViolationReporter.php b/src/sentry/src/Integration/ModelViolations/LazyLoadingModelViolationReporter.php index 9761c0d276..b3acff9234 100644 --- a/src/sentry/src/Integration/ModelViolations/LazyLoadingModelViolationReporter.php +++ b/src/sentry/src/Integration/ModelViolations/LazyLoadingModelViolationReporter.php @@ -26,6 +26,8 @@ protected function shouldReport(Model $model, string $property): bool /** * Get the context data for the violation. + * + * @return array */ protected function getViolationContext(Model $model, string $property): array { diff --git a/src/sentry/src/SentryConfig.php b/src/sentry/src/SentryConfig.php index 86e8103f8b..5d1c2e78f7 100644 --- a/src/sentry/src/SentryConfig.php +++ b/src/sentry/src/SentryConfig.php @@ -25,6 +25,11 @@ class SentryConfig 'notifications' => true, ]; + private const array CRONS_DEFAULTS = [ + 'monitor_scheduled_tasks' => false, + 'exclude_scheduled_tasks' => [], + ]; + private const array TRACING_DEFAULTS = [ 'queue_job_transactions' => true, 'queue_jobs' => true, @@ -115,6 +120,8 @@ public function all(): array $config = $this->config->array($this->root); $config['breadcrumbs'] = $this->config->array($this->root . '.breadcrumbs', []) + self::BREADCRUMB_DEFAULTS; + $config['crons'] = $this->config->array($this->root . '.crons', []) + + self::CRONS_DEFAULTS; $config['tracing'] = $this->config->array($this->root . '.tracing', []) + self::TRACING_DEFAULTS; diff --git a/src/sentry/src/SentryServiceProvider.php b/src/sentry/src/SentryServiceProvider.php index 64ad981fae..e600592369 100644 --- a/src/sentry/src/SentryServiceProvider.php +++ b/src/sentry/src/SentryServiceProvider.php @@ -77,6 +77,7 @@ class SentryServiceProvider extends ServiceProvider // We do not want these settings to hit the PHP SDK because they are Hypervel specific and the PHP SDK will throw errors 'tracing', 'breadcrumbs', + 'crons', 'features', 'pool', // We resolve the integrations through the container later, so we initially do not pass it to the SDK yet @@ -319,6 +320,13 @@ protected function configureAndRegisterClient(): void return false; } + // We also remove the default transaction integration so it can be readded + // after our own integration. This way the route name set by Hypervel takes + // precedence over the fallbacks of the SDK + if ($integration instanceof SdkIntegration\TransactionIntegration) { + return false; + } + return true; }); @@ -337,6 +345,10 @@ protected function configureAndRegisterClient(): void $userIntegrations ); + if ($options->hasDefaultIntegrations()) { + $integrations[] = new SdkIntegration\TransactionIntegration; + } + if (is_callable($userIntegrationOption)) { return $userIntegrationOption($integrations); } @@ -586,11 +598,21 @@ private function bindViewEngine(array $tracingConfig): void return; } - $viewObserver = static function (ViewFactory $viewFactory): void { - $viewFactory->observeRendering(static function (View $view): void { + $app = $this->app; + + $viewObserver = static function (ViewFactory $viewFactory) use ($app): void { + $viewFactory->observeRendering(static function (View $view) use ($app): void { + $viewName = $view->name(); + $basePath = $app->basePath(); + + // Views rendered from a file are named after their full path, strip the base path to keep the name short + if (str_starts_with($viewName, $basePath . DIRECTORY_SEPARATOR)) { + $viewName = substr($viewName, strlen($basePath)); + } + // The decorator reads this during the same render call; keep it // coroutine-local so concurrent renders do not swap view names. - CoroutineContext::set(ViewEngineDecorator::CONTEXT_KEY, $view->name()); + CoroutineContext::set(ViewEngineDecorator::CONTEXT_KEY, $viewName); }); }; diff --git a/tests/Console/Scheduling/EventTest.php b/tests/Console/Scheduling/EventTest.php index d995416e25..034ebc533b 100644 --- a/tests/Console/Scheduling/EventTest.php +++ b/tests/Console/Scheduling/EventTest.php @@ -942,6 +942,27 @@ public function testEventIsDueAtUsesEventTimezone(): void $this->assertFalse($event->isDueAt($app, CarbonImmutable::parse('2026-05-29 12:59:59', 'UTC'))); } + public function testEventTimezoneIsKeptDuringApplicationTimezoneClockChange(): void + { + $appDouble = Double::for(ApplicationContract::class, override: true)->strict(); + $app = $appDouble->instance(); + $appDouble->allows('isDownForMaintenance')->returns(false); + $appDouble->allows('environment')->returns('production'); + + $event = new Event(Double::for(EventMutex::class)->strict(), 'php foo'); + $event->dailyAt('02:30')->timezone('UTC'); + + $previousTimezone = date_default_timezone_get(); + date_default_timezone_set('Europe/Vienna'); + + try { + $this->assertTrue($event->isDueAt($app, CarbonImmutable::parse('2026-03-29 02:30:00', 'UTC'))); + $this->assertFalse($event->isDueAt($app, CarbonImmutable::parse('2026-03-29 03:30:00', 'UTC'))); + } finally { + date_default_timezone_set($previousTimezone); + } + } + public function testTimeBetweenChecks(): void { $app = $this->container; diff --git a/tests/Console/Scheduling/ScheduleRunCommandTest.php b/tests/Console/Scheduling/ScheduleRunCommandTest.php index 8407ce7eb3..f194bedc1e 100644 --- a/tests/Console/Scheduling/ScheduleRunCommandTest.php +++ b/tests/Console/Scheduling/ScheduleRunCommandTest.php @@ -1166,10 +1166,25 @@ public function testNonRepeatableEventOnlyRunsOncePerMinute(): void $this->invokeRunEvents($command, [$callbackEvent], $startedAt->addMinute()); $this->assertSame(2, $runCount); + + // A clock set back into the previous minute neither runs it again nor forgets the later minute's run + $this->invokeRunEvents($command, [$callbackEvent], $startedAt->addSeconds(59)); + $this->invokeRunEvents($command, [$callbackEvent], $startedAt->addMinute()->addSecond()); + $this->assertSame(2, $runCount); + + // A longer correction keeps scheduling the earlier minutes + $this->invokeRunEvents($command, [$callbackEvent], $startedAt->subHour()); + $this->assertSame(3, $runCount); + + // Polls without due events count too, so a later correction isn't mistaken for a one-minute one + $this->invokeRunEvents($command, [], $startedAt->subMinutes(40)); + $this->invokeRunEvents($command, [$callbackEvent], $startedAt->subHour()->subMinute()); + $this->assertSame(4, $runCount); } public function testRepeatableEventIsThrottledByLastChecked(): void { + Date::setTestNow('2026-05-28 12:34:00'); $runCount = 0; $eventMutex = Double::for(EventMutex::class)->strict(); @@ -1195,6 +1210,32 @@ public function testRepeatableEventIsThrottledByLastChecked(): void $this->assertSame(1, $runCount); } + public function testRepeatableEventRestartsItsCycleOnTheFirstCheckOfALaterMinute(): void + { + $runs = []; + + $eventMutex = Double::for(EventMutex::class)->strict(); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); + + $callbackEvent = new CallbackEvent($eventMutex, function () use (&$runs): int { + $runs[] = Date::now()->format('H:i:s'); + + return 0; + }); + $callbackEvent->repeatSeconds = 5; + + $command = $this->makeCommand(); + + // The clock is set back from 12:35:00.1 to 12:34:59.9, which isn't a later minute + foreach (['12:34:37', '12:34:40', '12:34:42', '12:34:57', '12:35:00.1', '12:34:59.9', '12:35:06'] as $time) { + Date::setTestNow("2026-05-28 {$time}"); + $this->invokeRunEvents($command, [$callbackEvent]); + } + + $this->assertSame(['12:34:37', '12:34:42', '12:34:57', '12:35:00', '12:35:06'], $runs); + } + public function testSingleServerEventClaimedElsewhereDoesNotReportThatNoCommandsWereReady(): void { $event = new Event(Double::for(EventMutex::class)->strict(), 'test:single-server'); diff --git a/tests/Data/Attributes/Validation/RulesTest.php b/tests/Data/Attributes/Validation/RulesTest.php index 51acfb3320..6966a543f3 100644 --- a/tests/Data/Attributes/Validation/RulesTest.php +++ b/tests/Data/Attributes/Validation/RulesTest.php @@ -4,10 +4,8 @@ namespace Hypervel\Tests\Data\Attributes\Validation; -use Hypervel\Data\Attributes\Validation\Exists; use Hypervel\Data\Attributes\Validation\Required; use Hypervel\Data\Attributes\Validation\Rule; -use Hypervel\Data\Attributes\Validation\Unique; use Hypervel\Data\Support\Validation\RuleDenormalizer; use Hypervel\Data\Support\Validation\RuleNormalizer; use Hypervel\Data\Support\Validation\ValidationPath; @@ -18,8 +16,8 @@ use Hypervel\Tests\Data\Fixtures\Rules\CustomHypervelValidationRule; use Hypervel\Tests\Data\Fixtures\RulesDataset; use Hypervel\Tests\TestCase; -use Hypervel\Validation\Rules\Exists as BaseExists; -use Hypervel\Validation\Rules\Unique as BaseUnique; +use Hypervel\Validation\Rules\Exists; +use Hypervel\Validation\Rules\Unique; use PHPUnit\Framework\Attributes\DataProvider; require_once dirname(__DIR__, 2) . '/Fixtures/RulesDataset.php'; @@ -46,7 +44,15 @@ public function testGetsTheCorrectRules( $resolved = (new RuleDenormalizer)->execute($attribute, ValidationPath::create()); - $this->assertRuleEquals($expected, $resolved[0]); + if ($expected instanceof Exists || $expected instanceof Unique) { + $this->assertInstanceOf($expected::class, $resolved[0]); + $this->assertSame((string) $expected, (string) $resolved[0]); + $this->assertSame($expected->queryCallbacks(), $resolved[0]->queryCallbacks()); + + return; + } + + $this->assertEquals($expected, $resolved[0]); } #[DataProvider('attributes')] @@ -64,7 +70,14 @@ public function testCreatesTheCorrectAttributes( $resolved = (new RuleNormalizer(new ValidationRuleFactory))->execute($expected); - $this->assertRuleEquals($expectedCreatedAttribute, $resolved[0]); + if ($expected instanceof Exists || $expected instanceof Unique) { + $this->assertInstanceOf($expectedCreatedAttribute::class, $resolved[0]); + $this->assertSame($expected, $resolved[0]->getRule(ValidationPath::create())); + + return; + } + + $this->assertEquals($expectedCreatedAttribute, $resolved[0]); } /** @@ -108,27 +121,4 @@ public function testCanUseTheRuleRuleWithValidationRuleContract(): void (new RuleDenormalizer)->execute($rule, ValidationPath::create()), ); } - - /** - * Assert two rules are equal, comparing database query callbacks by identity, since closures cannot be compared. - */ - protected function assertRuleEquals(mixed $expected, mixed $actual): void - { - if ($expected instanceof Exists || $expected instanceof Unique) { - $this->assertInstanceOf($expected::class, $actual); - - $expected = $expected->getRule(ValidationPath::create()); - $actual = $actual->getRule(ValidationPath::create()); - } - - if ($expected instanceof BaseExists || $expected instanceof BaseUnique) { - $this->assertInstanceOf($expected::class, $actual); - $this->assertSame((string) $expected, (string) $actual); - $this->assertSame($expected->queryCallbacks(), $actual->queryCallbacks()); - - return; - } - - $this->assertEquals($expected, $actual); - } } diff --git a/tests/Jwt/JwtManagerTest.php b/tests/Jwt/JwtManagerTest.php index dde1d41826..ebfd1fd71d 100644 --- a/tests/Jwt/JwtManagerTest.php +++ b/tests/Jwt/JwtManagerTest.php @@ -450,6 +450,40 @@ public function testRefreshSkipsTemporalValidationsInsideRefreshWindow(): void $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } + public function testDecodeStillRejectsExpiredTokensAfterARefresh(): void + { + $token = 'foo.bar.baz'; + $refreshedToken = 'baz.bar.foo'; + $payload = [ + 'sub' => 1, + 'exp' => $this->testNowTimestamp - 3600, + 'iat' => $this->testNowTimestamp - 7200, + ]; + $refreshPayload = [ + 'sub' => 1, + 'iat' => $this->testNowTimestamp - 7200, + 'exp' => $this->testNowTimestamp + 7200, + ]; + + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class, ExpiredClaim::class]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub']]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->with($payload, 120, false, false, [], [])->returns($refreshPayload); + $this->provider->expects('decode')->times(2)->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns($refreshedToken); + + $manager = $this->createManager(); + $this->assertSame($refreshedToken, $manager->refresh($token)); + + $this->expectException(TokenExpiredException::class); + + $manager->decode($token); + } + #[DataProvider('futureTimestampClaimProvider')] public function testRefreshRejectsFutureTimestampClaimsBeyondTheLeeway(string $validation, string $claim): void { diff --git a/tests/Permission/Integration/RouteTest.php b/tests/Permission/Integration/RouteTest.php index a17bee9326..bb3d8fb7ae 100644 --- a/tests/Permission/Integration/RouteTest.php +++ b/tests/Permission/Integration/RouteTest.php @@ -4,8 +4,10 @@ namespace Hypervel\Tests\Permission\Integration; +use Hypervel\Permission\Contracts\Permission; use Hypervel\Tests\Permission\Fixtures\Models\TestRolePermissionsEnum; use Hypervel\Tests\Permission\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; class RouteTest extends TestCase { @@ -128,4 +130,325 @@ public function testRoleOrPermissionFunctionWithBackedEnumArray(): void 'role_or_permission:' . TestRolePermissionsEnum::UserManager->value . '|' . TestRolePermissionsEnum::EditArticles->value, ], $this->getLastRouteMiddlewareFromRouter($router)); } + + public function testRoleFunctionOnRouteGroup(): void + { + $router = $this->getRouter(); + + $router->prefix('admin')->role('superadmin')->group(function () use ($router): void { + $router->get('role-group-test', $this->getRouteResponse())->name('role-group.test'); + }); + + $this->assertSame(['role:superadmin'], $this->getLastRouteMiddlewareFromRouter($router)); + } + + public function testPermissionFunctionOnRouteGroup(): void + { + $router = $this->getRouter(); + + $router->prefix('articles')->permission(['edit articles', 'save articles'])->group(function () use ($router): void { + $router->get('permission-group-test', $this->getRouteResponse())->name('permission-group.test'); + }); + + $this->assertSame(['permission:edit articles|save articles'], $this->getLastRouteMiddlewareFromRouter($router)); + } + + public function testRoleOrPermissionFunctionOnRouteGroup(): void + { + $router = $this->getRouter(); + + $router->prefix('articles')->roleOrPermission(['admin', 'edit articles'])->group(function () use ($router): void { + $router->get('role-or-permission-group-test', $this->getRouteResponse())->name('role-or-permission-group.test'); + }); + + $this->assertSame(['role_or_permission:admin|edit articles'], $this->getLastRouteMiddlewareFromRouter($router)); + } + + public function testPermissionFunctionOnRouteGroupWithBackedEnum(): void + { + $router = $this->getRouter(); + + $router->prefix('articles')->permission([TestRolePermissionsEnum::Writer, TestRolePermissionsEnum::Editor])->group(function () use ($router): void { + $router->get('permission-group-test.enum', $this->getRouteResponse())->name('permission-group.test.enum'); + }); + + $this->assertSame([ + 'permission:' . TestRolePermissionsEnum::Writer->value . '|' . TestRolePermissionsEnum::Editor->value, + ], $this->getLastRouteMiddlewareFromRouter($router)); + } + + public function testRoleAndPermissionFunctionsOnRouter(): void + { + $router = $this->getRouter(); + + $router->role('superadmin')->permission('edit articles')->group(function () use ($router): void { + $router->get('router-group-test', $this->getRouteResponse())->name('router-group.test'); + }); + + $this->assertSame([ + 'role:superadmin', + 'permission:edit articles', + ], $this->getLastRouteMiddlewareFromRouter($router)); + } + + public function testRoleAndPermissionFunctionsOnRouteGroupKeepExistingMiddleware(): void + { + $router = $this->getRouter(); + + $router->middleware('auth')->role('superadmin')->permission('edit articles')->group(function () use ($router): void { + $router->get('route-group-middleware-test', $this->getRouteResponse())->name('route-group-middleware.test'); + }); + + $this->assertSame([ + 'auth', + 'role:superadmin', + 'permission:edit articles', + ], $this->getLastRouteMiddlewareFromRouter($router)); + } + + #[DataProvider('groupMacroProvider')] + public function testEnforcesGroupMacrosAfterAuthAndRetainsThemInNestedMiddlewareGroups( + string $macro, + string $requirement, + string $grantMethod, + string $grant, + ): void { + $router = $this->getRouter(); + + $router->middleware('auth')->{$macro}($requirement)->group(function () use ($router): void { + $router->get('direct', fn () => 'allowed'); + + $router->middleware('permission:edit-news')->group(function () use ($router): void { + $router->get('nested', fn () => 'allowed'); + }); + }); + $router->get('outside', fn () => 'public'); + + $this->get('/outside')->assertOk(); + $this->getJson('/direct')->assertUnauthorized(); + $this->getJson('/nested')->assertUnauthorized(); + + $this->actingAs($this->testUser); + $this->get('/direct')->assertForbidden(); + $this->get('/nested')->assertForbidden(); + + $this->testUser->{$grantMethod}($grant); + $this->get('/direct')->assertOk()->assertSee('allowed'); + $this->get('/nested')->assertForbidden(); + + $this->testUser->givePermissionTo('edit-news'); + $this->get('/nested')->assertOk()->assertSee('allowed'); + + $this->testUser->{$grantMethod === 'assignRole' ? 'removeRole' : 'revokePermissionTo'}($grant); + $this->get('/nested')->assertForbidden(); + } + + /** + * Provide each group macro with a requirement and the grant that satisfies it. + */ + public static function groupMacroProvider(): array + { + return [ + ['role', 'testRole|testRole2', 'assignRole', 'testRole2'], + ['permission', 'edit-blog|edit-articles', 'givePermissionTo', 'edit-articles'], + ['roleOrPermission', 'testRole|edit-articles', 'givePermissionTo', 'edit-articles'], + ['canAny', 'edit-blog|edit-articles', 'givePermissionTo', 'edit-articles'], + ['canAll', 'edit-articles', 'givePermissionTo', 'edit-articles'], + ]; + } + + #[DataProvider('macroProvider')] + public function testUsesHypervelMiddlewareReplacementOnRegistrarsButAppendsOnIndividualRoutes(string $macro): void + { + $router = $this->getRouter(); + + $router->{$macro}('unassigned')->middleware('auth')->group(function () use ($router): void { + $router->get('group', fn () => 'allowed'); + }); + $router->get('individual', fn () => 'allowed')->{$macro}('unassigned')->middleware('auth'); + + $this->getJson('/group')->assertUnauthorized(); + + $this->actingAs($this->testUser); + $this->get('/group')->assertOk()->assertSee('allowed'); + $this->get('/individual')->assertForbidden(); + } + + /** + * Provide every route macro. + */ + public static function macroProvider(): array + { + return [['role'], ['permission'], ['roleOrPermission'], ['canAny'], ['canAll']]; + } + + #[DataProvider('listedPermissionProvider')] + public function testRequiresAnyListedPermissionForCanAnyAndEveryListedPermissionForCanAll( + string $macro, + bool $allowedWithOnePermission, + array $permissions, + string $firstGrant, + ): void { + $router = $this->getRouter(); + $this->app->make(Permission::class)->create(['name' => 'writer']); + + $router->middleware('auth')->{$macro}($permissions)->group(function () use ($router): void { + $router->get('group', fn () => 'allowed'); + }); + $router->get('individual', fn () => 'allowed')->middleware('auth')->{$macro}($permissions); + $router->{$macro}($permissions)->group(function () use ($router): void { + $router->get('router', fn () => 'allowed'); + }); + $router->canAll('edit-blog')->group(function () use ($router): void { + $router->get('sibling', fn () => 'allowed'); + }); + $router->get('public', fn () => 'public'); + + $this->get('/public')->assertOk(); + $this->getJson('/group')->assertUnauthorized(); + $this->getJson('/individual')->assertUnauthorized(); + $this->get('/router')->assertForbidden(); + + $this->actingAs($this->testUser); + $this->get('/group')->assertForbidden(); + $this->get('/individual')->assertForbidden(); + $this->get('/router')->assertForbidden(); + + $this->testUser->givePermissionTo($firstGrant); + $this->get('/group')->assertStatus($allowedWithOnePermission ? 200 : 403); + $this->get('/individual')->assertStatus($allowedWithOnePermission ? 200 : 403); + $this->get('/router')->assertStatus($allowedWithOnePermission ? 200 : 403); + + $this->testUser->givePermissionTo('edit-news'); + $this->get('/group')->assertOk()->assertSee('allowed'); + $this->get('/individual')->assertOk()->assertSee('allowed'); + $this->get('/router')->assertOk()->assertSee('allowed'); + $this->get('/sibling')->assertForbidden(); + + $this->testUser->revokePermissionTo($firstGrant); + $this->get('/group')->assertStatus($allowedWithOnePermission ? 200 : 403); + $this->get('/individual')->assertStatus($allowedWithOnePermission ? 200 : 403); + $this->get('/router')->assertStatus($allowedWithOnePermission ? 200 : 403); + + $this->testUser->revokePermissionTo('edit-news'); + $this->get('/group')->assertForbidden(); + $this->get('/individual')->assertForbidden(); + $this->get('/router')->assertForbidden(); + } + + /** + * Provide canAny and canAll permission lists and whether one listed permission is enough. + */ + public static function listedPermissionProvider(): array + { + return [ + ['canAny', true, ['edit-articles', 'edit-news'], 'edit-articles'], + ['canAll', false, ['edit-articles', 'edit-news'], 'edit-articles'], + ['canAny', true, [TestRolePermissionsEnum::Writer, 'edit-news'], 'writer'], + ['canAll', false, [TestRolePermissionsEnum::Writer, 'edit-news'], 'writer'], + ]; + } + + #[DataProvider('scalarPermissionProvider')] + public function testAcceptsScalarPermissionsWithoutReplacingNativeCanAuthorization( + string $macro, + string|TestRolePermissionsEnum $permission, + ): void { + $this->app->make(Permission::class)->create(['name' => 'writer']); + $router = $this->getRouter(); + + $router->get('allowed', fn () => 'allowed')->{$macro}($permission)->can('edit-news'); + + $this->actingAs($this->testUser); + $this->get('/allowed')->assertForbidden(); + + $this->testUser->givePermissionTo('writer'); + $this->get('/allowed')->assertForbidden(); + + $this->testUser->givePermissionTo('edit-news'); + $this->get('/allowed')->assertOk(); + + $this->testUser->revokePermissionTo('writer'); + $this->get('/allowed')->assertForbidden(); + } + + /** + * Provide canAny and canAll with a string and an enum permission. + */ + public static function scalarPermissionProvider(): array + { + return [ + ['canAny', 'writer'], + ['canAny', TestRolePermissionsEnum::Writer], + ['canAll', 'writer'], + ['canAll', TestRolePermissionsEnum::Writer], + ]; + } + + #[DataProvider('permissionAliasMacroProvider')] + public function testUsesTheGuardSelectedByAuthenticationMiddlewareForPermissionAliases(string $macro): void + { + $router = $this->getRouter(); + + $router->middleware('auth:admin')->{$macro}('admin-permission')->group(function () use ($router, $macro): void { + $router->get('admin', fn () => 'allowed')->{$macro}('admin-permission'); + }); + + $this->actingAs($this->testUser, 'web'); + $this->getJson('/admin')->assertUnauthorized(); + + $this->actingAs($this->testAdmin, 'admin'); + $this->get('/admin')->assertForbidden(); + + $this->testAdmin->givePermissionTo('admin-permission'); + $this->get('/admin')->assertOk(); + + $this->testAdmin->revokePermissionTo('admin-permission'); + $this->get('/admin')->assertForbidden(); + } + + /** + * Provide the canAny and canAll permission aliases. + */ + public static function permissionAliasMacroProvider(): array + { + return [['canAny'], ['canAll']]; + } + + public function testRequiresEveryCanAllEntryWhilePreservingPipeAlternativesWithinAnEntry(): void + { + $router = $this->getRouter(); + + $router->canAll(['edit-articles|edit-blog', 'edit-news'])->group(function () use ($router): void { + $router->get('articles', fn () => 'allowed'); + }); + + $this->actingAs($this->testUser); + $this->testUser->givePermissionTo('edit-news'); + $this->get('/articles')->assertForbidden(); + + $this->testUser->givePermissionTo('edit-blog'); + $this->get('/articles')->assertOk(); + + $this->testUser->revokePermissionTo('edit-news'); + $this->get('/articles')->assertForbidden(); + } + + public function testAddsNoAuthorizationChecksForAnEmptyCanAllList(): void + { + $router = $this->getRouter(); + + $router->canAll([])->group(function () use ($router): void { + $router->get('group', fn () => 'public')->canAll([]); + }); + $router->middleware('auth')->canAll([])->group(function () use ($router): void { + $router->get('authenticated', fn () => 'allowed'); + }); + + $this->get('/group')->assertOk(); + $this->getJson('/authenticated')->assertUnauthorized(); + + $this->actingAs($this->testUser); + $this->get('/authenticated')->assertOk(); + } } diff --git a/tests/Permission/PartitionRelationProvenanceTest.php b/tests/Permission/PartitionRelationProvenanceTest.php index f3b82494fe..eeadacba7b 100644 --- a/tests/Permission/PartitionRelationProvenanceTest.php +++ b/tests/Permission/PartitionRelationProvenanceTest.php @@ -52,6 +52,18 @@ public function testEmptyLoadedRelationIsNotReusedInAnotherPartition(): void $this->assertTrue($user->hasRole('member')); } + public function testLoadingTheDisabledTeamsRelationKeepsLoadedPermissionsCurrent(): void + { + $registrar = $this->app->make(PermissionRegistrar::class); + $user = GlobalPartitionUser::create(['email' => 'global@example.com']); + $user->givePermissionTo(PartitionedPermission::create(['name' => 'permission-a'])); + $user->load('permissions'); + + $user->teams()->getResults(); + + $this->assertTrue($registrar->loadedRelationIsCurrent($user, 'permissions')); + } + public function testManualRelationReplacementInvalidatesItsProvenanceMarker(): void { $user = GlobalPartitionUser::create(['email' => 'global@example.com']); diff --git a/tests/Permission/Traits/HasRolesTest.php b/tests/Permission/Traits/HasRolesTest.php index 85b03ba72a..2de3ce0c03 100644 --- a/tests/Permission/Traits/HasRolesTest.php +++ b/tests/Permission/Traits/HasRolesTest.php @@ -14,6 +14,8 @@ use Hypervel\Permission\Events\RoleDetachedEvent; use Hypervel\Permission\Exceptions\GuardDoesNotMatch; use Hypervel\Permission\Exceptions\RoleDoesNotExist; +use Hypervel\Permission\Exceptions\TeamsNotEnabled; +use Hypervel\Permission\Support\Config; use Hypervel\Permission\Traits\HasRoles; use Hypervel\Support\Facades\DB; use Hypervel\Support\Facades\Event; @@ -1172,4 +1174,107 @@ public function testItFiresDetachEventWhenSyncingRoles(): void && $event->rolesOrIds === $attachedRoleIds; }); } + + #[DataProvider('permissionModelsProvider')] + public function testCanQueryTheDisabledTeamsRelationWithoutMigratingTeamColumns(bool $customModels): void + { + if (Config::teamsEnabled()) { + $this->markTestSkipped('Covers the teams relation while teams are disabled.'); + } + + if ($customModels) { + $this->setUpCustomModels(); + } + + $this->testUser->givePermissionTo($this->testUserPermission); + $this->testUser->assignRole($this->testUserRole); + + $this->assertInstanceOf(BelongsToMany::class, $this->testUser->teams()); + $this->assertEmpty($this->testUser->teams()->get()); + $this->assertEmpty($this->testUser->teams()->wherePivot(fn ($query) => $query->where('model_type', $this->testUser->getMorphClass()))->get()); + $this->assertFalse($this->testUser->teams()->exists()); + $this->assertEmpty($this->testUser->teams()->allRelatedIds()); + $this->assertSame([$this->testUserPermission->getKey()], $this->testUser->permissions()->get()->modelKeys()); + $this->assertSame([$this->testUserRole->getKey()], $this->testUser->roles()->get()->modelKeys()); + } + + #[DataProvider('permissionModelsProvider')] + public function testCanEagerlyLoadDisabledTeamsWithoutMigratingTeamColumns(bool $customModels): void + { + if (Config::teamsEnabled()) { + $this->markTestSkipped('Covers the teams relation while teams are disabled.'); + } + + if ($customModels) { + $this->setUpCustomModels(); + } + + $this->testUser->givePermissionTo($this->testUserPermission); + $otherUser = User::create(['email' => 'without-permissions@example.com']); + + $users = User::with(['teams', 'permissions'])->withCount('teams')->get(); + + foreach ($users as $user) { + $this->assertTrue($user->relationLoaded('teams')); + $this->assertEmpty($user->teams); + $this->assertSame(0, $user->teams_count); + } + + $this->assertSame([$this->testUserPermission->getKey()], $users->find($this->testUser->getKey())->permissions->modelKeys()); + $this->assertEmpty($users->find($otherUser->getKey())->permissions); + $this->assertSame(0, User::whereHas('teams')->count()); + $this->assertEqualsCanonicalizing( + [$this->testUser->getKey(), $otherUser->getKey()], + User::whereDoesntHave('teams')->get()->modelKeys(), + ); + } + + /** + * Provide the default and custom UUID permission models. + */ + public static function permissionModelsProvider(): array + { + return [ + 'default models' => [false], + 'custom UUID models' => [true], + ]; + } + + public function testWritesThroughTheDisabledTeamsRelationAreRejectedWithoutChangingDirectPermissions(): void + { + if (Config::teamsEnabled()) { + $this->markTestSkipped('Covers the teams relation while teams are disabled.'); + } + + $this->testUser->givePermissionTo($this->testUserPermission); + $permissionModel = $this->app->make(Permission::class); + $newsPermission = $permissionModel::findByName('edit-news')->getKey(); + $articlesPermission = $this->testUserPermission->getKey(); + $permissionCount = $permissionModel::count(); + + $writes = [ + 'attach' => fn () => $this->testUser->teams()->attach($newsPermission), + 'attach with a custom pivot' => fn () => $this->testUser->teams()->using(MorphPivot::class)->attach($newsPermission), + 'sync' => fn () => $this->testUser->teams()->sync([$newsPermission]), + 'sync matching a direct permission' => fn () => $this->testUser->teams()->sync([$articlesPermission]), + 'toggle' => fn () => $this->testUser->teams()->toggle([$articlesPermission]), + 'detach' => fn () => $this->testUser->teams()->detach(), + 'detach with a custom pivot' => fn () => $this->testUser->teams()->using(MorphPivot::class)->detach(), + 'updateExistingPivot' => fn () => $this->testUser->teams()->updateExistingPivot($articlesPermission, ['model_type' => 'other']), + 'save' => fn () => $this->testUser->teams()->save($permissionModel->newInstance(['name' => 'saved-team'])), + 'create' => fn () => $this->testUser->teams()->create(['name' => 'created-team']), + 'forceCreate' => fn () => $this->testUser->teams()->forceCreate(['name' => 'force-created-team']), + ]; + + foreach ($writes as $method => $write) { + try { + $write(); + $this->fail("Expected {$method} to be rejected."); + } catch (TeamsNotEnabled) { + } + } + + $this->assertSame(['edit-articles'], $this->testUser->fresh()->getPermissionNames()->all()); + $this->assertSame($permissionCount, $permissionModel::count()); + } } diff --git a/tests/Saloon/Unit/Concerns/HasApiVersionTest.php b/tests/Saloon/Unit/Concerns/HasApiVersionTest.php index 0d3f68449c..acb47a041e 100644 --- a/tests/Saloon/Unit/Concerns/HasApiVersionTest.php +++ b/tests/Saloon/Unit/Concerns/HasApiVersionTest.php @@ -23,6 +23,7 @@ use Hypervel\Testbench\TestCase; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; class HasApiVersionTest extends TestCase { @@ -163,6 +164,23 @@ public function getApiVersion(): ?string $this->assertSame('override-version', $response->toPsrRequest()->getHeaderLine('api-version')); } + public function testTheConnectorCanOverrideTheApiVersionInTheUrl(): void + { + $connector = new class('https://api.provider.com/{version}', VersionMode::Url, null) extends VersionedConnector { + /** + * Get the API version. + */ + public function getApiVersion(): ?string + { + return 'override-version'; + } + }; + + $response = $this->sendVersionedRequest($connector, $this->makeVersionedRequest()); + + $this->assertSame('https://api.provider.com/override-version', (string) $response->toPsrRequest()->getUri()); + } + public function testTheRequestCanOverrideTheApiVersionAtRuntime(): void { $request = $this->makeVersionedRequest('override-version', VersionMode::Header); @@ -175,7 +193,85 @@ public function testTheRequestCanOverrideTheApiVersionAtRuntime(): void $this->assertSame('override-version', $response->toPsrRequest()->getHeaderLine('api-version')); } - #[DataProvider('versionModes')] + public function testTheRequestCanOverrideTheConnectorApiVersionInTheUrl(): void + { + $response = $this->sendVersionedRequest( + $this->makeVersionedConnector('https://api.provider.com/{version}', VersionMode::Url, 'v1'), + $this->makeVersionedRequest('beta', VersionMode::Url), + ); + + $this->assertSame('https://api.provider.com/beta', (string) $response->toPsrRequest()->getUri()); + } + + public function testARequestVersionedByHeaderLeavesTheConnectorApiVersionInTheUrl(): void + { + $response = $this->sendVersionedRequest( + $this->makeVersionedConnector('https://api.provider.com/{version}', VersionMode::Url, 'v1'), + $this->makeVersionedRequest('beta', VersionMode::Header), + ); + $psrRequest = $response->toPsrRequest(); + + $this->assertSame('https://api.provider.com/v1', (string) $psrRequest->getUri()); + $this->assertSame('beta', $psrRequest->getHeaderLine('api-version')); + } + + public function testARequestWithItsOwnVersionMethodsButNotTheTraitLeavesTheConnectorApiVersionInTheUrl(): void + { + $request = new class extends Request { + protected Method $method = Method::GET; + + /** + * Resolve the request endpoint. + */ + public function resolveEndpoint(): string + { + return ''; + } + + /** + * Get the API version. + */ + public function getApiVersion(): string + { + return 'beta'; + } + + /** + * Get where the API version is applied to the request. + */ + public function getVersionMode(): VersionMode + { + return VersionMode::Url; + } + }; + + $response = $this->sendVersionedRequest( + $this->makeVersionedConnector('https://api.provider.com/{version}', VersionMode::Url, 'v1'), + $request, + ); + + $this->assertSame('https://api.provider.com/v1', (string) $response->toPsrRequest()->getUri()); + } + + public function testTheConnectorCanChooseTheUrlVersionOverTheRequestVersion(): void + { + $connector = new class('https://api.provider.com/{version}', VersionMode::Url, 'v1') extends VersionedConnector { + /** + * Resolve which version to substitute into `{version}` for URL mode. + */ + protected function resolveUrlApiVersion(PendingRequest $pendingRequest): string + { + return 'v2'; + } + }; + + $response = $this->sendVersionedRequest($connector, $this->makeVersionedRequest('beta', VersionMode::Url)); + + $this->assertSame('https://api.provider.com/v2', (string) $response->toPsrRequest()->getUri()); + } + + #[TestWith([VersionMode::Header])] + #[TestWith([VersionMode::QueryParam])] public function testARequestVersionReplacesTheConnectorVersion(VersionMode $versionMode): void { $response = $this->sendVersionedRequest( @@ -187,7 +283,6 @@ public function testARequestVersionReplacesTheConnectorVersion(VersionMode $vers match ($versionMode) { VersionMode::Header => $this->assertSame(['request-version'], $psrRequest->getHeader('api-version')), VersionMode::QueryParam => $this->assertSame('api-version=request-version', $psrRequest->getUri()->getQuery()), - VersionMode::Url => $this->assertSame('https://api.provider.com/request-version', (string) $psrRequest->getUri()), }; } diff --git a/tests/Sentry/ConfigTest.php b/tests/Sentry/ConfigTest.php index 7028ead113..6253cd11d0 100644 --- a/tests/Sentry/ConfigTest.php +++ b/tests/Sentry/ConfigTest.php @@ -111,7 +111,7 @@ public function testStorageTelemetryIsEnabledByDefault(): void $this->assertTrue($config['tracing']['storage']); } - public function testOmittedBreadcrumbAndTracingOptionsUseTheShippedDefaults(): void + public function testOmittedBreadcrumbCronsAndTracingOptionsUseTheShippedDefaults(): void { $shippedConfig = $this->withEnvironmentValues(array_fill_keys([ 'SENTRY_BREADCRUMBS_LOGS_ENABLED', @@ -124,6 +124,7 @@ public function testOmittedBreadcrumbAndTracingOptionsUseTheShippedDefaults(): v 'SENTRY_BREADCRUMBS_COMMAND_JOBS_ENABLED', 'SENTRY_BREADCRUMBS_HTTP_CLIENT_REQUESTS_ENABLED', 'SENTRY_BREADCRUMBS_NOTIFICATIONS_ENABLED', + 'SENTRY_CRONS_MONITOR_SCHEDULED_TASKS', 'SENTRY_TRACE_QUEUE_ENABLED', 'SENTRY_TRACE_QUEUE_JOBS_ENABLED', 'SENTRY_TRACE_SQL_QUERIES_ENABLED', @@ -147,11 +148,12 @@ public function testOmittedBreadcrumbAndTracingOptionsUseTheShippedDefaults(): v 'sentry' => [ ...$shippedConfig, 'breadcrumbs' => [], + 'crons' => [], 'tracing' => [], ], ]), 'sentry'))->all(); - foreach (['breadcrumbs', 'tracing'] as $section) { + foreach (['breadcrumbs', 'crons', 'tracing'] as $section) { ksort($shippedConfig[$section]); ksort($config[$section]); @@ -195,6 +197,7 @@ public function testBooleanEnvironmentValuesAreNormalized(): void 'SENTRY_SEND_DEFAULT_PII' => '1', 'SENTRY_BREADCRUMBS_SQL_QUERIES_ENABLED' => '1', 'SENTRY_BREADCRUMBS_CACHE_ENABLED' => '1', + 'SENTRY_CRONS_MONITOR_SCHEDULED_TASKS' => '1', 'SENTRY_TRACE_VIEWS_ENABLED' => '1', 'SENTRY_TRACE_REDIS_COMMANDS' => '1', 'SENTRY_TRACE_SQL_ORIGIN_THRESHOLD_MS' => '250', @@ -207,6 +210,7 @@ public function testBooleanEnvironmentValuesAreNormalized(): void $this->assertTrue($config['send_default_pii']); $this->assertTrue($config['breadcrumbs']['sql_queries']); $this->assertTrue($config['breadcrumbs']['cache']); + $this->assertTrue($config['crons']['monitor_scheduled_tasks']); $this->assertTrue($config['tracing']['views']); $this->assertTrue($config['tracing']['redis_commands']); $this->assertSame(250, $config['tracing']['sql_origin_threshold_ms']); diff --git a/tests/Sentry/Features/ConsoleSchedulingIntegrationTest.php b/tests/Sentry/Features/ConsoleSchedulingIntegrationTest.php index d114429670..a86075af01 100644 --- a/tests/Sentry/Features/ConsoleSchedulingIntegrationTest.php +++ b/tests/Sentry/Features/ConsoleSchedulingIntegrationTest.php @@ -6,6 +6,7 @@ use DateTimeZone; use Hypervel\Bus\Queueable; +use Hypervel\Console\Application as ConsoleApplication; use Hypervel\Console\Events\ScheduledTaskCanceled; use Hypervel\Console\Events\ScheduledTaskStarting; use Hypervel\Console\Scheduling\Event; @@ -161,6 +162,20 @@ public function testScheduleMacroAutomaticSlugForJob(): void ); } + public function testSystemCommandPassingThePhpAndArtisanBinariesAsArgumentsKeepsItsName(): void + { + $command = 'echo ' . ConsoleApplication::formatCommandString('inspire'); + $this->getScheduler()->exec($command)->everyMinute()->sentryMonitor(); + + $this->artisan('schedule:run --once'); + + $checkIn = $this->getCapturedSentryEventsOfType(EventType::checkIn())[0][0]->getCheckIn(); + + $this->assertNotNull($checkIn); + $this->assertStringStartsWith('scheduled_echo-', $checkIn->getMonitorSlug()); + $this->assertSame($command, $this->getCapturedTransactions()[0]->getTransaction()); + } + public function testScheduleMacroWithoutSlugCommandOrDescriptionOrName(): void { $this->expectException(RuntimeException::class); diff --git a/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php new file mode 100644 index 0000000000..e6d90c5782 --- /dev/null +++ b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php @@ -0,0 +1,422 @@ + [ + ConsoleSchedulingIntegration::class, + ], + ]; + + protected array $setupConfig = [ + 'sentry.crons.monitor_scheduled_tasks' => true, + 'sentry.crons.exclude_scheduled_tasks' => ['excluded:*', 'scheduled_*-skipped'], + ]; + + public function testScheduledTasksAreMonitoredWhenTheSchedulerRuns(): void + { + // Off the hour, so only the every-minute task is due + Date::setTestNow('2026-01-01 12:30:00'); + + $this->getScheduler()->call(function (): void { + })->name('send-report')->hourly(); + $this->getScheduler()->call(function (): void { + })->name('every-minute')->everyMinute(); + + // Hypervel only dispatches `CommandStarting` outside of unit tests + $this->startCommand('schedule:run'); + $this->artisan('schedule:run', ['--once' => true]); + + $this->assertSentryCheckInCount(2); + + $checkIn = $this->getLastCheckIn(); + + $this->assertEquals('scheduled_every-minute', $checkIn->getMonitorSlug()); + $this->assertEquals('* * * * *', $checkIn->getMonitorConfig()->getSchedule()->getValue()); + } + + public function testScheduledTasksAreNotMonitoredByOtherCommands(): void + { + $task = $this->getScheduler()->call(function (): void { + })->name('send-report'); + + $this->startCommand('schedule:list'); + $task->run($this->app); + + $this->assertSentryCheckInCount(0); + } + + public function testManuallyMonitoredTaskIsNotMonitoredTwice(): void + { + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->sentryMonitor('custom-slug'); + + $this->startCommand('schedule:run'); + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(2); + $this->assertEquals('custom-slug', $this->getLastCheckIn()->getMonitorSlug()); + } + + public function testUnnamedClosureIsNotMonitored(): void + { + $task = $this->getScheduler()->call(function (): void { + }); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(0); + } + + public function testExcludedTasksAreNotMonitored(): void + { + $tasks = [ + $this->getScheduler()->call(function (): void { + })->name('excluded:by-name'), + $this->getScheduler()->call(function (): void { + })->name('report-skipped'), + $this->getScheduler()->call(function (): void { + })->name('report-included'), + ]; + + $this->startCommand('schedule:run'); + + foreach ($tasks as $task) { + $task->run($this->app); + } + + $this->assertSentryCheckInCount(2); + $this->assertEquals('scheduled_report-included', $this->getLastCheckIn()->getMonitorSlug()); + } + + public function testTasksSharingASlugAreNotMonitored(): void + { + $logs = $this->captureSdkLogs(); + $hourly = $this->getScheduler()->call(function (): void { + })->name('send-report')->hourly(); + $daily = $this->getScheduler()->call(function (): void { + })->name('send-report')->daily(); + + $this->startCommand('schedule:run'); + $hourly->run($this->app); + $daily->run($this->app); + + $this->assertSentryCheckInCount(0); + $this->assertTrue($logs->hasWarningThatContains('Not monitoring scheduled tasks with the slug "scheduled_send-report"')); + } + + public function testTaskWithAnExplicitSlugIsMonitoredNextToATaskWithTheSameName(): void + { + $logs = $this->captureSdkLogs(); + $hourly = $this->getScheduler()->call(function (): void { + })->name('send-report')->hourly()->sentryMonitor('send-report-hourly'); + $daily = $this->getScheduler()->call(function (): void { + })->name('send-report')->daily(); + + $this->startCommand('schedule:run'); + $hourly->run($this->app); + $this->assertEquals('send-report-hourly', $this->getLastCheckIn()->getMonitorSlug()); + $daily->run($this->app); + $this->assertEquals('scheduled_send-report', $this->getLastCheckIn()->getMonitorSlug()); + + $this->assertFalse($logs->hasWarningRecords()); + } + + public function testTaskSharingASlugWithAManuallyMonitoredTaskIsNotMonitored(): void + { + $logs = $this->captureSdkLogs(); + $this->getScheduler()->call(function (): void { + })->name('send-report')->daily()->sentryMonitor(); + $hourly = $this->getScheduler()->call(function (): void { + })->name('other-report')->hourly(); + $this->getScheduler()->call(function (): void { + })->name('send-report')->hourly()->sentryMonitor('scheduled_other-report'); + + $this->startCommand('schedule:run'); + $hourly->run($this->app); + + $this->assertSentryCheckInCount(0); + $this->assertTrue($logs->hasWarningThatContains('"scheduled_other-report"')); + } + + public function testLongSlugIsHashed(): void + { + $task = $this->getScheduler()->call(function (): void { + })->name(str_repeat('send-report-', 10))->hourly(); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $slug = $this->getLastCheckIn()->getMonitorSlug(); + + $this->assertSame(50, strlen($slug)); + $this->assertSame(1, preg_match('/_[0-9a-f]{8}$/', $slug)); + + // The slug Sentry shows can be copied into the exclusions + $this->resetApplicationWithConfig([ + ...$this->setupConfig, + 'sentry.crons.exclude_scheduled_tasks' => [$slug], + ]); + $task = $this->getScheduler()->call(function (): void { + })->name(str_repeat('send-report-', 10))->hourly(); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(0); + } + + public function testLongUniqueSlugsStayDistinct(): void + { + $prefix = str_repeat('send-report-', 5); + $first = $this->getScheduler()->call(function (): void { + })->name($prefix . 'first')->hourly(); + $second = $this->getScheduler()->call(function (): void { + })->name($prefix . 'second')->hourly(); + + $this->startCommand('schedule:run'); + $first->run($this->app); + $firstSlug = $this->getLastCheckIn()->getMonitorSlug(); + $second->run($this->app); + $secondSlug = $this->getLastCheckIn()->getMonitorSlug(); + + $this->assertSame(50, strlen($firstSlug)); + $this->assertSame(50, strlen($secondSlug)); + $this->assertNotEquals($firstSlug, $secondSlug); + } + + #[DataProvider('monitorConfigDataProvider')] + public function testMonitorConfig(callable $configure, ?string $expectedCrontab): void + { + $task = $configure($this->getScheduler()->call(function (): void { + })->name('send-report')->timezone('UTC')); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + if ($expectedCrontab === null) { + $this->assertSentryCheckInCount(0); + + return; + } + + $this->assertEquals('scheduled_send-report', $this->getLastCheckIn()->getMonitorSlug()); + $this->assertEquals($expectedCrontab, $this->getLastCheckIn()->getMonitorConfig()->getSchedule()->getValue()); + } + + /** + * Provide task schedules with the crontab Sentry should expect, or null when the task is not monitored. + */ + public static function monitorConfigDataProvider(): iterable + { + yield 'crontab' => [static fn (Event $task): Event => $task->weekdays()->at('9:30'), '30 9 * * 1-5']; + yield 'without overlapping' => [static fn (Event $task): Event => $task->hourly()->withoutOverlapping(), '0 * * * *']; + yield 'last day of month' => [static fn (Event $task): Event => $task->cron('0 0 L * *'), '0 0 L * *']; + yield 'question mark' => [static fn (Event $task): Event => $task->cron('0 0 ? * MON'), '0 0 * * MON']; + yield 'named timezone' => [static fn (Event $task): Event => $task->daily()->timezone('Europe/Vienna'), '0 0 * * *']; + yield 'nearest weekday' => [static fn (Event $task): Event => $task->cron('0 0 15W * *'), null]; + yield 'day step and weekday' => [static fn (Event $task): Event => $task->cron('0 0 */2 * 1'), null]; + yield 'day and weekday' => [static fn (Event $task): Event => $task->cron('0 0 1 * 1'), null]; + yield 'step from a number' => [static fn (Event $task): Event => $task->cron('5/15 * * * *'), null]; + yield 'step over a range' => [static fn (Event $task): Event => $task->cron('0 9-17/2 * * *'), '0 9-17/2 * * *']; + yield 'range of one value' => [static fn (Event $task): Event => $task->cron('05-5/2 * * * *'), null]; + yield 'step as large as the field' => [static fn (Event $task): Event => $task->cron('*/59 * * * *'), null]; + yield 'stepped weekday range ending at 7' => [static fn (Event $task): Event => $task->cron('0 0 * * 0-07/2'), null]; + yield 'start of a clock change' => [static fn (Event $task): Event => $task->dailyAt('2:00')->timezone('Europe/Vienna'), '0 2 * * *']; + yield 'weekdays at a time a Sunday clock change skips' => [static fn (Event $task): Event => $task->weekdays()->at('2:30')->timezone('Europe/Vienna'), '30 2 * * 1-5']; + yield 'Sundays at a time a Sunday clock change skips' => [static fn (Event $task): Event => $task->sundays()->at('2:30')->timezone('Europe/Vienna'), null]; + yield 'weekday that depends on the date' => [static fn (Event $task): Event => $task->cron('30 2 * * 1#1')->timezone('Europe/Vienna'), null]; + yield 'minutes during a clock change' => [static fn (Event $task): Event => $task->everyFifteenMinutes()->timezone('Europe/Vienna'), '*/15 * * * *']; + yield 'when' => [static fn (Event $task): Event => $task->daily()->when(fn (): bool => true), null]; + yield 'skip' => [static fn (Event $task): Event => $task->daily()->skip(fn (): bool => false), null]; + yield 'between' => [static fn (Event $task): Event => $task->hourly()->between('8:00', '17:00'), null]; + yield 'offset timezone' => [static fn (Event $task): Event => $task->daily()->timezone('+05:00'), null]; + } + + // Spring clock changes can be 371 days apart, so the year after the first date has none + #[TestWith(['2029-03-26 12:00:00'])] + #[TestWith(['2029-04-03 12:00:00'])] + public function testTimeAClockChangeSkipsIsNotMonitoredWhateverTheDate(string $now): void + { + Date::setTestNow($now); + + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->dailyAt('2:30')->timezone('Europe/Vienna'); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(0); + } + + // Upstream doesn't monitor `lastDayOfMonth()`, because Laravel writes this month's last day number. + // Hypervel writes "L", so the task is monitored with a crontab that holds for every month. + public function testLastDayOfMonthIsMonitored(): void + { + Date::setTestNow('2026-02-10 12:00:00'); + + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->timezone('UTC')->lastDayOfMonth(); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertEquals('0 0 L * *', $this->getLastCheckIn()->getMonitorConfig()->getSchedule()->getValue()); + } + + public function testTaskWithAnUnsupportedScheduleIsNotMonitored(): void + { + $logs = $this->captureSdkLogs(); + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->timezone('UTC')->daily()->when(fn (): bool => true); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(0); + $this->assertTrue($logs->hasDebugThatContains('Not monitoring the scheduled task "scheduled_send-report"')); + } + + public function testManuallyMonitoredTaskWithAnUnsupportedScheduleChecksInWithoutAConfig(): void + { + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->daily()->when(fn (): bool => true)->sentryMonitor('custom-slug', null, null, false); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(2); + $this->assertNull($this->getLastCheckIn()->getMonitorConfig()); + } + + // February 28 is February's last day, so this also checks that an ordinary day number isn't treated as `lastDayOfMonth()`. + public function testMonthlyOnHasMonitorConfig(): void + { + Date::setTestNow('2026-02-10 12:00:00'); + + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->timezone('UTC')->monthlyOn(28); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertEquals('0 0 28 * *', $this->getLastCheckIn()->getMonitorConfig()->getSchedule()->getValue()); + } + + public function testSubMinuteTaskIsNotMonitored(): void + { + $task = $this->getScheduler()->call(function (): void { + })->name('send-report')->everyTenSeconds(); + + $this->startCommand('schedule:run'); + $task->run($this->app); + + $this->assertSentryCheckInCount(0); + } + + public function testScheduleSetupFailureIsLoggedWithoutStoppingTheCommand(): void + { + $logs = $this->captureSdkLogs(); + $this->app->singleton(Schedule::class, static fn (): never => throw new RuntimeException('Broken schedule.')); + + $this->startCommand('schedule:run'); + + $this->assertTrue($logs->hasWarningThatContains('Failed to set up cron monitoring for scheduled tasks.')); + } + + #[TestWith([false])] + #[TestWith([true])] + public function testScheduleSetupCancellationIsRethrown(bool $wrapped): void + { + $cancellation = $wrapped ? new RuntimeException('Cleanup failed.', previous: new CanceledException) : new CanceledException; + $logs = $this->captureSdkLogs(); + $this->app->singleton(Schedule::class, static fn (): never => throw $cancellation); + + $caught = null; + + try { + $this->startCommand('schedule:run'); + } catch (Throwable $exception) { + $caught = $exception; + } + + $this->assertSame($cancellation, $caught); + $this->assertFalse($logs->hasWarningRecords()); + } + + public function testScheduledTasksAreNotMonitoredByDefault(): void + { + $this->resetApplicationWithConfig([]); + + $this->getScheduler()->call(function (): void { + })->name('every-minute')->everyMinute(); + + $this->startCommand('schedule:run'); + $this->artisan('schedule:run', ['--once' => true]); + + $this->assertSentryCheckInCount(0); + } + + /** + * Dispatch the event that starts the given command. + */ + private function startCommand(string $command): void + { + $this->app->make('events')->dispatch(new CommandStarting($command, new ArrayInput([]), new NullOutput)); + } + + /** + * Capture the Sentry SDK's log records. + */ + private function captureSdkLogs(): TestHandler + { + $handler = new TestHandler; + + $this->getSentryClientFromContainer()->getOptions()->setLogger(new Logger('sentry', [$handler])); + + return $handler; + } + + /** + * Get the last check-in sent to Sentry. + */ + private function getLastCheckIn(): CheckIn + { + $checkIn = $this->getLastSentryEvent()->getCheckIn(); + + $this->assertNotNull($checkIn); + + return $checkIn; + } + + /** + * Get the scheduler. + */ + private function getScheduler(): Schedule + { + return $this->app->make(Schedule::class); + } +} diff --git a/tests/Sentry/Features/RouteIntegrationTest.php b/tests/Sentry/Features/RouteIntegrationTest.php index 5a39d5bdfb..9a14d1e164 100644 --- a/tests/Sentry/Features/RouteIntegrationTest.php +++ b/tests/Sentry/Features/RouteIntegrationTest.php @@ -7,6 +7,7 @@ use Hypervel\Routing\Router; use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Tests\Sentry\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; class RouteIntegrationTest extends TestCase { @@ -24,6 +25,32 @@ protected function defineRoutes(Router $router): void abort((int) $code); }); }); + + foreach (['/horizon/api/stats', '/telescope/{view?}', '/horizontal'] as $uri) { + $router->get($uri, function (): string { + return 'ok'; + }); + } + } + + #[DataProvider('developmentToolRouteDataProvider')] + #[DefineEnvironment('envSamplingAllTransactions')] + public function testTransactionIsDroppedForDevelopmentToolRoutesByDefault(string $uri, int $expectedTransactionCount): void + { + $this->get($uri)->assertOk(); + + $this->assertSentryTransactionCount($expectedTransactionCount); + } + + /** + * Provide development tool routes and how many transactions each records. + */ + public static function developmentToolRouteDataProvider(): iterable + { + yield 'horizon' => ['/horizon/api/stats', 0]; + yield 'telescope' => ['/telescope', 0]; + // REMOVED: debugbar case; Hypervel has no Debugbar package. + yield 'route only sharing the start of its name' => ['/horizontal', 1]; } #[DefineEnvironment('envSamplingAllTransactions')] diff --git a/tests/Sentry/Features/ViewEngineDecoratorTest.php b/tests/Sentry/Features/ViewEngineDecoratorTest.php index 993f3b36b0..4f74da4a86 100644 --- a/tests/Sentry/Features/ViewEngineDecoratorTest.php +++ b/tests/Sentry/Features/ViewEngineDecoratorTest.php @@ -85,7 +85,7 @@ public function testViewEngineIsNotDoubleDecorated(): void } } - public function testViewNameIsAvailableDuringRender(): void + public function testNamedViewUsesViewNameAsSpanDescription(): void { $this->filesystem->put($this->viewPath . '/hello.blade.php', 'Hello'); @@ -103,6 +103,32 @@ public function testViewNameIsAvailableDuringRender(): void ); } + public function testFileViewInsideBasePathHasBasePathStrippedFromSpanDescription(): void + { + $this->filesystem->ensureDirectoryExists($this->viewPath . '/views'); + $this->filesystem->put($this->viewPath . '/views/hello.blade.php', 'Hello'); + + // Use the temporary directory as the application base path so the view file is located inside of it + $this->app->setBasePath($this->viewPath); + + $transaction = $this->startTransaction(); + + $this->app->make('view')->file($this->viewPath . '/views/hello.blade.php')->render(); + + $this->assertSame('/views/hello.blade.php', $this->lastViewSpanDescription($transaction)); + } + + public function testFileViewOutsideBasePathKeepsFullPathAsSpanDescription(): void + { + $this->filesystem->put($this->viewPath . '/hello.blade.php', 'Hello'); + + $transaction = $this->startTransaction(); + + $this->app->make('view')->file($this->viewPath . '/hello.blade.php')->render(); + + $this->assertSame($this->viewPath . '/hello.blade.php', $this->lastViewSpanDescription($transaction)); + } + public function testViewNamesAreIsolatedBetweenConcurrentRenders(): void { $this->filesystem->put($this->viewPath . '/first.blade.php', 'First'); diff --git a/tests/Sentry/IntegrationTest.php b/tests/Sentry/IntegrationTest.php index 5eccbc54e1..6e1a8490da 100644 --- a/tests/Sentry/IntegrationTest.php +++ b/tests/Sentry/IntegrationTest.php @@ -98,6 +98,45 @@ public function testTransactionIsNotAppliedToEventWhenTransactionIsAlreadySet(): }); } + public function testTransactionTakesPrecedenceOverRequestPath(): void + { + Integration::setTransaction($transaction = '/users/{id}'); + + $_SERVER['PATH_INFO'] = '/users/123'; + + try { + withScope(function (Scope $scope) use ($transaction): void { + $event = $scope->applyToEvent(Event::createEvent()); + + $this->assertNotNull($event); + + $this->assertSame($transaction, $event->getTransaction()); + }); + } finally { + unset($_SERVER['PATH_INFO']); + } + } + + public function testRequestPathIsAppliedToEventWithoutTransaction(): void + { + Integration::setTransaction(null); + + $requestPath = '/users/123'; + $_SERVER['PATH_INFO'] = $requestPath; + + try { + withScope(function (Scope $scope) use ($requestPath): void { + $event = $scope->applyToEvent(Event::createEvent()); + + $this->assertNotNull($event); + + $this->assertSame($requestPath, $event->getTransaction()); + }); + } finally { + unset($_SERVER['PATH_INFO']); + } + } + public function testExtractingNameForRouteWithoutName(): void { $route = new Route('GET', $url = '/foo', []);