You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/PaymentFxMysqlConcurrencyTe...

164 lines
8.0 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Payment\PaytaroCredentialCipher;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\PaytaroSigner;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateService;
use App\Services\Payment\YipayCredentialCipher;
use App\Services\Payment\YipayPaymentService;
use App\Services\Payment\YipaySigner;
use Illuminate\Database\Capsule\Manager as Capsule;
$socket = (string) getenv('VIRT_FX_TEST_MYSQL_SOCKET');
if ($socket === '') {
echo "Payment FX MySQL concurrency skipped: isolated socket not configured.\n";
exit(0);
}
$database = (string) getenv('VIRT_FX_TEST_MYSQL_DATABASE');
if (!preg_match('#^/(?:private/)?tmp/virt-fx-mysql\.[A-Za-z0-9]+/fx\.sock$#D', $socket)
|| !in_array($database, ['fx_fresh', 'fx_upgrade'], true)
|| !function_exists('pcntl_fork')) {
throw new RuntimeException('An isolated, freshly initialized MySQL fixture and pcntl are required.');
}
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'mysql', 'unix_socket' => $socket, 'database' => $database, 'username' => 'root',
'password' => '', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'strict' => true,
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$connection = $capsule->getConnection();
if ($connection->table('user')->exists() || $connection->table('cloud_invoices')->exists()) {
throw new RuntimeException('The concurrency fixture must start empty.');
}
$now = time();
$expiry = $now + 3600;
$secret = 'isolated-fx-test-merchant';
$GLOBALS['System_Config'] = ['cloud_data_key' => base64_encode(random_bytes(32))];
$_ENV['PAYTARO_CREDENTIAL_KEY'] = bin2hex(random_bytes(32));
$_ENV['YIPAY_CREDENTIAL_KEY'] = bin2hex(random_bytes(32));
foreach ([
'paytaro_app_id' => 'A1B2C3D4E5F', 'paytaro_app_key' => PaytaroCredentialCipher::encrypt($secret),
'yipay_pid' => '1001', 'yipay_secret_key' => YipayCredentialCipher::encrypt($secret),
] as $name => $value) {
$connection->table('configurations')->updateOrInsert(['name' => $name], ['value' => $value]);
}
$userId = $connection->table('user')->insertGetId([
'user_name' => 'fx-test', 'email' => 'fx-test@example.test', 'pass' => 'test-fixture-only',
'reg_date' => gmdate('Y-m-d H:i:s', $now),
]);
$instanceId = $connection->table('cloud_instances')->insertGetId([
'uuid' => '00000000-0000-4000-8000-000000000001', 'host_id' => 1, 'user_id' => $userId,
'name' => 'fx-test-renewal', 'plan_id' => 1, 'service_status' => 'active', 'expires_at' => $expiry,
'renewal_price' => '72.00', 'renewal_days' => 30, 'spec_json' => '{}', 'created_at' => $now, 'updated_at' => $now,
]);
$periodId = $connection->table('cloud_service_periods')->insertGetId([
'instance_id' => $instanceId, 'user_id' => $userId, 'plan_id' => 1, 'traffic_quota_mode' => 'unlimited',
'starts_at' => $now - 86400, 'ends_at' => $expiry, 'status' => 'active', 'activated_at' => $now - 86400,
'created_at' => $now, 'updated_at' => $now,
]);
$connection->table('cloud_instances')->where('id', $instanceId)->update(['current_period_id' => $periodId]);
$invoiceId = $connection->table('cloud_invoices')->insertGetId([
'invoice_no' => 'FX-CONCURRENT-RENEWAL', 'instance_id' => $instanceId, 'user_id' => $userId, 'plan_id' => 1,
'renews_expires_at' => $expiry, 'due_at' => $expiry, 'amount' => '72.00', 'validity_days' => 30,
'created_at' => $now, 'updated_at' => $now,
]);
$connection->table('cloud_invoice_items')->insert([
'invoice_id' => $invoiceId, 'code' => 'instance', 'label' => 'Renewal',
'amount' => '72.00', 'snapshot_json' => '{}', 'created_at' => $now,
]);
$callbacks = [];
foreach ([
'paytaro' => ['PT', '7.20', '518.40', 'A1B2C3D4E5F', 'fx-test-001'],
'yipay_alipay' => ['YP', '7.30', '525.60', '1001', 'fx-test-002'],
] as $provider => [$prefix, $rate, $charge, $merchant, $trade]) {
PaymentRateService::override('USD/CNY', $rate, $now + 600, 1, 'Isolated checkout acceptance', $now);
$orderNo = $prefix . gmdate('YmdHis', $now) . strtoupper(bin2hex(random_bytes(8)));
$paylist = $connection->table('paylist')->insertGetId([
'userid' => $userId, 'total' => '72.00', 'status' => 0, 'tradeno' => $orderNo, 'datetime' => $now,
]);
$channel = $provider === 'paytaro' ? 'paytaro' : 'yipay';
$connection->table($channel . '_orders')->insert([
'order_no' => $orderNo, 'paylist_id' => $paylist, 'user_id' => $userId, 'amount' => '72.00',
'status' => 'pending', 'created_at' => $now, 'updated_at' => $now,
] + ($channel === 'yipay' ? ['payment_type' => 'alipay'] : []));
$connection->table('cloud_invoice_payments')->insert([
'invoice_id' => $invoiceId, 'user_id' => $userId, 'provider' => $provider, 'provider_order_no' => $orderNo,
'idempotency_key' => 'fx-concurrent-key-' . $provider, 'amount' => '72.00', 'status' => 'pending',
'created_at' => $now, 'updated_at' => $now,
]);
$quote = PaymentCheckoutQuotes::prepare($provider, '72.00', $now, $now + 900);
PaymentCheckoutQuotes::persist($quote, $orderNo, $userId);
$payload = [
'pid' => $merchant, 'trade_no' => $trade, 'out_trade_no' => $orderNo, 'type' => 'alipay',
'money' => $charge, 'trade_status' => 'TRADE_SUCCESS', 'sign_type' => 'MD5',
];
$payload['sign'] = $channel === 'paytaro' ? PaytaroSigner::sign($payload, $secret) : YipaySigner::sign($payload, $secret);
$callbacks[] = [$channel, $payload];
}
PaymentRateService::override('USD/CNY', '7.50', $now + 600, 1, 'Changed after both orders', $now);
$connection->disconnect();
$children = [];
foreach ($callbacks as [$channel, $payload]) {
[$read, $write] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid = pcntl_fork();
if ($pid < 0) {
throw new RuntimeException('Could not fork callback worker.');
}
if ($pid === 0) {
fclose($write);
if (fread($read, 1) !== 'x') {
exit(1);
}
fclose($read);
$service = $channel === 'paytaro' ? new PaytaroPaymentService() : new YipayPaymentService();
$result = $service->processCallback($payload);
$duplicate = $service->processCallback($payload);
if (!$result['credited'] || !$duplicate['duplicate'] || $duplicate['credited']) {
fwrite(STDERR, "$channel callback/replay results: " . json_encode([$result, $duplicate]) . PHP_EOL);
exit(1);
}
exit(0);
}
fclose($read);
$children[$pid] = $write;
}
$connection->beginTransaction();
$connection->table('user')->where('id', $userId)->lockForUpdate()->first();
foreach ($children as $write) {
fwrite($write, 'x');
fclose($write);
}
usleep(150000);
$connection->commit();
$callbackFailed = false;
foreach (array_keys($children) as $pid) {
pcntl_waitpid($pid, $status);
if (!pcntl_wifexited($status) || pcntl_wexitstatus($status) !== 0) {
$callbackFailed = true;
}
}
if ($callbackFailed) {
throw new RuntimeException('A signed callback failed to settle or duplicate credit was posted.');
}
$attempts = $connection->table('cloud_invoice_payments')->where('invoice_id', $invoiceId)->orderBy('status')->pluck('status')->all();
if ($attempts !== ['credited_balance', 'paid_invoice']
|| $connection->table('cloud_invoices')->where('id', $invoiceId)->value('status') !== 'paid'
|| (string) $connection->table('user')->where('id', $userId)->value('money') !== '72.00'
|| $connection->table('cloud_renewals')->where('instance_id', $instanceId)->count() !== 1
|| (int) $connection->table('cloud_instances')->where('id', $instanceId)->value('expires_at') !== $expiry + 30 * 86400
|| $connection->table('cloud_service_periods')->where('instance_id', $instanceId)->count() !== 2
|| $connection->table('payment_checkout_quotes')->where('status', 'accepted')->where('credit_cents', 7200)->count() !== 2) {
throw new RuntimeException('Two independent valid payments did not renew once and preserve the second payment in USD.');
}
echo "Payment FX concurrent renewal and replay passed in MySQL ($database).\n";