@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonBudget;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$database = $argv[1] ?? '';
|
||||
$db = DB::connection();
|
||||
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $db->getConfig('host') !== '127.0.0.1') {
|
||||
throw new LogicException('Recovery is restricted to disposable local PostgreSQL QA.');
|
||||
}
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
$f = receiptFixture();
|
||||
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
auth()->guard()->setUser($author);
|
||||
$budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
|
||||
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Synthetic pre-extension budget.']);
|
||||
auth()->guard()->setUser($reviewer);
|
||||
app(CommonBudget::class)->for($reviewer)->approve($budget);
|
||||
auth()->guard()->setUser($author);
|
||||
app(CommonBudget::class)->for($author)->record($f['r']->id, $f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
|
||||
$balanceBefore = app(CommonBudget::class)->for($author)->balance($budget);
|
||||
$columns = [];
|
||||
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
|
||||
$columns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
|
||||
}
|
||||
$fingerprint = static function (Connection $connection, array $definition): array {
|
||||
$result = [];
|
||||
foreach ($definition as $table => $names) {
|
||||
$quoted = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.$table.'") t order by row_to_json(t)::text');
|
||||
$result[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $result;
|
||||
};
|
||||
$before = $fingerprint($db, $columns);
|
||||
$config = $db->getConfig();
|
||||
unset($config['name']);
|
||||
$directory = storage_path('framework/testing/distribution-recovery-'.$database);
|
||||
if (! mkdir($directory, 0700, true) && ! is_dir($directory)) {
|
||||
throw new RuntimeException('Unable to create the synthetic recovery directory.');
|
||||
}
|
||||
$pg = static function (string $binary, array $arguments) use ($config): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
||||
['PGHOST' => $config['host'], 'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password']], timeout: 60);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Synthetic backup/restore failed.');
|
||||
}
|
||||
};
|
||||
$preDump = $directory.'/before.dump';
|
||||
$postDump = $directory.'/after.dump';
|
||||
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
|
||||
budgetDistributionFixtureSchema();
|
||||
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore
|
||||
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
|
||||
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
|
||||
}
|
||||
$prepare = new Process([PHP_BINARY, __DIR__.'/budget-distribution-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
|
||||
$afterColumns = [];
|
||||
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
|
||||
$afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
|
||||
}
|
||||
$after = $fingerprint($db, $afterColumns);
|
||||
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
|
||||
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $restore) || $restore === $database) {
|
||||
throw new LogicException('Invalid isolated restore database.');
|
||||
}
|
||||
config(['database.connections.distribution_restore_admin' => [...$config, 'database' => 'postgres', 'url' => null],
|
||||
'database.connections.distribution_restore' => [...$config, 'database' => $restore, 'url' => null]]);
|
||||
$admin = DB::connection('distribution_restore_admin');
|
||||
$created = false;
|
||||
$default = DB::getDefaultConnection();
|
||||
try {
|
||||
$admin->statement('CREATE DATABASE "'.$restore.'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $postDump]);
|
||||
$restored = DB::connection('distribution_restore');
|
||||
if ($fingerprint($restored, $afterColumns) !== $after) {
|
||||
throw new RuntimeException('Restored distribution history or source data differs.');
|
||||
}
|
||||
DB::setDefaultConnection('distribution_restore');
|
||||
$restoredActor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($restoredActor);
|
||||
$again = app(CommonBudget::class)->for($restoredActor)->amendDistribution($input['origin'], $input['plan'], $input['hash'],
|
||||
'Explicit synthetic amendment preserved in backup.', $input['operation']);
|
||||
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
|
||||
throw new RuntimeException('Recovered command was not replayed without new effects.');
|
||||
}
|
||||
DB::setDefaultConnection($default);
|
||||
DB::purge('distribution_restore');
|
||||
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||
$created = false;
|
||||
$admin->statement('CREATE DATABASE "'.$restore.'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
|
||||
$restored = DB::connection('distribution_restore');
|
||||
if ($fingerprint($restored, $columns) !== $before || $restored->getSchemaBuilder()->hasTable('budget_distributions')
|
||||
|| $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
|
||||
throw new RuntimeException('Pre-extension recovery did not restore the original schema/data.');
|
||||
}
|
||||
DB::setDefaultConnection('distribution_restore');
|
||||
auth()->guard()->setUser(User::query()->findOrFail($author->id));
|
||||
if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) {
|
||||
throw new RuntimeException('Pre-extension recovery changed the native balance.');
|
||||
}
|
||||
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => 4, 'existing_balances_preserved' => true,
|
||||
'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true,
|
||||
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
DB::setDefaultConnection($default);
|
||||
DB::purge('distribution_restore');
|
||||
if ($created) {
|
||||
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||
echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Http\Controllers\QuotationController;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonBudget;
|
||||
use App\Services\PurchaseWorkflow;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$database = $argv[1] ?? '';
|
||||
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('Visual fixture is restricted to disposable PostgreSQL QA.');
|
||||
}
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
$f = receiptFixture();
|
||||
budgetDistributionFixtureSchema();
|
||||
config(['budget-distributions.qa_enabled' => true]);
|
||||
$users = [];
|
||||
foreach (['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin] as $name => $role) {
|
||||
$users[$name] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
|
||||
'name' => 'QA sintética · '.$role->label(), 'email' => 'qa-'.$name.'@sgc.example.invalid', 'purchasing_role' => $role]);
|
||||
}
|
||||
$centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'code' => 'QA-2', 'name' => 'Segundo centro sintético']);
|
||||
foreach ([$f['r']->cost_center_id, $centre->id] as $id) {
|
||||
auth()->guard()->setUser($users['finance']);
|
||||
$budget = app(CommonBudget::class)->for($users['finance'])->create(['cost_center_id' => $id, 'year' => (int) now()->year,
|
||||
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação exclusivamente sintética da revisão visual.']);
|
||||
auth()->guard()->setUser($users['admin']);
|
||||
app(CommonBudget::class)->for($users['admin'])->approve($budget);
|
||||
}
|
||||
$workflow = app(RequisitionWorkflow::class);
|
||||
$requests = [];
|
||||
foreach (['draft', 'award', 'foreign'] as $purpose) {
|
||||
auth()->guard()->setUser($users['owner']);
|
||||
$r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id,
|
||||
'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade exclusivamente sintética para revisão visual '.$purpose,
|
||||
'items' => [['description' => 'Material sintético '.$purpose, 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
|
||||
$rows = array_map(fn ($id) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $r->items()->firstOrFail()->id,
|
||||
'centre_id' => $id, 'subtotal' => '50.00', 'total' => '50.00'], [$f['r']->cost_center_id, $centre->id]);
|
||||
$r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'process_version' => $r->getAttribute('process_version'),
|
||||
'budget_distribution_preparation' => $rows, 'reason' => 'Parcelas explícitas sintéticas para revisão visual.'], $r);
|
||||
$requests[$purpose] = $r;
|
||||
if ($purpose === 'draft') {
|
||||
continue;
|
||||
}
|
||||
$workflow->submit($users['owner'], $r, (string) Str::uuid(), $r->getAttribute('process_version'));
|
||||
while (($r = $r->fresh())->status === 'pending') {
|
||||
$step = $r->steps()->where('decision', 'pending')->orderBy('position')->firstOrFail();
|
||||
$actor = match ($step->role) {
|
||||
'department_head' => $users['head'], 'procurement' => $users['buyer'], 'finance' => $users['finance']
|
||||
};
|
||||
auth()->guard()->setUser($actor);
|
||||
$workflow->decide($actor, $r, 'approved', null, (string) Str::uuid(), $r->getAttribute('process_version'));
|
||||
}
|
||||
if ($purpose === 'foreign') {
|
||||
auth()->guard()->setUser($users['finance']);
|
||||
app(QuotationExchange::class)->record($users['finance'], $r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD',
|
||||
'rate' => '1.0000000000', 'quoted_on' => today()->toDateString(), 'source' => 'Referência exclusivamente sintética, sem cotação de mercado.']);
|
||||
}
|
||||
$quotes = [];
|
||||
for ($index = 0; $index < 3; $index++) {
|
||||
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id)->replicate();
|
||||
$supplier->name = 'Fornecedor sintético '.$purpose.' '.$index;
|
||||
$supplier->nuit = (string) (200000000 + count($requests) * 100 + $index);
|
||||
$supplier->created_by = $users['buyer']->id;
|
||||
$supplier->save();
|
||||
$actor = $users['buyer'];
|
||||
auth()->guard()->setUser($actor);
|
||||
$input = Request::create('/', 'POST', ['supplier_id' => $supplier->id, 'currency' => $purpose === 'foreign' ? 'USD' : 'MZN',
|
||||
'reference' => 'QA-'.$purpose.'-'.$index, 'delivery_days' => 5, 'valid_until' => today()->addMonth()->toDateString(), 'payment_terms' => '30 dias',
|
||||
'no_conflict' => true, 'items' => [['requisition_item_id' => $r->items()->firstOrFail()->id, 'unit_price' => '100.00']]]);
|
||||
$input->setUserResolver(fn () => $actor);
|
||||
app(QuotationController::class)->store($input, $r, $workflow);
|
||||
$quote = Quotation::query()->where('requisition_id', $r->id)->latest('id')->firstOrFail();
|
||||
$quotes[] = $quote;
|
||||
foreach ([$users['buyer'], $users['finance']] as $actor) {
|
||||
auth()->guard()->setUser($actor);
|
||||
$input = Request::create('/', 'POST', ['quality' => '8', 'history' => '5', 'payment' => '8', 'comment' => 'Avaliação exclusivamente sintética.', 'no_conflict' => true]);
|
||||
$input->setUserResolver(fn () => $actor);
|
||||
app(QuotationController::class)->evaluate($input, $quote, $workflow);
|
||||
}
|
||||
}
|
||||
if ($purpose === 'foreign') {
|
||||
auth()->guard()->setUser($users['buyer']);
|
||||
$award = app(PurchaseWorkflow::class)->select($users['buyer'], $r, ['quotation_id' => $quotes[0]->id,
|
||||
'justification' => 'Proposta exclusivamente sintética para revisão visual.', 'delivery_date' => today()->addWeek()->toDateString(),
|
||||
'delivery_location' => 'Armazém sintético', 'budget_distribution_preparation' => $rows, 'reason' => 'Imputação explícita sintética da proposta em MZN.']);
|
||||
foreach ($award->approvals()->orderBy('position')->get() as $step) {
|
||||
$actor = match ($step->role) {
|
||||
'department_head' => $users['head'], 'finance' => $users['finance'], 'procurement' => $users['admin']
|
||||
};
|
||||
auth()->guard()->setUser($actor);
|
||||
app(PurchaseWorkflow::class)->decide($actor, $award, 'approved', null);
|
||||
}
|
||||
auth()->guard()->setUser($users['buyer']);
|
||||
$order = app(PurchaseWorkflow::class)->issue($users['buyer'], $award);
|
||||
}
|
||||
}
|
||||
echo json_encode(['synthetic_only' => true, 'draft' => $requests['draft']->id, 'award' => $requests['award']->id,
|
||||
'foreign_order' => $order->id, 'users' => array_map(fn ($user) => $user->email, $users)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonBudget;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Finance\Budget\BudgetFailure;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->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) || ! method_exists(BudgetControl::class, 'amendDistribution')) {
|
||||
throw new LogicException('Distribution concurrency requires the authorised common source and disposable QA database.');
|
||||
}
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
$f = receiptFixture();
|
||||
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'code' => 'QA-RACE', 'name' => 'Synthetic race centre']);
|
||||
foreach ([$f['r']->cost_center_id, $centre->id] as $id) {
|
||||
auth()->guard()->setUser($actor);
|
||||
$budget = app(CommonBudget::class)->for($actor)->create(['cost_center_id' => $id, 'year' => (int) now()->year,
|
||||
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Synthetic concurrency budget only.']);
|
||||
auth()->guard()->setUser($reviewer);
|
||||
app(CommonBudget::class)->for($reviewer)->approve($budget);
|
||||
}
|
||||
auth()->guard()->setUser($actor);
|
||||
$plan = array_map(fn ($id) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $f['line']->requisition_item_id,
|
||||
'centre_id' => $id, 'subtotal_minor' => 5000, 'total_minor' => 5000], [$f['r']->cost_center_id, $centre->id]);
|
||||
$lines = [$f['line']->requisition_item_id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$engine->recordDistribution($f['r']->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
|
||||
$commit = $engine->recordDistribution($f['r']->id, 'commit', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
|
||||
$plan[0]['subtotal_minor'] = $plan[0]['total_minor'] = 6000;
|
||||
$plan[1]['subtotal_minor'] = $plan[1]['total_minor'] = 4000;
|
||||
echo json_encode(['tenant' => $actor->tenant_id, 'actor' => $actor->id, 'origin' => $f['r']->id, 'source' => $commit['distribution_id'],
|
||||
'hash' => $commit['plan_hash'], 'plan' => $plan, 'operation' => (string) Str::uuid()], 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_distribution_write_'.getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$result = app(CommonBudget::class)->for($actor)->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic Finance amendment under real contention.', $input['operation']);
|
||||
echo json_encode(['status' => 200, 'version' => $result['amendment_version'], 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
|
||||
} catch (BudgetFailure $error) {
|
||||
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') !== 'race') {
|
||||
throw new InvalidArgumentException('Invalid distribution worker mode.');
|
||||
}
|
||||
budgetDistributionFixtureSchema();
|
||||
foreach (['same_operation', 'conflicting_version'] 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 ($index = 0; $index < 2; $index++) {
|
||||
if ($index === 1 && $scenario === 'conflicting_version') {
|
||||
$input['operation'] = (string) Str::uuid();
|
||||
$input['plan'][0]['subtotal_minor'] = $input['plan'][0]['total_minor'] = 5999;
|
||||
$input['plan'][1]['subtotal_minor'] = $input['plan'][1]['total_minor'] = 4001;
|
||||
}
|
||||
$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;
|
||||
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_distribution_write_%' and wait_event_type='Lock'", [$database])->n;
|
||||
if ($blocked >= 2) {
|
||||
break;
|
||||
}
|
||||
usleep(50000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($blocked < 2) {
|
||||
throw new RuntimeException('Real contention was not demonstrated.');
|
||||
}
|
||||
$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);
|
||||
$snapshot = json_decode($db->table('budget_distributions')->where('id', $input['source'])->value('snapshot'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $snapshot['amendment_version'] !== 1
|
||||
|| $db->table('budget_distribution_events')->where('distribution_id', $input['source'])->count() !== 3
|
||||
|| $db->table('budget_distribution_entries')->where('distribution_id', $input['source'])->count() !== 6
|
||||
|| $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.distribution_amended')->count() !== 1) {
|
||||
throw new RuntimeException('Version, effects, replay and unique audit were not demonstrated.');
|
||||
}
|
||||
echo json_encode(['distribution_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses,
|
||||
'one_amendment_version_and_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
foreach ($workers as $worker) {
|
||||
if ($worker->isRunning()) {
|
||||
$worker->stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user