"""Dry-run by default. Repairs visibility, never invents lost bytes or deletes referenced files.""" import argparse from datetime import datetime, timezone import hashlib import json import os import time from botocore.exceptions import ClientError import psycopg from psycopg.rows import dict_row from .storage import Storage, HEALTH_KEY def _run(storage, apply, grace_seconds): if grace_seconds < 60: raise ValueError('Safety grace must be at least 60s (request deadline is 30s)') started=time.perf_counter() result={'apply':apply,'grace_seconds':grace_seconds,'objects_scanned':0,'metadata_scanned':0, 'fresh_skipped':0,'busy_skipped':0,'actions':[]} cutoff=datetime.now(timezone.utc).timestamp()-grace_seconds with psycopg.connect(os.environ['DATABASE_URL'],row_factory=dict_row,autocommit=True, options='-c statement_timeout=10000 -c lock_timeout=1000') as db: for page in storage.client.get_paginator('list_objects_v2').paginate(Bucket=storage.bucket,Prefix='originals/'): for obj in page.get('Contents',[]): result['objects_scanned']+=1 key=obj['Key'] if key == HEALTH_KEY: continue # Reserved persistent readiness probe. if obj['LastModified'].timestamp()>=cutoff: result['fresh_skipped']+=1 continue with db.transaction(): lock=db.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS acquired',(key,)).fetchone() if not lock['acquired']: result['busy_skipped']+=1 continue if db.execute('SELECT 1 FROM attachments WHERE object_key=%s',(key,)).fetchone(): continue # Recheck actual modification time under lock (stale listing is insufficient). try: head=storage.client.head_object(Bucket=storage.bucket,Key=key) except ClientError as exc: if exc.response['Error']['Code'] in ('404','NoSuchKey'): continue raise if head['LastModified'].timestamp()>=cutoff: continue result['actions'].append({'action':'delete_orphan','key':key}) if apply: storage.delete(key) # Keyset scan keeps memory bounded even for a large metadata table. last=None while True: rows=db.execute('SELECT * FROM attachments WHERE (%s::uuid IS NULL OR id>%s::uuid) ORDER BY id LIMIT 100',(last,last)).fetchall() if not rows: break for row in rows: result['metadata_scanned']+=1 key=row['object_key'] with db.transaction(): lock=db.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS acquired',(key,)).fetchone() if not lock['acquired']: result['busy_skipped']+=1 continue try: head=storage.client.head_object(Bucket=storage.bucket,Key=key) present=head['ContentLength']==row['size_bytes'] and head.get('Metadata',{}).get('sha256')==row['sha256'] except ClientError as exc: if exc.response['Error']['Code'] not in ('404','NoSuchKey'): raise present=False if not present and row['storage_state']=='ready': result['actions'].append({'action':'quarantine_missing','id':str(row['id'])}) if apply: db.execute("UPDATE attachments SET storage_state='missing',updated_at=clock_timestamp() WHERE id=%s",(row['id'],)) elif present and row['storage_state']=='missing': # A repaired object must match actual bytes, not only user metadata. obj=storage.get(key) digest=hashlib.sha256() size=0 try: while block:=obj['Body'].read(65536): digest.update(block); size+=len(block) if size>row['size_bytes']: break finally: obj['Body'].close() if size==row['size_bytes'] and digest.hexdigest()==row['sha256']: result['actions'].append({'action':'restore_ready','id':str(row['id'])}) if apply: db.execute("UPDATE attachments SET storage_state='ready',updated_at=clock_timestamp() WHERE id=%s",(row['id'],)) last=rows[-1]['id'] result['elapsed_seconds']=round(time.perf_counter()-started,6) return result def run(apply=False, grace_seconds=600): storage=Storage() try: return _run(storage,apply,grace_seconds) finally: storage.client.close() if __name__=='__main__': p=argparse.ArgumentParser() p.add_argument('--apply',action='store_true') p.add_argument('--grace-seconds',type=int,default=600) args=p.parse_args() print(json.dumps(run(args.apply,args.grace_seconds),indent=2))