"""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', 'Очередь обработки заполнена; повторите загрузку позже')