feat: consolidar desenvolvimentos do portal InvestMoz
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use stdClass;
|
||||
|
||||
/** Attempt ownership in the existing audit ledger; callers hold the document row lock. */
|
||||
final class DocumentScanAttempts
|
||||
{
|
||||
private const SOURCE = 'document-malware-worker';
|
||||
|
||||
public function owns(stdClass $document, string $run, int $delivery, ?int $expectedAttempt = null): bool
|
||||
{
|
||||
$attempt = (int) $document->malware_scan_attempts;
|
||||
if ($expectedAttempt !== null && $attempt !== $expectedAttempt) {
|
||||
return false;
|
||||
}
|
||||
$events = DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'document-scan')->where('entity_id', $document->id)
|
||||
->where('action', 'scan_started')->whereRaw("after_data->>'attempt' = ?", [(string) $attempt])->get(['after_data']);
|
||||
if ($events->count() !== 1) {
|
||||
return false;
|
||||
}
|
||||
$lease = json_decode($events->first()->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return is_array($lease) && ($lease['run_id'] ?? null) === $run && ($lease['delivery_attempt'] ?? null) === $delivery && ($lease['attempt'] ?? null) === $attempt;
|
||||
}
|
||||
|
||||
public function start(stdClass $document, string $run, int $delivery): int
|
||||
{
|
||||
$attempt = (int) $document->malware_scan_attempts + 1;
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'entity_type' => 'document-scan', 'entity_id' => $document->id,
|
||||
'actor_user_id' => null, 'action' => 'scan_started', 'correlation_id' => $run, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['run_id' => $run, 'delivery_attempt' => $delivery, 'attempt' => $attempt, 'file_sha256' => trim($document->sha256), 'file_size_bytes' => $document->size_bytes ?? null], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $attempt;
|
||||
}
|
||||
|
||||
/** @return array{sha256:string,size_bytes:int|null}|null */
|
||||
public function descriptor(stdClass $document, string $run, int $delivery): ?array
|
||||
{
|
||||
if (! $this->owns($document, $run, $delivery)) {
|
||||
return null;
|
||||
}
|
||||
$event = DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'document-scan')->where('entity_id', $document->id)
|
||||
->where('action', 'scan_started')->whereRaw("after_data->>'attempt' = ?", [(string) $document->malware_scan_attempts])->first(['after_data']);
|
||||
$data = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR) : null;
|
||||
if (! is_array($data) || ! is_string($data['file_sha256'] ?? null) || preg_match('/^[a-f0-9]{64}$/D', $data['file_sha256']) !== 1
|
||||
|| ! array_key_exists('file_size_bytes', $data) || ($data['file_size_bytes'] !== null && ! is_int($data['file_size_bytes']))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['sha256' => $data['file_sha256'], 'size_bytes' => $data['file_size_bytes']];
|
||||
}
|
||||
|
||||
public function completed(string $documentId, string $run): bool
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'document-scan')->where('entity_id', $documentId)
|
||||
->where('action', 'scan_result_recorded')->where('correlation_id', $run)->whereRaw("after_data->>'retryable_failure' = 'false'")->exists();
|
||||
}
|
||||
|
||||
public function finish(stdClass $document, string $run, int $delivery, string $scanId, bool $retryableFailure): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'entity_type' => 'document-scan', 'entity_id' => $document->id,
|
||||
'actor_user_id' => null, 'action' => 'scan_result_recorded', 'correlation_id' => $run, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['run_id' => $run, 'delivery_attempt' => $delivery, 'attempt' => (int) $document->malware_scan_attempts, 'scan_id' => $scanId, 'retryable_failure' => $retryableFailure], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
public function discarded(stdClass $document, string $run, int $delivery, int $expectedAttempt): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'entity_type' => 'document-scan', 'entity_id' => $document->id,
|
||||
'actor_user_id' => null, 'action' => 'scan_result_discarded', 'correlation_id' => $run, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['run_id' => $run, 'delivery_attempt' => $delivery, 'attempt' => $expectedAttempt, 'current_attempt' => (int) $document->malware_scan_attempts], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use Closure;
|
||||
use Illuminate\Bus\UniqueLock;
|
||||
use Illuminate\Contracts\Cache\Repository;
|
||||
use Illuminate\Foundation\Queue\InteractsWithUniqueJobs;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
|
||||
/** Observe the existing unique-job lease without claiming that a worker ran. */
|
||||
final class DocumentScanDelivery
|
||||
{
|
||||
use InteractsWithUniqueJobs;
|
||||
|
||||
/** @param Closure():bool|null $prepare */
|
||||
public function dispatch(ScanDocumentForMalware $job, ?Closure $prepare = null): string
|
||||
{
|
||||
$lock = new UniqueLock(app(Repository::class));
|
||||
if (! $lock->acquire($job)) {
|
||||
return 'duplicate';
|
||||
}
|
||||
$attempted = false;
|
||||
$contextAdded = false;
|
||||
try {
|
||||
if ($prepare !== null && ! $prepare()) {
|
||||
return 'stale';
|
||||
}
|
||||
$this->addUniqueJobInformationToContext($job);
|
||||
$contextAdded = true;
|
||||
$attempted = true;
|
||||
Bus::dispatch($job);
|
||||
|
||||
return 'accepted';
|
||||
} finally {
|
||||
if ($contextAdded) {
|
||||
$this->removeUniqueJobInformationFromContext($job);
|
||||
}
|
||||
// A push error may follow acceptance. Keep its lease until the worker or expiry.
|
||||
if (! $attempted) {
|
||||
$lock->release($job);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentManagementAccess;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
final class DocumentScanRetry
|
||||
{
|
||||
/** @return array{outcome:string,reference:string} */
|
||||
public function request(User $actor, string $id): array
|
||||
{
|
||||
$job = new ScanDocumentForMalware($id);
|
||||
$outcome = 'deferred';
|
||||
DB::transaction(function () use ($actor, $id, $job, &$outcome): void {
|
||||
$document = app(DocumentManagementAccess::class)->documents($actor)->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
|
||||
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422,
|
||||
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.');
|
||||
|
||||
DB::afterCommit(function () use ($actor, $id, $job, $document, &$outcome): void {
|
||||
$prepared = false;
|
||||
try {
|
||||
$outcome = app(DocumentScanDelivery::class)->dispatch($job, function () use ($actor, $id, $job, $document, &$prepared): bool {
|
||||
$ready = DB::transaction(function () use ($actor, $id, $job, $document): bool {
|
||||
$currentActor = $actor->fresh();
|
||||
if (! $currentActor) {
|
||||
return false;
|
||||
}
|
||||
$access = app(DocumentManagementAccess::class);
|
||||
if (! $access->full($currentActor) && ! $access->limited($currentActor) && ! $access->editorial($currentActor)) {
|
||||
return false;
|
||||
}
|
||||
$current = $access->documents($currentActor)->where('id', $id)->lockForUpdate()->first();
|
||||
if (! $current || $current->status === 'deleted' || $current->deleted_at !== null
|
||||
|| $current->sha256 !== $document->sha256 || $current->malware_scan_attempts !== $document->malware_scan_attempts
|
||||
|| $current->malware_scan_status !== $document->malware_scan_status || $current->updated_at !== $document->updated_at) {
|
||||
return false;
|
||||
}
|
||||
DB::table('documents')->where('id', $id)->update(['status' => 'quarantined', 'malware_scan_status' => 'pending', 'malware_failure_reason' => null, 'updated_at' => now()]);
|
||||
$access->audit($currentActor, 'scan_retry_requested', ['document_id' => $id, 'reference' => $job->runIdentifier(), 'previous_scan_status' => $current->malware_scan_status]);
|
||||
|
||||
return true;
|
||||
});
|
||||
$prepared = $ready;
|
||||
|
||||
return $ready;
|
||||
});
|
||||
} catch (Throwable) {
|
||||
$outcome = 'unconfirmed';
|
||||
try {
|
||||
if ($prepared) {
|
||||
DB::transaction(function () use ($id, $document): void {
|
||||
$current = DB::table('documents')->where('id', $id)->lockForUpdate()->first();
|
||||
if ($current && $current->deleted_at === null && $current->status !== 'deleted'
|
||||
&& $current->sha256 === $document->sha256 && $current->malware_scan_attempts === $document->malware_scan_attempts && $current->malware_scan_status === 'pending') {
|
||||
DB::table('documents')->where('id', $id)->update(['status' => 'quarantined', 'malware_scan_status' => 'failed', 'malware_failure_reason' => 'queue_dispatch_failed', 'updated_at' => now()]);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (Throwable) {
|
||||
// An uncertain write remains private and needs reconciliation.
|
||||
}
|
||||
try {
|
||||
Log::warning('Document scan retry dispatch requires verification.', ['reference' => $job->runIdentifier(), 'error_code' => 'scan_dispatch_unconfirmed']);
|
||||
} catch (Throwable) {
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return ['outcome' => $outcome, 'reference' => $job->runIdentifier()];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user