forked from mtusi2026/mtusi2026lab5
add level 5
This commit is contained in:
@@ -87,6 +87,13 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
# Disabled by default; models a crash after PUT, before INSERT.
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
try:
|
||||
max_pending = int(os.environ.get("MAX_PENDING_JOBS", "100"))
|
||||
except ValueError as error:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит очереди") from error
|
||||
if max_pending < 1:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит очереди")
|
||||
await store.ensure_attachment_queue_capacity(connection, max_pending)
|
||||
attachment = await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key, job_id, connection=connection,
|
||||
|
||||
@@ -346,6 +346,18 @@ class PostgresStore:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return dict(row)
|
||||
|
||||
async def ensure_attachment_queue_capacity(self, connection: asyncpg.Connection, maximum: int) -> None:
|
||||
"""Globally serialize admission so replicas cannot over-accept queued work."""
|
||||
try:
|
||||
await connection.execute("SELECT pg_advisory_xact_lock(41005, 1)")
|
||||
pending = await connection.fetchval(
|
||||
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued', 'processing')"
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if pending >= maximum:
|
||||
raise ApiError(429, "rate_limited", "Очередь обработки заполнена")
|
||||
|
||||
async def attachment_for_member(self, attachment_id: UUID, user_id: UUID) -> dict:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
|
||||
+38
-17
@@ -6,6 +6,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import UUID
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
@@ -87,29 +88,45 @@ async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_second
|
||||
|
||||
def main() -> None:
|
||||
settings = load_settings()
|
||||
store = PostgresStore(settings.database_url)
|
||||
asyncio.run(store.connect())
|
||||
s3 = S3Store(S3Settings.load())
|
||||
connection = _connection()
|
||||
channel = connection.channel()
|
||||
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_CONCURRENCY", "2"))))
|
||||
workers = max(1, int(os.environ.get("WORKER_CONCURRENCY", "2")))
|
||||
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_PREFETCH", str(workers)))))
|
||||
|
||||
def consume(ch, method, properties, body):
|
||||
del properties
|
||||
async def handle_async(payload):
|
||||
"""Each executor thread owns its event loop and its DB/S3 clients."""
|
||||
store = PostgresStore(settings.database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await store.connect()
|
||||
try:
|
||||
await process(store, s3, payload, max(1, int(os.environ.get("JOB_TIMEOUT_SECONDS", "60"))))
|
||||
finally:
|
||||
s3.client.close()
|
||||
await store.close()
|
||||
|
||||
async def schedule_retry(attachment_id, delay):
|
||||
retry_store = PostgresStore(settings.database_url)
|
||||
await retry_store.connect()
|
||||
try:
|
||||
return await retry_store.retry_attachment_job(
|
||||
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay
|
||||
)
|
||||
finally:
|
||||
await retry_store.close()
|
||||
|
||||
def handle(body):
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
|
||||
raise ValueError("unexpected broker payload")
|
||||
asyncio.run(process(store, s3, payload, max(1, int(os.environ.get("JOB_TIMEOUT_SECONDS", "60")))))
|
||||
asyncio.run(handle_async(payload))
|
||||
except Exception:
|
||||
logging.exception("job failed")
|
||||
try:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
attempt = int(payload.get("attempt", 1))
|
||||
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
|
||||
retry = asyncio.run(store.retry_attachment_job(
|
||||
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay
|
||||
))
|
||||
retry = asyncio.run(schedule_retry(attachment_id, delay))
|
||||
except Exception:
|
||||
retry = False
|
||||
if not retry:
|
||||
@@ -117,17 +134,21 @@ def main() -> None:
|
||||
asyncio.run(publish_dlq(payload))
|
||||
except Exception:
|
||||
logging.exception("could not publish failed job to DLQ")
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
else:
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return None
|
||||
|
||||
def consume(ch, method, properties, body):
|
||||
del properties
|
||||
future = executor.submit(handle, body)
|
||||
def acknowledged(_future):
|
||||
connection.add_callback_threadsafe(lambda: ch.basic_ack(method.delivery_tag))
|
||||
future.add_done_callback(acknowledged)
|
||||
|
||||
try:
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
|
||||
channel.start_consuming()
|
||||
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="attachment-worker") as executor:
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
|
||||
channel.start_consuming()
|
||||
finally:
|
||||
connection.close()
|
||||
s3.client.close()
|
||||
asyncio.run(store.close())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user