forked from mtusi2026/mtusi2026lab5
170 lines
6.9 KiB
Python
170 lines
6.9 KiB
Python
import json
|
|
import random
|
|
import uuid
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from .config import secret
|
|
|
|
|
|
class Repository:
|
|
def __init__(self, settings):
|
|
self.settings = settings
|
|
|
|
def connection(self):
|
|
return psycopg.connect(
|
|
host=self.settings.db_host,
|
|
dbname=secret("postgres_db"),
|
|
user=secret("postgres_user"),
|
|
password=secret("postgres_password"),
|
|
connect_timeout=3,
|
|
options="-c statement_timeout=10000",
|
|
row_factory=dict_row,
|
|
)
|
|
|
|
def event(self, db, job, name):
|
|
db.execute(
|
|
"INSERT INTO pipeline_events(job_id,event,attempt) VALUES (%s,%s,%s)",
|
|
(job["job_id"], name, job.get("attempt", 0)),
|
|
)
|
|
|
|
def claim(self, message):
|
|
with self.connection() as db:
|
|
job = self._lock_job(db, message)
|
|
if (
|
|
not job
|
|
or job["status"] != "QUEUED"
|
|
or not job["due"]
|
|
or message["attempt"] != job["attempt"] + 1
|
|
):
|
|
return None
|
|
token = uuid.uuid4()
|
|
db.execute(
|
|
"""UPDATE processing_jobs SET status='PROCESSING', attempt=attempt+1,
|
|
lease_token=%s, lease_until=now() + %s * interval '1 second' WHERE job_id=%s""",
|
|
(token, self.settings.lease, job["job_id"]),
|
|
)
|
|
db.execute(
|
|
"UPDATE attachments SET status='PROCESSING',updated_at=now() WHERE id=%s",
|
|
(job["attachment_id"],),
|
|
)
|
|
job.update(lease_token=token, attempt=job["attempt"] + 1)
|
|
self.event(db, job, "claimed")
|
|
return job
|
|
|
|
def _lock_job(self, db, message):
|
|
return db.execute(
|
|
"""SELECT j.*, a.object_key, a.staging_key, a.content_type,
|
|
a.checksum, a.size_bytes, j.next_at <= now() AS due, j.lease_until > now() AS live
|
|
FROM attachments a JOIN processing_jobs j ON a.id=j.attachment_id
|
|
WHERE j.job_id=%s AND j.attachment_id=%s AND j.pipeline_version=%s
|
|
AND a.pipeline_version=j.pipeline_version
|
|
FOR UPDATE OF a,j SKIP LOCKED""",
|
|
(message["job_id"], message["attachment_id"], message["pipeline_version"]),
|
|
).fetchone()
|
|
|
|
def delivery_done(self, message):
|
|
with self.connection() as db:
|
|
row = db.execute(
|
|
"""SELECT j.status,j.attempt,a.pipeline_version FROM processing_jobs j
|
|
JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s AND j.attachment_id=%s""",
|
|
(message["job_id"], message["attachment_id"]),
|
|
).fetchone()
|
|
if not row or row["pipeline_version"] != message["pipeline_version"]:
|
|
return True
|
|
if row["status"] not in ("QUEUED", "PROCESSING"):
|
|
return True
|
|
expected = row["attempt"] + (1 if row["status"] == "QUEUED" else 0)
|
|
return message["attempt"] != expected
|
|
|
|
def publish_result(self, job, original_key, variants):
|
|
with self.connection() as db:
|
|
current = self._lock_job(db, job)
|
|
if not self._owns(current, job):
|
|
self.event(db, job, "fenced_stale_result")
|
|
return False
|
|
self._save_variants(db, job, variants)
|
|
db.execute(
|
|
"""UPDATE attachments SET object_key=%s,status='READY',error_code=NULL,
|
|
updated_at=now() WHERE id=%s AND pipeline_version=%s""",
|
|
(original_key, job["attachment_id"], job["pipeline_version"]),
|
|
)
|
|
db.execute(
|
|
"""UPDATE processing_jobs SET status='READY',completed_at=now(),
|
|
lease_until=NULL,error_code=NULL WHERE job_id=%s""",
|
|
(job["job_id"],),
|
|
)
|
|
self.event(db, job, "ready")
|
|
return True
|
|
|
|
def _owns(self, current, job):
|
|
return (
|
|
current
|
|
and current["status"] == "PROCESSING"
|
|
and current["lease_token"] == job["lease_token"]
|
|
and current["live"]
|
|
)
|
|
|
|
def _save_variants(self, db, job, variants):
|
|
for item in variants:
|
|
db.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"],
|
|
item["name"],
|
|
item["object_key"],
|
|
item["content_type"],
|
|
item["size_bytes"],
|
|
item["width"],
|
|
item["height"],
|
|
item["sha256"],
|
|
),
|
|
)
|
|
|
|
def fail(self, job, permanent=False, code="processing_failed"):
|
|
with self.connection() as db:
|
|
current = self._lock_job(db, job)
|
|
if not self._owns(current, job):
|
|
return
|
|
terminal = permanent or job["attempt"] >= job["attempt_limit"]
|
|
status = "FAILED" if terminal else "QUEUED"
|
|
delay = min(30, 2 ** job["attempt"]) + random.uniform(0, 1)
|
|
code = code if permanent else ("retry_exhausted" if terminal else code)
|
|
self.set_failure(db, job, status, code, delay)
|
|
self.event(db, job, "failed" if terminal else "retry_scheduled")
|
|
|
|
def set_failure(self, db, job, status, code, delay):
|
|
db.execute(
|
|
"""UPDATE processing_jobs SET status=%s,error_code=%s,lease_until=NULL,
|
|
next_at=now() + %s * interval '1 second',next_publish_at=now(),
|
|
completed_at=CASE WHEN %s='FAILED' THEN now() ELSE NULL END WHERE job_id=%s""",
|
|
(status, code, delay, status, job["job_id"]),
|
|
)
|
|
db.execute(
|
|
"UPDATE attachments SET status=%s,error_code=%s,updated_at=now() WHERE id=%s",
|
|
(status, code if status == "FAILED" else None, job["attachment_id"]),
|
|
)
|
|
|
|
def clear_staging(self, job):
|
|
with self.connection() as db:
|
|
result = db.execute(
|
|
"""UPDATE attachments SET staging_key=NULL WHERE id=%s AND pipeline_version=%s
|
|
AND status='READY' AND staging_key=%s""",
|
|
(job["attachment_id"], job["pipeline_version"], job["staging_key"]),
|
|
)
|
|
return result.rowcount == 1
|
|
|
|
def fault(self, job, point):
|
|
if not self.settings.faults:
|
|
return None
|
|
with self.connection() as db:
|
|
row = db.execute(
|
|
"""UPDATE pipeline_faults SET remaining=remaining-1,hits=hits+1
|
|
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s AND remaining>0
|
|
RETURNING action""",
|
|
(job["attachment_id"], job["pipeline_version"], point),
|
|
).fetchone()
|
|
return row["action"] if row else None
|