make(Kernel::class)->bootstrap(); if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) { throw new LogicException('Worker de conversão fora de QA.'); } config(['inventory_conversion.qa_enabled' => true]); if (($argv[2] ?? '') === 'prepare') { require __DIR__.'/../Support/ReceiptFixture.php'; $f = receiptFixture(); $f['stock']->update(['unit' => 'un']); $body = receiptPayload($f, '1.000'); $body['items'][0]['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de corrida', 'version' => 'QA-RACE-1']; echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['receiver']->id, 'order' => $f['order']->id, 'body' => $body], JSON_THROW_ON_ERROR); exit; } if (($argv[2] ?? '') === 'write') { $input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR); DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_conversion_write_'.getmypid()]); $actor = User::query()->findOrFail($input['actor']); auth()->guard()->setUser($actor); try { $receipt = app(ReceiptWorkflow::class)->confirm($actor, PurchaseOrder::query()->findOrFail($input['order']), $input['body']); echo json_encode(['status' => 200, 'id' => $receipt->id], JSON_THROW_ON_ERROR); } catch (ValidationException) { echo json_encode(['status' => 422, 'id' => null], JSON_THROW_ON_ERROR); } exit; } if (($argv[2] ?? '') !== 'race') { throw new InvalidArgumentException('Modo de worker inválido.'); } foreach (['same_body', 'conflicting_body'] as $scenario) { $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30); $prepare->mustRun(); $input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR); $workers = []; $db = DB::connection(); $db->beginTransaction(); try { $db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail(); for ($i = 0; $i < 2; $i++) { if ($i === 1 && $scenario === 'conflicting_body') { $input['body']['items'][0]['conversion']['numerator'] = '24'; } $worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30); $workers[] = $worker; $worker->start(); } $deadline = microtime(true) + 10; $blocked = 0; 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_conversion_write_%' and wait_event_type='Lock'", [$database])->n; if ($blocked >= 2) { break; } usleep(50000); } while (microtime(true) < $deadline); if ($blocked < 2) { throw new RuntimeException('Contenção real não demonstrada.'); } $db->commit(); $statuses = []; $ids = []; foreach ($workers as $worker) { $worker->wait(); if (! $worker->isSuccessful()) { throw new RuntimeException($worker->getErrorOutput()); } $result = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR); $statuses[] = $result['status']; if ($result['id'] !== null) { $ids[] = $result['id']; } } sort($statuses); $movements = $db->table('stock_movements')->where('tenant_id', $input['tenant'])->get(); if ($statuses !== ($scenario === 'same_body' ? [200, 200] : [200, 422]) || count(array_unique($ids)) !== 1 || $movements->count() !== 1 || $db->table('goods_receipts')->where('purchase_order_id', $input['order'])->count() !== 1 || $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'receipt.confirmed')->count() !== 1) { throw new RuntimeException('Unicidade da recepção/movimento/auditoria não demonstrada.'); } $movement = $movements->sole(); $basis = json_decode($movement->snapshot, true, 32, JSON_THROW_ON_ERROR)['quantity_conversion']; if ((string) $movement->quantity_milli !== $basis['accepted_stock_milli'] || $basis['accepted_document_milli'] !== '1000') { throw new RuntimeException('Quantidades física/documental divergentes.'); } echo json_encode(['conversion_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'one_receipt_movement_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL; } finally { if ($db->transactionLevel() > 0) { $db->rollBack(); } foreach ($workers as $worker) { if ($worker->isRunning()) { $worker->stop(); } } } }