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
@@ -1,36 +1,64 @@
package com.guo.learningprogresstracker.common;
import lombok.Getter;
/**
* 学习会话的时间口径常量。
* 学习会话的时间口径(会话-04 起改为可配置的值对象)。
*
* <p>番茄钟长度、遗忘判定阈值与有效时间下限集中在此处定义,避免阈值散落在实体与服务的各个角落。
* 修改口径时只改这里,不要就地写死数字。</p>
* <p>番茄钟长度、遗忘判定阈值、硬兜底阈值与有效时间下限集中在此处,避免阈值散落在实体与服务的各个角落。
* 生产路径由 Spring 从 {@code lpt.study-time} 配置构建并注入;{@link #DEFAULT} 只保留设计口径的默认值,
* 供实体自身的默认重载与单测使用,不要在服务里直接用它。</p>
*/
public final class StudyTimePolicy {
@Getter
public class StudyTimePolicy {
/** 与 lpt-docs 设计口径一致的默认值 */
public static final StudyTimePolicy DEFAULT = new StudyTimePolicy(25, 50, 120, 600);
/**
* 番茄钟长度(分钟)。
*/
public static final int WORK_DURATION_MINUTES = 25;
private final int workDurationMinutes;
/**
* 遗忘判定阈值(分钟):通常为 2 × 番茄钟。
*/
private final int forgetThresholdMinutes;
/**
* 硬兜底阈值(分钟):进行中的会话超过该时长未收敛,服务端强制暂停。
*/
private final int forcePauseMinutes;
/**
* 有效学习时间下限(秒)。
*/
private final long minEffectiveTimeSeconds;
public StudyTimePolicy(int workDurationMinutes, int forgetThresholdMinutes,
int forcePauseMinutes, long minEffectiveTimeSeconds) {
if (workDurationMinutes <= 0) {
throw new IllegalArgumentException("番茄钟长度必须大于 0 分钟");
}
if (forgetThresholdMinutes < workDurationMinutes) {
throw new IllegalArgumentException("遗忘判定阈值不能小于番茄钟长度");
}
if (forcePauseMinutes < forgetThresholdMinutes) {
throw new IllegalArgumentException("硬兜底阈值不能小于遗忘判定阈值");
}
if (minEffectiveTimeSeconds < 0) {
throw new IllegalArgumentException("有效学习时间下限不能为负数");
}
this.workDurationMinutes = workDurationMinutes;
this.forgetThresholdMinutes = forgetThresholdMinutes;
this.forcePauseMinutes = forcePauseMinutes;
this.minEffectiveTimeSeconds = minEffectiveTimeSeconds;
}
/**
* 番茄钟长度(毫秒)。
*/
public static final long WORK_DURATION_MILLIS = WORK_DURATION_MINUTES * 60_000L;
/**
* 遗忘判定阈值(分钟):2 × 番茄钟。
*
* <p>最后一段学习在超过该时长后仍没有任何操作,判定为「忘了点暂停/结束」,
* 该段只按一个番茄钟结算(见 {@code StudySessionsEntity#resolveSettlementTime})。</p>
*/
public static final int FORGET_THRESHOLD_MINUTES = WORK_DURATION_MINUTES * 2;
/**
* 有效学习时间下限(秒):低于该值的一次学习不计入总学习时间。
*/
public static final long MIN_EFFECTIVE_TIME_SECONDS = 10 * 60L;
private StudyTimePolicy() {
public long workDurationMillis() {
return workDurationMinutes * 60_000L;
}
}
@@ -0,0 +1,24 @@
package com.guo.learningprogresstracker.config;
import com.guo.learningprogresstracker.common.StudyTimePolicy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 学习会话的时间口径装配(会话-04)。
* <p>阈值来自 {@link StudyTimeProperties};非法组合在启动时直接失败,避免运行期出现「兜底阈值比遗忘阈值还小」这类矛盾配置。</p>
*/
@Configuration
@EnableScheduling
public class StudyTimeConfig {
@Bean
public StudyTimePolicy studyTimePolicy(StudyTimeProperties properties) {
return new StudyTimePolicy(
properties.getWorkDurationMinutes(),
properties.getForgetThresholdMinutes(),
properties.getForcePauseMinutes(),
properties.getMinEffectiveTimeSeconds());
}
}
@@ -0,0 +1,35 @@
package com.guo.learningprogresstracker.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 学习会话的时间口径配置(会话-04)。
*
* <p>番茄钟长度、遗忘判定阈值、硬兜底阈值与有效时间下限集中在这里,改口径不需要改代码。
* 默认值与 `lpt-docs` 的设计口径一致:25 分钟番茄钟、50 分钟遗忘判定、2 小时硬兜底。</p>
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "lpt.study-time")
public class StudyTimeProperties {
/** 番茄钟长度(分钟):单个学习段落的上限 */
private int workDurationMinutes = 25;
/** 遗忘判定阈值(分钟):超过该时长无操作,按「忘了点暂停/结束」只结算一个番茄钟 */
private int forgetThresholdMinutes = 50;
/** 硬兜底阈值(分钟):进行中的会话超过该时长仍未结算,由服务端强制收敛 */
private int forcePauseMinutes = 120;
/** 有效学习时间下限(秒):低于该值的一次学习不计入总学习时间 */
private long minEffectiveTimeSeconds = 600;
/** 低频定时收敛扫描的间隔(毫秒) */
private long scanIntervalMs = 600_000;
/** 是否开启低频定时收敛(测试环境可关掉,避免与用例互相干扰) */
private boolean scanEnabled = true;
}
@@ -50,4 +50,9 @@ public class StudySessionsDto {
* 学习会话的状态(进行中、暂停、已结束)
*/
private String sessionState;
/**
* 是否由服务端自动收敛(疑似忘记结束,会话-04)
*/
private Boolean autoConverged;
}
@@ -54,4 +54,7 @@ public class StudySessionResponse {
@Schema(description = "系统提示")
private String systemMessage;
@Schema(description = "是否由服务端自动收敛(疑似忘记结束,会话-04)")
private Boolean autoConverged;
}
@@ -76,6 +76,13 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
@TableField(value = "session_state")
private String sessionState;
/**
* 是否由服务端自动收敛(会话-04):为 true 表示这段学习疑似忘记点暂停/结束,
* 由惰性收敛或定时扫描强制结算,前端据此给出提示。
*/
@TableField(value = "auto_converged")
private Boolean autoConverged;
/**
* 计时器指针位置,时间戳形式存储(毫秒)
@@ -87,28 +94,42 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 初始化新会话
* @return
* 初始化新会话(使用默认时间口径)
*/
public static StudySessionsEntity initNewSession(){
return initNewSession(StudyTimePolicy.DEFAULT);
}
/**
* 初始化新会话
*/
public static StudySessionsEntity initNewSession(StudyTimePolicy policy){
StudySessionsEntity studySessionsEntity = new StudySessionsEntity();
studySessionsEntity.setSessionNum(GenerateNumTool.generateNum("SESSION"));
studySessionsEntity.setStartTime(LocalDateTime.now());
studySessionsEntity.setLastStartTime(LocalDateTime.now());
studySessionsEntity.setPointerPosition(StudyTimePolicy.WORK_DURATION_MILLIS);
studySessionsEntity.setPointerPosition(policy.workDurationMillis());
studySessionsEntity.setLastModifiedTime(LocalDateTime.now());
studySessionsEntity.setSessionState(StudySessionStateEnum.ONGOING.name());
studySessionsEntity.setAutoConverged(false);
return studySessionsEntity;
}
/**
* 继续会话(使用默认时间口径)
*/
public void continueStudySession() throws ServiceException {
continueStudySession(StudyTimePolicy.DEFAULT);
}
/**
* 继续会话
*/
public void continueStudySession() throws ServiceException {
public void continueStudySession(StudyTimePolicy policy) throws ServiceException {
if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())){
this.setSessionState(StudySessionStateEnum.ONGOING.name());
this.setLastStartTime(LocalDateTime.now());
this.calculatePointerPosition();
this.calculatePointerPosition(policy);
} else if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) {
log.info("进行中的学习会话({})被重新开始",this.getSessionNum());
} else{
@@ -117,13 +138,20 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
/**
* 暂停会话
* 暂停会话(使用默认时间口径)
*/
public void pausedStudySession(LocalDateTime endTime){
pausedStudySession(endTime, StudyTimePolicy.DEFAULT);
}
/**
* 暂停会话
*/
public void pausedStudySession(LocalDateTime endTime, StudyTimePolicy policy){
if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())) {
log.warn("不应出现的情况:暂停了一个状态为【{}】的学习会话({})", this.getSessionState(), this.getSessionNum());
} else {
LocalDateTime settlementTime = this.resolveSettlementTime(endTime);
LocalDateTime settlementTime = this.resolveSettlementTime(endTime, policy);
this.setEndTime(settlementTime);
this.setActualTime(Duration.between(this.startTime, this.endTime).toSeconds());
this.setEffectiveTime(this.getEffectiveTime() + Duration.between(this.lastStartTime, this.endTime).toSeconds());
@@ -132,39 +160,54 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
}
/**
* 计算本次学习分段的结算时间(使用默认时间口径)。
*/
public LocalDateTime resolveSettlementTime(LocalDateTime candidateEndTime) {
return resolveSettlementTime(candidateEndTime, StudyTimePolicy.DEFAULT);
}
/**
* 计算本次学习分段的结算时间:暂停、结束与超时收敛都必须走这里,避免同一行为产生两种统计结果。
*
* <p>{@code lastStartTime} 到候选结束时间超过遗忘判定阈值
* ({@link StudyTimePolicy#FORGET_THRESHOLD_MINUTES})时,按「忘了点暂停/结束」处理,
* 只结算一个番茄钟({@link StudyTimePolicy#WORK_DURATION_MINUTES} 分钟);否则按候选结束时间结算。</p>
* ({@link StudyTimePolicy#getForgetThresholdMinutes()})时,按「忘了点暂停/结束」处理,
* 只结算一个番茄钟({@link StudyTimePolicy#getWorkDurationMinutes()} 分钟);否则按候选结束时间结算。</p>
*/
public LocalDateTime resolveSettlementTime(LocalDateTime candidateEndTime) {
public LocalDateTime resolveSettlementTime(LocalDateTime candidateEndTime, StudyTimePolicy policy) {
LocalDateTime end = ObjectUtils.isEmpty(candidateEndTime) ? LocalDateTime.now() : candidateEndTime;
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return end;
}
long minutes = Duration.between(this.lastStartTime, end).toMinutes();
if (minutes >= StudyTimePolicy.FORGET_THRESHOLD_MINUTES) {
if (minutes >= policy.getForgetThresholdMinutes()) {
log.info("会话[{}]本段学习已超过{}分钟无操作,按{}分钟结算",
this.getSessionNum(), StudyTimePolicy.FORGET_THRESHOLD_MINUTES, StudyTimePolicy.WORK_DURATION_MINUTES);
return this.lastStartTime.plusMinutes(StudyTimePolicy.WORK_DURATION_MINUTES);
this.getSessionNum(), policy.getForgetThresholdMinutes(), policy.getWorkDurationMinutes());
return this.lastStartTime.plusMinutes(policy.getWorkDurationMinutes());
}
return end;
}
/**
* 结束会话
* 结束会话(使用默认时间口径)
*/
public void endedStudySession() {
endedStudySession(StudyTimePolicy.DEFAULT);
}
/**
* 结束会话
*/
public void endedStudySession(StudyTimePolicy policy) {
if (this.isEnded()){
log.warn("不应出现的情况:结束了一个状态为【{}】的学习会话",this.getSessionState());
}else {
if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) {
this.pausedStudySession(LocalDateTime.now());
this.pausedStudySession(LocalDateTime.now(), policy);
}
if (this.getEffectiveTime() < StudyTimePolicy.MIN_EFFECTIVE_TIME_SECONDS) {
log.info("会话[{}]有效学习时间({}秒)不足10分钟,不计入总学习时间", this.getSessionNum(), this.getEffectiveTime());
if (this.getEffectiveTime() < policy.getMinEffectiveTimeSeconds()) {
log.info("会话[{}]有效学习时间({}秒)不足{}分钟,不计入总学习时间",
this.getSessionNum(), this.getEffectiveTime(), policy.getMinEffectiveTimeSeconds() / 60);
this.setEffectiveTime(0);
this.setEffectivenessRatio(0);
}
@@ -172,6 +215,36 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
}
/**
* 服务端强制收敛悬挂会话(会话-04):进行中且超过硬兜底阈值时,
* 按遗忘规则结算为暂停并打上「自动收敛」标记,供前端提示「本次学习疑似忘记结束」。
*
* @return 是否发生了收敛(未满足条件时返回 false,便于调用方幂等处理)
*/
public boolean forceConverge(LocalDateTime now, StudyTimePolicy policy) {
if (!isForcePausable(now, policy)) {
return false;
}
log.warn("会话[{}]已悬挂超过{}分钟,服务端强制收敛为暂停", this.getSessionNum(), policy.getForcePauseMinutes());
this.setAutoConverged(true);
this.pausedStudySession(now, policy);
this.setLastModifiedTime(LocalDateTime.now());
return true;
}
/**
* 是否属于「长时间无人操作」的进行中会话:只有进行中且本段开始时间早于硬兜底阈值才成立。
*/
public boolean isForcePausable(LocalDateTime now, StudyTimePolicy policy) {
if (!StudySessionStateEnum.ONGOING.name().equals(this.sessionState)) {
return false;
}
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return false;
}
return Duration.between(this.lastStartTime, now).toMinutes() >= policy.getForcePauseMinutes();
}
/**
* 第一次运行
* @return
@@ -181,20 +254,27 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
/**
* 计算当前倒计时指针的位置(使用默认时间口径)
*/
public void calculatePointerPosition() throws ServiceException {
calculatePointerPosition(StudyTimePolicy.DEFAULT);
}
/**
* 计算当前倒计时指针的位置(单位:毫秒)
*
* 规则说明:
* - 如果是第一次运行(lastStartTime为null),则倒计时从25分钟开始
* - 如果是第一次运行(lastStartTime为null),则倒计时从番茄钟长度开始
* - 如果是暂停状态,返回上次保存的pointerPosition
* - 如果是进行中状态,返回 pointerPosition -(当前时间 - lastStartTime)
* 即从上次开始后经历的时间,从之前保存的pointerPosition中扣除
*
* @return 指针当前位置,单位为毫秒
*/
public void calculatePointerPosition() throws ServiceException {
public void calculatePointerPosition(StudyTimePolicy policy) throws ServiceException {
if (isFirstRun()) {
this.pointerPosition = StudyTimePolicy.WORK_DURATION_MILLIS; // 毫秒
this.pointerPosition = policy.workDurationMillis();
return;
}
@@ -209,12 +289,12 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
case ONGOING:
long elapsedMillis = Duration.between(lastStartTime, LocalDateTime.now()).toMillis();
long basePointerPosition = ObjectUtils.isEmpty(pointerPosition)
? StudyTimePolicy.WORK_DURATION_MILLIS
? policy.workDurationMillis()
: pointerPosition;
long newPointerPosition = basePointerPosition - elapsedMillis;
if (newPointerPosition <= 0) {
// 如果循环已经结束,则需要重置指针位置
this.pointerPosition = StudyTimePolicy.WORK_DURATION_MILLIS;
this.pointerPosition = policy.workDurationMillis();
} else {
this.pointerPosition = newPointerPosition;
}
@@ -241,17 +321,24 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
return StudySessionStateEnum.ENDED.name().equals(this.sessionState);
}
/**
* 本段学习是否已判定为「忘了点暂停/结束」(使用默认时间口径)。
*/
public boolean isForgotten() {
return isForgotten(LocalDateTime.now(), StudyTimePolicy.DEFAULT);
}
public boolean isForgotten(LocalDateTime now) {
return isForgotten(now, StudyTimePolicy.DEFAULT);
}
/**
* 本段学习是否已判定为「忘了点暂停/结束」,即需要按遗忘规则截断。
*
* <p>只有进行中的会话才成立:暂停与已结束的会话,其时间已在结算时入账,再次截断会重复扣减。
* 同时要求本段尚未结算过({@code end_time} 不早于 {@code last_start_time} 时视为已结算)。</p>
*/
public boolean isForgotten() {
return isForgotten(LocalDateTime.now());
}
public boolean isForgotten(LocalDateTime now) {
public boolean isForgotten(LocalDateTime now, StudyTimePolicy policy) {
if (!StudySessionStateEnum.ONGOING.name().equals(this.sessionState)) {
return false;
}
@@ -261,6 +348,6 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
if (!ObjectUtils.isEmpty(this.endTime) && !this.endTime.isBefore(this.lastStartTime)) {
return false;
}
return Duration.between(this.lastStartTime, now).toMinutes() >= StudyTimePolicy.FORGET_THRESHOLD_MINUTES;
return Duration.between(this.lastStartTime, now).toMinutes() >= policy.getForgetThresholdMinutes();
}
}
@@ -1,8 +1,15 @@
package com.guo.learningprogresstracker.mapper;
import com.guo.learningprogresstracker.entity.StudySessionsEntity;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
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.time.LocalDateTime;
import java.util.List;
/**
* @author guo
@@ -13,8 +20,47 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudySessionsMapper extends BaseMapper<StudySessionsEntity> {
/**
* 找出所有租户中「进行中且悬挂超过硬兜底阈值」的会话(会话-04)。
*
* <p>定时任务在请求之外执行,没有登录态,而租户拦截器会读取当前登录用户,因此这里显式忽略租户条件。
* 这是系统级的后台收敛,只用于定时扫描;请求内的惰性收敛走 {@code Wrappers} 的租户隔离路径。
* 自定义 SQL 不会被 {@code @TableLogic} 自动追加条件,所以 {@code deleted = 0} 必须显式写出。</p>
*/
@InterceptorIgnore(tenantLine = "true")
@Select("""
SELECT *
FROM study_sessions
WHERE deleted = 0
AND session_state = 'ONGOING'
AND last_start_time <= #{cutoff}
ORDER BY last_start_time ASC
LIMIT #{limit}
""")
List<StudySessionsEntity> selectForcePausableSessions(@Param("cutoff") LocalDateTime cutoff,
@Param("limit") int limit);
/**
* 条件写入收敛结果(会话-04):只有仍然处于 ONGOING 的会话才会被写入,保证并发下不会重复结算。
*
* <p>按主键更新(主键全局唯一),因此忽略租户条件是安全的:定时任务在请求之外执行,
* 没有登录态可供租户拦截器读取。</p>
*
* @return 受影响行数,0 表示已被其他请求收敛
*/
@InterceptorIgnore(tenantLine = "true")
@Update("""
UPDATE study_sessions
SET end_time = #{endTime},
actual_time = #{actualTime},
effective_time = #{effectiveTime},
effectiveness_ratio = #{effectivenessRatio},
session_state = #{sessionState},
auto_converged = #{autoConverged},
last_modified_time = #{lastModifiedTime}
WHERE id = #{id}
AND session_state = 'ONGOING'
AND deleted = 0
""")
int convergeStaleSession(StudySessionsEntity session);
}
@@ -40,4 +40,19 @@ public interface StudySessionsService extends IService<StudySessionsEntity> {
Page<StudyReportsEntity> getTaskReports(String taskNum, int page, int size, String keyword);
StudySessionResponse getActiveSession(String excludeTaskNum);
/**
* 惰性收敛(会话-04):把当前用户悬挂的进行中会话按硬兜底阈值强制暂停。
* <p>由读取路径调用(活跃会话、任务未结束会话),用户不访问时由定时扫描兜底。</p>
*
* @return 本次实际收敛的会话数
*/
int convergeStaleSessionsOfCurrentUser();
/**
* 定时收敛(会话-04):扫描所有用户悬挂的进行中会话并强制暂停。
*
* @return 本次实际收敛的会话数
*/
int scanAndConvergeStaleSessions();
}
@@ -0,0 +1,39 @@
package com.guo.learningprogresstracker.service.impl;
import com.guo.learningprogresstracker.service.StudySessionsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 悬挂会话的低频定时收敛(会话-04)。
*
* <p>惰性收敛只在用户访问时生效;用户不回来时「今日有效学习时间」等统计会一直滞后,
* 悬挂会话也会一直挡住新任务,因此增加这条定时兜底。扫描间隔由
* {@code lpt.study-time.scan-interval-ms} 配置,测试环境用 {@code lpt.study-time.scan-enabled=false} 关闭。</p>
*/
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "lpt.study-time", name = "scan-enabled", havingValue = "true", matchIfMissing = true)
public class StudySessionConvergenceScheduler {
private final StudySessionsService studySessionsService;
/**
* 定时扫描并收敛悬挂会话;异常只记录不抛出,避免一次失败导致调度任务停止。
*/
@Scheduled(fixedDelayString = "${lpt.study-time.scan-interval-ms:600000}")
public void convergeStaleSessions() {
try {
int converged = studySessionsService.scanAndConvergeStaleSessions();
if (converged > 0) {
log.info("[会话收敛] 定时扫描收敛了 {} 个悬挂会话", converged);
}
} catch (Exception e) {
log.error("[会话收敛] 定时扫描失败", e);
}
}
}
@@ -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;
}
}