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
@@ -1,11 +1,17 @@
# Real-time matchmaking channel.
#
# Client flow:
# 1. Connect: ws(s)://host/cable?token=<JWT>
# 2. Subscribe to "MatchmakingChannel"
# 3. Send { action: "start" } to enter the queue
# 4. Receive { type: "matched", ... } or { type: "timeout" }
# 5. Disconnecting (or sending { action: "stop" }) cancels the search.
# Client flows:
# 1. Random battle:
# Connect -> Subscribe -> { action: "start" }
# -> Receive { type: "matched", ... } or { type: "timeout" }
# 2. Invite battle:
# 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
def subscribed
# NB: must mirror MatchmakingService.broadcast, which uses
@@ -17,17 +23,36 @@ class MatchmakingChannel < ApplicationCable::Channel
# (e.g. brief reconnect), deliver it now — exactly once.
if match = MatchmakingService.claim(current_user.id)
transmit(match)
elsif code = MatchmakingService.current_invite_code(current_user.id)
transmit({ type: "invite_created", code: code })
end
end
def start(_data)
def start(_data = nil)
MatchmakingService.enqueue(current_user.id, rating: current_user.rating)
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
MatchmakingService.cancel(current_user.id)
end
def cancel_invite
MatchmakingService.cancel(current_user.id)
end
def unsubscribed
MatchmakingService.cancel(current_user.id)
end
@@ -19,6 +19,8 @@ class MatchmakingService
PENDING_KEY = "mm:pending"
MATCH_KEY_PREFIX = "mm:match:"
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"
# 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[4], 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
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
# Adds the user to the queue and immediately tries to pair them.
# The result (match or timeout) is delivered asynchronously via
@@ -198,14 +224,77 @@ class MatchmakingService
process_results(results)
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)
RedisConnection.with do |redis|
redis.eval(CANCEL_SCRIPT, keys: [ QUEUE_KEY, PENDING_KEY, SINCE_KEY, RATING_KEY, USER_KEY_PREFIX ],
argv: [ user_id ])
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 ])
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.
# Used on channel subscribe to deliver a match that was found while
# the user had no active subscription (at-most-once delivery).