forked from mtusi2026/mtusi2026lab5
328 lines
13 KiB
Python
328 lines
13 KiB
Python
"""Redis Streams worker for durable attachment processing."""
|
|
import hashlib
|
|
import io
|
|
import multiprocessing
|
|
import os
|
|
import random
|
|
import time
|
|
import uuid
|
|
|
|
import boto3
|
|
import psycopg
|
|
import redis
|
|
from botocore.config import Config
|
|
from PIL import Image, ImageOps
|
|
from psycopg.rows import dict_row
|
|
|
|
DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://messenger:messenger@postgres:5432/messenger')
|
|
BROKER_URL = os.getenv('BROKER_URL', 'redis://broker:6379/0')
|
|
S3_ENDPOINT = os.getenv('S3_ENDPOINT', 'http://minio:9000')
|
|
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])
|
|
|
|
broker = redis.Redis.from_url(
|
|
BROKER_URL, decode_responses=True, socket_connect_timeout=2,
|
|
socket_timeout=3, retry_on_timeout=False,
|
|
)
|
|
s3 = boto3.client(
|
|
's3', endpoint_url=S3_ENDPOINT, region_name='us-east-1',
|
|
aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY,
|
|
config=Config(connect_timeout=2, read_timeout=10, retries={'max_attempts': 1}),
|
|
)
|
|
|
|
|
|
# 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():
|
|
try:
|
|
broker.xgroup_create(STREAM, GROUP, id='0-0', mkstream=True)
|
|
except redis.ResponseError as exc:
|
|
if 'BUSYGROUP' not in str(exc):
|
|
raise
|
|
|
|
|
|
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
|
|
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': row['created_at'].isoformat().replace('+00:00', 'Z'),
|
|
}
|
|
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'],)
|
|
)
|
|
|
|
|
|
def white_background(image):
|
|
image = ImageOps.exif_transpose(image)
|
|
if image.mode in ('RGBA', 'LA') or 'transparency' in image.info:
|
|
background = Image.new('RGB', image.size, 'white')
|
|
alpha = image.convert('RGBA')
|
|
background.paste(alpha, mask=alpha.getchannel('A'))
|
|
return background
|
|
return image.convert('RGB')
|
|
|
|
|
|
def jpeg_bytes(image, size, crop=False):
|
|
image = image.copy()
|
|
if crop:
|
|
side = min(image.size)
|
|
left = (image.width - side) // 2
|
|
top = (image.height - side) // 2
|
|
image = image.crop((left, top, left + side, top + side))
|
|
if crop:
|
|
image = image.resize((size, size), Image.Resampling.LANCZOS)
|
|
else:
|
|
image.thumbnail((size, size), Image.Resampling.LANCZOS)
|
|
output = io.BytesIO()
|
|
image.save(output, format='JPEG', quality=85, optimize=True)
|
|
return output.getvalue(), image.size
|
|
|
|
|
|
def webp_bytes(image):
|
|
image = image.copy()
|
|
image.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
|
|
output = io.BytesIO()
|
|
image.save(output, format='WEBP', quality=82, method=6)
|
|
return output.getvalue(), image.size
|
|
|
|
|
|
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 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 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 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:
|
|
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:
|
|
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)
|
|
|
|
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 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:
|
|
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():
|
|
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()
|
|
messages = broker.xreadgroup(GROUP, CONSUMER, {STREAM: '>'}, count=1, block=1000)
|
|
for _stream, items in messages:
|
|
for message_id, fields in items:
|
|
handle_message(message_id, fields)
|
|
except Exception as exc:
|
|
print('worker loop error:', type(exc).__name__, flush=True)
|
|
time.sleep(1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|