Files
NqiTools/backend/app/features/download/jobs.py
T

1312 lines
46 KiB
Python

"""下载任务:协程并发查询,单个写者实时落盘。"""
from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import os
import re
import shutil
import tempfile
import time
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from app.platform.client import NqiAuthError, NqiError
from app.features.download.fields import columns_for
from app.features.download.journal import CsvJournal, explain_os_error
from app.features.download.rows import build_rows
from app.features.download.spool import IdSpool
from app.shared.paths import DATA_ROOT, DOWNLOAD_DIR, DOWNLOAD_ROOT
logger = logging.getLogger("nqi.download")
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
class DownloadJob:
id: str
directory: Path
network: str
city_code: str
city_name: str
month: str
groups: list[str]
concurrency: int
grid_ids: list[str]
csv_path: Path
created_at: str
grid_size: str = "GRID20"
whole_city: bool = False
id_field: str = "grid20_id"
status: str = "queued"
message: str = ""
completed: int = 0
failed: int = 0
written_rows: int = 0
duplicate_count: int = 0
discovered: int = 0
listing_done: bool = True
last_flush: float = 0.0
failures: list[dict[str, str]] = field(default_factory=list)
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)
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:
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]:
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 {
"id": self.id,
"status": self.status,
"message": self.message,
"network": self.network,
"cityCode": self.city_code,
"cityName": self.city_name,
"month": self.month,
"gridSize": self.grid_size,
"wholeCity": self.whole_city,
"listingDone": self.listing_done,
"concurrency": self.concurrency,
"total": self.total,
"discovered": self.discovered,
"duplicateCount": self.duplicate_count,
"completed": self.completed,
"failed": self.failed,
"writtenRows": self.written_rows,
"fileBytes": _file_bytes(self.csv_path),
"csvPath": str(self.csv_path),
"failures": self.failures[-20:],
"pausedBy": self.paused_by,
"stopping": self.stopping,
"failedTiles": list(self.failed_tiles),
"createdAt": self.created_at,
"name": f"{'5G' if self.network == 'NR' else '4G'} · {self.city_name} · {self.month}",
}
def save(self) -> None:
payload = {
"id": self.id,
"network": self.network,
"cityCode": self.city_code,
"cityName": self.city_name,
"month": self.month,
"gridSize": self.grid_size,
"wholeCity": self.whole_city,
"groups": self.groups,
"concurrency": self.concurrency,
"gridCount": self.id_count,
"discovered": self.discovered,
"listingDone": self.listing_done,
"csvPath": str(self.csv_path),
"createdAt": self.created_at,
"status": self.status,
"message": self.message,
"completed": self.completed,
"failed": self.failed,
"writtenRows": self.written_rows,
"duplicateCount": self.duplicate_count,
"failures": self.failures[-50:],
"pausedBy": self.paused_by,
"stopping": self.stopping,
"failedTiles": list(self.failed_tiles),
}
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:
# 进度改由轮询读取。subscribers 仍留在任务对象上,避免改动 C1 的 dataclass 字段。
return None
def _file_bytes(path: str | Path) -> int:
if not path:
return 0
try:
return Path(path).stat().st_size
except OSError:
return 0
def _set_event() -> asyncio.Event:
event = asyncio.Event()
event.set()
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")
number = 1
while True:
candidate = stamp if number == 1 else f"{stamp}_{number}"
try:
(DATA_DIR / candidate).mkdir()
except FileExistsError:
number += 1
continue
return candidate
def load_task_limit() -> int:
try:
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
return min(8, max(1, int(data.get("maxConcurrentJobs") or 2)))
except (OSError, json.JSONDecodeError, TypeError, ValueError):
return 2
def store_task_limit(value: int) -> int:
limit = min(8, max(1, int(value)))
_atomic_write_json(SETTINGS_PATH, {"maxConcurrentJobs": limit})
return limit
class JobManager:
def __init__(self) -> None:
self.jobs: dict[str, DownloadJob] = {}
self.max_concurrent = load_task_limit()
def running_count(self) -> int:
# 只统计真正在下载的任务。暂停后协程还在,但不占名额。
return sum(1 for job in self.jobs.values() if job.is_active() and job.status == "running")
def suspend_all(self, reason: str, mark: str) -> None:
for job in self.jobs.values():
if job.status not in {"running", "queued"}:
continue
if job.status == "running":
job.run_event.clear()
job.status = "paused"
job.paused_by = mark
job.message = reason
job.save()
def resume_marked(self, mark: str) -> None:
for job in self.jobs.values():
if job.paused_by != mark:
continue
job.paused_by = ""
if job.status == "paused":
job.status = "queued"
job.message = "等待中"
if job.whole_city:
job.listing_done = False
job.save()
def queued_jobs(self) -> list[DownloadJob]:
waiting = [job for job in self.jobs.values() if job.status == "queued"]
waiting.sort(key=lambda job: (job.created_at, job.id))
return waiting
def place(self, job: DownloadJob) -> str:
"""有空位就执行,否则等待。活跃任务只恢复,不另起一次。"""
if job.status == "done":
raise NqiError("这个任务已经完成")
if job.status == "running" and job.is_active():
raise NqiError("这个任务正在下载")
if self.running_count() >= self.max_concurrent:
self._queue(job)
return "wait"
job.stopping = False
job.run_event.set()
job.status = "running"
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()
return "resume"
job.cancel_event = asyncio.Event()
job.message = "准备中"
job.save()
return "run"
def pause(self, job: DownloadJob) -> None:
if job.stopping or job.cancel_event.is_set():
raise NqiError("任务正在停止")
if job.status != "running" or not job.is_active():
raise NqiError("这个任务没有在下载")
job.run_event.clear()
job.status = "paused"
job.message = "已暂停"
job.save()
def request_stop(self, job: DownloadJob) -> None:
if not job.is_active():
if job.status == "done":
raise NqiError("这个任务已经完成")
job.stopping = False
job.status = "cancelled"
job.message = "已取消"
job.save()
return
job.stopping = True
job.cancel_event.set()
job.run_event.set()
job.status = "running"
job.message = "正在停止"
job.save()
def _queue(self, job: DownloadJob) -> None:
job.status = "queued"
job.message = "等待中"
if job.whole_city:
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
def create(
self,
*,
network: str,
city_code: str,
city_name: str,
month: str,
groups: list[str],
concurrency: int,
grid_ids: list[str],
csv_path: Path | None,
grid_size: str = "GRID20",
whole_city: bool = False,
) -> DownloadJob:
job_id = _new_job_id()
directory = DATA_DIR / job_id
directory.mkdir(parents=True, exist_ok=True)
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 = DOWNLOAD_ROOT / job_id / filename
else:
target = csv_path.parent / job_id / csv_path.name
stored_ids = [] if whole_city else list(grid_ids)
job = DownloadJob(
id=job_id,
directory=directory,
network=network,
city_code=city_code,
city_name=city_name,
month=month,
groups=groups,
concurrency=concurrency,
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",
)
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:
job = self.jobs.get(job_id)
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 []
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, UnicodeError, TypeError, ValueError):
unfinished.append(_damaged_snapshot(directory.name))
continue
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 = "已中断"
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):
raise NqiError("任务不存在")
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=_combine_failed(data.get("failedTiles"), _spool_failed_tiles(path.parent)),
)
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"))
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"
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
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
def _note_progress(job: DownloadJob) -> None:
if job.stopping or job.cancel_event.is_set():
job.message = "正在停止"
return
if job.whole_city and job.status == "running" and not job.listing_done and IdSpool.listing_finished(job.directory):
job.listing_done = True
found = IdSpool.committed_count(job.directory)
if found > job.discovered:
job.discovered = found
if job.status == "paused":
if not job.message:
job.message = "已暂停"
return
if job.status == "running":
job.message = _describe(job)
def _describe(job: DownloadJob) -> str:
if job.whole_city and not job.listing_done:
return f"已完成 {job.completed},已读取 {job.discovered},失败 {job.failed}"
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() 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()
async def _publish(job: DownloadJob, force: bool = False) -> None:
now = time.monotonic()
if not force and now - job.last_flush < 0.5:
return
job.last_flush = now
job.save()
await job.emit("progress")
async def _iterate(ids: list[str]) -> AsyncIterator[str]:
for grid_id in ids:
yield grid_id
async def _mark(job: DownloadJob, status: str, message: str, event: str) -> None:
job.stopping = False
job.status = status
job.message = message
job.save()
await job.emit(event)
def _find_auth(exc: BaseException) -> NqiAuthError | None:
if isinstance(exc, NqiAuthError):
return exc
if isinstance(exc, BaseExceptionGroup):
for sub in exc.exceptions:
found = _find_auth(sub)
if found is not None:
return found
return None
def _primary_error(group: BaseExceptionGroup) -> BaseException | None:
auth = _find_auth(group)
if auth is not None:
return auth
found: list[BaseException] = []
def walk(item: BaseException) -> None:
if isinstance(item, BaseExceptionGroup):
for sub in item.exceptions:
walk(sub)
return
if isinstance(item, asyncio.CancelledError):
return
found.append(item)
walk(group)
for item in found:
if isinstance(item, NqiError):
return item
if not found:
return None
return found[0]
def _finished_id(completed, grid_id) -> bool:
"""进度里的纯数字编号是 int。字符串编号对不上,已完成的会被重下。"""
text = str(grid_id).strip()
if text.isdigit() and int(text) in completed:
return True
return text in completed
def _restore_cleared_ids(job: DownloadJob) -> None:
"""终态 save() 会清空内存编号。区域表继续下载前先从 ids.txt 读回。"""
if job.whole_city or job.grid_ids:
return
restored = [str(item) for item in job.load_ids()]
if not restored:
return
job.grid_ids = restored
job.id_count = len(restored)
job._ids_loaded = True
def _failed_key(item) -> tuple:
if isinstance(item, dict):
return ("dict", tuple(sorted((str(key), repr(value)) for key, value in item.items())))
if isinstance(item, (list, tuple)):
return ("seq", tuple(item))
return ("other", str(item))
def _combine_failed(*groups) -> list:
merged: list = []
seen: set[tuple] = set()
for group in groups:
if not isinstance(group, (list, tuple)):
continue
for item in group:
key = _failed_key(item)
if key in seen:
continue
seen.add(key)
if isinstance(item, dict):
merged.append(dict(item))
elif isinstance(item, (list, tuple)):
merged.append(list(item))
else:
merged.append(item)
return merged
def _spool_failed_tiles(directory: Path) -> list:
data = IdSpool._peek(directory)
if not isinstance(data, dict):
return []
tiles = data.get("failedTiles") or []
return list(tiles) if isinstance(tiles, list) else []
def _retry_bboxes(*groups) -> list[tuple]:
found: list[tuple] = []
seen: set[tuple] = set()
for group in groups:
for item in group or []:
if isinstance(item, (dict, str, bytes)):
continue
try:
key = tuple(item)
except TypeError:
continue
if len(key) != 4 or key in seen:
continue
seen.add(key)
found.append(key)
return found
def _fatal_io(exc: BaseException) -> NqiError | None:
if isinstance(exc, NqiError) and str(exc) in {"文件被占用,请先关闭 Excel 等程序", "磁盘空间不足"}:
return exc
message = explain_os_error(exc)
if message:
return NqiError(message)
return None
async def run_download(job: DownloadJob) -> None:
from app.shared.state import state
columns = columns_for(job.network, job.groups, job.grid_size)
journal = CsvJournal(job.csv_path, job.directory / "progress.jsonl", [column.label for column in columns])
spool = IdSpool(job.directory) if job.whole_city else None
try:
if job.status != "paused":
job.status = "running"
job.message = "准备中"
job.save()
_restore_cleared_ids(job)
await job.emit("progress")
journal.open()
if spool is not None:
await asyncio.to_thread(spool.open)
_seed_seen(spool, journal.completed)
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 "登录已失效,请重新登录"
job.run_event.clear()
state.on_session_expired(reason)
job.status = "paused"
job.paused_by = job.paused_by or "expired"
job.message = reason
job.save()
if spool is not None:
await asyncio.to_thread(spool.flush)
if not await _wait_job(job):
break
await _mark(job, "cancelled", "已停止", "cancelled")
except asyncio.CancelledError:
await _mark(job, "cancelled", "已停止", "cancelled")
raise
except NqiError as exc:
await _mark(job, "error", str(exc) or "下载失败", "error")
except Exception as exc:
message = explain_os_error(exc)
if message:
await _mark(job, "error", message, "error")
else:
logger.exception("下载任务失败 job=%s", job.id)
await _mark(job, "error", "下载失败,详情见日志", "error")
finally:
if spool is not None:
await asyncio.to_thread(spool.close)
journal.close()
def _seed_seen(spool: IdSpool, done: set[str]) -> None:
for grid_id in done:
if str(grid_id).isdigit():
spool.seen.add(int(grid_id))
async def _run_pass(job: DownloadJob, journal: CsvJournal, columns, spool: IdSpool | None) -> None:
from app.shared.state import state
client = state.get_client()
job.paused_by = ""
job.status = "running"
layer = await client.layer_code(
city_code=job.city_code,
month=job.month,
network=job.network,
grid_size=job.grid_size,
)
if job.cancel_event.is_set():
await _mark(job, "cancelled", "已停止", "cancelled")
return
service_code = str(layer["serviceCode"])
job.id_field = str(layer.get("originRelatedField") or job.id_field)
job.completed = len(journal.completed)
job.written_rows = journal.written_rows
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)
return
_restore_cleared_ids(job)
loaded = [str(item) for item in (job.grid_ids or job.load_ids())]
job.grid_ids = list(dict.fromkeys(loaded))
if job.grid_ids:
job.id_count = len(job.grid_ids)
job._ids_loaded = True
pending: list[str] = []
seen: set[str] = set()
for grid_id in job.grid_ids:
if grid_id in seen or _finished_id(journal.completed, grid_id):
continue
seen.add(grid_id)
pending.append(grid_id)
job.discovered = len(job.grid_ids)
job.listing_done = True
if not pending:
if job.cancel_event.is_set():
await _mark(job, "cancelled", "已停止", "cancelled")
return
await _mark(job, "done", "已完成", "done")
return
job.status = "running"
job.message = _describe(job)
await job.emit("progress")
await _pump(job, None, journal, columns, service_code, _iterate(pending))
async def _city_ids(job: DownloadJob, journal: CsvJournal, spool: IdSpool) -> AsyncIterator[str]:
while True:
if job.cancel_event.is_set():
return
if not await _wait_job(job):
return
batch = await asyncio.to_thread(spool.pull)
if not batch:
if spool.caught_up():
return
await asyncio.sleep(0.05)
continue
for grid_id in batch:
if _finished_id(journal.completed, grid_id):
continue
if job.cancel_event.is_set() or not await _wait_job(job):
return
yield grid_id
async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code: str, spool: IdSpool) -> None:
from app.shared.state import state
job.discovered = len(spool.seen)
job.failed_tiles = _combine_failed(job.failed_tiles, spool.failed_tiles)
retry = _retry_bboxes(job.failed_tiles)
if spool.complete and not retry:
job.discovered = len(spool.seen)
job.listing_done = True
job.failed_tiles = []
_note_progress(job)
await _publish(job, force=True)
await _pump(job, None, journal, columns, service_code, _city_ids(job, journal, spool))
return
# 补读失败块或继续全量扫描时,先取消“已读完”,下载侧才会等新编号。
tiles = retry if spool.complete else None
spool.complete = False
job.listing_done = False
job.failed_tiles = []
spool.failed_tiles = []
async def listing() -> None:
async def report(count: int) -> None:
job.discovered = count
if spool.due():
await asyncio.to_thread(spool.flush)
_note_progress(job)
await _publish(job)
client = state.get_client()
try:
iterator = client.iter_grid_ids(
service_code,
job.id_field,
job.cancel_event,
report,
None,
job.run_event,
halt_event=job.retune,
grid_size=job.grid_size,
failed_tiles=job.failed_tiles,
seen=spool.seen,
tiles=tiles,
)
async with contextlib.aclosing(iterator) as ids:
async for grid_id in ids:
if job.cancel_event.is_set() or job.retune.is_set():
break
spool.append(grid_id)
if spool.due():
await asyncio.to_thread(spool.flush)
except NqiAuthError:
spool.failed_tiles = [list(item) for item in job.failed_tiles]
await asyncio.to_thread(spool.flush)
raise
except NqiError as exc:
spool.failed_tiles = [list(item) for item in job.failed_tiles]
await asyncio.to_thread(spool.flush)
if job.cancel_event.is_set() or str(exc) == "已停止":
return
raise
spool.failed_tiles = [list(item) for item in job.failed_tiles]
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)
job.discovered = len(spool.seen)
job.listing_done = True
_note_progress(job)
await _publish(job, force=True)
job.status = "running"
job.message = "正在读取并下载"
await _pump(job, None, journal, columns, service_code, _city_ids(job, journal, spool), listing())
async def _pump(job: DownloadJob, client, journal, columns, service_code: str, source: AsyncIterator[str], listing=None) -> None:
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()
remaining = worker_count
def resolve():
if client is not None:
return client
from app.shared.state import state
return state.get_client()
async def produce() -> None:
try:
async with contextlib.aclosing(source):
async for grid_id in source:
if job.cancel_event.is_set() or job.retune.is_set():
return
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
except asyncio.TimeoutError:
continue
except NqiAuthError:
raise
except NqiError as exc:
if job.cancel_event.is_set() or str(exc) == "已停止":
return
raise
finally:
produce_done.set()
async def worker() -> None:
try:
while not job.cancel_event.is_set() and not job.retune.is_set():
if not await _wait_job(job):
return
try:
grid_id = await asyncio.wait_for(ids.get(), timeout=0.3)
except asyncio.TimeoutError:
if produce_done.is_set() and ids.empty():
return
continue
if not grid_id or not await _wait_job(job):
return
error = "下载失败"
rows = None
for attempt in range(2):
if job.cancel_event.is_set() or not await _wait_job(job):
return
try:
current = resolve()
properties = await current.grid_feature(service_code, grid_id, job.id_field)
cells = await current.cell_rows(service_code, grid_id, job.network)
rows = build_rows(grid_id, properties, cells, columns)
break
except NqiAuthError:
raise
except NqiError as exc:
fatal = _fatal_io(exc)
if fatal is not None:
raise fatal
error = str(exc) or "下载失败"
if attempt == 0:
await asyncio.sleep(0.4)
except Exception as exc:
fatal = _fatal_io(exc)
if fatal is not None:
raise fatal
logger.exception("栅格下载失败 id=%s", grid_id)
error = "下载失败,详情见日志"
if attempt == 0:
await asyncio.sleep(0.4)
if rows is None:
await results.put(("err", grid_id, error))
else:
await results.put(("ok", grid_id, rows))
finally:
nonlocal remaining
remaining -= 1
if remaining == 0:
workers_done.set()
async def flush(batch: list) -> None:
fresh = [(grid_id, item_rows) for grid_id, item_rows in batch if not _finished_id(journal.completed, grid_id)]
if not fresh:
return
try:
await asyncio.to_thread(journal.commit_many, fresh)
finally:
written = 0
for grid_id, _item_rows in fresh:
if _finished_id(journal.completed, grid_id):
written += 1
if written:
job.completed += written
job.written_rows = journal.written_rows
async def writer() -> None:
batch: list = []
deadline: float | None = None
while True:
if workers_done.is_set() and results.empty():
if batch:
await flush(batch)
batch = []
_note_progress(job)
await _publish(job, force=True)
return
timeout = 0.3
if deadline is not None:
timeout = max(0.0, deadline - time.monotonic())
try:
item = await asyncio.wait_for(results.get(), timeout)
except asyncio.TimeoutError:
if batch and (deadline is None or time.monotonic() >= deadline):
await flush(batch)
batch = []
deadline = None
_note_progress(job)
await _publish(job)
continue
kind, grid_id, payload = item
if kind == "ok":
if not batch:
deadline = time.monotonic() + 0.5
batch.append((grid_id, payload))
if len(batch) >= 200:
await flush(batch)
batch = []
deadline = None
_note_progress(job)
await _publish(job)
continue
job.failed += 1
job.failures.append({"id": str(grid_id), "message": str(payload)})
if len(job.failures) > 50:
del job.failures[:-50]
_note_progress(job)
await _publish(job)
try:
async with asyncio.TaskGroup() as group:
group.create_task(produce())
if listing is not None:
group.create_task(listing)
for _index in range(worker_count):
group.create_task(worker())
group.create_task(writer())
except BaseExceptionGroup as group:
error = _primary_error(group)
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)
if job.cancel_event.is_set() and unfinished:
await _mark(job, "cancelled", "已停止", "cancelled")
return
if job.failed_tiles:
await _mark(job, "done_with_errors", f"有 {len(job.failed_tiles)} 块区域没读到,点继续重试", "done")
return
if job.failed:
await _mark(job, "done_with_errors", f"{job.failed} 个失败", "done")
return
await _mark(job, "done", "已完成", "done")