Files
mtusi2026lab5/src/messenger/store.py
T

1192 lines
47 KiB
Python

"""PostgreSQL repository: users, chats, membership, messages, idempotency, attachment metadata."""
from __future__ import annotations
import hashlib
import json
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, List, Optional, Tuple
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from psycopg import Error as PsycopgError
from psycopg import errors as pg_errors
from psycopg.types.json import Json
from messenger import config
from messenger.db import get_pool
_ph = PasswordHasher()
class StoreUnavailable(Exception):
"""Raised when PostgreSQL is unreachable or timed out."""
def utc_now() -> datetime:
"""Wall clock for leases/backoff (full precision; compare due times in SQL)."""
return datetime.now(timezone.utc)
def utc_now_second() -> datetime:
"""Second-precision timestamps for API entities and keyset cursors."""
return utc_now().replace(microsecond=0)
def format_ts(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")
@dataclass
class User:
id: str
username: str
display_name: str
created_at: datetime
password_hash: str = ""
def to_dict(self) -> dict:
return {
"id": self.id,
"username": self.username,
"display_name": self.display_name,
"created_at": format_ts(self.created_at),
}
@dataclass
class Chat:
id: str
title: str
member_ids: List[str]
created_at: datetime
def to_dict(self) -> dict:
return {
"id": self.id,
"title": self.title,
"member_ids": list(self.member_ids),
"created_at": format_ts(self.created_at),
}
@dataclass
class Message:
id: str
chat_id: str
sender_id: str
text: str
created_at: datetime
attachment_ids: List[str] = field(default_factory=list)
def to_dict(self) -> dict:
return {
"id": self.id,
"chat_id": self.chat_id,
"sender_id": self.sender_id,
"text": self.text,
"created_at": format_ts(self.created_at),
"attachment_ids": list(self.attachment_ids),
}
@dataclass
class Variant:
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
object_key: str = ""
def to_dict(self) -> dict:
return {
"name": self.name,
"content_type": self.content_type,
"size_bytes": self.size_bytes,
"width": self.width,
"height": self.height,
"sha256": self.sha256,
}
@dataclass
class Attachment:
id: str
chat_id: str
owner_id: str
filename: str
content_type: str
size_bytes: int
sha256: str
width: int
height: int
object_key: Optional[str]
status: str
created_at: datetime
updated_at: datetime
staging_key: Optional[str] = None
error_code: Optional[str] = None
pipeline_version: int = 1
variants: List[Variant] = field(default_factory=list)
def to_dict(self) -> dict:
# object_key / staging_key are internal: the public API never exposes bucket keys.
return {
"id": self.id,
"chat_id": self.chat_id,
"owner_id": self.owner_id,
"filename": self.filename,
"content_type": self.content_type,
"size_bytes": self.size_bytes,
"sha256": self.sha256,
"status": self.status,
"variants": [v.to_dict() for v in self.variants],
"error_code": self.error_code,
"created_at": format_ts(self.created_at),
"updated_at": format_ts(self.updated_at),
}
class AttachmentNotFound(Exception):
"""Referenced attachment is unknown or belongs to another chat."""
class AttachmentFailed(Exception):
"""Attachment exists but is in failed status and cannot be linked."""
class IntentLost(Exception):
"""Upload intent vanished (reconciled) before metadata commit."""
class CommitUncertain(StoreUnavailable):
"""COMMIT was sent but its result is unknown: the row may or may not exist."""
def _row_user(row: dict) -> User:
return User(
id=str(row["id"]),
username=row["username"],
display_name=row["display_name"],
created_at=row["created_at"],
password_hash=row.get("password_hash", ""),
)
def _row_message(row: dict) -> Message:
return Message(
id=str(row["id"]),
chat_id=str(row["chat_id"]),
sender_id=str(row["sender_id"]),
text=bytes(row["text"]).decode("utf-8"),
created_at=row["created_at"],
attachment_ids=[str(a) for a in (row.get("attachment_ids") or [])],
)
def _row_attachment(row: dict, variants: Optional[List[Variant]] = None) -> Attachment:
return Attachment(
id=str(row["id"]),
chat_id=str(row["chat_id"]),
owner_id=str(row["owner_id"]),
filename=row["filename"],
content_type=row["content_type"],
size_bytes=int(row["size_bytes"]),
sha256=row["sha256"],
width=int(row["width"]),
height=int(row["height"]),
object_key=row.get("object_key"),
status=row["status"],
created_at=row["created_at"],
updated_at=row["updated_at"],
staging_key=row.get("staging_key"),
error_code=row.get("error_code"),
pipeline_version=int(row.get("pipeline_version") or 1),
variants=list(variants or []),
)
_ATTACHMENT_COLUMNS = (
"a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, "
"a.width, a.height, a.object_key, a.status, a.created_at, a.updated_at, "
"a.staging_key, a.error_code, a.pipeline_version"
)
_MESSAGE_ATTACHMENTS = (
"ARRAY(SELECT ma.attachment_id FROM message_attachments ma "
"WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids"
)
class Store:
def hash_password(self, password: str) -> str:
return _ph.hash(password)
def verify_password(self, password_hash: str, password: str) -> bool:
try:
return _ph.verify(password_hash, password)
except VerifyMismatchError:
return False
except Exception:
return False
def create_user(self, username: str, display_name: str, password: str) -> User:
user_id = uuid.uuid4()
created = utc_now_second()
password_hash = self.hash_password(password)
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(user_id, username, display_name, password_hash, created),
)
except (pg_errors.UniqueViolation, pg_errors.IntegrityError) as exc:
raise KeyError("username_taken") from exc
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return User(
id=str(user_id),
username=username,
display_name=display_name,
created_at=created,
)
def get_user(self, user_id: str) -> Optional[User]:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE id = %s
""",
(user_id,),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return _row_user(row) if row else None
def get_user_by_username(self, username: str) -> Optional[User]:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = %s
""",
(username,),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return _row_user(row) if row else None
def create_chat(self, title: str, member_ids: List[str]) -> Chat:
chat_id = uuid.uuid4()
created = utc_now_second()
try:
with get_pool().connection() as conn:
with conn.transaction():
# Atomic membership check + insert; rollback if any member missing.
rows = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s::uuid[])",
(member_ids,),
).fetchall()
found = {str(r["id"]) for r in rows}
if found != set(member_ids):
raise KeyError("unknown_member")
conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(chat_id, title, created),
)
for mid in member_ids:
conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
(chat_id, mid),
)
except KeyError:
raise
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return Chat(
id=str(chat_id),
title=title,
member_ids=list(member_ids),
created_at=created,
)
def get_chat(self, chat_id: str) -> Optional[Chat]:
try:
with get_pool().connection() as conn:
row = conn.execute(
"SELECT id, title, created_at FROM chats WHERE id = %s",
(chat_id,),
).fetchone()
if not row:
return None
members = conn.execute(
"""
SELECT user_id FROM chat_members
WHERE chat_id = %s
ORDER BY user_id
""",
(chat_id,),
).fetchall()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return Chat(
id=str(row["id"]),
title=row["title"],
member_ids=[str(m["user_id"]) for m in members],
created_at=row["created_at"],
)
def list_chats_for_user(
self,
user_id: str,
limit: int,
cursor: Optional[Tuple[datetime, uuid.UUID]],
) -> Tuple[List[Chat], Optional[str]]:
params: list = [user_id]
where = "cm.user_id = %s"
if cursor is not None:
where += " AND (c.created_at, c.id) > (%s, %s)"
params.extend([cursor[0], cursor[1]])
params.append(limit + 1)
try:
with get_pool().connection() as conn:
rows = conn.execute(
f"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE {where}
ORDER BY c.created_at ASC, c.id ASC
LIMIT %s
""",
params,
).fetchall()
chats: List[Chat] = []
for row in rows[:limit]:
members = conn.execute(
"""
SELECT user_id FROM chat_members
WHERE chat_id = %s
ORDER BY user_id
""",
(row["id"],),
).fetchall()
chats.append(
Chat(
id=str(row["id"]),
title=row["title"],
member_ids=[str(m["user_id"]) for m in members],
created_at=row["created_at"],
)
)
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
has_more = len(rows) > limit
return chats, "more" if has_more else None
@staticmethod
def request_hash_for_message(text: str, attachment_ids: List[str]) -> str:
# Canonical form: sorted keys; absent attachment_ids ≡ []; array order is significant.
canonical = json.dumps(
{"attachment_ids": list(attachment_ids), "text": text},
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def create_message_idempotent(
self,
chat_id: str,
sender_id: str,
text: str,
attachment_ids: List[str],
method: str,
path: str,
idem_key: str,
) -> Tuple[Message, bool]:
"""
Create message with shared idempotency across replicas.
Returns (message, replayed).
Raises KeyError('conflict') when same key was used with another body,
AttachmentNotFound when an attachment is unknown or belongs to another chat.
"""
req_hash = self.request_hash_for_message(text, attachment_ids)
ttl = timedelta(seconds=config.idempotency_ttl_seconds())
# Transaction-scoped advisory lock serializes same-key concurrent POSTs.
lock_material = f"{sender_id}|{method}|{path}|{idem_key}"
lock_key = int(
hashlib.sha256(lock_material.encode("utf-8")).hexdigest()[:15], 16
)
def _load_existing(conn) -> Optional[dict]:
return conn.execute(
"""
SELECT request_hash, response_status, response_body, created_at
FROM idempotency_records
WHERE user_id = %s AND method = %s AND path = %s AND idem_key = %s
""",
(sender_id, method, path, idem_key),
).fetchone()
def _message_from_body(body: Any) -> Message:
return Message(
id=str(body["id"]),
chat_id=str(body["chat_id"]),
sender_id=str(body["sender_id"]),
text=body["text"],
created_at=datetime.strptime(
body["created_at"], "%Y-%m-%dT%H:%M:%SZ"
).replace(tzinfo=timezone.utc),
attachment_ids=[str(a) for a in body.get("attachment_ids", [])],
)
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
existing = _load_existing(conn)
if existing is not None:
if existing["created_at"] >= utc_now() - ttl:
if existing["request_hash"] != req_hash:
raise KeyError("conflict")
return _message_from_body(existing["response_body"]), True
conn.execute(
"""
DELETE FROM idempotency_records
WHERE user_id = %s AND method = %s AND path = %s AND idem_key = %s
""",
(sender_id, method, path, idem_key),
)
if attachment_ids:
# Lab5: queued/processing/ready may be linked; failed → 409; unknown → 404.
found = conn.execute(
"""
SELECT id, status FROM attachments
WHERE id = ANY(%s::uuid[]) AND chat_id = %s
FOR SHARE
""",
(attachment_ids, chat_id),
).fetchall()
by_id = {str(r["id"]): r["status"] for r in found}
if set(by_id) != set(attachment_ids):
raise AttachmentNotFound()
if any(status == "failed" for status in by_id.values()):
raise AttachmentFailed()
msg_id = uuid.uuid4()
created = utc_now_second()
message = Message(
id=str(msg_id),
chat_id=chat_id,
sender_id=sender_id,
text=text,
created_at=created,
attachment_ids=list(attachment_ids),
)
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(msg_id, chat_id, sender_id, text.encode("utf-8"), created),
)
for position, attachment_id in enumerate(attachment_ids):
conn.execute(
"""
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES (%s, %s, %s)
""",
(msg_id, attachment_id, position),
)
conn.execute(
"""
INSERT INTO idempotency_records (
user_id, method, path, idem_key,
request_hash, response_status, response_body, created_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""",
(
sender_id,
method,
path,
idem_key,
req_hash,
201,
Json(message.to_dict()),
created,
),
)
return message, False
except (KeyError, AttachmentNotFound):
raise
except pg_errors.DataError as exc:
raise ValueError("invalid_text") from exc
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def list_messages(
self,
chat_id: str,
limit: int,
cursor: Optional[Tuple[datetime, uuid.UUID]],
) -> Tuple[List[Message], bool]:
params: list = [chat_id]
where = "m.chat_id = %s"
if cursor is not None:
where += " AND (m.created_at, m.id) > (%s, %s)"
params.extend([cursor[0], cursor[1]])
params.append(limit + 1)
try:
with get_pool().connection() as conn:
rows = conn.execute(
f"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
{_MESSAGE_ATTACHMENTS}
FROM messages m
WHERE {where}
ORDER BY m.created_at ASC, m.id ASC
LIMIT %s
""",
params,
).fetchall()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
messages = [_row_message(r) for r in rows[:limit]]
return messages, len(rows) > limit
def message_exists(self, chat_id: str, created_at: datetime, item_id: uuid.UUID) -> bool:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT 1 AS ok FROM messages
WHERE chat_id = %s AND created_at = %s AND id = %s
""",
(chat_id, created_at, item_id),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return bool(row)
def chat_exists_for_user(
self, user_id: str, created_at: datetime, item_id: uuid.UUID
) -> bool:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT 1 AS ok
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = %s AND c.created_at = %s AND c.id = %s
""",
(user_id, created_at, item_id),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return bool(row)
# --- attachments (lab4) ---------------------------------------------------
#
# Write protocol (see REPORT.md, "Согласованность БД/S3"):
# 1. record_intent() — durable intent row BEFORE any byte reaches S3;
# 2. S3 PUT of a server-generated key;
# 3. commit_attachment() — one transaction locks the intent, inserts the
# ready metadata and deletes the intent;
# 4. on failure: compensate (S3 DELETE + drop intent); whatever survives a
# crash is collected by messenger.reconcile after the grace period.
def record_intent(self, object_key: str, attachment_id: str, chat_id: str, instance: str) -> None:
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"""
INSERT INTO upload_intents (object_key, attachment_id, chat_id, instance_id, created_at)
VALUES (%s, %s, %s, %s, now())
""",
(object_key, attachment_id, chat_id, instance),
)
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def drop_intent(self, object_key: str) -> None:
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (object_key,))
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def commit_queued_attachment(
self,
att: Attachment,
*,
job_id: str,
staging_key: str,
job_payload: dict,
) -> Attachment:
"""Atomically: insert queued attachment + job + outbox, drop staging intent."""
committing = False
try:
with get_pool().connection() as conn:
with conn.transaction():
intent = conn.execute(
"SELECT object_key FROM upload_intents WHERE object_key = %s FOR UPDATE",
(staging_key,),
).fetchone()
if intent is None:
raise IntentLost(staging_key)
row = conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
width, height, object_key, staging_key, status, error_code,
pipeline_version, created_at, updated_at
) VALUES (
%s, %s, %s, %s, %s, %s, %s, %s, %s, NULL, %s, 'queued', NULL,
%s, now(), now()
)
RETURNING created_at, updated_at
""",
(
att.id, att.chat_id, att.owner_id, att.filename, att.content_type,
att.size_bytes, att.sha256, att.width, att.height, staging_key,
att.pipeline_version,
),
).fetchone()
conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at
) VALUES (%s, %s, %s, 1, 'pending', now(), now(), now())
""",
(job_id, att.id, att.pipeline_version),
)
conn.execute(
"""
INSERT INTO outbox (job_id, payload, created_at)
VALUES (%s, %s, now())
""",
(job_id, Json(job_payload)),
)
conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (staging_key,))
committing = True
except IntentLost:
raise
except PsycopgError as exc:
if committing:
raise CommitUncertain("commit outcome unknown") from exc
raise StoreUnavailable("database unavailable") from exc
att.status = "queued"
att.staging_key = staging_key
att.object_key = None
att.error_code = None
att.variants = []
att.created_at = row["created_at"]
att.updated_at = row["updated_at"]
return att
def _load_variants(self, conn, attachment_id: str, pipeline_version: int) -> List[Variant]:
rows = conn.execute(
"""
SELECT name, content_type, size_bytes, width, height, sha256, object_key
FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s
ORDER BY name
""",
(attachment_id, pipeline_version),
).fetchall()
return [
Variant(
name=r["name"],
content_type=r["content_type"],
size_bytes=int(r["size_bytes"]),
width=int(r["width"]),
height=int(r["height"]),
sha256=r["sha256"],
object_key=r["object_key"],
)
for r in rows
]
def get_attachment_for_user(self, attachment_id: str, user_id: str) -> Optional[Attachment]:
"""Return the attachment only if user_id is a member of its chat (else None → 404)."""
try:
with get_pool().connection() as conn:
row = conn.execute(
f"""
SELECT {_ATTACHMENT_COLUMNS}
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
WHERE a.id = %s
""",
(user_id, attachment_id),
).fetchone()
if row is None:
return None
variants = self._load_variants(conn, attachment_id, int(row["pipeline_version"] or 1))
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return _row_attachment(row, variants)
def get_attachment(self, attachment_id: str) -> Optional[Attachment]:
try:
with get_pool().connection() as conn:
row = conn.execute(
f"SELECT {_ATTACHMENT_COLUMNS} FROM attachments a WHERE a.id = %s",
(attachment_id,),
).fetchone()
if row is None:
return None
variants = self._load_variants(conn, attachment_id, int(row["pipeline_version"] or 1))
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return _row_attachment(row, variants)
# --- outbox / jobs (lab5) -------------------------------------------------
def claim_outbox_batch(self, limit: int = 50) -> List[dict]:
"""Bump attempts on a locked unpublished batch so concurrent publishers do not steal rows mid-flight."""
try:
with get_pool().connection() as conn:
with conn.transaction():
rows = conn.execute(
"""
WITH picked AS (
SELECT o.id
FROM outbox o
JOIN attachment_jobs j ON j.job_id = o.job_id
WHERE o.published_at IS NULL
AND (
j.status = 'pending'
AND (j.next_attempt_at IS NULL OR j.next_attempt_at <= now())
)
ORDER BY o.id
FOR UPDATE OF o SKIP LOCKED
LIMIT %s
)
UPDATE outbox o
SET publish_attempts = o.publish_attempts + 1
FROM picked
WHERE o.id = picked.id
RETURNING o.id, o.job_id, o.payload
""",
(limit,),
).fetchall()
return [
{"id": int(r["id"]), "job_id": str(r["job_id"]), "payload": dict(r["payload"])}
for r in rows
]
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def mark_outbox_published(self, outbox_id: int) -> None:
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"UPDATE outbox SET published_at = now() WHERE id = %s",
(outbox_id,),
)
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def bump_outbox_attempt(self, outbox_id: int) -> None:
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"UPDATE outbox SET publish_attempts = publish_attempts + 1 WHERE id = %s",
(outbox_id,),
)
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def try_lease_job(
self,
job_id: str,
owner: str,
lease_seconds: int,
) -> Optional[dict]:
"""Claim a pending/recoverable job. Returns job+attachment snapshot or None (retry later)."""
try:
with get_pool().connection() as conn:
with conn.transaction():
job = conn.execute(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, status,
lease_until, next_attempt_at
FROM attachment_jobs
WHERE job_id = %s
FOR UPDATE
""",
(job_id,),
).fetchone()
if job is None:
return None
if job["status"] == "done":
return {"already_done": True, "job_id": str(job["job_id"])}
if job["status"] == "failed":
return {"already_failed": True, "job_id": str(job["job_id"])}
# Compare in SQL so timestamptz precision matches the database clock.
due = conn.execute(
"""
SELECT
(status = 'leased' AND lease_until IS NOT NULL AND lease_until > now()) AS leased_busy,
(status = 'pending' AND next_attempt_at IS NOT NULL AND next_attempt_at > now()) AS not_due
FROM attachment_jobs WHERE job_id = %s
""",
(job_id,),
).fetchone()
if due and due["leased_busy"]:
return None
if due and due["not_due"]:
return None
now = utc_now()
lease_until = now + timedelta(seconds=lease_seconds)
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'leased', lease_owner = %s, lease_until = %s, updated_at = now()
WHERE job_id = %s
""",
(owner, lease_until, job_id),
)
conn.execute(
"""
UPDATE attachments
SET status = 'processing', updated_at = now(), error_code = NULL
WHERE id = %s AND status IN ('queued', 'processing')
""",
(job["attachment_id"],),
)
att = conn.execute(
f"SELECT {_ATTACHMENT_COLUMNS} FROM attachments a WHERE a.id = %s",
(job["attachment_id"],),
).fetchone()
if att is None:
return None
variants = self._load_variants(
conn, str(job["attachment_id"]), int(job["pipeline_version"])
)
return {
"job_id": str(job["job_id"]),
"attachment_id": str(job["attachment_id"]),
"pipeline_version": int(job["pipeline_version"]),
"attempt": int(job["attempt"]),
"attachment": _row_attachment(att, variants),
}
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def complete_job_ready(
self,
*,
job_id: str,
attachment_id: str,
pipeline_version: int,
original_key: str,
variants: List[Variant],
staging_key: Optional[str],
) -> bool:
"""Idempotent ready commit. Returns False if a newer/other terminal state won."""
try:
with get_pool().connection() as conn:
with conn.transaction():
att = conn.execute(
"""
SELECT id, status, pipeline_version, staging_key
FROM attachments WHERE id = %s FOR UPDATE
""",
(attachment_id,),
).fetchone()
if att is None:
return False
if att["status"] == "ready" and int(att["pipeline_version"]) >= pipeline_version:
# Already finished this or newer pipeline: treat as success (idempotent).
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'done', lease_owner = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = %s
""",
(job_id,),
)
return True
if int(att["pipeline_version"]) > pipeline_version:
return False
for v in variants:
conn.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type,
size_bytes, width, height, sha256, object_key
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
""",
(
attachment_id, pipeline_version, v.name, v.content_type,
v.size_bytes, v.width, v.height, v.sha256, v.object_key,
),
)
conn.execute(
"""
UPDATE attachments
SET status = 'ready', object_key = %s, error_code = NULL,
pipeline_version = %s, staging_key = NULL, updated_at = now()
WHERE id = %s
""",
(original_key, pipeline_version, attachment_id),
)
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'done', lease_owner = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = %s
""",
(job_id,),
)
return True
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def fail_or_retry_job(
self,
*,
job_id: str,
attachment_id: str,
error_code: str,
message: str,
permanent: bool,
max_attempts: int,
delay_seconds: float,
payload: dict,
) -> str:
"""Returns 'retry' | 'failed'."""
try:
with get_pool().connection() as conn:
with conn.transaction():
job = conn.execute(
"""
SELECT attempt FROM attachment_jobs WHERE job_id = %s FOR UPDATE
""",
(job_id,),
).fetchone()
if job is None:
return "failed"
attempt = int(job["attempt"])
if permanent or attempt >= max_attempts:
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'failed', last_error = %s, error_code = %s,
lease_owner = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = %s
""",
(message[:500], error_code, job_id),
)
conn.execute(
"""
UPDATE attachments
SET status = 'failed', error_code = %s, updated_at = now()
WHERE id = %s AND status <> 'ready'
""",
(error_code, attachment_id),
)
conn.execute(
"""
INSERT INTO dead_letter_jobs (
job_id, attachment_id, pipeline_version, payload,
error_code, attempts, failed_at
) VALUES (%s, %s, %s, %s, %s, %s, now())
""",
(
job_id,
attachment_id,
int(payload.get("pipeline_version", 1)),
Json(payload),
error_code,
attempt,
),
)
return "failed"
next_at = utc_now() + timedelta(seconds=delay_seconds)
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'pending', attempt = attempt + 1,
next_attempt_at = %s, last_error = %s, error_code = %s,
lease_owner = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = %s
""",
(next_at, message[:500], error_code, job_id),
)
conn.execute(
"""
UPDATE attachments
SET status = 'queued', updated_at = now()
WHERE id = %s AND status = 'processing'
""",
(attachment_id,),
)
# Re-enqueue via outbox so recovery does not depend on broker requeue timing.
retry_payload = dict(payload)
retry_payload["attempt"] = attempt + 1
conn.execute(
"""
INSERT INTO outbox (job_id, payload, created_at)
VALUES (%s, %s, now())
""",
(job_id, Json(retry_payload)),
)
return "retry"
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def recover_expired_leases(self, limit: int = 50) -> int:
"""Move expired leased jobs back to pending and re-outbox them."""
recovered = 0
try:
with get_pool().connection() as conn:
with conn.transaction():
rows = conn.execute(
"""
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt
FROM attachment_jobs j
WHERE j.status = 'leased' AND j.lease_until < now()
ORDER BY j.lease_until
FOR UPDATE SKIP LOCKED
LIMIT %s
""",
(limit,),
).fetchall()
for row in rows:
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'pending', lease_owner = NULL, lease_until = NULL,
next_attempt_at = now(), updated_at = now()
WHERE job_id = %s
""",
(row["job_id"],),
)
conn.execute(
"""
UPDATE attachments
SET status = 'queued', updated_at = now()
WHERE id = %s AND status = 'processing'
""",
(row["attachment_id"],),
)
payload = {
"schema_version": 1,
"job_id": str(row["job_id"]),
"type": "attachment.process.v1",
"attachment_id": str(row["attachment_id"]),
"pipeline_version": int(row["pipeline_version"]),
"attempt": int(row["attempt"]),
"created_at": format_ts(utc_now()),
}
conn.execute(
"""
INSERT INTO outbox (job_id, payload, created_at)
VALUES (%s, %s, now())
""",
(row["job_id"], Json(payload)),
)
recovered += 1
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return recovered
def replay_dead_letter(self, dead_letter_id: int, note: str = "operator replay") -> Optional[str]:
"""Explicit safe replay: only if attachment is not already ready for same/newer pipeline."""
try:
with get_pool().connection() as conn:
with conn.transaction():
dlq = conn.execute(
"""
SELECT id, job_id, attachment_id, pipeline_version, payload, replayed_at
FROM dead_letter_jobs WHERE id = %s FOR UPDATE
""",
(dead_letter_id,),
).fetchone()
if dlq is None:
return None
att = conn.execute(
"SELECT status, pipeline_version FROM attachments WHERE id = %s FOR UPDATE",
(dlq["attachment_id"],),
).fetchone()
if att is None:
return None
if att["status"] == "ready" and int(att["pipeline_version"]) >= int(dlq["pipeline_version"]):
# Do not re-execute a successful effect.
conn.execute(
"""
UPDATE dead_letter_jobs
SET replayed_at = now(), replay_note = %s
WHERE id = %s
""",
("skipped: already ready", dead_letter_id),
)
return "skipped_ready"
job_id = uuid.uuid4()
payload = dict(dlq["payload"])
payload["job_id"] = str(job_id)
payload["attempt"] = 1
payload["created_at"] = format_ts(utc_now())
conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at
) VALUES (%s, %s, %s, 1, 'pending', now(), now(), now())
""",
(job_id, dlq["attachment_id"], dlq["pipeline_version"]),
)
conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = %s
""",
(dlq["attachment_id"],),
)
conn.execute(
"INSERT INTO outbox (job_id, payload, created_at) VALUES (%s, %s, now())",
(job_id, Json(payload)),
)
conn.execute(
"""
UPDATE dead_letter_jobs
SET replayed_at = now(), replay_note = %s
WHERE id = %s
""",
(note[:200], dead_letter_id),
)
return str(job_id)
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc