forked from xhgit/webup-cloud
Confirm manual task stops and protect cancellation state
This commit is contained in:
1 parent
4f2cf2fc87
commit
fb82821dc7
4 files changed
+132
-14
No files matched your search
@@ -37,7 +37,7 @@ public class TaskController {
|
||||
public List<Map<String, Object>> list(@AuthenticationPrincipal SecurityConfig.Identity who) {
|
||||
return db.queryForList(
|
||||
"SELECT t.id,t.project_id,p.name AS"
|
||||
+ " project_name,t.model_id,t.prompt,t.status,t.step_count,t.error,t.created_at,t.admin_priority,t.run_next,t.paid_priority,t.started_at,r.amount"
|
||||
+ " project_name,t.model_id,t.prompt,t.status,t.requested_action,t.step_count,t.error,t.created_at,t.admin_priority,t.run_next,t.paid_priority,t.started_at,r.amount"
|
||||
+ " AS budget,r.spent FROM ai_tasks t JOIN projects p ON p.id=t.project_id JOIN"
|
||||
+ " wallet_reservations r ON r.id=t.reservation_id WHERE t.user_id=? ORDER BY"
|
||||
+ " t.created_at DESC LIMIT 100",
|
||||
|
||||
@@ -400,6 +400,12 @@ public class TaskService {
|
||||
@Transactional
|
||||
public void finish(UUID id, String lease, String status, String error, boolean release) {
|
||||
var t = locked(id, lease);
|
||||
if ("CANCEL".equals(t.get("requested_action"))
|
||||
&& !Set.of("CANCELLED", "REVIEW_REQUIRED").contains(status)) {
|
||||
status = "CANCELLED";
|
||||
error = "用户已停止任务,已结算产生的费用";
|
||||
release = true;
|
||||
}
|
||||
db.update(
|
||||
"UPDATE ai_tasks SET"
|
||||
+ " status=?,error=?,requested_action='',lease_token=NULL,lease_expires_at=NULL,updated_at=CURRENT_TIMESTAMP"
|
||||
@@ -419,6 +425,9 @@ public class TaskService {
|
||||
find(id, user);
|
||||
var t = db.queryForMap("SELECT * FROM ai_tasks WHERE id=? FOR UPDATE", id);
|
||||
String status = t.get("status").toString();
|
||||
boolean stopping = status.equals("RUNNING") && "CANCEL".equals(t.get("requested_action"));
|
||||
if (action.equals("cancel") && (stopping || status.equals("CANCELLED"))) return find(id, user);
|
||||
if (stopping) throw new ApiError.Failure(409, "任务正在停止");
|
||||
if (action.equals("resume") && status.equals("PAUSED")) {
|
||||
db.update(
|
||||
"UPDATE ai_tasks SET status='QUEUED',error='',requested_action='',max_steps=CASE WHEN"
|
||||
@@ -430,7 +439,10 @@ public class TaskService {
|
||||
else db.update("UPDATE ai_tasks SET requested_action='PAUSE' WHERE id=?", id);
|
||||
event(id, "PAUSE_REQUESTED", "当前步骤结束后暂停");
|
||||
} else if (action.equals("cancel") && (status.equals("QUEUED") || status.equals("PAUSED"))) {
|
||||
db.update("UPDATE ai_tasks SET status='CANCELLED' WHERE id=?", id);
|
||||
db.update(
|
||||
"UPDATE ai_tasks SET status='CANCELLED',requested_action='',updated_at=CURRENT_TIMESTAMP"
|
||||
+ " WHERE id=?",
|
||||
id);
|
||||
wallets.release(UUID.fromString(t.get("reservation_id").toString()));
|
||||
queue.refundUnused(id);
|
||||
event(id, "CANCELLED", "用户取消,未使用预留已释放");
|
||||
|
||||
@@ -170,6 +170,42 @@ class WalletTaskIntegrationTest {
|
||||
assertEquals(0, BigDecimal.ZERO.compareTo((BigDecimal) wallets.get(user).get("reserved")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void runningStopIsIdempotentAndCannotBeOverwrittenByPauseOrCompletion() {
|
||||
UUID id = task();
|
||||
var claimed = tasks.claim();
|
||||
String lease = claimed.get("lease_token").toString();
|
||||
UUID reservation = UUID.fromString(claimed.get("reservation_id").toString());
|
||||
wallets.charge(reservation, n("1.25"), "usage:before-stop");
|
||||
|
||||
assertEquals("CANCEL", tasks.action(id, user, "cancel").get("requested_action"));
|
||||
assertEquals("CANCEL", tasks.action(id, user, "cancel").get("requested_action"));
|
||||
assertEquals(
|
||||
1,
|
||||
identity
|
||||
.db()
|
||||
.queryForObject(
|
||||
"SELECT COUNT(*) FROM ai_task_steps WHERE task_id=? AND event='CANCEL_REQUESTED'",
|
||||
Integer.class,
|
||||
id));
|
||||
assertThrows(ApiError.Failure.class, () -> tasks.action(id, user, "pause"));
|
||||
tasks.finish(id, lease, "COMPLETED", "Finished after the stop request", true);
|
||||
|
||||
assertEquals("CANCELLED", tasks.action(id, user, "cancel").get("status"));
|
||||
assertEquals(0, n("98.75").compareTo((BigDecimal) wallets.get(user).get("balance")));
|
||||
assertEquals(0, BigDecimal.ZERO.compareTo((BigDecimal) wallets.get(user).get("reserved")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingDoesNotDiscardUnconfirmedCharges() {
|
||||
UUID id = task();
|
||||
String lease = tasks.claim().get("lease_token").toString();
|
||||
tasks.action(id, user, "cancel");
|
||||
tasks.finish(id, lease, "REVIEW_REQUIRED", "Unknown provider result", false);
|
||||
assertEquals("REVIEW_REQUIRED", tasks.find(id, user).get("status"));
|
||||
assertEquals(0, n("20").compareTo((BigDecimal) wallets.get(user).get("reserved")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exactUsageChargesWithSnapshot() throws Exception {
|
||||
UUID id = task();
|
||||
|
||||
@@ -20,6 +20,12 @@ const fileBusy = ref(false),
|
||||
let fileGeneration = 0;
|
||||
let fileTaskSignature = "";
|
||||
const logPanel = ref<HTMLElement | null>(null);
|
||||
const stopDialog = ref<HTMLDialogElement | null>(null);
|
||||
const stoppable = (task: any) =>
|
||||
task &&
|
||||
["QUEUED", "RUNNING", "PAUSED"].includes(task.status) &&
|
||||
task.requested_action !== "CANCEL";
|
||||
let stopTaskId = "";
|
||||
const followLogs = ref(true);
|
||||
let logRequest = 0;
|
||||
let appliedLogRequest = 0;
|
||||
@@ -85,10 +91,14 @@ const labels: Record<string, string> = {
|
||||
RUNNING: "执行中",
|
||||
PAUSED: "已暂停",
|
||||
COMPLETED: "已结束",
|
||||
CANCELLED: "已取消",
|
||||
CANCELLED: "已停止",
|
||||
FAILED: "失败",
|
||||
REVIEW_REQUIRED: "自动核算中",
|
||||
};
|
||||
const isStopping = (task: any) =>
|
||||
task.status === "RUNNING" && task.requested_action === "CANCEL";
|
||||
const taskStatus = (task: any) =>
|
||||
isStopping(task) ? "正在停止" : labels[task.status] || task.status;
|
||||
async function load() {
|
||||
try {
|
||||
[tasks.value, queue.value] = await Promise.all([
|
||||
@@ -160,12 +170,27 @@ async function start() {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
async function action(a: string) {
|
||||
if (a === "cancel" && !confirm("确认取消任务?当前调用会先结算实际费用。"))
|
||||
return;
|
||||
function requestStop() {
|
||||
if (busy.value || !stoppable(selected.value)) return;
|
||||
stopTaskId = selected.value.id;
|
||||
stopDialog.value?.showModal();
|
||||
}
|
||||
function confirmStop() {
|
||||
stopDialog.value?.close();
|
||||
if (selected.value?.id === stopTaskId && stoppable(selected.value))
|
||||
void action("cancel");
|
||||
}
|
||||
async function action(a: "pause" | "resume" | "cancel") {
|
||||
const id = selected.value?.id;
|
||||
if (busy.value || !id || selected.value.requested_action === "CANCEL") return;
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await api("/tasks/" + selected.value.id + "/" + a, { method: "POST" });
|
||||
const updated = await api("/tasks/" + id + "/" + a, { method: "POST" });
|
||||
if (selected.value?.id === id) {
|
||||
appliedLogRequest = ++logRequest;
|
||||
selected.value = { ...selected.value, ...updated };
|
||||
}
|
||||
await load();
|
||||
} catch (e) {
|
||||
error.value = (e as Error).message;
|
||||
@@ -478,7 +503,7 @@ onUnmounted(() => clearInterval(timer));
|
||||
@click="select(t)"
|
||||
>
|
||||
<b>{{ t.project_name }}</b
|
||||
><span class="status">{{ labels[t.status] || t.status }}</span>
|
||||
><span class="status">{{ taskStatus(t) }}</span>
|
||||
<small v-if="t.status === 'QUEUED'"
|
||||
>当前第 {{ position(t.id) || "—" }} 位 ·
|
||||
{{
|
||||
@@ -502,7 +527,7 @@ onUnmounted(() => clearInterval(timer));
|
||||
<section v-if="selected" class="panel table-panel">
|
||||
<div class="panel-heading">
|
||||
<div>
|
||||
<h3>任务日志 · {{ labels[selected.status] }}</h3>
|
||||
<h3>任务日志 · {{ taskStatus(selected) }}</h3>
|
||||
<p>当前消费 ¥{{ selected.spent }} / 预算 ¥{{ selected.budget }}</p>
|
||||
<p v-if="selected.status === 'QUEUED'">
|
||||
当前排队第 {{ position(selected.id) || "—" }} 位<span
|
||||
@@ -526,7 +551,7 @@ onUnmounted(() => clearInterval(timer));
|
||||
¥{{ queue.config.priority_price }} 购买优先权
|
||||
</button>
|
||||
<button
|
||||
v-if="['QUEUED', 'RUNNING'].includes(selected.status)"
|
||||
v-if="['QUEUED', 'RUNNING'].includes(selected.status) && !isStopping(selected)"
|
||||
class="secondary"
|
||||
:disabled="busy"
|
||||
@click="action('pause')"
|
||||
@@ -540,15 +565,42 @@ onUnmounted(() => clearInterval(timer));
|
||||
>
|
||||
继续</button
|
||||
><button
|
||||
v-if="['QUEUED', 'RUNNING', 'PAUSED'].includes(selected.status)"
|
||||
class="secondary"
|
||||
v-if="stoppable(selected)"
|
||||
class="secondary danger"
|
||||
:disabled="busy"
|
||||
@click="action('cancel')"
|
||||
@click="requestStop"
|
||||
>
|
||||
取消
|
||||
停止任务
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="isStopping(selected)" class="alert info" role="status">
|
||||
已请求停止。正在等待当前调用结束并结算。
|
||||
</p>
|
||||
<dialog
|
||||
ref="stopDialog"
|
||||
class="stop-dialog"
|
||||
aria-labelledby="stop-task-title"
|
||||
aria-describedby="stop-task-description"
|
||||
>
|
||||
<h3 id="stop-task-title">确定停止这个任务?</h3>
|
||||
<p id="stop-task-description">
|
||||
正在进行的调用会先结束并按实际用量结算。已生成的文件会保留,未用预算将释放;停止后不能继续此任务。
|
||||
</p>
|
||||
<div class="table-actions">
|
||||
<button type="button" class="secondary" autofocus @click="stopDialog?.close()">
|
||||
返回
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="secondary danger"
|
||||
:disabled="busy || !stoppable(selected)"
|
||||
@click="confirmStop"
|
||||
>
|
||||
确认停止
|
||||
</button>
|
||||
</div>
|
||||
</dialog>
|
||||
<div v-if="selected.error" class="alert info">{{ selected.error }}</div>
|
||||
<div
|
||||
ref="logPanel"
|
||||
@@ -668,3 +720,21 @@ onUnmounted(() => clearInterval(timer));
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.stop-dialog {
|
||||
width: min(420px, calc(100% - 32px));
|
||||
padding: 24px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: var(--surface, Canvas);
|
||||
color: var(--text, CanvasText);
|
||||
}
|
||||
.stop-dialog::backdrop {
|
||||
background: rgb(15 23 42 / 45%);
|
||||
}
|
||||
.stop-dialog p {
|
||||
margin: 12px 0 20px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user