Завершить уровень 4: проверить отказы, поочерёдную замену и ограничить ожидания кэша
This commit is contained in:
+3
-1
@@ -3,7 +3,7 @@ import os
|
||||
import socket
|
||||
from contextlib import asynccontextmanager
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout
|
||||
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
@@ -32,7 +32,9 @@ def create_app() -> FastAPI:
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
@app.exception_handler(psycopg.errors.QueryCanceled)
|
||||
@app.exception_handler(psycopg.errors.LockNotAvailable)
|
||||
@app.exception_handler(PoolTimeout)
|
||||
@app.exception_handler(TooManyRequests)
|
||||
async def dependency_error(request, exc):
|
||||
return JSONResponse(status_code=503, content=ErrorResponse(error={
|
||||
"code": "unavailable", "message": "хранилище временно недоступно",
|
||||
|
||||
+19
-2
@@ -1,6 +1,8 @@
|
||||
"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД."""
|
||||
import logging
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
|
||||
import threading
|
||||
from redis import Redis, RedisError
|
||||
from pydantic import ValidationError
|
||||
from src.config import setting
|
||||
@@ -14,12 +16,27 @@ class ProfileCache:
|
||||
socket_timeout=0.2, max_connections=16) if url else None
|
||||
self.ttl = int(os.getenv('PROFILE_CACHE_TTL_SECONDS','60'))
|
||||
self.hits = self.misses = self.errors = 0
|
||||
# DNS может ждать дольше socket timeout; один фоновый вызов ограничивает и время, и очередь.
|
||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='profile-cache')
|
||||
self._pending = None
|
||||
self._guard = threading.Lock()
|
||||
|
||||
def _bounded(self, action, *args, **kwargs):
|
||||
with self._guard:
|
||||
if self._pending is not None and not self._pending.done():
|
||||
raise RedisError('кэш занят')
|
||||
self._pending = self._executor.submit(action, *args, **kwargs)
|
||||
future = self._pending
|
||||
try:
|
||||
return future.result(timeout=0.25)
|
||||
except FutureTimeout:
|
||||
raise RedisError('истекло время ожидания кэша') from None
|
||||
|
||||
def get(self, user_id):
|
||||
if not self.client:
|
||||
return None
|
||||
try:
|
||||
value = self.client.get('profile:v1:'+user_id)
|
||||
value = self._bounded(self.client.get, 'profile:v1:'+user_id)
|
||||
if value:
|
||||
user=User.model_validate_json(value)
|
||||
if user.id != user_id:
|
||||
@@ -35,7 +52,7 @@ class ProfileCache:
|
||||
def put(self, user):
|
||||
if self.client:
|
||||
try:
|
||||
self.client.set('profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
|
||||
self._bounded(self.client.set, 'profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
|
||||
except RedisError:
|
||||
self.errors += 1
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from uuid import UUID
|
||||
import re
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
@@ -21,8 +22,12 @@ def create_message(
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
if os.getenv('OPTIMIZED_WRITES','1') == '1':
|
||||
allowed = storage.is_chat_member(chat_id_str, x_user_id)
|
||||
else:
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
allowed = bool(chat and x_user_id in chat.member_ids)
|
||||
if not allowed:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
|
||||
+11
-2
@@ -178,6 +178,11 @@ class PostgresStorage:
|
||||
members = conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()
|
||||
return Chat(**public_row(row), member_ids=[str(x['user_id']) for x in members])
|
||||
|
||||
def is_chat_member(self, chat_id, user_id):
|
||||
"""Проверить доступ без загрузки всего чата и списка участников."""
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id,user_id)).fetchone() is not None
|
||||
|
||||
def list_chats_for_user(self, user_id, cursor, limit):
|
||||
with self.pool.connection() as conn:
|
||||
params = [user_id]
|
||||
@@ -205,9 +210,13 @@ class PostgresStorage:
|
||||
raise ConflictError('ключ уже использован с другим сообщением')
|
||||
row = conn.execute('SELECT * FROM messages WHERE id=%s', (old['message_id'],)).fetchone()
|
||||
return Message(**public_row(row))
|
||||
conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s', (sender_id,chat_id,key))
|
||||
optimized = os.getenv('OPTIMIZED_WRITES','1') == '1'
|
||||
if not optimized:
|
||||
conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s', (sender_id,chat_id,key))
|
||||
row = conn.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(),chat_id,sender_id,text)).fetchone()
|
||||
conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')", (sender_id,chat_id,key,text,row['id']))
|
||||
# Под той же блокировкой UPSERT заменяет просроченный результат без отдельного DELETE.
|
||||
suffix = ' ON CONFLICT (user_id,chat_id,key) DO UPDATE SET body=EXCLUDED.body,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at' if optimized else ''
|
||||
conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')"+suffix, (sender_id,chat_id,key,text,row['id']))
|
||||
return Message(**public_row(row))
|
||||
|
||||
def list_messages(self, chat_id, cursor, limit):
|
||||
|
||||
Reference in New Issue
Block a user