Files
mtusi2026lab4-fork/src/reconcile.py
T

119 lines
6.0 KiB
Python

"""Repeatable bounded-memory reconciliation. Dry-run is the default."""
import argparse
from collections import Counter
from datetime import datetime, timezone
import hashlib
import json
import time
from botocore.exceptions import ClientError
from src.objects import client, BUCKET, object_lock
from src.storage import storage
def absent(exc):
return exc.response['Error']['Code'] in ('404','NoSuchKey','NotFound')
def reconcile(apply=False,grace_seconds=3600,page_size=100,output=None):
if grace_seconds<5 or not 1<=page_size<=1000:
raise ValueError('grace must be >=5 seconds; page size 1..1000')
started=time.monotonic(); s3=client(); counts=Counter()
# Fixed cutoff at run start protects objects created during the traversal.
cutoff=datetime.now(timezone.utc).timestamp()-grace_seconds
# Streaming listing; no full bucket/object-body materialization.
paginator=s3.get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket=BUCKET,Prefix='originals/',PaginationConfig={'PageSize':page_size}):
counts['list_requests']+=1
for obj in page.get('Contents',[]):
counts['objects_scanned']+=1; key=obj['Key']
with storage.pool.connection() as conn:
if not object_lock(conn,key,wait=False):
counts['locked_skipped']+=1; continue
row=conn.execute('SELECT id FROM attachments WHERE object_key=%s',(key,)).fetchone()
if row:
counts['referenced_kept']+=1; continue
counts['head_requests']+=1
try: head=s3.head_object(Bucket=BUCKET,Key=key)
except ClientError as exc:
if absent(exc): continue
raise
if head['LastModified'].timestamp()>cutoff:
counts['fresh_kept']+=1; continue
counts['orphan_candidates']+=1
if apply:
# Only application/reconciler may write this namespace; both hold this lock.
s3.delete_object(Bucket=BUCKET,Key=key)
counts['objects_deleted']+=1
# Keyset pages keep RAM bounded even for a large metadata table.
last='00000000-0000-0000-0000-000000000000'
while True:
with storage.pool.connection() as conn:
rows=conn.execute('SELECT id,object_key FROM attachments WHERE id>%s ORDER BY id LIMIT %s',(last,page_size)).fetchall()
if not rows: break
counts['db_pages']+=1
for item in rows:
last=str(item['id']); counts['metadata_scanned']+=1
with storage.pool.connection() as conn:
if not object_lock(conn,item['object_key'],wait=False):
counts['locked_skipped']+=1; continue
row=conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(item['id'],)).fetchone()
if not row: continue
counts['head_requests']+=1
try:
head=s3.head_object(Bucket=BUCKET,Key=row['object_key'])
except ClientError as exc:
if not absent(exc): raise
counts['missing_objects']+=1
if row['state']=='ready':
counts['mark_missing_candidates']+=1
if apply:
conn.execute("UPDATE attachments SET state='missing',updated_at=clock_timestamp() WHERE id=%s",(row['id'],))
counts['metadata_marked_missing']+=1
continue
# Verify actual bytes, never trust an ETag or user-provided hash metadata.
digest=hashlib.sha256(); size=0
counts['get_requests']+=1
obj=s3.get_object(Bucket=BUCKET,Key=row['object_key'])
try:
for chunk in obj['Body'].iter_chunks(64*1024):
size+=len(chunk); counts['bytes_verified']+=len(chunk)
if size>10*1024*1024: break
digest.update(chunk)
finally: obj['Body'].close()
valid=(size==row['size_bytes'] and digest.hexdigest()==row['sha256'] and head['ContentType']==row['content_type'])
desired='ready' if valid else 'missing'
counts['valid_objects' if valid else 'corrupt_objects']+=1
if desired!=row['state']:
counts['restore_candidates' if valid else 'mark_missing_candidates']+=1
if apply:
conn.execute('UPDATE attachments SET state=%s,updated_at=clock_timestamp() WHERE id=%s',(desired,row['id']))
counts['metadata_restored' if valid else 'metadata_marked_missing']+=1
result={'apply':apply,'grace_seconds':grace_seconds,'page_size':page_size,
'elapsed_seconds':round(time.monotonic()-started,6),'counts':dict(counts)}
if output:
from pathlib import Path
Path(output).write_text(json.dumps(result,indent=2),encoding='utf-8')
return result
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply',action='store_true')
parser.add_argument('--grace-seconds',type=int,default=3600)
parser.add_argument('--page-size',type=int,default=100)
parser.add_argument('--interval',type=int,default=0,help='repeat every N seconds, 0 = one shot')
args=parser.parse_args()
if args.interval and args.interval<5:
parser.error('interval must be >=5 seconds')
storage.pool.open(wait=True)
try:
while True:
try:
print(json.dumps(reconcile(args.apply,args.grace_seconds,args.page_size)),flush=True)
except Exception as exc:
# Do not log endpoint URLs, DSNs, object keys or credentials.
print(json.dumps({'result':'failed','error_type':type(exc).__name__}),flush=True)
if not args.interval: raise SystemExit(1) from None
if not args.interval: break
time.sleep(args.interval)
finally: storage.pool.close()
if __name__=='__main__': main()