add additional database table connecting game matches to participating players
This commit is contained in:
@@ -2,6 +2,9 @@ class Match < ApplicationRecord
|
|||||||
belongs_to :player1, class_name: "User"
|
belongs_to :player1, class_name: "User"
|
||||||
belongs_to :player2, class_name: "User"
|
belongs_to :player2, class_name: "User"
|
||||||
|
|
||||||
|
has_many :match_players, foreign_key: :match_uuid, primary_key: :uuid, dependent: :destroy, inverse_of: :match
|
||||||
|
has_many :players, through: :match_players, source: :player
|
||||||
|
|
||||||
enum :status, {
|
enum :status, {
|
||||||
ongoing: 0,
|
ongoing: 0,
|
||||||
player1_won: 1,
|
player1_won: 1,
|
||||||
@@ -11,6 +14,7 @@ class Match < ApplicationRecord
|
|||||||
}
|
}
|
||||||
|
|
||||||
before_validation :assign_uuid, on: :create
|
before_validation :assign_uuid, on: :create
|
||||||
|
after_create :create_match_players!
|
||||||
|
|
||||||
validates :uuid, presence: true, uniqueness: true
|
validates :uuid, presence: true, uniqueness: true
|
||||||
validates :status, presence: true
|
validates :status, presence: true
|
||||||
@@ -40,4 +44,9 @@ class Match < ApplicationRecord
|
|||||||
errors.add(:player2, "must differ from player1")
|
errors.add(:player2, "must differ from player1")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def create_match_players!
|
||||||
|
match_players.create!(player: player1)
|
||||||
|
match_players.create!(player: player2)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
class MatchPlayer < ApplicationRecord
|
||||||
|
belongs_to :match, foreign_key: :match_uuid, primary_key: :uuid, inverse_of: :match_players
|
||||||
|
belongs_to :player, class_name: "User", foreign_key: :player_id, inverse_of: :match_players
|
||||||
|
|
||||||
|
validates :match_uuid, presence: true
|
||||||
|
validates :player_id, presence: true
|
||||||
|
validates :player_id, uniqueness: { scope: :match_uuid }
|
||||||
|
end
|
||||||
@@ -4,6 +4,8 @@ class User < ApplicationRecord
|
|||||||
has_many :sessions, dependent: :destroy
|
has_many :sessions, dependent: :destroy
|
||||||
has_many :matches_as_player1, class_name: "Match", foreign_key: :player1_id, dependent: :restrict_with_exception, inverse_of: :player1
|
has_many :matches_as_player1, class_name: "Match", foreign_key: :player1_id, dependent: :restrict_with_exception, inverse_of: :player1
|
||||||
has_many :matches_as_player2, class_name: "Match", foreign_key: :player2_id, dependent: :restrict_with_exception, inverse_of: :player2
|
has_many :matches_as_player2, class_name: "Match", foreign_key: :player2_id, dependent: :restrict_with_exception, inverse_of: :player2
|
||||||
|
has_many :match_players, foreign_key: :player_id, dependent: :destroy, inverse_of: :player
|
||||||
|
has_many :matches, through: :match_players, source: :match
|
||||||
has_one_attached :avatar
|
has_one_attached :avatar
|
||||||
|
|
||||||
normalizes :nickname, with: ->(n) { n.strip }
|
normalizes :nickname, with: ->(n) { n.strip }
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
class CreateMatchPlayers < ActiveRecord::Migration[8.1]
|
||||||
|
def change
|
||||||
|
create_table :match_players do |t|
|
||||||
|
t.string :match_uuid, null: false
|
||||||
|
t.references :player, null: false, foreign_key: { to_table: :users }
|
||||||
|
end
|
||||||
|
|
||||||
|
add_foreign_key :match_players, :matches, column: :match_uuid, primary_key: :uuid
|
||||||
|
add_index :match_players, :match_uuid
|
||||||
|
add_index :match_players, [ :match_uuid, :player_id ], unique: true
|
||||||
|
|
||||||
|
reversible do |dir|
|
||||||
|
dir.up do
|
||||||
|
execute <<~SQL
|
||||||
|
INSERT INTO match_players (match_uuid, player_id)
|
||||||
|
SELECT uuid, player1_id FROM matches
|
||||||
|
UNION ALL
|
||||||
|
SELECT uuid, player2_id FROM matches
|
||||||
|
SQL
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# It's strongly recommended that you check this file into your version control system.
|
# It's strongly recommended that you check this file into your version control system.
|
||||||
|
|
||||||
ActiveRecord::Schema[8.1].define(version: 2026_11_03_000000) do
|
ActiveRecord::Schema[8.1].define(version: 2026_11_09_215241) do
|
||||||
create_table "active_storage_attachments", force: :cascade do |t|
|
create_table "active_storage_attachments", force: :cascade do |t|
|
||||||
t.bigint "blob_id", null: false
|
t.bigint "blob_id", null: false
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
@@ -39,6 +39,14 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_03_000000) do
|
|||||||
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
|
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
|
||||||
end
|
end
|
||||||
|
|
||||||
|
create_table "match_players", force: :cascade do |t|
|
||||||
|
t.string "match_uuid", null: false
|
||||||
|
t.integer "player_id", null: false
|
||||||
|
t.index ["match_uuid", "player_id"], name: "index_match_players_on_match_uuid_and_player_id", unique: true
|
||||||
|
t.index ["match_uuid"], name: "index_match_players_on_match_uuid"
|
||||||
|
t.index ["player_id"], name: "index_match_players_on_player_id"
|
||||||
|
end
|
||||||
|
|
||||||
create_table "matches", force: :cascade do |t|
|
create_table "matches", force: :cascade do |t|
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.integer "duration_seconds"
|
t.integer "duration_seconds"
|
||||||
@@ -81,6 +89,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_03_000000) do
|
|||||||
|
|
||||||
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
||||||
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
|
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
|
||||||
|
add_foreign_key "match_players", "matches", column: "match_uuid", primary_key: "uuid"
|
||||||
|
add_foreign_key "match_players", "users", column: "player_id"
|
||||||
add_foreign_key "matches", "users", column: "player1_id"
|
add_foreign_key "matches", "users", column: "player1_id"
|
||||||
add_foreign_key "matches", "users", column: "player2_id"
|
add_foreign_key "matches", "users", column: "player2_id"
|
||||||
add_foreign_key "sessions", "users"
|
add_foreign_key "sessions", "users"
|
||||||
|
|||||||
@@ -63,7 +63,8 @@ app/
|
|||||||
├── models/
|
├── models/
|
||||||
│ ├── application_record.rb # Базовый класс моделей
|
│ ├── application_record.rb # Базовый класс моделей
|
||||||
│ ├── user.rb # Модель игрока (никнейм, пароль, рейтинг, аватар)
|
│ ├── user.rb # Модель игрока (никнейм, пароль, рейтинг, аватар)
|
||||||
│ └── match.rb # Матч: участники, статус, длительность, дельты рейтинга
|
│ ├── match.rb # Матч: участники, статус, длительность, дельты рейтинга
|
||||||
|
│ └── match_player.rb # Связь матча и игрока (match_uuid, player_id)
|
||||||
├── serializers/
|
├── serializers/
|
||||||
│ └── match_serializer.rb # Общий JSON-формат матча для API и внутреннего endpoint
|
│ └── match_serializer.rb # Общий JSON-формат матча для API и внутреннего endpoint
|
||||||
└── services/
|
└── services/
|
||||||
|
|||||||
@@ -130,7 +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` возвращаются в очередь свипом.
|
- Создаётся запись о матче в БД (`matches`) с `uuid = match_id`, статусом `ongoing`, `game_server`, `started_at` и рейтингами игроков на момент подбора (`player1_rating_before` / `player2_rating_before`, изменения пока `0`). В той же транзакции для обоих игроков создаются записи в таблице связи `match_players` (`match_uuid`, `player_id`). Если запись создать не удаётся, финализация в Redis не выполняется: игроки остаются в `mm:pending` и через `pending_ttl` возвращаются в очередь свипом.
|
||||||
- Генерируется JWT-токен для `game-server`:
|
- Генерируется JWT-токен для `game-server`:
|
||||||
```ruby
|
```ruby
|
||||||
JwtService.encode(
|
JwtService.encode(
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
require "rails_helper"
|
||||||
|
|
||||||
|
RSpec.describe MatchPlayer, type: :model do
|
||||||
|
let(:player1) { User.create!(nickname: "player_one", password: "secret123") }
|
||||||
|
let(:player2) { User.create!(nickname: "player_two", password: "secret123") }
|
||||||
|
let(:other_player) { User.create!(nickname: "player_three", password: "secret123") }
|
||||||
|
|
||||||
|
let(:match) do
|
||||||
|
Match.create!(
|
||||||
|
player1: player1,
|
||||||
|
player2: player2,
|
||||||
|
status: :ongoing,
|
||||||
|
game_server: "ws://game-server:8080/ws",
|
||||||
|
started_at: Time.current,
|
||||||
|
player1_rating_before: 100,
|
||||||
|
player2_rating_before: 100,
|
||||||
|
player1_rating_change: 0,
|
||||||
|
player2_rating_change: 0
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "belongs to a match by uuid and a player by id" do
|
||||||
|
match_player = match.match_players.find_by(player: player1)
|
||||||
|
expect(match_player.match).to eq(match)
|
||||||
|
expect(match_player.player).to eq(player1)
|
||||||
|
expect(match_player.match_uuid).to eq(match.uuid)
|
||||||
|
expect(match_player.player_id).to eq(player1.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "validates uniqueness of player_id scoped to match_uuid" do
|
||||||
|
duplicate = MatchPlayer.new(match_uuid: match.uuid, player_id: player1.id)
|
||||||
|
expect(duplicate).not_to be_valid
|
||||||
|
expect(duplicate.errors[:player_id]).to be_present
|
||||||
|
end
|
||||||
|
|
||||||
|
it "requires match_uuid and player_id" do
|
||||||
|
expect(MatchPlayer.new(match_uuid: nil, player_id: player1.id)).not_to be_valid
|
||||||
|
expect(MatchPlayer.new(match_uuid: match.uuid, player_id: nil)).not_to be_valid
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -33,6 +33,12 @@ RSpec.describe Match, type: :model do
|
|||||||
expect(match.player2).to eq(player2)
|
expect(match.player2).to eq(player2)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it "automatically creates match_player records on creation" do
|
||||||
|
match = Match.create!(valid_attributes)
|
||||||
|
expect(match.match_players.pluck(:player_id)).to contain_exactly(player1.id, player2.id)
|
||||||
|
expect(match.players).to contain_exactly(player1, player2)
|
||||||
|
end
|
||||||
|
|
||||||
it "does not allow the same player on both sides" do
|
it "does not allow the same player on both sides" do
|
||||||
match = Match.new(valid_attributes.merge(player2: player1))
|
match = Match.new(valid_attributes.merge(player2: player1))
|
||||||
expect(match).not_to be_valid
|
expect(match).not_to be_valid
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ RSpec.describe MatchmakingService do
|
|||||||
expect(match.player1_rating_change).to eq(0)
|
expect(match.player1_rating_change).to eq(0)
|
||||||
expect(match.player2_rating_change).to eq(0)
|
expect(match.player2_rating_change).to eq(0)
|
||||||
expect(match.finished_at).to be_nil
|
expect(match.finished_at).to be_nil
|
||||||
|
expect(match.match_players.pluck(:player_id)).to contain_exactly(a, b)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user