persist match informtion in DB

This commit is contained in:
2026-11-09 22:07:37 +03:00
parent f48094cd55
commit f0616c7c51
4 changed files with 43 additions and 2 deletions
+1 -1
View File
@@ -288,7 +288,7 @@ Action Cable использует формат JSON-сообщений чере
| Поле | Описание |
|------|----------|
| `match_id` | Уникальный UUID матча, сгенерированный сервером |
| `match_id` | Уникальный UUID матча, сгенерированный сервером (совпадает с `matches.uuid` в БД) |
| `game_token` | Подписанный JWT-токен для авторизации на `game-server` (действителен `MATCHMAKING_TOKEN_TTL` сек) |
| `game_server` | WebSocket URL игрового сервера Go, на который должны подключиться оба игрока |
| `players` | Массив идентификаторов игроков матча `[player1_id, player2_id]` |
@@ -253,6 +253,24 @@ class MatchmakingService
exp: config.token_ttl.seconds.from_now.to_i
)
# Persist the match before finalizing in Redis: if the DB write fails,
# the players stay in "pending" and the sweep requeues them, so no
# match is announced without a corresponding DB record.
player1 = User.find(player1_id)
player2 = User.find(player2_id)
Match.create!(
uuid: match_id,
player1: player1,
player2: player2,
status: :ongoing,
game_server: config.game_server_url,
started_at: Time.current,
player1_rating_before: player1.rating,
player2_rating_before: player2.rating,
player1_rating_change: 0,
player2_rating_change: 0
)
payload = {
type: "matched",
match_id: match_id,
+1
View File
@@ -130,6 +130,7 @@ $$| \text{rating}_A - \text{rating}_B | \le \text{tolerance}\big(\min(t_{\text{s
1. **Генерация идентификаторов и токенов в Ruby:**
- Генерируется уникальный UUID матча: `match_id = SecureRandom.uuid`.
- Создаётся запись о матче в БД (`matches`) с `uuid = match_id`, статусом `ongoing`, `game_server`, `started_at` и рейтингами игроков на момент подбора (`player1_rating_before` / `player2_rating_before`, изменения пока `0`). Если запись создать не удаётся, финализация в Redis не выполняется: игроки остаются в `mm:pending` и через `pending_ttl` возвращаются в очередь свипом.
- Генерируется JWT-токен для `game-server`:
```ruby
JwtService.encode(
@@ -11,7 +11,12 @@ RSpec.describe MatchmakingService do
# are reset per example, so a global counter is used).
def uid(base)
$matchmaking_spec_uid = ($matchmaking_spec_uid || 0) + 1
$matchmaking_spec_uid * 1000 + base
# Explicit ids stay unique across examples: Action Cable test-adapter
# broadcasts persist between examples, so reusing ids would make a
# previous example's broadcast leak into the next one.
User.create!(id: 100_000 + $matchmaking_spec_uid,
nickname: "mm_user_#{$matchmaking_spec_uid}",
password: "secret123").id
end
def broadcasts_for(user_id)
@@ -71,6 +76,23 @@ RSpec.describe MatchmakingService do
expect(broadcasts_for(a).size).to eq(1)
expect(described_class.claim(a)).to be_nil
end
it "persists a Match record in the database" do
a, b = uid(1), uid(2)
described_class.enqueue(a, rating: 1000)
described_class.enqueue(b, rating: 1000)
match = Match.find_by!(uuid: broadcast_payloads(a).first[:match_id])
expect([ match.player1_id, match.player2_id ]).to contain_exactly(a, b)
expect(match).to be_ongoing
expect(match.game_server).to eq(described_class.config.game_server_url)
expect(match.started_at).to be_present
expect(match.player1_rating_before).to eq(User.find(a).rating)
expect(match.player2_rating_before).to eq(User.find(b).rating)
expect(match.player1_rating_change).to eq(0)
expect(match.player2_rating_change).to eq(0)
expect(match.finished_at).to be_nil
end
end
describe ".sweep" do