218 lines
8.3 KiB
Java
218 lines
8.3 KiB
Java
package run.webup.platform;
|
||
|
||
import java.math.BigDecimal;
|
||
import java.util.*;
|
||
import org.springframework.jdbc.core.JdbcTemplate;
|
||
import org.springframework.stereotype.Service;
|
||
import org.springframework.transaction.annotation.Transactional;
|
||
|
||
@Service
|
||
public class QueueService {
|
||
static final String ORDER = "run_next DESC,admin_priority DESC,paid_priority DESC,created_at,id";
|
||
private final JdbcTemplate db;
|
||
private final WalletService wallets;
|
||
private final ExecutionAvailability execution;
|
||
|
||
public QueueService(JdbcTemplate db, WalletService wallets, ExecutionAvailability execution) {
|
||
this.db = db;
|
||
this.wallets = wallets;
|
||
this.execution = execution;
|
||
}
|
||
|
||
Map<String, Object> lock() {
|
||
return db.queryForMap("SELECT * FROM ai_queue_config WHERE id=1 FOR UPDATE");
|
||
}
|
||
|
||
public long occupied() {
|
||
return db.queryForObject(
|
||
"SELECT COUNT(*) FROM ai_tasks WHERE status IN ('RUNNING','REVIEW_REQUIRED')", Long.class);
|
||
}
|
||
|
||
public Object info(UUID user) {
|
||
var config =
|
||
db.queryForMap(
|
||
"SELECT max_concurrent,priority_enabled,priority_price,version FROM ai_queue_config"
|
||
+ " WHERE id=1");
|
||
return Map.of(
|
||
"config",
|
||
config,
|
||
"running",
|
||
db.queryForObject("SELECT COUNT(*) FROM ai_tasks WHERE status='RUNNING'", Long.class),
|
||
"reviewSlots",
|
||
db.queryForObject(
|
||
"SELECT COUNT(*) FROM ai_tasks WHERE status='REVIEW_REQUIRED'", Long.class),
|
||
"queued",
|
||
db.queryForObject("SELECT COUNT(*) FROM ai_tasks WHERE status='QUEUED'", Long.class),
|
||
"execution",
|
||
execution.status(),
|
||
"positions",
|
||
db.queryForList(
|
||
"SELECT id,position FROM (SELECT id,user_id,ROW_NUMBER() OVER (ORDER BY "
|
||
+ ORDER
|
||
+ ") AS position FROM ai_tasks WHERE status='QUEUED') q WHERE user_id=?",
|
||
user));
|
||
}
|
||
|
||
@Transactional
|
||
public Object configure(
|
||
UUID actor, int concurrent, boolean enabled, BigDecimal price, String reason, String ip) {
|
||
price = WalletService.money(price);
|
||
if (concurrent < 1 || concurrent > 64 || price.signum() < 0 || (enabled && price.signum() == 0))
|
||
throw new ApiError.Failure(400, "并发需为 1–64,启用付费优先时价格必须大于零");
|
||
var previous = lock();
|
||
db.update(
|
||
"UPDATE ai_queue_config SET"
|
||
+ " max_concurrent=?,priority_enabled=?,priority_price=?,version=version+1,updated_at=CURRENT_TIMESTAMP"
|
||
+ " WHERE id=1",
|
||
concurrent,
|
||
enabled,
|
||
price);
|
||
audit(
|
||
actor,
|
||
"QUEUE_CONFIG",
|
||
"global",
|
||
"并发 "
|
||
+ previous.get("max_concurrent")
|
||
+ " → "
|
||
+ concurrent
|
||
+ ";优先费 "
|
||
+ price
|
||
+ ";启用 "
|
||
+ enabled
|
||
+ ";原因:"
|
||
+ reason,
|
||
ip);
|
||
return Map.of("message", "调度配置已保存;降低并发不强制中断已执行任务");
|
||
}
|
||
|
||
@Transactional
|
||
public Object prioritize(
|
||
UUID actor, UUID task, int priority, boolean next, String reason, String ip) {
|
||
var config = lock();
|
||
var rows = db.queryForList("SELECT status FROM ai_tasks WHERE id=? FOR UPDATE", task);
|
||
if (rows.isEmpty()) throw new ApiError.Failure(404, "任务不存在");
|
||
if (!"QUEUED".equals(rows.getFirst().get("status")))
|
||
throw new ApiError.Failure(409, "只能调整排队中的任务");
|
||
if (priority < -100 || priority > 100) throw new ApiError.Failure(400, "人工优先级需为 -100–100");
|
||
if (next) {
|
||
execution.requireReady();
|
||
db.update("UPDATE ai_tasks SET run_next=FALSE WHERE status='QUEUED' AND run_next=TRUE");
|
||
}
|
||
db.update(
|
||
"UPDATE ai_tasks SET admin_priority=?,run_next=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||
priority,
|
||
next,
|
||
task);
|
||
event(task, "QUEUE_PRIORITY", next ? "管理员指定为下一空闲执行位的首选任务" : "管理员调整排队优先级为 " + priority);
|
||
audit(
|
||
actor,
|
||
next ? "QUEUE_RUN_NEXT" : "QUEUE_PRIORITY",
|
||
task.toString(),
|
||
"优先级 " + priority + ";原因:" + reason,
|
||
ip);
|
||
boolean free = occupied() < ((Number) config.get("max_concurrent")).longValue();
|
||
return Map.of(
|
||
"message",
|
||
next ? (free ? "已请求立即调度,等待真实 Worker 领取" : "并发已满,已指定为下一空闲执行位的首选任务;未中断当前项目") : "排队顺序已更新");
|
||
}
|
||
|
||
@Transactional
|
||
public Object purchase(UUID user, UUID task, BigDecimal expectedPrice, String key) {
|
||
var config = lock();
|
||
var existing =
|
||
db.queryForList(
|
||
"SELECT * FROM queue_priority_orders WHERE user_id=? AND idempotency_key=?", user, key);
|
||
if (!existing.isEmpty()) {
|
||
if (!existing.getFirst().get("task_id").equals(task))
|
||
throw new ApiError.Failure(409, "优先权幂等标识已用于其他任务");
|
||
return existing.getFirst();
|
||
}
|
||
var rows =
|
||
db.queryForList("SELECT * FROM ai_tasks WHERE id=? AND user_id=? FOR UPDATE", task, user);
|
||
if (rows.isEmpty()) throw new ApiError.Failure(404, "任务不存在");
|
||
var previous = db.queryForList("SELECT * FROM queue_priority_orders WHERE task_id=?", task);
|
||
if (!previous.isEmpty()) return previous.getFirst();
|
||
if (!"QUEUED".equals(rows.getFirst().get("status")))
|
||
throw new ApiError.Failure(409, "只有排队中的任务可购买优先权");
|
||
if (!Boolean.TRUE.equals(config.get("priority_enabled")))
|
||
throw new ApiError.Failure(409, "平台暂未开放付费优先");
|
||
execution.requireReady();
|
||
BigDecimal price = (BigDecimal) config.get("priority_price");
|
||
if (price.compareTo(WalletService.money(expectedPrice)) != 0)
|
||
throw new ApiError.Failure(409, "优先权价格已更新,请刷新后确认");
|
||
UUID id = UUID.randomUUID();
|
||
wallets.spend(
|
||
user,
|
||
price,
|
||
id.toString(),
|
||
"priority-buy:" + id,
|
||
"PRIORITY_PURCHASE",
|
||
"本任务排队优先权;首次执行前取消自动退费,开始执行后不自动退费");
|
||
db.update(
|
||
"INSERT INTO"
|
||
+ " queue_priority_orders(id,task_id,user_id,amount,config_version,status,idempotency_key)"
|
||
+ " VALUES (?,?,?,?,?,'PAID',?)",
|
||
id,
|
||
task,
|
||
user,
|
||
price,
|
||
config.get("version"),
|
||
key);
|
||
db.update("UPDATE ai_tasks SET paid_priority=TRUE WHERE id=?", task);
|
||
event(task, "PRIORITY_PURCHASED", "已购买本任务优先权,费用 CNY " + price + ";不抢占正在执行的任务");
|
||
return db.queryForMap("SELECT * FROM queue_priority_orders WHERE id=?", id);
|
||
}
|
||
|
||
@Transactional
|
||
public void consume(UUID task) {
|
||
db.update(
|
||
"UPDATE queue_priority_orders SET status='CONSUMED',consumed_at=CURRENT_TIMESTAMP WHERE"
|
||
+ " task_id=? AND status='PAID'",
|
||
task);
|
||
}
|
||
|
||
@Transactional
|
||
public void refundUnused(UUID task) {
|
||
var orders =
|
||
db.queryForList("SELECT * FROM queue_priority_orders WHERE task_id=? FOR UPDATE", task);
|
||
if (orders.isEmpty() || !"PAID".equals(orders.getFirst().get("status"))) return;
|
||
var order = orders.getFirst();
|
||
UUID user = (UUID) order.get("user_id");
|
||
String id = order.get("id").toString();
|
||
wallets.refundPurchase(
|
||
user,
|
||
(BigDecimal) order.get("amount"),
|
||
"priority-buy:" + id,
|
||
"priority-refund:" + id,
|
||
id,
|
||
"任务首次执行前结束,优先费自动退回钱包");
|
||
db.update(
|
||
"UPDATE queue_priority_orders SET status='REFUNDED',refunded_at=CURRENT_TIMESTAMP WHERE"
|
||
+ " id=?",
|
||
order.get("id"));
|
||
db.update("UPDATE ai_tasks SET paid_priority=FALSE WHERE id=?", task);
|
||
event(task, "PRIORITY_REFUNDED", "首次执行前结束,优先费已退回钱包");
|
||
}
|
||
|
||
private void event(UUID task, String type, String detail) {
|
||
db.update(
|
||
"INSERT INTO ai_task_steps(id,task_id,event,detail) VALUES (?,?,?,?)",
|
||
UUID.randomUUID(),
|
||
task,
|
||
type,
|
||
detail);
|
||
}
|
||
|
||
private void audit(UUID actor, String action, String target, String detail, String ip) {
|
||
db.update(
|
||
"INSERT INTO admin_operation_logs(id,actor_id,action,target,ip,details) VALUES"
|
||
+ " (?,?,?,?,?,?)",
|
||
UUID.randomUUID(),
|
||
actor,
|
||
action,
|
||
target,
|
||
ip,
|
||
detail);
|
||
}
|
||
}
|