ЛР5 — БВТ2302 — Никитина — на 5
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from io import BytesIO
|
||||
|
||||
import psycopg
|
||||
import redis.asyncio as redis
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
sys.path.insert(0, '/app/src')
|
||||
from s3_client import upload_file, download_file
|
||||
|
||||
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||
REDIS_URL = os.environ["REDIS_URL"]
|
||||
STREAM_KEY = "attachment_jobs"
|
||||
GROUP_NAME = "workers"
|
||||
CONSUMER_NAME = os.environ.get("HOSTNAME", "worker")
|
||||
MAX_RETRIES = 5
|
||||
|
||||
async def process_image(data: bytes, attachment_id: str):
|
||||
img = Image.open(BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||
bg = Image.new("RGB", img.size, (255, 255, 255))
|
||||
bg.paste(img, mask=img.split()[-1])
|
||||
img = bg
|
||||
elif img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
|
||||
variants = []
|
||||
|
||||
# Thumbnail
|
||||
thumb = img.copy()
|
||||
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
thumb_data = BytesIO()
|
||||
thumb.save(thumb_data, format="JPEG", quality=85)
|
||||
thumb_key = f"{attachment_id}/thumbnail.jpg"
|
||||
upload_file(thumb_key, thumb_data.getvalue(), "image/jpeg")
|
||||
variants.append({"name": "thumbnail", "content_type": "image/jpeg", "size_bytes": len(thumb_data.getvalue()), "sha256": hashlib.sha256(thumb_data.getvalue()).hexdigest(), "width": thumb.width, "height": thumb.height})
|
||||
|
||||
# Crop
|
||||
crop = img.copy()
|
||||
min_dim = min(crop.size)
|
||||
left = (crop.width - min_dim) // 2
|
||||
top = (crop.height - min_dim) // 2
|
||||
crop = crop.crop((left, top, left + min_dim, top + min_dim))
|
||||
crop = crop.resize((128, 128), Image.Resampling.LANCZOS)
|
||||
crop_data = BytesIO()
|
||||
crop.save(crop_data, format="JPEG", quality=85)
|
||||
crop_key = f"{attachment_id}/crop.jpg"
|
||||
upload_file(crop_key, crop_data.getvalue(), "image/jpeg")
|
||||
variants.append({"name": "crop", "content_type": "image/jpeg", "size_bytes": len(crop_data.getvalue()), "sha256": hashlib.sha256(crop_data.getvalue()).hexdigest(), "width": 128, "height": 128})
|
||||
|
||||
# Optimized WebP
|
||||
opt = img.copy()
|
||||
opt.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
|
||||
opt_data = BytesIO()
|
||||
opt.save(opt_data, format="WEBP", quality=80, method=6)
|
||||
opt_key = f"{attachment_id}/optimized.webp"
|
||||
upload_file(opt_key, opt_data.getvalue(), "image/webp")
|
||||
variants.append({"name": "optimized", "content_type": "image/webp", "size_bytes": len(opt_data.getvalue()), "sha256": hashlib.sha256(opt_data.getvalue()).hexdigest(), "width": opt.width, "height": opt.height})
|
||||
|
||||
return variants
|
||||
|
||||
async def process_job(job: dict, redis_client):
|
||||
attachment_id = job["attachment_id"]
|
||||
s3_key = job["s3_key"]
|
||||
print(f"[worker] Processing {attachment_id}")
|
||||
|
||||
async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = %s AND status = 'queued'",
|
||||
(attachment_id,)
|
||||
)
|
||||
await conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
print(f"[worker] Job {attachment_id} already processed, skipping")
|
||||
return
|
||||
|
||||
try:
|
||||
data = download_file(s3_key)
|
||||
variants = await process_image(data, attachment_id)
|
||||
|
||||
async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"UPDATE attachments SET status = 'ready', variants = %s, updated_at = now() WHERE id = %s",
|
||||
(json.dumps(variants), attachment_id)
|
||||
)
|
||||
await conn.commit()
|
||||
print(f"[worker] Job {attachment_id} completed")
|
||||
|
||||
# ИМИТАЦИЯ ПАДЕНИЯ (Crash after side effect, before ack)
|
||||
if os.environ.get("SIMULATE_CRASH") == "worker":
|
||||
print(f"!!! SIMULATING CRASH BEFORE ACK FOR {attachment_id} !!!")
|
||||
os._exit(1)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[worker] Job {attachment_id} failed: {e}")
|
||||
async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT retry_count FROM attachments WHERE id = %s", (attachment_id,))
|
||||
row = await cur.fetchone()
|
||||
retry_count = row[0] if row else 0
|
||||
|
||||
if retry_count >= MAX_RETRIES:
|
||||
await cur.execute("UPDATE attachments SET status = 'failed', error_code = %s WHERE id = %s", ("processing_failed", attachment_id))
|
||||
else:
|
||||
await cur.execute("UPDATE attachments SET status = 'queued', retry_count = retry_count + 1 WHERE id = %s", (attachment_id,))
|
||||
await redis_client.xadd(STREAM_KEY, {"job": json.dumps(job)})
|
||||
await conn.commit()
|
||||
|
||||
async def main():
|
||||
redis_client = redis.from_url(REDIS_URL, decode_responses=True)
|
||||
try:
|
||||
await redis_client.xgroup_create(STREAM_KEY, GROUP_NAME, id="0", mkstream=True)
|
||||
except Exception as e:
|
||||
if "BUSYGROUP" not in str(e):
|
||||
raise
|
||||
|
||||
print(f"[worker] Listening on {STREAM_KEY} as {CONSUMER_NAME}")
|
||||
|
||||
while True:
|
||||
try:
|
||||
# 1. Сначала пытаемся забрать "зависшие" задачи у упавших воркеров (старше 10 секунд)
|
||||
claimed = await redis_client.xautoclaim(STREAM_KEY, GROUP_NAME, CONSUMER_NAME, min_idle_time=10000, start_id="0-0")
|
||||
if claimed and claimed[1]:
|
||||
for msg_id, fields in claimed[1]:
|
||||
if fields: # Если сообщение не пустое
|
||||
print(f"[worker] Reclaimed pending job: {msg_id}")
|
||||
job = json.loads(fields["job"])
|
||||
await process_job(job, redis_client)
|
||||
await redis_client.xack(STREAM_KEY, GROUP_NAME, msg_id)
|
||||
|
||||
# 2. Читаем новые задачи
|
||||
messages = await redis_client.xreadgroup(GROUP_NAME, CONSUMER_NAME, {STREAM_KEY: ">"}, count=1, block=3000)
|
||||
if not messages:
|
||||
continue
|
||||
|
||||
for stream, msgs in messages:
|
||||
for msg_id, fields in msgs:
|
||||
job = json.loads(fields["job"])
|
||||
await process_job(job, redis_client)
|
||||
await redis_client.xack(STREAM_KEY, GROUP_NAME, msg_id)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[worker] Error: {e}")
|
||||
await asyncio.sleep(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user