This commit is contained in:
2026-11-30 15:50:51 +03:00
parent aef85e362a
commit d4ca44b300
20 changed files with 641 additions and 335 deletions
+61 -3
View File
@@ -15,6 +15,7 @@ import threading
import unicodedata
import uuid
import warnings
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
@@ -34,6 +35,10 @@ from auth import (
from db import ApiError, Store
from s3store import ObjectStore, S3Unavailable
from sessions import SessionStore
from telemetry import configure, JsonLogFormatter
from opentelemetry import context, trace
from opentelemetry.propagate import extract, inject
from opentelemetry.trace import Status, StatusCode
MAX_BODY_BYTES = 1024 * 1024
MAX_UPLOAD_BYTES = min(10 * 1024 * 1024, int(os.environ.get('MAX_UPLOAD_BYTES', 10 * 1024 * 1024)))
@@ -49,6 +54,9 @@ CURSOR_TIMESTAMP_PATTERN = re.compile(
)
IDEMPOTENCY_KEY_PATTERN = re.compile(r'^[A-Za-z0-9._:-]{1,128}$')
LOG = logging.getLogger('messenger')
TRACER = None
HTTP_REQUESTS = None
HTTP_DURATION = None
OPENAPI_PATH = Path(__file__).resolve().parent / 'contracts' / 'openapi.json'
SWAGGER_HTML = b'''<!doctype html>
<html lang="ru">
@@ -151,7 +159,12 @@ class MessengerHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, _format, *args):
LOG.info('request method=%s status=%s request_id=%s', self.command, self._status, self._request_id)
LOG.info(
'request method=%s status=%s',
self.command,
self._status,
extra={'request_id': self._request_id},
)
def _send_bytes(self, status, request_id, body, content_type, extra_headers=None):
self._status = status
@@ -523,7 +536,7 @@ class MessengerHandler(BaseHTTPRequestHandler):
user = self.server.store.register_user(username, display_name, password_hash, created_at)
self._send(201, request_id, user)
def _dispatch(self):
def _dispatch_impl(self):
request_id = str(uuid.uuid4())
self._request_id = request_id
self._status = 500
@@ -704,6 +717,37 @@ class MessengerHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
self._dispatch()
def _dispatch(self):
carrier = {name.lower(): value for name, value in self.headers.items()}
context = extract(carrier)
route = urlsplit(self.path).path
route_template = route
route_template = re.sub(r'/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?=/|$)', '/{id}', route_template)
started = time.perf_counter()
with TRACER.start_as_current_span(
'HTTP ' + self.command,
context=context,
kind=trace.SpanKind.SERVER,
attributes={
'http.request.method': self.command,
'url.path': route_template,
},
) as span:
try:
self._dispatch_impl()
finally:
duration = time.perf_counter() - started
status = getattr(self, '_status', 500)
attributes = {
'http.request.method': self.command,
'http.route': route_template,
'http.response.status_code': status,
}
HTTP_REQUESTS.add(1, attributes)
HTTP_DURATION.record(duration, attributes)
span.set_attribute('http.response.status_code', status)
span.set_status(Status(StatusCode.ERROR if status >= 500 else StatusCode.OK))
class MessengerServer(ThreadingHTTPServer):
daemon_threads = False
@@ -739,11 +783,25 @@ def main():
if os.environ.get('SESSION_STORE', 'redis').lower() != 'redis':
raise SystemExit('SESSION_STORE must be redis for this implementation')
global TRACER, HTTP_REQUESTS, HTTP_DURATION
TRACER, meter, otel_handler = configure('messenger-api')
HTTP_REQUESTS = meter.create_counter(
'messenger.http.requests',
description='HTTP requests',
)
HTTP_DURATION = meter.create_histogram(
'messenger.http.duration',
unit='s',
description='HTTP request duration',
)
logging.basicConfig(
level=os.environ.get('LOG_LEVEL', 'INFO').upper(),
format='%(asctime)s %(levelname)s %(name)s %(message)s',
format='%(message)s',
stream=sys.stdout,
)
for handler in logging.getLogger().handlers:
handler.setFormatter(JsonLogFormatter('messenger-api'))
logging.getLogger().addHandler(otel_handler)
store = Store.connect(run_migrations=False)
sessions = SessionStore.from_env()
objects = ObjectStore.from_env()