Files
mtusi2026lab6/app/jobs.py
T
dawuduk baee48072c Подключить OpenTelemetry, Collector и Grafana для оценки 5.
API и worker отдают метрики, логи и трассы. Правила SLO записаны, прогон инцидентов ещё впереди.
2026-11-17 15:23:33 +03:00

830 lines
30 KiB
Python

"""Job rows are the transactional outbox. The broker never stores file bytes."""
from __future__ import annotations
import asyncio
import hashlib
import logging
import os
import random
import time
from datetime import datetime, timezone
from uuid import UUID, uuid4
from app import broker, config, db, pipeline, s3, telemetry
from app.errors import AppError
from app.pipeline import PermanentJobError, TransientJobError
from app.store import format_ts
logger = logging.getLogger("messenger.jobs")
_outbox_task: asyncio.Task | None = None
_publish_lock = asyncio.Lock()
def message_of(row) -> dict:
return {
"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(row["created_at"]),
}
def backoff_seconds(attempt: int) -> float:
base = min(config.JOB_BACKOFF_CAP_SECONDS, config.JOB_BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1)))
return base * random.uniform(0.5, 1.5)
def _trace_columns() -> tuple[str | None, str | None]:
carrier = telemetry.current_carrier()
return carrier.get("traceparent") or None, carrier.get("tracestate") or None
async def insert_job(conn, attachment_id: UUID, created: datetime) -> UUID:
job_id = uuid4()
traceparent, tracestate = _trace_columns()
await conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at, traceparent, tracestate
)
VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3, $4, $5)
""",
job_id,
attachment_id,
created,
traceparent,
tracestate,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'queued', 'upload committed')
""",
job_id,
attachment_id,
)
return job_id
def kick_publish() -> None:
try:
asyncio.get_running_loop().create_task(publish_pending())
except RuntimeError:
return
async def publish_pending(limit: int = 20) -> int:
if not config.BROKER_URL:
return 0
async with _publish_lock:
try:
async with db.require().acquire() as conn:
async with conn.transaction():
rows = await conn.fetch(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, created_at,
traceparent, tracestate
FROM attachment_jobs
WHERE published_at IS NULL
AND status = 'queued'
AND (next_attempt_at IS NULL OR next_attempt_at <= now())
ORDER BY created_at
LIMIT $1
FOR UPDATE SKIP LOCKED
""",
limit,
)
for row in rows:
await broker.publish_job(
message_of(row),
traceparent=row["traceparent"],
tracestate=row["tracestate"],
)
await conn.execute(
"UPDATE attachment_jobs SET published_at = now() WHERE job_id = $1",
row["job_id"],
)
return len(rows)
except Exception:
logger.warning("outbox publish failed; the job row stays unpublished")
return 0
async def _outbox_loop() -> None:
while True:
try:
await publish_pending()
except asyncio.CancelledError:
raise
except Exception:
logger.warning("outbox loop failed")
await asyncio.sleep(0.25)
def start_outbox() -> None:
global _outbox_task
if _outbox_task is None or _outbox_task.done():
_outbox_task = asyncio.create_task(_outbox_loop())
async def stop_outbox() -> None:
global _outbox_task
task = _outbox_task
_outbox_task = None
if task is None:
return
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
await broker.close()
def _aware(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
async def claim(job_id: UUID, pipeline_version: int):
token = uuid4()
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"SELECT * FROM attachment_jobs WHERE job_id = $1 FOR UPDATE",
job_id,
)
if row is None:
return "missing", None
if int(row["pipeline_version"]) != pipeline_version:
return "stale", row
if row["status"] == "ready":
return "ready", row
attachment = await conn.fetchrow(
"SELECT status, applied_pipeline_version FROM attachments WHERE id = $1",
row["attachment_id"],
)
applied = int(attachment["applied_pipeline_version"]) if attachment is not None else 0
if applied > int(row["pipeline_version"]):
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_token = NULL,
lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND status <> 'ready'
""",
job_id,
)
return "ready", row
if row["status"] == "failed":
return "failed", row
lease = _aware(row["lease_until"])
if row["status"] == "processing" and lease is not None and lease > datetime.now(timezone.utc):
return "busy", row
if int(row["attempt"]) > config.JOB_MAX_ATTEMPTS:
await _fail(conn, row, "retry_exhausted")
return "failed", row
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'processing',
lease_token = $2,
lease_until = now() + ($3::int * interval '1 second'),
error_code = NULL,
updated_at = now()
WHERE job_id = $1
""",
job_id,
token,
config.JOB_LEASE_SECONDS,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
claimed = dict(row)
claimed["lease_token"] = token
claimed["status"] = "processing"
return "claimed", claimed
async def _fail(conn, row, code: str) -> None:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'failed', error_code = $2, lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND status <> 'ready'
""",
row["job_id"],
code,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
code,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'failed', $3)
""",
row["job_id"],
row["attachment_id"],
code,
)
async def fail_job(job_id: UUID, lease_token: UUID, code: str) -> bool:
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"""
SELECT * FROM attachment_jobs
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
FOR UPDATE
""",
job_id,
lease_token,
)
if row is None:
return False
await _fail(conn, row, code)
failed = dict(row)
try:
await broker.publish_dlq(message_of(failed))
except Exception:
logger.warning("failed job is stored; DLQ publish will be retried by an operator replay")
return True
async def schedule_retry(job_id: UUID, lease_token: UUID, code: str) -> str:
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"""
SELECT * FROM attachment_jobs
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
FOR UPDATE
""",
job_id,
lease_token,
)
if row is None:
return "lost"
nxt = int(row["attempt"]) + 1
if nxt > config.JOB_MAX_ATTEMPTS:
await _fail(conn, row, "retry_exhausted")
failed = True
else:
delay = backoff_seconds(int(row["attempt"]))
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = $2,
error_code = $3,
lease_token = NULL,
lease_until = NULL,
published_at = NULL,
next_attempt_at = now() + ($4::double precision * interval '1 second'),
updated_at = now()
WHERE job_id = $1
""",
job_id,
nxt,
code,
delay,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'retry', $3)
""",
job_id,
row["attachment_id"],
code,
)
failed = False
failed_row = None
if failed:
failed_row = row
if failed:
try:
await broker.publish_dlq(message_of(failed_row))
except Exception:
logger.warning("retry exhausted; DLQ publish failed")
return "failed"
return "retry"
async def _intent(key: str) -> None:
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO blob_writes (object_key, committed)
VALUES ($1, FALSE)
ON CONFLICT (object_key) DO NOTHING
""",
key,
)
async def complete_job(
job_id: UUID,
lease_token: UUID,
attachment_id: UUID,
final_key: str,
variants: list,
pipeline_version: int,
) -> bool:
async with db.require().acquire() as conn:
async with conn.transaction():
owned = await conn.fetchrow(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
RETURNING pipeline_version
""",
job_id,
lease_token,
)
if owned is None:
return False
current = await conn.fetchrow(
"""
SELECT status, applied_pipeline_version
FROM attachments
WHERE id = $1
FOR UPDATE
""",
attachment_id,
)
if current is None:
raise PermanentJobError("invalid_image")
version = int(owned["pipeline_version"])
applied = int(current["applied_pipeline_version"])
superseded = applied > version
if not superseded:
await conn.execute(
"""
UPDATE attachments
SET status = 'ready',
object_key = CASE WHEN $2 = '' THEN object_key ELSE $2 END,
error_code = NULL,
applied_pipeline_version = $3,
updated_at = now()
WHERE id = $1 AND applied_pipeline_version <= $3
""",
attachment_id,
final_key,
version,
)
for variant in variants:
await conn.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
""",
attachment_id,
version,
variant["name"],
variant["content_type"],
variant["size_bytes"],
variant["width"],
variant["height"],
variant["sha256"],
variant["object_key"],
)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
variant["object_key"],
)
if final_key:
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
final_key,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'ready', $3)
""",
job_id,
attachment_id,
"superseded" if superseded else "variants committed",
)
return True
async def load_attachment(attachment_id: UUID):
async with db.require().acquire() as conn:
return await conn.fetchrow(
"""
SELECT id, filename, content_type, size_bytes, sha256, object_key, status,
applied_pipeline_version
FROM attachments
WHERE id = $1
""",
attachment_id,
)
async def process(job_id: UUID, pipeline_version: int) -> str:
started = time.perf_counter()
state, row = await claim(job_id, pipeline_version)
if state != "claimed":
return state
assert row is not None
lease = row["lease_token"]
try:
await asyncio.wait_for(_effect(row, lease), config.JOB_TIMEOUT_SECONDS)
outcome = "ready"
except PermanentJobError as exc:
await fail_job(job_id, lease, exc.code)
outcome = "failed"
except (TransientJobError, asyncio.TimeoutError, AppError):
outcome = await schedule_retry(job_id, lease, "processing_failed")
except Exception:
logger.warning("job processing failed job_id=%s", job_id)
outcome = await schedule_retry(job_id, lease, "processing_failed")
elapsed = time.perf_counter() - started
if outcome in ("ready", "failed", "retry", "lost"):
telemetry.record_job(outcome, elapsed)
if outcome == "ready":
created = _aware(row["created_at"])
if created is not None:
telemetry.record_time_to_ready((datetime.now(timezone.utc) - created).total_seconds())
return outcome
async def _effect(row, lease: UUID) -> None:
attachment = await load_attachment(row["attachment_id"])
if attachment is None:
raise PermanentJobError("invalid_image")
version = int(row["pipeline_version"])
if int(attachment["applied_pipeline_version"]) > version:
committed = await complete_job(row["job_id"], lease, attachment["id"], "", [], version)
if not committed:
raise TransientJobError("processing_failed")
return
fault = await consume_fault()
if fault == "crash_before_s3":
logger.warning("injected crash before side effect job_id=%s", row["job_id"])
os._exit(1)
if fault == "fail_once":
raise PermanentJobError("processing_failed")
with telemetry.span("s3.get", kind="client", attributes={"s3.operation": "get"}):
data = await s3.get_bytes(attachment["object_key"])
if len(data) != attachment["size_bytes"] or hashlib.sha256(data).hexdigest() != attachment["sha256"]:
raise PermanentJobError("invalid_image")
final_key = f"originals/{attachment['id']}"
if attachment["object_key"] != final_key:
await _intent(final_key)
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": "original"}):
await s3.put_bytes(final_key, data, attachment["content_type"])
with telemetry.span("image.render"):
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
stored = []
for name, (payload, content_type, width, height) in rendered.items():
suffix = "webp" if content_type == "image/webp" else "jpg"
key = f"variants/{attachment['id']}/v{version}/{name}.{suffix}"
await _intent(key)
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": name}):
await s3.put_bytes(key, payload, content_type)
stored.append(
{
"name": name,
"content_type": content_type,
"size_bytes": len(payload),
"width": width,
"height": height,
"sha256": hashlib.sha256(payload).hexdigest(),
"object_key": key,
}
)
if fault == "crash_after_s3" or config.WORKER_CRASH_POINT == "after_s3":
logger.warning("injected crash after object write before result commit job_id=%s", row["job_id"])
os._exit(1)
fresh = await load_attachment(attachment["id"])
if fresh is not None and int(fresh["applied_pipeline_version"]) > version:
stored = []
final_key = ""
with telemetry.span("db.complete", kind="client"):
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
if not committed:
raise TransientJobError("processing_failed")
if stored and attachment["object_key"] != final_key and final_key:
try:
await s3.delete_key(attachment["object_key"])
async with db.require().acquire() as conn:
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", attachment["object_key"])
except Exception:
logger.warning("staging object left for retention attachment_id=%s", attachment["id"])
async def consume_fault() -> str:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
UPDATE pipeline_faults
SET remaining = remaining - 1
WHERE id = 1 AND remaining > 0
RETURNING mode
"""
)
if row is None:
return ""
return row["mode"] or ""
async def arm_fault(mode: str, remaining: int) -> dict:
if mode not in ("", "crash_before_s3", "crash_after_s3", "fail_once"):
raise AppError(400, "invalid fault")
if remaining < 0 or remaining > 5:
raise AppError(400, "invalid fault")
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO pipeline_faults (id, mode, remaining)
VALUES (1, $1, $2)
ON CONFLICT (id) DO UPDATE SET mode = EXCLUDED.mode, remaining = EXCLUDED.remaining
""",
mode,
remaining,
)
return {"mode": mode, "remaining": remaining}
async def bump_pipeline(attachment_id: UUID) -> dict:
created = datetime.now(timezone.utc)
async with db.require().acquire() as conn:
async with conn.transaction():
current = await conn.fetchval(
"SELECT COALESCE(MAX(pipeline_version), 0) FROM attachment_jobs WHERE attachment_id = $1",
attachment_id,
)
if current is None:
return {"result": "missing"}
exists = await conn.fetchval("SELECT 1 FROM attachments WHERE id = $1", attachment_id)
if exists is None:
return {"result": "missing"}
version = int(current) + 1
job_id = uuid4()
traceparent, tracestate = _trace_columns()
await conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at, traceparent, tracestate
)
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4, $5, $6)
""",
job_id,
attachment_id,
version,
created,
traceparent,
tracestate,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'queued', 'pipeline version bumped')
""",
job_id,
attachment_id,
)
kick_publish()
return {"result": "queued", "job_id": str(job_id), "pipeline_version": version}
async def redeliver(job_id: UUID) -> dict:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status,
traceparent, tracestate
FROM attachment_jobs
WHERE job_id = $1
""",
job_id,
)
if row is None:
return {"result": "missing"}
await broker.publish_job(message_of(row), traceparent=row["traceparent"], tracestate=row["tracestate"])
return {
"result": "published",
"job_id": str(row["job_id"]),
"pipeline_version": int(row["pipeline_version"]),
"status": row["status"],
}
async def list_jobs(attachment_id: UUID) -> list:
async with db.require().acquire() as conn:
rows = await conn.fetch(
"""
SELECT job_id, pipeline_version, status, attempt
FROM attachment_jobs
WHERE attachment_id = $1
ORDER BY pipeline_version
""",
attachment_id,
)
variants = await conn.fetch(
"""
SELECT pipeline_version, name, sha256
FROM attachment_variants
WHERE attachment_id = $1
ORDER BY pipeline_version, name
""",
attachment_id,
)
applied = await conn.fetchval(
"SELECT applied_pipeline_version FROM attachments WHERE id = $1",
attachment_id,
)
return {
"applied_pipeline_version": applied,
"jobs": [
{
"job_id": str(row["job_id"]),
"pipeline_version": int(row["pipeline_version"]),
"status": row["status"],
"attempt": int(row["attempt"]),
}
for row in rows
],
"variants": [
{
"pipeline_version": int(row["pipeline_version"]),
"name": row["name"],
"sha256": row["sha256"],
}
for row in variants
],
}
async def replay_attachment(attachment_id: str) -> dict:
async with db.require().acquire() as conn:
job_id = await conn.fetchval(
"""
SELECT job_id FROM attachment_jobs
WHERE attachment_id = $1 AND status = 'failed'
ORDER BY pipeline_version DESC
LIMIT 1
""",
UUID(attachment_id),
)
if job_id is None:
return {"result": "missing"}
return await replay(job_id)
async def replay(job_id: UUID) -> dict:
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"SELECT * FROM attachment_jobs WHERE job_id = $1 FOR UPDATE",
job_id,
)
if row is None:
return {"result": "missing"}
if row["status"] == "ready":
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'replay', 'noop ready')
""",
row["job_id"],
row["attachment_id"],
)
return {"result": "noop", "job_id": str(row["job_id"])}
lease = _aware(row["lease_until"])
if row["status"] == "processing" and lease is not None and lease > datetime.now(timezone.utc):
return {"result": "busy", "job_id": str(row["job_id"])}
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = 1,
error_code = NULL,
lease_token = NULL,
lease_until = NULL,
published_at = NULL,
next_attempt_at = now(),
updated_at = now()
WHERE job_id = $1 AND status <> 'ready'
""",
job_id,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'replay', 'operator replay')
""",
row["job_id"],
row["attachment_id"],
)
await publish_pending()
return {"result": "queued", "job_id": str(job_id)}
async def reap_expired() -> int:
async with db.require().acquire() as conn:
async with conn.transaction():
rows = await conn.fetch(
"""
SELECT job_id, attachment_id, attempt
FROM attachment_jobs
WHERE status = 'processing' AND lease_until < now()
FOR UPDATE SKIP LOCKED
"""
)
changed = 0
for row in rows:
nxt = int(row["attempt"]) + 1
if nxt > config.JOB_MAX_ATTEMPTS:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'failed', error_code = 'retry_exhausted',
lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND status = 'processing'
""",
row["job_id"],
)
await conn.execute(
"""
UPDATE attachments
SET status = 'failed', error_code = 'retry_exhausted', updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
else:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = $2,
error_code = 'lease_expired',
lease_token = NULL,
lease_until = NULL,
published_at = NULL,
next_attempt_at = now(),
updated_at = now()
WHERE job_id = $1 AND status = 'processing'
""",
row["job_id"],
nxt,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
changed += 1
return changed