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