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 asyncio
import json import json
import os
import re import re
import shutil
import tempfile
import time import time
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from dataclasses import dataclass, field from dataclasses import dataclass, field
@@ -13,13 +16,16 @@ from pathlib import Path
from app.platform.client import NqiClient, NqiError from app.platform.client import NqiClient, NqiError
from app.features.download.fields import columns_for 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.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 DATA_DIR = DOWNLOAD_DIR
SETTINGS_PATH = DATA_ROOT / "settings.json" SETTINGS_PATH = DATA_ROOT / "settings.json"
_JOB_ID = re.compile(r"^(?:\d{14}(?:_\d+)?|[0-9a-f]{32})$") _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 @dataclass
@@ -51,6 +57,8 @@ class DownloadJob:
paused_by: str = "" paused_by: str = ""
stopping: bool = False stopping: bool = False
failed_tiles: list = field(default_factory=list) failed_tiles: list = field(default_factory=list)
id_count: int = 0
_ids_loaded: bool = True
subscribers: list[asyncio.Queue] = field(default_factory=list) subscribers: list[asyncio.Queue] = field(default_factory=list)
task: asyncio.Task | None = None task: asyncio.Task | None = None
cancel_event: asyncio.Event = field(default_factory=asyncio.Event) cancel_event: asyncio.Event = field(default_factory=asyncio.Event)
@@ -60,13 +68,31 @@ class DownloadJob:
def total(self) -> int: def total(self) -> int:
if self.whole_city: if self.whole_city:
return self.discovered return self.discovered
if self.id_count:
return self.id_count
return len(self.grid_ids) return len(self.grid_ids)
def is_active(self) -> bool: def is_active(self) -> bool:
return self.task is not None and not self.task.done() return self.task is not None and not self.task.done()
def load_ids(self) -> list[str]: 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: def snapshot(self) -> dict:
return { return {
@@ -108,7 +134,7 @@ class DownloadJob:
"wholeCity": self.whole_city, "wholeCity": self.whole_city,
"groups": self.groups, "groups": self.groups,
"concurrency": self.concurrency, "concurrency": self.concurrency,
"gridIds": [] if self.whole_city else self.grid_ids, "gridCount": self.id_count,
"discovered": self.discovered, "discovered": self.discovered,
"listingDone": self.listing_done, "listingDone": self.listing_done,
"csvPath": str(self.csv_path), "csvPath": str(self.csv_path),
@@ -120,11 +146,17 @@ class DownloadJob:
"writtenRows": self.written_rows, "writtenRows": self.written_rows,
"duplicateCount": self.duplicate_count, "duplicateCount": self.duplicate_count,
"failures": self.failures[-50:], "failures": self.failures[-50:],
"pausedBy": self.paused_by,
"stopping": self.stopping,
"failedTiles": list(self.failed_tiles),
} }
(self.directory / "job.json").write_text( if self.grid_ids:
json.dumps(payload, ensure_ascii=False, indent=2), self.id_count = len(self.grid_ids)
encoding="utf-8", 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: async def emit(self, kind: str, **extra) -> None:
event = {"type": kind, **self.snapshot(), **extra} event = {"type": kind, **self.snapshot(), **extra}
@@ -147,6 +179,138 @@ def _set_event() -> asyncio.Event:
return 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: def _new_job_id() -> str:
DATA_DIR.mkdir(parents=True, exist_ok=True) DATA_DIR.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d%H%M%S") 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: def store_task_limit(value: int) -> int:
limit = min(8, max(1, int(value))) limit = min(8, max(1, int(value)))
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True) _atomic_write_json(SETTINGS_PATH, {"maxConcurrentJobs": limit})
SETTINGS_PATH.write_text(
json.dumps({"maxConcurrentJobs": limit}, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return limit return limit
@@ -291,10 +451,10 @@ class JobManager:
size_name = "50米" if grid_size == "GRID50" else "20米" size_name = "50米" if grid_size == "GRID50" else "20米"
filename = f"栅格_{'5G' if network == 'NR' else '4G'}_{size_name}_{city_name}_{month}.csv" filename = f"栅格_{'5G' if network == 'NR' else '4G'}_{size_name}_{city_name}_{month}.csv"
if csv_path is None: if csv_path is None:
target = directory / filename target = DOWNLOAD_ROOT / job_id / filename
else: else:
target = csv_path.parent / job_id / csv_path.name 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( job = DownloadJob(
id=job_id, id=job_id,
directory=directory, directory=directory,
@@ -304,14 +464,25 @@ class JobManager:
month=month, month=month,
groups=groups, groups=groups,
concurrency=concurrency, concurrency=concurrency,
grid_ids=grid_ids, grid_ids=stored_ids,
csv_path=target, csv_path=target,
created_at=datetime.now().isoformat(timespec="seconds"), created_at=datetime.now().isoformat(timespec="seconds"),
grid_size=grid_size, grid_size=grid_size,
whole_city=whole_city, whole_city=whole_city,
id_count=len(stored_ids),
status="creating",
) )
job.save()
self.jobs[job_id] = job 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 return job
def get(self, job_id: str) -> DownloadJob: def get(self, job_id: str) -> DownloadJob:
@@ -319,65 +490,127 @@ class JobManager:
if job is None: if job is None:
job = self._load(job_id) job = self._load(job_id)
self.jobs[job_id] = job self.jobs[job_id] = job
self._ensure_ids(job)
return 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]: def list_jobs(self) -> list[dict]:
if not DATA_DIR.exists(): if not DATA_DIR.exists():
return [] return []
items = [] unfinished: list[dict] = []
for directory in sorted(DATA_DIR.iterdir(), reverse=True): finished: list[dict] = []
for directory in DATA_DIR.iterdir():
if not directory.is_dir():
continue
path = directory / "job.json" path = directory / "job.json"
if not path.exists(): if not path.exists():
continue continue
try: try:
data = json.loads(path.read_text(encoding="utf-8")) 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 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: if job_id in self.jobs:
job = self.jobs[job_id] job = self.jobs[job_id]
if job.status in {"running", "paused"} and not job.is_active(): if job.status in {"running", "paused"} and not job.is_active():
job.status = "cancelled" job.status = "cancelled"
job.message = "已中断" job.message = "已中断"
snap = job.snapshot() try:
items.append(snap) job.save()
continue except (OSError, NqiError):
status = data.get("status") or "queued" pass
message = data.get("message") or "" item = job.snapshot()
if status in {"running", "paused"}: else:
status = "cancelled" try:
message = "已中断" item = self._snapshot_from_file(directory, data)
finished, written = _progress_stats(directory) except (TypeError, ValueError, OSError):
whole = bool(data.get("wholeCity")) unfinished.append(_damaged_snapshot(job_id))
discovered = int(data.get("discovered") or 0) continue
stored_ids = data.get("gridIds") or [] if item.get("status") in _FINISHED_STATUSES:
items.append( finished.append(item)
{ else:
"id": job_id, unfinished.append(item)
"status": status, unfinished.sort(key=lambda item: item.get("createdAt") or "", reverse=True)
"message": message, finished.sort(key=lambda item: item.get("createdAt") or "", reverse=True)
"network": data.get("network"), return unfinished + finished[:50]
"cityCode": data.get("cityCode"),
"cityName": data.get("cityName"), def _snapshot_from_file(self, directory: Path, data: dict) -> dict:
"month": data.get("month"), status = str(data.get("status") or "queued")
"gridSize": data.get("gridSize") or "GRID20", message = str(data.get("message") or "")
"wholeCity": whole, if status in _INTERRUPTED_STATUSES:
"listingDone": bool(data.get("listingDone", not whole)), status = "cancelled"
"concurrency": data.get("concurrency") or 4, message = "已中断"
"total": (discovered or len(stored_ids)) if whole else len(stored_ids), data["status"] = status
"discovered": discovered, data["message"] = message
"duplicateCount": int(data.get("duplicateCount") or 0), try:
"completed": finished or data.get("completed") or 0, _atomic_write_json(directory / "job.json", data)
"failed": data.get("failed") or 0, except (OSError, NqiError):
"writtenRows": written or data.get("writtenRows") or 0, pass
"fileBytes": _file_bytes(data.get("csvPath") or ""), whole = bool(data.get("wholeCity"))
"csvPath": data.get("csvPath"), discovered = int(data.get("discovered") or 0)
"failures": data.get("failures") or [], if "gridCount" in data and data.get("gridCount") is not None:
"createdAt": data.get("createdAt"), grid_count = int(data.get("gridCount") or 0)
"name": f"{'5G' if data.get('network') == 'NR' else '4G'} · {data.get('cityName') or ''} · {data.get('month') or ''}", else:
} grid_count = len(data.get("gridIds") or [])
) network = data.get("network")
return items[:20] 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: def _load(self, job_id: str) -> DownloadJob:
if not _JOB_ID.fullmatch(job_id): if not _JOB_ID.fullmatch(job_id):
@@ -385,49 +618,107 @@ class JobManager:
path = DATA_DIR / job_id / "job.json" path = DATA_DIR / job_id / "job.json"
if not path.exists(): if not path.exists():
raise NqiError("任务不存在") 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")) data = json.loads(path.read_text(encoding="utf-8"))
return DownloadJob( csv_path = data.get("csvPath")
id=data["id"], if not csv_path:
directory=path.parent, return None
network=data["network"], return Path(csv_path).parent
city_code=data["cityCode"], except (OSError, json.JSONDecodeError, UnicodeError, TypeError, ValueError):
city_name=data["cityName"], return None
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 []),
)
def _progress_stats(directory: Path) -> tuple[int, int]: def _progress_stats(directory: Path) -> tuple[int, int]:
path = directory / "progress.jsonl" path = directory / "progress.jsonl"
if not path.exists(): try:
stat = path.stat()
except OSError:
return 0, 0 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 finished = 0
written = 0 written = 0
for line in path.read_text(encoding="utf-8").splitlines(): with path.open("rb") as handle:
text = line.strip() for line in handle:
if not text: text = line.strip()
continue if not text:
try: continue
record = json.loads(text) try:
except json.JSONDecodeError: record = json.loads(text)
break except (UnicodeDecodeError, json.JSONDecodeError):
finished += 1 break
written += int(record.get("rows") or 0) 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 return finished, written
+295
View File
@@ -1,10 +1,13 @@
import csv import csv
import json
import io import io
import os import os
import threading import threading
from pathlib import Path from pathlib import Path
from app.features.download import jobs as job_module
from app.features.download.ids import parse_table from app.features.download.ids import parse_table
from app.features.download.jobs import JobManager, ensure_output_dir
from app.features.download.journal import CsvJournal, explain_os_error from app.features.download.journal import CsvJournal, explain_os_error
from app.platform.client import NqiError from app.platform.client import NqiError
@@ -164,3 +167,295 @@ def _patch_fsync(monkeypatch):
monkeypatch.setattr("app.features.download.journal.os.fsync", spy) monkeypatch.setattr("app.features.download.journal.os.fsync", spy)
return calls return calls
def test_ids_file_replaces_grid_ids_and_release_reloads(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
manager = JobManager()
output = tmp_path / "save" / "栅格.csv"
job = manager.create(
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=2,
grid_ids=["7", "8"],
csv_path=output,
grid_size="GRID20",
whole_city=False,
)
stored = json.loads((job.directory / "job.json").read_text(encoding="utf-8"))
assert "gridIds" not in stored
assert stored["gridCount"] == 2
assert (job.directory / "ids.txt").read_text(encoding="utf-8").splitlines() == ["7", "8"]
assert job.csv_path == tmp_path / "save" / job.id / "栅格.csv"
job.paused_by = "expired"
job.stopping = True
job.failed_tiles = [{"west": 1}]
job.status = "done"
job.save()
assert job.grid_ids == []
loaded = JobManager()._load(job.id)
assert loaded.paused_by == "expired"
assert loaded.stopping is True
assert loaded.failed_tiles == [{"west": 1}]
assert loaded.snapshot()["pausedBy"] == "expired"
assert loaded.snapshot()["stopping"] is True
assert loaded.snapshot()["failedTiles"] == [{"west": 1}]
assert loaded.snapshot()["total"] == 2
assert loaded.load_ids() == ["7", "8"]
other = manager.create(
network="LTE",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["9"],
csv_path=output,
whole_city=False,
)
other.status = "cancelled"
other.message = "已停止"
other.save()
assert other.grid_ids == []
assert manager.get(other.id).grid_ids == ["9"]
def test_save_retries_permission_error_and_corrupt_record(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
monkeypatch.setattr(job_module.time, "sleep", lambda _seconds: None)
job = JobManager().create(
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["1"],
csv_path=tmp_path / "a.csv",
whole_city=False,
)
real = os.replace
calls = {"n": 0}
def flaky(src, dst):
calls["n"] += 1
if calls["n"] < 3:
error = PermissionError(13, "busy", str(dst))
error.winerror = 32
raise error
return real(src, dst)
monkeypatch.setattr(job_module.os, "replace", flaky)
job.message = "仍在"
job.save()
assert calls["n"] == 3
assert json.loads((job.directory / "job.json").read_text(encoding="utf-8"))["message"] == "仍在"
assert list(job.directory.glob("*.tmp")) == []
(job.directory / "job.json").write_text("{", encoding="utf-8")
try:
JobManager()._load(job.id)
except NqiError as exc:
assert str(exc) == "任务记录损坏"
else:
raise AssertionError("损坏的任务记录应被拒绝")
def test_startup_marks_leftover_jobs_interrupted_and_list_skips_progress(tmp_path: Path, monkeypatch):
jobs = tmp_path / "jobs"
monkeypatch.setattr(job_module, "DATA_DIR", jobs)
monkeypatch.setattr(job_module, "_progress_stats", lambda _directory: (_ for _ in ()).throw(AssertionError("不应读取进度")))
for index, status in enumerate(("running", "paused", "queued"), start=1):
_write_record(
jobs / f"2026010101010{index}",
status=status,
message="下载中",
createdAt=f"2026-01-0{index}T00:00:00",
completed=index,
writtenRows=index * 2,
)
(jobs / f"2026010101010{index}" / "progress.jsonl").write_text(
'{"id": 1, "offset": 1, "rows": 99}\n' * 20,
encoding="utf-8",
)
for index in range(60):
_write_record(
jobs / f"202602{index:08d}",
status="done",
message="已完成",
createdAt=f"2026-02-01T00:00:{index:02d}",
completed=1,
writtenRows=1,
)
reloaded = JobManager()._load("20260101010102")
assert reloaded.status == "cancelled"
assert reloaded.message == "已中断"
items = JobManager().list_jobs()
unfinished = [item for item in items if item["status"] != "done"]
finished = [item for item in items if item["status"] == "done"]
assert len(unfinished) == 3
assert len(finished) == 50
assert {item["message"] for item in unfinished} == {"已中断"}
assert {item["status"] for item in unfinished} == {"cancelled"}
assert {item["writtenRows"] for item in unfinished} == {2, 4, 6}
assert [item["completed"] for item in sorted(unfinished, key=lambda item: item["id"])] == [1, 2, 3]
assert finished[0]["createdAt"] >= finished[-1]["createdAt"]
stored = json.loads((jobs / "20260101010101" / "job.json").read_text(encoding="utf-8"))
assert stored["status"] == "cancelled"
assert stored["message"] == "已中断"
def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
manager = JobManager()
kept = manager.create(
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["1"],
csv_path=None,
whole_city=True,
)
download_dir = kept.csv_path.parent
assert download_dir == tmp_path / "downloads" / kept.id
manager.delete(kept.id, files=False)
assert not kept.directory.exists()
assert download_dir.exists()
removed = manager.create(
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["1"],
csv_path=None,
whole_city=True,
)
removed_dir = removed.csv_path.parent
manager.delete(removed.id, files=True)
assert not removed.directory.exists()
assert not removed_dir.exists()
active = manager.create(
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["1"],
csv_path=None,
whole_city=True,
)
class Alive:
def done(self):
return False
active.task = Alive()
active.status = "running"
try:
manager.delete(active.id, files=True)
except NqiError as exc:
assert "不能删除" in str(exc)
else:
raise AssertionError("进行中的任务不能删除")
assert active.directory.exists()
def test_output_dir_permission_message(tmp_path: Path, monkeypatch):
real_open = Path.open
def deny(self, *args, **kwargs):
if self.name.startswith(".nqi-write-"):
error = PermissionError(13, "busy")
error.winerror = 33
raise error
return real_open(self, *args, **kwargs)
monkeypatch.setattr(Path, "open", deny)
try:
ensure_output_dir(tmp_path)
except NqiError as exc:
assert str(exc) == "文件被占用,请先关闭 Excel 等程序"
else:
raise AssertionError("不可写目录应返回中文")
def test_legacy_grid_ids_can_still_be_loaded(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
directory = tmp_path / "jobs" / "20260101010101"
_write_record(
directory,
status="done",
message="已完成",
createdAt="2026-01-01T00:00:00",
completed=2,
writtenRows=2,
)
path = directory / "job.json"
data = json.loads(path.read_text(encoding="utf-8"))
del data["gridCount"]
data["gridIds"] = ["3", "4"]
path.write_text(json.dumps(data), encoding="utf-8")
loaded = JobManager()._load("20260101010101")
assert loaded.id_count == 2
assert loaded.load_ids() == ["3", "4"]
assert (directory / "ids.txt").read_text(encoding="utf-8").splitlines() == ["3", "4"]
def test_progress_stats_uses_mtime_cache(tmp_path: Path, monkeypatch):
progress = tmp_path / "progress.jsonl"
progress.write_bytes(b'{"id": 1, "offset": 3, "rows": 2}\n{"id": 2, "offset": 5, "rows": 1}\n')
assert job_module._progress_stats(tmp_path) == (2, 3)
def fail_open(*_args, **_kwargs):
raise AssertionError("缓存命中后不应再读进度")
monkeypatch.setattr(Path, "open", fail_open)
assert job_module._progress_stats(tmp_path) == (2, 3)
def _write_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": 3,
"wholeCity": False,
"discovered": 0,
"listingDone": True,
"csvPath": str(directory / "out.csv"),
"createdAt": "2026-09-21T12:00:09",
"status": "done",
"message": "已完成",
"completed": 3,
"failed": 0,
"writtenRows": 4,
"duplicateCount": 0,
"failures": [],
"pausedBy": "",
"stopping": False,
"failedTiles": [],
}
payload.update(overrides)
(directory / "job.json").write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")