Skip to content

Commit bbee38d

Browse files
committed
Merge branch 'feat/real-match-readiness': real-match readiness — unified OPS reporting, idempotency, party matchmaking, metrics
2 parents 8044fb5 + a40e2ea commit bbee38d

32 files changed

Lines changed: 2999 additions & 1397 deletions

‎api/handler/match.go‎

Lines changed: 59 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,66 @@
11
package handler
22

33
import (
4+
"errors"
45
"strconv"
56

67
"github.com/gin-gonic/gin"
78

89
"MatchCoreArena-Server/api/middleware"
910
"MatchCoreArena-Server/internal/apperr"
11+
"MatchCoreArena-Server/internal/metrics"
1012
"MatchCoreArena-Server/internal/response"
1113
"MatchCoreArena-Server/internal/service"
1214
)
1315

1416
// MatchHandler 对战 HTTP handler。
15-
// virtualEnabled 来自配置 virtual_matches.enabled,关闭时虚拟对局入口返回 400。
1617
type MatchHandler struct {
17-
svc service.MatchService
18-
virtualEnabled bool
18+
svc service.MatchService
1919
}
2020

2121
// NewMatchHandler 创建 MatchHandler。
22-
func NewMatchHandler(svc service.MatchService, virtualEnabled bool) *MatchHandler {
23-
return &MatchHandler{svc: svc, virtualEnabled: virtualEnabled}
22+
func NewMatchHandler(svc service.MatchService) *MatchHandler {
23+
return &MatchHandler{svc: svc}
2424
}
2525

2626
// Report POST /api/matches
27+
// 对局上报唯一入口(虚拟对局即运维方经此端点提交的假数据,服务端不区分)。
28+
// 仅允许持 match:report scope 的 OPS 级凭据(运维令牌/服务令牌)上报。
29+
// 同一 game_id 重复上报幂等:返回既有记录(200),不重复结算。
2730
func (h *MatchHandler) Report(c *gin.Context) {
28-
// 仅允许拥有 match:report scope 的客户端上报(系统/管理员)
29-
if !middleware.HasScope(c, "match:report") {
30-
response.FailCode(c, apperr.CodeOAuthInsufficientScope, "无权上报对战结果")
31+
if !middleware.HasScope(c, "match:report") || !middleware.GetOps(c) {
32+
response.FailCode(c, apperr.CodeOAuthInsufficientScope, "上报对局结果需要 OPS 级凭据(运维/服务令牌)")
3133
return
3234
}
3335

3436
uid := middleware.GetUID(c)
3537

3638
var body service.TeamReportInput
3739
if err := c.ShouldBindJSON(&body); err != nil {
40+
metrics.Default.Inc(metrics.MatchesRejectedPrefix+string(apperr.CodeMCAInvalidRequest), 1)
3841
response.FailCode(c, apperr.CodeMCAInvalidRequest, "请求参数格式错误: "+err.Error())
3942
return
4043
}
4144

42-
m, err := h.svc.Report(c.Request.Context(), uid, body)
45+
m, replayed, err := h.svc.Report(c.Request.Context(), uid, body)
4346
if err != nil {
47+
var ae *apperr.Error
48+
if errors.As(err, &ae) {
49+
metrics.Default.Inc(metrics.MatchesRejectedPrefix+string(ae.Code), 1)
50+
} else {
51+
metrics.Default.Inc(metrics.MatchesRejectedPrefix+string(apperr.CodeInternal), 1)
52+
}
4453
response.Fail(c, "上报对战结果失败", err)
4554
return
4655
}
47-
response.Created(c, "团队对战结果已记录", m)
48-
}
49-
50-
// Virtual POST /api/matches/virtual
51-
// 虚拟对局入口:不依赖游戏侧连接,直接灌入对局数据完成定级结算。
52-
// 与游戏上报同一鉴权姿态(match:report scope),不改动 POST /api/matches 语义。
53-
func (h *MatchHandler) Virtual(c *gin.Context) {
54-
if !h.virtualEnabled {
55-
response.FailCode(c, apperr.CodeMCAInvalidRequest, "虚拟对局未启用")
56-
return
57-
}
58-
if !middleware.HasScope(c, "match:report") {
59-
response.FailCode(c, apperr.CodeOAuthInsufficientScope, "无权提交虚拟对局")
60-
return
61-
}
6256

63-
uid := middleware.GetUID(c)
64-
65-
var body service.VirtualReportInput
66-
if err := c.ShouldBindJSON(&body); err != nil {
67-
response.FailCode(c, apperr.CodeMCAInvalidRequest, "请求参数格式错误: "+err.Error())
57+
if replayed {
58+
metrics.Default.Inc(metrics.MatchesReportedReplayTotal, 1)
59+
response.OK(c, "对局已记录(game_id 幂等重放)", m)
6860
return
6961
}
70-
71-
result, err := h.svc.ReportVirtual(c.Request.Context(), uid, body)
72-
if err != nil {
73-
response.Fail(c, "提交虚拟对局失败", err)
74-
return
75-
}
76-
response.Created(c, "虚拟对局已记录", result)
62+
metrics.Default.Inc(metrics.MatchesReportedTotal, 1)
63+
response.Created(c, "对战结果已记录", m)
7764
}
7865

7966
// GetByID GET /api/matches/:id
@@ -95,17 +82,30 @@ func (h *MatchHandler) GetByID(c *gin.Context) {
9582
// ListByMe GET /api/matches/me
9683
func (h *MatchHandler) ListByMe(c *gin.Context) {
9784
uid := middleware.GetUID(c)
85+
page := bindPage(c)
86+
if page.PageNum <= 0 {
87+
return
88+
}
9889

99-
var page service.Page
100-
if err := c.ShouldBindQuery(&page); err != nil {
101-
response.FailCode(c, apperr.CodeMCAInvalidRequest, "分页参数错误")
90+
matches, err := h.svc.ListByUser(c.Request.Context(), uid, page)
91+
if err != nil {
92+
response.Fail(c, "获取对战历史失败", err)
10293
return
10394
}
104-
if page.PageNum <= 0 {
105-
page.PageNum = 1
95+
response.OK(c, "获取对战历史成功", matches)
96+
}
97+
98+
// ListByUser GET /api/users/:uid/matches
99+
// 按玩家查询历史战绩(分页)。
100+
func (h *MatchHandler) ListByUser(c *gin.Context) {
101+
uid, err := strconv.ParseInt(c.Param("uid"), 10, 64)
102+
if err != nil {
103+
response.FailCode(c, apperr.CodeMCAInvalidRequest, "uid 格式错误")
104+
return
106105
}
107-
if page.PageSize <= 0 || page.PageSize > 100 {
108-
page.PageSize = 20
106+
page := bindPage(c)
107+
if page.PageNum <= 0 {
108+
return
109109
}
110110

111111
matches, err := h.svc.ListByUser(c.Request.Context(), uid, page)
@@ -115,3 +115,19 @@ func (h *MatchHandler) ListByMe(c *gin.Context) {
115115
}
116116
response.OK(c, "获取对战历史成功", matches)
117117
}
118+
119+
// bindPage 解析并归一分页参数;非法时已写响应,返回 PageNum<=0 供调用方短路。
120+
func bindPage(c *gin.Context) service.Page {
121+
var page service.Page
122+
if err := c.ShouldBindQuery(&page); err != nil {
123+
response.FailCode(c, apperr.CodeMCAInvalidRequest, "分页参数错误")
124+
return service.Page{}
125+
}
126+
if page.PageNum <= 0 {
127+
page.PageNum = 1
128+
}
129+
if page.PageSize <= 0 || page.PageSize > 100 {
130+
page.PageSize = 20
131+
}
132+
return page
133+
}

‎api/handler/match_test.go‎

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,25 +42,17 @@ type fakeMatchService struct {
4242
lastUID int64
4343
lastInput service.TeamReportInput
4444
reportErr error // 非 nil 时 Report 返回该错误
45+
replayed bool // Report 第二返回值(game_id 幂等重放)
4546
}
4647

47-
func (f *fakeMatchService) Report(_ context.Context, uid int64, in service.TeamReportInput) (*service.Match, error) {
48+
func (f *fakeMatchService) Report(_ context.Context, uid int64, in service.TeamReportInput) (*service.Match, bool, error) {
4849
f.reportCalls++
4950
f.lastUID = uid
5051
f.lastInput = in
5152
if f.reportErr != nil {
52-
return nil, f.reportErr
53+
return nil, false, f.reportErr
5354
}
54-
return &service.Match{ID: 42, MatchType: in.MatchType}, nil
55-
}
56-
57-
func (f *fakeMatchService) ReportVirtual(_ context.Context, uid int64, in service.VirtualReportInput) (*service.VirtualMatchResult, error) {
58-
f.reportCalls++
59-
f.lastUID = uid
60-
if f.reportErr != nil {
61-
return nil, f.reportErr
62-
}
63-
return &service.VirtualMatchResult{Match: service.Match{ID: 43, MatchType: in.MatchType, Source: service.MatchSourceVirtual}}, nil
55+
return &service.Match{ID: 42, MatchType: in.MatchType}, f.replayed, nil
6456
}
6557

6658
func (f *fakeMatchService) GetByID(context.Context, int64) (*service.Match, error) {
@@ -78,7 +70,7 @@ func newMatchRouter(v auth.Verifier, svc service.MatchService) *gin.Engine {
7870
r.Use(middleware.RequestID())
7971
api := r.Group("/api")
8072
api.Use(middleware.Auth(v))
81-
h := handler.NewMatchHandler(svc, true)
73+
h := handler.NewMatchHandler(svc)
8274
api.POST("/matches", h.Report)
8375
return r
8476
}
@@ -92,12 +84,18 @@ const validReportBody = `{
9284
"finished_at": "2026-11-05T10:10:00Z"
9385
}`
9486

87+
// newScopeVerifier 覆盖 scope 与 OPS 两个维度的令牌矩阵:
88+
// - tok-report:OPS 级 + match:report scope(允许上报)
89+
// - tok-report-player:玩家令牌持 match:report scope 但非 OPS(拒绝)
90+
// - tok-plain:普通玩家(拒绝)
91+
// - tok-maintenance:运维令牌(OPS,maintenance 穿透 scope)
9592
func newScopeVerifier() *fakeVerifier {
9693
return &fakeVerifier{
9794
results: map[string]*auth.TokenResult{
98-
"tok-report": {UID: 7, Scopes: []string{"user.read", "match:report"}},
99-
"tok-plain": {UID: 8, Scopes: []string{"user.read"}},
100-
"tok-maintenance": {UID: 9, Scopes: []string{"maintenance"}},
95+
"tok-report": {UID: 7, Scopes: []string{"user.read", "match:report"}, Ops: true},
96+
"tok-report-player": {UID: 10, Scopes: []string{"match:report"}, Ops: false},
97+
"tok-plain": {UID: 8, Scopes: []string{"user.read"}},
98+
"tok-maintenance": {UID: 9, Scopes: []string{"maintenance"}, Ops: true},
10199
},
102100
errs: map[string]error{
103101
"tok-expired": auth.ErrTokenExpired,
@@ -139,11 +137,12 @@ func assertEnvelope(t *testing.T, w *httptest.ResponseRecorder) string {
139137
return env.Code
140138
}
141139

142-
// TestMatchReportScopeMatrix 覆盖受保护组 POST /api/matches 的
143-
// scope 矩阵:有/无 match:report、maintenance 全权、过期/无效令牌、
144-
// 缺令牌、错误载荷(契约 matchcorearena-business.yaml)。
140+
// TestMatchReportScopeMatrix 覆盖 POST /api/matches(唯一上报入口)的
141+
// scope + OPS 矩阵:OPS 且持 match:report 放行、玩家令牌一律拒绝
142+
//(即使持有 scope)、maintenance 全权、过期/无效/缺令牌、错误载荷
143+
//(契约 matchcorearena-business.yaml)。
145144
func TestMatchReportScopeMatrix(t *testing.T) {
146-
t.Run("with match:report scope succeeds", func(t *testing.T) {
145+
t.Run("ops credential with match:report scope succeeds", func(t *testing.T) {
147146
svc := &fakeMatchService{}
148147
r := newMatchRouter(newScopeVerifier(), svc)
149148

@@ -162,6 +161,32 @@ func TestMatchReportScopeMatrix(t *testing.T) {
162161
}
163162
})
164163

164+
t.Run("idempotent replay answers 200", func(t *testing.T) {
165+
svc := &fakeMatchService{replayed: true}
166+
r := newMatchRouter(newScopeVerifier(), svc)
167+
168+
w := doMatch(t, r, "tok-report", validReportBody)
169+
if w.Code != http.StatusOK {
170+
t.Fatalf("status = %d, want 200 for a game_id replay (body=%s)", w.Code, w.Body.String())
171+
}
172+
})
173+
174+
t.Run("player token with match:report scope is rejected 403", func(t *testing.T) {
175+
svc := &fakeMatchService{}
176+
r := newMatchRouter(newScopeVerifier(), svc)
177+
178+
w := doMatch(t, r, "tok-report-player", validReportBody)
179+
if w.Code != http.StatusForbidden {
180+
t.Fatalf("status = %d, want 403 (body=%s)", w.Code, w.Body.String())
181+
}
182+
if code := assertEnvelope(t, w); code != "oauth_insufficient_scope" {
183+
t.Fatalf("code = %q, want oauth_insufficient_scope", code)
184+
}
185+
if svc.reportCalls != 0 {
186+
t.Errorf("Report must not be called for a non-OPS token, got %d calls", svc.reportCalls)
187+
}
188+
})
189+
165190
t.Run("without match:report scope is rejected 403", func(t *testing.T) {
166191
svc := &fakeMatchService{}
167192
r := newMatchRouter(newScopeVerifier(), svc)

‎api/handler/matchmaking.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,13 @@ func NewMatchmakingHandler(svc service.MatchmakingService) *MatchmakingHandler {
2222
// joinInput POST /api/matchmaking/join 请求体。
2323
type joinInput struct {
2424
MatchType string `json:"match_type" binding:"required"`
25+
// PartyMembers 可选成员 UUID 列表(与运维台字段同名同义);
26+
// 非空时以队为单位整体入队。
27+
PartyMembers []string `json:"party_members"`
2528
}
2629

2730
// Join POST /api/matchmaking/join
31+
// 返回本次入队的全部队列条目(单人 1 条,队伍整队多条)。
2832
func (h *MatchmakingHandler) Join(c *gin.Context) {
2933
uid := middleware.GetUID(c)
3034

@@ -34,12 +38,12 @@ func (h *MatchmakingHandler) Join(c *gin.Context) {
3438
return
3539
}
3640

37-
entry, err := h.svc.Join(c.Request.Context(), uid, body.MatchType)
41+
entries, err := h.svc.Join(c.Request.Context(), uid, body.MatchType, body.PartyMembers)
3842
if err != nil {
3943
response.Fail(c, "加入匹配队列失败", err)
4044
return
4145
}
42-
response.Created(c, "已加入匹配队列", entry)
46+
response.Created(c, "已加入匹配队列", entries)
4347
}
4448

4549
// Leave DELETE /api/matchmaking/leave

0 commit comments

Comments
 (0)