add level 5

This commit is contained in:
Матвей
2026-10-26 10:36:01 +03:00
parent ff33b8a7c2
commit 4f6e69cfac
8 changed files with 214 additions and 21 deletions
+38 -17
View File
@@ -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__":