feat: 任务可调并发、可批量操作,导航栏可收缩
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user