forked from mtusi2026/mtusi2026lab5
61 lines
2.2 KiB
Python
61 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
from datetime import datetime, timezone
|
|
from uuid import UUID
|
|
|
|
from ..config import load_settings
|
|
from ..db import create_engine, create_session_factory
|
|
from ..repositories import JobRepository
|
|
from ..storage import S3Storage
|
|
|
|
|
|
async def replay(job_id: UUID | None, attachment_id: UUID | None, dry_run: bool) -> int:
|
|
settings = load_settings()
|
|
engine = create_engine(settings.database_url)
|
|
try:
|
|
repository = JobRepository(create_session_factory(engine))
|
|
if job_id is None:
|
|
assert attachment_id is not None
|
|
job_id = await repository.id_for_attachment(attachment_id)
|
|
if job_id is None:
|
|
print(f'REJECTED attachment_id={attachment_id} reason=job_not_found')
|
|
return 2
|
|
staging_key = await repository.failed_staging_key(job_id)
|
|
if staging_key is None:
|
|
print(f'REJECTED job_id={job_id} reason=not_failed_or_staging_missing')
|
|
return 2
|
|
storage = S3Storage(
|
|
settings.s3_endpoint,
|
|
settings.s3_access_key_id,
|
|
settings.s3_secret_access_key,
|
|
settings.s3_bucket,
|
|
settings.s3_region,
|
|
)
|
|
if not await storage.exists(staging_key):
|
|
print(f'REJECTED job_id={job_id} reason=staging_object_missing')
|
|
return 2
|
|
accepted = await repository.replay(job_id, datetime.now(timezone.utc), dry_run)
|
|
if not accepted:
|
|
print(f'REJECTED job_id={job_id} reason=not_failed_or_staging_missing')
|
|
return 2
|
|
print(f'{"WOULD_REPLAY" if dry_run else "REPLAYED"} job_id={job_id}')
|
|
return 0
|
|
finally:
|
|
await engine.dispose()
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description='Safely replay one failed attachment job')
|
|
target = parser.add_mutually_exclusive_group(required=True)
|
|
target.add_argument('--job-id', type=UUID)
|
|
target.add_argument('--attachment-id', type=UUID)
|
|
parser.add_argument('--dry-run', action='store_true')
|
|
args = parser.parse_args()
|
|
raise SystemExit(asyncio.run(replay(args.job_id, args.attachment_id, args.dry_run)))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|