125 lines
7.9 KiB
Java
125 lines
7.9 KiB
Java
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.common.ApiException;
|
||
|
|
import com.moyi.controlplane.gateway.EnterprisePolicies;
|
||
|
|
import com.moyi.controlplane.gateway.GatewayGuard;
|
||
|
|
import com.moyi.controlplane.usage.UsageAuditService;
|
||
|
|
import java.math.BigDecimal;
|
||
|
|
import java.nio.charset.StandardCharsets;
|
||
|
|
import java.util.LinkedHashMap;
|
||
|
|
import java.util.List;
|
||
|
|
import java.util.Map;
|
||
|
|
import java.util.UUID;
|
||
|
|
import java.util.function.Supplier;
|
||
|
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||
|
|
import org.springframework.stereotype.Service;
|
||
|
|
import org.springframework.transaction.PlatformTransactionManager;
|
||
|
|
import org.springframework.transaction.support.TransactionTemplate;
|
||
|
|
|
||
|
|
/** The one task/wallet/usage settlement transaction, shared by workers and audited reconciliation. */
|
||
|
|
@Service
|
||
|
|
public class TaskSettlementService {
|
||
|
|
private final JdbcTemplate jdbc;
|
||
|
|
private final ObjectMapper json;
|
||
|
|
private final GatewayGuard guard;
|
||
|
|
private final UsageAuditService usage;
|
||
|
|
private final EnterprisePolicies policies;
|
||
|
|
private final TransactionTemplate transactions;
|
||
|
|
|
||
|
|
public TaskSettlementService(JdbcTemplate jdbc, ObjectMapper json, GatewayGuard guard,
|
||
|
|
UsageAuditService usage, PlatformTransactionManager manager) {
|
||
|
|
this.jdbc = jdbc;
|
||
|
|
this.json = json;
|
||
|
|
this.guard = guard;
|
||
|
|
this.usage = usage;
|
||
|
|
this.policies = new EnterprisePolicies(jdbc, json);
|
||
|
|
this.transactions = manager == null ? null : new TransactionTemplate(manager);
|
||
|
|
}
|
||
|
|
|
||
|
|
void finish(String taskId, String status, int progress, Map<String,Object> result, String code, String message) {
|
||
|
|
if (!List.of("succeeded", "failed", "cancelled").contains(status)) throw new IllegalArgumentException("Terminal task state required");
|
||
|
|
transaction(() -> {
|
||
|
|
var task = jdbc.queryForMap("SELECT status,completion_status,pricing_snapshot::text AS pricing_snapshot FROM model_tasks WHERE id=? FOR UPDATE", taskId);
|
||
|
|
if (!List.of("queued", "running", "reconciling").contains(task.get("status"))) return null;
|
||
|
|
if (task.get("completion_status") != null && !status.equals(task.get("completion_status"))) return null;
|
||
|
|
AsyncPriceSchedule.Bill bill = null;
|
||
|
|
String finalCode = code, finalMessage = message;
|
||
|
|
if ("succeeded".equals(status) && task.get("pricing_snapshot") != null) {
|
||
|
|
try { bill = AsyncPriceSchedule.bill(pricing(task.get("pricing_snapshot")), result); }
|
||
|
|
catch (ApiException exception) {
|
||
|
|
finalCode = "TASK_USAGE_PENDING";
|
||
|
|
finalMessage = "生成已完成,但上游计费用量未能核对;暂不扣费,等待核账";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
jdbc.update("UPDATE model_tasks SET status=?,progress=?,result=CAST(? AS jsonb),error=CAST(? AS jsonb),reconciliation_required_at=NULL,updated_at=now(),completed_at=now() WHERE id=?",
|
||
|
|
status, progress, encode(result), finalCode == null ? null : encode(Map.of("code", finalCode, "message", finalMessage)), taskId);
|
||
|
|
if ("TASK_USAGE_PENDING".equals(finalCode)) {
|
||
|
|
release(taskId);
|
||
|
|
jdbc.update("UPDATE model_tasks SET cost_amount=NULL WHERE id=?", taskId);
|
||
|
|
var observed = new LinkedHashMap<String,Object>();
|
||
|
|
if (result != null) for (String field : List.of("usage", "usageMetadata")) if (result.get(field) instanceof Map<?,?> value) observed.put(field, value);
|
||
|
|
jdbc.update("UPDATE usage_events SET cost_amount=NULL,cost_status='pending',observed_usage=CAST(? AS jsonb) WHERE provider_task_id=? AND event_kind='task'", encode(observed), taskId);
|
||
|
|
} else if ("succeeded".equals(status)) settle(taskId, bill);
|
||
|
|
else release(taskId);
|
||
|
|
usage.updateTask(taskId, status, result, finalCode, finalMessage);
|
||
|
|
return null;
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Strict calculation for explicit administrator confirmation: missing usage is an error, not a refund. */
|
||
|
|
BigDecimal confirmedCharge(Map<String,Object> task, Map<String,Object> result) {
|
||
|
|
if (task.get("pricing_snapshot") == null) return (BigDecimal) task.get("reserved_amount");
|
||
|
|
return AsyncPriceSchedule.bill(pricing(task.get("pricing_snapshot")), result).amount();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void settle(String taskId, AsyncPriceSchedule.Bill bill) {
|
||
|
|
var task = jdbc.queryForMap("SELECT user_id,reserved_amount,cost_amount FROM model_tasks WHERE id=? FOR UPDATE", taskId);
|
||
|
|
BigDecimal reserved = (BigDecimal) task.get("reserved_amount");
|
||
|
|
BigDecimal amount = bill == null ? reserved : bill.amount();
|
||
|
|
releasePolicies(taskId, task);
|
||
|
|
if (amount == null || task.get("cost_amount") != null) return;
|
||
|
|
UUID userId = (UUID) task.get("user_id");
|
||
|
|
var wallet = jdbc.queryForMap("SELECT balance,reserved_balance FROM user_wallets WHERE user_id=? FOR UPDATE", userId);
|
||
|
|
BigDecimal before = (BigDecimal) wallet.get("balance"), after = before.subtract(amount);
|
||
|
|
jdbc.update("UPDATE user_wallets SET balance=?,reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", after, reserved, userId);
|
||
|
|
if (amount.signum() > 0) jdbc.update("INSERT INTO wallet_entries(id,user_id,request_id,amount,balance_after,currency,reason,operation,requested_amount,balance_before,actor_user_id) VALUES (?,?,?,?,?,'CNY',?,'usage',?,?,NULL)",
|
||
|
|
UUID.randomUUID(), userId, taskRequestId(taskId), amount.negate(), after, "异步模型任务 · " + taskId, amount, before);
|
||
|
|
jdbc.update("UPDATE model_tasks SET cost_amount=? WHERE id=?", amount, taskId);
|
||
|
|
jdbc.update("UPDATE usage_events SET cost_amount=? WHERE provider_task_id=? AND event_kind='task'", amount, taskId);
|
||
|
|
if (bill != null) jdbc.update("UPDATE usage_events SET input_units=?,output_units=?,observed_usage=jsonb_build_object('input_tokens',?::bigint,'output_tokens',?::bigint,'image_input_tokens',?::bigint) WHERE provider_task_id=? AND event_kind='task'",
|
||
|
|
bill.input(), bill.output(), bill.input(), bill.output(), bill.imageInput(), taskId);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void release(String taskId) {
|
||
|
|
var task = jdbc.queryForMap("SELECT user_id,reserved_amount,cost_amount FROM model_tasks WHERE id=? FOR UPDATE", taskId);
|
||
|
|
BigDecimal amount = (BigDecimal) task.get("reserved_amount");
|
||
|
|
releasePolicies(taskId, task);
|
||
|
|
if (amount != null && task.get("cost_amount") == null) {
|
||
|
|
if (amount.signum() > 0) jdbc.update("UPDATE user_wallets SET reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", amount, task.get("user_id"));
|
||
|
|
jdbc.update("UPDATE model_tasks SET cost_amount=0 WHERE id=?", taskId);
|
||
|
|
jdbc.update("UPDATE usage_events SET cost_amount=0 WHERE provider_task_id=? AND event_kind='task'", taskId);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void releasePolicies(String taskId, Map<String,Object> task) {
|
||
|
|
policies.release(taskId);
|
||
|
|
guard.releaseTaskUserSlot((UUID) task.get("user_id"), taskId);
|
||
|
|
}
|
||
|
|
|
||
|
|
private Map<String,Object> pricing(Object value) {
|
||
|
|
try { return json.readValue(String.valueOf(value), new TypeReference<>() {}); }
|
||
|
|
catch (JsonProcessingException exception) { throw new ApiException("INVALID_PRICE_SNAPSHOT", "任务价格快照无法核验", 409); }
|
||
|
|
}
|
||
|
|
|
||
|
|
private String encode(Object value) {
|
||
|
|
if (value == null) return null;
|
||
|
|
try { return json.writeValueAsString(value); }
|
||
|
|
catch (JsonProcessingException exception) { throw new IllegalStateException("Task settlement cannot be encoded"); }
|
||
|
|
}
|
||
|
|
|
||
|
|
private UUID taskRequestId(String taskId) { return UUID.nameUUIDFromBytes(("moyi-async:" + taskId).getBytes(StandardCharsets.UTF_8)); }
|
||
|
|
private <T> T transaction(Supplier<T> work) { return transactions == null ? work.get() : transactions.execute(status -> work.get()); }
|
||
|
|
}
|