add invite game mode

This commit is contained in:
2026-11-15 19:19:35 +03:00
parent 8f70bb639d
commit a91eccbeaa
12 changed files with 600 additions and 58 deletions
+12 -3
View File
@@ -9,22 +9,29 @@ export default function App() {
const { token } = useAuth() const { token } = useAuth()
const { openAuthModal } = useAuthModal() const { openAuthModal } = useAuthModal()
const [screen, setScreen] = useState('menu') // 'menu' | 'search' | 'game' const [screen, setScreen] = useState('menu') // 'menu' | 'search' | 'game'
const [searchMode, setSearchMode] = useState('random') // 'random' | 'invite' | 'join'
const [joinCode, setJoinCode] = useState(null)
const [gameSession, setGameSession] = useState(null) const [gameSession, setGameSession] = useState(null)
const handleRandomBattle = () => { const handleRandomBattle = () => {
if (!token) return openAuthModal() if (!token) return openAuthModal()
setSearchMode('random')
setJoinCode(null)
setScreen('search') setScreen('search')
} }
const handleInvite = () => { const handleInvite = () => {
if (!token) return openAuthModal() if (!token) return openAuthModal()
// TODO: создание приватной комнаты setSearchMode('invite')
setJoinCode(null)
setScreen('search')
} }
const handleJoinByCode = (code) => { const handleJoinByCode = (code) => {
if (!token) return openAuthModal() if (!token) return openAuthModal()
// TODO: присоединение к комнате по коду setSearchMode('join')
console.log('join code:', code) setJoinCode(code)
setScreen('search')
} }
const handleMatched = useCallback((match) => { const handleMatched = useCallback((match) => {
@@ -45,6 +52,8 @@ export default function App() {
return ( return (
<SearchScreen <SearchScreen
token={token} token={token}
mode={searchMode}
joinCode={joinCode}
onMatched={handleMatched} onMatched={handleMatched}
onCancel={() => setScreen('menu')} onCancel={() => setScreen('menu')}
/> />
+2 -2
View File
@@ -12,7 +12,7 @@ export default function CodeInput({ onSubmit }) {
const focusInput = (i) => inputsRef.current[i]?.focus() const focusInput = (i) => inputsRef.current[i]?.focus()
const handleChange = (i, raw) => { const handleChange = (i, raw) => {
const chars = raw.toUpperCase().replace(/[^A-Z0-9]/g, '') const chars = raw.toUpperCase().replace(/[^A-Z]/g, '')
if (!chars) return if (!chars) return
const next = [...values] const next = [...values]
// Поддержка вставки нескольких символов (paste в отдельное поле тоже) // Поддержка вставки нескольких символов (paste в отдельное поле тоже)
@@ -47,7 +47,7 @@ export default function CodeInput({ onSubmit }) {
const handlePaste = (e) => { const handlePaste = (e) => {
e.preventDefault() e.preventDefault()
const text = e.clipboardData.getData('text').toUpperCase().replace(/[^A-Z0-9]/g, '') const text = e.clipboardData.getData('text').toUpperCase().replace(/[^A-Z]/g, '')
if (!text) return if (!text) return
const next = Array(CODE_LENGTH).fill('') const next = Array(CODE_LENGTH).fill('')
for (let k = 0; k < Math.min(text.length, CODE_LENGTH); k++) next[k] = text[k] for (let k = 0; k < Math.min(text.length, CODE_LENGTH); k++) next[k] = text[k]
+95 -10
View File
@@ -5,6 +5,8 @@ import { useCable } from '../cable'
const STAGE_LABELS = { const STAGE_LABELS = {
connecting: 'Подключение...', connecting: 'Подключение...',
searching: 'Подбор соперника...', searching: 'Подбор соперника...',
waiting_for_opponent: 'Ожидание соперника...',
joining: 'Подключение к игре...',
} }
const ERROR_LABELS = { const ERROR_LABELS = {
@@ -13,9 +15,10 @@ const ERROR_LABELS = {
rejected: 'Не удалось начать поиск. Попробуйте позже.', rejected: 'Не удалось начать поиск. Попробуйте позже.',
} }
export default function SearchScreen({ token, onMatched, onCancel }) { export default function SearchScreen({ token, mode = 'random', joinCode = null, onMatched, onCancel }) {
const { consumer } = useCable() const { consumer } = useCable()
const [stage, setStage] = useState('connecting') // 'connecting' | 'searching' const [stage, setStage] = useState('connecting')
const [inviteCode, setInviteCode] = useState(null)
const [error, setError] = useState(null) const [error, setError] = useState(null)
const [retryToken, setRetryToken] = useState(0) const [retryToken, setRetryToken] = useState(0)
const attemptRef = useRef(0) const attemptRef = useRef(0)
@@ -27,15 +30,27 @@ export default function SearchScreen({ token, onMatched, onCancel }) {
setStage('connecting') setStage('connecting')
setError(null) setError(null)
setInviteCode(null)
matchmaking = createMatchmaking(consumer || token, (status) => { matchmaking = createMatchmaking(consumer || token, {
mode,
code: joinCode,
onStatus: (status) => {
if (!cancelled && attempt === attemptRef.current) setStage(status) if (!cancelled && attempt === attemptRef.current) setStage(status)
},
onInviteCreated: (code) => {
if (!cancelled && attempt === attemptRef.current) setInviteCode(code)
},
}) })
matchmaking.promise.then(onMatched).catch((err) => { matchmaking.promise.then(onMatched).catch((err) => {
if (cancelled || attempt !== attemptRef.current) return if (cancelled || attempt !== attemptRef.current) return
if (err instanceof MatchmakingError) { if (err instanceof MatchmakingError) {
setError(ERROR_LABELS[err.code] || ERROR_LABELS.connection) if (err.code === 'invite_error') {
setError(err.message || 'Ошибка приглашения')
} else {
setError(ERROR_LABELS[err.code] || err.message || ERROR_LABELS.connection)
}
} else { } else {
setError(ERROR_LABELS.connection) setError(ERROR_LABELS.connection)
} }
@@ -45,16 +60,15 @@ export default function SearchScreen({ token, onMatched, onCancel }) {
cancelled = true cancelled = true
matchmaking.cancel() matchmaking.cancel()
} }
}, [consumer, token, onMatched, retryToken]) }, [consumer, token, mode, joinCode, onMatched, retryToken])
const handleCancel = () => { const handleCancel = () => {
onCancel() onCancel()
} }
const renderContent = () => {
if (error) {
return ( return (
<div className="page">
<main className="search-screen">
{error ? (
<> <>
<div className="search-error">{error}</div> <div className="search-error">{error}</div>
<div className="search-actions"> <div className="search-actions">
@@ -66,9 +80,14 @@ export default function SearchScreen({ token, onMatched, onCancel }) {
</button> </button>
</div> </div>
</> </>
) : ( )
}
if (mode === 'invite') {
if (!inviteCode) {
return (
<> <>
<div className="search-label">{STAGE_LABELS[stage]}</div> <div className="search-label">Создание приглашения...</div>
<div className="bouncing-dots" aria-hidden="true"> <div className="bouncing-dots" aria-hidden="true">
<span /> <span />
<span /> <span />
@@ -78,7 +97,73 @@ export default function SearchScreen({ token, onMatched, onCancel }) {
Отмена Отмена
</button> </button>
</> </>
)
}
return (
<>
<div className="search-label">Код приглашения</div>
<div className="code-inputs invite-code-inputs">
{inviteCode.split('').map((ch, i) => (
<div key={i} className="code-cell invite-code-cell">{ch}</div>
))}
</div>
<div className="invite-hint">Сообщите этот код второму игроку</div>
<div className="invite-status">Ожидание соперника...</div>
<div className="bouncing-dots" aria-hidden="true">
<span />
<span />
<span />
</div>
<button className="btn btn-big btn-secondary" onClick={handleCancel}>
Отмена
</button>
</>
)
}
if (mode === 'join') {
return (
<>
<div className="search-label">Подключение к игре...</div>
{joinCode && (
<div className="code-inputs invite-code-inputs">
{joinCode.split('').map((ch, i) => (
<div key={i} className="code-cell invite-code-cell">{ch}</div>
))}
</div>
)} )}
<div className="bouncing-dots" aria-hidden="true">
<span />
<span />
<span />
</div>
<button className="btn btn-big btn-secondary" onClick={handleCancel}>
Отмена
</button>
</>
)
}
return (
<>
<div className="search-label">{STAGE_LABELS[stage] || STAGE_LABELS.searching}</div>
<div className="bouncing-dots" aria-hidden="true">
<span />
<span />
<span />
</div>
<button className="btn btn-big btn-secondary" onClick={handleCancel}>
Отмена
</button>
</>
)
}
return (
<div className="page">
<main className="search-screen">
{renderContent()}
</main> </main>
</div> </div>
) )
+51 -2
View File
@@ -30,9 +30,21 @@ let activeSession = null
* @param {(status: 'connecting' | 'searching') => void} [onStatus] * @param {(status: 'connecting' | 'searching') => void} [onStatus]
* @returns {{ promise: Promise<{ matchId: string, gameToken: string, gameServerUrl: string, players: [number, number] }>, cancel: () => void }} * @returns {{ promise: Promise<{ matchId: string, gameToken: string, gameServerUrl: string, players: [number, number] }>, cancel: () => void }}
*/ */
export function createMatchmaking(consumerOrToken, onStatus) { export function createMatchmaking(consumerOrToken, optionsOrOnStatus) {
let consumer = null let consumer = null
let statusCallback = onStatus let mode = 'random' // 'random' | 'invite' | 'join'
let code = null
let onInviteCreated = null
let statusCallback = null
if (typeof optionsOrOnStatus === 'function') {
statusCallback = optionsOrOnStatus
} else if (optionsOrOnStatus && typeof optionsOrOnStatus === 'object') {
mode = optionsOrOnStatus.mode || 'random'
code = optionsOrOnStatus.code || null
onInviteCreated = optionsOrOnStatus.onInviteCreated || null
statusCallback = optionsOrOnStatus.onStatus || null
}
if (typeof consumerOrToken === 'function') { if (typeof consumerOrToken === 'function') {
statusCallback = consumerOrToken statusCallback = consumerOrToken
@@ -54,16 +66,32 @@ export function createMatchmaking(consumerOrToken, onStatus) {
// Если уже существует активная сессия подписки (например, от предыдущего быстрого mount в StrictMode) // Если уже существует активная сессия подписки (например, от предыдущего быстрого mount в StrictMode)
if (activeSession && activeSession.consumer === consumer && !activeSession.settled) { if (activeSession && activeSession.consumer === consumer && !activeSession.settled) {
if (activeSession.mode === mode && activeSession.code === code) {
activeSession.cancelled = false activeSession.cancelled = false
activeSession.statusCallback = statusCallback activeSession.statusCallback = statusCallback
activeSession.onInviteCreated = onInviteCreated
// Если подписка уже успела подтвердиться ранее // Если подписка уже успела подтвердиться ранее
if (activeSession.isSubscribed) { if (activeSession.isSubscribed) {
if (mode === 'invite') {
statusCallback?.('waiting_for_opponent')
if (!activeSession.started) {
activeSession.subscription.perform('create_invite')
activeSession.started = true
}
} else if (mode === 'join') {
statusCallback?.('joining')
if (!activeSession.started) {
activeSession.subscription.perform('join_invite', { code })
activeSession.started = true
}
} else {
statusCallback?.('searching') statusCallback?.('searching')
if (!activeSession.started) { if (!activeSession.started) {
activeSession.subscription.perform('start') activeSession.subscription.perform('start')
activeSession.started = true activeSession.started = true
} }
}
} else { } else {
statusCallback?.('connecting') statusCallback?.('connecting')
} }
@@ -72,10 +100,16 @@ export function createMatchmaking(consumerOrToken, onStatus) {
promise: activeSession.promise, promise: activeSession.promise,
cancel: activeSession.cancel, cancel: activeSession.cancel,
} }
} else {
activeSession.cancel()
}
} }
const session = { const session = {
consumer, consumer,
mode,
code,
onInviteCreated,
statusCallback, statusCallback,
isSubscribed: false, isSubscribed: false,
cancelled: false, cancelled: false,
@@ -164,9 +198,19 @@ export function createMatchmaking(consumerOrToken, onStatus) {
session.disconnectTimeoutId = null session.disconnectTimeoutId = null
} }
if (mode === 'invite') {
session.statusCallback?.('waiting_for_opponent')
this.perform('create_invite')
session.started = true
} else if (mode === 'join') {
session.statusCallback?.('joining')
this.perform('join_invite', { code })
session.started = true
} else {
session.statusCallback?.('searching') session.statusCallback?.('searching')
this.perform('start') this.perform('start')
session.started = true session.started = true
}
}, },
rejected() { rejected() {
@@ -205,6 +249,11 @@ export function createMatchmaking(consumerOrToken, onStatus) {
}) })
} else if (message.type === 'timeout') { } else if (message.type === 'timeout') {
fail(new MatchmakingError('timeout', 'Соперник не найден')) fail(new MatchmakingError('timeout', 'Соперник не найден'))
} else if (message.type === 'invite_created') {
session.statusCallback?.('waiting_for_opponent')
session.onInviteCreated?.(message.code)
} else if (message.type === 'invite_error') {
fail(new MatchmakingError('invite_error', message.message || 'Ошибка приглашения'))
} }
}, },
} }
+28
View File
@@ -239,6 +239,34 @@ input:not([type]), input[type="text"] {
width: min(320px, 90vw); width: min(320px, 90vw);
} }
.invite-code-inputs {
justify-content: center;
}
.invite-code-cell {
display: inline-flex;
align-items: center;
justify-content: center;
user-select: all;
font-family: 'Comfortaa', sans-serif;
}
.invite-hint {
font-family: 'Nunito', sans-serif;
font-size: clamp(16px, 2.5vw, 20px);
font-weight: 600;
color: var(--text-soft);
text-align: center;
}
.invite-status {
font-family: 'Comfortaa', sans-serif;
font-size: clamp(18px, 3vw, 22px);
font-weight: 700;
color: var(--text);
text-align: center;
}
.btn-secondary { .btn-secondary {
color: var(--primary); color: var(--primary);
background: #fff; background: #fff;
+75
View File
@@ -325,6 +325,81 @@ Action Cable использует формат JSON-сообщений чере
--- ---
### Игра по приглашению (Код из 5 букв)
Помимо случайного матчмейкинга, игроки могут играть друг с другом по 5-значному коду приглашения (5 заглавных латинских букв `A-Z`). Игроки взаимодействуют через тот же WebSocket-канал `MatchmakingChannel`, но не участвуют в общей очереди подбора.
#### 1. Создание приглашения (Игрок 1)
Клиент отправляет команду `create_invite`:
```json
{
"command": "message",
"identifier": "{\"channel\":\"MatchmakingChannel\"}",
"data": "{\"action\":\"create_invite\"}"
}
```
Сервер генерирует случайный уникальный 5-буквенный код (`[A-Z]{5}`), сохраняет его в Redis с TTL (`MATCHMAKING_INVITE_TTL`, по умолчанию 300 секунд) и передаёт клиенту:
```json
{
"identifier": "{\"channel\":\"MatchmakingChannel\"}",
"message": {
"type": "invite_created",
"code": "ABCDE"
}
}
```
Игрок ожидает подключения второго игрока. Если соединение кратковременно разрывается, при повторной подписке сервер возвращает активный код созданного приглашения.
#### 2. Присоединение по коду (Игрок 2)
Клиент отправляет команду `join_invite` с кодом:
```json
{
"command": "message",
"identifier": "{\"channel\":\"MatchmakingChannel\"}",
"data": "{\"action\":\"join_invite\",\"code\":\"ABCDE\"}"
}
```
- **Успех:** Сервер атомарно связывает обоих игроков, удаляет код из Redis, создаёт запись `Match` в БД и рассылает обоим игрокам стандартное сообщение `matched`:
```json
{
"identifier": "{\"channel\":\"MatchmakingChannel\"}",
"message": {
"type": "matched",
"match_id": "145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f",
"game_token": "eyJhbGciOiJIUzI1NiJ9...",
"game_server": "ws://localhost:8080",
"players": [1, 2]
}
}
```
- **Ошибка (код не найден, истёк, неверный формат или попытка сыграть с самим собой):**
Сервер отправляет сообщение `invite_error`:
```json
{
"identifier": "{\"channel\":\"MatchmakingChannel\"}",
"message": {
"type": "invite_error",
"error": "not_found",
"message": "Приглашение не найдено или истекло"
}
}
```
Возможные коды ошибок:
- `not_found` — приглашение с таким кодом не существует или истекло по таймауту;
- `cannot_join_self` — игрок пытается подключиться по собственному коду;
- `invalid_code` — строка не соответствует формату из 5 заглавных латинских букв.
#### 3. Отмена приглашения
Создатель приглашения может отменить его отправкой `{ action: "stop" }` или `{ action: "cancel_invite" }`, а также простым закрытием WebSocket (`unsubscribe`). При этом код атомарно удаляется из Redis.
---
### История матчей ### История матчей
Возвращает постраничный список матчей текущего авторизованного пользователя, отсортированный от новых к старым (по дате начала `started_at`). Возвращает постраничный список матчей текущего авторизованного пользователя, отсортированный от новых к старым (по дате начала `started_at`).
@@ -1,11 +1,17 @@
# Real-time matchmaking channel. # Real-time matchmaking channel.
# #
# Client flow: # Client flows:
# 1. Connect: ws(s)://host/cable?token=<JWT> # 1. Random battle:
# 2. Subscribe to "MatchmakingChannel" # Connect -> Subscribe -> { action: "start" }
# 3. Send { action: "start" } to enter the queue # -> Receive { type: "matched", ... } or { type: "timeout" }
# 4. Receive { type: "matched", ... } or { type: "timeout" } # 2. Invite battle:
# 5. Disconnecting (or sending { action: "stop" }) cancels the search. # Host: Connect -> Subscribe -> { action: "create_invite" }
# -> Receive { type: "invite_created", code: "ABCDE" }
# -> Wait -> Receive { type: "matched", ... }
# Guest: Connect -> Subscribe -> { action: "join_invite", code: "ABCDE" }
# -> Receive { type: "matched", ... } or { type: "invite_error", ... }
# 3. Cancellation:
# Disconnecting or sending { action: "stop" } cancels active search or invite.
class MatchmakingChannel < ApplicationCable::Channel class MatchmakingChannel < ApplicationCable::Channel
def subscribed def subscribed
# NB: must mirror MatchmakingService.broadcast, which uses # NB: must mirror MatchmakingService.broadcast, which uses
@@ -17,17 +23,36 @@ class MatchmakingChannel < ApplicationCable::Channel
# (e.g. brief reconnect), deliver it now — exactly once. # (e.g. brief reconnect), deliver it now — exactly once.
if match = MatchmakingService.claim(current_user.id) if match = MatchmakingService.claim(current_user.id)
transmit(match) transmit(match)
elsif code = MatchmakingService.current_invite_code(current_user.id)
transmit({ type: "invite_created", code: code })
end end
end end
def start(_data) def start(_data = nil)
MatchmakingService.enqueue(current_user.id, rating: current_user.rating) MatchmakingService.enqueue(current_user.id, rating: current_user.rating)
end end
def create_invite
code = MatchmakingService.create_invite(current_user.id)
transmit({ type: "invite_created", code: code })
end
def join_invite(data)
code = data&.[]("code") || data&.[](:code)
result = MatchmakingService.join_invite(current_user.id, code)
if result[:error]
transmit({ type: "invite_error", error: result[:error], message: result[:message] })
end
end
def stop def stop
MatchmakingService.cancel(current_user.id) MatchmakingService.cancel(current_user.id)
end end
def cancel_invite
MatchmakingService.cancel(current_user.id)
end
def unsubscribed def unsubscribed
MatchmakingService.cancel(current_user.id) MatchmakingService.cancel(current_user.id)
end end
@@ -19,6 +19,8 @@ class MatchmakingService
PENDING_KEY = "mm:pending" PENDING_KEY = "mm:pending"
MATCH_KEY_PREFIX = "mm:match:" MATCH_KEY_PREFIX = "mm:match:"
USER_KEY_PREFIX = "mm:user:" USER_KEY_PREFIX = "mm:user:"
INVITE_KEY_PREFIX = "mm:invite:"
USER_INVITE_KEY_PREFIX = "mm:user_invite:"
# Enqueues a player and tries to find an opponent immediately; in "sweep" # Enqueues a player and tries to find an opponent immediately; in "sweep"
# mode pairs up everyone in the queue, expires timed-out waiters and # mode pairs up everyone in the queue, expires timed-out waiters and
@@ -179,9 +181,33 @@ class MatchmakingService
redis.call("HDEL", KEYS[3], ARGV[1]) redis.call("HDEL", KEYS[3], ARGV[1])
redis.call("HDEL", KEYS[4], ARGV[1]) redis.call("HDEL", KEYS[4], ARGV[1])
redis.call("DEL", KEYS[5] .. ARGV[1]) redis.call("DEL", KEYS[5] .. ARGV[1])
local user_invite_key = KEYS[6] .. ARGV[1]
local code = redis.call("GET", user_invite_key)
if code then
redis.call("DEL", KEYS[7] .. code)
redis.call("DEL", user_invite_key)
end
return 1 return 1
LUA LUA
CLAIM_INVITE_SCRIPT = <<~LUA
local invite_key = KEYS[1]
local user_invite_prefix = KEYS[2]
local joiner_id = tostring(ARGV[1])
local inviter = redis.call("GET", invite_key)
if not inviter then
return { "err", "not_found" }
end
if tostring(inviter) == joiner_id then
return { "err", "cannot_join_self" }
end
redis.call("DEL", invite_key)
redis.call("DEL", user_invite_prefix .. inviter)
return { "ok", inviter }
LUA
class << self class << self
# Adds the user to the queue and immediately tries to pair them. # Adds the user to the queue and immediately tries to pair them.
# The result (match or timeout) is delivered asynchronously via # The result (match or timeout) is delivered asynchronously via
@@ -198,14 +224,77 @@ class MatchmakingService
process_results(results) process_results(results)
end end
# Removes the user from the queue / pending state. # Removes the user from the queue / pending state and cancels any active invite.
def cancel(user_id) def cancel(user_id)
RedisConnection.with do |redis| RedisConnection.with do |redis|
redis.eval(CANCEL_SCRIPT, keys: [ QUEUE_KEY, PENDING_KEY, SINCE_KEY, RATING_KEY, USER_KEY_PREFIX ], redis.eval(CANCEL_SCRIPT,
keys: [ QUEUE_KEY, PENDING_KEY, SINCE_KEY, RATING_KEY, USER_KEY_PREFIX, USER_INVITE_KEY_PREFIX, INVITE_KEY_PREFIX ],
argv: [ user_id ]) argv: [ user_id ])
end end
end end
# Creates an invitation with a unique 5 uppercase latin letters code.
# Any previous matchmaking queue or invite session for this user is cancelled.
def create_invite(user_id)
cancel(user_id)
RedisConnection.with do |redis|
10.times do
code = generate_invite_code
invite_k = invite_key(code)
user_k = user_invite_key(user_id)
if redis.set(invite_k, user_id, nx: true, ex: config.invite_ttl)
redis.set(user_k, code, ex: config.invite_ttl)
return code
end
end
end
raise "Failed to generate unique invite code"
end
# Joins a game using an invite code.
# Returns { ok: true } on success, or { error: ..., message: ... } on failure.
def join_invite(user_id, raw_code)
code = raw_code.to_s.strip.upcase
unless code.match?(/\A[A-Z]{5}\z/)
return { error: "invalid_code", message: "Неверный формат кода" }
end
res = RedisConnection.with do |redis|
redis.eval(CLAIM_INVITE_SCRIPT,
keys: [ invite_key(code), USER_INVITE_KEY_PREFIX ],
argv: [ user_id.to_s ])
end
status, inviter_id = res
if status == "err"
case inviter_id
when "not_found"
{ error: "not_found", message: "Приглашение не найдено или истекло" }
when "cannot_join_self"
{ error: "cannot_join_self", message: "Нельзя играть с самим собой" }
else
{ error: "unknown", message: "Ошибка присоединения к игре" }
end
else
cancel(user_id)
create_match(inviter_id.to_i, user_id.to_i)
{ ok: true }
end
end
def current_invite_code(user_id)
RedisConnection.with { |redis| redis.get(user_invite_key(user_id)) }
end
def invite_key(code) = "#{INVITE_KEY_PREFIX}#{code}"
def user_invite_key(user_id) = "#{USER_INVITE_KEY_PREFIX}#{user_id}"
def generate_invite_code
Array.new(5) { ("A".."Z").to_a.sample }.join
end
# Atomically reads and clears the match pointer for the user. # Atomically reads and clears the match pointer for the user.
# Used on channel subscribe to deliver a match that was found while # Used on channel subscribe to deliver a match that was found while
# the user had no active subscription (at-most-once delivery). # the user had no active subscription (at-most-once delivery).
@@ -9,6 +9,9 @@ mm.game_server_url = ENV.fetch("GAME_SERVER_URL", "ws://localhost:8080")
mm.match_ttl = ENV.fetch("MATCHMAKING_MATCH_TTL", 120).to_i mm.match_ttl = ENV.fetch("MATCHMAKING_MATCH_TTL", 120).to_i
mm.token_ttl = ENV.fetch("MATCHMAKING_TOKEN_TTL", 120).to_i mm.token_ttl = ENV.fetch("MATCHMAKING_TOKEN_TTL", 120).to_i
# How long an invite code stays valid, in seconds.
mm.invite_ttl = ENV.fetch("MATCHMAKING_INVITE_TTL", 300).to_i
# How long a player waits in the queue before a timeout, in seconds. # How long a player waits in the queue before a timeout, in seconds.
mm.queue_ttl = ENV.fetch("MATCHMAKING_QUEUE_TTL", 60).to_i mm.queue_ttl = ENV.fetch("MATCHMAKING_QUEUE_TTL", 60).to_i
+24
View File
@@ -27,6 +27,8 @@
| `mm:pending` | Sorted Set | `score` = `timestamp` спаривания (мс), `member` = `user_id` | Игроки, для которых пара найдена, но генерация матча и JWT ещё выполняется в Ruby. | | `mm:pending` | Sorted Set | `score` = `timestamp` спаривания (мс), `member` = `user_id` | Игроки, для которых пара найдена, но генерация матча и JWT ещё выполняется в Ruby. |
| `mm:match:<match_id>` | String (JSON) | Полный payload матча | Данные матча (TTL = `MATCHMAKING_MATCH_TTL`, по умолчанию 120 сек). | | `mm:match:<match_id>` | String (JSON) | Полный payload матча | Данные матча (TTL = `MATCHMAKING_MATCH_TTL`, по умолчанию 120 сек). |
| `mm:user:<user_id>` | String (JSON) | Копия payload матча | Индивидуальный указатель для игрока для механизма `claim` при реконнекте (TTL = `MATCHMAKING_MATCH_TTL`). | | `mm:user:<user_id>` | String (JSON) | Копия payload матча | Индивидуальный указатель для игрока для механизма `claim` при реконнекте (TTL = `MATCHMAKING_MATCH_TTL`). |
| `mm:invite:<code>` | String | `user_id` создателя | Активный код приглашения из 5 букв (TTL = `MATCHMAKING_INVITE_TTL`, по умолчанию 300 сек). |
| `mm:user_invite:<user_id>` | String | `code` приглашения | Обратный указатель пользователя на созданный им код приглашения (TTL = `MATCHMAKING_INVITE_TTL`). |
--- ---
@@ -226,3 +228,25 @@ stateDiagram-v2
Matched --> InGame: Подключение к Game Server по game_token Matched --> InGame: Подключение к Game Server по game_token
InGame --> Idle: Завершение игры InGame --> Idle: Завершение игры
``` ```
---
## 7. Режим игры по приглашению (Invite Mode)
Помимо случайного подбора, поддерживается прямая игра двух игроков по 5-значному коду приглашения (5 заглавных латинских букв `A-Z`).
### Принцип работы:
1. **Изоляция от общей очереди:** Игроки в режиме приглашения не попадают в `mm:queue` и не участвуют в динамическом подборе по рейтингу.
2. **Создание приглашения (`create_invite`):**
- Сервер генерирует случайный код из 5 заглавных букв (`[A-Z]{5}`).
- В Redis атомарно сохраняются ключи `mm:invite:<code>` и `mm:user_invite:<user_id>` с TTL `MATCHMAKING_INVITE_TTL` (300 сек).
- Любая предыдущая сессия ожидания или приглашения этого пользователя сбрасывается.
3. **Присоединение (`join_invite`):**
- Второй игрок передаёт код через WebSocket Action Cable.
- Атомарный Lua-скрипт `CLAIM_INVITE_SCRIPT`:
- Проверяет существование кода в `mm:invite:<code>`.
- Проверяет, что игрок не присоединяется к собственной игре (`inviter != joiner`).
- Атомарно удаляет ключи `mm:invite:<code>` и `mm:user_invite:<inviter>`.
- После успешного захвата приглашения вызывается стандартный метод создания матча: запись в БД `matches`, выпуск `game_token` (JWT) и push-уведомление `matched` обоим участникам.
4. **Отмена и очистка:**
- При вызове `stop`, `cancel_invite` или обрыве соединения (`unsubscribed`) Lua-скрипт `CANCEL_SCRIPT` удаляет как записи случайной очереди, так и активные ключи приглашения.
@@ -30,6 +30,16 @@ RSpec.describe MatchmakingChannel, type: :channel do
expect(subscription).to be_confirmed expect(subscription).to be_confirmed
expect(transmissions.last).to eq(match_payload.as_json) expect(transmissions.last).to eq(match_payload.as_json)
end end
it "transmits current invite code if one was active for the user" do
allow(MatchmakingService).to receive(:claim).with(user.id).and_return(nil)
allow(MatchmakingService).to receive(:current_invite_code).with(user.id).and_return("ABCDE")
subscribe
expect(subscription).to be_confirmed
expect(transmissions.last).to eq({ "type" => "invite_created", "code" => "ABCDE" })
end
end end
describe "#start" do describe "#start" do
@@ -57,6 +67,46 @@ RSpec.describe MatchmakingChannel, type: :channel do
end end
end end
describe "#create_invite" do
it "calls MatchmakingService.create_invite and transmits invite_created" do
subscribe
expect(MatchmakingService).to receive(:create_invite).with(user.id).and_return("XYZAB")
perform :create_invite
expect(transmissions.last).to eq({ "type" => "invite_created", "code" => "XYZAB" })
end
end
describe "#join_invite" do
it "calls MatchmakingService.join_invite with code" do
subscribe
expect(MatchmakingService).to receive(:join_invite).with(user.id, "XYZAB").and_return({ ok: true })
perform :join_invite, { "code" => "XYZAB" }
end
it "transmits invite_error if join fails" do
subscribe
expect(MatchmakingService).to receive(:join_invite).with(user.id, "WRONG").and_return(
{ error: "not_found", message: "Приглашение не найдено или истекло" }
)
perform :join_invite, { "code" => "WRONG" }
expect(transmissions.last).to eq(
{ "type" => "invite_error", "error" => "not_found", "message" => "Приглашение не найдено или истекло" }
)
end
end
describe "#cancel_invite" do
it "calls MatchmakingService.cancel for the current user" do
subscribe
expect(MatchmakingService).to receive(:cancel).with(user.id)
perform :cancel_invite
end
end
describe "#unsubscribed" do describe "#unsubscribed" do
it "cancels matchmaking search when unsubscribing" do it "cancels matchmaking search when unsubscribing" do
subscribe subscribe
@@ -170,6 +170,111 @@ RSpec.describe MatchmakingService do
expect(redis.zrange(described_class::QUEUE_KEY, 0, -1)).to be_empty expect(redis.zrange(described_class::QUEUE_KEY, 0, -1)).to be_empty
expect(redis.hget(described_class::SINCE_KEY, a.to_s)).to be_nil expect(redis.hget(described_class::SINCE_KEY, a.to_s)).to be_nil
end end
it "removes the player's active invite and code mapping" do
a = uid(1)
code = described_class.create_invite(a)
expect(redis.get(described_class.invite_key(code))).to eq(a.to_s)
described_class.cancel(a)
expect(redis.get(described_class.invite_key(code))).to be_nil
expect(redis.get(described_class.user_invite_key(a))).to be_nil
expect(described_class.current_invite_code(a)).to be_nil
end
end
describe ".create_invite" do
it "generates a 5-letter uppercase code and stores it in Redis with TTL" do
a = uid(1)
code = described_class.create_invite(a)
expect(code).to match(/\A[A-Z]{5}\z/)
expect(redis.get(described_class.invite_key(code))).to eq(a.to_s)
expect(redis.get(described_class.user_invite_key(a))).to eq(code)
expect(described_class.current_invite_code(a)).to eq(code)
expect(redis.ttl(described_class.invite_key(code))).to be > 0
end
it "clears previous matchmaking queue or invite when creating a new one" do
a = uid(1)
described_class.enqueue(a, rating: 1000)
code1 = described_class.create_invite(a)
expect(redis.zrange(described_class::QUEUE_KEY, 0, -1)).to be_empty
code2 = described_class.create_invite(a)
expect(code2).to be_present
expect(redis.get(described_class.invite_key(code1))).to be_nil
expect(redis.get(described_class.invite_key(code2))).to eq(a.to_s)
end
end
describe ".join_invite" do
it "rejects invalid code formats" do
a = uid(1)
expect(described_class.join_invite(a, "12345")[:error]).to eq("invalid_code")
expect(described_class.join_invite(a, "ABC")[:error]).to eq("invalid_code")
expect(described_class.join_invite(a, "TOOLONG")[:error]).to eq("invalid_code")
expect(described_class.join_invite(a, "")[:error]).to eq("invalid_code")
end
it "returns not_found if code does not exist" do
a = uid(1)
result = described_class.join_invite(a, "ABCDE")
expect(result[:error]).to eq("not_found")
end
it "returns cannot_join_self if player attempts to join their own invite" do
a = uid(1)
code = described_class.create_invite(a)
result = described_class.join_invite(a, code)
expect(result[:error]).to eq("cannot_join_self")
end
it "pairs the players, creates a Match record, broadcasts to both, and cleans up Redis" do
host = uid(1)
guest = uid(2)
code = described_class.create_invite(host)
result = described_class.join_invite(guest, code.downcase) # should be case-insensitive
expect(result[:ok]).to be true
# Redis invite keys are removed
expect(redis.get(described_class.invite_key(code))).to be_nil
expect(redis.get(described_class.user_invite_key(host))).to be_nil
# Neither player is in the public matchmaking queue
expect(redis.zrange(described_class::QUEUE_KEY, 0, -1)).to be_empty
# Match record created in DB
host_broadcast = broadcast_payloads(host).first
guest_broadcast = broadcast_payloads(guest).first
expect(host_broadcast[:type]).to eq("matched")
expect(guest_broadcast[:type]).to eq("matched")
expect(host_broadcast[:match_id]).to eq(guest_broadcast[:match_id])
expect(host_broadcast[:players]).to contain_exactly(host, guest)
match = Match.find_by!(uuid: host_broadcast[:match_id])
expect(match.player1_id).to eq(host)
expect(match.player2_id).to eq(guest)
expect(match).to be_ongoing
expect(match.match_players.pluck(:player_id)).to contain_exactly(host, guest)
end
it "handles concurrent join attempts so only one guest succeeds" do
host = uid(1)
guest1 = uid(2)
guest2 = uid(3)
code = described_class.create_invite(host)
res1 = described_class.join_invite(guest1, code)
res2 = described_class.join_invite(guest2, code)
expect(res1[:ok]).to be true
expect(res2[:error]).to eq("not_found")
end
end end
describe ".claim" do describe ".claim" do