fix(activity-mutual): close Phase 16 KEEP-VERIFY/EXTEND — 7 defects + 1 hidden compile defect (reopenEpisode) + 1 test-fidelity; unify dual-impl to confirmActivityInterest; INV-006 fix; +7 tests (481 green)

This commit is contained in:
WorkBuddy
2026-09-17 16:47:10 +08:00
parent 29112eed6e
commit 556f95a562
16 changed files with 638 additions and 71 deletions
@@ -23,6 +23,10 @@ public class ActivityMutualConsent extends BaseEntity {
private String userAStatus;
/** B的同意状态:pending / accepted / declined */
private String userBStatus;
/** 双方都同意时的时间戳 */
/** 双方都同意时的时间戳(非 NULL 即代表已双确认,exactly-once 的判定依据) */
private Instant bothConfirmedAt;
/** 二阶段同意截止时间(V041);NULL 表示不限制。超时后不能再推动成双确认 */
private Instant expiresAt;
/** 双确认形成的 Match Episode id(V041),仅用于溯源 */
private String matchId;
}
@@ -5,6 +5,7 @@ import com.danyang.match.platform.activity_mutual.entity.ActivityMutualConsent;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
import java.util.Optional;
@@ -12,20 +13,76 @@ import java.util.Optional;
@Mapper
public interface ActivityMutualConsentMapper extends BaseMapper<ActivityMutualConsent> {
// Phase 16 修复:以下查询此前全部缺少 deleted_at IS NULL。
// V037 已为该表补上 deleted_at,软删后的同意记录仍会被检出,
// 导致已作废的互选关系继续参与判断。
@Select("SELECT * FROM activity_mutual_connection_consents " +
"WHERE activity_id = #{activityId} " +
"AND ((user_a_id = #{userId} AND user_b_id = #{partnerId}) " +
"OR (user_a_id = #{partnerId} AND user_b_id = #{userId})) " +
"AND deleted_at IS NULL " +
"LIMIT 1")
Optional<ActivityMutualConsent> findByActivityPair(@Param("activityId") String activityId,
@Param("userId") String userId,
@Param("partnerId") String partnerId);
@Select("SELECT * FROM activity_mutual_connection_consents " +
"WHERE activity_id = #{activityId} AND user_a_status = 'accepted' AND user_b_status = 'accepted'")
"WHERE activity_id = #{activityId} AND user_a_status = 'accepted' AND user_b_status = 'accepted' " +
"AND deleted_at IS NULL")
List<ActivityMutualConsent> findBothConfirmedByActivity(String activityId);
@Select("SELECT * FROM activity_mutual_connection_consents " +
"WHERE (user_a_id = #{userId} OR user_b_id = #{userId}) AND user_a_status = 'accepted' AND user_b_status = 'accepted'")
"WHERE (user_a_id = #{userId} OR user_b_id = #{userId}) " +
"AND user_a_status = 'accepted' AND user_b_status = 'accepted' " +
"AND deleted_at IS NULL")
List<ActivityMutualConsent> findBothConfirmedByUser(String userId);
/**
* 原子确认本方(Phase 16 核心)。
*
* <p>单条 SQL 内完成三件事,避免「先读后写」在并发下丢更新:
* <ol>
* <li>只把「调用方所在侧」置为 accepted(CASE WHEN 定位本侧);</li>
* <li>若两侧因此都变成 accepted,则同一语句写入 both_confirmed_at = NOW();</li>
* <li>WHERE 同时要求:未软删、尚未双确认、未过期、本侧当前为 pending。</li>
* </ol>
*
* <p><b>exactly-once 依据</b>:把 both_confirmed_at 从 NULL 改成非 NULL 只能有一个事务成功
* (其它并发事务的 WHERE both_confirmed_at IS NULL 不再成立),
* 因此只有 affectedRows == 1 且回读 both_confirmed_at != null 的那一方负责创建 Match。
*
* @return 受影响行数:1 = 本次写入生效;0 = 已双确认 / 本方已表态 / 已过期 / 已软删
*/
@Update("UPDATE activity_mutual_connection_consents SET " +
" user_a_status = CASE WHEN user_a_id = #{userId} THEN 'accepted' ELSE user_a_status END, " +
" user_b_status = CASE WHEN user_b_id = #{userId} THEN 'accepted' ELSE user_b_status END, " +
" both_confirmed_at = CASE WHEN " +
" (CASE WHEN user_a_id = #{userId} THEN 'accepted' ELSE user_a_status END) = 'accepted' " +
" AND (CASE WHEN user_b_id = #{userId} THEN 'accepted' ELSE user_b_status END) = 'accepted' " +
" THEN NOW() ELSE NULL END, " +
" updated_at = NOW() " +
"WHERE id = #{id} AND deleted_at IS NULL " +
" AND both_confirmed_at IS NULL " +
" AND (expires_at IS NULL OR expires_at > NOW()) " +
" AND CASE WHEN user_a_id = #{userId} THEN user_a_status ELSE user_b_status END = 'pending'")
int confirmSideIfPending(@Param("id") String id, @Param("userId") String userId);
/**
* 原子拒绝本方。declined 是终态:本侧一旦 declined 就不再接受后续 confirm
* (WHERE 里的 pending 条件保证),如需重新开启必须走运营重置或重新互选。
*/
@Update("UPDATE activity_mutual_connection_consents SET " +
" user_a_status = CASE WHEN user_a_id = #{userId} THEN 'declined' ELSE user_a_status END, " +
" user_b_status = CASE WHEN user_b_id = #{userId} THEN 'declined' ELSE user_b_status END, " +
" updated_at = NOW() " +
"WHERE id = #{id} AND deleted_at IS NULL " +
" AND both_confirmed_at IS NULL " +
" AND CASE WHEN user_a_id = #{userId} THEN user_a_status ELSE user_b_status END = 'pending'")
int declineSideIfPending(@Param("id") String id, @Param("userId") String userId);
/** 记录双确认后形成的 Match,便于溯源与幂等回查 */
@Update("UPDATE activity_mutual_connection_consents SET match_id = #{matchId}, updated_at = NOW() " +
"WHERE id = #{id} AND deleted_at IS NULL")
int bindMatch(@Param("id") String id, @Param("matchId") String matchId);
}
@@ -3,10 +3,12 @@ package com.danyang.match.platform.activity_mutual.service;
import com.danyang.match.platform.activity_mutual.dto.MutualInterestResultDTO;
import com.danyang.match.platform.activity_mutual.entity.ActivityMutualConsent;
import com.danyang.match.platform.activity_mutual.mapper.ActivityMutualConsentMapper;
import com.danyang.match.platform.relationship.service.RelationshipService;
import com.danyang.match.platform.shared.constant.Constants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
@@ -17,7 +19,7 @@ import java.util.*;
public class ActivityMutualConsentService {
private final ActivityMutualConsentMapper consentMapper;
private final com.danyang.match.platform.match.mapper.MatchMapper matchMapper;
private final RelationshipService relationshipService;
public List<MutualInterestResultDTO> detectMutualResults(String activityId) {
List<ActivityMutualConsent> bothConfirmed = consentMapper.findBothConfirmedByActivity(activityId);
@@ -47,32 +49,60 @@ public class ActivityMutualConsentService {
return consent;
}
@Transactional
public Map<String, Object> confirmConnection(String userId, String activityId, String partnerId) {
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
.orElseThrow(() -> new RuntimeException("没有找到该活动的互选记录"));
if (userId.equals(consent.getUserAId())) {
consent.setUserAStatus(Constants.MUTUAL_CONSENT_STATUS_ACCEPTED);
} else {
consent.setUserBStatus(Constants.MUTUAL_CONSENT_STATUS_ACCEPTED);
}
consent.setUpdatedAt(Instant.now());
consentMapper.updateById(consent);
// 原子确认本方(Phase 16 核心):仅当本方 pending、未过期、未软删时写入 accepted,
// 并借助 both_confirmed_at 从 NULL→非NULL 的原子 UPDATE 实现 exactly-once。
// return 1 表示该事务是「把双确认落定」的那一方。
int affected = consentMapper.confirmSideIfPending(consent.getId(), userId);
// 回读权威状态(可能受并发另一方提交影响)
consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
.orElseThrow(() -> new RuntimeException("互选记录已不存在"));
boolean aAccepted = Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserAStatus());
boolean bAccepted = Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserBStatus());
boolean amA = userId.equals(consent.getUserAId());
Map<String, Object> result = new HashMap<>();
result.put("myStatus", userId.equals(consent.getUserAId()) ? (aAccepted ? "accepted" : "pending") : (bAccepted ? "accepted" : "pending"));
result.put("partnerStatus", userId.equals(consent.getUserAId()) ? (bAccepted ? "accepted" : "pending") : (aAccepted ? "accepted" : "pending"));
result.put("myStatus", amA ? (aAccepted ? "accepted" : "pending") : (bAccepted ? "accepted" : "pending"));
result.put("partnerStatus", amA ? (bAccepted ? "accepted" : "pending") : (aAccepted ? "accepted" : "pending"));
if (aAccepted && bAccepted) {
consent.setBothConfirmedAt(Instant.now());
consentMapper.updateById(consent);
result.put("bothConfirmed", true);
log.info("双方确认活动互选: activityId={}, userA={}, userB={}", activityId, consent.getUserAId(), consent.getUserBId());
// exactly-once 赢家(本次 confirmSideIfPending 翻转 both_confirmed_at 的一方)负责建 Match + 开启会话。
// 另一方即使随后也进入该分支,affected==0,不会重复建 Match(confirmActivityInterest 本身亦幂等复用)。
if (affected == 1 && consent.getBothConfirmedAt() != null) {
createMatchAndConversation(consent);
}
result.put("matchCreated", true);
} else {
result.put("bothConfirmed", false);
result.put("matchCreated", false);
}
return result;
}
/**
* 双确认后形成 Match 并开启 Conversation(Gate:互选确认后双方可沟通)。
* 通过统一的 {@code RelationshipService.confirmActivityInterest} 完成,避免「双实现」:
* 该方法负责 active Match 复用 / 历史 Unmatch 开新 Episode / source=activity_mutual /
* 显式开启会话,全部集中在一处。
*/
private void createMatchAndConversation(ActivityMutualConsent consent) {
Map<String, Object> matchResult = relationshipService.confirmActivityInterest(
consent.getUserAId(), consent.getUserBId());
Object matchIdObj = matchResult.get("matchId");
if (matchIdObj != null) {
consentMapper.bindMatch(consent.getId(), String.valueOf(matchIdObj));
}
log.info("活动互选双确认后形成Match并开启会话: activityId={}, userA={}, userB={}, matchId={}",
consent.getActivityId(), consent.getUserAId(), consent.getUserBId(), matchIdObj);
}
public Map<String, Object> declineConnection(String userId, String activityId, String partnerId) {
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userId, partnerId)
.orElseThrow(() -> new RuntimeException("没有找到该活动的互选记录"));
@@ -89,10 +119,6 @@ public class ActivityMutualConsentService {
return result;
}
public boolean hasActiveMatch(String userId, String partnerId) {
return matchMapper.findActiveMatch(userId, partnerId).isPresent();
}
public List<MutualInterestResultDTO> getMyMutualResults(String userId) {
List<ActivityMutualConsent> consents = consentMapper.findBothConfirmedByUser(userId);
return consents.stream().map(c -> toResultDTO(c, c.getActivityId())).toList();
@@ -108,8 +134,11 @@ public class ActivityMutualConsentService {
ActivityMutualConsent consent = consentOpt.get();
boolean myAccepted = (userId.equals(consent.getUserAId()) && Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserAStatus()))
|| (userId.equals(consent.getUserBId()) && Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserBStatus()));
boolean partnerAccepted = (userId.equals(consent.getUserAId()) && Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserBStatus()))
boolean partnerSideAccepted = (userId.equals(consent.getUserAId()) && Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserBStatus()))
|| (userId.equals(consent.getUserBId()) && Constants.MUTUAL_CONSENT_STATUS_ACCEPTED.equals(consent.getUserAStatus()));
// INV-006 单向意向保密:只有本侧也已确认,才允许回显对方是否已确认。
// 否则 A 已确认、B 未确认时,B 能通过此接口探知 A 的意向,违反「单向意向不暴露」。
boolean partnerAccepted = myAccepted && partnerSideAccepted;
Map<String, Object> result = new HashMap<>();
result.put("exists", true);
result.put("myStatus", myAccepted ? "accepted" : "pending");
@@ -5,6 +5,7 @@ import com.danyang.match.platform.match.entity.Match;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
import java.util.Optional;
@@ -53,4 +54,19 @@ public interface MatchMapper extends BaseMapper<Match> {
/** 活跃 Match 数(带软删过滤) */
@Select("SELECT COUNT(*) FROM matches WHERE (user_a_id = #{userId} OR user_b_id = #{userId}) AND status IN ('active', 'getting_to_know') AND deleted_at IS NULL")
int countActiveMatches(String userId);
/**
* 历史 Unmatch 复用行开启新 Episode(Phase 16 修复 D4 必崩路径)。
*
* <p>生产 {@code uk_match_pair UNIQUE(user_a_id, user_b_id)} 决定同一对用户只能存在一行。
* 此前该场景走 INSERT → 抛 DuplicateKeyException(500),AGENTS.md #20「历史 Unmatch 则创建新 Episode」
* 在生产上根本不可用。改为复用同一行、递增 episode、状态回到 active。
*
* <p>乐观锁:仅当该行仍为 {@code unmatched} 时才更新;若并发下已被改(如另一方已抢先 reopen),
* 命中 0 行 → 调用方抛出重试。
*/
@Update("UPDATE matches SET status = 'active', source = #{source}, episode = #{episode}, " +
"matched_at = NOW(), last_activity_at = NOW(), unmatched_at = NULL, updated_at = NOW() " +
"WHERE id = #{id} AND status = 'unmatched' AND deleted_at IS NULL")
int reopenEpisode(@Param("id") String id, @Param("episode") int episode, @Param("source") String source);
}
@@ -192,9 +192,10 @@ public class RelationshipService {
/**
* 创建双向匹配(事务)
* @param autoCreateConversation 是否自动创建会话(V1.1: 活动互选不自动创建)
* @param autoCreateConversation 是否自动创建会话(V1.1: 活动互选不自动创建,由调用方在双确认后显式开启)
* @return 新建或复用的 Match(V1.1 Phase 16: 返回以便调用方开启会话/溯源)
*/
private void createMatch(String userId, String targetUserId, String source, boolean autoCreateConversation) {
private Match createMatch(String userId, String targetUserId, String source, boolean autoCreateConversation) {
// 标准化user_a/user_b顺序
String userA = userId.compareTo(targetUserId) < 0 ? userId : targetUserId;
String userB = userId.compareTo(targetUserId) < 0 ? targetUserId : userId;
@@ -207,10 +208,7 @@ public class RelationshipService {
}
// Phase 12 复验修复(D5):本方法此前不设置 episode / lastActivityAt,
// 而另一条创建路径 MatchService.createOrReuseMatch 会设置 —— 两条路径字段填充不一致:
// · episode 为 null → 后续 MatchService.createOrReuseMatch 里
// `m.getEpisode() + 1` 会对 null 自动拆箱抛 NPE;
// · lastActivityAt 为 null → 沉默期服务建议(RelationshipStageService)失效。
// 而另一条创建路径 MatchService.createOrReuseMatch 会设置 —— 两条路径字段填充不一致。
// 统一按 AGENTS.md #20 推导 episode:prior Unmatch → prior.episode + 1,否则 1。
int episode = 1;
Match prior = matchMapper.findLatestMatch(userId, targetUserId).orElse(null);
@@ -219,33 +217,55 @@ public class RelationshipService {
episode = (priorEpisode == null ? 1 : priorEpisode) + 1;
}
Match match = new Match();
match.setUserAId(userA);
match.setUserBId(userB);
match.setStatus(Constants.MATCH_STATUS_ACTIVE);
match.setSource(source);
match.setMatchedAt(Instant.now());
match.setLastActivityAt(Instant.now());
match.setEpisode(episode);
matchMapper.insert(match);
// V1.1: 活动互选不自动创建Conversation,需双方确认后由confirmActivityInterest处理
if (autoCreateConversation) {
try {
chatService.getOrCreateConversation(match.getId(), userId, targetUserId);
log.info("Match后自动创建会话: matchId={}, users={}", match.getId(), userId + "," + targetUserId);
} catch (Exception e) {
log.warn("创建会话失败,Match已创建但聊天可能不可用: matchId={}, error={}",
match.getId(), e.toString(), e);
Match match;
if (prior != null && Constants.MATCH_STATUS_UNMATCHED.equals(prior.getStatus())) {
// Phase 16 修复(D1,必崩):生产 uk_match_pair UNIQUE(user_a_id, user_b_id)
// 决定同一对用户只能存在一行。此前这里走 INSERT → prior Unmatch 场景必定
// 抛 DuplicateKeyException(500),AGENTS.md #20「历史 Unmatch 则创建新 Episode」
// 在生产上根本不可用。测试库此前也缺该 UNIQUE,所以零覆盖。
// 正确语义:复用同一行、递增 episode、状态回到 active。
int reopened = matchMapper.reopenEpisode(prior.getId(), episode, source);
if (reopened == 0) {
throw new IllegalStateException("匹配状态已变更,请重试");
}
prior.setStatus(Constants.MATCH_STATUS_ACTIVE);
prior.setSource(source);
prior.setEpisode(episode);
prior.setMatchedAt(Instant.now());
prior.setLastActivityAt(Instant.now());
prior.setUnmatchedAt(null);
match = prior;
log.info("历史 Unmatch 复用行开启新 Episode: matchId={}, episode={}", match.getId(), episode);
} else {
match = new Match();
match.setUserAId(userA);
match.setUserBId(userB);
match.setStatus(Constants.MATCH_STATUS_ACTIVE);
match.setSource(source);
match.setMatchedAt(Instant.now());
match.setLastActivityAt(Instant.now());
match.setEpisode(episode);
matchMapper.insert(match);
}
// V1.1: 活动互选不自动创建Conversation,需双方确认后由confirmActivityInterest处理
if (autoCreateConversation) {
try {
chatService.getOrCreateConversation(match.getId(), userId, targetUserId);
log.info("Match后自动创建会话: matchId={}, users={}", match.getId(), userId + "," + targetUserId);
} catch (Exception e) {
log.warn("创建会话失败,Match已创建但聊天可能不可用: matchId={}, error={}",
match.getId(), e.toString(), e);
}
}
return match;
}
}
/**
* 重载:默认自动创建Conversation(保持原有行为)
*/
private void createMatch(String userId, String targetUserId, String source) {
createMatch(userId, targetUserId, source, true);
private Match createMatch(String userId, String targetUserId, String source) {
return createMatch(userId, targetUserId, source, true);
}
/**
@@ -263,6 +283,7 @@ public class RelationshipService {
result.put("matchReused", true);
result.put("matchId", existingMatch.get().getId());
result.put("status", existingMatch.get().getStatus());
result.put("conversationAutoCreated", true);
log.info("活动互选复用已有Match: userId={}, partnerId={}, matchId={}", userId, partnerId, existingMatch.get().getId());
return result;
}
@@ -273,14 +294,24 @@ public class RelationshipService {
&& Constants.MATCH_STATUS_UNMATCHED.equals(priorUnmatch.get().getStatus());
// 3. 创建新 Match Episode(source=activity_mutual,不自动创建 Conversation)
createMatch(userId, partnerId, Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, false);
Match match = createMatch(userId, partnerId, Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, false);
// V1.1 Phase 16 修复(Gate:互选确认后双方可沟通):双确认后必须开启会话。
// 此前此处未建会话,仅靠首条消息惰性创建,导致「双方可沟通」的入口不可见。
// 现显式开启,保证互选成功后聊天入口立即可见。
try {
chatService.getOrCreateConversation(match.getId(), match.getUserAId(), match.getUserBId());
} catch (Exception e) {
log.warn("活动互选开启会话失败(Match 已创建): matchId={}, error={}", match.getId(), e.toString(), e);
}
Map<String, Object> result = new HashMap<>();
result.put("matchCreated", true);
result.put("matchId", match.getId());
result.put("priorUnmatch", priorUnmatchExists);
result.put("conversationAutoCreated", false); // V1.1: 不自动创建Conversation
log.info("活动互选创建新Match Episode: userId={}, partnerId={}, priorUnmatch={}",
userId, partnerId, priorUnmatchExists);
result.put("conversationAutoCreated", true);
log.info("活动互选创建新Match Episode: userId={}, partnerId={}, priorUnmatch={}, matchId={}",
userId, partnerId, priorUnmatchExists, match.getId());
return result;
}
@@ -0,0 +1,25 @@
-- ============================================================
-- V041: V1.1 Phase 16 - 活动互选二阶段同意补全
-- ============================================================
-- 目的:
-- 1) expires_at —— 二阶段同意的截止时间(Phase 16 计划「补 timeout 测试」)。
-- 互选确认不能无限期挂起:超时后双方都必须重新确认,避免长期 pending
-- 记录被后续某一方单点确认直接推动成 Match(INV-015 要求双方确认)。
-- 2) match_id —— 双确认后形成的 Match Episode 溯源字段。
-- exactly-once 由「both_confirmed_at 从 NULL 变为非 NULL 的原子 UPDATE」保证,
-- match_id 只用于回查与审计,不作为唯一性依据。
ALTER TABLE activity_mutual_connection_consents
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
ALTER TABLE activity_mutual_connection_consents
ADD COLUMN IF NOT EXISTS match_id UUID;
COMMENT ON COLUMN activity_mutual_connection_consents.expires_at IS
'二阶段同意截止时间;为 NULL 表示不限制。超过该时间的 pending/accepted 不得再推动成双确认。';
COMMENT ON COLUMN activity_mutual_connection_consents.match_id IS
'双确认后形成的 Match Episode id;仅用于溯源,唯一性由 both_confirmed_at 原子更新保证。';
CREATE INDEX IF NOT EXISTS idx_mutual_consents_expiry
ON activity_mutual_connection_consents(expires_at)
WHERE both_confirmed_at IS NULL;
@@ -0,0 +1,210 @@
package com.danyang.match.platform.activity_mutual;
import com.danyang.match.platform.activity_mutual.entity.ActivityMutualConsent;
import com.danyang.match.platform.activity_mutual.mapper.ActivityMutualConsentMapper;
import com.danyang.match.platform.activity_mutual.service.ActivityMutualConsentService;
import com.danyang.match.platform.chat.mapper.ConversationMapper;
import com.danyang.match.platform.match.entity.Match;
import com.danyang.match.platform.match.mapper.MatchMapper;
import com.danyang.match.platform.shared.constant.Constants;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
/**
* Phase 16:活动互选二阶段同意 —— 真实运行时路径测试。
*
* <p><b>测试保真度</b>:走真实 Service + 真实落库;测试库 {@code schema-h2.sql} 已补齐
* {@code activity_mutual_connection_consents} 表(含 deleted_at / expires_at / match_id 与
* chk_consent_status),此前该表完全缺失 → 互选核心路径零覆盖(只能写假测试)。
*
* <p>覆盖 Gate:
* <ol>
* <li>双确认后必须形成 Match + 开启 Conversation(此前双确认只打日志,根本不建 Match,Gate 失败);</li>
* <li>单向意向保密(INV-006):A 已确认而 B 未确认时,B 不得探知 A 的意向;</li>
* <li>decline 不建 Match;幂等重确认不重复建 Match;超时 expires_at 后确认被拒;</li>
* <li>软删过滤:已软删的同意记录不参与判断;</li>
* <li>复用已有 active Match(AGENTS.md #19):双方确认后不创建新 Match,引导已有聊天。</li>
* </ol>
*/
@SpringBootTest
@ActiveProfiles("test")
@Transactional
class ActivityMutualConsentServiceTest {
@Autowired
private ActivityMutualConsentService consentService;
@Autowired
private ActivityMutualConsentMapper consentMapper;
@Autowired
private MatchMapper matchMapper;
@Autowired
private ConversationMapper conversationMapper;
@MockBean
private StringRedisTemplate redisTemplate;
private String activityId;
private String userA;
private String userB;
@BeforeEach
void setup() {
activityId = UUID.randomUUID().toString();
userA = UUID.randomUUID().toString();
userB = UUID.randomUUID().toString();
}
@Test
@DisplayName("Gate: 双确认后形成 Match 并开启 Conversation(此前只打日志,Gate 失败)")
void doubleConfirmCreatesMatchAndConversation() {
// 第一阶段:建立互选同意记录(二阶段同意)
consentService.createMutualConsent(activityId, userA, userB);
// A 单方确认:不应形成 Match
Map<String, Object> r1 = consentService.confirmConnection(userA, activityId, userB);
assertFalse((Boolean) r1.get("bothConfirmed"));
assertFalse((Boolean) r1.get("matchCreated"));
assertTrue(matchMapper.findActiveMatch(userA, userB).isEmpty(),
"单方确认不应产生 Match");
// B 确认:双方都已确认 → 必须形成 Match + 开启会话
Map<String, Object> r2 = consentService.confirmConnection(userB, activityId, userA);
assertTrue((Boolean) r2.get("bothConfirmed"));
assertTrue((Boolean) r2.get("matchCreated"));
Match match = matchMapper.findActiveMatch(userA, userB)
.orElseThrow(() -> new AssertionError("双确认后必须存在 active Match"));
assertEquals(Constants.MATCH_STATUS_ACTIVE, match.getStatus());
assertEquals(Constants.MATCH_SOURCE_ACTIVITY_MUTUAL, match.getSource());
// 会话必须已开启(Gate:互选确认后双方可沟通)
assertTrue(conversationMapper.findByMatchId(match.getId()).isPresent(),
"双确认后必须已开启 Conversation");
// 溯源字段:consent 记录应绑定 match_id
ActivityMutualConsent consent = consentMapper.findByActivityPair(activityId, userA, userB).orElseThrow();
assertNotNull(consent.getMatchId(), "consent 记录应绑定 match_id 用于溯源");
assertEquals(match.getId(), consent.getMatchId());
}
@Test
@DisplayName("INV-006 单向意向保密:A 已确认而 B 未确认时,B 不得探知 A 的意向")
void singleSideIntentionNotExposed() {
consentService.createMutualConsent(activityId, userA, userB);
// 仅 A 确认
consentService.confirmConnection(userA, activityId, userB);
// A 视角:自己已确认,对方(B)未确认
Map<String, Object> aStatus = consentService.getMyConsentStatus(userA, activityId, userB);
assertEquals("accepted", aStatus.get("myStatus"));
assertEquals("pending", aStatus.get("partnerStatus"));
// B 视角:B 尚未确认,绝不能看到 A 已确认(INV-006 核心)—— 修复前此处会泄露为 accepted
Map<String, Object> bStatus = consentService.getMyConsentStatus(userB, activityId, userA);
assertEquals("pending", bStatus.get("myStatus"));
assertEquals("pending", bStatus.get("partnerStatus"),
"INV-006 泄漏:B 未确认却探知了 A 的确认状态");
assertFalse((Boolean) bStatus.get("bothConfirmed"));
}
@Test
@DisplayName("decline 不形成 Match:一方拒绝后双方确认流程终止")
void declinePreventsMatch() {
consentService.createMutualConsent(activityId, userA, userB);
// A 确认、B 拒绝
consentService.confirmConnection(userA, activityId, userB);
Map<String, Object> decline = consentService.declineConnection(userB, activityId, userA);
assertEquals("declined", decline.get("myStatus"));
// 此后即便 A 再确认(已是 accepted 不会再变),也不应产生 Match
assertTrue(matchMapper.findActiveMatch(userA, userB).isEmpty(),
"一方拒绝后不应形成 Match");
}
@Test
@DisplayName("幂等:双方已确认后再重复确认不重复创建 Match")
void idempotentReconfirmDoesNotDuplicateMatch() {
consentService.createMutualConsent(activityId, userA, userB);
consentService.confirmConnection(userA, activityId, userB);
consentService.confirmConnection(userB, activityId, userA);
// 重复确认
consentService.confirmConnection(userA, activityId, userB);
consentService.confirmConnection(userB, activityId, userA);
// active Match 仅一条
assertEquals(1, matchMapper.findActiveMatchesByUser(userA).size(),
"重复确认不应产生多条 Match");
assertTrue(matchMapper.findActiveMatch(userA, userB).isPresent());
}
@Test
@DisplayName("超时:expires_at 过期后确认被拒,both_confirmed_at 不落定")
void expiredConsentRejectsConfirm() {
ActivityMutualConsent consent = consentService.createMutualConsent(activityId, userA, userB);
// 设为已过期
consent.setExpiresAt(Instant.now().minusSeconds(3600));
consentMapper.updateById(consent);
// A 确认:因已过期,confirmSideIfPending 命中 WHERE 条件失败 → 本方不被置为 accepted
Map<String, Object> r = consentService.confirmConnection(userA, activityId, userB);
assertEquals("pending", r.get("myStatus"));
assertFalse((Boolean) r.get("bothConfirmed"));
assertTrue(matchMapper.findActiveMatch(userA, userB).isEmpty(),
"过期互选不应形成 Match");
}
@Test
@DisplayName("软删过滤:已软删的同意记录不参与判断,confirmConnection 视为不存在")
void softDeletedConsentIsFiltered() {
ActivityMutualConsent consent = consentService.createMutualConsent(activityId, userA, userB);
// 软删(BaseEntity 无 @TableLogic,物理 UPDATE deleted_at)
consent.setDeletedAt(Instant.now());
consentMapper.updateById(consent);
// 查询应过滤掉
assertTrue(consentMapper.findByActivityPair(activityId, userA, userB).isEmpty(),
"findByActivityPair 必须过滤软删记录");
// 确认视为记录不存在
assertThrows(RuntimeException.class,
() -> consentService.confirmConnection(userA, activityId, userB));
}
@Test
@DisplayName("复用已有 active Match(AGENTS.md #19):双方确认后不创建新 Match,引导已有聊天")
void reuseExistingActiveMatch() {
// 预先存在一条 active Match(如来自 like)
Match prior = new Match();
prior.setId(UUID.randomUUID().toString());
prior.setUserAId(userA.compareTo(userB) < 0 ? userA : userB);
prior.setUserBId(userA.compareTo(userB) < 0 ? userB : userA);
prior.setStatus(Constants.MATCH_STATUS_ACTIVE);
prior.setSource(Constants.MATCH_SOURCE_USER_LIKE);
prior.setEpisode(1);
prior.setMatchedAt(Instant.now());
prior.setLastActivityAt(Instant.now());
matchMapper.insert(prior);
// 互选双确认
consentService.createMutualConsent(activityId, userA, userB);
consentService.confirmConnection(userA, activityId, userB);
consentService.confirmConnection(userB, activityId, userA);
// 仍只有一条 active Match,且复用的是 prior(不新建、不重复)
Match active = matchMapper.findActiveMatch(userA, userB).orElseThrow();
assertEquals(prior.getId(), active.getId(), "应复用已有 active Match,而非新建");
}
}
@@ -341,7 +341,11 @@ class ChatPhase09IntegrationTest {
assertTrue(body.contains(activityMatch.getId()));
Conversation activityConv = conversationMapper.findByMatchId(activityMatch.getId()).orElseThrow();
assertNotEquals(conv.getId(), activityConv.getId(), "新 Match 应有独立会话");
// AGENTS.md #19/#20:同对用户此前 Unmatch 后由活动互选重连,复用同一 Match 行(episode 递增),
// 会话由 match_id 唯一绑定,因此随之复用。本测试的核心不变量是"活动来源的会话走同一套发送/推送管线",
// 而非"每轮活动互选都新建独立会话"。故此处断言复用而非不等。
assertEquals(conv.getId(), activityConv.getId(),
"AGENTS.md #20:同对用户 Unmatch 后重连复用同一 Match 行与会话");
// 3. 同一套发送 + 推送逻辑对活动来源同样生效
chatService.sendText(activityConv.getId(), userA, "活动认识,你好", "cmid-activity");
@@ -53,7 +53,6 @@ class EntityMigrationParityTest {
*/
private static final Set<String> TEST_SCHEMA_OPTIONAL_TABLES = Set.of(
"activity_interests",
"activity_mutual_connection_consents",
"appeals",
"consent_records",
"content_categories",
@@ -114,7 +113,10 @@ class EntityMigrationParityTest {
// 「取消后重报名」的必崩路径零覆盖;活动工作人员指派表完全不存在 ——
// 签到数据范围无人可测。二者均已补入 schema-h2.sql。
"activity_registrations",
"activity_staff_assignments"
"activity_staff_assignments",
// Phase 16:活动互选二阶段同意表此前在可选白名单(= 无人测),
// 导致双确认→建Match+会话的核心路径零覆盖。已补入 schema-h2.sql。
"activity_mutual_connection_consents"
);
/** BaseEntity 声明的公共列(对照 shared/base/BaseEntity.java)。 */
private static final Set<String> BASE_ENTITY_COLUMNS =
@@ -16,8 +16,8 @@ import static org.junit.jupiter.api.Assertions.*;
class MigrationValidationTest {
// 基线守卫:新增 Flyway 迁移时必须同步递增此值
// Phase 15:V040 活动工作人员指派(activity_staff_assignments,签到数据范围)
private static final int LATEST_MIGRATION = 40;
// Phase 16:V041 活动互选二阶段同意补全(expires_at / match_id 溯源字段)
private static final int LATEST_MIGRATION = 41;
private static final String MIGRATION_DIR =
"backend/src/main/resources/db/migration/";
+23
View File
@@ -33,6 +33,29 @@ CREATE TABLE matches (
-- 测试库若缺此约束,形如 source='liked' 的非法取值会被静默放过,只在 PostgreSQL 上炸。
CONSTRAINT chk_match_source CHECK (source IN ('user_like', 'activity_mutual', 'matchmaker'))
);
-- Phase 16:活动互选二阶段同意表(与 V024 + V037 + V041 生产 DDL 对齐)。
-- 此前完全缺失 → 互选相关路径零覆盖(只能写假测试)。
-- 注意 deleted_at 必须为可空 TIMESTAMP(V037 已为生产表补该列;BaseEntity 逻辑删除依赖它)。
CREATE TABLE activity_mutual_connection_consents (
id VARCHAR(36) PRIMARY KEY,
activity_id VARCHAR(36) NOT NULL,
user_a_id VARCHAR(36) NOT NULL,
user_b_id VARCHAR(36) NOT NULL,
user_a_status VARCHAR(32) NOT NULL DEFAULT 'pending',
user_b_status VARCHAR(32) NOT NULL DEFAULT 'pending',
both_confirmed_at TIMESTAMP WITH TIME ZONE,
expires_at TIMESTAMP WITH TIME ZONE,
match_id VARCHAR(36),
created_at TIMESTAMP WITH TIME ZONE,
updated_at TIMESTAMP WITH TIME ZONE,
deleted_at TIMESTAMP WITH TIME ZONE,
UNIQUE (activity_id, user_a_id, user_b_id),
CONSTRAINT chk_consent_status CHECK (
user_a_status IN ('pending', 'accepted', 'declined')
AND user_b_status IN ('pending', 'accepted', 'declined')
)
);
CREATE TABLE relationship_success_requests (
id VARCHAR(36) PRIMARY KEY, match_id VARCHAR(36), initiated_by VARCHAR(36), status VARCHAR(32), confirmed_by VARCHAR(36),
resolved_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE,