feat: AI 调用改为异步任务并支持结果重复获取
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package com.guo.learningprogresstracker.common;
|
||||
|
||||
/**
|
||||
* 显式的租户上下文(AI-02)。
|
||||
*
|
||||
* <p>租户拦截器与公共字段自动填充都从 {@code StpUtil} 取当前用户,而它依赖 Web 请求上下文。
|
||||
* 后台执行线程(AI 任务执行器、定时收敛)没有请求上下文,直接调用会抛
|
||||
* {@code NotWebContextException};这里让后台线程显式声明「我以哪个用户身份在执行」。</p>
|
||||
*
|
||||
* <p>取值优先级:<b>本上下文优先</b>,没有时才回落到 {@code StpUtil}。这样请求线程的行为完全不变,
|
||||
* 后台线程也只能以任务所属用户的身份执行,不会意外变成「无租户」而看到全部数据。</p>
|
||||
*/
|
||||
public final class TenantContext {
|
||||
|
||||
/**
|
||||
* 执行身份。
|
||||
*
|
||||
* @param loginId 登录用户
|
||||
* @param device 设备类型,可为 null(后台任务通常没有设备信息)
|
||||
*/
|
||||
public record Identity(String loginId, String device) {
|
||||
}
|
||||
|
||||
private static final ThreadLocal<Identity> CURRENT = new ThreadLocal<>();
|
||||
|
||||
private TenantContext() {
|
||||
}
|
||||
|
||||
/** 取当前执行身份;未设置时返回 null(表示应回落到 StpUtil) */
|
||||
public static Identity get() {
|
||||
return CURRENT.get();
|
||||
}
|
||||
|
||||
/** 在指定身份下执行;执行结束后恢复原身份,避免线程池复用造成身份串号 */
|
||||
public static void runAs(String loginId, String device, Runnable action) {
|
||||
callAs(loginId, device, () -> {
|
||||
action.run();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** 在指定身份下执行并返回结果(异常原样向外抛,由调用方决定如何回写) */
|
||||
public static <T> T callAs(String loginId, String device, java.util.function.Supplier<T> action) {
|
||||
Identity previous = CURRENT.get();
|
||||
CURRENT.set(new Identity(loginId, device));
|
||||
try {
|
||||
return action.get();
|
||||
} finally {
|
||||
if (previous == null) {
|
||||
CURRENT.remove();
|
||||
} else {
|
||||
CURRENT.set(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.guo.learningprogresstracker.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
/**
|
||||
* AI 任务执行器装配(AI-02)。
|
||||
* <p>执行线程与请求线程分离,AI 调用不会占用 HTTP 请求线程,也不会持有请求期间打开的数据库连接。</p>
|
||||
*/
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class AiTaskConfig {
|
||||
|
||||
public static final String AI_TASK_EXECUTOR = "aiTaskExecutor";
|
||||
|
||||
@Bean(name = AI_TASK_EXECUTOR)
|
||||
public ThreadPoolTaskExecutor aiTaskExecutor(AiTaskProperties properties) {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(properties.getExecutorCoreSize());
|
||||
executor.setMaxPoolSize(properties.getExecutorMaxSize());
|
||||
executor.setQueueCapacity(properties.getExecutorQueueCapacity());
|
||||
executor.setThreadNamePrefix("ai-task-");
|
||||
// 队列满时由调用线程执行,避免任务被静默丢弃(定时兜底仍会接手)
|
||||
executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.guo.learningprogresstracker.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* AI 异步任务配置(AI-02)。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "lpt.ai-task")
|
||||
public class AiTaskProperties {
|
||||
|
||||
/** 单个任务允许的最长执行时间(秒):超过则视为进程中断,回收后可重试 */
|
||||
private long stuckTimeoutSeconds = 900;
|
||||
|
||||
/** 兜底扫描间隔(毫秒) */
|
||||
private long scanIntervalMs = 3000;
|
||||
|
||||
/** 首次兜底扫描的延迟(毫秒):让「提交后立即投递」先执行 */
|
||||
private long scanInitialDelayMs = 3000;
|
||||
|
||||
/** 单次扫描最多处理多少个任务 */
|
||||
private int scanBatchSize = 10;
|
||||
|
||||
/** 立即投递用的线程池大小 */
|
||||
private int executorCoreSize = 2;
|
||||
|
||||
private int executorMaxSize = 4;
|
||||
|
||||
private int executorQueueCapacity = 50;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.guo.learningprogresstracker.config;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.guo.learningprogresstracker.common.TenantContext;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -20,18 +21,35 @@ public class AutoTableField implements MetaObjectHandler {
|
||||
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "createdBy", StpUtil::getLoginIdAsString, String.class);
|
||||
this.strictInsertFill(metaObject, "createdBy", AutoTableField::currentLoginId, String.class);
|
||||
this.strictInsertFill(metaObject, "createdTime", LocalDateTime::now, LocalDateTime.class);
|
||||
this.strictInsertFill(metaObject, "lastModifiedBy", StpUtil::getLoginIdAsString, String.class);
|
||||
this.strictInsertFill(metaObject, "lastModifiedBy", AutoTableField::currentLoginId, String.class);
|
||||
this.strictInsertFill(metaObject, "lastModifiedTime", LocalDateTime::now, LocalDateTime.class);
|
||||
this.strictInsertFill(metaObject, "deviceInfo", AutoTableField::currentDevice, String.class);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "lastModifiedBy", StpUtil::getLoginIdAsString, String.class);
|
||||
this.strictInsertFill(metaObject, "lastModifiedBy", AutoTableField::currentLoginId, String.class);
|
||||
this.strictInsertFill(metaObject, "lastModifiedTime", LocalDateTime::now, LocalDateTime.class);
|
||||
this.strictInsertFill(metaObject,"deviceInfo",StpUtil::getLoginDevice,String.class);
|
||||
this.strictInsertFill(metaObject, "deviceInfo", AutoTableField::currentDevice, String.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前登录用户:后台执行线程通过 {@link TenantContext} 显式声明身份,请求线程仍走 StpUtil。
|
||||
*/
|
||||
static String currentLoginId() {
|
||||
TenantContext.Identity identity = TenantContext.get();
|
||||
return identity != null ? identity.loginId() : StpUtil.getLoginIdAsString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前设备:后台任务通常没有设备信息,返回 null 时跳过该项填充(保持列为空而不是写脏值)。
|
||||
*/
|
||||
static String currentDevice() {
|
||||
TenantContext.Identity identity = TenantContext.get();
|
||||
return identity != null ? identity.device() : StpUtil.getLoginDevice();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.guo.learningprogresstracker.config;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import com.guo.learningprogresstracker.common.TenantContext;
|
||||
import net.sf.jsqlparser.expression.StringValue;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
@@ -39,7 +40,10 @@ public class MybatisPlusConfig {
|
||||
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
|
||||
@Override
|
||||
public Expression getTenantId() {
|
||||
return new StringValue(StpUtil.getLoginIdAsString());
|
||||
// 后台执行线程(AI 任务、定时收敛)通过 TenantContext 显式声明身份;
|
||||
// 请求线程没有设置,仍走 StpUtil,行为完全不变
|
||||
TenantContext.Identity identity = TenantContext.get();
|
||||
return new StringValue(identity != null ? identity.loginId() : StpUtil.getLoginIdAsString());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.guo.learningprogresstracker.controller;
|
||||
|
||||
import com.guo.learningprogresstracker.dto.AiTaskResponse;
|
||||
import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest;
|
||||
import com.guo.learningprogresstracker.entity.CommonResult;
|
||||
import com.guo.learningprogresstracker.exception.ErrorParameterException;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
import com.guo.learningprogresstracker.service.AiTaskService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* AI 异步任务控制层(AI-02)。
|
||||
*
|
||||
* <p>提交与查询分离:提交接口秒级返回任务标识,前端随后轮询查询接口拿结果。
|
||||
* 这样刷新或离开页面都不会丢结果,AI 已消耗的 token 也不会白费。</p>
|
||||
*/
|
||||
@RequestMapping("/ai/tasks")
|
||||
@RestController
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
public class AiTaskController {
|
||||
|
||||
private final AiTaskService aiTaskService;
|
||||
|
||||
/**
|
||||
* 提交 AI 任务。
|
||||
* <p>同一目标已有进行中任务时直接返回该任务(AI-04:对外是任务状态,而不是可能为空的实体)。</p>
|
||||
*/
|
||||
@PostMapping
|
||||
public CommonResult<AiTaskResponse> submit(@Valid @RequestBody AiTaskSubmitRequest request)
|
||||
throws ErrorParameterException, NotFindEntitiesException {
|
||||
return CommonResult.success(aiTaskService.submit(request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询任务状态与结果;结果可重复获取。
|
||||
*/
|
||||
@GetMapping("/{taskNum}")
|
||||
public CommonResult<AiTaskResponse> getTask(@PathVariable String taskNum) throws NotFindEntitiesException {
|
||||
return CommonResult.success(aiTaskService.getByTaskNum(taskNum));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询某目标最近的 AI 任务,用于离开页面再回来时恢复生成状态。
|
||||
*
|
||||
* @return 无任务时 data 为 null
|
||||
*/
|
||||
@GetMapping("/latest")
|
||||
public CommonResult<AiTaskResponse> getLatestTask(@RequestParam String type,
|
||||
@RequestParam String targetNum) {
|
||||
return CommonResult.success(aiTaskService.findLatest(type, targetNum));
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package com.guo.learningprogresstracker.controller;
|
||||
|
||||
import com.guo.learningprogresstracker.dto.ReviewFeedItem;
|
||||
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
|
||||
import com.guo.learningprogresstracker.dto.ReviewTiming;
|
||||
import com.guo.learningprogresstracker.dto.request.RecallCompareRequest;
|
||||
import com.guo.learningprogresstracker.dto.request.UpdateStandardMindMapRequest;
|
||||
import com.guo.learningprogresstracker.entity.CommonResult;
|
||||
import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity;
|
||||
@@ -88,26 +86,15 @@ public class ReviewController {
|
||||
// ============ 标准思维导图与回忆对比 ============
|
||||
|
||||
/**
|
||||
* 获取或自动生成任务的标准思维导图
|
||||
* 获取任务的标准思维导图。
|
||||
*
|
||||
* <p>读取不触发生成(AI-02):不存在时 data 为 null,由前端提交
|
||||
* {@code POST /ai/tasks}(type=MIND_MAP)后轮询结果。</p>
|
||||
*/
|
||||
@GetMapping("/standard-mind-map/{taskNum}")
|
||||
public CommonResult<ReviewStandardMindMapEntity> getStandardMindMap(
|
||||
@PathVariable String taskNum) throws NotFindEntitiesException, OperationFailedException {
|
||||
return CommonResult.success(standardMindMapService.getOrGenerate(taskNum));
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新生成任务的标准思维导图
|
||||
* @param mode 生成模式:full(全量覆盖,默认)或 incremental(增量合并)
|
||||
*/
|
||||
@PostMapping("/standard-mind-map/{taskNum}/regenerate")
|
||||
public CommonResult<ReviewStandardMindMapEntity> regenerateStandardMindMap(
|
||||
@PathVariable String taskNum,
|
||||
@RequestParam(defaultValue = "full") String mode) throws NotFindEntitiesException, OperationFailedException {
|
||||
if ("incremental".equals(mode)) {
|
||||
return CommonResult.success(standardMindMapService.incrementalGenerate(taskNum));
|
||||
}
|
||||
return CommonResult.success(standardMindMapService.regenerate(taskNum));
|
||||
@PathVariable String taskNum) throws NotFindEntitiesException {
|
||||
return CommonResult.success(standardMindMapService.getExisting(taskNum));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,19 +107,6 @@ public class ReviewController {
|
||||
return CommonResult.success(standardMindMapService.updateByOutline(taskNum, request.getOutline()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户提交回忆大纲,与标准导图对比
|
||||
*/
|
||||
@PostMapping("/standard-mind-map/{taskNum}/recall")
|
||||
public CommonResult<ReviewStandardMindMapEntity> recallCompare(
|
||||
@PathVariable String taskNum,
|
||||
@Valid @RequestBody RecallCompareRequest request) throws NotFindEntitiesException, OperationFailedException {
|
||||
return CommonResult.success(standardMindMapService.recallCompare(
|
||||
taskNum, request.getRecallOutline(), request.getFocusPath(),
|
||||
new ReviewTiming(request.getReviewStartedAt(), request.getReviewLastInteractionAt(),
|
||||
request.getReviewDurationSeconds())));
|
||||
}
|
||||
|
||||
/**
|
||||
* 在标准导图中查找与给定内容最匹配的节点
|
||||
*/
|
||||
|
||||
@@ -114,14 +114,6 @@ public class StudySessionController {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成学习报告草稿:AI 聚合残片(不可用时降级为拼接),返回给前端作为编辑起点
|
||||
*/
|
||||
@GetMapping("/{sessionNum}/report-draft")
|
||||
public CommonResult<String> getReportDraft(@PathVariable("sessionNum") String sessionNum) throws ErrorParameterException {
|
||||
return CommonResult.success("请求成功", studySessionsServiceImpl.generateReportDraft(sessionNum));
|
||||
}
|
||||
|
||||
/** 分页查询任务的残片历史 */
|
||||
@GetMapping("/tasks/{taskNum}/fragments")
|
||||
public CommonResult<Page<StudyReportFragmentsEntity>> getTaskFragments(
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.guo.learningprogresstracker.dto;
|
||||
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 任务对外视图(AI-02)。
|
||||
* <p>提交与查询都返回它:前端只依赖 {@code status} 与 {@code result},
|
||||
* 不需要在请求线程里等 AI(也就不会出现「AI 成功了但客户端已超时」)。</p>
|
||||
*/
|
||||
@Data
|
||||
public class AiTaskResponse {
|
||||
|
||||
@Schema(description = "AI 任务编号")
|
||||
private String taskNum;
|
||||
|
||||
@Schema(description = "任务类型:RECALL_COMPARE / MIND_MAP / REPORT_DRAFT")
|
||||
private String type;
|
||||
|
||||
@Schema(description = "目标编号:学习任务编号或学习会话编号")
|
||||
private String targetNum;
|
||||
|
||||
@Schema(description = "状态:PENDING / RUNNING / SUCCEEDED / FAILED")
|
||||
private String status;
|
||||
|
||||
@Schema(description = "失败原因(用户可见文案)")
|
||||
private String errorMessage;
|
||||
|
||||
@Schema(description = "提交时间")
|
||||
private LocalDateTime createdTime;
|
||||
|
||||
@Schema(description = "结束时间")
|
||||
private LocalDateTime finishedTime;
|
||||
|
||||
@Schema(description = "成功结果,随任务类型不同;未完成时为 null")
|
||||
private Map<String, Object> result;
|
||||
|
||||
public static AiTaskResponse from(AiTaskEntity entity, Map<String, Object> result) {
|
||||
AiTaskResponse response = new AiTaskResponse();
|
||||
response.setTaskNum(entity.getTaskNum());
|
||||
response.setType(entity.getAiType());
|
||||
response.setTargetNum(entity.getTargetNum());
|
||||
response.setStatus(entity.getStatus());
|
||||
response.setErrorMessage(entity.getErrorMessage());
|
||||
response.setCreatedTime(entity.getCreatedTime());
|
||||
response.setFinishedTime(entity.getFinishedTime());
|
||||
response.setResult(result);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.guo.learningprogresstracker.dto;
|
||||
|
||||
/**
|
||||
* 一次回忆对比的结果(AI-02)。
|
||||
*
|
||||
* <p>对比在 AI 任务执行器里完成,因此不再把「标准导图实体」直接返回给提交接口;
|
||||
* 这个结果写进 AI 任务的 {@code result_payload},由前端在轮询到成功后再取详情。</p>
|
||||
*
|
||||
* @param standardMapId 对比所用的标准导图 ID
|
||||
* @param recallRecordId 本次生成的回忆记录 ID
|
||||
* @param recallRatio 覆盖率(0-1)
|
||||
* @param matchedCount 命中节点数
|
||||
* @param missedCount 遗漏节点数
|
||||
* @param extraCount 额外节点数
|
||||
*/
|
||||
public record RecallCompareOutcome(Integer standardMapId, Integer recallRecordId, Double recallRatio,
|
||||
Integer matchedCount, Integer missedCount, Integer extraCount) {
|
||||
|
||||
/** 转成 AI 任务结果载荷 */
|
||||
public java.util.Map<String, Object> toPayload() {
|
||||
java.util.Map<String, Object> payload = new java.util.LinkedHashMap<>();
|
||||
payload.put("standardMapId", standardMapId);
|
||||
payload.put("recallRecordId", recallRecordId);
|
||||
payload.put("recallRatio", recallRatio);
|
||||
payload.put("matchedCount", matchedCount);
|
||||
payload.put("missedCount", missedCount);
|
||||
payload.put("extraCount", extraCount);
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.guo.learningprogresstracker.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 提交 AI 任务请求(AI-02)。
|
||||
*/
|
||||
@Data
|
||||
public class AiTaskSubmitRequest {
|
||||
|
||||
@NotBlank(message = "请先指定要处理的类型")
|
||||
private String type;
|
||||
|
||||
@NotBlank(message = "请先指定要处理的对象")
|
||||
private String targetNum;
|
||||
|
||||
/** 类型相关的参数;无需参数时可为空 */
|
||||
private Map<String, Object> params;
|
||||
|
||||
/** 阅读友好度:null 表示不关心 */
|
||||
public String paramAsString(String key) {
|
||||
Object value = params == null ? null : params.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
public Integer paramAsInteger(String key) {
|
||||
Object value = params == null ? null : params.get(key);
|
||||
if (value instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
if (value instanceof String text && !text.isBlank()) {
|
||||
try {
|
||||
return Integer.valueOf(text.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.guo.learningprogresstracker.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskStatusEnum;
|
||||
import com.guo.learningprogresstracker.utils.GenerateNumTool;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* AI 异步任务(AI-02):提交后立即返回任务标识,结果由执行器回写、按标识重复获取。
|
||||
*/
|
||||
@TableName(value = "ai_tasks")
|
||||
@Data
|
||||
public class AiTaskEntity extends BaseEntity implements Serializable {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
/** 对外任务标识 */
|
||||
@TableField(value = "task_num")
|
||||
private String taskNum;
|
||||
|
||||
/** 任务类型,取值见 {@code AiTaskTypeEnum} */
|
||||
@TableField(value = "ai_type")
|
||||
private String aiType;
|
||||
|
||||
/** 目标编号:学习任务编号或学习会话编号 */
|
||||
@TableField(value = "target_num")
|
||||
private String targetNum;
|
||||
|
||||
/** 状态,取值见 {@code AiTaskStatusEnum} */
|
||||
@TableField(value = "status")
|
||||
private String status;
|
||||
|
||||
/** 提交时的请求参数 JSON */
|
||||
@TableField(value = "request_payload")
|
||||
private String requestPayload;
|
||||
|
||||
/** 成功结果 JSON */
|
||||
@TableField(value = "result_payload")
|
||||
private String resultPayload;
|
||||
|
||||
/** 失败原因(用户可见文案) */
|
||||
@TableField(value = "error_message")
|
||||
private String errorMessage;
|
||||
|
||||
@TableField(value = "started_time")
|
||||
private LocalDateTime startedTime;
|
||||
|
||||
@TableField(value = "finished_time")
|
||||
private LocalDateTime finishedTime;
|
||||
|
||||
@TableField(exist = false)
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static AiTaskEntity initNewTask(String aiType, String targetNum, String requestPayload) {
|
||||
AiTaskEntity task = new AiTaskEntity();
|
||||
task.setTaskNum(GenerateNumTool.generateNum("AITASK"));
|
||||
task.setAiType(aiType);
|
||||
task.setTargetNum(targetNum);
|
||||
task.setStatus(AiTaskStatusEnum.PENDING.name());
|
||||
task.setRequestPayload(requestPayload);
|
||||
return task;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return AiTaskStatusEnum.ACTIVE.contains(AiTaskStatusEnum.valueOf(status));
|
||||
}
|
||||
|
||||
public boolean isFinished() {
|
||||
return AiTaskStatusEnum.SUCCEEDED.name().equals(status)
|
||||
|| AiTaskStatusEnum.FAILED.name().equals(status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.guo.learningprogresstracker.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* AI 任务状态(AI-02)。
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum AiTaskStatusEnum {
|
||||
|
||||
/** 已提交,等待执行 */
|
||||
PENDING("正在准备"),
|
||||
|
||||
/** 执行中 */
|
||||
RUNNING("正在生成"),
|
||||
|
||||
/** 已完成,结果可重复获取 */
|
||||
SUCCEEDED("已完成"),
|
||||
|
||||
/** 已失败,允许用户重新提交 */
|
||||
FAILED("失败了");
|
||||
|
||||
private final String description;
|
||||
|
||||
/** 进行中的状态集合:用于「生成中」判定与防重复提交 */
|
||||
public static final Set<AiTaskStatusEnum> ACTIVE = EnumSet.of(PENDING, RUNNING);
|
||||
|
||||
public static Set<String> activeNames() {
|
||||
return ACTIVE.stream().map(Enum::name).collect(java.util.stream.Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.guo.learningprogresstracker.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* AI 任务类型(AI-02)。
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum AiTaskTypeEnum {
|
||||
|
||||
/** 回忆对比:把用户回忆大纲与标准导图对比 */
|
||||
RECALL_COMPARE("回忆对比"),
|
||||
|
||||
/** 标准思维导图生成:全量、增量或按需生成 */
|
||||
MIND_MAP("思维导图生成"),
|
||||
|
||||
/** 学习报告草稿聚合 */
|
||||
REPORT_DRAFT("学习报告草稿");
|
||||
|
||||
private final String description;
|
||||
|
||||
/** 宽松解析:默认大小写不敏感,并用该类型的默认用户可见名称兜底 */
|
||||
public static AiTaskTypeEnum parse(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.guo.learningprogresstracker.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
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;
|
||||
|
||||
/**
|
||||
* AI 异步任务 Mapper(AI-02)。
|
||||
*/
|
||||
@Mapper
|
||||
public interface AiTaskMapper extends BaseMapper<AiTaskEntity> {
|
||||
|
||||
/**
|
||||
* 取待处理任务(执行器用)。
|
||||
*
|
||||
* <p>执行器在请求之外运行,没有登录态供租户拦截器读取,因此显式忽略租户条件;
|
||||
* 这是系统级后台处理,与请求路径的租户隔离互不影响。自定义 SQL 不会被
|
||||
* {@code @TableLogic} 自动追加条件,所以 {@code deleted = 0} 必须显式写出。</p>
|
||||
*/
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
@Select("""
|
||||
SELECT *
|
||||
FROM ai_tasks
|
||||
WHERE deleted = 0
|
||||
AND status = 'PENDING'
|
||||
ORDER BY created_time ASC
|
||||
LIMIT #{limit}
|
||||
""")
|
||||
List<AiTaskEntity> selectPendingTasks(@Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 按主键取任务(执行器用)。
|
||||
*
|
||||
* <p>执行器在请求之外运行,此时还不知道任务属于哪个租户,无法让租户拦截器注入条件;
|
||||
* 因此这里显式忽略租户。读到任务后,执行器会以任务自己的 {@code created_by} 作为租户身份执行,
|
||||
* 后续所有业务查询仍然受租户隔离约束。</p>
|
||||
*/
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
@Select("SELECT * FROM ai_tasks WHERE id = #{id} AND deleted = 0")
|
||||
AiTaskEntity selectTaskById(@Param("id") Integer id);
|
||||
|
||||
/**
|
||||
* 抢占任务:只有仍处于 PENDING 的任务才会被置为 RUNNING,保证多副本/多线程下不重复执行。
|
||||
*
|
||||
* @return 受影响行数,0 表示已被其他执行者抢走
|
||||
*/
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
@Update("""
|
||||
UPDATE ai_tasks
|
||||
SET status = 'RUNNING',
|
||||
started_time = #{startedTime},
|
||||
last_modified_time = #{startedTime}
|
||||
WHERE id = #{id}
|
||||
AND status = 'PENDING'
|
||||
AND deleted = 0
|
||||
""")
|
||||
int claimTask(@Param("id") Integer id, @Param("startedTime") LocalDateTime startedTime);
|
||||
|
||||
/**
|
||||
* 回收超时未回写的任务(执行器崩溃或进程被杀时,任务会永远停在 RUNNING)。
|
||||
* 置回 PENDING 让执行器重试;同时清掉开始时间,便于重新计时。
|
||||
*/
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
@Update("""
|
||||
UPDATE ai_tasks
|
||||
SET status = 'PENDING',
|
||||
started_time = NULL,
|
||||
last_modified_time = #{now}
|
||||
WHERE status = 'RUNNING'
|
||||
AND deleted = 0
|
||||
AND started_time IS NOT NULL
|
||||
AND started_time <= #{cutoff}
|
||||
""")
|
||||
int reclaimStuckTasks(@Param("cutoff") LocalDateTime cutoff, @Param("now") LocalDateTime now);
|
||||
|
||||
/**
|
||||
* 回写结果:只有仍处于 RUNNING 的任务才会被写入,避免超时回收后与新执行者互相覆盖。
|
||||
*/
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
@Update("""
|
||||
UPDATE ai_tasks
|
||||
SET status = #{status},
|
||||
result_payload = #{resultPayload},
|
||||
error_message = #{errorMessage},
|
||||
finished_time = #{finishedTime},
|
||||
last_modified_time = #{finishedTime}
|
||||
WHERE id = #{id}
|
||||
AND status = 'RUNNING'
|
||||
AND deleted = 0
|
||||
""")
|
||||
int finishTask(AiTaskEntity task);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.guo.learningprogresstracker.service;
|
||||
|
||||
import com.guo.learningprogresstracker.dto.AiTaskResponse;
|
||||
import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest;
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.exception.ErrorParameterException;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 异步任务服务(AI-02)。
|
||||
*
|
||||
* <p>提交与执行分离:提交只落一条 PENDING 记录并立刻返回任务标识;执行由请求线程之外
|
||||
* 的执行器完成。因此接口不再随 AI 耗时增长,刷新页面也不会丢失结果。</p>
|
||||
*/
|
||||
public interface AiTaskService {
|
||||
|
||||
/**
|
||||
* 提交 AI 任务。
|
||||
*
|
||||
* <p>同一用户 + 同一类型 + 同一目标若已有进行中任务,直接复用(AI-04 的「生成中」语义:
|
||||
* 返回任务状态而不是可能为空的实体),不会重复触发生成。</p>
|
||||
*/
|
||||
AiTaskResponse submit(AiTaskSubmitRequest request) throws ErrorParameterException, NotFindEntitiesException;
|
||||
|
||||
/**
|
||||
* 按任务标识查询任务状态与结果;结果可重复获取。
|
||||
*/
|
||||
AiTaskResponse getByTaskNum(String taskNum) throws NotFindEntitiesException;
|
||||
|
||||
/**
|
||||
* 查询某目标最近的 AI 任务(用于离开页面再回来时恢复生成状态)。
|
||||
*
|
||||
* @return 无任务时返回 null
|
||||
*/
|
||||
AiTaskResponse findLatest(String type, String targetNum);
|
||||
|
||||
/**
|
||||
* 取出并抢占待处理任务(执行器入口);没有可执行任务时返回空列表。
|
||||
*/
|
||||
List<AiTaskEntity> claimPendingTasks(int limit);
|
||||
|
||||
/**
|
||||
* 抢占指定任务(提交后立即投递的入口)。
|
||||
*
|
||||
* @return 抢占成功返回任务;已被其他执行者抢走或状态不允许时返回空
|
||||
*/
|
||||
java.util.Optional<AiTaskEntity> claimTask(Integer id);
|
||||
|
||||
/**
|
||||
* 回写成功结果。
|
||||
*/
|
||||
void markSucceeded(AiTaskEntity task, Map<String, Object> result);
|
||||
|
||||
/**
|
||||
* 回写失败结果(只记用户可见文案,技术细节由调用方写日志)。
|
||||
*/
|
||||
void markFailed(AiTaskEntity task, String message);
|
||||
|
||||
/**
|
||||
* 回收因进程中断而卡在 RUNNING 的任务,使其可被重新执行。
|
||||
*
|
||||
* @return 被回收的任务数
|
||||
*/
|
||||
int reclaimStuckTasks();
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.guo.learningprogresstracker.service;
|
||||
|
||||
import com.guo.learningprogresstracker.dto.RecallCompareOutcome;
|
||||
import com.guo.learningprogresstracker.dto.ReviewTiming;
|
||||
import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity;
|
||||
import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity;
|
||||
@@ -16,9 +17,11 @@ import java.util.Map;
|
||||
public interface StandardMindMapService {
|
||||
|
||||
/**
|
||||
* 获取指定任务的标准思维导图,不存在时自动生成。
|
||||
* 获取指定任务已有的标准思维导图;不存在时返回 null。
|
||||
*
|
||||
* <p>不在读取路径上触发生成:生成可能耗时数分钟(AI-02),应由 AI 任务异步完成。</p>
|
||||
*/
|
||||
ReviewStandardMindMapEntity getOrGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException;
|
||||
ReviewStandardMindMapEntity getExisting(String taskNum) throws NotFindEntitiesException;
|
||||
|
||||
/**
|
||||
* 强制重新生成指定任务的标准思维导图。
|
||||
@@ -36,14 +39,16 @@ public interface StandardMindMapService {
|
||||
ReviewStandardMindMapEntity updateByOutline(String taskNum, String outline) throws NotFindEntitiesException;
|
||||
|
||||
/**
|
||||
* 用户提交回忆大纲,与标准导图对比并返回结果。
|
||||
* 用户提交回忆大纲,与标准导图对比。
|
||||
*
|
||||
* <p>由 AI 任务执行器在请求线程之外调用;方法本身不持有事务,避免等待 AI 时占用数据库连接。</p>
|
||||
*
|
||||
* @param recallOutline 用户回忆的缩进大纲文本
|
||||
* @param focusPath 可选:标准导图中的节点路径(/ 分隔),指定后仅对比该子树
|
||||
* @param timing 可选:本次复习行为的计时信息(复习-07),为空时不计复习耗时
|
||||
*/
|
||||
ReviewStandardMindMapEntity recallCompare(String taskNum, String recallOutline, String focusPath,
|
||||
ReviewTiming timing) throws NotFindEntitiesException, OperationFailedException;
|
||||
RecallCompareOutcome recallCompare(String taskNum, String recallOutline, String focusPath,
|
||||
ReviewTiming timing) throws NotFindEntitiesException, OperationFailedException;
|
||||
|
||||
/**
|
||||
* 根据内容文本在标准导图中查找最匹配的节点,返回节点路径。
|
||||
|
||||
@@ -41,6 +41,13 @@ public interface StudySessionsService extends IService<StudySessionsEntity> {
|
||||
|
||||
StudySessionResponse getActiveSession(String excludeTaskNum);
|
||||
|
||||
/**
|
||||
* 生成学习报告草稿(AI 聚合残片,不可用时降级为按序拼接)。
|
||||
*
|
||||
* <p>由 AI 任务执行器调用,不在请求线程内执行(AI-02)。</p>
|
||||
*/
|
||||
String buildReportDraft(String sessionNum) throws ErrorParameterException;
|
||||
|
||||
/**
|
||||
* 惰性收敛(会话-04):把当前用户悬挂的进行中会话按硬兜底阈值强制暂停。
|
||||
* <p>由读取路径调用(活跃会话、任务未结束会话),用户不访问时由定时扫描兜底。</p>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.guo.learningprogresstracker.service.event;
|
||||
|
||||
/**
|
||||
* AI 任务已提交事件(AI-02)。
|
||||
*
|
||||
* <p>提交与执行解耦:提交方只负责落库并发出事件,执行由异步监听器在请求线程之外完成,
|
||||
* 这样 {@code AiTaskService} 不必反过来依赖执行器,也不会形成循环依赖。</p>
|
||||
*
|
||||
* @param taskId 任务主键
|
||||
*/
|
||||
public record AiTaskSubmittedEvent(Integer taskId) {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
/**
|
||||
* AI 任务执行失败(AI-02):{@code message} 是给用户看的文案,技术细节由抛出方写日志。
|
||||
*/
|
||||
public class AiTaskFailedException extends RuntimeException {
|
||||
|
||||
public AiTaskFailedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public AiTaskFailedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskTypeEnum;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 一类 AI 任务的具体执行逻辑(AI-02)。
|
||||
*
|
||||
* <p>实现类在请求线程之外被调用,因此可以放心地同步等待 AI;但不要在实现里开启长事务,
|
||||
* 否则会把「等待 AI 时不占用数据库连接」这条约束重新破坏掉。</p>
|
||||
*/
|
||||
public interface AiTaskHandler {
|
||||
|
||||
/** 该实现负责的任务类型 */
|
||||
AiTaskTypeEnum type();
|
||||
|
||||
/**
|
||||
* 执行任务。
|
||||
*
|
||||
* @param task 任务实体(status 已是 RUNNING)
|
||||
* @param params 提交时的参数(可能为空 Map)
|
||||
* @return 写回 result_payload 的结果
|
||||
* @throws AiTaskFailedException 业务上可预期的失败,消息会展示给用户
|
||||
*/
|
||||
Map<String, Object> execute(AiTaskEntity task, Map<String, Object> params);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskTypeEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 任务处理器注册表(AI-02):按类型分发到具体实现。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AiTaskHandlerRegistry {
|
||||
|
||||
private final Map<AiTaskTypeEnum, AiTaskHandler> handlers = new EnumMap<>(AiTaskTypeEnum.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AiTaskHandlerRegistry(List<AiTaskHandler> handlerList, ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
for (AiTaskHandler handler : handlerList) {
|
||||
AiTaskHandler previous = handlers.put(handler.type(), handler);
|
||||
if (previous != null) {
|
||||
log.warn("AI 任务类型 {} 有多个处理器,后注册的 {} 覆盖了 {}",
|
||||
handler.type(), handler.getClass().getSimpleName(), previous.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
log.info("AI 任务处理器已注册: {}", handlers.keySet());
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行任务。
|
||||
*
|
||||
* @throws AiTaskFailedException 类型无处理器或参数解析失败
|
||||
*/
|
||||
public Map<String, Object> execute(AiTaskEntity task) {
|
||||
AiTaskTypeEnum type = AiTaskTypeEnum.parse(task.getAiType());
|
||||
AiTaskHandler handler = type == null ? null : handlers.get(type);
|
||||
if (handler == null) {
|
||||
log.error("AI 任务类型[{}]没有对应的处理器", task.getAiType());
|
||||
throw new AiTaskFailedException("这个功能暂时不可用,请稍后再试");
|
||||
}
|
||||
return handler.execute(task, parseParams(task));
|
||||
}
|
||||
|
||||
private Map<String, Object> parseParams(AiTaskEntity task) {
|
||||
if (!StringUtils.hasText(task.getRequestPayload())) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(task.getRequestPayload(), new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error("AI 任务[{}]参数解析失败", task.getTaskNum(), e);
|
||||
throw new AiTaskFailedException("这次请求的参数丢了,请重新发起");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.guo.learningprogresstracker.config.AiTaskConfig;
|
||||
import com.guo.learningprogresstracker.config.AiTaskProperties;
|
||||
import com.guo.learningprogresstracker.common.TenantContext;
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.service.AiTaskService;
|
||||
import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 任务执行器(AI-02)。
|
||||
*
|
||||
* <p>两条触发路径共用同一套「条件更新抢占」,因此不会重复执行:</p>
|
||||
* <ul>
|
||||
* <li>提交后立即投递:让「无需 AI 的降级路径」也能秒级完成,用户不必等一个扫描周期;</li>
|
||||
* <li>定时兜底扫描:进程重启、投递失败或事件丢失时接手待处理任务。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AiTaskRunner {
|
||||
|
||||
private final AiTaskService aiTaskService;
|
||||
private final AiTaskHandlerRegistry handlerRegistry;
|
||||
private final AiTaskProperties properties;
|
||||
|
||||
/**
|
||||
* 提交后立即执行。事务提交后才触发,保证执行线程能读到刚插入的任务行;
|
||||
* 无事务时(单条 insert 自动提交)由 {@code fallbackExecution} 直接执行。
|
||||
*/
|
||||
@Async(AiTaskConfig.AI_TASK_EXECUTOR)
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
|
||||
public void onTaskSubmitted(AiTaskSubmittedEvent event) {
|
||||
try {
|
||||
aiTaskService.claimTask(event.taskId()).ifPresent(this::executeClaimed);
|
||||
} catch (Exception e) {
|
||||
// 不向外抛:定时扫描会重新接手这个任务
|
||||
log.error("[AI 任务] 立即执行失败,等待定时扫描接手: taskId={}", event.taskId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时兜底扫描。异常只记录不抛出,避免一次失败导致调度停止。
|
||||
*
|
||||
* <p>{@code initialDelayString} 让「立即投递」先跑:生产上延迟一个扫描周期即可,
|
||||
* 测试环境把它调大,保证自动扫描不会与用例互相干扰(用例直接调本方法)。</p>
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "${lpt.ai-task.scan-interval-ms:3000}",
|
||||
initialDelayString = "${lpt.ai-task.scan-initial-delay-ms:3000}")
|
||||
public void scanPendingTasks() {
|
||||
try {
|
||||
List<AiTaskEntity> tasks = aiTaskService.claimPendingTasks(properties.getScanBatchSize());
|
||||
for (AiTaskEntity task : tasks) {
|
||||
executeClaimed(task);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("[AI 任务] 定时扫描失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行已抢占的任务并回写结果。
|
||||
*
|
||||
* <p>执行线程没有 Web 上下文,租户拦截器与公共字段自动填充都取不到当前用户,
|
||||
* 因此这里显式以任务所属用户的身份执行;后续业务查询与写入仍然受租户隔离约束。</p>
|
||||
*/
|
||||
private void executeClaimed(AiTaskEntity task) {
|
||||
try {
|
||||
Map<String, Object> result = TenantContext.callAs(task.getCreatedBy(), task.getDeviceInfo(),
|
||||
() -> handlerRegistry.execute(task));
|
||||
aiTaskService.markSucceeded(task, result);
|
||||
log.info("[AI 任务] 完成: taskNum={}, type={}, targetNum={}",
|
||||
task.getTaskNum(), task.getAiType(), task.getTargetNum());
|
||||
} catch (AiTaskFailedException e) {
|
||||
log.warn("[AI 任务] 失败: taskNum={}, type={}, 原因={}",
|
||||
task.getTaskNum(), task.getAiType(), e.getMessage());
|
||||
aiTaskService.markFailed(task, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("[AI 任务] 异常: taskNum={}, type={}", task.getTaskNum(), task.getAiType(), e);
|
||||
aiTaskService.markFailed(task, "生成失败了,请稍后再试");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.guo.learningprogresstracker.config.AiTaskProperties;
|
||||
import com.guo.learningprogresstracker.dto.AiTaskResponse;
|
||||
import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest;
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskStatusEnum;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskTypeEnum;
|
||||
import com.guo.learningprogresstracker.exception.ErrorParameterException;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
import com.guo.learningprogresstracker.mapper.AiTaskMapper;
|
||||
import com.guo.learningprogresstracker.service.AiTaskService;
|
||||
import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* AI 异步任务服务实现(AI-02)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AiTaskServiceImpl implements AiTaskService {
|
||||
|
||||
private final AiTaskMapper aiTaskMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AiTaskProperties properties;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@Override
|
||||
public AiTaskResponse submit(AiTaskSubmitRequest request)
|
||||
throws ErrorParameterException, NotFindEntitiesException {
|
||||
AiTaskTypeEnum type = AiTaskTypeEnum.parse(request.getType());
|
||||
if (type == null) {
|
||||
log.warn("不支持的 AI 任务类型: {}", request.getType());
|
||||
throw new ErrorParameterException("这个功能暂时不可用,请稍后再试");
|
||||
}
|
||||
if (!StringUtils.hasText(request.getTargetNum())) {
|
||||
throw new ErrorParameterException("请先指定要处理的对象");
|
||||
}
|
||||
|
||||
String targetNum = request.getTargetNum().trim();
|
||||
|
||||
// AI-04:同一目标已有进行中任务时复用,不重复触发生成
|
||||
Optional<AiTaskEntity> active = findActiveTask(type, targetNum);
|
||||
if (active.isPresent()) {
|
||||
log.info("AI 任务复用进行中的任务: type={}, targetNum={}, taskNum={}",
|
||||
type, targetNum, active.get().getTaskNum());
|
||||
return toResponse(active.get());
|
||||
}
|
||||
|
||||
AiTaskEntity task = AiTaskEntity.initNewTask(type.name(), targetNum, writeJson(request.getParams()));
|
||||
aiTaskMapper.insert(task);
|
||||
log.info("AI 任务已提交: type={}, targetNum={}, taskNum={}", type, targetNum, task.getTaskNum());
|
||||
|
||||
// 立即投递执行(事件在事务提交后触发);投递失败也不影响正确性,定时兜底会接手
|
||||
eventPublisher.publishEvent(new AiTaskSubmittedEvent(task.getId()));
|
||||
|
||||
return toResponse(task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AiTaskResponse getByTaskNum(String taskNum) throws NotFindEntitiesException {
|
||||
AiTaskEntity task = aiTaskMapper.selectOne(Wrappers.<AiTaskEntity>lambdaQuery()
|
||||
.eq(AiTaskEntity::getTaskNum, taskNum)
|
||||
.last("LIMIT 1"));
|
||||
if (task == null) {
|
||||
log.warn("AI 任务[{}]不存在", taskNum);
|
||||
throw new NotFindEntitiesException("这个任务不存在或已被清理,请重新发起");
|
||||
}
|
||||
return toResponse(task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AiTaskResponse findLatest(String type, String targetNum) {
|
||||
AiTaskTypeEnum taskType = AiTaskTypeEnum.parse(type);
|
||||
if (taskType == null || !StringUtils.hasText(targetNum)) {
|
||||
return null;
|
||||
}
|
||||
AiTaskEntity task = aiTaskMapper.selectOne(Wrappers.<AiTaskEntity>lambdaQuery()
|
||||
.eq(AiTaskEntity::getAiType, taskType.name())
|
||||
.eq(AiTaskEntity::getTargetNum, targetNum.trim())
|
||||
.orderByDesc(AiTaskEntity::getCreatedTime)
|
||||
.last("LIMIT 1"));
|
||||
return task == null ? null : toResponse(task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiTaskEntity> claimPendingTasks(int limit) {
|
||||
reclaimStuckTasks();
|
||||
|
||||
List<AiTaskEntity> pending = aiTaskMapper.selectPendingTasks(limit);
|
||||
if (pending.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<AiTaskEntity> claimed = new ArrayList<>();
|
||||
for (AiTaskEntity task : pending) {
|
||||
claimTask(task.getId()).ifPresent(claimed::add);
|
||||
}
|
||||
return claimed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AiTaskEntity> claimTask(Integer id) {
|
||||
if (id == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// 抢占阶段还不知道租户,必须走忽略租户的读取(见 AiTaskMapper)
|
||||
AiTaskEntity task = aiTaskMapper.selectTaskById(id);
|
||||
if (task == null || !AiTaskStatusEnum.PENDING.name().equals(task.getStatus())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
// 条件更新抢占:多副本 / 立即投递与定时扫描并发时都只有一个执行者成功
|
||||
if (aiTaskMapper.claimTask(id, now) == 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
task.setStatus(AiTaskStatusEnum.RUNNING.name());
|
||||
task.setStartedTime(now);
|
||||
return Optional.of(task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markSucceeded(AiTaskEntity task, Map<String, Object> result) {
|
||||
task.setStatus(AiTaskStatusEnum.SUCCEEDED.name());
|
||||
task.setResultPayload(writeJson(result));
|
||||
task.setErrorMessage(null);
|
||||
task.setFinishedTime(LocalDateTime.now());
|
||||
if (aiTaskMapper.finishTask(task) == 0) {
|
||||
log.warn("AI 任务[{}]结果回写时已被回收或结束,本次结果丢弃", task.getTaskNum());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markFailed(AiTaskEntity task, String message) {
|
||||
task.setStatus(AiTaskStatusEnum.FAILED.name());
|
||||
task.setResultPayload(null);
|
||||
task.setErrorMessage(abbreviate(message));
|
||||
task.setFinishedTime(LocalDateTime.now());
|
||||
if (aiTaskMapper.finishTask(task) == 0) {
|
||||
log.warn("AI 任务[{}]失败状态回写时已被回收或结束", task.getTaskNum());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int reclaimStuckTasks() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime cutoff = now.minusSeconds(properties.getStuckTimeoutSeconds());
|
||||
int reclaimed = aiTaskMapper.reclaimStuckTasks(cutoff, now);
|
||||
if (reclaimed > 0) {
|
||||
log.warn("[AI 任务] 回收了 {} 个卡在执行中的任务(可能因进程中断)", reclaimed);
|
||||
}
|
||||
return reclaimed;
|
||||
}
|
||||
|
||||
/** 进行中任务:PENDING 或 RUNNING */
|
||||
private Optional<AiTaskEntity> findActiveTask(AiTaskTypeEnum type, String targetNum) {
|
||||
return Optional.ofNullable(aiTaskMapper.selectOne(Wrappers.<AiTaskEntity>lambdaQuery()
|
||||
.eq(AiTaskEntity::getAiType, type.name())
|
||||
.eq(AiTaskEntity::getTargetNum, targetNum)
|
||||
.in(AiTaskEntity::getStatus, AiTaskStatusEnum.activeNames())
|
||||
.orderByDesc(AiTaskEntity::getCreatedTime)
|
||||
.last("LIMIT 1")));
|
||||
}
|
||||
|
||||
private AiTaskResponse toResponse(AiTaskEntity task) {
|
||||
return AiTaskResponse.from(task, readResult(task));
|
||||
}
|
||||
|
||||
/** 未完成的任务不返回结果,避免前端拿到半成品 */
|
||||
private Map<String, Object> readResult(AiTaskEntity task) {
|
||||
if (!AiTaskStatusEnum.SUCCEEDED.name().equals(task.getStatus())
|
||||
|| !StringUtils.hasText(task.getResultPayload())) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(task.getResultPayload(), new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error("AI 任务[{}]结果解析失败", task.getTaskNum(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String writeJson(Map<String, Object> payload) {
|
||||
if (payload == null || payload.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(payload);
|
||||
} catch (Exception e) {
|
||||
log.warn("AI 任务参数序列化失败: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String abbreviate(String message) {
|
||||
if (message == null) {
|
||||
return "生成失败,请稍后再试";
|
||||
}
|
||||
return message.length() > 500 ? message.substring(0, 500) : message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskTypeEnum;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
import com.guo.learningprogresstracker.exception.OperationFailedException;
|
||||
import com.guo.learningprogresstracker.service.StandardMindMapService;
|
||||
import com.guo.learningprogresstracker.utils.MindMapTreeTool;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 标准思维导图生成任务(AI-02)。
|
||||
*
|
||||
* <p>支持三种模式:{@code full}(全量重新生成)、{@code incremental}(增量合并保留用户编辑)、
|
||||
* {@code ensure}(仅在缺失时生成,用于读取页面按需触发)。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MindMapAiTaskHandler implements AiTaskHandler {
|
||||
|
||||
private static final String MODE_INCREMENTAL = "incremental";
|
||||
private static final String MODE_ENSURE = "ensure";
|
||||
|
||||
private final StandardMindMapService standardMindMapService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public AiTaskTypeEnum type() {
|
||||
return AiTaskTypeEnum.MIND_MAP;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> execute(AiTaskEntity task, Map<String, Object> params) {
|
||||
String mode = params.get("mode") == null ? "full" : String.valueOf(params.get("mode"));
|
||||
String taskNum = task.getTargetNum();
|
||||
|
||||
try {
|
||||
// ensure 模式下已有导图就直接返回,不做无意义的重新生成(也不重复计费)
|
||||
if (MODE_ENSURE.equalsIgnoreCase(mode)) {
|
||||
ReviewStandardMindMapEntity existing = standardMindMapService.getExisting(taskNum);
|
||||
if (existing != null) {
|
||||
return toPayload(existing, "已存在,跳过生成");
|
||||
}
|
||||
return toPayload(standardMindMapService.regenerate(taskNum), "按需生成");
|
||||
}
|
||||
if (MODE_INCREMENTAL.equalsIgnoreCase(mode)) {
|
||||
return toPayload(standardMindMapService.incrementalGenerate(taskNum), "增量更新");
|
||||
}
|
||||
return toPayload(standardMindMapService.regenerate(taskNum), "全量生成");
|
||||
} catch (NotFindEntitiesException | OperationFailedException e) {
|
||||
throw new AiTaskFailedException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> toPayload(ReviewStandardMindMapEntity entity, String summary) {
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("standardMapId", entity.getId());
|
||||
payload.put("generator", entity.getGenerator());
|
||||
payload.put("nodeCount", MindMapTreeTool.countNodes(
|
||||
MindMapTreeTool.fromJson(entity.getContent(), objectMapper)));
|
||||
payload.put("summary", summary);
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.guo.learningprogresstracker.dto.RecallCompareOutcome;
|
||||
import com.guo.learningprogresstracker.dto.ReviewTiming;
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskTypeEnum;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
import com.guo.learningprogresstracker.exception.OperationFailedException;
|
||||
import com.guo.learningprogresstracker.service.StandardMindMapService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 回忆对比任务(AI-02):把用户回忆大纲与标准导图对比并落回忆记录。
|
||||
*
|
||||
* <p>这条链路原先在 {@code @Transactional} 里同步等待 AI 最长 10 分钟,会占满数据库连接池;
|
||||
* 现在跑在 AI 任务执行器里,等待期间不持有任何请求期事务。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RecallCompareAiTaskHandler implements AiTaskHandler {
|
||||
|
||||
private final StandardMindMapService standardMindMapService;
|
||||
|
||||
@Override
|
||||
public AiTaskTypeEnum type() {
|
||||
return AiTaskTypeEnum.RECALL_COMPARE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> execute(AiTaskEntity task, Map<String, Object> params) {
|
||||
String recallOutline = asString(params, "recallOutline");
|
||||
if (!StringUtils.hasText(recallOutline)) {
|
||||
throw new AiTaskFailedException("请先填写回忆大纲");
|
||||
}
|
||||
String focusPath = asString(params, "focusPath");
|
||||
ReviewTiming timing = new ReviewTiming(
|
||||
asTime(params, "reviewStartedAt"),
|
||||
asTime(params, "reviewLastInteractionAt"),
|
||||
asInteger(params, "reviewDurationSeconds"));
|
||||
|
||||
try {
|
||||
RecallCompareOutcome outcome = standardMindMapService.recallCompare(
|
||||
task.getTargetNum(), recallOutline, focusPath, timing);
|
||||
return outcome.toPayload();
|
||||
} catch (NotFindEntitiesException e) {
|
||||
throw new AiTaskFailedException(e.getMessage());
|
||||
} catch (OperationFailedException e) {
|
||||
throw new AiTaskFailedException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static String asString(Map<String, Object> params, String key) {
|
||||
Object value = params.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
private static Integer asInteger(Map<String, Object> params, String key) {
|
||||
Object value = params.get(key);
|
||||
if (value instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
if (value instanceof String text && !text.isBlank()) {
|
||||
try {
|
||||
return Integer.valueOf(text.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 前端上报的是无时区的本地时间字符串;解析失败按缺失处理,不影响对比本身 */
|
||||
private static LocalDateTime asTime(Map<String, Object> params, String key) {
|
||||
String text = asString(params, key);
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return LocalDateTime.parse(text.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
log.warn("AI 任务参数[{}]时间格式无法解析,按缺失处理: {}", key, text);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.guo.learningprogresstracker.entity.AiTaskEntity;
|
||||
import com.guo.learningprogresstracker.enums.AiTaskTypeEnum;
|
||||
import com.guo.learningprogresstracker.exception.ErrorParameterException;
|
||||
import com.guo.learningprogresstracker.service.StudySessionsService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 学习报告草稿任务(AI-02)。
|
||||
*
|
||||
* <p>报告草稿原先由 {@code GET /study-sessions/{sessionNum}/report-draft} 同步触发聚合,
|
||||
* 一个 GET 就可能阻塞 10 分钟并按 AI 计费;现在改为异步任务,读取接口不再产生副作用。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ReportDraftAiTaskHandler implements AiTaskHandler {
|
||||
|
||||
private final StudySessionsService studySessionsService;
|
||||
|
||||
@Override
|
||||
public AiTaskTypeEnum type() {
|
||||
return AiTaskTypeEnum.REPORT_DRAFT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> execute(AiTaskEntity task, Map<String, Object> params) {
|
||||
try {
|
||||
String draft = studySessionsService.buildReportDraft(task.getTargetNum());
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("draft", draft);
|
||||
return payload;
|
||||
} catch (ErrorParameterException e) {
|
||||
throw new AiTaskFailedException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
-56
@@ -3,6 +3,7 @@ package com.guo.learningprogresstracker.service.impl;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.guo.learningprogresstracker.dto.RecallCompareOutcome;
|
||||
import com.guo.learningprogresstracker.dto.ReviewTiming;
|
||||
import com.guo.learningprogresstracker.entity.*;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
@@ -22,8 +23,6 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -51,38 +50,22 @@ public class StandardMindMapServiceImpl implements StandardMindMapService {
|
||||
private static final String MATCH_STATUS_MATCHED = "MATCHED";
|
||||
private static final String MATCH_STATUS_MISSED = "MISSED";
|
||||
|
||||
/** 防并发生成:taskNum → 是否正在生成中 */
|
||||
private final ConcurrentHashMap<String, AtomicBoolean> generatingTasks = new ConcurrentHashMap<>();
|
||||
|
||||
// ============ 查询与生成 ============
|
||||
|
||||
@Override
|
||||
public ReviewStandardMindMapEntity getOrGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException {
|
||||
public ReviewStandardMindMapEntity getExisting(String taskNum) throws NotFindEntitiesException {
|
||||
ensureTaskExists(taskNum);
|
||||
ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum);
|
||||
return existing != null ? existing : doGenerate(taskNum);
|
||||
return queryByTaskNum(taskNum);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReviewStandardMindMapEntity regenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
// 防并发生成:同一任务正在生成时直接返回当前实体
|
||||
AtomicBoolean lock = generatingTasks.computeIfAbsent(taskNum, k -> new AtomicBoolean(false));
|
||||
if (!lock.compareAndSet(false, true)) {
|
||||
ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum);
|
||||
log.warn("任务[{}]正在生成中,跳过重复请求", taskNum);
|
||||
return existing;
|
||||
}
|
||||
try {
|
||||
return doGenerate(taskNum);
|
||||
} finally {
|
||||
lock.set(false);
|
||||
generatingTasks.remove(taskNum);
|
||||
}
|
||||
// 并发生成由 ai_tasks 的进行中任务判定拦截(AI-04),不再依赖 JVM 内存锁
|
||||
return doGenerate(taskNum);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ReviewStandardMindMapEntity incrementalGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum);
|
||||
@@ -90,34 +73,24 @@ public class StandardMindMapServiceImpl implements StandardMindMapService {
|
||||
log.warn("任务[{}]标准思维导图尚不存在,无法增量更新", taskNum);
|
||||
throw new NotFindEntitiesException("还没有生成过标准思维导图,请先完整生成一次哦");
|
||||
}
|
||||
// 防并发生成
|
||||
AtomicBoolean lock = generatingTasks.computeIfAbsent(taskNum, k -> new AtomicBoolean(false));
|
||||
if (!lock.compareAndSet(false, true)) {
|
||||
log.warn("任务[{}]正在生成中,跳过重复增量请求", taskNum);
|
||||
return existing;
|
||||
}
|
||||
try {
|
||||
ReviewStandardMindMapEntity fresh = doGenerate(taskNum);
|
||||
// 合并新旧树:保留用户编辑过的节点,追加新节点
|
||||
MindMapNode oldRoot = MindMapTreeTool.fromJson(existing.getContent(), objectMapper);
|
||||
MindMapNode newRoot = MindMapTreeTool.fromJson(fresh.getContent(), objectMapper);
|
||||
MindMapNode merged = MindMapTreeTool.mergeTrees(oldRoot, newRoot);
|
||||
String mergedJson = MindMapTreeTool.toJson(merged, objectMapper);
|
||||
String mergedOutline = MindMapTreeTool.toFullOutline(merged);
|
||||
|
||||
existing.setContent(mergedJson);
|
||||
existing.setOutline(mergedOutline);
|
||||
existing.setTitle(merged.getTitle() != null ? merged.getTitle() : "思维导图");
|
||||
existing.setGenerator(GENERATOR_USER_MERGE);
|
||||
existing.setGeneratorVersion(fresh.getGeneratorVersion());
|
||||
existing.setSummary("增量更新,共 " + MindMapTreeTool.countNodes(merged) + " 个节点");
|
||||
existing.setGeneratedTime(LocalDateTime.now());
|
||||
standardMindMapMapper.updateById(existing);
|
||||
return existing;
|
||||
} finally {
|
||||
lock.set(false);
|
||||
generatingTasks.remove(taskNum);
|
||||
}
|
||||
// 生成(可能调用 AI)不放在事务里:等待 AI 期间不应占用数据库连接(AI-01)
|
||||
ReviewStandardMindMapEntity fresh = doGenerate(taskNum);
|
||||
|
||||
// 合并新旧树:保留用户编辑过的节点,追加新节点
|
||||
MindMapNode oldRoot = MindMapTreeTool.fromJson(existing.getContent(), objectMapper);
|
||||
MindMapNode newRoot = MindMapTreeTool.fromJson(fresh.getContent(), objectMapper);
|
||||
MindMapNode merged = MindMapTreeTool.mergeTrees(oldRoot, newRoot);
|
||||
|
||||
existing.setContent(MindMapTreeTool.toJson(merged, objectMapper));
|
||||
existing.setOutline(MindMapTreeTool.toFullOutline(merged));
|
||||
existing.setTitle(merged.getTitle() != null ? merged.getTitle() : "思维导图");
|
||||
existing.setGenerator(GENERATOR_USER_MERGE);
|
||||
existing.setGeneratorVersion(fresh.getGeneratorVersion());
|
||||
existing.setSummary("增量更新,共 " + MindMapTreeTool.countNodes(merged) + " 个节点");
|
||||
existing.setGeneratedTime(LocalDateTime.now());
|
||||
standardMindMapMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -153,14 +126,16 @@ public class StandardMindMapServiceImpl implements StandardMindMapService {
|
||||
// ============ 回忆对比 ============
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ReviewStandardMindMapEntity recallCompare(String taskNum, String recallOutline, String focusPath,
|
||||
ReviewTiming timing)
|
||||
public RecallCompareOutcome recallCompare(String taskNum, String recallOutline, String focusPath,
|
||||
ReviewTiming timing)
|
||||
throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
|
||||
// 1. 获取标准导图(自动生成)
|
||||
ReviewStandardMindMapEntity standard = getOrGenerate(taskNum);
|
||||
// 1. 取标准导图;缺失时按需生成(可能调用 AI,故整个方法不持有事务)
|
||||
ReviewStandardMindMapEntity standard = queryByTaskNum(taskNum);
|
||||
if (standard == null) {
|
||||
standard = doGenerate(taskNum);
|
||||
}
|
||||
|
||||
// 2. 解析标准树和用户回忆树
|
||||
MindMapNode standardRoot = MindMapTreeTool.fromJson(standard.getContent(), objectMapper);
|
||||
@@ -230,7 +205,8 @@ public class StandardMindMapServiceImpl implements StandardMindMapService {
|
||||
taskNum, result.getRecallRatio(), result.getMatchedCount(),
|
||||
result.getMissedCount(), result.getExtraCount(), record.getReviewDurationSeconds());
|
||||
|
||||
return standard;
|
||||
return new RecallCompareOutcome(standard.getId(), record.getId(), result.getRecallRatio(),
|
||||
result.getMatchedCount(), result.getMissedCount(), result.getExtraCount());
|
||||
}
|
||||
|
||||
// ============ 节点查找 ============
|
||||
@@ -238,7 +214,15 @@ public class StandardMindMapServiceImpl implements StandardMindMapService {
|
||||
@Override
|
||||
public Map<String, Object> findNode(String taskNum, String content) throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
ReviewStandardMindMapEntity standard = getOrGenerate(taskNum);
|
||||
ReviewStandardMindMapEntity standard = queryByTaskNum(taskNum);
|
||||
if (standard == null) {
|
||||
// 还没有标准导图时无从匹配;由调用方决定是否先发起生成任务
|
||||
Map<String, Object> empty = new LinkedHashMap<>();
|
||||
empty.put("path", "");
|
||||
empty.put("nodeTitle", "");
|
||||
empty.put("score", 0.0);
|
||||
return empty;
|
||||
}
|
||||
MindMapNode root = MindMapTreeTool.fromJson(standard.getContent(), objectMapper);
|
||||
|
||||
MindMapNode closest = MindMapTreeTool.findClosestNode(root, content);
|
||||
|
||||
+5
-1
@@ -234,8 +234,12 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
|
||||
/**
|
||||
* 生成学习报告草稿:优先调用 lpt-ai 聚合残片,服务不可用时降级为按序拼接。
|
||||
* 草稿仅作为编辑起点返回,不落库——最终报告由用户确认后经 endedStudySession 保存。
|
||||
*
|
||||
* <p>由 AI 任务执行器在请求线程之外调用(AI-02):聚合可能等待 AI 数分钟,
|
||||
* 不能放在读取接口里,否则一个 GET 就会阻塞并按 AI 计费。</p>
|
||||
*/
|
||||
public String generateReportDraft(String sessionNum) throws ErrorParameterException {
|
||||
@Override
|
||||
public String buildReportDraft(String sessionNum) throws ErrorParameterException {
|
||||
StudySessionsEntity session = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class)
|
||||
.eq(StudySessionsEntity::getSessionNum, sessionNum))
|
||||
.orElseThrow(() -> sessionNotFound(sessionNum));
|
||||
|
||||
Reference in New Issue
Block a user