fix: 编号进度被拒绝访问时继续下载
This commit is contained in:
@@ -3,11 +3,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("nqi.download")
|
||||
|
||||
|
||||
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}
|
||||
|
||||
|
||||
class IdSpool:
|
||||
"""ids.spool 每行一个编号。meta 记录已 fsync 的行数、是否读完和失败块。"""
|
||||
@@ -30,6 +40,7 @@ class IdSpool:
|
||||
self._read_offset = 0
|
||||
self._committed_size = 0
|
||||
self._lock = threading.Lock()
|
||||
self._meta_warned = 0.0
|
||||
|
||||
def open(self) -> None:
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
@@ -198,13 +209,35 @@ class IdSpool:
|
||||
"complete": self.complete,
|
||||
"failedTiles": self.failed_tiles,
|
||||
}
|
||||
text = json.dumps(payload, ensure_ascii=False)
|
||||
temporary = self.meta_path.with_suffix(".tmp")
|
||||
with open(temporary, "w", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, self.meta_path)
|
||||
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
|
||||
|
||||
@staticmethod
|
||||
def _peek(directory: Path) -> dict | None:
|
||||
|
||||
Reference in New Issue
Block a user