96 lines
4.3 KiB
Java
96 lines
4.3 KiB
Java
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, "生成失败了,请稍后再试");
|
|
}
|
|
}
|
|
}
|