Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
078b14840e | ||
|
|
e634ea9699 |
@@ -0,0 +1,20 @@
|
||||
name: Application integration
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
integration:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: python3 scripts/bootstrap.py
|
||||
- run: docker compose up -d --build --wait api
|
||||
- run: python3 scripts/verify.py
|
||||
- if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: lab2-evidence
|
||||
path: evidence/
|
||||
- if: always()
|
||||
run: docker compose --profile test down
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
FROM python:3.12.7-slim-bookworm
|
||||
WORKDIR /srv
|
||||
COPY app/requirements.txt app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r app/requirements.txt && useradd --uid 10001 --create-home app
|
||||
COPY app app
|
||||
COPY migrations migrations
|
||||
USER 10001:10001
|
||||
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=5s --timeout=4s --start-period=20s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=3)" || exit 1
|
||||
CMD ["python", "app/server.py"]
|
||||
@@ -0,0 +1,24 @@
|
||||
## Лабораторная 2
|
||||
|
||||
Автор / группа: Шурман А.Р., БПИ2302
|
||||
Целевая оценка: **4**. Трек 5: не заявлен.
|
||||
|
||||
Мессенджер из собственной lab1 перенесён на PostgreSQL. Добавлены атомарные миграции,
|
||||
Argon2id, Basic login, сохраняемые opaque Bearer-сессии с TTL/logout и Valkey-кэш
|
||||
публичных профилей с fallback. Запуск API и хранилищ — через Compose с именованными
|
||||
volumes; API доступен только на loopback.
|
||||
|
||||
Запуск: `python3 scripts/bootstrap.py`, затем `docker compose up -d --build --wait api`.
|
||||
Проверка: `python3 scripts/verify.py`. Полная инструкция и ограничения — [REPORT.md](REPORT.md).
|
||||
|
||||
- [x] Обязательный минимум lab1 сохранён с переходом на Bearer.
|
||||
- [x] Контракт и публичные тесты не изменены.
|
||||
- [x] make check, make validate, make test и persistence выполнены успешно.
|
||||
- [x] Проверены гонка username, rollback, 100 конкурентных сообщений, expiry/logout, отказ Valkey/БД.
|
||||
- [x] EXPLAIN (ANALYZE, BUFFERS) на 10000 сообщениях использует messages_history.
|
||||
- [x] Результаты в evidence/, отчёт и воспроизводимые команды приложены.
|
||||
- [x] Secrets и volumes исключены из Git и build context.
|
||||
|
||||
Ограничения: один PostgreSQL, локальный HTTP, без HA/backup и фоновой очистки
|
||||
истёкших сессий. Использованы FastAPI, psycopg, argon2-cffi, redis-py, собственная
|
||||
lab1 и помощь OpenAI Codex. Возможности оценки 5 не заявляются.
|
||||
@@ -1,37 +1,161 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Шурман А.Р., БПИ2302.
|
||||
- Целевая оценка: **4**. Треки оценки 5 не выполнялись.
|
||||
- Ветка: `solution/bpi2302-shurman` в `aliska/mtusi2026lab2-fork`; [PR #113](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/113) в исходный `mtusi2026/mtusi2026lab2`. Реализация и локальные проверки: commit `e634ea9`.
|
||||
- Источники: контракт и публичные тесты текущего skeleton; собственный мессенджер [лабораторной 1](https://gitflic.ru/project/alisapussy/vp-lab1-fork); помощь OpenAI Codex при реализации, тестировании и оформлении. Библиотеки FastAPI, Uvicorn, psycopg/pool, argon2-cffi и redis-py; полный lock версий в `app/requirements.txt`.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Git, Python 3.9+ для тестов и Docker с Compose v2+ (проверено Compose 5.5.1).
|
||||
Приложение работает на Python 3.12.7 в контейнере. Образы закреплены:
|
||||
`python:3.12.7-slim-bookworm`, `postgres:16.6-bookworm`, `valkey/valkey:8.0.2-alpine`.
|
||||
|
||||
```sh
|
||||
git clone https://gitea.privcloud.tech/aliska/mtusi2026lab2-fork.git
|
||||
cd mtusi2026lab2-fork
|
||||
git switch solution/bpi2302-shurman
|
||||
python3 scripts/bootstrap.py
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait api
|
||||
make check
|
||||
make test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 student-tests/verify.py
|
||||
python3 student-tests/explain.py
|
||||
```
|
||||
|
||||
Полный набор с сохранением вывода и подтверждением рестарта каждого контейнера:
|
||||
`python3 scripts/verify.py`. Собственные тесты временно останавливают **только**
|
||||
PostgreSQL/Valkey этого Compose-проекта, затем восстанавливают их через finally.
|
||||
Стенд предназначен для синтетических учебных данных. Проверка expiry поднимает
|
||||
дополнительный API на 8082 с TTL=2, затем останавливает его.
|
||||
|
||||
OpenAPI-проверка отдельно (зависимости только для валидатора):
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||
make validate PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
API: http://localhost:8080; Swagger: http://localhost:8080/docs.
|
||||
Создание пользователя требует password; затем `POST /api/v1/auth/sessions`
|
||||
с Basic (UTF-8 username:password), далее Bearer. Примеры — в исходном
|
||||
`examples/requests.http`. UI для лабораторной не требуется.
|
||||
|
||||
Bootstrap не перезаписывает существующие secrets. Он генерирует случайный
|
||||
пароль PostgreSQL и локальные файлы `secrets/`; каталог 0700, файлы 0644 для
|
||||
чтения Docker Desktop UID 10001. `.env` содержит TTL и порт, секреты не печатаются.
|
||||
Они исключены из Git и build context. DB/Valkey не публикуют порты на host;
|
||||
API привязан только к 127.0.0.1. `APP_HOST/APP_PORT/APP_ENV`,
|
||||
`SESSION_TTL_SECONDS`, `SESSION_STORE=postgres`, `DATABASE_URL_FILE`,
|
||||
`CACHE_URL_FILE` из `.env.example` заданы Compose; `HOST_PORT` управляет host-портом.
|
||||
Переключение SESSION_STORE не реализовано: источник сессий всегда PostgreSQL.
|
||||
|
||||
Миграция запускается отдельным сервисом до API. Повторный запуск:
|
||||
`docker compose run --rm migrate`. Версии и checksums — в schema_migrations;
|
||||
advisory lock сериализует миграторы. Изменять уже применённый SQL нельзя.
|
||||
|
||||
Безопасная остановка: `docker compose --profile test down` — volumes остаются.
|
||||
Повторный старт сохраняет все данные и срок сессий. **Намеренный сброс учебных
|
||||
данных**, если оператору нужен полностью пустой стенд:
|
||||
`docker compose --profile test down -v` (безвозвратно удаляет volumes этого проекта).
|
||||
При обычном запуске и проверке сохранности эта команда не используется.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Клиент → FastAPI → PostgreSQL; дополнительно Valkey для cache-aside публичного
|
||||
профиля. Проект схемы, индексы, FK и границы транзакций описаны в
|
||||
[infra/SCHEMA.md](infra/SCHEMA.md). Из lab1 перенесены модели, строгий набор полей,
|
||||
проверки строк, ошибки/request ID, разграничение доступа и cursor; in-memory Store
|
||||
заменён SQL. Новая аутентификация — объявленный переход курса.
|
||||
README, COURSE, contracts и публичные tests сохранены.
|
||||
|
||||
## Доказательства критериев
|
||||
Пользователи, чаты, участники, сообщения и сессии находятся в PostgreSQL.
|
||||
Регистрация защищена UNIQUE; создание чата и всех участников атомарно.
|
||||
Токен — 32 случайных байта (256 бит), сервер хранит только его SHA-256 и абсолютный
|
||||
expires_at. Пароли — Argon2id (19 MiB, time_cost=2, parallelism=1), без усечения
|
||||
UTF-8. Basic разрешён только для login; X-User-Id не авторизует запросы.
|
||||
Logout удаляет сессию. Истёкшие записи не дают доступ даже до физической очистки.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
Valkey хранит публичный неизменяемый User на 60 секунд. Это убирает повторный
|
||||
SELECT профиля после проверки сессии. Сессия при каждом запросе проверяется в
|
||||
PostgreSQL: cached profile не продлевает TTL и не отменяет logout. Источник истины
|
||||
— PostgreSQL, инвалидация профилей — TTL/eviction (операции изменения профиля нет).
|
||||
При сбое Valkey чтение идёт в PostgreSQL. AOF и именованный volume настроены, но
|
||||
потеря кэша допустима. История не кэшируется, чтение после COMMIT идёт в primary.
|
||||
|
||||
SQL параметризован; pool 1–8 соединений, очередь до 32, ожидание 3 s,
|
||||
connect timeout 3 s, statement timeout 3 s, lock timeout 2 s.
|
||||
Valkey connect/socket timeout 0.2 s. Синхронная работа выполняется в worker pool.
|
||||
Readiness зависит от PostgreSQL, liveness от жизни API. Контейнер API non-root
|
||||
10001:10001, SIGTERM получает Uvicorn напрямую.
|
||||
|
||||
## Доказательства критериев оценки 4
|
||||
|
||||
Измерения выполнены локально 29.10.2026; реальные выводы в `evidence/`.
|
||||
|
||||
| Критерий | Команда/сценарий | Наблюдение | Доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Структура и обязательный API | `make check`; `make validate`; `make test` | PASS | check.txt, validate.txt, smoke.txt |
|
||||
| Данные и сессия переживают полный рестарт | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | прежний токен читает подтверждённые данные | persistence.txt |
|
||||
| Перезапущены API и оба хранилища | сравнение Docker StartedAt до/после | время старта всех трёх изменилось, IDs/volumes сохранены | restart-containers.json |
|
||||
| Миграции с нуля / повторяемость | чистые именованные volumes при bootstrap; два `compose run --rm migrate` | старт с нуля успешен; количество сущностей не изменилось | student-tests.json, migration_reapply |
|
||||
| Password KDF, Unicode/двоеточие | регистрация/вход, проверка записи БД | Argon2id, plaintext отсутствует, вход PASS | student-tests.json |
|
||||
| Bearer, Basic только login, отказ X-User-Id | публичный smoke | PASS, чужой чат 404 | smoke.txt |
|
||||
| Logout и expiry | cached profile + logout; отдельный API TTL=2 | отозванный/истёкший token 401 | student-tests.json |
|
||||
| Реальная роль Valkey | запрос User → TTL ключа | TTL в диапазоне 1–60; fallback работает | student-tests.json |
|
||||
| Гонка username | 8 одновременных регистраций | один 201, семь 409 | student-tests.json |
|
||||
| Rollback чата | существующий и несуществующий участники | 400, количество чатов не меняется, сирот нет | student-tests.json |
|
||||
| Конкурентная запись/пагинация | 100 сообщений из 8 потоков, страницы по 7 | 100 уникальных ID без потерь; чужой cursor 400 | student-tests.json |
|
||||
| Индекс истории | `python3 student-tests/explain.py` | Index Scan messages_history, без Seq Scan | explain.json, explain.txt |
|
||||
| Отказы зависимостей | `python3 student-tests/verify.py` | Valkey fallback 200; PostgreSQL 503; анонимный 401 | student-tests.json |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Полные пути: все файлы доказательств из таблицы находятся в [evidence](evidence).
|
||||
GitHub integration workflow добавлен отдельно от исходной проверки контракта;
|
||||
на Gitea наличие файла само по себе не означает запуска CI. Доказательства здесь
|
||||
получены локально, CI-status не заявляется.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Docker Desktop aarch64, 10 доступных CPU, 8 319 504 384 байта RAM VM (~7.75 GiB).
|
||||
Это функциональная проверка, не оценка максимальной производительности.
|
||||
HTTP: 8 клиентских потоков, 100 сообщений; отдельная гонка из 8 регистраций.
|
||||
EXPLAIN: 10 000 синтетических сообщений в одном чате, cursor около позиции 9000,
|
||||
LIMIT 51 (50 + один элемент для next_cursor), один прогон, тёплый buffer cache
|
||||
после INSERT/ANALYZE. Данные эксперимента откатываются транзакцией.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
Гипотеза: составной B-tree позволяет прочитать только следующую страницу,
|
||||
вместо сканирования истории с начала. Получен `Index Scan using messages_history`,
|
||||
51 строка, 4 shared hit blocks, без чтений диска. Последний прогон: Execution Time
|
||||
0.019 ms, Planning Time 0.063 ms. Актуальные повторные результаты — в explain.json.
|
||||
Это подтверждает выбор плана, но не cold-cache latency и не throughput API;
|
||||
RPS/p50/p95/p99 и CPU/RAM процесса не измерялись и не заявляются.
|
||||
|
||||
| Воздействие | Ожидание | Последний наблюдаемый результат | Потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Restart API + PostgreSQL + Valkey | тот же токен и история | persistence PASS | нет потерь проверенных данных |
|
||||
| Остановка Valkey | fallback, ready 200 | User 200 за 0.4205 s; запись успешна | нет |
|
||||
| Остановка PostgreSQL | bounded 503, live 200 | 503 за 3.009 s; ready 503, anonymous 401 | подтверждённое сообщение сохранено |
|
||||
| Запуск PostgreSQL после отказа | возвращается готовность | 1.045 s ожидания после `compose start` | нет в проверенном сценарии |
|
||||
| SESSION_TTL_SECONDS=2 | expiry без продления | через 2.2 s token 401 | ожидаемый отзыв доступа |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Числа повторного запуска могут отличаться; машинные результаты каждого последнего
|
||||
прогона находятся в student-tests.json. Время восстановления отсчитывается после
|
||||
завершения compose start, а не от начала аварии. Штатный stop/restart не моделирует
|
||||
поломку диска или потерю питания. Секреты/токены в доказательства не записываются.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
## Ограничения
|
||||
|
||||
Один PostgreSQL — точка отказа; HA, backup/restore и исследования уровня 5
|
||||
не входят в выбранную оценку. Успешный COMMIT использует стандартные fsync и
|
||||
synchronous_commit PostgreSQL, но не гарантирует выживание при потере volume.
|
||||
HTTP допустим здесь только на loopback для синтетических данных.
|
||||
Нет фоновой уборки истёкших сессий, rate limiting и изменения профилей.
|
||||
При будущем редактировании профиля потребуется явная инвалидация Valkey.
|
||||
|
||||
Keyset гарантирует отсутствие повторов на неизменной истории; snapshot между
|
||||
страницами не создаётся. При конкурентных вставках поздний COMMIT с более ранним
|
||||
created_at может оказаться за уже пройденным cursor; это не протокол доставки
|
||||
событий. Проверка истории после подтверждённой записи читает актуальную БД.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Atomic, serialized, versioned migrations; changed applied files are rejected."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(Path(os.environ["DATABASE_URL_FILE"]).read_text().strip()) as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(20260002)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL)")
|
||||
for path in sorted(Path("migrations").glob("*.sql")):
|
||||
sql = path.read_text()
|
||||
digest = hashlib.sha256(sql.encode()).hexdigest()
|
||||
row = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
||||
if row:
|
||||
if row[0] != digest:
|
||||
raise RuntimeError("Applied migration changed: " + path.name)
|
||||
continue
|
||||
conn.execute(sql)
|
||||
conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name,digest))
|
||||
print("Applied", path.name)
|
||||
print("Migrations OK")
|
||||
@@ -0,0 +1,20 @@
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
argon2-cffi==23.1.0
|
||||
argon2-cffi-bindings==26.1.0
|
||||
cffi==2.1.1
|
||||
click==8.5.0
|
||||
fastapi==0.115.6
|
||||
h11==0.16.0
|
||||
idna==3.20
|
||||
psycopg==3.2.6
|
||||
psycopg-binary==3.2.6
|
||||
psycopg-pool==3.3.3
|
||||
pycparser==3.12
|
||||
pydantic==2.14.1
|
||||
pydantic_core==2.50.1
|
||||
redis==5.2.1
|
||||
starlette==0.41.3
|
||||
typing-inspection==0.4.4
|
||||
typing_extensions==4.16.0
|
||||
uvicorn==0.34.0
|
||||
+460
@@ -0,0 +1,460 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 2 PostgreSQL messenger, adapted from the author's lab 1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import hashlib
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from contextlib import asynccontextmanager
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests
|
||||
import redis
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
import uvicorn
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
LOG = logging.getLogger("messenger")
|
||||
|
||||
|
||||
def env_int(name: str, default: int, minimum: int = 0) -> int:
|
||||
try:
|
||||
value = int(os.environ.get(name, str(default)))
|
||||
except ValueError as exc:
|
||||
raise SystemExit("%s must be an integer" % name) from exc
|
||||
if value < minimum:
|
||||
raise SystemExit("%s must be at least %s" % (name, minimum))
|
||||
return value
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class Health(StrictModel):
|
||||
status: str = Field(pattern="^ok$")
|
||||
|
||||
|
||||
class User(StrictModel):
|
||||
id: uuid.UUID
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def non_blank_password(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("password must not be blank")
|
||||
return value
|
||||
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def non_blank_display_name(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("display_name must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class Chat(StrictModel):
|
||||
id: uuid.UUID
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def non_blank_title(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def unique_members(cls, value: list[uuid.UUID]) -> list[uuid.UUID]:
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return value
|
||||
|
||||
|
||||
class Message(StrictModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def non_blank_text(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("text must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class ChatPage(StrictModel):
|
||||
items: list[Chat]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
|
||||
class MessagePage(StrictModel):
|
||||
items: list[Message]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
|
||||
class ErrorDetails(StrictModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(StrictModel):
|
||||
error: ErrorDetails
|
||||
|
||||
|
||||
def valid_uuid(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
try:
|
||||
return str(uuid.UUID(value)) == value.lower()
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def make_cursor(scope: str, item: dict[str, Any]) -> str:
|
||||
raw = json.dumps(
|
||||
{"v": 1, "scope": scope, "created_at": item["created_at"], "id": item["id"]},
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def read_cursor(value: str, scope: str) -> Tuple[str, str]:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
||||
data = json.loads(raw)
|
||||
if set(data) != {"v", "scope", "created_at", "id"}:
|
||||
raise ValueError
|
||||
if data["v"] != 1 or data["scope"] != scope or not valid_uuid(data["id"]):
|
||||
raise ValueError
|
||||
datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
|
||||
return data["created_at"], data["id"]
|
||||
except (ValueError, TypeError, AttributeError, UnicodeError, json.JSONDecodeError, binascii.Error):
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor") from None
|
||||
|
||||
|
||||
|
||||
def secret(name):
|
||||
return Path(os.environ[name + "_FILE"]).read_text().strip()
|
||||
|
||||
POOL = ConnectionPool(secret("DATABASE_URL"), min_size=1, max_size=8, timeout=3,
|
||||
max_waiting=32, open=False, check=ConnectionPool.check_connection,
|
||||
kwargs={"row_factory": dict_row, "connect_timeout": 3,
|
||||
"options": "-c statement_timeout=3000 -c lock_timeout=2000"})
|
||||
CACHE = redis.Redis.from_url(secret("CACHE_URL"), socket_connect_timeout=0.2,
|
||||
socket_timeout=0.2, decode_responses=True)
|
||||
HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DUMMY_HASH = HASHER.hash(secrets.token_urlsafe(32))
|
||||
TTL = env_int("SESSION_TTL_SECONDS", 3600, 1)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
POOL.open()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
POOL.close()
|
||||
CACHE.close()
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — Lab 2", version="2.0.0", lifespan=lifespan)
|
||||
|
||||
|
||||
def wire(row):
|
||||
return {k: (v.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
if isinstance(v, datetime) else str(v) if isinstance(v, uuid.UUID) else v)
|
||||
for k, v in row.items()}
|
||||
|
||||
|
||||
def query(sql, params=()):
|
||||
with POOL.connection() as conn:
|
||||
return [wire(row) for row in conn.execute(sql, params).fetchall()]
|
||||
|
||||
|
||||
def profile(user_id):
|
||||
key = "user:" + user_id
|
||||
try:
|
||||
value = CACHE.get(key)
|
||||
if value:
|
||||
return json.loads(value)
|
||||
except (redis.RedisError, ValueError):
|
||||
pass
|
||||
rows = query("SELECT id, username, display_name, created_at FROM users WHERE id=%s", (user_id,))
|
||||
if not rows:
|
||||
raise ApiError(401, "unauthorized", "Invalid session")
|
||||
user = rows[0]
|
||||
try:
|
||||
CACHE.setex(key, 60, json.dumps(user))
|
||||
except redis.RedisError:
|
||||
pass
|
||||
return user
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def bearer(authorization):
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise ApiError(401, "unauthorized", "Bearer session required")
|
||||
token = authorization[7:]
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
|
||||
raise ApiError(401, "unauthorized", "Invalid session")
|
||||
return token_hash(token)
|
||||
|
||||
|
||||
def current_user(authorization: Optional[str] = Header(default=None)):
|
||||
digest = bearer(authorization)
|
||||
rows = query("SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()", (digest,))
|
||||
if not rows:
|
||||
raise ApiError(401, "unauthorized", "Invalid session")
|
||||
return profile(rows[0]["user_id"])
|
||||
|
||||
|
||||
def visible_chat(chat_id, actor_id):
|
||||
if not valid_uuid(chat_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid chat id")
|
||||
rows = query("SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s", (chat_id, actor_id))
|
||||
if not rows:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
return chat_members(rows)[0]
|
||||
|
||||
|
||||
def chat_members(rows):
|
||||
if rows:
|
||||
members = query("SELECT chat_id, user_id FROM members WHERE chat_id=ANY(%s::uuid[]) ORDER BY user_id", ([r["id"] for r in rows],))
|
||||
grouped = {r["id"]: [] for r in rows}
|
||||
for m in members:
|
||||
grouped[m["chat_id"]].append(m["user_id"])
|
||||
for row in rows:
|
||||
row["member_ids"] = grouped[row["id"]]
|
||||
return rows
|
||||
|
||||
|
||||
def page_args(request, scope, limit, cursor):
|
||||
if set(request.query_params).difference({"limit", "cursor"}):
|
||||
raise ApiError(400, "invalid_request", "Invalid query parameters")
|
||||
return limit, read_cursor(cursor, scope) if cursor is not None else None
|
||||
|
||||
|
||||
def page(rows, limit, scope):
|
||||
return {"items": rows[:limit], "next_cursor": make_cursor(scope, rows[limit-1]) if len(rows)>limit else None}
|
||||
def request_id(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
|
||||
|
||||
def error_response(request: Request, status: int, code: str, message: str) -> JSONResponse:
|
||||
rid = request_id(request)
|
||||
response = JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": rid}},
|
||||
)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
if status == 401:
|
||||
response.headers["WWW-Authenticate"] = ('Basic realm="messenger", charset="UTF-8"'
|
||||
if request.url.path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"')
|
||||
return response
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_envelope(request: Request, call_next: Any) -> JSONResponse:
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
LOG.error("request_id=%s unexpected error", request_id(request))
|
||||
response = error_response(request, 500, "internal_error", "Internal server error")
|
||||
response.headers["X-Request-Id"] = request_id(request)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, error: ApiError) -> JSONResponse:
|
||||
return error_response(request, error.status, error.code, error.message)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, _error: RequestValidationError) -> JSONResponse:
|
||||
return error_response(request, 400, "invalid_request", "Request validation failed")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(request: Request, error: StarletteHTTPException) -> JSONResponse:
|
||||
if error.status_code == 404:
|
||||
return error_response(request, 404, "not_found", "Resource not found")
|
||||
return error_response(request, error.status_code, "invalid_request", "Request failed")
|
||||
|
||||
|
||||
async def require_json(request: Request) -> None:
|
||||
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if content_type != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Content-Type must be application/json")
|
||||
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.Error)
|
||||
@app.exception_handler(PoolTimeout)
|
||||
@app.exception_handler(TooManyRequests)
|
||||
async def database_error(request, error):
|
||||
return error_response(request, 503, "unavailable", "Database temporarily unavailable")
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
def health_ready():
|
||||
query("SELECT 1 FROM schema_migrations LIMIT 1")
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201, dependencies=[Depends(require_json)])
|
||||
def create_user(payload: CreateUser):
|
||||
password_hash = HASHER.hash(payload.password)
|
||||
try:
|
||||
return query("INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at",
|
||||
(uuid.uuid4(), payload.username, payload.display_name, password_hash))[0]
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409, "conflict", "Username already exists") from None
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def login(request: Request, authorization: Optional[str] = Header(default=None)):
|
||||
# CPU/SQL work runs in FastAPI's worker pool, not in the event loop.
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
if await request.body():
|
||||
raise ApiError(400, "invalid_request", "Session request must not have a body")
|
||||
return await run_in_threadpool(login_sync, authorization)
|
||||
|
||||
|
||||
def login_sync(authorization):
|
||||
try:
|
||||
if not authorization or not authorization.startswith("Basic "):
|
||||
raise ValueError
|
||||
username, password = base64.b64decode(authorization[6:], validate=True).decode("utf-8").split(":", 1)
|
||||
if not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128:
|
||||
raise ValueError
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials") from None
|
||||
users = query("SELECT * FROM users WHERE username=%s", (username,))
|
||||
try:
|
||||
HASHER.verify(users[0]["password_hash"] if users else DUMMY_HASH, password)
|
||||
except VerificationError:
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials") from None
|
||||
if not users:
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials")
|
||||
token = secrets.token_urlsafe(32)
|
||||
expiry = query("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at",
|
||||
(token_hash(token), users[0]["id"], TTL))[0]["expires_at"]
|
||||
user = users[0]
|
||||
del user["password_hash"]
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": expiry, "user": user}
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(actor=Depends(current_user), authorization: Optional[str] = Header(default=None)):
|
||||
query("DELETE FROM sessions WHERE token_hash=%s RETURNING user_id", (bearer(authorization),))
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
def get_me(actor=Depends(current_user)):
|
||||
return actor
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201, dependencies=[Depends(require_json)])
|
||||
def create_chat(payload: CreateChat, actor=Depends(current_user)):
|
||||
members = [str(m) for m in payload.member_ids]
|
||||
if actor["id"] not in members:
|
||||
raise ApiError(400, "invalid_request", "The current user must be a member")
|
||||
try:
|
||||
with POOL.connection() as conn:
|
||||
chat = wire(conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (uuid.uuid4(),payload.title)).fetchone())
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany("INSERT INTO members(chat_id,user_id) VALUES (%s,%s)", [(chat["id"],m) for m in members])
|
||||
chat["member_ids"] = members
|
||||
return chat
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise ApiError(400, "invalid_request", "All chat members must exist") from None
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(request: Request, limit: int = Query(50,ge=1,le=100), cursor: Optional[str] = Query(None,min_length=1), actor=Depends(current_user)):
|
||||
scope = "chats:" + actor["id"]
|
||||
limit, after = page_args(request,scope,limit,cursor)
|
||||
sql = "SELECT c.* FROM chats c JOIN members m ON c.id=m.chat_id WHERE m.user_id=%s"
|
||||
params = [actor["id"]]
|
||||
if after:
|
||||
sql += " AND (c.created_at,c.id) > (%s,%s)"
|
||||
params.extend(after)
|
||||
rows = query(sql + " ORDER BY c.created_at,c.id LIMIT %s", params + [limit+1])
|
||||
return page(chat_members(rows),limit,scope)
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(chat_id: str, actor=Depends(current_user)):
|
||||
return visible_chat(chat_id,actor["id"])
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201, dependencies=[Depends(require_json)])
|
||||
def create_message(chat_id: str, payload: CreateMessage, actor=Depends(current_user)):
|
||||
visible_chat(chat_id,actor["id"])
|
||||
return query("INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *", (uuid.uuid4(),chat_id,actor["id"],payload.text))[0]
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(request: Request, chat_id: str, limit: int = Query(50,ge=1,le=100), cursor: Optional[str] = Query(None,min_length=1), actor=Depends(current_user)):
|
||||
visible_chat(chat_id,actor["id"])
|
||||
scope = "messages:" + chat_id
|
||||
limit,after = page_args(request,scope,limit,cursor)
|
||||
sql = "SELECT * FROM messages WHERE chat_id=%s"
|
||||
params = [chat_id]
|
||||
if after:
|
||||
sql += " AND (created_at,id) > (%s,%s)"
|
||||
params.extend(after)
|
||||
return page(query(sql+" ORDER BY created_at,id LIMIT %s",params+[limit+1]),limit,scope)
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app, host=os.environ.get("APP_HOST","0.0.0.0"), port=env_int("APP_PORT",8080,1))
|
||||
@@ -0,0 +1,66 @@
|
||||
name: mtusi-lab2
|
||||
x-app: &app
|
||||
build: .
|
||||
image: mtusi-messenger:lab2
|
||||
environment: &env
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: postgres
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
secrets: [database_url, cache_url]
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.6-bookworm
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets: [postgres_password]
|
||||
volumes: [postgres-data:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'pg_isready -U messenger -d messenger']
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
valkey:
|
||||
image: valkey/valkey:8.0.2-alpine
|
||||
command: [valkey-server, --appendonly, 'yes', --maxmemory, 64mb, --maxmemory-policy, allkeys-lru]
|
||||
volumes: [valkey-data:/data]
|
||||
healthcheck:
|
||||
test: [CMD, valkey-cli, ping]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
migrate:
|
||||
<<: *app
|
||||
command: [python, app/migrate.py]
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
api:
|
||||
<<: *app
|
||||
ports: ['127.0.0.1:${HOST_PORT:-8080}:8080']
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
valkey: {condition: service_healthy}
|
||||
expiry-api:
|
||||
<<: *app
|
||||
profiles: [test]
|
||||
environment:
|
||||
<<: *env
|
||||
SESSION_TTL_SECONDS: 2
|
||||
ports: ['127.0.0.1:8082:8080']
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
volumes:
|
||||
postgres-data:
|
||||
valkey-data:
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,74 @@
|
||||
[
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 16.24,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 78,
|
||||
"Actual Startup Time": 0.005,
|
||||
"Actual Total Time": 0.009,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_history",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 371.12,
|
||||
"Plan Rows": 1185,
|
||||
"Plan Width": 78,
|
||||
"Actual Startup Time": 0.004,
|
||||
"Actual Total Time": 0.007,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "((chat_id = '888e913d-fb7a-4aa8-8fab-6d302ee925c2'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:09+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 39,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.063,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.019
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
[
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 16.24,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 78,
|
||||
"Actual Startup Time": 0.005,
|
||||
"Actual Total Time": 0.009,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_history",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 371.12,
|
||||
"Plan Rows": 1185,
|
||||
"Plan Width": 78,
|
||||
"Actual Startup Time": 0.004,
|
||||
"Actual Total Time": 0.007,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "((chat_id = '888e913d-fb7a-4aa8-8fab-6d302ee925c2'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:09+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 39,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.063,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.019
|
||||
}
|
||||
]
|
||||
PASS: 10000 messages; indexed keyset page after 9000; experiment rolled back
|
||||
@@ -0,0 +1,3 @@
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"before": [
|
||||
{
|
||||
"Name": "/mtusi-lab2-api-1",
|
||||
"Id": "be19ec097578692a63ffc49eff4a58cd451854d5fe95822c7ce363a2c667e409",
|
||||
"StartedAt": "2026-10-29T13:20:02.353966763Z"
|
||||
},
|
||||
{
|
||||
"Name": "/mtusi-lab2-postgres-1",
|
||||
"Id": "bffa85f567e255fd4b619a151601a024c777777feac1b208268f62188fa98608",
|
||||
"StartedAt": "2026-10-29T13:14:34.459669389Z"
|
||||
},
|
||||
{
|
||||
"Name": "/mtusi-lab2-valkey-1",
|
||||
"Id": "549e49bd8ec7220c09a68c030c52b0a3e13c1c8e3d2331a3c22e84034d23a4c7",
|
||||
"StartedAt": "2026-10-29T13:14:28.072368052Z"
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"Name": "/mtusi-lab2-api-1",
|
||||
"Id": "be19ec097578692a63ffc49eff4a58cd451854d5fe95822c7ce363a2c667e409",
|
||||
"StartedAt": "2026-10-29T13:20:09.028900585Z"
|
||||
},
|
||||
{
|
||||
"Name": "/mtusi-lab2-postgres-1",
|
||||
"Id": "bffa85f567e255fd4b619a151601a024c777777feac1b208268f62188fa98608",
|
||||
"StartedAt": "2026-10-29T13:20:08.810265501Z"
|
||||
},
|
||||
{
|
||||
"Name": "/mtusi-lab2-valkey-1",
|
||||
"Id": "549e49bd8ec7220c09a68c030c52b0a3e13c1c8e3d2331a3c22e84034d23a4c7",
|
||||
"StartedAt": "2026-10-29T13:20:08.904470501Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"registration_race": {
|
||||
"201": 1,
|
||||
"409": 7
|
||||
},
|
||||
"unicode_password_with_colon": "PASS",
|
||||
"password_storage": "Argon2id; no plaintext",
|
||||
"rollback": "PASS: chat count unchanged after failed member FK",
|
||||
"validation_and_access": "PASS",
|
||||
"concurrent_messages": "100/100; pages of 7; no loss or duplicates; cross-chat cursor rejected",
|
||||
"cache_ttl_seconds": 59,
|
||||
"valkey_outage": {
|
||||
"fallback_status": 200,
|
||||
"latency_seconds": 0.4205,
|
||||
"anonymous": 401,
|
||||
"ready": 200
|
||||
},
|
||||
"database_outage": {
|
||||
"authenticated": 503,
|
||||
"latency_seconds": 3.009,
|
||||
"anonymous": 401,
|
||||
"live": 200,
|
||||
"ready": 503
|
||||
},
|
||||
"database_recovery_seconds": 1.045,
|
||||
"committed_message_after_outage": "PASS",
|
||||
"logout": "PASS even with cached profile",
|
||||
"expiry": "PASS: SESSION_TTL_SECONDS=2",
|
||||
"migration_reapply": "PASS twice; all entity counts unchanged"
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"registration_race": {
|
||||
"201": 1,
|
||||
"409": 7
|
||||
},
|
||||
"unicode_password_with_colon": "PASS",
|
||||
"password_storage": "Argon2id; no plaintext",
|
||||
"rollback": "PASS: chat count unchanged after failed member FK",
|
||||
"validation_and_access": "PASS",
|
||||
"concurrent_messages": "100/100; pages of 7; no loss or duplicates; cross-chat cursor rejected",
|
||||
"cache_ttl_seconds": 59,
|
||||
"valkey_outage": {
|
||||
"fallback_status": 200,
|
||||
"latency_seconds": 0.4205,
|
||||
"anonymous": 401,
|
||||
"ready": 200
|
||||
},
|
||||
"database_outage": {
|
||||
"authenticated": 503,
|
||||
"latency_seconds": 3.009,
|
||||
"anonymous": 401,
|
||||
"live": 200,
|
||||
"ready": 503
|
||||
},
|
||||
"database_recovery_seconds": 1.045,
|
||||
"committed_message_after_outage": "PASS",
|
||||
"logout": "PASS even with cached profile",
|
||||
"expiry": "PASS: SESSION_TTL_SECONDS=2",
|
||||
"migration_reapply": "PASS twice; all entity counts unchanged"
|
||||
}
|
||||
PASS: all level 4 integration checks
|
||||
@@ -0,0 +1,3 @@
|
||||
/Users/sleepy13/Desktop/projects/vp/vp-lab1-fork/.venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
|
||||
warnings.warn(
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
@@ -0,0 +1,29 @@
|
||||
# План хранения (до реализации SQL)
|
||||
|
||||
Источник истины — PostgreSQL. users: UUID PK, UNIQUE username, Argon2id hash.
|
||||
chats: UUID PK; members: PK(chat_id,user_id), оба FK; messages: UUID PK,
|
||||
FK на чат и на пару участник/чат. sessions: SHA-256 случайного 256-битного токена
|
||||
(PK), FK user_id, абсолютный expires_at. Hash токена не заменяет password KDF.
|
||||
|
||||
Транзакции: регистрация — INSERT + UNIQUE; чат и все участники — один COMMIT
|
||||
(ошибка любого FK откатывает весь чат); сообщение — один INSERT/COMMIT;
|
||||
создание/отзыв сессии — отдельный COMMIT. Ответ 201 выдаётся после commit.
|
||||
Default PostgreSQL fsync/synchronous_commit включены. Миграции защищены
|
||||
advisory lock, версией и checksum; весь запуск атомарен.
|
||||
|
||||
Индекс истории (chat_id,created_at,id) соответствует WHERE chat_id=? AND
|
||||
(created_at,id)>(?,?) ORDER BY created_at,id LIMIT limit+1. OFFSET отсутствует.
|
||||
Членство индексируется в обе стороны; чаты — по (created_at,id).
|
||||
READ COMMITTED; snapshot между страницами нет. Конкурентный поздний COMMIT
|
||||
с ранним timestamp может оказаться за уже пройденным cursor; неизменная история
|
||||
обходится полностью. Это не механизм доставки событий.
|
||||
|
||||
Valkey — cache-aside неизменяемого публичного профиля пользователя на 60 секунд.
|
||||
Только /users/me и аутентифицированные запросы используют профиль; сессия ВСЕГДА
|
||||
проверяется в PostgreSQL, logout не зависит от кэша. При недоступности Valkey
|
||||
профиль читается из БД. Нет API редактирования/удаления профиля, поэтому
|
||||
инвалидация сейчас только TTL/eviction; при добавлении update нужна инвалидация.
|
||||
История не кэшируется: read-after-write обеспечивается чтением primary.
|
||||
|
||||
Pool: 1–8 соединений, очередь 32, ожидание 3s; connect 3s, SQL 3s, lock 2s.
|
||||
Valkey socket/connect timeout 0.2s. Сбой БД — 503, liveness остаётся 200.
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY, username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name varchar(100) NOT NULL CHECK (length(trim(display_name))>0),
|
||||
password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (id uuid PRIMARY KEY, title varchar(100) NOT NULL CHECK(length(trim(title))>0), created_at timestamptz NOT NULL DEFAULT clock_timestamp());
|
||||
CREATE TABLE members (chat_id uuid REFERENCES chats(id), user_id uuid REFERENCES users(id), PRIMARY KEY(chat_id,user_id));
|
||||
CREATE INDEX members_user_chat ON members(user_id,chat_id);
|
||||
CREATE TABLE messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id), sender_id uuid NOT NULL REFERENCES users(id), text varchar(4000) NOT NULL CHECK(length(trim(text))>0), created_at timestamptz NOT NULL DEFAULT clock_timestamp(), FOREIGN KEY(chat_id,sender_id) REFERENCES members(chat_id,user_id));
|
||||
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
|
||||
CREATE INDEX chats_order ON chats(created_at,id);
|
||||
CREATE TABLE sessions (token_hash char(64) PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id), expires_at timestamptz NOT NULL);
|
||||
CREATE INDEX sessions_expiry ON sessions(expires_at);
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Generate local-only synthetic credentials once; never overwrite them."""
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
os.umask(0o077)
|
||||
(root / "secrets").mkdir(exist_ok=True)
|
||||
p = root / "secrets/postgres_password"
|
||||
if not p.exists():
|
||||
p.write_text(secrets.token_hex(32))
|
||||
values = {"database_url": "postgresql://messenger:" + p.read_text().strip() + "@postgres:5432/messenger", "cache_url": "redis://valkey:6379/0"}
|
||||
for name, value in values.items():
|
||||
dest = root / "secrets" / name
|
||||
if not dest.exists():
|
||||
dest.write_text(value)
|
||||
# Docker Desktop bind-mounted secrets need read permission for container UID 10001.
|
||||
for name in ["postgres_password", "database_url", "cache_url"]:
|
||||
(root / "secrets" / name).chmod(0o644)
|
||||
env = root / ".env"
|
||||
if not env.exists():
|
||||
env.write_text("SESSION_TTL_SECONDS=3600\nHOST_PORT=8080\n")
|
||||
print("Local configuration ready (secrets not printed)")
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart postgres valkey api
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Run against an already started local Compose stack; save sanitized evidence."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def run(name, args):
|
||||
p = subprocess.run(args, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
(ROOT / "evidence" / name).write_text(p.stdout)
|
||||
print(p.stdout, end="", flush=True)
|
||||
p.check_returncode()
|
||||
|
||||
def states():
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q"], cwd=ROOT, text=True).split()
|
||||
data = json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True))
|
||||
return [{"Name": d["Name"], "Id": d["Id"], "StartedAt": d["State"]["StartedAt"]} for d in data]
|
||||
|
||||
run("check.txt", ["make", "check"])
|
||||
run("smoke.txt", ["make", "test"])
|
||||
before = states()
|
||||
run("persistence.txt", ["make", "test-persistence", "ACTION_SCRIPT=scripts/restart.sh"])
|
||||
after = states()
|
||||
for name in ("api", "postgres", "valkey"):
|
||||
b = next(x for x in before if x["Name"] == "/mtusi-lab2-" + name + "-1")
|
||||
a = next(x for x in after if x["Name"] == b["Name"])
|
||||
assert a["StartedAt"] != b["StartedAt"], name + " did not restart"
|
||||
(ROOT / "evidence/restart-containers.json").write_text(json.dumps({"before":before,"after":after},indent=2)+"\n")
|
||||
run("student-tests.txt", [sys.executable, "student-tests/verify.py"])
|
||||
run("explain.txt", [sys.executable, "student-tests/explain.py"])
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Repeatable 10,000-message keyset plan, rolled back after measurement."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
user,chat=str(uuid.uuid4()),str(uuid.uuid4())
|
||||
# All interpolated values are locally generated UUIDs, never request input.
|
||||
sql=f"""
|
||||
BEGIN;
|
||||
INSERT INTO users(id,username,display_name,password_hash) VALUES ('{user}','plan_{user.replace('-','')[:20]}','Synthetic EXPLAIN user','disabled');
|
||||
INSERT INTO chats(id,title) VALUES ('{chat}','EXPLAIN 10000');
|
||||
INSERT INTO members VALUES ('{chat}','{user}');
|
||||
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(),'{chat}','{user}','Synthetic message '||n,
|
||||
'2026-01-01T00:00:00Z'::timestamptz + n * interval '1 millisecond'
|
||||
FROM generate_series(1,10000) n;
|
||||
ANALYZE messages;
|
||||
EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON)
|
||||
SELECT * FROM messages WHERE chat_id='{chat}'
|
||||
AND (created_at,id)>('2026-01-01T00:00:09Z'::timestamptz,'00000000-0000-0000-0000-000000000000'::uuid)
|
||||
ORDER BY created_at,id LIMIT 51;
|
||||
ROLLBACK;
|
||||
"""
|
||||
raw=subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-qAt','-v','ON_ERROR_STOP=1'],input=sql,text=True,cwd=root)
|
||||
plan=json.loads(raw)
|
||||
text=json.dumps(plan,indent=2)
|
||||
assert 'messages_history' in text and 'Seq Scan' not in text, 'Expected indexed keyset plan'
|
||||
(root/'evidence/explain.json').write_text(text+'\n')
|
||||
print(text)
|
||||
print('PASS: 10000 messages; indexed keyset page after 9000; experiment rolled back')
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Level 4 integration evidence; only synthetic data in this Compose project."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(['docker','compose','--env-file','.env',*args], cwd=ROOT, input=input, text=True, stderr=subprocess.STDOUT)
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1','-c',statement).strip()
|
||||
|
||||
|
||||
def wait_ready(client):
|
||||
start=time.monotonic()
|
||||
while time.monotonic()-start < 60:
|
||||
try:
|
||||
client.call('GET','/health/ready',schema='Health')
|
||||
return round(time.monotonic()-start,3)
|
||||
except AssertionError:
|
||||
time.sleep(0.25)
|
||||
raise AssertionError('Recovery timeout')
|
||||
|
||||
|
||||
def main():
|
||||
results={}
|
||||
c=Client()
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
path='/api/v1/chats/'+chat['id']
|
||||
# Registration race must be resolved by a database unique constraint.
|
||||
body={'username':'race_'+uuid.uuid4().hex[:20], 'display_name':'Гонка', 'password':'тестовый:пароль🔒'}
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
statuses=list(pool.map(lambda _: Client().call('POST','/api/v1/users',[201,409],body=body)['status'],range(8)))
|
||||
check(statuses.count(201)==1 and statuses.count(409)==7,'Registration race')
|
||||
results['registration_race']={'201':1,'409':7}
|
||||
credential=base64.b64encode((body['username']+':'+body['password']).encode()).decode()
|
||||
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
|
||||
results['unicode_password_with_colon']='PASS'
|
||||
digest=sql("SELECT password_hash FROM users WHERE username='"+body['username']+"'")
|
||||
check(digest.startswith('$argon2id$') and body['password'] not in digest,'Password KDF')
|
||||
results['password_storage']='Argon2id; no plaintext'
|
||||
before=sql('SELECT count(*) FROM chats')
|
||||
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'Rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
|
||||
check(sql('SELECT count(*) FROM chats')==before,'Chat transaction was not rolled back')
|
||||
check(sql('SELECT count(*) FROM members m LEFT JOIN chats c ON m.chat_id=c.id WHERE c.id IS NULL')=='0','Orphan members')
|
||||
results['rollback']='PASS: chat count unchanged after failed member FK'
|
||||
for body in ({'text':' '},{'text':42},{'text':'x','sender_id':eve['id']}):
|
||||
c.call('POST',path+'/messages',400,actor=alice,body=body)
|
||||
c.call('POST',path+'/messages',400,actor=alice,raw=b'{',headers={'Content-Type':'application/json'})
|
||||
c.call('POST',path+'/messages',415,actor=alice,raw=b'text')
|
||||
c.call('GET',path,401)
|
||||
c.call('GET',path,404,actor=eve)
|
||||
results['validation_and_access']='PASS'
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
messages=list(pool.map(lambda i: Client().message(alice,chat,'Сообщение '+str(i))['json'],range(100)))
|
||||
found=[]; cursor=None
|
||||
while True:
|
||||
suffix='?limit=7'+('&cursor='+quote(cursor,safe='') if cursor else '')
|
||||
page=c.call('GET',path+'/messages'+suffix,actor=bob,schema='MessagePage')['json']
|
||||
found.extend(page['items']); cursor=page['next_cursor']
|
||||
if not cursor: break
|
||||
check(len(found)==100 and {m['id'] for m in found}=={m['id'] for m in messages},'Concurrent pagination')
|
||||
first=c.call('GET',path+'/messages?limit=1',actor=alice,schema='MessagePage')['json']
|
||||
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Other','member_ids':[alice['id']]},schema='Chat')['json']
|
||||
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(first['next_cursor']),400,actor=alice)
|
||||
results['concurrent_messages']='100/100; pages of 7; no loss or duplicates; cross-chat cursor rejected'
|
||||
# Real cache use, expiry and fallback; cached profiles never authenticate tokens.
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
cache_ttl=int(compose('exec','-T','valkey','valkey-cli','TTL','user:'+alice['id']).strip())
|
||||
check(0 < cache_ttl <= 60,'Profile cache not used')
|
||||
results['cache_ttl_seconds']=cache_ttl
|
||||
try:
|
||||
compose('stop','valkey')
|
||||
response=c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
c.message(alice,chat,'Cache unavailable')
|
||||
c.call('GET','/api/v1/users/me',401)
|
||||
c.call('GET','/health/ready',schema='Health')
|
||||
results['valkey_outage']={'fallback_status':response['status'],'latency_seconds':round(response['elapsed'],4),'anonymous':401,'ready':200}
|
||||
finally:
|
||||
compose('start','valkey')
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
before_msg=c.message(alice,chat,'Before DB outage')['json']
|
||||
try:
|
||||
compose('stop','postgres')
|
||||
response=c.call('GET','/api/v1/users/me',503,actor=alice)
|
||||
check(response['elapsed']<8,'DB outage not bounded')
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
c.call('GET','/api/v1/users/me',401)
|
||||
results['database_outage']={'authenticated':503,'latency_seconds':round(response['elapsed'],3),'anonymous':401,'live':200,'ready':503}
|
||||
finally:
|
||||
compose('start','postgres')
|
||||
results['database_recovery_seconds']=wait_ready(c)
|
||||
history=c.call('GET',path+'/messages?limit=100',actor=alice,schema='MessagePage')['json']
|
||||
while history['next_cursor']:
|
||||
history=c.call('GET',path+'/messages?limit=100&cursor='+quote(history['next_cursor']),actor=alice,schema='MessagePage')['json']
|
||||
check(before_msg in history['items'],'Committed message lost after outage')
|
||||
results['committed_message_after_outage']='PASS'
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice)
|
||||
results['logout']='PASS even with cached profile'
|
||||
# Independent API, same database, SESSION_TTL_SECONDS=2.
|
||||
compose('--profile','test','up','-d','expiry-api')
|
||||
try:
|
||||
short=Client('http://localhost:8082')
|
||||
wait_ready(short)
|
||||
actor=short.user('ttl')
|
||||
short.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
time.sleep(2.2)
|
||||
short.call('GET','/api/v1/users/me',401,actor=actor)
|
||||
results['expiry']='PASS: SESSION_TTL_SECONDS=2'
|
||||
finally:
|
||||
compose('--profile','test','stop','expiry-api')
|
||||
counts=sql('SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions)')
|
||||
compose('run','--rm','migrate')
|
||||
compose('run','--rm','migrate')
|
||||
check(counts==sql('SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions)'),'Migrations duplicated data')
|
||||
results['migration_reapply']='PASS twice; all entity counts unchanged'
|
||||
(ROOT/'evidence/student-tests.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps(results,ensure_ascii=False,indent=2))
|
||||
print('PASS: all level 4 integration checks')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user