add level 4

This commit is contained in:
Матвей
2026-10-26 10:29:54 +03:00
parent df15ab0967
commit ff33b8a7c2
9 changed files with 265 additions and 40 deletions
+83 -15
View File
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, timedelta, timezone
from contextlib import asynccontextmanager
from hashlib import sha256
import json
@@ -330,6 +330,18 @@ class PostgresStore:
await (connection or self.pool).execute(
"INSERT INTO attachment_jobs (job_id, attachment_id) VALUES ($1, $2)", job_id, attachment_id
)
payload = {
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
"attachment_id": str(attachment_id), "pipeline_version": 1, "attempt": 1,
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}
await (connection or self.pool).execute(
"INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)",
uuid4(), job_id, json.dumps(payload, separators=(",", ":")),
)
await (connection or self.pool).execute(
"UPDATE attachment_jobs SET next_attempt_at = 'infinity' WHERE job_id = $1", job_id
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return dict(row)
@@ -356,37 +368,44 @@ class PostgresStore:
result["variants"] = [dict(item) for item in variants]
return result
async def claim_attachment_job(self, attachment_id: UUID) -> dict | None:
async def claim_attachment_job(self, attachment_id: UUID, lease_seconds: int) -> dict | None:
try:
async with self.pool.acquire() as connection, connection.transaction():
row = await connection.fetchrow("SELECT * FROM attachments WHERE id = $1 FOR UPDATE", attachment_id)
row = await connection.fetchrow(
"SELECT a.*, j.job_id, j.attempt, j.lease_until FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
"WHERE a.id = $1 FOR UPDATE", attachment_id
)
if row is None or row["status"] in {"ready", "failed"}:
return None
if row["status"] == "processing" and row["lease_until"] is not None and row["lease_until"] > datetime.now(timezone.utc):
return None
await connection.execute(
"UPDATE attachments SET status = 'processing', processing_started_at = now(), updated_at = now() WHERE id = $1",
attachment_id,
)
await connection.execute(
"UPDATE attachment_jobs SET status = 'processing', updated_at = now() WHERE attachment_id = $1", attachment_id
"UPDATE attachment_jobs SET status = 'processing', lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
attachment_id, lease_seconds,
)
return dict(row)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variant: dict) -> None:
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict]) -> None:
try:
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute(
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
"VALUES ($1, 1, 'thumbnail', $2, $3, $4, $5, $6, $7) "
"ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256",
attachment_id, variant["object_key"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"],
)
for variant in variants:
await connection.execute(
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
"VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8) "
"ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256",
attachment_id, variant["name"], variant["object_key"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"],
)
await connection.execute(
"UPDATE attachments SET status = 'ready', original_key = $2, error_code = NULL, updated_at = now() WHERE id = $1",
attachment_id, original_key,
)
await connection.execute("UPDATE attachment_jobs SET status = 'ready', updated_at = now() WHERE attachment_id = $1", attachment_id)
await connection.execute("UPDATE attachment_jobs SET status = 'ready', lease_until = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
@@ -401,7 +420,7 @@ class PostgresStore:
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int) -> bool:
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float) -> bool:
"""Return true only when a bounded at-least-once retry was recorded."""
try:
async with self.pool.acquire() as connection, connection.transaction():
@@ -410,8 +429,8 @@ class PostgresStore:
)
if job is not None and job["attempt"] < max_attempts:
await connection.execute(
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', updated_at = now() WHERE attachment_id = $1",
attachment_id,
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', lease_until = NULL, next_attempt_at = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
attachment_id, delay_seconds,
)
await connection.execute(
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
@@ -422,6 +441,55 @@ class PostgresStore:
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def due_outbox_events(self, limit: int = 20) -> list[dict]:
try:
return [dict(row) for row in await self.pool.fetch(
"SELECT id, payload FROM attachment_outbox WHERE published_at IS NULL ORDER BY created_at LIMIT $1", limit
)]
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def mark_outbox_published(self, event_id: UUID) -> None:
await self.pool.execute("UPDATE attachment_outbox SET published_at = now(), attempts = attempts + 1 WHERE id = $1", event_id)
async def schedule_due_jobs(self) -> None:
"""Outbox dispatcher also restores expired leases and scheduled retries."""
try:
async with self.pool.acquire() as connection, connection.transaction():
rows = await connection.fetch(
"SELECT job_id, attachment_id, pipeline_version, attempt, status FROM attachment_jobs "
"WHERE (status = 'queued' AND next_attempt_at <= now()) OR (status = 'processing' AND lease_until < now()) "
"FOR UPDATE SKIP LOCKED"
)
for row in rows:
if row["status"] == "processing":
await connection.execute(
"UPDATE attachment_jobs SET status = 'queued', lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"]
)
await connection.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", 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": row["pipeline_version"], "attempt": row["attempt"], "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
await connection.execute("INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)", uuid4(), row["job_id"], json.dumps(payload, separators=(",", ":")))
await connection.execute("UPDATE attachment_jobs SET next_attempt_at = 'infinity' WHERE job_id = $1", row["job_id"])
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def replay_failed_attachment(self, attachment_id: UUID) -> bool:
"""Explicit operator-only replay; never requeues an already successful job."""
try:
async with self.pool.acquire() as connection, connection.transaction():
job = await connection.fetchrow(
"SELECT job_id, status FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
)
if job is None or job["status"] != "failed":
return False
await connection.execute(
"UPDATE attachment_jobs SET status = 'queued', attempt = 1, next_attempt_at = now(), lease_until = NULL, replayed_at = now(), last_error = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id
)
await connection.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1", attachment_id)
return True
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def attachment_keys(self) -> dict[str, UUID]:
"""Inventory used only by the maintenance reconciler."""
try: