"""下载任务:协程并发查询,单个写者实时落盘。""" from __future__ import annotations import asyncio import json import re 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 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 DATA_ROOT, DOWNLOAD_DIR DATA_DIR = DOWNLOAD_DIR SETTINGS_PATH = DATA_ROOT / "settings.json" _JOB_ID = re.compile(r"^(?:\d{14}(?:_\d+)?|[0-9a-f]{32})$") @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) 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()) @property def total(self) -> int: if self.whole_city: return self.discovered 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, "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:], "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, "gridIds": [] if self.whole_city else self.grid_ids, "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:], } (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) 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 _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))) 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", ) return limit class JobManager: def __init__(self) -> None: self.jobs: dict[str, DownloadJob] = {} self.max_concurrent = load_task_limit() def running_count(self) -> int: total = 0 for job in self.jobs.values(): if job.status != "running": continue if job.task is not None and job.task.done(): continue total += 1 return total def hydrate(self) -> None: """进程重启后,把仍在等待的任务装回内存,空位出现时可以继续排。""" if not DATA_DIR.exists(): return for directory in DATA_DIR.iterdir(): if not directory.is_dir() or _JOB_ID.fullmatch(directory.name) is None: continue if directory.name in self.jobs: continue path = directory / "job.json" if not path.exists(): continue try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): continue if data.get("status") != "queued" or data.get("id") != directory.name: continue try: self.jobs[directory.name] = self._load(directory.name) except NqiError: continue 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: job.status = "queued" job.message = "等待中" job.save() return "wait" job.run_event.set() job.status = "running" if job.is_active(): 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.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.status = "cancelled" job.message = "已取消" job.save() return job.cancel_event.set() job.run_event.set() job.status = "running" job.message = "正在停止" 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 = directory / filename else: target = csv_path.parent / job_id / csv_path.name 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"), grid_size=grid_size, whole_city=whole_city, ) 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] 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] 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("任务不存在") 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 []), ) 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 _note_progress(job: DownloadJob) -> None: if job.cancel_event.is_set(): job.message = "正在停止" return if job.status == "paused": 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}" async def _wait_job(job: DownloadJob) -> bool: while not job.run_event.is_set(): if job.cancel_event.is_set(): return False try: await asyncio.wait_for(job.run_event.wait(), timeout=0.3) except asyncio.TimeoutError: continue 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 run_download(job: DownloadJob, client: NqiClient) -> None: 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]) if job.status != "paused": 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, grid_size=job.grid_size, ) if job.cancel_event.is_set(): job.status = "cancelled" job.message = "已停止" job.save() await job.emit("cancelled") return service_code = layer["serviceCode"] job.id_field = str(layer.get("originRelatedField") or job.id_field) journal.open() job.completed = len(journal.completed) job.written_rows = journal.written_rows job.failures = [] job.failed = 0 if job.whole_city: job.listing_done = False job.discovered = len(journal.completed) if job.status != "paused": job.message = "正在读取并下载" await job.emit("progress") async def report(count: int) -> None: job.discovered = count _note_progress(job) await _publish(job) async def city_ids() -> AsyncIterator[str]: async for grid_id in client.iter_grid_ids( service_code, job.id_field, job.cancel_event, report, journal.completed, job.run_event, ): yield grid_id job.listing_done = True _note_progress(job) await _publish(job, force=True) await _pump(job, client, journal, columns, service_code, city_ids()) return pending: list[str] = [] seen: set[str] = set() for grid_id in job.grid_ids: if grid_id in seen or grid_id in journal.completed: continue seen.add(grid_id) pending.append(grid_id) job.grid_ids = list(dict.fromkeys(job.grid_ids)) job.discovered = len(job.grid_ids) job.listing_done = True if not pending: if job.cancel_event.is_set(): job.status = "cancelled" job.message = "已停止" job.save() await job.emit("cancelled") return job.status = "done" job.message = "已完成" job.save() await job.emit("done") return if job.status != "paused": job.message = _describe(job) await job.emit("progress") await _pump(job, client, journal, columns, service_code, _iterate(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: DownloadJob, client, journal, columns, service_code: str, source: AsyncIterator[str]) -> None: ids: asyncio.Queue[str | None] = asyncio.Queue(maxsize=max(64, job.concurrency * 8)) results: asyncio.Queue = asyncio.Queue(maxsize=max(8, job.concurrency * 2)) produce_done = asyncio.Event() workers = max(1, job.concurrency) async def produce() -> None: try: async for grid_id in source: if job.cancel_event.is_set(): return while not job.cancel_event.is_set(): try: await asyncio.wait_for(ids.put(grid_id), timeout=0.3) break except asyncio.TimeoutError: continue except NqiError as exc: if job.cancel_event.is_set() or str(exc) == "已停止": return raise finally: produce_done.set() async def worker() -> None: while not job.cancel_event.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 grid_id is None or not await _wait_job(job): 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, job.id_field) 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": journal.write_rows(grid_id, payload) job.completed += 1 job.written_rows = journal.written_rows else: job.failed += 1 job.failures.append({"id": grid_id, "message": payload}) if len(job.failures) > 50: del job.failures[:-50] _note_progress(job) await _publish(job) async def finish_workers() -> None: try: await asyncio.gather(produce(), *(worker() for _ in range(workers))) finally: await results.put(None) closer = asyncio.create_task(finish_workers()) try: await writer() await closer finally: if not closer.done(): closer.cancel() if job.whole_city and not job.cancel_event.is_set() and job.discovered == 0 and job.completed == 0: 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: 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")