"""Состояния задания. Эффект один на (attachment_id, pipeline_version, вариант).""" import hashlib import json import os import random import threading import uuid from datetime import datetime, timezone from psycopg.pq import TransactionStatus from psycopg.types.json import Json from opentelemetry.trace import SpanKind, Status, StatusCode from blobs import delete_quiet, put_bytes, read_bytes, variant_object_key from errors import DependencyDown from broker import publish_delay, publish_failed, publish_raw, broker_channel, PROCESS_QUEUE from faults import take_fault from images import PermanentJobError, TransientJobError, render from telemetry import ( extract_context, now_monotonic, record_job, record_time_to_ready, start_span, structured_log, ) REQUIRED = ("original", "thumbnail", "crop", "optimized") PUBLIC_CODES = ("invalid_image", "processing_failed", "retry_exhausted", "processing_timeout") class LostLease(Exception): pass def _idle(conn): if conn.info.transaction_status != TransactionStatus.IDLE: conn.rollback() def max_attempts(): raw = os.environ.get("JOB_MAX_ATTEMPTS", "5") value = int(raw) if not 1 <= value <= 20: raise RuntimeError("JOB_MAX_ATTEMPTS") return value def lease_seconds(): raw = os.environ.get("JOB_TIMEOUT_SECONDS", "60") value = int(raw) if value < 5: raise RuntimeError("JOB_TIMEOUT_SECONDS") return value def retention_seconds(): raw = os.environ.get("STAGING_RETENTION_SECONDS", "86400") value = int(raw) if value < 60: raise RuntimeError("STAGING_RETENTION_SECONDS") return value def utc_now(): return datetime.now(timezone.utc) def dump_time(value): if value.tzinfo is None: value = value.replace(tzinfo=timezone.utc) text = value.astimezone(timezone.utc).isoformat(timespec="microseconds") if text.endswith("+00:00"): text = text[:-6] + "Z" return text def backoff_seconds(failed_attempt): base = min(30.0, 0.5 * (2 ** (failed_attempt - 1))) return base + random.uniform(0, base * 0.25) def job_message(job_id, attachment_id, pipeline_version, attempt, created_at, carrier=None): if not isinstance(created_at, str): created_at = dump_time(created_at) payload = { "schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1", "attachment_id": str(attachment_id), "pipeline_version": int(pipeline_version), "attempt": int(attempt), "created_at": created_at, } if carrier: traceparent = carrier.get("traceparent") tracestate = carrier.get("tracestate") if isinstance(traceparent, str) and len(traceparent) == 55: payload["traceparent"] = traceparent if isinstance(tracestate, str) and 0 < len(tracestate) <= 512: payload["tracestate"] = tracestate return payload def _uuid(value): try: return str(uuid.UUID(str(value))) except (ValueError, AttributeError, TypeError): return None def _stamp(value): if not isinstance(value, str) or not value.endswith("Z"): return None try: datetime.fromisoformat(value[:-1] + "+00:00") except ValueError: return None return value def parse_job(body): try: payload = json.loads(body.decode("utf-8")) except (UnicodeError, ValueError, AttributeError): return None if not isinstance(payload, dict): return None allowed = { "schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at", "traceparent", "tracestate", } if set(payload) - allowed: return None required = allowed - {"traceparent", "tracestate"} if not required <= set(payload): return None if payload.get("schema_version") != 1 or payload.get("type") != "attachment.process.v1": return None job_id = _uuid(payload.get("job_id")) attachment_id = _uuid(payload.get("attachment_id")) created_at = _stamp(payload.get("created_at")) version = payload.get("pipeline_version") attempt = payload.get("attempt") if job_id is None or attachment_id is None or created_at is None: return None if type(version) is not int or type(attempt) is not int: return None if version < 1 or attempt < 1: return None if "traceparent" in payload: traceparent = payload["traceparent"] if not isinstance(traceparent, str) or len(traceparent) != 55: return None if "tracestate" in payload: tracestate = payload["tracestate"] if not isinstance(tracestate, str) or len(tracestate) > 512: return None payload["job_id"] = job_id payload["attachment_id"] = attachment_id return payload def _event(conn, job, kind, detail=None): conn.execute( """ INSERT INTO job_events (job_id, attachment_id, pipeline_version, kind, detail) VALUES (%s, %s, %s, %s, %s) """, (job["id"], job["attachment_id"], job["pipeline_version"], kind, detail), ) def _message_body(job, attempt, created_at): payload = job_message(job["id"], job["attachment_id"], job["pipeline_version"], attempt, created_at) return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") def fail_job(conn, job, code): if code not in PUBLIC_CODES and code != "superseded": code = "processing_failed" _idle(conn) with conn.transaction(): conn.execute( """ UPDATE attachment_jobs SET status = 'failed', error_code = %s, lease_owner = NULL, lease_until = NULL, next_attempt_at = NULL, updated_at = now() WHERE id = %s AND status IN ('queued', 'processing') """, (code, job["id"]), ) if code in PUBLIC_CODES: conn.execute( """ UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now() WHERE id = %s AND pipeline_version = %s AND status IN ('queued', 'processing') """, (code, job["attachment_id"], job["pipeline_version"]), ) _event(conn, job, "failed", code) try: publish_failed(_message_body(job, job["attempt"], job["created_at"])) except Exception: # Реестр failed уже в базе. Повторная доставка увидит failed и подтвердит сообщение. return def schedule_retry(conn, job, code, owner): attempt = int(job["attempt"]) if attempt >= int(job["max_attempts"]): fail_job(conn, job, "retry_exhausted") return delay = backoff_seconds(attempt) new_attempt = attempt + 1 created = utc_now() payload = job_message(job["id"], job["attachment_id"], job["pipeline_version"], new_attempt, created) _idle(conn) with conn.transaction(): updated = conn.execute( """ UPDATE attachment_jobs SET status = 'queued', attempt = %s, lease_owner = NULL, lease_until = NULL, next_attempt_at = now() + make_interval(secs => %s), error_code = NULL, updated_at = now() WHERE id = %s AND status = 'processing' AND lease_owner = %s RETURNING id """, (new_attempt, delay, job["id"], owner), ).fetchone() if updated is None: return conn.execute( """ UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = %s AND pipeline_version = %s AND status = 'processing' """, (job["attachment_id"], job["pipeline_version"]), ) conn.execute( """ INSERT INTO outbox (id, job_id, attempt, payload, created_at) VALUES (%s, %s, %s, %s, %s) """, (uuid.uuid4(), job["id"], new_attempt, Json(payload), created), ) _event(conn, job, "retry", code) def release_expired(conn): released = 0 _idle(conn) with conn.transaction(): rows = conn.execute( """ UPDATE attachment_jobs SET status = 'queued', lease_owner = NULL, lease_until = NULL, updated_at = now() WHERE status = 'processing' AND lease_until < now() RETURNING id, attachment_id, pipeline_version, attempt, created_at """ ).fetchall() for row in rows: payload = job_message(row["id"], row["attachment_id"], row["pipeline_version"], row["attempt"], utc_now()) conn.execute( """ INSERT INTO outbox (id, job_id, attempt, payload, created_at) SELECT %s, %s, %s, %s, now() WHERE NOT EXISTS ( SELECT 1 FROM outbox WHERE job_id = %s AND published_at IS NULL ) """, (uuid.uuid4(), row["id"], row["attempt"], Json(payload), row["id"]), ) conn.execute( """ UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = %s AND pipeline_version = %s AND status = 'processing' """, (row["attachment_id"], row["pipeline_version"]), ) _event(conn, row, "lease_expired", None) released += 1 return released def cleanup_staging(conn): removed = 0 _idle(conn) with conn.transaction(): rows = conn.execute( """ SELECT a.id, a.staging_key FROM attachments a WHERE a.staging_key IS NOT NULL AND a.staging_deleted_at IS NULL AND a.status IN ('ready', 'failed') AND NOT EXISTS ( SELECT 1 FROM attachment_jobs j WHERE j.attachment_id = a.id AND j.status IN ('queued', 'processing') ) """ ).fetchall() for row in rows: if delete_quiet(row["staging_key"]): with conn.transaction(): conn.execute( """ UPDATE attachments SET staging_deleted_at = now() WHERE id = %s AND staging_deleted_at IS NULL """, (row["id"],), ) removed += 1 return removed def _load_job(conn, job_id): return conn.execute( """ SELECT id, attachment_id, pipeline_version, status, attempt, max_attempts, lease_owner, lease_until, next_attempt_at, error_code, created_at FROM attachment_jobs WHERE id = %s """, (job_id,), ).fetchone() def _load_attachment(conn, attachment_id): return conn.execute( """ SELECT id, content_type, sha256, object_key, staging_key, staging_deleted_at, status, pipeline_version FROM attachments WHERE id = %s """, (attachment_id,), ).fetchone() def _acquire(conn, job, owner, seconds): _idle(conn) with conn.transaction(): locked = conn.execute( """ UPDATE attachment_jobs SET status = 'processing', lease_owner = %s, lease_until = now() + make_interval(secs => %s), updated_at = now() WHERE id = %s AND status IN ('queued', 'processing') AND attempt = %s AND pipeline_version = %s AND (lease_owner IS NULL OR lease_owner = %s OR lease_until < now()) RETURNING id """, (owner, seconds, job["id"], job["attempt"], job["pipeline_version"], owner), ).fetchone() if locked is None: return False conn.execute( """ UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = %s AND pipeline_version = %s AND status IN ('queued', 'processing') """, (job["attachment_id"], job["pipeline_version"]), ) _event(conn, job, "leased", None) return True def _variants(conn, attachment_id, version): rows = conn.execute( """ SELECT name, object_key, sha256 FROM attachment_variants WHERE attachment_id = %s AND pipeline_version = %s """, (attachment_id, version), ).fetchall() return {row["name"]: row for row in rows} def _source(conn, attachment): if attachment["staging_key"] and attachment["staging_deleted_at"] is None: data = read_bytes(attachment["staging_key"]) if data: return data data = read_bytes(attachment["object_key"]) if data: return data row = conn.execute( """ SELECT object_key FROM attachment_variants WHERE attachment_id = %s AND name = 'original' ORDER BY pipeline_version DESC LIMIT 1 """, (attachment["id"],), ).fetchone() if row is None: raise TransientJobError("processing_failed") data = read_bytes(row["object_key"]) if not data: raise TransientJobError("processing_failed") return data def _render_limited(data, declared, seconds): budget = max(5, seconds - 5) box = [] errors = [] def run(): try: box.append(render(data, declared)) except Exception as exc: errors.append(exc) thread = threading.Thread(target=run, daemon=True) thread.start() thread.join(budget) if thread.is_alive(): raise TransientJobError("processing_timeout") if errors: exc = errors[0] if isinstance(exc, (PermanentJobError, TransientJobError)): raise exc raise PermanentJobError("invalid_image") return box[0] def _beat(pool, job_id, owner, seconds, stop): pause = max(2, seconds // 3) while not stop.wait(pause): try: with pool.connection() as conn: with conn.transaction(): conn.execute( """ UPDATE attachment_jobs SET lease_until = now() + make_interval(secs => %s), updated_at = now() WHERE id = %s AND lease_owner = %s AND status = 'processing' """, (seconds, job_id, owner), ) except Exception: return def _supersede(conn, job): _idle(conn) with conn.transaction(): conn.execute( """ UPDATE attachment_jobs SET status = 'superseded', error_code = 'superseded', lease_owner = NULL, lease_until = NULL, next_attempt_at = NULL, updated_at = now() WHERE id = %s AND status IN ('queued', 'processing') """, (job["id"],), ) _event(conn, job, "superseded", None) def _finalize(conn, job, owner, rendered): _idle(conn) with conn.transaction(): current = conn.execute( """ SELECT lease_owner, status, pipeline_version FROM attachment_jobs WHERE id = %s FOR UPDATE """, (job["id"],), ).fetchone() if current is None or current["lease_owner"] != owner or current["status"] != "processing": raise LostLease() attachment = conn.execute( """ SELECT pipeline_version, status FROM attachments WHERE id = %s FOR UPDATE """, (job["attachment_id"],), ).fetchone() if attachment is None or int(attachment["pipeline_version"]) > int(job["pipeline_version"]): conn.execute( """ UPDATE attachment_jobs SET status = 'superseded', error_code = 'superseded', lease_owner = NULL, lease_until = NULL, updated_at = now() WHERE id = %s """, (job["id"],), ) _event(conn, job, "superseded", None) return "superseded" now = utc_now() for name in REQUIRED: item = rendered[name] conn.execute( """ INSERT INTO attachment_variants ( attachment_id, pipeline_version, name, content_type, size_bytes, width, height, sha256, object_key, created_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING """, ( job["attachment_id"], job["pipeline_version"], name, item["content_type"], len(item["bytes"]), item["width"], item["height"], item["sha256"], item["object_key"], now, ), ) stored = conn.execute( """ SELECT count(*) AS n FROM attachment_variants WHERE attachment_id = %s AND pipeline_version = %s AND name IN ('original', 'thumbnail', 'crop', 'optimized') """, (job["attachment_id"], job["pipeline_version"]), ).fetchone() if int(stored["n"]) < len(REQUIRED): raise TransientJobError("processing_failed") original = rendered["original"] conn.execute( """ UPDATE attachments SET status = 'ready', error_code = NULL, pipeline_version = %s, object_key = %s, updated_at = %s WHERE id = %s AND pipeline_version <= %s """, ( job["pipeline_version"], original["object_key"], now, job["attachment_id"], job["pipeline_version"], ), ) conn.execute( """ UPDATE attachment_jobs SET status = 'ready', error_code = NULL, lease_owner = NULL, lease_until = NULL, next_attempt_at = NULL, updated_at = %s WHERE id = %s AND lease_owner = %s """, (now, job["id"], owner), ) _event(conn, job, "ready", None) return "ready" def _drop_staging(conn, attachment): _idle(conn) with conn.transaction(): active = conn.execute( """ SELECT count(*) AS n FROM attachment_jobs WHERE attachment_id = %s AND status IN ('queued', 'processing') """, (attachment["id"],), ).fetchone() if int(active["n"]) > 0 or not attachment["staging_key"]: return if delete_quiet(attachment["staging_key"]): with conn.transaction(): conn.execute( """ UPDATE attachments SET staging_deleted_at = now() WHERE id = %s AND staging_deleted_at IS NULL """, (attachment["id"],), ) def process_delivery(pool, body, owner): payload = parse_job(body) if payload is None: return "ack" carrier = {} if "traceparent" in payload: carrier["traceparent"] = payload["traceparent"] if "tracestate" in payload: carrier["tracestate"] = payload["tracestate"] parent = extract_context(carrier) if carrier else None started = now_monotonic() with start_span( "attachments.process consume", kind=SpanKind.CONSUMER, context=parent, attributes={ "messaging.system": "rabbitmq", "messaging.destination.name": PROCESS_QUEUE, "messaging.operation": "process", "job.type": "attachment.process.v1", }, ) as span: return _process_delivery_body(pool, body, owner, payload, span, started) def _process_delivery_body(pool, body, owner, payload, span, started): import logging logger = logging.getLogger("worker") with pool.connection() as conn: job = _load_job(conn, payload["job_id"]) if job is None: return "ack" if job["status"] in ("ready", "failed", "superseded"): return "ack" if int(payload["attempt"]) != int(job["attempt"]) or int(payload["pipeline_version"]) != int(job["pipeline_version"]): return "ack" if job["next_attempt_at"] is not None and job["next_attempt_at"] > utc_now(): delay = (job["next_attempt_at"] - utc_now()).total_seconds() publish_delay(body, int(delay * 1000)) return "ack" with pool.connection() as conn: attachment = _load_attachment(conn, job["attachment_id"]) if attachment is None: fail_job(conn, job, "invalid_image") record_job("failed", now_monotonic() - started) return "ack" if int(attachment["pipeline_version"]) > int(job["pipeline_version"]): _supersede(conn, job) record_job("superseded", now_monotonic() - started) return "ack" if not _acquire(conn, job, owner, lease_seconds()): publish_delay(body, 2000) return "ack" structured_log(logger, "job_leased", job_id=str(job["id"]), attempt=int(job["attempt"])) stop = threading.Event() beater = threading.Thread( target=_beat, args=(pool, job["id"], owner, lease_seconds(), stop), daemon=True, ) beater.start() try: with start_span("s3.read_source", kind=SpanKind.CLIENT): with pool.connection() as conn: if take_fault(conn, "crash_before_effect", job["attachment_id"]): os_exit() if take_fault(conn, "transient_once", job["attachment_id"]): raise TransientJobError("processing_failed") present = _variants(conn, job["attachment_id"], job["pipeline_version"]) source = None if set(REQUIRED) <= set(present) else _source(conn, attachment) if source is None: rendered = _rendered_from_rows(conn, job, present) if source is not None: if hashlib.sha256(source).hexdigest() != attachment["sha256"]: raise PermanentJobError("invalid_image") with start_span("image.render", kind=SpanKind.INTERNAL): rendered = _render_limited(source, attachment["content_type"], lease_seconds()) with start_span("s3.write_variants", kind=SpanKind.CLIENT): for name in REQUIRED: item = rendered[name] item["sha256"] = hashlib.sha256(item["bytes"]).hexdigest() item["object_key"] = variant_object_key(job["attachment_id"], job["pipeline_version"], name) if name in present: continue put_bytes(item["object_key"], item["bytes"], item["content_type"], utc_now()) with pool.connection() as conn: if take_fault(conn, "crash_after_objects", job["attachment_id"]): os_exit() with start_span("db.finalize_ready", kind=SpanKind.CLIENT): with pool.connection() as conn: _finalize(conn, job, owner, rendered) with pool.connection() as conn: if take_fault(conn, "crash_after_commit", job["attachment_id"]): os_exit() with pool.connection() as conn: _drop_staging(conn, attachment) duration = now_monotonic() - started record_job("ready", duration) if job.get("created_at") is not None: created = job["created_at"] if created.tzinfo is None: created = created.replace(tzinfo=timezone.utc) record_time_to_ready((utc_now() - created).total_seconds()) structured_log(logger, "job_ready", job_id=str(job["id"]), duration_ms=round(duration * 1000, 3)) span.set_status(Status(StatusCode.OK)) return "ack" except PermanentJobError as exc: with pool.connection() as conn: fail_job(conn, job, exc.code) record_job("failed", now_monotonic() - started) span.set_status(Status(StatusCode.ERROR, exc.code)) structured_log(logger, "job_failed", level=30, job_id=str(job["id"]), error_code=exc.code) return "ack" except LostLease: return "ack" except (TransientJobError, DependencyDown) as exc: code = exc.code if isinstance(exc, TransientJobError) else "processing_failed" with pool.connection() as conn: schedule_retry(conn, job, code, owner) record_job("retry", now_monotonic() - started) span.set_status(Status(StatusCode.ERROR, code)) structured_log(logger, "job_retry", level=30, job_id=str(job["id"]), error_code=code) return "ack" finally: stop.set() def os_exit(): os._exit(75) def _rendered_from_rows(conn, job, present): # Повтор после уже записанного эффекта не перекодирует файлы. rendered = {} for name in REQUIRED: row = present[name] data = read_bytes(row["object_key"]) if data is None: raise TransientJobError("processing_failed") meta = conn.execute( """ SELECT content_type, width, height, sha256, object_key FROM attachment_variants WHERE attachment_id = %s AND pipeline_version = %s AND name = %s """, (job["attachment_id"], job["pipeline_version"], name), ).fetchone() rendered[name] = { "bytes": data, "content_type": meta["content_type"], "width": int(meta["width"]), "height": int(meta["height"]), "sha256": meta["sha256"], "object_key": meta["object_key"], } return rendered def bump_pipeline(conn, attachment_id): _idle(conn) with conn.transaction(): row = conn.execute( "SELECT id, pipeline_version FROM attachments WHERE id = %s FOR UPDATE", (attachment_id,), ).fetchone() if row is None: return None version = int(row["pipeline_version"]) + 1 job_id = uuid.uuid4() created = utc_now() final_key = variant_object_key(attachment_id, version, "original") conn.execute( """ UPDATE attachments SET pipeline_version = %s, status = 'queued', error_code = NULL, object_key = %s, updated_at = %s WHERE id = %s """, (version, final_key, created, attachment_id), ) attempts = max_attempts() conn.execute( """ INSERT INTO attachment_jobs ( id, attachment_id, pipeline_version, status, attempt, max_attempts, created_at, updated_at ) VALUES (%s, %s, %s, 'queued', 1, %s, %s, %s) """, (job_id, attachment_id, version, attempts, created, created), ) payload = job_message(job_id, attachment_id, version, 1, created) conn.execute( """ INSERT INTO outbox (id, job_id, attempt, payload, created_at) VALUES (%s, %s, 1, %s, %s) """, (uuid.uuid4(), job_id, Json(payload), created), ) conn.execute( """ INSERT INTO job_events (job_id, attachment_id, pipeline_version, kind, detail) VALUES (%s, %s, %s, 'version', %s) """, (job_id, attachment_id, version, str(version)), ) return {"job_id": str(job_id), "pipeline_version": version} def replay_job(conn, job_id): _idle(conn) with conn.transaction(): job = conn.execute( """ SELECT id, attachment_id, pipeline_version, status, attempt, max_attempts, created_at FROM attachment_jobs WHERE id = %s FOR UPDATE """, (job_id,), ).fetchone() if job is None: return {"result": "missing"} if job["status"] == "ready": return {"result": "already_ready"} names = conn.execute( """ SELECT name FROM attachment_variants WHERE attachment_id = %s AND pipeline_version = %s """, (job["attachment_id"], job["pipeline_version"]), ).fetchall() have = {row["name"] for row in names} if set(REQUIRED) <= have: conn.execute( """ UPDATE attachment_jobs SET status = 'ready', error_code = NULL, lease_owner = NULL, lease_until = NULL, next_attempt_at = NULL, updated_at = now() WHERE id = %s AND status <> 'ready' """, (job["id"],), ) return {"result": "already_done"} if job["status"] != "failed": return {"result": "not_failed"} created = utc_now() conn.execute( """ UPDATE attachment_jobs SET status = 'queued', attempt = 1, error_code = NULL, lease_owner = NULL, lease_until = NULL, next_attempt_at = NULL, updated_at = %s WHERE id = %s """, (created, job["id"]), ) conn.execute( """ UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = %s WHERE id = %s AND pipeline_version = %s AND status = 'failed' """, (created, job["attachment_id"], job["pipeline_version"]), ) payload = job_message(job["id"], job["attachment_id"], job["pipeline_version"], 1, created) conn.execute( """ INSERT INTO outbox (id, job_id, attempt, payload, created_at) VALUES (%s, %s, 1, %s, %s) """, (uuid.uuid4(), job["id"], Json(payload), created), ) _event(conn, job, "replay", None) return {"result": "queued"} def republish(conn, job_id, attempt=None): job = conn.execute( """ SELECT id, attachment_id, pipeline_version, attempt, created_at FROM attachment_jobs WHERE id = %s """, (job_id,), ).fetchone() if job is None: return False chosen = int(job["attempt"] if attempt is None else attempt) body = _message_body(job, chosen, utc_now()) with broker_channel() as channel: publish_raw(channel, PROCESS_QUEUE, body) return True