forked from mtusi2026/mtusi2026lab5
182 lines
11 KiB
Python
182 lines
11 KiB
Python
"""PostgreSQL outbox, Redis Streams at-least-once transport and fenced effects."""
|
|
import asyncio
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import random
|
|
import sys
|
|
import tempfile
|
|
from uuid import uuid4, UUID
|
|
from psycopg.types.json import Jsonb
|
|
from redis.asyncio import Redis
|
|
from redis.exceptions import ResponseError
|
|
from .attachments import Attachments, BUCKET
|
|
from .config import Settings
|
|
from .store import Store
|
|
|
|
STREAM='images.v1'
|
|
GROUP='workers'
|
|
MAX_ATTEMPTS=int(os.getenv('MAX_ATTEMPTS','5'))
|
|
|
|
def broker():
|
|
return Redis.from_url(Path('/run/secrets/cache_url').read_text().strip().replace('@redis:', '@broker:'), decode_responses=True)
|
|
|
|
async def publish(store, queue, attachments):
|
|
async with store.pool.connection() as conn:
|
|
# Row locks fence stale workers; recovery waits until their connection is gone.
|
|
expired=await conn.execute("""SELECT id,attachment_id,attempts FROM jobs WHERE state='processing'
|
|
AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED""")
|
|
for row in await expired.fetchall():
|
|
if row['attempts']>=MAX_ATTEMPTS:
|
|
await conn.execute("UPDATE jobs SET state='failed',lease_until=NULL WHERE id=%s",(row['id'],))
|
|
await conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=%s",(row['attachment_id'],))
|
|
continue
|
|
await conn.execute("UPDATE jobs SET state='queued', available_at=clock_timestamp(),last_published=NULL WHERE id=%s",(row['id'],))
|
|
await conn.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s",(row['attachment_id'],))
|
|
cur=await conn.execute("""SELECT * FROM jobs WHERE state='queued' AND available_at<=clock_timestamp()
|
|
AND (last_published IS NULL OR last_published<clock_timestamp()-interval '5 seconds')
|
|
ORDER BY available_at LIMIT 50 FOR UPDATE SKIP LOCKED""")
|
|
for row in await cur.fetchall():
|
|
payload=dict(schema_version=1,job_id=str(row['id']),type='attachment.process.v1',
|
|
attachment_id=str(row['attachment_id']),pipeline_version=1,attempt=row['attempts']+1,
|
|
created_at=row['created_at'].isoformat())
|
|
await queue.xadd(STREAM,{'payload':json.dumps(payload)})
|
|
# Redis appendfsync=always confirms its AOF before replying. A lost reply
|
|
# or DB rollback causes a duplicate. DB intent stays until terminal state.
|
|
await conn.execute('UPDATE jobs SET last_published=clock_timestamp() WHERE id=%s',(row['id'],))
|
|
# Delete staging only for safely committed ready; repeated deletion is safe.
|
|
async with store.pool.connection() as conn:
|
|
cur=await conn.execute("SELECT id FROM attachments WHERE status='ready' AND staging_cleaned=false LIMIT 100")
|
|
for row in await cur.fetchall():
|
|
await asyncio.to_thread(attachments.s3.delete_object,Bucket=BUCKET,Key='staging/'+row['id'].hex)
|
|
await conn.execute('UPDATE attachments SET staging_cleaned=true WHERE id=%s',(row['id'],))
|
|
# Failed inputs retained for replay for 7 days, then removed; row remains auditable.
|
|
cur=await conn.execute("""SELECT a.id FROM attachments a JOIN jobs j ON j.attachment_id=a.id
|
|
WHERE a.status='failed' AND a.updated_at<clock_timestamp()-interval '7 days'
|
|
AND NOT a.staging_cleaned LIMIT 100 FOR UPDATE OF j SKIP LOCKED""")
|
|
for row in await cur.fetchall():
|
|
await asyncio.to_thread(attachments.s3.delete_object,Bucket=BUCKET,Key='staging/'+row['id'].hex)
|
|
await conn.execute('UPDATE attachments SET staging_cleaned=true WHERE id=%s',(row['id'],))
|
|
|
|
async def process(store, attachments, payload):
|
|
job_id=UUID(payload['job_id'])
|
|
async with store.pool.connection() as conn:
|
|
cur=await conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(job_id,))
|
|
job=await cur.fetchone()
|
|
if not job or job['state'] in ('ready','failed'):
|
|
return
|
|
if str(job['attachment_id'])!=payload['attachment_id'] or payload['pipeline_version']!=1:
|
|
return
|
|
# DB is authoritative for attempts, availability and lease, never the duplicate payload.
|
|
cur=await conn.execute("""UPDATE jobs SET state='processing',attempts=attempts+1,
|
|
lease_until=clock_timestamp()+interval '90 seconds' WHERE id=%s AND state='queued'
|
|
AND available_at<=clock_timestamp() RETURNING *""",(job_id,))
|
|
job=await cur.fetchone()
|
|
if not job:
|
|
return
|
|
await conn.execute("UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=%s",(job['attachment_id'],))
|
|
# Claim is committed and visible. Effect transaction locks the job for fencing.
|
|
async with store.pool.connection() as conn:
|
|
await conn.execute('SELECT id FROM jobs WHERE id=%s FOR UPDATE',(job_id,))
|
|
cur=await conn.execute('SELECT * FROM attachments WHERE id=%s',(job['attachment_id'],))
|
|
row=await cur.fetchone()
|
|
code=None
|
|
try:
|
|
if job['attempts']>MAX_ATTEMPTS:
|
|
code='retry_exhausted'
|
|
else:
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source=Path(directory)/'source'
|
|
await asyncio.to_thread(attachments.s3.download_file,BUCKET,'staging/'+row['id'].hex,str(source))
|
|
if source.stat().st_size!=row['size_bytes'] or hashlib.sha256(source.read_bytes()).hexdigest()!=row['sha256']:
|
|
code='invalid_image'
|
|
else:
|
|
child=await asyncio.create_subprocess_exec(sys.executable,'-m','app.transform',str(source),row['content_type'],directory,
|
|
stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.DEVNULL)
|
|
try:
|
|
stdout,_=await asyncio.wait_for(child.communicate(),30)
|
|
except BaseException:
|
|
child.kill()
|
|
await child.wait()
|
|
raise
|
|
if child.returncode:
|
|
code='invalid_image'
|
|
else:
|
|
variants=json.loads(stdout)
|
|
await asyncio.to_thread(attachments.s3.copy_object,Bucket=BUCKET,Key=row['object_key'],
|
|
CopySource={'Bucket':BUCKET,'Key':'staging/'+row['id'].hex})
|
|
# Test-only one-shot crash marker on the disposable container filesystem.
|
|
if Path('/tmp/crash_after_object').exists():
|
|
Path('/tmp/crash_after_object').unlink()
|
|
os._exit(86)
|
|
for variant in variants:
|
|
body=(Path(directory)/variant['name']).read_bytes()
|
|
variant.update(size_bytes=len(body),sha256=hashlib.sha256(body).hexdigest())
|
|
await asyncio.to_thread(attachments.s3.put_object,Bucket=BUCKET,
|
|
Key='variants/'+row['id'].hex+'/v1/'+variant['name'],Body=body,ContentType=variant['content_type'])
|
|
await conn.execute("UPDATE attachments SET status='ready',variants=%s,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(Jsonb(variants),row['id']))
|
|
await conn.execute("UPDATE jobs SET state='ready',lease_until=NULL WHERE id=%s",(job_id,))
|
|
return
|
|
except TimeoutError:
|
|
code='processing_timeout'
|
|
except Exception:
|
|
code='storage_unavailable'
|
|
terminal=code=='invalid_image' or job['attempts']>=MAX_ATTEMPTS
|
|
if terminal and code!='invalid_image':
|
|
code='retry_exhausted'
|
|
delay=min(60,2**min(job['attempts'],6))+random.uniform(0,1)
|
|
state='failed' if terminal else 'queued'
|
|
await conn.execute("UPDATE jobs SET state=%s,available_at=clock_timestamp()+(%s*interval '1 second'),lease_until=NULL,last_published=NULL WHERE id=%s",(state,delay,job_id))
|
|
await conn.execute('UPDATE attachments SET status=%s,error_code=%s,updated_at=clock_timestamp() WHERE id=%s',(state,code if terminal else None,row['id']))
|
|
|
|
async def replay(store, job_id, reason):
|
|
if not reason.strip():
|
|
raise ValueError('Replay reason required')
|
|
async with store.pool.connection() as conn:
|
|
cur=await conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(UUID(job_id),))
|
|
job=await cur.fetchone()
|
|
if not job or job['state']!='failed':
|
|
raise ValueError('Only failed jobs can be replayed')
|
|
cur=await conn.execute('SELECT staging_cleaned FROM attachments WHERE id=%s',(job['attachment_id'],))
|
|
if (await cur.fetchone())['staging_cleaned']:
|
|
raise ValueError('Replay retention expired')
|
|
await conn.execute('INSERT INTO replay_audit(job_id,reason) VALUES (%s,%s)',(job['id'],reason))
|
|
await conn.execute("UPDATE jobs SET state='queued',attempts=0,available_at=clock_timestamp(),last_published=NULL WHERE id=%s",(job['id'],))
|
|
await conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(job['attachment_id'],))
|
|
|
|
async def main(role):
|
|
store=Store(Settings.load()); await store.open()
|
|
queue=broker(); attachments=Attachments(store)
|
|
try:
|
|
if role=='replay':
|
|
await replay(store,*sys.argv[2:]); return
|
|
if role=='worker':
|
|
try: await queue.xgroup_create(STREAM,GROUP,id='0',mkstream=True)
|
|
except ResponseError as error:
|
|
if 'BUSYGROUP' not in str(error): raise
|
|
consumer=uuid4().hex
|
|
while True:
|
|
try:
|
|
Path('/tmp/pipeline_alive').touch()
|
|
if role=='publisher':
|
|
await publish(store,queue,attachments); await asyncio.sleep(.5)
|
|
else:
|
|
claimed=await queue.xautoclaim(STREAM,GROUP,consumer,5000,'0-0',count=1)
|
|
entries=claimed[1]
|
|
if not entries:
|
|
batches=await queue.xreadgroup(GROUP,consumer,{STREAM:'>'},count=1,block=1000)
|
|
entries=batches[0][1] if batches else []
|
|
for message_id, fields in entries:
|
|
await process(store,attachments,json.loads(fields['payload']))
|
|
await queue.xack(STREAM,GROUP,message_id)
|
|
await queue.xdel(STREAM,message_id)
|
|
except Exception:
|
|
print(role+': operation deferred',flush=True)
|
|
await asyncio.sleep(1)
|
|
finally:
|
|
await queue.aclose(); await store.close()
|
|
|
|
if __name__=='__main__':
|
|
asyncio.run(main(sys.argv[1]))
|