Implement observable messenger, SLO alerts and measured incident scenarios
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
import logging
|
||||
import os
|
||||
import uvicorn
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(message)s')
|
||||
uvicorn.run('src.app:app', host=os.environ.get('APP_HOST', '0.0.0.0'),
|
||||
port=int(os.environ.get('APP_PORT', '8080')), workers=1,
|
||||
access_log=False, server_header=False, timeout_keep_alive=2,
|
||||
timeout_graceful_shutdown=32, backlog=64, h11_max_incomplete_event_size=16384)
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
import asyncio
|
||||
import base64
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import tempfile
|
||||
import unicodedata
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError, InvalidHashError
|
||||
from fastapi import FastAPI, Request, Response
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.responses import StreamingResponse
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from .common import ApiError, invalid, json_body, object_fields, pagination, string, uuid_value
|
||||
from .http import Boundaries, error_response
|
||||
from .store import Store, clean
|
||||
from .storage import Storage, MAX_BYTES, validate_image
|
||||
from .offload import complete_thread
|
||||
from . import telemetry as tel
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
database_url: str
|
||||
redis_url: str
|
||||
cursor_secret: str
|
||||
session_ttl_seconds: int = 3600
|
||||
db_pool_size: int = 5
|
||||
max_body_bytes: int = 32768
|
||||
max_inflight: int = 32
|
||||
request_timeout: int = 30
|
||||
write_rps: int = 100
|
||||
write_burst: int = 100
|
||||
|
||||
@classmethod
|
||||
def environment(cls):
|
||||
result=cls(database_url=os.environ['DATABASE_URL'],redis_url=os.environ['REDIS_URL'],cursor_secret=os.environ['CURSOR_SECRET'],
|
||||
**{name:int(os.environ.get(name.upper(),field.default)) for name,field in cls.__dataclass_fields__.items() if field.type is int})
|
||||
if len(result.cursor_secret)<32 or any(getattr(result,name)<=0 for name,field in cls.__dataclass_fields__.items() if field.type is int):
|
||||
raise ValueError('Invalid configuration')
|
||||
return result
|
||||
|
||||
|
||||
def create_app(settings=None):
|
||||
tel.setup('messenger-api')
|
||||
cfg=settings or Settings.environment()
|
||||
store=Store(cfg)
|
||||
storage=Storage()
|
||||
uploads=asyncio.Semaphore(2)
|
||||
decoders=asyncio.Semaphore(1)
|
||||
downloads=asyncio.Semaphore(4)
|
||||
hasher=PasswordHasher(time_cost=2,memory_cost=32768,parallelism=1)
|
||||
dummy_hash=hasher.hash(secrets.token_urlsafe(32))
|
||||
kdf_slots=asyncio.Semaphore(4)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(api):
|
||||
await store.open()
|
||||
async def gauges():
|
||||
while True:
|
||||
stats=store.pool.get_stats()
|
||||
attrs={'process_instance':tel.instance}
|
||||
tel.pool_used.set(stats.get('pool_size',0)-stats.get('pool_available',0),attrs)
|
||||
tel.pool_waiting.set(stats.get('requests_waiting',0),attrs)
|
||||
tel.process_metrics()
|
||||
await asyncio.sleep(5)
|
||||
task=asyncio.create_task(gauges())
|
||||
try: yield
|
||||
finally:
|
||||
task.cancel()
|
||||
try: await task
|
||||
except asyncio.CancelledError: pass
|
||||
await store.close()
|
||||
storage.client.close()
|
||||
await asyncio.to_thread(tel.shutdown)
|
||||
|
||||
# This pinned FastAPI release has native telemetry. Disable it because the
|
||||
# explicit boundary below owns sampling, health exclusion and redaction.
|
||||
api=FastAPI(lifespan=lifespan,openapi_url=None,docs_url=None,redoc_url=None,
|
||||
telemetry={'tracing':False,'metrics':False,'logs':False,
|
||||
'operation_spans':False,'auto_configure':False})
|
||||
api.state.store=store
|
||||
|
||||
@api.exception_handler(ApiError)
|
||||
async def api_error(request,exc): return error_response(exc,request.state.request_id)
|
||||
|
||||
@api.exception_handler(HTTPException)
|
||||
async def http_error(request,exc):
|
||||
return error_response(ApiError(404,'not_found','Route not found'),request.state.request_id)
|
||||
|
||||
async def database_error(request,exc):
|
||||
return error_response(ApiError(503,'unavailable','Database unavailable',{'Retry-After':'1'}),request.state.request_id)
|
||||
for exception in (psycopg.Error,PoolTimeout,TooManyRequests): api.add_exception_handler(exception,database_error)
|
||||
|
||||
async def storage_error(request,exc):
|
||||
return error_response(ApiError(503,'unavailable','Object storage unavailable',{'Retry-After':'1'}),request.state.request_id)
|
||||
for exception in (BotoCoreError,ClientError): api.add_exception_handler(exception,storage_error)
|
||||
|
||||
@api.exception_handler(psycopg.DataError)
|
||||
async def data_error(request,exc):
|
||||
return error_response(ApiError(400,'invalid_request','Unsupported field value'),request.state.request_id)
|
||||
|
||||
def unauthorized(basic=False):
|
||||
scheme='Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"'
|
||||
return ApiError(401,'unauthorized','Invalid credentials',{'WWW-Authenticate':scheme})
|
||||
|
||||
def bearer(request):
|
||||
value=request.headers.get('authorization','')
|
||||
parts=value.split()
|
||||
if len(parts)!=2 or parts[0].lower()!='bearer' or not re.fullmatch(r'[A-Za-z0-9_-]{43}',parts[1]):
|
||||
raise unauthorized()
|
||||
return parts[1]
|
||||
|
||||
async def actor(request):
|
||||
with tel.span('db.session.authenticate',attributes={'db.system.name':'postgresql'}):
|
||||
return await store.authenticate(bearer(request))
|
||||
|
||||
@api.get('/health/live')
|
||||
async def live(): return {'status':'ok'}
|
||||
|
||||
@api.get('/health/ready')
|
||||
async def ready():
|
||||
await store.ready()
|
||||
await asyncio.to_thread(storage.ready)
|
||||
return {'status':'ok'}
|
||||
|
||||
@api.post('/api/v1/users',status_code=201)
|
||||
async def register(request:Request):
|
||||
body=object_fields(await json_body(request),('username','display_name','password'))
|
||||
username=string(body['username'],32)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}',username): invalid('Invalid username')
|
||||
name=string(body['display_name'],100)
|
||||
password=string(body['password'],128)
|
||||
if len(password)<12: invalid('Password must contain 12..128 code points')
|
||||
async with kdf_slots: hashed=await asyncio.to_thread(hasher.hash,password)
|
||||
return await store.register(username,name,hashed)
|
||||
|
||||
@api.post('/api/v1/auth/sessions',status_code=201)
|
||||
async def login(request:Request):
|
||||
try:
|
||||
scheme,encoded=request.headers.get('authorization','').split(' ',1)
|
||||
if scheme.lower()!='basic': raise ValueError()
|
||||
username,password=base64.b64decode(encoded,validate=True).decode('utf-8').split(':',1)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}',username) or not 12<=len(password)<=128: raise ValueError()
|
||||
except (ValueError,UnicodeError): raise unauthorized(True) from None
|
||||
if await request.body(): invalid('Session login does not accept a body')
|
||||
row=await store.credentials(username)
|
||||
try:
|
||||
async with kdf_slots: await asyncio.to_thread(hasher.verify,row['password_hash'] if row else dummy_hash,password)
|
||||
except (VerificationError,InvalidHashError): raise unauthorized(True) from None
|
||||
if not row: raise unauthorized(True)
|
||||
token=secrets.token_urlsafe(32)
|
||||
expires=await store.create_session(row['id'],token)
|
||||
return {'token':token,'token_type':'Bearer','expires_at':expires,
|
||||
'user':clean({k:v for k,v in row.items() if k!='password_hash'})}
|
||||
|
||||
@api.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||
async def logout(request:Request):
|
||||
await actor(request)
|
||||
await store.logout(bearer(request))
|
||||
return Response(status_code=204)
|
||||
|
||||
@api.get('/api/v1/users/me')
|
||||
async def me(request:Request): return await actor(request)
|
||||
|
||||
@api.post('/api/v1/chats',status_code=201)
|
||||
async def create_chat(request:Request):
|
||||
user=await actor(request)
|
||||
body=object_fields(await json_body(request),('title','member_ids'))
|
||||
title=string(body['title'],100)
|
||||
if not isinstance(body['member_ids'],list) or not 1<=len(body['member_ids'])<=100: invalid('Invalid members')
|
||||
members=[uuid_value(v) for v in body['member_ids']]
|
||||
if len(set(members))!=len(members): invalid('Duplicate member')
|
||||
return await store.create_chat(user['id'],title,members)
|
||||
|
||||
@api.get('/api/v1/chats')
|
||||
async def list_chats(request:Request):
|
||||
user=await actor(request)
|
||||
limit,cursor=pagination(request,'chats:'+user['id'],store.secret)
|
||||
return await store.page(user['id'],None,limit,cursor)
|
||||
|
||||
@api.get('/api/v1/chats/{chat_id}')
|
||||
async def get_chat(chat_id:str,request:Request):
|
||||
user=await actor(request)
|
||||
return await store.chat(user['id'],uuid_value(chat_id))
|
||||
|
||||
@api.get('/api/v1/chats/{chat_id}/messages')
|
||||
async def list_messages(chat_id:str,request:Request):
|
||||
user=await actor(request); chat_id=uuid_value(chat_id)
|
||||
await store.chat(user['id'],chat_id)
|
||||
limit,cursor=pagination(request,'messages:'+chat_id,store.secret)
|
||||
return await store.page(user['id'],chat_id,limit,cursor)
|
||||
|
||||
@api.post('/api/v1/chats/{chat_id}/messages',status_code=201)
|
||||
async def create_message(chat_id:str,request:Request):
|
||||
user=await actor(request); chat_id=uuid_value(chat_id)
|
||||
await store.chat(user['id'],chat_id)
|
||||
body=object_fields(await json_body(request),('text',),('attachment_ids',))
|
||||
key=request.headers.get('idempotency-key','')
|
||||
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}',key): invalid('Invalid Idempotency-Key')
|
||||
ids=body.get('attachment_ids',[])
|
||||
if not isinstance(ids,list) or len(ids)>10: invalid('Invalid attachments')
|
||||
ids=[uuid_value(v) for v in ids]
|
||||
if len(ids)!=len(set(ids)): invalid('Duplicate attachment')
|
||||
text=string(body['text'],4000,blank=True)
|
||||
if not text.strip() and not ids: invalid('Message must have content')
|
||||
with tel.span('db.message.commit',attributes={'db.system.name':'postgresql'}):
|
||||
return await store.create_message(user['id'],chat_id,text,key,ids)
|
||||
|
||||
def metadata(row):
|
||||
fields=('id','chat_id','owner_id','filename','content_type','size_bytes','sha256','created_at','updated_at','status','error_code')
|
||||
result={k:row[k] for k in fields}
|
||||
result['variants']=[{k:v for k,v in variant.items() if k!='object_key'} for variant in row['variants']] if row['status']=='ready' else []
|
||||
return result
|
||||
|
||||
@api.post('/api/v1/chats/{chat_id}/attachments',status_code=202)
|
||||
async def upload(chat_id:str,request:Request):
|
||||
user=await actor(request); chat_id=uuid_value(chat_id)
|
||||
await store.chat(user['id'],chat_id)
|
||||
if set(request.query_params)!={'filename'} or len(request.query_params.getlist('filename'))!=1:
|
||||
invalid('Expected one filename')
|
||||
filename=string(request.query_params['filename'],255)
|
||||
if any(c in '/\\' or unicodedata.category(c)=='Cc' for c in filename): invalid('Invalid filename')
|
||||
mime=request.headers.get('content-type','').strip().lower()
|
||||
if mime not in ('image/png','image/jpeg'): raise ApiError(415,'unsupported_media_type','Expected PNG/JPEG')
|
||||
if uploads.locked(): raise ApiError(503,'unavailable','Upload slots busy',{'Retry-After':'1'})
|
||||
async with uploads:
|
||||
with tempfile.TemporaryFile() as file:
|
||||
size=0
|
||||
async for chunk in request.stream():
|
||||
size+=len(chunk)
|
||||
if size>MAX_BYTES: raise ApiError(413,'payload_too_large','Upload exceeds 10 MiB')
|
||||
file.write(chunk)
|
||||
async with decoders:
|
||||
digest=await complete_thread(validate_image,file,mime)
|
||||
with tel.span('attachment.durable_accept'):
|
||||
row=await store.save_attachment(user['id'],chat_id,filename,mime,size,digest,file,storage)
|
||||
return metadata(row)
|
||||
|
||||
@api.get('/api/v1/attachments/{attachment_id}')
|
||||
async def attachment(attachment_id:str,request:Request):
|
||||
user=await actor(request)
|
||||
return metadata(await store.attachment(user['id'],uuid_value(attachment_id)))
|
||||
|
||||
@api.get('/api/v1/attachments/{attachment_id}/content')
|
||||
async def content(attachment_id:str,request:Request):
|
||||
user=await actor(request)
|
||||
row=await store.attachment(user['id'],uuid_value(attachment_id))
|
||||
if row['status']!='ready': raise ApiError(409,'conflict','Attachment is not ready')
|
||||
if set(request.query_params)-{'variant'} or len(request.query_params.getlist('variant'))>1: invalid('Invalid query')
|
||||
variant=request.query_params.get('variant','original')
|
||||
target=row if variant=='original' else next((v for v in row['variants'] if v['name']==variant),None)
|
||||
if target is None: raise ApiError(404,'not_found','Variant not found')
|
||||
if downloads.locked(): raise ApiError(503,'unavailable','Download slots busy')
|
||||
await downloads.acquire()
|
||||
try:
|
||||
obj=await asyncio.to_thread(storage.get,target['object_key'])
|
||||
except BaseException:
|
||||
downloads.release()
|
||||
raise
|
||||
async def chunks():
|
||||
try:
|
||||
while data:=await asyncio.to_thread(obj['Body'].read,65536):
|
||||
yield data
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
downloads.release()
|
||||
return StreamingResponse(chunks(),media_type=target['content_type'],headers={
|
||||
'Content-Length':str(target['size_bytes']),'X-Content-Type-Options':'nosniff',
|
||||
'Content-Disposition':'attachment'})
|
||||
|
||||
api.add_middleware(Boundaries,settings=cfg)
|
||||
return api
|
||||
|
||||
|
||||
app=create_app()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Idempotent private bucket bootstrap; only this one-shot service receives admin credentials."""
|
||||
import time
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from .storage import Storage, HEALTH_KEY, HEALTH_BYTES
|
||||
|
||||
storage=Storage()
|
||||
for attempt in range(60):
|
||||
try:
|
||||
storage.client.list_buckets()
|
||||
break
|
||||
except (BotoCoreError,ClientError):
|
||||
if attempt==59: raise RuntimeError('Object storage did not become available') from None
|
||||
time.sleep(1)
|
||||
try:
|
||||
storage.client.head_bucket(Bucket=storage.bucket)
|
||||
except ClientError as exc:
|
||||
if exc.response['Error']['Code'] not in ('404','NoSuchBucket'): raise
|
||||
storage.client.create_bucket(Bucket=storage.bucket)
|
||||
# No anonymous identity and no public bucket policy. Do not overwrite any policy
|
||||
# silently on repeat; reject a public policy if an operator added one accidentally.
|
||||
try:
|
||||
policy=storage.client.get_bucket_policy(Bucket=storage.bucket)
|
||||
except ClientError as exc:
|
||||
if exc.response['Error']['Code'] not in ('NoSuchBucketPolicy','404'): raise
|
||||
else:
|
||||
raise RuntimeError('Unexpected bucket policy; inspect it before starting API')
|
||||
deadline=time.monotonic()+90
|
||||
while True:
|
||||
try:
|
||||
try:
|
||||
storage.client.head_object(Bucket=storage.bucket, Key=HEALTH_KEY)
|
||||
except ClientError as exc:
|
||||
if exc.response['Error']['Code'] not in ('404','NoSuchKey'): raise
|
||||
# Fixed, reserved key/content: retry after uncertain PUT is safe.
|
||||
storage.client.put_object(Bucket=storage.bucket, Key=HEALTH_KEY, Body=HEALTH_BYTES)
|
||||
storage.ready()
|
||||
break
|
||||
except (BotoCoreError,ClientError):
|
||||
if time.monotonic()>=deadline:
|
||||
raise RuntimeError('Storage volumes did not become ready within bootstrap deadline') from None
|
||||
time.sleep(1)
|
||||
print('Private bucket ready; bootstrap is repeatable')
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Persistent Valkey Streams transport; database outbox remains the durable intent."""
|
||||
import json
|
||||
import os
|
||||
|
||||
import redis
|
||||
|
||||
STREAM = 'attachment-jobs'
|
||||
GROUP = 'image-workers'
|
||||
|
||||
|
||||
def connect():
|
||||
return redis.Redis.from_url(os.environ['BROKER_URL'], decode_responses=True,
|
||||
socket_connect_timeout=2, socket_timeout=3)
|
||||
|
||||
|
||||
def ensure_group(client):
|
||||
try:
|
||||
client.xgroup_create(STREAM, GROUP, id='0', mkstream=True)
|
||||
except redis.ResponseError as exc:
|
||||
if not str(exc).startswith('BUSYGROUP'):
|
||||
raise
|
||||
|
||||
|
||||
def publish(client, payload):
|
||||
# appendfsync always in Compose: successful XADD is the broker acceptance
|
||||
# boundary. This is NOT an atomic transaction with PostgreSQL's outbox update.
|
||||
return client.xadd(STREAM, {'job': json.dumps(payload, separators=(',', ':'))})
|
||||
|
||||
|
||||
def receive(client, consumer):
|
||||
ensure_group(client)
|
||||
claimed = client.xautoclaim(STREAM, GROUP, consumer, min_idle_time=65_000,
|
||||
start_id='0-0', count=1)
|
||||
if claimed[1]:
|
||||
return claimed[1][0]
|
||||
items = client.xreadgroup(GROUP, consumer, {STREAM: '>'}, count=1, block=1000)
|
||||
return items[0][1][0] if items else None
|
||||
|
||||
|
||||
def acknowledge(client, message_id):
|
||||
# Called only after durable terminal/no-op outcome (or durable scheduled retry).
|
||||
# One consumer group owns this stream. Ack+delete prevents unbounded history.
|
||||
with client.pipeline(transaction=True) as pipe:
|
||||
pipe.xack(STREAM, GROUP, message_id)
|
||||
pipe.xdel(STREAM, message_id)
|
||||
pipe.execute()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Version-aware staging retention. Never deletes active jobs or referenced final effects."""
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import signal
|
||||
import threading
|
||||
|
||||
from .jobs import database
|
||||
from .storage import HEALTH_KEY, Storage
|
||||
|
||||
stop=threading.Event()
|
||||
|
||||
|
||||
def run():
|
||||
storage=Storage(); deleted=0; scanned=0
|
||||
try:
|
||||
with database() as db:
|
||||
for prefix in ('staging/','originals/','variants/'):
|
||||
for page in storage.client.get_paginator('list_objects_v2').paginate(Bucket=storage.bucket,Prefix=prefix):
|
||||
for obj in page.get('Contents',[]):
|
||||
key=obj['Key']; scanned+=1
|
||||
if key==HEALTH_KEY: continue
|
||||
age=datetime.now(timezone.utc).timestamp()-obj['LastModified'].timestamp()
|
||||
if age<600: continue
|
||||
with db.transaction():
|
||||
if not db.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS ok',(key,)).fetchone()['ok']: continue
|
||||
if prefix=='staging/':
|
||||
att=db.execute('SELECT * FROM attachments WHERE staging_key=%s FOR UPDATE',(key,)).fetchone()
|
||||
if att and (att['status'] in ('queued','processing') or (att['status']=='failed' and age<7*86400)):
|
||||
continue
|
||||
# Ready staging is obsolete. Failed staging retained 7 days;
|
||||
# explicit operator replay afterwards requires a restored source.
|
||||
storage.delete(key); deleted+=1
|
||||
if att:
|
||||
db.execute('UPDATE attachments SET staging_key=NULL WHERE id=%s AND staging_key=%s',(att['id'],key))
|
||||
else:
|
||||
# Keep every version for a known attachment; old versions
|
||||
# are bounded by the two supported pipelines and aid audit.
|
||||
part=key.split('/')[1]
|
||||
row=db.execute('SELECT 1 FROM attachments WHERE id::text=%s',(part,)).fetchone()
|
||||
if row: continue
|
||||
storage.delete(key); deleted+=1
|
||||
return {'scanned':scanned,'deleted':deleted}
|
||||
finally: storage.client.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
signal.signal(signal.SIGTERM,lambda *_:stop.set())
|
||||
signal.signal(signal.SIGINT,lambda *_:stop.set())
|
||||
while not stop.is_set():
|
||||
try: print(json.dumps({'event':'cleanup',**run()}),flush=True)
|
||||
except Exception as exc: print(json.dumps({'event':'cleanup_retry','type':type(exc).__name__}),flush=True)
|
||||
stop.wait(60)
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
"""Strict contract validation and resource-bound cursors."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
self.status, self.code, self.message = status, code, message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid(message='Invalid request'):
|
||||
raise ApiError(400, 'invalid_request', message)
|
||||
|
||||
|
||||
def uuid_value(value):
|
||||
if not isinstance(value, str) or not re.fullmatch(
|
||||
r'[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}', value
|
||||
):
|
||||
invalid('Invalid UUID')
|
||||
return str(UUID(value))
|
||||
|
||||
|
||||
def string(value, maximum, *, blank=False):
|
||||
if not isinstance(value, str) or len(value) > maximum or (not blank and not value.strip()):
|
||||
invalid('Invalid string')
|
||||
# JSON can encode unpaired surrogates; they are not Unicode scalar values.
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeError:
|
||||
invalid('Invalid Unicode')
|
||||
return value
|
||||
|
||||
|
||||
def object_fields(value, required, optional=()):
|
||||
if not isinstance(value, dict) or not set(required) <= value.keys() or value.keys() - set(required) - set(optional):
|
||||
invalid('Invalid fields')
|
||||
return value
|
||||
|
||||
|
||||
def timestamp():
|
||||
return datetime.now(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def encode_cursor(resource, key, secret):
|
||||
data = json.dumps([resource, *key], separators=(',', ':')).encode()
|
||||
return base64.urlsafe_b64encode(data + hmac.digest(secret, data, 'sha256')).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(value, resource, secret):
|
||||
try:
|
||||
if len(value) > 1024 or not re.fullmatch(r'[A-Za-z0-9_-]+', value):
|
||||
raise ValueError()
|
||||
raw = base64.b64decode(value + '=' * (-len(value) % 4), altchars=b'-_', validate=True)
|
||||
data, signature = raw[:-32], raw[-32:]
|
||||
if not hmac.compare_digest(hmac.digest(secret, data, 'sha256'), signature):
|
||||
raise ValueError()
|
||||
scope, created, identifier = json.loads(data)
|
||||
if scope != resource or not isinstance(created, str) or not created.endswith('Z'):
|
||||
raise ValueError()
|
||||
datetime.fromisoformat(created.replace('Z', '+00:00'))
|
||||
UUID(identifier)
|
||||
return created, identifier
|
||||
except (ValueError, TypeError, binascii.Error, UnicodeError):
|
||||
invalid('Invalid cursor')
|
||||
|
||||
|
||||
def pagination(request, resource, secret):
|
||||
if any(len(request.query_params.getlist(k)) != 1 for k in request.query_params):
|
||||
invalid('Duplicate query parameter')
|
||||
if set(request.query_params) - {'limit', 'cursor'}:
|
||||
invalid('Unknown query parameter')
|
||||
value = request.query_params.get('limit', '50')
|
||||
if not re.fullmatch(r'[0-9]{1,3}', value) or not 1 <= int(value) <= 100:
|
||||
invalid('Limit must be 1..100')
|
||||
cursor = request.query_params.get('cursor')
|
||||
return int(value), decode_cursor(cursor, resource, secret) if cursor is not None else None
|
||||
|
||||
|
||||
async def json_body(request):
|
||||
if request.headers.get('content-type', '').split(';')[0].strip().lower() != 'application/json':
|
||||
raise ApiError(415, 'unsupported_media_type', 'Expected application/json')
|
||||
def unique_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError('duplicate key')
|
||||
result[key] = value
|
||||
return result
|
||||
def no_constant(value):
|
||||
raise ValueError('non-finite number')
|
||||
try:
|
||||
return json.loads((await request.body()).decode('utf-8'), object_pairs_hook=unique_pairs, parse_constant=no_constant)
|
||||
except (ValueError, UnicodeError, RecursionError):
|
||||
invalid('Invalid JSON')
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Recover committed intent automatically and republish after uncertain acceptance."""
|
||||
import json
|
||||
import signal
|
||||
import threading
|
||||
|
||||
from .broker import connect, ensure_group, publish
|
||||
from .jobs import database, payload, recover_expired
|
||||
from . import telemetry as tel
|
||||
|
||||
stop = threading.Event()
|
||||
|
||||
|
||||
def tick():
|
||||
with database() as db, connect() as client:
|
||||
recover_expired(db)
|
||||
ensure_group(client)
|
||||
with db.transaction():
|
||||
# Bounded batch and SKIP LOCKED allow another dispatcher without
|
||||
# duplicate simultaneous publication. Crash after XADD may redeliver.
|
||||
rows = db.execute("""SELECT j.* FROM outbox o JOIN jobs j ON j.id=o.job_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 '30 seconds')
|
||||
ORDER BY j.created_at LIMIT 20 FOR UPDATE OF o SKIP LOCKED""").fetchall()
|
||||
for job in rows:
|
||||
with tel.span('attachment.publish',kind=tel.trace.SpanKind.PRODUCER,
|
||||
carrier={key:job[key] for key in ('traceparent','tracestate') if job.get(key)},
|
||||
attributes={'messaging.system':'redis','messaging.destination.name':'attachment-jobs'}):
|
||||
item=payload(job); item.update(tel.carrier())
|
||||
publish(client,item)
|
||||
tel.event('job_published',job_id=str(job['id']),attempt=job['attempts']+1)
|
||||
db.execute('UPDATE outbox SET published_at=clock_timestamp(),publications=publications+1 WHERE job_id=%s',
|
||||
(job['id'],))
|
||||
queue=db.execute("SELECT count(*) AS n,coalesce(extract(epoch FROM clock_timestamp()-min(created_at)),0) AS age FROM jobs WHERE status IN ('queued','processing')").fetchone()
|
||||
attrs={'queue':'attachment-jobs'}
|
||||
tel.queue_depth.set(queue['n'],attrs); tel.queue_age.set(float(queue['age']),attrs)
|
||||
for window in (60,300):
|
||||
slo=db.execute("""SELECT count(*) AS total,count(*) FILTER (WHERE status!='ready'
|
||||
OR updated_at>accepted_at+interval '30 seconds') AS bad FROM attachments
|
||||
WHERE accepted_at<=clock_timestamp()-interval '30 seconds'
|
||||
AND accepted_at>clock_timestamp()-((%s+30)*interval '1 second')""",(window,)).fetchone()
|
||||
tel.slo_total.set(slo['total'],{'window':str(window)})
|
||||
tel.slo_bad.set(slo['bad'],{'window':str(window)})
|
||||
tel.process_metrics()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def main():
|
||||
tel.setup('messenger-dispatcher')
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
while not stop.is_set():
|
||||
try:
|
||||
count = tick()
|
||||
if count:
|
||||
tel.event('jobs_published',count=count)
|
||||
except Exception as exc:
|
||||
tel.event('dispatch_retry',error_type=type(exc).__name__)
|
||||
stop.wait(.5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.requests import ClientDisconnect
|
||||
from .common import ApiError
|
||||
from . import telemetry as tel
|
||||
logger=logging.getLogger("messenger")
|
||||
|
||||
def error_response(exc, request_id):
|
||||
return JSONResponse({'error': {'code': exc.code, 'message': exc.message, 'request_id': request_id}},
|
||||
status_code=exc.status, headers={'X-Request-Id': request_id, **exc.headers})
|
||||
|
||||
|
||||
class Boundaries:
|
||||
"""Admission before body buffering; no unbounded application waiting queue."""
|
||||
def __init__(self, app, settings):
|
||||
self.app, self.cfg = app, settings
|
||||
self.instance_id = uuid4().hex
|
||||
self.active, self.tokens, self.updated = 0, float(settings.write_burst), time.monotonic()
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope['type']!='http' or scope['path'].startswith('/health/'):
|
||||
return await self._call(scope,receive,send)
|
||||
status=500; started=time.monotonic()
|
||||
headers={k.decode():v.decode() for k,v in scope.get('headers',[]) if k in (b'traceparent',b'tracestate')}
|
||||
async def observed_send(message):
|
||||
nonlocal status
|
||||
if message['type']=='http.response.start': status=message['status']
|
||||
await send(message)
|
||||
with tel.span('HTTP '+scope['method'],kind=tel.trace.SpanKind.SERVER,carrier=headers) as current:
|
||||
try:
|
||||
await self._call(scope,receive,observed_send)
|
||||
finally:
|
||||
route=getattr(scope.get('route'),'path','unmatched')
|
||||
method=scope['method'] if scope['method'] in {'GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS','TRACE','CONNECT'} else 'OTHER'
|
||||
attrs={'method':method,'route':route,'status_class':str(status//100)+'xx'}
|
||||
current.update_name(scope['method']+' '+route)
|
||||
current.set_attributes({'http.request.method':scope['method'],'http.route':route,'http.response.status_code':status})
|
||||
if status>=500: current.set_status(tel.trace.Status(tel.trace.StatusCode.ERROR))
|
||||
duration=time.monotonic()-started
|
||||
tel.http_count.add(1,attrs); tel.http_duration.record(duration,attrs)
|
||||
tel.event('http_request',request_id=scope.get('state',{}).get('request_id'),status=status,route=route,duration_seconds=round(duration,6))
|
||||
|
||||
async def _call(self, scope, receive, send):
|
||||
if scope['type'] != 'http':
|
||||
return await self.app(scope, receive, send)
|
||||
request_id, started, status = uuid4().hex, time.monotonic(), 500
|
||||
scope.setdefault('state', {})['request_id'] = request_id
|
||||
started_response = False
|
||||
async def tracked_send(message):
|
||||
nonlocal status, started_response
|
||||
if message['type'] == 'http.response.start':
|
||||
status, started_response = message['status'], True
|
||||
message['headers'] = [(k, v) for k, v in message.get('headers', []) if k.lower() != b'x-request-id'] + [(b'x-request-id', request_id.encode()), (b'x-instance-id', self.instance_id.encode())]
|
||||
await send(message)
|
||||
admitted = False
|
||||
try:
|
||||
if self.active >= self.cfg.max_inflight:
|
||||
raise ApiError(503, 'unavailable', 'Too many in-flight requests', {'Retry-After': '1'})
|
||||
now = time.monotonic()
|
||||
self.tokens = min(self.cfg.write_burst, self.tokens + (now - self.updated) * self.cfg.write_rps)
|
||||
self.updated = now
|
||||
if scope['method'] in ('POST', 'PUT', 'PATCH'):
|
||||
if self.tokens < 1:
|
||||
raise ApiError(429, 'rate_limited', 'Write rate exceeded', {'Retry-After': '1'})
|
||||
self.tokens -= 1
|
||||
self.active += 1
|
||||
admitted = True
|
||||
# Binary uploads are streamed by the authorized route into a bounded
|
||||
# temporary file; do not copy a 10 MiB body into every API request.
|
||||
if scope['method']=='POST' and scope['path'].endswith('/attachments'):
|
||||
async with asyncio.timeout(self.cfg.request_timeout):
|
||||
await self.app(scope,receive,tracked_send)
|
||||
return
|
||||
chunks, total = bytearray(), 0
|
||||
async with asyncio.timeout(self.cfg.request_timeout):
|
||||
while True:
|
||||
message = await receive()
|
||||
if message['type'] == 'http.disconnect':
|
||||
return
|
||||
chunk = message.get('body', b'')
|
||||
total += len(chunk)
|
||||
if total > self.cfg.max_body_bytes:
|
||||
raise ApiError(413, 'payload_too_large', 'Request body exceeds byte limit')
|
||||
chunks.extend(chunk)
|
||||
if not message.get('more_body', False):
|
||||
break
|
||||
body = bytes(chunks)
|
||||
delivered = False
|
||||
async def replay():
|
||||
nonlocal delivered
|
||||
if delivered:
|
||||
return await receive()
|
||||
delivered = True
|
||||
return {'type': 'http.request', 'body': body, 'more_body': False}
|
||||
await self.app(scope, replay, tracked_send)
|
||||
except ClientDisconnect:
|
||||
status=499
|
||||
except TimeoutError:
|
||||
if not started_response:
|
||||
await error_response(ApiError(503, 'unavailable', 'Request timed out'), request_id)(scope, receive, tracked_send)
|
||||
except ApiError as exc:
|
||||
if not started_response:
|
||||
await error_response(exc, request_id)(scope, receive, tracked_send)
|
||||
except Exception as exc:
|
||||
logger.error(json.dumps({'event': 'unexpected_error', 'request_id': request_id, 'type': type(exc).__name__}))
|
||||
if not started_response:
|
||||
await error_response(ApiError(500, 'internal_error', 'Internal error'), request_id)(scope, receive, tracked_send)
|
||||
finally:
|
||||
if admitted:
|
||||
self.active -= 1
|
||||
# No query, body, headers, usernames, or message content in logs.
|
||||
route = scope.get('route')
|
||||
logger.info(json.dumps({'event': 'http', 'request_id': request_id, 'method': scope['method'],
|
||||
'route': getattr(route, 'path', 'unmatched'), 'status': status,
|
||||
'duration_ms': round((time.monotonic() - started) * 1000, 3)}))
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
"""Job state, transactional outbox and explicit operator transitions."""
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
MAX_ATTEMPTS = 5
|
||||
LEASE_SECONDS = 60
|
||||
|
||||
|
||||
def database():
|
||||
return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row,
|
||||
connect_timeout=3, autocommit=True,
|
||||
options='-c statement_timeout=5000 -c lock_timeout=1000')
|
||||
|
||||
|
||||
def audit(db, job_id, event, **details):
|
||||
db.execute('INSERT INTO job_audit(job_id,event,details) VALUES (%s,%s,%s)',
|
||||
(job_id, event, Jsonb(details)))
|
||||
|
||||
|
||||
def payload(job):
|
||||
result = {'schema_version': 1, 'job_id': str(job['id']), 'type': 'attachment.process.v1',
|
||||
'attachment_id': str(job['attachment_id']), 'pipeline_version': job['pipeline_version'],
|
||||
'attempt': job['attempts'] + 1,
|
||||
'created_at': job['created_at'].astimezone(timezone.utc).isoformat().replace('+00:00', 'Z')}
|
||||
if job.get('traceparent'):
|
||||
result['traceparent'] = job['traceparent']
|
||||
if job.get('tracestate'):
|
||||
result['tracestate'] = job['tracestate']
|
||||
return result
|
||||
|
||||
|
||||
def recover_expired(db):
|
||||
with db.transaction():
|
||||
rows = db.execute("SELECT * FROM jobs WHERE status='processing' AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED").fetchall()
|
||||
for job in rows:
|
||||
exhausted = job['attempts'] >= MAX_ATTEMPTS
|
||||
status = 'failed' if exhausted else 'queued'
|
||||
db.execute("UPDATE jobs SET status=%s,lease_token=NULL,lease_until=NULL,error_code=%s,next_attempt_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=%s",
|
||||
(status, 'retry_exhausted' if exhausted else 'lease_expired', job['id']))
|
||||
db.execute("UPDATE attachments SET status=%s,error_code=%s,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s AND status='processing'",
|
||||
(status, 'retry_exhausted' if exhausted else None, job['attachment_id'], job['pipeline_version']))
|
||||
db.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s', (job['id'],))
|
||||
audit(db, job['id'], 'lease_expired', attempt=job['attempts'], outcome=status)
|
||||
|
||||
|
||||
def take_fault(db, job_id):
|
||||
# Only the operator test harness can populate this table. No HTTP fault switches.
|
||||
with db.transaction():
|
||||
row = db.execute('UPDATE job_faults SET remaining=remaining-1 WHERE job_id=%s AND remaining>0 RETURNING point',
|
||||
(job_id,)).fetchone()
|
||||
return row['point'] if row else None
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Versioned, transactional migrations, serialized across deployers."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
|
||||
|
||||
def main():
|
||||
with psycopg.connect(os.environ['DATABASE_URL'],autocommit=True,connect_timeout=5) as conn:
|
||||
conn.execute('SELECT pg_advisory_lock(23012026)')
|
||||
try:
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, sha256 text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
|
||||
for file in sorted((Path(__file__).resolve().parents[1]/'migrations').glob('*.sql')):
|
||||
data=file.read_bytes(); digest=hashlib.sha256(data).hexdigest()
|
||||
row=conn.execute('SELECT sha256 FROM schema_migrations WHERE name=%s',(file.name,)).fetchone()
|
||||
if row:
|
||||
if row[0]!=digest: raise RuntimeError('An applied migration was modified: '+file.name)
|
||||
print('Already applied:',file.name,flush=True)
|
||||
continue
|
||||
with conn.transaction():
|
||||
conn.execute(data.decode('utf-8'))
|
||||
conn.execute('INSERT INTO schema_migrations(name,sha256) VALUES (%s,%s)',(file.name,digest))
|
||||
print('Applied:',file.name,flush=True)
|
||||
finally:
|
||||
conn.execute('SELECT pg_advisory_unlock(23012026)')
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Keep resource leases until a blocking operation actually finishes on cancellation."""
|
||||
import asyncio
|
||||
|
||||
|
||||
async def complete_thread(function, *args):
|
||||
task = asyncio.create_task(asyncio.to_thread(function, *args))
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
# asyncio cancellation cannot stop a Python thread. Do not close its file
|
||||
# or release its decoder/upload permit while it is still using them.
|
||||
try:
|
||||
await asyncio.shield(task)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Local operator CLI: failed registry, audited replay and versioned reprocessing."""
|
||||
import argparse
|
||||
import json
|
||||
import tempfile
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from .jobs import audit, database
|
||||
from .storage import MAX_BYTES, Storage
|
||||
|
||||
|
||||
def replay(job_id):
|
||||
storage=Storage()
|
||||
try:
|
||||
with database() as db, db.transaction():
|
||||
job=db.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(job_id,)).fetchone()
|
||||
if not job or job['status']!='failed': raise ValueError('Only failed jobs can be replayed')
|
||||
att=db.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(job['attachment_id'],)).fetchone()
|
||||
if att['pipeline_version']!=job['pipeline_version'] or not att['staging_key']:
|
||||
raise ValueError('Stale version or expired staging; replay refused')
|
||||
storage.client.head_object(Bucket=storage.bucket,Key=att['staging_key'])
|
||||
db.execute("UPDATE jobs SET status='queued',attempts=0,error_code=NULL,lease_token=NULL,lease_until=NULL,next_attempt_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=%s",(job_id,))
|
||||
db.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(att['id'],))
|
||||
db.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(job_id,))
|
||||
audit(db,job_id,'operator_replay',previous_attempts=job['attempts'])
|
||||
return {'job_id':str(job_id),'status':'queued'}
|
||||
finally: storage.client.close()
|
||||
|
||||
|
||||
def upgrade(attachment_id,version):
|
||||
if version not in (1,2): raise ValueError('Supported pipeline versions are 1 and 2')
|
||||
storage=Storage()
|
||||
try:
|
||||
with database() as db, db.transaction():
|
||||
att=db.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(attachment_id,)).fetchone()
|
||||
if not att or version<=att['pipeline_version']: raise ValueError('Version must strictly increase')
|
||||
source=att['object_key'] if att['status']=='ready' else att['staging_key']
|
||||
if not source: raise ValueError('Original is no longer available')
|
||||
key=f'staging/{attachment_id}/v{version}'
|
||||
db.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s,0))',(key,))
|
||||
obj=storage.get(source)
|
||||
try:
|
||||
with tempfile.TemporaryFile() as file:
|
||||
size=0
|
||||
while block:=obj['Body'].read(65536):
|
||||
size+=len(block)
|
||||
if size>MAX_BYTES: raise ValueError('Original exceeds byte limit')
|
||||
file.write(block)
|
||||
storage.put(key,file,size,att['content_type'],att['sha256'])
|
||||
finally: obj['Body'].close()
|
||||
job_id=uuid4()
|
||||
db.execute("UPDATE attachments SET pipeline_version=%s,status='queued',staging_key=%s,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(version,key,attachment_id))
|
||||
db.execute('INSERT INTO jobs(id,attachment_id,pipeline_version) VALUES (%s,%s,%s)',(job_id,attachment_id,version))
|
||||
db.execute('INSERT INTO outbox(job_id) VALUES (%s)',(job_id,))
|
||||
audit(db,job_id,'operator_upgrade',previous_version=att['pipeline_version'],version=version)
|
||||
return {'job_id':str(job_id),'pipeline_version':version,'status':'queued'}
|
||||
finally: storage.client.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser()
|
||||
commands=parser.add_subparsers(dest='command',required=True)
|
||||
commands.add_parser('failed')
|
||||
commands.add_parser('replay').add_argument('job_id',type=UUID)
|
||||
p=commands.add_parser('upgrade'); p.add_argument('attachment_id',type=UUID); p.add_argument('version',type=int)
|
||||
args=parser.parse_args()
|
||||
if args.command=='failed':
|
||||
with database() as db:
|
||||
result=db.execute("SELECT id,attachment_id,pipeline_version,attempts,error_code,updated_at FROM jobs WHERE status='failed' ORDER BY updated_at DESC LIMIT 100").fetchall()
|
||||
elif args.command=='replay': result=replay(args.job_id)
|
||||
else: result=upgrade(args.attachment_id,args.version)
|
||||
print(json.dumps(result,default=str,indent=2))
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Isolated image CPU/memory workload. Input/output paths are operator-owned temporary files."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
|
||||
def fit_size(width, height, bound):
|
||||
ratio = min(1, bound / width, bound / height)
|
||||
return max(1, int(width * ratio)), max(1, int(height * ratio))
|
||||
|
||||
|
||||
def render(source, destination, version):
|
||||
# Both versions are explicit, reproducible pipelines. Version 2 changes quality;
|
||||
# storage effect keys include version, so old jobs cannot overwrite new bytes.
|
||||
quality = {1: (85, 80), 2: (90, 85)}[version]
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
with Image.open(source, formats=['PNG', 'JPEG']) as opened:
|
||||
if opened.width * opened.height > 40_000_000:
|
||||
raise ValueError('pixel_limit')
|
||||
opened.load()
|
||||
image = ImageOps.exif_transpose(opened)
|
||||
try:
|
||||
if image.mode in ('RGBA', 'LA') or 'transparency' in image.info:
|
||||
rgba = image.convert('RGBA')
|
||||
rgb = Image.new('RGB', rgba.size, 'white')
|
||||
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
||||
rgba.close()
|
||||
else:
|
||||
rgb = image.convert('RGB')
|
||||
finally:
|
||||
image.close()
|
||||
rgb.info.clear() # Do not propagate EXIF, ICC or arbitrary image metadata.
|
||||
result = []
|
||||
try:
|
||||
for name, mime, fmt in [('thumbnail', 'image/jpeg', 'JPEG'),
|
||||
('crop', 'image/jpeg', 'JPEG'),
|
||||
('optimized', 'image/webp', 'WEBP')]:
|
||||
if name == 'crop':
|
||||
variant = ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS,
|
||||
centering=(.5, .5))
|
||||
else:
|
||||
variant = rgb.resize(fit_size(*rgb.size, 256 if name == 'thumbnail' else 1280),
|
||||
Image.Resampling.LANCZOS)
|
||||
try:
|
||||
variant.info.clear()
|
||||
target = destination / name
|
||||
options = {'quality': quality[1], 'method': 4} if fmt == 'WEBP' else {
|
||||
'quality': quality[0], 'optimize': True, 'subsampling': 0}
|
||||
variant.save(target, format=fmt, **options)
|
||||
result.append({'name': name, 'content_type': mime, 'width': variant.width,
|
||||
'height': variant.height, 'size_bytes': target.stat().st_size,
|
||||
'sha256': hashlib.sha256(target.read_bytes()).hexdigest()})
|
||||
finally:
|
||||
variant.close()
|
||||
finally:
|
||||
rgb.close()
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Container is the outer memory boundary; subprocess also has finite virtual
|
||||
# memory and CPU budgets. Parent enforces a wall-clock timeout and kills it.
|
||||
resource.setrlimit(resource.RLIMIT_AS, (640 * 1024 * 1024, 640 * 1024 * 1024))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (20, 20))
|
||||
print(json.dumps(render(Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]))))
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Bounded S3 calls and strict PNG/JPEG validation; never trust a client filename."""
|
||||
import hashlib
|
||||
import os
|
||||
import warnings
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .common import ApiError
|
||||
from . import telemetry as tel
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
HEALTH_KEY = 'originals/.storage-health'
|
||||
HEALTH_BYTES = b'messenger-storage-ready-v1'
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def validate_image(file, content_type):
|
||||
try:
|
||||
file.seek(0)
|
||||
with Image.open(file, formats=['PNG', 'JPEG']) as image:
|
||||
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}[image.format]
|
||||
if actual != content_type:
|
||||
raise ApiError(415, 'unsupported_media_type', 'Image content does not match MIME')
|
||||
if image.width * image.height > MAX_PIXELS:
|
||||
raise ApiError(413, 'payload_too_large', 'Too many decoded pixels')
|
||||
image.verify()
|
||||
file.seek(0)
|
||||
with Image.open(file, formats=['PNG', 'JPEG']) as image:
|
||||
image.load() # JPEG.verify alone does not detect a truncated entropy stream.
|
||||
file.seek(0)
|
||||
digest = hashlib.file_digest(file, 'sha256').hexdigest()
|
||||
file.seek(0)
|
||||
return digest
|
||||
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
|
||||
raise ApiError(413, 'payload_too_large', 'Too many decoded pixels') from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise ApiError(415, 'unsupported_media_type', 'Invalid PNG/JPEG') from None
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self):
|
||||
self.bucket = os.environ['S3_BUCKET']
|
||||
self.client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'],
|
||||
aws_access_key_id=os.environ['S3_ACCESS_KEY'],
|
||||
aws_secret_access_key=os.environ['S3_SECRET_KEY'],
|
||||
region_name='us-east-1',
|
||||
config=Config(connect_timeout=2, read_timeout=4,
|
||||
retries={'total_max_attempts': 1},
|
||||
max_pool_connections=8,
|
||||
s3={'addressing_style': 'path'}))
|
||||
|
||||
def ready(self):
|
||||
# Listing proves only filer metadata readiness. After a SeaweedFS restart,
|
||||
# volume registration can lag; require a real read from a persisted volume.
|
||||
obj = self.get(HEALTH_KEY)
|
||||
try:
|
||||
if obj['Body'].read(len(HEALTH_BYTES)+1) != HEALTH_BYTES:
|
||||
raise ApiError(503, 'unavailable', 'Storage probe unavailable')
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
|
||||
def put(self, key, file, size, content_type, digest):
|
||||
file.seek(0)
|
||||
with tel.span('s3.put',attributes={'rpc.system':'aws-api','rpc.service':'S3','rpc.method':'PutObject'}):
|
||||
self.client.put_object(Bucket=self.bucket, Key=key, Body=file, ContentLength=size,
|
||||
ContentType=content_type, Metadata={'sha256': digest})
|
||||
|
||||
def get(self, key):
|
||||
if key==HEALTH_KEY:
|
||||
return self.client.get_object(Bucket=self.bucket, Key=key)
|
||||
with tel.span('s3.get',attributes={'rpc.system':'aws-api','rpc.service':'S3','rpc.method':'GetObject'}):
|
||||
return self.client.get_object(Bucket=self.bucket, Key=key)
|
||||
|
||||
def delete(self, key):
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
import hashlib
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .common import ApiError, encode_cursor, invalid
|
||||
from . import telemetry as tel
|
||||
|
||||
|
||||
def clean(row):
|
||||
if isinstance(row,dict): return {k:clean(v) for k,v in row.items()}
|
||||
if isinstance(row,list): return [clean(v) for v in row]
|
||||
if hasattr(row,'isoformat'): return row.isoformat(timespec='microseconds').replace('+00:00','Z')
|
||||
if type(row).__name__=='UUID': return str(row)
|
||||
return row
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self,cfg):
|
||||
self.cfg=cfg
|
||||
self.secret=cfg.cursor_secret.encode()
|
||||
self.pool=AsyncConnectionPool(cfg.database_url,min_size=1,max_size=cfg.db_pool_size,
|
||||
timeout=2,max_waiting=32,open=False,
|
||||
kwargs={'row_factory':dict_row,'connect_timeout':3,
|
||||
'options':'-c statement_timeout=2000 -c lock_timeout=1000 -c timezone=UTC'})
|
||||
self.cache=Redis.from_url(cfg.redis_url,socket_timeout=.2,socket_connect_timeout=.2,
|
||||
max_connections=8,decode_responses=True)
|
||||
|
||||
async def open(self): await self.pool.open(wait=True,timeout=20)
|
||||
async def close(self):
|
||||
await self.cache.aclose()
|
||||
await self.pool.close()
|
||||
|
||||
async def ready(self):
|
||||
async with self.pool.connection() as c: await c.execute('SELECT 1')
|
||||
|
||||
async def register(self,username,display_name,password_hash):
|
||||
try:
|
||||
async with self.pool.connection() as c:
|
||||
row=await (await c.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at',
|
||||
(uuid4(),username,display_name,password_hash))).fetchone()
|
||||
return clean(row)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409,'conflict','Username already exists') from None
|
||||
|
||||
async def credentials(self,username):
|
||||
async with self.pool.connection() as c:
|
||||
return await (await c.execute('SELECT * FROM users WHERE username=%s',(username,))).fetchone()
|
||||
|
||||
async def create_session(self,user_id,token):
|
||||
async with self.pool.connection() as c:
|
||||
row=await (await c.execute("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,clock_timestamp()+%s*interval '1 second') RETURNING expires_at",
|
||||
(hashlib.sha256(token.encode()).hexdigest(),user_id,self.cfg.session_ttl_seconds))).fetchone()
|
||||
return clean(row)['expires_at']
|
||||
|
||||
async def authenticate(self,token):
|
||||
async with self.pool.connection() as c:
|
||||
session=await (await c.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp()',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),))).fetchone()
|
||||
if session is None: raise ApiError(401,'unauthorized','Invalid session',{'WWW-Authenticate':'Bearer realm="messenger"'})
|
||||
key='user:'+str(session['user_id'])
|
||||
try:
|
||||
cached=await self.cache.get(key)
|
||||
if cached: return json.loads(cached)
|
||||
except (RedisError,ValueError):
|
||||
logging.getLogger('messenger').warning('{"event":"cache_bypass"}')
|
||||
row=await (await c.execute('SELECT id,username,display_name,created_at FROM users WHERE id=%s',(session['user_id'],))).fetchone()
|
||||
user=clean(row)
|
||||
try: await self.cache.set(key,json.dumps(user),ex=60)
|
||||
except RedisError: pass
|
||||
return user
|
||||
|
||||
async def logout(self,token):
|
||||
async with self.pool.connection() as c:
|
||||
await c.execute('DELETE FROM sessions WHERE token_hash=%s',(hashlib.sha256(token.encode()).hexdigest(),))
|
||||
|
||||
async def _chat(self,c,actor,chat_id):
|
||||
row=await (await c.execute('SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM members WHERE chat_id=c.id ORDER BY user_id) AS member_ids FROM chats c JOIN members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s',(chat_id,actor))).fetchone()
|
||||
if row is None: raise ApiError(404,'not_found','Object not found')
|
||||
return clean(row)
|
||||
|
||||
async def chat(self,actor,chat_id):
|
||||
async with self.pool.connection() as c: return await self._chat(c,actor,chat_id)
|
||||
|
||||
async def create_chat(self,actor,title,members):
|
||||
if actor not in members: invalid('Members must include the current user')
|
||||
try:
|
||||
async with self.pool.connection() as c:
|
||||
cid=uuid4()
|
||||
await c.execute('INSERT INTO chats(id,title) VALUES (%s,%s)',(cid,title))
|
||||
async with c.cursor() as cur:
|
||||
await cur.executemany('INSERT INTO members(chat_id,user_id) VALUES (%s,%s)',[(cid,m) for m in members])
|
||||
return await self._chat(c,actor,cid)
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
invalid('All members must exist')
|
||||
|
||||
async def create_message(self,actor,chat_id,text,key,attachment_ids):
|
||||
digest=hashlib.sha256(json.dumps({'text':text,'attachment_ids':attachment_ids},sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
|
||||
async with self.pool.connection() as c:
|
||||
await self._chat(c,actor,chat_id)
|
||||
# Fixed operation POST /chats/{id}/messages; lock and both rows share one transaction.
|
||||
scope='POST:'+chat_id+':'+actor+':'+key
|
||||
await c.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s,0))',(scope,))
|
||||
previous=await (await c.execute("SELECT request_hash,message_id FROM idempotency WHERE actor_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()",(actor,chat_id,key))).fetchone()
|
||||
if previous:
|
||||
if previous['request_hash']!=digest: raise ApiError(409,'conflict','Key was used for another message')
|
||||
return clean(await (await c.execute('SELECT id,chat_id,sender_id,text,created_at,attachment_ids FROM messages WHERE id=%s',(previous['message_id'],))).fetchone())
|
||||
for aid in attachment_ids:
|
||||
attachment=await (await c.execute('SELECT status,storage_state FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE',(aid,chat_id))).fetchone()
|
||||
if attachment is None: raise ApiError(404,'not_found','Object not found')
|
||||
if attachment['status']=='failed': raise ApiError(409,'conflict','Attachment processing failed')
|
||||
if attachment['status']=='ready' and attachment['storage_state']!='ready': raise ApiError(503,'unavailable','Object temporarily unavailable')
|
||||
await c.execute('DELETE FROM idempotency WHERE actor_id=%s AND chat_id=%s AND key=%s',(actor,chat_id,key))
|
||||
row=await (await c.execute('INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids) VALUES (%s,%s,%s,%s,%s::uuid[]) RETURNING id,chat_id,sender_id,text,created_at,attachment_ids',
|
||||
(uuid4(),chat_id,actor,text,attachment_ids))).fetchone()
|
||||
for aid in attachment_ids:
|
||||
await c.execute('INSERT INTO message_attachments(message_id,attachment_id) VALUES (%s,%s)',(row['id'],aid))
|
||||
await c.execute("INSERT INTO idempotency(actor_id,chat_id,key,request_hash,message_id,expires_at) VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')",(actor,chat_id,key,digest,row['id']))
|
||||
return clean(row)
|
||||
|
||||
async def page(self,actor,chat_id,limit,cursor):
|
||||
async with self.pool.connection() as c:
|
||||
if chat_id:
|
||||
await self._chat(c,actor,chat_id)
|
||||
query='SELECT id,chat_id,sender_id,text,created_at,attachment_ids FROM messages WHERE chat_id=%s'
|
||||
args=[chat_id]; resource='messages:'+chat_id
|
||||
if cursor:
|
||||
query+=' AND (created_at,id)>(%s::timestamptz,%s::uuid)'; args.extend(cursor)
|
||||
query+=' ORDER BY created_at,id LIMIT %s'; args.append(limit+1)
|
||||
else:
|
||||
query='SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM members WHERE chat_id=c.id ORDER BY user_id) AS member_ids FROM chats c JOIN members m ON m.chat_id=c.id WHERE m.user_id=%s'
|
||||
args=[actor]; resource='chats:'+actor
|
||||
if cursor:
|
||||
query+=' AND (c.created_at,c.id)>(%s::timestamptz,%s::uuid)'; args.extend(cursor)
|
||||
query+=' ORDER BY c.created_at,c.id LIMIT %s'; args.append(limit+1)
|
||||
rows=[clean(row) for row in await (await c.execute(query,args)).fetchall()]
|
||||
selected=rows[:limit]
|
||||
next_cursor=encode_cursor(resource,(selected[-1]['created_at'],selected[-1]['id']),self.secret) if len(rows)>limit else None
|
||||
return {'items':selected,'next_cursor':next_cursor}
|
||||
|
||||
async def attachment(self,actor,identifier):
|
||||
async with self.pool.connection() as c:
|
||||
row=await (await c.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',(identifier,actor))).fetchone()
|
||||
if row is None: raise ApiError(404,'not_found','Object not found')
|
||||
if row['status']=='ready' and row['storage_state']!='ready': raise ApiError(503,'unavailable','Object temporarily unavailable')
|
||||
return clean(row)
|
||||
|
||||
async def save_attachment(self,actor,chat_id,filename,mime,size,digest,file,storage):
|
||||
identifier=uuid4()
|
||||
key='staging/'+str(identifier)+'/v1'
|
||||
# The same lock is taken by reconciliation before it can delete an orphan.
|
||||
# DB COMMIT uncertainty must NEVER trigger an unconditional S3 delete: the row
|
||||
# may have committed. Leave a possible orphan for the grace-period reconciler.
|
||||
async with self.pool.connection() as c:
|
||||
await self._chat(c,actor,chat_id)
|
||||
# Admission is global and serialized: no unbounded durable backlog.
|
||||
await c.execute("SELECT pg_advisory_xact_lock(hashtextextended('job-admission',0))")
|
||||
pending=await (await c.execute("SELECT count(*) AS n FROM jobs WHERE status IN ('queued','processing')")).fetchone()
|
||||
if pending['n']>=1000: raise ApiError(503,'unavailable','Processing backlog is full')
|
||||
await c.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s,0))',(key,))
|
||||
from .offload import complete_thread
|
||||
await complete_thread(storage.put,key,file,size,mime,digest)
|
||||
row=await (await c.execute("INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status,staging_key) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued',%s) RETURNING *",
|
||||
(identifier,chat_id,actor,filename,key,mime,size,digest,key))).fetchone()
|
||||
job_id=uuid4()
|
||||
context=tel.carrier()
|
||||
await c.execute('INSERT INTO jobs(id,attachment_id,pipeline_version,traceparent,tracestate) VALUES (%s,%s,1,%s,%s)',(job_id,identifier,context.get('traceparent'),context.get('tracestate')))
|
||||
await c.execute('INSERT INTO outbox(job_id) VALUES (%s)',(job_id,))
|
||||
return clean(row)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Explicit low-cardinality OTLP signals. Business operation never waits for export."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import SeverityNumber
|
||||
from opentelemetry.propagate import extract, inject
|
||||
from opentelemetry.sdk._logs import LoggerProvider
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
|
||||
configured=False
|
||||
log_provider=None
|
||||
service='messenger'
|
||||
instance=uuid4().hex
|
||||
|
||||
|
||||
def setup(name):
|
||||
global configured,log_provider,service,http_count,http_duration,job_count,job_duration,ready_duration,pool_used,pool_waiting,worker_busy,worker_capacity,queue_depth,queue_age,process_rss,process_cpu,slo_total,slo_bad
|
||||
if configured: return
|
||||
configured=True; service=name
|
||||
enabled=os.environ.get('TELEMETRY_ENABLED','1')=='1'
|
||||
endpoint=os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT','http://otel-collector:4318').rstrip('/')
|
||||
res=Resource.create({'service.name':name,'service.version':'lab6-v1','service.instance.id':instance,
|
||||
'deployment.environment.name':'lab'})
|
||||
if enabled:
|
||||
tracer=TracerProvider(resource=res,sampler=ParentBased(TraceIdRatioBased(float(os.environ.get('TRACE_SAMPLE_RATIO','1')))))
|
||||
tracer.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint+'/v1/traces',timeout=2),
|
||||
max_queue_size=256,max_export_batch_size=64,schedule_delay_millis=1000,export_timeout_millis=2000))
|
||||
trace.set_tracer_provider(tracer)
|
||||
log_provider=LoggerProvider(resource=res)
|
||||
log_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint+'/v1/logs',timeout=2),
|
||||
max_queue_size=256,max_export_batch_size=64,schedule_delay_millis=1000,export_timeout_millis=2000))
|
||||
reader=PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=endpoint+'/v1/metrics',timeout=2),export_interval_millis=5000,export_timeout_millis=3000)
|
||||
metrics.set_meter_provider(MeterProvider(resource=res,metric_readers=[reader],views=[
|
||||
View(instrument_type=metrics.Histogram,aggregation=ExplicitBucketHistogramAggregation([.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10,30,60,120]))]))
|
||||
meter=metrics.get_meter('messenger')
|
||||
http_count=meter.create_counter('http_server_requests')
|
||||
http_duration=meter.create_histogram('http_server_duration',unit='s')
|
||||
job_count=meter.create_counter('jobs_processed')
|
||||
job_duration=meter.create_histogram('job_processing_duration',unit='s')
|
||||
ready_duration=meter.create_histogram('attachment_time_to_ready',unit='s')
|
||||
pool_used=meter.create_gauge('db_pool_used')
|
||||
pool_waiting=meter.create_gauge('db_pool_waiting')
|
||||
worker_busy=meter.create_gauge('worker_busy')
|
||||
worker_capacity=meter.create_gauge('worker_capacity')
|
||||
queue_depth=meter.create_gauge('queue_depth')
|
||||
queue_age=meter.create_gauge('queue_oldest_age',unit='s')
|
||||
process_rss=meter.create_gauge('process_rss',unit='By')
|
||||
process_cpu=meter.create_gauge('process_cpu_time',unit='s')
|
||||
slo_total=meter.create_gauge('attachment_slo_eligible')
|
||||
slo_bad=meter.create_gauge('attachment_slo_bad')
|
||||
|
||||
|
||||
def tracer(): return trace.get_tracer('messenger')
|
||||
|
||||
|
||||
@contextmanager
|
||||
def span(name,kind=trace.SpanKind.INTERNAL,carrier=None,attributes=None):
|
||||
with tracer().start_as_current_span(name,kind=kind,context=extract(carrier) if carrier else None,
|
||||
attributes=attributes or {},record_exception=False,set_status_on_exception=False) as current:
|
||||
try: yield current
|
||||
except BaseException:
|
||||
current.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
|
||||
def carrier():
|
||||
result={}; inject(result); return result
|
||||
|
||||
|
||||
def event(name,**fields):
|
||||
# Callers pass controlled fields only. Never capture arbitrary exceptions,
|
||||
# HTTP headers/bodies/raw URLs, passwords, tokens, filenames or S3 URLs.
|
||||
context=trace.get_current_span().get_span_context()
|
||||
row={'timestamp':time.time(),'severity':'INFO','service.name':service,'event':name,
|
||||
'trace_id':format(context.trace_id,'032x'),'span_id':format(context.span_id,'016x'),**fields}
|
||||
print(json.dumps(row),flush=True)
|
||||
if log_provider:
|
||||
log_provider.get_logger('messenger').emit(body=json.dumps(row),severity_number=SeverityNumber.INFO,
|
||||
severity_text='INFO',attributes={'event':name})
|
||||
|
||||
|
||||
def process_metrics():
|
||||
# Linux ru_maxrss is KiB; use actual current RSS from proc for memory trend.
|
||||
with open('/proc/self/statm') as file:
|
||||
rss=int(file.read().split()[1])*os.sysconf('SC_PAGE_SIZE')
|
||||
usage=resource.getrusage(resource.RUSAGE_SELF)
|
||||
attrs={'service':service,'process_instance':instance}
|
||||
process_rss.set(rss,attrs); process_cpu.set(usage.ru_utime+usage.ru_stime,attrs)
|
||||
|
||||
|
||||
def shutdown():
|
||||
for provider in (trace.get_tracer_provider(),metrics.get_meter_provider(),log_provider):
|
||||
if provider and hasattr(provider,'shutdown'):
|
||||
try: provider.shutdown()
|
||||
except Exception: pass
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
"""At-least-once processing with versioned effects, fenced commits and bounded retries."""
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .broker import acknowledge, connect, receive
|
||||
from .jobs import MAX_ATTEMPTS, audit, database, take_fault
|
||||
from .storage import MAX_BYTES, Storage
|
||||
from . import telemetry as tel
|
||||
|
||||
stop = threading.Event()
|
||||
|
||||
|
||||
class Permanent(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def crash(point, job_id, code):
|
||||
print(json.dumps({'event':'injected_crash','point':point,'job_id':str(job_id),'exit_code':code}),flush=True)
|
||||
os._exit(code)
|
||||
|
||||
|
||||
def parse(raw):
|
||||
item = json.loads(raw)
|
||||
required = {'schema_version','job_id','type','attachment_id','pipeline_version','attempt','created_at'}
|
||||
if set(item)-required-{'traceparent','tracestate'} or required-set(item):
|
||||
raise ValueError('invalid_job_fields')
|
||||
if item['schema_version'] != 1 or item['type'] != 'attachment.process.v1':
|
||||
raise ValueError('unsupported_job')
|
||||
UUID(item['job_id']); UUID(item['attachment_id'])
|
||||
for field in ('attempt','pipeline_version'):
|
||||
if type(item[field]) is not int or item[field]<1:
|
||||
raise ValueError('invalid_job_number')
|
||||
datetime.fromisoformat(item['created_at'].replace('Z','+00:00'))
|
||||
return item
|
||||
|
||||
|
||||
def claim(db, item):
|
||||
with db.transaction():
|
||||
job = db.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE', (item['job_id'],)).fetchone()
|
||||
if not job or job['status'] in ('done','failed','superseded'):
|
||||
return None
|
||||
if str(job['attachment_id'])!=item['attachment_id'] or job['pipeline_version']!=item['pipeline_version']:
|
||||
return None
|
||||
attachment = db.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE', (job['attachment_id'],)).fetchone()
|
||||
if attachment['pipeline_version']!=job['pipeline_version']:
|
||||
db.execute("UPDATE jobs SET status='superseded',updated_at=clock_timestamp() WHERE id=%s", (job['id'],))
|
||||
audit(db, job['id'], 'stale_version_ignored')
|
||||
return None
|
||||
if job['status']!='queued' or job['next_attempt_at']>datetime.now(timezone.utc):
|
||||
return None
|
||||
if item['attempt']!=job['attempts']+1:
|
||||
return None
|
||||
token=uuid4()
|
||||
job=db.execute("""UPDATE jobs SET status='processing',attempts=attempts+1,lease_token=%s,
|
||||
lease_until=clock_timestamp()+interval '60 seconds',updated_at=clock_timestamp()
|
||||
WHERE id=%s RETURNING *""", (token,job['id'])).fetchone()
|
||||
db.execute("UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s", (attachment['id'],))
|
||||
audit(db,job['id'],'claimed',attempt=job['attempts'],version=job['pipeline_version'])
|
||||
return job,attachment
|
||||
|
||||
|
||||
def process_bytes(storage, attachment, version, folder):
|
||||
source=folder/'source'
|
||||
if not attachment['staging_key']:
|
||||
raise Permanent('staging_missing')
|
||||
try:
|
||||
obj=storage.get(attachment['staging_key'])
|
||||
except ClientError as exc:
|
||||
if exc.response['Error']['Code'] in ('404','NoSuchKey'):
|
||||
raise Permanent('staging_missing') from None
|
||||
raise
|
||||
size=0; digest=hashlib.sha256()
|
||||
try:
|
||||
with source.open('wb') as file:
|
||||
while block:=obj['Body'].read(65536):
|
||||
size+=len(block)
|
||||
if size>MAX_BYTES:
|
||||
raise Permanent('size_limit')
|
||||
digest.update(block); file.write(block)
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
if size!=attachment['size_bytes'] or digest.hexdigest()!=attachment['sha256']:
|
||||
raise Permanent('checksum_mismatch')
|
||||
try:
|
||||
with tel.span('image.render'):
|
||||
rendering=subprocess.run([sys.executable,'-m','src.render',str(source),str(folder),str(version)],
|
||||
capture_output=True,text=True,timeout=25)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Permanent('processing_timeout') from None
|
||||
if rendering.returncode:
|
||||
raise Permanent('invalid_image_or_resource_limit')
|
||||
variants=json.loads(rendering.stdout)
|
||||
# Version is part of every final key. Never use an unversioned mutable alias.
|
||||
key=f'originals/{attachment["id"]}/v{version}'
|
||||
with source.open('rb') as file:
|
||||
storage.put(key,file,size,attachment['content_type'],attachment['sha256'])
|
||||
for variant in variants:
|
||||
variant['object_key']=f'variants/{attachment["id"]}/v{version}/{variant["name"]}'
|
||||
with (folder/variant['name']).open('rb') as file:
|
||||
storage.put(variant['object_key'],file,variant['size_bytes'],variant['content_type'],variant['sha256'])
|
||||
return key,variants
|
||||
|
||||
|
||||
def publish_result(db, job, key, variants):
|
||||
with db.transaction():
|
||||
current=db.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE', (job['id'],)).fetchone()
|
||||
att=db.execute('SELECT pipeline_version FROM attachments WHERE id=%s FOR UPDATE', (job['attachment_id'],)).fetchone()
|
||||
if current['status']!='processing' or current['lease_token']!=job['lease_token'] or current['lease_until']<=datetime.now(timezone.utc):
|
||||
return False
|
||||
if att['pipeline_version']!=job['pipeline_version']:
|
||||
db.execute("UPDATE jobs SET status='superseded',lease_token=NULL,lease_until=NULL,updated_at=clock_timestamp() WHERE id=%s",(job['id'],))
|
||||
audit(db,job['id'],'stale_commit_ignored')
|
||||
return False
|
||||
db.execute("""UPDATE attachments SET status='ready',storage_state='ready',object_key=%s,
|
||||
variants=%s,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s""",
|
||||
(key,Jsonb(variants),job['attachment_id']))
|
||||
db.execute("UPDATE jobs SET status='done',error_code=NULL,lease_token=NULL,lease_until=NULL,updated_at=clock_timestamp() WHERE id=%s",(job['id'],))
|
||||
audit(db,job['id'],'ready',attempt=job['attempts'],version=job['pipeline_version'])
|
||||
return True
|
||||
|
||||
|
||||
def failed_attempt(db, job, exc):
|
||||
permanent=isinstance(exc,Permanent)
|
||||
final=permanent or job['attempts']>=MAX_ATTEMPTS
|
||||
code=str(exc) if permanent else ('retry_exhausted' if final else 'storage_or_processing_unavailable')
|
||||
delay=min(30,2**job['attempts'])+random.uniform(0,.5)
|
||||
state='failed' if final else 'queued'
|
||||
with db.transaction():
|
||||
row=db.execute("""UPDATE jobs SET status=%s,error_code=%s,lease_token=NULL,lease_until=NULL,
|
||||
next_attempt_at=clock_timestamp()+(%s*interval '1 second'),updated_at=clock_timestamp()
|
||||
WHERE id=%s AND status='processing' AND lease_token=%s RETURNING id""",
|
||||
(state,code,delay,job['id'],job['lease_token'])).fetchone()
|
||||
if not row: return
|
||||
db.execute("UPDATE attachments SET status=%s,error_code=%s,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s",
|
||||
(state,code if final else None,job['attachment_id'],job['pipeline_version']))
|
||||
db.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(job['id'],))
|
||||
audit(db,job['id'],state,error_code=code,attempt=job['attempts'],retry_delay_seconds=round(delay,3))
|
||||
|
||||
|
||||
def handle(item):
|
||||
with database() as db:
|
||||
claimed=claim(db,item)
|
||||
if claimed is None: return 'noop'
|
||||
job,attachment=claimed
|
||||
fault=take_fault(db,job['id'])
|
||||
if fault=='before_effect': crash(fault,job['id'],71)
|
||||
storage=Storage()
|
||||
try:
|
||||
if fault=='transient': raise RuntimeError('synthetic_transient')
|
||||
if fault=='permanent': raise Permanent('synthetic_permanent')
|
||||
with tempfile.TemporaryDirectory(prefix='job-') as directory:
|
||||
key,variants=process_bytes(storage,attachment,job['pipeline_version'],Path(directory))
|
||||
if fault=='after_effect': crash(fault,job['id'],72)
|
||||
with tel.span('db.attachment.commit',attributes={'db.system.name':'postgresql'}):
|
||||
done=publish_result(db,job,key,variants)
|
||||
if done:
|
||||
tel.ready_duration.record((datetime.now(timezone.utc)-attachment['accepted_at']).total_seconds(),{'pipeline_version':str(job['pipeline_version'])})
|
||||
if fault=='after_commit': crash(fault,job['id'],73)
|
||||
# Cleanup is independently repeatable. Failure cannot roll back ready.
|
||||
if done and attachment['staging_key']:
|
||||
try:
|
||||
storage.delete(attachment['staging_key'])
|
||||
db.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s AND pipeline_version=%s AND status='ready' AND staging_key=%s",
|
||||
(attachment['id'],job['pipeline_version'],attachment['staging_key']))
|
||||
except Exception:
|
||||
print(json.dumps({'event':'staging_cleanup_deferred'}),flush=True)
|
||||
return 'ready' if done else 'superseded'
|
||||
except Exception as exc:
|
||||
failed_attempt(db,job,exc)
|
||||
return 'failed' if isinstance(exc,Permanent) or job['attempts']>=MAX_ATTEMPTS else 'retry'
|
||||
finally:
|
||||
storage.client.close()
|
||||
|
||||
|
||||
def main():
|
||||
tel.setup('messenger-worker')
|
||||
tel.worker_capacity.set(1,{'process_instance':tel.instance})
|
||||
tel.worker_busy.set(0,{'process_instance':tel.instance})
|
||||
signal.signal(signal.SIGTERM,lambda *_:stop.set())
|
||||
signal.signal(signal.SIGINT,lambda *_:stop.set())
|
||||
consumer='worker-'+uuid4().hex
|
||||
while not stop.is_set():
|
||||
try:
|
||||
with connect() as client:
|
||||
entry=receive(client,consumer)
|
||||
if not entry:
|
||||
tel.process_metrics()
|
||||
continue
|
||||
message_id,fields=entry
|
||||
try: item=parse(fields.get('job',''))
|
||||
except (ValueError,KeyError,TypeError):
|
||||
print(json.dumps({'event':'invalid_broker_payload'}),flush=True)
|
||||
acknowledge(client,message_id)
|
||||
continue
|
||||
started=time.monotonic()
|
||||
with tel.span('attachment.consume',kind=tel.trace.SpanKind.CONSUMER,carrier=item,
|
||||
attributes={'messaging.system':'redis','messaging.destination.name':'attachment-jobs'}) as current:
|
||||
tel.worker_busy.set(1,{'process_instance':tel.instance})
|
||||
try: outcome=handle(item)
|
||||
finally: tel.worker_busy.set(0,{'process_instance':tel.instance})
|
||||
acknowledge(client,message_id)
|
||||
duration=time.monotonic()-started
|
||||
attrs={'job_type':'attachment.process.v1','outcome':outcome}
|
||||
tel.job_count.add(1,attrs); tel.job_duration.record(duration,attrs)
|
||||
if outcome in ('retry','failed'): current.set_status(tel.trace.Status(tel.trace.StatusCode.ERROR))
|
||||
tel.event('job_finished',job_id=item['job_id'],attempt=item['attempt'],outcome=outcome,duration_seconds=round(duration,6))
|
||||
tel.process_metrics()
|
||||
except Exception as exc:
|
||||
# No ack on uncertain DB/transport result; lease/outbox re-drive intent.
|
||||
tel.event('worker_retry',error_type=type(exc).__name__)
|
||||
stop.wait(1)
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
Reference in New Issue
Block a user