Răsfoiți Sursa

feat(S-cfc-327): child.game.reportScore 小游戏成绩上报契约落地(异常分数拦截 SC-C-03/G-09 + 上报幂等 SC-C-02)

E2E Test Bot 4 zile în urmă
părinte
comite
a0a1af162d

+ 73 - 37
cfc-backend/src/main/java/com/etotem/cfc/service/MiniGameService.java

@@ -42,6 +42,18 @@ public class MiniGameService implements MiniGameServiceInterface {
     @Resource
     private ContentDimensionThresholdService contentDimensionThresholdService;
 
+    /** 契约合法分数区间(SC-C-03 / G-09):score 越界拒绝发分,防巨额积分污染 Redis 排行榜 */
+    private static final int SCORE_MIN = 0;
+    private static final int SCORE_MAX = 100;
+    /** 成绩上报幂等窗口(毫秒):同一局(memberId+gameCode+completionTime+score)在窗口内重复上报仅发一次分(SC-C-02 / G-09) */
+    private static final long REPORT_DEDUP_WINDOW_MS = 30_000L;
+    /** JVM 内成绩上报登记表:dedupKey → Object[]{首次结果Map, 登记时间戳}(不依赖 DB 事务提交时机,参考 TaskService SC-P-10 幂等模式) */
+    private final java.util.concurrent.ConcurrentHashMap<String, Object[]> RECENT_REPORTS =
+            new java.util.concurrent.ConcurrentHashMap<>();
+    /** 按上报去重键持有的 JVM 内锁,保证并发双发时 check-then-insert 原子性 */
+    private final java.util.concurrent.ConcurrentHashMap<String, Object> REPORT_DEDUP_LOCKS =
+            new java.util.concurrent.ConcurrentHashMap<>();
+
     /**
      * 获取所有启用的小游戏(无家庭上下文 → fail-open 全保留)
      */
@@ -120,48 +132,72 @@ public class MiniGameService implements MiniGameServiceInterface {
      */
     @Transactional
     public Map<String, Object> completeGame(Long memberId, String gameCode, Integer completionTime, Integer score) {
-        MiniGame game = getGameByCode(gameCode);
-        if (game == null) {
-            throw new RuntimeException("游戏不存在");
+        // SC-C-03 / G-09:异常分数拦截(score 越界 → 拒绝发分,防巨额积分污染 Redis 排行榜)
+        if (score != null && (score < SCORE_MIN || score > SCORE_MAX)) {
+            throw new IllegalArgumentException(
+                    "分数不合法: score=" + score + " 超出合法区间 [" + SCORE_MIN + "," + SCORE_MAX
+                            + "],拒绝发分(SC-C-03 异常分数拦截 / G-09)");
         }
 
-        FamilyMember child = familyMemberMapper.selectById(memberId);
-        if (child == null) {
-            throw new RuntimeException("成员不存在");
-        }
+        // SC-C-02 / G-09:成绩上报幂等(同一局重复上报 → 不重复发分/写流水/写记录)
+        String dedupKey = reportDedupKey(memberId, gameCode, completionTime, score);
+        Object lock = REPORT_DEDUP_LOCKS.computeIfAbsent(dedupKey, k -> new Object());
+        synchronized (lock) {
+            Object[] prior = RECENT_REPORTS.get(dedupKey);
+            if (prior != null && System.currentTimeMillis() - (Long) prior[1] < REPORT_DEDUP_WINDOW_MS) {
+                MiniGameService.log.info("成绩上报幂等命中(key={}),同一局重复上报不重复发分/写流水/写记录", dedupKey);
+                return (Map<String, Object>) prior[0];
+            }
+
+            MiniGame game = getGameByCode(gameCode);
+            if (game == null) {
+                throw new RuntimeException("游戏不存在");
+            }
+
+            FamilyMember child = familyMemberMapper.selectById(memberId);
+            if (child == null) {
+                throw new RuntimeException("成员不存在");
+            }
+
+            // 计算积分
+            int basePoints = game.getDefaultPoints() != null ? game.getDefaultPoints() : 5;
+            int earnedPoints = calculatePoints(gameCode, basePoints, completionTime, score);
 
-        // 计算积分
-        int basePoints = game.getDefaultPoints() != null ? game.getDefaultPoints() : 5;
-        int earnedPoints = calculatePoints(gameCode, basePoints, completionTime, score);
-
-        // 更新家庭成员积分
-        child.setTotalPoints(child.getTotalPoints() + earnedPoints);
-        child.setUpdatedAt(new Date());
-        familyMemberMapper.updateById(child);
-
-        // 记录积分流水
-        PointsLog log = new PointsLog();
-        log.setMemberId(memberId);
-        log.setAmount(earnedPoints);
-        log.setType("earn");
-        log.setDescription("完成游戏: " + game.getGameName());
-        log.setCreatedAt(new Date());
-        pointsLogMapper.insert(log);
-
-        // 持久化游戏记录
-        try {
-            gameRecordService.saveRecord(memberId, gameCode, completionTime, score, "medium", earnedPoints);
-        } catch (Exception e) {
-            MiniGameService.log.warn("保存游戏记录失败: {}", e.getMessage());
+            // 更新家庭成员积分
+            child.setTotalPoints(child.getTotalPoints() + earnedPoints);
+            child.setUpdatedAt(new Date());
+            familyMemberMapper.updateById(child);
+
+            // 记录积分流水
+            PointsLog log = new PointsLog();
+            log.setMemberId(memberId);
+            log.setAmount(earnedPoints);
+            log.setType("earn");
+            log.setDescription("完成游戏: " + game.getGameName());
+            log.setCreatedAt(new Date());
+            pointsLogMapper.insert(log);
+
+            // 持久化游戏记录
+            try {
+                gameRecordService.saveRecord(memberId, gameCode, completionTime, score, "medium", earnedPoints);
+            } catch (Exception e) {
+                MiniGameService.log.warn("保存游戏记录失败: {}", e.getMessage());
+            }
+
+            // 返回结果
+            Map<String, Object> result = new HashMap<>();
+            result.put("pointsEarned", earnedPoints);
+            result.put("newBalance", child.getTotalPoints());
+            result.put("gameName", game.getGameName());
+
+            RECENT_REPORTS.put(dedupKey, new Object[]{result, System.currentTimeMillis()});
+            return result;
         }
+    }
 
-        // 返回结果
-        Map<String, Object> result = new HashMap<>();
-        result.put("pointsEarned", earnedPoints);
-        result.put("newBalance", child.getTotalPoints());
-        result.put("gameName", game.getGameName());
-        
-        return result;
+    /** 成绩上报幂等去重键:memberId + gameCode + completionTime + score(同一局重复上报的判别依据) */
+    private String reportDedupKey(Long memberId, String gameCode, Integer completionTime, Integer score) {
+        return memberId + "|" + gameCode + "|" + completionTime + "|" + score;
     }
 
     /**