diff --git a/.env.example b/.env.example index 8fcd21a..249e778 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,7 @@ S3_SECRET_ACCESS_KEY=change-me-local-only BROKER_URL=redis://broker:6379/0 MAX_JOB_ATTEMPTS=5 PROCESSING_LEASE_SECONDS=30 +JOB_TIMEOUT_SECONDS=20 ACK_DELAY_SECONDS=0 MINIO_ROOT_USER=minioadmin MINIO_ROOT_PASSWORD=change-me-minio-local-only diff --git a/REPORT.md b/REPORT.md index ed3dd8e..fe196de 100644 --- a/REPORT.md +++ b/REPORT.md @@ -35,7 +35,7 @@ python3 -m venv .venv | Балансировщик | `lb` | единственный внешний `localhost:8080` | | База | `postgres` | `postgres_data` volume | | Сессии/кэш | `redis` | `redis_data` volume, AOF | -| Broker | `broker` | Redis Streams, `broker_data` volume, AOF | +| Broker | `broker` | Redis Streams, `broker_data` volume, AOF с `appendfsync always` | | Файлы | `minio` | приватный S3 bucket, `s3_data` volume | | Обработка | `worker` | отдельный процесс, resize и фиксация результата | @@ -71,13 +71,18 @@ Redis Streams работает как отдельный durable broker с AOF Transactional outbox закрывает разрыв между PostgreSQL и broker. API сначала коммитит staging, metadata и `attachment_jobs`. Worker отдельным циклом публикует неподтверждённые outbox-записи. Если worker остановлен после commit, запись остаётся в PostgreSQL и публикуется после восстановления; ручное создание нового задания не требуется. -У processing есть lease 30 секунд. После смерти worker просроченный lease переводит вложение обратно в `queued`, а тот же job снова появляется в outbox. Временные ошибки получают ограниченные повторы до 5 попыток с exponential backoff и jitter. Постоянная ошибка изображения становится `failed` с безопасным `error_code`; для явного операторского повтора используется: +На одну попытку отводится `JOB_TIMEOUT_SECONDS` (20 с по умолчанию). Чтение из S3, декодирование, преобразования, запись файлов и фиксация результата выполняются в дочернем процессе. По исчерпании времени worker принудительно завершает процесс и планирует повтор с причиной `processing_timeout`. Lease (30 с по умолчанию) позволяет восстановить задание после остановки всего worker. Таймаут попытки должен быть короче lease. Временные ошибки получают до 5 попыток с нарастающей задержкой и случайной добавкой. + +При постоянной ошибке или исчерпании попыток вложение получает статус `failed`. Та же транзакция сохраняет намерение отправить событие в отдельный поток Redis `attachment-jobs-dlq`. Worker публикует событие перед подтверждением исходного сообщения. Идентификатор события защищает от повторной записи, если Redis принял публикацию, а worker не успел отметить её в PostgreSQL. В DLQ хранятся идентификаторы задания и вложения, номер попытки и безопасные коды ошибок. + +Оператор может просмотреть последние события и повторить обработку конкретного вложения после устранения причины сбоя. ```sh +docker compose exec broker redis-cli XREVRANGE attachment-jobs-dlq + - COUNT 10 docker compose exec worker python scripts/replay_failed.py ATTACHMENT_UUID ``` -Варианты записываются с `ON CONFLICT` по имени, поэтому повторная доставка не создаёт второй набор вариантов и старая job не перезаписывает новый результат. +Replay разрешён для вложения в состоянии `failed` после публикации события в DLQ. Он возвращает то же задание в очередь и сохраняет историю ошибок в DLQ. Варианты записываются с `ON CONFLICT` по имени, а повтор для готового вложения пропускает обработку. Для проверки окна «результат уже записан, но ack ещё не отправлен» worker поддерживает локальный тестовый `ACK_DELAY_SECONDS`; в обычном `.env` он равен нулю и не влияет на обработку. @@ -90,6 +95,8 @@ docker compose exec worker python scripts/replay_failed.py ATTACHMENT_UUID | Публичный сценарий | `make test BASE_URL=http://localhost:8080` | `PASS: lab5 public API scenario` | | MIME/размер/доступ | `python3 student-tests/attachments.py` | PASS; 415/413/404 | | Все варианты | `python3 student-tests/variants.py` | thumbnail, crop и optimized PASS | +| Оригинал JPEG | `python3 student-tests/jpeg_original.py` | 202 → ready → 200, исходные байты и SHA-256 совпадают | +| Таймаут и DLQ | `python3 student-tests/timeout_dlq.py` | worker переживает таймаут, DLQ сохраняется при рестарте broker, replay возвращает ready | | Идемпотентность сообщений | `python3 student-tests/idempotency.py` | один Message ID при 8 повторах | | 10 конкурентных upload | `python3 student-tests/upload_load.py` | все 10 получили `202` | | Worker остановлен | `python3 student-tests/worker_recovery.py` | upload 202 сохраняется и после старта worker становится ready | @@ -102,6 +109,8 @@ docker compose exec worker python scripts/replay_failed.py ATTACHMENT_UUID ## Ограничения +DLQ и индекс идентификаторов событий хранят историю. Автоматическая очистка истории на учебном стенде не настроена. + Один PostgreSQL, один Redis-сервис сессий, один Redis broker, один MinIO и один Nginx остаются единичными точками отказа. Стенд проверяет отказ worker, повторную доставку, сохранность volumes и отказ одной API-реплики; потеря Docker-host и удаление volumes в модель не входят. Redis Streams использует at-least-once доставку, поэтому exactly-once доставка не заявляется: ровно один эффект достигается идемпотентной записью результата. Все пользователи и изображения синтетические. ИИ использовался как помощник при разборе skeleton и подготовке кода; команды и результаты проверены на локальном Compose-стенде. diff --git a/app/main.py b/app/main.py index 596be50..a4123bf 100644 --- a/app/main.py +++ b/app/main.py @@ -13,6 +13,7 @@ from datetime import datetime, timedelta, timezone import redis import boto3 from botocore.config import Config +from botocore.exceptions import ClientError from argon2 import PasswordHasher from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, Response @@ -644,8 +645,16 @@ def download_attachment(attachment_id: str, request: Request, variant: str = 'or object_key = row['object_key'] if variant == 'original' else variant_row['object_key'] content_type = row['content_type'] if variant == 'original' else variant_row['content_type'] try: - value = s3_client.get_object(Bucket=S3_BUCKET, Key=object_key) - data = value['Body'].read(MAX_UPLOAD_BYTES + 1) + try: + value = s3_client.get_object(Bucket=S3_BUCKET, Key=object_key) + except ClientError as exc: + # Older workers included .jpg in the original JPEG key. + if (variant != 'original' or content_type != 'image/jpeg' + or exc.response['Error']['Code'] != 'NoSuchKey'): + raise + value = s3_client.get_object(Bucket=S3_BUCKET, Key=object_key + '.jpg') + with value['Body'] as body: + data = body.read(MAX_UPLOAD_BYTES + 1) if len(data) > MAX_UPLOAD_BYTES: return error_response(request, 503, 'unavailable', 'Некорректный объект в хранилище') except Exception: diff --git a/compose.yaml b/compose.yaml index 906afc9..a3b7724 100644 --- a/compose.yaml +++ b/compose.yaml @@ -59,7 +59,7 @@ services: broker: image: redis:7.4.2-alpine - command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always"] volumes: - broker_data:/data healthcheck: @@ -89,8 +89,10 @@ services: S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-api} S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-messenger-api-secret-123} MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} MAX_JOB_ATTEMPTS: ${MAX_JOB_ATTEMPTS:-5} PROCESSING_LEASE_SECONDS: ${PROCESSING_LEASE_SECONDS:-30} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-20} ACK_DELAY_SECONDS: ${ACK_DELAY_SECONDS:-0} depends_on: migrate: {condition: service_completed_successfully} diff --git a/migrations/005_dead_letter.sql b/migrations/005_dead_letter.sql new file mode 100644 index 0000000..76960ff --- /dev/null +++ b/migrations/005_dead_letter.sql @@ -0,0 +1,6 @@ +ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS dead_letter_id UUID; + +-- Adopt already failed jobs when upgrading an existing Lab 5 database. +UPDATE attachment_jobs j SET dead_letter_id=gen_random_uuid(), published_at=NULL +FROM attachments a +WHERE a.id=j.attachment_id AND a.status='failed' AND j.dead_letter_id IS NULL; diff --git a/scripts/replay_failed.py b/scripts/replay_failed.py index 1987e36..28ed0e3 100644 --- a/scripts/replay_failed.py +++ b/scripts/replay_failed.py @@ -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)})) diff --git a/scripts/worker.py b/scripts/worker.py index b17af37..4b0242e 100644 --- a/scripts/worker.py +++ b/scripts/worker.py @@ -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() diff --git a/student-tests/jpeg_original.py b/student-tests/jpeg_original.py new file mode 100644 index 0000000..8f6b752 --- /dev/null +++ b/student-tests/jpeg_original.py @@ -0,0 +1,31 @@ +"""A valid JPEG must survive upload and download without any byte changes.""" +import hashlib +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parents[1] / 'tests')) +from client import Client, check + + +def main(): + client = Client() + alice, bob, _, chat = client.bootstrap() + original = Path(__file__).with_name('sample.jpg').read_bytes() + attachment = client.call( + 'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.jpg', + 202, actor=alice, raw=original, headers={'Content-Type': 'image/jpeg'}, + schema='Attachment', + )['json'] + check(attachment['status'] == 'queued', 'JPEG upload must start queued') + ready = client.wait_ready(bob, attachment) + result = client.call( + 'GET', '/api/v1/attachments/' + ready['id'] + '/content', 200, actor=bob, + ) + check(result['headers'].get_content_type() == 'image/jpeg', 'JPEG content type changed') + check(result['bytes'] == original, 'JPEG original bytes changed') + check(ready['sha256'] == hashlib.sha256(original).hexdigest(), 'JPEG checksum mismatch') + print('PASS: JPEG upload 202 -> ready -> original 200, bytes and SHA-256 match') + + +if __name__ == '__main__': + main() diff --git a/student-tests/sample.jpg b/student-tests/sample.jpg new file mode 100644 index 0000000..ab783e3 Binary files /dev/null and b/student-tests/sample.jpg differ diff --git a/student-tests/timeout_dlq.py b/student-tests/timeout_dlq.py new file mode 100644 index 0000000..ac6cb0a --- /dev/null +++ b/student-tests/timeout_dlq.py @@ -0,0 +1,103 @@ +"""Force two timeouts, verify durable DLQ delivery, then replay the attachment.""" +import json +import subprocess +import sys +import time +from pathlib import Path +from uuid import uuid4 + +sys.path.insert(0, str(Path(__file__).parents[1] / 'tests')) +from client import Client, check + + +def compose(*args): + result = subprocess.run( + ['docker', 'compose', *args], check=True, text=True, stdout=subprocess.PIPE, + ) + return result.stdout.strip() + + +def dead_letters(attachment_id): + records = json.loads(compose( + 'exec', '-T', 'broker', 'redis-cli', '--json', 'XRANGE', 'attachment-jobs-dlq', '-', '+', + )) + events = [dict(zip(fields[::2], fields[1::2])) for _, fields in records] + return [event for event in events if event.get('attachment_id') == attachment_id] + + +def wait_for(check_state, seconds=25): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + result = check_state() + if result: + return result + time.sleep(0.2) + raise AssertionError('timed out waiting for the expected state') + + +def main(): + client = Client() + alice, bob, _, chat = client.bootstrap() + container = 'lab5-timeout-' + uuid4().hex[:8] + compose('stop', 'worker') + try: + compose( + 'run', '--no-deps', '--rm', '-d', '--name', container, + '-e', 'JOB_TIMEOUT_SECONDS=2', '-e', 'MAX_JOB_ATTEMPTS=2', + '-e', 'LAB5_TEST_PROCESS_DELAY_SECONDS=60', 'worker', + ) + started = time.monotonic() + attachment, original = client.attachment(alice, chat) + other, _ = client.attachment(alice, chat) + attachment_id = attachment['id'] + path = '/api/v1/attachments/' + attachment_id + events = wait_for(lambda: dead_letters(attachment_id)) + check(len(events) == 1, 'expected exactly one event in the DLQ') + event = events[0] + check(event['attempt'] == '2', 'timeout did not retry before the final failure') + check(event['error_code'] == 'retry_exhausted', 'unexpected terminal error') + check(event['last_error'] == 'processing_timeout', 'deadline did not stop processing') + other_events = wait_for(lambda: dead_letters(other['id'])) + check(len(other_events) == 1, 'each failed job needs its own DLQ entry') + check(other_events[0]['event_id'] != event['event_id'], 'DLQ event ID was reused') + state = client.call('GET', path, actor=bob, schema='Attachment')['json'] + check(state['status'] == 'failed', 'terminal error did not reach the API') + client.call('GET', path + '/content', 409, actor=bob) + alive = subprocess.check_output( + ['docker', 'inspect', '--format', '{{.State.Running}} {{.RestartCount}}', container], + text=True, + ).strip() + check(alive == 'true 0', 'worker restarted instead of handling the timeout') + print(f'PASS: two attempts per job, two failed jobs, two DLQ events in {time.monotonic() - started:.1f}s') + finally: + subprocess.run(['docker', 'stop', '--time', '1', container], check=False, capture_output=True) + compose('up', '-d', '--no-deps', 'worker') + + compose('restart', 'broker') + compose('up', '-d', '--wait', '--no-deps', 'broker') + check(dead_letters(attachment_id) == events, 'DLQ did not survive broker restart') + # Repeat the PostgreSQL outbox delivery as if Redis accepted XADD before + # the publisher recorded its success in PostgreSQL. + compose('exec', '-T', 'worker', 'python', '-c', """ +import sys +sys.path.insert(0, 'scripts') +from worker import connect, publish_outbox +with connect() as connection: + connection.execute( + 'UPDATE attachment_jobs SET published_at=NULL WHERE attachment_id=%s', + (sys.argv[1],), + ) +publish_outbox(sys.argv[1]) +""", attachment_id) + check(dead_letters(attachment_id) == events, 'outbox redelivery duplicated a DLQ event') + replay = json.loads(compose('exec', '-T', 'worker', 'python', 'scripts/replay_failed.py', attachment_id)) + check(replay['job_id'] == event['job_id'], 'replay replaced the logical job') + client.wait_ready(bob, attachment) + downloaded = client.call('GET', path + '/content', actor=bob) + check(downloaded['bytes'] == original, 'replayed original changed') + check(dead_letters(attachment_id) == events, 'replay changed the original DLQ event') + print('PASS: DLQ survived broker restart and explicit replay reached ready') + + +if __name__ == '__main__': + main()