Files
NqiTools/backend/app/features/download/spool.py
T

341 lines
11 KiB
Python

"""全市编号暂存。只有写入线程碰文件,其他线程只改内存。"""
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 上替换小文件时,杀毒或索引可能短暂拒绝访问。"""
winerror = getattr(exc, "winerror", None)
errno = getattr(exc, "errno", None)
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 的行数、是否读完和失败块。"""
batch_size = 200
flush_seconds = 0.5
def __init__(self, directory: Path) -> None:
self.directory = Path(directory)
self.path = self.directory / "ids.spool"
self.meta_path = self.directory / "ids.spool.meta"
self.seen: set[int] = set()
self.committed = 0
self.complete = False
self.failed_tiles: list[list[float]] = []
self._pending: list[str] = []
self._pending_at = 0.0
self._file = None
self._read = None
self._read_offset = 0
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)
meta = self._read_meta()
raw = self.path.read_bytes() if self.path.exists() else b""
lines = raw.splitlines()
if meta is None:
if raw and not raw.endswith(b"\n"):
lines = lines[:-1]
committed = len(lines)
complete = False
failed: list[list[float]] = []
else:
committed = int(meta.get("committed") or 0)
complete = bool(meta.get("complete"))
failed = [list(item) for item in meta.get("failedTiles") or []]
if len(lines) > committed:
lines = lines[:committed]
elif len(lines) < committed:
committed = len(lines)
complete = False
data = b"".join(line + b"\n" for line in lines)
with open(self.path, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
self.committed = len(lines)
self.complete = complete
self.failed_tiles = failed
self.seen = set()
for line in lines:
text = line.decode("utf-8").strip()
if text.isdigit():
self.seen.add(int(text))
self._committed_size = len(data)
self._pending = []
self._pending_at = 0.0
self._read_offset = 0
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 视为同一个。"""
if not str(grid_id).isdigit():
return False
number = int(grid_id)
with self._lock:
if number in self.seen:
return False
self.seen.add(number)
self._remember(str(number))
return True
def append(self, grid_id: str) -> None:
"""调用方已经放进 seen 时,只追加到待写缓冲。"""
with self._lock:
self._remember(str(grid_id))
def due(self) -> bool:
with self._lock:
if not self._pending:
return False
if len(self._pending) >= self.batch_size:
return True
return time.monotonic() - self._pending_at >= self.flush_seconds
def set_scan_state(self, *, complete: bool | None = None, failed_tiles: list | None = None) -> None:
with self._lock:
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._submit("complete")
def caught_up(self) -> bool:
"""编号已经读完,并且下载侧已经取走全部已提交行。"""
with self._lock:
return self.complete and not self._pending and self._read_offset >= self._committed_size
def pull(self) -> list[str]:
"""按顺序读出上次之后新提交的编号。"""
box: list[list[str]] = []
self._submit("pull", box)
return box[0] if box else []
def close(self) -> 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:
data = cls._peek(directory)
if data is None:
return False
return bool(data.get("complete")) and not data.get("failedTiles")
@classmethod
def committed_count(cls, directory: Path) -> int:
data = cls._peek(directory)
if data is None:
return 0
try:
return int(data.get("committed") or 0)
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)
if len(blob) == size:
return blob
self._read.close()
self._read = open(self.path, "rb")
self._read.seek(offset)
return self._read.read(size)
def _read_meta(self) -> dict | None:
if not self.meta_path.exists():
return None
try:
data = json.loads(self.meta_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
if not isinstance(data, dict):
return None
return data
def _write_meta(self) -> None:
with self._lock:
payload = {
"committed": self.committed,
"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
def _replace_meta(self, temporary: Path, text: str) -> None:
last: OSError | None = None
for attempt in range(5):
try:
with open(temporary, "w", encoding="utf-8") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, self.meta_path)
return
except OSError as exc:
last = exc
if not _file_busy(exc) or attempt == 4:
raise
time.sleep(0.05 * (attempt + 1))
if last is not None:
raise last
@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"))
except (OSError, json.JSONDecodeError):
return None
if not isinstance(data, dict):
return None
return data