persist match informtion in DB
This commit is contained in:
+1
-1
@@ -288,7 +288,7 @@ Action Cable использует формат JSON-сообщений чере
|
|||||||
|
|
||||||
| Поле | Описание |
|
| Поле | Описание |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `match_id` | Уникальный UUID матча, сгенерированный сервером |
|
| `match_id` | Уникальный UUID матча, сгенерированный сервером (совпадает с `matches.uuid` в БД) |
|
||||||
| `game_token` | Подписанный JWT-токен для авторизации на `game-server` (действителен `MATCHMAKING_TOKEN_TTL` сек) |
|
| `game_token` | Подписанный JWT-токен для авторизации на `game-server` (действителен `MATCHMAKING_TOKEN_TTL` сек) |
|
||||||
| `game_server` | WebSocket URL игрового сервера Go, на который должны подключиться оба игрока |
|
| `game_server` | WebSocket URL игрового сервера Go, на который должны подключиться оба игрока |
|
||||||
| `players` | Массив идентификаторов игроков матча `[player1_id, player2_id]` |
|
| `players` | Массив идентификаторов игроков матча `[player1_id, player2_id]` |
|
||||||
|
|||||||
@@ -253,6 +253,24 @@ class MatchmakingService
|
|||||||
exp: config.token_ttl.seconds.from_now.to_i
|
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 = {
|
payload = {
|
||||||
type: "matched",
|
type: "matched",
|
||||||
match_id: match_id,
|
match_id: match_id,
|
||||||
|
|||||||
@@ -130,6 +130,7 @@ $$| \text{rating}_A - \text{rating}_B | \le \text{tolerance}\big(\min(t_{\text{s
|
|||||||
|
|
||||||
1. **Генерация идентификаторов и токенов в Ruby:**
|
1. **Генерация идентификаторов и токенов в Ruby:**
|
||||||
- Генерируется уникальный UUID матча: `match_id = SecureRandom.uuid`.
|
- Генерируется уникальный 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`:
|
- Генерируется JWT-токен для `game-server`:
|
||||||
```ruby
|
```ruby
|
||||||
JwtService.encode(
|
JwtService.encode(
|
||||||
|
|||||||
@@ -11,7 +11,12 @@ RSpec.describe MatchmakingService do
|
|||||||
# are reset per example, so a global counter is used).
|
# are reset per example, so a global counter is used).
|
||||||
def uid(base)
|
def uid(base)
|
||||||
$matchmaking_spec_uid = ($matchmaking_spec_uid || 0) + 1
|
$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
|
end
|
||||||
|
|
||||||
def broadcasts_for(user_id)
|
def broadcasts_for(user_id)
|
||||||
@@ -71,6 +76,23 @@ RSpec.describe MatchmakingService do
|
|||||||
expect(broadcasts_for(a).size).to eq(1)
|
expect(broadcasts_for(a).size).to eq(1)
|
||||||
expect(described_class.claim(a)).to be_nil
|
expect(described_class.claim(a)).to be_nil
|
||||||
end
|
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
|
end
|
||||||
|
|
||||||
describe ".sweep" do
|
describe ".sweep" do
|
||||||
|
|||||||
Reference in New Issue
Block a user