feat: 支持开奖重开与风险池原子扣减,完善投注部分成功流程
This commit is contained in:
@@ -6,6 +6,8 @@ use App\Models\RiskPool;
|
||||
use App\Lottery\ErrorCode;
|
||||
use App\Models\TicketItem;
|
||||
use App\Models\RiskPoolLockLog;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use App\Exceptions\TicketOperationException;
|
||||
|
||||
final class RiskPoolService
|
||||
@@ -47,46 +49,106 @@ final class RiskPoolService
|
||||
*/
|
||||
public function acquire(int $drawId, ?TicketItem $ticketItem, array $locks): int
|
||||
{
|
||||
$total = 0;
|
||||
foreach ($locks as $lock) {
|
||||
$pool = RiskPool::query()
|
||||
->where('draw_id', $drawId)
|
||||
->where('normalized_number', $lock['number_4d'])
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
if ($this->shouldUseRedisAtomicLocks()) {
|
||||
return $this->acquireWithRedisLua($drawId, $ticketItem, $locks);
|
||||
}
|
||||
|
||||
if ($pool === null) {
|
||||
$pool = $this->createPool($drawId, $lock['number_4d']);
|
||||
return $this->acquireWithDatabaseLocks($drawId, $ticketItem, $locks);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{number_4d:string, amount:int}> $locks
|
||||
*/
|
||||
private function acquireWithDatabaseLocks(int $drawId, ?TicketItem $ticketItem, array $locks): int
|
||||
{
|
||||
$acquired = [];
|
||||
$total = 0;
|
||||
|
||||
try {
|
||||
foreach ($locks as $lock) {
|
||||
$pool = RiskPool::query()
|
||||
->where('draw_id', $drawId)
|
||||
->where('normalized_number', $lock['number_4d'])
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
->first();
|
||||
|
||||
if ($pool === null) {
|
||||
$pool = $this->createPool($drawId, $lock['number_4d']);
|
||||
$pool = RiskPool::query()
|
||||
->where('draw_id', $drawId)
|
||||
->where('normalized_number', $lock['number_4d'])
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
}
|
||||
|
||||
$amount = (int) $lock['amount'];
|
||||
if ((int) $pool->remaining_amount < $amount) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
}
|
||||
|
||||
$pool->forceFill([
|
||||
'locked_amount' => (int) $pool->locked_amount + $amount,
|
||||
'remaining_amount' => (int) $pool->remaining_amount - $amount,
|
||||
'sold_out_status' => ((int) $pool->remaining_amount - $amount) <= 0 ? 1 : 0,
|
||||
'version' => (int) $pool->version + 1,
|
||||
])->save();
|
||||
|
||||
RiskPoolLockLog::query()->create([
|
||||
'draw_id' => $drawId,
|
||||
'normalized_number' => $lock['number_4d'],
|
||||
'ticket_item_id' => $ticketItem?->id,
|
||||
'action_type' => 'lock',
|
||||
'amount' => $amount,
|
||||
'source_reason' => 'ticket_place',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
$acquired[] = ['number_4d' => $lock['number_4d'], 'amount' => $amount];
|
||||
$total += $amount;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$this->releaseDatabaseLocks($drawId, $ticketItem, $acquired, 'ticket_failed_line');
|
||||
|
||||
$amount = (int) $lock['amount'];
|
||||
if ((int) $pool->remaining_amount < $amount) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redis Lua 负责额度判断与扣减的原子性;数据库事实表随后同步,失败时释放 Redis 占用。
|
||||
*
|
||||
* @param list<array{number_4d:string, amount:int}> $locks
|
||||
*/
|
||||
private function acquireWithRedisLua(int $drawId, ?TicketItem $ticketItem, array $locks): int
|
||||
{
|
||||
$acquired = [];
|
||||
$total = 0;
|
||||
|
||||
try {
|
||||
foreach ($locks as $lock) {
|
||||
$number4d = $lock['number_4d'];
|
||||
$amount = (int) $lock['amount'];
|
||||
$pool = $this->firstOrMakePool($drawId, $number4d);
|
||||
$key = $this->redisPoolKey($drawId, $number4d);
|
||||
|
||||
Redis::eval($this->initLua(), 1, $key, (int) $pool->total_cap_amount, (int) $pool->locked_amount);
|
||||
|
||||
$result = (int) Redis::eval($this->acquireLua(), 1, $key, $amount);
|
||||
if ($result !== 1) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
}
|
||||
|
||||
$acquired[] = ['number_4d' => $number4d, 'amount' => $amount];
|
||||
$total += $amount;
|
||||
|
||||
$this->syncDatabaseAfterRedisAcquire($drawId, $ticketItem, $number4d, $amount);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$this->releaseRedisLocks($drawId, $acquired);
|
||||
$this->releaseDatabaseLocks($drawId, $ticketItem, $acquired, 'ticket_failed_line');
|
||||
|
||||
$pool->forceFill([
|
||||
'locked_amount' => (int) $pool->locked_amount + $amount,
|
||||
'remaining_amount' => (int) $pool->remaining_amount - $amount,
|
||||
'sold_out_status' => ((int) $pool->remaining_amount - $amount) <= 0 ? 1 : 0,
|
||||
'version' => (int) $pool->version + 1,
|
||||
])->save();
|
||||
|
||||
RiskPoolLockLog::query()->create([
|
||||
'draw_id' => $drawId,
|
||||
'normalized_number' => $lock['number_4d'],
|
||||
'ticket_item_id' => $ticketItem?->id,
|
||||
'action_type' => 'lock',
|
||||
'amount' => $amount,
|
||||
'source_reason' => 'ticket_place',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
$total += $amount;
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $total;
|
||||
@@ -96,6 +158,109 @@ final class RiskPoolService
|
||||
* @param list<array{number_4d:string, amount:int}> $locks
|
||||
*/
|
||||
public function release(int $drawId, ?TicketItem $ticketItem, array $locks): void
|
||||
{
|
||||
if ($this->shouldUseRedisAtomicLocks()) {
|
||||
$this->releaseRedisLocks($drawId, $locks);
|
||||
}
|
||||
|
||||
foreach ($locks as $lock) {
|
||||
$this->releaseDatabaseLocks($drawId, $ticketItem, [$lock], 'ticket_rollback');
|
||||
}
|
||||
}
|
||||
|
||||
private function shouldUseRedisAtomicLocks(): bool
|
||||
{
|
||||
if (App::environment('testing')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) config('lottery.risk_pool.use_redis_lua', true);
|
||||
}
|
||||
|
||||
private function redisPoolKey(int $drawId, string $number4d): string
|
||||
{
|
||||
return "risk_pool:draw:{$drawId}:number:{$number4d}";
|
||||
}
|
||||
|
||||
private function initLua(): string
|
||||
{
|
||||
return <<<'LUA'
|
||||
if redis.call('EXISTS', KEYS[1]) == 0 then
|
||||
redis.call('HMSET', KEYS[1], 'total', ARGV[1], 'locked', ARGV[2], 'remaining', ARGV[1] - ARGV[2])
|
||||
end
|
||||
return 1
|
||||
LUA;
|
||||
}
|
||||
|
||||
private function acquireLua(): string
|
||||
{
|
||||
return <<<'LUA'
|
||||
local amount = tonumber(ARGV[1])
|
||||
local remaining = tonumber(redis.call('HGET', KEYS[1], 'remaining') or '0')
|
||||
if remaining < amount then
|
||||
return 0
|
||||
end
|
||||
redis.call('HINCRBY', KEYS[1], 'locked', amount)
|
||||
redis.call('HINCRBY', KEYS[1], 'remaining', -amount)
|
||||
return 1
|
||||
LUA;
|
||||
}
|
||||
|
||||
private function releaseLua(): string
|
||||
{
|
||||
return <<<'LUA'
|
||||
local amount = tonumber(ARGV[1])
|
||||
local locked = tonumber(redis.call('HGET', KEYS[1], 'locked') or '0')
|
||||
local releaseAmount = amount
|
||||
if locked < releaseAmount then
|
||||
releaseAmount = locked
|
||||
end
|
||||
redis.call('HINCRBY', KEYS[1], 'locked', -releaseAmount)
|
||||
redis.call('HINCRBY', KEYS[1], 'remaining', releaseAmount)
|
||||
return releaseAmount
|
||||
LUA;
|
||||
}
|
||||
|
||||
private function syncDatabaseAfterRedisAcquire(int $drawId, ?TicketItem $ticketItem, string $number4d, int $amount): void
|
||||
{
|
||||
$pool = RiskPool::query()
|
||||
->where('draw_id', $drawId)
|
||||
->where('normalized_number', $number4d)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$pool->forceFill([
|
||||
'locked_amount' => (int) $pool->locked_amount + $amount,
|
||||
'remaining_amount' => (int) $pool->remaining_amount - $amount,
|
||||
'sold_out_status' => ((int) $pool->remaining_amount - $amount) <= 0 ? 1 : 0,
|
||||
'version' => (int) $pool->version + 1,
|
||||
])->save();
|
||||
|
||||
RiskPoolLockLog::query()->create([
|
||||
'draw_id' => $drawId,
|
||||
'normalized_number' => $number4d,
|
||||
'ticket_item_id' => $ticketItem?->id,
|
||||
'action_type' => 'lock',
|
||||
'amount' => $amount,
|
||||
'source_reason' => 'ticket_place',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{number_4d:string, amount:int}> $locks
|
||||
*/
|
||||
private function releaseRedisLocks(int $drawId, array $locks): void
|
||||
{
|
||||
foreach ($locks as $lock) {
|
||||
Redis::eval($this->releaseLua(), 1, $this->redisPoolKey($drawId, $lock['number_4d']), (int) $lock['amount']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{number_4d:string, amount:int}> $locks
|
||||
*/
|
||||
private function releaseDatabaseLocks(int $drawId, ?TicketItem $ticketItem, array $locks, string $sourceReason): void
|
||||
{
|
||||
foreach ($locks as $lock) {
|
||||
$pool = RiskPool::query()
|
||||
@@ -122,7 +287,7 @@ final class RiskPoolService
|
||||
'ticket_item_id' => $ticketItem?->id,
|
||||
'action_type' => 'release',
|
||||
'amount' => $amount,
|
||||
'source_reason' => 'ticket_rollback',
|
||||
'source_reason' => $sourceReason,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user