feat: 完成后清理进度文件,并支持迁移数据目录
This commit is contained in:
@@ -678,10 +678,16 @@ class JobManager:
|
||||
try:
|
||||
status = str(data.get("status") or "queued")
|
||||
message = str(data.get("message") or "")
|
||||
interrupted = status in _INTERRUPTED_STATUSES
|
||||
paused_by = str(data.get("pausedBy") or "")
|
||||
# 迁移前主动收起来的任务要保持暂停,重启后按记录继续,不要当成意外中断。
|
||||
held_for_move = paused_by == "move"
|
||||
interrupted = status in _INTERRUPTED_STATUSES and not held_for_move
|
||||
if interrupted:
|
||||
status = "cancelled"
|
||||
message = "已中断"
|
||||
elif held_for_move:
|
||||
status = "paused"
|
||||
message = "已暂停"
|
||||
whole = bool(data.get("wholeCity"))
|
||||
legacy_ids = [str(item) for item in data.get("gridIds") or []]
|
||||
if data.get("gridCount") is None:
|
||||
@@ -717,17 +723,51 @@ class JobManager:
|
||||
written_rows=int(data.get("writtenRows") or 0),
|
||||
duplicate_count=int(data.get("duplicateCount") or 0),
|
||||
failures=list(data.get("failures") or []),
|
||||
paused_by=str(data.get("pausedBy") or ""),
|
||||
paused_by=paused_by,
|
||||
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:
|
||||
raise NqiError("任务记录损坏") from exc
|
||||
_clear_temp_files(path.parent)
|
||||
if status == "done":
|
||||
release_finished_work(path.parent)
|
||||
if interrupted:
|
||||
job.save()
|
||||
return job
|
||||
|
||||
async def shelve_for_move(self) -> list[str]:
|
||||
"""停掉还开着文件的任务。正在下载和排队的记下来,迁移完成后继续。"""
|
||||
self._discover()
|
||||
jobs = [job for job in self.jobs.values() if not job.deleting]
|
||||
for job in jobs:
|
||||
if job.building or job.deleting:
|
||||
raise NqiError("有任务还在创建或删除,请稍后再迁移")
|
||||
resume: list[str] = []
|
||||
for job in jobs:
|
||||
should_resume = job.status in {"running", "queued"} or job.paused_by == "move"
|
||||
if should_resume:
|
||||
resume.append(job.id)
|
||||
busy = job.is_active() or (job.files_closed is not None and not job.files_closed.done())
|
||||
if busy:
|
||||
try:
|
||||
await _stop_and_wait(job)
|
||||
except NqiError as exc:
|
||||
if str(exc) == "任务还在收尾,请稍后再删":
|
||||
raise NqiError("任务还在收尾,请稍后再迁移") from exc
|
||||
raise
|
||||
if not should_resume:
|
||||
continue
|
||||
job.status = "paused"
|
||||
job.paused_by = "move"
|
||||
job.message = "已暂停"
|
||||
job.stopping = False
|
||||
job.cancel_event = asyncio.Event()
|
||||
job.save()
|
||||
await job.flush_record()
|
||||
await asyncio.wrap_future(RECORDS.barrier())
|
||||
return resume
|
||||
|
||||
|
||||
def _clear_temp_files(directory: Path) -> None:
|
||||
"""进程被强行结束时可能留下替换前的临时文件。只在任务没在运行时清。"""
|
||||
@@ -742,6 +782,21 @@ def _clear_temp_files(directory: Path) -> None:
|
||||
pass
|
||||
|
||||
|
||||
_FINISHED_WORK = ("progress.jsonl", "ids.spool", "ids.spool.meta")
|
||||
|
||||
|
||||
def release_finished_work(directory: Path) -> None:
|
||||
"""任务已经全部下完。进度和编号暂存只为继续下载服务,删掉以免一直占空间。"""
|
||||
for name in _FINISHED_WORK:
|
||||
path = directory / name
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
except OSError as exc:
|
||||
logger.warning("完成后的进度文件暂时删不掉 %s: %s", path, exc)
|
||||
|
||||
|
||||
async def _stop_and_wait(job: DownloadJob) -> None:
|
||||
"""强制结束任务协程,并等它关完文件。"""
|
||||
task = job.task
|
||||
@@ -1119,6 +1174,8 @@ async def _close_files(job: DownloadJob, io: JobIO, journal: CsvJournal, spool:
|
||||
await io.close()
|
||||
if job.io is io:
|
||||
job.io = None
|
||||
if job.status == "done":
|
||||
await asyncio.to_thread(release_finished_work, job.directory)
|
||||
await job.flush_record()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""把数据目录迁到用户选的位置。真正搬文件夹由桌面壳在停掉后台之后做。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from app.features.download import jobs as job_module
|
||||
from app.features.download.journal import explain_os_error
|
||||
from app.platform.client import NqiError
|
||||
from app.shared.files import write_atomic
|
||||
from app.shared.state import state
|
||||
|
||||
RESUME_NAME = "resume-after-move.json"
|
||||
|
||||
|
||||
def data_root() -> Path:
|
||||
return job_module.DATA_DIR.parent
|
||||
|
||||
|
||||
def resume_path() -> Path:
|
||||
return data_root() / RESUME_NAME
|
||||
|
||||
|
||||
def current_dir() -> dict:
|
||||
return {"path": str(data_root())}
|
||||
|
||||
|
||||
def _same(left: Path, right: Path) -> bool:
|
||||
if left.exists() and right.exists():
|
||||
try:
|
||||
return left.samefile(right)
|
||||
except OSError:
|
||||
pass
|
||||
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(os.path.abspath(right))
|
||||
|
||||
|
||||
def _within(child: Path, parent: Path) -> bool:
|
||||
if _same(child, parent):
|
||||
return False
|
||||
child_text = os.path.normcase(os.path.abspath(child))
|
||||
parent_text = os.path.normcase(os.path.abspath(parent)).rstrip("\\/")
|
||||
return child_text.startswith(parent_text + os.sep)
|
||||
|
||||
|
||||
def validate_target(raw: str) -> Path:
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
raise NqiError("请选择数据目录")
|
||||
target = Path(text)
|
||||
if not target.is_absolute():
|
||||
raise NqiError("数据目录必须是绝对路径")
|
||||
current = data_root().resolve()
|
||||
chosen = target.resolve()
|
||||
if _same(chosen, current):
|
||||
raise NqiError("已经是当前数据目录")
|
||||
if _within(chosen, current) or _within(current, chosen):
|
||||
raise NqiError("不能选在当前数据目录里面,也不能选它的上级")
|
||||
if target.exists() and not target.is_dir():
|
||||
raise NqiError("请选择文件夹")
|
||||
if target.exists() and any(target.iterdir()):
|
||||
raise NqiError("请选择一个空文件夹")
|
||||
job_module.ensure_output_dir(target)
|
||||
return target.resolve()
|
||||
|
||||
|
||||
async def prepare(raw: str) -> dict:
|
||||
target = validate_target(raw)
|
||||
ids = await state.jobs.shelve_for_move()
|
||||
payload = json.dumps({"ids": ids}, ensure_ascii=False).encode("utf-8")
|
||||
try:
|
||||
write_atomic(resume_path(), payload)
|
||||
except OSError as exc:
|
||||
message = explain_os_error(exc) or "迁移记录写不进去"
|
||||
raise NqiError(message) from exc
|
||||
return {"path": str(data_root()), "target": str(target), "resumeIds": ids}
|
||||
|
||||
|
||||
async def resume_moved() -> dict:
|
||||
path = resume_path()
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {"resumed": []}
|
||||
except (OSError, json.JSONDecodeError, UnicodeError, TypeError, ValueError) as exc:
|
||||
raise NqiError("迁移记录读不出来") from exc
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as exc:
|
||||
message = explain_os_error(exc) or "迁移记录暂时删不掉"
|
||||
raise NqiError(message) from exc
|
||||
raw_ids = data.get("ids") if isinstance(data, dict) else []
|
||||
if not isinstance(raw_ids, list):
|
||||
raw_ids = []
|
||||
resumed: list[str] = []
|
||||
for job_id in raw_ids:
|
||||
text = str(job_id)
|
||||
try:
|
||||
job = state.jobs.get(text)
|
||||
except NqiError:
|
||||
continue
|
||||
if job.status == "done":
|
||||
continue
|
||||
job.paused_by = ""
|
||||
if job.status != "queued":
|
||||
job.status = "queued"
|
||||
job.message = "等待中"
|
||||
job.save()
|
||||
resumed.append(text)
|
||||
from app.features.download.router import fill_slots
|
||||
|
||||
fill_slots()
|
||||
return {"resumed": resumed}
|
||||
@@ -15,6 +15,7 @@ from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile
|
||||
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
|
||||
from app.features.download.ids import parse_upload
|
||||
from app.features.download.jobs import _write_ids, app_settings, ensure_output_dir, run_download, store_app_settings
|
||||
from app.features.download.relocate import current_dir, prepare, resume_moved
|
||||
from app.features.download.journal import explain_os_error
|
||||
from app.platform.client import NqiError
|
||||
from app.platform.constants import CITIES
|
||||
@@ -62,6 +63,32 @@ def fill_slots() -> None:
|
||||
_spawn(waiting[0])
|
||||
|
||||
|
||||
@router.get("/data-dir")
|
||||
async def read_data_dir() -> dict:
|
||||
state.require_client()
|
||||
return current_dir()
|
||||
|
||||
|
||||
@router.post("/data-dir/prepare")
|
||||
async def prepare_data_dir(body: Any = Body(default=None)) -> dict:
|
||||
state.require_client()
|
||||
if not isinstance(body, dict):
|
||||
raise _bad("参数格式不正确")
|
||||
try:
|
||||
return await prepare(str(body.get("path") or ""))
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/data-dir/resume")
|
||||
async def resume_data_dir() -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
return await resume_moved()
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/settings/app")
|
||||
async def read_app_settings() -> dict:
|
||||
return app_settings()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.features.download import jobs as job_module
|
||||
from app.features.download import relocate
|
||||
from app.features.download.jobs import JobManager
|
||||
from app.platform.client import NqiError
|
||||
from app.shared.state import state
|
||||
|
||||
|
||||
def _use_data(monkeypatch, root: Path) -> Path:
|
||||
jobs = root / "jobs"
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", jobs)
|
||||
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", root / "downloads")
|
||||
return jobs
|
||||
|
||||
|
||||
def _record(directory: Path, **overrides) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"id": directory.name,
|
||||
"network": "NR",
|
||||
"cityCode": "JM",
|
||||
"cityName": "江门",
|
||||
"month": "2026-09",
|
||||
"groups": ["rsrp"],
|
||||
"concurrency": 2,
|
||||
"gridCount": 1,
|
||||
"wholeCity": False,
|
||||
"discovered": 1,
|
||||
"listingDone": True,
|
||||
"csvPath": str(directory / "out.csv"),
|
||||
"createdAt": "2026-10-26T09:00:00",
|
||||
"status": "done",
|
||||
"message": "已完成",
|
||||
"completed": 1,
|
||||
"failed": 0,
|
||||
"writtenRows": 1,
|
||||
"duplicateCount": 0,
|
||||
"failures": [],
|
||||
"pausedBy": "",
|
||||
"stopping": False,
|
||||
"failedTiles": [],
|
||||
}
|
||||
payload.update(overrides)
|
||||
(directory / "job.json").write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def test_finished_job_drops_progress_and_keeps_the_id_list(tmp_path: Path, monkeypatch):
|
||||
jobs = _use_data(monkeypatch, tmp_path / "data")
|
||||
done = jobs / "20261026090001"
|
||||
partial = jobs / "20261026090002"
|
||||
_record(done, status="done")
|
||||
_record(partial, status="done_with_errors", message="1 个失败")
|
||||
for directory in (done, partial):
|
||||
(directory / "progress.jsonl").write_text('{"id": 1, "offset": 2, "rows": 1}\n', encoding="utf-8")
|
||||
(directory / "ids.spool").write_text("1\n", encoding="utf-8")
|
||||
(directory / "ids.spool.meta").write_text("{}", encoding="utf-8")
|
||||
(directory / "ids.txt").write_text("1\n", encoding="utf-8")
|
||||
loaded = JobManager()._load(done.name)
|
||||
assert loaded.status == "done"
|
||||
assert not (done / "progress.jsonl").exists()
|
||||
assert not (done / "ids.spool").exists()
|
||||
assert not (done / "ids.spool.meta").exists()
|
||||
assert (done / "ids.txt").read_text(encoding="utf-8") == "1\n"
|
||||
kept = JobManager()._load(partial.name)
|
||||
assert kept.status == "done_with_errors"
|
||||
assert (partial / "progress.jsonl").exists()
|
||||
assert (partial / "ids.spool").exists()
|
||||
|
||||
|
||||
def test_move_hold_stays_paused(tmp_path: Path, monkeypatch):
|
||||
jobs = _use_data(monkeypatch, tmp_path / "data")
|
||||
directory = jobs / "20261026090003"
|
||||
_record(directory, status="running", message="下载中", pausedBy="move")
|
||||
loaded = JobManager()._load(directory.name)
|
||||
assert loaded.status == "paused"
|
||||
assert loaded.message == "已暂停"
|
||||
assert loaded.paused_by == "move"
|
||||
|
||||
|
||||
def test_prepare_shelves_active_jobs_and_resume_starts_them(tmp_path: Path, monkeypatch):
|
||||
asyncio.run(_prepare_and_resume(tmp_path, monkeypatch))
|
||||
|
||||
|
||||
async def _prepare_and_resume(tmp_path: Path, monkeypatch) -> None:
|
||||
root = tmp_path / "data"
|
||||
_use_data(monkeypatch, root)
|
||||
manager = JobManager()
|
||||
running = _make(manager, "running")
|
||||
queued = _make(manager, "queued")
|
||||
paused = _make(manager, "paused")
|
||||
old_jobs = state.jobs
|
||||
old_client = state.client
|
||||
old_user = state.user
|
||||
old_expired = state.expired
|
||||
state.jobs = manager
|
||||
|
||||
async def _quiet(_job):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("app.features.download.router.run_download", _quiet)
|
||||
try:
|
||||
with pytest.raises(NqiError, match="请选择一个空文件夹"):
|
||||
busy = tmp_path / "busy"
|
||||
busy.mkdir()
|
||||
(busy / "keep.txt").write_text("x", encoding="utf-8")
|
||||
await relocate.prepare(str(busy))
|
||||
with pytest.raises(NqiError, match="已经是当前数据目录"):
|
||||
await relocate.prepare(str(root))
|
||||
target = tmp_path / "next"
|
||||
prepared = await relocate.prepare(str(target))
|
||||
assert prepared["resumeIds"] == [running.id, queued.id]
|
||||
assert running.status == "paused" and running.paused_by == "move"
|
||||
assert queued.paused_by == "move"
|
||||
assert paused.status == "paused" and paused.paused_by == ""
|
||||
stored = json.loads((root / "resume-after-move.json").read_text(encoding="utf-8"))
|
||||
assert stored["ids"] == [running.id, queued.id]
|
||||
assert target.is_dir()
|
||||
state.client = object()
|
||||
state.user = {"loginId": "u"}
|
||||
state.expired = False
|
||||
resumed = await relocate.resume_moved()
|
||||
assert resumed["resumed"] == [running.id, queued.id]
|
||||
assert not (root / "resume-after-move.json").exists()
|
||||
assert running.status == "running"
|
||||
assert queued.status == "running"
|
||||
assert paused.status == "paused"
|
||||
await asyncio.sleep(0)
|
||||
finally:
|
||||
state.jobs = old_jobs
|
||||
state.client = old_client
|
||||
state.user = old_user
|
||||
state.expired = old_expired
|
||||
|
||||
|
||||
def _make(manager: JobManager, status: str):
|
||||
job = manager.create(
|
||||
network="NR",
|
||||
city_code="JM",
|
||||
city_name="江门",
|
||||
month="2026-09",
|
||||
groups=["rsrp"],
|
||||
concurrency=1,
|
||||
grid_ids=["1"],
|
||||
csv_path=None,
|
||||
grid_size="GRID20",
|
||||
whole_city=False,
|
||||
)
|
||||
job.status = status
|
||||
job.paused_by = ""
|
||||
job.message = "下载中" if status == "running" else "已暂停" if status == "paused" else "等待中"
|
||||
job.save()
|
||||
return job
|
||||
Reference in New Issue
Block a user