Files
mtusi2026lab7/src/recovery.py
T

115 lines
4.1 KiB
Python

"""Reclaim expired jobs and remove staging after safe publication or retention."""
from datetime import datetime, timedelta, timezone
import os
import time
from botocore.exceptions import ClientError
from .database import get_connection
from .jobs import recover_one
from .process import serve
from .queue_metrics import observe
from .storage import BUCKET, s3
RETENTION = int(os.getenv('STAGING_RETENTION_SECONDS', '86400'))
def lock_staging(conn, key):
return conn.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS ok',
(key,)).fetchone()['ok']
def detach_staging(key, cutoff):
with get_connection() as conn:
if not lock_staging(conn, key):
return False
row = conn.execute("""
SELECT id,status,active_version,object_key,updated_at
FROM attachments WHERE staging_key=%s FOR NO KEY UPDATE
""", (key,)).fetchone()
if not row:
return False
if row['active_version'] is not None:
if row['object_key'] == key or row['object_key'].startswith('staging/'):
return False
elif row['status'] != 'failed' or row['updated_at'] >= cutoff:
return False
conn.execute('UPDATE attachments SET staging_key=NULL WHERE id=%s', (row['id'],))
# Commit the detach before deleting. Replay and reprocess can no longer use
# a failed attachment's staging even if the DELETE succeeds but times out.
return True
def delete_unreferenced(key):
with get_connection() as conn:
if not lock_staging(conn, key):
return
if conn.execute("""
SELECT 1 FROM attachments
WHERE staging_key=%s OR (object_key=%s AND status <> 'failed')
""", (key, key)).fetchone():
return
try:
s3.delete_object(Bucket=BUCKET, Key=key)
except ClientError as exc:
if exc.response.get('Error', {}).get('Code') != 'NoSuchKey':
raise
def cleanup():
cutoff = datetime.now(timezone.utc) - timedelta(seconds=RETENTION)
# Start from PostgreSQL so an already absent object cannot leave a dangling
# staging pointer that would otherwise be invisible to the S3 listing.
after = 'staging/'
while True:
with get_connection() as conn:
rows = conn.execute("""
SELECT staging_key FROM attachments
WHERE staging_key > %s AND staging_key LIKE 'staging/%%'
AND (active_version IS NOT NULL OR (status='failed' AND updated_at < %s))
ORDER BY staging_key LIMIT 100
""", (after, cutoff)).fetchall()
if not rows:
break
for row in rows:
key = row['staging_key']
if detach_staging(key, cutoff):
delete_unreferenced(key)
after = rows[-1]['staging_key']
# An upload that did not commit, or a detached object whose delete failed,
# becomes eligible for collection from S3 after retention.
params = {'Bucket': BUCKET, 'Prefix': 'staging/'}
while True:
page = s3.list_objects_v2(**params)
for obj in page.get('Contents', []):
if obj['LastModified'] < cutoff and obj['Key'].startswith('staging/'):
delete_unreferenced(obj['Key'])
if not page.get('IsTruncated'):
break
params['ContinuationToken'] = page['NextContinuationToken']
def loop(stopping, progress):
next_cleanup = next_observation = 0
while not stopping.is_set():
# Bound each batch so an expired-job backlog cannot starve cleanup.
for _ in range(100):
if stopping.is_set() or not recover_one():
break
progress()
if stopping.is_set():
break
if time.monotonic() >= next_observation:
observe()
next_observation = time.monotonic() + 3
if time.monotonic() >= next_cleanup:
cleanup()
next_cleanup = time.monotonic() + 15
progress()
stopping.wait(0.5)
if __name__ == '__main__':
serve(loop, 'recovery')