'testing', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array'] as $key => $value) { putenv($key.'='.$value); $_ENV[$key] = $_SERVER[$key] = $value; } $app = require __DIR__.'/../../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); require __DIR__.'/../Support/QualificationFixture.php'; $original = DB::connection(); if ($original->getDriverName() !== 'pgsql') { throw new LogicException('Exige PostgreSQL.'); } $config = $original->getConfig(); $admin = $original->getPdo(); $database = 'compras_receipts_test_'.bin2hex(random_bytes(6)); $created = false; $lockHeld = false; $process = null; $report = ['tested_at_utc' => gmdate('c'), 'separate_database' => true, 'transport' => 'Independent report reader and concurrent PostgreSQL business connection', 'scenarios' => []]; try { $admin->exec('CREATE DATABASE "'.$database.'"'); $created = true; config(['database.connections.pgsql' => [...$config, 'database' => $database, 'url' => null]]); DB::purge('pgsql'); DB::setDefaultConnection('pgsql'); Schema::clearResolvedInstance('db.schema'); app()->forgetInstance('db.schema'); if (DB::connection()->getDatabaseName() !== $database || Schema::getConnection()->getDatabaseName() !== $database) { throw new LogicException('Migração fora do isolamento recusada.'); } Artisan::call('migrate', ['--database' => 'pgsql', '--force' => true]); $workerEnv = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_DATABASE' => $database, 'DB_HOST' => $config['host'], 'DB_PORT' => (string) $config['port'], 'DB_USERNAME' => $config['username'], 'DB_PASSWORD' => $config['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array']; foreach (['consistent_snapshot', 'revoked_role', 'changed_department'] as $scenario) { $f = qualificationFixture(); $workflow = app(DocumentaryQualificationWorkflow::class); $set = $workflow->define($f['issuer'], $f['r'], $f['definition']); $actor = $f['analyst']; auth()->guard()->setUser($actor); $first = $workflow->assess($actor, $set, $f['assessment']); if ($scenario === 'changed_department') { $actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]); } $lock = random_int(1, 1000000000); DB::select('select pg_advisory_lock(?)', [$lock]); $lockHeld = true; $process = new Process([PHP_BINARY, __DIR__.'/review-report-worker.php', $database, (string) $actor->id, (string) $f['r']->id, (string) $lock, $scenario], base_path(), $workerEnv); $process->setTimeout(40); $process->start(); $statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name = 'sgc_review_report' AND wait_event_type = 'Lock' AND wait_event = 'advisory'"); $deadline = microtime(true) + 20; do { $statement->execute([$database]); $waits = (int) $statement->fetchColumn(); if ($waits === 1) { break; } if (! $process->isRunning()) { throw new RuntimeException('Leitor terminou antes do bloqueio: '.$process->getErrorOutput()); } usleep(20000); } while (microtime(true) < $deadline); if ($waits !== 1) { throw new RuntimeException('Leitura concorrente não demonstrada.'); } if ($scenario === 'consistent_snapshot') { $answers = $f['assessment']['answers']; $answers[0]['result'] = 'not_met'; $workflow->assess($f['analyst'], $set, [...$f['assessment'], 'previous_id' => $first->id, 'answers' => $answers]); $f['quote']->update(['reference' => 'REFERENCIA-CONCORRENTE']); auth()->guard()->setUser($f['issuer']); $opening = app(ProposalOpeningWorkflow::class); $workflow->define($f['issuer'], $f['r'], [...$f['definition'], 'previous_id' => $set->id, 'basis_hash' => $opening->basis($opening->proposals($f['r']))]); } elseif ($scenario === 'revoked_role') { DB::table('users')->where('id', $actor->id)->update(['purchasing_role' => 'requester']); } else { $other = Department::query()->create(['tenant_id' => $f['tenant']->id, 'name' => 'Departamento posterior fictício']); DB::table('users')->where('id', $actor->id)->update(['department_id' => $other->id]); } $audits = AuditLog::query()->count(); DB::select('select pg_advisory_unlock(?)', [$lock]); $lockHeld = false; $process->wait(); if (! $process->isSuccessful()) { throw new RuntimeException('Falha do leitor: '.$process->getErrorOutput()); } $result = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR); if (AuditLog::query()->count() !== $audits) { throw new RuntimeException('O relatório criou eventos de negócio.'); } if ($scenario === 'consistent_snapshot') { $data = $result['report']; if ($result['status'] !== 200 || $result['proof']['isolation'] !== 'repeatable read' || $result['proof']['read_only'] !== 'on' || $data['comparison']['rows'][0]['reference'] !== 'PROP-TEST' || $data['qualification']['revision'] !== 1 || $data['qualification']['proposals'][0]['analyses'][0]['revision'] !== 1 || $data['qualification']['proposals'][0]['analyses'][0]['answers'][0]['result'] !== 'met' || QualificationSet::query()->count() !== 2 || QualificationAssessment::query()->max('revision') !== 2) { throw new RuntimeException('Relatório misturou momentos de consulta.'); } } elseif ($result['status'] !== ($scenario === 'revoked_role' ? 403 : 404) || $result['report'] !== null) { throw new RuntimeException('Acesso revogado expôs o relatório.'); } $report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'observed_advisory_waits' => $waits, 'business_audit_unchanged' => true]; } $report['passed'] = true; } finally { if ($process && $process->isRunning()) { $process->stop(); } if ($lockHeld) { DB::select('select pg_advisory_unlock(?)', [$lock]); } DB::disconnect('pgsql'); if ($created && $database !== $original->getDatabaseName() && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/', $database)) { $admin->exec('DROP DATABASE "'.$database.'"'); $report['test_database_dropped'] = true; } } file_put_contents(base_path('docs/relatorio-concorrencia-postgresql.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL); echo json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;