fix: 编号进度被拒绝访问时继续下载
This commit is contained in:
@@ -20,6 +20,8 @@ def explain_os_error(exc: BaseException) -> str | None:
|
||||
errno = getattr(exc, "errno", None)
|
||||
if winerror in {32, 33} or errno in {32, 33}:
|
||||
return "文件被占用,请先关闭 Excel 等程序"
|
||||
if winerror == 5 or errno == 13:
|
||||
return "文件被拒绝访问"
|
||||
if winerror in {112, 28} or errno in {112, 28}:
|
||||
return "磁盘空间不足"
|
||||
return None
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -323,6 +323,29 @@ async def _server_error_is_retried(monkeypatch):
|
||||
assert waits == [1, 3, 9]
|
||||
|
||||
|
||||
def test_spool_keeps_downloading_when_meta_replace_is_denied(monkeypatch, tmp_path: Path):
|
||||
sleeps: list[float] = []
|
||||
monkeypatch.setattr(spool_module.time, "sleep", lambda seconds: sleeps.append(seconds))
|
||||
spool = IdSpool(tmp_path)
|
||||
spool.open()
|
||||
real = spool_module.os.replace
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky(src, dst):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
raise PermissionError(13, "Access is denied", str(src), 5)
|
||||
real(src, dst)
|
||||
|
||||
monkeypatch.setattr(spool_module.os, "replace", flaky)
|
||||
assert spool.add("10") is True
|
||||
spool.flush()
|
||||
assert spool.committed == 1
|
||||
assert IdSpool._peek(tmp_path)["committed"] == 1
|
||||
assert calls["n"] == 2
|
||||
assert sleeps
|
||||
|
||||
|
||||
def test_spool_dedups_ints_and_drops_uncommitted_tail(monkeypatch, tmp_path: Path):
|
||||
clock = {"now": 10.0}
|
||||
monkeypatch.setattr(spool_module.time, "monotonic", lambda: clock["now"])
|
||||
|
||||
@@ -121,7 +121,10 @@ def test_file_errors_use_chinese(tmp_path: Path, monkeypatch):
|
||||
full.winerror = 112
|
||||
full_errno = OSError("full")
|
||||
full_errno.errno = 28
|
||||
denied = OSError("denied")
|
||||
denied.winerror = 5
|
||||
assert explain_os_error(busy) == "文件被占用,请先关闭 Excel 等程序"
|
||||
assert explain_os_error(denied) == "文件被拒绝访问"
|
||||
assert explain_os_error(locked) == "文件被占用,请先关闭 Excel 等程序"
|
||||
assert explain_os_error(full) == "磁盘空间不足"
|
||||
assert explain_os_error(full_errno) == "磁盘空间不足"
|
||||
|
||||
Reference in New Issue
Block a user