add private endpoint for match reporting

This commit is contained in:
2026-11-09 23:17:55 +03:00
parent f0616c7c51
commit dcb76fa570
11 changed files with 738 additions and 4 deletions
@@ -0,0 +1,19 @@
module Api
module Internal
# Base class for endpoints intended for the game-server only (never for
# browsers). Authenticated via HMAC of the request body instead of a JWT:
# see InternalSignatureService.
class BaseController < ApplicationController
skip_before_action :authenticate_request!
before_action :authenticate_internal_request!
private
def authenticate_internal_request!
unless InternalSignatureService.valid?(request)
render json: { error: "Unauthorized" }, status: :unauthorized
end
end
end
end
end
@@ -0,0 +1,53 @@
module Api
module Internal
# Receives match results reported by the game-server when a match ends.
#
# Transitions a match from `ongoing` to its final status and stores the
# duration. Rating recalculation is not implemented yet, so the
# rating_change fields stay as they are (0).
#
# The report is idempotent: re-reporting the same outcome for an already
# finished match returns 200, a different one returns 409.
class MatchResultsController < Api::Internal::BaseController
FINAL_STATUSES = %w[player1_won player2_won draw abandoned].freeze
def create
match = Match.find_by(uuid: params[:uuid])
return render json: { error: "Match not found" }, status: :not_found unless match
status_param = params[:status].to_s
unless FINAL_STATUSES.include?(status_param)
return render json: { error: "status must be one of: #{FINAL_STATUSES.join(', ')}" },
status: :unprocessable_content
end
duration = parse_duration
return render json: { error: "duration_seconds must be a non-negative integer" },
status: :unprocessable_content if duration.nil?
unless match.ongoing?
if match.status == status_param
# Idempotent re-report of the same outcome.
return render json: { match: MatchSerializer.as_json(match) }
end
return render json: { error: "Match already finished" }, status: :conflict
end
match.update!(status: status_param, duration_seconds: duration, finished_at: Time.current)
render json: { match: MatchSerializer.as_json(match) }
end
private
# Accepts an integer or a string of digits; nil/floats/garbage are invalid.
def parse_duration
value = params[:duration_seconds]
value = value.to_s if value.is_a?(Numeric)
return nil unless value.is_a?(String) && value.match?(/\A\d+\z/)
value.to_i
end
end
end
end
@@ -0,0 +1,11 @@
# Player-facing match details. Only participants of a match can view it:
# a non-participant (or an unknown uuid) gets 404 to avoid leaking
# information about other players' matches.
class Api::MatchesController < ApplicationController
def show
match = Match.for_user(current_user).find_by(uuid: params[:uuid])
return render json: { error: "Match not found" }, status: :not_found unless match
render json: { match: MatchSerializer.as_json(match, viewer: current_user) }
end
end