forked from mtusi2026/mtusi2026lab5
исправление
This commit is contained in:
+44
-24
@@ -113,6 +113,10 @@ def create(conn, attachment_id, actor: str) -> uuid.UUID:
|
||||
_CLEAR_LEASE = "lease_owner = NULL, lease_token = NULL, lease_until = NULL"
|
||||
|
||||
|
||||
class LockBusy(Exception):
|
||||
"""Строку задания дольше lock_timeout держит другая транзакция (уборщик, worker)."""
|
||||
|
||||
|
||||
class JobStore:
|
||||
def __init__(self, pool, actor: str):
|
||||
self.pool = pool
|
||||
@@ -306,40 +310,56 @@ class JobStore:
|
||||
|
||||
# ---------- оператор ----------
|
||||
|
||||
def _job_of(self, conn, attachment_id: str, lock: bool = False):
|
||||
return conn.execute(
|
||||
f"""SELECT j.job_id, j.status, j.attempt, j.last_error_code, a.staging_key, a.error_code
|
||||
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.attachment_id = %s AND j.pipeline_version = %s {'FOR UPDATE OF j' if lock else ''}""",
|
||||
(uuid.UUID(attachment_id), config.PIPELINE_VERSION)).fetchone()
|
||||
|
||||
def replay(self, attachment_id: str, staging_exists) -> dict:
|
||||
"""failed -> queued по команде оператора. Готовое или ещё идущее задание НЕ повторяется."""
|
||||
"""failed -> queued по команде оператора. Готовое или ещё идущее задание НЕ повторяется.
|
||||
|
||||
Всё в ОДНОЙ транзакции под блокировкой строк задания и вложения — тех же, что берёт уборщик
|
||||
(store.cleanup_attachment), в том же порядке. Поэтому уборщик не удалит staging между
|
||||
проверкой исходника и переводом в queued (замечание к MR):
|
||||
- уборщик успел раньше: он уже пометил staging удалённым (staging_key = NULL) и удалил его,
|
||||
replay ждал блокировку и теперь безопасно отказывает (source_missing), задание остаётся failed;
|
||||
- replay успел раньше: уборщик ждёт блокировку, потом видит queued — исходник нужен текущей
|
||||
работе, и он его не трогает.
|
||||
Наличие объекта в S3 (staging_exists) проверяется тоже под блокировкой.
|
||||
"""
|
||||
aid = uuid.UUID(attachment_id)
|
||||
try:
|
||||
return self._replay(aid, staging_exists)
|
||||
except LockBusy:
|
||||
return {"result": "busy", "detail": "вложение сейчас обрабатывает уборщик или worker, повторите позже"}
|
||||
|
||||
def _replay(self, aid: uuid.UUID, staging_exists) -> dict:
|
||||
with self._tx() as conn:
|
||||
row = self._job_of(conn, attachment_id)
|
||||
if row is None:
|
||||
return {"result": "not_found"}
|
||||
job_id, status, attempt, last_code, staging_key, error_code = row
|
||||
# Команда оператора может подождать блокировку дольше обычного запроса (5 с).
|
||||
conn.execute("SET LOCAL lock_timeout = '20s'")
|
||||
conn.execute("SET LOCAL statement_timeout = '25s'")
|
||||
try:
|
||||
row = conn.execute("""SELECT job_id, status, attempt, last_error_code FROM attachment_jobs
|
||||
WHERE attachment_id = %s AND pipeline_version = %s FOR UPDATE""",
|
||||
(aid, config.PIPELINE_VERSION)).fetchone()
|
||||
if row is None:
|
||||
return {"result": "not_found"}
|
||||
staging_key, error_code = conn.execute(
|
||||
"SELECT staging_key, error_code FROM attachments WHERE id = %s FOR UPDATE", (aid,)).fetchone()
|
||||
except psycopg.errors.LockNotAvailable:
|
||||
raise LockBusy() from None
|
||||
job_id, status, attempt, last_code = row
|
||||
if status != "failed":
|
||||
event(conn, job_id, uuid.UUID(attachment_id), attempt, "replay_refused", self.actor,
|
||||
event(conn, job_id, aid, attempt, "replay_refused", self.actor,
|
||||
f"задание в состоянии {status}: повторять нечего")
|
||||
return {"result": "noop", "reason": status}
|
||||
if not staging_key or not staging_exists(staging_key):
|
||||
return {"result": "refused", "reason": "source_missing",
|
||||
"detail": "оригинал в staging уже удалён (истёк STAGING_RETENTION_SECONDS)"}
|
||||
with self._tx() as conn:
|
||||
row = self._job_of(conn, attachment_id, lock=True)
|
||||
job_id, status, attempt, last_code, staging_key, error_code = row
|
||||
if status != "failed": # пока проверяли S3, статус поменялся
|
||||
return {"result": "noop", "reason": status}
|
||||
if not staging_key or not staging_exists(staging_key):
|
||||
detail = "оригинал в staging уже удалён (истёк STAGING_RETENTION_SECONDS)"
|
||||
event(conn, job_id, aid, attempt, "replay_refused", self.actor, "source_missing: " + detail)
|
||||
return {"result": "refused", "reason": "source_missing", "detail": detail}
|
||||
new_attempt = attempt + 1
|
||||
conn.execute(f"""UPDATE attachment_jobs SET status = 'queued', attempt = %s, max_attempts = %s,
|
||||
{_CLEAR_LEASE}, next_attempt_at = now(), finished_at = NULL, updated_at = now()
|
||||
WHERE job_id = %s""", (new_attempt, attempt + config.JOB_MAX_ATTEMPTS, job_id))
|
||||
conn.execute("""UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now()
|
||||
WHERE id = %s AND status = 'failed'""", (uuid.UUID(attachment_id),))
|
||||
enqueue(conn, job_id, uuid.UUID(attachment_id), config.PIPELINE_VERSION, new_attempt)
|
||||
event(conn, job_id, uuid.UUID(attachment_id), new_attempt, "replay_requested", self.actor,
|
||||
WHERE id = %s AND status = 'failed'""", (aid,))
|
||||
enqueue(conn, job_id, aid, config.PIPELINE_VERSION, new_attempt)
|
||||
event(conn, job_id, aid, new_attempt, "replay_requested", self.actor,
|
||||
f"replay оператора: было {error_code} (последняя ошибка {last_code}); "
|
||||
f"новая попытка {new_attempt}, ещё {config.JOB_MAX_ATTEMPTS} попыток")
|
||||
return {"result": "queued", "attempt": new_attempt, "previous_error": error_code}
|
||||
|
||||
Reference in New Issue
Block a user