Files
mtusi2026lab5/src/pipeline_jobs.py
T
Самохвалов Андрей Ремович b23ecc111f feat: Accept durable queued uploads and publish outbox jobs (U2)
Carry forward the lab4 API and storage baseline, stage verified originals in
MinIO, and atomically commit attachment, job, and outbox records before 202.
Publish identifier-only jobs with broker confirms and reclaimable outbox leases.
Clean abandoned and completed staging objects after database checks.
2026-10-02 14:35:35 +03:00

279 lines
13 KiB
Python

"""Atomic PostgreSQL state changes for the attachment processing pipeline.
Callers own the connection and must commit before replying 202 or acking AMQP.
S3 writes and RabbitMQ publication happen outside these transactions.
"""
from datetime import timezone
from uuid import uuid4
REQUIRED_VARIANTS = {"original", "thumbnail", "crop", "optimized"}
def job_payload(row):
"""Broker message per jobs.schema.json: identifiers only, never file bytes."""
return {
"schema_version": 1,
"job_id": str(row["job_id"]),
"type": "attachment.process.v1",
"attachment_id": str(row["attachment_id"]),
"pipeline_version": row["pipeline_version"],
"attempt": row["attempt"],
"created_at": row["created_at"].astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
}
def reserve_upload(conn, attachment_id, staging_key, lease_seconds=300):
"""Record an active staging PUT before it starts."""
if lease_seconds < 1:
raise ValueError("invalid upload lease")
with conn.transaction():
conn.execute(
"INSERT INTO attachment_uploads (id,staging_key,lease_expires_at) "
"VALUES (%s,%s,clock_timestamp()+make_interval(secs => %s))",
(attachment_id, staging_key, lease_seconds),
)
def renew_upload(conn, attachment_id, lease_seconds=300):
"""Keep a slow, active upload protected from orphan cleanup."""
if lease_seconds < 1:
raise ValueError("invalid upload lease")
with conn.transaction():
return conn.execute(
"UPDATE attachment_uploads SET lease_expires_at=clock_timestamp()+make_interval(secs => %s) "
"WHERE id=%s AND lease_expires_at>clock_timestamp() RETURNING id",
(lease_seconds, attachment_id),
).fetchone() is not None
def queue_attachment(conn, *, attachment_id, chat_id, owner_id, filename,
staging_key, object_key, content_type, size_bytes, sha256,
pipeline_version=1):
"""Commit attachment, job, and outbox after the full S3 staging PUT."""
job_id = uuid4()
with conn.transaction():
marker = conn.execute(
"SELECT id FROM attachment_uploads WHERE id=%s AND staging_key=%s "
"AND lease_expires_at>clock_timestamp() FOR UPDATE",
(attachment_id, staging_key),
).fetchone()
if marker is None:
raise ValueError("upload reservation is missing")
row = conn.execute(
"INSERT INTO attachments "
"(id,chat_id,owner_id,filename,object_key,staging_key,content_type,size_bytes,sha256,status,pipeline_version) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued',%s) "
"RETURNING id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at",
(attachment_id, chat_id, owner_id, filename, object_key, staging_key,
content_type, size_bytes, sha256, pipeline_version),
).fetchone()
conn.execute(
"INSERT INTO attachment_jobs (id,attachment_id,pipeline_version) VALUES (%s,%s,%s)",
(job_id, attachment_id, pipeline_version),
)
conn.execute(
"INSERT INTO attachment_outbox (job_id,attempt) VALUES (%s,1)",
(job_id,),
)
conn.execute("DELETE FROM attachment_uploads WHERE id=%s", (attachment_id,))
return row, job_id
def claim_outbox(conn, limit=10, lease_seconds=30):
"""Lease pending publications; publisher confirms must call confirm_outbox."""
if not 1 <= limit <= 100 or lease_seconds < 1:
raise ValueError("invalid outbox lease")
token = uuid4()
with conn.transaction():
rows = conn.execute(
"WITH due AS ("
" SELECT id FROM attachment_outbox"
" WHERE published_at IS NULL AND available_at<=clock_timestamp()"
" AND (claim_expires_at IS NULL OR claim_expires_at<clock_timestamp())"
" ORDER BY available_at,id LIMIT %s FOR UPDATE SKIP LOCKED"
") UPDATE attachment_outbox o"
" SET claim_token=%s,claim_expires_at=clock_timestamp()+make_interval(secs => %s)"
" FROM due,attachment_jobs j"
" WHERE o.id=due.id AND j.id=o.job_id"
" RETURNING o.id,o.job_id,o.attempt,j.attachment_id,j.pipeline_version,j.created_at",
(limit, token, lease_seconds),
).fetchall()
return token, rows
def confirm_outbox(conn, outbox_id, token):
"""Mark published only after RabbitMQ publisher confirm."""
with conn.transaction():
return conn.execute(
"UPDATE attachment_outbox SET published_at=clock_timestamp(),"
"claim_token=NULL,claim_expires_at=NULL "
"WHERE id=%s AND claim_token=%s AND published_at IS NULL RETURNING id",
(outbox_id, token),
).fetchone() is not None
def claim_job(conn, job_id, delivery_attempt, lease_seconds=60):
"""A stale/redelivered message cannot steal an active or finished job."""
if lease_seconds < 1:
raise ValueError("invalid job lease")
token = uuid4()
with conn.transaction():
job = conn.execute(
"SELECT j.*,a.staging_key,a.object_key,a.sha256,a.content_type,a.size_bytes,"
"a.pipeline_version AS current_pipeline_version "
"FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
"WHERE j.id=%s FOR UPDATE OF j",
(job_id,),
).fetchone()
if (job is None or job["status"] != "queued" or
job["pipeline_version"] != job["current_pipeline_version"] or
job["attempt"] != delivery_attempt or
job["next_attempt_at"] > conn.execute("SELECT clock_timestamp() AS now").fetchone()["now"]):
return None
conn.execute(
"UPDATE attachment_jobs SET status='processing',lease_token=%s,"
"lease_expires_at=clock_timestamp()+make_interval(secs => %s),"
"updated_at=clock_timestamp() WHERE id=%s",
(token, lease_seconds, job_id),
)
conn.execute(
"UPDATE attachments SET status='processing',updated_at=clock_timestamp() "
"WHERE id=%s AND pipeline_version=%s AND status='queued'",
(job["attachment_id"], job["pipeline_version"]),
)
return {**job, "lease_token": token}
def _reschedule_locked(conn, job, *, max_attempts, delay_seconds, error_code, permanent):
if max_attempts < 1 or delay_seconds < 0:
raise ValueError("invalid retry configuration")
failed = permanent or job["attempt"] >= max_attempts
if failed:
code = error_code if permanent else "retry_exhausted"
conn.execute(
"UPDATE attachment_jobs SET status='failed',lease_token=NULL,lease_expires_at=NULL,"
"error_code=%s,updated_at=clock_timestamp() WHERE id=%s",
(code, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() "
"WHERE id=%s AND pipeline_version=%s",
(code, job["attachment_id"], job["pipeline_version"]),
)
else:
attempt = job["attempt"] + 1
due = conn.execute(
"UPDATE attachment_jobs SET status='queued',attempt=%s,lease_token=NULL,lease_expires_at=NULL,"
"next_attempt_at=clock_timestamp()+make_interval(secs => %s),"
"error_code=%s,updated_at=clock_timestamp() WHERE id=%s RETURNING next_attempt_at",
(attempt, delay_seconds, error_code, job["id"]),
).fetchone()["next_attempt_at"]
conn.execute(
"INSERT INTO attachment_outbox (job_id,attempt,available_at) VALUES (%s,%s,%s)",
(job["id"], attempt, due),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() "
"WHERE id=%s AND pipeline_version=%s",
(job["attachment_id"], job["pipeline_version"]),
)
return "failed" if failed else "queued"
def finish_attempt(conn, job_id, token, *, max_attempts, delay_seconds=0,
error_code="processing_failed", permanent=False):
"""Persist retry or terminal failure before the worker acks delivery."""
if error_code not in {"invalid_image", "processing_failed", "storage_unavailable", "worker_timeout"}:
raise ValueError("unsafe error code")
with conn.transaction():
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job_id,)
).fetchone()
if job is None or job["status"] != "processing" or job["lease_token"] != token:
raise ValueError("job lease is no longer owned")
return _reschedule_locked(
conn, job, max_attempts=max_attempts, delay_seconds=delay_seconds,
error_code=error_code, permanent=permanent,
)
def recover_expired(conn, *, max_attempts, delay_seconds=0, limit=20):
"""Requeue dead workers; old delivery attempts become harmless duplicates."""
if not 1 <= limit <= 100:
raise ValueError("invalid recovery batch")
with conn.transaction():
jobs = conn.execute(
"SELECT * FROM attachment_jobs WHERE status='processing' "
"AND lease_expires_at<=clock_timestamp() "
"ORDER BY lease_expires_at,id LIMIT %s FOR UPDATE SKIP LOCKED",
(limit,),
).fetchall()
return [
(job["id"], _reschedule_locked(
conn, job, max_attempts=max_attempts, delay_seconds=delay_seconds,
error_code="worker_timeout", permanent=False,
))
for job in jobs
]
def complete_job(conn, job_id, token, variants):
"""Record every versioned effect, then expose ready atomically.
Returns True when this version is still current. A duplicate ready job is
a harmless no-op; an old version never changes the current attachment.
"""
if set(variants) != REQUIRED_VARIANTS:
raise ValueError("incomplete variant set")
with conn.transaction():
job = conn.execute(
"SELECT j.*,a.object_key,a.sha256,a.content_type,a.size_bytes,"
"a.pipeline_version AS current_pipeline_version "
"FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
"WHERE j.id=%s FOR UPDATE OF j",
(job_id,),
).fetchone()
if job is None:
raise ValueError("unknown job")
if job["status"] == "ready":
return job["pipeline_version"] == job["current_pipeline_version"]
if job["status"] != "processing" or job["lease_token"] != token:
raise ValueError("job lease is no longer owned")
original = variants["original"]
if (original["object_key"] != job["object_key"] or
original["sha256"] != job["sha256"] or
original["content_type"] != job["content_type"] or
original["size_bytes"] != job["size_bytes"]):
raise ValueError("original does not match accepted upload")
for name, value in variants.items():
fields = (value["object_key"], value["content_type"], value["size_bytes"],
value["width"], value["height"], value["sha256"])
conn.execute(
"INSERT INTO attachment_variants "
"(attachment_id,pipeline_version,name,object_key,content_type,size_bytes,width,height,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT DO NOTHING",
(job["attachment_id"], job["pipeline_version"], name, *fields),
)
stored = conn.execute(
"SELECT object_key,content_type,size_bytes,width,height,sha256 "
"FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s AND name=%s",
(job["attachment_id"], job["pipeline_version"], name),
).fetchone()
if stored is None or tuple(stored[key] for key in
("object_key", "content_type", "size_bytes", "width", "height", "sha256")) != fields:
raise ValueError("versioned variant conflicts with a previous effect")
conn.execute(
"UPDATE attachment_jobs SET status='ready',lease_token=NULL,lease_expires_at=NULL,"
"error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",
(job_id,),
)
current = conn.execute(
"UPDATE attachments SET status='ready',error_code=NULL,"
"updated_at=clock_timestamp() "
"WHERE id=%s AND pipeline_version=%s RETURNING id",
(job["attachment_id"], job["pipeline_version"]),
).fetchone()
return current is not None