"""Separate process: publish the staged original and the level-4 variants. Ack happens only after the ready row is committed. A kill after the object put and before ack redelivers the same job id; variant primary keys keep a single set. Staging is removed only after that commit. Failed staging stays until retention so an operator can still replay. """ import asyncio import hashlib import logging import os import signal import uuid from datetime import datetime, timedelta, timezone from pathlib import Path import asyncpg from .broker import Broker, BrokerDown from .config import ( effective_lease_seconds, job_max_attempts, job_timeout_seconds, load_broker_url, load_object_settings, load_settings, retry_base_seconds, retry_cap_seconds, staging_retention_seconds, worker_concurrency, ) from .fault import consume_fault from .jobs import ( DLQ, PIPELINE_VERSION, REQUIRED_VARIANTS, PermanentJobError, TransientJobError, backoff_seconds, load_job, lock_key, variant_key, ) from .objects import MissingObject, ObjectStore, StorageError from .outbox import due_at, publish_pending, reclaim_expired from .thumbnail import ImageRejected, render_variants logger = logging.getLogger('messenger') _HEARTBEAT = Path('/tmp/worker-alive') _inflight = 0 _ACK_LOCK = asyncio.Lock() def _prepare(objects: ObjectStore, attachment_id: str, staging: str, final: str, size: int, digest: str, content_type: str) -> list: """Copy the original unchanged and write every required variant. Runs off the event loop.""" try: data = objects.get(staging) except MissingObject: raise TransientJobError() from None except StorageError: raise TransientJobError() from None if len(data) != size or hashlib.sha256(data).hexdigest() != digest: raise PermanentJobError('processing_failed') if staging != final: try: objects.put(final, data, content_type) except StorageError: raise TransientJobError() from None try: rendered = render_variants(data) except ImageRejected: raise PermanentJobError('invalid_image') from None except MemoryError: raise PermanentJobError('invalid_image') from None if set(rendered) != set(REQUIRED_VARIANTS): raise PermanentJobError('processing_failed') stored = [] for name in REQUIRED_VARIANTS: item = rendered[name] key = variant_key(attachment_id, name) blob = item['data'] try: objects.put(key, blob, str(item['content_type'])) except StorageError: raise TransientJobError() from None stored.append({ 'name': name, 'content_type': item['content_type'], 'object_key': key, 'size_bytes': len(blob), 'width': int(item['width']), 'height': int(item['height']), 'sha256': hashlib.sha256(blob).hexdigest(), }) return stored async def _record_failure(conn: asyncpg.Connection, job: dict, code: str, permanent: bool) -> None: await conn.execute( ''' INSERT INTO attachment_job_failures (job_id, attempt, error_code, permanent, created_at) VALUES ($1, $2, $3, $4, clock_timestamp()) ON CONFLICT (job_id, attempt, error_code) DO NOTHING ''', uuid.UUID(job['job_id']), job['attempt'], code, permanent, ) async def _fail(conn: asyncpg.Connection, broker: Broker, job: dict, attachment_id: uuid.UUID, code: str, permanent: bool) -> None: """Terminal state plus the failure registry. The DLQ copy is best-effort after the commit.""" async with conn.transaction(): status = await conn.fetchval( 'SELECT status FROM attachments WHERE id = $1 FOR UPDATE', attachment_id, ) if status == 'ready': return await conn.execute( ''' UPDATE attachments SET status = 'failed', error_code = $2, updated_at = clock_timestamp() WHERE id = $1 AND status = 'processing' ''', attachment_id, code, ) await _record_failure(conn, job, code, permanent) await conn.execute( ''' UPDATE attachment_jobs SET lease_until = NULL, last_error = $2, updated_at = clock_timestamp() WHERE id = $1 ''', uuid.UUID(job['job_id']), code, ) try: await broker.publish(dump_current(job), DLQ, {'x-error-code': code}) except BrokerDown: logger.warning('job %s recorded as %s; DLQ did not confirm', job['job_id'], code) def dump_current(job: dict) -> bytes: from .jobs import dump_job return dump_job(job['job_id'], job['attachment_id'], job['attempt'], job['created_at']) async def _schedule_retry(conn: asyncpg.Connection, job: dict, attachment_id: uuid.UUID, limit: int, code: str) -> None: """Park the next attempt in the outbox. The current delivery is acked by the caller.""" nxt = job['attempt'] + 1 if nxt > limit: return False delay = backoff_seconds(job['attempt'], retry_base_seconds(), retry_cap_seconds()) async with conn.transaction(): moved = await conn.fetchval( ''' UPDATE attachment_jobs SET attempt = $2, runs = 0, available_at = $3, published_at = NULL, lease_until = NULL, last_error = $4, updated_at = clock_timestamp() WHERE id = $1 AND attempt = $5 RETURNING attempt ''', uuid.UUID(job['job_id']), nxt, due_at(delay), code, job['attempt'], ) if moved is None: return True await conn.execute( ''' UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() WHERE id = $1 AND status = 'processing' ''', attachment_id, ) logger.info('attachment %s attempt %s will retry in %.3fs (%s)', job['attachment_id'], job['attempt'], delay, code) return True async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, job_id: uuid.UUID, variants: list) -> bool: async with conn.transaction(): status = await conn.fetchval( 'SELECT status FROM attachments WHERE id = $1 FOR UPDATE', attachment_id, ) if status != 'processing': return False for item in variants: await conn.execute( ''' INSERT INTO attachment_variants ( attachment_id, pipeline_version, name, content_type, size_bytes, width, height, sha256, object_key ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256, object_key = EXCLUDED.object_key ''', attachment_id, PIPELINE_VERSION, item['name'], item['content_type'], item['size_bytes'], item['width'], item['height'], item['sha256'], item['object_key'], ) await conn.execute( ''' UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() WHERE id = $1 AND status = 'processing' ''', attachment_id, ) await conn.execute( ''' UPDATE attachment_jobs SET lease_until = NULL, last_error = NULL, updated_at = clock_timestamp() WHERE id = $1 ''', job_id, ) return True async def _drop_staging(conn: asyncpg.Connection, objects: ObjectStore, attachment_id: uuid.UUID, staging: str, final: str) -> None: """Remove staging only after ready is committed and the final object is the copy.""" if not staging or staging == final: return try: await asyncio.to_thread(objects.delete, staging) except StorageError: logger.warning('staging left in place for %s', attachment_id) return await conn.execute( ''' UPDATE attachments SET staging_key = object_key WHERE id = $1 AND status = 'ready' AND staging_key = $2 ''', attachment_id, staging, ) async def _beat_lease(pool: asyncpg.Pool, job_id: uuid.UUID, stop: asyncio.Event, lease_seconds: int) -> None: interval = max(1.0, lease_seconds / 3) while not stop.is_set(): try: async with pool.acquire() as conn: await conn.execute( ''' UPDATE attachment_jobs SET lease_until = $2 WHERE id = $1 ''', job_id, datetime.now(timezone.utc) + timedelta(seconds=lease_seconds), ) except Exception: logger.warning('lease refresh failed') try: await asyncio.wait_for(stop.wait(), timeout=interval) except asyncio.TimeoutError: pass async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, lease_seconds: int, timeout: int) -> None: attachment_id = uuid.UUID(job['attachment_id']) job_id = uuid.UUID(job['job_id']) async with pool.acquire() as conn: await conn.execute('SELECT pg_advisory_lock($1)', lock_key(attachment_id)) try: row = await conn.fetchrow( ''' SELECT a.status, a.staging_key, a.object_key, a.size_bytes, a.sha256, a.content_type, j.attempt, j.max_attempts FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = $1 ''', job_id, ) if row is None or row['status'] in ('ready', 'failed'): return if job['attempt'] != row['attempt']: # A newer attempt is already in the outbox, or this delivery is stale. return lease_until = datetime.now(timezone.utc) + timedelta(seconds=lease_seconds) async with conn.transaction(): runs = await conn.fetchval( ''' UPDATE attachment_jobs SET runs = runs + 1, lease_until = $2, updated_at = clock_timestamp() WHERE id = $1 AND attempt = $3 RETURNING runs ''', job_id, lease_until, job['attempt'], ) if runs is None: return if runs > row['max_attempts']: await conn.execute( ''' UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', updated_at = clock_timestamp() WHERE id = $1 AND status IN ('queued', 'processing') ''', attachment_id, ) await _record_failure(conn, job, 'retry_exhausted', True) await conn.execute( ''' UPDATE attachment_jobs SET lease_until = NULL, last_error = 'retry_exhausted', updated_at = clock_timestamp() WHERE id = $1 ''', job_id, ) exhausted = True else: await conn.execute( ''' UPDATE attachments SET status = 'processing', error_code = NULL, updated_at = clock_timestamp() WHERE id = $1 AND status IN ('queued', 'processing') ''', attachment_id, ) exhausted = False if exhausted: try: await broker.publish(dump_current(job), DLQ, {'x-error-code': 'retry_exhausted'}) except BrokerDown: logger.warning('job %s exhausted; DLQ did not confirm', job['job_id']) return stop_lease = asyncio.Event() beat = asyncio.create_task(_beat_lease(pool, job_id, stop_lease, lease_seconds)) try: try: if await consume_fault(pool, 'transient-once'): raise TransientJobError() if await consume_fault(pool, 'permanent-once'): raise PermanentJobError('invalid_image') variants = await asyncio.wait_for( asyncio.to_thread( _prepare, objects, job['attachment_id'], row['staging_key'], row['object_key'], row['size_bytes'], row['sha256'], row['content_type'], ), timeout=timeout, ) except PermanentJobError as exc: await _fail(conn, broker, job, attachment_id, exc.code, True) return except TransientJobError: if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'storage'): await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True) return except asyncio.TimeoutError: if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'timeout'): await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True) return except Exception as exc: logger.warning( 'attachment %s attempt %s failed (%s)', job['attachment_id'], job['attempt'], type(exc).__name__, ) if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'processing_failed'): await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True) return if await consume_fault(pool, 'exit-after-put'): logger.warning('fault exit-after-put: leaving %s unacked after object put', job['attachment_id']) logging.shutdown() os._exit(75) finished = await _finish(conn, attachment_id, job_id, variants) if finished: await _drop_staging(conn, objects, attachment_id, row['staging_key'], row['object_key']) logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt']) finally: stop_lease.set() beat.cancel() finally: await conn.execute('SELECT pg_advisory_unlock($1)', lock_key(attachment_id)) async def _handle(pool, objects, broker, body: bytes, lease_seconds: int, timeout: int) -> None: job = load_job(body) if job is None: logger.warning('dropped a job message that does not match the contract') return await _process(pool, objects, broker, job, lease_seconds, timeout) async def _alive(stop: asyncio.Event) -> None: while not stop.is_set(): _HEARTBEAT.write_text('ok', encoding='ascii') try: await asyncio.wait_for(stop.wait(), timeout=5) except asyncio.TimeoutError: pass async def _cleanup_staging(pool: asyncpg.Pool, objects: ObjectStore, retention: int) -> None: cutoff = datetime.now(timezone.utc) - timedelta(seconds=retention) async with pool.acquire() as conn: ready = await conn.fetch( ''' SELECT id, staging_key, object_key FROM attachments WHERE status = 'ready' AND staging_key <> object_key LIMIT 20 ''' ) failed = await conn.fetch( ''' SELECT id, staging_key FROM attachments WHERE status = 'failed' AND staging_key <> object_key AND updated_at <= $1 LIMIT 20 ''', cutoff, ) for row in ready: try: await asyncio.to_thread(objects.delete, row['staging_key']) except StorageError: continue async with pool.acquire() as conn: await conn.execute( ''' UPDATE attachments SET staging_key = object_key WHERE id = $1 AND status = 'ready' AND staging_key = $2 ''', row['id'], row['staging_key'], ) for row in failed: async with pool.acquire() as conn: claimed = await conn.fetchval( ''' UPDATE attachments SET staging_key = object_key WHERE id = $1 AND status = 'failed' AND staging_key = $2 AND updated_at <= $3 RETURNING id ''', row['id'], row['staging_key'], cutoff, ) if claimed is None: continue try: await asyncio.to_thread(objects.delete, row['staging_key']) except StorageError: logger.warning('failed staging %s was unlinked in metadata and is still in the bucket', row['id']) async def _maintain(pool, broker, objects, stop: asyncio.Event, retention: int) -> None: ticks = 0 while not stop.is_set(): try: await publish_pending(pool, broker) await reclaim_expired(pool) ticks += 1 if ticks % 30 == 0: await _cleanup_staging(pool, objects, retention) except Exception: logger.exception('worker maintenance failed') try: await asyncio.wait_for(stop.wait(), timeout=1) except asyncio.TimeoutError: pass async def _run() -> None: logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s') logging.getLogger('aio_pika').setLevel(logging.ERROR) logging.getLogger('aiormq').setLevel(logging.ERROR) stop = asyncio.Event() loop = asyncio.get_running_loop() for sig in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(sig, stop.set) # Imported for the side effect of validating the pool settings the API also uses. load_settings() job_max_attempts() timeout = job_timeout_seconds() lease_seconds = effective_lease_seconds() retention = staging_retention_seconds() prefetch = worker_concurrency() pool = await open_pool_from_settings() objects = ObjectStore(load_object_settings()) broker = Broker(load_broker_url()) alive = asyncio.create_task(_alive(stop)) maintain = None try: await broker.connect() # consumer_channel stays referenced until this function returns, so it is not closed early. consumer_channel, queue = await broker.open_consumer(prefetch) maintain = asyncio.create_task(_maintain(pool, broker, objects, stop, retention)) async def on_message(message) -> None: global _inflight _inflight += 1 try: await _handle(pool, objects, broker, message.body, lease_seconds, timeout) except BrokerDown: async with _ACK_LOCK: await message.nack(requeue=True) return except Exception: logger.exception('job was not finished') async with _ACK_LOCK: await message.nack(requeue=True) return else: async with _ACK_LOCK: await message.ack() finally: _inflight -= 1 consumer = await queue.consume(on_message) logger.info( 'worker consuming %s prefetch %s lease %ss channel %s', queue.name, prefetch, lease_seconds, id(consumer_channel), ) await stop.wait() logger.info('worker draining') await queue.cancel(consumer) for _ in range(500): if _inflight == 0: break await asyncio.sleep(0.05) finally: alive.cancel() if maintain is not None: maintain.cancel() await broker.close() await pool.close() async def open_pool_from_settings(): from .db import open_pool return await open_pool(load_settings().database_url) def main() -> None: asyncio.run(_run()) if __name__ == '__main__': main()