ЛР 3 — БВТ2301 — Майорова — на 5
This commit is contained in:
@@ -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)
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
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 psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
import redis
|
||||
|
||||
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(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)
|
||||
self.cache = redis.Redis.from_url(setting('CACHE_URL'), socket_connect_timeout=0.15, socket_timeout=0.15, decode_responses=True)
|
||||
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 = '003_idempotency.sql'").fetchone():
|
||||
raise RuntimeError('Run the separate migration service first')
|
||||
|
||||
@contextlib.contextmanager
|
||||
def connection(self):
|
||||
try:
|
||||
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()
|
||||
|
||||
def ready(self):
|
||||
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()
|
||||
# Lab3 has no attachments, but absent attachment_ids and [] are equivalent.
|
||||
if body.get('attachment_ids', []) != []:
|
||||
invalid()
|
||||
content = text(body['text'], 4000)
|
||||
canonical = json.dumps({'text': content, 'attachment_ids': []}, 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
|
||||
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)
|
||||
# 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)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
''', (uuid.uuid4(), chat_id, actor['id'], content.encode('utf-8'), stamp)).fetchone()
|
||||
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
|
||||
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 re_username(value):
|
||||
import re
|
||||
return re.fullmatch(r'[a-z0-9_]{3,32}', value)
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
"""Bounded threaded API; persistent correctness state is shared across replicas."""
|
||||
import concurrent.futures
|
||||
import http.server
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
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):
|
||||
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 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
|
||||
status = 500
|
||||
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:
|
||||
# No bodies, credentials, tokens, SQL or exception details in logs/responses.
|
||||
LOG.error('request_failed request_id=%s', self.request_id)
|
||||
result = {'error': {'code': 'internal_error', 'message': 'Внутренняя ошибка', 'request_id': self.request_id}}
|
||||
try:
|
||||
self.reply(status, result)
|
||||
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
||||
pass
|
||||
LOG.info('method=%s status=%s request_id=%s', self.command, status, self.request_id)
|
||||
|
||||
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', '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] == '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 = uuid.uuid4().hex
|
||||
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')
|
||||
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()
|
||||
LOG.info('shutdown_complete')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user