Files

246 lines
8.9 KiB
Python

"""全市编号暂存。去重后按行追加,批量 fsync,并记下已提交行数。
文件只在任务自己的读写线程里打开和写入。下载协程和界面只碰内存里的计数。
"""
from __future__ import annotations
import json
import logging
import os
import threading
import time
from pathlib import Path
from app.shared.files import write_atomic
logger = logging.getLogger("nqi.download")
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
# _lock 只护内存状态,持有时间很短;_io 护文件句柄,读写都在它里面按顺序执行。
self._lock = threading.Lock()
self._io = threading.RLock()
self._meta_warned = 0.0
def open(self) -> None:
with self._io:
self._open_files()
def _open_files(self) -> None:
self.directory.mkdir(parents=True, exist_ok=True)
meta = self.read_meta(self.directory)
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]
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:
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())
seen: set[int] = set()
for line in lines:
text = line.decode("utf-8").strip()
if text.isdigit():
seen.add(int(text))
with self._lock:
self.committed = len(lines)
self.complete = complete
self.failed_tiles = failed
self.seen = seen
self._committed_size = len(data)
self._pending = []
self._pending_at = 0.0
self._read_offset = 0
# 不带缓冲:写失败时可以按已提交长度截回去,不留下半行。
self._file = open(self.path, "ab", buffering=0)
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()
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:
with self._io:
self._flush_files()
def mark_complete(self) -> None:
# 先把缓冲写稳,再标记读完,避免下载侧提前认为没有新编号。
with self._io:
self._flush_files()
with self._lock:
self.complete = True
self._write_meta()
def rewind(self) -> None:
"""新一轮从头读。已下载的由下载侧跳过,上一轮读出但没下完的不会漏。"""
with self._io:
with self._lock:
self._read_offset = 0
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]:
"""按顺序读出上次之后新提交的编号。"""
with self._io:
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:
self._read_offset = offset + len(blob)
return [line.strip() for line in blob.decode("utf-8").split("\n") if line.strip()]
def close(self) -> None:
with self._io:
try:
if self._file is not None:
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
@staticmethod
def read_meta(directory: Path) -> dict | None:
"""只用于没有在下载的任务。正在下载的任务直接读对象里的计数。"""
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
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
base = self._committed_size
if pending and self._file is not None:
blob = "".join(f"{item}\n" for item in pending).encode("utf-8")
try:
view = memoryview(blob)
while view:
written = self._file.write(view)
view = view[written:]
os.fsync(self._file.fileno())
except OSError:
# 截掉写了一半的尾巴,编号放回缓冲,下次再写,不会丢。
try:
os.ftruncate(self._file.fileno(), base)
except OSError:
pass
with self._lock:
self._pending = pending + self._pending
if not self._pending_at:
self._pending_at = time.monotonic()
raise
with self._lock:
self.committed += len(pending)
self._committed_size += len(blob)
self._write_meta()
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 _write_meta(self) -> None:
with self._lock:
payload = {
"committed": self.committed,
"complete": self.complete,
"failedTiles": [list(item) for item in self.failed_tiles],
}
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
try:
write_atomic(self.meta_path, data)
except OSError as exc:
# meta 只是加速续传。写不进去时下次打开会按旧计数截断并补读,不影响已写的数据。
now = time.monotonic()
if now - self._meta_warned >= 5:
logger.warning("编号进度暂时写不进去,下载继续: %s", exc)
self._meta_warned = now