ЛР6: наблюдаемость, сквозные traces и исследование sampling
This commit is contained in:
+127
@@ -0,0 +1,127 @@
|
||||
"""Explicit local operator tools; no administrative HTTP endpoint."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from pipeline import connect, audit
|
||||
from objects import Objects
|
||||
from postgres import setting
|
||||
|
||||
|
||||
def replay(job_id):
|
||||
with connect() as conn, conn.transaction():
|
||||
job = conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s FOR UPDATE', (job_id,)).fetchone()
|
||||
if job is None or job['state'] != 'failed':
|
||||
raise ValueError('Replay requires a failed job')
|
||||
attachment = conn.execute('SELECT * FROM attachments WHERE 1=1 AND current_job_id = %s FOR UPDATE', (job_id,)).fetchone()
|
||||
if attachment is None or attachment['state'] != 'failed' or Objects(setting).head(job['source_key']) is None:
|
||||
raise ValueError('Current failed source is unavailable')
|
||||
conn.execute('''
|
||||
UPDATE attachment_jobs
|
||||
SET state = 'queued'
|
||||
, max_attempts = attempt + %s
|
||||
, published_at = NULL
|
||||
, next_attempt_at = clock_timestamp()
|
||||
, error_code = NULL
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
''', (int(os.environ.get('JOB_MAX_ATTEMPTS', '5')), job_id))
|
||||
conn.execute("UPDATE attachments SET state = 'queued', error_code = NULL, updated_at = clock_timestamp() WHERE 1=1 AND current_job_id = %s", (job_id,))
|
||||
audit(conn, job, 'operator_replay')
|
||||
return {'job_id': str(job_id), 'replayed': True}
|
||||
|
||||
|
||||
def version(attachment_id, number):
|
||||
if number not in (1, 2):
|
||||
raise ValueError('Only implemented pipeline versions 1 and 2 are supported')
|
||||
with connect() as conn, conn.transaction():
|
||||
row = conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s FOR UPDATE', (attachment_id,)).fetchone()
|
||||
if row is None or number != row['pipeline_version'] + 1 or row['state'] in ('uploading', 'failed', 'storage_missing'):
|
||||
raise ValueError('Version must advance the current process exactly once')
|
||||
old = conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s FOR UPDATE', (row['current_job_id'],)).fetchone()
|
||||
source = row['object_key'] if row['state'] == 'ready' else old['source_key']
|
||||
if Objects(setting).head(source) is None:
|
||||
raise ValueError('Source unavailable')
|
||||
conn.execute("UPDATE attachment_jobs SET state = 'superseded', lease_token = NULL, lease_until = NULL WHERE 1=1 AND id = %s", (old['id'],))
|
||||
audit(conn, old, 'operator_supersede')
|
||||
job_id = uuid.uuid4()
|
||||
conn.execute('''
|
||||
INSERT INTO attachment_jobs (id, attachment_id, pipeline_version, source_key, max_attempts)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
''', (job_id, attachment_id, number, source, int(os.environ.get('JOB_MAX_ATTEMPTS', '5'))))
|
||||
conn.execute('''
|
||||
UPDATE attachments
|
||||
SET pipeline_version = %s
|
||||
, current_job_id = %s
|
||||
, state = 'queued'
|
||||
, variants = '[]'
|
||||
, error_code = NULL
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
''', (number, job_id, attachment_id))
|
||||
return {'job_id': str(job_id), 'version': number}
|
||||
|
||||
|
||||
def cleanup(apply=False, retention=86400):
|
||||
if retention < 86400:
|
||||
raise ValueError('Retention must be >=24 hours')
|
||||
objects = Objects(setting)
|
||||
counts = {'ready_staging': 0, 'expired_staging': 0}
|
||||
with connect() as conn:
|
||||
# Intent rows cover every valid staging PUT. Never collect active jobs.
|
||||
last = '00000000-0000-0000-0000-000000000000'
|
||||
while True:
|
||||
rows = conn.execute('SELECT id FROM attachments WHERE 1=1 AND id > %s ORDER BY id LIMIT 100', (last,)).fetchall()
|
||||
if not rows:
|
||||
break
|
||||
for candidate in rows:
|
||||
last = candidate['id']
|
||||
with conn.transaction():
|
||||
row = conn.execute('''
|
||||
SELECT *
|
||||
FROM attachments
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
AND (state = 'ready' OR (state IN ('uploading', 'failed') AND updated_at < clock_timestamp() - %s * INTERVAL '1 second'))
|
||||
FOR UPDATE SKIP LOCKED
|
||||
''', (last, retention)).fetchone()
|
||||
if row is None or not row['staging_key'] or not row['staging_key'].startswith('staging/'):
|
||||
continue
|
||||
counts['ready_staging' if row['state'] == 'ready' else 'expired_staging'] += 1
|
||||
if apply:
|
||||
objects.delete(row['staging_key'])
|
||||
if row['state'] == 'uploading' and row['current_job_id'] is None:
|
||||
conn.execute('DELETE FROM attachments WHERE 1=1 AND id = %s', (last,))
|
||||
else:
|
||||
conn.execute('UPDATE attachments SET staging_key = NULL WHERE 1=1 AND id = %s', (last,))
|
||||
return dict(apply=apply, retention_seconds=retention, counts=counts)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('action', choices=['failed', 'replay', 'version', 'cleanup'])
|
||||
p.add_argument('identifier', nargs='?')
|
||||
p.add_argument('--version', type=int)
|
||||
p.add_argument('--apply', action='store_true')
|
||||
args = p.parse_args()
|
||||
try:
|
||||
if args.action == 'failed':
|
||||
with connect() as conn:
|
||||
result = conn.execute("SELECT id, attachment_id, pipeline_version, attempt, max_attempts, error_code FROM attachment_jobs WHERE 1=1 AND state = 'failed' ORDER BY created_at LIMIT 100").fetchall()
|
||||
elif args.action == 'replay':
|
||||
result = replay(uuid.UUID(args.identifier))
|
||||
elif args.action == 'version':
|
||||
result = version(uuid.UUID(args.identifier), args.version)
|
||||
else:
|
||||
result = cleanup(args.apply)
|
||||
print(json.dumps(result, default=str, indent=2))
|
||||
except Exception:
|
||||
print(json.dumps({'error': 'Operator action refused or dependency unavailable; no secrets logged.'}))
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Idempotent private bucket bootstrap, executed only with administrative S3 keys."""
|
||||
from botocore.exceptions import ClientError
|
||||
from objects import Objects
|
||||
from postgres import setting
|
||||
|
||||
objects = Objects(setting)
|
||||
try:
|
||||
objects.client.create_bucket(Bucket=objects.bucket)
|
||||
except ClientError as exc:
|
||||
if exc.response['Error']['Code'] not in ('BucketAlreadyOwnedByYou', 'BucketAlreadyExists'):
|
||||
raise RuntimeError('Bucket bootstrap failed') from None
|
||||
objects.ready()
|
||||
print('Private bucket ready; static authenticated identities loaded from local secret config.')
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Shared HTTP contract; storage is supplied by each laboratory."""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, status, code, message):
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
def invalid():
|
||||
raise APIError(400, 'invalid_request', 'Неверные параметры запроса')
|
||||
|
||||
|
||||
def unauthorized():
|
||||
raise APIError(401, 'unauthorized', 'Требуется действительная идентификация')
|
||||
|
||||
|
||||
def missing():
|
||||
raise APIError(404, 'not_found', 'Объект не найден')
|
||||
|
||||
|
||||
def identifier(value):
|
||||
try:
|
||||
if not isinstance(value, str):
|
||||
invalid()
|
||||
return str(uuid.UUID(value))
|
||||
except ValueError:
|
||||
invalid()
|
||||
|
||||
|
||||
def text(value, maximum, minimum=1):
|
||||
if not isinstance(value, str) or not minimum <= len(value) <= maximum or not value.strip():
|
||||
invalid()
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeError:
|
||||
invalid()
|
||||
return value
|
||||
|
||||
|
||||
def fields(value, required):
|
||||
if not isinstance(value, dict) or set(value) != set(required):
|
||||
invalid()
|
||||
|
||||
|
||||
def username(value):
|
||||
if not isinstance(value, str) or not re.fullmatch(r'[a-z0-9_]{3,32}', value):
|
||||
invalid()
|
||||
return value
|
||||
|
||||
|
||||
def now():
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def page_args(query, scope):
|
||||
if set(query) - {'limit', 'cursor'} or any(len(v) != 1 for v in query.values()):
|
||||
invalid()
|
||||
limit = query.get('limit', ['50'])[0]
|
||||
if not re.fullmatch(r'[0-9]+', limit):
|
||||
invalid()
|
||||
try:
|
||||
limit = int(limit)
|
||||
except ValueError:
|
||||
invalid()
|
||||
if not 1 <= limit <= 100:
|
||||
invalid()
|
||||
cursor = None
|
||||
if 'cursor' in query:
|
||||
raw = query['cursor'][0]
|
||||
try:
|
||||
if not raw or len(raw) > 1024:
|
||||
invalid()
|
||||
decoded = json.loads(base64.b64decode(raw + '=' * (-len(raw) % 4), altchars=b'-_', validate=True))
|
||||
if not isinstance(decoded, list) or len(decoded) != 3 or decoded[0] != scope:
|
||||
invalid()
|
||||
stamp = decoded[1]
|
||||
if not isinstance(stamp, str) or not stamp.endswith('Z'):
|
||||
invalid()
|
||||
stamp = dt.datetime.fromisoformat(stamp[:-1] + '+00:00').isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
cursor = (stamp, identifier(decoded[2]))
|
||||
except (ValueError, TypeError, UnicodeError):
|
||||
invalid()
|
||||
return limit, cursor
|
||||
|
||||
|
||||
def page(items, limit, scope):
|
||||
more = len(items) > limit
|
||||
items = items[:limit]
|
||||
cursor = None
|
||||
if more:
|
||||
last = items[-1]
|
||||
cursor = base64.urlsafe_b64encode(json.dumps([scope, last['created_at'], last['id']]).encode()).decode().rstrip('=')
|
||||
return {'items': items, 'next_cursor': cursor}
|
||||
@@ -0,0 +1,13 @@
|
||||
"""One-shot migration job; replicas never execute DDL."""
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from postgres import setting
|
||||
|
||||
with psycopg.connect(setting('DATABASE_URL'), connect_timeout=5) as conn:
|
||||
conn.execute('SELECT pg_advisory_xact_lock(2301003)')
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY)')
|
||||
for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')):
|
||||
if not conn.execute('SELECT version FROM schema_migrations WHERE 1=1 AND version = %s', (path.name,)).fetchone():
|
||||
conn.execute(path.read_text())
|
||||
conn.execute('INSERT INTO schema_migrations (version) VALUES (%s)', (path.name,))
|
||||
print('Applied', path.name)
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
"""Bounded S3 operations. No root credentials or filename-derived object keys."""
|
||||
import contextlib
|
||||
import telemetry as tele
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
import warnings
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from PIL import Image, PngImagePlugin, UnidentifiedImageError
|
||||
|
||||
from common import APIError, invalid
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
PngImagePlugin.MAX_TEXT_CHUNK = 1024 * 1024
|
||||
PngImagePlugin.MAX_TEXT_MEMORY = 1024 * 1024
|
||||
warnings.filterwarnings('error', category=Image.DecompressionBombWarning)
|
||||
UPLOAD_SLOTS = threading.BoundedSemaphore(8)
|
||||
DECODE_SLOTS = threading.BoundedSemaphore(1)
|
||||
|
||||
|
||||
def unavailable():
|
||||
raise APIError(503, 'unavailable', 'Объектное хранилище временно недоступно')
|
||||
|
||||
|
||||
def filename(value):
|
||||
if not isinstance(value, str) or not 1 <= len(value) <= 255 or not value.strip():
|
||||
invalid()
|
||||
if any(c in '/\\' or unicodedata.category(c) == 'Cc' for c in value):
|
||||
invalid()
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeError:
|
||||
invalid()
|
||||
return value
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def bounded_upload():
|
||||
if not UPLOAD_SLOTS.acquire(blocking=False):
|
||||
raise APIError(503, 'unavailable', 'Все слоты загрузки заняты')
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
UPLOAD_SLOTS.release()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def receive(handler):
|
||||
lengths = handler.headers.get_all('Content-Length', [])
|
||||
if len(lengths) != 1 or handler.headers.get('Transfer-Encoding'):
|
||||
invalid()
|
||||
try:
|
||||
length = int(lengths[0])
|
||||
except ValueError:
|
||||
invalid()
|
||||
if length > MAX_BYTES:
|
||||
raise APIError(413, 'payload_too_large', 'Максимум 10 MiB')
|
||||
if length <= 0:
|
||||
invalid()
|
||||
mime = handler.headers.get_content_type()
|
||||
if mime not in ('image/png', 'image/jpeg'):
|
||||
raise APIError(415, 'unsupported_media_type', 'Требуется PNG или JPEG')
|
||||
deadline = time.monotonic() + 15
|
||||
digest = hashlib.sha256()
|
||||
# Ephemeral bounded spool is never a durable source of a confirmed attachment.
|
||||
with tempfile.TemporaryFile(mode='w+b') as source:
|
||||
remaining = length
|
||||
while remaining:
|
||||
handler.connection.settimeout(min(3, max(0.01, deadline - time.monotonic())))
|
||||
if time.monotonic() >= deadline:
|
||||
invalid()
|
||||
try:
|
||||
chunk = handler.rfile.read1(min(64 * 1024, remaining))
|
||||
except (OSError, TimeoutError):
|
||||
invalid()
|
||||
if not chunk:
|
||||
invalid()
|
||||
digest.update(chunk)
|
||||
source.write(chunk)
|
||||
remaining -= len(chunk)
|
||||
if not DECODE_SLOTS.acquire(timeout=10):
|
||||
raise APIError(503, 'unavailable', 'Проверка изображений перегружена')
|
||||
try:
|
||||
source.flush()
|
||||
for decode in (False,):
|
||||
source.seek(0)
|
||||
# Pillow.close releases pixel buffers and may close its input file.
|
||||
# A duplicate descriptor preserves the original for the S3 PUT.
|
||||
with os.fdopen(os.dup(source.fileno()), 'rb') as image_file:
|
||||
image = Image.open(image_file, formats=['PNG', 'JPEG'])
|
||||
try:
|
||||
if image.width * image.height > MAX_PIXELS:
|
||||
raise APIError(413, 'payload_too_large', 'Максимум 40 миллионов пикселей')
|
||||
if Image.MIME[image.format] != mime:
|
||||
raise APIError(415, 'unsupported_media_type', 'MIME не соответствует изображению')
|
||||
if decode:
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
finally:
|
||||
image.close() # Free pixels BEFORE releasing the decoder semaphore.
|
||||
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
|
||||
raise APIError(413, 'payload_too_large', 'Максимум 40 миллионов пикселей') from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise APIError(415, 'unsupported_media_type', 'Повреждённое изображение') from None
|
||||
finally:
|
||||
DECODE_SLOTS.release()
|
||||
source.seek(0)
|
||||
yield source, length, mime, digest.hexdigest()
|
||||
|
||||
|
||||
class Objects:
|
||||
def __init__(self, setting):
|
||||
self.bucket = os.environ.get('S3_BUCKET', 'messenger-attachments')
|
||||
self.client = boto3.client('s3', endpoint_url=os.environ.get('S3_ENDPOINT', 'http://s3:8333'), region_name='us-east-1', aws_access_key_id=setting('S3_ACCESS_KEY_ID'), aws_secret_access_key=setting('S3_SECRET_ACCESS_KEY'), config=Config(signature_version='s3v4', s3={'addressing_style': 'path'}, connect_timeout=1, read_timeout=3, max_pool_connections=16, retries={'total_max_attempts': 1}, request_checksum_calculation='when_required', response_checksum_validation='when_required'))
|
||||
self.client = tele.S3Client(self.client)
|
||||
|
||||
def head(self, key):
|
||||
try:
|
||||
return self.client.head_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response['Error']['Code'] in ('404', 'NoSuchKey', 'NotFound'):
|
||||
return None
|
||||
unavailable()
|
||||
except BotoCoreError:
|
||||
unavailable()
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
except (ClientError, BotoCoreError):
|
||||
unavailable()
|
||||
|
||||
def put(self, key, source, length, mime, digest):
|
||||
try:
|
||||
self.client.put_object(Bucket=self.bucket, Key=key, Body=source, ContentLength=length, ContentType=mime, Metadata={'sha256': digest})
|
||||
except (ClientError, BotoCoreError):
|
||||
unavailable()
|
||||
|
||||
def get(self, key):
|
||||
try:
|
||||
return self.client.get_object(Bucket=self.bucket, Key=key)
|
||||
except (ClientError, BotoCoreError):
|
||||
unavailable()
|
||||
|
||||
def delete(self, key):
|
||||
try:
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
except (ClientError, BotoCoreError):
|
||||
unavailable()
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
"""Durable outbox, Redis Streams delivery, bounded worker and fenced result commits."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import contextlib
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import telemetry as tele
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
import redis
|
||||
from botocore.exceptions import ClientError, BotoCoreError
|
||||
from common import APIError
|
||||
from objects import Objects, MAX_BYTES
|
||||
from postgres import setting
|
||||
|
||||
STREAM, GROUP = 'attachment-jobs', 'image-workers'
|
||||
LEASE = int(os.environ.get('JOB_LEASE_SECONDS', '60'))
|
||||
STOP = threading.Event()
|
||||
|
||||
|
||||
def raw_connect():
|
||||
return psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row, autocommit=True, connect_timeout=2, options='-c statement_timeout=2000 -c lock_timeout=1500')
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def connect():
|
||||
with tele.span('db.transaction', {'db.system':'postgresql'}, tele.SpanKind.CLIENT):
|
||||
with raw_connect() as connection:
|
||||
yield connection
|
||||
|
||||
|
||||
def broker():
|
||||
client = redis.Redis.from_url(setting('BROKER_URL'), decode_responses=True, socket_connect_timeout=1, socket_timeout=3)
|
||||
try:
|
||||
client.xgroup_create(STREAM, GROUP, id='0', mkstream=True)
|
||||
except redis.ResponseError as error:
|
||||
if 'BUSYGROUP' not in str(error):
|
||||
raise
|
||||
return client
|
||||
|
||||
|
||||
def event(job):
|
||||
return {'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['attempt'] + 1, 'created_at': job['created_at'].isoformat().replace('+00:00', 'Z'), **(job.get('trace_context') or {})}
|
||||
|
||||
|
||||
def validate(message):
|
||||
required = {'schema_version', 'job_id', 'type', 'attachment_id', 'pipeline_version', 'attempt', 'created_at'}
|
||||
if not isinstance(message, dict) or set(message) - required - {'traceparent', 'tracestate'} or not required <= set(message):
|
||||
return False
|
||||
try:
|
||||
uuid.UUID(message['job_id']); uuid.UUID(message['attachment_id'])
|
||||
stamp = dt.datetime.fromisoformat(message['created_at'].replace('Z', '+00:00'))
|
||||
if stamp.tzinfo is None or not message['created_at'].endswith('Z'):
|
||||
return False
|
||||
if 'traceparent' in message and (not isinstance(message['traceparent'], str) or not re.fullmatch(r'00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}', message['traceparent'])):
|
||||
return False
|
||||
if 'tracestate' in message and (not isinstance(message['tracestate'], str) or len(message['tracestate']) > 512):
|
||||
return False
|
||||
return type(message['schema_version']) is int and message['schema_version'] == 1 and message['type'] == 'attachment.process.v1' and all(type(message[k]) is int and message[k] >= 1 for k in ['pipeline_version', 'attempt'])
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def audit(conn, job, name):
|
||||
conn.execute('INSERT INTO job_events (job_id, event, attempt) VALUES (%s, %s, %s)', (job['id'], name, job['attempt']))
|
||||
|
||||
|
||||
def retry(conn, job, code, permanent=False):
|
||||
failed = permanent or job['attempt'] >= job['max_attempts']
|
||||
state = 'failed' if failed else 'queued'
|
||||
code = code if permanent or not failed else 'retry_exhausted'
|
||||
delay = min(8, .5 * 2 ** min(job['attempt'] - 1, 4)) + random.uniform(0, .5)
|
||||
conn.execute('''
|
||||
UPDATE attachment_jobs
|
||||
SET state = %s
|
||||
, error_code = %s
|
||||
, lease_token = NULL
|
||||
, lease_until = NULL
|
||||
, published_at = NULL
|
||||
, next_attempt_at = clock_timestamp() + %s * INTERVAL '1 second'
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
''', (state, code, delay, job['id']))
|
||||
conn.execute('''
|
||||
UPDATE attachments
|
||||
SET state = %s
|
||||
, error_code = %s
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND current_job_id = %s
|
||||
''', (state, code if failed else None, job['id']))
|
||||
audit(conn, job, 'failed:' + code if failed else 'retry:' + code)
|
||||
tele.count('job_retries', {'job_type':'image', 'outcome':'failed' if failed else 'retry'})
|
||||
tele.log('job_failed' if failed else 'job_retry', job_id=str(job['id']), attempt=job['attempt'], error_code=code)
|
||||
|
||||
|
||||
def dispatch_once(client, fault=None):
|
||||
with connect() as conn:
|
||||
with conn.transaction():
|
||||
expired = conn.execute("SELECT * FROM attachment_jobs WHERE 1=1 AND state = 'processing' AND lease_until < clock_timestamp() FOR UPDATE SKIP LOCKED LIMIT 20").fetchall()
|
||||
for job in expired:
|
||||
retry(conn, job, 'lease_expired')
|
||||
with conn.transaction():
|
||||
jobs = conn.execute('''
|
||||
SELECT j.*
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.current_job_id = j.id
|
||||
WHERE 1=1
|
||||
AND j.state = 'queued'
|
||||
AND j.next_attempt_at <= clock_timestamp()
|
||||
AND (j.published_at IS NULL OR j.published_at < clock_timestamp() - %s * INTERVAL '1 second')
|
||||
ORDER BY j.created_at
|
||||
LIMIT 10
|
||||
FOR UPDATE OF j SKIP LOCKED
|
||||
''', (LEASE,)).fetchall()
|
||||
for job in jobs:
|
||||
with tele.span('attachment publish', {'messaging.system':'redis', 'messaging.destination.name':STREAM},
|
||||
tele.SpanKind.PRODUCER, job.get('trace_context') or {}):
|
||||
message = event(job)
|
||||
message.update(tele.carrier())
|
||||
client.xadd(STREAM, {'event': json.dumps(message, separators=(',', ':'))})
|
||||
tele.log('job_published', job_id=str(job['id']), attempt=job['attempt']+1)
|
||||
if fault:
|
||||
fault('after_publish', job)
|
||||
conn.execute('UPDATE attachment_jobs SET published_at = clock_timestamp() WHERE 1=1 AND id = %s', (job['id'],))
|
||||
audit(conn, job, 'published')
|
||||
return len(jobs)
|
||||
|
||||
|
||||
def claim(message):
|
||||
with connect() as conn, conn.transaction():
|
||||
job = conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s FOR UPDATE', (message['job_id'],)).fetchone()
|
||||
if job is None:
|
||||
return None
|
||||
attachment = conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s FOR UPDATE', (job['attachment_id'],)).fetchone()
|
||||
if str(job['attachment_id']) != message['attachment_id'] or job['pipeline_version'] != message['pipeline_version']:
|
||||
return None
|
||||
if attachment['current_job_id'] != job['id'] or attachment['pipeline_version'] != job['pipeline_version']:
|
||||
audit(conn, job, 'stale_noop')
|
||||
return None
|
||||
if job['state'] in ('ready', 'failed', 'superseded'):
|
||||
audit(conn, job, 'terminal_noop')
|
||||
return None
|
||||
if job['state'] != 'queued' or job['next_attempt_at'] > dt.datetime.now(dt.timezone.utc) or message['attempt'] != job['attempt'] + 1:
|
||||
audit(conn, job, 'duplicate_or_early_noop')
|
||||
return None
|
||||
token = uuid.uuid4()
|
||||
job = conn.execute('''
|
||||
UPDATE attachment_jobs
|
||||
SET state = 'processing'
|
||||
, attempt = attempt + 1
|
||||
, lease_token = %s
|
||||
, lease_until = clock_timestamp() + %s * INTERVAL '1 second'
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
RETURNING *
|
||||
''', (token, LEASE, job['id'])).fetchone()
|
||||
conn.execute("UPDATE attachments SET state = 'processing', updated_at = clock_timestamp() WHERE 1=1 AND current_job_id = %s", (job['id'],))
|
||||
audit(conn, job, 'claimed')
|
||||
return job, attachment
|
||||
|
||||
|
||||
class Permanent(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def immutable(objects, key, path, mime, sha):
|
||||
head = objects.head(key)
|
||||
if head is not None:
|
||||
if head['ContentLength'] != path.stat().st_size or head.get('Metadata', {}).get('sha256') != sha:
|
||||
raise Permanent('result_conflict')
|
||||
return
|
||||
try:
|
||||
with path.open('rb') as source:
|
||||
objects.client.put_object(Bucket=objects.bucket, Key=key, Body=source, ContentLength=path.stat().st_size, ContentType=mime, Metadata={'sha256': sha}, IfNoneMatch='*')
|
||||
except ClientError as error:
|
||||
if error.response['ResponseMetadata']['HTTPStatusCode'] in (409, 412):
|
||||
head = objects.head(key)
|
||||
if head and head['ContentLength'] == path.stat().st_size and head.get('Metadata', {}).get('sha256') == sha:
|
||||
return
|
||||
raise
|
||||
|
||||
|
||||
def process_core(message, fault=None):
|
||||
claimed = claim(message)
|
||||
if claimed is None:
|
||||
return 'noop'
|
||||
job, attachment = claimed
|
||||
objects = Objects(setting)
|
||||
try:
|
||||
if fault:
|
||||
fault('before_side_effect', job)
|
||||
with tempfile.TemporaryDirectory(prefix='job-') as temporary:
|
||||
directory = Path(temporary)
|
||||
source = directory / 'original'
|
||||
head = objects.head(job['source_key'])
|
||||
if head is None:
|
||||
raise Permanent('source_missing')
|
||||
response = objects.get(job['source_key'])
|
||||
digest, size = hashlib.sha256(), 0
|
||||
deadline = time.monotonic() + 15
|
||||
with response['Body'] as stream, source.open('wb') as out:
|
||||
for chunk in iter(lambda: stream.read(64 * 1024), b''):
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES or time.monotonic() > deadline:
|
||||
raise Permanent('invalid_image')
|
||||
digest.update(chunk); out.write(chunk)
|
||||
if size != attachment['size_bytes'] or digest.hexdigest() != attachment['sha256']:
|
||||
raise Permanent('checksum_mismatch')
|
||||
result = subprocess.run([sys.executable, str(Path(__file__).with_name('render.py')), str(source), str(directory), str(job['pipeline_version'])], capture_output=True, timeout=int(os.environ.get('JOB_TIMEOUT_SECONDS', '20')))
|
||||
if result.returncode == 2:
|
||||
raise Permanent('invalid_image')
|
||||
if result.returncode:
|
||||
raise RuntimeError('render_failed')
|
||||
variants = json.loads(result.stdout)
|
||||
prefix = 'results/' + str(attachment['id']) + '/v' + str(job['pipeline_version']) + '/'
|
||||
original_key = prefix + 'original'
|
||||
immutable(objects, original_key, source, attachment['content_type'], attachment['sha256'])
|
||||
if fault:
|
||||
fault('after_original', job)
|
||||
for variant in variants:
|
||||
variant['object_key'] = prefix + variant['name']
|
||||
immutable(objects, variant['object_key'], directory / variant['name'], variant['content_type'], variant['sha256'])
|
||||
if fault:
|
||||
fault('after_objects', job)
|
||||
with connect() as conn, conn.transaction():
|
||||
current = conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s FOR UPDATE', (job['id'],)).fetchone()
|
||||
changed = conn.execute('''
|
||||
UPDATE attachments
|
||||
SET state = 'ready'
|
||||
, object_key = %s
|
||||
, variants = %s
|
||||
, error_code = NULL
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND current_job_id = %s
|
||||
AND pipeline_version = %s
|
||||
AND %s
|
||||
RETURNING id
|
||||
''', (original_key, Jsonb(variants), job['id'], job['pipeline_version'], current['state'] == 'processing' and current['lease_token'] == job['lease_token'] and current['lease_until'] > dt.datetime.now(dt.timezone.utc))).fetchone()
|
||||
if changed:
|
||||
conn.execute("UPDATE attachment_jobs SET state = 'ready', error_code = NULL, lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() WHERE 1=1 AND id = %s", (job['id'],))
|
||||
audit(conn, job, 'ready')
|
||||
else:
|
||||
audit(conn, job, 'fenced_noop')
|
||||
if fault:
|
||||
fault('after_commit', job)
|
||||
if changed and job['source_key'].startswith('staging/'):
|
||||
objects.delete(job['source_key'])
|
||||
if changed:
|
||||
tele.duration('job_ready_duration', (dt.datetime.now(dt.timezone.utc)-job['created_at']).total_seconds(), {'job_type':'image'})
|
||||
return 'ready' if changed else 'fenced'
|
||||
except Exception as error:
|
||||
code = str(error) if isinstance(error, Permanent) else 'processing_timeout' if isinstance(error, subprocess.TimeoutExpired) else 'storage_unavailable' if isinstance(error, (APIError, ClientError, BotoCoreError)) else 'processing_failed'
|
||||
with connect() as conn, conn.transaction():
|
||||
current = conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s FOR UPDATE', (job['id'],)).fetchone()
|
||||
if current['state'] == 'processing' and current['lease_token'] == job['lease_token']:
|
||||
retry(conn, current, code, isinstance(error, Permanent))
|
||||
return 'failed_or_retry'
|
||||
finally:
|
||||
objects.client.close()
|
||||
|
||||
|
||||
def process(message, fault=None):
|
||||
started = time.monotonic()
|
||||
with tele.span('attachment process', {'messaging.system':'redis', 'messaging.destination.name':STREAM,
|
||||
'job.id':message['job_id'], 'job.attempt':message['attempt']},
|
||||
tele.SpanKind.CONSUMER, message):
|
||||
with tele.LOCK:
|
||||
tele.STATE['worker_busy'] += 1
|
||||
outcome = 'error'
|
||||
try:
|
||||
outcome = process_core(message, fault)
|
||||
if outcome == 'failed_or_retry':
|
||||
tele.trace.get_current_span().set_status(tele.Status(tele.StatusCode.ERROR))
|
||||
return outcome
|
||||
finally:
|
||||
with tele.LOCK:
|
||||
tele.STATE['worker_busy'] -= 1
|
||||
attributes = {'job_type':'image', 'outcome':outcome}
|
||||
tele.count('jobs_processed', attributes)
|
||||
tele.duration('job_processing_duration', time.monotonic()-started, attributes)
|
||||
tele.log('job_processed', job_id=message['job_id'], attempt=message['attempt'], outcome=outcome)
|
||||
|
||||
|
||||
def observe_queue():
|
||||
try:
|
||||
with raw_connect() as conn:
|
||||
row = conn.execute("""
|
||||
SELECT
|
||||
count(*) AS depth
|
||||
, coalesce(extract(epoch FROM clock_timestamp() - min(created_at)), 0) AS age
|
||||
FROM attachment_jobs
|
||||
WHERE 1=1
|
||||
AND state IN ('queued', 'processing')
|
||||
""").fetchone()
|
||||
tele.STATE.update(queue_depth=row['depth'], queue_oldest_age=float(row['age']), queue_observation_ok=1)
|
||||
except psycopg.Error:
|
||||
tele.STATE['queue_observation_ok'] = 0
|
||||
|
||||
|
||||
def ack(client, identifier):
|
||||
# Atomic ack+delete; PostgreSQL is the durable completion/replay registry.
|
||||
client.eval("redis.call('XACK',KEYS[1],ARGV[1],ARGV[2]); return redis.call('XDEL',KEYS[1],ARGV[2])", 1, STREAM, GROUP, identifier)
|
||||
|
||||
|
||||
def consume(once=False, fault=None):
|
||||
client = broker()
|
||||
consumer = uuid.uuid4().hex
|
||||
while not STOP.is_set():
|
||||
messages = []
|
||||
try:
|
||||
pending = client.xautoclaim(STREAM, GROUP, consumer, min_idle_time=LEASE * 1000, start_id='0-0', count=1)[1]
|
||||
if pending:
|
||||
messages = pending
|
||||
else:
|
||||
batches = client.xreadgroup(GROUP, consumer, {STREAM: '>'}, count=1, block=500)
|
||||
messages = batches[0][1] if batches else []
|
||||
for identifier, fields in messages:
|
||||
raw = fields.get('event', '')
|
||||
try:
|
||||
message = json.loads(raw) if len(raw) <= 4096 else None
|
||||
except ValueError:
|
||||
message = None
|
||||
if validate(message):
|
||||
process(message, fault)
|
||||
else:
|
||||
client.xadd('rejected-jobs', {'source_message_id': identifier, 'sha256': hashlib.sha256(raw.encode()).hexdigest(), 'reason': 'invalid_envelope'}, maxlen=1000, approximate=False)
|
||||
ack(client, identifier)
|
||||
if once:
|
||||
return
|
||||
except (redis.RedisError, psycopg.Error):
|
||||
STOP.wait(.5)
|
||||
if once and not messages:
|
||||
return
|
||||
client.close()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('mode', choices=['dispatch', 'work'])
|
||||
parser.add_argument('--once', action='store_true')
|
||||
parser.add_argument('--fault-point', choices=['before_side_effect', 'after_original', 'after_objects', 'after_commit', 'after_publish'])
|
||||
args = parser.parse_args()
|
||||
tele.configure('messenger-dispatcher' if args.mode=='dispatch' else 'messenger-worker')
|
||||
# Operator-only opt-in injection; no request header or public endpoint controls it.
|
||||
def fault(point, job):
|
||||
if point == args.fault_point:
|
||||
os._exit(77)
|
||||
signal.signal(signal.SIGTERM, lambda *_: STOP.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: STOP.set())
|
||||
if args.mode == 'dispatch':
|
||||
client = broker()
|
||||
while not STOP.is_set():
|
||||
observe_queue()
|
||||
try:
|
||||
dispatch_once(client, fault)
|
||||
except (redis.RedisError, psycopg.Error):
|
||||
pass
|
||||
if args.once:
|
||||
break
|
||||
STOP.wait(.2)
|
||||
else:
|
||||
count = int(os.environ.get('WORKER_CONCURRENCY', '1'))
|
||||
if not 1 <= count <= 2:
|
||||
raise ValueError('WORKER_CONCURRENCY must be 1..2')
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool:
|
||||
futures = [pool.submit(consume, args.once, fault) for _ in range(count)]
|
||||
for result in futures:
|
||||
result.result()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
finally:
|
||||
tele.shutdown()
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
import base64
|
||||
import contextlib
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import threading
|
||||
import uuid
|
||||
import telemetry as tele
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
import redis
|
||||
|
||||
from objects import Objects, unavailable
|
||||
|
||||
from common import APIError, fields, identifier, invalid, missing, page, text, unauthorized, username
|
||||
|
||||
KDF_SLOTS = threading.BoundedSemaphore(2)
|
||||
|
||||
|
||||
def setting(name):
|
||||
path = os.environ.get(name + '_FILE')
|
||||
return Path(path).read_text().strip() if path else os.environ[name]
|
||||
|
||||
|
||||
def public(row):
|
||||
return {k: (v.decode('utf-8') if isinstance(v, bytes) else [str(x) for x in v] if isinstance(v, list) else str(v) if isinstance(v, uuid.UUID) else v.isoformat(timespec='microseconds').replace('+00:00', 'Z') if isinstance(v, dt.datetime) else v) for k, v in row.items() if k != 'password_hash'}
|
||||
|
||||
|
||||
def password_hash(password, salt=None):
|
||||
salt = salt or secrets.token_bytes(16)
|
||||
if not KDF_SLOTS.acquire(timeout=1.5):
|
||||
raise APIError(503, 'unavailable', 'Аутентификация временно перегружена')
|
||||
try:
|
||||
digest = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=16384, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024)
|
||||
finally:
|
||||
KDF_SLOTS.release()
|
||||
return 'scrypt$16384$8$1$' + salt.hex() + '$' + digest.hex()
|
||||
|
||||
|
||||
class Store:
|
||||
persistent = True
|
||||
|
||||
def __init__(self):
|
||||
self.ttl = int(os.environ.get('SESSION_TTL_SECONDS', '3600'))
|
||||
if not 1 <= self.ttl <= 86400:
|
||||
raise ValueError('SESSION_TTL_SECONDS must be 1..86400')
|
||||
self.access_mode = os.environ.get('DB_ACCESS_MODE', 'optimized')
|
||||
if self.access_mode not in ('baseline', 'optimized'):
|
||||
raise ValueError('DB_ACCESS_MODE must be baseline or optimized')
|
||||
pool_size = int(os.environ.get('DB_POOL_MAX', '8'))
|
||||
if not 1 <= pool_size <= 32:
|
||||
raise ValueError('DB_POOL_MAX must be 1..32')
|
||||
self.pool = ConnectionPool(setting('DATABASE_URL'), min_size=1, max_size=pool_size, timeout=2, kwargs={'row_factory': dict_row, 'connect_timeout': 2, 'options': '-c statement_timeout=2000 -c lock_timeout=1500'}, open=True)
|
||||
self.pool.wait(timeout=10)
|
||||
tele.pool(self.pool)
|
||||
self.cache = redis.Redis.from_url(setting('CACHE_URL'), socket_connect_timeout=0.15, socket_timeout=0.15, decode_responses=True)
|
||||
self.objects = Objects(setting)
|
||||
self.dummy_hash = password_hash('dummy-password-for-unknown-users')
|
||||
with self.connection() as conn:
|
||||
if not conn.execute("SELECT version FROM schema_migrations WHERE 1=1 AND version = '006_observability.sql'").fetchone():
|
||||
raise RuntimeError('Run the separate migration service first')
|
||||
|
||||
@contextlib.contextmanager
|
||||
def connection(self):
|
||||
try:
|
||||
with tele.span('db.transaction', {'db.system':'postgresql'}, tele.SpanKind.CLIENT):
|
||||
with self.pool.connection() as conn:
|
||||
yield conn
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise APIError(409, 'conflict', 'Имя пользователя занято') from None
|
||||
except (psycopg.Error, PoolTimeout):
|
||||
raise APIError(503, 'unavailable', 'Хранилище временно недоступно') from None
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
self.cache.close()
|
||||
self.objects.client.close()
|
||||
|
||||
def ready(self):
|
||||
self.objects.ready()
|
||||
with self.connection() as conn:
|
||||
conn.execute('SELECT 1')
|
||||
|
||||
def register(self, body):
|
||||
fields(body, ('username', 'display_name', 'password'))
|
||||
name, display = username(body['username']), text(body['display_name'], 100)
|
||||
# Passwords may contain spaces and colons; only length/UTF-8 are restricted.
|
||||
password = body['password']
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
invalid()
|
||||
try:
|
||||
password.encode('utf-8')
|
||||
except UnicodeError:
|
||||
invalid()
|
||||
hashed = password_hash(password)
|
||||
with self.connection() as conn:
|
||||
row = conn.execute('''
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
''', (uuid.uuid4(), name, display.encode('utf-8'), hashed)).fetchone()
|
||||
return public(row)
|
||||
|
||||
def login(self, headers):
|
||||
authorization = headers.get('Authorization', '')
|
||||
try:
|
||||
scheme, encoded = authorization.split(' ', 1)
|
||||
if scheme.lower() != 'basic':
|
||||
unauthorized()
|
||||
name, password = base64.b64decode(encoded, validate=True).decode('utf-8').split(':', 1)
|
||||
except (ValueError, UnicodeError):
|
||||
unauthorized()
|
||||
if not re_username(name) or not 12 <= len(password) <= 128:
|
||||
unauthorized()
|
||||
with self.connection() as conn:
|
||||
row = conn.execute('SELECT id, username, display_name, created_at, password_hash FROM users WHERE 1=1 AND username = %s', (name,)).fetchone()
|
||||
hashed = row['password_hash'] if row else self.dummy_hash
|
||||
verified = hmac.compare_digest(password_hash(password, bytes.fromhex(hashed.split('$')[4])), hashed)
|
||||
if row is None or not verified:
|
||||
unauthorized()
|
||||
token = secrets.token_urlsafe(32)
|
||||
with self.connection() as conn:
|
||||
expiry = conn.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(), row['id'], self.ttl)).fetchone()['expires_at']
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': public({'expires_at': expiry})['expires_at'], 'user': public(row)}
|
||||
|
||||
def token_hash(self, headers):
|
||||
parts = headers.get('Authorization', '').split(' ')
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer' or len(parts[1]) != 43 or not parts[1].isascii():
|
||||
unauthorized()
|
||||
return hashlib.sha256(parts[1].encode()).hexdigest()
|
||||
|
||||
def authenticate(self, headers):
|
||||
token_hash = self.token_hash(headers)
|
||||
with self.connection() as conn:
|
||||
session = conn.execute('''
|
||||
SELECT user_id
|
||||
FROM sessions
|
||||
WHERE 1=1
|
||||
AND token_hash = %s
|
||||
AND expires_at > clock_timestamp()
|
||||
''', (token_hash,)).fetchone()
|
||||
if session is None:
|
||||
unauthorized()
|
||||
key = 'user:' + str(session['user_id'])
|
||||
try:
|
||||
cached = self.cache.get(key)
|
||||
if cached:
|
||||
return json.loads(cached)
|
||||
except (redis.RedisError, ValueError):
|
||||
pass
|
||||
row = conn.execute('SELECT id, username, display_name, created_at FROM users WHERE 1=1 AND id = %s', (session['user_id'],)).fetchone()
|
||||
if row is None:
|
||||
unauthorized()
|
||||
user = public(row)
|
||||
try:
|
||||
self.cache.setex(key, 60, json.dumps(user))
|
||||
except redis.RedisError:
|
||||
pass
|
||||
return user
|
||||
|
||||
def logout(self, headers):
|
||||
with self.connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE 1=1 AND token_hash = %s', (self.token_hash(headers),))
|
||||
|
||||
def chat_in(self, conn, actor, chat_id):
|
||||
row = conn.execute('''
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE 1=1
|
||||
AND c.id = %s
|
||||
AND cm.user_id = %s
|
||||
''', (chat_id, actor['id'])).fetchone()
|
||||
if row is None:
|
||||
missing()
|
||||
members = conn.execute('SELECT user_id FROM chat_members WHERE 1=1 AND chat_id = %s ORDER BY user_id', (chat_id,)).fetchall()
|
||||
return dict(public(row), member_ids=[str(v['user_id']) for v in members])
|
||||
|
||||
def chat(self, actor, chat_id):
|
||||
with self.connection() as conn:
|
||||
return self.chat_in(conn, actor, chat_id)
|
||||
|
||||
def create_chat(self, actor, body):
|
||||
fields(body, ('title', 'member_ids'))
|
||||
title = text(body['title'], 100)
|
||||
members = body['member_ids']
|
||||
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
||||
invalid()
|
||||
members = [identifier(v) for v in members]
|
||||
if len(set(members)) != len(members) or actor['id'] not in members:
|
||||
invalid()
|
||||
with self.connection() as conn:
|
||||
chat_id = uuid.uuid4()
|
||||
conn.execute('INSERT INTO chats (id, title) VALUES (%s, %s)', (chat_id, title.encode('utf-8')))
|
||||
# Checking after INSERT exercises rollback of the whole composite operation.
|
||||
found = conn.execute('SELECT id FROM users WHERE 1=1 AND id = ANY(%s::uuid[])', (members,)).fetchall()
|
||||
if len(found) != len(members):
|
||||
invalid()
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany('INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)', [(chat_id, v) for v in members])
|
||||
return self.chat_in(conn, actor, chat_id)
|
||||
|
||||
def list_chats(self, actor, limit, cursor, scope):
|
||||
with self.connection() as conn:
|
||||
where = 'AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)' if cursor else ''
|
||||
params = [actor['id']] + list(cursor or ()) + [limit + 1]
|
||||
rows = conn.execute('''
|
||||
SELECT c.id
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE 1=1
|
||||
AND cm.user_id = %s
|
||||
''' + where + '''
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
''', params).fetchall()
|
||||
return page([self.chat_in(conn, actor, v['id']) for v in rows], limit, scope)
|
||||
|
||||
def require_member(self, conn, actor, chat_id):
|
||||
if self.access_mode == 'baseline':
|
||||
return self.chat_in(conn, actor, chat_id)
|
||||
if not conn.execute('''
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE 1=1
|
||||
AND chat_id = %s
|
||||
AND user_id = %s
|
||||
''', (chat_id, actor['id'])).fetchone():
|
||||
missing()
|
||||
|
||||
def send(self, actor, chat_id, body, key):
|
||||
if not isinstance(key, str) or not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
|
||||
invalid()
|
||||
if not isinstance(body, dict) or set(body) - {'text', 'attachment_ids'} or 'text' not in body:
|
||||
invalid()
|
||||
attachments = body.get('attachment_ids', [])
|
||||
if not isinstance(attachments, list) or len(attachments) > 10:
|
||||
invalid()
|
||||
attachments = [identifier(v) for v in attachments]
|
||||
if len(set(attachments)) != len(attachments):
|
||||
invalid()
|
||||
content = body['text']
|
||||
if not isinstance(content, str) or len(content) > 4000 or (not attachments and not content.strip()):
|
||||
invalid()
|
||||
try:
|
||||
content.encode('utf-8')
|
||||
except UnicodeError:
|
||||
invalid()
|
||||
canonical = json.dumps({'text': content, 'attachment_ids': attachments}, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
digest = hashlib.sha256(canonical.encode('utf-8')).hexdigest()
|
||||
with self.connection() as conn:
|
||||
self.require_member(conn, actor, chat_id)
|
||||
# The unique key arbitrates concurrent processes; everything commits together.
|
||||
claimed = conn.execute('''
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, expires_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp() + INTERVAL '24 hours')
|
||||
ON CONFLICT (user_id, chat_id, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash
|
||||
, message_id = NULL
|
||||
, expires_at = EXCLUDED.expires_at
|
||||
WHERE 1=1
|
||||
AND idempotency_keys.expires_at <= clock_timestamp()
|
||||
RETURNING request_hash
|
||||
''', (actor['id'], chat_id, key, digest)).fetchone()
|
||||
if claimed is None:
|
||||
previous = conn.execute('''
|
||||
SELECT ik.request_hash
|
||||
, m.id
|
||||
, m.chat_id
|
||||
, m.sender_id
|
||||
, m.text
|
||||
, m.created_at
|
||||
, m.attachment_ids
|
||||
FROM idempotency_keys ik
|
||||
JOIN messages m ON m.id = ik.message_id
|
||||
WHERE 1=1
|
||||
AND ik.user_id = %s
|
||||
AND ik.chat_id = %s
|
||||
AND ik.key = %s
|
||||
''', (actor['id'], chat_id, key)).fetchone()
|
||||
if previous['request_hash'] != digest:
|
||||
raise APIError(409, 'conflict', 'Ключ уже использован для другого сообщения')
|
||||
previous.pop('request_hash')
|
||||
return public(previous)
|
||||
if attachments:
|
||||
rows = conn.execute('''
|
||||
SELECT id, state
|
||||
FROM attachments
|
||||
WHERE 1=1
|
||||
AND id = ANY(%s::uuid[])
|
||||
AND chat_id = %s
|
||||
ORDER BY id
|
||||
FOR SHARE
|
||||
''', (attachments, chat_id)).fetchall()
|
||||
if len(rows) != len(attachments):
|
||||
missing()
|
||||
if any(v['state'] not in ('ready', 'queued', 'processing') for v in rows):
|
||||
raise APIError(409, 'conflict', 'Вложение ещё не готово')
|
||||
# Per-chat row lock preserves committed history order across replicas/clocks.
|
||||
stamp = conn.execute('''
|
||||
UPDATE chats
|
||||
SET last_message_at = GREATEST(clock_timestamp(), last_message_at + INTERVAL '1 microsecond')
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
RETURNING last_message_at
|
||||
''', (chat_id,)).fetchone()['last_message_at']
|
||||
row = conn.execute('''
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids)
|
||||
VALUES (%s, %s, %s, %s, %s, %s::uuid[])
|
||||
RETURNING id, chat_id, sender_id, text, created_at, attachment_ids
|
||||
''', (uuid.uuid4(), chat_id, actor['id'], content.encode('utf-8'), stamp, attachments)).fetchone()
|
||||
if attachments:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany('INSERT INTO message_attachments (message_id, attachment_id) VALUES (%s, %s)', [(row['id'], v) for v in attachments])
|
||||
conn.execute('''
|
||||
UPDATE idempotency_keys
|
||||
SET message_id = %s
|
||||
WHERE 1=1
|
||||
AND user_id = %s
|
||||
AND chat_id = %s
|
||||
AND key = %s
|
||||
''', (row['id'], actor['id'], chat_id, key))
|
||||
return public(row)
|
||||
|
||||
def history(self, actor, chat_id, limit, cursor, scope):
|
||||
with self.connection() as conn:
|
||||
self.require_member(conn, actor, chat_id)
|
||||
where = 'AND (created_at, id) > (%s::timestamptz, %s::uuid)' if cursor else ''
|
||||
params = [chat_id] + list(cursor or ()) + [limit + 1]
|
||||
rows = conn.execute('''
|
||||
SELECT id, chat_id, sender_id, text, created_at, attachment_ids
|
||||
FROM messages
|
||||
WHERE 1=1
|
||||
AND chat_id = %s
|
||||
''' + where + '''
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
''', params).fetchall()
|
||||
return page([public(v) for v in rows], limit, scope)
|
||||
|
||||
def upload(self, actor, chat_id, name, source, length, mime, digest):
|
||||
attachment_id, job_id = uuid.uuid4(), uuid.uuid4()
|
||||
key = 'staging/' + str(attachment_id)
|
||||
with self.connection() as conn:
|
||||
self.require_member(conn, actor, chat_id)
|
||||
conn.execute('SELECT pg_advisory_xact_lock(2301005)')
|
||||
pending = conn.execute("SELECT count(*) AS n FROM attachments WHERE 1=1 AND state IN ('uploading', 'queued', 'processing')").fetchone()['n']
|
||||
if pending >= int(os.environ.get('MAX_PENDING_JOBS', '100')):
|
||||
raise APIError(503, 'unavailable', 'Очередь принятых работ заполнена')
|
||||
conn.execute('''
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, staging_key, content_type, size_bytes, sha256, state)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'uploading')
|
||||
''', (attachment_id, chat_id, actor['id'], name, 'results/' + str(attachment_id) + '/v1/original', key, mime, length, digest))
|
||||
with self.connection() as conn:
|
||||
if conn.execute('SELECT id FROM attachments WHERE 1=1 AND id = %s FOR UPDATE', (attachment_id,)).fetchone() is None:
|
||||
unavailable()
|
||||
self.objects.put(key, source, length, mime, digest)
|
||||
conn.execute('''
|
||||
INSERT INTO attachment_jobs (id, attachment_id, pipeline_version, source_key, max_attempts, trace_context)
|
||||
VALUES (%s, %s, 1, %s, %s, %s)
|
||||
''', (job_id, attachment_id, key, int(os.environ.get('JOB_MAX_ATTEMPTS', '5')), Jsonb(tele.carrier())))
|
||||
row = conn.execute('''
|
||||
UPDATE attachments
|
||||
SET state = 'queued'
|
||||
, current_job_id = %s
|
||||
, updated_at = clock_timestamp()
|
||||
WHERE 1=1
|
||||
AND id = %s
|
||||
RETURNING *
|
||||
''', (job_id, attachment_id)).fetchone()
|
||||
tele.log('attachment_accepted', attachment_id=str(attachment_id), job_id=str(job_id))
|
||||
# Capture the queued snapshot, even if the worker finishes before HTTP reply.
|
||||
return self.attachment_public(row)
|
||||
|
||||
def attachment_public(self, row):
|
||||
keys = ('id', 'chat_id', 'owner_id', 'filename', 'content_type', 'size_bytes', 'sha256', 'created_at', 'updated_at')
|
||||
result = public({k: row[k] for k in keys})
|
||||
variants = [{k: v for k, v in item.items() if k != 'object_key'} for item in row['variants']]
|
||||
return dict(result, status=row['state'], variants=variants, error_code=row['error_code'])
|
||||
|
||||
def attachment(self, actor, attachment_id):
|
||||
with self.connection() as conn:
|
||||
row = conn.execute('''
|
||||
SELECT a.*
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id
|
||||
WHERE 1=1
|
||||
AND a.id = %s
|
||||
AND cm.user_id = %s
|
||||
''', (attachment_id, actor['id'])).fetchone()
|
||||
if row is None:
|
||||
missing()
|
||||
if row['state'] == 'storage_missing':
|
||||
unavailable()
|
||||
if row['state'] == 'uploading':
|
||||
raise APIError(409, 'conflict', 'Приём не завершён')
|
||||
return row
|
||||
|
||||
|
||||
def re_username(value):
|
||||
import re
|
||||
return re.fullmatch(r'[a-z0-9_]{3,32}', value)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Isolated image decoder/resizer; no network, database or credentials."""
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (15, 16))
|
||||
from PIL import Image, ImageOps, PngImagePlugin
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
PngImagePlugin.MAX_TEXT_CHUNK = PngImagePlugin.MAX_TEXT_MEMORY = 1024 * 1024
|
||||
warnings.filterwarnings('error', category=Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def render(source, directory, version):
|
||||
output = []
|
||||
with Image.open(source, formats=['PNG', 'JPEG']) as image:
|
||||
if image.width * image.height > 40_000_000:
|
||||
raise ValueError('pixels')
|
||||
image.load()
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
rgba = None
|
||||
if image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info):
|
||||
rgba = image if image.mode == 'RGBA' else image.convert('RGBA')
|
||||
rgb = Image.new('RGB', rgba.size, 'white')
|
||||
alpha = rgba.getchannel('A')
|
||||
rgb.paste(rgba, mask=alpha)
|
||||
alpha.close()
|
||||
else:
|
||||
rgb = image if image.mode == 'RGB' else image.convert('RGB')
|
||||
try:
|
||||
for name, bound, fmt, quality in [('thumbnail', 256, 'JPEG', 85), ('crop', 128, 'JPEG', 85), ('optimized', 1280, 'WEBP', 82 if version == 1 else 70)]:
|
||||
if name == 'crop':
|
||||
result = ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS, centering=(.5, .5))
|
||||
else:
|
||||
scale = min(1, bound / max(rgb.size))
|
||||
size = tuple(max(1, math.floor(v * scale)) for v in rgb.size)
|
||||
result = rgb.resize(size, Image.Resampling.LANCZOS)
|
||||
try:
|
||||
path = directory / name
|
||||
options = {'quality': quality, 'exif': b'', 'icc_profile': None}
|
||||
if fmt == 'WEBP':
|
||||
options['method'] = 4
|
||||
result.save(path, format=fmt, **options)
|
||||
raw = path.read_bytes()
|
||||
output.append({'name': name, 'width': result.width, 'height': result.height, 'content_type': 'image/jpeg' if fmt == 'JPEG' else 'image/webp', 'size_bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()})
|
||||
finally:
|
||||
result.close()
|
||||
finally:
|
||||
if rgb is not image:
|
||||
rgb.close()
|
||||
if rgba is not None and rgba is not image:
|
||||
rgba.close()
|
||||
return output
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
print(json.dumps(render(sys.argv[1], Path(sys.argv[2]), int(sys.argv[3]))))
|
||||
except (OSError, ValueError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise SystemExit(2)
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
"""Bounded threaded API; persistent correctness state is shared across replicas."""
|
||||
import concurrent.futures
|
||||
import contextlib
|
||||
import http.server
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import signal
|
||||
import socket
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from objects import bounded_upload, receive, filename, unavailable
|
||||
|
||||
import telemetry as tele
|
||||
|
||||
from common import APIError, identifier, invalid, missing, page_args
|
||||
|
||||
LOG = logging.getLogger('messenger')
|
||||
|
||||
|
||||
def unique_object(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
invalid()
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(3)
|
||||
|
||||
def send_error(self, code, message=None, explain=None):
|
||||
# BaseHTTPRequestHandler otherwise emits HTML without contract headers.
|
||||
self.request_id = uuid.uuid4().hex
|
||||
self.route = ''
|
||||
self.close_connection = True
|
||||
status = 413 if code == 413 else 400
|
||||
self.reply(status, {'error': {'code': 'payload_too_large' if status == 413 else 'invalid_request', 'message': 'Некорректный HTTP-запрос', 'request_id': self.request_id}})
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def reply(self, status, body):
|
||||
if status == 200 and isinstance(body, tuple):
|
||||
return self.download(*body)
|
||||
raw = b'' if status == 204 else json.dumps(body, ensure_ascii=False, allow_nan=False).encode('utf-8')
|
||||
if status >= 400:
|
||||
self.close_connection = True
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(raw)))
|
||||
if self.close_connection:
|
||||
self.send_header('Connection', 'close')
|
||||
self.send_header('X-Request-Id', self.request_id)
|
||||
self.send_header('X-Instance-Id', self.server.instance_id)
|
||||
if status == 401 and self.server.store.persistent:
|
||||
self.send_header('WWW-Authenticate', 'Basic realm="messenger", charset="UTF-8"' if self.route == '/api/v1/auth/sessions' else 'Bearer realm="messenger"')
|
||||
self.end_headers()
|
||||
if self.command != 'HEAD':
|
||||
self.wfile.write(raw)
|
||||
|
||||
def download(self, row, response, chunk):
|
||||
stream = response['Body']
|
||||
try:
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', row['content_type'])
|
||||
self.send_header('Content-Length', str(row['size_bytes']))
|
||||
self.send_header('X-Request-Id', self.request_id)
|
||||
self.send_header('X-Instance-Id', self.server.instance_id)
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
self.send_header('Cache-Control', 'private, no-store')
|
||||
self.end_headers()
|
||||
deadline = time.monotonic() + 15
|
||||
while chunk:
|
||||
self.wfile.write(chunk)
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError()
|
||||
chunk = stream.read(64 * 1024)
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
def body(self):
|
||||
lengths = self.headers.get_all('Content-Length', [])
|
||||
if len(lengths) != 1 or self.headers.get('Transfer-Encoding'):
|
||||
invalid()
|
||||
try:
|
||||
length = int(lengths[0])
|
||||
except ValueError:
|
||||
invalid()
|
||||
if length > 32768:
|
||||
raise APIError(413, 'payload_too_large', 'Максимальный JSON — 32768 байт')
|
||||
if length <= 0:
|
||||
invalid()
|
||||
if self.headers.get_content_type() != 'application/json':
|
||||
raise APIError(415, 'unsupported_media_type', 'Требуется application/json')
|
||||
try:
|
||||
raw = self.rfile.read(length)
|
||||
if len(raw) != length:
|
||||
invalid()
|
||||
return json.loads(raw.decode('utf-8'), object_pairs_hook=unique_object, parse_constant=lambda _: invalid())
|
||||
except (ValueError, UnicodeError, RecursionError):
|
||||
invalid()
|
||||
|
||||
def dispatch(self):
|
||||
self.request_id = uuid.uuid4().hex
|
||||
self.route = urlsplit(self.path).path
|
||||
template = tele.route(self.route)
|
||||
method = self.command if self.command in ('GET','POST','DELETE','PUT','PATCH','HEAD','OPTIONS') else 'OTHER'
|
||||
attrs = {'method':method, 'route':template}
|
||||
started = time.monotonic()
|
||||
context = tele.span(method+' '+template, {'http.request.method':method, 'http.route':template},
|
||||
tele.SpanKind.SERVER, {k:self.headers[k] for k in ('traceparent','tracestate') if k in self.headers})
|
||||
# Health probes do not enter business telemetry or create noisy dependency spans.
|
||||
if template.startswith('/health/'):
|
||||
context = tele.suppressed()
|
||||
status = 500
|
||||
with context as current:
|
||||
try:
|
||||
status, result = self.route_request()
|
||||
except APIError as exc:
|
||||
status = exc.status
|
||||
result = {'error': {'code': exc.code, 'message': exc.message, 'request_id': self.request_id}}
|
||||
except Exception:
|
||||
result = {'error': {'code': 'internal_error', 'message': 'Внутренняя ошибка', 'request_id': self.request_id}}
|
||||
try:
|
||||
self.reply(status, result)
|
||||
except (BrokenPipeError, ConnectionResetError, TimeoutError, OSError):
|
||||
self.close_connection = True
|
||||
if not template.startswith('/health/'):
|
||||
attrs['status_class'] = str(status//100)+'xx'
|
||||
tele.count('http_server_requests', attrs)
|
||||
tele.duration('http_server_duration', time.monotonic()-started, attrs)
|
||||
if current is not None:
|
||||
current.set_attribute('http.response.status_code', status)
|
||||
if status >= 500:
|
||||
current.set_status(tele.Status(tele.StatusCode.ERROR))
|
||||
tele.log('http_request', request_id=self.request_id, method=method, route=template, status=status, duration_seconds=round(time.monotonic()-started,6))
|
||||
|
||||
def route_request(self):
|
||||
method, path, store = self.command, self.route, self.server.store
|
||||
if method == 'GET' and path in ('/health/live', '/health/ready'):
|
||||
if path.endswith('ready'):
|
||||
store.ready()
|
||||
return 200, {'status': 'ok'}
|
||||
if method == 'POST' and path == '/api/v1/users':
|
||||
return 201, store.register(self.body())
|
||||
if store.persistent and method == 'POST' and path == '/api/v1/auth/sessions':
|
||||
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Length', '0') != '0':
|
||||
invalid()
|
||||
return 201, store.login(self.headers)
|
||||
actor = store.authenticate(self.headers)
|
||||
if store.persistent and method == 'DELETE' and path == '/api/v1/auth/sessions/current':
|
||||
store.logout(self.headers)
|
||||
return 204, None
|
||||
if method == 'GET' and path == '/api/v1/users/me':
|
||||
return 200, actor
|
||||
query = parse_qs(urlsplit(self.path).query, keep_blank_values=True)
|
||||
if path == '/api/v1/chats':
|
||||
if method == 'POST':
|
||||
return 201, store.create_chat(actor, self.body())
|
||||
if method == 'GET':
|
||||
scope = 'chats:' + actor['id']
|
||||
limit, cursor = page_args(query, scope)
|
||||
return 200, store.list_chats(actor, limit, cursor, scope)
|
||||
parts = path.split('/')
|
||||
if len(parts) in (5, 6) and parts[1:4] == ['api', 'v1', 'attachments'] and method == 'GET':
|
||||
row = store.attachment(actor, identifier(parts[4]))
|
||||
if len(parts) == 5:
|
||||
if query:
|
||||
invalid()
|
||||
return 200, store.attachment_public(row)
|
||||
if parts[5] == 'content':
|
||||
if set(query) - {'variant'} or any(len(v) != 1 for v in query.values()):
|
||||
invalid()
|
||||
if row['state'] != 'ready':
|
||||
raise APIError(409, 'conflict', 'Вложение ещё не готово')
|
||||
variant = query.get('variant', ['original'])[0]
|
||||
if variant != 'original':
|
||||
item = next((v for v in row['variants'] if v['name'] == variant), None)
|
||||
if item is None:
|
||||
missing()
|
||||
row = dict(row, object_key=item['object_key'], content_type=item['content_type'], size_bytes=item['size_bytes'])
|
||||
response = store.objects.get(row['object_key'])
|
||||
try:
|
||||
chunk = response['Body'].read(64 * 1024)
|
||||
if response['ContentLength'] != row['size_bytes'] or not chunk:
|
||||
unavailable()
|
||||
except Exception:
|
||||
response['Body'].close()
|
||||
unavailable()
|
||||
return 200, (row, response, chunk)
|
||||
if len(parts) in (5, 6) and parts[1:4] == ['api', 'v1', 'chats']:
|
||||
chat_id = identifier(parts[4])
|
||||
if store.access_mode == 'baseline':
|
||||
store.chat(actor, chat_id)
|
||||
if len(parts) == 5 and method == 'GET':
|
||||
return 200, store.chat(actor, chat_id)
|
||||
if len(parts) == 6 and parts[5] == 'attachments' and method == 'POST':
|
||||
store.chat(actor, chat_id)
|
||||
if set(query) != {'filename'} or len(query['filename']) != 1:
|
||||
invalid()
|
||||
name = filename(query['filename'][0])
|
||||
with bounded_upload():
|
||||
with receive(self) as (source, length, mime, digest):
|
||||
return 202, store.upload(actor, chat_id, name, source, length, mime, digest)
|
||||
if len(parts) == 6 and parts[5] == 'messages':
|
||||
if method == 'POST':
|
||||
keys = self.headers.get_all('Idempotency-Key', [])
|
||||
return 201, store.send(actor, chat_id, self.body(), keys[0] if len(keys) == 1 else None)
|
||||
if method == 'GET':
|
||||
scope = 'messages:' + chat_id
|
||||
limit, cursor = page_args(query, scope)
|
||||
return 200, store.history(actor, chat_id, limit, cursor, scope)
|
||||
missing()
|
||||
|
||||
do_GET = do_POST = do_DELETE = do_PUT = do_PATCH = do_OPTIONS = dispatch
|
||||
|
||||
|
||||
class Server(http.server.HTTPServer):
|
||||
request_queue_size = 64
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, address, store):
|
||||
self.store = store
|
||||
self.instance_id = tele.INSTANCE
|
||||
workers = int(os.environ.get('HTTP_WORKERS', '16'))
|
||||
if not 1 <= workers <= 128:
|
||||
raise ValueError('HTTP_WORKERS must be 1..128')
|
||||
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
|
||||
self.slots = threading.BoundedSemaphore(workers * 2)
|
||||
self.connections = set()
|
||||
self.connections_lock = threading.Lock()
|
||||
super().__init__(address, Handler)
|
||||
|
||||
def process_request(self, request, address):
|
||||
if not self.slots.acquire(blocking=False):
|
||||
rid = uuid.uuid4().hex
|
||||
raw = json.dumps({'error': {'code': 'unavailable', 'message': 'Очередь запросов заполнена', 'request_id': rid}}).encode()
|
||||
try:
|
||||
request.settimeout(0.2)
|
||||
request.sendall(('HTTP/1.0 503 Service Unavailable\r\nContent-Type: application/json\r\nX-Instance-Id: ' + self.instance_id + '\r\nX-Request-Id: ' + rid + '\r\nContent-Length: ' + str(len(raw)) + '\r\n\r\n').encode() + raw)
|
||||
except OSError:
|
||||
pass
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
with self.connections_lock:
|
||||
self.connections.add(request)
|
||||
self.executor.submit(self.worker, request, address)
|
||||
|
||||
def worker(self, request, address):
|
||||
try:
|
||||
self.finish_request(request, address)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
self.shutdown_request(request)
|
||||
with self.connections_lock:
|
||||
self.connections.discard(request)
|
||||
self.slots.release()
|
||||
|
||||
def close_connections(self):
|
||||
with self.connections_lock:
|
||||
connections = list(self.connections)
|
||||
for connection in connections:
|
||||
try:
|
||||
connection.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def server_close(self):
|
||||
super().server_close()
|
||||
# Bound draining even when a slow client keeps an incomplete request alive.
|
||||
deadline = threading.Timer(5, self.close_connections)
|
||||
deadline.start()
|
||||
try:
|
||||
self.executor.shutdown(wait=True)
|
||||
finally:
|
||||
deadline.cancel()
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=os.environ.get('LOG_LEVEL', 'INFO'), format='%(asctime)s %(levelname)s %(message)s')
|
||||
tele.configure('messenger-api')
|
||||
from postgres import Store
|
||||
store = Store()
|
||||
server = Server((os.environ.get('APP_HOST', '0.0.0.0'), int(os.environ.get('APP_PORT', '8080'))), store)
|
||||
stopping = threading.Event()
|
||||
|
||||
def stop(signum, frame):
|
||||
if not stopping.is_set():
|
||||
stopping.set()
|
||||
LOG.info('shutdown_started signal=%s', signum)
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGUSR1, lambda *_: LOG.warning('pool_stats instance=%s stats=%s', server.instance_id, json.dumps(store.pool.get_stats())))
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
LOG.info('started port=%s', server.server_address[1])
|
||||
try:
|
||||
server.serve_forever(poll_interval=0.1)
|
||||
finally:
|
||||
server.server_close()
|
||||
store.close()
|
||||
tele.shutdown()
|
||||
LOG.info('shutdown_complete')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Allowlisted manual SDK telemetry; bounded exporters never carry business payloads."""
|
||||
import contextlib
|
||||
import contextvars
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import resource
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from opentelemetry import trace, metrics
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider, SpanProcessor
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter, SpanExportResult
|
||||
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
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
|
||||
|
||||
INSTANCE = uuid.uuid4().hex
|
||||
ACTIVE = False
|
||||
SUPPRESSED = contextvars.ContextVar('telemetry_suppressed', default=False)
|
||||
PROVIDERS = []
|
||||
COUNTERS = {}
|
||||
HISTOGRAMS = {}
|
||||
STATE = {'worker_busy': 0, 'queue_depth': 0, 'queue_oldest_age': 0, 'queue_observation_ok': 1,
|
||||
'spans_finished': 0, 'spans_exported': 0, 'spans_export_failed': 0}
|
||||
LOCK = threading.Lock()
|
||||
PROPAGATOR = TraceContextTextMapPropagator()
|
||||
LOGGER = logging.getLogger('messenger.telemetry')
|
||||
TRACER = trace.get_tracer('messenger')
|
||||
POOL = None
|
||||
SERVICE = ''
|
||||
BUCKETS = [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60]
|
||||
|
||||
class FinishedSpans(SpanProcessor):
|
||||
def on_end(self, span):
|
||||
with LOCK:
|
||||
STATE['spans_finished'] += 1
|
||||
|
||||
class CountedExporter(SpanExporter):
|
||||
def __init__(self, delegate):
|
||||
self.delegate = delegate
|
||||
|
||||
def export(self, spans):
|
||||
result = self.delegate.export(spans)
|
||||
with LOCK:
|
||||
STATE['spans_exported' if result == SpanExportResult.SUCCESS else 'spans_export_failed'] += len(spans)
|
||||
return result
|
||||
|
||||
def shutdown(self):
|
||||
self.delegate.shutdown()
|
||||
|
||||
def force_flush(self, timeout_millis=30000):
|
||||
return self.delegate.force_flush(timeout_millis)
|
||||
|
||||
def configure(service):
|
||||
global ACTIVE, TRACER, SERVICE
|
||||
if PROVIDERS or os.environ.get('TELEMETRY_ENABLED', '1') == '0':
|
||||
return
|
||||
SERVICE = service
|
||||
ratio = float(os.environ.get('TRACE_SAMPLE_RATIO', '0.25'))
|
||||
if not 0 <= ratio <= 1:
|
||||
raise ValueError('TRACE_SAMPLE_RATIO must be 0..1')
|
||||
resource_attributes = Resource.create({
|
||||
'service.name': service, 'service.version': 'lab6.1',
|
||||
'service.instance.id': INSTANCE, 'deployment.environment.name': 'lab',
|
||||
})
|
||||
endpoint = os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/')
|
||||
provider = TracerProvider(resource=resource_attributes, sampler=ParentBased(TraceIdRatioBased(ratio)))
|
||||
provider.add_span_processor(FinishedSpans())
|
||||
provider.add_span_processor(BatchSpanProcessor(
|
||||
CountedExporter(OTLPSpanExporter(endpoint=endpoint+'/v1/traces', timeout=1)),
|
||||
max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=500,
|
||||
export_timeout_millis=1500))
|
||||
trace.set_tracer_provider(provider)
|
||||
TRACER = trace.get_tracer('messenger')
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=endpoint+'/v1/metrics', timeout=1),
|
||||
export_interval_millis=2000, export_timeout_millis=1500)
|
||||
meter_provider = MeterProvider(resource=resource_attributes, metric_readers=[reader],
|
||||
views=[View(instrument_name='*duration', aggregation=ExplicitBucketHistogramAggregation(BUCKETS))])
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
meter = metrics.get_meter('messenger')
|
||||
for name in ['http_server_requests', 'jobs_processed', 'job_retries']:
|
||||
COUNTERS[name] = meter.create_counter(name)
|
||||
for name in ['http_server_duration', 'job_processing_duration', 'job_ready_duration']:
|
||||
HISTOGRAMS[name] = meter.create_histogram(name, unit='s')
|
||||
def gauge(name, getter, unit=''):
|
||||
def observe(options):
|
||||
try:
|
||||
yield metrics.Observation(getter(), {})
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
meter.create_observable_gauge(name, callbacks=[observe], unit=unit)
|
||||
for name in ['queue_depth', 'queue_oldest_age', 'queue_observation_ok', 'worker_busy',
|
||||
'spans_finished', 'spans_exported', 'spans_export_failed']:
|
||||
gauge(name, lambda name=name: STATE[name], 's' if name=='queue_oldest_age' else '')
|
||||
gauge('worker_capacity', lambda: int(os.environ.get('WORKER_CONCURRENCY', '1')) if service=='messenger-worker' else 0)
|
||||
gauge('db_pool_used', lambda: max(0, POOL.get_stats().get('pool_size',0)-POOL.get_stats().get('pool_available',0)) if POOL else 0)
|
||||
gauge('db_pool_waiting', lambda: POOL.get_stats().get('requests_waiting',0) if POOL else 0)
|
||||
gauge('db_pool_capacity', lambda: int(os.environ.get('DB_POOL_MAX','8')) if POOL else 0)
|
||||
gauge('process_resident_memory', lambda: int(Path('/proc/self/statm').read_text().split()[1])*os.sysconf('SC_PAGE_SIZE'), 'By')
|
||||
gauge('container_memory', lambda: int(Path('/sys/fs/cgroup/memory.current').read_text()), 'By')
|
||||
def cpu(options):
|
||||
use = resource.getrusage(resource.RUSAGE_SELF)
|
||||
yield metrics.Observation(use.ru_utime+use.ru_stime, {})
|
||||
meter.create_observable_counter('process_cpu', callbacks=[cpu], unit='s')
|
||||
log_provider = LoggerProvider(resource=resource_attributes)
|
||||
log_provider.add_log_record_processor(BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=endpoint+'/v1/logs', timeout=1),
|
||||
max_queue_size=256, max_export_batch_size=64, schedule_delay_millis=500,
|
||||
export_timeout_millis=1500))
|
||||
LOGGER.setLevel(logging.INFO)
|
||||
LOGGER.propagate = False
|
||||
LOGGER.addHandler(LoggingHandler(level=logging.INFO, logger_provider=log_provider))
|
||||
PROVIDERS.extend([provider, meter_provider, log_provider])
|
||||
ACTIVE = True
|
||||
|
||||
def pool(value):
|
||||
global POOL
|
||||
POOL = value
|
||||
|
||||
def route(path):
|
||||
if path in ['/health/live', '/health/ready', '/api/v1/users', '/api/v1/users/me',
|
||||
'/api/v1/auth/sessions', '/api/v1/auth/sessions/current', '/api/v1/chats']:
|
||||
return path
|
||||
patterns = [
|
||||
(r'/api/v1/chats/[^/]+/messages', '/api/v1/chats/{chat_id}/messages'),
|
||||
(r'/api/v1/chats/[^/]+/attachments', '/api/v1/chats/{chat_id}/attachments'),
|
||||
(r'/api/v1/chats/[^/]+', '/api/v1/chats/{chat_id}'),
|
||||
(r'/api/v1/attachments/[^/]+/content', '/api/v1/attachments/{attachment_id}/content'),
|
||||
(r'/api/v1/attachments/[^/]+', '/api/v1/attachments/{attachment_id}'),
|
||||
]
|
||||
return next((template for pattern,template in patterns if re.fullmatch(pattern,path)), 'unmatched')
|
||||
|
||||
@contextlib.contextmanager
|
||||
def span(name, attributes=None, kind=SpanKind.INTERNAL, carrier=None):
|
||||
if not ACTIVE or SUPPRESSED.get() or (name == 'db.transaction' and not trace.get_current_span().get_span_context().is_valid):
|
||||
yield trace.get_current_span()
|
||||
return
|
||||
context = PROPAGATOR.extract(carrier) if carrier is not None else None
|
||||
with TRACER.start_as_current_span(name, attributes=attributes or {}, kind=kind,
|
||||
context=context, record_exception=False, set_status_on_exception=False) as current:
|
||||
try:
|
||||
yield current
|
||||
except Exception as error:
|
||||
current.set_attribute('error.type', type(error).__name__)
|
||||
current.set_status(Status(StatusCode.ERROR))
|
||||
log('operation_failed', error_type=type(error).__name__)
|
||||
raise
|
||||
|
||||
@contextlib.contextmanager
|
||||
def suppressed():
|
||||
token = SUPPRESSED.set(True)
|
||||
try:
|
||||
yield None
|
||||
finally:
|
||||
SUPPRESSED.reset(token)
|
||||
|
||||
def carrier():
|
||||
result = {}
|
||||
if ACTIVE:
|
||||
PROPAGATOR.inject(result)
|
||||
return result
|
||||
|
||||
def log(event, **attributes):
|
||||
if not ACTIVE:
|
||||
return
|
||||
# Callers pass only fixed event names, bounded outcomes and technical correlation IDs.
|
||||
context = trace.get_current_span().get_span_context()
|
||||
body = {'timestamp': dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
'severity': 'INFO', 'service.name': SERVICE, 'event': event,
|
||||
'sampled': bool(context.trace_flags.sampled), 'trace_id': format(context.trace_id,'032x'), 'span_id': format(context.span_id,'016x'),
|
||||
**attributes}
|
||||
LOGGER.info(json.dumps(body, ensure_ascii=True, separators=(',',':')))
|
||||
|
||||
def count(name, attributes=None):
|
||||
if ACTIVE:
|
||||
COUNTERS[name].add(1, attributes or {})
|
||||
|
||||
def duration(name, seconds, attributes=None):
|
||||
if ACTIVE:
|
||||
HISTOGRAMS[name].record(max(0, seconds), attributes or {})
|
||||
|
||||
def flush():
|
||||
for provider in PROVIDERS:
|
||||
provider.force_flush(timeout_millis=5000)
|
||||
|
||||
def shutdown():
|
||||
for provider in PROVIDERS:
|
||||
provider.shutdown()
|
||||
|
||||
class S3Client:
|
||||
"""Span each SDK request without serializing args, keys, URLs or SDK exceptions."""
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
def __getattr__(self, name):
|
||||
method = getattr(self.client,name)
|
||||
if name not in {'head_object','get_object','put_object','delete_object','head_bucket','create_bucket','list_objects_v2'}:
|
||||
return method
|
||||
def call(*args, **kwargs):
|
||||
with span('s3.'+name, {'rpc.system':'aws-api','rpc.service':'S3','rpc.method':name}, SpanKind.CLIENT):
|
||||
return method(*args, **kwargs)
|
||||
return call
|
||||
Reference in New Issue
Block a user