ЛР4 - БПИ2302 Федоров - на 3 #106
@@ -18,3 +18,12 @@ S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
|
||||
# Local synthetic credentials only. Use new values; do not commit .env.
|
||||
S3_ACCESS_KEY_ID=localminio
|
||||
S3_SECRET_ACCESS_KEY=replace_with_long_random_local_secret_12345
|
||||
|
||||
# Required by Docker Compose
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=local_lab4_password_2026
|
||||
POSTGRES_DB=messenger
|
||||
|
||||
+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"]
|
||||
@@ -0,0 +1,14 @@
|
||||
# Локальный запуск лабораторной №4 (Windows PowerShell)
|
||||
|
||||
1. Склонировать **свой форк lab4**, перейти в ветку `solution/BPI2302-fedorov` и скопировать файлы этого архива поверх skeleton, **не удаляя `.git`**.
|
||||
2. `Copy-Item .env.example .env` и заменить `POSTGRES_PASSWORD`, `S3_SECRET_ACCESS_KEY` на собственные локальные значения без спецсимволов URL (`@`, `:`, `/`, `#`, `%`) в пароле PostgreSQL.
|
||||
3. Остановить предыдущий стенд lab3: `docker compose --env-file .env down` **из каталога lab3**, без `-v`.
|
||||
4. Из lab4: `docker compose --env-file .env config --quiet`, затем `docker compose --env-file .env up -d --build`.
|
||||
5. `docker compose --env-file .env ps -a`: миграция и `s3-init` должны завершиться с кодом 0, API — healthy.
|
||||
6. В PowerShell: `$env:PYTHONUTF8="1"`; `make check PYTHON="py -3"`; `make test PYTHON="py -3"`.
|
||||
7. `py -3 tests/image_probe.py` не является самостоятельным тестом; `tests/smoke.py` проверяет PNG upload/download.
|
||||
8. Проверить failover: остановить `api1`, повторить `make test`, восстановить `docker compose --env-file .env up -d --no-deps api1`.
|
||||
9. Проверить `go test ./...` в Go 1.25 контейнере: `docker run --rm -v "${PWD}:/app" -w /app golang:1.25.0-alpine go test ./...`.
|
||||
10. После реальных PASS дополнить `REPORT.md`, создать коммит и push. **Не отмечать непроверенные пункты в PR**.
|
||||
|
||||
Важно: `.env` — локальный секрет, не коммитить. `docker compose down` сохраняет данные; `docker compose down -v` уничтожает учебные volumes.
|
||||
@@ -1,37 +1,79 @@
|
||||
# Отчёт — лабораторная 4
|
||||
# Отчёт — лабораторная работа № 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
**Студент:** Федоров Арсений
|
||||
**Группа:** БПИ2302
|
||||
**Целевая оценка:** 3 (трек на 5 не заявлен)
|
||||
**Ветка:** `solution/BPI2302-fedorov`
|
||||
**Коммит / Pull Request:** заполнить после публикации.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## 1. Цель и результат
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Реализован учебный сервис обмена сообщениями с загрузкой и скачиванием вложений. Исходные изображения PNG/JPEG сохраняются в S3-совместимом хранилище, метаданные — в PostgreSQL. Две реплики Go API работают за Nginx и используют общие хранилища.
|
||||
|
||||
## Архитектура и решения
|
||||
## 2. Архитектура
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Клиент → Nginx → `api1` / `api2` → PostgreSQL, Redis и SeaweedFS (S3 API).
|
||||
|
||||
## Доказательства критериев
|
||||
- **Go API:** HTTP-обработчики пользователей, сессий, чатов, сообщений и вложений.
|
||||
- **PostgreSQL 16:** постоянные данные и метаданные вложений; SQL-миграции выполняет отдельный сервис `migrate`.
|
||||
- **Redis 7:** кэширование данных сессий.
|
||||
- **SeaweedFS:** S3-совместимое хранение оригиналов файлов в бакете `messenger-attachments`; данные размещены в постоянном Docker volume.
|
||||
- **Nginx:** входная точка `http://localhost:8080`, распределение запросов между двумя репликами API.
|
||||
- **`s3-init`:** однократная проверка/создание бакета посредством AWS CLI (`awslocal` из вспомогательного образа LocalStack). Сам LocalStack не используется как хранилище данных.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Для оригиналов используются серверные ключи вида `original/<UUID>`. Приложение использует переменные окружения для подключения к базе, Redis и S3; локальный `.env` не должен попадать в Git.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## 3. Запуск
|
||||
|
||||
## Эксперименты и отказы
|
||||
Требуются Docker Desktop, Docker Compose, Git, Python 3.10+ и GNU Make. Создать `.env` на основе `.env.example`, указать собственные значения переменных окружения. Далее из корня репозитория:
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
```powershell
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build
|
||||
docker compose --env-file .env ps -a
|
||||
make check PYTHON="py -3"
|
||||
make test PYTHON="py -3"
|
||||
```
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
Остановить стенд без удаления данных:
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
```powershell
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Команда `down -v` удаляет постоянные тома и не применяется при проверке сохранности файлов.
|
||||
|
||||
## 4. Фактически выполненные проверки
|
||||
|
||||
| Проверка | Фактический результат |
|
||||
| --- | --- |
|
||||
| `docker compose --env-file .env config --quiet` | Выполнено без ошибок |
|
||||
| `docker compose --env-file .env up -d --build` | Сервисы запущены; `api1` и `api2` имеют статус `healthy`; `migrate` и `s3-init` завершились с кодом 0 |
|
||||
| `make check PYTHON="py -3"` | PASS (проводилось ранее в ходе работы) |
|
||||
| `make test PYTHON="py -3"` | `PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.` |
|
||||
| `go test ./...` в контейнере Go | PASS (проводилось ранее в ходе работы) |
|
||||
| Проверка S3-объекта после `docker compose down` и `up -d` | `head-object` успешно вернул метаданные исходного PNG |
|
||||
|
||||
**Доказательство сохранности:** после перезапуска контейнеров объект `original/8d2f350f-8add-49a1-b7e0-6cad21911af1` остался доступен в бакете `messenger-attachments`. Команда `s3api head-object` вернула `ContentLength: 111817`, `ContentType: image/png` и ETag `c2ab21400d8c13ea847e4d5d3c9832ad`.
|
||||
|
||||
Пример команды проверки:
|
||||
|
||||
```powershell
|
||||
docker compose --env-file .env run --rm --no-deps --entrypoint awslocal s3-init --endpoint-url=http://s3:4566 s3api head-object --bucket messenger-attachments --key original/8d2f350f-8add-49a1-b7e0-6cad21911af1
|
||||
```
|
||||
|
||||
## 5. Что ещё не подтверждено отдельным экспериментом
|
||||
|
||||
- Отказоустойчивость запросов при принудительной остановке одной из двух реплик API.
|
||||
- Отказ в доступе к S3-объекту без авторизации (проверка приватности бакета).
|
||||
- Нагрузочные характеристики RPS, p50/p95/p99, потребление CPU/RAM.
|
||||
|
||||
Эти результаты не заявляются как проверенные. Успешный публичный smoke-тест не заменяет отдельные инфраструктурные испытания.
|
||||
|
||||
## 6. Ограничения
|
||||
|
||||
Стенд учебный и использует локальный HTTP; для внешнего доступа необходим TLS. Nginx, PostgreSQL, Redis и экземпляр SeaweedFS остаются потенциальными единичными точками отказа. Полной атомарности операций между PostgreSQL и S3 нет. Для промышленной эксплуатации потребуются ограниченные учётные данные S3, наблюдаемость, резервное копирование и дополнительные проверки безопасности.
|
||||
|
||||
## 7. Источники и инструменты
|
||||
|
||||
Исходные требования и контракты лабораторной работы, документация Go, PostgreSQL, Docker Compose и S3 API.
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
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 os.Getenv("RUN_MIGRATIONS_ONLY") == "1" {
|
||||
if err := storage.ApplyMigrations(ctx, pool); err != nil {
|
||||
log.Fatalf("database migrations failed: %v", err)
|
||||
}
|
||||
log.Println("database migrations applied; exiting")
|
||||
return
|
||||
}
|
||||
if os.Getenv("RUN_MIGRATIONS_ON_START") == "1" {
|
||||
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)
|
||||
s3, err := storage.NewS3Client()
|
||||
if err != nil {
|
||||
log.Fatalf("S3 configuration: %v", err)
|
||||
}
|
||||
attachmentHandler := &handler.AttachmentHandler{Chats: chatStore, Attachments: storage.NewAttachmentStore(pool), S3: s3}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if err := s3.Ready(pingCtx); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(503)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": "unavailable", "message": "object storage 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("POST /api/v1/chats/{chat_id}/attachments", auth(http.HandlerFunc(attachmentHandler.Upload)))
|
||||
mux.Handle("GET /api/v1/attachments/{id}", auth(http.HandlerFunc(attachmentHandler.Metadata)))
|
||||
mux.Handle("GET /api/v1/attachments/{id}/content", auth(http.HandlerFunc(attachmentHandler.Content)))
|
||||
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(instanceHeader(databaseDeadline(mux))),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 25 * 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(), 20*time.Second)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// instanceHeader identifies the real API process behind the load balancer.
|
||||
func instanceHeader(next http.Handler) http.Handler {
|
||||
id := os.Getenv("INSTANCE_ID")
|
||||
if id == "" {
|
||||
id = "api-unknown"
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.10-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB
|
||||
interval: 3s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
redis:
|
||||
image: redis:7.4.6-alpine
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- redis-server
|
||||
- --appendonly
|
||||
- 'yes'
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- redis-cli
|
||||
- ping
|
||||
interval: 3s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:latest
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- mini
|
||||
- -dir=/data
|
||||
- -s3.port=4566
|
||||
volumes:
|
||||
- seaweed_data:/data
|
||||
s3-init:
|
||||
image: localstack/localstack:4.9.1
|
||||
entrypoint:
|
||||
- /bin/bash
|
||||
- -c
|
||||
command:
|
||||
- until awslocal --endpoint-url=http://s3:4566 s3api list-buckets >/dev/null 2>&1;
|
||||
do sleep 2; done; awslocal --endpoint-url=http://s3:4566 s3api head-bucket --bucket
|
||||
messenger-attachments >/dev/null 2>&1 || awslocal --endpoint-url=http://s3:4566
|
||||
s3api create-bucket --bucket messenger-attachments
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}
|
||||
AWS_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY}
|
||||
AWS_DEFAULT_REGION: us-east-1
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_started
|
||||
restart: 'no'
|
||||
migrate:
|
||||
build: .
|
||||
environment:
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
|
||||
RUN_MIGRATIONS_ONLY: '1'
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: 'no'
|
||||
api1:
|
||||
build: .
|
||||
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
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
INSTANCE_ID: api1
|
||||
S3_ENDPOINT: http://s3:4566
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}
|
||||
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
healthcheck: &id001
|
||||
test:
|
||||
- CMD
|
||||
- wget
|
||||
- -q
|
||||
- -O
|
||||
- /dev/null
|
||||
- http://127.0.0.1:8080/health/ready
|
||||
interval: 3s
|
||||
timeout: 2s
|
||||
retries: 10
|
||||
api2:
|
||||
build: .
|
||||
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
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
INSTANCE_ID: api2
|
||||
S3_ENDPOINT: http://s3:4566
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}
|
||||
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
healthcheck: *id001
|
||||
lb:
|
||||
image: nginx:1.29-alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- 127.0.0.1:8080:8080
|
||||
volumes:
|
||||
- ./infra/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
depends_on:
|
||||
api1:
|
||||
condition: service_healthy
|
||||
api2:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
postgres_data: null
|
||||
redis_data: null
|
||||
seaweed_data: null
|
||||
@@ -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,24 @@
|
||||
events { worker_connections 1024; }
|
||||
http {
|
||||
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||
upstream messenger {
|
||||
zone messenger 64k;
|
||||
server api1:8080 resolve max_fails=1 fail_timeout=2s;
|
||||
server api2:8080 resolve max_fails=1 fail_timeout=2s;
|
||||
keepalive 16;
|
||||
}
|
||||
server {
|
||||
listen 8080;
|
||||
location / {
|
||||
proxy_pass http://messenger;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Request-Id $http_x_request_id;
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_read_timeout 8s;
|
||||
proxy_send_timeout 8s;
|
||||
proxy_next_upstream error timeout http_502 http_503;
|
||||
proxy_next_upstream_tries 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxUpload = 10 * 1024 * 1024
|
||||
const maxPixels = 40000000
|
||||
|
||||
type AttachmentHandler struct {
|
||||
Chats *storage.ChatStore
|
||||
Attachments *storage.AttachmentStore
|
||||
S3 *storage.S3Client
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
user, _ := middleware.GetCurrentUser(r.Context())
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, 400, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
_, err = h.Chats.GetChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, 404, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, 503, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if filename == "" || utf8.RuneCountInString(filename) > 255 || strings.ContainsAny(filename, "/\\") || strings.IndexFunc(filename, unicode.IsControl) >= 0 {
|
||||
writeError(w, r, 400, "invalid_request", "invalid filename")
|
||||
return
|
||||
}
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct != "image/png" && ct != "image/jpeg" {
|
||||
writeError(w, r, 415, "unsupported_media_type", "unsupported content type")
|
||||
return
|
||||
}
|
||||
if r.ContentLength > maxUpload {
|
||||
writeError(w, r, 413, "payload_too_large", "file too large")
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(r.Body, maxUpload+1))
|
||||
if err != nil {
|
||||
writeError(w, r, 400, "invalid_request", "invalid body")
|
||||
return
|
||||
}
|
||||
if len(data) > maxUpload {
|
||||
writeError(w, r, 413, "payload_too_large", "file too large")
|
||||
return
|
||||
}
|
||||
if len(data) == 0 {
|
||||
writeError(w, r, 415, "unsupported_media_type", "empty file")
|
||||
return
|
||||
}
|
||||
actual := http.DetectContentType(data)
|
||||
if actual != ct {
|
||||
writeError(w, r, 415, "unsupported_media_type", "image content type mismatch")
|
||||
return
|
||||
}
|
||||
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || (format != "png" && format != "jpeg") {
|
||||
writeError(w, r, 415, "unsupported_media_type", "invalid image")
|
||||
return
|
||||
}
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > maxPixels {
|
||||
writeError(w, r, 413, "payload_too_large", "too many pixels")
|
||||
return
|
||||
}
|
||||
// Decode fully to reject truncated/corrupt compressed image data. Dimensions already checked.
|
||||
if _, _, err = image.Decode(bytes.NewReader(data)); err != nil {
|
||||
writeError(w, r, 415, "unsupported_media_type", "corrupt image")
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
id := uuid.New()
|
||||
key := "original/" + id.String()
|
||||
digest := sha256.Sum256(data)
|
||||
a := model.Attachment{ID: id, ChatID: chatID, OwnerID: user.ID, Filename: filename, ContentType: ct, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now, ObjectKey: key}
|
||||
if err = h.S3.Put(r.Context(), key, ct, data); err != nil {
|
||||
writeError(w, r, 503, "unavailable", "object storage unavailable")
|
||||
return
|
||||
}
|
||||
if err = h.Attachments.Create(r.Context(), a); err != nil {
|
||||
// Best-effort rollback for S3 write that could not be committed to DB.
|
||||
cleanupCtx := r.Context()
|
||||
_ = h.S3.Delete(cleanupCtx, key)
|
||||
writeError(w, r, 503, "unavailable", "metadata unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, a)
|
||||
}
|
||||
func (h *AttachmentHandler) read(w http.ResponseWriter, r *http.Request, content bool) {
|
||||
user, _ := middleware.GetCurrentUser(r.Context())
|
||||
id, err := uuid.Parse(r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeError(w, r, 400, "invalid_request", "invalid attachment id")
|
||||
return
|
||||
}
|
||||
a, err := h.Attachments.GetForUser(r.Context(), id, user.ID)
|
||||
if errors.Is(err, storage.ErrAttachmentNotFound) {
|
||||
writeError(w, r, 404, "not_found", "attachment not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, 503, "unavailable", "metadata unavailable")
|
||||
return
|
||||
}
|
||||
if !content {
|
||||
writeJSON(w, 200, a)
|
||||
return
|
||||
}
|
||||
variant := r.URL.Query().Get("variant")
|
||||
if variant != "" && variant != "original" {
|
||||
writeError(w, r, 404, "not_found", "variant not found")
|
||||
return
|
||||
}
|
||||
data, err := h.S3.Get(r.Context(), a.ObjectKey)
|
||||
if err != nil {
|
||||
writeError(w, r, 503, "unavailable", "object storage unavailable")
|
||||
return
|
||||
}
|
||||
if int64(len(data)) != a.SizeBytes {
|
||||
writeError(w, r, 503, "unavailable", "object size mismatch")
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
if hex.EncodeToString(sum[:]) != a.SHA256 {
|
||||
writeError(w, r, 503, "unavailable", "object checksum mismatch")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", a.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
|
||||
w.WriteHeader(200)
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
func (h *AttachmentHandler) Metadata(w http.ResponseWriter, r *http.Request) { h.read(w, r, false) }
|
||||
func (h *AttachmentHandler) Content(w http.ResponseWriter, r *http.Request) { h.read(w, r, true) }
|
||||
@@ -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,230 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"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"`
|
||||
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyPattern.MatchString(key) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing Idempotency-Key")
|
||||
return
|
||||
}
|
||||
|
||||
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) == "" && len(req.AttachmentIDs) == 0) || textLength > 4000 || len(req.AttachmentIDs) > 10 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "text must contain from 1 to 4000 characters")
|
||||
return
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]bool)
|
||||
for _, id := range req.AttachmentIDs {
|
||||
if id == uuid.Nil || seen[id] {
|
||||
writeError(w, r, 400, "invalid_request", "invalid attachment_ids")
|
||||
return
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
if req.AttachmentIDs == nil {
|
||||
req.AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: currentUser.ID,
|
||||
Text: req.Text,
|
||||
AttachmentIDs: req.AttachmentIDs,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
message, err := h.messages.CreateMessageIdempotent(r.Context(), message, key)
|
||||
if errors.Is(err, storage.ErrIdempotencyConflict) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "Idempotency-Key reused with different body")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, storage.ErrAttachmentNotFound) {
|
||||
writeError(w, r, 404, "not_found", "attachment not found")
|
||||
return
|
||||
}
|
||||
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,22 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ChatID uuid.UUID `json:"chat_id"`
|
||||
OwnerID uuid.UUID `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []any `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ObjectKey string `json:"-"`
|
||||
}
|
||||
@@ -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,16 @@
|
||||
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"`
|
||||
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
|
||||
}
|
||||
@@ -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,31 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type AttachmentStore struct{ Pool *pgxpool.Pool }
|
||||
|
||||
func NewAttachmentStore(p *pgxpool.Pool) *AttachmentStore { return &AttachmentStore{p} }
|
||||
func (s *AttachmentStore) Create(ctx context.Context, a model.Attachment) error {
|
||||
_, err := s.Pool.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey, a.CreatedAt, a.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
func (s *AttachmentStore) GetForUser(ctx context.Context, id, user uuid.UUID) (model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
err := s.Pool.QueryRow(ctx, `SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256,a.object_key,a.created_at,a.updated_at FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=$1 AND cm.user_id=$2`, id, user).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.ObjectKey, &a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return a, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
a.Status = "ready"
|
||||
a.Variants = []any{}
|
||||
return a, nil
|
||||
}
|
||||
@@ -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,242 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"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)
|
||||
}
|
||||
|
||||
message.AttachmentIDs, err = s.attachmentIDs(ctx, message.ID)
|
||||
if err != nil {
|
||||
return nil, false, 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
|
||||
}
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key reused with different message")
|
||||
|
||||
// CreateMessageIdempotent stores both the message and its deduplication record
|
||||
// in one PostgreSQL transaction. The unique constraint serializes concurrent
|
||||
// attempts across independent API processes. A rollback records neither.
|
||||
func (s *MessageStore) CreateMessageIdempotent(ctx context.Context, message model.Message, key string) (model.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("begin idempotent message: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Expired keys may be reused; only the exact scope is pruned here.
|
||||
_, err = tx.Exec(ctx, `DELETE FROM message_idempotency
|
||||
WHERE sender_id=$1 AND chat_id=$2 AND idem_key=$3 AND created_at < NOW() - INTERVAL '24 hours'`,
|
||||
message.SenderID, message.ChatID, key)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("expire idempotency: %w", err)
|
||||
}
|
||||
|
||||
tag, err := tx.Exec(ctx, `INSERT INTO message_idempotency
|
||||
(sender_id, chat_id, idem_key, text, message_id)
|
||||
VALUES ($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`,
|
||||
message.SenderID, message.ChatID, key, messageFingerprint(message), message.ID)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("reserve idempotency: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
var existingText string
|
||||
var existingID uuid.UUID
|
||||
err = tx.QueryRow(ctx, `SELECT text, message_id FROM message_idempotency
|
||||
WHERE sender_id=$1 AND chat_id=$2 AND idem_key=$3`,
|
||||
message.SenderID, message.ChatID, key).Scan(&existingText, &existingID)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("lookup idempotency: %w", err)
|
||||
}
|
||||
if existingText != messageFingerprint(message) {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
var original model.Message
|
||||
err = tx.QueryRow(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE id=$1`, existingID).
|
||||
Scan(&original.ID, &original.ChatID, &original.SenderID, &original.Text, &original.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("read idempotent message: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
original.AttachmentIDs, err = s.attachmentIDs(ctx, original.ID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return original, nil
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `INSERT INTO messages (id,chat_id,sender_id,text,created_at)
|
||||
VALUES ($1,$2,$3,$4,$5)`, 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 model.Message{}, ErrMessageMemberNotFound
|
||||
}
|
||||
return model.Message{}, fmt.Errorf("insert idempotent message: %w", err)
|
||||
}
|
||||
if err := s.linkAttachments(ctx, tx, message); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, fmt.Errorf("commit idempotent message: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MessageStore) attachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY attachment_id`, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := make([]uuid.UUID, 0)
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
func (s *MessageStore) linkAttachments(ctx context.Context, tx pgx.Tx, m model.Message) error {
|
||||
for _, id := range m.AttachmentIDs {
|
||||
tag, err := tx.Exec(ctx, `INSERT INTO message_attachments(message_id,attachment_id)
|
||||
SELECT $1,a.id FROM attachments a WHERE a.id=$2 AND a.chat_id=$3`, m.ID, id, m.ChatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var ErrAttachmentNotFound = errors.New("attachment not found in chat")
|
||||
|
||||
func messageFingerprint(m model.Message) string {
|
||||
ids := append([]uuid.UUID(nil), m.AttachmentIDs...)
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i].String() < ids[j].String() })
|
||||
b, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
IDs []uuid.UUID `json:"attachment_ids"`
|
||||
}{m.Text, ids})
|
||||
return string(b)
|
||||
}
|
||||
@@ -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,102 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// S3Client uses AWS Signature V4 with path-style requests (MinIO-compatible).
|
||||
// No credentials or bucket identifiers are returned through the public API.
|
||||
type S3Client struct {
|
||||
Endpoint, Region, Bucket, Key, Secret string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func NewS3Client() (*S3Client, error) {
|
||||
s := &S3Client{Endpoint: strings.TrimRight(os.Getenv("S3_ENDPOINT"), "/"), Region: os.Getenv("S3_REGION"), Bucket: os.Getenv("S3_BUCKET"), Key: os.Getenv("S3_ACCESS_KEY_ID"), Secret: os.Getenv("S3_SECRET_ACCESS_KEY"), HTTP: &http.Client{Timeout: 12 * time.Second}}
|
||||
if s.Region == "" {
|
||||
s.Region = "us-east-1"
|
||||
}
|
||||
if s.Endpoint == "" || s.Bucket == "" || s.Key == "" || s.Secret == "" {
|
||||
return nil, errors.New("missing S3 configuration")
|
||||
}
|
||||
u, err := url.Parse(s.Endpoint)
|
||||
if err != nil || u.Scheme != "http" && u.Scheme != "https" || u.Host == "" {
|
||||
return nil, errors.New("invalid S3 endpoint")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
func mac(key []byte, value string) []byte {
|
||||
m := hmac.New(sha256.New, key)
|
||||
m.Write([]byte(value))
|
||||
return m.Sum(nil)
|
||||
}
|
||||
func hexsum(data []byte) string { v := sha256.Sum256(data); return hex.EncodeToString(v[:]) }
|
||||
func (s *S3Client) request(ctx context.Context, method, key, contentType string, body []byte) ([]byte, error) {
|
||||
path := "/" + s.Bucket
|
||||
if key != "" {
|
||||
path += "/" + strings.ReplaceAll(url.PathEscape(key), "%2F", "/")
|
||||
}
|
||||
endpoint, err := url.Parse(s.Endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target := s.Endpoint + path
|
||||
req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
date := now.Format("20060102")
|
||||
amzDate := now.Format("20060102T150405Z")
|
||||
digest := hexsum(body)
|
||||
req.Header.Set("x-amz-date", amzDate)
|
||||
req.Header.Set("x-amz-content-sha256", digest)
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
canonicalHeaders := "host:" + endpoint.Host + "\n" + "x-amz-content-sha256:" + digest + "\n" + "x-amz-date:" + amzDate + "\n"
|
||||
signedHeaders := "host;x-amz-content-sha256;x-amz-date"
|
||||
canonical := method + "\n" + path + "\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + digest
|
||||
scope := date + "/" + s.Region + "/s3/aws4_request"
|
||||
toSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + scope + "\n" + hexsum([]byte(canonical))
|
||||
signingKey := mac(mac(mac(mac([]byte("AWS4"+s.Secret), date), s.Region), "s3"), "aws4_request")
|
||||
auth := "AWS4-HMAC-SHA256 Credential=" + s.Key + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + hex.EncodeToString(mac(signingKey, toSign))
|
||||
req.Header.Set("Authorization", auth)
|
||||
resp, err := s.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return nil, fmt.Errorf("S3 returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024+1))
|
||||
}
|
||||
func (s *S3Client) Put(ctx context.Context, key, mime string, body []byte) error {
|
||||
_, err := s.request(ctx, "PUT", key, mime, body)
|
||||
return err
|
||||
}
|
||||
func (s *S3Client) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return s.request(ctx, "GET", key, "", nil)
|
||||
}
|
||||
func (s *S3Client) Delete(ctx context.Context, key string) error {
|
||||
_, err := s.request(ctx, "DELETE", key, "", nil)
|
||||
return err
|
||||
}
|
||||
func (s *S3Client) Ready(ctx context.Context) error {
|
||||
_, err := s.request(ctx, "HEAD", "", "", nil)
|
||||
return err
|
||||
}
|
||||
@@ -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 @@
|
||||
DROP TABLE IF EXISTS message_idempotency;
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS message_idempotency (
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
idem_key VARCHAR(128) NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
message_id UUID NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (sender_id, chat_id, idem_key)
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank CHECK (length(btrim(text)) > 0);
|
||||
DROP TABLE message_attachments;
|
||||
DROP TABLE attachments;
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id),
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
sha256 CHAR(64) NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
|
||||
CREATE TABLE message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||||
PRIMARY KEY(message_id,attachment_id)
|
||||
);
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_not_blank;
|
||||
@@ -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
|
||||
@@ -8,8 +8,8 @@ import re
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
@@ -41,11 +41,11 @@ def main():
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
json.loads(file.read_text(encoding='utf-8'))
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
+3
-3
@@ -13,8 +13,8 @@ import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LAB = json.loads((ROOT / 'lab.json').read_text())['number']
|
||||
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text())
|
||||
LAB = json.loads((ROOT / 'lab.json').read_text(encoding='utf-8'))['number']
|
||||
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
|
||||
class Failure(AssertionError):
|
||||
pass
|
||||
@@ -26,7 +26,7 @@ def check(condition, message):
|
||||
def timestamp(value):
|
||||
check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z')
|
||||
try:
|
||||
return dt.datetime.fromisoformat(value[:-1] + '+00:00')
|
||||
return dt.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=dt.timezone.utc) if '.' in value else dt.datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=dt.timezone.utc)
|
||||
except ValueError as exc:
|
||||
raise Failure('invalid RFC3339 timestamp') from exc
|
||||
|
||||
|
||||
Reference in New Issue
Block a user