make(Kernel::class)->bootstrap(); $database = $argv[1] ?? ''; $mode = $argv[2] ?? ''; $db = DB::connection(); if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database || $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) { throw new LogicException('Expense contention requires disposable local PostgreSQL QA.'); } config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'explicit-expense-qa', 'expense-allocations.qa_enabled' => true]); require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php'; $financial = static function () use ($db): string { $rows = []; foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'stock_movements', 'pa_commands'] as $table) { $rows[$table] = $db->table($table)->orderBy('id')->get()->toJson(); } return hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)); }; if ($mode === 'prepare') { $fixture = expenseAllocationQaFixture(); $f = $fixture['f']; if (($argv[3] ?? '') === 'same_version') { $record = app(ExpenseAllocations::class)->save($f['validator'], $fixture['payment']->id, $fixture['input']); $fixture['input']['version'] = $record->version; $fixture['input']['operation_key'] = (string) Str::uuid(); } echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['validator']->id, 'alternate' => $f['author']->id, 'payment' => $fixture['payment']->id, 'input' => $fixture['input'], 'financial_fingerprint' => $financial(), 'records_before' => $db->table('supply_records')->where('tenant_id', $f['tenant']->id)->where('kind', 'expense_allocation')->count(), 'audits_before' => $db->table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'expense.allocation_recorded')->count()], JSON_THROW_ON_ERROR); exit; } if ($mode === 'write') { $input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR); $db->select('select set_config(?, ?, false)', ['application_name', 'sgc_expense_write_'.getmypid()]); $actor = User::query()->findOrFail($input['actor']); auth()->guard()->setUser($actor); try { app(ExpenseAllocations::class)->save($actor, $input['payment'], $input['input']); echo json_encode(['status' => 200]); } catch (HttpExceptionInterface $error) { echo json_encode(['status' => $error->getStatusCode()]); } exit; } if ($mode !== 'race-expense') { throw new InvalidArgumentException('Unknown expense contention mode.'); } foreach (['same_operation', 'same_version'] as $scenario) { $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30); $prepare->mustRun(); $input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR); $workers = []; $db->beginTransaction(); try { $db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail(); for ($index = 0; $index < 2; $index++) { $payload = $input; if ($scenario === 'same_version' && $index === 1) { $payload['actor'] = $input['alternate']; $payload['input']['operation_key'] = (string) Str::uuid(); } $worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($payload, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30); $workers[] = $worker; $worker->start(); } $deadline = microtime(true) + 10; do { $db->select('select pg_stat_clear_snapshot()'); $blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_expense_write_%' and wait_event_type='Lock'", [$database])->n; if ($blocked >= 2) { break; } usleep(50000); } while (microtime(true) < $deadline); if ($blocked < 2) { throw new RuntimeException('Both Finance writers must demonstrably wait on the company lock.'); } $db->commit(); $statuses = []; foreach ($workers as $worker) { $worker->wait(); if (! $worker->isSuccessful()) { throw new RuntimeException($worker->getErrorOutput()); } $statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status']; } sort($statuses); $records = $db->table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', 'expense_allocation')->count() - $input['records_before']; $audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'expense.allocation_recorded')->count() - $input['audits_before']; if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $financial() !== $input['financial_fingerprint']) { throw new RuntimeException('Expense contention must retain one attribution/audit and unchanged native financial sources.'); } echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked, 'expense_versions_created' => $records, 'audits' => $audits, 'financial_sources_unchanged' => true], JSON_THROW_ON_ERROR).PHP_EOL; } finally { if ($db->transactionLevel() > 0) { $db->rollBack(); } foreach ($workers as $worker) { if ($worker->isRunning()) { $worker->stop(); } } } }