fix cached history pagination and setup docs
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
- Автор, группа: Козырев Матвей БВТ2301
|
||||
- Целевая оценка: 5; трек 1 — согласованность кэша
|
||||
- Commit/PR: TODO после публикации
|
||||
- PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/22
|
||||
- Использованные библиотеки: FastAPI 0.141.1, Uvicorn 0.40.0, asyncpg 0.31.0, argon2-cffi 25.1.0, redis 5.0.8; зафиксированы в `pyproject.toml` и `uv.lock`.
|
||||
|
||||
## Запуск из чистого clone
|
||||
@@ -13,10 +13,11 @@
|
||||
```sh
|
||||
mkdir -p secrets
|
||||
openssl rand -hex 32 -out secrets/postgres_password
|
||||
awk '{printf "postgresql://messenger:%s@postgres:5432/messenger\\n", $0}' \
|
||||
awk '{printf "postgresql://messenger:%s@postgres:5432/messenger\n", $0}' \
|
||||
secrets/postgres_password > secrets/database_url
|
||||
printf '%s\n' 'redis://redis:6379/0' > secrets/cache_url
|
||||
chmod 700 secrets
|
||||
chmod 600 secrets/postgres_password secrets/database_url
|
||||
chmod 600 secrets/postgres_password secrets/database_url secrets/cache_url
|
||||
docker compose --env-file .env.example config --quiet
|
||||
docker compose --env-file .env.example up -d --build
|
||||
```
|
||||
@@ -100,7 +101,7 @@ AOF и named volume `redis_data`.
|
||||
| Согласованность lock-файла | `uv lock --check` | PASS | выполнено |
|
||||
| Публичный smoke | `make test` | `PASS: lab2 public API scenario` | `evidence/smoke-2026-10-08.txt` |
|
||||
| Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | `evidence/persistence-2026-10-08.txt` |
|
||||
| Redis cache | `make test-grade4`; `redis-cli --scan` | read-after-write без stale read; создан ключ `history:first:…` | `evidence/redis-cache-2026-10-08.txt` |
|
||||
| Redis cache и курсор | `make test-grade4`; `redis-cli --scan` | read-after-write без stale read; повторный GET кэшированной страницы и её continuation возвращают 200 | `evidence/cache-pagination-2026-10-09.txt` |
|
||||
| Гонка и rollback | `make test-grade4` | Ровно одна регистрация успешна; неуспешный чат не виден | `evidence/grade4-checks-2026-10-08.txt` |
|
||||
| TTL и зависимости | `make test-grade4`; TTL=2 | Expired session → 401; Redis fallback проходит smoke; DB readiness → 503 | `evidence/grade4-checks-2026-10-08.txt` |
|
||||
| Индекс истории | `./scripts/explain_history.sh` | Index Scan, 50 строк, shared hit=3 | `evidence/explain-history-2026-10-08.txt` |
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
PASS: registration race, chat rollback and cache read-after-write
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
from asyncio import Lock, sleep
|
||||
from datetime import UTC, datetime
|
||||
from time import monotonic
|
||||
from secrets import token_urlsafe
|
||||
from uuid import UUID
|
||||
@@ -73,13 +74,22 @@ class HistoryCache:
|
||||
def _lock_key(cls, chat_id: UUID, version: int, limit: int) -> str:
|
||||
return cls._key(chat_id, version, limit) + ":lock"
|
||||
|
||||
@staticmethod
|
||||
def _decode_rows(value: str) -> list[dict]:
|
||||
rows = json.loads(value)
|
||||
for row in rows:
|
||||
created_at = row.get("created_at")
|
||||
if isinstance(created_at, str):
|
||||
row["created_at"] = datetime.fromisoformat(created_at).astimezone(UTC)
|
||||
return rows
|
||||
|
||||
async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None:
|
||||
client = await self._client_or_none()
|
||||
if client is None:
|
||||
return None
|
||||
try:
|
||||
value = await client.get(self._key(chat_id, version, limit))
|
||||
return json.loads(value) if value else None
|
||||
return self._decode_rows(value) if value else None
|
||||
except RedisError:
|
||||
await self._mark_unavailable(client)
|
||||
return None
|
||||
|
||||
@@ -59,6 +59,22 @@ def main() -> None:
|
||||
{message["id"] for message in history} == {first["id"], second["id"]},
|
||||
"history cache returned stale data after write",
|
||||
)
|
||||
|
||||
first_page_path = "/api/v1/chats/" + chat["id"] + "/messages?limit=1"
|
||||
first_page = client.call(
|
||||
"GET", first_page_path, actor=alice, schema="MessagePage"
|
||||
)["json"]
|
||||
cached_page = client.call(
|
||||
"GET", first_page_path, actor=alice, schema="MessagePage"
|
||||
)["json"]
|
||||
check(first_page == cached_page, "cached page differs from the first response")
|
||||
check(first_page["next_cursor"], "first page has no continuation cursor")
|
||||
client.call(
|
||||
"GET",
|
||||
first_page_path + "&cursor=" + first_page["next_cursor"],
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)
|
||||
print("PASS: registration race, chat rollback and cache read-after-write")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user