The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
fix(http): 恢复 range 请求的 Accept-Encoding: identity
XiaoYouChR0ee14c58b4d1
diff --git a/features/http_pack/task.py b/features/http_pack/task.pyindex 1c8ce949..66d4309a 100644--- a/features/http_pack/task.py+++ b/features/http_pack/task.py@@ -12,7 +12,6 @@ from struct import unpack, packfrom loguru import loggerfrom app.client import buildClient, toEmulation-from wreq.exceptions import DecodingError as WreqDecodingError, RequestError as WreqRequestErrorfrom app.config.cfg import cfgfrom app.models.task import Task, TaskError, TaskStep, TaskStatus, SpecialFileSizefrom app.platform.sysio import ftruncate, pwrite@@ -267,7 +266,7 @@ class HttpTaskStep(TaskStep):while True:try:httpPos = self.httpByteOffset + subworker.position- headers = {**self._effectiveHeaders, "range": f"bytes={httpPos}-"}+ headers = {**self._effectiveHeaders, "range": f"bytes={httpPos}-", "accept-encoding": "identity"}response = await client.get(self._effectiveUrl, headers=headers)try:status = response.status.as_int()@@ -291,10 +290,6 @@ class HttpTaskStep(TaskStep):raiseexcept (PermanentDownloadError, RangeNotSupportedError):raise- except (WreqDecodingError, WreqRequestError):- # CDN 只存了 Brotli 压缩版,range 切的是压缩流中间,无法解压- # TODO: 并发下载压缩流 + 下载后统一解压,避免降级丢失并发速度- raise RangeNotSupportedError()except Exception as e:if isinstance(e, OSError) and e.errno in FATAL_IO_ERRNO:raise@@ -342,6 +337,7 @@ class HttpTaskStep(TaskStep):headers = {**self._effectiveHeaders,"range": f"bytes={httpPos}-{httpEnd}",+ "accept-encoding": "identity",}response = await client.get(self._effectiveUrl, headers=headers)try:@@ -374,10 +370,6 @@ class HttpTaskStep(TaskStep):raiseexcept (PermanentDownloadError, RangeNotSupportedError):raise- except (WreqDecodingError, WreqRequestError):- # CDN 只存了 Brotli 压缩版,range 切的是压缩流中间,无法解压- # TODO: 并发下载压缩流 + 下载后统一解压,避免降级丢失并发速度- raise RangeNotSupportedError()except Exception as e:if isinstance(e, OSError) and e.errno in FATAL_IO_ERRNO:raisediff --git a/tests/test_http_subworker.py b/tests/test_http_subworker.pyindex ef31ea96..2f533cad 100644--- a/tests/test_http_subworker.py+++ b/tests/test_http_subworker.py@@ -9,11 +9,7 @@ Seam S13e: 请求构造(_effectiveHeaders 一致性)from __future__ import annotationsimport asyncio-import brotli-import gzipimport os-import zlib-import zstandardfrom pathlib import Pathimport pytest@@ -632,186 +628,5 @@ class TestStallRecovery:releaseHang.set()-# ── S13a/S13c: Compressed range ──---ENCODINGS = {- "gzip": lambda data: gzip.compress(data),- "deflate": lambda data: zlib.compress(data),- "br": lambda data: brotli.compress(data),- "zstd": lambda data: zstandard.compress(data),-}---def compressedRangeHandler(content: bytes, encoding: str):- """Server that compresses each range response with the given encoding."""- compress = ENCODINGS[encoding]-- async def handler(request: web.Request) -> web.Response:- rangeHeader = request.headers.get("Range")- if rangeHeader is None:- return web.Response(- body=content,- headers={"Content-Length": str(len(content)), "Accept-Ranges": "bytes"},- )- rangeSpec = rangeHeader.replace("bytes=", "")- parts = rangeSpec.split("-")- start = int(parts[0])- end = int(parts[1]) if parts[1] else len(content) - 1- body = content[start:end + 1]- compressed = compress(body)- return web.Response(- status=206,- body=compressed,- headers={- "Content-Range": f"bytes {start}-{end}/{len(content)}",- "Content-Encoding": encoding,- "Content-Length": str(len(compressed)),- },- )- return handler---def brokenEncodingRangeHandler(content: bytes, encoding: str):- """Server claims encoding for ranges but sends raw bytes. Full requests are correct."""- async def handler(request: web.Request) -> web.Response:- rangeHeader = request.headers.get("Range")- if rangeHeader is None:- return web.Response(- body=content,- headers={"Content-Length": str(len(content))},- )- rangeSpec = rangeHeader.replace("bytes=", "")- parts = rangeSpec.split("-")- start = int(parts[0])- end = int(parts[1]) if parts[1] else len(content) - 1- body = content[start:end + 1]- return web.Response(- status=206,- body=body,- headers={- "Content-Range": f"bytes {start}-{end}/{len(content)}",- "Content-Encoding": encoding,- },- )- return handler---class TestCompressedRange:-- @pytest.mark.parametrize("encoding", list(ENCODINGS))- async def test_compressed_range_produces_correct_file(self, server, tmp_path, encoding):- content = buildFileContent(1000)- url = await server(compressedRangeHandler(content, encoding))- task, step = makeStep(url, tmp_path, fileSize=1000, subworkerCount=2)- task.setStatus(TaskStatus.RUNNING)-- await runStep(step)-- assert (tmp_path / "test.bin").read_bytes() == content-- @pytest.mark.parametrize("encoding", list(ENCODINGS))- async def test_broken_encoding_falls_back_to_single_stream(self, server, tmp_path, monkeypatch, encoding):- content = buildFileContent(500)-- _real_sleep = asyncio.sleep-- async def fast_sleep(n):- await _real_sleep(0 if n >= 5 else min(n, 0.01))-- monkeypatch.setattr(asyncio, "sleep", fast_sleep)-- url = await server(brokenEncodingRangeHandler(content, encoding))- task, step = makeStep(url, tmp_path, fileSize=500, subworkerCount=2,- canUseRangeRequests=True)- task.setStatus(TaskStatus.RUNNING)-- await asyncio.wait_for(runStep(step), timeout=15)-- assert not step.canUseRangeRequests- assert (tmp_path / "test.bin").read_bytes() == content-- async def test_mixed_encodings_across_subworkers(self, server, tmp_path):- """Different subworkers get different Content-Encoding (CDN edge variance)."""- content = buildFileContent(1000)- encodingNames = list(ENCODINGS)- requestIndex = 0-- async def handler(request: web.Request) -> web.Response:- nonlocal requestIndex- rangeHeader = request.headers.get("Range")- if rangeHeader is None:- return web.Response(- body=content,- headers={"Content-Length": str(len(content)), "Accept-Ranges": "bytes"},- )- rangeSpec = rangeHeader.replace("bytes=", "")- parts = rangeSpec.split("-")- start = int(parts[0])- end = int(parts[1]) if parts[1] else len(content) - 1- body = content[start:end + 1]- encoding = encodingNames[requestIndex % len(encodingNames)]- requestIndex += 1- compressed = ENCODINGS[encoding](body)- return web.Response(- status=206,- body=compressed,- headers={- "Content-Range": f"bytes {start}-{end}/{len(content)}",- "Content-Encoding": encoding,- "Content-Length": str(len(compressed)),- },- )-- url = await server(handler)- task, step = makeStep(url, tmp_path, fileSize=1000, subworkerCount=4)- task.setStatus(TaskStatus.RUNNING)-- await runStep(step)-- assert (tmp_path / "test.bin").read_bytes() == content-- async def test_reassignment_with_compressed_range(self, server, tmp_path):- """_splitSlowest during compressed streaming: clamp on decompressed bytes, new subworker gets correct compressed range."""- content = buildFileContent(2_000_000)- requestCount = 0-- compress = ENCODINGS["gzip"]-- async def handler(request: web.Request) -> web.Response:- nonlocal requestCount- requestCount += 1- rangeHeader = request.headers.get("Range")- if rangeHeader is None:- return web.Response(- body=content,- headers={"Content-Length": str(len(content)), "Accept-Ranges": "bytes"},- )- rangeSpec = rangeHeader.replace("bytes=", "")- parts = rangeSpec.split("-")- start = int(parts[0])- end = int(parts[1]) if parts[1] else len(content) - 1- body = content[start:end + 1]- compressed = compress(body)- return web.Response(- status=206,- body=compressed,- headers={- "Content-Range": f"bytes {start}-{end}/{len(content)}",- "Content-Encoding": "gzip",- "Content-Length": str(len(compressed)),- },- )-- url = await server(handler)- task, step = makeStep(url, tmp_path, fileSize=2_000_000, subworkerCount=2)- task.setStatus(TaskStatus.RUNNING)-- await runStep(step)-- assert (tmp_path / "test.bin").read_bytes() == content- assert requestCount > 2--if __name__ == "__main__":pytest.main([__file__, "-v", "--tb=short"])