139 lines
7.5 KiB
PHP
139 lines
7.5 KiB
PHP
<?php
|
|
|
|
use App\Models\AuditLog;
|
|
use App\Models\PurchasePlanMilestone;
|
|
use App\Services\PurchasePlanningWorkflow;
|
|
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/ReceiptFixture.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 (['competing_dates', 'competing_responsibles', 'duplicate_milestone', 'revoked_role'] as $scenario) {
|
|
$f = receiptFixture();
|
|
$actor = $f['issuer'];
|
|
auth()->guard()->setUser($actor);
|
|
$workflow = app(PurchasePlanningWorkflow::class);
|
|
$item = $workflow->create($actor, ['title' => 'Planeamento exclusivamente fictício', 'department_id' => $f['department']->id, 'responsible_id' => $f['receiver']->id, 'nature' => 'goods', 'requisition_id' => $f['r']->id]);
|
|
$target = $item->id;
|
|
if ($scenario === 'competing_dates') {
|
|
$workflow->milestone($actor, $item, 'Marco para datas concorrentes', today()->format('Y-m-d'));
|
|
$milestone = PurchasePlanMilestone::query()->sole();
|
|
$target = $milestone->id;
|
|
}
|
|
$connection = DB::connection();
|
|
$connection->beginTransaction();
|
|
$connection->table('tenants')->where('id', $actor->tenant_id)->lockForUpdate()->first();
|
|
$processes = [];
|
|
foreach (['A', 'B'] as $index => $suffix) {
|
|
$payload = match ($scenario) {
|
|
'competing_dates' => ['action' => 'dates', 'actual_on' => today()->subDays($index)->format('Y-m-d')],
|
|
'competing_responsibles' => ['action' => 'assign', 'responsible_id' => $index === 0 ? $f['otherReceiver']->id : $actor->id],
|
|
default => ['action' => 'milestone'],
|
|
};
|
|
$process = new Process([PHP_BINARY, __DIR__.'/planning-worker.php', $database, (string) $actor->id, (string) $target, $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_planning_A','sgc_planning_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 ($scenario === 'revoked_role') {
|
|
$connection->table('users')->where('id', $actor->id)->update(['purchasing_role' => 'requester']);
|
|
}
|
|
$connection->commit();
|
|
if ($waits !== 2) {
|
|
throw new RuntimeException('Sem sobreposição de bloqueios.');
|
|
}
|
|
$results = [];
|
|
foreach ($processes as $process) {
|
|
$process->wait();
|
|
if (! $process->isSuccessful()) {
|
|
throw new RuntimeException('Falha do worker: '.$process->getErrorOutput());
|
|
}
|
|
$results[] = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
|
|
}
|
|
$statuses = array_column($results, 'status');
|
|
sort($statuses);
|
|
$eventName = match ($scenario) {
|
|
'competing_dates' => 'planning.milestone_updated', 'competing_responsibles' => 'planning.assigned', default => 'planning.milestone_created'
|
|
};
|
|
$count = AuditLog::query()->where('action', $eventName)->count();
|
|
if ($statuses !== ($scenario === 'revoked_role' ? [403, 403] : [200, 422]) || count(array_unique(array_column($results, 'backend_pid'))) !== 2 || $count !== ($scenario === 'revoked_role' ? 0 : 1)) {
|
|
throw new RuntimeException('Resultado concorrente inesperado.');
|
|
}
|
|
if ($scenario === 'competing_dates' && ($milestone->refresh()->version !== 2 || ! in_array($milestone->actual_on, [today()->format('Y-m-d'), today()->subDay()->format('Y-m-d')]))) {
|
|
throw new RuntimeException('Datas ou versão inconsistentes.');
|
|
}
|
|
if ($scenario === 'competing_responsibles' && ($item->refresh()->version !== 2 || ! in_array($item->responsible_id, [$actor->id, $f['otherReceiver']->id]))) {
|
|
throw new RuntimeException('Responsabilidade ou versão inconsistentes.');
|
|
}
|
|
if (in_array($scenario, ['duplicate_milestone', 'revoked_role']) && PurchasePlanMilestone::query()->count() !== ($scenario === 'revoked_role' ? 0 : 1)) {
|
|
throw new RuntimeException('Marco duplicado ou criado após revogação.');
|
|
}
|
|
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'successful_audit_entries' => $count];
|
|
}
|
|
$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/planeamento-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;
|