Grade 5
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
"""A shared admission limit for unfinished attachments across all API replicas."""
|
||||
import os
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .errors import APIError
|
||||
from .models import Attachment
|
||||
|
||||
MAX_PENDING = int(os.getenv('MAX_PENDING_ATTACHMENTS', '64'))
|
||||
if MAX_PENDING < 1:
|
||||
raise ValueError('MAX_PENDING_ATTACHMENTS must be positive')
|
||||
|
||||
|
||||
def reserve_capacity(session):
|
||||
# Keep the lock until the new queued row commits. Counting without this lock
|
||||
# would allow simultaneous uploads on different replicas to exceed the limit.
|
||||
session.execute(select(func.pg_advisory_xact_lock(202605)))
|
||||
count = session.scalar(select(func.count()).select_from(Attachment).where(
|
||||
Attachment.status.in_(['queued', 'processing'])))
|
||||
if count >= MAX_PENDING:
|
||||
raise APIError(429, 'rate_limited', 'Очередь обработки заполнена; повторите загрузку позже')
|
||||
@@ -6,6 +6,7 @@ from PIL import Image, UnidentifiedImageError
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .errors import APIError
|
||||
from .admission import reserve_capacity
|
||||
from .models import Attachment, AttachmentJob, ChatMember
|
||||
from .object_storage import BUCKET, PREFIX, s3_client
|
||||
from .store import ensure_uuid, serialize, store
|
||||
@@ -61,6 +62,7 @@ def save_attachment(source, chat_id, actor_id, filename, content_type, size, dig
|
||||
staging_key = 'staging/' + attachment_id
|
||||
with store.sessions.begin() as session:
|
||||
store._chat(session, chat_id, actor_id)
|
||||
reserve_capacity(session)
|
||||
lock_object(session, staging_key)
|
||||
s3_client().put_object(Bucket=BUCKET, Key=staging_key, Body=source,
|
||||
ContentLength=size, ContentType=content_type)
|
||||
|
||||
@@ -14,6 +14,7 @@ from sqlalchemy import and_, or_, select
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from .database import create_db_engine
|
||||
from .admission import reserve_capacity
|
||||
from .models import Attachment, AttachmentJob
|
||||
from .object_storage import BUCKET, s3_client
|
||||
|
||||
@@ -96,6 +97,8 @@ def claim(sessions, message):
|
||||
if attachment.status != 'queued' or job.available_at > now():
|
||||
return None
|
||||
job.attempt += 1
|
||||
if job.first_started_at is None:
|
||||
job.first_started_at = now()
|
||||
job.lease_token = str(uuid4())
|
||||
job.lease_until = now() + timedelta(seconds=LEASE_SECONDS)
|
||||
attachment.status = 'processing'
|
||||
@@ -124,6 +127,7 @@ def replay(sessions, job_id, reason):
|
||||
if not attachment.staging_key:
|
||||
raise ValueError('Staging retention expired; upload the file again')
|
||||
s3_client().head_object(Bucket=BUCKET, Key=attachment.staging_key)
|
||||
reserve_capacity(session)
|
||||
job.replay_audit = job.replay_audit + [{'at': now().isoformat(), 'reason': reason,
|
||||
'after_attempt': job.attempt,
|
||||
'last_error': job.last_error}]
|
||||
|
||||
@@ -90,6 +90,7 @@ class AttachmentJob(Base):
|
||||
attempt: Mapped[int] = mapped_column(BigInteger, server_default='0')
|
||||
failures: Mapped[int] = mapped_column(BigInteger, server_default='0')
|
||||
last_error: Mapped[str | None] = mapped_column(Text)
|
||||
first_started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
Reference in New Issue
Block a user