forked from mtusi2026/mtusi2026lab2
Хранить отзывы сессий в PostgreSQL, сохранять U+0000, ограничить ожидание БД
This commit is contained in:
+4
-7
@@ -12,7 +12,8 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
import auth
|
||||
from cache import cache
|
||||
from db import pool
|
||||
from config import settings
|
||||
from db import connection, pool, request_deadline
|
||||
from errors import ApiError, error_response
|
||||
from models import CreateChat, CreateMessage, CreateUser
|
||||
import store
|
||||
@@ -45,6 +46,7 @@ app = FastAPI(title='MTUSI Messenger lab2', lifespan=lifespan)
|
||||
@app.middleware('http')
|
||||
async def request_context(request: Request, call_next):
|
||||
request.state.request_id = uuid.uuid4().hex
|
||||
request_deadline.set(time.monotonic() + settings.db_request_timeout)
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
response = await call_next(request)
|
||||
@@ -82,11 +84,6 @@ async def handle_validation_error(request: Request, exc: RequestValidationError)
|
||||
return error_response(request, 400, 'Некорректный запрос: ' + where)
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.DataError)
|
||||
async def handle_data_error(request: Request, exc: psycopg.DataError):
|
||||
return error_response(request, 400, 'Некорректные данные')
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
@app.exception_handler(psycopg.InterfaceError)
|
||||
async def handle_database_unavailable(request: Request, exc: psycopg.Error):
|
||||
@@ -103,7 +100,7 @@ async def liveness():
|
||||
def readiness():
|
||||
if not state['ready']:
|
||||
raise ApiError(503, 'Сервис не готов')
|
||||
with pool.connection(timeout=1) as conn:
|
||||
with connection(limit=1) as conn:
|
||||
conn.execute('SELECT 1')
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
+27
-2
@@ -6,6 +6,7 @@ import secrets
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
import psycopg
|
||||
|
||||
from cache import REVOKED, cache
|
||||
from config import settings
|
||||
@@ -13,6 +14,8 @@ from db import iso
|
||||
from errors import BASIC_CHALLENGE, BEARER_CHALLENGE, unauthorized
|
||||
import store
|
||||
|
||||
REVOCATION_MARGIN_SECONDS = 5
|
||||
|
||||
USERNAME = re.compile(r'^[a-z0-9_]{3,32}$')
|
||||
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
@@ -77,6 +80,8 @@ def authenticate(header):
|
||||
if token is None or not token.isascii():
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
digest = token_hash(token)
|
||||
if cache.client is not None and not cache.synced:
|
||||
sync_revocations()
|
||||
user = cache.get(digest)
|
||||
if user == REVOKED:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
@@ -89,6 +94,26 @@ def authenticate(header):
|
||||
return {'user': user, 'token_hash': digest}
|
||||
|
||||
|
||||
def sync_revocations():
|
||||
errors_before = cache.errors
|
||||
try:
|
||||
pending = store.pending_revocations()
|
||||
except psycopg.Error:
|
||||
return
|
||||
if not cache.revoke_all(pending):
|
||||
return
|
||||
if pending:
|
||||
try:
|
||||
store.clear_revocations(pending)
|
||||
except psycopg.Error:
|
||||
pass
|
||||
cache.mark_synced(errors_before)
|
||||
|
||||
|
||||
def logout(session):
|
||||
store.delete_session(session['token_hash'])
|
||||
cache.revoke(session['token_hash'])
|
||||
store.revoke_session(session['token_hash'], cache.max_ttl + REVOCATION_MARGIN_SECONDS)
|
||||
if cache.revoke(session['token_hash']):
|
||||
try:
|
||||
store.clear_revocations([session['token_hash']])
|
||||
except psycopg.Error:
|
||||
pass
|
||||
|
||||
+23
-14
@@ -1,6 +1,7 @@
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
import redis
|
||||
@@ -20,7 +21,9 @@ class SessionCache:
|
||||
decode_responses=True) if url else None
|
||||
self.max_ttl = max_ttl
|
||||
self.bypass_until = 0.0
|
||||
self.pending = set()
|
||||
self.lock = threading.Lock()
|
||||
self.errors = 0
|
||||
self.synced = False
|
||||
|
||||
def _run(self, action, force=False):
|
||||
if self.client is None:
|
||||
@@ -32,25 +35,23 @@ class SessionCache:
|
||||
except redis.RedisError as error:
|
||||
log.warning('session cache unavailable (%s), using PostgreSQL for %ds', type(error).__name__, BYPASS_SECONDS)
|
||||
self.bypass_until = time.monotonic() + BYPASS_SECONDS
|
||||
with self.lock:
|
||||
self.errors += 1
|
||||
self.synced = False
|
||||
return FAILED
|
||||
|
||||
@staticmethod
|
||||
def key(token_hash):
|
||||
return 'session:' + token_hash.hex()
|
||||
|
||||
def _tombstone(self, token_hash, force=False):
|
||||
return self._run(lambda c: c.set(self.key(token_hash), REVOKED, ex=self.max_ttl), force) is not FAILED
|
||||
|
||||
def _apply_pending(self):
|
||||
for token_hash in list(self.pending):
|
||||
if not self._tombstone(token_hash):
|
||||
return False
|
||||
self.pending.discard(token_hash)
|
||||
return True
|
||||
def mark_synced(self, errors_before):
|
||||
with self.lock:
|
||||
if self.errors == errors_before:
|
||||
self.synced = True
|
||||
|
||||
def get(self, token_hash):
|
||||
if self.pending and not self._apply_pending():
|
||||
return REVOKED if token_hash in self.pending else None
|
||||
if not self.synced:
|
||||
return None
|
||||
raw = self._run(lambda c: c.get(self.key(token_hash)))
|
||||
if raw is FAILED or not raw or raw == REVOKED:
|
||||
return REVOKED if raw == REVOKED else None
|
||||
@@ -68,8 +69,16 @@ class SessionCache:
|
||||
self._run(lambda c: c.set(self.key(token_hash), value, ex=ttl, nx=True))
|
||||
|
||||
def revoke(self, token_hash):
|
||||
if self.client is not None and not self._tombstone(token_hash, force=True):
|
||||
self.pending.add(token_hash)
|
||||
return self._run(lambda c: c.set(self.key(token_hash), REVOKED, ex=self.max_ttl), force=True) is not FAILED
|
||||
|
||||
def revoke_all(self, token_hashes):
|
||||
def write(client):
|
||||
with client.pipeline(transaction=False) as pipe:
|
||||
for token_hash in token_hashes:
|
||||
pipe.set(self.key(token_hash), REVOKED, ex=self.max_ttl)
|
||||
pipe.execute()
|
||||
return True
|
||||
return not token_hashes or self._run(write) is not FAILED
|
||||
|
||||
|
||||
cache = SessionCache(settings.cache_url, settings.session_cache_ttl)
|
||||
|
||||
+2
-1
@@ -29,7 +29,8 @@ class Settings:
|
||||
self.db_pool_min = positive_int('DB_POOL_MIN', '1')
|
||||
self.db_pool_max = positive_int('DB_POOL_MAX', '10')
|
||||
self.db_pool_timeout = float(os.environ.get('DB_POOL_TIMEOUT_SECONDS', '2'))
|
||||
self.db_statement_timeout_ms = positive_int('DB_STATEMENT_TIMEOUT_MS', '5000')
|
||||
self.db_statement_timeout_ms = positive_int('DB_STATEMENT_TIMEOUT_MS', '3000')
|
||||
self.db_request_timeout = float(os.environ.get('DB_REQUEST_TIMEOUT_SECONDS', '4'))
|
||||
if not self.database_url:
|
||||
raise SystemExit('DATABASE_URL or DATABASE_URL_FILE is required')
|
||||
|
||||
|
||||
@@ -1,16 +1,85 @@
|
||||
from contextlib import contextmanager
|
||||
import contextvars
|
||||
from datetime import timezone
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from config import settings
|
||||
|
||||
log = logging.getLogger('messenger.db')
|
||||
|
||||
request_deadline = contextvars.ContextVar('request_deadline', default=None)
|
||||
|
||||
CHECK_SECONDS = 1
|
||||
|
||||
|
||||
def abort(conn):
|
||||
try:
|
||||
sock = socket.socket(fileno=os.dup(conn.fileno()))
|
||||
except (OSError, psycopg.Error):
|
||||
return
|
||||
try:
|
||||
sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
class Watchdog:
|
||||
def __init__(self):
|
||||
self.cond = threading.Condition()
|
||||
self.armed = {}
|
||||
self.ids = itertools.count()
|
||||
threading.Thread(target=self.loop, name='db-watchdog', daemon=True).start()
|
||||
|
||||
@contextmanager
|
||||
def guard(self, conn, seconds):
|
||||
key = next(self.ids)
|
||||
with self.cond:
|
||||
self.armed[key] = (time.monotonic() + seconds, conn)
|
||||
self.cond.notify()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
with self.cond:
|
||||
self.armed.pop(key, None)
|
||||
|
||||
def loop(self):
|
||||
with self.cond:
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
for key, (deadline, conn) in list(self.armed.items()):
|
||||
if deadline <= now:
|
||||
del self.armed[key]
|
||||
log.warning('database did not answer in time, aborting connection')
|
||||
abort(conn)
|
||||
wake = min((deadline for deadline, _ in self.armed.values()), default=now + 60)
|
||||
self.cond.wait(max(wake - now, 0.01))
|
||||
|
||||
|
||||
watchdog = Watchdog()
|
||||
|
||||
|
||||
def check(conn):
|
||||
with watchdog.guard(conn, CHECK_SECONDS):
|
||||
ConnectionPool.check_connection(conn)
|
||||
|
||||
|
||||
pool = ConnectionPool(
|
||||
settings.database_url,
|
||||
min_size=settings.db_pool_min,
|
||||
max_size=settings.db_pool_max,
|
||||
timeout=settings.db_pool_timeout,
|
||||
check=ConnectionPool.check_connection,
|
||||
check=check,
|
||||
open=False,
|
||||
name='messenger',
|
||||
kwargs={
|
||||
@@ -21,5 +90,33 @@ pool = ConnectionPool(
|
||||
)
|
||||
|
||||
|
||||
def remaining(limit=None):
|
||||
deadline = request_deadline.get()
|
||||
left = settings.db_request_timeout if deadline is None else deadline - time.monotonic()
|
||||
if limit is not None:
|
||||
left = min(left, limit)
|
||||
if left <= 0:
|
||||
raise psycopg.OperationalError('request deadline exceeded')
|
||||
return left
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection(limit=None):
|
||||
conn = pool.getconn(timeout=min(settings.db_pool_timeout, remaining(limit)))
|
||||
try:
|
||||
with watchdog.guard(conn, remaining(limit)):
|
||||
try:
|
||||
yield conn
|
||||
except BaseException:
|
||||
try:
|
||||
conn.rollback()
|
||||
except psycopg.Error:
|
||||
pass
|
||||
raise
|
||||
conn.commit()
|
||||
finally:
|
||||
pool.putconn(conn)
|
||||
|
||||
|
||||
def iso(value):
|
||||
return value.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
|
||||
|
||||
@@ -8,6 +8,10 @@ class StrictModel(BaseModel):
|
||||
def not_blank(value):
|
||||
if not value.strip():
|
||||
raise ValueError('must not be blank')
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeEncodeError:
|
||||
raise ValueError('must be valid Unicode') from None
|
||||
return value
|
||||
|
||||
|
||||
|
||||
+41
-18
@@ -2,7 +2,7 @@ import uuid
|
||||
|
||||
from psycopg import errors
|
||||
|
||||
from db import iso, pool
|
||||
from db import connection, iso
|
||||
from errors import ApiError
|
||||
from pagination import decode_cursor, page
|
||||
|
||||
@@ -13,41 +13,49 @@ CHAT_SELECT = ('SELECT c.id, c.title, c.created_at, '
|
||||
'FROM chats c ')
|
||||
|
||||
|
||||
def utf8(value):
|
||||
return value.encode('utf-8')
|
||||
|
||||
|
||||
def unicode(value):
|
||||
return bytes(value).decode('utf-8')
|
||||
|
||||
|
||||
def user_out(row):
|
||||
return {'id': str(row['id']), 'username': row['username'],
|
||||
'display_name': row['display_name'], 'created_at': iso(row['created_at'])}
|
||||
'display_name': unicode(row['display_name']), 'created_at': iso(row['created_at'])}
|
||||
|
||||
|
||||
def chat_out(row):
|
||||
return {'id': str(row['id']), 'title': row['title'],
|
||||
return {'id': str(row['id']), 'title': unicode(row['title']),
|
||||
'member_ids': [str(m) for m in row['member_ids']], 'created_at': iso(row['created_at'])}
|
||||
|
||||
|
||||
def message_out(row):
|
||||
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
|
||||
'text': row['text'], 'created_at': iso(row['created_at'])}
|
||||
'text': unicode(row['text']), 'created_at': iso(row['created_at'])}
|
||||
|
||||
|
||||
def create_user(username, display_name, password_hash):
|
||||
try:
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
row = conn.execute(
|
||||
'INSERT INTO users AS u (username, display_name, password_hash) VALUES (%s, %s, %s) '
|
||||
'RETURNING ' + USER_COLUMNS,
|
||||
(username, display_name, password_hash)).fetchone()
|
||||
(username, utf8(display_name), password_hash)).fetchone()
|
||||
except errors.UniqueViolation:
|
||||
raise ApiError(409, 'Имя пользователя уже занято') from None
|
||||
return user_out(row)
|
||||
|
||||
|
||||
def find_credentials(username):
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
return conn.execute('SELECT ' + USER_COLUMNS + ', u.password_hash FROM users u WHERE u.username = %s',
|
||||
(username,)).fetchone()
|
||||
|
||||
|
||||
def create_session(user_id, token_hash, ttl_seconds):
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE user_id = %s AND expires_at <= now()', (user_id,))
|
||||
return conn.execute(
|
||||
'INSERT INTO sessions (token_hash, user_id, expires_at) '
|
||||
@@ -56,16 +64,31 @@ def create_session(user_id, token_hash, ttl_seconds):
|
||||
|
||||
|
||||
def session_user(token_hash):
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
return conn.execute(
|
||||
'SELECT ' + USER_COLUMNS + ', s.expires_at FROM sessions s JOIN users u ON u.id = s.user_id '
|
||||
'WHERE s.token_hash = %s AND s.expires_at > now()',
|
||||
(token_hash,)).fetchone()
|
||||
|
||||
|
||||
def delete_session(token_hash):
|
||||
with pool.connection() as conn:
|
||||
def revoke_session(token_hash, keep_seconds):
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,))
|
||||
conn.execute('INSERT INTO session_revocations (token_hash, expires_at) '
|
||||
'VALUES (%s, now() + make_interval(secs => %s)) '
|
||||
'ON CONFLICT (token_hash) DO UPDATE SET expires_at = EXCLUDED.expires_at',
|
||||
(token_hash, keep_seconds))
|
||||
|
||||
|
||||
def pending_revocations():
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM session_revocations WHERE expires_at <= now()')
|
||||
return [bytes(r['token_hash']) for r in conn.execute('SELECT token_hash FROM session_revocations').fetchall()]
|
||||
|
||||
|
||||
def clear_revocations(token_hashes):
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM session_revocations WHERE token_hash = ANY(%s)', (list(token_hashes),))
|
||||
|
||||
|
||||
def create_chat(creator_id, title, member_ids):
|
||||
@@ -78,9 +101,9 @@ def create_chat(creator_id, title, member_ids):
|
||||
if creator_id not in members:
|
||||
raise ApiError(400, 'Создатель должен быть участником чата')
|
||||
try:
|
||||
with pool.connection() as conn, conn.transaction():
|
||||
with connection() as conn, conn.transaction():
|
||||
chat = conn.execute('INSERT INTO chats (title, created_by) VALUES (%s, %s) RETURNING id, title, created_at',
|
||||
(title, creator_id)).fetchone()
|
||||
(utf8(title), creator_id)).fetchone()
|
||||
conn.execute('INSERT INTO chat_members (chat_id, user_id, position) '
|
||||
'SELECT %s, member, position FROM unnest(%s::uuid[]) WITH ORDINALITY AS t(member, position)',
|
||||
(chat['id'], members))
|
||||
@@ -90,7 +113,7 @@ def create_chat(creator_id, title, member_ids):
|
||||
|
||||
|
||||
def get_chat(chat_id, user_id):
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
row = conn.execute(CHAT_SELECT + 'JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s '
|
||||
'WHERE c.id = %s', (user_id, chat_id)).fetchone()
|
||||
if row is None:
|
||||
@@ -106,7 +129,7 @@ def list_chats(user_id, cursor, limit):
|
||||
sql += 'AND (c.created_at, c.id) > (%s, %s) '
|
||||
params += decode_cursor(scope, cursor)
|
||||
sql += 'ORDER BY c.created_at, c.id LIMIT %s'
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
rows = conn.execute(sql, params + [limit + 1]).fetchall()
|
||||
return page([chat_out(r) for r in rows], scope, limit)
|
||||
|
||||
@@ -117,12 +140,12 @@ def is_member(conn, chat_id, user_id):
|
||||
|
||||
|
||||
def create_message(chat_id, sender_id, text):
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
row = conn.execute(
|
||||
'INSERT INTO messages (chat_id, sender_id, text) SELECT %s, %s, %s '
|
||||
'WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s) '
|
||||
'RETURNING ' + MESSAGE_COLUMNS,
|
||||
(chat_id, sender_id, text, chat_id, sender_id)).fetchone()
|
||||
(chat_id, sender_id, utf8(text), chat_id, sender_id)).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
return message_out(row)
|
||||
@@ -136,7 +159,7 @@ def list_messages(chat_id, user_id, cursor, limit):
|
||||
sql += 'AND (created_at, id) > (%s, %s) '
|
||||
params += decode_cursor(scope, cursor)
|
||||
sql += 'ORDER BY created_at, id LIMIT %s'
|
||||
with pool.connection() as conn:
|
||||
with connection() as conn:
|
||||
if not is_member(conn, chat_id, user_id):
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
rows = conn.execute(sql, params + [limit + 1]).fetchall()
|
||||
|
||||
Reference in New Issue
Block a user