Skip to content

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

fix(http): 死连接不再卡住分片 #665

XiaoYouChR503a04c735ad
diff --git a/features/http_pack/task.py b/features/http_pack/task.py
index a5927876..6eca6827 100644
--- a/features/http_pack/task.py
+++ b/features/http_pack/task.py
@@ -254,38 +254,48 @@ class HttpTaskStep(TaskStep):
if recordFile is not None:
recordFile.close()
- async def _runSubworker(self, subworker: HttpSubworker, fd: int) -> None:
- client = buildClient(emulation=self._emulation, userAgent=self.userAgent or None, readTimeout=STREAM_READ_TIMEOUT)
- try:
- await self._runSubworkerWith(subworker, fd, client)
- finally:
- client.close()
+ async def _fetch(self, client, headers):
+ return await asyncio.wait_for(
+ client.get(self._effectiveUrl, headers=headers),
+ timeout=STREAM_READ_TIMEOUT,
+ )
- async def _runSubworkerWith(self, subworker: HttpSubworker, fd: int, client) -> None:
+ def _openClient(self):
+ return buildClient(
+ emulation=self._emulation,
+ userAgent=self.userAgent or None,
+ readTimeout=STREAM_READ_TIMEOUT,
+ )
+
+ async def _runSubworker(self, subworker: HttpSubworker, fd: int) -> None:
if subworker.end == SpecialFileSize.UNKNOWN:
while True:
+ client = self._openClient()
try:
- httpPos = self.httpByteOffset + subworker.position
- headers = {**self._effectiveHeaders, "range": f"bytes={httpPos}-", "accept-encoding": "identity"}
- response = await client.get(self._effectiveUrl, headers=headers)
try:
- status = response.status.as_int()
- if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):
- raise PermanentDownloadError(status)
- if status == 200:
- raise RangeNotSupportedError()
- if status != 206:
- raise Exception(f"服务器拒绝了范围请求,状态码:{status}")
- async for chunk in response.stream():
- if not chunk:
- continue
- pwrite(fd, chunk, subworker.position)
- subworker.receivedBytes += len(chunk)
- self._reportSpeed(len(chunk))
- await self._waitForSpeedLimit()
+ httpPos = self.httpByteOffset + subworker.position
+ headers = {**self._effectiveHeaders, "range": f"bytes={httpPos}-", "accept-encoding": "identity"}
+ response = await self._fetch(client, headers)
+ try:
+ status = response.status.as_int()
+ if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):
+ raise PermanentDownloadError(status)
+ if status == 200:
+ raise RangeNotSupportedError()
+ if status != 206:
+ raise Exception(f"服务器拒绝了范围请求,状态码:{status}")
+ async for chunk in response.stream():
+ if not chunk:
+ continue
+ pwrite(fd, chunk, subworker.position)
+ subworker.receivedBytes += len(chunk)
+ self._reportSpeed(len(chunk))
+ await self._waitForSpeedLimit()
+ finally:
+ response.close()
+ return
finally:
- response.close()
- return
+ client.close()
except CancelledError:
raise
except (PermanentDownloadError, RangeNotSupportedError):
@@ -298,27 +308,31 @@ class HttpTaskStep(TaskStep):
elif subworker.end == SpecialFileSize.NOT_SUPPORTED:
while True:
+ client = self._openClient()
try:
- ftruncate(fd, 0)
- subworker.receivedBytes = 0
- response = await client.get(self._effectiveUrl, headers=dict(self._effectiveHeaders))
try:
- status = response.status.as_int()
- if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):
- raise PermanentDownloadError(status)
- if status != 200:
- raise Exception(f"服务器返回了异常状态码:{status}")
- async for chunk in response.stream():
- if not chunk:
- continue
- pwrite(fd, chunk, subworker.receivedBytes)
- subworker.receivedBytes += len(chunk)
- self._reportSpeed(len(chunk))
- await self._waitForSpeedLimit()
+ ftruncate(fd, 0)
+ subworker.receivedBytes = 0
+ response = await self._fetch(client, dict(self._effectiveHeaders))
+ try:
+ status = response.status.as_int()
+ if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):
+ raise PermanentDownloadError(status)
+ if status != 200:
+ raise Exception(f"服务器返回了异常状态码:{status}")
+ async for chunk in response.stream():
+ if not chunk:
+ continue
+ pwrite(fd, chunk, subworker.receivedBytes)
+ subworker.receivedBytes += len(chunk)
+ self._reportSpeed(len(chunk))
+ await self._waitForSpeedLimit()
+ finally:
+ response.close()
+ ftruncate(fd, subworker.receivedBytes)
+ return
finally:
- response.close()
- ftruncate(fd, subworker.receivedBytes)
- return
+ client.close()
except CancelledError:
raise
except PermanentDownloadError:
@@ -331,41 +345,44 @@ class HttpTaskStep(TaskStep):
else:
while subworker.position <= subworker.end:
+ client = self._openClient()
try:
- httpPos = self.httpByteOffset + subworker.position
- httpEnd = self.httpByteOffset + subworker.end
- headers = {
- **self._effectiveHeaders,
- "range": f"bytes={httpPos}-{httpEnd}",
- "accept-encoding": "identity",
- }
- response = await client.get(self._effectiveUrl, headers=headers)
try:
- status = response.status.as_int()
- if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):
- raise PermanentDownloadError(status)
- if status == 200:
- raise RangeNotSupportedError()
- if status != 206:
- raise Exception(f"服务器拒绝了范围请求,状态码:{status}")
- async for chunk in response.stream():
- if not chunk:
- continue
- remaining = subworker.end - subworker.position + 1
- if len(chunk) > remaining:
- chunk = chunk[:remaining]
- pwrite(fd, chunk, subworker.position)
- subworker.receivedBytes += len(chunk)
- self._reportSpeed(len(chunk))
- await self._waitForSpeedLimit()
- if subworker.position > subworker.end:
- break
+ httpPos = self.httpByteOffset + subworker.position
+ httpEnd = self.httpByteOffset + subworker.end
+ headers = {
+ **self._effectiveHeaders,
+ "range": f"bytes={httpPos}-{httpEnd}",
+ "accept-encoding": "identity",
+ }
+ response = await self._fetch(client, headers)
+ try:
+ status = response.status.as_int()
+ if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):
+ raise PermanentDownloadError(status)
+ if status == 200:
+ raise RangeNotSupportedError()
+ if status != 206:
+ raise Exception(f"服务器拒绝了范围请求,状态码:{status}")
+ async for chunk in response.stream():
+ if not chunk:
+ continue
+ remaining = subworker.end - subworker.position + 1
+ if len(chunk) > remaining:
+ chunk = chunk[:remaining]
+ pwrite(fd, chunk, subworker.position)
+ subworker.receivedBytes += len(chunk)
+ self._reportSpeed(len(chunk))
+ await self._waitForSpeedLimit()
+ if subworker.position > subworker.end:
+ break
+ finally:
+ response.close()
+
+ if subworker.position > subworker.end:
+ subworker.receivedBytes = subworker.end - subworker.start + 1
finally:
- response.close()
-
- if subworker.position > subworker.end:
- subworker.receivedBytes = subworker.end - subworker.start + 1
-
+ client.close()
except CancelledError:
raise
except (PermanentDownloadError, RangeNotSupportedError):
diff --git a/tests/test_http_subworker.py b/tests/test_http_subworker.py
index 2f533cad..513c16a9 100644
--- a/tests/test_http_subworker.py
+++ b/tests/test_http_subworker.py
@@ -15,6 +15,7 @@ from pathlib import Path
import pytest
from aiohttp import web
+from app.client import buildClient as realBuildClient
from features.http_pack.task import HttpTask, HttpTaskStep, HttpSubworker, PermanentDownloadError, RangeNotSupportedError
from app.models.task import TaskStatus, TaskError
from tests.helpers import buildFileContent, buildRangeHandler, runStep
@@ -627,6 +628,103 @@ class TestStallRecovery:
assert hasStalled
releaseHang.set()
+ async def test_hung_headers_recover_and_complete(self, server, tmp_path, monkeypatch):
+ """Response headers never arrive; the attempt ends and a new one completes the file."""
+ content = buildFileContent(500)
+ hasHung = False
+ releaseHang = asyncio.Event()
+
+ async def hangHeadersOnce(request: web.Request) -> web.StreamResponse:
+ nonlocal hasHung
+ rangeHeader = request.headers.get("Range", "")
+ if rangeHeader == "bytes=0-0":
+ return web.Response(
+ status=206,
+ body=content[:1],
+ headers={
+ "Content-Range": f"bytes 0-0/{len(content)}",
+ "Content-Length": "1",
+ },
+ )
+ if not hasHung:
+ hasHung = True
+ try:
+ await releaseHang.wait()
+ except asyncio.CancelledError:
+ raise
+ return web.Response(status=500, text="released after hang")
+
+ rangeSpec = rangeHeader.replace("bytes=", "")
+ parts = rangeSpec.split("-")
+ start = int(parts[0])
+ end = int(parts[1]) if len(parts) > 1 and 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-Length": str(len(body)),
+ },
+ )
+
+ monkeypatch.setattr("features.http_pack.task.STREAM_READ_TIMEOUT", 1)
+
+ _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(hangHeadersOnce)
+ task, step = makeStep(url, tmp_path, fileSize=500, subworkerCount=1)
+ task.setStatus(TaskStatus.RUNNING)
+
+ try:
+ await asyncio.wait_for(runStep(step), timeout=10)
+ assert (tmp_path / "test.bin").read_bytes() == content
+ assert hasHung
+ finally:
+ releaseHang.set()
+
+ async def test_dead_client_retries_on_a_new_one(self, server, tmp_path, monkeypatch):
+ """A client that cannot fetch does not keep the Task Step. The next attempt finishes the file."""
+ content = buildFileContent(500)
+ firstAttempt = True
+
+ class DeadClient:
+ async def get(self, *args, **kwargs):
+ raise ConnectionError("dead connection")
+
+ def close(self):
+ pass
+
+ def buildClient(**kwargs):
+ nonlocal firstAttempt
+ if kwargs.get("readTimeout") is not None and firstAttempt:
+ firstAttempt = False
+ return DeadClient()
+ return realBuildClient(**kwargs)
+
+ monkeypatch.setattr("features.http_pack.task.buildClient", buildClient)
+
+ _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(buildRangeHandler(content))
+ task, step = makeStep(url, tmp_path, fileSize=500, subworkerCount=1)
+ task.setStatus(TaskStatus.RUNNING)
+
+ await asyncio.wait_for(runStep(step), timeout=10)
+
+ assert (tmp_path / "test.bin").read_bytes() == content
+ assert firstAttempt is False
+
if __name__ == "__main__":
pytest.main([__file__, "-v", "--tb=short"])