solution
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Доступ к данным PostgreSQL и Redis."""
|
||||
@@ -0,0 +1,99 @@
|
||||
"""SQL-запросы метаданных и журнала; commit выполняется в domain."""
|
||||
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.attachment import Attachment, MessageAttachment, UploadIntent
|
||||
|
||||
|
||||
async def create_attachment(session: AsyncSession, **values) -> Attachment:
|
||||
record = Attachment(**values)
|
||||
session.add(record)
|
||||
await session.flush()
|
||||
return record
|
||||
|
||||
|
||||
async def get_attachment(
|
||||
session: AsyncSession, attachment_id: UUID
|
||||
) -> Attachment | None:
|
||||
return await session.get(Attachment, attachment_id)
|
||||
|
||||
|
||||
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]:
|
||||
records = []
|
||||
if attachment_ids:
|
||||
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)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
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)
|
||||
)
|
||||
for link in rows.scalars():
|
||||
result[link.message_id].append(link.attachment_id)
|
||||
return result
|
||||
|
||||
|
||||
async def reserve_upload(session: AsyncSession, id: UUID, key: str) -> None:
|
||||
session.add(UploadIntent(id=id, object_key=key))
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def lock_upload(session: AsyncSession, id: UUID) -> UploadIntent | None:
|
||||
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)
|
||||
)
|
||||
return list(result)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""RabbitMQ: durable queue, persistent messages, publisher confirms и manual ack."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractIncomingMessage
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
from app.schemas.job import JobMessage
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Delivery:
|
||||
id: AbstractIncomingMessage
|
||||
payload: bytes
|
||||
|
||||
|
||||
class JobBroker:
|
||||
"""Один consumer/канал на экземпляр; publisher использует отдельный экземпляр."""
|
||||
|
||||
def __init__(self, settings: JobSettings) -> None:
|
||||
self.settings = settings
|
||||
self.connection = self.channel = self.queue = self.iterator = None
|
||||
# Transport exceptions могут содержать URL с credentials.
|
||||
logging.getLogger("aio_pika").setLevel(logging.CRITICAL)
|
||||
logging.getLogger("aiormq").setLevel(logging.CRITICAL)
|
||||
|
||||
async def ensure_ready(self) -> None:
|
||||
if (
|
||||
self.connection is None
|
||||
or self.connection.is_closed
|
||||
or self.channel is None
|
||||
or self.channel.is_closed
|
||||
):
|
||||
await self.aclose()
|
||||
self.connection = await aio_pika.connect(
|
||||
host=self.settings.broker_host,
|
||||
port=self.settings.broker_port,
|
||||
login=self.settings.broker_user,
|
||||
password=self.settings.broker_password_file.read_text().strip(),
|
||||
virtualhost=self.settings.broker_vhost,
|
||||
timeout=5,
|
||||
heartbeat=30,
|
||||
)
|
||||
self.channel = await self.connection.channel(
|
||||
publisher_confirms=True, on_return_raises=True
|
||||
)
|
||||
await self.channel.set_qos(prefetch_count=1)
|
||||
self.queue = await self.channel.declare_queue(
|
||||
self.settings.broker_queue, durable=True
|
||||
)
|
||||
|
||||
async def publish_job(self, message: JobMessage) -> None:
|
||||
await self.ensure_ready()
|
||||
headers = {}
|
||||
TraceContextTextMapPropagator().inject(headers)
|
||||
await self.channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=message.model_dump_json(exclude_none=True).encode(),
|
||||
content_type="application/json",
|
||||
headers=headers,
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=f"{message.job_id}:{message.attempt}",
|
||||
),
|
||||
routing_key=self.settings.broker_queue,
|
||||
mandatory=True,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
async def receive(self, consumer: str) -> Delivery:
|
||||
await self.ensure_ready()
|
||||
if self.iterator is None:
|
||||
self.iterator = self.queue.iterator(no_ack=False, consumer_tag=consumer)
|
||||
await self.iterator.__aenter__()
|
||||
message = await self.iterator.__anext__()
|
||||
return Delivery(message, message.body)
|
||||
|
||||
async def acknowledge_job(self, delivery_id: AbstractIncomingMessage) -> None:
|
||||
await delivery_id.ack()
|
||||
|
||||
async def defer_job(self, delivery_id: AbstractIncomingMessage) -> None:
|
||||
# Живая чужая lease: не удерживать единственный prefetch slot навсегда.
|
||||
await asyncio.sleep(self.settings.publisher_poll_seconds)
|
||||
await delivery_id.nack(requeue=True)
|
||||
|
||||
async def reject_invalid(self, delivery_id: AbstractIncomingMessage) -> None:
|
||||
# Failed jobs находятся в PostgreSQL; неизвестные payload не копируются в DLQ.
|
||||
logging.getLogger(__name__).warning("Rejected invalid job envelope")
|
||||
await delivery_id.reject(requeue=False)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
connection = self.connection
|
||||
self.connection = self.channel = self.queue = self.iterator = None
|
||||
if connection is not None and not connection.is_closed:
|
||||
await connection.close()
|
||||
@@ -0,0 +1,67 @@
|
||||
from collections.abc import Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import exists, select, tuple_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.chat import Chat
|
||||
from app.models.chat_member import ChatMember
|
||||
from app.storage.types import Position
|
||||
|
||||
|
||||
async def create_chat(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: Sequence[UUID],
|
||||
) -> Chat:
|
||||
chat = Chat(
|
||||
title=title,
|
||||
members=[ChatMember(user_id=user_id) for user_id in member_ids],
|
||||
)
|
||||
session.add(chat)
|
||||
await session.flush()
|
||||
return chat
|
||||
|
||||
|
||||
async def get_chat_for_member(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> Chat | None:
|
||||
stmt = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
chat = result.scalar_one_or_none()
|
||||
return chat
|
||||
|
||||
|
||||
async def is_chat_member(session: AsyncSession, chat_id: UUID, user_id: UUID) -> bool:
|
||||
stmt = select(
|
||||
exists().where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
is_member = bool(result.scalar_one())
|
||||
return is_member
|
||||
|
||||
|
||||
async def list_chats_for_user(
|
||||
session: AsyncSession,
|
||||
user_id: UUID,
|
||||
after: Position | None,
|
||||
limit: int,
|
||||
) -> list[Chat]:
|
||||
stmt = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user_id)
|
||||
)
|
||||
if after is not None:
|
||||
stmt = stmt.where(tuple_(Chat.created_at, Chat.id) > tuple_(*after))
|
||||
stmt = stmt.order_by(Chat.created_at, Chat.id).limit(limit)
|
||||
result = await session.execute(stmt)
|
||||
chats = list(result.scalars().all())
|
||||
return chats
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Простые проверки соединения с общими хранилищами."""
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
|
||||
|
||||
async def check_database(engine: AsyncEngine) -> bool:
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
|
||||
|
||||
async def check_redis(client: Redis) -> bool:
|
||||
return bool(await client.ping())
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Хранение и блокировка ключей в PostgreSQL."""
|
||||
|
||||
from datetime import timedelta
|
||||
import hashlib
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import BigInteger, func, literal, select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.idempotency_key import IdempotencyKey
|
||||
|
||||
Scope = tuple[UUID, str, str, str]
|
||||
|
||||
|
||||
async def lock_key(session: AsyncSession, scope: Scope) -> None:
|
||||
raw = json.dumps([str(scope[0]), *scope[1:]]).encode()
|
||||
lock_id = int.from_bytes(hashlib.sha256(raw).digest()[:8], signed=True)
|
||||
await session.execute(
|
||||
select(func.pg_advisory_xact_lock(literal(lock_id, type_=BigInteger)))
|
||||
)
|
||||
|
||||
|
||||
async def get_active_key(
|
||||
session: AsyncSession, scope: Scope, ttl_seconds: int
|
||||
) -> IdempotencyKey | None:
|
||||
stmt = select(IdempotencyKey).where(
|
||||
tuple_(
|
||||
IdempotencyKey.user_id,
|
||||
IdempotencyKey.method,
|
||||
IdempotencyKey.path,
|
||||
IdempotencyKey.key,
|
||||
)
|
||||
== tuple_(*scope),
|
||||
IdempotencyKey.created_at
|
||||
> func.clock_timestamp() - timedelta(seconds=ttl_seconds),
|
||||
)
|
||||
return await session.scalar(stmt)
|
||||
|
||||
|
||||
async def save_result(
|
||||
session: AsyncSession, scope: Scope, request_hash: str, message_id: UUID
|
||||
) -> None:
|
||||
stmt = insert(IdempotencyKey).values(
|
||||
user_id=scope[0],
|
||||
method=scope[1],
|
||||
path=scope[2],
|
||||
key=scope[3],
|
||||
request_hash=request_hash,
|
||||
message_id=message_id,
|
||||
)
|
||||
await session.execute(
|
||||
stmt.on_conflict_do_update(
|
||||
index_elements=[
|
||||
IdempotencyKey.user_id,
|
||||
IdempotencyKey.method,
|
||||
IdempotencyKey.path,
|
||||
IdempotencyKey.key,
|
||||
],
|
||||
set_={
|
||||
"request_hash": request_hash,
|
||||
"message_id": message_id,
|
||||
"created_at": func.clock_timestamp(),
|
||||
},
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Операторские выборки и журнал replay; транзакция принадлежит domain."""
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
from app.models.job_replay import JobReplay
|
||||
|
||||
|
||||
async def failed_jobs(session, limit: int):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(Attachment.status == "failed")
|
||||
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id)
|
||||
.limit(limit)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
async def replay_record(session, request_id):
|
||||
return await session.get(JobReplay, request_id)
|
||||
|
||||
|
||||
async def insert_replay(session, **values) -> bool:
|
||||
result = await session.scalar(
|
||||
insert(JobReplay)
|
||||
.values(**values)
|
||||
.on_conflict_do_nothing(index_elements=[JobReplay.id])
|
||||
.returning(JobReplay.id)
|
||||
)
|
||||
return result is not None
|
||||
|
||||
|
||||
async def replay_history(session, job_id):
|
||||
return (
|
||||
await session.scalars(
|
||||
select(JobReplay)
|
||||
.where(JobReplay.job_id == job_id)
|
||||
.order_by(JobReplay.created_at)
|
||||
.limit(100)
|
||||
)
|
||||
).all()
|
||||
|
||||
|
||||
def reset_failed(job, attachment, now, attempt_limit):
|
||||
job.cycle_start_attempt = job.attempt
|
||||
job.attempt_limit = attempt_limit
|
||||
job.published_attempt = job.attempt
|
||||
job.next_attempt_at = now
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.finished_at = None
|
||||
job.last_error_code = None
|
||||
job.last_error_permanent = None
|
||||
attachment.status = "queued"
|
||||
attachment.error_code = None
|
||||
attachment.updated_at = now
|
||||
@@ -0,0 +1,182 @@
|
||||
"""SQL и изменения jobs/attachments; commit остаётся в domain."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from sqlalchemy import and_, or_, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
from app.schemas.attachment import VARIANT_FILENAMES
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JobWork:
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
lease_token: UUID
|
||||
pipeline_version: int
|
||||
staging_key: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
|
||||
@property
|
||||
def original_key(self) -> str:
|
||||
return f"originals/{self.attachment_id.hex}/v{self.pipeline_version}"
|
||||
|
||||
def variant_key(self, name: str) -> str:
|
||||
filename = VARIANT_FILENAMES[name]
|
||||
return f"variants/{self.attachment_id.hex}/v{self.pipeline_version}/{filename}"
|
||||
|
||||
|
||||
async def create_job(
|
||||
session: AsyncSession, attachment_id: UUID, staging_key: str
|
||||
) -> UUID:
|
||||
carrier = {}
|
||||
TraceContextTextMapPropagator().inject(carrier)
|
||||
job = AttachmentJob(
|
||||
attachment_id=attachment_id,
|
||||
staging_key=staging_key,
|
||||
trace_context=carrier or None,
|
||||
)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
return job.id
|
||||
|
||||
|
||||
async def lock_job(session: AsyncSession, job_id: UUID):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.with_for_update(of=AttachmentJob)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
return result.one_or_none()
|
||||
|
||||
|
||||
async def database_time(session: AsyncSession) -> datetime:
|
||||
return await session.scalar(select(func.clock_timestamp()))
|
||||
|
||||
|
||||
async def queued_backlog(session: AsyncSession) -> tuple[int, float]:
|
||||
count, oldest = (
|
||||
await session.execute(
|
||||
select(func.count(), func.min(AttachmentJob.created_at))
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(Attachment.status == "queued")
|
||||
)
|
||||
).one()
|
||||
return count, (
|
||||
max(0, ((await database_time(session)) - oldest).total_seconds())
|
||||
if oldest
|
||||
else 0.0
|
||||
)
|
||||
|
||||
|
||||
async def expired_jobs(session: AsyncSession, limit: int = 20):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(
|
||||
Attachment.status == "processing",
|
||||
AttachmentJob.lease_until < func.clock_timestamp(),
|
||||
)
|
||||
.order_by(AttachmentJob.lease_until)
|
||||
.limit(limit)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
def start_job(
|
||||
job, attachment, token: UUID, now: datetime, lease_seconds: int
|
||||
) -> JobWork:
|
||||
job.attempt += 1
|
||||
job.lease_token = token
|
||||
job.lease_until = now + timedelta(seconds=lease_seconds)
|
||||
attachment.status = "processing"
|
||||
attachment.updated_at = now
|
||||
return JobWork(
|
||||
job.id,
|
||||
attachment.id,
|
||||
token,
|
||||
job.pipeline_version,
|
||||
job.staging_key,
|
||||
attachment.content_type,
|
||||
attachment.size_bytes,
|
||||
attachment.sha256,
|
||||
)
|
||||
|
||||
|
||||
def record_failure(
|
||||
job,
|
||||
attachment,
|
||||
now: datetime,
|
||||
error_code: str,
|
||||
*,
|
||||
terminal: bool,
|
||||
retry_seconds: float,
|
||||
) -> None:
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.last_error_code = error_code
|
||||
job.next_attempt_at = now + timedelta(seconds=retry_seconds)
|
||||
job.finished_at = now if terminal else None
|
||||
attachment.status = "failed" if terminal else "queued"
|
||||
attachment.error_code = error_code if terminal else None
|
||||
attachment.updated_at = now
|
||||
|
||||
|
||||
def complete_job(
|
||||
job, attachment, work: JobWork, variants: list[dict], now: datetime
|
||||
) -> None:
|
||||
attachment.object_key = work.original_key
|
||||
attachment.thumbnail_key = work.variant_key("thumbnail")
|
||||
attachment.crop_key = work.variant_key("crop")
|
||||
attachment.optimized_key = work.variant_key("optimized")
|
||||
attachment.variants = variants
|
||||
attachment.status = "ready"
|
||||
attachment.error_code = None
|
||||
attachment.updated_at = now
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.last_error_code = None
|
||||
job.last_error_permanent = None
|
||||
job.finished_at = now
|
||||
|
||||
|
||||
async def terminal_staging(
|
||||
session: AsyncSession, retention: int, failed_retention: int, limit: int = 20
|
||||
):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(
|
||||
AttachmentJob.staging_key.is_not(None),
|
||||
or_(
|
||||
and_(
|
||||
Attachment.status == "ready",
|
||||
AttachmentJob.finished_at
|
||||
< func.clock_timestamp() - timedelta(seconds=retention),
|
||||
),
|
||||
and_(
|
||||
Attachment.status == "failed",
|
||||
AttachmentJob.finished_at
|
||||
< func.clock_timestamp() - timedelta(seconds=failed_retention),
|
||||
),
|
||||
),
|
||||
)
|
||||
.order_by(AttachmentJob.finished_at)
|
||||
.limit(limit)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
def clear_staging(job) -> None:
|
||||
job.staging_key = None
|
||||
@@ -0,0 +1,59 @@
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.counter import Counter
|
||||
from app.models.message import Message
|
||||
from app.storage.types import Position
|
||||
|
||||
MESSAGES_COUNTER = "messages"
|
||||
|
||||
|
||||
async def get_message(session: AsyncSession, message_id: UUID) -> Message | None:
|
||||
return await session.get(Message, message_id)
|
||||
|
||||
|
||||
async def create_message(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
) -> Message:
|
||||
message = Message(chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
session.add(message)
|
||||
await session.flush()
|
||||
return message
|
||||
|
||||
|
||||
async def list_messages(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
after: Position | None,
|
||||
limit: int,
|
||||
) -> list[Message]:
|
||||
stmt = select(Message).where(Message.chat_id == chat_id)
|
||||
if after is not None:
|
||||
stmt = stmt.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
|
||||
stmt = stmt.order_by(Message.created_at, Message.id).limit(limit)
|
||||
result = await session.execute(stmt)
|
||||
messages = list(result.scalars().all())
|
||||
return messages
|
||||
|
||||
|
||||
async def reserve_message_slot(session: AsyncSession, max_messages: int) -> bool:
|
||||
stmt = (
|
||||
insert(Counter)
|
||||
.values(name=MESSAGES_COUNTER, value=1)
|
||||
.on_conflict_do_update(
|
||||
index_elements=[Counter.name],
|
||||
set_={"value": Counter.value + 1},
|
||||
where=Counter.value < max_messages,
|
||||
)
|
||||
.returning(Counter.value)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
is_reserved = result.scalar_one_or_none() is not None
|
||||
return is_reserved
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Jobs одновременно хранят намерение публикации очередной попытки."""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
|
||||
|
||||
async def next_unpublished_job(
|
||||
session: AsyncSession, *, attachment_id: UUID | None = None
|
||||
) -> AttachmentJob | None:
|
||||
statement = (
|
||||
select(AttachmentJob)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(
|
||||
Attachment.status == "queued",
|
||||
AttachmentJob.next_attempt_at <= func.clock_timestamp(),
|
||||
AttachmentJob.published_attempt <= AttachmentJob.attempt,
|
||||
)
|
||||
.order_by(AttachmentJob.next_attempt_at, AttachmentJob.id)
|
||||
.limit(1)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
)
|
||||
if attachment_id is not None:
|
||||
statement = statement.where(AttachmentJob.attachment_id == attachment_id)
|
||||
return await session.scalar(statement)
|
||||
|
||||
|
||||
def mark_published(job: AttachmentJob) -> None:
|
||||
job.published_attempt = job.attempt + 1
|
||||
@@ -0,0 +1,180 @@
|
||||
"""MinIO SDK выполняется в потоках; ресурсы живут до конца операции."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TypeVar
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from anyio import CancelScope
|
||||
from minio import Minio
|
||||
import urllib3
|
||||
|
||||
from app.core.s3 import S3Settings
|
||||
|
||||
T = TypeVar("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:
|
||||
result = await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
with CancelScope(shield=True):
|
||||
await settle_cancelled_call(task, discard_result)
|
||||
raise
|
||||
return result
|
||||
|
||||
|
||||
async def settle_cancelled_call(
|
||||
task: asyncio.Task, discard_result: Callable | None
|
||||
) -> None:
|
||||
"""wait не переносит исключение SDK; повторная отмена не прерывает компенсацию."""
|
||||
while not task.done():
|
||||
with suppress(asyncio.CancelledError):
|
||||
await asyncio.wait([task])
|
||||
completed = not task.cancelled() and task.exception() is None
|
||||
if completed and discard_result is not None:
|
||||
discard_result(task.result())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ObjectInfo:
|
||||
"""Поля S3 сохраняют необязательность SDK; согласованность проверяет domain."""
|
||||
|
||||
key: str
|
||||
size_bytes: int | None
|
||||
content_type: str | None
|
||||
last_modified: datetime | None
|
||||
|
||||
|
||||
def close_response(response) -> None:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
|
||||
class ObjectStream:
|
||||
"""Закрывается даже если StreamingResponse не успел начать итерацию."""
|
||||
|
||||
def __init__(self, storage, response):
|
||||
self.storage = storage
|
||||
self.response = response
|
||||
self.deadline = time.monotonic() + storage.settings.download_timeout_seconds
|
||||
self.closed = False
|
||||
|
||||
def __aiter__(self):
|
||||
return self
|
||||
|
||||
async def __anext__(self):
|
||||
if self.closed:
|
||||
raise StopAsyncIteration
|
||||
try:
|
||||
remaining = self.deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError
|
||||
async with asyncio.timeout(remaining):
|
||||
chunk = await self.storage._call(
|
||||
lambda: self.response.read(self.storage.settings.chunk_bytes)
|
||||
)
|
||||
if not chunk:
|
||||
await self.aclose()
|
||||
raise StopAsyncIteration
|
||||
except BaseException:
|
||||
await self.aclose()
|
||||
raise
|
||||
return chunk
|
||||
|
||||
async def aclose(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
close_response(self.response)
|
||||
|
||||
|
||||
class MinioStorage:
|
||||
def __init__(self, settings: S3Settings) -> None:
|
||||
self.settings = settings
|
||||
|
||||
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,
|
||||
)
|
||||
self._health_http = urllib3.PoolManager(
|
||||
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,
|
||||
access_key=settings.access_key_id_file.read_text().strip(),
|
||||
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:
|
||||
def put():
|
||||
with path.open("rb") as source:
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
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,
|
||||
)
|
||||
return ObjectStream(self, response)
|
||||
|
||||
async def stat_object(self, key: str) -> ObjectInfo:
|
||||
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
|
||||
)
|
||||
return status == 200
|
||||
|
||||
async def aclose(self) -> None:
|
||||
self._http.clear()
|
||||
self._health_http.clear()
|
||||
|
||||
|
||||
def create_s3_storage(settings: S3Settings) -> MinioStorage:
|
||||
return MinioStorage(settings)
|
||||
@@ -0,0 +1,34 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
|
||||
SESSION_KEY_PREFIX = "session:"
|
||||
|
||||
|
||||
def session_key(token_hash: str) -> str:
|
||||
return f"{SESSION_KEY_PREFIX}{token_hash}"
|
||||
|
||||
|
||||
async def create_session(
|
||||
redis: Redis,
|
||||
*,
|
||||
token_hash: str,
|
||||
user_id: UUID,
|
||||
expires_at: datetime,
|
||||
) -> None:
|
||||
await redis.set(session_key(token_hash), str(user_id), pxat=expires_at)
|
||||
|
||||
|
||||
async def get_session_user_id(redis: Redis, token_hash: str) -> UUID | None:
|
||||
raw_user_id = await redis.get(session_key(token_hash))
|
||||
if isinstance(raw_user_id, bytes):
|
||||
raw_user_id = raw_user_id.decode()
|
||||
user_id = UUID(raw_user_id) if raw_user_id else None
|
||||
return user_id
|
||||
|
||||
|
||||
async def delete_session(redis: Redis, token_hash: str) -> bool:
|
||||
deleted_count = await redis.delete(session_key(token_hash))
|
||||
is_deleted = deleted_count > 0
|
||||
return is_deleted
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Общие типы слоя хранения."""
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
Position = tuple[datetime, UUID]
|
||||
@@ -0,0 +1,43 @@
|
||||
from collections.abc import Collection
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
async def create_user(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password_hash: str,
|
||||
) -> User:
|
||||
user = User(
|
||||
username=username, display_name=display_name, password_hash=password_hash
|
||||
)
|
||||
session.add(user)
|
||||
await session.flush()
|
||||
return user
|
||||
|
||||
|
||||
async def get_user_by_id(session: AsyncSession, user_id: UUID) -> User | None:
|
||||
user = await session.get(User, user_id)
|
||||
return user
|
||||
|
||||
|
||||
async def get_user_by_username(session: AsyncSession, username: str) -> User | None:
|
||||
stmt = select(User).where(User.username == username)
|
||||
result = await session.execute(stmt)
|
||||
user = result.scalar_one_or_none()
|
||||
return user
|
||||
|
||||
|
||||
async def get_existing_user_ids(
|
||||
session: AsyncSession, user_ids: Collection[UUID]
|
||||
) -> set[UUID]:
|
||||
stmt = select(User.id).where(User.id.in_(user_ids))
|
||||
result = await session.execute(stmt)
|
||||
existing_ids = set(result.scalars().all())
|
||||
return existing_ids
|
||||
Reference in New Issue
Block a user