162 lines
9.3 KiB
PHP
162 lines
9.3 KiB
PHP
<?php
|
|
|
|
use App\Models\AuditLog;
|
|
use App\Models\PurchaseAward;
|
|
use App\Models\RecommendationAttempt;
|
|
use App\Models\RecommendationReview;
|
|
use App\Services\FormalRecommendation;
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
require __DIR__.'/../../vendor/autoload.php';
|
|
foreach (['APP_ENV' => '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/RecommendationFixture.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;
|
|
$processes = [];
|
|
$report = ['tested_at_utc' => gmdate('c'), 'separate_database' => true, 'transport' => 'Independent PHP service transactions and PostgreSQL connections', '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 (['same_person', 'distinct_people', 'opposing_reviews', 'revoked_role', 'changed_basis', 'new_adoption', 'competing_attempts', 'recommendation_versus_award'] as $scenario) {
|
|
$f = recommendationFixture(2);
|
|
$workflow = app(FormalRecommendation::class);
|
|
$decision = $workflow->propose($f['buyer'], $f['r'], $f['proposal']);
|
|
if ($scenario === 'recommendation_versus_award') {
|
|
foreach ([$f['reviewer'], $f['other_reviewer']] as $reviewer) {
|
|
auth()->guard()->setUser($reviewer);
|
|
$workflow->review($reviewer, $decision, 'approved', 'Confirmação fictícia antes da corrida');
|
|
}
|
|
auth()->guard()->setUser($f['buyer']);
|
|
}
|
|
$beforeReviews = RecommendationReview::query()->count();
|
|
$connection = DB::connection();
|
|
$connection->beginTransaction();
|
|
$connection->table('tenants')->where('id', $f['tenant']->id)->lockForUpdate()->first();
|
|
$processes = [];
|
|
foreach (['A', 'B'] as $index => $suffix) {
|
|
$actor = $scenario === 'distinct_people' && $index === 1 ? $f['other_reviewer'] : $f['reviewer'];
|
|
$verdict = $scenario === 'opposing_reviews' && $index === 1 ? 'returned' : 'approved';
|
|
$payload = ['action' => 'review', 'verdict' => $verdict];
|
|
if (in_array($scenario, ['competing_attempts', 'recommendation_versus_award'], true)) {
|
|
$actor = $f['buyer'];
|
|
$award = $scenario === 'recommendation_versus_award' && $index === 1;
|
|
$payload = ['action' => $award ? 'award' : 'propose', 'requisition_id' => $f['r']->id, 'data' => $award ? $f['selection'] : [...$f['proposal'], 'previous_id' => $decision->id]];
|
|
}
|
|
$process = new Process([PHP_BINARY, __DIR__.'/recommendation-worker.php', $database, (string) $actor->id, (string) $decision->id, $suffix], base_path(), $workerEnv);
|
|
$process->setInput(json_encode($payload, JSON_THROW_ON_ERROR));
|
|
$process->setTimeout(40);
|
|
$process->start();
|
|
$processes[] = $process;
|
|
}
|
|
$statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name IN ('sgc_recommendation_A','sgc_recommendation_B') AND wait_event_type = 'Lock'");
|
|
$deadline = microtime(true) + 20;
|
|
do {
|
|
$statement->execute([$database]);
|
|
$waits = (int) $statement->fetchColumn();
|
|
if ($waits === 2) {
|
|
break;
|
|
}
|
|
foreach ($processes as $process) {
|
|
if (! $process->isRunning()) {
|
|
throw new RuntimeException('Worker terminou antes do bloqueio: '.$process->getErrorOutput());
|
|
}
|
|
}
|
|
usleep(20000);
|
|
} while (microtime(true) < $deadline);
|
|
if ($waits !== 2) {
|
|
throw new RuntimeException('Sem sobreposição dos dois bloqueios.');
|
|
}
|
|
if ($scenario === 'revoked_role') {
|
|
$connection->table('users')->where('id', $f['reviewer']->id)->update(['purchasing_role' => 'requester']);
|
|
}
|
|
if ($scenario === 'changed_basis') {
|
|
$connection->table('proposal_evaluations')->where('quotation_id', $f['quote']->id)->update(['comment' => 'Alteração fictícia durante a espera']);
|
|
}
|
|
if ($scenario === 'new_adoption') {
|
|
auth()->guard()->setUser($f['admin']);
|
|
$policy = $workflow->policy($f['admin'], [...$f['policy_data'], 'previous_id' => $f['policy']->id]);
|
|
auth()->guard()->setUser($f['buyer']);
|
|
$workflow->adopt($f['buyer'], $f['r'], $policy->id, $f['adoption']->id, 'Nova adopção enquanto os conferentes aguardam');
|
|
}
|
|
$connection->commit();
|
|
$results = [];
|
|
foreach ($processes as $process) {
|
|
$process->wait();
|
|
if (! $process->isSuccessful()) {
|
|
throw new RuntimeException('Worker falhou: '.$process->getErrorOutput());
|
|
}
|
|
$results[] = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
|
|
}
|
|
$statuses = array_column($results, 'status');
|
|
sort($statuses);
|
|
$expected = match ($scenario) {
|
|
'revoked_role' => [403, 403], 'changed_basis', 'new_adoption' => [422, 422], 'opposing_reviews', 'competing_attempts', 'recommendation_versus_award' => [200, 422], default => [200, 200]
|
|
};
|
|
auth()->guard()->setUser($f['buyer']);
|
|
$reviews = RecommendationReview::query()->count();
|
|
$expectedReviews = match ($scenario) {
|
|
'distinct_people' => 2, 'same_person', 'opposing_reviews' => 1, default => 0
|
|
};
|
|
$expectedReviews += $beforeReviews;
|
|
if ($statuses !== $expected || $reviews !== $expectedReviews || AuditLog::query()->where('action', 'recommendation.reviewed')->count() !== $reviews || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
|
|
throw new RuntimeException('Resultado concorrente inconsistente: '.json_encode([$scenario, $statuses, $reviews], JSON_THROW_ON_ERROR));
|
|
}
|
|
$state = $workflow->status($decision, $f['adoption']);
|
|
$attempts = RecommendationAttempt::query()->count();
|
|
$awards = PurchaseAward::query()->count();
|
|
$newAttempt = $scenario === 'competing_attempts' || ($scenario === 'recommendation_versus_award' && $results[0]['status'] === 200);
|
|
if (($scenario === 'distinct_people' && $state !== 'confirmed') || ($scenario === 'same_person' && $state !== 'pending') || $attempts !== ($newAttempt ? 2 : 1) || $awards !== ($scenario === 'recommendation_versus_award' && ! $newAttempt ? 1 : 0)) {
|
|
throw new RuntimeException('Quórum ou tentativa alterados indevidamente.');
|
|
}
|
|
if ($awards && PurchaseAward::query()->sole()->recommendation_snapshot['attempt_id'] !== $decision->id) {
|
|
throw new RuntimeException('Adjudicação ligada à tentativa errada.');
|
|
}
|
|
if (AuditLog::query()->where('action', 'recommendation.proposed')->count() !== $attempts || AuditLog::query()->where('action', 'award.created')->count() !== $awards) {
|
|
throw new RuntimeException('Auditoria de tentativa/adjudicação inconsistente.');
|
|
}
|
|
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'reviews' => $reviews, 'state' => $state, 'attempts' => $attempts, 'awards' => $awards];
|
|
}
|
|
$report['passed'] = true;
|
|
} finally {
|
|
foreach ($processes as $process) {
|
|
if ($process->isRunning()) {
|
|
$process->stop();
|
|
}
|
|
}
|
|
if (isset($connection) && $connection->transactionLevel() > 0) {
|
|
$connection->rollBack();
|
|
}
|
|
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/recomendacao-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;
|