S3: не падать на синхронном close() у StreamingBody
This commit is contained in:
1 parent
c6b2f0a520
commit
75e49f5a7f
2 files changed
+61
-1
No files matched your search
+9
-1
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import codecs
|
||||
import contextlib
|
||||
import inspect
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime
|
||||
from types import TracebackType
|
||||
@@ -202,7 +203,14 @@ class S3Client:
|
||||
if pending:
|
||||
yield pending
|
||||
finally:
|
||||
await body.close()
|
||||
# В разных версиях aiobotocore/aiohttp close() может быть sync или async.
|
||||
# Ошибка закрытия не должна отменять уже обработанные строки.
|
||||
try:
|
||||
close_result = body.close()
|
||||
if inspect.isawaitable(close_result):
|
||||
await close_result
|
||||
except Exception:
|
||||
logger.warning("Не удалось закрыть поток S3", key=key, exc_info=True)
|
||||
|
||||
async def list_csv_files(self) -> list[str]:
|
||||
"""Возвращает ключи .csv-файлов в bucket/prefix (сначала самые старые)."""
|
||||
|
||||
@@ -392,6 +392,58 @@ async def test_stream_file_lines_multibyte_split_across_chunks(
|
||||
assert lines == ["id,content", "1,привет", "2,мир"]
|
||||
|
||||
|
||||
class SyncCloseBody:
|
||||
"""Мок с синхронным close() (так ведёт себя StreamingBody в некоторых версиях)."""
|
||||
|
||||
def __init__(self, chunks: list[bytes]) -> None:
|
||||
self._chunks = chunks
|
||||
self.closed = False
|
||||
|
||||
def __aiter__(self):
|
||||
async def _iter():
|
||||
for chunk in self._chunks:
|
||||
yield chunk
|
||||
|
||||
return _iter()
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
async def test_stream_file_lines_sync_close(mock_s3_client_obj, settings):
|
||||
"""Синхронный close() не должен вызывать TypeError."""
|
||||
mock_body = SyncCloseBody([b"a,b\nc,d\n"])
|
||||
mock_s3_client_obj.get_object = AsyncMock(return_value={"Body": mock_body})
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
lines = [line async for line in client.stream_file_lines("input/data.csv")]
|
||||
|
||||
assert lines == ["a,b", "c,d"]
|
||||
assert mock_body.closed
|
||||
|
||||
|
||||
async def test_stream_file_lines_close_error_does_not_fail(
|
||||
mock_s3_client_obj, settings
|
||||
):
|
||||
"""Ошибка закрытия потока не отменяет уже прочитанные строки."""
|
||||
|
||||
class BrokenCloseBody(SyncCloseBody):
|
||||
def close(self) -> None:
|
||||
raise RuntimeError("close failed")
|
||||
|
||||
mock_body = BrokenCloseBody([b"line1\nline2\n"])
|
||||
mock_s3_client_obj.get_object = AsyncMock(return_value={"Body": mock_body})
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
lines = [line async for line in client.stream_file_lines("input/data.csv")]
|
||||
|
||||
assert lines == ["line1", "line2"]
|
||||
|
||||
|
||||
# --- Тесты list_csv_files ---
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user