fix: 编号进度改为单线程写入并在任务上显示原因

This commit is contained in:
2026-10-25 08:57:34 +08:00
parent e99a112965
commit 2aa8990b63
5 changed files with 211 additions and 63 deletions
+6 -7
View File
@@ -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:
+140 -51
View File
@@ -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"))