refactor(dingtalk): use streaming media downloads in tests and runtime
This commit is contained in:
1 parent
8cc5748464
commit
e998268661
2 files changed
+74
-82
No files matched your search
@@ -489,89 +489,46 @@ class DingTalkChannel(BaseChannel):
|
|||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Prefer streaming with a running byte cap so large responses are not
|
|
||||||
# materialized before the limit is enforced. Test fakes may only
|
|
||||||
# implement get(), so keep a small compatibility fallback below.
|
|
||||||
stream = getattr(self._http, "stream", None)
|
|
||||||
if stream is not None:
|
|
||||||
current_url = media_ref
|
|
||||||
for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1):
|
|
||||||
async with stream("GET", current_url, follow_redirects=False) as resp:
|
|
||||||
final_ok, final_err = validate_resolved_url(str(resp.url))
|
|
||||||
if not final_ok:
|
|
||||||
self.logger.warning(
|
|
||||||
"remote media redirect blocked ref={} final={} reason={}",
|
|
||||||
media_ref,
|
|
||||||
resp.url,
|
|
||||||
final_err,
|
|
||||||
)
|
|
||||||
return None, None
|
|
||||||
if 300 <= resp.status_code < 400:
|
|
||||||
next_url = self._next_remote_media_url(
|
|
||||||
str(resp.url), resp.headers.get("location")
|
|
||||||
)
|
|
||||||
if not next_url:
|
|
||||||
return None, None
|
|
||||||
current_url = next_url
|
|
||||||
continue
|
|
||||||
if resp.status_code >= 400:
|
|
||||||
self.logger.warning(
|
|
||||||
"media download failed status={} ref={}",
|
|
||||||
resp.status_code,
|
|
||||||
current_url,
|
|
||||||
)
|
|
||||||
return None, None
|
|
||||||
chunks: list[bytes] = []
|
|
||||||
total = 0
|
|
||||||
async for chunk in resp.aiter_bytes():
|
|
||||||
total += len(chunk)
|
|
||||||
if total > DINGTALK_MAX_REMOTE_MEDIA_BYTES:
|
|
||||||
self.logger.warning(
|
|
||||||
"media download too large ref={} bytes>{}",
|
|
||||||
current_url,
|
|
||||||
DINGTALK_MAX_REMOTE_MEDIA_BYTES,
|
|
||||||
)
|
|
||||||
return None, None
|
|
||||||
chunks.append(chunk)
|
|
||||||
return b"".join(chunks), (resp.headers.get("content-type") or "")
|
|
||||||
self.logger.warning("media download exceeded redirect limit ref={}", media_ref)
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
current_url = media_ref
|
current_url = media_ref
|
||||||
for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1):
|
for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1):
|
||||||
resp = await self._http.get(current_url, follow_redirects=False)
|
async with self._http.stream("GET", current_url, follow_redirects=False) as resp:
|
||||||
final_ok, final_err = validate_resolved_url(str(getattr(resp, "url", current_url)))
|
final_ok, final_err = validate_resolved_url(str(resp.url))
|
||||||
if not final_ok:
|
if not final_ok:
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
"remote media redirect blocked ref={} final={} reason={}",
|
"remote media redirect blocked ref={} final={} reason={}",
|
||||||
media_ref,
|
media_ref,
|
||||||
getattr(resp, "url", current_url),
|
resp.url,
|
||||||
final_err,
|
final_err,
|
||||||
)
|
)
|
||||||
return None, None
|
|
||||||
if 300 <= resp.status_code < 400:
|
|
||||||
next_url = self._next_remote_media_url(
|
|
||||||
str(getattr(resp, "url", current_url)), resp.headers.get("location")
|
|
||||||
)
|
|
||||||
if not next_url:
|
|
||||||
return None, None
|
return None, None
|
||||||
current_url = next_url
|
if 300 <= resp.status_code < 400:
|
||||||
continue
|
next_url = self._next_remote_media_url(
|
||||||
if resp.status_code >= 400:
|
str(resp.url), resp.headers.get("location")
|
||||||
self.logger.warning(
|
)
|
||||||
"media download failed status={} ref={}",
|
if not next_url:
|
||||||
resp.status_code,
|
return None, None
|
||||||
current_url,
|
current_url = next_url
|
||||||
)
|
continue
|
||||||
return None, None
|
if resp.status_code >= 400:
|
||||||
if len(resp.content) > DINGTALK_MAX_REMOTE_MEDIA_BYTES:
|
self.logger.warning(
|
||||||
self.logger.warning(
|
"media download failed status={} ref={}",
|
||||||
"media download too large ref={} bytes>{}",
|
resp.status_code,
|
||||||
current_url,
|
current_url,
|
||||||
DINGTALK_MAX_REMOTE_MEDIA_BYTES,
|
)
|
||||||
)
|
return None, None
|
||||||
return None, None
|
chunks: list[bytes] = []
|
||||||
return resp.content, (resp.headers.get("content-type") or "")
|
total = 0
|
||||||
|
async for chunk in resp.aiter_bytes():
|
||||||
|
total += len(chunk)
|
||||||
|
if total > DINGTALK_MAX_REMOTE_MEDIA_BYTES:
|
||||||
|
self.logger.warning(
|
||||||
|
"media download too large ref={} bytes>{}",
|
||||||
|
current_url,
|
||||||
|
DINGTALK_MAX_REMOTE_MEDIA_BYTES,
|
||||||
|
)
|
||||||
|
return None, None
|
||||||
|
chunks.append(chunk)
|
||||||
|
return b"".join(chunks), (resp.headers.get("content-type") or "")
|
||||||
self.logger.warning("media download exceeded redirect limit ref={}", media_ref)
|
self.logger.warning("media download exceeded redirect limit ref={}", media_ref)
|
||||||
return None, None
|
return None, None
|
||||||
except httpx.TransportError:
|
except httpx.TransportError:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import zipfile
|
import zipfile
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
@@ -45,6 +46,9 @@ class _FakeResponse:
|
|||||||
self.headers = headers or {"content-type": "application/json"}
|
self.headers = headers or {"content-type": "application/json"}
|
||||||
self.url = httpx.URL(url)
|
self.url = httpx.URL(url)
|
||||||
|
|
||||||
|
async def aiter_bytes(self):
|
||||||
|
yield self.content
|
||||||
|
|
||||||
def json(self) -> dict:
|
def json(self) -> dict:
|
||||||
return self._json_body
|
return self._json_body
|
||||||
|
|
||||||
@@ -59,6 +63,11 @@ class _FakeHttp:
|
|||||||
return self._responses.pop(0)
|
return self._responses.pop(0)
|
||||||
return _FakeResponse()
|
return _FakeResponse()
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def stream(self, method, url, **kwargs):
|
||||||
|
assert method == "GET"
|
||||||
|
yield await self.get(url, **kwargs)
|
||||||
|
|
||||||
async def post(self, url: str, json=None, headers=None, **kwargs):
|
async def post(self, url: str, json=None, headers=None, **kwargs):
|
||||||
self.calls.append(
|
self.calls.append(
|
||||||
{"method": "POST", "url": url, "json": json, "headers": headers, "kwargs": kwargs}
|
{"method": "POST", "url": url, "json": json, "headers": headers, "kwargs": kwargs}
|
||||||
@@ -1267,7 +1276,7 @@ async def test_send_media_ref_short_circuits_on_download_transport_error() -> No
|
|||||||
channel = DingTalkChannel(config, MessageBus())
|
channel = DingTalkChannel(config, MessageBus())
|
||||||
|
|
||||||
# First POST (sampleImageMsg) returns API error → False, then GET (download) raises transport error
|
# First POST (sampleImageMsg) returns API error → False, then GET (download) raises transport error
|
||||||
class _MixedHttp:
|
class _MixedHttp(_FakeHttp):
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.calls: list[dict] = []
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
@@ -1299,7 +1308,7 @@ async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None
|
|||||||
|
|
||||||
image_bytes = b"\xff\xd8\xff\xe0" + b"\x00" * 100 # minimal JPEG-ish data
|
image_bytes = b"\xff\xd8\xff\xe0" + b"\x00" * 100 # minimal JPEG-ish data
|
||||||
|
|
||||||
class _UploadFailsHttp:
|
class _UploadFailsHttp(_FakeHttp):
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.calls: list[dict] = []
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
@@ -1326,3 +1335,29 @@ async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None
|
|||||||
# POST (image URL), GET (download), POST (upload) attempted — no further sends
|
# POST (image URL), GET (download), POST (upload) attempted — no further sends
|
||||||
methods = [c["method"] for c in channel._http.calls]
|
methods = [c["method"] for c in channel._http.calls]
|
||||||
assert methods == ["POST", "GET", "POST"]
|
assert methods == ["POST", "GET", "POST"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_remote_media_stops_reading_at_limit_and_closes_stream(monkeypatch):
|
||||||
|
monkeypatch.setattr(dingtalk_module, "DINGTALK_MAX_REMOTE_MEDIA_BYTES", 8)
|
||||||
|
channel = DingTalkChannel(
|
||||||
|
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
|
||||||
|
MessageBus(),
|
||||||
|
)
|
||||||
|
|
||||||
|
class BoundedStream(httpx.AsyncByteStream):
|
||||||
|
closed = False
|
||||||
|
|
||||||
|
async def __aiter__(self):
|
||||||
|
yield b"12345"
|
||||||
|
yield b"6789"
|
||||||
|
raise AssertionError("must stop consuming when the size limit is exceeded")
|
||||||
|
|
||||||
|
async def aclose(self):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
body = BoundedStream()
|
||||||
|
transport = httpx.MockTransport(lambda request: httpx.Response(200, stream=body))
|
||||||
|
async with httpx.AsyncClient(transport=transport) as client:
|
||||||
|
channel._http = client
|
||||||
|
assert await channel._fetch_remote_media_bytes("https://example.com/large") == (None, None)
|
||||||
|
assert body.closed
|
||||||
Reference in new issue
Block a user