Учесть замечания по таймаутам и кэшу
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Nik
2026-10-15 18:50:46 +03:00
parent 7dbccb2206
commit 132f1fb3e3
5 changed files with 156 additions and 53 deletions
+41 -18
View File
@@ -26,10 +26,15 @@ db_pool = ConnectionPool(
kwargs={'row_factory': dict_row}, open=False,
)
redis_client = redis.Redis.from_url(
REDIS_URL, decode_responses=True, socket_connect_timeout=1,
REDIS_URL,
decode_responses=True,
socket_connect_timeout=1,
socket_timeout=1,
retry_on_timeout=False,
)
chat_cache_lock = threading.Lock()
chat_cache_sql_reads = 0
invalidated_chat_caches = set()
app = FastAPI(title='MTUSI Messenger Lab 2', version='1.2.0')
@@ -198,6 +203,16 @@ def page_chats(items, limit, cursor_data, owner_id):
return {'items': page, 'next_cursor': next_cursor}
def parse_limit(value):
try:
limit = int(value)
except (TypeError, ValueError) as exc:
raise ValueError('invalid limit') from exc
if not 1 <= limit <= 100:
raise ValueError('invalid limit')
return limit
@app.get('/health/live')
def health_live():
return {'status': 'ok'}
@@ -324,12 +339,12 @@ async def create_chat(request: Request):
chat_id, created_at = uuid.uuid4(), utc_now()
with db_pool.connection() as connection:
count = connection.execute(
'SELECT count(*) AS n FROM users WHERE id = ANY(%s)', (member_ids,)
).fetchone()['n']
if count != len(member_ids):
raise ValueError('unknown member')
with connection.transaction():
count = connection.execute(
'SELECT count(*) AS n FROM users WHERE id = ANY(%s)', (member_ids,)
).fetchone()['n']
if count != len(member_ids):
raise ValueError('unknown member')
connection.execute('INSERT INTO chats VALUES (%s,%s,%s)', (chat_id, title, created_at))
for member_id in member_ids:
connection.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id, member_id))
@@ -337,19 +352,22 @@ async def create_chat(request: Request):
try:
redis_client.delete('chats:' + str(member_id))
except Exception:
pass
with chat_cache_lock:
invalidated_chat_caches.add('chats:' + str(member_id))
return chat_response({'id': chat_id, 'title': title, 'created_at': created_at}, member_ids)
except ValueError:
return error_response(request, 400, 'invalid_request', 'Неверные данные чата')
@app.get('/api/v1/chats')
def list_chats(request: Request, limit: int = 50, cursor: str | None = None):
def list_chats(request: Request, limit: str = '50', cursor: str | None = None):
global chat_cache_sql_reads
user, failure = require_current_user(request)
if failure:
return failure
if not 1 <= limit <= 100:
try:
limit = parse_limit(limit)
except ValueError:
return error_response(request, 400, 'invalid_request', 'limit должен быть от 1 до 100')
cursor_data = None
@@ -362,16 +380,18 @@ def list_chats(request: Request, limit: int = 50, cursor: str | None = None):
return error_response(request, 400, 'invalid_request', 'Неверный cursor')
cache_key = 'chats:' + str(user['id'])
try:
cached = redis_client.get(cache_key)
if cached:
return page_chats(json.loads(cached), limit, cursor_data, str(user['id']))
except Exception:
pass
cache_needs_refresh = cache_key in invalidated_chat_caches
if not cache_needs_refresh:
try:
cached = redis_client.get(cache_key)
if cached:
return page_chats(json.loads(cached), limit, cursor_data, str(user['id']))
except Exception:
pass
with chat_cache_lock:
try:
cached = redis_client.get(cache_key)
cached = None if cache_needs_refresh else redis_client.get(cache_key)
except Exception:
cached = None
if cached:
@@ -391,6 +411,7 @@ def list_chats(request: Request, limit: int = 50, cursor: str | None = None):
chat_cache_sql_reads += 1
try:
redis_client.setex(cache_key, 30, json.dumps(chats))
invalidated_chat_caches.discard(cache_key)
except Exception:
pass
return page_chats(chats, limit, cursor_data, str(user['id']))
@@ -441,11 +462,13 @@ async def create_message(chat_id: str, request: Request):
@app.get('/api/v1/chats/{chat_id}/messages')
def list_messages(chat_id: str, request: Request, limit: int = 50, cursor: str | None = None):
def list_messages(chat_id: str, request: Request, limit: str = '50', cursor: str | None = None):
user, failure = require_current_user(request)
if failure:
return failure
if not 1 <= limit <= 100:
try:
limit = parse_limit(limit)
except ValueError:
return error_response(request, 400, 'invalid_request', 'limit должен быть от 1 до 100')
try:
parsed_chat_id = parse_uuid(chat_id)