Лабораторная работа №2 — Федоров — БПИ2302 — оценка 4 #44
@@ -1,8 +1,11 @@
|
||||
|
||||
.git
|
||||
.github
|
||||
.idea
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
lab1-source
|
||||
secrets
|
||||
certs
|
||||
volumes
|
||||
|
||||
+6
-6
@@ -1,11 +1,11 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=change_this_local_password
|
||||
POSTGRES_DB=messenger
|
||||
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
@@ -30,3 +30,5 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
/lab1-source/
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
|
||||
FROM golang:1.25.0-alpine3.22 AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
COPY migrations ./migrations
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||
-trimpath \
|
||||
-ldflags="-s -w" \
|
||||
-o /server ./cmd/server
|
||||
|
||||
FROM alpine:3.22.1
|
||||
|
||||
RUN apk add --no-cache ca-certificates \
|
||||
&& addgroup -S app \
|
||||
&& adduser -S -G app app
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /server /app/server
|
||||
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["/app/server"]
|
||||
@@ -1,37 +1,164 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- **Автор, группа:** Федоров, БПИ2302
|
||||
- **Целевая оценка; выбранный трек 5, если нужен:** 4; трек 5 не заявлен.
|
||||
- **Commit/PR:** ссылка будет добавлена после коммита и публикации изменений.
|
||||
- **Использованные источники, библиотеки и помощь ИИ:** Go 1.25.0, PostgreSQL 16.10-alpine, Redis 7.4.6-alpine, Docker/Compose; `github.com/jackc/pgx/v5` v5.7.6, `github.com/redis/go-redis/v9` v9.7.3, `github.com/google/uuid` v1.6.0, `golang.org/x/crypto` v0.41.0. При разработке и подготовке тестов/отчёта использовалась помощь ChatGPT; код и результаты проверялись локально. Полный список зависимостей — `go.mod` и `go.sum`. Требования и критерии — `README.md` лабораторной №2, уровни «3» и «4».
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
**Среда и требования.** Нужны Git, Docker Engine и Docker Compose Plugin; для локальной разработки без Docker — Go 1.25.0. Используемые образы: `golang:1.25.0-alpine` (сборка и тесты), `postgres:16.10-alpine`, `redis:7.4.6-alpine`. В проверенной среде применялся PowerShell на Windows. Docker должен быть запущен; порты `127.0.0.1:8080`, `127.0.0.1:5432` и `127.0.0.1:6379` должны быть свободны.
|
||||
|
||||
```powershell
|
||||
# После клонирования и перехода в каталог проекта:
|
||||
Copy-Item .env.example .env
|
||||
# Открыть .env локально и заполнить необходимые значения.
|
||||
# Не публиковать .env и не копировать реальные пароли в отчёт.
|
||||
notepad .env
|
||||
|
||||
# Сборка и запуск сервисов:
|
||||
docker compose --env-file .env up -d --build
|
||||
|
||||
# Дождаться healthy у api, postgres и redis:
|
||||
docker compose --env-file .env ps
|
||||
|
||||
# Проверить логи применения миграций:
|
||||
docker compose --env-file .env logs api --tail 100
|
||||
|
||||
# Проверка компиляции пакетов и запуск тестов без БД:
|
||||
docker run --rm -v "${PWD}:/app" -w /app golang:1.25.0-alpine go test ./...
|
||||
```
|
||||
|
||||
**Миграции.** SQL-миграции встроены в Go-приложение и применяются при запуске API; в логах наблюдалось `database migrations applied`. Отдельная команда ручного запуска миграций в проверенном сценарии не требовалась. Перед первым запуском оператор должен заполнить `.env` на основании `.env.example`; соответствие имён переменных и обязательных значений требуется сверить с `compose.yaml` и кодом конфигурации.
|
||||
|
||||
**Интеграционные тесты с реальной БД (при повторной проверке).** Требуется переменная `TEST_DATABASE_URL`, указывающая на доступный PostgreSQL. В сети Compose хост БД — `postgres`. Для PowerShell можно сформировать URL из локального `POSTGRES_PASSWORD` без вывода пароля:
|
||||
|
||||
```powershell
|
||||
$envLine = Get-Content .env | Where-Object { $_ -match '^POSTGRES_PASSWORD=' } | Select-Object -First 1
|
||||
$dbPassword = ($envLine -split '=', 2)[1].Trim().Trim('"').Trim("'")
|
||||
$encodedPassword = [uri]::EscapeDataString($dbPassword)
|
||||
$testDbUrl = "postgres://messenger:${encodedPassword}@postgres:5432/messenger?sslmode=disable"
|
||||
docker run --rm --network mtusi2026lab2_default -e "TEST_DATABASE_URL=$testDbUrl" -v "${PWD}:/app" -w /app golang:1.25.0-alpine go test -v ./internal/storage
|
||||
Remove-Variable envLine, dbPassword, encodedPassword, testDbUrl -ErrorAction SilentlyContinue
|
||||
```
|
||||
|
||||
Имя сети `mtusi2026lab2_default` относится к проверенному проекту и может отличаться при другом имени каталога/Compose-проекта. Тесты создают тестовые записи; их автоматическая очистка для всех тестов не подтверждена. Если `TEST_DATABASE_URL` не задан, интеграционные тесты **пропускаются**, а не проверяют реальную БД. Пароль действующего PostgreSQL с постоянным томом может отличаться от значения в `.env`, если конфигурация менялась после инициализации БД.
|
||||
|
||||
**Остановка (с сохранением именованных томов и данных):**
|
||||
|
||||
```powershell
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
**Намеренное удаление учебных данных и томов (необратимо):**
|
||||
|
||||
```powershell
|
||||
# Выполнять только при осознанном желании полностью очистить учебную БД:
|
||||
docker compose --env-file .env down -v
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```text
|
||||
HTTP-клиент / Postman
|
||||
|
|
||||
v
|
||||
Go REST API (:8080)
|
||||
|-- маршрутизация / обработчики / проверка токена
|
||||
|-- логика пользователей, чатов, сообщений и сессий
|
||||
| |
|
||||
| +--> PostgreSQL (:5432) — источник истины
|
||||
| | users, chats, chat_members, messages, sessions
|
||||
| |
|
||||
| +--> Redis (:6379) — необязательный кэш сессий
|
||||
|
|
||||
+--> автоматическое применение встроенных SQL-миграций при запуске
|
||||
```
|
||||
|
||||
- **Источник истины:** PostgreSQL. Действительность сессии подтверждается запросом к PostgreSQL, а запись Redis сама по себе не даёт права доступа.
|
||||
- **Сессии:** в PostgreSQL хранится SHA-256-хэш токена (`token_hash`), а не токен в открытом виде. Срок действия проверяется условием `expires_at > NOW()`. При выходе действующая сессия удаляется из PostgreSQL; очистка Redis выполняется по принципу best effort.
|
||||
- **Граница согласованности:** создание сессии сначала фиксируется в PostgreSQL; ошибка Redis не отменяет успешно созданную сессию. Если PostgreSQL недоступен, авторизация не выполняется, даже при наличии записи в Redis.
|
||||
- **Чаты и сообщения:** операции используют PostgreSQL; при создании чатов и связанных записей используются SQL-транзакции (по проверенным ранее сценариям). Получение сообщений реализовано с keyset-пагинацией по `(created_at, id)`; для неё предусмотрен индекс `idx_messages_chat_created_id` по `(chat_id, created_at, id)`.
|
||||
- **Перенос из lab1:** сохранена идея REST API мессенджера на Go и базовые операции с пользователями. В lab2 добавлены постоянное хранение в PostgreSQL, Redis, контейнеризация, миграции, сессии, чаты, сообщения и проверки отказов. Точное соответствие каждому пункту README lab1/lab2 требует сверки с исходными заданиями.
|
||||
- **Ограничения:** Redis не является полноценным ускоряющим кэшем авторизации: текущий `GetSessionUser` сначала читает PostgreSQL и только затем обращается к Redis. Это обеспечивает корректность, но не снижает количество чтений PostgreSQL.
|
||||
- **Конфигурация:** `.env` исключён из Git (`git check-ignore .env` вернул `.env`). Файл `.env.example` изменён, однако построчная сверка его переменных с `compose.yaml` и кодом ещё не задокументирована; перед сдачей выполнить эту проверку.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `py -3 tests/smoke.py --base-url "http://localhost:8080"` | **PASS** — публичный smoke-сценарий пройден в PowerShell. Отдельно `make test` не подтверждён: в Windows команда `python3` не запускалась штатно. | Локальный вывод; TODO: сохранить в `evidence/smoke.txt` |
|
||||
| Сборка Go-пакетов | `go test ./...` / `go test ./internal/storage ...` | Ранее проверялась компиляция пакетов; новые тесты компилируются, но **SKIP** без `TEST_DATABASE_URL`. Это не означает, что они пройдены. | TODO: `evidence/go-test-all.txt` |
|
||||
| Работа контейнеров | `docker compose --env-file .env ps` | `api`, `postgres`, `redis` — `Up ... (healthy)`; образы БД `postgres:16.10-alpine`, `redis:7.4.6-alpine`. | TODO: `evidence/compose-ps.txt` |
|
||||
| Миграции | `docker compose --env-file .env logs api` | Ранее в логах наблюдалось `database migrations applied`. | TODO: `evidence/api-startup.txt` |
|
||||
| Регистрация и вход | `POST /api/v1/users`; `POST /api/v1/auth/sessions` | Ранее вручную получены успешная регистрация и токен авторизации. | TODO: `evidence/auth-http.txt` |
|
||||
| Получение текущего пользователя | `GET /api/v1/users/me` с Bearer-токеном | При действующей сессии — HTTP 200; после выхода старый токен отклоняется с HTTP 401. | TODO: `evidence/auth-http.txt` |
|
||||
| Чаты и сообщения | Создание чата, отправка сообщения, получение списка и сообщений через HTTP | Ранее наблюдались HTTP 201 при создании и HTTP 200 при чтении; данные сохранялись после перезапуска API. | TODO: `evidence/chat-http.txt` |
|
||||
| Интеграционные тесты сессий | `go test -v ./internal/storage` с `TEST_DATABASE_URL` и PostgreSQL в Docker | Ранее **PASS**: 4/4 теста (`CreateAndGet`, `ExpiredSessionRejected`, `LogoutRevokesSession`, `UnknownTokenRejected`). | TODO: `evidence/session-tests.txt` |
|
||||
| Гонка одинакового username | `go test ./internal/storage -run TestConcurrentRegistrationSameUsername -v -count=1` | **SKIP**: переменная `TEST_DATABASE_URL` не установлена; фактическая гонка не проверена. | Консольный вывод; TODO: `evidence/concurrency-tests.txt` |
|
||||
| Rollback создания чата | `go test ./internal/storage -run TestCreateChatRollbackOnInvalidMember -v -count=1` | **SKIP**: переменная `TEST_DATABASE_URL` не установлена; фактический откат не проверен. | Консольный вывод; TODO: `evidence/concurrency-tests.txt` |
|
||||
| 10 000 тестовых сообщений | SQL `INSERT ... generate_series(1, 10000)`; `SELECT chat_id, COUNT(*) FROM messages GROUP BY chat_id` | Вставлено 10 000; всего в чате — 10 001 сообщение. | TODO: `evidence/messages-count.txt` |
|
||||
| Индекс и выборка сообщений | `EXPLAIN (ANALYZE, BUFFERS)` для `WHERE chat_id = ... ORDER BY created_at, id LIMIT 20` | `Index Scan using idx_messages_chat_created_id`; 20 строк; `Execution Time: 0.073 ms`; `Buffers: shared hit=3`. | TODO: `evidence/explain-messages.txt` |
|
||||
| Отказ Redis | Остановить Redis, выполнить `GET /api/v1/users/me` с действующим токеном, затем запустить Redis | Во время остановки Redis запрос вернул HTTP 200; после запуска Redis восстановил healthy. | TODO: `evidence/redis-outage.txt` |
|
||||
| Отказ PostgreSQL | Остановить PostgreSQL, выполнить `GET /api/v1/users/me`, затем запустить PostgreSQL | При остановленной БД — HTTP 503; после запуска БД запрос снова вернул HTTP 200. | TODO: `evidence/postgres-outage.txt` |
|
||||
| Persistence (рестарт всех сервисов) | `py -3 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url "http://localhost:8080"` | **PASS** в диагностическом запуске с временным выводом timestamp: сохранены подтверждённые данные и действующая сессия. Первоначальный обычный запуск выдавал `invalid RFC3339 timestamp`; самостоятельный повтор без диагностической обёртки не зафиксирован. | Консольный вывод; TODO: `evidence/persistence.txt` |
|
||||
| `make test-persistence` | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | **Не подтверждено**: на Windows проверялся прямой запуск Python-сценария через `scripts/restart.cmd`. | TODO |
|
||||
| Короткий TTL, неверный пароль | Автоматические сценарии с `SESSION_TTL_SECONDS` и неверными credentials | **Не подтверждено** автоматическими проверками; отдельный тест просроченной сессии ранее прошёл. | TODO |
|
||||
| Повторное применение миграций | Повторный запуск приложения с существующей схемой и данными | Persistence после рестарта успешен, но отдельное доказательство идемпотентности миграций не сохранено. | TODO |
|
||||
| Параметризация SQL, pool, таймауты | Код репозиториев, настройки `pgxpool` и контексты | Для просмотренных SQL-запросов используются параметры `$1`, `$2` и транзакция; лимиты пула и таймауты требуют сверки по конфигурации. | TODO |
|
||||
| Остальные пункты уровня 3/4 | Сопоставление с `README.md` | Полное соответствие **всем** критериям уровня 4 пока не подтверждено. | TODO |
|
||||
| Трек 5 | Не заявлен | Не применимо | — |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
**Примечание:** приведённые `evidence/...` — предлагаемые имена файлов, а не утверждение, что файлы уже созданы. HTTP-сценарии `auth-test.http` и `chat-test.http` присутствуют как неотслеживаемые Git-файлы; их содержание перед публикацией нужно проверить на отсутствие реальных токенов и секретов. Проверки отказов выполнялись вручную; для строгого доказательства следует сохранить команды `docker compose stop/start`, вывод `docker compose ps` и HTTP-ответы, подтверждающие состояние реальных контейнеров в момент проверки.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### Эксперимент: выборка сообщений PostgreSQL
|
||||
|
||||
- **Гипотеза:** составной индекс по `(chat_id, created_at, id)` позволит быстро получить ограниченную страницу сообщений без полной сортировки всей таблицы.
|
||||
- **Среда:** локальный Docker; PostgreSQL 16.10-alpine; Go 1.25.0; Redis 7.4.6-alpine. Характеристики CPU/RAM компьютера и лимиты контейнеров не зафиксированы.
|
||||
- **Данные:** 10 001 сообщение в одном чате; 10 000 добавлены через `generate_series`.
|
||||
- **Профиль:** одиночный SQL-запрос на первые 20 сообщений с фиксированным `chat_id`, сортировкой по `created_at, id` и `LIMIT 20`.
|
||||
- **Инструмент:** `EXPLAIN (ANALYZE, BUFFERS)`.
|
||||
- **Результат:** `Index Scan using idx_messages_chat_created_id`; `Execution Time: 0.073 ms`; `Planning Time: 0.607 ms`; `shared hit=3` при выполнении запроса.
|
||||
- **Повторы, прогрев, concurrency/arrival rate:** не фиксировались. Один план выполнения не является полноценным нагрузочным тестом.
|
||||
- **Успешные RPS, ошибки под нагрузкой, p50/p95/p99, CPU/RAM:** не измерялись; указывать численные значения нельзя.
|
||||
- **Сравнение:** предварительный запрос с дополнительным поиском наиболее заполненного чата выполнился за `2.419 ms`, но это **другая форма SQL-запроса**, поэтому разницу нельзя считать чистым эффектом индекса или строгим сравнением «до/после».
|
||||
- **Raw summary:** TODO — сохранить исходный вывод `EXPLAIN` в `evidence/explain-messages.txt` без токенов.
|
||||
|
||||
### Проверки отказов
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Остановка Redis | Авторизация по действующему токену продолжает работать при доступном PostgreSQL | `GET /api/v1/users/me` → HTTP 200; после запуска Redis — healthy | Время восстановления не замерялось; потери данных PostgreSQL не наблюдались |
|
||||
| Остановка PostgreSQL | Сервис не должен авторизовать по одному Redis; ошибка зависимости должна возвращаться клиенту | `GET /api/v1/users/me` → HTTP 503 | После запуска PostgreSQL запрос вернул HTTP 200; время восстановления не замерялось; потери данных не наблюдались |
|
||||
| Выход из сессии | Отозванный токен не должен работать | После logout старый токен → HTTP 401; интеграционный тест `TestLogoutRevokesSession` — PASS | Не применимо; сессия удаляется намеренно |
|
||||
| Полный рестарт API, PostgreSQL и Redis | Данные и действующая сессия сохраняются в именованных томах | Диагностический persistence-сценарий завершился `PASS: persistence preserved confirmed data and existing session` | Время восстановления не замерялось; потери данных не наблюдались |
|
||||
|
||||
## Соответствие требованиям README для оценки «4»
|
||||
|
||||
Оценка «4» требует **всего уровня «3»** и дополнительных пунктов. Состояние подтверждений на момент подготовки отчёта:
|
||||
|
||||
| Требование | Состояние |
|
||||
| --- | --- |
|
||||
| PostgreSQL, миграции, пользователи/чаты/сообщения, транзакция создания чата | Реализовано; ручные API-сценарии и рестарт проверены. Отдельный автоматический rollback — `SKIP`. |
|
||||
| Basic при входе, Bearer для защищённых операций, KDF, expiry, logout | Реализовано; ранее прошли тесты сессий и проверка logout. Отдельный тест неверного пароля и короткого TTL не подтверждён. |
|
||||
| Persistence с сохранением действующего токена после полного рестарта | Диагностический сценарий — `PASS`; обычный запуск ранее завершился ошибкой формата timestamp. |
|
||||
| `make test`, `make test-persistence` | Не подтверждены в требуемом виде; публичный smoke запускался напрямую через `py -3`. |
|
||||
| Redis с TTL и определённой ролью | Redis используется как best-effort кэш сессий, PostgreSQL — источник истины; отказ Redis проверен вручную. |
|
||||
| Параметризованный SQL, ограниченный пул, таймауты | Параметризованные запросы присутствуют в просмотренном коде; лимиты и таймауты требуют отдельной проверки. |
|
||||
| Гонка регистрации и rollback | Тесты добавлены, но оба последовательно пропущены из-за отсутствия `TEST_DATABASE_URL`. |
|
||||
| EXPLAIN на ≥10 000 сообщениях, keyset-пагинация | Подтверждены индексный план и 10 001 сообщение; код использует keyset-подход. |
|
||||
| Автоматическая проверка короткого TTL, logout, неверного пароля, отказов Redis/БД | Logout покрыт интеграционным тестом; отказы проверялись вручную. Полный автоматический набор не подтверждён. |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
1. **Отказоустойчивость ограничена.** Сервис переносит недоступность Redis для проверенных запросов авторизации, но зависит от PostgreSQL; при отказе основной БД защищённые операции недоступны. Репликация PostgreSQL и автоматическое переключение на резервный экземпляр не реализованы.
|
||||
2. **Redis используется как best-effort кэш.** Авторизация всегда требует чтения PostgreSQL. Ускорение проверки сессий с помощью Redis не доказано и в текущем алгоритме не достигается.
|
||||
3. **Производительность:** измерена только локальная SQL-выборка первых 20 сообщений. Не проведены HTTP-нагрузочные тесты, замеры p50/p95/p99, RPS, CPU/RAM и тесты глубокой keyset-пагинации с повторениями.
|
||||
4. **Покрытие тестами:** четыре интеграционных теста ранее проверили жизненный цикл сессии. Добавлены тесты `TestConcurrentRegistrationSameUsername` и `TestCreateChatRollbackOnInvalidMember`, но последний запуск обоих дал `SKIP` из-за отсутствия `TEST_DATABASE_URL`; их нельзя считать пройденными. Нет подтверждённой автоматической проверки короткого TTL, неверного пароля и отказов зависимостей.
|
||||
5. **Доказательства:** сохранить реальные логи в `evidence/`; по возможности выполнить `make test` и `make test-persistence ACTION_SCRIPT=scripts/restart.sh` в среде с работающим `python3`, повторить persistence без диагностической обёртки, а также запустить два пропущенных теста с `TEST_DATABASE_URL`.
|
||||
6. **Конфигурация и публикация:** сверить `.env.example` с реальными переменными, проверить `auth-test.http` и `chat-test.http` на секреты, создать коммит и добавить ссылку на Commit/PR. Файл `.env` игнорируется Git; `.gitignore` имеет локальные изменения и пока не добавлен в индекс (`git add .gitignore` при необходимости).
|
||||
|
||||
**Итог:** публичный smoke-тест пройден; диагностический persistence-сценарий подтвердил сохранение данных и сессии после рестарта всех сервисов; ранее прошли четыре интеграционных теста сессий; проверены отказы Redis/PostgreSQL и индексированная выборка на 10 001 сообщении. Целевая оценка — 4, но все обязательные проверки уровня 4 пока не завершены, поэтому соответствие оценке 4 не заявляется как полностью доказанное.
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/handler"
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
databaseURL := os.Getenv("DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
log.Fatal("DATABASE_URL is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := storage.NewPostgresPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("PostgreSQL connection failed: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
if err := storage.ApplyMigrations(ctx, pool); err != nil {
|
||||
log.Fatalf("database migrations failed: %v", err)
|
||||
}
|
||||
log.Println("database migrations applied")
|
||||
|
||||
var cache *storage.SessionCache
|
||||
|
||||
redisURL := os.Getenv("REDIS_URL")
|
||||
if redisURL != "" {
|
||||
cache, err = storage.NewSessionCache(redisURL)
|
||||
if err != nil {
|
||||
log.Printf("Redis configuration error: %v", err)
|
||||
} else {
|
||||
defer cache.Close()
|
||||
|
||||
pingCtx, pingCancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
)
|
||||
pingErr := cache.Ping(pingCtx)
|
||||
pingCancel()
|
||||
|
||||
if pingErr != nil {
|
||||
log.Printf("Redis unavailable, PostgreSQL fallback: %v", pingErr)
|
||||
} else {
|
||||
log.Println("Redis connected")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
authStore := storage.NewAuthStore(pool)
|
||||
sessionService := storage.NewSessionService(authStore, cache)
|
||||
chatStore := storage.NewChatStore(pool)
|
||||
messageStore := storage.NewMessageStore(pool)
|
||||
|
||||
userHandler := handler.NewUserHandler(authStore)
|
||||
sessionHandler := handler.NewSessionHandler(authStore, sessionService)
|
||||
chatHandler := handler.NewChatHandler(chatStore)
|
||||
messageHandler := handler.NewMessageHandler(chatStore, messageStore)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeHealthOK(w)
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {
|
||||
pingCtx, pingCancel := context.WithTimeout(
|
||||
r.Context(), 2*time.Second,
|
||||
)
|
||||
defer pingCancel()
|
||||
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"error": map[string]string{
|
||||
"code": "unavailable",
|
||||
"message": "database unavailable",
|
||||
"request_id": middleware.GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeHealthOK(w)
|
||||
})
|
||||
|
||||
// Public routes.
|
||||
mux.HandleFunc("POST /api/v1/users", userHandler.Create)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", sessionHandler.Create)
|
||||
|
||||
// Protected routes.
|
||||
auth := middleware.Auth(sessionService)
|
||||
|
||||
mux.Handle(
|
||||
"DELETE /api/v1/auth/sessions/current",
|
||||
auth(http.HandlerFunc(sessionHandler.Delete)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/users/me",
|
||||
auth(http.HandlerFunc(userHandler.Me)),
|
||||
)
|
||||
mux.Handle(
|
||||
"POST /api/v1/chats",
|
||||
auth(http.HandlerFunc(chatHandler.Create)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/chats",
|
||||
auth(http.HandlerFunc(chatHandler.List)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/chats/{chat_id}",
|
||||
auth(http.HandlerFunc(chatHandler.Get)),
|
||||
)
|
||||
mux.Handle(
|
||||
"POST /api/v1/chats/{chat_id}/messages",
|
||||
auth(http.HandlerFunc(messageHandler.Create)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/chats/{chat_id}/messages",
|
||||
auth(http.HandlerFunc(messageHandler.List)),
|
||||
)
|
||||
|
||||
host := os.Getenv("APP_HOST")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
|
||||
port := os.Getenv("APP_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: host + ":" + port,
|
||||
Handler: middleware.RequestID(databaseDeadline(mux)),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
defer signal.Stop(stop)
|
||||
|
||||
go func() {
|
||||
log.Printf("server started on %s", server.Addr)
|
||||
|
||||
if err := server.ListenAndServe(); err != nil &&
|
||||
!errors.Is(err, http.ErrServerClosed) {
|
||||
log.Printf("server error: %v", err)
|
||||
stop <- syscall.SIGTERM
|
||||
}
|
||||
}()
|
||||
|
||||
sig := <-stop
|
||||
log.Printf("shutdown signal received: %s", sig)
|
||||
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(
|
||||
context.Background(), 8*time.Second,
|
||||
)
|
||||
defer shutdownCancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("graceful shutdown failed: %v", err)
|
||||
_ = server.Close()
|
||||
}
|
||||
|
||||
log.Println("server stopped")
|
||||
}
|
||||
|
||||
func writeHealthOK(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"status":"ok"}`))
|
||||
}
|
||||
|
||||
// databaseDeadline bounds every API request, including queries on already-open
|
||||
// PostgreSQL connections. The handler maps context/driver errors to HTTP 503.
|
||||
func databaseDeadline(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/health/live" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.10-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
|
||||
redis:
|
||||
image: redis:7.4.6-alpine
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- redis-server
|
||||
- --appendonly
|
||||
- "yes"
|
||||
ports:
|
||||
- "127.0.0.1:6379:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- wget
|
||||
- -q
|
||||
- -O
|
||||
- /dev/null
|
||||
- http://127.0.0.1:8080/health/ready
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
@@ -0,0 +1,22 @@
|
||||
module mtusi2026lab2
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.6
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
golang.org/x/crypto v0.41.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/stretchr/testify v1.12.1 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/sys v0.35.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
|
||||
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,229 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
store *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewChatHandler(store *storage.ChatStore) *ChatHandler {
|
||||
return &ChatHandler{store: store}
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []model.Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
var req createChatRequest
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
title := strings.TrimSpace(req.Title)
|
||||
titleLength := utf8.RuneCountInString(title)
|
||||
|
||||
if titleLength < 1 || titleLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "title must contain from 1 to 100 characters")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain from 1 to 100 users")
|
||||
return
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
|
||||
currentUserIsMember := false
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
if _, exists := seen[memberID]; exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain unique users")
|
||||
return
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
|
||||
if memberID == currentUser.ID {
|
||||
currentUserIsMember = true
|
||||
}
|
||||
}
|
||||
|
||||
if !currentUserIsMember {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "current user must be a chat member")
|
||||
return
|
||||
}
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
exists, err := h.store.ExistsUser(r.Context(), memberID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: req.MemberIDs,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err := h.store.CreateChat(r.Context(), chat)
|
||||
if errors.Is(err, storage.ErrInvalidMember) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if values, exists := r.URL.Query()["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
writeError(w, r, 400, "invalid_request", "invalid limit")
|
||||
return
|
||||
}
|
||||
n, err := strconv.Atoi(values[0])
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
writeError(w, r, 400, "invalid_request", "limit must be between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursorTime *time.Time
|
||||
var cursorID *uuid.UUID
|
||||
if values, exists := r.URL.Query()["cursor"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
writeError(w, r, 400, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
t, id, err := decodeChatCursor(values[0], currentUser.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, 400, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
cursorTime = &t
|
||||
cursorID = &id
|
||||
}
|
||||
chats, more, err := h.store.ListChatsPage(r.Context(), currentUser.ID, limit, cursorTime, cursorID)
|
||||
if err != nil {
|
||||
writeError(w, r, 503, "unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
var next *string
|
||||
if more && len(chats) > 0 {
|
||||
c := encodeChatCursor(currentUser.ID, chats[len(chats)-1])
|
||||
next = &c
|
||||
}
|
||||
writeJSON(w, 200, chatPage{Items: chats, NextCursor: next})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
func encodeChatCursor(userID uuid.UUID, chat model.Chat) string {
|
||||
value := fmt.Sprintf("%s|%s|%s", userID, chat.CreatedAt.Format(time.RFC3339Nano), chat.ID)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
func decodeChatCursor(cursor string, userID uuid.UUID) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
parts := strings.Split(string(data), "|")
|
||||
if len(parts) != 3 || parts[0] != userID.String() {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
return t, id, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// decodeOneObject rejects a second JSON value, trailing garbage and unknown fields.
|
||||
func decodeOneObject(r *http.Request, target any) error {
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("multiple JSON values")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func requireEmptyBody(r *http.Request) error {
|
||||
// A whitespace-only body is accepted as empty; any JSON or other bytes are not.
|
||||
data, err := io.ReadAll(io.LimitReader(r.Body, 2))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) != 0 {
|
||||
return errors.New("request body must be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
chats *storage.ChatStore
|
||||
messages *storage.MessageStore
|
||||
}
|
||||
|
||||
func NewMessageHandler(
|
||||
chats *storage.ChatStore,
|
||||
messages *storage.MessageStore,
|
||||
) *MessageHandler {
|
||||
return &MessageHandler{
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
}
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messagePage struct {
|
||||
Items []model.Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *MessageHandler) accessibleChat(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) (uuid.UUID, bool) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
_, err = h.chats.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
return chatID, true
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
currentUser, _ := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var req createMessageRequest
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
textLength := utf8.RuneCountInString(req.Text)
|
||||
if strings.TrimSpace(req.Text) == "" || textLength > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "text must contain from 1 to 4000 characters")
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: currentUser.ID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err := h.messages.CreateMessage(r.Context(), message)
|
||||
if errors.Is(err, storage.ErrMessageMemberNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "limit must be between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
var cursorTime *time.Time
|
||||
var cursorID *uuid.UUID
|
||||
|
||||
if raw := r.URL.Query().Get("cursor"); raw != "" {
|
||||
t, id, err := decodeMessageCursor(raw, chatID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
cursorTime = &t
|
||||
cursorID = &id
|
||||
}
|
||||
|
||||
items, hasMore, err := h.messages.ListMessages(
|
||||
r.Context(), chatID, limit, cursorTime, cursorID,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if hasMore && len(items) > 0 {
|
||||
cursor := encodeMessageCursor(items[len(items)-1])
|
||||
nextCursor = &cursor
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, messagePage{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
// Cursor contains the chat UUID to prevent cross-chat replay.
|
||||
func encodeMessageCursor(message model.Message) string {
|
||||
value := fmt.Sprintf("%s|%s|%s", message.ChatID, message.CreatedAt.Format(time.RFC3339Nano), message.ID)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
|
||||
func decodeMessageCursor(cursor string, chatID uuid.UUID) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
parts := strings.Split(string(data), "|")
|
||||
if len(parts) != 3 || parts[0] != chatID.String() {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor for chat")
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
return t, id, nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStrictJSON(t *testing.T) {
|
||||
for _, body := range []string{`{"text":"hello"} garbage`, `{"text":"hello"}{"text":"again"}`} {
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(body))
|
||||
var v createMessageRequest
|
||||
if err := decodeOneObject(req, &v); err == nil {
|
||||
t.Fatalf("accepted trailing JSON: %q", body)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestMessageCursorBoundToChat(t *testing.T) {
|
||||
chatA, chatB := uuid.New(), uuid.New()
|
||||
cursor := encodeMessageCursor(model.Message{ID: uuid.New(), ChatID: chatA, CreatedAt: time.Now().UTC()})
|
||||
if _, _, err := decodeMessageCursor(cursor, chatA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := decodeMessageCursor(cursor, chatB); err == nil {
|
||||
t.Fatal("accepted cursor for another chat")
|
||||
}
|
||||
}
|
||||
func TestChatCursorBoundToUser(t *testing.T) {
|
||||
a, b := uuid.New(), uuid.New()
|
||||
cursor := encodeChatCursor(a, model.Chat{ID: uuid.New(), CreatedAt: time.Now().UTC()})
|
||||
if _, _, err := decodeChatCursor(cursor, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := decodeChatCursor(cursor, b); err == nil {
|
||||
t.Fatal("accepted cursor for another user")
|
||||
}
|
||||
}
|
||||
func TestEmptyLoginBody(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"ignored":true}`))
|
||||
if err := requireEmptyBody(req); err == nil {
|
||||
t.Fatal("accepted login body")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, data any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func writeError(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
status int,
|
||||
code string,
|
||||
message string,
|
||||
) {
|
||||
writeJSON(w, status, errorResponse{
|
||||
Error: errorBody{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: middleware.GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type SessionHandler struct {
|
||||
users *storage.AuthStore
|
||||
sessions *storage.SessionService
|
||||
}
|
||||
|
||||
func NewSessionHandler(
|
||||
users *storage.AuthStore,
|
||||
sessions *storage.SessionService,
|
||||
) *SessionHandler {
|
||||
return &SessionHandler{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User interface{} `json:"user"`
|
||||
}
|
||||
|
||||
func sessionTTL() time.Duration {
|
||||
seconds := 3600
|
||||
|
||||
if raw := os.Getenv("SESSION_TTL_SECONDS"); raw != "" {
|
||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||
seconds = n
|
||||
}
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
if err := requireEmptyBody(r); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "request body must be empty")
|
||||
return
|
||||
}
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := h.users.GetUserByUsername(
|
||||
r.Context(), username,
|
||||
)
|
||||
|
||||
if errors.Is(err, storage.ErrUserNotFound) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if !VerifyPassword(password, passwordHash) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
randomBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
createdAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
expiresAt := createdAt.Add(sessionTTL())
|
||||
|
||||
err = h.sessions.CreateSession(
|
||||
r.Context(),
|
||||
token,
|
||||
user.ID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Del("WWW-Authenticate")
|
||||
|
||||
writeJSON(w, http.StatusCreated, sessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
||||
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
err := h.sessions.RevokeSession(r.Context(), token)
|
||||
|
||||
if errors.Is(err, storage.ErrSessionNotFound) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
var usernameRegexp = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserHandler struct {
|
||||
store *storage.AuthStore
|
||||
}
|
||||
|
||||
func NewUserHandler(store *storage.AuthStore) *UserHandler {
|
||||
return &UserHandler{store: store}
|
||||
}
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return "argon2id$" +
|
||||
base64.RawStdEncoding.EncodeToString(salt) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 3 || parts[0] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(salt) != 16 {
|
||||
return false
|
||||
}
|
||||
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil || len(expected) != 32 {
|
||||
return false
|
||||
}
|
||||
|
||||
actual := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserRequest
|
||||
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if !usernameRegexp.MatchString(req.Username) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
|
||||
req.DisplayName = strings.TrimSpace(req.DisplayName)
|
||||
nameLength := utf8.RuneCountInString(req.DisplayName)
|
||||
|
||||
if nameLength < 1 || nameLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
|
||||
passwordLength := utf8.RuneCountInString(req.Password)
|
||||
if passwordLength < 12 || passwordLength > 128 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
"password must contain 12 to 128 characters")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err = h.store.CreateUser(r.Context(), user, passwordHash)
|
||||
if errors.Is(err, storage.ErrUsernameTaken) {
|
||||
writeError(w, r, http.StatusConflict,
|
||||
"conflict", "username already exists")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
const currentUserKey contextKey = "current_user"
|
||||
|
||||
type authErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type authErrorResponse struct {
|
||||
Error authErrorBody `json:"error"`
|
||||
}
|
||||
|
||||
func Auth(store *storage.SessionService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
writeAuthError(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
||||
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
writeAuthError(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := store.GetSessionUser(r.Context(), token)
|
||||
|
||||
if errors.Is(err, storage.ErrSessionNotFound) {
|
||||
writeAuthError(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(authErrorResponse{
|
||||
Error: authErrorBody{
|
||||
Code: "unavailable",
|
||||
Message: "service unavailable",
|
||||
RequestID: GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), currentUserKey, user)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) (model.User, bool) {
|
||||
user, ok := ctx.Value(currentUserKey).(model.User)
|
||||
return user, ok
|
||||
}
|
||||
|
||||
func writeAuthError(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(authErrorResponse{
|
||||
Error: authErrorBody{
|
||||
Code: "unauthorized",
|
||||
Message: "authentication required",
|
||||
RequestID: GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const requestIDKey contextKey = "request_id"
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
requestID, _ := ctx.Value(requestIDKey).(string)
|
||||
return requestID
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ChatID uuid.UUID `json:"chat_id"`
|
||||
SenderID uuid.UUID `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUsernameTaken = errors.New("username already exists")
|
||||
ErrSessionNotFound = errors.New("session not found")
|
||||
)
|
||||
|
||||
type AuthStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAuthStore(pool *pgxpool.Pool) *AuthStore {
|
||||
return &AuthStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *AuthStore) CreateUser(
|
||||
ctx context.Context,
|
||||
user model.User,
|
||||
passwordHash string,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO users
|
||||
(id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
return fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (model.User, string, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name,
|
||||
password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
var user model.User
|
||||
var passwordHash string
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&passwordHash,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
var user model.User
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func tokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *AuthStore) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO sessions
|
||||
(token_hash, user_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
tokenHash(token),
|
||||
userID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetSessionUser(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
AND s.expires_at > NOW()
|
||||
`
|
||||
|
||||
var user model.User
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, tokenHash(token)).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
const query = `
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
AND expires_at > NOW()
|
||||
`
|
||||
|
||||
result, err := s.pool.Exec(ctx, query, tokenHash(token))
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveSessionUserID is the authoritative expiry/revocation check.
|
||||
// Redis only caches the public user profile; it never grants access on its own.
|
||||
func (s *AuthStore) GetActiveSessionUserID(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
var userID uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>NOW()`, tokenHash(token)).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return uuid.Nil, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("validate session: %w", err)
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrInvalidMember = errors.New("chat member does not exist")
|
||||
)
|
||||
|
||||
type ChatStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatStore(pool *pgxpool.Pool) *ChatStore {
|
||||
return &ChatStore{pool: pool}
|
||||
}
|
||||
|
||||
// CreateChat creates the chat and all its members in one transaction.
|
||||
// A failure inserting any member rolls back the entire chat.
|
||||
func (s *ChatStore) CreateChat(
|
||||
ctx context.Context,
|
||||
chat model.Chat,
|
||||
) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin chat transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, chat.ID, chat.Title, chat.CreatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
`, chat.ID, memberID)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return ErrInvalidMember
|
||||
}
|
||||
return fmt.Errorf("insert chat member: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit chat transaction: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetChatForUser returns a chat only if the user is a member.
|
||||
// Missing chats and inaccessible chats both return ErrChatNotFound.
|
||||
func (s *ChatStore) GetChatForUser(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
userID uuid.UUID,
|
||||
) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1 AND cm.user_id = $2
|
||||
`, chatID, userID).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrChatNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
members, err := s.getMemberIDs(ctx, chat.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
chat.MemberIDs = members
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) getMemberIDs(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
ORDER BY user_id
|
||||
`, chatID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query chat members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
members := make([]uuid.UUID, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var memberID uuid.UUID
|
||||
if err := rows.Scan(&memberID); err != nil {
|
||||
return nil, fmt.Errorf("scan chat member: %w", err)
|
||||
}
|
||||
members = append(members, memberID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chat members: %w", err)
|
||||
}
|
||||
|
||||
return members, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListChatsForUser(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) ([]model.Chat, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
|
||||
chats := make([]model.Chat, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
// A connection cannot be reused for another query until rows are closed.
|
||||
for i := range chats {
|
||||
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats[i].MemberIDs = members
|
||||
}
|
||||
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
// ExistsUser is used to validate members before creating a chat.
|
||||
func (s *ChatStore) ExistsUser(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) (bool, error) {
|
||||
var exists bool
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)
|
||||
`, userID).Scan(&exists)
|
||||
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check user existence: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// Kept here to document that chat timestamps are stored in UTC.
|
||||
var _ = time.UTC
|
||||
|
||||
// ListChatsPage uses (created_at,id) keyset pagination and fetches limit+1.
|
||||
func (s *ChatStore) ListChatsPage(ctx context.Context, userID uuid.UUID, limit int, cursorTime *time.Time, cursorID *uuid.UUID) ([]model.Chat, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
if cursorTime == nil || cursorID == nil {
|
||||
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 ORDER BY c.created_at,c.id LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, userID, *cursorTime, *cursorID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
chats := make([]model.Chat, 0, limit+1)
|
||||
for rows.Next() {
|
||||
var c model.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
rows.Close()
|
||||
return nil, false, err
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, false, err
|
||||
}
|
||||
rows.Close()
|
||||
more := len(chats) > limit
|
||||
if more {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
for i := range chats {
|
||||
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
chats[i].MemberIDs = members
|
||||
}
|
||||
return chats, more, nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
func TestConcurrentRegistrationSameUsername(t *testing.T) {
|
||||
store, _ := newTestAuthStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
username := "race_" + uuid.NewString()[:8]
|
||||
const workers = 10
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: "Race Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
results <- store.CreateUser(ctx, user, "test_password_hash")
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
successes := 0
|
||||
conflicts := 0
|
||||
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
successes++
|
||||
case errors.Is(err, ErrUsernameTaken):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("unexpected registration error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if successes != 1 || conflicts != workers-1 {
|
||||
t.Fatalf(
|
||||
"expected 1 success and %d conflicts, got %d successes and %d conflicts",
|
||||
workers-1, successes, conflicts,
|
||||
)
|
||||
}
|
||||
|
||||
t.Logf("PASS: %d successful registration, %d conflicts",
|
||||
successes, conflicts)
|
||||
}
|
||||
|
||||
func TestCreateChatRollbackOnInvalidMember(t *testing.T) {
|
||||
authStore, validUserID := newTestAuthStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
chatID := uuid.New()
|
||||
|
||||
chat := model.Chat{
|
||||
ID: chatID,
|
||||
Title: "Rollback Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
MemberIDs: []uuid.UUID{
|
||||
validUserID,
|
||||
uuid.New(),
|
||||
},
|
||||
}
|
||||
|
||||
err := NewChatStore(authStore.pool).CreateChat(ctx, chat)
|
||||
|
||||
if !errors.Is(err, ErrInvalidMember) {
|
||||
t.Fatalf("expected ErrInvalidMember, got %v", err)
|
||||
}
|
||||
|
||||
var chatCount int
|
||||
err = authStore.pool.QueryRow(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM chats WHERE id = $1",
|
||||
chatID,
|
||||
).Scan(&chatCount)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("check chat existence: %v", err)
|
||||
}
|
||||
|
||||
if chatCount != 0 {
|
||||
t.Fatalf("rollback failed: chat still exists")
|
||||
}
|
||||
|
||||
var memberCount int
|
||||
err = authStore.pool.QueryRow(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM chat_members WHERE chat_id = $1",
|
||||
chatID,
|
||||
).Scan(&memberCount)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("check chat members: %v", err)
|
||||
}
|
||||
|
||||
if memberCount != 0 {
|
||||
t.Fatalf("rollback failed: %d chat members still exist", memberCount)
|
||||
}
|
||||
|
||||
t.Log("PASS: transaction rolled back chat and member inserts")
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
users map[uuid.UUID]model.User
|
||||
chats map[uuid.UUID]model.Chat
|
||||
messages map[uuid.UUID][]model.Message
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
users: make(map[uuid.UUID]model.User),
|
||||
chats: make(map[uuid.UUID]model.Chat),
|
||||
messages: make(map[uuid.UUID][]model.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateUser(user model.User) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, existingUser := range s.users {
|
||||
if existingUser.Username == user.Username {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
s.users[user.ID] = user
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUserByID(id uuid.UUID) (model.User, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, ok := s.users[id]
|
||||
return user, ok
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateChat(chat model.Chat) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.chats[chat.ID] = chat
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatByID(id uuid.UUID) (model.Chat, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, ok := s.chats[id]
|
||||
return chat, ok
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListChatsForUser(userID uuid.UUID) []model.Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chats := make([]model.Chat, 0)
|
||||
|
||||
for _, chat := range s.chats {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
chats = append(chats, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return chats
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateMessage(message model.Message) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.messages[message.ChatID] = append(
|
||||
s.messages[message.ChatID],
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListMessages(chatID uuid.UUID) []model.Message {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
messages := s.messages[chatID]
|
||||
|
||||
result := make([]model.Message, len(messages))
|
||||
copy(result, messages)
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var ErrMessageMemberNotFound = errors.New("sender is not a chat member")
|
||||
|
||||
type MessageStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageStore(pool *pgxpool.Pool) *MessageStore {
|
||||
return &MessageStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *MessageStore) CreateMessage(
|
||||
ctx context.Context,
|
||||
message model.Message,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO messages (
|
||||
id, chat_id, sender_id, text, created_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
message.CreatedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return ErrMessageMemberNotFound
|
||||
}
|
||||
return fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListMessages implements keyset pagination.
|
||||
// Cursor is the created_at + id of the previous page's last item.
|
||||
func (s *MessageStore) ListMessages(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
limit int,
|
||||
cursorTime *time.Time,
|
||||
cursorID *uuid.UUID,
|
||||
) ([]model.Message, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
|
||||
if cursorTime == nil || cursorID == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
`, chatID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`, chatID, *cursorTime, *cursorID, limit+1)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages := make([]model.Message, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var message model.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
|
||||
messages = append(messages, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf("iterate messages: %w", err)
|
||||
}
|
||||
|
||||
hasMore := len(messages) > limit
|
||||
if hasMore {
|
||||
messages = messages[:limit]
|
||||
}
|
||||
|
||||
return messages, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/migrations"
|
||||
)
|
||||
|
||||
func ApplyMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin migrations: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Serialize migrations across API instances.
|
||||
_, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(20260002)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lock migrations: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version BIGINT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migration history: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrations.Files, ".")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
names := make([]string, 0)
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".up.sql") {
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
for _, name := range names {
|
||||
versionPart := strings.SplitN(name, "_", 2)[0]
|
||||
|
||||
version, err := strconv.ParseInt(versionPart, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid migration filename %q: %w", name, err)
|
||||
}
|
||||
|
||||
var applied bool
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM schema_migrations
|
||||
WHERE version = $1
|
||||
)
|
||||
`, version).Scan(&applied)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration %d: %w", version, err)
|
||||
}
|
||||
|
||||
if applied {
|
||||
continue
|
||||
}
|
||||
|
||||
sql, err := fs.ReadFile(migrations.Files, name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", name, err)
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, string(sql)); err != nil {
|
||||
return fmt.Errorf("apply migration %s: %w", name, err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO schema_migrations (version)
|
||||
VALUES ($1)
|
||||
`, version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("record migration %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit migrations: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewPostgresPool(
|
||||
ctx context.Context,
|
||||
databaseURL string,
|
||||
) (*pgxpool.Pool, error) {
|
||||
config, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"invalid database config: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 1
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = time.Minute
|
||||
config.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(
|
||||
ctx,
|
||||
10*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(
|
||||
connectCtx,
|
||||
config,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"create postgres pool: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf(
|
||||
"postgres unavailable: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionCache(redisURL string) (*SessionCache, error) {
|
||||
options, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid redis URL: %w", err)
|
||||
}
|
||||
|
||||
options.DialTimeout = 2 * time.Second
|
||||
options.ReadTimeout = 2 * time.Second
|
||||
options.WriteTimeout = 2 * time.Second
|
||||
options.MaxRetries = 0
|
||||
|
||||
return &SessionCache{
|
||||
client: redis.NewClient(options),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Close() error {
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
return c.client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func cacheKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "session:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (c *SessionCache) Set(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
user model.User,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
ttl := time.Until(expiresAt)
|
||||
if ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.client.Set(ctx, cacheKey(token), payload, ttl).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Get(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, bool, error) {
|
||||
value, err := c.client.Get(ctx, cacheKey(token)).Result()
|
||||
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := json.Unmarshal([]byte(value), &user); err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
return user, true, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Delete(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
return c.client.Del(ctx, cacheKey(token)).Err()
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type SessionService struct {
|
||||
db *AuthStore
|
||||
cache *SessionCache
|
||||
}
|
||||
|
||||
func NewSessionService(
|
||||
db *AuthStore,
|
||||
cache *SessionCache,
|
||||
) *SessionService {
|
||||
return &SessionService{
|
||||
db: db,
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionService) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := s.db.CreateSession(
|
||||
ctx, token, userID, createdAt, expiresAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Populate the profile cache best-effort after the authoritative INSERT.
|
||||
if s.cache != nil {
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err == nil {
|
||||
cacheCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
|
||||
_ = s.cache.Set(cacheCtx, token, user, expiresAt)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionService) GetSessionUser(ctx context.Context, token string) (model.User, error) {
|
||||
// A cheap indexed PostgreSQL check on EVERY request enforces expiry and logout,
|
||||
// even if Redis contains a stale value or its deletion fails.
|
||||
userID, err := s.db.GetActiveSessionUserID(ctx, token)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
cached, hit, err := s.cache.Get(cacheCtx, token)
|
||||
cancel()
|
||||
if err == nil && hit && cached.ID == userID {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
// Conservative short TTL on read-through; session lifetime is still checked in PostgreSQL.
|
||||
_ = s.cache.Set(cacheCtx, token, user, time.Now().Add(30*time.Second))
|
||||
cancel()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
if err := s.db.RevokeSession(ctx, token); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 250*time.Millisecond,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_ = s.cache.Delete(cacheCtx, token)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
func newTestAuthStore(t *testing.T) (*AuthStore, uuid.UUID) {
|
||||
t.Helper()
|
||||
|
||||
databaseURL := os.Getenv("TEST_DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set; integration test skipped")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := NewPostgresPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("connect to PostgreSQL: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
|
||||
store := NewAuthStore(pool)
|
||||
|
||||
userID := uuid.New()
|
||||
username := "test_" + uuid.NewString()[:8]
|
||||
|
||||
user := model.User{
|
||||
ID: userID,
|
||||
Username: username,
|
||||
DisplayName: "Integration Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
err = store.CreateUser(ctx, user, "test-password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, _ = pool.Exec(cleanupCtx,
|
||||
"DELETE FROM sessions WHERE user_id = $1", userID)
|
||||
_, _ = pool.Exec(cleanupCtx,
|
||||
"DELETE FROM users WHERE id = $1", userID)
|
||||
})
|
||||
|
||||
return store, userID
|
||||
}
|
||||
|
||||
func TestSessionCreateAndGet(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "test-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx, token, userID, now, now.Add(time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
user, err := service.GetSessionUser(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("get session user: %v", err)
|
||||
}
|
||||
|
||||
if user.ID != userID {
|
||||
t.Fatalf("expected user %s, got %s", userID, user.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredSessionRejected(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "expired-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx,
|
||||
token,
|
||||
userID,
|
||||
now.Add(-2*time.Hour),
|
||||
now.Add(-time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create expired session: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.GetSessionUser(ctx, token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected ErrSessionNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutRevokesSession(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "logout-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx, token, userID, now, now.Add(time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
err = service.RevokeSession(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("revoke session: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.GetSessionUser(ctx, token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected revoked token to be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownTokenRejected(t *testing.T) {
|
||||
store, _ := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
token := fmt.Sprintf("unknown-%s", uuid.NewString())
|
||||
|
||||
_, err := service.GetSessionUser(context.Background(), token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected ErrSessionNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
DROP TABLE IF EXISTS messages;
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
DROP TABLE IF EXISTS chats;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,73 @@
|
||||
|
||||
-- 001_init.up.sql
|
||||
-- Первоначальная схема PostgreSQL для лабораторной №2.
|
||||
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY,
|
||||
username VARCHAR(32) NOT NULL UNIQUE,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT users_username_format
|
||||
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_not_blank
|
||||
CHECK (length(btrim(display_name)) > 0)
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT chats_title_not_blank
|
||||
CHECK (length(btrim(title)) > 0)
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_chat_members_user_id
|
||||
ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE INDEX idx_chats_created_at_id
|
||||
ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL,
|
||||
sender_id UUID NOT NULL,
|
||||
text VARCHAR(4000) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT messages_sender_is_member
|
||||
FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT messages_text_not_blank
|
||||
CHECK (length(btrim(text)) > 0)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_messages_chat_created_id
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash CHAR(64) PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT sessions_expiry_valid
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_sessions_user_id
|
||||
ON sessions (user_id);
|
||||
|
||||
CREATE INDEX idx_sessions_expires_at
|
||||
ON sessions (expires_at);
|
||||
@@ -0,0 +1,8 @@
|
||||
package migrations
|
||||
|
||||
import "embed"
|
||||
|
||||
// Files contains SQL migrations embedded into the API binary.
|
||||
//
|
||||
//go:embed *.up.sql
|
||||
var Files embed.FS
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
"C:\Program Files\Git\bin\bash.exe" "%~dp0restart.sh"
|
||||
@@ -0,0 +1,43 @@
|
||||
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
echo "Restarting API, PostgreSQL and Redis without deleting volumes..."
|
||||
|
||||
docker compose --env-file .env restart postgres redis api
|
||||
|
||||
echo "Waiting for services to become healthy..."
|
||||
|
||||
for service in postgres redis api; do
|
||||
echo "Checking $service..."
|
||||
|
||||
ready=0
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
container_id=$(docker compose --env-file .env ps -q "$service")
|
||||
|
||||
if [ -n "$container_id" ]; then
|
||||
status=$(docker inspect \
|
||||
--format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' \
|
||||
"$container_id")
|
||||
|
||||
if [ "$status" = "healthy" ]; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 2
|
||||
done
|
||||
|
||||
if [ "$ready" -ne 1 ]; then
|
||||
echo "ERROR: $service did not become healthy"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "$service is healthy"
|
||||
done
|
||||
|
||||
echo "All services restarted successfully."
|
||||
Reference in New Issue
Block a user