feat: add persistent async task mock

This commit is contained in:
wlx committed 2026-09-07 17:42:48 +08:00
1 parent 7949f29f1a
commit cbc7317aa8
6 files changed
+186 -3

No files matched your search

@@ -0,0 +1,105 @@
package com.moyi.controlplane.task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.catalog.CatalogService;
import com.moyi.controlplane.common.ApiException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AsyncTaskService {
private final JdbcTemplate jdbc;
private final ObjectMapper objectMapper;
private final CatalogService catalogService;
public AsyncTaskService(JdbcTemplate jdbc, ObjectMapper objectMapper, CatalogService catalogService) {
this.jdbc = jdbc;
this.objectMapper = objectMapper;
this.catalogService = catalogService;
}
@Transactional
public Map<String, Object> create(String authorization, String taskType, Map<String, Object> input) {
Map<String, Object> key = requireKey(authorization);
String modelId = String.valueOf(input.getOrDefault("model", ""));
Map<String, Object> model = catalogService.activeModel(modelId);
if (model == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
if (!catalogService.keyCanInvoke(key, modelId)) throw new ApiException("MODEL_FORBIDDEN", "当前 Key 无权调用该模型", 403);
if (!taskType.equals(model.get("type")) || !"async".equals(model.get("mode"))) throw new ApiException("NOT_ASYNC_MEDIA_MODEL", "该模型不是对应的异步媒体模型", 400);
String prompt = String.valueOf(input.getOrDefault("prompt", "")).trim();
if (prompt.isBlank()) throw new ApiException("PROMPT_REQUIRED", "生成提示词不能为空");
String id = "task_" + UUID.randomUUID().toString().replace("-", "").substring(0, 24);
UUID apiKeyId = UUID.fromString(String.valueOf(key.get("id")));
UUID userId = catalogService.keyOwnerId(apiKeyId);
OffsetDateTime now = now();
jdbc.update(
"INSERT INTO model_tasks (id, user_id, api_key_id, model_id, task_type, provider_task_id, status, progress, prompt, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'mock', 'queued', 0, ?, ?, ?)",
id, userId, apiKeyId, modelId, taskType, prompt, now, now
);
catalogService.touchKey(key);
return taskView(id);
}
public Map<String, Object> get(String authorization, String taskId) {
Map<String, Object> key = requireKey(authorization);
UUID userId = catalogService.keyOwnerId(UUID.fromString(String.valueOf(key.get("id"))));
try {
return jdbc.queryForObject("SELECT * FROM model_tasks WHERE id = ? AND user_id = ?", this::mapTask, taskId, userId);
} catch (org.springframework.dao.EmptyResultDataAccessException exception) {
throw new ApiException("TASK_NOT_FOUND", "任务不存在", 404);
}
}
@Scheduled(fixedDelayString = "${MOYI_TASK_WORKER_INTERVAL_MS:1000}")
public void completeMockTasks() {
jdbc.update(
"UPDATE model_tasks SET status = 'succeeded', progress = 100, result = CAST(CASE WHEN task_type = '3d' THEN ? ELSE ? END AS jsonb), updated_at = ?, completed_at = ? WHERE status IN ('queued', 'running') AND provider_task_id = 'mock' AND created_at < now() - INTERVAL '500 milliseconds'",
"{\"format\":\"glb\",\"url\":\"https://mock.moyi.ai/tasks/result.glb\"}",
"{\"format\":\"mp4\",\"url\":\"https://mock.moyi.ai/tasks/result.mp4\"}", now(), now()
);
}
private Map<String, Object> requireKey(String authorization) {
if (authorization == null || !authorization.startsWith("Bearer ")) throw new ApiException("UNAUTHENTICATED", "请提供有效的 API Key", 401);
Map<String, Object> key = catalogService.authenticateKey(authorization.substring(7));
if (key == null) throw new ApiException("INVALID_API_KEY", "API Key 无效或已停用", 401);
return key;
}
private Map<String, Object> taskView(String id) { return jdbc.queryForObject("SELECT * FROM model_tasks WHERE id = ?", this::mapTask, id); }
private Map<String, Object> mapTask(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> task = new LinkedHashMap<>();
task.put("id", resultSet.getString("id"));
task.put("provider", "mock");
task.put("model", resultSet.getString("model_id"));
task.put("status", resultSet.getString("status"));
task.put("progress", resultSet.getInt("progress"));
task.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
task.put("updatedAt", resultSet.getObject("updated_at", OffsetDateTime.class));
String result = resultSet.getString("result");
if (result != null) task.put("result", readMap(result));
String error = resultSet.getString("error");
if (error != null) task.put("error", readMap(error));
return task;
}
private Map<String, Object> readMap(String value) {
try { return objectMapper.readValue(value, new TypeReference<>() {}); }
catch (JsonProcessingException exception) { return Map.of(); }
}
private OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); }
}
@@ -0,0 +1,46 @@
package com.moyi.controlplane.task;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1")
public class TaskController {
private final AsyncTaskService tasks;
public TaskController(AsyncTaskService tasks) {
this.tasks = tasks;
}
@PostMapping("/3d/tasks")
public ResponseEntity<Map<String, Object>> create3d(
@RequestHeader(value = "Authorization", required = false) String authorization,
@RequestBody Map<String, Object> input
) {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(Map.of("task", tasks.create(authorization, "3d", input)));
}
@PostMapping("/video/tasks")
public ResponseEntity<Map<String, Object>> createVideo(
@RequestHeader(value = "Authorization", required = false) String authorization,
@RequestBody Map<String, Object> input
) {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(Map.of("task", tasks.create(authorization, "video", input)));
}
@GetMapping("/tasks/{id}")
public Map<String, Object> get(
@RequestHeader(value = "Authorization", required = false) String authorization,
@PathVariable String id
) {
return Map.of("task", tasks.get(authorization, id));
}
}