forked from mtusi2026/mtusi2026lab5
level 5 track 1
This commit is contained in:
+23
-2
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user