"""Worker обрабатывает одну доставку за раз и подтверждает после COMMIT.""" import hashlib import json import logging import signal import subprocess import sys import tempfile import threading import time from datetime import datetime, timezone from contextlib import closing from pathlib import Path import pika import psycopg from botocore.exceptions import BotoCoreError, ClientError from psycopg_pool import PoolTimeout from src import broker, jobs, telemetry from opentelemetry.propagate import extract from opentelemetry.trace import SpanKind, Status, StatusCode from src.objects import BUCKET, ObjectConflict, client, put_immutable from src.storage import storage class PermanentError(Exception): pass def fetch(s3, key, attachment, destination): digest = hashlib.sha256() size = 0 obj = s3.get_object(Bucket=BUCKET, Key=key) with closing(obj['Body']) as stream, destination.open('wb') as output: for chunk in stream.iter_chunks(chunk_size=64 * 1024): size += len(chunk) if size > attachment['size_bytes']: raise PermanentError('staging_integrity') digest.update(chunk) output.write(chunk) if (size, digest.hexdigest()) != (attachment['size_bytes'], attachment['sha256']): raise PermanentError('staging_integrity') def process(job): attachment = job['attachment'] s3 = client() with tempfile.TemporaryDirectory() as temp: directory = Path(temp) original = directory / 'original' source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key'] fetch(s3, source, attachment, original) result = subprocess.run([sys.executable, '-m', 'src.image_pipeline', temp, str(job['pipeline_version'])], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=jobs.JOB_TIMEOUT, check=False) if result.returncode == 2: raise PermanentError('invalid_image') result.check_returncode() with original.open('rb') as stream: put_immutable(s3, attachment['object_key'], stream, attachment['size_bytes'], attachment['content_type'], attachment['sha256']) variants = [] for name, mime, width, height in json.loads((directory / 'manifest.json').read_text()): key = f"variants/{attachment['id']}/v{job['pipeline_version']}/{name}" output = directory / name size = output.stat().st_size with output.open('rb') as stream: digest = hashlib.file_digest(stream, 'sha256').hexdigest() stream.seek(0) put_immutable(s3, key, stream, size, mime, digest) variants.append((name, key, mime, size, digest, width, height)) published = jobs.complete(job, variants) if published: telemetry.ready_duration.record((datetime.now(timezone.utc)-job["attachment"]["created_at"]).total_seconds(), {"job_type":"attachment"}) def handle_inner(channel, delivery, body): try: message = jobs.validate(json.loads(body)) except (ValueError, TypeError, AttributeError): logging.warning('invalid broker job') channel.basic_reject(delivery.delivery_tag, requeue=False) return job = jobs.claim(message) if job: telemetry.busy = 1 started = time.monotonic() outcome = "success" try: with telemetry.span("attachment.transform_and_publish"): process(job) except PermanentError as exc: outcome = "failed" jobs.fail(job, str(exc), permanent=True) except ObjectConflict: outcome = "failed" jobs.fail(job, 'object_conflict', permanent=True) except (BotoCoreError, ClientError, OSError, subprocess.SubprocessError) as exc: outcome = "retry" logging.warning('processing retry job=%s cause=%s', job['id'], type(exc).__name__) jobs.fail(job, 'processing_timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'processing_failed') except (psycopg.Error, PoolTimeout): # No ack: reconnect and durable lease recovery handle this attempt. outcome = "retry" raise finally: telemetry.busy = 0 attrs = {"job_type":"attachment", "outcome":outcome} telemetry.job_count.add(1, attrs) telemetry.job_duration.record(time.monotonic()-started, attrs) if outcome != "success": telemetry.trace.get_current_span().set_status(Status(StatusCode.ERROR)) telemetry.event("job.processed", job_id=str(job["id"]), attempt=job["attempt"], outcome=outcome) else: telemetry.event("job.duplicate") channel.basic_ack(delivery.delivery_tag) def handle(channel, delivery, body): try: raw = json.loads(body) carrier = {k:raw[k] for k in ('traceparent','tracestate') if k in raw} except (ValueError, TypeError): carrier = {} with telemetry.tracer.start_as_current_span('attachment.consume', context=extract(carrier), kind=SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False) as sp: sp.set_attribute('messaging.system', 'rabbitmq') sp.set_attribute('messaging.destination.name', broker.QUEUE) sp.set_attribute('messaging.message.redelivered', delivery.redelivered) handle_inner(channel, delivery, body) def main(): telemetry.setup("messenger-worker") telemetry.register_gauges(storage.pool, worker=True) logging.basicConfig(level=logging.WARNING) stopping = threading.Event() for sig in (signal.SIGINT, signal.SIGTERM): signal.signal(sig, lambda *_: stopping.set()) storage.pool.open(wait=True) try: while not stopping.is_set(): try: with broker.channel(heartbeat=jobs.LEASE_SECONDS + 15) as (_, channel): channel.basic_qos(prefetch_count=1) for delivery, _, body in channel.consume(broker.QUEUE, inactivity_timeout=0.5): if stopping.is_set(): break if delivery: handle(channel, delivery, body) except (pika.exceptions.AMQPError, OSError, psycopg.Error, PoolTimeout) as exc: logging.warning('worker temporarily unavailable: %s', type(exc).__name__) stopping.wait(1) finally: storage.pool.close() if __name__ == '__main__': main()