Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99079c94c9 | ||
|
|
4080e2110a | ||
|
|
35a2642851 |
@@ -9,3 +9,4 @@ DATABASE_URL_FILE=/run/secrets/database_url
|
|||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||||
SESSION_STORE=postgres
|
SESSION_STORE=postgres
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
|
POSTGRES_PASSWORD=ahahaha_change
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
FROM python:3.11.7-slim-bookworm AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||||
|
|
||||||
|
FROM python:3.11.7-slim-bookworm AS runner
|
||||||
|
|
||||||
|
RUN useradd -u 10001 -m appuser
|
||||||
|
WORKDIR /home/appuser
|
||||||
|
|
||||||
|
COPY --from=builder /install /usr/local
|
||||||
|
COPY app.py .
|
||||||
|
|
||||||
|
USER appuser
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=5s --timeout=3s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready')"
|
||||||
|
|
||||||
|
ENV PYTHONUNBUFFERED=1
|
||||||
|
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||||
@@ -1,37 +1,129 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Бондаренко Мария Максимовна, БПИ2302
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 4
|
||||||
- Commit/PR: TODO после публикации
|
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Команды запуска и тестов
|
||||||
|
|
||||||
|
1. Создание локального окружения и секретов (.env):
|
||||||
|
cp .env.example .env
|
||||||
|
|
||||||
|
2. Сборка и запуск сервисов:
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
|
||||||
|
3. Ожидание готовности:
|
||||||
|
Приложение будет доступно после того, как все контейнеры перейдут в состояние healthy.
|
||||||
|
|
||||||
|
4. Запуск публичных тестов:
|
||||||
|
Базовый smoke-тест (проверка соответствия OpenAPI)
|
||||||
|
python3 tests/smoke.py --base-url http://localhost:8080
|
||||||
|
Тест сохранности данных при перезапуске stack
|
||||||
|
python3 tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080
|
||||||
|
|
||||||
|
5. Остановка и очистка:
|
||||||
|
Безопасная остановка без удаления данных:
|
||||||
|
docker compose down
|
||||||
|
Полный сброс тестовых данных (удаление volumes):
|
||||||
|
docker compose down --volumes
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Схема процессов и хранилищ
|
||||||
|
+-----------------------+
|
||||||
|
| FastAPI Application |
|
||||||
|
| (Container) |
|
||||||
|
+-----------+-----------+
|
||||||
|
|
|
||||||
|
+-------------------------+-------------------------+
|
||||||
|
| |
|
||||||
|
v v
|
||||||
|
+-------------------+ +-------------------+
|
||||||
|
| PostgreSQL | | Redis |
|
||||||
|
| (Container) | | (Container) |
|
||||||
|
| - Users | | - Sessions |
|
||||||
|
| - Chats | | (Key: |
|
||||||
|
| - Chat Members | | session:<token> |
|
||||||
|
| - Messages | | TTL: 3600s) |
|
||||||
|
+-------------------+ +-------------------+
|
||||||
|
|
||||||
|
## Источник истины и роль Redis
|
||||||
|
|
||||||
|
PostgreSQL -- реляционный источник истины для пользователей, структуры чатов, членства и текстов сообщений
|
||||||
|
Redis 7 -- хранилище оперативных сессий с авто-истечением по TTL. Сессии хранятся по ключу session:<token> со значением user_id. Для обеспечения сохранности сессий при перезапуске сервисов в compose.yaml включена RDB-персистентность (redis-server --save 60 1) и подключен persistent volume redisdata.
|
||||||
|
|
||||||
|
## Транзакционные границы и безопасность
|
||||||
|
|
||||||
|
Атомарность: Создание чатов и привязка участников выполняются в единой SQL-транзакции (conn.commit() при успехе, conn.rollback() при ошибке). Для предотвращения гонки при регистрации одинакового username используется обработка исключения psycopg2.errors.UniqueViolation с откатом транзакции (rollback).
|
||||||
|
Хеширование паролей: Использован KDF bcrypt с генерацией соли для предотвращения утечки незашифрованных паролей
|
||||||
|
Безопасные запросы: Все SQL-запросы параметризованы (используются кортежи %s), что исключает возможность SQL-инъекций
|
||||||
|
Миграции: Файл migrations/init.sql монтируется в /docker-entrypoint-initdb.d/init.sql контейнера PostgreSQL для чистой инициализации структуры БД при старте. Дополнительно init_db() в Python обеспечивает идемпотентный fallback. Таблица sessions была удалена из PostgreSQL, так как на оценку 4 источником истины для сессий является Redis
|
||||||
|
|
||||||
|
## Оптимизация пагинации сообщений
|
||||||
|
|
||||||
|
В запросе GET /api/v1/chats/{chat_id}/messages реализован курсорный подход на уровне SQL:
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||||
|
WHERE chat_id = %s AND (created_at, id) > (%s, %s)
|
||||||
|
ORDER BY created_at ASC, id ASC LIMIT %s;
|
||||||
|
Пагинация опирается на составной индекс idx_messages_chat_pagination (chat_id, created_at, id), исключая необходимость полного сканирования таблицы
|
||||||
|
|
||||||
|
### Доказательство эффективности индекса (EXPLAIN ANALYZE)
|
||||||
|
Для проверки пагинации было сгенерировано 10 000 сообщений. Запрос второй страницы (с курсором) показывает, что используется Index Scan, база читает ровно 50 строк (LIMIT) и не тратит время на полную сортировку таблицы.
|
||||||
|
|
||||||
|
Проверка:
|
||||||
|
docker compose exec postgres psql -U postgres -d messenger
|
||||||
|
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES ('11111111-1111-1111-1111-111111111111', 'testuser', 'Test', 'hash', NOW());
|
||||||
|
|
||||||
|
INSERT INTO chats (id, title, created_at)
|
||||||
|
VALUES ('22222222-2222-2222-2222-222222222222', 'Test Chat', NOW());
|
||||||
|
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT
|
||||||
|
gen_random_uuid(),
|
||||||
|
'22222222-2222-2222-2222-222222222222',
|
||||||
|
'11111111-1111-1111-1111-111111111111',
|
||||||
|
'Message ' || i,
|
||||||
|
NOW() + (i || ' seconds')::interval
|
||||||
|
FROM generate_series(1, 10000) AS i;
|
||||||
|
|
||||||
|
SET enable_bitmapscan = off;
|
||||||
|
|
||||||
|
Вывод в консоли:
|
||||||
|
Limit (cost=0.28..16.34 rows=3 width=572) (actual time=0.018..0.025 rows=50 loops=1)
|
||||||
|
Buffers: shared hit=3
|
||||||
|
-> Index Scan using idx_messages_chat_pagination on messages (cost=0.28..16.34 rows=3 width=572) (actual time=0.017..0.022 rows=50 loops=1)
|
||||||
|
Index Cond: ((chat_id = '22222222-2222-2222-2222-222222222222'::uuid) AND (ROW(created_at, id) > ROW('2026-11-05 13:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Buffers: shared hit=3
|
||||||
|
Planning:
|
||||||
|
Buffers: shared hit=22
|
||||||
|
Planning Time: 0.272 ms
|
||||||
|
Execution Time: 0.085 ms
|
||||||
|
(9 rows)
|
||||||
|
|
||||||
|
Вывод: время выполнения составило 0.085 мс, прочитано всего 3 страницы буферов, что доказывает отсутствие полного сканирования таблицы
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | python3 tests/smoke.py --base-url http://localhost:8080 | PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. | Логи терминала |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Сохранение данных | python3 tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080 (Для сред Linux/Mac предусмотрен эквивалентный скрипт scripts/restart.sh) | PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. | scripts/restart.bat / restart.sh |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Использование Redis для сессий | Проверка ключей через docker compose exec redis redis-cli keys "session:*" | Ключи сессий присутствуют в Redis с корректным TTL | app.py, compose.yaml |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Изоляция чужих чатов | tests/smoke.py (запрос GET /api/v1/chats/{id} чужим пользователем) | Возвращается статус 404 not_found без раскрытия факта существования | app.py (get_chat) |
|
||||||
|
| Обработка ошибок валидации | Запрос с некорректными полями / незаполненными строками | Возвращается 400 invalid_request с заголовком X-Request-Id | app.py (validation_exception_handler) |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Обработка недоступности Redis | Остановка контейнера redis (docker compose stop redis) | /health/ready возвращает 503, бизнес-эндпоинты не пускают анонимов | app.py (health_ready, get_current_user_from_token) |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| docker compose restart (в рамках test-persistence) | Сохранение пользователей, сообщений в Postgres и сессий в Redis. | Все запросы со старым Bearer-токеном продолжают успешно работать. | 0 сек потери данных, восстановление ~4-5 сек (время старта контейнеров) |
|
||||||
|
| Неверный пароль при входе | 401 Unauthorized с заголовком WWW-Authenticate: Basic ... | Возвращен 401 и корректный challenge header | Мгновенно (0 сек) |
|
||||||
|
| Отключение контейнера Redis | Приложение определяет падение зависимости на /health/ready и блокирует доступ с ошибкой 503 | GET /health/ready вернул 503 Database or Redis unavailable | Восстановление происходит автоматически при старте Redis |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
В текущей реализации соединение с PostgreSQL создается на каждый запрос (psycopg2.connect), а не через пул соединений. Для production следует использовать psycopg2.pool или ORM
|
||||||
|
Redis настроен с базовым RDB-снапшотом (раз в 60 секунд). При аппаратном сбое возможна потеря сессий, созданных за последнюю минуту
|
||||||
@@ -0,0 +1,588 @@
|
|||||||
|
import os
|
||||||
|
import base64
|
||||||
|
import secrets
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import List, Optional
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import psycopg2
|
||||||
|
import psycopg2.extras
|
||||||
|
import bcrypt
|
||||||
|
from fastapi import FastAPI, Header, HTTPException, Query, Response, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||||
|
|
||||||
|
import redis
|
||||||
|
|
||||||
|
app = FastAPI(title="MTUSI Messenger — lab2", version="1.2.0")
|
||||||
|
|
||||||
|
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/messenger")
|
||||||
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
|
||||||
|
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||||
|
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
|
||||||
|
|
||||||
|
def get_db_connection():
|
||||||
|
conn = psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username VARCHAR(32) UNIQUE NOT NULL,
|
||||||
|
display_name VARCHAR(100) NOT NULL,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title VARCHAR(100) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_members (
|
||||||
|
chat_id UUID REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
text VARCHAR(4000) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_chat_pagination ON messages(chat_id, created_at, id);
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
def startup_event():
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
def generate_request_id() -> str:
|
||||||
|
return uuid.uuid4().hex
|
||||||
|
|
||||||
|
def make_error_response(
|
||||||
|
status_code: int,
|
||||||
|
code: str,
|
||||||
|
message: str,
|
||||||
|
req_id: str,
|
||||||
|
extra_headers: Optional[dict] = None,
|
||||||
|
) -> JSONResponse:
|
||||||
|
headers = {"X-Request-Id": req_id, "X-Instance-Id": "instance-1"}
|
||||||
|
if extra_headers:
|
||||||
|
headers.update(extra_headers)
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status_code,
|
||||||
|
headers=headers,
|
||||||
|
content={
|
||||||
|
"error": {
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"request_id": req_id,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
|
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||||
|
return make_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code="invalid_request",
|
||||||
|
message="Validation error in request body or parameters",
|
||||||
|
req_id=req_id
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||||
|
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||||
|
headers = {"X-Request-Id": req_id, "X-Instance-Id": "instance-1"}
|
||||||
|
if exc.headers:
|
||||||
|
headers.update(exc.headers)
|
||||||
|
|
||||||
|
detail = exc.detail
|
||||||
|
if isinstance(detail, dict) and "error" in detail:
|
||||||
|
detail["error"]["request_id"] = req_id
|
||||||
|
return JSONResponse(status_code=exc.status_code, headers=headers, content=detail)
|
||||||
|
|
||||||
|
code_map = {
|
||||||
|
400: "invalid_request",
|
||||||
|
401: "unauthorized",
|
||||||
|
404: "not_found",
|
||||||
|
409: "conflict",
|
||||||
|
413: "payload_too_large",
|
||||||
|
415: "unsupported_media_type",
|
||||||
|
429: "rate_limited",
|
||||||
|
503: "unavailable",
|
||||||
|
500: "internal_error",
|
||||||
|
}
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=exc.status_code,
|
||||||
|
headers=headers,
|
||||||
|
content={
|
||||||
|
"error": {
|
||||||
|
"code": code_map.get(exc.status_code, "internal_error"),
|
||||||
|
"message": str(detail),
|
||||||
|
"request_id": req_id,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
class CreateUser(BaseModel):
|
||||||
|
model_config = ConfigDict(extra='forbid')
|
||||||
|
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||||
|
display_name: str = Field(..., min_length=1, max_length=100)
|
||||||
|
password: str = Field(..., min_length=12, max_length=128)
|
||||||
|
|
||||||
|
@field_validator("display_name", "password")
|
||||||
|
def not_blank(cls, v):
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("Must not be blank")
|
||||||
|
return v
|
||||||
|
|
||||||
|
class CreateChat(BaseModel):
|
||||||
|
model_config = ConfigDict(extra='forbid')
|
||||||
|
title: str = Field(..., min_length=1, max_length=100)
|
||||||
|
member_ids: List[uuid.UUID] = Field(..., min_items=1, max_items=100)
|
||||||
|
|
||||||
|
@field_validator("title")
|
||||||
|
def not_blank(cls, v):
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("Must not be blank")
|
||||||
|
return v
|
||||||
|
|
||||||
|
class CreateMessage(BaseModel):
|
||||||
|
model_config = ConfigDict(extra='forbid')
|
||||||
|
text: str = Field(..., min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
@field_validator("text")
|
||||||
|
def not_blank(cls, v):
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("Must not be blank")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@app.get("/health/live")
|
||||||
|
def health_live(response: Response):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
@app.get("/health/ready")
|
||||||
|
def health_ready(response: Response):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
try:
|
||||||
|
conn = get_db_connection()
|
||||||
|
conn.close()
|
||||||
|
redis_client.ping()
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=503, detail="Database or Redis unavailable")
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
@app.post("/api/v1/users", status_code=201)
|
||||||
|
def register_user(body: CreateUser, response: Response):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
|
||||||
|
password_hash = bcrypt.hashpw(body.password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
||||||
|
user_id = str(uuid.uuid4())
|
||||||
|
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES (%s, %s, %s, %s, %s)",
|
||||||
|
(user_id, body.username, body.display_name, password_hash, created_at)
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except psycopg2.errors.UniqueViolation:
|
||||||
|
conn.rollback()
|
||||||
|
raise HTTPException(status_code=409, detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}})
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": user_id,
|
||||||
|
"username": body.username,
|
||||||
|
"display_name": body.display_name,
|
||||||
|
"created_at": created_at
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||||
|
def create_session(authorization: Optional[str] = Header(None), response: Response = None):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
|
||||||
|
if not authorization or not authorization.startswith("Basic "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Missing or invalid basic auth",
|
||||||
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
encoded = authorization.split(" ")[1]
|
||||||
|
decoded = base64.b64decode(encoded).decode("utf-8")
|
||||||
|
username, password = decoded.split(":", 1)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Invalid credentials format",
|
||||||
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
|
||||||
|
user = cur.fetchone()
|
||||||
|
|
||||||
|
if not user or not bcrypt.checkpw(password.encode('utf-8'), user['password_hash'].encode('utf-8')):
|
||||||
|
conn.close()
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Invalid credentials",
|
||||||
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
token = secrets.token_urlsafe(48)
|
||||||
|
redis_client.setex(f"session:{token}", SESSION_TTL_SECONDS, user['id'])
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||||
|
expires_at_str = expires_at.isoformat().replace("+00:00", "Z")
|
||||||
|
created_at_str = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"token": token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": expires_at_str,
|
||||||
|
"user": {
|
||||||
|
"id": user['id'],
|
||||||
|
"username": user['username'],
|
||||||
|
"display_name": user['display_name'],
|
||||||
|
"created_at": user['created_at'].isoformat().replace("+00:00", "Z") if isinstance(user['created_at'], datetime) else user['created_at']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_current_user_from_token(authorization: Optional[str] = Header(None)) -> dict:
|
||||||
|
if not authorization or not authorization.startswith("Bearer "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Missing or invalid bearer token",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
token = authorization.split(" ")[1]
|
||||||
|
|
||||||
|
try:
|
||||||
|
user_id = redis_client.get(f"session:{token}")
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=503, detail="Session store unavailable")
|
||||||
|
|
||||||
|
if not user_id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Invalid or expired session token",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="User not found",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": row['id'],
|
||||||
|
"username": row['username'],
|
||||||
|
"display_name": row['display_name'],
|
||||||
|
"created_at": row['created_at'].isoformat().replace("+00:00", "Z") if isinstance(row['created_at'], datetime) else row['created_at']
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||||
|
def revoke_session(authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
|
||||||
|
if not authorization or not authorization.startswith("Bearer "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Unauthorized",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
token = authorization.split(" ")[1]
|
||||||
|
|
||||||
|
deleted = redis_client.delete(f"session:{token}")
|
||||||
|
|
||||||
|
if not deleted:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Invalid session token",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
return Response(
|
||||||
|
status_code=204,
|
||||||
|
headers={
|
||||||
|
"X-Request-Id": req_id,
|
||||||
|
"X-Instance-Id": "instance-1"
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.get("/api/v1/users/me")
|
||||||
|
def current_user(response: Response, authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
return get_current_user_from_token(authorization)
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats", status_code=201)
|
||||||
|
def create_chat(body: CreateChat, response: Response, authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
user = get_current_user_from_token(authorization)
|
||||||
|
|
||||||
|
member_ids_str = [str(mid) for mid in body.member_ids]
|
||||||
|
|
||||||
|
if user["id"] not in member_ids_str:
|
||||||
|
raise HTTPException(status_code=400, detail="Caller must be in member_ids")
|
||||||
|
if len(member_ids_str) != len(set(member_ids_str)):
|
||||||
|
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for mid_str in member_ids_str:
|
||||||
|
cur.execute("SELECT id FROM users WHERE id = %s", (mid_str,))
|
||||||
|
if not cur.fetchone():
|
||||||
|
conn.close()
|
||||||
|
raise HTTPException(status_code=400, detail=f"User {mid_str} not found")
|
||||||
|
|
||||||
|
chat_id = str(uuid.uuid4())
|
||||||
|
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||||
|
(chat_id, body.title, created_at)
|
||||||
|
)
|
||||||
|
for mid_str in member_ids_str:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||||
|
(chat_id, mid_str)
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
conn.rollback()
|
||||||
|
conn.close()
|
||||||
|
raise HTTPException(status_code=500, detail="Internal error creating chat")
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": chat_id,
|
||||||
|
"title": body.title,
|
||||||
|
"member_ids": member_ids_str,
|
||||||
|
"created_at": created_at
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats")
|
||||||
|
def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response = None, authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
user = get_current_user_from_token(authorization)
|
||||||
|
|
||||||
|
if limit < 1 or limit > 100:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT c.id, c.title, c.created_at FROM chats c
|
||||||
|
JOIN chat_members cm ON c.id = cm.chat_id
|
||||||
|
WHERE cm.user_id = %s
|
||||||
|
ORDER BY c.created_at ASC, c.id ASC
|
||||||
|
""", (user["id"],))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
user_chats = []
|
||||||
|
for r in rows:
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r['id'],))
|
||||||
|
m_rows = cur.fetchall()
|
||||||
|
conn.close()
|
||||||
|
user_chats.append({
|
||||||
|
"id": r['id'],
|
||||||
|
"title": r['title'],
|
||||||
|
"member_ids": [m['user_id'] for m in m_rows],
|
||||||
|
"created_at": r['created_at'].isoformat().replace("+00:00", "Z") if isinstance(r['created_at'], datetime) else r['created_at']
|
||||||
|
})
|
||||||
|
|
||||||
|
start_idx = 0
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
parts = cursor.split("_")
|
||||||
|
c_time, c_id = parts[0], parts[1]
|
||||||
|
found = False
|
||||||
|
for idx, c in enumerate(user_chats):
|
||||||
|
if (c["created_at"], c["id"]) >= (c_time, c_id):
|
||||||
|
start_idx = idx if (c["created_at"], c["id"]) > (c_time, c_id) else idx + 1
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
if not found:
|
||||||
|
start_idx = len(user_chats)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid cursor format")
|
||||||
|
|
||||||
|
page_items = user_chats[start_idx:start_idx + limit]
|
||||||
|
next_cursor = None
|
||||||
|
if start_idx + limit < len(user_chats):
|
||||||
|
last = page_items[-1]
|
||||||
|
next_cursor = f"{last['created_at']}_{last['id']}"
|
||||||
|
|
||||||
|
return {"items": page_items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}")
|
||||||
|
def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
user = get_current_user_from_token(authorization)
|
||||||
|
|
||||||
|
chat_id_str = str(chat_id)
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT c.* FROM chats c
|
||||||
|
JOIN chat_members cm ON c.id = cm.chat_id
|
||||||
|
WHERE c.id = %s AND cm.user_id = %s
|
||||||
|
""", (chat_id_str, user["id"]))
|
||||||
|
chat = cur.fetchone()
|
||||||
|
if chat:
|
||||||
|
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id_str,))
|
||||||
|
members = cur.fetchall()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
if not chat:
|
||||||
|
raise HTTPException(status_code=404, detail="Chat not found")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": chat['id'],
|
||||||
|
"title": chat['title'],
|
||||||
|
"member_ids": [m['user_id'] for m in members],
|
||||||
|
"created_at": chat['created_at'].isoformat().replace("+00:00", "Z") if isinstance(chat['created_at'], datetime) else chat['created_at']
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||||
|
def create_message(chat_id: UUID, body: CreateMessage, response: Response, authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
user = get_current_user_from_token(authorization)
|
||||||
|
|
||||||
|
chat_id_str = str(chat_id)
|
||||||
|
conn = get_db_connection()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s
|
||||||
|
""", (chat_id_str, user["id"]))
|
||||||
|
if not cur.fetchone():
|
||||||
|
conn.close()
|
||||||
|
raise HTTPException(status_code=404, detail="Chat not found")
|
||||||
|
|
||||||
|
msg_id = str(uuid.uuid4())
|
||||||
|
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, %s)",
|
||||||
|
(msg_id, chat_id_str, user["id"], body.text, created_at)
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": msg_id,
|
||||||
|
"chat_id": chat_id_str,
|
||||||
|
"sender_id": user["id"],
|
||||||
|
"text": body.text,
|
||||||
|
"created_at": created_at
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||||
|
def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None, response: Response = None, authorization: Optional[str] = Header(None)):
|
||||||
|
req_id = generate_request_id()
|
||||||
|
response.headers["X-Request-Id"] = req_id
|
||||||
|
response.headers["X-Instance-Id"] = "instance-1"
|
||||||
|
user = get_current_user_from_token(authorization)
|
||||||
|
|
||||||
|
chat_id_str = str(chat_id)
|
||||||
|
conn = get_db_connection()
|
||||||
|
|
||||||
|
if limit < 1 or limit > 100:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||||
|
|
||||||
|
query = """
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||||
|
WHERE chat_id = %s
|
||||||
|
"""
|
||||||
|
params = [chat_id_str]
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
parts = cursor.split("_")
|
||||||
|
c_time, c_id = parts[0], parts[1]
|
||||||
|
query += " AND (created_at, id) > (%s, %s)"
|
||||||
|
params.extend([c_time, c_id])
|
||||||
|
except Exception:
|
||||||
|
conn.close()
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid cursor format")
|
||||||
|
|
||||||
|
query += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
||||||
|
|
||||||
|
params.append(limit + 1)
|
||||||
|
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(query, tuple(params))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
has_next = len(rows) > limit
|
||||||
|
page_items = rows[:limit]
|
||||||
|
|
||||||
|
formatted_msgs = []
|
||||||
|
for m in page_items:
|
||||||
|
formatted_msgs.append({
|
||||||
|
"id": m['id'],
|
||||||
|
"chat_id": m['chat_id'],
|
||||||
|
"sender_id": m['sender_id'],
|
||||||
|
"text": m['text'],
|
||||||
|
"created_at": m['created_at'].isoformat().replace("+00:00", "Z") if isinstance(m['created_at'], datetime) else m['created_at']
|
||||||
|
})
|
||||||
|
|
||||||
|
next_cursor = None
|
||||||
|
if has_next and formatted_msgs:
|
||||||
|
last = formatted_msgs[-1]
|
||||||
|
next_cursor = f"{last['created_at']}_{last['id']}"
|
||||||
|
|
||||||
|
return {"items": formatted_msgs, "next_cursor": next_cursor}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:15-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
- ./migrations/init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres -d messenger"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
command: redis-server --save 60 1 --loglevel warning
|
||||||
|
volumes:
|
||||||
|
- redisdata:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/messenger
|
||||||
|
- REDIS_URL=redis://redis:6379/0
|
||||||
|
- SESSION_TTL_SECONDS=3600
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready')"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
|
redisdata:
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 1,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 30.0,
|
||||||
|
"elapsed_seconds": 30.14,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 10199,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 338.388,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 15.0,
|
||||||
|
"p95": 31.0,
|
||||||
|
"p99": 47.0
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 1,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 10.0,
|
||||||
|
"elapsed_seconds": 10.062,
|
||||||
|
"concurrency": 2,
|
||||||
|
"successful_requests": 1284,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 127.609,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 16.0,
|
||||||
|
"p95": 32.0,
|
||||||
|
"p99": 47.0
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 1,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 10.0,
|
||||||
|
"elapsed_seconds": 10.656,
|
||||||
|
"concurrency": 32,
|
||||||
|
"successful_requests": 5569,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 522.616,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 62.0,
|
||||||
|
"p95": 78.0,
|
||||||
|
"p99": 94.0
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 1,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 10.0,
|
||||||
|
"elapsed_seconds": 10.156,
|
||||||
|
"concurrency": 8,
|
||||||
|
"successful_requests": 4663,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 459.137,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 16.0,
|
||||||
|
"p95": 32.0,
|
||||||
|
"p99": 47.0
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username VARCHAR(32) UNIQUE NOT NULL,
|
||||||
|
display_name VARCHAR(100) NOT NULL,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title VARCHAR(100) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_members (
|
||||||
|
chat_id UUID REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
text VARCHAR(4000) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_chat_pagination ON messages(chat_id, created_at, id);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
fastapi==0.110.0
|
||||||
|
uvicorn==0.28.0
|
||||||
|
pydantic==2.6.2
|
||||||
|
starlette==0.36.3
|
||||||
|
idna==3.6
|
||||||
|
anyio==4.3.0
|
||||||
|
sniffio==1.3.1
|
||||||
|
click==8.1.7
|
||||||
|
h11==0.14.0
|
||||||
|
annotated-types==0.6.0
|
||||||
|
psycopg2-binary==2.9.9
|
||||||
|
bcrypt==4.1.2
|
||||||
|
redis==5.0.1
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
@echo off
|
||||||
|
docker compose restart
|
||||||
|
exit /b %ERRORLEVEL%
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
docker compose restart
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import concurrent.futures
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
from client import Client
|
||||||
|
|
||||||
|
class TestMessengerLab4(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.client = Client()
|
||||||
|
self.alice = self.client.user("alice")
|
||||||
|
self.bob = self.client.user("bob")
|
||||||
|
self.eve = self.client.user("eve")
|
||||||
|
|
||||||
|
res = self.client.call(
|
||||||
|
'POST', '/api/v1/chats', 201,
|
||||||
|
actor=self.alice,
|
||||||
|
body={"title": "Test Chat", "member_ids": [self.alice["id"], self.bob["id"]]},
|
||||||
|
schema='Chat'
|
||||||
|
)
|
||||||
|
self.chat = res['json']
|
||||||
|
|
||||||
|
def test_unauthorized_access_to_chat(self):
|
||||||
|
self.client.call('GET', f"/api/v1/chats/{self.chat['id']}", 404, actor=self.eve)
|
||||||
|
|
||||||
|
def test_empty_message(self):
|
||||||
|
self.client.call('POST', f"/api/v1/chats/{self.chat['id']}/messages", 400, actor=self.alice, body={"text": ""})
|
||||||
|
|
||||||
|
def test_malformed_json(self):
|
||||||
|
url = self.client.base + f"/api/v1/chats/{self.chat['id']}/messages"
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url,
|
||||||
|
data=b"{broken json content without quotes",
|
||||||
|
headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-User-Id": self.alice["id"]
|
||||||
|
},
|
||||||
|
method="POST"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req) as resp:
|
||||||
|
self.fail("Expected HTTP 400 for malformed JSON")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
self.assertEqual(e.code, 400)
|
||||||
|
body = json.loads(e.read().decode())
|
||||||
|
self.assertEqual(body["error"]["code"], "invalid_request")
|
||||||
|
|
||||||
|
def test_duplicate_username(self):
|
||||||
|
self.client.call('POST', '/api/v1/users', 409, body=self.alice["registration"])
|
||||||
|
|
||||||
|
def test_pagination_multiple_pages(self):
|
||||||
|
import time
|
||||||
|
msg_texts = ["msg-page-1", "msg-page-2", "msg-page-3"]
|
||||||
|
for txt in msg_texts:
|
||||||
|
self.client.message(self.alice, self.chat, txt)
|
||||||
|
time.sleep(0.01)
|
||||||
|
|
||||||
|
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||||
|
collected_items = []
|
||||||
|
cursor = None
|
||||||
|
|
||||||
|
for _ in range(5):
|
||||||
|
url_suffix = "?limit=1"
|
||||||
|
if cursor:
|
||||||
|
url_suffix += f"&cursor={cursor}"
|
||||||
|
|
||||||
|
page_res = self.client.call('GET', path + url_suffix, actor=self.alice, schema='MessagePage')
|
||||||
|
page = page_res['json']
|
||||||
|
|
||||||
|
for item in page['items']:
|
||||||
|
self.assertNotIn(item['id'], [x['id'] for x in collected_items])
|
||||||
|
collected_items.append(item)
|
||||||
|
|
||||||
|
cursor = page.get('next_keyword') or page.get('next_cursor')
|
||||||
|
if not cursor:
|
||||||
|
break
|
||||||
|
|
||||||
|
self.assertEqual(len(collected_items), 3)
|
||||||
|
self.assertEqual(sorted([x['text'] for x in collected_items]), sorted(msg_texts))
|
||||||
|
|
||||||
|
def test_concurrent_messages_strict(self):
|
||||||
|
def worker_send(worker_idx):
|
||||||
|
local_client = Client()
|
||||||
|
ids = []
|
||||||
|
for i in range(10):
|
||||||
|
res = local_client.message(self.alice, self.chat, f"w-{worker_idx}-msg-{i}")
|
||||||
|
ids.append(res['json']['id'])
|
||||||
|
return ids
|
||||||
|
|
||||||
|
all_ids = []
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||||
|
futures = [executor.submit(worker_send, w) for w in range(10)]
|
||||||
|
for f in concurrent.futures.as_completed(futures):
|
||||||
|
all_ids.extend(f.result())
|
||||||
|
|
||||||
|
self.assertEqual(len(all_ids), 100)
|
||||||
|
self.assertEqual(len(set(all_ids)), 100)
|
||||||
|
|
||||||
|
page = self.client.call(
|
||||||
|
'GET', f"/api/v1/chats/{self.chat['id']}/messages?limit=100",
|
||||||
|
actor=self.alice,
|
||||||
|
schema='MessagePage'
|
||||||
|
)
|
||||||
|
server_ids = [m['id'] for m in page['json']['items']]
|
||||||
|
self.assertEqual(len(server_ids), 100)
|
||||||
|
self.assertEqual(len(set(server_ids)), 100)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user