forked from mtusi2026/mtusi2026lab5
89 lines
2.9 KiB
Python
89 lines
2.9 KiB
Python
"""Доставка намерений из PostgreSQL; crash hook включается только явно через CLI."""
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import os
|
|
import signal
|
|
from uuid import UUID
|
|
|
|
from app.core.background import (
|
|
TRANSIENT_JOB_ERRORS,
|
|
log_background_error,
|
|
shutdown_event,
|
|
wait_or_stop,
|
|
)
|
|
from app.core.config import Settings
|
|
from app.core.database import create_db_engine, create_session_factory
|
|
from app.core.jobs import JobSettings
|
|
from app.domain.attachment_jobs import publish_next_job, recover_expired_jobs
|
|
from app.storage.broker import JobBroker
|
|
|
|
|
|
def crash_before_publish(attachment_id: UUID) -> None:
|
|
"""Реальный SIGKILL после чтения принятой job, до publisher confirm и отметки publish."""
|
|
print(
|
|
json.dumps({"fault": "before_publish", "attachment_id": str(attachment_id)}),
|
|
flush=True,
|
|
)
|
|
os.kill(os.getpid(), signal.SIGKILL)
|
|
|
|
|
|
async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
|
|
settings = Settings()
|
|
jobs = JobSettings()
|
|
logging.basicConfig(level=settings.log_level)
|
|
stop = shutdown_event()
|
|
engine = create_db_engine(settings)
|
|
broker = None
|
|
try:
|
|
broker = JobBroker(jobs)
|
|
factory = create_session_factory(engine)
|
|
while not stop.is_set():
|
|
published = False
|
|
try:
|
|
await broker.ensure_ready()
|
|
async with factory() as session:
|
|
await recover_expired_jobs(session, jobs)
|
|
published = await publish_next_job(
|
|
session,
|
|
broker,
|
|
attachment_id=crash_attachment_id,
|
|
before_publish=(
|
|
crash_before_publish
|
|
if crash_attachment_id is not None
|
|
else None
|
|
),
|
|
)
|
|
except TRANSIENT_JOB_ERRORS as error:
|
|
log_background_error("Publisher deferred", error)
|
|
if not published:
|
|
await wait_or_stop(stop, jobs.publisher_poll_seconds)
|
|
finally:
|
|
if broker is not None:
|
|
await broker.aclose()
|
|
await engine.dispose()
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(
|
|
description="Публикация устойчивых jobs в RabbitMQ"
|
|
)
|
|
parser.add_argument(
|
|
"--crash-before-publish",
|
|
type=UUID,
|
|
metavar="ATTACHMENT_ID",
|
|
help="аварийно завершить этот процесс перед публикацией только указанного вложения",
|
|
)
|
|
args = parser.parse_args()
|
|
try:
|
|
asyncio.run(run_publisher(args.crash_before_publish))
|
|
except Exception as error:
|
|
log_background_error("Publisher stopped", error)
|
|
raise SystemExit(1) from None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|