179 lines
6.0 KiB
PHP
179 lines
6.0 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Models\BulkOperationRun;
|
|
use App\Models\PolicyVersion;
|
|
use App\Services\BulkOperationService;
|
|
use Filament\Notifications\Notification;
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Queue\SerializesModels;
|
|
use Throwable;
|
|
|
|
class BulkPolicyVersionPruneJob implements ShouldQueue
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
|
public function __construct(
|
|
public int $bulkRunId,
|
|
public int $retentionDays = 90,
|
|
) {}
|
|
|
|
public function handle(BulkOperationService $service): void
|
|
{
|
|
$run = BulkOperationRun::with('user')->find($this->bulkRunId);
|
|
|
|
if (! $run || $run->status !== 'pending') {
|
|
return;
|
|
}
|
|
|
|
$service->start($run);
|
|
|
|
$itemCount = 0;
|
|
$succeeded = 0;
|
|
$failed = 0;
|
|
$skipped = 0;
|
|
$skipReasons = [];
|
|
|
|
$chunkSize = 10;
|
|
$totalItems = $run->total_items ?: count($run->item_ids ?? []);
|
|
$failureThreshold = (int) floor($totalItems / 2);
|
|
|
|
foreach (($run->item_ids ?? []) as $versionId) {
|
|
$itemCount++;
|
|
|
|
try {
|
|
/** @var PolicyVersion|null $version */
|
|
$version = PolicyVersion::withTrashed()
|
|
->where('tenant_id', $run->tenant_id)
|
|
->whereKey($versionId)
|
|
->first();
|
|
|
|
if (! $version) {
|
|
$service->recordFailure($run, (string) $versionId, 'Policy version not found');
|
|
$failed++;
|
|
|
|
if ($failed > $failureThreshold) {
|
|
$service->abort($run, 'Circuit breaker: more than 50% of items failed.');
|
|
|
|
if ($run->user) {
|
|
Notification::make()
|
|
->title('Bulk Prune Aborted')
|
|
->body('Circuit breaker triggered: too many failures (>50%).')
|
|
->icon('heroicon-o-exclamation-triangle')
|
|
->danger()
|
|
->sendToDatabase($run->user)
|
|
->send();
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($version->trashed()) {
|
|
$service->recordSkippedWithReason($run, (string) $version->id, 'Already archived');
|
|
$skipped++;
|
|
$skipReasons['Already archived'] = ($skipReasons['Already archived'] ?? 0) + 1;
|
|
|
|
continue;
|
|
}
|
|
|
|
$eligible = PolicyVersion::query()
|
|
->where('tenant_id', $run->tenant_id)
|
|
->whereKey($version->id)
|
|
->pruneEligible($this->retentionDays)
|
|
->exists();
|
|
|
|
if (! $eligible) {
|
|
$capturedAt = $version->captured_at;
|
|
$isTooRecent = $capturedAt && $capturedAt->gte(now()->subDays($this->retentionDays));
|
|
|
|
$latestVersionNumber = PolicyVersion::query()
|
|
->where('tenant_id', $run->tenant_id)
|
|
->where('policy_id', $version->policy_id)
|
|
->whereNull('deleted_at')
|
|
->max('version_number');
|
|
|
|
$isCurrent = $latestVersionNumber !== null && (int) $version->version_number === (int) $latestVersionNumber;
|
|
|
|
$reason = $isCurrent
|
|
? 'Current version'
|
|
: ($isTooRecent ? 'Too recent' : 'Not eligible');
|
|
|
|
$service->recordSkippedWithReason($run, (string) $version->id, $reason);
|
|
$skipped++;
|
|
$skipReasons[$reason] = ($skipReasons[$reason] ?? 0) + 1;
|
|
|
|
continue;
|
|
}
|
|
|
|
$version->delete();
|
|
$service->recordSuccess($run);
|
|
$succeeded++;
|
|
} catch (Throwable $e) {
|
|
$service->recordFailure($run, (string) $versionId, $e->getMessage());
|
|
$failed++;
|
|
|
|
if ($failed > $failureThreshold) {
|
|
$service->abort($run, 'Circuit breaker: more than 50% of items failed.');
|
|
|
|
if ($run->user) {
|
|
Notification::make()
|
|
->title('Bulk Prune Aborted')
|
|
->body('Circuit breaker triggered: too many failures (>50%).')
|
|
->icon('heroicon-o-exclamation-triangle')
|
|
->danger()
|
|
->sendToDatabase($run->user)
|
|
->send();
|
|
}
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
if ($itemCount % $chunkSize === 0) {
|
|
$run->refresh();
|
|
}
|
|
}
|
|
|
|
$service->complete($run);
|
|
|
|
if ($run->user) {
|
|
$message = "Pruned {$succeeded} policy versions";
|
|
if ($skipped > 0) {
|
|
$message .= " ({$skipped} skipped)";
|
|
}
|
|
if ($failed > 0) {
|
|
$message .= " ({$failed} failed)";
|
|
}
|
|
|
|
if (! empty($skipReasons)) {
|
|
$summary = collect($skipReasons)
|
|
->sortDesc()
|
|
->map(fn (int $count, string $reason) => "{$reason} ({$count})")
|
|
->take(3)
|
|
->implode(', ');
|
|
|
|
if ($summary !== '') {
|
|
$message .= " Skip reasons: {$summary}.";
|
|
}
|
|
}
|
|
|
|
$message .= '.';
|
|
|
|
Notification::make()
|
|
->title('Bulk Prune Completed')
|
|
->body($message)
|
|
->icon('heroicon-o-check-circle')
|
|
->success()
|
|
->sendToDatabase($run->user)
|
|
->send();
|
|
}
|
|
}
|
|
}
|