TenantAtlas/tests/Feature/OperationRunServiceTest.php
ahmido 3030dd9af2 054-unify-runs-suitewide (#63)
Summary

Kurz: Implementiert Feature 054 — canonical OperationRun-flow, Monitoring UI, dispatch-safety, notifications, dedupe, plus small UX safety clarifications (RBAC group search delegated; Restore group mapping DB-only).
What Changed

Core service: OperationRun lifecycle, dedupe and dispatch helpers — OperationRunService.php.
Model + migration: OperationRun model and migration — OperationRun.php, 2026_01_16_180642_create_operation_runs_table.php.
Notifications: queued + terminal DB notifications (initiator-only) — OperationRunQueued.php, OperationRunCompleted.php.
Monitoring UI: Filament list/detail + Livewire pieces (DB-only render) — OperationRunResource.php and related pages/views.
Start surfaces / Jobs: instrumented start surfaces, job middleware, and job updates to use canonical runs — multiple app/Jobs/* and app/Filament/* updates (see tests for full coverage).
RBAC + Restore UX clarifications: RBAC group search is delegated-Graph-based and disabled without delegated token; Restore group mapping remains DB-only (directory cache) and helper text always visible — TenantResource.php, RestoreRunResource.php.
Specs / Constitution: updated spec & quickstart and added one-line constitution guideline about Graph usage:
spec.md
quickstart.md
constitution.md
Tests & Verification

Unit / Feature tests added/updated for run lifecycle, notifications, idempotency, and UI guards: see tests/Feature/* (notably OperationRunServiceTest, MonitoringOperationsTest, OperationRunNotificationTest, and various Filament feature tests).
Full test run locally: ./vendor/bin/sail artisan test → 587 passed, 5 skipped.
Migrations

Adds create_operation_runs_table migration; run php artisan migrate in staging after review.
Notes / Rationale

Monitoring pages are explicitly DB-only at render time (no Graph calls). Start surfaces enqueue work only and return a “View run” link.
Delegated Graph access is used only for explicit user actions (RBAC group search); restore mapping intentionally uses cached DB data only to avoid render-time Graph calls.
Dispatch wrapper marks runs failed immediately if background dispatch throws synchronously to avoid misleading “queued” states.
Upgrade / Deploy Considerations

Run migrations: ./vendor/bin/sail artisan migrate.
Background workers should be running to process queued jobs (recommended to monitor queue health during rollout).
No secret or token persistence changes.
PR checklist

 Tests updated/added for changed behavior
 Specs updated: 054-unify-runs-suitewide docs + quickstart
 Constitution note added (.specify)
 Pint formatting applied

Co-authored-by: Ahmed Darrazi <ahmeddarrazi@adsmac.local>
Reviewed-on: #63
2026-01-17 22:25:00 +00:00

172 lines
5.6 KiB
PHP

<?php
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationRunService;
it('creates a new operation run', function () {
$tenant = Tenant::factory()->create();
$user = User::factory()->create();
$service = new OperationRunService;
$run = $service->ensureRun($tenant, 'test.action', ['scope' => 'full'], $user);
expect($run)->toBeInstanceOf(OperationRun::class);
$this->assertDatabaseHas('operation_runs', [
'id' => $run->getKey(),
'tenant_id' => $tenant->getKey(),
'type' => 'test.action',
'status' => 'queued',
'initiator_name' => $user->name,
]);
});
it('reuses an active run (idempotent)', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$runA = $service->ensureRun($tenant, 'test.action', ['scope' => 'full']);
$runB = $service->ensureRun($tenant, 'test.action', ['scope' => 'full']);
expect($runA->getKey())->toBe($runB->getKey());
expect(OperationRun::query()->count())->toBe(1);
});
it('does not replace the initiator when deduping', function () {
$tenant = Tenant::factory()->create();
$userA = User::factory()->create();
$userB = User::factory()->create();
$service = new OperationRunService;
$runA = $service->ensureRun($tenant, 'test.action', ['scope' => 'full'], $userA);
$runB = $service->ensureRun($tenant, 'test.action', ['scope' => 'full'], $userB);
expect($runA->getKey())->toBe($runB->getKey());
expect($runB->fresh()?->user_id)->toBe($userA->getKey());
expect($runB->fresh()?->initiator_name)->toBe($userA->name);
});
it('hashes inputs deterministically regardless of key order', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$runA = $service->ensureRun($tenant, 'test.action', ['b' => 2, 'a' => 1]);
$runB = $service->ensureRun($tenant, 'test.action', ['a' => 1, 'b' => 2]);
expect($runA->getKey())->toBe($runB->getKey());
});
it('hashes list inputs deterministically regardless of list order', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$runA = $service->ensureRun($tenant, 'test.action', ['ids' => [2, 1]]);
$runB = $service->ensureRun($tenant, 'test.action', ['ids' => [1, 2]]);
expect($runA->getKey())->toBe($runB->getKey());
});
it('handles unique-index race collisions by returning the active run', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$fired = false;
$dispatcher = OperationRun::getEventDispatcher();
OperationRun::creating(function (OperationRun $model) use (&$fired): void {
if ($fired) {
return;
}
$fired = true;
OperationRun::withoutEvents(function () use ($model): void {
OperationRun::query()->create([
'tenant_id' => $model->tenant_id,
'user_id' => $model->user_id,
'initiator_name' => $model->initiator_name,
'type' => $model->type,
'status' => $model->status,
'outcome' => $model->outcome,
'run_identity_hash' => $model->run_identity_hash,
'context' => $model->context,
]);
});
});
try {
$run = $service->ensureRun($tenant, 'test.race', ['scope' => 'full']);
} finally {
OperationRun::flushEventListeners();
OperationRun::setEventDispatcher($dispatcher);
}
expect($run)->toBeInstanceOf(OperationRun::class);
expect(OperationRun::query()->where('tenant_id', $tenant->getKey())->where('type', 'test.race')->count())
->toBe(1);
});
it('creates a new run after the previous one completed', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$runA = $service->ensureRun($tenant, 'test.action', ['scope' => 'full']);
$runA->update(['status' => 'completed']);
$runB = $service->ensureRun($tenant, 'test.action', ['scope' => 'full']);
expect($runA->getKey())->not->toBe($runB->getKey());
expect(OperationRun::query()->count())->toBe(2);
});
it('updates run lifecycle fields and summaries', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$run = $service->ensureRun($tenant, 'test.action', []);
$service->updateRun($run, 'running');
$fresh = $run->fresh();
expect($fresh?->status)->toBe('running');
expect($fresh?->started_at)->not->toBeNull();
$service->updateRun($run, 'completed', 'succeeded', ['success' => 1]);
$fresh = $run->fresh();
expect($fresh?->status)->toBe('completed');
expect($fresh?->outcome)->toBe('succeeded');
expect($fresh?->completed_at)->not->toBeNull();
expect($fresh?->summary_counts)->toBe(['success' => 1]);
});
it('sanitizes failure messages and redacts obvious secrets', function () {
$tenant = Tenant::factory()->create();
$service = new OperationRunService;
$run = $service->ensureRun($tenant, 'test.action', []);
try {
throw new RuntimeException('Authorization: Bearer abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
} catch (Throwable $e) {
$service->failRun($run, $e);
}
$fresh = $run->fresh();
expect($fresh?->status)->toBe('completed');
expect($fresh?->outcome)->toBe('failed');
expect($fresh?->failure_summary)->toBeArray();
$message = (string) (($fresh?->failure_summary[0]['message'] ?? ''));
expect($message)->not->toContain('abcdefghijklmnopqrstuvwxyz');
expect($message)->toContain('[REDACTED]');
});