feat: 悬挂学习会话惰性收敛与定时兜底

This commit is contained in:
2026-10-09 12:32:11 +08:00
parent faaaa132c1
commit db552182ae
17 changed files with 712 additions and 65 deletions
@@ -27,6 +27,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -44,12 +45,16 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
*/
public static final String MISOPERATION_CONFIRMATION = "我误操作导致开启了本次学习";
/** 单次定时扫描最多处理的会话数,避免一次拉回过多数据 */
private static final int SCAN_BATCH_SIZE = 200;
private final TasksServiceImpl tasksServiceImpl;
private final StudyReportFragmentsServiceImpl studyReportFragmentsServiceImpl;
private final StudyReportFragmentsMapper studyReportFragmentsMapper;
private final StudyReportsMapper studyReportsMapper;
private final AiServiceClient aiServiceClient;
private final StudyExpectationsService studyExpectationsService;
private final StudyTimePolicy studyTimePolicy;
public StudySessionResponse startOrContinueStudySession(String taskNum) throws NotFindEntitiesException, ServiceException {
TaskEntity taskEntity = tasksServiceImpl.getOneOpt(
@@ -64,19 +69,20 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
.ne(StudySessionsEntity::getSessionState, StudySessionStateEnum.ENDED.name()))
.orElseGet(() -> {
// 如果没有则创建新会话
StudySessionsEntity newSession = StudySessionsEntity.initNewSession();
StudySessionsEntity newSession = StudySessionsEntity.initNewSession(studyTimePolicy);
newSession.setTaskNum(taskNum);
newSession.setLastStartTime(LocalDateTime.now());
this.save(newSession);
return newSession;
});
session.calculatePointerPosition();
LocalDateTime now = LocalDateTime.now();
session.calculatePointerPosition(studyTimePolicy);
// 只有进行中且本段尚未结算的会话才需要收敛;已暂停/已结束的会话不再重复截断
boolean forgotten = session.isForgotten();
boolean forgotten = session.isForgotten(now, studyTimePolicy);
if (forgotten) {
session.pausedStudySession(null);
session.pausedStudySession(null, studyTimePolicy);
this.updateById(session);
}
@@ -88,7 +94,7 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
if (forgotten) {
response.setSystemMessage(String.format(
"上段学习已超过%d分钟没有任何操作,仅计算为%d分钟的有效学习时间,请注意休息!",
StudyTimePolicy.FORGET_THRESHOLD_MINUTES, StudyTimePolicy.WORK_DURATION_MINUTES));
studyTimePolicy.getForgetThresholdMinutes(), studyTimePolicy.getWorkDurationMinutes()));
}
return response;
@@ -104,8 +110,8 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
log.error("会话[" + studySessionsEntity.getSessionNum() + "]重复暂停");
throw new ErrorParameterException("这次学习会话已经暂停了,不用重复暂停哦");
}
studySessionsEntity.calculatePointerPosition();
studySessionsEntity.pausedStudySession(endTime);
studySessionsEntity.calculatePointerPosition(studyTimePolicy);
studySessionsEntity.pausedStudySession(endTime, studyTimePolicy);
this.updateById(studySessionsEntity);
}
@@ -124,7 +130,7 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
}
boolean wasOngoing = StudySessionStateEnum.ONGOING.name().equals(studySessionsEntity.getSessionState());
studySessionsEntity.endedStudySession();
studySessionsEntity.endedStudySession(studyTimePolicy);
// 条件更新:只有数据库中仍未结束的会话才会被写入结算结果,
// 避免重复点击/网络重试等并发请求各自插入一条学习报告
@@ -141,7 +147,7 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
studyReportsEntity.setContent(content);
studyReportsMapper.insert(studyReportsEntity);
if (wasOngoing && studySessionsEntity.getEffectiveTime() == 0) {
return "本次有效学习时间不足10分钟,不计入总学习时间";
return "本次有效学习时间不足" + (studyTimePolicy.getMinEffectiveTimeSeconds() / 60) + "分钟,不计入总学习时间";
}
return null;
}
@@ -173,6 +179,8 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
@Override
public StudySessionResponse getNotEndedStudySessionByTaskNum(String taskNum) throws ErrorParameterException {
// 惰性收敛:先把悬挂会话收敛掉,避免返回一个早该暂停的进行中会话
convergeStaleSessionsOfCurrentUser();
TaskEntity task = tasksServiceImpl.getOneOpt(Wrappers.lambdaQuery(TaskEntity.class)
.eq(TaskEntity::getTaskNum, taskNum))
.orElseThrow(() -> taskNotFound(taskNum));
@@ -209,7 +217,7 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
log.error("会话[" + studySessionsEntity.getSessionNum() + "]处于结束状态,不可开始该会话!");
throw new ErrorParameterException("这次学习会话已经结束,无法再次开始");
}
studySessionsEntity.continueStudySession();
studySessionsEntity.continueStudySession(studyTimePolicy);
this.updateById(studySessionsEntity);
}
@@ -293,6 +301,9 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
*/
@Override
public StudySessionResponse getActiveSession(String excludeTaskNum) {
// 惰性收敛:用户不访问任务页时,统计与阻塞问题靠这里先行修正(定时扫描兜底)
convergeStaleSessionsOfCurrentUser();
var wrapper = Wrappers.lambdaQuery(StudySessionsEntity.class)
.in(StudySessionsEntity::getSessionState,
StudySessionStateEnum.ONGOING.name(),
@@ -328,4 +339,58 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
return new ErrorParameterException("这个任务不存在或已被删除");
}
// ============ 悬挂会话收敛(会话-04)============
@Override
public int convergeStaleSessionsOfCurrentUser() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes());
// 惰性收敛走租户隔离路径:只可能读到当前用户自己的会话
List<StudySessionsEntity> staleSessions = this.list(Wrappers.<StudySessionsEntity>lambdaQuery()
.eq(StudySessionsEntity::getSessionState, StudySessionStateEnum.ONGOING.name())
.le(StudySessionsEntity::getLastStartTime, cutoff)
.orderByAsc(StudySessionsEntity::getLastStartTime));
int converged = 0;
for (StudySessionsEntity session : staleSessions) {
if (convergeOne(session, now)) {
converged++;
}
}
return converged;
}
@Override
public int scanAndConvergeStaleSessions() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes());
// 定时任务在请求之外执行,没有登录态,走忽略租户条件的扫描(系统级兜底)
List<StudySessionsEntity> staleSessions = baseMapper.selectForcePausableSessions(cutoff, SCAN_BATCH_SIZE);
int converged = 0;
for (StudySessionsEntity session : staleSessions) {
if (convergeOne(session, now)) {
converged++;
}
}
return converged;
}
/**
* 收敛单个悬挂会话:先按硬兜底阈值复核,再用「状态仍为 ONGOING」的条件更新写入。
*
* <p>条件更新保证惰性收敛与定时扫描并发时只结算一次(与结束会话的幂等处理同一思路),
* 写入按主键定位,所以定时扫描分支可以安全地忽略租户条件。</p>
*
* @return 是否由本次调用完成收敛
*/
private boolean convergeOne(StudySessionsEntity session, LocalDateTime now) {
if (!session.forceConverge(now, studyTimePolicy)) {
return false;
}
return baseMapper.convergeStaleSession(session) > 0;
}
}