forked from mtusi2026/mtusi2026lab6
Lab 6: track - 1
This commit is contained in:
+512
@@ -0,0 +1,512 @@
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from flask import Flask, g, request
|
||||
from opentelemetry import context as otel_context, trace
|
||||
from opentelemetry.metrics import Observation
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
import psycopg
|
||||
from psycopg.errors import UniqueViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
import redis
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from app.migrate import setting
|
||||
from app.telemetry import Telemetry
|
||||
|
||||
app = Flask(__name__)
|
||||
MAX_UPLOAD = int(os.getenv('MAX_UPLOAD_BYTES', '10485760'))
|
||||
MAX_PIXELS = int(os.getenv('MAX_IMAGE_PIXELS', '40000000'))
|
||||
MAX_QUEUED = int(os.getenv('MAX_QUEUED_JOBS', '500'))
|
||||
app.config['MAX_CONTENT_LENGTH'] = MAX_UPLOAD
|
||||
pool = ConnectionPool(
|
||||
setting('DATABASE_URL'),
|
||||
min_size=1,
|
||||
max_size=int(os.getenv('POOL_MAX', '8')),
|
||||
timeout=3,
|
||||
kwargs={
|
||||
'row_factory': dict_row,
|
||||
'connect_timeout': 3,
|
||||
'options': '-c statement_timeout=3000 -c lock_timeout=2000',
|
||||
},
|
||||
)
|
||||
cache = redis.Redis.from_url(setting('CACHE_URL'), socket_connect_timeout=0.2, socket_timeout=0.2)
|
||||
broker = redis.Redis.from_url(setting('BROKER_URL'), socket_connect_timeout=0.3, socket_timeout=0.5)
|
||||
kdf = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
dummy = kdf.hash(secrets.token_urlsafe(32))
|
||||
ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600'))
|
||||
def envsetting(name): return setting(name) if os.getenv(name + '_FILE') else os.environ[name]
|
||||
s3 = boto3.client(
|
||||
's3',
|
||||
endpoint_url=os.getenv('S3_ENDPOINT', 'http://rustfs:9000'),
|
||||
region_name=os.getenv('S3_REGION', 'us-east-1'),
|
||||
aws_access_key_id=envsetting('S3_ACCESS_KEY_ID'),
|
||||
aws_secret_access_key=envsetting('S3_SECRET_ACCESS_KEY'),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={'max_attempts': 1}),
|
||||
)
|
||||
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
instance = os.getenv('HOSTNAME', 'api') + '-' + secrets.token_hex(4)
|
||||
|
||||
tel = Telemetry('messenger-api', instance)
|
||||
http_requests_counter = tel.meter.create_counter(
|
||||
'http.server.requests',
|
||||
unit='1',
|
||||
description='HTTP requests count',
|
||||
)
|
||||
http_duration_hist = tel.meter.create_histogram(
|
||||
'http.server.request.duration',
|
||||
unit='s',
|
||||
description='HTTP request duration in seconds',
|
||||
explicit_bucket_boundaries_advisory=[0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 10.0],
|
||||
)
|
||||
|
||||
def _pool_callbacks(_opts):
|
||||
try:
|
||||
st = pool.get_stats()
|
||||
size = st.get('pool_size', 0)
|
||||
avail = st.get('pool_available', 0)
|
||||
used = max(0, size - avail)
|
||||
waiting = st.get('requests_waiting', 0)
|
||||
return [
|
||||
Observation(used, {'state': 'used'}),
|
||||
Observation(avail, {'state': 'idle'}),
|
||||
Observation(waiting, {'state': 'waiting'}),
|
||||
Observation(st.get('pool_max', 8), {'state': 'max'}),
|
||||
]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
tel.meter.create_observable_gauge(
|
||||
'db.pool.connections',
|
||||
callbacks=[_pool_callbacks],
|
||||
unit='',
|
||||
description='PostgreSQL connection pool usage and waiting queue',
|
||||
)
|
||||
|
||||
def _api_queue_depth_cb(_opts):
|
||||
counts = {'pending': 0, 'published': 0, 'processing': 0}
|
||||
try:
|
||||
with pool.connection() as c:
|
||||
rows = c.execute("SELECT state, count(*) AS n FROM attachment_jobs WHERE state IN ('pending','published','processing') GROUP BY state").fetchall()
|
||||
for r in rows:
|
||||
counts[r['state']] = int(r['n'])
|
||||
except Exception:
|
||||
return []
|
||||
return [Observation(v, {'queue_name': 'attachment-jobs', 'state': k}) for k, v in counts.items()]
|
||||
|
||||
def _api_oldest_age_cb(_opts):
|
||||
try:
|
||||
with pool.connection() as c:
|
||||
row = c.execute("SELECT COALESCE(EXTRACT(EPOCH FROM (clock_timestamp() - min(created_at))), 0) AS age FROM attachment_jobs WHERE state IN ('pending','published','processing')").fetchone()
|
||||
return [Observation(max(0.0, float(row['age'])) if row else 0.0, {'queue_name': 'attachment-jobs'})]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
tel.meter.create_observable_gauge('worker.queue.depth', callbacks=[_api_queue_depth_cb], unit='', description='Queued jobs by state')
|
||||
tel.meter.create_observable_gauge('worker.oldest_job.age', callbacks=[_api_oldest_age_cb], unit='s', description='Age of oldest unfinished job in seconds')
|
||||
http_requests_counter.add(0, {'http.request.method': 'POST', 'http.route': '/api/v1/chats/{chat_id}/messages', 'http.response.status_class': '5xx'})
|
||||
http_requests_counter.add(0, {'http.request.method': 'POST', 'http.route': '/api/v1/chats/{chat_id}/attachments', 'http.response.status_class': '5xx'})
|
||||
|
||||
def route_template(path):
|
||||
if path in ('/health/live', '/health/ready'):
|
||||
return path
|
||||
if path.startswith('/api/v1/'):
|
||||
rel = path[8:]
|
||||
if rel in ('users', 'users/me', 'auth/sessions', 'auth/sessions/current', 'chats'):
|
||||
return '/api/v1/' + rel
|
||||
parts = rel.split('/')
|
||||
if len(parts) == 2 and parts[0] == 'chats':
|
||||
return '/api/v1/chats/{chat_id}'
|
||||
if len(parts) == 3 and parts[0] == 'chats' and parts[2] in ('messages', 'attachments'):
|
||||
return '/api/v1/chats/{chat_id}/' + parts[2]
|
||||
if len(parts) == 2 and parts[0] == 'attachments':
|
||||
return '/api/v1/attachments/{attachment_id}'
|
||||
if len(parts) == 3 and parts[0] == 'attachments' and parts[2] == 'content':
|
||||
return '/api/v1/attachments/{attachment_id}/content'
|
||||
return '/api/v1/{unknown}'
|
||||
return '/{other}'
|
||||
|
||||
class Problem(Exception):
|
||||
def __init__(self, status, code):
|
||||
self.status, self.code = status, code
|
||||
|
||||
def fail(status, code): raise Problem(status, code)
|
||||
def invalid(): fail(400, 'invalid_request')
|
||||
def uid(value):
|
||||
try: return str(uuid.UUID(value))
|
||||
except (ValueError, TypeError, AttributeError): invalid()
|
||||
def clean(row):
|
||||
return {k: (v.isoformat().replace('+00:00', 'Z') if isinstance(v, dt.datetime) else str(v) if isinstance(v, uuid.UUID) else v) for k, v in row.items()}
|
||||
def user(row): return clean({k: row[k] for k in ('id', 'username', 'display_name', 'created_at')})
|
||||
def body(fields):
|
||||
if request.mimetype != 'application/json': fail(415, 'unsupported_media_type')
|
||||
try: data = request.get_json()
|
||||
except HTTPException: invalid()
|
||||
if not isinstance(data, dict) or set(data) != set(fields): invalid()
|
||||
return data
|
||||
def string(s, maximum, minimum=1):
|
||||
if not isinstance(s, str) or not s.strip() or not minimum <= len(s) <= maximum: invalid()
|
||||
try: s.encode('utf-8')
|
||||
except UnicodeError: invalid()
|
||||
return s
|
||||
|
||||
def db_exec(c, op, query, params=()):
|
||||
with tel.span('db.query', {'db.system': 'postgresql', 'db.operation.name': op}):
|
||||
return c.execute(query, params)
|
||||
|
||||
def actor(c):
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth.startswith('Bearer ') or not 1 <= len(auth[7:]) <= 256: fail(401, 'unauthorized')
|
||||
digest = hashlib.sha256(auth[7:].encode()).hexdigest()
|
||||
row = db_exec(c, 'select_session', 'SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp()', (digest,)).fetchone()
|
||||
if not row: fail(401, 'unauthorized')
|
||||
g.digest = digest
|
||||
return row['user_id']
|
||||
|
||||
def public_user(c, ident):
|
||||
key = 'user:' + str(ident)
|
||||
with tel.span('cache.get_user', {'db.system': 'redis'}):
|
||||
try:
|
||||
value = cache.get(key)
|
||||
if value: return json.loads(value)
|
||||
except (redis.RedisError, ValueError): pass
|
||||
result = user(db_exec(c, 'select_user', 'SELECT * FROM users WHERE id=%s', (ident,)).fetchone())
|
||||
try: cache.setex(key, 60, json.dumps(result))
|
||||
except redis.RedisError: pass
|
||||
return result
|
||||
|
||||
def chat(c, ident, who):
|
||||
row = db_exec(c, 'select_chat', 'SELECT c.* FROM chats c JOIN members m ON c.id=m.chat_id WHERE c.id=%s AND m.user_id=%s', (ident, who)).fetchone()
|
||||
if not row: fail(404, 'not_found')
|
||||
row = clean(row)
|
||||
row['member_ids'] = [str(x['user_id']) for x in db_exec(c, 'select_members', 'SELECT user_id FROM members WHERE chat_id=%s ORDER BY user_id', (ident,))]
|
||||
return row
|
||||
|
||||
def page_args(resource):
|
||||
if set(request.args) - {'limit', 'cursor'} or any(len(request.args.getlist(k)) != 1 for k in request.args): invalid()
|
||||
raw = request.args.get('limit', '50')
|
||||
if len(raw) > 3 or not re.fullmatch(r'[0-9]+', raw) or not 1 <= int(raw) <= 100: invalid()
|
||||
cursor = request.args.get('cursor')
|
||||
pair = None
|
||||
if cursor is not None:
|
||||
try:
|
||||
data = json.loads(base64.b64decode(cursor, altchars=b'-_', validate=True))
|
||||
if not isinstance(data, list) or len(data) != 3 or data[0] != resource: invalid()
|
||||
stamp = dt.datetime.fromisoformat(data[1].replace('Z', '+00:00'))
|
||||
if stamp.tzinfo is None: invalid()
|
||||
pair = (stamp, uid(data[2]))
|
||||
except (ValueError, TypeError, KeyError, AttributeError, OverflowError): invalid()
|
||||
return int(raw), pair
|
||||
|
||||
def page(rows, limit, resource):
|
||||
more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
cursor = base64.urlsafe_b64encode(json.dumps([resource, rows[-1]['created_at'], rows[-1]['id']]).encode()).decode() if more else None
|
||||
return {'items': rows, 'next_cursor': cursor}
|
||||
|
||||
@app.before_request
|
||||
def before():
|
||||
g.request_id = str(uuid.uuid4())
|
||||
g._req_start = time.monotonic()
|
||||
g._route = route_template(request.path)
|
||||
parent = tel.extract_context(request.headers.get('traceparent'), request.headers.get('tracestate'))
|
||||
span = tel.tracer.start_span(
|
||||
f'{request.method} {g._route}',
|
||||
context=parent,
|
||||
kind=SpanKind.SERVER,
|
||||
attributes={
|
||||
'http.request.method': request.method,
|
||||
'http.route': g._route,
|
||||
'messenger.request_id': g.request_id,
|
||||
},
|
||||
)
|
||||
g._otel_span = span
|
||||
g._otel_token = otel_context.attach(trace.set_span_in_context(span))
|
||||
|
||||
@app.after_request
|
||||
def after(response):
|
||||
response.headers['X-Request-Id'] = g.request_id
|
||||
response.headers['X-Instance-Id'] = instance
|
||||
duration = time.monotonic() - getattr(g, '_req_start', time.monotonic())
|
||||
status = response.status_code
|
||||
status_class = f'{status // 100}xx'
|
||||
route = getattr(g, '_route', '/{other}')
|
||||
attrs = {
|
||||
'http.request.method': request.method,
|
||||
'http.route': route,
|
||||
'http.response.status_class': status_class,
|
||||
}
|
||||
http_requests_counter.add(1, attrs)
|
||||
http_duration_hist.record(duration, attrs)
|
||||
span = getattr(g, '_otel_span', None)
|
||||
if span is not None:
|
||||
span.set_attribute('http.response.status_code', status)
|
||||
if status >= 500:
|
||||
span.set_status(Status(StatusCode.ERROR, f'http_{status}'))
|
||||
if not route.startswith('/health/') or status >= 500:
|
||||
lvl = logging.ERROR if status >= 500 else logging.WARNING if status >= 400 else logging.INFO
|
||||
tel.log(
|
||||
lvl,
|
||||
'http.request',
|
||||
request_id=g.request_id,
|
||||
http_method=request.method,
|
||||
http_route=route,
|
||||
http_status=status,
|
||||
duration_ms=round(duration * 1000, 2),
|
||||
)
|
||||
return response
|
||||
|
||||
@app.teardown_request
|
||||
def teardown(exc):
|
||||
span = getattr(g, '_otel_span', None)
|
||||
token = getattr(g, '_otel_token', None)
|
||||
if span is not None:
|
||||
if exc is not None:
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
span.record_exception(exc)
|
||||
span.end()
|
||||
if token is not None:
|
||||
otel_context.detach(token)
|
||||
|
||||
@app.errorhandler(Exception)
|
||||
def error(exc):
|
||||
if isinstance(exc, Problem):
|
||||
status, code = exc.status, exc.code
|
||||
elif isinstance(exc, UniqueViolation):
|
||||
status, code = 409, 'conflict'
|
||||
elif isinstance(exc, (psycopg.Error, __import__('psycopg_pool').PoolTimeout)):
|
||||
status, code = 503, 'unavailable'
|
||||
elif isinstance(exc, HTTPException):
|
||||
status = exc.code
|
||||
code = {404: 'not_found', 413: 'payload_too_large', 415: 'unsupported_media_type'}.get(status, 'invalid_request')
|
||||
else:
|
||||
tel.log(logging.ERROR, 'http.unhandled_exception', request_id=g.request_id, exc_type=type(exc).__name__)
|
||||
status, code = 500, 'internal_error'
|
||||
span = getattr(g, '_otel_span', None)
|
||||
if span is not None and status >= 500:
|
||||
span.set_status(Status(StatusCode.ERROR, code))
|
||||
span.set_attribute('error.code', code)
|
||||
response = app.json.response({'error': {'code': code, 'message': code, 'request_id': g.request_id}})
|
||||
response.status_code = status
|
||||
if status == 401:
|
||||
response.headers['WWW-Authenticate'] = 'Basic realm="messenger", charset="UTF-8"' if request.path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"'
|
||||
return response
|
||||
|
||||
@app.get('/health/live')
|
||||
def live():
|
||||
return {'status': 'ok'}
|
||||
|
||||
@app.get('/health/ready')
|
||||
def ready():
|
||||
with tel.span('db.pool.connect', {'db.system': 'postgresql'}):
|
||||
with pool.connection() as c:
|
||||
db_exec(c, 'health_select', 'SELECT 1')
|
||||
with tel.span('broker.ping', {'db.system': 'redis'}):
|
||||
try:
|
||||
broker.ping()
|
||||
except redis.RedisError:
|
||||
fail(503, 'unavailable')
|
||||
return {'status': 'ok'}
|
||||
|
||||
@app.route('/api/v1/<path:path>', methods=['GET', 'POST', 'DELETE'])
|
||||
def api(path):
|
||||
if os.getenv('FAULT_HANDLER_DELAY_MS', '0') != '0' and path.endswith('/messages') and request.method == 'POST':
|
||||
time.sleep(int(os.getenv('FAULT_HANDLER_DELAY_MS', '0')) / 1000.0)
|
||||
public = (path in ('users', 'auth/sessions') and request.method == 'POST')
|
||||
if not public and not request.headers.get('Authorization', '').startswith('Bearer '):
|
||||
fail(401, 'unauthorized')
|
||||
with tel.span('db.pool.connect', {'db.system': 'postgresql'}):
|
||||
conn_cm = pool.connection()
|
||||
c = conn_cm.__enter__()
|
||||
exc_info = (None, None, None)
|
||||
try:
|
||||
if path == 'users' and request.method == 'POST':
|
||||
d = body(['username', 'display_name', 'password'])
|
||||
if not isinstance(d['username'], str) or not re.fullmatch('[a-z0-9_]{3,32}', d['username']): invalid()
|
||||
string(d['display_name'], 100); string(d['password'], 128, 12)
|
||||
row = db_exec(c, 'insert_user', 'INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(), d['username'], d['display_name'], kdf.hash(d['password']))).fetchone()
|
||||
return user(row), 201
|
||||
if path == 'auth/sessions' and request.method == 'POST':
|
||||
a = request.headers.get('Authorization', '')
|
||||
try:
|
||||
if not a.startswith('Basic ') or request.get_data(): raise ValueError()
|
||||
name, password = base64.b64decode(a[6:], validate=True).decode('utf-8').split(':', 1)
|
||||
except (ValueError, UnicodeError): fail(401, 'unauthorized')
|
||||
row = db_exec(c, 'select_user_by_name', 'SELECT * FROM users WHERE username=%s', (name,)).fetchone()
|
||||
try: valid = kdf.verify(row['password_hash'] if row else dummy, password)
|
||||
except VerificationError: valid = False
|
||||
if not valid or not row: fail(401, 'unauthorized')
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = db_exec(c, 'insert_session', "INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at", (hashlib.sha256(token.encode()).hexdigest(), row['id'], ttl)).fetchone()['expires_at']
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': expires.isoformat().replace('+00:00', 'Z'), 'user': user(row)}, 201
|
||||
who = actor(c)
|
||||
if path == 'auth/sessions/current' and request.method == 'DELETE':
|
||||
db_exec(c, 'delete_session', 'DELETE FROM sessions WHERE token_hash=%s', (g.digest,))
|
||||
return '', 204
|
||||
if path == 'users/me' and request.method == 'GET':
|
||||
return public_user(c, who)
|
||||
if path == 'chats':
|
||||
if request.method == 'POST':
|
||||
d = body(['title', 'member_ids']); string(d['title'], 100)
|
||||
ids = d['member_ids']
|
||||
if not isinstance(ids, list) or not 1 <= len(ids) <= 100: invalid()
|
||||
ids = [uid(x) for x in ids]
|
||||
if len(ids) != len(set(ids)) or str(who) not in ids: invalid()
|
||||
if db_exec(c, 'count_users', 'SELECT count(*) AS n FROM users WHERE id=ANY(%s::uuid[])', (ids,)).fetchone()['n'] != len(ids): invalid()
|
||||
ident = uuid.uuid4()
|
||||
db_exec(c, 'insert_chat', 'INSERT INTO chats(id,title) VALUES (%s,%s)', (ident, d['title']))
|
||||
for member in ids: db_exec(c, 'insert_member', 'INSERT INTO members VALUES (%s,%s)', (ident, member))
|
||||
return chat(c, ident, who), 201
|
||||
if request.method == 'GET':
|
||||
resource = 'chats:' + str(who); limit, pair = page_args(resource)
|
||||
query = 'SELECT c.id FROM chats c JOIN members m ON c.id=m.chat_id WHERE m.user_id=%s'
|
||||
params = [who]
|
||||
if pair: query += ' AND (c.created_at,c.id)>(%s,%s)'; params += list(pair)
|
||||
query += ' ORDER BY c.created_at,c.id LIMIT %s'; params += [limit + 1]
|
||||
return page([chat(c, x['id'], who) for x in db_exec(c, 'list_chats', query, params).fetchall()], limit, resource)
|
||||
parts = path.split('/')
|
||||
if len(parts) in (2, 3) and parts[0] == 'chats':
|
||||
ident = uid(parts[1])
|
||||
if len(parts) == 3 and parts[2] == 'messages' and os.getenv('MESSAGE_ACCESS_FAST', '1') == '1':
|
||||
if not db_exec(c, 'check_member', 'SELECT 1 FROM members WHERE chat_id=%s AND user_id=%s', (ident, who)).fetchone(): fail(404, 'not_found')
|
||||
result = None
|
||||
else:
|
||||
result = chat(c, ident, who)
|
||||
if len(parts) == 2 and request.method == 'GET': return result
|
||||
if len(parts) == 3 and parts[2] == 'messages':
|
||||
if request.method == 'POST':
|
||||
key = request.headers.get('Idempotency-Key', '')
|
||||
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key): invalid()
|
||||
if request.mimetype != 'application/json': fail(415, 'unsupported_media_type')
|
||||
try: d = request.get_json()
|
||||
except HTTPException: invalid()
|
||||
if not isinstance(d, dict) or set(d) - {'text', 'attachment_ids'} or 'text' not in d: invalid()
|
||||
if not isinstance(d['text'], str) or len(d['text']) > 4000: invalid()
|
||||
aids = d.get('attachment_ids', [])
|
||||
if not isinstance(aids, list) or len(aids) > 10: invalid()
|
||||
aids = [uid(x) for x in aids]
|
||||
if len(set(aids)) != len(aids): invalid()
|
||||
if not d['text'].strip() and not aids: invalid()
|
||||
if aids:
|
||||
found = db_exec(c, 'check_attachments', 'SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[])', (ident, aids)).fetchall()
|
||||
if len(found) != len(aids): fail(404, 'not_found')
|
||||
if any(x['status'] == 'failed' for x in found): fail(409, 'conflict')
|
||||
canonical = json.dumps({'text': d['text'], 'attachment_ids': aids}, sort_keys=True, ensure_ascii=False)
|
||||
scope = str(who) + ':POST:' + ident + ':' + key
|
||||
db_exec(c, 'advisory_lock', 'SELECT pg_advisory_xact_lock(hashtextextended(%s,0))', (scope,))
|
||||
old = db_exec(c, 'select_idempotency', 'SELECT body,response FROM idempotency WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (who, ident, key)).fetchone()
|
||||
if old:
|
||||
if old['body'] != canonical: fail(409, 'conflict')
|
||||
return old['response'], 201
|
||||
mid = uuid.uuid4()
|
||||
result = clean(db_exec(c, 'insert_message', 'INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (mid, ident, who, d['text'])).fetchone())
|
||||
result['attachment_ids'] = aids
|
||||
for pos, aid in enumerate(aids):
|
||||
db_exec(c, 'insert_msg_attachment', 'INSERT INTO message_attachments VALUES (%s,%s,%s)', (mid, aid, pos))
|
||||
db_exec(c, 'upsert_idempotency', "INSERT INTO idempotency(user_id,chat_id,key,body,response,expires_at) VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body=excluded.body,response=excluded.response,expires_at=excluded.expires_at", (who, ident, key, canonical, psycopg.types.json.Jsonb(result)))
|
||||
return result, 201
|
||||
if request.method == 'GET':
|
||||
limit, pair = page_args(ident)
|
||||
query = 'SELECT * FROM messages WHERE chat_id=%s'; params = [ident]
|
||||
if pair: query += ' AND (created_at,id)>(%s,%s)'; params += list(pair)
|
||||
query += ' ORDER BY created_at,id LIMIT %s'; params += [limit + 1]
|
||||
items = [clean(x) for x in db_exec(c, 'list_messages', query, params)]
|
||||
for m in items:
|
||||
m['attachment_ids'] = [str(x['attachment_id']) for x in db_exec(c, 'list_msg_attachments', 'SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (m['id'],))]
|
||||
return page(items, limit, ident)
|
||||
if len(parts) == 3 and parts[2] == 'attachments' and request.method == 'POST':
|
||||
backlog = db_exec(c, 'count_backlog', "SELECT count(*) AS n FROM attachment_jobs WHERE state IN ('pending','published','processing')").fetchone()['n']
|
||||
if backlog >= MAX_QUEUED: fail(503, 'unavailable')
|
||||
filename = request.args.get('filename', '')
|
||||
if len(filename) < 1 or len(filename) > 255 or any(ord(ch) < 32 or ch in '/\\' for ch in filename): invalid()
|
||||
if request.mimetype not in ('image/png', 'image/jpeg'): fail(415, 'unsupported_media_type')
|
||||
raw = request.get_data(cache=False)
|
||||
if not raw: invalid()
|
||||
try:
|
||||
im = Image.open(io.BytesIO(raw)); fmt = im.format; w, h = im.size
|
||||
if w * h > MAX_PIXELS: fail(413, 'payload_too_large')
|
||||
im.verify()
|
||||
except Problem: raise
|
||||
except (UnidentifiedImageError, OSError, ValueError): fail(415, 'unsupported_media_type')
|
||||
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(fmt)
|
||||
if actual != request.mimetype: fail(415, 'unsupported_media_type')
|
||||
ident_att = uuid.uuid4(); key = 'original/' + str(ident) + '/' + str(ident_att); staging = 'staging/' + str(ident) + '/' + str(ident_att)
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
carrier = tel.inject_context()
|
||||
try:
|
||||
with tel.span('s3.put_staging', {'storage.system': 's3', 'attachment.id': str(ident_att)}):
|
||||
s3.put_object(Bucket=bucket, Key=staging, Body=raw, ContentType=actual, Metadata={'sha256': digest})
|
||||
row = db_exec(c, 'insert_attachment', "INSERT INTO attachments(id,chat_id,owner_id,object_key,staging_key,filename,content_type,size_bytes,sha256,status) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *", (ident_att, ident, who, key, staging, filename, actual, len(raw), digest)).fetchone()
|
||||
job_id = uuid.uuid4()
|
||||
db_exec(c, 'insert_attachment_job', 'INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,traceparent,tracestate) VALUES (%s,%s,1,%s,%s)', (job_id, ident_att, carrier.get('traceparent'), carrier.get('tracestate')))
|
||||
tel.log(logging.INFO, 'attachment.queued', request_id=g.request_id, attachment_id=str(ident_att), job_id=str(job_id), size_bytes=len(raw))
|
||||
except Exception:
|
||||
try: s3.delete_object(Bucket=bucket, Key=staging)
|
||||
except Exception: tel.log(logging.WARNING, 'attachment.compensation_deferred', request_id=g.request_id, attachment_id=str(ident_att))
|
||||
if isinstance(__import__('sys').exc_info()[1], psycopg.Error): raise
|
||||
fail(503, 'unavailable')
|
||||
return attachment_json(row), 202
|
||||
if path.startswith('attachments/'):
|
||||
bits = path.split('/')
|
||||
if len(bits) not in (2, 3): fail(404, 'not_found')
|
||||
aid = uid(bits[1])
|
||||
row = db_exec(c, 'select_attachment', '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, who)).fetchone()
|
||||
if not row: fail(404, 'not_found')
|
||||
if len(bits) == 2 and request.method == 'GET': return attachment_json(row)
|
||||
if len(bits) == 3 and bits[2] == 'content' and request.method == 'GET':
|
||||
variant = request.args.get('variant', 'original')
|
||||
if variant not in ('original', 'thumbnail', 'crop', 'optimized'): invalid()
|
||||
if row['status'] != 'ready': fail(409, 'conflict')
|
||||
if variant != 'original':
|
||||
v = next((v for v in row['variants'] if v['name'] == variant), None)
|
||||
if v is None: fail(404, 'not_found')
|
||||
object_key = f'variants/v1/{aid}/{variant}'; content_type = v['content_type']
|
||||
else:
|
||||
object_key = row['object_key']; content_type = row['content_type']
|
||||
try:
|
||||
with tel.span('s3.get_object', {'storage.system': 's3', 'attachment.variant': variant}):
|
||||
obj = s3.get_object(Bucket=bucket, Key=object_key); data = obj['Body'].read(MAX_UPLOAD + 1)
|
||||
except Exception:
|
||||
fail(503, 'unavailable')
|
||||
if len(data) > MAX_UPLOAD or (variant == 'original' and hashlib.sha256(data).hexdigest() != row['sha256']): fail(503, 'unavailable')
|
||||
disposition = 'attachment; filename="attachment"; filename*=UTF-8\'\'' + quote(row['filename'], safe='')
|
||||
return app.response_class(data, 200, mimetype=content_type, headers={'Content-Disposition': disposition})
|
||||
fail(404, 'not_found')
|
||||
except BaseException as exc:
|
||||
exc_info = (type(exc), exc, exc.__traceback__)
|
||||
raise
|
||||
finally:
|
||||
conn_cm.__exit__(*exc_info)
|
||||
|
||||
def attachment_json(row):
|
||||
stamp = row['created_at'].isoformat().replace('+00:00', 'Z')
|
||||
return {
|
||||
'id': str(row['id']),
|
||||
'chat_id': str(row['chat_id']),
|
||||
'owner_id': str(row['owner_id']),
|
||||
'filename': row['filename'],
|
||||
'content_type': row['content_type'],
|
||||
'size_bytes': row['size_bytes'],
|
||||
'sha256': row['sha256'].strip(),
|
||||
'status': row['status'],
|
||||
'variants': row.get('variants', []),
|
||||
'error_code': row.get('error_code'),
|
||||
'created_at': stamp,
|
||||
'updated_at': row.get('updated_at', row['created_at']).isoformat().replace('+00:00', 'Z'),
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
|
||||
def setting(name):
|
||||
file = os.getenv(name + '_FILE')
|
||||
return Path(file).read_text().strip() if file else os.environ[name]
|
||||
|
||||
def migrate():
|
||||
with psycopg.connect(setting('DATABASE_URL'), connect_timeout=3) as c:
|
||||
c.execute('SELECT pg_advisory_xact_lock(202602)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
|
||||
for p in sorted(Path('migrations').glob('*.sql')):
|
||||
if not c.execute('SELECT 1 FROM schema_migrations WHERE version=%s',(p.name,)).fetchone():
|
||||
c.execute(p.read_text())
|
||||
c.execute('INSERT INTO schema_migrations(version) VALUES (%s)',(p.name,))
|
||||
if __name__ == '__main__':
|
||||
migrate()
|
||||
@@ -0,0 +1,196 @@
|
||||
"""OpenTelemetry setup for API and worker: traces, metrics, structured logs, W3C context."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
from opentelemetry import metrics, propagate, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.metrics import Observation
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
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 ALWAYS_OFF, ALWAYS_ON, ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
REDACTED_KEYS = {'password', 'token', 'authorization', 'secret', 'text', 'body', 'raw', 'signed_url', 'cookie'}
|
||||
|
||||
class JsonStdoutFormatter(logging.Formatter):
|
||||
def __init__(self, service_name, instance_id):
|
||||
super().__init__()
|
||||
self.service_name = service_name
|
||||
self.instance_id = instance_id
|
||||
|
||||
def format(self, record):
|
||||
payload = {
|
||||
'timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(record.created)),
|
||||
'severity': record.levelname,
|
||||
'service.name': self.service_name,
|
||||
'service.instance.id': self.instance_id,
|
||||
'event': getattr(record, 'event', record.getMessage()),
|
||||
}
|
||||
span = trace.get_current_span()
|
||||
ctx = span.get_span_context() if span else None
|
||||
if ctx and ctx.is_valid:
|
||||
payload['trace_id'] = format(ctx.trace_id, '032x')
|
||||
payload['span_id'] = format(ctx.span_id, '016x')
|
||||
attrs = getattr(record, 'otel_attrs', None)
|
||||
if isinstance(attrs, dict):
|
||||
for k, v in attrs.items():
|
||||
if k.lower() not in REDACTED_KEYS and v is not None:
|
||||
payload[k] = v
|
||||
return json.dumps(payload, ensure_ascii=False, separators=(',', ':'))
|
||||
|
||||
def _sampler_from_env():
|
||||
name = os.getenv('OTEL_TRACES_SAMPLER', 'always_on').strip().lower()
|
||||
arg_raw = os.getenv('OTEL_TRACES_SAMPLER_ARG', '1.0').strip()
|
||||
try:
|
||||
ratio = max(0.0, min(1.0, float(arg_raw)))
|
||||
except ValueError:
|
||||
ratio = 1.0
|
||||
if name == 'always_off':
|
||||
return ALWAYS_OFF
|
||||
if name == 'traceidratio':
|
||||
return TraceIdRatioBased(ratio)
|
||||
if name == 'parentbased_traceidratio':
|
||||
return ParentBased(TraceIdRatioBased(ratio))
|
||||
if name == 'parentbased_always_on':
|
||||
return ParentBased(ALWAYS_ON)
|
||||
return ALWAYS_ON
|
||||
|
||||
def _env_name():
|
||||
raw = os.getenv('OTEL_RESOURCE_ATTRIBUTES', 'deployment.environment.name=lab')
|
||||
for part in raw.split(','):
|
||||
if '=' in part:
|
||||
k, v = part.split('=', 1)
|
||||
if k.strip() == 'deployment.environment.name' and v.strip():
|
||||
return v.strip()
|
||||
return 'lab'
|
||||
|
||||
def _proc_rss_bytes():
|
||||
try:
|
||||
pages = int(Path('/proc/self/statm').read_text().split()[1])
|
||||
return pages * os.sysconf('SC_PAGE_SIZE')
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
class Telemetry:
|
||||
def __init__(self, service_name, instance_id):
|
||||
self.service_name = service_name
|
||||
self.instance_id = instance_id
|
||||
self.disabled = os.getenv('OTEL_SDK_DISABLED', 'false').strip().lower() in ('1', 'true', 'yes')
|
||||
self.logger = logging.getLogger('messenger.' + service_name)
|
||||
self.logger.handlers.clear()
|
||||
self.logger.setLevel(logging.INFO)
|
||||
self.logger.propagate = False
|
||||
|
||||
stdout_handler = logging.StreamHandler()
|
||||
stdout_handler.setFormatter(JsonStdoutFormatter(service_name, instance_id))
|
||||
self.logger.addHandler(stdout_handler)
|
||||
|
||||
logging.getLogger('opentelemetry').setLevel(logging.CRITICAL)
|
||||
logging.getLogger('urllib3').setLevel(logging.WARNING)
|
||||
|
||||
if not self.disabled:
|
||||
endpoint = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/')
|
||||
timeout = float(os.getenv('OTEL_EXPORT_TIMEOUT_SECONDS', '2.0'))
|
||||
interval_ms = int(os.getenv('OTEL_METRIC_EXPORT_INTERVAL', '5000'))
|
||||
resource = Resource.create({
|
||||
'service.name': service_name,
|
||||
'service.version': os.getenv('OTEL_SERVICE_VERSION', '1.6.0'),
|
||||
'service.instance.id': instance_id,
|
||||
'deployment.environment.name': _env_name(),
|
||||
})
|
||||
|
||||
tracer_provider = TracerProvider(resource=resource, sampler=_sampler_from_env())
|
||||
span_exporter = OTLPSpanExporter(endpoint=f'{endpoint}/v1/traces', timeout=timeout)
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
span_exporter,
|
||||
max_queue_size=1024,
|
||||
schedule_delay_millis=1000,
|
||||
max_export_batch_size=256,
|
||||
export_timeout_millis=int(timeout * 1000),
|
||||
)
|
||||
)
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
metric_exporter = OTLPMetricExporter(endpoint=f'{endpoint}/v1/metrics', timeout=timeout)
|
||||
reader = PeriodicExportingMetricReader(
|
||||
metric_exporter,
|
||||
export_interval_millis=interval_ms,
|
||||
export_timeout_millis=int(timeout * 1000),
|
||||
)
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
log_exporter = OTLPLogExporter(endpoint=f'{endpoint}/v1/logs', timeout=timeout)
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
log_exporter,
|
||||
max_queue_size=1024,
|
||||
schedule_delay_millis=1000,
|
||||
max_export_batch_size=256,
|
||||
export_timeout_millis=int(timeout * 1000),
|
||||
)
|
||||
)
|
||||
set_logger_provider(logger_provider)
|
||||
self.logger.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logger_provider))
|
||||
|
||||
self.tracer = trace.get_tracer(service_name, '1.6.0')
|
||||
self.meter = metrics.get_meter(service_name, '1.6.0')
|
||||
|
||||
self.meter.create_observable_counter(
|
||||
'process.cpu.time',
|
||||
callbacks=[lambda _opts: [Observation(time.process_time())]],
|
||||
unit='s',
|
||||
description='Process CPU time in seconds',
|
||||
)
|
||||
self.meter.create_observable_gauge(
|
||||
'process.memory.rss',
|
||||
callbacks=[lambda _opts: [Observation(_proc_rss_bytes())]],
|
||||
unit='By',
|
||||
description='Process resident set size in bytes',
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def span(self, name, attributes=None, kind=SpanKind.INTERNAL, context=None):
|
||||
with self.tracer.start_as_current_span(name, context=context, kind=kind, attributes=attributes or {}) as sp:
|
||||
try:
|
||||
yield sp
|
||||
except Exception as exc:
|
||||
sp.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
sp.record_exception(exc)
|
||||
raise
|
||||
|
||||
def log(self, level, event, **fields):
|
||||
safe = {k: v for k, v in fields.items() if k.lower() not in REDACTED_KEYS and v is not None}
|
||||
safe['event'] = event
|
||||
self.logger.log(level, event, extra={'event': event, 'otel_attrs': safe})
|
||||
|
||||
def inject_context(self):
|
||||
span = trace.get_current_span()
|
||||
ctx = span.get_span_context() if span else None
|
||||
if not ctx or not ctx.is_valid:
|
||||
return {}
|
||||
carrier = {}
|
||||
propagate.inject(carrier)
|
||||
return carrier
|
||||
|
||||
def extract_context(self, traceparent=None, tracestate=None):
|
||||
carrier = {}
|
||||
if traceparent:
|
||||
carrier['traceparent'] = traceparent
|
||||
if tracestate:
|
||||
carrier['tracestate'] = tracestate
|
||||
return propagate.extract(carrier) if carrier else None
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
"""Durable outbox relay and idempotent Redis Streams image worker with OpenTelemetry."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from opentelemetry.metrics import Observation
|
||||
from opentelemetry.trace import SpanKind
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
import redis
|
||||
|
||||
from app.migrate import setting
|
||||
from app.telemetry import Telemetry
|
||||
|
||||
def envsetting(name): return setting(name) if os.getenv(name + '_FILE') else os.environ[name]
|
||||
|
||||
db = ConnectionPool(setting('DATABASE_URL'), min_size=1, max_size=8, kwargs={'row_factory': dict_row, 'connect_timeout': 3})
|
||||
broker = redis.Redis.from_url(setting('BROKER_URL'), socket_connect_timeout=1, socket_timeout=2, decode_responses=True)
|
||||
s3 = boto3.client(
|
||||
's3',
|
||||
endpoint_url=os.getenv('S3_ENDPOINT', 'http://rustfs:9000'),
|
||||
region_name=os.getenv('S3_REGION', 'us-east-1'),
|
||||
aws_access_key_id=envsetting('S3_ACCESS_KEY_ID'),
|
||||
aws_secret_access_key=envsetting('S3_SECRET_ACCESS_KEY'),
|
||||
config=Config(connect_timeout=3, read_timeout=10, retries={'max_attempts': 2}),
|
||||
)
|
||||
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
stream = 'attachment-jobs'
|
||||
group = 'image-workers'
|
||||
attempts = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
|
||||
concurrency = int(os.getenv('WORKER_CONCURRENCY', '2'))
|
||||
timeout = int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))
|
||||
|
||||
instance = os.getenv('HOSTNAME', 'worker') + '-' + uuid.uuid4().hex[:8]
|
||||
tel = Telemetry('messenger-worker', instance)
|
||||
|
||||
jobs_counter = tel.meter.create_counter('worker.jobs', unit='1', description='Processed worker jobs')
|
||||
job_duration_hist = tel.meter.create_histogram(
|
||||
'worker.job.duration',
|
||||
unit='s',
|
||||
description='Worker job execution duration in seconds',
|
||||
explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
|
||||
)
|
||||
e2e_ready_hist = tel.meter.create_histogram(
|
||||
'attachment.time_to_ready',
|
||||
unit='s',
|
||||
description='End-to-end attachment time from durable acceptance to ready',
|
||||
explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0],
|
||||
)
|
||||
|
||||
_busy_lock = threading.Lock()
|
||||
_busy_threads = 0
|
||||
|
||||
def _threads_callback(_opts):
|
||||
with _busy_lock:
|
||||
busy = _busy_threads
|
||||
return [
|
||||
Observation(busy, {'state': 'busy'}),
|
||||
Observation(concurrency, {'state': 'capacity'}),
|
||||
]
|
||||
|
||||
def _queue_callbacks(_opts):
|
||||
counts = {'pending': 0, 'published': 0, 'processing': 0}
|
||||
try:
|
||||
with db.connection() as c:
|
||||
rows = c.execute(
|
||||
"SELECT state, count(*) AS n "
|
||||
"FROM attachment_jobs WHERE state IN ('pending','published','processing') GROUP BY state"
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
counts[r['state']] = int(r['n'])
|
||||
except Exception:
|
||||
return []
|
||||
return [Observation(v, {'queue_name': stream, 'state': k}) for k, v in counts.items()]
|
||||
|
||||
def _oldest_age_callback(_opts):
|
||||
try:
|
||||
with db.connection() as c:
|
||||
row = c.execute(
|
||||
"SELECT COALESCE(EXTRACT(EPOCH FROM (clock_timestamp() - min(created_at))), 0) AS age "
|
||||
"FROM attachment_jobs WHERE state IN ('pending','published','processing')"
|
||||
).fetchone()
|
||||
age = max(0.0, float(row['age'])) if row else 0.0
|
||||
return [Observation(age, {'queue_name': stream})]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
tel.meter.create_observable_gauge('worker.threads', callbacks=[_threads_callback], unit='', description='Worker thread saturation')
|
||||
tel.meter.create_observable_gauge('worker.queue.depth', callbacks=[_queue_callbacks], unit='', description='Queued jobs by state')
|
||||
tel.meter.create_observable_gauge('worker.oldest_job.age', callbacks=[_oldest_age_callback], unit='s', description='Age of oldest unfinished job in seconds')
|
||||
|
||||
try:
|
||||
broker.xgroup_create(stream, group, id='0', mkstream=True)
|
||||
except redis.ResponseError as e:
|
||||
if 'BUSYGROUP' not in str(e):
|
||||
raise
|
||||
|
||||
def publish_outbox():
|
||||
with db.connection() as c:
|
||||
rows = c.execute(
|
||||
"SELECT job_id,attachment_id,pipeline_version,attempt,created_at,traceparent,tracestate "
|
||||
"FROM attachment_jobs WHERE state IN ('pending','published') AND available_at<=clock_timestamp() "
|
||||
"ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED"
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
parent_ctx = tel.extract_context(r.get('traceparent'), r.get('tracestate'))
|
||||
with tel.span(
|
||||
'outbox.publish',
|
||||
attributes={
|
||||
'messaging.system': 'redis',
|
||||
'messaging.destination.name': stream,
|
||||
'messaging.operation.type': 'publish',
|
||||
'job.id': str(r['job_id']),
|
||||
'attachment.id': str(r['attachment_id']),
|
||||
},
|
||||
kind=SpanKind.PRODUCER,
|
||||
context=parent_ctx,
|
||||
):
|
||||
carrier = tel.inject_context()
|
||||
msg = {
|
||||
'schema_version': 1,
|
||||
'job_id': str(r['job_id']),
|
||||
'type': 'attachment.process.v1',
|
||||
'attachment_id': str(r['attachment_id']),
|
||||
'pipeline_version': r['pipeline_version'],
|
||||
'attempt': max(1, r['attempt'] + 1),
|
||||
'created_at': r['created_at'].isoformat().replace('+00:00', 'Z'),
|
||||
}
|
||||
if carrier.get('traceparent'):
|
||||
msg['traceparent'] = carrier['traceparent']
|
||||
if carrier.get('tracestate'):
|
||||
msg['tracestate'] = carrier['tracestate']
|
||||
broker.xadd(stream, {'job': json.dumps(msg, separators=(',', ':'))})
|
||||
c.execute("UPDATE attachment_jobs SET state='published',available_at=clock_timestamp()+interval '15 seconds' WHERE job_id=%s AND state IN ('pending','published')", (r['job_id'],))
|
||||
tel.log(logging.INFO, 'outbox.published', job_id=str(r['job_id']), attachment_id=str(r['attachment_id']))
|
||||
|
||||
def resize(raw):
|
||||
im = Image.open(io.BytesIO(raw)); im.load(); im = ImageOps.exif_transpose(im)
|
||||
if im.width * im.height > 40_000_000:
|
||||
raise ValueError('oversized_image')
|
||||
if im.mode in ('RGBA', 'LA') or 'transparency' in im.info:
|
||||
rgba = im.convert('RGBA'); bg = Image.new('RGBA', rgba.size, 'white'); bg.alpha_composite(rgba); im = bg.convert('RGB')
|
||||
else:
|
||||
im = im.convert('RGB')
|
||||
thumb = im.copy(); thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
out = io.BytesIO(); thumb.save(out, format='JPEG', quality=85, optimize=True)
|
||||
crop = ImageOps.fit(im, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)); cropout = io.BytesIO(); crop.save(cropout, format='JPEG', quality=85, optimize=True)
|
||||
opt = im.copy(); opt.thumbnail((1280, 1280), Image.Resampling.LANCZOS); webp = io.BytesIO(); opt.save(webp, format='WEBP', quality=82, method=4, exif=b'')
|
||||
return [
|
||||
('thumbnail', 'image/jpeg', thumb.size, out.getvalue()),
|
||||
('crop', 'image/jpeg', crop.size, cropout.getvalue()),
|
||||
('optimized', 'image/webp', opt.size, webp.getvalue()),
|
||||
]
|
||||
|
||||
def process(job):
|
||||
global _busy_threads
|
||||
jid = uuid.UUID(job['job_id']); aid = uuid.UUID(job['attachment_id'])
|
||||
parent_ctx = tel.extract_context(job.get('traceparent'), job.get('tracestate'))
|
||||
started = time.monotonic()
|
||||
outcome = 'noop'
|
||||
with _busy_lock:
|
||||
_busy_threads += 1
|
||||
try:
|
||||
with tel.span(
|
||||
'worker.process',
|
||||
attributes={
|
||||
'messaging.system': 'redis',
|
||||
'messaging.destination.name': stream,
|
||||
'messaging.operation.type': 'process',
|
||||
'job.id': str(jid),
|
||||
'job.type': job.get('type', 'attachment.process.v1'),
|
||||
'attachment.id': str(aid),
|
||||
},
|
||||
kind=SpanKind.CONSUMER,
|
||||
context=parent_ctx,
|
||||
) as sp:
|
||||
with tel.span('db.claim_job', {'db.system': 'postgresql'}):
|
||||
with db.connection() as c:
|
||||
c.execute('BEGIN')
|
||||
r = c.execute(
|
||||
'SELECT j.*, a.chat_id, a.owner_id, a.object_key, a.staging_key, a.content_type, a.sha256, a.status, a.created_at AS att_created_at '
|
||||
'FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s FOR UPDATE OF j,a',
|
||||
(jid,),
|
||||
).fetchone()
|
||||
if not r:
|
||||
c.rollback()
|
||||
return
|
||||
if r['state'] in ('done', 'failed') or (r['state'] == 'processing' and r['lease_until'] and r['lease_until'].timestamp() > time.time()):
|
||||
c.rollback()
|
||||
return
|
||||
c.execute("UPDATE attachment_jobs SET state='processing',attempt=attempt+1,lease_until=clock_timestamp()+(%s * interval '1 second') WHERE job_id=%s", (timeout, jid))
|
||||
c.execute("UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=%s AND status<>'ready'", (aid,))
|
||||
c.execute("INSERT INTO attachment_job_audit(job_id,event) VALUES (%s,'processing')", (jid,))
|
||||
c.commit()
|
||||
attempt_num = r['attempt'] + 1
|
||||
sp.set_attribute('job.attempt', attempt_num)
|
||||
tel.log(logging.INFO, 'worker.processing', job_id=str(jid), attachment_id=str(aid), attempt=attempt_num)
|
||||
try:
|
||||
with tel.span('s3.get_staging', {'storage.system': 's3'}):
|
||||
raw = s3.get_object(Bucket=bucket, Key=r['staging_key'])['Body'].read(10_485_761)
|
||||
if len(raw) > 10_485_760 or hashlib.sha256(raw).hexdigest() != r['sha256'].strip():
|
||||
raise ValueError('invalid_image')
|
||||
with tel.span('image.resize'):
|
||||
variants = resize(raw)
|
||||
with tel.span('s3.put_variants', {'storage.system': 's3'}):
|
||||
s3.put_object(Bucket=bucket, Key=r['object_key'], Body=raw, ContentType=r['content_type'], Metadata={'sha256': r['sha256'].strip()})
|
||||
meta = []
|
||||
for name, mime, size, data in variants:
|
||||
key = f'variants/v1/{aid}/{name}'
|
||||
s3.put_object(Bucket=bucket, Key=key, Body=data, ContentType=mime, Metadata={'pipeline-version': '1'})
|
||||
meta.append({'name': name, 'content_type': mime, 'size_bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'width': size[0], 'height': size[1]})
|
||||
if os.getenv('FAULT_AFTER_S3_WRITE_ONCE', '0') == '1':
|
||||
with db.connection() as c:
|
||||
seen = c.execute("SELECT 1 FROM attachment_job_audit WHERE job_id=%s AND event='fault_injected'", (jid,)).fetchone()
|
||||
if not seen:
|
||||
c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'fault_injected','crash after deterministic S3 writes, before ready commit')", (jid,))
|
||||
c.commit()
|
||||
os._exit(72)
|
||||
with tel.span('db.commit_ready', {'db.system': 'postgresql'}):
|
||||
with db.connection() as c:
|
||||
c.execute("UPDATE attachments SET status='ready',variants=%s::jsonb,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=1 AND status<>'ready'", (json.dumps(meta), aid))
|
||||
c.execute("UPDATE attachment_jobs SET state='done',lease_until=NULL,last_error=NULL WHERE job_id=%s", (jid,))
|
||||
c.execute("INSERT INTO attachment_job_audit(job_id,event) VALUES (%s,'ready')", (jid,))
|
||||
row_now = c.execute('SELECT clock_timestamp() AS now').fetchone()
|
||||
with tel.span('s3.delete_staging', {'storage.system': 's3'}):
|
||||
s3.delete_object(Bucket=bucket, Key=r['staging_key'])
|
||||
outcome = 'ready'
|
||||
e2e_sec = max(0.0, (row_now['now'] - r['att_created_at']).total_seconds())
|
||||
e2e_ready_hist.record(e2e_sec, {'pipeline_version': '1'})
|
||||
tel.log(logging.INFO, 'worker.ready', job_id=str(jid), attachment_id=str(aid), e2e_seconds=round(e2e_sec, 3))
|
||||
except (UnidentifiedImageError, ValueError) as exc:
|
||||
outcome = 'failed'
|
||||
retry_or_fail(jid, aid, 'invalid_image', True)
|
||||
sp.record_exception(exc)
|
||||
except Exception as exc:
|
||||
outcome = retry_or_fail(jid, aid, 'processing_failed', False)
|
||||
sp.record_exception(exc)
|
||||
finally:
|
||||
with _busy_lock:
|
||||
_busy_threads -= 1
|
||||
elapsed = time.monotonic() - started
|
||||
attrs = {'job.type': job.get('type', 'attachment.process.v1'), 'outcome': outcome}
|
||||
jobs_counter.add(1, attrs)
|
||||
job_duration_hist.record(elapsed, attrs)
|
||||
|
||||
def retry_or_fail(jid, aid, code, permanent):
|
||||
with db.connection() as c:
|
||||
r = c.execute('SELECT attempt,state FROM attachment_jobs WHERE job_id=%s', (jid,)).fetchone()
|
||||
if not r or r['state'] == 'done':
|
||||
return 'noop'
|
||||
n = r['attempt']
|
||||
if permanent or n >= attempts:
|
||||
c.execute("UPDATE attachment_jobs SET state='failed',lease_until=NULL,last_error=%s WHERE job_id=%s", (code, jid))
|
||||
c.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() WHERE id=%s", ('invalid_image' if permanent else 'retry_exhausted', aid))
|
||||
c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'failed',%s)", (jid, code))
|
||||
broker.xadd('attachment-jobs-dlq', {'job_id': str(jid), 'attachment_id': str(aid), 'error_code': code})
|
||||
tel.log(logging.ERROR, 'worker.failed', job_id=str(jid), attachment_id=str(aid), error_code=code, attempt=n)
|
||||
return 'failed'
|
||||
delay = min(60, 2 ** n) * (0.8 + random.random() * 0.4)
|
||||
c.execute("UPDATE attachment_jobs SET state='pending',available_at=clock_timestamp()+(%s * interval '1 second'),lease_until=NULL,last_error=%s WHERE job_id=%s", (delay, code, jid))
|
||||
c.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s", (aid,))
|
||||
tel.log(logging.WARNING, 'worker.retry', job_id=str(jid), attachment_id=str(aid), error_code=code, attempt=n, retry_delay_s=round(delay, 2))
|
||||
return 'retry'
|
||||
|
||||
def recover_leases():
|
||||
with db.connection() as c:
|
||||
expired = c.execute("SELECT job_id,attachment_id,attempt FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED").fetchall()
|
||||
for row in expired:
|
||||
if row['attempt'] >= attempts:
|
||||
c.execute("UPDATE attachment_jobs SET state='failed',lease_until=NULL,last_error='retry_exhausted' WHERE job_id=%s", (row['job_id'],))
|
||||
c.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=%s", (row['attachment_id'],))
|
||||
c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'failed','lease attempts exhausted')", (row['job_id'],))
|
||||
broker.xadd('attachment-jobs-dlq', {'job_id': str(row['job_id']), 'attachment_id': str(row['attachment_id']), 'error_code': 'retry_exhausted'})
|
||||
tel.log(logging.ERROR, 'worker.lease_exhausted', job_id=str(row['job_id']), attachment_id=str(row['attachment_id']))
|
||||
else:
|
||||
c.execute("UPDATE attachment_jobs SET state='pending',lease_until=NULL,available_at=clock_timestamp() WHERE job_id=%s", (row['job_id'],))
|
||||
tel.log(logging.WARNING, 'worker.lease_recovered', job_id=str(row['job_id']), attachment_id=str(row['attachment_id']))
|
||||
c.execute("UPDATE attachments a SET status='queued',updated_at=clock_timestamp() FROM attachment_jobs j WHERE j.attachment_id=a.id AND j.state='pending' AND a.status='processing'")
|
||||
|
||||
def main():
|
||||
consumer = f'worker-{uuid.uuid4()}'
|
||||
while True:
|
||||
try:
|
||||
recover_leases(); publish_outbox()
|
||||
if os.getenv('WORKER_PAUSE_CONSUME', '0') == '1':
|
||||
time.sleep(0.2); continue
|
||||
msgs = broker.xreadgroup(group, consumer, {stream: '>'}, count=concurrency, block=1000)
|
||||
claimed = broker.xautoclaim(stream, group, consumer, min_idle_time=timeout * 1000, start_id='0-0', count=concurrency)
|
||||
if claimed and claimed[1]:
|
||||
msgs.append((stream, claimed[1]))
|
||||
for _, entries in msgs:
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as executor:
|
||||
futures = []
|
||||
for mid, fields in entries:
|
||||
try:
|
||||
job = json.loads(fields['job'])
|
||||
except Exception:
|
||||
broker.xadd('attachment-jobs-dlq', {'message_id': mid, 'error_code': 'invalid_job'})
|
||||
broker.xack(stream, group, mid)
|
||||
continue
|
||||
futures.append((mid, executor.submit(process, job)))
|
||||
for mid, future in futures:
|
||||
try:
|
||||
future.result(); broker.xack(stream, group, mid)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user