"""下载任务:协程并发查询,单个写者实时落盘。 文件规则:一个任务的 CSV、进度、编号暂存只在它自己的读写线程里打开和写入; job.json 只由后台记录线程写;接口和界面只读内存,不去打开正在写的文件。 """ from __future__ import annotations import asyncio import contextlib import json import logging import os import re import shutil import threading import time from collections.abc import AsyncIterator from concurrent.futures import Future from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from app.platform.client import NqiAuthError, NqiError, NqiNetworkError 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.files import RECORDS, JobIO, write_atomic 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"} # 整轮下载遇到网络或未知错误时,依次等这些秒数后自动重试。 PASS_RETRY_WAITS = (3, 10, 30) # 删除时等任务收尾的最长时间。 STOP_WAIT_SECONDS = 30 _HOLD_MESSAGES = {"文件被占用,请先关闭 Excel 等程序", "磁盘空间不足", "文件被拒绝访问"} @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 io: JobIO | None = field(default=None, repr=False, compare=False) closing: bool = False files_closed: asyncio.Future | None = field(default=None, repr=False, compare=False) deleting: bool = False building: bool = False _saved: Future | None = field(default=None, repr=False, compare=False) @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: ids = [str(item) for item in grid_ids] if not self.whole_city: _write_ids(self.directory, ids) self.keep_ids(ids) def keep_ids(self, ids: list[str]) -> None: self.grid_ids = ids self.id_count = len(ids) self._ids_loaded = True 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 # 在调用方线程里序列化好,交给记录线程写;之后再改任务对象也不影响这份内容。 data = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8") self._saved = RECORDS.submit(self.directory / "job.json", data) if self.status in _TERMINAL_STATUSES: self.grid_ids = [] self._ids_loaded = False if not _in_event_loop(): self._saved.result() async def flush_record(self) -> None: """等最近一次 save() 真正写到磁盘。""" saved = self._saved if saved is not None: await asyncio.wrap_future(saved) 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 _in_event_loop() -> bool: try: asyncio.get_running_loop() except RuntimeError: return False return True def _write_ids(directory: Path, grid_ids: list[str]) -> None: directory.mkdir(parents=True, exist_ok=True) data = "".join(f"{grid_id}\n" for grid_id in grid_ids).encode("utf-8") try: write_atomic(directory / "ids.txt", data) except OSError as exc: message = explain_os_error(exc) if message: raise NqiError(message) from exc raise def _remove_tree(folder: Path) -> None: """杀毒或索引可能刚好打开着里面的文件,删不掉时稍等重试。""" for wait in (0.1, 0.3, 0.8, 1.5): try: shutil.rmtree(folder) return except FileNotFoundError: return except OSError: time.sleep(wait) try: shutil.rmtree(folder) except FileNotFoundError: return except OSError as exc: raise NqiError(explain_os_error(exc) or "文件夹被占用,没有删干净,请稍后再删") from exc 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 _remove_tree(folder) 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 _SETTINGS_LOCK = threading.Lock() def _read_settings() -> dict: try: data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError, TypeError, ValueError): return {} return data if isinstance(data, dict) else {} def _write_settings(data: dict) -> None: SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True) payload = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8") write_atomic(SETTINGS_PATH, payload) def load_task_limit() -> int: with _SETTINGS_LOCK: try: return min(8, max(1, int(_read_settings().get("maxConcurrentJobs") or 2))) except (TypeError, ValueError): return 2 def store_task_limit(value: int) -> int: limit = min(8, max(1, int(value))) with _SETTINGS_LOCK: data = _read_settings() data["maxConcurrentJobs"] = limit try: _write_settings(data) except OSError as exc: raise NqiError(explain_os_error(exc) or "设置保存失败,请稍后重试") from exc return limit def app_settings() -> dict: """未写过的项用默认值:显示托盘,关闭窗口时留在托盘。""" with _SETTINGS_LOCK: data = _read_settings() return { "showTray": data.get("showTray") is not False, "closeToTray": data.get("closeToTray") is not False, } def store_app_settings(show_tray: bool, close_to_tray: bool) -> dict: with _SETTINGS_LOCK: data = _read_settings() data["showTray"] = bool(show_tray) data["closeToTray"] = bool(close_to_tray) try: _write_settings(data) except OSError as exc: raise NqiError(explain_os_error(exc) or "设置保存失败,请稍后重试") from exc return app_settings() class JobManager: def __init__(self) -> None: self.jobs: dict[str, DownloadJob] = {} self.max_concurrent = load_task_limit() self._damaged: set[str] = set() 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" and not job.deleting and not (job.closing and job.is_active()) ] 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.deleting: raise NqiError("任务正在删除") if job.status == "running" and job.is_active() and not job.closing: raise NqiError("这个任务正在下载") if job.closing and job.is_active(): self._queue(job) return "wait" 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 {"", "等待中", "已暂停"} or job.paused_by == "file": job.message = "下载中" job.paused_by = "" job.save() return "resume" job.cancel_event = asyncio.Event() job.closing = False job.message = "准备中" job.save() return "run" def pause(self, job: DownloadJob) -> None: if job.deleting: raise NqiError("任务正在删除") if job.stopping or job.cancel_event.is_set(): raise NqiError("任务正在停止") if job.status == "queued": # 排队中的任务移出队列。还挂着的协程保持停住,点继续时接着用。 job.run_event.clear() job.status = "paused" job.message = "已暂停" job.save() return if job.status != "running" or not job.is_active() or job.closing: raise NqiError("这个任务没有在下载") job.run_event.clear() job.status = "paused" 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) RECORDS.revive(directory) 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 if job.deleting: raise NqiError("任务正在删除") 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]: """只读内存。磁盘上的任务第一次见到时读一次 job.json,之后不再去读。""" self._discover() unfinished: list[dict] = [] finished: list[dict] = [] for job in list(self.jobs.values()): if job.deleting: continue # 只有标着在下载却没有协程的才算中断。暂停的任务可以没有协程(排队时暂停、登录失效时暂停)。 if job.status == "running" and not job.is_active(): job.status = "cancelled" job.message = "已中断" job.stopping = False job.save() item = job.snapshot() if item.get("status") in _FINISHED_STATUSES: finished.append(item) else: unfinished.append(item) for job_id in self._damaged: unfinished.append(_damaged_snapshot(job_id)) 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 _discover(self) -> None: if not DATA_DIR.exists(): return try: entries = list(os.scandir(DATA_DIR)) except OSError: return for entry in entries: name = entry.name if name in self.jobs or name in self._damaged or not _JOB_ID.fullmatch(name): continue try: if not entry.is_dir() or not os.path.exists(os.path.join(entry.path, "job.json")): continue except OSError: continue try: self.jobs[name] = self._load(name) except NqiError: self._damaged.add(name) async 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 job_id not in self._damaged and not data_dir.exists(): raise NqiError("任务不存在") if job is not None: if job.deleting: raise NqiError("任务正在删除") if job.building: raise NqiError("任务还在创建,请稍后再删") if job.status == "running" or job.stopping: raise NqiError("这个任务正在下载,不能删除") job.deleting = True try: if job is not None: await _stop_and_wait(job) # 先让记录线程放下这个目录,确认没有写到一半的 job.json,再删。 await asyncio.wrap_future(RECORDS.drop(data_dir)) csv_parent = job.csv_path.parent if job is not None else _csv_parent(data_dir) self.jobs.pop(job_id, None) self._damaged.discard(job_id) await asyncio.to_thread(_remove_tree, data_dir) if files and csv_parent is not None: await asyncio.to_thread(_remove_download_dir, csv_parent, data_dir, job_id) finally: if job is not None: job.deleting = False 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 "") paused_by = str(data.get("pausedBy") or "") # 迁移前主动收起来的任务要保持暂停,重启后按记录继续,不要当成意外中断。 held_for_move = paused_by == "move" interrupted = status in _INTERRUPTED_STATUSES and not held_for_move if interrupted: status = "cancelled" message = "已中断" elif held_for_move: status = "paused" 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=paused_by, stopping=bool(data.get("stopping") or False) and not interrupted, failed_tiles=_combine_failed(data.get("failedTiles"), _spool_failed_tiles(path.parent)), ) except (KeyError, TypeError, ValueError) as exc: raise NqiError("任务记录损坏") from exc _clear_temp_files(path.parent) if status == "done": release_finished_work(path.parent) if interrupted: job.save() return job async def shelve_for_move(self) -> list[str]: """停掉还开着文件的任务。正在下载和排队的记下来,迁移完成后继续。""" self._discover() jobs = [job for job in self.jobs.values() if not job.deleting] for job in jobs: if job.building or job.deleting: raise NqiError("有任务还在创建或删除,请稍后再迁移") resume: list[str] = [] for job in jobs: should_resume = job.status in {"running", "queued"} or job.paused_by == "move" if should_resume: resume.append(job.id) busy = job.is_active() or (job.files_closed is not None and not job.files_closed.done()) if busy: try: await _stop_and_wait(job) except NqiError as exc: if str(exc) == "任务还在收尾,请稍后再删": raise NqiError("任务还在收尾,请稍后再迁移") from exc raise if not should_resume: continue job.status = "paused" job.paused_by = "move" job.message = "已暂停" job.stopping = False job.cancel_event = asyncio.Event() job.save() await job.flush_record() await asyncio.wrap_future(RECORDS.barrier()) return resume def _clear_temp_files(directory: Path) -> None: """进程被强行结束时可能留下替换前的临时文件。只在任务没在运行时清。""" try: leftovers = list(directory.glob("*.tmp")) except OSError: return for leftover in leftovers: try: leftover.unlink() except OSError: pass _FINISHED_WORK = ("progress.jsonl", "ids.spool", "ids.spool.meta") def release_finished_work(directory: Path) -> None: """任务已经全部下完。进度和编号暂存只为继续下载服务,删掉以免一直占空间。""" for name in _FINISHED_WORK: path = directory / name try: path.unlink() except FileNotFoundError: continue except OSError as exc: logger.warning("完成后的进度文件暂时删不掉 %s: %s", path, exc) async def _stop_and_wait(job: DownloadJob) -> None: """强制结束任务协程,并等它关完文件。""" task = job.task if task is not None and not task.done(): job.cancel_event.set() job.run_event.set() task.cancel() done, _pending = await asyncio.wait({task}, timeout=STOP_WAIT_SECONDS) if not done: raise NqiError("任务还在收尾,请稍后再删") closed = job.files_closed if closed is not None and not closed.done(): done, _pending = await asyncio.wait({closed}, timeout=STOP_WAIT_SECONDS) if not done: raise NqiError("任务还在收尾,请稍后再删") 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 _note_progress(job: DownloadJob) -> None: if job.stopping or job.cancel_event.is_set(): job.message = "正在停止" return 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 _wait_resume(job: DownloadJob) -> bool: """暂停后等用户点继续。并发改了也照样继续,只有停止才返回 False。""" 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 _sleep_unless_stopped(job: DownloadJob, seconds: float) -> bool: deadline = time.monotonic() + seconds while True: if job.cancel_event.is_set(): return False left = deadline - time.monotonic() if left <= 0: return await _wait_resume(job) await asyncio.sleep(min(0.3, left)) async def _disk(job: DownloadJob, fn, /, *args): """任务的文件读写交给它自己的读写线程。单独调用 _pump 的测试没有这条线程,退回线程池。""" if job.io is not None: return await job.io.run(fn, *args) return await asyncio.to_thread(fn, *args) 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 async 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 await _disk(job, job.load_ids)] if restored: job.keep_ids(restored) def _pending_ids(loaded: list[str], completed) -> tuple[list[str], list[str]]: unique = list(dict.fromkeys(str(item) for item in loaded)) pending = [grid_id for grid_id in unique if not _finished_id(completed, grid_id)] return pending, unique 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.read_meta(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 _HOLD_MESSAGES: return exc message = explain_os_error(exc) if message: return NqiError(message) return None def _hold_reason(exc: BaseException) -> str | None: """写不进文件(被占用、磁盘满、被拒绝访问)时先停下等用户处理,而不是判成出错。""" if isinstance(exc, NqiError): text = str(exc) elif isinstance(exc, OSError): text = explain_os_error(exc) or "" else: return None return text if text in _HOLD_MESSAGES else None def _retryable(exc: BaseException) -> bool: if isinstance(exc, NqiNetworkError): return True if isinstance(exc, NqiError): return False return isinstance(exc, Exception) def _retry_text(exc: BaseException, wait: int) -> str: if isinstance(exc, NqiNetworkError): reason = str(exc).replace(",请稍后重试", "") else: reason = "下载出错" return f"{reason},{wait} 秒后自动重试" async def _flush_spool(job: DownloadJob, spool: IdSpool | None) -> None: if spool is None: return try: await _disk(job, spool.flush) except Exception as exc: logger.warning("编号暂存写不进去 job=%s: %s", job.id, exc) async def run_download(job: DownloadJob) -> None: from app.shared.state import state previous = job.files_closed if previous is not None and not previous.done(): # 上一轮还在关文件。等它关完,避免两条线程同时写同一个文件。 await asyncio.wait({previous}) 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 io = JobIO(job.id) job.io = io job.closing = False retries = 0 progress_mark = -1 try: if job.status != "paused": job.status = "running" job.message = "准备中" job.save() await job.emit("progress") await _restore_cleared_ids(job) await io.run(journal.open) if spool is not None: await io.run(spool.open) 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() await _flush_spool(job, spool) if not await _wait_resume(job): break except Exception as exc: hold = _hold_reason(exc) if hold is not None: job.run_event.clear() job.status = "paused" job.paused_by = "file" job.message = f"{hold},处理好后点继续" job.save() await _flush_spool(job, spool) if not await _wait_resume(job): break continue if job.completed > progress_mark: # 上次出错后又下了新的栅格,重试次数重新算。 retries = 0 progress_mark = job.completed if not _retryable(exc) or retries >= len(PASS_RETRY_WAITS): raise wait = PASS_RETRY_WAITS[retries] retries += 1 logger.warning("下载出错,%s 秒后第 %s 次重试 job=%s: %r", wait, retries, job.id, exc) job.message = _retry_text(exc, wait) job.save() await _flush_spool(job, spool) if not await _sleep_unless_stopped(job, wait): 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: job.closing = True closing = asyncio.ensure_future(_close_files(job, io, journal, spool)) job.files_closed = closing # 即使任务被再次取消,关文件也会做完;删除会等 files_closed。 await asyncio.shield(closing) async def _close_files(job: DownloadJob, io: JobIO, journal: CsvJournal, spool: IdSpool | None) -> None: try: if spool is not None: try: await io.run(spool.close) except Exception as exc: logger.warning("编号暂存没有正常关闭 job=%s: %s", job.id, exc) try: await io.run(journal.close) except Exception as exc: logger.warning("下载文件没有正常关闭 job=%s: %s", job.id, exc) finally: await io.close() if job.io is io: job.io = None if job.status == "done": await asyncio.to_thread(release_finished_work, job.directory) await job.flush_record() def _seed_seen(spool: IdSpool, done) -> 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 # 每一轮都会把没下完的(包括上一轮失败的)重新下一遍,失败数从零算。 job.failed = 0 job.failures = [] if spool is not None: await _disk(job, _seed_seen, spool, journal.completed) await _run_city(job, journal, columns, service_code, spool) return await _restore_cleared_ids(job) loaded = job.grid_ids or await _disk(job, job.load_ids) pending, unique = await _disk(job, _pending_ids, list(loaded), journal.completed) if unique: job.keep_ids(unique) 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 _disk(job, 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) # 每一轮都从暂存开头读:上一轮读出但没下完的编号不会因为读位置已经往后挪而漏掉。 await _disk(job, spool.rewind) 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 job.listing_done = False job.failed_tiles = [] spool.set_scan_state(complete=False, failed_tiles=[]) async def listing() -> None: async def report(count: int) -> None: job.discovered = count if spool.due(): await _disk(job, 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: # 读取侧交出编号时已把它记进 seen,先放进暂存缓冲再判断要不要停,否则会漏。 spool.append(grid_id) if job.cancel_event.is_set() or job.retune.is_set(): break if spool.due(): await _disk(job, spool.flush) except NqiAuthError: spool.set_scan_state(failed_tiles=job.failed_tiles) await _flush_spool(job, spool) raise except NqiError as exc: spool.set_scan_state(failed_tiles=job.failed_tiles) await _flush_spool(job, spool) if job.cancel_event.is_set() or str(exc) == "已停止": return raise spool.set_scan_state(failed_tiles=job.failed_tiles) if job.cancel_event.is_set() or job.retune.is_set(): await _flush_spool(job, spool) return await _disk(job, 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 = explain_os_error(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)) 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 _disk(job, 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")