make(Kernel::class)->bootstrap(); $config = DB::connection('pgsql')->getConfig(); unset($config['name']); if ($config['host'] !== '127.0.0.1') { throw new LogicException('Ensaio permitido apenas no servidor PostgreSQL local.'); } $database = 'compras_receipts_test_'.bin2hex(random_bytes(6)); if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $database === $config['database']) { throw new LogicException('Base descartável inválida.'); } config(['database.connections.quotation_fx_admin' => [...$config, 'database' => 'postgres', 'url' => null]]); $admin = DB::connection('quotation_fx_admin'); $admin->statement('CREATE DATABASE "'.$database.'"'); try { $environment = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_HOST' => $config['host'], 'DB_PORT' => (string) $config['port'], 'DB_DATABASE' => $database, 'DB_USERNAME' => $config['username'], 'DB_PASSWORD' => $config['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'BROADCAST_CONNECTION' => 'null']; $commands = [ // One Pest kernel: a second migrate:fresh would retain PostgreSQL functions // from existing immutable package schemas while dropping their tables. [PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/QuotationExchangeTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php', 'tests/Feature/SupplierDocumentIntegrityTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=foreign|mixed currency|exchange|finance freezes|quotation screen|only current finance|supplier download|supplier upload|supplier document integrity'], [PHP_BINARY, 'tests/Concurrency/quotation-exchange-report-worker.php', $database], ]; if (in_array('--concurrency-only', $argv, true)) { $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate']]; } $bankMode = in_array('--bank-accounts-only', $argv, true); $conversionMode = in_array('--unit-conversion-only', $argv, true); if ($conversionMode) { $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ReceiptQuantityConversionTest.php']]; $commands[] = [PHP_BINARY, 'tests/Concurrency/unit-conversion-worker.php', $database, 'race']; } if ($bankMode && ! in_array('--concurrency-only', $argv, true)) { $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierBankAccountsTest.php', 'tests/Feature/SupplierBankTest.php', 'tests/Feature/ExternalPaymentTest.php', 'tests/Feature/PaymentIntegrationTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php']]; } foreach ($commands as $command) { $process = new Process($command, dirname(__DIR__), $environment, timeout: 180); $process->run(); echo $process->getOutput(); if (! $process->isSuccessful()) { echo $process->getErrorOutput(); throw new RuntimeException('Validação PostgreSQL não aprovada.'); } } if ($conversionMode) { return; } config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]); $proof = DB::connection('quotation_fx_proof'); if ($proof->getDatabaseName() !== $database) { throw new LogicException('Ligação de concorrência não isolada.'); } foreach (['same_operation', $bankMode ? 'different_accounts' : 'different_operation_same_currency'] as $scenario) { $prepare = new Process([PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, $bankMode ? 'bank_prepare' : 'prepare'], dirname(__DIR__), $environment, timeout: 30); $prepare->mustRun(); $ids = json_decode($prepare->getOutput(), true, 16, JSON_THROW_ON_ERROR); $rate = ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60.1234567890', 'quoted_on' => date('Y-m-d'), 'source' => 'Fonte exclusivamente sintética de concorrência']; if ($bankMode) { $rate = [...$ids['bank_data'], 'previous_id' => 0, 'account_key' => (string) Str::uuid(), 'account_identifier' => 'FIRST-SYNTHETIC-ACCOUNT']; } $beforeAudit = $proof->table('audit_logs')->where('tenant_id', $ids['tenant'])->where('action', $bankMode ? 'supplier.bank_proposed' : 'quotation.exchange_rate_recorded')->count(); $workers = []; $proof->beginTransaction(); try { $proof->table('tenants')->where('id', $ids['tenant'])->lockForUpdate()->firstOrFail(); for ($i = 0; $i < 2; $i++) { if ($i === 1 && $scenario !== 'same_operation') { if ($bankMode) { $rate['account_key'] = (string) Str::uuid(); $rate['account_identifier'] = 'OTHER-SYNTHETIC-ACCOUNT'; } else { $rate['operation_id'] = (string) Str::uuid(); $rate['rate'] = '61'; } } $worker = new Process([PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, $bankMode ? 'bank_write' : 'write', json_encode([...$ids, 'rate' => $rate], JSON_THROW_ON_ERROR)], dirname(__DIR__), $environment, timeout: 30); $workers[] = $worker; $worker->start(); } $deadline = microtime(true) + 10; $blocked = 0; do { $proof->select('select pg_stat_clear_snapshot()'); $blocked = (int) $proof->selectOne("select count(*) as n from pg_stat_activity where datname = ? and application_name like ? and wait_event_type = 'Lock'", [$database, $bankMode ? 'sgc_bank_write_%' : 'sgc_fx_write_%'])->n; if ($blocked >= 2) { break; } usleep(20000); } while (microtime(true) < $deadline); if ($blocked < 2) { throw new RuntimeException('Contenção real de dois escritores não demonstrada.'); } $proof->commit(); $statuses = []; $savedIds = []; foreach ($workers as $worker) { $worker->wait(); if (! $worker->isSuccessful()) { throw new RuntimeException('Worker de concorrência não concluído.'); } $result = json_decode($worker->getOutput(), true, 16, JSON_THROW_ON_ERROR); $statuses[] = $result['status']; $savedIds[] = $result['id']; } sort($statuses); if ($bankMode) { $expected = $scenario === 'same_operation' ? 1 : 2; $versions = $proof->table('supplier_bank_details')->where('supplier_id', $ids['supplier'])->pluck('revision')->all(); if ($statuses !== [200, 200] || count(array_unique($savedIds)) !== $expected || count($versions) !== 1 + $expected || count(array_unique($versions)) !== count($versions) || $proof->table('audit_logs')->where('tenant_id', $ids['tenant'])->where('action', 'supplier.bank_proposed')->count() !== $beforeAudit + $expected) { throw new RuntimeException('Identidades, versões ou auditoria de contas independentes não demonstradas.'); } echo json_encode(['bank_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'distinct_new_accounts' => $expected, 'distinct_global_versions' => true], JSON_THROW_ON_ERROR).PHP_EOL; continue; } if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 422]) || $proof->table('quotation_exchange_rates')->where('requisition_id', $ids['request'])->count() !== 1 || $proof->table('audit_logs')->where('tenant_id', $ids['tenant'])->where('action', 'quotation.exchange_rate_recorded')->count() !== 1) { throw new RuntimeException('Unicidade, repetição ou auditoria não demonstradas.'); } echo json_encode(['scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'one_rate_and_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL; } finally { if ($proof->transactionLevel() > 0) { $proof->rollBack(); } foreach ($workers as $worker) { if ($worker->isRunning()) { $worker->stop(); } } } } } finally { $admin->statement('DROP DATABASE "'.$database.'" WITH (FORCE)'); echo json_encode(['database' => $database, 'isolated_database_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL; }