fix s3 storage
This commit is contained in:
+45
-16
@@ -16,7 +16,9 @@ async def create_attachment(session: AsyncSession, **values) -> Attachment:
|
||||
return record
|
||||
|
||||
|
||||
async def get_attachment(session: AsyncSession, attachment_id: UUID) -> Attachment | None:
|
||||
async def get_attachment(
|
||||
session: AsyncSession, attachment_id: UUID
|
||||
) -> Attachment | None:
|
||||
return await session.get(Attachment, attachment_id)
|
||||
|
||||
|
||||
@@ -24,27 +26,43 @@ async def get_by_key(session: AsyncSession, key: str) -> Attachment | None:
|
||||
return await session.scalar(select(Attachment).where(Attachment.object_key == key))
|
||||
|
||||
|
||||
async def get_for_chat(session: AsyncSession, chat_id: UUID, attachment_ids: list[UUID]) -> list[Attachment]:
|
||||
async def get_for_chat(
|
||||
session: AsyncSession, chat_id: UUID, attachment_ids: list[UUID]
|
||||
) -> list[Attachment]:
|
||||
records = []
|
||||
if attachment_ids:
|
||||
records = list(await session.scalars(select(Attachment).where(
|
||||
Attachment.id.in_(attachment_ids), Attachment.chat_id == chat_id,
|
||||
)))
|
||||
records = list(
|
||||
await session.scalars(
|
||||
select(Attachment).where(
|
||||
Attachment.id.in_(attachment_ids),
|
||||
Attachment.chat_id == chat_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
async def bind_attachments(session: AsyncSession, message_id: UUID, attachment_ids: list[UUID]) -> None:
|
||||
session.add_all(MessageAttachment(message_id=message_id, attachment_id=id, position=position)
|
||||
for position, id in enumerate(attachment_ids))
|
||||
async def bind_attachments(
|
||||
session: AsyncSession, message_id: UUID, attachment_ids: list[UUID]
|
||||
) -> None:
|
||||
session.add_all(
|
||||
MessageAttachment(message_id=message_id, attachment_id=id, position=position)
|
||||
for position, id in enumerate(attachment_ids)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def message_attachment_ids(session: AsyncSession, message_ids: list[UUID]) -> dict[UUID, list[UUID]]:
|
||||
async def message_attachment_ids(
|
||||
session: AsyncSession, message_ids: list[UUID]
|
||||
) -> dict[UUID, list[UUID]]:
|
||||
result: dict[UUID, list[UUID]] = {id: [] for id in message_ids}
|
||||
if not message_ids:
|
||||
return result
|
||||
rows = await session.execute(select(MessageAttachment).where(
|
||||
MessageAttachment.message_id.in_(message_ids)).order_by(MessageAttachment.position))
|
||||
rows = await session.execute(
|
||||
select(MessageAttachment)
|
||||
.where(MessageAttachment.message_id.in_(message_ids))
|
||||
.order_by(MessageAttachment.position)
|
||||
)
|
||||
for link in rows.scalars():
|
||||
result[link.message_id].append(link.attachment_id)
|
||||
return result
|
||||
@@ -56,15 +74,26 @@ async def reserve_upload(session: AsyncSession, id: UUID, key: str) -> None:
|
||||
|
||||
|
||||
async def lock_upload(session: AsyncSession, id: UUID) -> UploadIntent | None:
|
||||
return await session.scalar(select(UploadIntent).where(UploadIntent.id == id).with_for_update())
|
||||
return await session.scalar(
|
||||
select(UploadIntent).where(UploadIntent.id == id).with_for_update()
|
||||
)
|
||||
|
||||
|
||||
async def finish_upload(session: AsyncSession, id: UUID) -> None:
|
||||
await session.execute(delete(UploadIntent).where(UploadIntent.id == id))
|
||||
|
||||
|
||||
async def stale_uploads(session: AsyncSession, grace_seconds: int, limit: int) -> list[UploadIntent]:
|
||||
result = await session.scalars(select(UploadIntent).where(
|
||||
UploadIntent.created_at < func.clock_timestamp() - timedelta(seconds=grace_seconds),
|
||||
).order_by(UploadIntent.created_at).limit(limit).with_for_update(skip_locked=True))
|
||||
async def stale_uploads(
|
||||
session: AsyncSession, grace_seconds: int, limit: int
|
||||
) -> list[UploadIntent]:
|
||||
result = await session.scalars(
|
||||
select(UploadIntent)
|
||||
.where(
|
||||
UploadIntent.created_at
|
||||
< func.clock_timestamp() - timedelta(seconds=grace_seconds),
|
||||
)
|
||||
.order_by(UploadIntent.created_at)
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
return list(result)
|
||||
|
||||
+48
-19
@@ -19,7 +19,9 @@ from app.core.s3 import S3Settings
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
async def run_sync(operation: Callable[..., T], *args, discard_result=None, **kwargs) -> T:
|
||||
async def run_sync(
|
||||
operation: Callable[..., T], *args, discard_result=None, **kwargs
|
||||
) -> T:
|
||||
"""При отмене дождаться потока: иначе PUT может догнать компенсацию удаления."""
|
||||
task = asyncio.create_task(asyncio.to_thread(operation, *args, **kwargs))
|
||||
try:
|
||||
@@ -31,7 +33,9 @@ async def run_sync(operation: Callable[..., T], *args, discard_result=None, **kw
|
||||
return result
|
||||
|
||||
|
||||
async def settle_cancelled_call(task: asyncio.Task, discard_result: Callable | None) -> None:
|
||||
async def settle_cancelled_call(
|
||||
task: asyncio.Task, discard_result: Callable | None
|
||||
) -> None:
|
||||
"""wait не переносит исключение SDK; повторная отмена не прерывает компенсацию."""
|
||||
while not task.done():
|
||||
with suppress(asyncio.CancelledError):
|
||||
@@ -43,10 +47,12 @@ async def settle_cancelled_call(task: asyncio.Task, discard_result: Callable | N
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ObjectInfo:
|
||||
"""Поля S3 сохраняют необязательность SDK; согласованность проверяет domain."""
|
||||
|
||||
key: str
|
||||
size_bytes: int
|
||||
content_type: str
|
||||
last_modified: datetime
|
||||
size_bytes: int | None
|
||||
content_type: str | None
|
||||
last_modified: datetime | None
|
||||
|
||||
|
||||
def close_response(response) -> None:
|
||||
@@ -74,7 +80,9 @@ class ObjectStream:
|
||||
if remaining <= 0:
|
||||
raise TimeoutError
|
||||
async with asyncio.timeout(remaining):
|
||||
chunk = await self.storage._call(lambda: self.response.read(self.storage.settings.chunk_bytes))
|
||||
chunk = await self.storage._call(
|
||||
lambda: self.response.read(self.storage.settings.chunk_bytes)
|
||||
)
|
||||
if not chunk:
|
||||
await self.aclose()
|
||||
raise StopAsyncIteration
|
||||
@@ -95,35 +103,52 @@ class MinioStorage:
|
||||
# Клиент создаётся в event loop один раз, не конкурентно в worker threads.
|
||||
url = urlsplit(settings.endpoint)
|
||||
self._http = urllib3.PoolManager(
|
||||
timeout=urllib3.Timeout(connect=settings.connect_timeout_seconds, read=settings.read_timeout_seconds),
|
||||
retries=urllib3.Retry(total=0), maxsize=32,
|
||||
timeout=urllib3.Timeout(
|
||||
connect=settings.connect_timeout_seconds,
|
||||
read=settings.read_timeout_seconds,
|
||||
),
|
||||
retries=urllib3.Retry(total=0),
|
||||
maxsize=32,
|
||||
)
|
||||
self._health_http = urllib3.PoolManager(
|
||||
timeout=urllib3.Timeout(connect=0.25, read=0.5), retries=urllib3.Retry(total=0),
|
||||
timeout=urllib3.Timeout(connect=0.25, read=0.5),
|
||||
retries=urllib3.Retry(total=0),
|
||||
)
|
||||
self._client = Minio(
|
||||
url.netloc, secure=url.scheme == "https", region=settings.region,
|
||||
url.netloc,
|
||||
secure=url.scheme == "https",
|
||||
region=settings.region,
|
||||
access_key=settings.access_key_id_file.read_text().strip(),
|
||||
secret_key=settings.secret_access_key_file.read_text().strip(), http_client=self._http,
|
||||
secret_key=settings.secret_access_key_file.read_text().strip(),
|
||||
http_client=self._http,
|
||||
)
|
||||
|
||||
async def _call(self, operation: Callable, *, discard_result=None):
|
||||
return await run_sync(operation, discard_result=discard_result)
|
||||
|
||||
async def put_file(self, key: str, path: Path, *, size_bytes: int, content_type: str, sha256: str) -> None:
|
||||
async def put_file(
|
||||
self, key: str, path: Path, *, size_bytes: int, content_type: str, sha256: str
|
||||
) -> None:
|
||||
def put():
|
||||
with path.open("rb") as source:
|
||||
# Один PUT: размер части равен максимальному разрешённому файлу.
|
||||
self._client.put_object(
|
||||
self.settings.bucket, key, source, size_bytes,
|
||||
content_type=content_type, metadata={"sha256": sha256},
|
||||
part_size=10_485_760, num_parallel_uploads=1,
|
||||
self.settings.bucket,
|
||||
key,
|
||||
source,
|
||||
size_bytes,
|
||||
content_type=content_type,
|
||||
metadata={"sha256": sha256},
|
||||
part_size=10_485_760,
|
||||
num_parallel_uploads=1,
|
||||
)
|
||||
|
||||
await self._call(put)
|
||||
|
||||
async def open_object(self, key: str) -> ObjectStream:
|
||||
response = await self._call(
|
||||
lambda: self._client.get_object(self.settings.bucket, key), discard_result=close_response,
|
||||
lambda: self._client.get_object(self.settings.bucket, key),
|
||||
discard_result=close_response,
|
||||
)
|
||||
return ObjectStream(self, response)
|
||||
|
||||
@@ -131,15 +156,19 @@ class MinioStorage:
|
||||
def stat():
|
||||
info = self._client.stat_object(self.settings.bucket, key)
|
||||
return ObjectInfo(key, info.size, info.content_type, info.last_modified)
|
||||
|
||||
return await self._call(stat)
|
||||
|
||||
async def delete_object(self, key: str) -> None:
|
||||
await self._call(lambda: self._client.remove_object(self.settings.bucket, key))
|
||||
|
||||
async def check_available(self) -> bool:
|
||||
status = await self._call(lambda: self._health_http.request(
|
||||
"GET", self.settings.endpoint.rstrip("/") + "/minio/health/ready",
|
||||
).status)
|
||||
status = await self._call(
|
||||
lambda: self._health_http.request(
|
||||
"GET",
|
||||
self.settings.endpoint.rstrip("/") + "/minio/health/ready",
|
||||
).status
|
||||
)
|
||||
return status == 200
|
||||
|
||||
async def aclose(self) -> None:
|
||||
|
||||
Reference in New Issue
Block a user