import asyncio import hashlib import io import json import logging import os import socket import uuid import warnings import time from datetime import timezone import asyncpg import ssl from PIL import Image, ImageOps, UnidentifiedImageError from redis.asyncio import Redis from app.core.config import settings from app.core.openbao import load_service_secrets from app.repositories.object_store import S3ObjectStore from app.telemetry import configure_telemetry from opentelemetry import trace LOG = logging.getLogger('attachment-worker') STREAM = 'messenger:attachment-jobs' GROUP = 'attachment-workers-v1' MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5')) POLL_SECONDS = 0.5 RECLAIM_IDLE_MS = 3000 class InvalidImage(Exception): pass def _make_thumbnail(data: bytes) -> tuple[bytes, int, int]: try: with warnings.catch_warnings(): warnings.simplefilter('error', Image.DecompressionBombWarning) with Image.open(io.BytesIO(data)) as source: if source.width * source.height > settings.max_image_pixels: raise InvalidImage() image = ImageOps.exif_transpose(source) if image.mode in ('RGBA', 'LA') or 'transparency' in image.info: rgba = image.convert('RGBA') rgb = Image.new('RGB', rgba.size, 'white') rgb.paste(rgba, mask=rgba.getchannel('A')) else: rgb = image.convert('RGB') rgb.thumbnail((256, 256), Image.Resampling.LANCZOS) if rgb.width < 1 or rgb.height < 1: raise InvalidImage() output = io.BytesIO() rgb.save(output, format='JPEG', quality=85, optimize=True) return output.getvalue(), rgb.width, rgb.height except InvalidImage: raise except (UnidentifiedImageError, Image.DecompressionBombError, Image.DecompressionBombWarning, OSError, SyntaxError, ValueError): raise InvalidImage() from None class AttachmentWorker: def __init__(self, pool: asyncpg.Pool, redis: Redis, store: S3ObjectStore, meter): self.pool = pool self.redis = redis self.store = store self.consumer = 'worker-' + socket.gethostname() self.tracer = trace.get_tracer('attachment-worker') self.job_counter = meter.create_counter('messenger_jobs_total', unit='{job}') self.job_duration = meter.create_histogram('messenger_job_duration_seconds', unit='s') async def ensure_group(self) -> None: try: await self.redis.xgroup_create(STREAM, GROUP, id='0-0', mkstream=True) except Exception as exc: if 'BUSYGROUP' not in str(exc): raise async def dispatch_outbox(self) -> None: """Публикует задания из PostgreSQL; повтор после сбоя даёт безопасный дубль.""" while True: try: async with self.pool.acquire() as connection: jobs = await connection.fetch( "SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at " "FROM attachment_jobs j WHERE j.state = 'queued' " 'AND j.published_at IS NULL AND j.available_at <= now() ' 'ORDER BY j.available_at, j.created_at LIMIT 20' ) for job in jobs: payload = { 'schema_version': 1, 'job_id': str(job['id']), 'type': 'attachment.process.v1', 'attachment_id': str(job['attachment_id']), 'pipeline_version': job['pipeline_version'], 'attempt': job['attempt'], 'created_at': job['created_at'].astimezone(timezone.utc).isoformat().replace('+00:00', 'Z'), } # XADD завершился успешно — Redis Streams хранит запись на persistent volume. await self.redis.xadd(STREAM, {'payload': json.dumps(payload, separators=(',', ':'))}) await self.pool.execute( "UPDATE attachment_jobs SET published_at = now(), updated_at = now() " "WHERE id = $1 AND state = 'queued' AND attempt = $2 AND published_at IS NULL", job['id'], job['attempt'], ) except asyncio.CancelledError: raise except Exception: LOG.warning('outbox_dispatch_failed') await asyncio.sleep(POLL_SECONDS) async def _load_job(self, payload: dict): job_id = uuid.UUID(payload['job_id']) attachment_id = uuid.UUID(payload['attachment_id']) async with self.pool.acquire() as connection: async with connection.transaction(): job = await connection.fetchrow( 'SELECT * FROM attachment_jobs WHERE id = $1 AND attachment_id = $2 FOR UPDATE', job_id, attachment_id, ) if job is None or job['state'] in ('ready', 'failed'): return None, None, None attachment = await connection.fetchrow( 'SELECT * FROM attachments WHERE id = $1 FOR UPDATE', attachment_id ) if attachment is None: await connection.execute( "UPDATE attachment_jobs SET state = 'failed', error_code = 'processing_failed', updated_at = now() WHERE id = $1", job_id, ) return None, None, None await connection.execute( "UPDATE attachment_jobs SET state = 'processing', updated_at = now() WHERE id = $1", job_id, ) await connection.execute( "UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = $1 AND status <> 'ready'", attachment_id, ) return job, attachment, str(attachment_id) async def _finish_ready(self, job_id, attachment_id, variants: list) -> None: async with self.pool.acquire() as connection: async with connection.transaction(): await connection.execute( "UPDATE attachments SET status = 'ready', variants = $2::jsonb, error_code = NULL, updated_at = now() WHERE id = $1", attachment_id, json.dumps(variants, separators=(',', ':')), ) await connection.execute( "UPDATE attachment_jobs SET state = 'ready', error_code = NULL, updated_at = now() WHERE id = $1", job_id, ) async def _fail_or_retry(self, job_id, attachment_id, permanent: bool, permanent_code: str = 'invalid_image') -> bool: """Сохраняет retry/terminal failure; возвращает True, если попытки исчерпаны.""" async with self.pool.acquire() as connection: async with connection.transaction(): row = await connection.fetchrow( 'SELECT attempt, state FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id ) if row is None or row['state'] in ('ready', 'failed'): return True attempt = row['attempt'] if permanent or attempt >= MAX_ATTEMPTS: code = permanent_code if permanent else 'retry_exhausted' await connection.execute( "UPDATE attachment_jobs SET state = 'failed', error_code = $2, updated_at = now() WHERE id = $1", job_id, code, ) await connection.execute( "UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1", attachment_id, code, ) return True delay = min(2 ** (attempt - 1), 30) await connection.execute( "UPDATE attachment_jobs SET state = 'queued', attempt = attempt + 1, " "available_at = now() + ($2 * interval '1 second'), published_at = NULL, " "error_code = 'processing_retry', updated_at = now() WHERE id = $1", job_id, delay, ) await connection.execute( "UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1", attachment_id, ) return False async def process(self, payload: dict) -> None: started = time.perf_counter() outcome = 'success' job_id = payload.get('job_id') if isinstance(payload, dict) else None with self.tracer.start_as_current_span('attachment.process') as span: span.set_attribute('job.type', 'attachment.process.v1') if isinstance(job_id, str): span.set_attribute('job.id', job_id) try: await self._process_job(payload) if isinstance(job_id, str): try: state = await self.pool.fetchval('SELECT state FROM attachment_jobs WHERE id = $1', uuid.UUID(job_id)) outcome = {'ready': 'success', 'failed': 'error', 'queued': 'retry', 'processing': 'success'}.get(state, 'skipped') except Exception: outcome = 'error' except Exception as exc: outcome = 'error' span.record_exception(exc) raise finally: elapsed = time.perf_counter() - started attrs = {'job.type': 'attachment.process.v1', 'outcome': outcome} self.job_counter.add(1, attrs) self.job_duration.record(elapsed, attrs) LOG.info('attachment_job_completed', extra={'event.name': 'attachment.job.completed', 'job.type': 'attachment.process.v1', 'job.outcome': outcome}) async def _process_job(self, payload: dict) -> None: try: if payload.get('schema_version') != 1 or payload.get('type') != 'attachment.process.v1': return job_id = uuid.UUID(payload['job_id']) attachment_id = uuid.UUID(payload['attachment_id']) except (KeyError, TypeError, ValueError): return job, attachment, attachment_id_text = await self._load_job(payload) if job is None or attachment is None: return stage_key = attachment['staging_key'] if not stage_key: await self._fail_or_retry(job_id, attachment_id, permanent=True, permanent_code='processing_failed') return try: original = await self.store.get(stage_key) thumb_bytes, width, height = await asyncio.to_thread(_make_thumbnail, original) original_key = f'original/{attachment_id_text}' thumbnail_key = f'variants/{attachment_id_text}/v1/thumbnail.jpg' await self.store.put(original_key, original, attachment['content_type']) await self.store.put(thumbnail_key, thumb_bytes, 'image/jpeg') variants = [{ 'name': 'thumbnail', 'content_type': 'image/jpeg', 'size_bytes': len(thumb_bytes), 'sha256': hashlib.sha256(thumb_bytes).hexdigest(), 'width': width, 'height': height, }] await self._finish_ready(job_id, attachment_id, variants) try: await self.store.delete(stage_key) except Exception: LOG.warning('staging_cleanup_failed attachment_id=%s', attachment_id_text) except InvalidImage: terminal = await self._fail_or_retry(job_id, attachment_id, permanent=True) if terminal: try: await self.store.delete(stage_key) except Exception: LOG.warning('staging_cleanup_failed attachment_id=%s', attachment_id_text) except Exception: terminal = await self._fail_or_retry(job_id, attachment_id, permanent=False) if terminal: try: await self.store.delete(stage_key) except Exception: LOG.warning('staging_cleanup_failed attachment_id=%s', attachment_id_text) else: LOG.warning('attachment_retry_scheduled attachment_id=%s', attachment_id_text) async def _ack(self, message_id: str) -> None: await self.redis.xack(STREAM, GROUP, message_id) async def consume(self) -> None: while True: try: claimed = await self.redis.xautoclaim( STREAM, GROUP, self.consumer, RECLAIM_IDLE_MS, start_id='0-0', count=5 ) messages = claimed[1] if claimed and len(claimed) > 1 else [] if not messages: rows = await self.redis.xreadgroup( GROUP, self.consumer, {STREAM: '>'}, count=1, block=1000 ) messages = rows[0][1] if rows else [] for message_id, fields in messages: payload_raw = fields.get('payload', '{}') try: payload = json.loads(payload_raw) except (TypeError, json.JSONDecodeError): payload = {} try: await self.process(payload) except asyncio.CancelledError: raise except Exception: LOG.warning('attachment_job_processing_interrupted') continue await self._ack(message_id) except asyncio.CancelledError: raise except Exception: LOG.warning('stream_consumer_unavailable') await asyncio.sleep(1) async def run() -> None: _, meter = configure_telemetry('messenger-worker') service_secrets = await asyncio.to_thread(load_service_secrets) settings.database_url = service_secrets['database_url'] settings.redis_url = service_secrets['redis_url'] settings.s3_access_key_id = service_secrets['s3_access_key_id'] settings.s3_secret_access_key = service_secrets['s3_secret_access_key'] dsn = settings.resolved_database_url() if not dsn: raise RuntimeError('Set DATABASE_URL before starting the worker') tls = ssl.create_default_context(cafile=settings.tls_ca_file) pool = await asyncpg.create_pool( dsn, ssl=tls, min_size=1, max_size=int(os.getenv('WORKER_DB_POOL_MAX_SIZE', '4')), timeout=settings.db_pool_acquire_timeout_seconds, command_timeout=settings.db_command_timeout_seconds, ) redis_args = dict(decode_responses=True, socket_connect_timeout=settings.redis_timeout_seconds, socket_timeout=settings.redis_timeout_seconds) if settings.resolved_redis_url().startswith('rediss://'): redis_args['ssl_ca_certs'] = settings.tls_ca_file redis_args['ssl_check_hostname'] = True redis = Redis.from_url(settings.resolved_redis_url(), **redis_args) store = S3ObjectStore() worker = AttachmentWorker(pool, redis, store, meter) try: await worker.ensure_group() dispatcher = asyncio.create_task(worker.dispatch_outbox()) consumer = asyncio.create_task(worker.consume()) try: await asyncio.gather(dispatcher, consumer) finally: dispatcher.cancel() consumer.cancel() await asyncio.gather(dispatcher, consumer, return_exceptions=True) finally: await redis.aclose() await pool.close() if __name__ == '__main__': logging.basicConfig(level=os.getenv('LOG_LEVEL', 'INFO')) asyncio.run(run())