"""下载任务:协程并发查询,单个写者实时落盘。""" from __future__ import annotations import asyncio import json import uuid from dataclasses import dataclass, field from datetime import datetime 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.rows import build_rows from app.shared.paths import DOWNLOAD_DIR DATA_DIR = DOWNLOAD_DIR @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 status: str = "queued" message: str = "" completed: int = 0 failed: int = 0 written_rows: int = 0 failures: list[dict[str, str]] = field(default_factory=list) subscribers: list[asyncio.Queue] = field(default_factory=list) task: asyncio.Task | None = None cancel_event: asyncio.Event = field(default_factory=asyncio.Event) @property def total(self) -> int: return len(self.grid_ids) def is_active(self) -> bool: return self.task is not None and not self.task.done() 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, "concurrency": self.concurrency, "total": self.total, "completed": self.completed, "failed": self.failed, "writtenRows": self.written_rows, "csvPath": str(self.csv_path), "failures": self.failures[-20:], "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, "groups": self.groups, "concurrency": self.concurrency, "gridIds": self.grid_ids, "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, "failures": self.failures[-50:], } (self.directory / "job.json").write_text( json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8", ) async def emit(self, kind: str, **extra) -> None: event = {"type": kind, **self.snapshot(), **extra} for subscriber in list(self.subscribers): await subscriber.put(event) class JobManager: def __init__(self) -> None: self.jobs: dict[str, DownloadJob] = {} 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, ) -> DownloadJob: job_id = uuid.uuid4().hex directory = DATA_DIR / job_id directory.mkdir(parents=True, exist_ok=True) target = csv_path or directory / f"栅格_{'5G' if network == 'NR' else '4G'}_{city_name}_{month}.csv" target.parent.mkdir(parents=True, exist_ok=True) 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=grid_ids, csv_path=target, created_at=datetime.now().isoformat(timespec="seconds"), ) job.save() self.jobs[job_id] = job 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 return job def list_jobs(self) -> list[dict]: if not DATA_DIR.exists(): return [] items = [] for directory in sorted(DATA_DIR.iterdir(), reverse=True): path = directory / "job.json" if not path.exists(): continue try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): continue job_id = data.get("id") if job_id in self.jobs: job = self.jobs[job_id] snap = job.snapshot() if snap["status"] == "running" and not job.is_active(): snap["status"] = "cancelled" snap["message"] = "已中断" items.append(snap) continue status = data.get("status") or "queued" message = data.get("message") or "" if status == "running": status = "cancelled" message = "已中断" finished, written = _progress_stats(directory) 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"), "concurrency": data.get("concurrency") or 4, "total": len(data.get("gridIds") or []), "completed": finished or data.get("completed") or 0, "failed": data.get("failed") or 0, "writtenRows": written or data.get("writtenRows") or 0, "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] def _load(self, job_id: str) -> DownloadJob: if not re_fullmatch_hex(job_id): raise NqiError("任务不存在") path = DATA_DIR / job_id / "job.json" if not path.exists(): raise NqiError("任务不存在") 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"], groups=list(data.get("groups") or []), concurrency=int(data.get("concurrency") or 4), grid_ids=[str(item) for item in data.get("gridIds") or []], 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), failures=list(data.get("failures") or []), ) def _progress_stats(directory: Path) -> tuple[int, int]: path = directory / "progress.jsonl" if not path.exists(): return 0, 0 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) return finished, written def re_fullmatch_hex(value: str) -> bool: return len(value) == 32 and all(char in "0123456789abcdef" for char in value) async def run_download(job: DownloadJob, client: NqiClient) -> None: columns = columns_for(job.network, job.groups) journal = CsvJournal(job.csv_path, job.directory / "progress.jsonl", [column.label for column in columns]) job.status = "running" job.message = "准备中" job.save() await job.emit("progress") try: layer = await client.layer_code(city_code=job.city_code, month=job.month, network=job.network) service_code = layer["serviceCode"] journal.open() job.completed = len(journal.completed) job.written_rows = journal.written_rows job.failures = [] job.failed = 0 pending = [grid_id for grid_id in job.grid_ids if grid_id not in journal.completed] job.message = "下载中" await job.emit("progress") if not pending: job.status = "done" job.message = "已完成" job.save() await job.emit("done") return await _pump(job, client, journal, columns, service_code, pending) except asyncio.CancelledError: job.status = "cancelled" job.message = "已停止" job.save() await job.emit("cancelled") raise except Exception as exc: job.status = "error" job.message = str(exc) or "下载失败" job.save() await job.emit("error") finally: journal.close() async def _pump(job, client, journal, columns, service_code: str, pending: list[str]) -> None: ids: asyncio.Queue[str] = asyncio.Queue() results: asyncio.Queue = asyncio.Queue() for grid_id in pending: ids.put_nowait(grid_id) async def worker() -> None: while not job.cancel_event.is_set(): try: grid_id = ids.get_nowait() except asyncio.QueueEmpty: return error = "" rows = None for attempt in range(2): if job.cancel_event.is_set(): return try: properties = await client.grid_feature(service_code, grid_id) cells = await client.cell_rows(service_code, grid_id, job.network) rows = build_rows(grid_id, properties, cells, columns) error = "" break except Exception as exc: error = str(exc) or "下载失败" 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)) async def writer() -> None: while True: item = await results.get() if item is None: return kind, grid_id, payload = item if kind == "ok": written = journal.write_rows(grid_id, payload) job.completed += 1 job.written_rows = journal.written_rows if written == 0: job.written_rows = journal.written_rows else: job.failed += 1 job.failures.append({"id": grid_id, "message": payload}) job.message = f"已完成 {job.completed}/{job.total},失败 {job.failed}" job.save() await job.emit("progress") async def finish_workers() -> None: await asyncio.gather(*(worker() for _ in range(job.concurrency))) await results.put(None) closer = asyncio.create_task(finish_workers()) try: await writer() await closer finally: if not closer.done(): closer.cancel() unfinished = job.completed + job.failed < job.total if job.cancel_event.is_set() and unfinished: job.status = "cancelled" job.message = "已停止" job.save() await job.emit("cancelled") return job.status = "done" if job.failed == 0 else "done_with_errors" job.message = "已完成" if job.failed == 0 else f"{job.failed} 个失败" job.save() await job.emit("done")