From 2aa8990b63b90a77c0159732399c8294cc6cbd7f Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 25 Oct 2026 08:57:34 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=BC=96=E5=8F=B7=E8=BF=9B=E5=BA=A6?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=8D=95=E7=BA=BF=E7=A8=8B=E5=86=99=E5=85=A5?= =?UTF-8?q?=E5=B9=B6=E5=9C=A8=E4=BB=BB=E5=8A=A1=E4=B8=8A=E6=98=BE=E7=A4=BA?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/features/download/jobs.py | 13 +- backend/app/features/download/spool.py | 191 +++++++++++++----- backend/tests/test_engine.py | 43 +++- .../features/download/DownloadManagerView.vue | 14 +- desktop/src/styles.css | 13 ++ 5 files changed, 211 insertions(+), 63 deletions(-) diff --git a/backend/app/features/download/jobs.py b/backend/app/features/download/jobs.py index 43f5200..7e77bde 100644 --- a/backend/app/features/download/jobs.py +++ b/backend/app/features/download/jobs.py @@ -971,7 +971,7 @@ async def run_download(job: DownloadJob) -> None: await _mark(job, "error", message, "error") else: logger.exception("下载任务失败 job=%s", job.id) - await _mark(job, "error", "下载失败,详情见日志", "error") + await _mark(job, "error", "下载中断,已下载的内容还在,点继续即可", "error") finally: if spool is not None: await asyncio.to_thread(spool.close) @@ -1074,10 +1074,9 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code # 补读失败块或继续全量扫描时,先取消“已读完”,下载侧才会等新编号。 tiles = retry if spool.complete else None - spool.complete = False job.listing_done = False job.failed_tiles = [] - spool.failed_tiles = [] + spool.set_scan_state(complete=False, failed_tiles=[]) async def listing() -> None: async def report(count: int) -> None: @@ -1110,16 +1109,16 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code if spool.due(): await asyncio.to_thread(spool.flush) except NqiAuthError: - spool.failed_tiles = [list(item) for item in job.failed_tiles] + spool.set_scan_state(failed_tiles=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] + spool.set_scan_state(failed_tiles=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] + spool.set_scan_state(failed_tiles=job.failed_tiles) if job.cancel_event.is_set() or job.retune.is_set(): await asyncio.to_thread(spool.flush) return @@ -1210,7 +1209,7 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s if fatal is not None: raise fatal logger.exception("栅格下载失败 id=%s", grid_id) - error = "下载失败,详情见日志" + error = explain_os_error(exc) or "这个栅格暂时下载失败" if attempt == 0: await asyncio.sleep(0.4) if rows is None: diff --git a/backend/app/features/download/spool.py b/backend/app/features/download/spool.py index 8c183f0..90b08d7 100644 --- a/backend/app/features/download/spool.py +++ b/backend/app/features/download/spool.py @@ -1,16 +1,20 @@ -"""全市编号暂存。去重后按行追加,批量 fsync,并记下已提交行数。""" +"""全市编号暂存。只有写入线程碰文件,其他线程只改内存。""" from __future__ import annotations import json import logging import os +import queue import threading import time from pathlib import Path logger = logging.getLogger("nqi.download") +_LIVE_LOCK = threading.Lock() +_LIVE: dict[str, "IdSpool"] = {} + def _file_busy(exc: OSError) -> bool: """Windows 上替换小文件时,杀毒或索引可能短暂拒绝访问。""" @@ -19,6 +23,10 @@ def _file_busy(exc: OSError) -> bool: return winerror in {5, 32, 33} or errno in {13, 32, 33} +def _directory_key(directory: Path) -> str: + return str(Path(directory).resolve()) + + class IdSpool: """ids.spool 每行一个编号。meta 记录已 fsync 的行数、是否读完和失败块。""" @@ -41,6 +49,8 @@ class IdSpool: self._committed_size = 0 self._lock = threading.Lock() self._meta_warned = 0.0 + self._queue: queue.Queue = queue.Queue() + self._thread: threading.Thread | None = None def open(self) -> None: self.directory.mkdir(parents=True, exist_ok=True) @@ -79,10 +89,14 @@ class IdSpool: self._pending = [] self._pending_at = 0.0 self._read_offset = 0 - self._file = open(self.path, "a+b") + self._file = open(self.path, "ab") self._read = open(self.path, "rb") if meta is None or int(meta.get("committed") or 0) != self.committed or bool(meta.get("complete")) != self.complete: self._write_meta() + with _LIVE_LOCK: + _LIVE[_directory_key(self.directory)] = self + self._thread = threading.Thread(target=self._serve, name="nqi-spool", daemon=True) + self._thread.start() def add(self, grid_id: str) -> bool: """去重后放入待写缓冲。编号按整数比较,010 与 10 视为同一个。""" @@ -109,27 +123,18 @@ class IdSpool: return True return time.monotonic() - self._pending_at >= self.flush_seconds - def flush(self) -> None: + def set_scan_state(self, *, complete: bool | None = None, failed_tiles: list | None = None) -> None: with self._lock: - pending = self._pending - self._pending = [] - self._pending_at = 0.0 - if pending and self._file is not None: - blob = "".join(f"{item}\n" for item in pending).encode("utf-8") - self._file.write(blob) - self._file.flush() - os.fsync(self._file.fileno()) - with self._lock: - self.committed += len(pending) - self._committed_size += len(blob) - self._write_meta() + if complete is not None: + self.complete = complete + if failed_tiles is not None: + self.failed_tiles = [list(item) for item in failed_tiles] + + def flush(self) -> None: + self._submit("flush") def mark_complete(self) -> None: - # 先把缓冲写稳,再标记读完,避免下载侧提前认为没有新编号。 - self.flush() - with self._lock: - self.complete = True - self._write_meta() + self._submit("complete") def caught_up(self) -> bool: """编号已经读完,并且下载侧已经取走全部已提交行。""" @@ -138,26 +143,18 @@ class IdSpool: def pull(self) -> list[str]: """按顺序读出上次之后新提交的编号。""" - with self._lock: - end = self._committed_size - offset = self._read_offset - if offset >= end or self._read is None: - return [] - blob = self._read_at(offset, end - offset) - with self._lock: - if self._read_offset == offset: - self._read_offset = offset + len(blob) - return [line.strip() for line in blob.decode("utf-8").split("\n") if line.strip()] + box: list[list[str]] = [] + self._submit("pull", box) + return box[0] if box else [] def close(self) -> None: - if self._file is not None or self._pending: - self.flush() - if self._file is not None: - self._file.close() - self._file = None - if self._read is not None: - self._read.close() - self._read = None + thread = self._thread + if thread is None: + self._shutdown_files() + return + self._queue.put(None) + thread.join() + self._thread = None @classmethod def listing_finished(cls, directory: Path) -> bool: @@ -176,11 +173,94 @@ class IdSpool: except (TypeError, ValueError): return 0 + def _submit(self, kind: str, box=None) -> None: + thread = self._thread + if thread is None or threading.current_thread() is thread: + self._dispatch(kind, box) + return + done = threading.Event() + slot: dict = {"error": None} + self._queue.put((kind, box, slot, done)) + done.wait() + error = slot["error"] + if error is not None: + raise error + + def _serve(self) -> None: + while True: + item = self._queue.get() + if item is None: + self._shutdown_files() + return + kind, box, slot, done = item + try: + self._dispatch(kind, box) + except Exception as exc: + slot["error"] = exc + finally: + done.set() + + def _dispatch(self, kind: str, box) -> None: + if kind == "flush": + self._flush_files() + return + if kind == "pull": + box.append(self._pull_files()) + return + if kind == "complete": + self._flush_files() + with self._lock: + self.complete = True + self._write_meta() + + def _shutdown_files(self) -> None: + try: + if self._file is not None or self._pending: + self._flush_files() + finally: + if self._file is not None: + self._file.close() + self._file = None + if self._read is not None: + self._read.close() + self._read = None + with _LIVE_LOCK: + key = _directory_key(self.directory) + if _LIVE.get(key) is self: + _LIVE.pop(key, None) + def _remember(self, grid_id: str) -> None: if not self._pending: self._pending_at = time.monotonic() self._pending.append(grid_id) + def _flush_files(self) -> None: + with self._lock: + pending = self._pending + self._pending = [] + self._pending_at = 0.0 + if pending and self._file is not None: + blob = "".join(f"{item}\n" for item in pending).encode("utf-8") + self._file.write(blob) + self._file.flush() + os.fsync(self._file.fileno()) + with self._lock: + self.committed += len(pending) + self._committed_size += len(blob) + self._write_meta() + + def _pull_files(self) -> list[str]: + with self._lock: + end = self._committed_size + offset = self._read_offset + if offset >= end or self._read is None: + return [] + blob = self._read_at(offset, end - offset) + with self._lock: + if self._read_offset == offset: + self._read_offset = offset + len(blob) + return [line.strip() for line in blob.decode("utf-8").split("\n") if line.strip()] + def _read_at(self, offset: int, size: int) -> bytes: self._read.seek(offset) blob = self._read.read(size) @@ -209,17 +289,17 @@ class IdSpool: "complete": self.complete, "failedTiles": self.failed_tiles, } - text = json.dumps(payload, ensure_ascii=False) - temporary = self.meta_path.with_name(self.meta_path.name + ".tmp") - try: - self._replace_meta(temporary, text) - except OSError as exc: - if not _file_busy(exc): - raise - now = time.monotonic() - if now - self._meta_warned >= 5: - logger.warning("编号进度暂时写不进去,下载继续: %s", exc) - self._meta_warned = now + text = json.dumps(payload, ensure_ascii=False) + temporary = self.meta_path.with_name(self.meta_path.name + ".tmp") + try: + self._replace_meta(temporary, text) + except OSError as exc: + if not _file_busy(exc): + raise + now = time.monotonic() + if now - self._meta_warned >= 5: + logger.warning("编号进度暂时写不进去,下载继续: %s", exc) + self._meta_warned = now def _replace_meta(self, temporary: Path, text: str) -> None: last: OSError | None = None @@ -239,8 +319,17 @@ class IdSpool: if last is not None: raise last - @staticmethod - def _peek(directory: Path) -> dict | None: + @classmethod + def _peek(cls, directory: Path) -> dict | None: + with _LIVE_LOCK: + live = _LIVE.get(_directory_key(directory)) + if live is not None: + with live._lock: + return { + "committed": live.committed, + "complete": live.complete, + "failedTiles": [list(item) for item in live.failed_tiles], + } path = Path(directory) / "ids.spool.meta" try: data = json.loads(path.read_text(encoding="utf-8")) diff --git a/backend/tests/test_engine.py b/backend/tests/test_engine.py index 9c5ba26..c0153af 100644 --- a/backend/tests/test_engine.py +++ b/backend/tests/test_engine.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio import logging +import threading from pathlib import Path import httpx @@ -346,6 +347,46 @@ def test_spool_keeps_downloading_when_meta_replace_is_denied(monkeypatch, tmp_pa assert sleeps +def test_spool_writer_serves_flush_and_read_together(tmp_path: Path): + spool = IdSpool(tmp_path) + spool.open() + errors: list[BaseException] = [] + found: list[str] = [] + + def produce() -> None: + try: + for index in range(300): + spool.add(str(index)) + if index % 40 == 0: + spool.flush() + IdSpool.listing_finished(tmp_path) + spool.mark_complete() + except BaseException as exc: + errors.append(exc) + + def consume() -> None: + try: + while len(found) < 300: + found.extend(spool.pull()) + if spool.caught_up() and len(found) < 300: + break + except BaseException as exc: + errors.append(exc) + + try: + writer = threading.Thread(target=produce) + reader = threading.Thread(target=consume) + writer.start() + reader.start() + writer.join() + reader.join() + assert errors == [] + assert found == [str(index) for index in range(300)] + assert spool.caught_up() is True + finally: + spool.close() + + def test_spool_dedups_ints_and_drops_uncommitted_tail(monkeypatch, tmp_path: Path): clock = {"now": 10.0} monkeypatch.setattr(spool_module.time, "monotonic", lambda: clock["now"]) @@ -685,7 +726,7 @@ async def _unknown_download_error_is_generic(tmp_path: Path, caplog): finally: _restore(saved) assert job.status == "error" - assert job.message == "下载失败,详情见日志" + assert job.message == "下载中断,已下载的内容还在,点继续即可" assert "socket exploded" in caplog.text assert "socket exploded" not in job.message diff --git a/desktop/src/features/download/DownloadManagerView.vue b/desktop/src/features/download/DownloadManagerView.vue index bca47b8..177de05 100644 --- a/desktop/src/features/download/DownloadManagerView.vue +++ b/desktop/src/features/download/DownloadManagerView.vue @@ -90,7 +90,10 @@ function statusLabel(job: DownloadJob) { } function noteText(job: DownloadJob) { - const text = job.message.trim(); + let text = job.message.trim(); + if (text === "下载失败,详情见日志") { + text = "保存编号进度时文件被拒绝访问,已下载的内容还在,点继续即可"; + } if (!text || text === statusLabel(job)) return ""; return text; } @@ -553,9 +556,12 @@ async function removeJob(job: DownloadJob, files: boolean) { :processing="job.status === 'running'" />
- - {{ statusLabel(job) }} - + + + {{ statusLabel(job) }} + + {{ noteText(job) }} + 失败 {{ job.failed }} · {{ formatSize(job.fileBytes) }}