From a685f0d46772f962f5a5835ec165796a7eb96181 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:15 +0000 Subject: [PATCH 01/18] Assert the exact Exists and Unique rules in data validation tests Ports the test changes of spatie/laravel-data#1224 from spatie/laravel-data at 7bda01d6. RulesTest compared created Exists and Unique attributes through a helper that only matched their string or callback forms. Both dataset tests now take upstream's inline branches: the resolved attribute must be the expected class, and the normalizer case asserts that getRule() returns the given rule instance. The PR's Pest, Testbench, Livewire, CI matrix, PHP floor and PHPUnit schema updates don't apply to Hypervel; its snapshot renames keep identical content, and Hypervel's serialization tests use inline expected strings. Validation: RulesTest passes; formatting and static analysis pass. --- .../Data/Attributes/Validation/RulesTest.php | 48 ++++++++----------- 1 file changed, 19 insertions(+), 29 deletions(-) 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); - } } From 0b89f84575cf5f27b0537fd783d7ff74c77ded2f Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:21 +0000 Subject: [PATCH 02/18] Add permission route group macros and document global scopes Ports spatie/laravel-permission#2980, #2981 and #2985 from spatie/laravel-permission at 799e1aec. They share the route macro tests and permission docs, so they land together. Route groups now take the role, permission and roleOrPermission macros on both RouteRegistrar and Router, appending to the group's middleware like Laravel's registrar. Routes, registrars and the router also gain canAny, an alias for permission, and canAll, which adds one permission check per entry. The Route Macros docs take upstream's group, canAny/canAll, middleware ordering and nested group examples. A new Global Scopes and Multitenancy section explains that the shared permission caches are filled through the role and permission models' global scopes. It is adapted to Hypervel: it covers the per-model assignment caches as well as the catalog, and points tenant isolation to row partitioning. Upstream's custom registrar override is omitted, since it wouldn't cover the role or assignment caches. Tests: upstream's group and canAny/canAll RouteTest cases are ported with data providers. Upstream's alias registration isn't needed, since the provider registers the middleware aliases. Validation: the permission suite passes; formatting and static analysis pass. --- src/docs/permission.md | 63 +++- .../src/PermissionServiceProvider.php | 88 +++++ tests/Permission/Integration/RouteTest.php | 323 ++++++++++++++++++ 3 files changed, 473 insertions(+), 1 deletion(-) 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/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/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(); + } } From 9f0cd77c0f0e7984fc8eebceefc4b383d0a1d97b Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:28 +0000 Subject: [PATCH 03/18] Make the disabled teams relation queryable and read-only Ports spatie/laravel-permission#2982 from spatie/laravel-permission at 799e1aec. With teams disabled, teams() joined the roles pivot on a team column that only exists when teams are enabled, so every query, eager load or count on it failed. It now returns an always-empty relation over the direct permissions pivot, so tooling that inspects model relations keeps working. Upstream returns permissions()->whereRaw('1 = 0'). That condition only constrains the related query, so detach(), sync(), toggle(), attach() and updateExistingPivot() through teams() would change the model's direct permissions, and loading it would record its empty results as the model's loaded permissions. The new DisabledTeamsMorphToMany rejects every pivot statement with TeamsNotEnabled and returns no related IDs, and its results aren't recorded as loaded permissions. Tests: upstream's query and eager loading cases are ported for the default and custom UUID models, and skip when teams are enabled since the teams test case inherits them. New cases cover rejected writes leaving direct permissions unchanged and loaded permissions staying current. Validation: the permission suite passes; formatting and static analysis pass. --- .../Relations/DisabledTeamsMorphToMany.php | 45 +++++++++ src/permission/src/Traits/HasRoles.php | 20 +++- .../PartitionRelationProvenanceTest.php | 12 +++ tests/Permission/Traits/HasRolesTest.php | 95 +++++++++++++++++++ 4 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 src/permission/src/Relations/DisabledTeamsMorphToMany.php diff --git a/src/permission/src/Relations/DisabledTeamsMorphToMany.php b/src/permission/src/Relations/DisabledTeamsMorphToMany.php new file mode 100644 index 0000000000..dc916ce7ae --- /dev/null +++ b/src/permission/src/Relations/DisabledTeamsMorphToMany.php @@ -0,0 +1,45 @@ + + */ +class DisabledTeamsMorphToMany extends MorphToMany +{ + /** + * Reject a pivot statement, since teams are disabled. + * + * @throws TeamsNotEnabled + */ + public function newPivotStatement(): 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; + } +} diff --git a/src/permission/src/Traits/HasRoles.php b/src/permission/src/Traits/HasRoles.php index 45e76f787c..29958e3ee1 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 or + * detaching 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/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..77c59fc766 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,97 @@ 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->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); + $newsPermission = $this->app->make(Permission::class)::findByName('edit-news')->getKey(); + $articlesPermission = $this->testUserPermission->getKey(); + + $writes = [ + 'attach' => fn () => $this->testUser->teams()->attach($newsPermission), + 'sync' => fn () => $this->testUser->teams()->sync([$newsPermission]), + 'toggle' => fn () => $this->testUser->teams()->toggle([$articlesPermission]), + 'detach' => fn () => $this->testUser->teams()->detach(), + 'updateExistingPivot' => fn () => $this->testUser->teams()->updateExistingPivot($articlesPermission, ['model_type' => 'other']), + ]; + + 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()); + } } From d20b9fb25382f544702aacb57f6f012719be66f5 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:37 +0000 Subject: [PATCH 04/18] Test that a refresh doesn't leave the JWT manager in refresh mode Ports the behavior covered by PHP-Open-Source-Saver/jwt-auth#305 from PHP-Open-Source-Saver/jwt-auth at d0089327. Upstream's manager, claim factory and auth kept refresh flow and claims between calls, which leaked across Octane requests. Hypervel's JwtManager takes the refresh mode per call and its claim factory takes claims as arguments, so no source change is needed. The new test refreshes an expired token with a shared manager and checks that decoding it is still rejected. Upstream's decode factory case doesn't apply, since Hypervel's decode uses no payload factory, and its provider scoping case maps to the existing guard isolation tests. Validation: JwtManagerTest passes; formatting and static analysis pass. --- tests/Jwt/JwtManagerTest.php | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) 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 { From 9503cc36afb3e20ff040358a4664721ada641cf0 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:37 +0000 Subject: [PATCH 05/18] Let a connector choose the URL API version for its requests Ports saloonphp/saloon#567 from saloonphp/saloon at 378856e6. HasApiVersion gains upstream's public getVersionMode() and protected resolveUrlApiVersion() hook. In URL mode, the connector substitutes the hook's result, which by default is the request's version when the request uses the plugin in URL mode, and otherwise the connector's getApiVersion(). The result is still validated as a single URL label or path segment. Adaptation: upstream replaces {version} once, so the connector's choice is final. Hypervel sets a URL parameter that the request's plugin, booted later, would replace, so a URL-mode request now leaves the version to a connector that applies one. Without that, a connector overriding the hook couldn't choose the URL version. Tests: upstream's three cases are ported, with Hypervel's duplicate URL case folded into upstream's. New cases cover a connector choosing the URL version through the hook and a computed connector version in the URL. The docs note request precedence and the hook. Validation: the Saloon suite passes; formatting and static analysis pass. --- src/docs/saloon.md | 2 +- .../src/Traits/Plugins/HasApiVersion.php | 52 +++++++++- .../Unit/Concerns/HasApiVersionTest.php | 99 ++++++++++++++++++- 3 files changed, 149 insertions(+), 4 deletions(-) diff --git a/src/docs/saloon.md b/src/docs/saloon.md index 470db843e8..bf82a825d5 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 may override the protected `resolveUrlApiVersion` method, which receives the pending request. ### Authentication 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/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()), }; } From 4f6dfa8fe443052b56e53214654784075f0d4091 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:44 +0000 Subject: [PATCH 06/18] Restart sub-minute task cycles each minute in the long-running scheduler Addresses the defect class of hyperf/hyperf#7805 (hyperf/hyperf at 27198f21) in Hypervel's Laravel-style scheduler; Hyperf's crontab package has no Hypervel equivalent. Laravel starts a fresh scheduler each minute, so a sub-minute task's first check in a minute runs. Hypervel's long-running schedule:run kept the task's last check across minutes, so a late check delayed the task in every later minute. A repeatable task's first check in a later minute now runs, while other checks keep Laravel's elapsed-time rule, including after the clock is set back. The once-per-minute check for other tasks compared formatted minutes for inequality, so setting the clock back across a minute boundary ran both minutes' tasks again. A clock set back into the previous minute now treats it as already evaluated, while a longer correction evaluates the earlier minutes again, as a fresh scheduler would. Both checks compare minute numbers computed once per poll. Validation: the console and console integration suites pass; formatting and static analysis pass. --- .../src/Commands/ScheduleRunCommand.php | 22 ++++++++---- .../Scheduling/ScheduleRunCommandTest.php | 36 +++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/console/src/Commands/ScheduleRunCommand.php b/src/console/src/Commands/ScheduleRunCommand.php index 382df1c5e2..f3ce7a89d9 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,23 @@ protected function repeatEvents(Collection $events): void protected function runEvents(Collection $events, CarbonInterface $startedAt): void { $paused = $this->isPaused(); + $minute = intdiv($startedAt->getTimestamp(), 60); 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, $minute)) { continue; } @@ -419,13 +425,17 @@ 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, int $minute): bool { if ($event->isRepeatable()) { return false; } - $minute = $startedAt->format('YmdHi'); + // 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 + if ($this->evaluatedEventsMinute !== null && $minute === $this->evaluatedEventsMinute - 1) { + return true; + } if ($this->evaluatedEventsMinute !== $minute) { $this->evaluatedEventsMinute = $minute; diff --git a/tests/Console/Scheduling/ScheduleRunCommandTest.php b/tests/Console/Scheduling/ScheduleRunCommandTest.php index 8407ce7eb3..637ce40091 100644 --- a/tests/Console/Scheduling/ScheduleRunCommandTest.php +++ b/tests/Console/Scheduling/ScheduleRunCommandTest.php @@ -1166,10 +1166,20 @@ 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); } public function testRepeatableEventIsThrottledByLastChecked(): void { + Date::setTestNow('2026-05-28 12:34:00'); $runCount = 0; $eventMutex = Double::for(EventMutex::class)->strict(); @@ -1195,6 +1205,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'); From 13d88412ded7e53b1243b32d58ef0237c2aa1de0 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:44 +0000 Subject: [PATCH 07/18] Document Sentry violation context and classification message types Ports getsentry/sentry-laravel#1227, #1230 and #1238 from getsentry/sentry-laravel at cf8f5ed7. The model violation reporters' context and the classification formatter's encoded message gain upstream's array shape docblocks. --- .../Features/Classification/ClassificationMessageFormatter.php | 2 ++ .../ModelViolations/DiscardedAttributeViolationReporter.php | 2 ++ .../ModelViolations/LazyLoadingModelViolationReporter.php | 2 ++ 3 files changed, 6 insertions(+) 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/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 { From 87419a2cdcdd17f99e387091dae39c2e77f0c344 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:37:56 +0000 Subject: [PATCH 08/18] Monitor all scheduled tasks and refine Sentry transaction names Ports getsentry/sentry-laravel#1202, #1222, #1223 and #1228 from getsentry/sentry-laravel at cf8f5ed7. They share the service provider, config and docs, so they land together. #1202: with crons.monitor_scheduled_tasks enabled, schedule:run and schedule:test call sentryMonitor() on every task that can be monitored reliably. Tasks are left out when listed in crons.exclude_scheduled_tasks, when they share a slug, or when Sentry would expect runs the task skips or read its schedule differently. Adaptations: - Monitored tasks are tracked in a WeakMap, so schedules built by other resolveConsoleSchedule() calls are freed. - A cancellation while building the schedule propagates; other setup failures are logged as upstream. - Last-day-of-month tasks stay monitored, since Hypervel writes L. - There is no schedule:finish, since background tasks finish in the scheduler process. Two fixes over upstream: exclusions also match the shortened slug that Sentry shows, and the slug and command name helpers only remove the PHP and Artisan binaries from the start of a command, so a command passing them as arguments keeps its name. #1222: the SDK's transaction integration ran before Hypervel's, so the request path replaced the route transaction name. It is now added after Hypervel's and the user's integrations. #1223: Horizon and Telescope routes are ignored by default. Upstream's Debugbar pattern is omitted, since Hypervel has no Debugbar. #1228: view spans for views rendered from a file show the path relative to the base path. Tests: upstream's monitor-all suite is ported with Hypervel's scheduler and frozen dates, with added cases for setup failures, cancellation, excluding a shortened slug and binaries passed as arguments. Upstream's integration, route and view cases are ported, and the config tests cover the crons defaults. The Sentry docs cover monitoring every task and the ignored routes. Validation: the Sentry suite passes; formatting and static analysis pass. --- src/docs/sentry.md | 13 +- src/sentry/config/sentry.php | 12 + .../Features/ConsoleSchedulingIntegration.php | 188 ++++++++- src/sentry/src/SentryConfig.php | 7 + src/sentry/src/SentryServiceProvider.php | 28 +- tests/Sentry/ConfigTest.php | 8 +- .../ConsoleSchedulingIntegrationTest.php | 15 + .../ConsoleSchedulingMonitorAllTasksTest.php | 398 ++++++++++++++++++ .../Sentry/Features/RouteIntegrationTest.php | 27 ++ .../Features/ViewEngineDecoratorTest.php | 28 +- tests/Sentry/IntegrationTest.php | 39 ++ 11 files changed, 751 insertions(+), 12 deletions(-) create mode 100644 tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php diff --git a/src/docs/sentry.md b/src/docs/sentry.md index 0bd1abcff3..c341c70751 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, job classes, or names in the `crons.exclude_scheduled_tasks` configuration option, using `*` as a wildcard: + +```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 are left out. 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/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/ConsoleSchedulingIntegration.php b/src/sentry/src/Features/ConsoleSchedulingIntegration.php index 085a1ee9b7..52969e50d9 100644 --- a/src/sentry/src/Features/ConsoleSchedulingIntegration.php +++ b/src/sentry/src/Features/ConsoleSchedulingIntegration.php @@ -6,12 +6,15 @@ 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\Str; @@ -25,6 +28,8 @@ use Sentry\Tracing\SpanStatus; use Sentry\Tracing\TransactionContext; use Sentry\Tracing\TransactionSource; +use Throwable; +use WeakMap; class ConsoleSchedulingIntegration extends Feature { @@ -38,11 +43,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 +93,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 +101,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 +159,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 +171,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 +276,135 @@ 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; + } + } + } + + return implode(' ', $fields); + } + /** * Send the in-progress check-in for the scheduled event. */ @@ -401,8 +577,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 +597,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/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/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..4d41fe3784 --- /dev/null +++ b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php @@ -0,0 +1,398 @@ + [ + 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 '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]; + } + + // 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', []); From 8a285ded8f4cb9af1e199f2ec26d4bd61c9edadd Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:39:24 +0000 Subject: [PATCH 09/18] Explain using Hypervel's migrations for framework tables when porting Laravel applications ported to Hypervel need Hypervel's schema for framework tables such as jobs, job batches, sessions and cache. The Porting Applications section now says to use Hypervel's migrations for those tables, bring over the application's own migrations and reapply framework-table customizations on Hypervel's schema. For an existing database, it says to keep the migration history and write migrations that bring the framework tables in line with Hypervel's schema. --- src/docs/porting-from-laravel.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 87067cbadd..6d50f98bc6 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 write new migrations for the changes needed to bring its framework tables in line with Hypervel's schema. + 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). From d471d1d60c6f811d768c0c52a8d006f7ba8d3c83 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:01 +0000 Subject: [PATCH 10/18] Evaluate scheduled tasks in their own timezone Event::expressionPasses() formatted the task's local date as a string before passing it to cron-expression, as Laravel does. cron-expression reads a string in PHP's default timezone, so a task whose timezone differs from the application's was checked against the application timezone's clock. Around that timezone's daylight saving changes, such tasks ran at the wrong times: with the application in Europe/Vienna, a UTC task at 02:30 also ran at 03:30 UTC on the spring change day. Pass the date itself. cron-expression 3 evaluates a date object in its own timezone, which is how the scheduler's next run date and schedule:list already call it. Laravel's string form dates from cron-expression 1, which forced the default timezone onto date objects. A comment beside the call records the difference so a future sync doesn't restore the string. Adds a regression test for the Vienna and UTC example. --- src/console/src/Scheduling/Event.php | 5 +++-- tests/Console/Scheduling/EventTest.php | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) 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/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; From b5d5302e44ae4ea974501fb20a2a21f8eaf0e019 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:01 +0000 Subject: [PATCH 11/18] Record every polled minute when detecting a clock set back The long-running scheduler doesn't run non-repeatable events again when the clock is set back into the previous minute, and evaluates the earlier minutes again after a longer correction, as a fresh scheduler would. It only recorded the minute while evaluating a non-repeatable event, so after polls with no due events, a longer correction that landed one minute before the last recorded minute was mistaken for a one-minute rollback and the task was skipped. Record the minute on every poll before evaluating events, and pass whether the poll is in the previous minute to hasAlreadyEvaluatedNonRepeatableEvent(). The existing rollback test now covers a correction after polls without due events. --- .../src/Commands/ScheduleRunCommand.php | 23 +++++++++++-------- .../Scheduling/ScheduleRunCommandTest.php | 5 ++++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/console/src/Commands/ScheduleRunCommand.php b/src/console/src/Commands/ScheduleRunCommand.php index f3ce7a89d9..c9e15228e1 100644 --- a/src/console/src/Commands/ScheduleRunCommand.php +++ b/src/console/src/Commands/ScheduleRunCommand.php @@ -295,6 +295,16 @@ protected function runEvents(Collection $events, CarbonInterface $startedAt): vo $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; @@ -309,7 +319,7 @@ protected function runEvents(Collection $events, CarbonInterface $startedAt): vo continue; } - if ($this->hasAlreadyEvaluatedNonRepeatableEvent($event, $minute)) { + if ($this->hasAlreadyEvaluatedNonRepeatableEvent($event, $isPreviousMinute)) { continue; } @@ -425,23 +435,16 @@ protected function runScheduledEvent(Event $event, CarbonInterface $startedAt): /** * Determine if the non-repeatable event was already evaluated this minute. */ - protected function hasAlreadyEvaluatedNonRepeatableEvent(Event $event, int $minute): bool + protected function hasAlreadyEvaluatedNonRepeatableEvent(Event $event, bool $isPreviousMinute): bool { if ($event->isRepeatable()) { return false; } - // 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 - if ($this->evaluatedEventsMinute !== null && $minute === $this->evaluatedEventsMinute - 1) { + if ($isPreviousMinute) { return true; } - if ($this->evaluatedEventsMinute !== $minute) { - $this->evaluatedEventsMinute = $minute; - $this->evaluatedEvents = []; - } - $eventId = spl_object_id($event); if (isset($this->evaluatedEvents[$eventId])) { diff --git a/tests/Console/Scheduling/ScheduleRunCommandTest.php b/tests/Console/Scheduling/ScheduleRunCommandTest.php index 637ce40091..f194bedc1e 100644 --- a/tests/Console/Scheduling/ScheduleRunCommandTest.php +++ b/tests/Console/Scheduling/ScheduleRunCommandTest.php @@ -1175,6 +1175,11 @@ public function testNonRepeatableEventOnlyRunsOncePerMinute(): void // 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 From 1c18166d6f2ac9f4d577233792984649bdda40dd Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:01 +0000 Subject: [PATCH 12/18] Reject every write through the disabled teams relation With teams disabled, teams() returns a relation over the direct permissions pivot whose queries never match a row, and writes through it are meant to throw. Rejecting newPivotStatement() didn't do that reliably: - reads that filter pivot columns with a closure, such as wherePivot(), build a pivot statement, so they threw instead of returning no rows; - attaching with a custom pivot saves a pivot model and skipped the guard; - save(), create() and forceCreate() stored the related model before the attach failed; - sync() and toggle() read the live pivot rows, so syncing an ID that matched an existing direct permission reported success. Reject attach() and newPivotQuery() instead. Syncing, toggling, detaching and updating pivot records all start with newPivotQuery(), with or without a custom pivot. save(), create() and forceCreate() are rejected before anything is stored. Pivot statements stay available, so closure filters keep returning no rows. The tests cover a closure filter, a custom pivot attach and detach, saving, creating and force creating, and syncing an ID that matches a direct permission, and check that no permission is created. --- .../Relations/DisabledTeamsMorphToMany.php | 51 +++++++++++++++++-- src/permission/src/Traits/HasRoles.php | 4 +- tests/Permission/Traits/HasRolesTest.php | 12 ++++- 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/src/permission/src/Relations/DisabledTeamsMorphToMany.php b/src/permission/src/Relations/DisabledTeamsMorphToMany.php index dc916ce7ae..667aab5dab 100644 --- a/src/permission/src/Relations/DisabledTeamsMorphToMany.php +++ b/src/permission/src/Relations/DisabledTeamsMorphToMany.php @@ -13,8 +13,8 @@ /** * The teams relation while the teams feature is disabled. * - * Its queries join the direct permissions pivot but never match a row. Every pivot - * statement, such as attaching or detaching, is rejected so it can't change those rows. + * Its queries join the direct permissions pivot but never match a row. Every write, such as + * attaching, detaching or creating a related model, is rejected before it changes any rows. * * @template TRelatedModel of Model * @template TDeclaringModel of Model @@ -24,11 +24,24 @@ class DisabledTeamsMorphToMany extends MorphToMany { /** - * Reject a pivot statement, since teams are disabled. + * Reject attaching models, since teams are disabled. * * @throws TeamsNotEnabled */ - public function newPivotStatement(): QueryBuilder + 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(); } @@ -42,4 +55,34 @@ 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 29958e3ee1..2dcaab13ab 100644 --- a/src/permission/src/Traits/HasRoles.php +++ b/src/permission/src/Traits/HasRoles.php @@ -264,8 +264,8 @@ 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, and attaching or - * detaching through it throws. + * break. Querying it is a no-op and produces no rows, and writing through it + * throws. */ public function teams(): BelongsToMany { diff --git a/tests/Permission/Traits/HasRolesTest.php b/tests/Permission/Traits/HasRolesTest.php index 77c59fc766..2de3ce0c03 100644 --- a/tests/Permission/Traits/HasRolesTest.php +++ b/tests/Permission/Traits/HasRolesTest.php @@ -1191,6 +1191,7 @@ public function testCanQueryTheDisabledTeamsRelationWithoutMigratingTeamColumns( $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()); @@ -1246,15 +1247,23 @@ public function testWritesThroughTheDisabledTeamsRelationAreRejectedWithoutChang } $this->testUser->givePermissionTo($this->testUserPermission); - $newsPermission = $this->app->make(Permission::class)::findByName('edit-news')->getKey(); + $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) { @@ -1266,5 +1275,6 @@ public function testWritesThroughTheDisabledTeamsRelationAreRejectedWithoutChang } $this->assertSame(['edit-articles'], $this->testUser->fresh()->getPermissionNames()->all()); + $this->assertSame($permissionCount, $permissionModel::count()); } } From 58853f890a8dfe2c15928786497018160f528e0b Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:02 +0000 Subject: [PATCH 13/18] Leave out schedules Sentry would read differently Automatic monitoring sends each eligible task's crontab to Sentry, whose cron parser reads some schedules differently from the scheduler's. Leave out the remaining cases where they disagree: - a range of a single value, such as 5-5/2; - a step as large as the field's last value, such as */59; - a stepped weekday range ending at 7, which Sentry reads with Sundays; - a set minute and hour that a daylight saving change skips, unless the scheduler runs the task when the change ends. Like Debian cron, Sentry expects such a task right after the change and would report it missed. Clock changes fall on the same weekday each year but not on the same date, so only the time and an ordinary weekday are compared with the timezone's forward changes over the next two years. The result doesn't depend on when the scheduler starts, and weekday tasks that never meet a change stay monitored. Weekdays that depend on the date, such as "5L" and "1#2", are compared as any day. The integration now uses cron-expression directly, so the package requires it. The Sentry docs explain how scheduled jobs are named for exclusion and that daylight saving changes can leave some tasks out. --- src/docs/sentry.md | 4 +- src/sentry/composer.json | 1 + .../Features/ConsoleSchedulingIntegration.php | 55 +++++++++++++++++++ .../ConsoleSchedulingMonitorAllTasksTest.php | 24 ++++++++ 4 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/docs/sentry.md b/src/docs/sentry.md index c341c70751..8fd972f073 100644 --- a/src/docs/sentry.md +++ b/src/docs/sentry.md @@ -368,7 +368,7 @@ 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, job classes, or names in the `crons.exclude_scheduled_tasks` configuration option, using `*` as a wildcard: +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' => [ @@ -377,7 +377,7 @@ To monitor every scheduled task without calling `sentryMonitor` on each one, set ], ``` -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 are left out. Call `sentryMonitor` on such a task to monitor it yourself. +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. 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/src/Features/ConsoleSchedulingIntegration.php b/src/sentry/src/Features/ConsoleSchedulingIntegration.php index 52969e50d9..63b08418b4 100644 --- a/src/sentry/src/Features/ConsoleSchedulingIntegration.php +++ b/src/sentry/src/Features/ConsoleSchedulingIntegration.php @@ -4,6 +4,8 @@ namespace Hypervel\Sentry\Features; +use Cron\CronExpression; +use DateTimeImmutable; use DateTimeZone; use Hypervel\Console\Application as ConsoleApplication; use Hypervel\Console\Events\CommandStarting; @@ -17,6 +19,7 @@ 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; @@ -399,12 +402,64 @@ private function getMonitorCrontab(SchedulingEvent $task): ?string 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 !== '' && $start === $end) + || ($step !== '' && ((int) $step >= [59, 23, 31, 12, 7][$position] || ($position === 4 && $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. */ diff --git a/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php index 4d41fe3784..5f7b67a712 100644 --- a/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php +++ b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php @@ -242,12 +242,36 @@ public static function monitorConfigDataProvider(): iterable 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('5-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-7/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 From dbb099ae9a2b361fe52123dc5f775d05e64b0f1a Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:02 +0000 Subject: [PATCH 14/18] Note that only connectors with an API version use the URL version hook A connector's resolveUrlApiVersion() runs when the connector sends an API version in URL mode. Without one, a request's own version fills the URL, so say that the method applies to a connector with an API version. --- src/docs/saloon.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/saloon.md b/src/docs/saloon.md index bf82a825d5..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 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 may override the protected `resolveUrlApiVersion` method, which receives the pending request. +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 From 9db9dbb48794cda71006716dc156a9ed108fe8f4 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:02 +0000 Subject: [PATCH 15/18] Keep skeleton migrations only for missing framework tables when porting When a ported application keeps its existing database, the skeleton's migrations for framework tables it already has would try to create those tables again. Explain that only the migrations for missing framework tables are kept, and that existing framework tables are brought in line with Hypervel's schema through new migrations. --- src/docs/porting-from-laravel.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 6d50f98bc6..4b5c89d9aa 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -1029,7 +1029,7 @@ 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 write new migrations for the changes needed to bring its framework tables in line with Hypervel's schema. +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. 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. From 18ea58ba7ac3f91895a20c3e589cf4c35ccfa804 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:19:22 +0000 Subject: [PATCH 16/18] Compare cron range values as numbers when checking Sentry schedules Automatic Sentry monitoring leaves out a range of a single value with a step, such as 5-5/2, and a stepped weekday range ending at 7, because Sentry's cron parser reads them differently from the scheduler's. Both checks compared the values as strings, so padded forms such as 05-5/2 and 0-07/2 got through and Sentry expected runs the scheduler never makes. Compare them as numbers. The existing test cases now use the padded forms, so they cover both the guards and the numeric comparison. --- src/sentry/src/Features/ConsoleSchedulingIntegration.php | 4 ++-- .../Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sentry/src/Features/ConsoleSchedulingIntegration.php b/src/sentry/src/Features/ConsoleSchedulingIntegration.php index 63b08418b4..66c332d156 100644 --- a/src/sentry/src/Features/ConsoleSchedulingIntegration.php +++ b/src/sentry/src/Features/ConsoleSchedulingIntegration.php @@ -408,8 +408,8 @@ private function getMonitorCrontab(SchedulingEvent $task): ?string // 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 !== '' && $start === $end) - || ($step !== '' && ((int) $step >= [59, 23, 31, 12, 7][$position] || ($position === 4 && $end === '7')))) { + if (($start !== '' && (int) $start === (int) $end) + || ($step !== '' && ((int) $step >= [59, 23, 31, 12, 7][$position] || ($position === 4 && (int) $end === 7)))) { return null; } } diff --git a/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php index 5f7b67a712..e6d90c5782 100644 --- a/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php +++ b/tests/Sentry/Features/ConsoleSchedulingMonitorAllTasksTest.php @@ -242,9 +242,9 @@ public static function monitorConfigDataProvider(): iterable 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('5-5/2 * * * *'), null]; + 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-7/2'), 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]; From dfd40badfcc60777fbb582befe380249f6c69b40 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:19:22 +0000 Subject: [PATCH 17/18] Start fresh databases from a schema dump after porting an existing one When a ported application keeps its existing database, its framework tables were created by Laravel migrations that aren't brought over, so a fresh database, such as one built by migrate:fresh in tests, would never create them and the migrations that align those tables with Hypervel's schema would fail. Tell readers to dump the schema with its migration records once the alignment migrations have run, so fresh databases start from the dump, and link to the existing schema dump documentation. --- src/docs/porting-from-laravel.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 4b5c89d9aa..2efd13c99b 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -1029,7 +1029,7 @@ 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. +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. From a57b08bbf124d5915cd4a21c07a888ef11509d17 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:19:22 +0000 Subject: [PATCH 18/18] Describe exactly which writes the disabled teams relation rejects The disabled teams relation rejects attaching, detaching, syncing, and saving or creating related models through it. Query builder writes forwarded through any relation, such as insert() or upsert(), skip relation constraints and aren't guarded, so the class and teams() docblocks now name the guarded operations instead of claiming every write is rejected. --- src/permission/src/Relations/DisabledTeamsMorphToMany.php | 5 +++-- src/permission/src/Traits/HasRoles.php | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/permission/src/Relations/DisabledTeamsMorphToMany.php b/src/permission/src/Relations/DisabledTeamsMorphToMany.php index 667aab5dab..9f31955189 100644 --- a/src/permission/src/Relations/DisabledTeamsMorphToMany.php +++ b/src/permission/src/Relations/DisabledTeamsMorphToMany.php @@ -13,8 +13,9 @@ /** * The teams relation while the teams feature is disabled. * - * Its queries join the direct permissions pivot but never match a row. Every write, such as - * attaching, detaching or creating a related model, is rejected before it changes any rows. + * Its queries join the direct permissions pivot but never match a row. Attaching, detaching, + * syncing, and saving or creating a related model through it are rejected before they change + * any rows. * * @template TRelatedModel of Model * @template TDeclaringModel of Model diff --git a/src/permission/src/Traits/HasRoles.php b/src/permission/src/Traits/HasRoles.php index 2dcaab13ab..0dbc7e7e40 100644 --- a/src/permission/src/Traits/HasRoles.php +++ b/src/permission/src/Traits/HasRoles.php @@ -264,8 +264,8 @@ 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, and writing through it - * throws. + * 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 {