diff --git a/REPORT.md b/REPORT.md index a41389f..88b6a72 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,8 +1,8 @@ -# Отчёт — лабораторная 2 +## Лабораторная 2 - Автор, группа: Савин Александр БВТ2303 -- Целевая оценка: 5; выбранный трек: 1 -- Commit/PR: локальный рабочий результат в текущем clone +- Целевая оценка: 5; выбранный трек: 1 (cache consistency) +- Commit/PR: локальный рабочий результат в текущем clone, подготовленный к пушу в Gitea - Использованные источники, библиотеки и помощь ИИ: README проекта, OpenAPI-контракт, FastAPI, Uvicorn, PostgreSQL, Valkey/Redis client, Python 3.13 ## Запуск из чистого окружения @@ -105,8 +105,8 @@ cd /Users/alexander/Documents/вп/mtusi2026lab2 && . .venv/bin/activate && make python3 tests/cache_consistency.py cache_key_exists=True ttl_seconds=3599 -avg_latency_ms=10.31 -p95_latency_ms=10.70 +avg_latency_ms=11.44 +p95_latency_ms=12.35 stale_cache_rejected=True logout_revokes_cache=True ``` @@ -119,7 +119,7 @@ logout_revokes_cache=True | TTL работает | запись истекает по таймауту | `ttl_seconds=3599` | PASS | | Stale cache не принимается | старые данные не должны использоваться | `stale_cache_rejected=True` | PASS | | Logout отменяет сессию | запись удаляется и запросы с токеном отклоняются | `logout_revokes_cache=True` | PASS | -| Latency | запросы выполняются быстро | `avg_latency_ms=10.31`, `p95_latency_ms=10.70` | PASS | +| Latency | запросы выполняются быстро | `avg_latency_ms=11.44`, `p95_latency_ms=12.35` | PASS | ## Эксперимент и вывод по треку 1 (cache consistency) @@ -138,6 +138,8 @@ logout_revokes_cache=True Проверка подтверждает, что stale cache и logout корректно обрабатываются. Это соответствует требованиям уровня 5 и обеспечивает устойчивость аутентификации при падении/конфликте кэша. +Дополнительно была исправлена пагинация сообщений: курсор теперь корректно работает по `(created_at, id)` и связан с конкретным чатом, что закрывает публичный smoke test и устраняет повторяющуюся ошибку "second page must finish history". + ## Ограничения - PostgreSQL остаётся источником истины; Valkey выполняет роль кэша, а не единственного хранилища. @@ -148,6 +150,8 @@ logout_revokes_cache=True Лабораторная работа 2 выполнена в полном объёме: PostgreSQL задействован как реальный источник данных, Valkey используется как TTL-кэш сессий, аутентификация реализована по Basic/Bearer, а выбранный трек 1 по cache consistency подтверждён на живом стенде. Все ключевые проверки проходят: public smoke test, OpenAPI validation и проверка корректности кэша. Это соответствует README: уровень 4 + завершённый трек 1 для оценки 5. +Финальная рабочая версия исправлена, проверена и подготовлена к пушу в удалённый Gitea-репозиторий. + ```bash lsof -t -i :8080 | xargs kill -9 ``` diff --git a/app.py b/app.py index 660b2b3..50b47b1 100644 --- a/app.py +++ b/app.py @@ -393,12 +393,11 @@ class Store: JOIN chat_members cm ON cm.chat_id = c.id WHERE cm.user_id = %s ORDER BY c.created_at ASC, c.id ASC - LIMIT %s """, - (user_id, limit + 1), + (user_id,), ) rows = cur.fetchall() - rows = [ + items = [ { "id": str(row[0]), "title": row[1], @@ -408,39 +407,45 @@ class Store: for row in rows ] + start_index = 0 if cursor: - cursor_parts = cursor.split("|", 1) - if len(cursor_parts) != 2: + prefix = f"user:{user_id}|" + if not cursor.startswith(prefix): + raise ApiError(400, "invalid_request", "cursor does not match user chat list") + remainder = cursor[len(prefix):] + if not remainder: raise ApiError(400, "invalid_request", "invalid cursor") try: - cursor_ts_raw, cursor_id = cursor_parts + cursor_ts_raw, cursor_id = remainder.split("|", 1) cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00")) except ValueError as exc: raise ApiError(400, "invalid_request", "invalid cursor") from exc - filtered = [] - for item in rows: + for idx, item in enumerate(items): item_dt = datetime.fromisoformat(item["created_at"].replace("Z", "+00:00")) if (item_dt, item["id"]) > (cursor_dt.astimezone(timezone.utc), cursor_id): - filtered.append(item) - rows = filtered + start_index = idx + break + else: + start_index = len(items) + page = items[start_index:start_index + limit] next_cursor = None - if len(rows) > limit: - next_cursor = f"{rows[limit-1]['created_at']}|{rows[limit-1]['id']}" - rows = rows[:limit] + if start_index + limit < len(items): + last_item = page[-1] + next_cursor = f"user:{user_id}|{last_item['created_at']}|{last_item['id']}" - return {"items": rows, "next_cursor": next_cursor} + return {"items": page, "next_cursor": next_cursor} def list_messages_for_chat(self, chat_id: str, limit: int, cursor: Optional[str]): with self.connect() as conn: with conn.cursor() as cur: cur.execute( - "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s ORDER BY created_at ASC, id ASC LIMIT %s", - (chat_id, limit + 1), + "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s ORDER BY created_at ASC, id ASC", + (chat_id,), ) rows = cur.fetchall() - normalised = [{ + items = [{ "id": str(row[0]), "chat_id": str(row[1]), "sender_id": str(row[2]), @@ -448,29 +453,34 @@ class Store: "created_at": self.isoformat_utc(row[4]), } for row in rows] + start_index = 0 if cursor: - cursor_parts = cursor.split("|", 1) - if len(cursor_parts) != 2: + prefix = f"chat:{chat_id}|" + if not cursor.startswith(prefix): + raise ApiError(400, "invalid_request", "cursor does not match chat") + remainder = cursor[len(prefix):] + if not remainder: raise ApiError(400, "invalid_request", "invalid cursor") try: - cursor_ts_raw, cursor_id = cursor_parts + cursor_ts_raw, cursor_id = remainder.split("|", 1) cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00")) except ValueError as exc: raise ApiError(400, "invalid_request", "invalid cursor") from exc - filtered = [] - for item in normalised: + for idx, item in enumerate(items): item_dt = datetime.fromisoformat(item["created_at"].replace("Z", "+00:00")) if (item_dt, item["id"]) > (cursor_dt.astimezone(timezone.utc), cursor_id): - filtered.append(item) - normalised = filtered + start_index = idx + break + else: + start_index = len(items) + page = items[start_index:start_index + limit] next_cursor = None - if len(normalised) > limit: - last_item = normalised[limit - 1] - next_cursor = f"{last_item['created_at']}|{last_item['id']}" - normalised = normalised[:limit] + if start_index + limit < len(items): + last_item = page[-1] + next_cursor = f"chat:{chat_id}|{last_item['created_at']}|{last_item['id']}" - return {"items": normalised, "next_cursor": next_cursor} + return {"items": page, "next_cursor": next_cursor} def create_session(self, user_id: str, username: str): token = secrets.token_urlsafe(32)