level 5 track 1

This commit is contained in:
2026-11-22 19:20:51 +03:00
parent 813fc03da5
commit b3a8b2e4e0
8 changed files with 619 additions and 10 deletions
+5
View File
@@ -102,6 +102,11 @@ def worker_concurrency() -> int:
return _bounded_int('WORKER_CONCURRENCY', 1, 8)
def max_inflight_jobs() -> int:
"""How many queued plus processing attachments may exist. The next upload is 429."""
return _bounded_int('MAX_INFLIGHT_JOBS', 20, 100000)
def _bounded_float(name: str, default: float, upper: float) -> float:
raw = os.getenv(name, '').strip()
try:
+4
View File
@@ -33,5 +33,9 @@ def unsupported_media_type(message: str) -> ApiError:
return ApiError(415, 'unsupported_media_type', message)
def rate_limited(message: str) -> ApiError:
return ApiError(429, 'rate_limited', message)
def unavailable(message: str) -> ApiError:
return ApiError(503, 'unavailable', message)
+23 -2
View File
@@ -11,8 +11,8 @@ from typing import BinaryIO, Dict, List, Optional, Sequence, Tuple
import asyncpg
from .config import job_max_attempts
from .errors import conflict, invalid_request, not_found, unavailable
from .config import job_max_attempts, max_inflight_jobs
from .errors import conflict, invalid_request, not_found, rate_limited, unavailable
from .jobs import PIPELINE_VERSION, original_key, staging_key
from .migrate import expected_versions
from .objects import MissingObject, ObjectStore, StorageError
@@ -435,6 +435,10 @@ class Store:
staged = staging_key(str(attachment_id))
final = original_key(str(attachment_id))
created = self._now()
# Reject before the object is stored when the cap is already reached.
# The transaction below locks and counts again, so concurrent uploads cannot all slip in.
if await self._inflight_jobs() >= max_inflight_jobs():
raise rate_limited('Очередь заполнена, новая работа не принята')
try:
await asyncio.to_thread(self._objects.put_stream, staged, body, size_bytes, content_type)
except StorageError:
@@ -443,6 +447,7 @@ class Store:
try:
async with self._pool.acquire() as conn:
async with conn.transaction():
await self._admit_job(conn)
await conn.execute(
'''
INSERT INTO attachments (
@@ -665,6 +670,22 @@ class Store:
raise unavailable('Хранилище недоступно')
return row['content_type'], body
async def _inflight_jobs(self) -> int:
async with self._pool.acquire() as conn:
value = await conn.fetchval(
"SELECT count(*)::int FROM attachments WHERE status IN ('queued', 'processing')"
)
return int(value or 0)
async def _admit_job(self, conn) -> None:
"""One lock for the cap. Held only until this transaction commits or rolls back."""
await conn.execute('SELECT pg_advisory_xact_lock($1)', 48151)
inflight = await conn.fetchval(
"SELECT count(*)::int FROM attachments WHERE status IN ('queued', 'processing')"
)
if int(inflight or 0) >= max_inflight_jobs():
raise rate_limited('Очередь заполнена, новая работа не принята')
async def _discard_object(self, object_key: str) -> None:
try:
await asyncio.to_thread(self._objects.delete, object_key)