From 5f3bb312b3f2adcfb52730d904dd16ea27a3605f Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 25 Oct 2026 08:22:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BB=BB=E5=8A=A1=E5=8F=AF=E8=B0=83?= =?UTF-8?q?=E5=B9=B6=E5=8F=91=E3=80=81=E5=8F=AF=E6=89=B9=E9=87=8F=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=EF=BC=8C=E5=AF=BC=E8=88=AA=E6=A0=8F=E5=8F=AF=E6=94=B6?= =?UTF-8?q?=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/features/download/jobs.py | 48 ++++- backend/app/features/download/router.py | 17 ++ backend/app/platform/client.py | 22 +- backend/tests/test_core.py | 28 +++ .../features/download/DownloadManagerView.vue | 188 +++++++++++++++++- .../features/download/GridDownloadView.vue | 2 +- desktop/src/features/download/api.ts | 7 + desktop/src/shell/Shell.vue | 63 ++++-- desktop/src/shell/navigation.ts | 4 +- desktop/src/styles.css | 52 ++++- 10 files changed, 375 insertions(+), 56 deletions(-) diff --git a/backend/app/features/download/jobs.py b/backend/app/features/download/jobs.py index a31eadc..43f5200 100644 --- a/backend/app/features/download/jobs.py +++ b/backend/app/features/download/jobs.py @@ -68,6 +68,8 @@ class DownloadJob: task: asyncio.Task | None = None cancel_event: asyncio.Event = field(default_factory=asyncio.Event) run_event: asyncio.Event = field(default_factory=lambda: _set_event()) + retune: asyncio.Event = field(default_factory=asyncio.Event) + applied_concurrency: int = 0 @property def total(self) -> int: @@ -395,6 +397,8 @@ class JobManager: if job.whole_city: job.listing_done = False if job.is_active(): + if job.applied_concurrency and job.concurrency != job.applied_concurrency: + job.retune.set() if job.message in {"", "等待中", "已暂停"}: job.message = "下载中" job.save() @@ -437,6 +441,14 @@ class JobManager: job.listing_done = False job.save() + def set_concurrency(self, job: DownloadJob, value: int) -> None: + if job.status == "done": + raise NqiError("这个任务已经完成") + if job.status == "running" and job.is_active(): + raise NqiError("请先暂停,再调整并发") + job.concurrency = min(32, max(1, int(value))) + job.save() + def set_limit(self, value: int) -> int: self.max_concurrent = store_task_limit(value) return self.max_concurrent @@ -755,14 +767,20 @@ def _describe(job: DownloadJob) -> str: return f"已完成 {job.completed}/{job.total},失败 {job.failed}" +def _should_retune(job: DownloadJob) -> bool: + return job.retune.is_set() and not job.cancel_event.is_set() + + async def _wait_job(job: DownloadJob) -> bool: while not job.run_event.is_set(): - if job.cancel_event.is_set(): + if job.cancel_event.is_set() or job.retune.is_set(): return False try: await asyncio.wait_for(job.run_event.wait(), timeout=0.3) except asyncio.TimeoutError: continue + if job.retune.is_set(): + return False return not job.cancel_event.is_set() @@ -926,6 +944,8 @@ async def run_download(job: DownloadJob) -> None: while not job.cancel_event.is_set(): try: await _run_pass(job, journal, columns, spool) + if job.retune.is_set() and not job.cancel_event.is_set(): + continue return except NqiAuthError as exc: reason = str(exc) or "登录已失效,请重新登录" @@ -983,8 +1003,9 @@ async def _run_pass(job: DownloadJob, journal: CsvJournal, columns, spool: IdSpo job.id_field = str(layer.get("originRelatedField") or job.id_field) job.completed = len(journal.completed) job.written_rows = journal.written_rows - job.failed = 0 - job.failures = [] + if not job.retune.is_set(): + job.failed = 0 + job.failures = [] if spool is not None: _seed_seen(spool, journal.completed) await _run_city(job, journal, columns, service_code, spool) @@ -1075,6 +1096,7 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code report, None, job.run_event, + halt_event=job.retune, grid_size=job.grid_size, failed_tiles=job.failed_tiles, seen=spool.seen, @@ -1082,7 +1104,7 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code ) async with contextlib.aclosing(iterator) as ids: async for grid_id in ids: - if job.cancel_event.is_set(): + if job.cancel_event.is_set() or job.retune.is_set(): break spool.append(grid_id) if spool.due(): @@ -1098,7 +1120,7 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code return raise spool.failed_tiles = [list(item) for item in job.failed_tiles] - if job.cancel_event.is_set(): + if job.cancel_event.is_set() or job.retune.is_set(): await asyncio.to_thread(spool.flush) return await asyncio.to_thread(spool.mark_complete) @@ -1113,11 +1135,13 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code async def _pump(job: DownloadJob, client, journal, columns, service_code: str, source: AsyncIterator[str], listing=None) -> None: - ids: asyncio.Queue[str] = asyncio.Queue(maxsize=max(64, job.concurrency * 8)) - results: asyncio.Queue = asyncio.Queue(maxsize=max(8, job.concurrency * 2)) + job.retune.clear() + worker_count = max(1, min(32, job.concurrency)) + job.applied_concurrency = worker_count + ids: asyncio.Queue[str] = asyncio.Queue(maxsize=max(64, worker_count * 8)) + results: asyncio.Queue = asyncio.Queue(maxsize=max(8, worker_count * 2)) produce_done = asyncio.Event() workers_done = asyncio.Event() - worker_count = max(1, job.concurrency) remaining = worker_count def resolve(): @@ -1131,9 +1155,9 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s try: async with contextlib.aclosing(source): async for grid_id in source: - if job.cancel_event.is_set(): + if job.cancel_event.is_set() or job.retune.is_set(): return - while not job.cancel_event.is_set(): + while not job.cancel_event.is_set() and not job.retune.is_set(): try: await asyncio.wait_for(ids.put(grid_id), timeout=0.3) break @@ -1150,7 +1174,7 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s async def worker() -> None: try: - while not job.cancel_event.is_set(): + while not job.cancel_event.is_set() and not job.retune.is_set(): if not await _wait_job(job): return try: @@ -1270,6 +1294,8 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s if error is None: raise asyncio.CancelledError() from None raise error from None + if _should_retune(job): + return if job.whole_city and not job.cancel_event.is_set() and job.discovered == 0 and job.completed == 0 and not job.failed_tiles: raise NqiError("这个地市没有栅格") unfinished = job.completed + job.failed < job.total or (job.whole_city and not job.listing_done) diff --git a/backend/app/features/download/router.py b/backend/app/features/download/router.py index de9202a..eaae6af 100644 --- a/backend/app/features/download/router.py +++ b/backend/app/features/download/router.py @@ -280,6 +280,23 @@ async def resume_job(job_id: str) -> dict: return job.snapshot() +@router.put("/jobs/{job_id}/concurrency") +async def update_concurrency(job_id: str, body: dict) -> dict: + state.require_client() + if not isinstance(body, dict): + raise _bad("并发格式不正确") + try: + value = int(body.get("concurrency")) + except (TypeError, ValueError) as exc: + raise _bad("并发需要是 1 到 32 的整数") from exc + try: + job = state.jobs.get(job_id) + state.jobs.set_concurrency(job, value) + except NqiError as exc: + raise _bad(str(exc), 404 if str(exc) == "任务不存在" else 400) from exc + return job.snapshot() + + @router.post("/jobs/{job_id}/pause") async def pause_job(job_id: str) -> dict: state.require_client() diff --git a/backend/app/platform/client.py b/backend/app/platform/client.py index cb08270..d77823a 100644 --- a/backend/app/platform/client.py +++ b/backend/app/platform/client.py @@ -475,6 +475,7 @@ class NqiClient: progress, skip: set[str] | None = None, run_event: asyncio.Event | None = None, + halt_event: asyncio.Event | None = None, *, grid_size: str = "GRID20", failed_tiles: list | None = None, @@ -519,7 +520,7 @@ class NqiClient: try: await progress(len(seen)) while not cancel_event.is_set() and (pending or inflight): - if not await _wait_turn(cancel_event, run_event): + if not await _wait_turn(cancel_event, run_event, halt_event): break while pending and len(inflight) < 3 and not cancel_event.is_set(): if run_event is not None and not run_event.is_set(): @@ -566,7 +567,7 @@ class NqiClient: fresh.append(grid_id) await progress(len(seen)) for grid_id in fresh: - if not await _wait_turn(cancel_event, run_event): + if not await _wait_turn(cancel_event, run_event, halt_event): break yield grid_id if cancel_event.is_set(): @@ -739,18 +740,25 @@ async def _interruptible_sleep(seconds: float, cancel_event: asyncio.Event, run_ return not cancel_event.is_set() -async def _wait_turn(cancel_event: asyncio.Event, run_event: asyncio.Event | None) -> bool: - """暂停时停住。返回 False 表示任务已停止。""" +async def _wait_turn( + cancel_event: asyncio.Event, + run_event: asyncio.Event | None, + halt_event: asyncio.Event | None = None, +) -> bool: + """暂停时停住。返回 False 表示停止或要按新的并发重开。""" + def halted() -> bool: + return halt_event is not None and halt_event.is_set() + if run_event is None: - return not cancel_event.is_set() + return not cancel_event.is_set() and not halted() while not run_event.is_set(): - if cancel_event.is_set(): + if cancel_event.is_set() or halted(): return False try: await asyncio.wait_for(run_event.wait(), timeout=0.3) except asyncio.TimeoutError: continue - return not cancel_event.is_set() + return not cancel_event.is_set() and not halted() def _public_user(data: dict) -> dict: diff --git a/backend/tests/test_core.py b/backend/tests/test_core.py index 6ba1620..c96b197 100644 --- a/backend/tests/test_core.py +++ b/backend/tests/test_core.py @@ -588,6 +588,34 @@ async def _pause_holds_the_next_grid(tmp_path: Path): assert job.status == "done" +def test_concurrency_waits_until_resume(tmp_path: Path, monkeypatch): + monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs") + manager = JobManager() + manager.max_concurrent = 2 + job = _make_job(manager, None) + job.status = "running" + job.applied_concurrency = 4 + + class Alive: + def done(self): + return False + + job.task = Alive() + try: + manager.set_concurrency(job, 8) + except NqiError as exc: + assert "暂停" in str(exc) + else: + raise AssertionError("下载中不应直接改并发") + manager.pause(job) + manager.set_concurrency(job, 12) + assert job.concurrency == 12 + assert job.status == "paused" + assert manager.place(job) == "resume" + assert job.retune.is_set() + assert job.status == "running" + + def _make_job(manager: JobManager, output: Path | None) -> DownloadJob: return manager.create( network="NR", diff --git a/desktop/src/features/download/DownloadManagerView.vue b/desktop/src/features/download/DownloadManagerView.vue index 6fe436b..c206bc7 100644 --- a/desktop/src/features/download/DownloadManagerView.vue +++ b/desktop/src/features/download/DownloadManagerView.vue @@ -1,9 +1,9 @@ diff --git a/desktop/src/shell/navigation.ts b/desktop/src/shell/navigation.ts index 4f30e85..405a03b 100644 --- a/desktop/src/shell/navigation.ts +++ b/desktop/src/shell/navigation.ts @@ -1,7 +1,7 @@ import type { Component } from "vue"; import { h } from "vue"; import { NIcon } from "naive-ui"; -import { CloudDownloadOutline, ListOutline } from "@vicons/ionicons5"; +import { CloudDownloadOutline, GridOutline, ListOutline } from "@vicons/ionicons5"; function renderIcon(icon: Component) { return () => h(NIcon, null, { default: () => h(icon) }); @@ -15,7 +15,7 @@ export const navOptions = [ key: "download", icon: renderIcon(CloudDownloadOutline), children: [ - { label: "栅格下载", key: "grid" as const, icon: renderIcon(CloudDownloadOutline) }, + { label: "栅格下载", key: "grid" as const, icon: renderIcon(GridOutline) }, ], }, { label: "下载管理", key: "tasks" as const, icon: renderIcon(ListOutline) }, diff --git a/desktop/src/styles.css b/desktop/src/styles.css index 6a44ea3..11da78f 100644 --- a/desktop/src/styles.css +++ b/desktop/src/styles.css @@ -177,17 +177,19 @@ select { .shell { height: 100%; - display: grid; - grid-template-columns: 220px minmax(0, 1fr); background: var(--bg); color: var(--ink); } -.sider { +.sider-body { + height: 100%; display: flex; flex-direction: column; - background: var(--sidebar); - border-right: 1px solid var(--line); + min-height: 0; +} + +.sider-body .n-menu { + flex: 1; min-height: 0; } @@ -195,6 +197,7 @@ select { padding: 18px 16px 8px; font-weight: 650; font-size: 16px; + white-space: nowrap; } .sider-user { @@ -206,6 +209,11 @@ select { gap: 8px; } +.sider-user.compact { + flex-direction: column; + padding: 8px 0 12px; +} + .sider-user .who { min-width: 0; flex: 1; @@ -227,10 +235,18 @@ select { .content { min-width: 0; min-height: 0; + height: 100%; display: flex; flex-direction: column; } +.content .n-layout-scroll-container { + height: 100%; + display: flex; + flex-direction: column; + min-height: 0; +} + .page { min-height: 0; flex: 1; @@ -286,6 +302,8 @@ select { display: flex; gap: 8px; align-items: center; + flex-wrap: wrap; + justify-content: flex-end; } .panel, @@ -324,6 +342,7 @@ select { .tabs { display: flex; + align-items: center; gap: 8px; padding: 12px 20px 0; } @@ -454,7 +473,28 @@ select { } .limit-control { - width: 112px; + width: 148px; +} + +.n-input-number .n-input__input-el { + text-align: center; +} + +.speed { + color: var(--muted); + font-size: 13px; + white-space: nowrap; +} + +.task-main { + display: flex; + align-items: flex-start; + gap: 10px; + min-width: 0; +} + +.task.picked { + border-color: var(--accent); } .fail-list {