60 lines
2.0 KiB
Ruby
60 lines
2.0 KiB
Ruby
# Real-time matchmaking channel.
|
|
#
|
|
# 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
|
|
# broadcast_to(user_id) → "matchmaking:<id>". stream_for(current_user)
|
|
# would use the GlobalID-based name and never receive those broadcasts.
|
|
stream_from "matchmaking:#{current_user.id}"
|
|
|
|
# If a match was found while this user had no subscription
|
|
# (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 = 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
|
|
end
|