forked from mtusi2026/mtusi2026lab5
Исправить скачивание JPEG и добавить таймаут и DLQ
This commit is contained in:
@@ -15,7 +15,7 @@ def main():
|
||||
with psycopg.connect(database_url) as connection:
|
||||
with connection.transaction():
|
||||
row = connection.execute(
|
||||
"SELECT a.status, j.job_id FROM attachments a "
|
||||
"SELECT a.status, j.job_id, j.published_at FROM attachments a "
|
||||
"JOIN attachment_jobs j ON j.attachment_id=a.id "
|
||||
"WHERE a.id=%s FOR UPDATE",
|
||||
(args.attachment_id,),
|
||||
@@ -24,6 +24,8 @@ def main():
|
||||
raise SystemExit('attachment not found')
|
||||
if row[0] != 'failed':
|
||||
raise SystemExit('attachment is not failed')
|
||||
if row[2] is None:
|
||||
raise SystemExit('wait until the failure is published to the dead-letter stream')
|
||||
replay_id = uuid.uuid4()
|
||||
connection.execute(
|
||||
'INSERT INTO attachment_replays (replay_id,job_id) VALUES (%s,%s)',
|
||||
@@ -34,7 +36,8 @@ def main():
|
||||
(args.attachment_id,),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE attachment_jobs SET attempt=1, published_at=NULL, next_attempt_at=now(), last_error=NULL WHERE job_id=%s",
|
||||
"UPDATE attachment_jobs SET attempt=1, published_at=NULL, next_attempt_at=now(), "
|
||||
"last_error=NULL, dead_letter_id=NULL WHERE job_id=%s",
|
||||
(row[1],),
|
||||
)
|
||||
print(json.dumps({'attachment_id': str(args.attachment_id), 'job_id': str(row[1]), 'replay_id': str(replay_id)}))
|
||||
|
||||
+196
-139
@@ -1,17 +1,17 @@
|
||||
"""Redis Streams worker for durable attachment processing."""
|
||||
import hashlib
|
||||
import io
|
||||
import multiprocessing
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
import redis
|
||||
from botocore.config import Config
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from PIL import Image, ImageOps
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://messenger:messenger@postgres:5432/messenger')
|
||||
@@ -21,10 +21,14 @@ S3_BUCKET = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
S3_ACCESS_KEY_ID = os.getenv('S3_ACCESS_KEY_ID', 'messenger-api')
|
||||
S3_SECRET_ACCESS_KEY = os.getenv('S3_SECRET_ACCESS_KEY', 'messenger-api-secret-123')
|
||||
MAX_IMAGE_PIXELS = int(os.getenv('MAX_IMAGE_PIXELS', '40000000'))
|
||||
MAX_UPLOAD_BYTES = int(os.getenv('MAX_UPLOAD_BYTES', '10485760'))
|
||||
MAX_JOB_ATTEMPTS = int(os.getenv('MAX_JOB_ATTEMPTS', '5'))
|
||||
PROCESSING_LEASE_SECONDS = int(os.getenv('PROCESSING_LEASE_SECONDS', '30'))
|
||||
JOB_TIMEOUT_SECONDS = int(os.getenv('JOB_TIMEOUT_SECONDS', '20'))
|
||||
TEST_PROCESS_DELAY = float(os.getenv('LAB5_TEST_PROCESS_DELAY_SECONDS', '0'))
|
||||
ACK_DELAY_SECONDS = int(os.getenv('ACK_DELAY_SECONDS', '0'))
|
||||
STREAM = 'attachment-jobs'
|
||||
DLQ = 'attachment-jobs-dlq'
|
||||
GROUP = 'attachment-workers'
|
||||
CONSUMER = os.getenv('WORKER_ID', 'worker-' + uuid.uuid4().hex[:8])
|
||||
|
||||
@@ -39,8 +43,20 @@ s3 = boto3.client(
|
||||
)
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc)
|
||||
# Redis 7 has no idempotent XADD. Record the event ID and append in one script.
|
||||
append_dead_letter = broker.register_script("""
|
||||
if redis.call('HEXISTS', KEYS[2], ARGV[2]) == 1 then return end
|
||||
local stream_id = redis.call('XADD', KEYS[1], '*', unpack(ARGV))
|
||||
redis.call('HSET', KEYS[2], ARGV[2], stream_id)
|
||||
return stream_id
|
||||
""")
|
||||
|
||||
|
||||
def connect():
|
||||
return psycopg.connect(
|
||||
DATABASE_URL, row_factory=dict_row, connect_timeout=3,
|
||||
options='-c statement_timeout=3000',
|
||||
)
|
||||
|
||||
|
||||
def ensure_group():
|
||||
@@ -51,47 +67,42 @@ def ensure_group():
|
||||
raise
|
||||
|
||||
|
||||
def recover_expired_leases():
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as connection:
|
||||
with connection.transaction():
|
||||
rows = connection.execute(
|
||||
"SELECT id FROM attachments WHERE status='processing' AND lease_until < now()"
|
||||
).fetchall()
|
||||
for item in rows:
|
||||
attachment_id = item['id']
|
||||
connection.execute(
|
||||
"UPDATE attachments SET status='queued', lease_until=NULL, next_attempt_at=now(), "
|
||||
"updated_at=now(), error_code=NULL WHERE id=%s",
|
||||
(attachment_id,),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE attachment_jobs SET published_at=NULL, next_attempt_at=now(), "
|
||||
"last_error='worker_lease_expired' WHERE attachment_id=%s",
|
||||
(attachment_id,),
|
||||
)
|
||||
|
||||
|
||||
def publish_outbox():
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as connection:
|
||||
row = connection.execute(
|
||||
"SELECT job_id, attachment_id, pipeline_version, attempt "
|
||||
"FROM attachment_jobs WHERE published_at IS NULL AND next_attempt_at <= now() "
|
||||
"ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"
|
||||
).fetchone()
|
||||
def publish_outbox(failed_attachment_id=None):
|
||||
query = (
|
||||
"SELECT j.*, a.error_code FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
|
||||
"WHERE j.published_at IS NULL AND j.next_attempt_at <= now() "
|
||||
)
|
||||
with connect() as connection:
|
||||
if failed_attachment_id is None:
|
||||
row = connection.execute(
|
||||
query + "ORDER BY j.next_attempt_at LIMIT 1 FOR UPDATE OF j SKIP LOCKED"
|
||||
).fetchone()
|
||||
else:
|
||||
row = connection.execute(
|
||||
query + "AND a.id=%s AND j.dead_letter_id IS NOT NULL FOR UPDATE OF j",
|
||||
(failed_attachment_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
return
|
||||
payload = {
|
||||
'schema_version': '1', 'job_id': str(row['job_id']),
|
||||
'type': 'attachment.process.v1', 'attachment_id': str(row['attachment_id']),
|
||||
'pipeline_version': str(row['pipeline_version']), 'attempt': str(row['attempt']),
|
||||
'created_at': now().isoformat().replace('+00:00', 'Z'),
|
||||
'created_at': row['created_at'].isoformat().replace('+00:00', 'Z'),
|
||||
}
|
||||
broker.xadd(STREAM, payload, maxlen=10000, approximate=True)
|
||||
if row['dead_letter_id'] is None:
|
||||
broker.xadd(STREAM, payload)
|
||||
else:
|
||||
payload['error_code'] = row['error_code'] or 'processing_failed'
|
||||
payload['last_error'] = row['last_error'] or payload['error_code']
|
||||
fields = [field for pair in payload.items() for field in pair]
|
||||
append_dead_letter(
|
||||
keys=[DLQ, DLQ + ':events'],
|
||||
args=['event_id', str(row['dead_letter_id']), *fields],
|
||||
)
|
||||
connection.execute(
|
||||
'UPDATE attachment_jobs SET published_at=now() WHERE job_id=%s', (row['job_id'],)
|
||||
)
|
||||
connection.commit()
|
||||
return True
|
||||
|
||||
|
||||
def white_background(image):
|
||||
@@ -128,132 +139,178 @@ def webp_bytes(image):
|
||||
return output.getvalue(), image.size
|
||||
|
||||
|
||||
def get_attachment(attachment_id):
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as connection:
|
||||
return connection.execute('SELECT * FROM attachments WHERE id=%s', (attachment_id,)).fetchone()
|
||||
def claim(fields):
|
||||
with connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT a.*, j.attempt AS job_attempt, j.next_attempt_at <= now() AS due "
|
||||
"FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id "
|
||||
"WHERE a.id=%s AND j.job_id=%s AND j.pipeline_version=%s FOR UPDATE OF a",
|
||||
(fields['attachment_id'], fields['job_id'], fields['pipeline_version']),
|
||||
).fetchone()
|
||||
if row is None or row['job_attempt'] != int(fields['attempt']):
|
||||
return None, False
|
||||
if row['status'] == 'processing':
|
||||
return None, True
|
||||
if row['status'] != 'queued' or not row['due']:
|
||||
return None, False
|
||||
row['attempt'] = row['job_attempt']
|
||||
row['lease_until'] = connection.execute(
|
||||
"UPDATE attachments SET status='processing', attempt=%s, "
|
||||
"lease_until=now()+%s * interval '1 second', updated_at=now(), error_code=NULL "
|
||||
"WHERE id=%s RETURNING lease_until",
|
||||
(row['attempt'], PROCESSING_LEASE_SECONDS, row['id']),
|
||||
).fetchone()['lease_until']
|
||||
return row, False
|
||||
|
||||
|
||||
def claim(attachment_id, message_attempt):
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as connection:
|
||||
with connection.transaction():
|
||||
row = connection.execute(
|
||||
'SELECT * FROM attachments WHERE id=%s FOR UPDATE', (attachment_id,)
|
||||
).fetchone()
|
||||
if row is None or row['status'] in ('ready', 'failed'):
|
||||
return row, False
|
||||
if row['status'] == 'processing' and row['lease_until'] and row['lease_until'] > now():
|
||||
return row, False
|
||||
attempt = max(row['attempt'] + 1, message_attempt)
|
||||
connection.execute(
|
||||
"UPDATE attachments SET status='processing', attempt=%s, lease_until=%s, "
|
||||
"updated_at=now(), error_code=NULL WHERE id=%s",
|
||||
(attempt, now() + timedelta(seconds=PROCESSING_LEASE_SECONDS), attachment_id),
|
||||
)
|
||||
row['attempt'] = attempt
|
||||
row['status'] = 'processing'
|
||||
return row, True
|
||||
def mark_retry(row, error_code, permanent=False):
|
||||
attempt = row['attempt']
|
||||
terminal = permanent or attempt >= MAX_JOB_ATTEMPTS
|
||||
status = 'failed' if terminal else 'queued'
|
||||
public_code = 'retry_exhausted' if terminal and not permanent else error_code
|
||||
with connect() as connection:
|
||||
updated = connection.execute(
|
||||
"UPDATE attachments SET status=%s, lease_until=NULL, error_code=%s, updated_at=now() "
|
||||
"WHERE id=%s AND status='processing' AND lease_until=%s",
|
||||
(status, public_code, row['id'], row['lease_until']),
|
||||
)
|
||||
if updated.rowcount == 0:
|
||||
return
|
||||
delay = 0 if terminal else min(30, 2 ** (attempt - 1)) + random.uniform(0, 1)
|
||||
connection.execute(
|
||||
"UPDATE attachment_jobs SET attempt=%s, published_at=NULL, "
|
||||
"next_attempt_at=now()+%s * interval '1 second', last_error=%s, dead_letter_id=%s "
|
||||
"WHERE attachment_id=%s",
|
||||
(attempt if terminal else attempt + 1, delay, error_code,
|
||||
uuid.uuid4() if terminal else None, row['id']),
|
||||
)
|
||||
|
||||
|
||||
def mark_retry(attachment_id, attempt, error_code, permanent=False):
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as connection:
|
||||
with connection.transaction():
|
||||
if permanent or attempt >= MAX_JOB_ATTEMPTS:
|
||||
connection.execute(
|
||||
"UPDATE attachments SET status='failed', lease_until=NULL, error_code=%s, updated_at=now() WHERE id=%s",
|
||||
('invalid_image' if permanent else 'retry_exhausted', attachment_id),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE attachment_jobs SET published_at=now(), last_error=%s WHERE attachment_id=%s",
|
||||
('invalid_image' if permanent else 'retry_exhausted', attachment_id),
|
||||
)
|
||||
else:
|
||||
delay = min(30, 2 ** max(0, attempt - 1)) + random.uniform(0, 1)
|
||||
connection.execute(
|
||||
"UPDATE attachments SET status='queued', lease_until=NULL, next_attempt_at=now(), "
|
||||
"error_code=%s, updated_at=now() WHERE id=%s",
|
||||
(error_code, attachment_id),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE attachment_jobs SET attempt=%s, published_at=NULL, next_attempt_at=now()+%s * interval '1 second', last_error=%s "
|
||||
"WHERE attachment_id=%s",
|
||||
(attempt + 1, delay, error_code, attachment_id),
|
||||
)
|
||||
def recover_expired_leases():
|
||||
with connect() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT id, attempt, lease_until FROM attachments "
|
||||
"WHERE status='processing' AND lease_until < now()"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
mark_retry(row, 'worker_lease_expired')
|
||||
|
||||
|
||||
def process(attachment_id, message_attempt):
|
||||
row, owned = claim(attachment_id, message_attempt)
|
||||
if not owned:
|
||||
return
|
||||
def store_result(row):
|
||||
value = s3.get_object(Bucket=S3_BUCKET, Key=row['staging_key'])
|
||||
with value['Body'] as body:
|
||||
original = body.read(MAX_UPLOAD_BYTES + 1)
|
||||
try:
|
||||
value = s3.get_object(Bucket=S3_BUCKET, Key=row['staging_key'])
|
||||
original = value['Body'].read()
|
||||
if TEST_PROCESS_DELAY:
|
||||
time.sleep(TEST_PROCESS_DELAY)
|
||||
if len(original) > MAX_UPLOAD_BYTES or hashlib.sha256(original).hexdigest() != row['sha256']:
|
||||
raise ValueError('staging data mismatch')
|
||||
with Image.open(io.BytesIO(original)) as source:
|
||||
if source.format not in ('PNG', 'JPEG') or source.width * source.height > MAX_IMAGE_PIXELS:
|
||||
expected_type = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(source.format)
|
||||
if (expected_type != row['content_type']
|
||||
or source.width * source.height > MAX_IMAGE_PIXELS):
|
||||
raise ValueError('invalid image')
|
||||
image = white_background(source)
|
||||
thumbnail, thumb_size = jpeg_bytes(image, 256)
|
||||
crop, crop_size = jpeg_bytes(image, 128, crop=True)
|
||||
optimized, optimized_size = webp_bytes(image)
|
||||
except (Image.DecompressionBombError, ValueError, OSError):
|
||||
raise SystemExit(2)
|
||||
|
||||
base = 'attachments/' + str(attachment_id) + '/'
|
||||
objects = [
|
||||
('original', original, row['content_type'], image.size),
|
||||
('thumbnail', thumbnail, 'image/jpeg', thumb_size),
|
||||
('crop', crop, 'image/jpeg', crop_size),
|
||||
('optimized', optimized, 'image/webp', optimized_size),
|
||||
]
|
||||
for name, data, content_type, _size in objects:
|
||||
key = base + name + ('.jpg' if content_type == 'image/jpeg' else '.webp' if content_type == 'image/webp' else '')
|
||||
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=data, ContentType=content_type, ContentLength=len(data))
|
||||
s3.put_object(
|
||||
Bucket=S3_BUCKET, Key=row['object_key'], Body=original,
|
||||
ContentType=row['content_type'], ContentLength=len(original),
|
||||
)
|
||||
base = 'attachments/' + str(row['id']) + '/'
|
||||
variants = []
|
||||
for name, data, content_type, dimensions, extension in (
|
||||
('thumbnail', thumbnail, 'image/jpeg', thumb_size, '.jpg'),
|
||||
('crop', crop, 'image/jpeg', crop_size, '.jpg'),
|
||||
('optimized', optimized, 'image/webp', optimized_size, '.webp'),
|
||||
):
|
||||
key = base + name + extension
|
||||
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=data, ContentType=content_type)
|
||||
variants.append((row['id'], name, content_type, key, len(data), *dimensions,
|
||||
hashlib.sha256(data).hexdigest()))
|
||||
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as connection:
|
||||
with connection.transaction():
|
||||
connection.execute(
|
||||
"UPDATE attachments SET status='ready', lease_until=NULL, error_code=NULL, updated_at=now() WHERE id=%s",
|
||||
(attachment_id,),
|
||||
)
|
||||
for name, data, content_type, dimensions in objects[1:]:
|
||||
key = base + name + ('.jpg' if content_type == 'image/jpeg' else '.webp')
|
||||
connection.execute(
|
||||
'INSERT INTO attachment_variants '
|
||||
'(attachment_id,name,content_type,object_key,size_bytes,width,height,sha256) '
|
||||
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s) '
|
||||
'ON CONFLICT (attachment_id,name) DO UPDATE SET '
|
||||
'content_type=EXCLUDED.content_type,object_key=EXCLUDED.object_key,size_bytes=EXCLUDED.size_bytes,'
|
||||
'width=EXCLUDED.width,height=EXCLUDED.height,sha256=EXCLUDED.sha256',
|
||||
(attachment_id, name, content_type, key, len(data), dimensions[0], dimensions[1], hashlib.sha256(data).hexdigest()),
|
||||
)
|
||||
try:
|
||||
s3.delete_object(Bucket=S3_BUCKET, Key=row['staging_key'])
|
||||
except Exception:
|
||||
pass
|
||||
if ACK_DELAY_SECONDS:
|
||||
time.sleep(ACK_DELAY_SECONDS)
|
||||
except (UnidentifiedImageError, ValueError, OSError):
|
||||
mark_retry(attachment_id, row['attempt'], 'invalid_image', permanent=True)
|
||||
except Exception:
|
||||
mark_retry(attachment_id, row['attempt'], 'processing_failed')
|
||||
|
||||
|
||||
def handle_message(message_id, fields):
|
||||
process(uuid.UUID(fields['attachment_id']), int(fields.get('attempt', '1')))
|
||||
broker.xack(STREAM, GROUP, message_id)
|
||||
|
||||
|
||||
def reclaim_pending():
|
||||
with connect() as connection:
|
||||
updated = connection.execute(
|
||||
"UPDATE attachments SET status='ready', lease_until=NULL, error_code=NULL, updated_at=now() "
|
||||
"WHERE id=%s AND status='processing' AND lease_until=%s AND lease_until > now()",
|
||||
(row['id'], row['lease_until']),
|
||||
)
|
||||
if updated.rowcount == 0:
|
||||
raise SystemExit(1)
|
||||
for variant in variants:
|
||||
connection.execute(
|
||||
'INSERT INTO attachment_variants '
|
||||
'(attachment_id,name,content_type,object_key,size_bytes,width,height,sha256) '
|
||||
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s) '
|
||||
'ON CONFLICT (attachment_id,name) DO UPDATE SET '
|
||||
'content_type=EXCLUDED.content_type,object_key=EXCLUDED.object_key,size_bytes=EXCLUDED.size_bytes,'
|
||||
'width=EXCLUDED.width,height=EXCLUDED.height,sha256=EXCLUDED.sha256',
|
||||
variant,
|
||||
)
|
||||
try:
|
||||
result = broker.xautoclaim(STREAM, GROUP, CONSUMER, min_idle_time=1000, start_id='0-0', count=10)
|
||||
for message_id, fields in result[1]:
|
||||
handle_message(message_id, fields)
|
||||
except (redis.ResponseError, AttributeError):
|
||||
s3.delete_object(Bucket=S3_BUCKET, Key=row['staging_key'])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_attempt(row):
|
||||
try:
|
||||
store_result(row)
|
||||
except Exception as exc:
|
||||
print('attachment processing error:', type(exc).__name__, flush=True)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def process_with_deadline(row):
|
||||
# Pillow and S3 calls run in a process the worker can kill even if native code hangs.
|
||||
child = multiprocessing.get_context('spawn').Process(target=run_attempt, args=(row,))
|
||||
child.start()
|
||||
child.join(JOB_TIMEOUT_SECONDS)
|
||||
if child.is_alive():
|
||||
child.kill()
|
||||
child.join()
|
||||
mark_retry(row, 'processing_timeout')
|
||||
elif child.exitcode == 2:
|
||||
mark_retry(row, 'invalid_image', permanent=True)
|
||||
elif child.exitcode != 0:
|
||||
mark_retry(row, 'processing_failed')
|
||||
child.close()
|
||||
|
||||
|
||||
def handle_message(message_id, fields):
|
||||
row, busy = claim(fields)
|
||||
if busy:
|
||||
return
|
||||
if row is not None:
|
||||
process_with_deadline(row)
|
||||
if ACK_DELAY_SECONDS:
|
||||
time.sleep(ACK_DELAY_SECONDS)
|
||||
# If the DB committed a terminal failure but Redis is unavailable, leave the
|
||||
# delivery pending. Redelivery will retry DLQ publication before acknowledging it.
|
||||
publish_outbox(fields['attachment_id'])
|
||||
with broker.pipeline() as transaction:
|
||||
transaction.xack(STREAM, GROUP, message_id)
|
||||
transaction.xdel(STREAM, message_id) # This stream has one consumer group.
|
||||
transaction.execute()
|
||||
|
||||
|
||||
def reclaim_pending():
|
||||
result = broker.xautoclaim(STREAM, GROUP, CONSUMER, min_idle_time=1000, start_id='0-0', count=1)
|
||||
for message_id, fields in result[1]:
|
||||
handle_message(message_id, fields)
|
||||
|
||||
|
||||
def main():
|
||||
ensure_group()
|
||||
if not 0 < JOB_TIMEOUT_SECONDS < PROCESSING_LEASE_SECONDS or MAX_JOB_ATTEMPTS < 1:
|
||||
raise SystemExit('require 0 < JOB_TIMEOUT_SECONDS < PROCESSING_LEASE_SECONDS and positive MAX_JOB_ATTEMPTS')
|
||||
print('worker started', CONSUMER, flush=True)
|
||||
while True:
|
||||
try:
|
||||
ensure_group()
|
||||
recover_expired_leases()
|
||||
publish_outbox()
|
||||
reclaim_pending()
|
||||
|
||||
Reference in New Issue
Block a user