feat: 去掉停止按钮,等待中的任务也能暂停

This commit is contained in:
2026-10-25 09:35:39 +08:00
parent d3e553155d
commit 2064519008
6 changed files with 63 additions and 115 deletions
+19 -31
View File
@@ -436,38 +436,24 @@ class JobManager:
return "run"
def pause(self, job: DownloadJob) -> None:
if job.deleting:
raise NqiError("任务正在删除")
if job.stopping or job.cancel_event.is_set():
raise NqiError("任务正在停止")
if job.status != "running" or not job.is_active():
if job.status == "queued":
# 排队中的任务移出队列。还挂着的协程保持停住,点继续时接着用。
job.run_event.clear()
job.status = "paused"
job.message = "已暂停"
job.save()
return
if job.status != "running" or not job.is_active() or job.closing:
raise NqiError("这个任务没有在下载")
job.run_event.clear()
job.status = "paused"
job.message = "已暂停"
job.save()
def request_stop(self, job: DownloadJob) -> None:
if job.closing and job.is_active():
# 上一轮已经在收尾;只取消排队,不再去碰正在关闭的任务。
if job.status == "queued":
job.status = "cancelled"
job.message = "已取消"
job.save()
return
if not job.is_active():
if job.status == "done":
raise NqiError("这个任务已经完成")
job.stopping = False
job.status = "cancelled"
job.message = "已取消"
job.save()
return
job.stopping = True
job.cancel_event.set()
job.run_event.set()
job.status = "running"
job.message = "正在停止"
job.save()
def _queue(self, job: DownloadJob) -> None:
job.status = "queued"
job.message = "等待中"
@@ -568,9 +554,11 @@ class JobManager:
for job in list(self.jobs.values()):
if job.deleting:
continue
if job.status in {"running", "paused"} and not job.is_active():
# 只有标着在下载却没有协程的才算中断。暂停的任务可以没有协程(排队时暂停、登录失效时暂停)。
if job.status == "running" and not job.is_active():
job.status = "cancelled"
job.message = "已中断"
job.stopping = False
job.save()
item = job.snapshot()
if item.get("status") in _FINISHED_STATUSES:
@@ -689,7 +677,7 @@ class JobManager:
duplicate_count=int(data.get("duplicateCount") or 0),
failures=list(data.get("failures") or []),
paused_by=str(data.get("pausedBy") or ""),
stopping=bool(data.get("stopping") or False),
stopping=bool(data.get("stopping") or False) and not interrupted,
failed_tiles=_combine_failed(data.get("failedTiles"), _spool_failed_tiles(path.parent)),
)
except (KeyError, TypeError, ValueError) as exc:
@@ -1054,9 +1042,9 @@ async def run_download(job: DownloadJob) -> None:
await _flush_spool(job, spool)
if not await _sleep_unless_stopped(job, wait):
break
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
except asyncio.CancelledError:
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
raise
except NqiError as exc:
await _mark(job, "error", str(exc) or "下载失败", "error")
@@ -1112,7 +1100,7 @@ async def _run_pass(job: DownloadJob, journal: CsvJournal, columns, spool: IdSpo
grid_size=job.grid_size,
)
if job.cancel_event.is_set():
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
return
service_code = str(layer["serviceCode"])
job.id_field = str(layer.get("originRelatedField") or job.id_field)
@@ -1134,7 +1122,7 @@ async def _run_pass(job: DownloadJob, journal: CsvJournal, columns, spool: IdSpo
job.listing_done = True
if not pending:
if job.cancel_event.is_set():
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
return
await _mark(job, "done", "已完成", "done")
return
@@ -1409,7 +1397,7 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s
raise NqiError("这个地市没有栅格")
unfinished = job.completed + job.failed < job.total or (job.whole_city and not job.listing_done)
if job.cancel_event.is_set() and unfinished:
await _mark(job, "cancelled", "已停止", "cancelled")
await _mark(job, "cancelled", "已中断", "cancelled")
return
if job.failed_tiles:
await _mark(job, "done_with_errors", f"有 {len(job.failed_tiles)} 块区域没读到,点继续重试", "done")
-14
View File
@@ -268,20 +268,6 @@ def _remove_created(data: Path, output: Path) -> None:
shutil.rmtree(output, ignore_errors=True)
@router.post("/jobs/{job_id}/cancel")
async def cancel_job(job_id: str) -> dict:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
try:
state.jobs.request_stop(job)
except NqiError as exc:
raise _bad(str(exc)) from exc
return job.snapshot()
@router.post("/jobs/{job_id}/resume")
async def resume_job(job_id: str) -> dict:
state.require_client()
+6 -3
View File
@@ -477,9 +477,12 @@ def test_only_the_task_limit_runs(tmp_path: Path, monkeypatch):
assert manager.place(second) == "wait"
assert second.status == "queued"
assert second.message == "等待中"
manager.request_stop(second)
assert second.status == "cancelled"
assert second.message == "已取消"
manager.pause(second)
assert second.status == "paused"
assert second.message == "已暂停"
assert manager.queued_jobs() == []
assert len(manager.list_jobs()) == 2
assert second.status == "paused"
first.task = Alive()
manager.pause(first)
+20 -4
View File
@@ -467,7 +467,7 @@ def test_running_count_ignores_paused_and_dead_tasks(tmp_path: Path):
assert manager.running_count() == 0
def test_request_stop_sets_stopping_and_requeue_clears_listing(tmp_path: Path):
def test_requeue_clears_listing_and_queued_job_can_pause(tmp_path: Path):
manager = JobManager()
manager.max_concurrent = 1
city = _job(tmp_path, whole_city=True)
@@ -487,9 +487,25 @@ def test_request_stop_sets_stopping_and_requeue_clears_listing(tmp_path: Path):
manager.jobs[holder.id] = holder
assert manager.place(city) == "wait"
assert city.listing_done is False
manager.request_stop(holder)
assert holder.stopping is True
assert holder.message == "正在停止"
manager.pause(city)
assert city.status == "paused"
assert not city.run_event.is_set()
assert manager.queued_jobs() == []
def test_jobs_paused_by_expiry_stay_paused_until_login(tmp_path: Path):
manager = JobManager()
waiting = _job(tmp_path)
waiting.status = "queued"
manager.jobs[waiting.id] = waiting
manager.suspend_all("登录已失效,请重新登录", mark="expired")
assert waiting.status == "paused"
for item in manager.list_jobs():
if item["id"] == waiting.id:
assert item["status"] == "paused"
assert waiting.status == "paused"
manager.resume_marked("expired")
assert waiting.status == "queued"
def test_active_count_and_sse_removed(tmp_path: Path):
@@ -1,9 +1,9 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NButton, NCheckbox, NEmpty, NIcon, NInputNumber, NProgress, NTag, NTooltip, useDialog, useMessage } from "naive-ui";
import { ChevronBackOutline, FolderOpenOutline, HelpCircleOutline, PauseOutline, PlayOutline, StopCircleOutline, TrashOutline } from "@vicons/ionicons5";
import { ChevronBackOutline, FolderOpenOutline, HelpCircleOutline, PauseOutline, PlayOutline, TrashOutline } from "@vicons/ionicons5";
import { ApiError, revealLocal } from "../../shared/http";
import { cancelJob, deleteJob, loadDownloadSettings, loadJobs, pauseJob, resumeJob, saveDownloadSettings, updateConcurrency, type DownloadJob } from "./api";
import { deleteJob, loadDownloadSettings, loadJobs, pauseJob, resumeJob, saveDownloadSettings, updateConcurrency, type DownloadJob } from "./api";
const props = defineProps<{ focusId: string }>();
const message = useMessage();
@@ -25,7 +25,7 @@ const doneJobs = computed(() => jobs.value.filter((job) => job.status === "done"
const visible = computed(() => (tab.value === "active" ? activeJobs.value : doneJobs.value));
const opened = computed(() => jobs.value.find((job) => job.id === openedId.value) ?? null);
const selectedVisible = computed(() => visible.value.filter((job) => selectedIds.value.includes(job.id)));
const pauseTargets = computed(() => selectedVisible.value.filter((job) => job.status === "running" && !job.stopping));
const pauseTargets = computed(() => selectedVisible.value.filter((job) => canPause(job)));
const resumeTargets = computed(() =>
selectedVisible.value.filter((job) => job.status !== "running" && job.status !== "done" && job.status !== "queued"),
);
@@ -212,15 +212,6 @@ async function pause(job: DownloadJob) {
}
}
async function stop(job: DownloadJob) {
try {
await cancelJob(job.id);
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "停止失败");
}
}
async function resume(job: DownloadJob) {
try {
await resumeJob(job.id);
@@ -237,7 +228,11 @@ async function openDir(job: DownloadJob) {
}
function inProgress(job: DownloadJob) {
return Boolean(job.stopping) || job.status === "running" || job.status === "queued";
return Boolean(job.stopping) || job.status === "running";
}
function canPause(job: DownloadJob) {
return !job.stopping && (job.status === "running" || job.status === "queued");
}
function confirmDelete(job: DownloadJob) {
@@ -301,7 +296,7 @@ function resumeSelected() {
function confirmDeleteSelected() {
const targets = deleteTargets.value;
if (!targets.length) {
message.info("正在下载的任务要先停止才能删除");
message.info("正在下载的任务要先暂停才能删除");
return;
}
dialog.warning({
@@ -350,28 +345,11 @@ async function removeJob(job: DownloadJob, files: boolean) {
<n-tag size="small" :type="opened.status === 'running' ? 'info' : opened.status === 'done' ? 'success' : opened.status === 'paused' ? 'warning' : 'default'">
{{ statusLabel(opened) }}
</n-tag>
<template v-if="opened.status === 'running'">
<n-button v-if="!opened.stopping" size="small" @click="pause(opened)">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button size="small" @click="stop(opened)">
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
停止
</n-button>
</template>
<template v-else-if="opened.status === 'paused'">
<n-button size="small" type="primary" secondary @click="resume(opened)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
<n-button size="small" @click="stop(opened)">
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
停止
</n-button>
</template>
<n-button v-else-if="opened.status === 'queued'" size="small" @click="stop(opened)">取消</n-button>
<n-button v-else-if="opened.status !== 'done'" size="small" type="primary" secondary @click="resume(opened)">
<n-button v-if="canPause(opened)" size="small" @click="pause(opened)">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button v-else-if="opened.status !== 'done' && !inProgress(opened)" size="small" type="primary" secondary @click="resume(opened)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
@@ -507,30 +485,11 @@ async function removeJob(job: DownloadJob, files: boolean) {
</div>
</div>
<div class="task-actions" @click.stop>
<template v-if="job.status === 'running'">
<n-button v-if="!job.stopping" size="small" @click="pause(job)">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button size="small" @click="stop(job)">
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
停止
</n-button>
</template>
<template v-else-if="job.status === 'paused'">
<n-button size="small" type="primary" secondary @click="resume(job)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
<n-button size="small" @click="stop(job)">
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
停止
</n-button>
</template>
<n-button v-else-if="job.status === 'queued'" size="small" @click="stop(job)">
取消
<n-button v-if="canPause(job)" size="small" @click="pause(job)">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button v-else-if="job.status !== 'done'" size="small" type="primary" secondary @click="resume(job)">
<n-button v-else-if="job.status !== 'done' && !inProgress(job)" size="small" type="primary" secondary @click="resume(job)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
-4
View File
@@ -62,10 +62,6 @@ export function createJob(form: FormData) {
return api<DownloadJob>("/api/download/jobs", { method: "POST", body: form });
}
export function cancelJob(id: string) {
return api<DownloadJob>(`/api/download/jobs/${id}/cancel`, { method: "POST" });
}
export function resumeJob(id: string) {
return api<DownloadJob>(`/api/download/jobs/${id}/resume`, { method: "POST" });
}