Add durable Redis Streams broker for attachment jobs

This commit is contained in:
2026-11-20 21:02:33 +03:00
parent d8332e17f6
commit 930963f1ea
4 changed files with 49 additions and 0 deletions
+12
View File
@@ -6,6 +6,7 @@ import time
from PIL import Image, ImageOps
from src.db import make_pool
from src.storage import BUCKET, s3
from src.queue import ensure_group, client as broker, STREAM, GROUP
MAX_ATTEMPTS = 5
@@ -41,7 +42,18 @@ def process(row, pool):
def loop():
pool=make_pool()
ensure_group()
while True:
# Repair the transactional-outbox -> stream gap after a crash between commit and XADD.
with pool.connection() as conn:
pending = conn.execute("SELECT attachment_id FROM attachment_jobs WHERE completed_at IS NULL AND available_at<=clock_timestamp() AND (locked_until IS NULL OR locked_until<clock_timestamp()) LIMIT 50").fetchall()
for pending_row in pending:
broker.xadd(STREAM, {'attachment_id': str(pending_row['attachment_id'])}, maxlen=10000, approximate=True)
messages = broker.xreadgroup(GROUP, 'worker-1', {STREAM:'>'}, count=1, block=1000)
if messages:
for _, entries in messages:
for message_id, fields in entries:
broker.xack(STREAM, GROUP, message_id)
with pool.connection() as conn:
job=conn.execute("UPDATE attachment_jobs SET attempts=attempts+1,locked_until=clock_timestamp()+interval '60 seconds' WHERE attachment_id=(SELECT attachment_id FROM attachment_jobs WHERE completed_at IS NULL AND available_at<=clock_timestamp() AND (locked_until IS NULL OR locked_until<clock_timestamp()) ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *").fetchone()
row=conn.execute('SELECT * FROM attachments WHERE id=%s',(job['attachment_id'],)).fetchone() if job else None