ЛР 5 — БВТ2303 — Брезгунова — на 5

This commit is contained in:
2026-11-13 13:10:15 +03:00
parent 276dbdad8a
commit ab9161be3d
64 changed files with 5191 additions and 34 deletions
+1
View File
@@ -0,0 +1 @@
+523
View File
@@ -0,0 +1,523 @@
"""Messenger API: durable ingress, asynchronous versioned image pipeline."""
import asyncio
import base64
import datetime as dt
import hashlib
import hmac
import json
import logging
import os
import re
import secrets
import tempfile
import unicodedata
import uuid
import warnings
from contextlib import asynccontextmanager
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
from botocore.exceptions import BotoCoreError, ClientError
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from PIL import Image, UnidentifiedImageError
import psycopg
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import ClientDisconnect
from .storage import BUCKET, PREFIX, STORAGE_LOCK, db, s3, setting
from .jobs import enqueue
MAX_BYTES = min(int(os.getenv('MAX_UPLOAD_BYTES', '10485760')), 10485760)
MAX_PIXELS = min(int(os.getenv('MAX_IMAGE_PIXELS', '40000000')), 40000000)
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
INSTANCE = os.getenv('INSTANCE_ID', uuid.uuid4().hex)
PH = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
DUMMY_HASH = PH.hash(secrets.token_hex(32))
CODES = {400:'invalid_request',401:'unauthorized',404:'not_found',409:'conflict',
413:'payload_too_large',415:'unsupported_media_type',429:'rate_limited',
503:'unavailable',500:'internal_error'}
MESSAGES = {400:'Invalid request',401:'Authentication required',404:'Resource not found',
409:'Conflicting request',413:'Upload limit exceeded',415:'Invalid image or media type',
429:'Upload capacity exhausted',503:'Storage temporarily unavailable',500:'Internal error'}
class APIError(Exception):
def __init__(self, status):
self.status = status
def fail(status):
raise APIError(status)
def stamp(value):
return value.astimezone(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def ident(value):
if not isinstance(value, str):
fail(400)
try:
return str(uuid.UUID(value))
except ValueError:
fail(400)
def string(value, lo, hi, nonblank=True):
if not isinstance(value, str) or not lo <= len(value) <= hi or (nonblank and not value.strip()):
fail(400)
if any(0xD800 <= ord(c) <= 0xDFFF or c == '\x00' for c in value):
fail(400)
return value
def ids(value, maximum, minimum=0):
if not isinstance(value, list) or not minimum <= len(value) <= maximum:
fail(400)
result = [ident(x) for x in value]
if len(set(result)) != len(result):
fail(400)
return result
def strict_json(data, required, optional=()):
try:
def pairs(items):
result = {}
for k, v in items:
if k in result:
raise ValueError('Duplicate key')
result[k] = v
return result
value = json.loads(data, object_pairs_hook=pairs,
parse_constant=lambda x: (_ for _ in ()).throw(ValueError()))
except (ValueError, UnicodeError, RecursionError):
fail(400)
if not isinstance(value, dict) or not set(required) <= value.keys() or value.keys() - set(required) - set(optional):
fail(400)
return value
def user(row):
return {k: str(row[k]) for k in ('id','username','display_name')} | {'created_at':stamp(row['created_at'])}
def chat(conn, row):
members = conn.execute('SELECT user_id FROM members WHERE chat_id=%s ORDER BY user_id', (row['id'],)).fetchall()
return {'id':str(row['id']), 'title':row['title'], 'created_at':stamp(row['created_at']),
'member_ids':[str(x['user_id']) for x in members]}
def message(conn, row):
attached = conn.execute('SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (row['id'],)).fetchall()
return {'id':str(row['id']), 'chat_id':str(row['chat_id']), 'sender_id':str(row['sender_id']),
'text':row['text'], 'created_at':stamp(row['created_at']),
'attachment_ids':[str(x['attachment_id']) for x in attached]}
def attachment(row):
return {k:str(row[k]) for k in ('id','chat_id','owner_id','filename','content_type','sha256')} | {
'size_bytes':row['size_bytes'], 'status':row['status'],
'variants':[{k:v for k,v in x.items() if k != 'object_key'} for x in row['variants']],
'error_code':row['error_code'],
'created_at':stamp(row['created_at']), 'updated_at':stamp(row['updated_at'])}
def authenticate(conn, authorization):
if not authorization.startswith('Bearer ') or not authorization[7:]:
fail(401)
token_hash = hashlib.sha256(authorization[7:].encode()).hexdigest()
row = conn.execute('SELECT u.* FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=%s AND s.expires_at>clock_timestamp()', (token_hash,)).fetchone()
if not row:
fail(401)
return row, token_hash
def access(conn, uid, cid):
row = conn.execute('SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s', (cid,uid)).fetchone()
if not row:
fail(404)
return row
def authorize_upload(authorization, cid):
with db() as conn:
actor, _ = authenticate(conn, authorization)
cid = ident(cid)
access(conn, actor['id'], cid)
return str(actor['id']), cid
def query(request, allowed):
if set(request.query_params) - set(allowed) or any(len(request.query_params.getlist(k)) != 1 for k in request.query_params):
fail(400)
return dict(request.query_params)
def page(conn, kind, resource, actor, params):
raw = params.get('limit','50')
if len(raw)>3 or not re.fullmatch(r'[0-9]+', raw) or not 1 <= int(raw) <= 100:
fail(400)
limit = int(raw)
boundary = dt.datetime.min.replace(tzinfo=dt.timezone.utc)
bid = '00000000-0000-0000-0000-000000000000'
scope = kind + ':' + resource
if 'cursor' in params:
if len(params['cursor'])>2048:
fail(400)
try:
encoded, signature = params['cursor'].split('.')
expected = hmac.new(setting('CURSOR_SECRET').encode(), encoded.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
fail(400)
payload = json.loads(base64.urlsafe_b64decode(encoded + '=' * (-len(encoded) % 4)))
if payload['scope'] != scope:
fail(400)
boundary = dt.datetime.fromisoformat(payload['time'])
bid = ident(payload['id'])
except (ValueError, KeyError, TypeError):
fail(400)
if kind == 'chats':
rows = conn.execute('SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id WHERE m.user_id=%s AND (c.created_at,c.id)>(%s,%s::uuid) ORDER BY c.created_at,c.id LIMIT %s', (actor,boundary,bid,limit+1)).fetchall()
items = [chat(conn,x) for x in rows[:limit]]
else:
rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s::uuid) ORDER BY created_at,id LIMIT %s', (resource,boundary,bid,limit+1)).fetchall()
items = [message(conn,x) for x in rows[:limit]]
cursor = None
if len(rows) > limit:
last = rows[limit-1]
encoded = base64.urlsafe_b64encode(json.dumps({'scope':scope,'time':stamp(last['created_at']),'id':str(last['id'])}, sort_keys=True).encode()).decode().rstrip('=')
cursor = encoded + '.' + hmac.new(setting('CURSOR_SECRET').encode(), encoded.encode(), hashlib.sha256).hexdigest()
return {'items':items, 'next_cursor':cursor}
@asynccontextmanager
async def lifespan(app):
app.state.upload_slots = asyncio.Semaphore(4)
app.state.json_slots = asyncio.Semaphore(16)
yield
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
def error_response(request, status):
headers = {}
if status == 401:
headers['WWW-Authenticate'] = ('Basic realm="messenger", charset="UTF-8"' if request.url.path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"')
return JSONResponse({'error':{'code':CODES[status], 'message':MESSAGES[status],
'request_id':request.state.request_id}}, status, headers=headers)
@app.middleware('http')
async def errors_and_identity(request, call_next):
request.state.request_id = uuid.uuid4().hex
try:
result = await call_next(request)
except APIError as exc:
result = error_response(request, exc.status)
except (psycopg.Error, BotoCoreError, ClientError) as exc:
code = exc.response.get('Error',{}).get('Code','') if isinstance(exc,ClientError) else getattr(exc,'sqlstate','')
logging.warning('Storage failure: %s code=%s',type(exc).__name__,code)
result = error_response(request, 503)
except Exception:
result = error_response(request, 500)
result.headers['X-Request-Id'] = request.state.request_id
result.headers['X-Instance-Id'] = INSTANCE
return result
@app.exception_handler(APIError)
async def api_error(request, exc):
return error_response(request, exc.status)
@app.exception_handler(HTTPException)
async def http_error(request, exc):
return error_response(request, 404 if exc.status_code == 404 else 400)
@app.get('/health/live')
def live():
return {'status':'ok'}
@app.get('/internal-test/memory')
def test_memory():
if os.getenv('ENABLE_TEST_METRICS') != '1':
fail(404)
with open('/proc/self/status') as status:
rss = next(int(line.split()[1])*1024 for line in status if line.startswith('VmRSS:'))
usage = os.times()
with open('/sys/fs/cgroup/memory.current') as current:
container_memory = int(current.read())
with open('/sys/fs/cgroup/memory.peak') as peak:
container_peak = int(peak.read())
return {'rss_bytes':rss, 'cpu_seconds':usage.user+usage.system,
'container_memory_bytes':container_memory, 'container_peak_bytes':container_peak}
@app.get('/health/ready')
def ready():
with db() as conn:
conn.execute('SELECT 1 FROM attachments LIMIT 1')
s3().head_bucket(Bucket=BUCKET)
return {'status':'ok'}
def validate_image(file, declared):
try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
file.seek(0)
with Image.open(file) as im:
if im.format not in ('PNG','JPEG') or Image.MIME[im.format] != declared:
fail(415)
if im.width * im.height > MAX_PIXELS:
fail(413)
if getattr(im,'n_frames',1) != 1:
fail(415)
im.verify()
file.seek(0)
with Image.open(file) as im:
im.load() # JPEG verify() alone does not detect truncation.
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
fail(413)
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
fail(415)
file.seek(0)
def persist_upload(file, authorization, cid, filename, declared, size, sha):
validate_image(file, declared)
client = s3()
aid = str(uuid.uuid4())
key = 'staging/' + aid
# Shared transaction lock covers PUT -> COMMIT; reconciler takes the exclusive lock.
# If COMMIT outcome is ambiguous, never delete here: the reconciler checks the committed DB.
with db() as conn:
actor, _ = authenticate(conn, authorization)
access(conn, actor['id'], cid)
conn.execute('SELECT pg_advisory_xact_lock_shared(%s)', (STORAGE_LOCK,))
# Serialize admission across replicas; the DB includes unpublished work.
conn.execute('SELECT pg_advisory_xact_lock(550005)')
pending = conn.execute("SELECT count(*) AS n FROM attachments WHERE status IN ('queued','processing')").fetchone()['n']
if pending >= int(os.getenv('MAX_PENDING_JOBS','1000')):
fail(429)
md5 = base64.b64encode(hashlib.file_digest(file, 'md5').digest()).decode()
file.seek(0)
client.put_object(Bucket=BUCKET, Key=key, Body=file, ContentLength=size,
ContentType=declared, Metadata={'sha256':sha},
ContentMD5=md5)
# Test-only fault injection is disabled in the regular Compose configuration.
if os.getenv('FAULT_AFTER_PUT') == '1':
fail(503)
row = conn.execute('INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,staging_key,content_type,size_bytes,sha256) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *',
(aid,cid,actor['id'],filename,f'results/{aid}/v1/original',key,declared,size,sha)).fetchone()
enqueue(conn,aid,1)
result = attachment(row)
return result
@app.post('/api/v1/chats/{cid}/attachments')
async def upload(request: Request, cid: str):
authorization = request.headers.get('authorization','')
_, cid = await run_in_threadpool(authorize_upload, authorization, cid)
params = query(request, ('filename',))
filename = string(params.get('filename'),1,255)
if any(c in '/\\' or unicodedata.category(c).startswith('C') for c in filename):
fail(400)
declared = request.headers.get('content-type','').lower()
if declared not in ('image/png','image/jpeg'):
fail(415)
length = request.headers.get('content-length')
if length is not None:
if len(length)>10 or not re.fullmatch('[0-9]+', length):
fail(400)
if int(length) > MAX_BYTES:
fail(413)
try:
await asyncio.wait_for(request.app.state.upload_slots.acquire(), timeout=1)
except TimeoutError:
fail(429)
try:
with tempfile.TemporaryFile() as file: # receive buffer; durable staging is S3 before 202
digest = hashlib.sha256()
size = 0
async def receive():
nonlocal size
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
fail(413)
digest.update(chunk)
file.write(chunk)
try:
await asyncio.wait_for(receive(), timeout=30)
except (TimeoutError, ClientDisconnect):
fail(400)
if not size or (length is not None and size != int(length)):
fail(415 if not size else 400)
file.seek(0)
# file_digest leaves position at EOF; compute MD5 without moving the PUT body.
result = await run_in_threadpool(persist_upload, file, authorization, cid, filename, declared, size, digest.hexdigest())
return JSONResponse(result,202)
finally:
request.app.state.upload_slots.release()
def dispatch(method, path, authorization, data, params, headers):
with db() as conn:
if path == '/api/v1/users' and method == 'POST':
value = strict_json(data, ('username','display_name','password'))
name = string(value['username'],3,32)
if not re.fullmatch('[a-z0-9_]{3,32}',name):
fail(400)
display = string(value['display_name'],1,100)
password = string(value['password'],12,128,False)
try:
row = conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES(%s,%s,%s,%s) RETURNING *',
(str(uuid.uuid4()),name,display,PH.hash(password))).fetchone()
except psycopg.errors.UniqueViolation:
fail(409)
return 201, user(row)
if path == '/api/v1/auth/sessions' and method == 'POST':
if data or not authorization.startswith('Basic '):
fail(401)
try:
name,password = base64.b64decode(authorization[6:],validate=True).decode('utf-8').split(':',1)
except (ValueError, UnicodeError):
fail(401)
row = conn.execute('SELECT * FROM users WHERE username=%s',(name,)).fetchone()
try:
PH.verify(row['password_hash'] if row else DUMMY_HASH, password)
except VerificationError:
fail(401)
if not row:
fail(401)
token = secrets.token_urlsafe(32)
expires = dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=int(os.getenv('SESSION_TTL_SECONDS','3600')))
conn.execute('INSERT INTO sessions VALUES(%s,%s,%s)',(hashlib.sha256(token.encode()).hexdigest(),row['id'],expires))
return 201, {'token':token,'token_type':'Bearer','expires_at':stamp(expires),'user':user(row)}
actor, token_hash = authenticate(conn, authorization)
uid = actor['id']
if path == '/api/v1/users/me' and method == 'GET':
return 200, user(actor)
if path == '/api/v1/auth/sessions/current' and method == 'DELETE':
conn.execute('DELETE FROM sessions WHERE token_hash=%s',(token_hash,))
return 204, None
if path == '/api/v1/chats':
if method == 'POST':
value = strict_json(data,('title','member_ids'))
title = string(value['title'],1,100)
members = ids(value['member_ids'],100,1)
if str(uid) not in members or conn.execute('SELECT count(*) AS n FROM users WHERE id=ANY(%s::uuid[])',(members,)).fetchone()['n'] != len(members):
fail(400)
row = conn.execute('INSERT INTO chats(id,title) VALUES(%s,%s) RETURNING *',(str(uuid.uuid4()),title)).fetchone()
for member in members:
conn.execute('INSERT INTO members VALUES(%s,%s)',(row['id'],member))
return 201, chat(conn,row)
if method == 'GET':
return 200, page(conn,'chats',str(uid),uid,params)
match = re.fullmatch(r'/api/v1/chats/([^/]+)(/messages)?', path)
if match:
cid = ident(match[1])
current_chat = access(conn,uid,cid)
if not match[2] and method == 'GET':
return 200, chat(conn,current_chat)
if match[2] and method == 'GET':
return 200, page(conn,'messages',cid,uid,params)
if match[2] and method == 'POST':
value = strict_json(data,('text',),('attachment_ids',))
text = string(value['text'],0,4000,False)
attachments = ids(value.get('attachment_ids',[]),10)
if not text.strip() and not attachments:
fail(400)
key = headers.get('idempotency-key','')
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}',key):
fail(400)
canonical = json.dumps({'text':text,'attachment_ids':attachments},sort_keys=True,ensure_ascii=False)
body_hash = hashlib.sha256(canonical.encode()).hexdigest()
# One transaction lock per user/chat/key, shared across API replicas.
lock = int.from_bytes(hashlib.sha256((str(uid)+cid+key).encode()).digest()[:8],'big',signed=True)
conn.execute('SELECT pg_advisory_xact_lock(%s)',(lock,))
for aid in attachments:
a = conn.execute('SELECT * FROM attachments WHERE id=%s AND chat_id=%s',(aid,cid)).fetchone()
if not a:
fail(404)
if a['status'] == 'failed':
fail(409)
if a['availability'] != 'present':
fail(503)
old = conn.execute('SELECT * FROM idempotency WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (uid,cid,key)).fetchone()
if old:
if old['body_hash'] != body_hash:
fail(409)
return 201, message(conn,conn.execute('SELECT * FROM messages WHERE id=%s',(old['message_id'],)).fetchone())
conn.execute('DELETE FROM idempotency WHERE user_id=%s AND chat_id=%s AND key=%s',(uid,cid,key))
row = conn.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES(%s,%s,%s,%s) RETURNING *',(str(uuid.uuid4()),cid,uid,text)).fetchone()
for pos,aid in enumerate(attachments):
conn.execute('INSERT INTO message_attachments VALUES(%s,%s,%s)',(row['id'],aid,pos))
conn.execute("INSERT INTO idempotency VALUES(%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')",(uid,cid,key,body_hash,row['id']))
return 201, message(conn,row)
match = re.fullmatch(r'/api/v1/attachments/([^/]+)(/content)?',path)
if match and method == 'GET':
aid = ident(match[1])
row = conn.execute('SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id WHERE a.id=%s AND m.user_id=%s',(aid,uid)).fetchone()
if not row:
fail(404)
if not match[2]:
return 200, attachment(row)
if row['status'] != 'ready':
fail(409)
variant = params.get('variant','original')
selected = row if variant == 'original' else next((x for x in row['variants'] if x['name']==variant),None)
if selected is None:
fail(404)
if row['availability'] != 'present':
fail(503)
content = s3().get_object(Bucket=BUCKET,Key=selected['object_key'])
body = content['Body']
def stream():
try:
while chunk := body.read(65536):
yield chunk
finally:
body.close()
return 200, StreamingResponse(stream(),media_type=selected['content_type'],
headers={'Content-Length':str(selected['size_bytes']), 'X-Content-Type-Options':'nosniff'})
fail(404)
@app.api_route('/api/v1/{path:path}', methods=['GET','POST','DELETE','PUT','PATCH'])
async def api(request: Request, path: str):
if not (path == 'users' and request.method == 'POST') and not (path == 'auth/sessions' and request.method == 'POST'):
def check_auth():
with db() as conn:
authenticate(conn,request.headers.get('authorization',''))
await run_in_threadpool(check_auth)
params = query(request, ('limit','cursor') if request.method == 'GET' and (path == 'chats' or path.endswith('/messages')) else ('variant',) if path.endswith('/content') else ())
try:
await asyncio.wait_for(request.app.state.json_slots.acquire(),timeout=1)
except TimeoutError:
fail(429)
try:
data = bytearray()
async def receive():
async for chunk in request.stream():
data.extend(chunk)
if len(data) > 65536:
fail(400)
try:
await asyncio.wait_for(receive(),timeout=10)
except (TimeoutError, ClientDisconnect):
fail(400)
# Authentication for protected routes is performed before parsing JSON in dispatch.
status, result = await run_in_threadpool(dispatch, request.method, '/api/v1/'+path,
request.headers.get('authorization',''),bytes(data),params,dict(request.headers))
if isinstance(result, Response):
return result
return Response(status_code=204) if status == 204 else JSONResponse(result,status)
finally:
request.app.state.json_slots.release()
+39
View File
@@ -0,0 +1,39 @@
"""Bounded staging janitor. Never expires queued/processing originals."""
import logging
import os
import time
from .storage import BUCKET,STORAGE_LOCK,db,s3
from .jobs import lock_id
def sweep():
client = s3()
retention = int(os.getenv('STAGING_RETENTION_SECONDS','86400'))
count = 0
for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix='staging/',PaginationConfig={'PageSize':100}):
for obj in page.get('Contents',[]):
if time.time()-obj['LastModified'].timestamp()<retention:
continue
with db() as conn:
conn.execute('SELECT pg_advisory_xact_lock(%s)',(STORAGE_LOCK,))
aid = obj['Key'].removeprefix('staging/')
if not conn.execute('SELECT pg_try_advisory_xact_lock(%s) AS ok',(lock_id(aid),)).fetchone()['ok']:
continue
row = conn.execute('SELECT *,updated_at<clock_timestamp()-(%s*interval \'1 second\') AS expired FROM attachments WHERE staging_key=%s',(retention,obj['Key'])).fetchone()
if row and (row['status'] in ('queued','processing') or not row['expired']):
continue
# HEAD rechecks age under the upload lock; old listing alone is unsafe.
head = client.head_object(Bucket=BUCKET,Key=obj['Key'])
if time.time()-head['LastModified'].timestamp()>=retention:
client.delete_object(Bucket=BUCKET,Key=obj['Key'])
count += 1
return count
if __name__=='__main__':
while True:
try:
print('Expired staging deleted:',sweep(),flush=True)
except Exception as exc:
logging.warning('Cleanup aborted: %s',type(exc).__name__)
time.sleep(60)
+78
View File
@@ -0,0 +1,78 @@
"""DB is the durable intent; Redis Streams provides at-least-once notifications."""
import datetime as dt
import hashlib
import json
import os
import uuid
import redis
from psycopg.types.json import Jsonb
from .storage import setting
STREAM = 'attachments:v1'
GROUP = 'image-workers'
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS','5'))
TIMEOUT = int(os.getenv('JOB_TIMEOUT_SECONDS','60'))
LEASE = max(int(os.getenv('JOB_LEASE_SECONDS','90')), TIMEOUT + 5)
def broker():
return redis.Redis.from_url(setting('BROKER_URL'),decode_responses=True,
socket_timeout=5, socket_connect_timeout=3)
def lock_id(aid):
return int.from_bytes(hashlib.sha256(str(aid).encode()).digest()[:8],'big',signed=True)
def audit(conn,jid,event,detail=''):
conn.execute('INSERT INTO job_audit(job_id,event,detail) VALUES(%s,%s,%s)',(jid,event,detail))
def enqueue(conn,aid,version):
jid = uuid.uuid4()
conn.execute('INSERT INTO jobs(id,attachment_id,pipeline_version) VALUES(%s,%s,%s)',(jid,aid,version))
conn.execute('INSERT INTO outbox(job_id) VALUES(%s)',(jid,))
audit(conn,jid,'accepted')
return jid
def payload(row):
return {'schema_version':1,'job_id':str(row['id']), 'type':'attachment.process.v1',
'attachment_id':str(row['attachment_id']),'pipeline_version':row['pipeline_version'],
'attempt':row['attempts']+1,
'created_at':row['created_at'].astimezone(dt.timezone.utc).isoformat().replace('+00:00','Z')}
def parse_payload(raw):
value = json.loads(raw)
required = {'schema_version','job_id','type','attachment_id','pipeline_version','attempt','created_at'}
if not isinstance(value,dict) or not required <= value.keys() or value.keys()-required-{'traceparent','tracestate'}:
raise ValueError('invalid envelope')
if value['schema_version'] != 1 or value['type'] != 'attachment.process.v1':
raise ValueError('invalid envelope')
for key in ('job_id','attachment_id'):
uuid.UUID(value[key])
for key in ('pipeline_version','attempt'):
if type(value[key]) is not int or value[key] < 1:
raise ValueError('invalid envelope')
dt.datetime.fromisoformat(value['created_at'].replace('Z','+00:00'))
return value
def trip(conn,jid,point):
if os.getenv('ENABLE_FAULTS') != '1':
return False
row = conn.execute('UPDATE fault_rules SET remaining=remaining-1 WHERE job_id=%s AND point=%s AND remaining>0 RETURNING job_id',(jid,point)).fetchone()
if row:
audit(conn,jid,'fault',point)
return bool(row)
def finish_failed(conn,job,code):
conn.execute("UPDATE jobs SET status='failed',error_code=%s,lease_until=NULL WHERE id=%s",(code,job['id']))
conn.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s",(code,job['attachment_id'],job['pipeline_version']))
audit(conn,job['id'],'failed',code)
def set_variants(conn,aid,version,variants):
conn.execute("UPDATE attachments SET variants=%s,status='ready',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s",(Jsonb(variants),aid,version))
+58
View File
@@ -0,0 +1,58 @@
"""Explicit operator-only CLI. No public replay/version/fault HTTP endpoints."""
import argparse
import json
from .storage import BUCKET,db,s3
from .jobs import audit,enqueue,lock_id,trip
def replay(aid):
with db() as conn:
conn.execute('SELECT pg_advisory_xact_lock(%s)',(lock_id(aid),))
row = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(aid,)).fetchone()
if not row or row['status']!='failed':
raise ValueError('replay requires failed attachment')
# Do not reset successful jobs; only replay if immutable input still exists.
head = s3().head_object(Bucket=BUCKET,Key=row['staging_key'])
if head['ContentLength']!=row['size_bytes'] or head['Metadata'].get('sha256')!=row['sha256']:
raise ValueError('input unavailable')
job = conn.execute('SELECT * FROM jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE',(aid,row['pipeline_version'])).fetchone()
conn.execute("UPDATE jobs SET status='queued',attempts=0,error_code=NULL,lease_until=NULL,next_attempt_at=clock_timestamp() WHERE id=%s",(job['id'],))
conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(aid,))
conn.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(job['id'],))
audit(conn,job['id'],'operator_replay')
return str(job['id'])
def upgrade(aid):
with db() as conn:
conn.execute('SELECT pg_advisory_xact_lock(%s)',(lock_id(aid),))
row = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(aid,)).fetchone()
if not row or row['status']!='ready':
raise ValueError('upgrade requires ready attachment')
client = s3()
client.copy_object(Bucket=BUCKET,Key=row['staging_key'],CopySource={'Bucket':BUCKET,'Key':row['object_key']})
version = row['pipeline_version']+1
conn.execute("UPDATE jobs SET status='superseded' WHERE attachment_id=%s",(aid,))
conn.execute("UPDATE attachments SET pipeline_version=%s,object_key=%s,status='queued',variants='[]',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(version,f'results/{aid}/v{version}/original',aid))
jid = enqueue(conn,aid,version)
audit(conn,jid,'pipeline_upgrade')
return str(jid)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action',choices=['failed','replay','upgrade'])
parser.add_argument('attachment_id',nargs='?')
args = parser.parse_args()
if args.action=='failed':
with db() as conn:
rows = conn.execute("SELECT id,attachment_id,pipeline_version,attempts,error_code FROM jobs WHERE status='failed' ORDER BY created_at LIMIT 100").fetchall()
print(json.dumps(rows,default=str))
else:
if not args.attachment_id:
parser.error('attachment_id required')
print((replay if args.action=='replay' else upgrade)(args.attachment_id))
if __name__=='__main__':
main()
+64
View File
@@ -0,0 +1,64 @@
"""Outbox relay and lease recovery. A lost publish response causes a safe duplicate."""
import json
import logging
import os
import time
from .storage import db
from .jobs import broker, STREAM, MAX_ATTEMPTS, lock_id, payload, audit, trip, finish_failed
def recover():
with db() as conn:
rows = conn.execute("SELECT * FROM jobs WHERE status='processing' AND lease_until<clock_timestamp() ORDER BY lease_until LIMIT 100").fetchall()
for row in rows:
with db() as conn:
if not conn.execute('SELECT pg_try_advisory_xact_lock(%s) AS ok',(lock_id(row['attachment_id']),)).fetchone()['ok']:
continue
job = conn.execute("SELECT * FROM jobs WHERE id=%s AND status='processing' AND lease_until<clock_timestamp() FOR UPDATE",(row['id'],)).fetchone()
if not job:
continue
if job['attempts'] >= MAX_ATTEMPTS:
finish_failed(conn,job,'retry_exhausted')
else:
conn.execute("UPDATE jobs SET status='queued',lease_until=NULL,next_attempt_at=clock_timestamp() WHERE id=%s",(job['id'],))
conn.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s",(job['attachment_id'],job['pipeline_version']))
conn.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(job['id'],))
audit(conn,job['id'],'lease_recovered')
def publish_once():
with db() as conn:
row = conn.execute("""SELECT j.* FROM jobs j JOIN outbox o ON o.job_id=j.id
WHERE j.status='queued' AND j.next_attempt_at<=clock_timestamp()
AND (o.published_at IS NULL OR o.published_at<clock_timestamp()-interval '15 seconds')
ORDER BY j.next_attempt_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED""").fetchone()
if not row:
return False
crash = trip(conn,row['id'],'before_publish')
if crash:
os._exit(91) # accepted DB intent exists, no publish
with db() as conn:
# Separate relay processes may race: notifications may duplicate, effects cannot.
broker().xadd(STREAM,{'job':json.dumps(payload(row),separators=(',',':'))})
if trip(conn,row['id'],'after_publish'):
conn.commit()
os._exit(92) # Redis has the job, outbox does not yet record confirmation
conn.execute('UPDATE outbox SET published_at=clock_timestamp(),publish_count=publish_count+1 WHERE job_id=%s',(row['id'],))
audit(conn,row['id'],'published',str(row['attempts']+1))
return True
def main():
while True:
try:
recover()
for _ in range(100):
if not publish_once():
break
except Exception as exc:
logging.warning('Relay unavailable: %s',type(exc).__name__)
time.sleep(0.5)
if __name__ == '__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
"""Shared dependencies. No raw credentials are printed or exposed through HTTP."""
import os
from pathlib import Path
import boto3
from botocore.config import Config
import psycopg
from psycopg.rows import dict_row
BUCKET = os.getenv('S3_BUCKET', 'messenger-attachments')
PREFIX = 'results/'
STORAGE_LOCK = 440004
def setting(name, default=''):
path = os.getenv(name + '_FILE')
return Path(path).read_text().strip() if path else os.getenv(name, default)
def db():
return psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row,
connect_timeout=3, options='-c statement_timeout=15000 -c lock_timeout=10000')
def s3():
return boto3.client('s3', endpoint_url=os.getenv('S3_ENDPOINT', 'http://s3:9000'),
region_name=os.getenv('S3_REGION', 'us-east-1'),
aws_access_key_id=setting('S3_ACCESS_KEY_ID'),
aws_secret_access_key=setting('S3_SECRET_ACCESS_KEY'),
config=Config(connect_timeout=3, read_timeout=10, max_pool_connections=16,
retries={'total_max_attempts': 1}, s3={'addressing_style': 'path'}))
+56
View File
@@ -0,0 +1,56 @@
"""Sandboxed subprocess: bound decoded pixels, address space and CPU time."""
import json
import os
from pathlib import Path
import resource
import sys
import warnings
from PIL import Image, ImageOps, UnidentifiedImageError
def fit_size(size,bound):
w,h = size
largest = max(w,h)
return (w,h) if largest <= bound else (max(1,w*bound//largest),max(1,h*bound//largest))
def transform(source,destination):
Image.MAX_IMAGE_PIXELS = min(int(os.getenv('MAX_IMAGE_PIXELS','40000000')),40000000)
with warnings.catch_warnings():
warnings.simplefilter('error',Image.DecompressionBombWarning)
with Image.open(source) as original:
if original.format not in ('PNG','JPEG') or original.width*original.height>Image.MAX_IMAGE_PIXELS or getattr(original,'n_frames',1)!=1:
raise ValueError('invalid image')
oriented = ImageOps.exif_transpose(original)
# Composite transparency before resize; strip all metadata by fresh RGB image.
rgba = oriented.convert('RGBA')
rgb = Image.new('RGB',rgba.size,'white')
rgb.paste(rgba,mask=rgba.getchannel('A'))
rgba.close()
oriented.close()
sizes = {}
for name, bound, fmt, quality in [('thumbnail',256,'JPEG',85),('crop',128,'JPEG',85),('optimized',1280,'WEBP',80)]:
image = ImageOps.fit(rgb,(128,128),method=Image.Resampling.LANCZOS,centering=(0.5,0.5)) if name=='crop' else rgb.resize(fit_size(rgb.size,bound),Image.Resampling.LANCZOS)
image.info.clear()
image.save(Path(destination)/name,format=fmt,quality=quality,**({'method':6} if fmt=='WEBP' else {'optimize':True,'subsampling':0}))
sizes[name] = image.size
image.close()
rgb.close()
return sizes
def main():
resource.setrlimit(resource.RLIMIT_AS,(768*1024*1024,768*1024*1024))
timeout = int(os.getenv('JOB_TIMEOUT_SECONDS','60'))
resource.setrlimit(resource.RLIMIT_CPU,(timeout,timeout+1))
try:
result = {'sizes':transform(sys.argv[1],sys.argv[2])}
except MemoryError:
result = {'error':'image_resource_limit'}
except (ValueError,OSError,UnidentifiedImageError,Image.DecompressionBombError,Image.DecompressionBombWarning):
result = {'error':'invalid_image'}
print(json.dumps(result))
if __name__ == '__main__':
main()
+223
View File
@@ -0,0 +1,223 @@
"""One notification per consumer; DB lease and session lock fence all side effects."""
import hashlib
import json
import logging
import multiprocessing
import os
from pathlib import Path
import random
import signal
import subprocess
import sys
import tempfile
import time
import uuid
from botocore.exceptions import ClientError
import redis
from .storage import BUCKET, db, s3
from .jobs import (STREAM,GROUP,LEASE,TIMEOUT,MAX_ATTEMPTS,broker,lock_id,
parse_payload,audit,trip,finish_failed,set_variants)
class Permanent(Exception):
pass
def verify_ready(client,row):
for effect in [row]+row['variants']:
head = client.head_object(Bucket=BUCKET,Key=effect['object_key'])
if head['ContentLength'] != effect['size_bytes'] or head.get('Metadata',{}).get('sha256') != effect['sha256']:
raise RuntimeError('effect unavailable')
def cleanup(client,row):
if row['staging_key']:
client.delete_object(Bucket=BUCKET,Key=row['staging_key'])
def crash(conn,jid,point):
with conn.transaction():
fire = trip(conn,jid,point)
if fire:
os._exit(93)
def process(value):
with db() as conn:
conn.autocommit = True
# Held across claim, decode, PUT and COMMIT. A dead process releases it.
if not conn.execute('SELECT pg_try_advisory_lock(%s) AS ok',(lock_id(value['attachment_id']),)).fetchone()['ok']:
return True # active work is durable in DB; relay recovers its lease if needed
with conn.transaction():
job = conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(value['job_id'],)).fetchone()
if not job:
return True
if str(job['attachment_id']) != value['attachment_id'] or job['pipeline_version'] != value['pipeline_version']:
return True
row = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(job['attachment_id'],)).fetchone()
if row['pipeline_version'] != job['pipeline_version'] or job['status']=='superseded':
audit(conn,job['id'],'stale_ignored')
return True
if job['status']=='ready':
verify_ready(s3(),row)
cleanup(s3(),row)
audit(conn,job['id'],'duplicate_ignored')
return True
if job['status']=='failed':
return True
# Retry notifications are only valid for the next managed attempt.
if job['status']!='queued' or value['attempt']!=job['attempts']+1:
return True
due = conn.execute('SELECT next_attempt_at<=clock_timestamp() AS ok FROM jobs WHERE id=%s',(job['id'],)).fetchone()['ok']
if not due:
return True
if job['attempts']>=MAX_ATTEMPTS:
finish_failed(conn,job,'retry_exhausted')
return True
job = conn.execute("UPDATE jobs SET status='processing',attempts=attempts+1,lease_until=clock_timestamp()+(%s*interval '1 second') WHERE id=%s RETURNING *",(LEASE,job['id'])).fetchone()
conn.execute("UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(row['id'],))
audit(conn,job['id'],'processing',str(job['attempts']))
client = s3()
try:
crash(conn,job['id'],'before_effect')
with conn.transaction():
transient = trip(conn,job['id'],'transient')
permanent = trip(conn,job['id'],'permanent')
if transient:
raise TimeoutError()
if permanent:
raise Permanent('invalid_image')
def timeout_handler(signum,frame):
raise TimeoutError()
signal.signal(signal.SIGALRM,timeout_handler)
signal.alarm(TIMEOUT)
with conn.transaction():
hang = trip(conn,job['id'],'hang')
if hang:
time.sleep(TIMEOUT+2) # test exercises the real wall-clock deadline
with tempfile.TemporaryDirectory() as folder:
source = Path(folder)/'original'
response = client.get_object(Bucket=BUCKET,Key=row['staging_key'])
digest = hashlib.sha256()
size = 0
try:
with source.open('wb') as file:
for chunk in response['Body'].iter_chunks(65536):
size += len(chunk)
if size>10485760:
raise Permanent('invalid_image')
digest.update(chunk)
file.write(chunk)
finally:
response['Body'].close()
if size!=row['size_bytes'] or digest.hexdigest()!=row['sha256']:
raise Permanent('checksum_mismatch')
child = subprocess.Popen([sys.executable,'-m','src.transform',str(source),folder],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True)
try:
output,_ = child.communicate(timeout=TIMEOUT)
finally:
if child.poll() is None:
child.kill()
child.wait()
if child.returncode:
raise Permanent('image_resource_limit')
transformed = json.loads(output)
if 'error' in transformed:
raise Permanent(transformed['error'])
variants = []
for name in ('original','thumbnail','crop','optimized'):
file = Path(folder)/name
data = file.read_bytes()
sha = hashlib.sha256(data).hexdigest()
key = f"results/{row['id']}/v{job['pipeline_version']}/{name}"
mime = row['content_type'] if name=='original' else 'image/webp' if name=='optimized' else 'image/jpeg'
client.put_object(Bucket=BUCKET,Key=key,Body=data,ContentType=mime,Metadata={'sha256':sha})
if name=='original':
crash(conn,job['id'],'after_object')
else:
width,height = transformed['sizes'][name]
variants.append({'name':name,'object_key':key,'content_type':mime,'size_bytes':len(data),'sha256':sha,'width':width,'height':height})
crash(conn,job['id'],'before_result_commit')
with conn.transaction():
set_variants(conn,row['id'],job['pipeline_version'],variants)
conn.execute("UPDATE jobs SET status='ready',lease_until=NULL,error_code=NULL WHERE id=%s",(job['id'],))
audit(conn,job['id'],'ready')
crash(conn,job['id'],'after_result_commit')
signal.alarm(0)
cleanup(client,row)
return True
except Exception as exc:
signal.alarm(0)
with conn.transaction():
latest = conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(job['id'],)).fetchone()
# A cleanup/network failure after ready never rolls back a committed result.
if latest['status']=='ready':
return False
permanent = isinstance(exc,Permanent)
if isinstance(exc,ClientError) and exc.response.get('Error',{}).get('Code')=='NoSuchKey':
permanent,exc = True,Permanent('staging_missing')
if permanent or job['attempts']>=MAX_ATTEMPTS:
finish_failed(conn,job,str(exc) if permanent else 'retry_exhausted')
else:
base = float(os.getenv('RETRY_BASE_SECONDS','1'))
delay = min(30,base*2**(job['attempts']-1))*random.uniform(0.5,1.5)
conn.execute("UPDATE jobs SET status='queued',lease_until=NULL,error_code='temporary_failure',next_attempt_at=clock_timestamp()+(%s*interval '1 second') WHERE id=%s",(delay,job['id']))
conn.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s",(row['id'],))
conn.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(job['id'],))
audit(conn,job['id'],'retry_scheduled',f'{delay:.3f}')
return True
def consumer():
name = uuid.uuid4().hex
cursor = '0-0'
while True:
try:
r = broker()
try:
r.xgroup_create(STREAM,GROUP,id='0-0',mkstream=True)
except redis.ResponseError as exc:
if 'BUSYGROUP' not in str(exc):
raise
cursor,entries,_ = r.xautoclaim(STREAM,GROUP,name,LEASE*1000,cursor,count=1)
if not entries:
result = r.xreadgroup(GROUP,name,{STREAM:'>'},count=1,block=1000)
entries = result[0][1] if result else []
for mid,fields in entries:
try:
value = parse_payload(fields.get('job',''))
except (ValueError,TypeError,KeyError):
r.xadd('attachments:invalid',{'message_id':mid,'error_code':'invalid_envelope'})
r.xack(STREAM,GROUP,mid)
r.xdel(STREAM,mid)
continue
if process(value):
r.xack(STREAM,GROUP,mid)
r.xdel(STREAM,mid) # only one consumer group; no pending work is trimmed
except Exception as exc:
logging.warning('Consumer unavailable: %s',type(exc).__name__)
time.sleep(1)
def main():
count = int(os.getenv('WORKER_CONCURRENCY','2'))
if not 1<=count<=8:
raise ValueError('WORKER_CONCURRENCY must be 1..8')
processes = []
while True:
alive = []
for p in processes:
if p.is_alive():
alive.append(p)
else:
p.join()
processes = alive
while len(processes)<count:
p = multiprocessing.Process(target=consumer)
p.start()
processes.append(p)
time.sleep(0.5)
if __name__=='__main__':
main()