fix: 任务编号改存文件,列表按状态返回并在启动时标记已中断

This commit is contained in:
2026-10-25 07:20:39 +08:00
parent 6b9a2ad860
commit fb572a53df
2 changed files with 681 additions and 95 deletions
+386 -95
View File
@@ -4,7 +4,10 @@ from __future__ import annotations
import asyncio
import json
import os
import re
import shutil
import tempfile
import time
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
@@ -13,13 +16,16 @@ from pathlib import Path
from app.platform.client import NqiClient, NqiError
from app.features.download.fields import columns_for
from app.features.download.journal import CsvJournal
from app.features.download.journal import CsvJournal, explain_os_error
from app.features.download.rows import build_rows
from app.shared.paths import DATA_ROOT, DOWNLOAD_DIR
from app.shared.paths import DATA_ROOT, DOWNLOAD_DIR, DOWNLOAD_ROOT
DATA_DIR = DOWNLOAD_DIR
SETTINGS_PATH = DATA_ROOT / "settings.json"
_JOB_ID = re.compile(r"^(?:\d{14}(?:_\d+)?|[0-9a-f]{32})$")
_TERMINAL_STATUSES = {"done", "done_with_errors", "cancelled", "error"}
_INTERRUPTED_STATUSES = {"running", "paused", "queued", "creating"}
_FINISHED_STATUSES = {"done", "done_with_errors"}
@dataclass
@@ -51,6 +57,8 @@ class DownloadJob:
paused_by: str = ""
stopping: bool = False
failed_tiles: list = field(default_factory=list)
id_count: int = 0
_ids_loaded: bool = True
subscribers: list[asyncio.Queue] = field(default_factory=list)
task: asyncio.Task | None = None
cancel_event: asyncio.Event = field(default_factory=asyncio.Event)
@@ -60,13 +68,31 @@ class DownloadJob:
def total(self) -> int:
if self.whole_city:
return self.discovered
if self.id_count:
return self.id_count
return len(self.grid_ids)
def is_active(self) -> bool:
return self.task is not None and not self.task.done()
def load_ids(self) -> list[str]:
return self.grid_ids
path = self.directory / "ids.txt"
if not path.exists():
return []
found: list[str] = []
with path.open("r", encoding="utf-8") as handle:
for line in handle:
text = line.strip()
if text:
found.append(text)
return found
def store_ids(self, grid_ids: list[str]) -> None:
self.grid_ids = [str(item) for item in grid_ids]
self.id_count = len(self.grid_ids)
self._ids_loaded = True
if not self.whole_city:
_write_ids(self.directory, self.grid_ids)
def snapshot(self) -> dict:
return {
@@ -108,7 +134,7 @@ class DownloadJob:
"wholeCity": self.whole_city,
"groups": self.groups,
"concurrency": self.concurrency,
"gridIds": [] if self.whole_city else self.grid_ids,
"gridCount": self.id_count,
"discovered": self.discovered,
"listingDone": self.listing_done,
"csvPath": str(self.csv_path),
@@ -120,11 +146,17 @@ class DownloadJob:
"writtenRows": self.written_rows,
"duplicateCount": self.duplicate_count,
"failures": self.failures[-50:],
"pausedBy": self.paused_by,
"stopping": self.stopping,
"failedTiles": list(self.failed_tiles),
}
(self.directory / "job.json").write_text(
json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8",
)
if self.grid_ids:
self.id_count = len(self.grid_ids)
payload["gridCount"] = self.id_count
_atomic_write_json(self.directory / "job.json", payload)
if self.status in _TERMINAL_STATUSES:
self.grid_ids = []
self._ids_loaded = False
async def emit(self, kind: str, **extra) -> None:
event = {"type": kind, **self.snapshot(), **extra}
@@ -147,6 +179,138 @@ def _set_event() -> asyncio.Event:
return event
def _atomic_write_json(path: Path, payload: dict) -> None:
data = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent)
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
last_error: PermissionError | None = None
for attempt in range(5):
try:
os.replace(tmp_path, path)
return
except PermissionError as exc:
last_error = exc
time.sleep(0.05 * (attempt + 1))
message = explain_os_error(last_error) if last_error else None
raise NqiError(message or "任务记录保存失败,请稍后重试")
except OSError as exc:
message = explain_os_error(exc)
if message:
raise NqiError(message) from exc
raise
finally:
if tmp_path.exists():
try:
tmp_path.unlink()
except OSError:
pass
def _write_ids(directory: Path, grid_ids: list[str]) -> None:
directory.mkdir(parents=True, exist_ok=True)
target = directory / "ids.txt"
fd, tmp_name = tempfile.mkstemp(prefix="ids.txt.", suffix=".tmp", dir=directory)
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
for grid_id in grid_ids:
handle.write(str(grid_id))
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, target)
except OSError as exc:
message = explain_os_error(exc)
if message:
raise NqiError(message) from exc
raise
finally:
if tmp_path.exists():
try:
tmp_path.unlink()
except OSError:
pass
def ensure_output_dir(folder: Path) -> None:
if not folder.is_absolute():
raise NqiError("保存位置必须是绝对路径")
probe: Path | None = None
try:
folder.mkdir(parents=True, exist_ok=True)
probe = folder / f".nqi-write-{os.getpid()}-{time.time_ns()}"
with probe.open("wb") as handle:
handle.write(b"")
handle.flush()
os.fsync(handle.fileno())
except OSError as exc:
message = explain_os_error(exc)
raise NqiError(message or "保存位置不可写") from exc
finally:
if probe is not None:
try:
probe.unlink()
except OSError:
pass
def _mkdir_download(folder: Path) -> None:
try:
folder.mkdir(parents=True, exist_ok=True)
except OSError as exc:
message = explain_os_error(exc)
raise NqiError(message or "无法创建下载目录") from exc
def _remove_download_dir(folder: Path, data_dir: Path, job_id: str) -> None:
try:
if not folder.exists():
return
if folder.resolve() == data_dir.resolve():
return
except OSError:
return
if folder.name != job_id:
return
shutil.rmtree(folder, ignore_errors=True)
def _damaged_snapshot(job_id: str) -> dict:
return {
"id": job_id,
"status": "error",
"message": "任务记录损坏",
"network": "",
"cityCode": "",
"cityName": "",
"month": "",
"gridSize": "GRID20",
"wholeCity": False,
"listingDone": True,
"concurrency": 1,
"total": 0,
"discovered": 0,
"duplicateCount": 0,
"completed": 0,
"failed": 0,
"writtenRows": 0,
"fileBytes": 0,
"csvPath": "",
"failures": [],
"pausedBy": "",
"stopping": False,
"failedTiles": [],
"createdAt": "",
"name": "任务记录损坏",
}
def _new_job_id() -> str:
DATA_DIR.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
@@ -171,11 +335,7 @@ def load_task_limit() -> int:
def store_task_limit(value: int) -> int:
limit = min(8, max(1, int(value)))
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
SETTINGS_PATH.write_text(
json.dumps({"maxConcurrentJobs": limit}, ensure_ascii=False, indent=2),
encoding="utf-8",
)
_atomic_write_json(SETTINGS_PATH, {"maxConcurrentJobs": limit})
return limit
@@ -291,10 +451,10 @@ class JobManager:
size_name = "50米" if grid_size == "GRID50" else "20米"
filename = f"栅格_{'5G' if network == 'NR' else '4G'}_{size_name}_{city_name}_{month}.csv"
if csv_path is None:
target = directory / filename
target = DOWNLOAD_ROOT / job_id / filename
else:
target = csv_path.parent / job_id / csv_path.name
target.parent.mkdir(parents=True, exist_ok=True)
stored_ids = [] if whole_city else list(grid_ids)
job = DownloadJob(
id=job_id,
directory=directory,
@@ -304,14 +464,25 @@ class JobManager:
month=month,
groups=groups,
concurrency=concurrency,
grid_ids=grid_ids,
grid_ids=stored_ids,
csv_path=target,
created_at=datetime.now().isoformat(timespec="seconds"),
grid_size=grid_size,
whole_city=whole_city,
id_count=len(stored_ids),
status="creating",
)
job.save()
self.jobs[job_id] = job
try:
_mkdir_download(target.parent)
if stored_ids:
_write_ids(directory, stored_ids)
job.save()
except Exception:
self.jobs.pop(job_id, None)
shutil.rmtree(directory, ignore_errors=True)
_remove_download_dir(target.parent, directory, job_id)
raise
return job
def get(self, job_id: str) -> DownloadJob:
@@ -319,65 +490,127 @@ class JobManager:
if job is None:
job = self._load(job_id)
self.jobs[job_id] = job
self._ensure_ids(job)
return job
def _ensure_ids(self, job: DownloadJob) -> None:
if job.whole_city or job._ids_loaded or job.status == "done":
return
job.grid_ids = job.load_ids()
if job.grid_ids:
job.id_count = len(job.grid_ids)
job._ids_loaded = True
def list_jobs(self) -> list[dict]:
if not DATA_DIR.exists():
return []
items = []
for directory in sorted(DATA_DIR.iterdir(), reverse=True):
unfinished: list[dict] = []
finished: list[dict] = []
for directory in DATA_DIR.iterdir():
if not directory.is_dir():
continue
path = directory / "job.json"
if not path.exists():
continue
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
except (OSError, json.JSONDecodeError, UnicodeError, TypeError, ValueError):
unfinished.append(_damaged_snapshot(directory.name))
continue
job_id = data.get("id")
if not isinstance(data, dict):
unfinished.append(_damaged_snapshot(directory.name))
continue
job_id = str(data.get("id") or directory.name)
if job_id in self.jobs:
job = self.jobs[job_id]
if job.status in {"running", "paused"} and not job.is_active():
job.status = "cancelled"
job.message = "已中断"
snap = job.snapshot()
items.append(snap)
continue
status = data.get("status") or "queued"
message = data.get("message") or ""
if status in {"running", "paused"}:
status = "cancelled"
message = "已中断"
finished, written = _progress_stats(directory)
whole = bool(data.get("wholeCity"))
discovered = int(data.get("discovered") or 0)
stored_ids = data.get("gridIds") or []
items.append(
{
"id": job_id,
"status": status,
"message": message,
"network": data.get("network"),
"cityCode": data.get("cityCode"),
"cityName": data.get("cityName"),
"month": data.get("month"),
"gridSize": data.get("gridSize") or "GRID20",
"wholeCity": whole,
"listingDone": bool(data.get("listingDone", not whole)),
"concurrency": data.get("concurrency") or 4,
"total": (discovered or len(stored_ids)) if whole else len(stored_ids),
"discovered": discovered,
"duplicateCount": int(data.get("duplicateCount") or 0),
"completed": finished or data.get("completed") or 0,
"failed": data.get("failed") or 0,
"writtenRows": written or data.get("writtenRows") or 0,
"fileBytes": _file_bytes(data.get("csvPath") or ""),
"csvPath": data.get("csvPath"),
"failures": data.get("failures") or [],
"createdAt": data.get("createdAt"),
"name": f"{'5G' if data.get('network') == 'NR' else '4G'} · {data.get('cityName') or ''} · {data.get('month') or ''}",
}
)
return items[:20]
try:
job.save()
except (OSError, NqiError):
pass
item = job.snapshot()
else:
try:
item = self._snapshot_from_file(directory, data)
except (TypeError, ValueError, OSError):
unfinished.append(_damaged_snapshot(job_id))
continue
if item.get("status") in _FINISHED_STATUSES:
finished.append(item)
else:
unfinished.append(item)
unfinished.sort(key=lambda item: item.get("createdAt") or "", reverse=True)
finished.sort(key=lambda item: item.get("createdAt") or "", reverse=True)
return unfinished + finished[:50]
def _snapshot_from_file(self, directory: Path, data: dict) -> dict:
status = str(data.get("status") or "queued")
message = str(data.get("message") or "")
if status in _INTERRUPTED_STATUSES:
status = "cancelled"
message = "已中断"
data["status"] = status
data["message"] = message
try:
_atomic_write_json(directory / "job.json", data)
except (OSError, NqiError):
pass
whole = bool(data.get("wholeCity"))
discovered = int(data.get("discovered") or 0)
if "gridCount" in data and data.get("gridCount") is not None:
grid_count = int(data.get("gridCount") or 0)
else:
grid_count = len(data.get("gridIds") or [])
network = data.get("network")
return {
"id": str(data.get("id") or directory.name),
"status": status,
"message": message,
"network": network,
"cityCode": data.get("cityCode"),
"cityName": data.get("cityName"),
"month": data.get("month"),
"gridSize": data.get("gridSize") or "GRID20",
"wholeCity": whole,
"listingDone": bool(data.get("listingDone", not whole)),
"concurrency": data.get("concurrency") or 4,
"total": discovered if whole else grid_count,
"discovered": discovered,
"duplicateCount": int(data.get("duplicateCount") or 0),
"completed": int(data.get("completed") or 0),
"failed": int(data.get("failed") or 0),
"writtenRows": int(data.get("writtenRows") or 0),
"fileBytes": _file_bytes(data.get("csvPath") or ""),
"csvPath": data.get("csvPath"),
"failures": data.get("failures") or [],
"pausedBy": data.get("pausedBy") or "",
"stopping": bool(data.get("stopping") or False),
"failedTiles": list(data.get("failedTiles") or []),
"createdAt": data.get("createdAt"),
"name": f"{'5G' if network == 'NR' else '4G'} · {data.get('cityName') or ''} · {data.get('month') or ''}",
}
def delete(self, job_id: str, *, files: bool = False) -> None:
if not _JOB_ID.fullmatch(job_id or ""):
raise NqiError("任务不存在")
data_dir = DATA_DIR / job_id
job = self.jobs.get(job_id)
if job is None and not data_dir.exists():
raise NqiError("任务不存在")
if job is not None and (job.is_active() or job.status == "running"):
raise NqiError("这个任务正在下载,不能删除")
csv_parent: Path | None = None
if job is not None:
csv_parent = job.csv_path.parent
else:
csv_parent = _csv_parent(data_dir)
self.jobs.pop(job_id, None)
if data_dir.exists():
shutil.rmtree(data_dir)
if files and csv_parent is not None:
_remove_download_dir(csv_parent, data_dir, job_id)
def _load(self, job_id: str) -> DownloadJob:
if not _JOB_ID.fullmatch(job_id):
@@ -385,49 +618,107 @@ class JobManager:
path = DATA_DIR / job_id / "job.json"
if not path.exists():
raise NqiError("任务不存在")
try:
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("任务记录不是对象")
except (OSError, json.JSONDecodeError, UnicodeError, TypeError, ValueError) as exc:
raise NqiError("任务记录损坏") from exc
try:
status = str(data.get("status") or "queued")
message = str(data.get("message") or "")
interrupted = status in _INTERRUPTED_STATUSES
if interrupted:
status = "cancelled"
message = "已中断"
whole = bool(data.get("wholeCity"))
legacy_ids = [str(item) for item in data.get("gridIds") or []]
if data.get("gridCount") is None:
id_count = len(legacy_ids)
else:
id_count = int(data.get("gridCount") or 0)
ids_path = path.parent / "ids.txt"
if not whole and legacy_ids and not ids_path.exists():
_write_ids(path.parent, legacy_ids)
id_count = len(legacy_ids)
job = DownloadJob(
id=str(data["id"]),
directory=path.parent,
network=str(data["network"]),
city_code=str(data["cityCode"]),
city_name=str(data["cityName"]),
month=str(data["month"]),
grid_size=str(data.get("gridSize") or "GRID20"),
whole_city=whole,
groups=list(data.get("groups") or []),
concurrency=int(data.get("concurrency") or 4),
grid_ids=[],
id_count=id_count,
_ids_loaded=whole or status == "done",
discovered=int(data.get("discovered") or 0),
listing_done=bool(data.get("listingDone", not whole)),
csv_path=Path(data["csvPath"]),
created_at=str(data.get("createdAt") or ""),
status=status,
message=message,
completed=int(data.get("completed") or 0),
failed=int(data.get("failed") or 0),
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 ""),
stopping=bool(data.get("stopping") or False),
failed_tiles=list(data.get("failedTiles") or []),
)
except (KeyError, TypeError, ValueError) as exc:
raise NqiError("任务记录损坏") from exc
if interrupted:
job.save()
return job
def _csv_parent(data_dir: Path) -> Path | None:
path = data_dir / "job.json"
try:
data = json.loads(path.read_text(encoding="utf-8"))
return DownloadJob(
id=data["id"],
directory=path.parent,
network=data["network"],
city_code=data["cityCode"],
city_name=data["cityName"],
month=data["month"],
grid_size=data.get("gridSize") or "GRID20",
whole_city=bool(data.get("wholeCity")),
groups=list(data.get("groups") or []),
concurrency=int(data.get("concurrency") or 4),
grid_ids=[] if data.get("wholeCity") else [str(item) for item in data.get("gridIds") or []],
discovered=int(data.get("discovered") or 0),
listing_done=bool(data.get("listingDone", not data.get("wholeCity"))),
csv_path=Path(data["csvPath"]),
created_at=data.get("createdAt") or "",
status=data.get("status") or "queued",
message=data.get("message") or "",
completed=int(data.get("completed") or 0),
failed=int(data.get("failed") or 0),
written_rows=int(data.get("writtenRows") or 0),
duplicate_count=int(data.get("duplicateCount") or 0),
failures=list(data.get("failures") or []),
)
csv_path = data.get("csvPath")
if not csv_path:
return None
return Path(csv_path).parent
except (OSError, json.JSONDecodeError, UnicodeError, TypeError, ValueError):
return None
def _progress_stats(directory: Path) -> tuple[int, int]:
path = directory / "progress.jsonl"
if not path.exists():
try:
stat = path.stat()
except OSError:
return 0, 0
stamp = (stat.st_mtime_ns, stat.st_size)
cache: dict = getattr(_progress_stats, "_cache", {})
found = cache.get(str(path))
if found and found[0] == stamp:
return found[1]
finished = 0
written = 0
for line in path.read_text(encoding="utf-8").splitlines():
text = line.strip()
if not text:
continue
try:
record = json.loads(text)
except json.JSONDecodeError:
break
finished += 1
written += int(record.get("rows") or 0)
with path.open("rb") as handle:
for line in handle:
text = line.strip()
if not text:
continue
try:
record = json.loads(text)
except (UnicodeDecodeError, json.JSONDecodeError):
break
finished += 1
written += int(record.get("rows") or 0)
if not cache:
cache = {}
_progress_stats._cache = cache
if len(cache) > 256:
cache.clear()
cache[str(path)] = (stamp, (finished, written))
return finished, written