Files
mtusi2026lab6/app/jobs.py
T

146 lines
6.0 KiB
Python

"""Transactional outbox relay, expired-lease recovery and staging janitor.
DB COMMIT and RabbitMQ publish cannot be one transaction. Keep outbox rows
until a publisher confirm, accepting harmless duplicate delivery on crash.
"""
from __future__ import annotations
import asyncio
import logging
from sqlalchemy import text
from app.db import SessionLocal, engine
from app.pipeline import (RETENTION_SECONDS, arm_from_env, broker_channel,
crash_if_armed, envelope, publish, retry_or_fail)
from app.storage import storage
from app.telemetry import configure, emit, install_termination_handler, shutdown
from app import advanced
logger = logging.getLogger("messenger.jobs")
async def recover_leases() -> int:
async with SessionLocal() as db:
result = await db.execute(text("""
SELECT * FROM attachments WHERE status='processing' AND lease_until<now()
ORDER BY lease_until LIMIT 20 FOR UPDATE SKIP LOCKED
"""))
rows = list(result.mappings())
for row in rows:
await retry_or_fail(db, row, "lease_expired")
await db.commit()
if rows:
logger.warning("recovered expired leases count=%s", len(rows))
return len(rows)
async def cleanup_staging() -> None:
# One object transaction at a time: S3's bounded deadline is shorter
# than idle_in_transaction_session_timeout. Replay takes the same lock.
for _ in range(10):
async with SessionLocal() as db:
# Failed retention may remove five objects. Keep its row lock
# until all bounded deletes finish, so replay cannot race it.
await db.execute(text("SET LOCAL idle_in_transaction_session_timeout='60s'"))
result = await db.execute(text("""
SELECT * FROM attachments
WHERE staging_key IS NOT NULL AND NOT staging_deleted AND
(status='ready' OR (status='failed' AND updated_at <
now()-make_interval(secs => :retention)))
ORDER BY updated_at LIMIT 1 FOR UPDATE SKIP LOCKED
"""), {"retention": RETENTION_SECONDS})
row = result.mappings().first()
if row is None:
await db.rollback()
return
await storage.delete(row["staging_key"])
# Partial final objects of an exhausted job are no longer
# useful after retention; ready objects are never deleted.
if row["status"] == "failed":
prefix = row["object_key"].rsplit("/", 1)[0]
for suffix in ("original", "thumbnail.jpg", "crop.jpg", "optimized.webp"):
await storage.delete(f"{prefix}/{suffix}")
await db.execute(text("""
UPDATE attachments SET staging_deleted=true WHERE id=:id
"""), {"id": row["id"]})
await db.commit()
logger.info("staging cleaned attachment=%s", row["id"])
async def relay_one(channel) -> bool:
async with SessionLocal() as db:
result = await db.execute(text("""
SELECT o.*,a.pipeline_version FROM outbox o
JOIN attachments a ON a.id=o.attachment_id
WHERE o.published_at IS NULL AND o.available_at<=now()
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED
"""))
row = result.mappings().first()
if row is None:
await db.rollback()
return False
# The upload COMMIT already exists; the pending row is untouched
# by this crash, so the restarted relay finds it automatically.
await crash_if_armed("crash_after_commit_before_publish")
await publish(channel, envelope(row))
await db.execute(text("UPDATE outbox SET published_at=now() WHERE id=:id"),
{"id": row["id"]})
await db.commit()
logger.info("published job=%s attempt=%s", row["job_id"], row["attempt"])
return True
async def main() -> None:
configure("messenger-publisher")
install_termination_handler()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
for name in ("aio_pika", "aiormq"):
logging.getLogger(name).setLevel(logging.CRITICAL)
await storage.start()
backlog = asyncio.create_task(advanced.backlog_loop(SessionLocal))
connection = None
try:
await arm_from_env("PUBLISHER_FAULT")
while True:
try:
connection, channel, _ = await broker_channel()
last_maintenance = 0.0
while True:
now = asyncio.get_running_loop().time()
if now - last_maintenance > 1:
await recover_leases()
try:
await cleanup_staging()
except Exception as exc:
# Retention is best effort. S3 failure must not
# starve outbox delivery or exhaustible retries.
logger.warning("staging cleanup deferred: %s", type(exc).__name__)
last_maintenance = now
if not await relay_one(channel):
await asyncio.sleep(0.25)
except asyncio.CancelledError:
raise
except Exception as exc:
# Exception text can contain connection URLs. Log type only.
logger.warning("relay unavailable: %s", type(exc).__name__)
if connection:
await connection.close()
connection = None
await asyncio.sleep(1)
finally:
backlog.cancel()
await asyncio.gather(backlog, return_exceptions=True)
if connection:
await connection.close()
await storage.close()
await engine.dispose()
await asyncio.to_thread(shutdown)
if __name__ == "__main__":
try:
asyncio.run(main())
except asyncio.CancelledError:
pass # SIGTERM has run finally/SDK flush; exit cleanly.