Implements Spec 087: Legacy Runs Removal (rigorous). ### What changed - Canonicalized run history: **`operation_runs` is the only run system** for inventory sync, Entra group sync, backup schedule execution/retention/purge. - Removed legacy UI surfaces (Filament Resources / relation managers) for legacy run models. - Legacy run URLs now return **404** (no redirects), with RBAC semantics preserved (404 vs 403 as specified). - Canonicalized affected `operation_runs.type` values (dotted → underscore) via migration. - Drift + inventory references now point to canonical operation runs; includes backfills and then drops legacy FK columns. - Drops legacy run tables after cutover. - Added regression guards to prevent reintroducing legacy run tokens or “backfilling” canonical runs from legacy tables. ### Migrations - `2026_02_12_000001..000006_*` canonicalize types, add/backfill operation_run_id references, drop legacy columns, and drop legacy run tables. ### Tests Focused pack for this spec passed: - `tests/Feature/Guards/NoLegacyRunsTest.php` - `tests/Feature/Guards/NoLegacyRunBackfillTest.php` - `tests/Feature/Operations/LegacyRunRoutesNotFoundTest.php` - `tests/Feature/Monitoring/MonitoringOperationsTest.php` - `tests/Feature/Jobs/RunInventorySyncJobTest.php` ### Notes / impact - Destructive cleanup is handled via migrations (drops legacy tables) after code cutover; deploy should run migrations in the same release. Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de> Reviewed-on: #106
293 lines
11 KiB
PHP
293 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Jobs\Middleware\TrackOperationRun;
|
|
use App\Models\OperationRun;
|
|
use App\Models\Tenant;
|
|
use App\Models\User;
|
|
use App\Services\Intune\AuditLogger;
|
|
use App\Services\Inventory\InventorySyncService;
|
|
use App\Services\OperationRunService;
|
|
use App\Support\OperationRunOutcome;
|
|
use App\Support\OperationRunStatus;
|
|
use App\Support\Providers\ProviderReasonCodes;
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Queue\SerializesModels;
|
|
use RuntimeException;
|
|
|
|
class RunInventorySyncJob implements ShouldQueue
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
|
public ?OperationRun $operationRun = null;
|
|
|
|
/**
|
|
* Create a new job instance.
|
|
*/
|
|
public function __construct(
|
|
public int $tenantId,
|
|
public int $userId,
|
|
?OperationRun $operationRun = null
|
|
) {
|
|
$this->operationRun = $operationRun;
|
|
}
|
|
|
|
/**
|
|
* Get the middleware the job should pass through.
|
|
*
|
|
* @return array<int, object>
|
|
*/
|
|
public function middleware(): array
|
|
{
|
|
return [new TrackOperationRun];
|
|
}
|
|
|
|
/**
|
|
* Execute the job.
|
|
*/
|
|
public function handle(InventorySyncService $inventorySyncService, AuditLogger $auditLogger, OperationRunService $operationRunService): void
|
|
{
|
|
if (! $this->operationRun) {
|
|
$this->fail(new RuntimeException('OperationRun context is required for RunInventorySyncJob.'));
|
|
|
|
return;
|
|
}
|
|
|
|
$tenant = Tenant::query()->find($this->tenantId);
|
|
if (! $tenant instanceof Tenant) {
|
|
throw new RuntimeException('Tenant not found.');
|
|
}
|
|
|
|
$user = User::query()->find($this->userId);
|
|
if (! $user instanceof User) {
|
|
throw new RuntimeException('User not found.');
|
|
}
|
|
|
|
$context = is_array($this->operationRun->context) ? $this->operationRun->context : [];
|
|
$policyTypes = $context['policy_types'] ?? [];
|
|
$policyTypes = is_array($policyTypes) ? array_values(array_filter(array_map('strval', $policyTypes))) : [];
|
|
|
|
$processedPolicyTypes = [];
|
|
$successCount = 0;
|
|
$failedCount = 0;
|
|
|
|
// Note: The TrackOperationRun middleware will automatically set status to 'running' at start.
|
|
// It will also handle success completion if no exceptions thrown.
|
|
// However, InventorySyncService execution logic might be complex with partial failures.
|
|
// We might want to explicitly update the OperationRun if partial failures occur.
|
|
|
|
$result = $inventorySyncService->executeSelection(
|
|
$this->operationRun,
|
|
$tenant,
|
|
$context,
|
|
function (string $policyType, bool $success, ?string $errorCode) use (&$processedPolicyTypes, &$successCount, &$failedCount): void {
|
|
$processedPolicyTypes[] = $policyType;
|
|
|
|
if ($success) {
|
|
$successCount++;
|
|
|
|
return;
|
|
}
|
|
|
|
$failedCount++;
|
|
},
|
|
);
|
|
|
|
$updatedContext = is_array($this->operationRun->context) ? $this->operationRun->context : [];
|
|
$updatedContext['result'] = [
|
|
'had_errors' => (bool) ($result['had_errors'] ?? true),
|
|
'error_codes' => is_array($result['error_codes'] ?? null) ? array_values($result['error_codes']) : [],
|
|
'error_context' => is_array($result['error_context'] ?? null) ? $result['error_context'] : null,
|
|
];
|
|
|
|
$this->operationRun->update([
|
|
'context' => $updatedContext,
|
|
]);
|
|
|
|
$this->operationRun->refresh();
|
|
|
|
$status = (string) ($result['status'] ?? 'failed');
|
|
$errorCodes = is_array($result['error_codes'] ?? null) ? $result['error_codes'] : [];
|
|
$reason = (string) ($errorCodes[0] ?? $status);
|
|
|
|
$errorContext = is_array($result['error_context'] ?? null) ? $result['error_context'] : [];
|
|
$sanitizedErrorMessage = is_string($errorContext['message'] ?? null) ? (string) $errorContext['message'] : null;
|
|
|
|
$reasonCode = null;
|
|
$sanitizedMessageWithoutReasonCode = null;
|
|
|
|
if (is_string($sanitizedErrorMessage)) {
|
|
$sanitizedMessageWithoutReasonCode = preg_replace('/^\[[^\]]+\]\s*/', '', $sanitizedErrorMessage);
|
|
$sanitizedMessageWithoutReasonCode = is_string($sanitizedMessageWithoutReasonCode)
|
|
? trim($sanitizedMessageWithoutReasonCode)
|
|
: null;
|
|
|
|
if (preg_match('/^\[(?<code>[^\]]+)\]/', $sanitizedErrorMessage, $m)) {
|
|
$candidate = (string) ($m['code'] ?? '');
|
|
if ($candidate !== '' && ProviderReasonCodes::isKnown($candidate)) {
|
|
$reasonCode = $candidate;
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($reason === 'unexpected_exception' && is_string($sanitizedErrorMessage) && $sanitizedErrorMessage !== '') {
|
|
$reason = is_string($sanitizedMessageWithoutReasonCode) && $sanitizedMessageWithoutReasonCode !== ''
|
|
? $sanitizedMessageWithoutReasonCode
|
|
: $sanitizedErrorMessage;
|
|
}
|
|
|
|
$itemsObserved = (int) ($result['items_observed_count'] ?? 0);
|
|
$itemsUpserted = (int) ($result['items_upserted_count'] ?? 0);
|
|
$errorsCount = (int) ($result['errors_count'] ?? 0);
|
|
|
|
if ($status === 'success') {
|
|
$operationRunService->updateRun(
|
|
$this->operationRun,
|
|
status: OperationRunStatus::Completed->value,
|
|
outcome: OperationRunOutcome::Succeeded->value,
|
|
summaryCounts: [
|
|
'total' => count($policyTypes),
|
|
'processed' => count($policyTypes),
|
|
'succeeded' => count($policyTypes),
|
|
'failed' => 0,
|
|
'items' => $itemsObserved,
|
|
'updated' => $itemsUpserted,
|
|
],
|
|
);
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'inventory.sync.completed',
|
|
context: [
|
|
'metadata' => [
|
|
'operation_run_id' => (int) $this->operationRun->getKey(),
|
|
'observed' => $itemsObserved,
|
|
'upserted' => $itemsUpserted,
|
|
],
|
|
],
|
|
actorId: $user->id,
|
|
actorEmail: $user->email,
|
|
actorName: $user->name,
|
|
resourceType: 'operation_run',
|
|
resourceId: (string) $this->operationRun->getKey(),
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
if ($status === 'partial') {
|
|
$operationRunService->updateRun(
|
|
$this->operationRun,
|
|
status: OperationRunStatus::Completed->value,
|
|
outcome: OperationRunOutcome::PartiallySucceeded->value,
|
|
summaryCounts: [
|
|
'total' => count($policyTypes),
|
|
'processed' => count($policyTypes),
|
|
'succeeded' => max(0, count($policyTypes) - $errorsCount),
|
|
'failed' => $errorsCount,
|
|
'items' => $itemsObserved,
|
|
'updated' => $itemsUpserted,
|
|
],
|
|
failures: [
|
|
['code' => 'inventory.partial', 'message' => "Errors: {$errorsCount}"],
|
|
],
|
|
);
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'inventory.sync.partial',
|
|
context: [
|
|
'metadata' => [
|
|
'operation_run_id' => (int) $this->operationRun->getKey(),
|
|
'observed' => $itemsObserved,
|
|
'upserted' => $itemsUpserted,
|
|
'errors' => $errorsCount,
|
|
],
|
|
],
|
|
actorId: $user->id,
|
|
actorEmail: $user->email,
|
|
actorName: $user->name,
|
|
status: 'failure',
|
|
resourceType: 'operation_run',
|
|
resourceId: (string) $this->operationRun->getKey(),
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
if ($status === 'skipped') {
|
|
$operationRunService->updateRun(
|
|
$this->operationRun,
|
|
status: OperationRunStatus::Completed->value,
|
|
outcome: OperationRunOutcome::Failed->value,
|
|
summaryCounts: [
|
|
'total' => count($policyTypes),
|
|
'processed' => count($policyTypes),
|
|
'succeeded' => 0,
|
|
'failed' => 0,
|
|
'skipped' => count($policyTypes),
|
|
],
|
|
failures: [
|
|
['code' => 'inventory.skipped', 'message' => $reason],
|
|
],
|
|
);
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'inventory.sync.skipped',
|
|
context: [
|
|
'metadata' => [
|
|
'operation_run_id' => (int) $this->operationRun->getKey(),
|
|
'reason' => $reason,
|
|
],
|
|
],
|
|
actorId: $user->id,
|
|
actorEmail: $user->email,
|
|
actorName: $user->name,
|
|
resourceType: 'operation_run',
|
|
resourceId: (string) $this->operationRun->getKey(),
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
$missingPolicyTypes = array_values(array_diff($policyTypes, array_unique($processedPolicyTypes)));
|
|
|
|
$operationRunService->updateRun(
|
|
$this->operationRun,
|
|
status: OperationRunStatus::Completed->value,
|
|
outcome: OperationRunOutcome::Failed->value,
|
|
summaryCounts: [
|
|
'total' => count($policyTypes),
|
|
'processed' => count($policyTypes),
|
|
'succeeded' => $successCount,
|
|
'failed' => max($failedCount, count($missingPolicyTypes)),
|
|
],
|
|
failures: [
|
|
['code' => 'inventory.failed', 'reason_code' => $reasonCode, 'message' => $reason],
|
|
],
|
|
);
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'inventory.sync.failed',
|
|
context: [
|
|
'metadata' => [
|
|
'operation_run_id' => (int) $this->operationRun->getKey(),
|
|
'reason' => $reason,
|
|
],
|
|
],
|
|
actorId: $user->id,
|
|
actorEmail: $user->email,
|
|
actorName: $user->name,
|
|
status: 'failure',
|
|
resourceType: 'operation_run',
|
|
resourceId: (string) $this->operationRun->getKey(),
|
|
);
|
|
}
|
|
}
|