fix: 下载文件改由任务自己的线程读写,消除并发竞争和漏下载
This commit is contained in:
@@ -1,31 +1,21 @@
|
||||
"""全市编号暂存。只有写入线程碰文件,其他线程只改内存。"""
|
||||
"""全市编号暂存。去重后按行追加,批量 fsync,并记下已提交行数。
|
||||
|
||||
文件只在任务自己的读写线程里打开和写入。下载协程和界面只碰内存里的计数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from app.shared.files import write_atomic
|
||||
|
||||
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 的行数、是否读完和失败块。"""
|
||||
@@ -47,20 +37,23 @@ class IdSpool:
|
||||
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
|
||||
self._queue: queue.Queue = queue.Queue()
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
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()
|
||||
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]
|
||||
committed = len(lines)
|
||||
complete = False
|
||||
failed: list[list[float]] = []
|
||||
else:
|
||||
@@ -70,33 +63,31 @@ class IdSpool:
|
||||
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()
|
||||
seen: set[int] = 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")
|
||||
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()
|
||||
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 视为同一个。"""
|
||||
@@ -131,10 +122,22 @@ class IdSpool:
|
||||
self.failed_tiles = [list(item) for item in failed_tiles]
|
||||
|
||||
def flush(self) -> None:
|
||||
self._submit("flush")
|
||||
with self._io:
|
||||
self._flush_files()
|
||||
|
||||
def mark_complete(self) -> None:
|
||||
self._submit("complete")
|
||||
# 先把缓冲写稳,再标记读完,避免下载侧提前认为没有新编号。
|
||||
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:
|
||||
"""编号已经读完,并且下载侧已经取走全部已提交行。"""
|
||||
@@ -143,91 +146,41 @@ class IdSpool:
|
||||
|
||||
def pull(self) -> list[str]:
|
||||
"""按顺序读出上次之后新提交的编号。"""
|
||||
box: list[list[str]] = []
|
||||
self._submit("pull", box)
|
||||
return box[0] if box else []
|
||||
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:
|
||||
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
|
||||
with self._io:
|
||||
try:
|
||||
self._dispatch(kind, box)
|
||||
except Exception as exc:
|
||||
slot["error"] = exc
|
||||
if self._file is not None:
|
||||
self._flush_files()
|
||||
finally:
|
||||
done.set()
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
if self._read is not None:
|
||||
self._read.close()
|
||||
self._read = None
|
||||
|
||||
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:
|
||||
@staticmethod
|
||||
def read_meta(directory: Path) -> dict | None:
|
||||
"""只用于没有在下载的任务。正在下载的任务直接读对象里的计数。"""
|
||||
path = Path(directory) / "ids.spool.meta"
|
||||
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)
|
||||
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:
|
||||
@@ -239,28 +192,31 @@ class IdSpool:
|
||||
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")
|
||||
self._file.write(blob)
|
||||
self._file.flush()
|
||||
os.fsync(self._file.fileno())
|
||||
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 _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)
|
||||
@@ -271,70 +227,19 @@ class IdSpool:
|
||||
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,
|
||||
"failedTiles": [list(item) for item in self.failed_tiles],
|
||||
}
|
||||
text = json.dumps(payload, ensure_ascii=False)
|
||||
temporary = self.meta_path.with_name(self.meta_path.name + ".tmp")
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
try:
|
||||
self._replace_meta(temporary, text)
|
||||
write_atomic(self.meta_path, data)
|
||||
except OSError as exc:
|
||||
if not _file_busy(exc):
|
||||
raise
|
||||
# meta 只是加速续传。写不进去时下次打开会按旧计数截断并补读,不影响已写的数据。
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user