Skip to content

The only downloader you need. 下载器的集大成者。

fix(http): Windows 上分片下载写盘失败一直重试

XiaoYouChRfa535fa3571d
diff --git a/app/platform/sysio.py b/app/platform/sysio.py
index cb86c4f1..13b23abd 100644
--- a/app/platform/sysio.py
+++ b/app/platform/sysio.py
@@ -5,70 +5,44 @@ from sys import platform
if platform == "win32":
import msvcrt
- from ctypes import wintypes, Structure, Union, c_void_p, POINTER, windll, WinError, cast, c_char_p, byref, \
+ from ctypes import wintypes, Structure, c_void_p, POINTER, WinDLL, WinError, get_last_error, c_char_p, byref, \
c_longlong
- INVALID_HANDLE_VALUE = -1
-
- def _check_error(msg: str):
- def _check(result, func, arg):
- if not result:
- err = WinError()
- raise OSError(err.winerror, f"{msg}: {err.strerror}")
- return result
-
- return _check
-
- class _dummy_s(Structure):
- _fields_ = [("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD)]
-
- class _dummy_u(Union):
- _fields_ = [("DUMMYSTRUCTNAME", _dummy_s), ("Pointer", c_void_p)]
+ # 独立实例,不改全局 windll 上的 argtypes
+ kernel32 = WinDLL("kernel32", use_last_error=True)
class OVERLAPPED(Structure):
_fields_ = [
- ("Internal", POINTER(wintypes.ULONG)),
- ("InternalHigh", POINTER(wintypes.ULONG)),
- ("DUMMYUNIONNAME", _dummy_u),
+ ("Internal", c_void_p),
+ ("InternalHigh", c_void_p),
+ ("Offset", wintypes.DWORD),
+ ("OffsetHigh", wintypes.DWORD),
("hEvent", wintypes.HANDLE),
]
- _anonymous_ = ("DUMMYUNIONNAME",)
- WriteFile = windll.kernel32.WriteFile
+ WriteFile = kernel32.WriteFile
WriteFile.argtypes = [
wintypes.HANDLE,
- wintypes.LPCVOID,
+ c_char_p,
wintypes.DWORD,
wintypes.LPDWORD,
POINTER(OVERLAPPED),
]
WriteFile.restype = wintypes.BOOL
- WriteFile.errcheck = _check_error("WriteFile failed")
- def pwrite(fd: int | wintypes.HANDLE, data: bytes, offset: int) -> int:
- if isinstance(fd, int):
- handle = wintypes.HANDLE(
- msvcrt.get_osfhandle(fd)
- )
- else:
- handle = fd
- written = wintypes.DWORD(0)
- overlapped = OVERLAPPED()
- overlapped.DUMMYSTRUCTNAME.OffsetHigh = wintypes.DWORD(offset >> 32)
- overlapped.DUMMYSTRUCTNAME.Offset = wintypes.DWORD(offset)
- WriteFile(
- handle,
- cast(c_char_p(data), wintypes.LPCVOID),
- len(data),
- byref(written),
- byref(overlapped),
- )
- return written.value
+ def pwrite(fd: int, data: bytes | memoryview, offset: int) -> int:
+ # 实测比 PyObject_GetBuffer 零拷贝快
+ buffer = bytes(data)
+ overlapped = OVERLAPPED(Offset=offset & 0xFFFFFFFF, OffsetHigh=offset >> 32)
+ # 同步写文件要么全部写完要么失败,所以不取实际写入字节数
+ if not WriteFile(msvcrt.get_osfhandle(fd), buffer, len(buffer), None, byref(overlapped)):
+ raise WinError(get_last_error())
+ return len(buffer)
FSCTL_SET_SPARSE = 0x000900C4
FILE_BEGIN = 0
- DeviceIoControl = windll.kernel32.DeviceIoControl
+ DeviceIoControl = kernel32.DeviceIoControl
DeviceIoControl.argtypes = [
wintypes.HANDLE,
wintypes.DWORD,
@@ -80,9 +54,8 @@ if platform == "win32":
wintypes.LPVOID,
]
DeviceIoControl.restype = wintypes.BOOL
- DeviceIoControl.errcheck = _check_error("FSCTL_SET_SPARSE failed")
- SetFilePointerEx = windll.kernel32.SetFilePointerEx
+ SetFilePointerEx = kernel32.SetFilePointerEx
SetFilePointerEx.argtypes = [
wintypes.HANDLE,
c_longlong,
@@ -90,41 +63,19 @@ if platform == "win32":
wintypes.DWORD,
]
SetFilePointerEx.restype = wintypes.BOOL
- SetFilePointerEx.errcheck = _check_error("SetFilePointerEx failed")
- SetEndOfFile = windll.kernel32.SetEndOfFile
+ SetEndOfFile = kernel32.SetEndOfFile
SetEndOfFile.argtypes = [wintypes.HANDLE]
SetEndOfFile.restype = wintypes.BOOL
- SetEndOfFile.errcheck = _check_error("SetEndOfFile failed")
- def ftruncate(fd: int | wintypes.HANDLE, size: int) -> None:
- if isinstance(fd, int):
- handle = wintypes.HANDLE(
- msvcrt.get_osfhandle(fd)
- )
- else:
- handle = fd
-
- returned = wintypes.DWORD(0)
- try:
- DeviceIoControl(
- handle,
- FSCTL_SET_SPARSE,
- None,
- 0,
- None,
- 0,
- byref(returned),
- None,
- )
- except OSError:
+ # 不用 os.ftruncate:它在 Windows 上扩展文件时会逐块写零,预分配大文件很慢
+ def ftruncate(fd: int, size: int) -> None:
+ handle = msvcrt.get_osfhandle(fd)
+ if not DeviceIoControl(handle, FSCTL_SET_SPARSE, None, 0, None, 0, byref(wintypes.DWORD()), None):
from loguru import logger
logger.debug("文件系统不支持稀疏文件,使用常规预分配")
-
- newPos = c_longlong()
- SetFilePointerEx(handle, size, byref(newPos), FILE_BEGIN)
-
- SetEndOfFile(handle)
+ if not SetFilePointerEx(handle, size, None, FILE_BEGIN) or not SetEndOfFile(handle):
+ raise WinError(get_last_error())
else:
# noinspection PyUnresolvedReferences
diff --git a/features/http_pack/task.py b/features/http_pack/task.py
index 15f7bec1..546b51fe 100644
--- a/features/http_pack/task.py
+++ b/features/http_pack/task.py
@@ -18,7 +18,7 @@ from app.platform.sysio import ftruncate, pwrite
STREAM_READ_TIMEOUT = 30
PERMANENT_STATUS = frozenset({400, 401, 403, 404, 405, 410, 451})
-FATAL_IO_ERRNO = frozenset({errno.ENOSPC, errno.EDQUOT, errno.EROFS, errno.EIO, 39, 112})
+FATAL_IO_ERRNO = frozenset({errno.ENOSPC, errno.EDQUOT, errno.EROFS, errno.EIO})
class PermanentDownloadError(Exception):
diff --git a/tests/test_sysio.py b/tests/test_sysio.py
new file mode 100644
index 00000000..ac8be1a2
--- /dev/null
+++ b/tests/test_sysio.py
@@ -0,0 +1,39 @@
+import errno
+import os
+import sys
+
+import pytest
+
+from app.platform.sysio import ftruncate, pwrite
+
+O_BINARY = getattr(os, "O_BINARY", 0)
+
+
+def test_pwrite_readonly_memoryview_at_offset(tmp_path):
+ path = tmp_path / "out.bin"
+ fd = os.open(path, os.O_RDWR | os.O_CREAT | O_BINARY)
+ data = memoryview(b"ghost-downloader").toreadonly()
+ try:
+ ftruncate(fd, 123 + len(data))
+ assert pwrite(fd, data, 123) == len(data)
+ finally:
+ os.close(fd)
+
+ assert path.read_bytes() == bytes(123) + b"ghost-downloader"
+
+
+def test_pwrite_raises_like_os_on_readonly_fd(tmp_path):
+ path = tmp_path / "out.bin"
+ path.write_bytes(b"")
+ fd = os.open(path, os.O_RDONLY | O_BINARY)
+ try:
+ with pytest.raises(OSError) as info:
+ pwrite(fd, b"x", 0)
+ finally:
+ os.close(fd)
+
+ if sys.platform == "win32":
+ assert info.value.winerror == 5
+ assert info.value.errno == errno.EACCES
+ else:
+ assert info.value.errno == errno.EBADF