"""Job payload for the broker. Bytes and credentials never go into the message.""" import json import re from typing import Optional JOB_TYPE = 'attachment.process.v1' PIPELINE_VERSION = 1 QUEUE = 'attachment.jobs' # Same arguments on every declare, otherwise RabbitMQ rejects the second one. QUEUE_ARGUMENTS = {'x-queue-type': 'classic'} _UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') class PermanentJobError(Exception): """Do not retry: another attempt would fail the same way.""" def __init__(self, code: str) -> None: super().__init__(code) self.code = code class TransientJobError(Exception): """Worth another attempt: storage or the broker blinked.""" def staging_key(attachment_id: str) -> str: return 'staging/' + attachment_id def original_key(attachment_id: str) -> str: return 'originals/' + attachment_id def variant_key(attachment_id: str, name: str) -> str: return 'variants/' + attachment_id + '/' + name def dump_job(job_id: str, attachment_id: str, attempt: int, created_at: str) -> bytes: payload = { 'schema_version': 1, 'job_id': job_id, 'type': JOB_TYPE, 'attachment_id': attachment_id, 'pipeline_version': PIPELINE_VERSION, 'attempt': attempt, 'created_at': created_at, } return json.dumps(payload, separators=(',', ':')).encode('utf-8') def load_job(raw: bytes) -> Optional[dict]: """Return the fields the worker trusts, or None when the body is not our job.""" try: data = json.loads(raw.decode('utf-8')) except (UnicodeDecodeError, ValueError): return None if not isinstance(data, dict): return None if data.get('schema_version') != 1 or data.get('type') != JOB_TYPE: return None if data.get('pipeline_version') != PIPELINE_VERSION: return None attempt = data.get('attempt') if type(attempt) is not int or attempt < 1: return None for field in ('job_id', 'attachment_id'): value = data.get(field) if not isinstance(value, str) or _UUID.fullmatch(value) is None: return None created_at = data.get('created_at') if not isinstance(created_at, str) or not created_at.endswith('Z') or len(created_at) > 40: return None return { 'job_id': data['job_id'], 'attachment_id': data['attachment_id'], 'pipeline_version': PIPELINE_VERSION, 'attempt': attempt, 'created_at': created_at, }