Files
mtusi2026lab5-fork/app/jobs.py
T
2026-11-22 17:59:11 +03:00

116 lines
3.7 KiB
Python

"""Job payload for the broker. Bytes and credentials never go into the message."""
import json
import random
import re
import uuid
from datetime import datetime, timezone
from typing import Optional
JOB_TYPE = 'attachment.process.v1'
PIPELINE_VERSION = 1
QUEUE = 'attachment.jobs'
DLQ = 'attachment.jobs.dlq'
# Same arguments on every declare, otherwise RabbitMQ rejects the second one.
QUEUE_ARGUMENTS = {'x-queue-type': 'classic'}
DLQ_ARGUMENTS = {'x-queue-type': 'classic'}
REQUIRED_VARIANTS = ('thumbnail', 'crop', 'optimized')
_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 lock_key(attachment_id: uuid.UUID) -> int:
"""Stable bigint for a session advisory lock. One attachment, one runner."""
return attachment_id.int & ((1 << 63) - 1)
def format_timestamp(moment: datetime) -> str:
if moment.tzinfo is None:
moment = moment.replace(tzinfo=timezone.utc)
text = moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
if not text.endswith('Z') or len(text) > 40:
raise ValueError('timestamp does not fit the job contract')
return text
def backoff_seconds(attempt: int, base: float, cap: float, rng: Optional[random.Random] = None) -> float:
"""Full jitter. The ceiling is min(cap, base * 2^(attempt-1)); the draw is uniform below it."""
step = attempt - 1
if step < 0:
step = 0
if step > 20:
step = 20
ceiling = min(cap, base * float(2 ** step))
if ceiling <= 0:
return 0.0
if rng is None:
return random.uniform(0, ceiling)
return rng.uniform(0, ceiling)
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,
}