forked from mtusi2026/mtusi2026lab5
131 lines
4.2 KiB
Python
131 lines
4.2 KiB
Python
"""Explicit replay of a failed attachment job.
|
|
|
|
A ready job is recorded and left alone: replay does not run the pipeline again.
|
|
Queued and processing jobs are left to the worker that already owns them.
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
import sys
|
|
import uuid
|
|
|
|
from .broker import Broker, BrokerDown
|
|
from .config import load_broker_url, load_settings
|
|
from .db import open_pool
|
|
from .jobs import PIPELINE_VERSION
|
|
from .outbox import publish_job
|
|
|
|
|
|
def _parse_id(value: str) -> uuid.UUID:
|
|
try:
|
|
parsed = uuid.UUID(value)
|
|
except ValueError:
|
|
raise SystemExit(2) from None
|
|
if str(parsed) != value.lower():
|
|
raise SystemExit(2)
|
|
return parsed
|
|
|
|
|
|
async def _decide(pool, attachment_id: uuid.UUID) -> tuple[str, str | None]:
|
|
async with pool.acquire() as conn:
|
|
async with conn.transaction():
|
|
row = await conn.fetchrow(
|
|
'''
|
|
SELECT a.status, j.id AS job_id
|
|
FROM attachments a
|
|
JOIN attachment_jobs j
|
|
ON j.attachment_id = a.id AND j.pipeline_version = $2
|
|
WHERE a.id = $1
|
|
FOR UPDATE
|
|
''',
|
|
attachment_id,
|
|
PIPELINE_VERSION,
|
|
)
|
|
if row is None:
|
|
return 'missing', None
|
|
job_id = row['job_id']
|
|
if row['status'] == 'ready':
|
|
outcome = 'already_ready'
|
|
elif row['status'] != 'failed':
|
|
outcome = 'not_failed'
|
|
else:
|
|
outcome = 'requeued'
|
|
await conn.execute(
|
|
'''
|
|
UPDATE attachment_jobs
|
|
SET attempt = 1,
|
|
runs = 0,
|
|
lease_until = NULL,
|
|
available_at = NULL,
|
|
published_at = NULL,
|
|
last_error = NULL,
|
|
updated_at = clock_timestamp()
|
|
WHERE id = $1
|
|
''',
|
|
job_id,
|
|
)
|
|
await conn.execute(
|
|
'''
|
|
UPDATE attachments
|
|
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
|
WHERE id = $1 AND status = 'failed'
|
|
''',
|
|
attachment_id,
|
|
)
|
|
await conn.execute(
|
|
'''
|
|
INSERT INTO attachment_job_replays (id, job_id, attachment_id, outcome, created_at)
|
|
VALUES ($1, $2, $3, $4, clock_timestamp())
|
|
''',
|
|
uuid.uuid4(),
|
|
job_id,
|
|
attachment_id,
|
|
outcome,
|
|
)
|
|
return outcome, str(job_id)
|
|
|
|
|
|
async def _main(attachment_id: uuid.UUID) -> int:
|
|
pool = await open_pool(load_settings().database_url)
|
|
broker = None
|
|
try:
|
|
outcome, job_id = await _decide(pool, attachment_id)
|
|
if outcome == 'missing':
|
|
print('missing')
|
|
return 1
|
|
if outcome == 'requeued' and job_id is not None:
|
|
try:
|
|
broker = Broker(load_broker_url())
|
|
await broker.connect()
|
|
await publish_job(pool, broker, job_id)
|
|
except (BrokerDown, RuntimeError):
|
|
print('requeued %s outbox' % attachment_id)
|
|
return 0
|
|
print('%s %s' % (outcome, attachment_id))
|
|
return 0
|
|
finally:
|
|
if broker is not None:
|
|
await broker.close()
|
|
await pool.close()
|
|
|
|
|
|
def main() -> None:
|
|
logging.basicConfig(level=logging.WARNING, format='%(levelname)s %(message)s')
|
|
logging.getLogger('aio_pika').setLevel(logging.ERROR)
|
|
logging.getLogger('aiormq').setLevel(logging.ERROR)
|
|
if len(sys.argv) != 2:
|
|
print('usage: python -m app.replay ATTACHMENT_ID', file=sys.stderr)
|
|
raise SystemExit(2)
|
|
try:
|
|
attachment_id = _parse_id(sys.argv[1])
|
|
code = asyncio.run(_main(attachment_id))
|
|
except SystemExit:
|
|
raise
|
|
except Exception as exc:
|
|
print('replay failed (%s)' % type(exc).__name__, file=sys.stderr)
|
|
raise SystemExit(1) from None
|
|
raise SystemExit(code)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|