"""Process attachment jobs and acknowledge only committed results.""" import hashlib from io import BytesIO import json import logging import signal import tempfile from uuid import UUID from PIL import Image, ImageOps import pika from .attachments import AttachmentStorage, MAX_UPLOAD_BYTES, validate_image from .config import Config from .db import Database from .errors import NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType from .job_lifecycle import claim, complete from .publish_jobs import QUEUE, connect log = logging.getLogger(__name__) def fitted(image, bound): width, height = image.size longest = max(width, height) if longest <= bound: return image.copy() return image.resize((max(1, width * bound // longest), max(1, height * bound // longest)), Image.Resampling.LANCZOS) def save_variants(source, storage, prefix): with Image.open(source, formats=['PNG', 'JPEG']) as original: with ImageOps.exif_transpose(original) as corrected: with corrected.convert('RGBA') as rgba: rgb = Image.new('RGB', rgba.size, 'white') rgb.paste(rgba, mask=rgba.getchannel('A')) with rgb: specs = ( ('thumbnail', 'jpeg', 85, lambda: fitted(rgb, 256)), ('crop', 'jpeg', 85, lambda: ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS)), ('optimized', 'webp', 82, lambda: fitted(rgb, 1280)), ) results = [] for name, fmt, quality, render in specs: with render() as image, BytesIO() as file: image.save(file, format=fmt.upper(), quality=quality) size = file.tell() digest = hashlib.sha256(file.getbuffer()).hexdigest() file.seek(0) key = f'{prefix}/{name}.{fmt}' mime = f'image/{fmt}' storage.put(key, file, size, mime) results.append((name, key, mime, size, digest, image.width, image.height)) return results def materialize(attachment, storage, version, attempt): prefix = f"attachments/final/{attachment['id']}/v{version}/a{attempt}" key = prefix + '/original' stream = storage.download(attachment) try: with tempfile.TemporaryFile() as source: digest, size = hashlib.sha256(), 0 for chunk in stream.chunks(): size += len(chunk) if size > MAX_UPLOAD_BYTES: raise PayloadTooLarge() digest.update(chunk) source.write(chunk) if size != attachment['size_bytes'] or digest.hexdigest() != attachment['sha256']: raise UnsupportedMediaType('Контрольная сумма оригинала не совпадает') validate_image(source, attachment['content_type']) source.seek(0) variants = save_variants(source, storage, prefix) source.seek(0) storage.put(key, source, size, attachment['content_type']) finally: stream.close() return key, variants def process(database, storage, job): attachment = claim(database, job) if attachment is None: return try: result = materialize(attachment, storage, job['pipeline_version'], job['attempt']) except (PayloadTooLarge, UnsupportedMediaType, NotFound): complete(database, job, error_code='invalid_image') except (Unavailable, OSError): complete(database, job) else: complete(database, job, result=result) def parse_job(body): job = json.loads(body) if not isinstance(job, dict) or job.get('type') != QUEUE or job.get('schema_version') != 1: raise ValueError('Unknown job format') for field in ('job_id', 'attachment_id'): UUID(job[field]) for field in ('pipeline_version', 'attempt'): if type(job[field]) is not int or job[field] < 1: raise ValueError('Invalid job number') return job def main(): logging.basicConfig(level=logging.INFO) database = Database(Config.from_env()) database.open() storage = AttachmentStorage() connection = None def timeout(_signal, _frame): raise TimeoutError('Attachment processing exceeded 20 seconds') signal.signal(signal.SIGALRM, timeout) def consume(channel, method, _properties, body): try: job = parse_job(body) except (ValueError, KeyError, TypeError, AttributeError): channel.basic_reject(method.delivery_tag, requeue=False) return signal.alarm(20) try: process(database, storage, job) finally: signal.alarm(0) channel.basic_ack(method.delivery_tag) try: connection = connect() channel = connection.channel() channel.queue_declare(queue=QUEUE, durable=True) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue=QUEUE, on_message_callback=consume) channel.start_consuming() finally: if connection and connection.is_open: connection.close() database.close() if __name__ == '__main__': main()