Files
mtusi2026lab5/app/replay.py
T

189 lines
5.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import argparse
import hashlib
import json
import os
from uuid import UUID, uuid4
from app.job_db import connect_db
from app.responses import to_json
from app.storage import _get
def list_failed():
with connect_db() as db:
return db.execute(
"""
SELECT id AS job_id, attachment_id,
pipeline_version, attempt, max_attempts,
error_code, updated_at
FROM attachment_jobs
WHERE status = 'failed'
ORDER BY updated_at, id
LIMIT 100
"""
).fetchall()
def replay(job_id, *, actor, reason, apply):
budget = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
if not 1 <= budget <= 100:
raise ValueError("Invalid retry budget")
with connect_db() as db:
with db.transaction():
row = db.execute(
"""
SELECT j.*,
a.status AS attachment_status,
a.pipeline_version AS current_version,
a.staging_key, a.size_bytes, a.sha256
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = %s
FOR UPDATE OF j, a
""",
(job_id,),
).fetchone()
if row is None:
raise ValueError("Unknown job")
if (
row["status"] != "failed"
or row["attachment_status"] != "failed"
or row["pipeline_version"] != row["current_version"]
):
return {
"result": "noop",
"job_id": str(job_id),
"status": row["status"],
"reason": "job_is_not_current_failed_work",
}
if not row["staging_key"]:
raise ValueError("Staging is unavailable")
plan = {
"result": "replayed" if apply else "dry_run",
"job_id": str(job_id),
"previous_attempt": row["attempt"],
"new_attempt": row["attempt"] + 1,
"new_max_attempts": row["attempt"] + budget,
"previous_error_code": row["error_code"],
}
if not apply:
return plan
# Не ставим задачу в очередь, если исходник отсутствует
# или не совпадает с устойчиво принятыми метаданными.
db.execute(
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
)
original = _get(row["staging_key"])
if (
len(original) != row["size_bytes"]
or hashlib.sha256(original).hexdigest() != row["sha256"]
):
raise ValueError("Staging integrity check failed")
db.execute(
"""
INSERT INTO attachment_job_replays (
id, job_id, actor, reason,
previous_attempt, new_attempt, previous_error_code
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""",
(
uuid4(), job_id, actor, reason,
row["attempt"], plan["new_attempt"], row["error_code"],
),
)
db.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = %s,
max_attempts = %s,
error_code = NULL,
lease_token = NULL,
lease_until = NULL,
available_at = clock_timestamp(),
updated_at = clock_timestamp()
WHERE id = %s
""",
(
plan["new_attempt"],
plan["new_max_attempts"],
job_id,
),
)
db.execute(
"""
UPDATE attachments
SET status = 'queued',
error_code = NULL,
updated_at = clock_timestamp()
WHERE id = %s
""",
(row["attachment_id"],),
)
db.execute(
"""
INSERT INTO attachment_outbox (id, job_id, attempt)
VALUES (%s, %s, %s)
""",
(uuid4(), job_id, plan["new_attempt"]),
)
return plan
def main():
parser = argparse.ArgumentParser()
selection = parser.add_mutually_exclusive_group(required=True)
selection.add_argument("--list", action="store_true")
selection.add_argument("--job-id", type=UUID)
parser.add_argument("--actor")
parser.add_argument("--reason")
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
if args.list and args.apply:
parser.error("--apply requires --job-id")
if args.job_id:
if not args.actor or not 1 <= len(args.actor.strip()) <= 100:
parser.error("--actor must contain 1–100 characters")
if not args.reason or not 1 <= len(args.reason.strip()) <= 500:
parser.error("--reason must contain 1–500 characters")
try:
if args.list:
result = list_failed()
else:
result = replay(
args.job_id,
actor=args.actor.strip(),
reason=args.reason.strip(),
apply=args.apply,
)
except Exception as exc:
print(json.dumps({
"result": "error",
"error_type": type(exc).__name__,
}))
raise SystemExit(1)
print(json.dumps(to_json(result), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()